可以使用牛顿迭代法来求解 sqrt(2) 的值,精确到小数点后 10 位。
首先,我们定义一个函数 sqrt(x) 来实现这个功能:
def sqrt(x, precision=10):
"""
使用牛顿迭代法求 x 的平方根,精确到小数点后 precision 位
"""
if x < 0:
raise ValueError("输入不能为负数")
# 初始猜测值
guess = 1.0
# 进行牛顿迭代
while True:
# 计算当前猜测值的平方根
root = (guess + x / guess) / 2
# 计算误差
error = abs(root - guess)
# 若误差小于所需精度,返回结果
if error <= 10 ** -precision:
return root
# 更新猜测值
guess = root
现在我们可以使用这个函数来求 sqrt(2) 的值:
sqrt_2 = sqrt(2, 10)
print(f"sqrt(2) 的值为: {sqrt_2:.10f}")
输出结果为:
sqrt(2) 的值为: 1.4142135624
这个结果已经精确到小数点后 10 位了。
让我们来