首页 > 解决方案 > 为什么 Python 中这两个被证明相等的小数中的一些被认为不相等?

问题描述

我正在尝试比较在我的 Python 课程中将多个浮点数加在一起与将多个小数加在一起的精度。实验室的要求之一是计算添加 0.1 的迭代次数得到正确的总和。我的代码中的所有内容都正常工作,除了我的计数器对于小数加法有多少加法是正确的。对于 100 次迭代,它仅将 20 次视为正确(每 5 次迭代),即使我已经通过打印每次迭代来证明它们都是正确的。为什么会发生这种情况,如何解决?谢谢。(您可以在下面找到完整的代码以获取完整的上下文以及输出。)

代码:

from decimal import *

floatSum = 0
decSum = 0
toAddFloat = .1
toAddDec = Decimal(".1")
max = 100 # number of iterations
floatCorrect = 0
decCorrect = 0

# continually add .1 as floats together for specified number of iterations
for i in range (0, max, 1):
    floatSum = floatSum + toAddFloat
    print(floatSum,(i + 1) / 10)
    if (floatSum == (i + 1) / 10): # check if the addition is what it should be
        floatCorrect += 1

i = 0

# continually add .1 as decimals together for specified number of iterations
for i in range (0, max, 1):
    decSum = decSum + toAddDec
    print(decSum, (i + 1) / 10)
    print(decCorrect)
    if (decSum == (i + 1) / 10): # check if the addition is what it should be
        decCorrect += 1

print("\nFLOAT RESULTS:")
print("--------------")
print("Iterations: ", max, ", Added Number: ", toAddFloat, ", Calculated Sum: ", floatSum,
        ", Times Correct: ", floatCorrect, ", Correct Result: ", toAddFloat * max, ", Difference: ", (toAddFloat * max) - floatSum, "\n")

print("DECIMAL RESULTS:")
print("----------------")
print("Iterations: ", max, ", Added Number: ", toAddDec, ", Calculated Sum: ", decSum, 
        ", Times Correct: ", decCorrect, ", Correct Result: ", toAddDec * max, ", Difference: ", (toAddDec * max) - decSum)

(部分) 输出:

FLOAT RESULTS:
--------------
Iterations:  100 , Added Number:  0.1 , Calculated Sum:  9.99999999999998 , Times Correct:  11 , Correct Result:  10.0 , Difference:  1.9539925233402755e-14

DECIMAL RESULTS:
----------------
Iterations:  100 , Added Number:  0.1 , Calculated Sum:  10.0 , Times Correct:  20 , Correct Result:  10.0 , Difference:  0.0

标签: pythonfloating-pointdecimalprecisionequality

解决方案


将此行更新为

 if (decSum*10 == (i + 1)):

对于 python 除法给出一个浮点结果。如果这个数字看起来没有精确的表示,它不会等于十进制对应物。


推荐阅读