noob: Decimal Comparison in Python

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jan 2007
Posts: 58
Reputation: jobs is an unknown quantity at this point 
Solved Threads: 0
jobs jobs is offline Offline
Junior Poster in Training

noob: Decimal Comparison in Python

 
0
  #1
Nov 4th, 2007
How do you compare two decimal numbers in python?
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 137
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: noob: Decimal Comparison in Python

 
0
  #2
Nov 4th, 2007
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:
  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.
Should you find Irony, you can keep her!
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: noob: Decimal Comparison in Python

 
0
  #3
Nov 4th, 2007
I've resorted to creating a function:

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

Jeff
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 311
Reputation: BearofNH is on a distinguished road 
Solved Threads: 40
BearofNH's Avatar
BearofNH BearofNH is offline Offline
Posting Whiz

Re: noob: Decimal Comparison in Python

 
0
  #4
Nov 6th, 2007
If you mean decimal, not float, I don't see the need for anything special. E.g.,
  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. >>>
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC