简体   繁体   English

大于或等于浮动失败

[英]Greater than or equal for floats failed

I was running a small python test I wrote against some data and got some weird results. 我正在运行一个针对某些数据编写的小型python测试,并得到了一些奇怪的结果。 Boiled it down to this: 归结为:

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

The result is "NO" 结果为“否”

Why is 0.40 not >= .40? 为什么0.40不是> = .40?

From Documentation 从文档

Representation error refers to the fact that some (most, actually) decimal fractions cannot be represented exactly as binary (base 2) fractions. 表示错误是指以下事实:某些(大多数,实际上)小数部分不能完全表示为二进制(基数2)分数。 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: 这是Python(或Perl,C,C ++,Java,Fortran和其他许多语言)经常不显示您期望的确切十进制数字的主要原因:

0.1 + 0.2
0.30000000000000004

Python offers controlled environment to work with floats in the form of " Decimal ". 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 ). 它提供了多个选项来控制/调整舍入,以及不同策略的舍入量。( 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)

IMHO this is better interms of readability and implementaion of calculations that are precision sensitive wrt application. 恕我直言,这是更好的可读性,是对精度要求较高的应用程序的计算的实现。 Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM