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???

18th Oct 2016, 9:40 AM
Konstantin Markov
Konstantin  Markov - avatar
5 odpowiedzi
+ 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.
18th Oct 2016, 11:00 AM
Kirk Schafer
Kirk Schafer - avatar
+ 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
18th Oct 2016, 11:08 AM
bea.
bea. - avatar
+ 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.
18th Oct 2016, 1:01 PM
Kirk Schafer
Kirk Schafer - avatar
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.
4th Feb 2017, 11:56 PM
Alexander Kozhaev
Alexander Kozhaev - avatar
- 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?
18th Oct 2016, 12:49 PM
Scivias
Scivias - avatar