克服分数方面的二进制无能

Overcoming the binary incompetence in regards to fractions

我正在尝试将分数加在一起(1/5 等),由于二进制无法添加某些分数,我得到的答案非常糟糕,例如 2.99999999999996 等等。我知道我可以使用 math.round(因为 pythons round 实际上不是圆的)将它变成 3,但我不想那样。

是否有任何模块可以用来将两个数字相加(例如 0.2 和 0.2)并得到除 0.39999999999999999999999996 以外的结果?

编辑:

我试过用十进制,输入6、12、24、24得到的结果是2.9999999999:

while True:
            try:
                x += 1
                print("\n" + "Enter resistance of resistor " + str(x))
                resistors.append(int(input()))
            except:
                temp = Decimal(0)
                print(temp)
                for i in resistors:
                    print(temp)
                    temp += Decimal(1)/Decimal(i) 
                temp = temp**-1
                print("\n" + "The total resistance of inputted resistors in parallel is: " + str(temp))
                input()
                break

不是 "binary incompetence"。它是使用真实机器来表示理想化数学实体的结果。在 0 和 1 之间有无限多个实数。无论你使用什么表示,二进制、三进制、八进制、十进制或十六进制,如果你只有有限的数字,那么其中一些实数将不得不共享相同的表示。您不能用二进制准确表示 1/100,因为它是一个循环出现的二进制分数。就像你不能用十进制表示 1/3 一样,因为它是循环小数。但是,当您的 4 功能袖珍计算器显示 1/3 为 0.3333333 时,您不会称其为小数无能。

如果你想准确地表示有理数,那么你可以使用 fractions 模块:

>>> import fractions
>>> fifth = fractions.Fraction(1,5)
>>> fifth * 2
Fraction(2, 5)

但是当您将 Fraction(2,5) 转换为浮点数时,您将返回到浮点表示。

不过,我认为这不是真正的问题。我想你只需要修复这一行:

print("\n" + "The total resistance of inputted resistors in parallel is: " + str(temp))

这是为您提供数字的默认字符串表示形式,它显示最接近可能精度的表示形式。但你实际上想看到一个不错的数字:

print("\n" + "The total resistance of inputted resistors in parallel is: %g" % temp)