【问题标题】:Why does counting down in decimals result in a xxx.9999999999999999999x?为什么以小数倒数会导致 xxx.99999999999999999999x?
【发布时间】:2020-06-18 15:56:30
【问题描述】:
import time
def timer():
    a = 300.0
    while a > 0: #stopes at 0
        print(a)
        time.sleep(0.11) #for roughly 100 millisecond
        a = a - 0.1
timer()

我编写了一段代码,每 0.100 秒倒计时 1/10(大约。它必须大于 0.100,否则脚本会忽略它)。 但是,输出如下所示:

300.0
299.9
299.79999999999995
299.69999999999993
299.5999999999999
299.4999999999999
299.39999999999986
299.29999999999984
299.1999999999998
299.0999999999998
298.9999999999998
298.89999999999975
298.7999999999997
298.6999999999997
298.5999999999997
298.49999999999966
298.39999999999964
298.2999999999996
298.1999999999996
298.09999999999957
297.99999999999955
297.8999999999995
297.7999999999995
297.6999999999995
297.59999999999945
297.49999999999943
297.3999999999994
297.2999999999994
297.19999999999936
297.09999999999934
296.9999999999993
296.8999999999993
296.7999999999993
296.69999999999925
...

为什么?有解决办法吗?

【问题讨论】:

  • 这能回答你的问题吗? Is floating point math broken?
  • 您建议的文章并非没有帮助,只是我无法将其实现到我的代码中。不过还是谢谢!

标签: python-3.x interactive-shell


【解决方案1】:

您实际上可以使用名为round 的python 函数。 round 函数将有效地对 9999999 进行四舍五入...并且只显示您想要的内容。

修改后的代码是:

import time
def timer():
    for a in range(3000,0,-1):
        print(round(a*.1, 1))
        time.sleep(0.101) #for roughly 1 millisecond


timer()

要使用round 函数,请执行以下操作:

round([variableornumber]*.[float], [numberofdecimals]) #in this example, its limited to 1

使用roundprint 的另一种方式:

print(round([variableornumber]*.[float], [numberofdecimals]))

python 创建999999999999... 的原因是因为 python 无法创建以 2 为底的 1/10 的精确分数。

15.Floating Point Arithmetic: issues and limitations--python 3.8.2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    相关资源
    最近更新 更多