Im trying to do a project and for some reason the same divisions give me different results. I am trying to check if 2 divisions are equal and give me the same results but When I try 5.99/1
and 0.599/0.1
the script says that they are different while they are supposed to return the same results. I figured out what the problem is that 5.99/1 = 5.99
and 0.599/0.1 = 5.989999999999999
but I cant find a fix for this.
Asked
Active
Viewed 34 times
-2

IskandarG
- 1
- 1
- 3
-
Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Pranav Hosangadi Oct 22 '20 at 15:38
-
It doest answer my question on why this happens but I cant seem to find a fix for python. – IskandarG Oct 22 '20 at 15:42
-
Does it or doesn't it? You wrote "doest", which is halfway between does and doesn't :) Read the answers there carefully. The accepted answer contains a workaround for equality checks with floating point numbers. There is no _fix_ for this because it's an intrinsic problem with floating-point binary numbers. There are links in the answers to further information. [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) is pretty comprehensive – Pranav Hosangadi Oct 22 '20 at 15:45
-
there's no way to fix except using a decimal floating-point type – phuclv Oct 22 '20 at 15:46
-
For good alternatives, it is useful to see your true code. Consider posting a [mcve] to improve this question. – chux - Reinstate Monica Oct 22 '20 at 16:38
-
"When I try 5.99/1 and 0.599/0.1 the script says that they are different" --> Because `5.99, 5.999, 0.1` do not encode exactly as floating point numbers. Perhaps tolerate a small difference in the two quotients? Is that allowed? – chux - Reinstate Monica Oct 22 '20 at 16:41
-
its doesnt and by fix i meant a way to make my code work and round() function worked – IskandarG Oct 22 '20 at 17:22
1 Answers
0
You can find the reason in this answer: https://stackoverflow.com/a/588014/11502612
I have written a possible solution for you:
Code:
a = 5.99 / 1
b = 0.599 / 0.1
a_str = "{:.4f}".format(5.99 / 1)
b_str = "{:.4f}".format(0.599 / 0.1)
print(a, b)
print(a_str, b_str)
print(a == b)
print(a_str == b_str)
Output:
>>> python3 test.py
5.99 5.989999999999999
5.9900 5.9900
False
True
As you can see below I have converted the result of division to a formatted string and I check them instead of default floating type.

milanbalazs
- 4,811
- 4
- 23
- 45
-
1It's cheaper to do `abs(a - b) < 1e-4`, which is what the linked duplicate's accepted answer suggests. Please don't answer duplicate questions. Instead, flag / vote to close them. – Pranav Hosangadi Oct 22 '20 at 15:47