【问题标题】:Return values to fixed lengths将值返回到固定长度
【发布时间】:2020-10-05 01:21:14
【问题描述】:

我正在尝试使用 Newton-Raphson 方法计算数字的平方根。这部分相对简单。但是,当我想确保最终答案返回的值始终为小数点后 100 位时,我似乎无法让它工作。我在 VS Code 和 Jupyter Notebooks 上试过,似乎只能显示到小数点后 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

长度:17

99 : 3.87298334620741702138957407441921532154083251953125

长度:17

100 : 3.87298334620741702138957407441921532154083251953125

长度:17

101:3.87298334620741702138957407441921532154083251953125

长度:17

Newton-Raphson 方法 =
3.87298334620741702138957407441921532154083251953125

长度:17

关于如何获得小数位以显示 100 个小数位的任何建议?请注意,我必须使用 Newton-Raphson 方法,因为它是必需的。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在浮点运算中,至少有一个变量必须用 Decimal 类型初始化。

    你必须使用Number = Dec.Decimal(5)

    【讨论】:

    • 感谢您的解决方案。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    相关资源
    最近更新 更多