Finding multiple of a decimal number in a floating point list
Alejandro
alejandro.weinstein at gmail.com
Mon Aug 18 13:52:45 EDT 2008
Hi:
I need to find the multiples of a decimal number in a floating point
list. For instance, if a have the list [0,0.01,0.02,...1], I want the
multiples of 0.2: [0, 0.2,0.4,0.6,0.8,1].
With integers this problem is easy, just test for (i%n == 0), where i
is the number I am testing, and n is the multiple. Given the finite
resolution of floating point numbers, this is more complicated for
float.
I came with this solution:
from numpy import arange
from math import modf, fabs
float_range = arange(0, 1, 0.01)
for f in float_range:
m = modf(f / 0.2)[0]
if m<1e-13 or fabs(1-m)<1e-13:
print f
# Do something else
This code works, however, I found it a little ugly. Is there a better
way to do the same?
Alejandro.
More information about the Python-list
mailing list