Greater than or equal for floats failed

yellowandy picture yellowandy · Jan 17, 2017 · Viewed 10.2k times · Source

I was running a small python test I wrote against some data and got some weird results. 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?

Answer

Anuragh27crony picture Anuragh27crony · Jan 17, 2017

Python offers controlled environment to work with floats in the form of "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)

IMHO this is better interms of readability and implementaion of calculations that are precision sensitive w.r.t application. Hope this helps