为什么 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,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: ",",Added Number: ",toAddFloat,Calculated Sum: ",floatSum,Times Correct: ",floatCorrect,Correct Result: ",toAddFloat * max,Difference: ",(toAddFloat * max) - floatSum,"\n")

print("DECIMAL RESULTS:")
print("----------------")
print("Iterations: ",toAddDec,decSum,decCorrect,toAddDec * max,(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,Calculated Sum:  10.0,Times Correct:  20,Difference:  0.0

解决方法

将此行更新为

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

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