Sure Mr. Aivar Paalberg. I would like to Thankyou for sharing the informative link. I am sure I will go through on floating Point limitations. I have simple concern that since childhood I learnt that 0.29 * 100 = 29 only, even simple calculator returning 29 only. I feel like Python proving them Wrong.
In One of my application I came across this logic which is giving wrong results for business(Business Impact). I am sure we can solve this with round(0.29 * 100). Out of curiosity posted this to understand the Python’s programmatical view in treating the multiplication in these 2 scenarios.
Welcome to floating point numbers and computers.
The short answer is that most decimal numbers, i.e. 0.28 * 100 can not be representeded exactly as the computer stores them in binary, for example 28 .0 is not the same as 0.28 * 100.0 there is an error.
In your childhood, you also probably learned that one third is 0.33333333, but that it goes on forever. Since you don’t have infinite paper, you can’t write down all the digits of one third. Try doing some arithmetic with it:
0.666666666666667 (because you round up with two thirds)
It’s never going to be perfect. You always have to round one way or the other, and whichever way you round, it’ll be a little bit wrong. Computers are doing the exact same thing, and 0.28 is actually stored as (binary) 0.0100011110101110000101000111101011100001010001111011; it really should be infinitely repeating, but it just can’t.
Python is not proving anything wrong here. It shows the limitations of representing fractions in a limited number of digits. The representation may be exact in some number base and an approximation in another.
If you need an exact value, try fraction.Fraction (fractions — Rational numbers — Python 3.10.6 documentation). However, that’s for rational numbers, so it too has its limitations.