Modulus and float numbers

89 Views Asked by At

How modulus are interpreted is by saying how many times "a" can reach to "b" but not by multiplying, just by adding up.

If we were going to find the modulus of 20 from 1.3, it will add up 1.3 + 1.3 +...+ 1.3 = 19.5 which 20-19.5 will be 0.5.

But if we operate the formula that everyone explains with modulus, that's by dividing and multiplying and then getting the remainder, we will not get an exact number, for example:

6%2 = 0 and 7%2 = 1 because 6/2 = 3 times and 3*2 = 6, that's why answer is 0 and 1, but if we use 20 % 1.3 this will be 20/1.3 = 15.384615 and 15.384 times multiplied by 1.3 is 15.384615385 * 1.3 = 20 therefore this formula is not true, and shows the inability of expressing how modulus operates with float numbers, but by adding up 1.3 and then not passing 20, it will give 1.3 added 15 times = 19.5. 20 - 19.5 = 0.5 therefore we have an exact remainder.

I wanted to know if this approach is correct, and how does Python interprets modulus?

1

There are 1 best solutions below

2
Armali On

20 % 1.3 this will be 20/1.3 = 15,384615 and 15,384 times multiplied by 1,3 is 15,384615385 * 1,3 = 20 therefore this formula is not true…

I wanted to know if this approach is correct

Your computation is incomplete; therefore the conclusion is wrong.

You have to take the integer part, i. e. 15, multiply by 1.3, which gives 19.5, and subtract that from 20. This yields 0.5 as expected.

For Python's implementation see float_rem(). It uses fmod() to compute. The output representation is generated by float_repr(), which calls PyOS_double_to_string().
We get the same output with the C expression printf("%.17g\n", fmod(20, 1.3)).

It shouldn't be a surprise that floating point computation results are sometimes inexact.