我试图用牛顿-拉斐逊方法计算一个数的平方根。这一部分比较直截了当。然而,当我想确保最终答案上返回的值始终是100位小数时,我似乎无法让它工作。我在VS代码和Jupyter笔记本上试过,似乎只能显示到小数点后17或18位
我的代码是:
import decimal as Dec
Dec.getcontext().prec = 100
Number = 5
bStart = 1 # Start value is 1
zStart = 1 # Start value is 1 (x0)
aCount = 0 # Iteration count
yNewNum = 0 # New value of estimate (x1)
xRoot = 0 # Used to transfer values between yNewNum and zStart
while aCount < 101: # While the difference between zStart and yNewNum is greater than 0.0000001 (7 decimal places)
yNewNum = (zStart + (Number / zStart)) / 2 # x1 = (x0 + (S/x0)) / 2
zStart = yNewNum # Replace the value x0 with the value of x1
yNewNum = xRoot # Replace the value of x1 with the transfer value
xRoot = zStart # Replace the transfer value with x0
aCount += 1 # aCount iterates by 1
print()
print(aCount, ":", Dec.Decimal(zStart))
print(len(str(zStart)))
print("Newton-Raphson method = ", Dec.Decimal(zStart))
print("Length:", len(str(zStart)))
在两个平台上,当起始值为15时,最后几次迭代的输出如下所示:
98 : 3.87298334620741702138957407441921532154083251953125
Length: 17
99 : 3.87298334620741702138957407441921532154083251953125
Length: 17
100 : 3.87298334620741702138957407441921532154083251953125
Length: 17
101 : 3.87298334620741702138957407441921532154083251953125
Length: 17
Newton-Raphson method =
3.87298334620741702138957407441921532154083251953125Length: 17
有没有关于如何让小数点显示100位小数的建议?请注意,我必须使用Newton-Raphson方法,因为这是一个要求
在浮点操作中,必须至少使用十进制类型初始化一个变量
您必须使用
Number = Dec.Decimal(5)
相关问题 更多 >
编程相关推荐