How do you compare two decimal numbers in python?

I assume you mean floating point numbers. The way they are represented in most computer languages you can have small roundoff errors in the last bit. You have to compare them in narrow range, example:

pi1 = 355/113.0
print pi1  # 3.14159292035

pi2 = 3.14159
delta = 0.00003
# compare within narrow range
if (pi2 + delta) > pi1 > (pi2 - delta):
    print 'close enough'

Python also has high accuracy module decimal avoiding round off errors.

I've resorted to creating a function:

def fuzzyequals(a,b,delta = 0.00001):
    return -delta < a-b < delta

Jeff

If you mean decimal, not float, I don't see the need for anything special. E.g.,

>>> import decimal
>>> x1 = decimal.Decimal("4.567567567")
>>> x2 = decimal.Decimal("4.56756757")
>>> if x1==x2:
...     print "OK!"
...
>>> if x1<x2:
...     print "OK!"
...
OK!
>>>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.