Python 实现雷神之锤开方算法
以下是使用 Python 代码实现的雷神之锤开方算法:
import math
def square_root(x):
if x < 0:
return 'Invalid input'
elif x == 0:
return 0
else:
guess = x / 2
while True:
new_guess = (guess + x / guess) / 2
if abs(new_guess - guess) < 1e-6:
return new_guess
guess = new_guess
# 测试
print(square_root(16)) # 4.0
print(square_root(2)) # 1.4142135623730951
print(square_root(-1)) # Invalid input
该算法使用牛顿迭代法来逼近平方根,直到两次迭代之间的差小于 1e-6 为止。如果输入为负数,返回'Invalid input'。如果输入为 0,则返回 0。
原文地址: https://www.cveoy.top/t/topic/gFm5 著作权归作者所有。请勿转载和采集!