[Numpy-discussion] simple problem with arange / roundoff
Timothy Hochberg
tim.hochberg@ieee....
Tue Jul 31 09:44:20 CDT 2007
On 7/31/07, Eric Emsellem <emsellem@obs.univ-lyon1.fr> wrote:
>
> Hi,
>
> I discovered a bug in one of my program probably due to a round-off
> problem in a "arange" statement.
> I use something like:
>
> step = (end - start) / (npix - 1.)
> gridX = num.arange(start-step/2., end+step/2., step)
>
> where I wish to get a simple 1D array with npix+1 numbers going from
> (start-step/2.) to (end+step/2.).
>
> But then, "arange" often gets me an array only going from
> "start-step/2." to "end - step/2." instead, due very probably to
> round-off problems (I guess it does not reach the last value because
> <<(start-step/2.) + npix * step >> is found to be larger than
> (end+step/2.).
>
> Here is an example:
>
> start = -30.
> end = 30.
> npix = 31
> step = (end - start) / (npix - 1.)
> gridX = num.arange(start-step/2., end+step/2., step)
> array([-31., -29., -27., -25., -23., -21., -19., -17., -15., -13., -11.,
> -9., -7., -5., -3., -1., 1., 3., 5., 7., 9., 11.,
> 13., 15., 17., 19., 21., 23., 25., 27., 29.])
>
> As you can see, it does not go up to 31., but only to 29, although step
> is = 2.0
>
> Is there is a way out of this ?
> (except by doing the silly: gridX = num.arange(start-step/2.,
> end+1.001*step/2., step) )
Yes. Don't use arange with floating point numbers steps. Either write this
as something equivalent to:
gridX = num.arange(npix) * step + start
or use linspace.
gridX = num.linspace(start, stop, npix)
Thanks for any input there (and sorry for the silly question)
>
> Eric
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
--
. __
. |-\
.
. tim.hochberg@ieee.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20070731/07403f7e/attachment.html
More information about the Numpy-discussion
mailing list