Strange behavior of mod with float


What is the best way to determine if a float number b is an integer multiple of another float number a, (i.e. b = k a with k an integer)? I wanted to use the following test
abs(mod(b, a))<1e-12, but I am confused with the behavior of the mod routine:

@show mod(2*0.1, 0.1), mod(3*0.1, 0.1), mod(5*0.1, 0.1), mod(8*0.1, 0.1), mod(9*0.1, 0.1)


(0.0, 2.7755575615628914e-17, 0.09999999999999998, 0.0, 0.09999999999999998)

Aren’t we supposed to get 0 for all these results (up to machine precision)? I would appreciate your help for a more robust test.

Linking similar thread.

1 Like

Thank you for your answer. I definitely missed this thread.

1 Like

For what it’s worth you can get that idea to work if you shift the mod away from zero:

abs(mod(b + 0.5 * a, a) - 0.5 * a) < 1e-12