python 使用二分法計算平方根

python 使用二分法計算平方根


from math import sqrt
def mysqrt(num,small):
    assert num>0
    assert small>0
    low = 0.0
    high = max(num,1)
    loops=1
    while True and loops<=100:
        a = (high + low) / 2
        test = a ** 2
        if abs(test-num)<small:
            break
        elif test > num:
            high = a
        else:
            low = a
        loops+=1
    return a

if __name__ == '__main__':
    num = input("number:")
    small=0.0000000001
    print mysqrt(num,small),"my sqrt "        #對比我寫的這個和math庫的計算值的差別
    print sqrt(num),"math sqrt"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章