python 使用二分法计算平方根
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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"
|
本文转自 Xuenqlve 51CTO博客,原文链接:http://blog.51cto.com/13558754/2062629,如需转载请自行联系原作者