大于或等于浮动失败

Greater than or equal for floats failed

我是 运行 一个小型 python 测试,我针对一些数据编写了测试并得到了一些奇怪的结果。归结为:

priceDiff = 219.92 - 219.52
if(priceDiff >= .40):
   print "YES"
else:
   print "NO"

结果是"NO"

为什么 0.40 不是 >=.40?

来自文档

Representation error refers to the fact that some (most, actually) decimal fractions cannot be represented exactly as binary (base 2) fractions. This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many others) often won’t display the exact decimal number you expect:

0.1 + 0.2
0.30000000000000004

Python 提供受控环境以使用“Decimal". It provides multiple options to control/tweak the rounding with amount of rounding along with different strategies.(https://docs.python.org/3.5/library/decimal.html#rounding-modes”形式的浮点数。

from decimal import Decimal, ROUND_HALF_EVEN
a = Decimal(219.92).quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN)
b = Decimal(219.52).quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN)
priceDiff = a - b
cmp = Decimal(0.40).quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN)

if priceDiff.compare(cmp) >= 0:
    print "YES"
else:
    print "NO"

print(d)
print(d2)
print(priceDiff)
print(cmp)

恕我直言,这在可读性和对精度敏感的计算的实施方面更好 w.r.t 应用程序。希望这有帮助