944,052 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 1946
  • Python RSS
Nov 4th, 2007
0

noob: Decimal Comparison in Python

Expand Post »
How do you compare two decimal numbers in python?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
jobs is offline Offline
58 posts
since Jan 2007
Nov 4th, 2007
0

Re: noob: Decimal Comparison 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:
python Syntax (Toggle Plain Text)
  1. pi1 = 355/113.0
  2. print pi1 # 3.14159292035
  3.  
  4. pi2 = 3.14159
  5. delta = 0.00003
  6. # compare within narrow range
  7. if (pi2 + delta) > pi1 > (pi2 - delta):
  8. print 'close enough'
Python also has high accuracy module decimal avoiding round off errors.
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Nov 4th, 2007
0

Re: noob: Decimal Comparison in Python

I've resorted to creating a function:

Python Syntax (Toggle Plain Text)
  1. def fuzzyequals(a,b,delta = 0.00001):
  2. return -delta < a-b < delta

Jeff
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Nov 6th, 2007
0

Re: noob: Decimal Comparison in Python

If you mean decimal, not float, I don't see the need for anything special. E.g.,
Python Syntax (Toggle Plain Text)
  1. >>> import decimal
  2. >>> x1 = decimal.Decimal("4.567567567")
  3. >>> x2 = decimal.Decimal("4.56756757")
  4. >>> if x1==x2:
  5. ... print "OK!"
  6. ...
  7. >>> if x1<x2:
  8. ... print "OK!"
  9. ...
  10. OK!
  11. >>>
Reputation Points: 94
Solved Threads: 48
Posting Whiz
BearofNH is offline Offline
321 posts
since May 2007

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: assign the values to each members of a large list of class objects
Next Thread in Python Forum Timeline: about image





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC