[ fractional part of numpy array ]
I need to get only the fractional part of an array. using numpy or simply python modf function is convenient.
In case we big arrays of positive fractional data, that can be as big as (1000000,3) for instance, what is more convenient to do:
numpy.modf(array)[0]
array-numpy.trunc(array)
In my opinion 2 is faster and cheaper in memory usage ... but not sure. What do python and numpy experts think ?
Answer 1
I'm not an expert, so I have to use the timeit
module to check speed. I use IPython (which makes timing things really easy) but even without it the timeit
module is probably the way to go.
In [21]: a = numpy.random.random((10**6, 3))
In [22]: timeit numpy.modf(a)[0]
10 loops, best of 3: 90.1 ms per loop
In [23]: timeit a-numpy.trunc(a)
10 loops, best of 3: 135 ms per loop
In [24]: timeit numpy.mod(a, 1.0)
10 loops, best of 3: 68.3 ms per loop
In [25]: timeit a % 1.0
10 loops, best of 3: 68.1 ms per loop
The last two are equivalent. I don't know much about memory use, but I'd be surprised if modf(a)[0]
and a-numpy.trunc(a)
both didn't use more memory than simply taking the mod directly.
[BTW, if your code does what you want it to and you're only interested in improvements, you might be interested in the codereview stackexchange. I still don't have a good handle on where the dividing line is, but this feels a little more like their cup of tea.]