1. 程式人生 > >pyhon3 二分法求算術平方根

pyhon3 二分法求算術平方根

a= float(input ("請輸入您要開平方的數:\n"))
if a > 0:
   if a>1:
       low = 0
       high = a
       guess = (low + high) / 2
       while abs(guess **2 - a)> 1e-5:
           if guess ** 2>a:
               high= guess
           else :
               low = guess
           guess = (low + high) / 2
       print(guess)
   else:
       low = a
       high = 1
       guess = (low + high)/2
       while abs(guess ** 2 -a)> 1e-5:
           if guess**2 > a:
               high=guess
           else:
               low= guess
           guess = (low + high)/2
       print (guess)
else :
    print("請輸入恰當的值")