+ 3

Why is 0.1 * 3 not equal to 0.3 in Python?

https://code.sololearn.com/ce92KxDmm0i9/?ref=app This is unexpected and I cannot understand why I am getting this result. On printing 0.1 * 3 the output is not 0.3 but 0.300000004.

29th Sep 2018, 6:47 AM
Ashwani Kumar Kamal
Ashwani Kumar Kamal - avatar
5 ответов
+ 3
Interesting...
30th Sep 2018, 10:51 AM
ShortCode
+ 3
Python can’t accurately hold decimals as floats, as in binary 1/10 turns into a repeating decimal, so it rounds to a good amount of decimal places that is fine for normal use. It works just like the repeating decimal 1/3, which infinitely repeats.
30th Sep 2018, 11:52 PM
soup
+ 2
It's funny, this is what CS101 would show you about the limitations of floating point numbers, yet a lot of people on here stumble across it by themselves. It's good though as it's important to know (:
29th Sep 2018, 7:26 AM
Dan Walker
Dan Walker - avatar
+ 1
In a given base, you only get a terminating decimal when the denominator is expressed only in powers of primes in the prime factorisation of that base i.e. 10 = 2 × 5, so only denominators of the form 2^n × 5^m are terminating (n, m >= 0) so only powers of 1/2 have exact representations in binary
1st Oct 2018, 7:00 AM
Dan Walker
Dan Walker - avatar