1. 程式人生 > >Python的二分法求平方根

Python的二分法求平方根

def sq2(x,e):
    e = e #誤差範圍
    
    low= 0 
    high = max(x,1.0) #處理大於0小於1的數
    guess = (low + high) / 2.0
    ctr = 1
    
    while abs(guess**2 - x) > e and ctr<= 1000:
        if guess**2 < x:
            low = guess
        else:
            high = guess
            
        guess = (low + high) / 2.0
        ctr += 1
    print(guess)