二分法求平方根(Python實現)

2021-09-06 12:21:47 字數 1528 閱讀 6036

使用二分法(bisection method)求平方根。

1

defsqrtbi(x, epsilon):

2assert x>0, '

x must be non-nagtive, not

' +str(x)

3assert epsilon > 0, '

epsilon must be postive, not

' +str(epsilon)

45 low =0

6 high =x

7 guess = (low + high)/2.0

8 counter = 1

9while (abs(guess ** 2 - x) > epsilon) and (counter <= 100):

10if guess ** 2

11 low =guess

12else

:13 high =guess

14 guess = (low + high)/2.0

15 counter += 1

16return guess

驗證一下。

上面的方法,如果 x<1 ,就會有問題。因為 x (x<1)的平方根不在 [0, x] 的範圍內。例如,0.25,它的平方根——0.5 不在 [0, 0.25] 的區間內。

那如何求0.25的平方根呢?

只要略微改動上面的**即可。注意6行和7行的**。

1

defsqrtbi(x, epsilon):

2assert x>0, '

x must be non-nagtive, not

' +str(x)

3assert epsilon > 0, '

epsilon must be postive, not

' +str(epsilon)

45 low =0

6 high = max(x, 1.0)7#

# high = x

8 guess = (low + high)/2.0

9 counter = 1

10while (abs(guess ** 2 - x) > epsilon) and (counter <= 100):

11if guess ** 2

12 low =guess

13else

:14 high =guess

15 guess = (low + high)/2.0

16 counter += 1

17return guess

再檢驗一下:

如果不知道怎樣去呼叫自定義的方法(模組),可參考

Python用二分法求平方根

好了,正如標題所示,我們今天要用二分法來求平方根。首先要有數字,但是老是有人寫字串該怎麼辦呢?老是有人在寫數學題的時候打字串 try x int input please enter a whole number to measure to square root except print 然後是重...

二分法做平方根

注意這裡的浮點數 不然的話程式會報錯 coding utf 8 二分法計算20的平方根 import math a 0.0 多次二分後會變成二分法,所以要設定成浮點數,python裡就是直接賦值成浮點數 b c float raw input enter a number n 100 while t...

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 g...