0
Float * int (mistake): a=179*1.13 print(a) Output = 202,269999999999999 But right answer is 202.27 What is the mistake in python???
5 Answers
+ 3
It's not a mistake...in the sense that some clever entities had to figure out how to approximate floats [a stream of digits] in binary [a precision value system]. The imprecision results from collisions in how floats are stored [truncated] internally, within an 'acceptable' margin of error [a matter of perspective, since the wiggle room can be quantum-ly 'useful'].
1.13 has a max precision of...
1.12999999523162841796875E0
http://www.binaryconvert.com/result_float.html?decimal=049046049051
And 179 (1.79E2):
http://www.binaryconvert.com/result_float.html?decimal=049055057
Using truncated numbers...
>>> 1.129999*1.79*100
202.26982100000001
and as I increase precision I'll approach your value. The user Zen provided this site originally in another thread; see Bea's answer for typical handling.
+ 1
use round(number[, ndigits]) if you want to get the rounded decimal. Although, the behavior of round() for floats can be surprising, example: round(1.875, 2) gives 1.87 instead of the expected 1.88. It's not a bug: itâs a result of the fact that most decimal fractions canât be represented exactly as a float. The decimal string 1.875 is converted to a binary approximation (like 1.87499999999 etc etc). In that case, use from decimal import
+ 1
@Scivias Perhaps unfortunately for your question, these 'insights' (if this even is one) usually come to me all in a rush. I hinted at the other people because I always feel like I'm catching up to smarter people; maybe Zen will be around later to contribute.
0
Try to do 0.1 + 0.1 + 0.1 - 0.3. There are differences between math real numbers and fpu real numbers. In math they are infinite, compact an uninterrupted. In fpu they are finite and discrete. That's why you need, for example, to compare float numbers with the precision like that abs(a-b)<epsilon. It will be true if float numbers are equal in fpu.
- 1
I cannot give a technical explanation as others have done, but I do know that when I learned the BASIC programming language 25 years ago (anyone else old enough to remember BASIC?) it would do the same thing. So I am not surprised to see it's an issue in Python. It just has to do with how computers do math. There are ways to correct it as others have mentioned. Question: do these corrections/workarounds have to be integrated into every script to ensure good output?