python利用牛顿迭代法求出1~n之间的所有整数的算术平方根,并与math库中sqrt函数的结果进行比较
时间: 2024-05-05 08:16:01 浏览: 204
以下是使用牛顿迭代法求出1~n之间所有整数的算术平方根的Python代码:
```python
import math
def newton_sqrt(n):
x = n
while True:
y = (x + n / x) / 2
if abs(y - x) < 0.000001:
return y
x = y
n = 10
for i in range(1, n+1):
my_sqrt = newton_sqrt(i)
math_sqrt = math.sqrt(i)
print(f"{i}: my_sqrt={my_sqrt:.6f} math_sqrt={math_sqrt:.6f} diff={abs(my_sqrt - math_sqrt):.6f}")
```
输出:
```
1: my_sqrt=1.000000 math_sqrt=1.000000 diff=0.000000
2: my_sqrt=1.414214 math_sqrt=1.414214 diff=0.000000
3: my_sqrt=1.732051 math_sqrt=1.732051 diff=0.000000
4: my_sqrt=2.000000 math_sqrt=2.000000 diff=0.000000
5: my_sqrt=2.236068 math_sqrt=2.236068 diff=0.000000
6: my_sqrt=2.449490 math_sqrt=2.449490 diff=0.000000
7: my_sqrt=2.645751 math_sqrt=2.645751 diff=0.000000
8: my_sqrt=2.828427 math_sqrt=2.828427 diff=0.000000
9: my_sqrt=3.000000 math_sqrt=3.000000 diff=0.000000
10: my_sqrt=3.162278 math_sqrt=3.162278 diff=0.000000
```
可以看到,使用牛顿迭代法得到的结果与math库中的sqrt函数得到的结果非常接近,两者之间的差异非常小。
阅读全文