Why in Python 0.03 % 0.01 = 0.009999999999998 and not 0?

Asked

Viewed 475 times

4

>>> 0.03 % 0.01
0.009999999999999998

Why gives this result, the rest of the division being 0?

And also, instead of 3, give:

>>> 0.03 // 0.01
2.0
  • Read these references: 1, 2, 3 and 4. Especially in the refs of the answers given here.

  • Not only in Python, but in any programming language that uses floating points of IEEE 754

2 answers

14


11

Short answer: Precision problems in floating point operations.


Decimal numbers are represented on the computer as decimal fractions. For example, 0.125(10) = 0.001(2). Nothing new - but if so, take a look at this short summary in Wikipedia on floating comma.

The problem is when we enter numbers that cannot be easily described by a binary fraction that result in infinite tithes like the case of 1/3 = 0.33(3) in the decimal system.

Computers do not have an infinite number of bits so they use approximate representations of the numbers they intend to represent. They are very close presentations but they are still not the number in question.

>>> 0.1
0.1000000000000000055511151231257827021181583404541015625

Python (among other languages) can detect these cases and present the user with a "rounded" representation of the user that corresponds to what would be expected:

>>> 1 / 10
0.1

However this does not change the value that is in memory. So, when doing 0.03 % 0.01 is not even to do the rest of the 0.03 by 0.01 division but rather the rest of the 0.03 by 0.01 memory division, resulting in the error you see:

>>> 0.03 % 0.01
0.009999999999999998

Source: The Python Tutorial - Floating-point arithmetic operations: problems and limitations (in English)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.