二分法和牛顿迭代法求平方根(Python实现)

1：二分法

a:折半：       5/2=2.5

b:平方校验:  2.5*2.5=6.25>5，并且得到当前上限2.5

c:再次向下折半:2.5/2=1.25

d:平方校验：1.25*1.25=1.5625<5,得到当前下限1.25

e:再次折半:2.5-(2.5-1.25)/2=1.875

f:平方校验：1.875*1.875=3.515625<5,得到当前下限1.875

import math
from math import sqrt

def sqrt_binary(num):
x=sqrt(num)
y=num/2.0
low=0.0
up=num*1.0
count=1
while abs(y-x)>0.00000001:
print count,y
count+=1
if (y*y>num):
up=y
y=low+(y-low)/2
else:
low=y
y=up-(up-y)/2
return y

print(sqrt_binary(5))
print(sqrt(5))

1 2.5
2 1.25
3 1.875
4 2.1875
5 2.34375
6 2.265625
7 2.2265625
8 2.24609375
9 2.236328125
10 2.2314453125
11 2.23388671875
12 2.23510742188
13 2.23571777344
14 2.23602294922
15 2.23617553711
16 2.23609924316
17 2.23606109619
18 2.23608016968
19 2.23607063293
20 2.23606586456
21 2.23606824875
22 2.23606705666
23 2.2360676527
24 2.23606795073
25 2.23606809974
26 2.23606802523
27 2.23606798798
2.23606796935
2.2360679775
[Finished in 0.1s]

0.001需要迭代8次

2：牛顿迭代

def sqrt_newton(num):
x=sqrt(num)
y=num/2.0
count=1
while abs(y-x)>0.00000001:
print count,y
count+=1
y=((y*1.0)+(1.0*num)/y)/2.0000
return y

print(sqrt_newton(5))
print(sqrt(5))

1 2.5
2 2.25
3 2.23611111111
2.23606797792
2.2360679775

3：利用牛顿法求开立方

def cube_newton(num):
x=num/3.0
y=0
count=1
while abs(x-y)>0.00000001:
print count,x
count+=1
y=x
x=(2.0/3.0)*x+(num*1.0)/(x*x*3.0)
return x

print(cube_newton(27))	

07-11 5988

01-13 848
10-19 9810
10-30 134
04-03 1444
10-29 2377
03-13 14万+