| | |
noob: Decimal Comparison in Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
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 also has high accuracy module decimal avoiding round off errors.
python Syntax (Toggle Plain Text)
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'
Should you find Irony, you can keep her!
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
I've resorted to creating a function:
Jeff
Python Syntax (Toggle Plain Text)
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.,
Python Syntax (Toggle Plain Text)
>>> import decimal >>> x1 = decimal.Decimal("4.567567567") >>> x2 = decimal.Decimal("4.56756757") >>> if x1==x2: ... print "OK!" ... >>> if x1<x2: ... print "OK!" ... OK! >>>
![]() |
Similar Threads
- Why should i learn Python? (Python)
- Starting a project in python (Game and quiz) (Python)
- Python noob needs random help (Python)
- wxCanvas-Get current coordinates (Python)
- Comparing Python and C, Part 10, Structures (Python)
- Including other python programs (Python)
- Convert from JAVA/JSP to Python (Python)
- Computer Languages Comparison Tutorials (Computer Science)
Other Threads in the Python Forum
- Previous Thread: assign the values to each members of a large list of class objects
- Next Thread: about image
| Thread Tools | Search this Thread |
abrupt ansi anti apache approximation array assignment backend beginner binary book builtin calculator character chmod converter countpasswordentry curved customdialog dan08 dictionaries dictionary drive dynamic examples exe file filename float format function gui heads homework import inches input java launcher library line lines linux list lists loop mouse mysql mysqlquery number numbers numeric output parsing path phonebook plugin pointer port prime programming progressbar projects py2exe pygame pysimplewizard python random recursion redirect scrolledtext software statictext statistics string strings sum table terminal text textarea thread threading time tkinter tlapse trick tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable windows wordgame write wxpython






