[Numpy-discussion] Weird numpy.arange behavoir
Luke
hazelnusse at gmail.com
Wed Jun 6 21:55:42 EDT 2007
I am integrating some equations and need to generate rank 1 time
arrays to pass to my integrator. I need them to have the same
interval between each entry and have the same number of elements. In
matlab this is trivial, and it is in numpy as well, except I'm getting
some weird behavoir:
import numpy as N
T = 0.1
dt = 0.01
k=0
t = N.arange(k*T,(k+1)*T+h,h)
Output:
array([ 0. , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08,
0.09, 0.1 ])
So far so good.
Here is where the problem arises:
k=1
t = N.arange(k*T,(k+1)*T+h,h)
array([ 0.1 , 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18,
0.19, 0.2 , 0.21])
Note that this time array has more entries, and in fact, the last
entry is greater than (k+1)*T = (1+1)*0.01 = 2*0.01 = 0.2
Now if it was consistent for all k>0, then it would be fine. However,
this is not the case:
k=3
t = N.arange(k*T,(k+1)*T+h,h)
Output:
array([ 0.3 , 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38,
0.39, 0.4 ])
Now, this one has the same number of entries as the case where k=0.
Can anybody:
1) Offer a solution to this?
2) Explain this behavoir would occur and ever be desirable?
I read the numpy.arange docstring and it says that this may occur, but
I don't understand why you would ever want this to occur. Apparently,
the length of the returned array is:
ceil((stop-start)/step)
The weird thing is that in this simple example, (stop-start)/step is
always exactly 11, since ((k+1)*T + h - k*T)/(h) = (T+h)/h =
(0.1+0.01)/(0.01) = 11.0. In this, there shouldn't be any roundoff
error. So in this simple example that was harmlessly constructed
(i.e., my period time was an exact integer multiple of my step time),
arange behaves undesirably (at least I think it does).
After a few tests, I found that if instead of ceil, round was used,
then it eliminated my problem, but I don't know if this would have
other undesirable effects in other situations.
I guess I could use range, but it is just a bit more tedious to code.
Thanks,
~Luke
More information about the NumPy-Discussion
mailing list