Does anyone know a good way in Python to check if a number is divisible by another in floating point in python?
The first thing I tried was ...
3.5 % 0.1 == 0.0
But this returns False so then maybe
3.5 % 0.1 >= 1e-6
But also False ... bummer ... it turns out that
3.5 % 0.1
>> 0.099999999924
So then this works:
LAMBDA = 1e-9
def is_divisible_by(x, y):
m = x % y
dy = abs(y - m)
return m < LAMBDA or dy < LAMBDA
is_divisible_by(3.5, 0.1)
But this seems dangerous because I have to pick a LAMBDA. What about if y = LAMBDA / 2...
is_divisible_by(LAMBDA/2, (LAMBDA/2) + 1e-10)
>>> True
So then
def is_divisible_by(x, y):
l = y * 1e-2
m = x % y
dy = abs(y - m)
return m < l or dy < l
is_divisible_by(3.5 * 1e-10, 0.1 * 1e-10)
>>> True
is_divisible_by(0.21, 0.211)
>>> True
Bummer.
Is there anyway to solve this without going down a massive rabbit hole?
Depending on the source of your floating point numbers, the decimal module might be useful.
>>> import decimal
>>> decimal.Decimal("3.5") % decimal.Decimal("0.1")
Decimal('0.0')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With