Numerical Errors when Dividing Floats and Python Rationals

Development | Programming languages
Author
autor-image
Alto Lagato
Content

So, I was writing a program and testing it. After eliminating the truncation errors, I discovered that there is another type of error that happens for dividing 2 floats/rational in python.

(ml_optimization) C:\Users\victo>python
Python 3.7.7 (default, May  6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.9/0.3
3.0
>>> 0.99/0.33
3.0
>>> 0.57/0.19
2.9999999999999996
>>> 0.63/0.21
3.0
>>> 0.75/0.25
3.0
>>> 0.66/0.22
3.0
>>> 0.54/0.18
3.0000000000000004
>>> 0.51/0.17
3.0
>>> import fractions as frac
>>> float(frac.Fraction(0.57)/frac.Fraction(0.19))
2.9999999999999996
>>>
In general, I want to know:

I want to know what is going on here? Why is it happening for division involving 3 in particular, but not all the cases? If this happens, how does it happen for IEEE 754 AND Python Rational?

For my project I want to know: How to detect this? How to correct this?

Attachments
No attachments

Deadline: 31.12.2030

Comments
autor-image
Senior Python Developer
Python forever!
Do not do if (x == y) { ... }
Instead do if (abs(x - y) < myToleranceValue) { ... }.

03.08.2020, 10:35:02
-
You must be logged for add a new comment and price offer! LOGIN
We use cookies to give you the best possible experience on our site. By continuing to use the site you agree to our use of cookies. Find out more Accept