+ 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.
5 Respostas
+ 3
Interesting...
+ 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.
+ 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 (:
+ 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