Finding multiple of a decimal number in a floating point list

Dan Lenski dlenski at gmail.com
Mon Aug 18 14:10:30 EDT 2008


On Mon, 18 Aug 2008 18:04:53 +0000, Dan Lenski wrote:

> On Mon, 18 Aug 2008 10:52:45 -0700, Alejandro wrote:
> 
>> 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.
> 
> Hi Alejandro, you can do the same thing more efficiently (both in terms
> of lines of code and execution speed) by doing the whole array at once:
> 
> from numpy import arange, absolute
> from math import modf, fabs
> 
> float_range = arange(0, 1, 0.01)
> multiples = absolute(float_range % 0.2)<1e-13 # now multiples is a
> boolean array
> print float_range[multiples]
> 
> HTH,
> Dan

Oh, I forgot that you have to check the other case of it being slightly 
less than a multiple too!

from numpy import arange, absolute
from math import modf, fabs

float_range = arange(0, 1, 0.01)
mod = absolute(float_range % 0.2)
multiples = (mod < 1e-13) + (mod > 0.2-1e-13)
print float_range[multiples]

That should do the trick!

Dan



More information about the Python-list mailing list