Incorrect Decimal-Float behaviour in comparison tests

Steve Holden steve at holdenweb.com
Fri Mar 3 17:39:56 CET 2006


Cassiano, Marco wrote:
> I have difficulties with a weird Python 2.4.2 behaviour in comparing Decimal to Floats.
> 
> For Example :
> 
> 
> 
>>>>from decimal import Decimal
>>>>a=Decimal('3.7')
>>>>b=6.3
> 
> 
>>>>if a > b :print a,b,'a is greater than b - NOT TRUE!!!!'
> 
> ... else: print a,b,'b is greater than a - CORRECT'
> ... 
> 
> 
> 3.7 6.3 a is greater than b - NOT TRUE!!!!
> 
> 
> Have you ever encountered this behaviour ? It seems a bug to me...
> Do you konw if there is any patch available for this?
> 
  >>> if a > Decimal(str(b)):
  ...   print "oh oh!"
  ... else:
  ...   print "This looks better"
  ...
This looks better
  >>>

Decimals and floats aren't meant to be directly compared. You can't 
even convert a float directly into a Decimal:

  >>> Decimal(3.7)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "/usr/lib/python2.4/decimal.py", line 534, in __new__
     raise TypeError("Cannot convert float to Decimal.  " +
TypeError: Cannot convert float to Decimal.  First convert the float to 
a string

So what you are seeing is the result of a comparison based on types: you 
will probably find that all floats compare less than all Decimals.

The correct thing to do is apply the float() function to Decimals before 
comparing them with other floats:

  >>> if float(a) > float(b):
  ...   print "a > b"
  ... else:
  ...   print "b > a"
  ...
b > a
  >>>

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd                 www.holdenweb.com
Love me, love my blog         holdenweb.blogspot.com




More information about the Python-list mailing list