[Numpy-discussion] Array of size 'n' with common difference < 1
Sebastian Haase
seb.haase at gmail.com
Fri Apr 29 16:27:06 EDT 2011
On Fri, Apr 29, 2011 at 5:41 PM, Christopher Barker
<Chris.Barker at noaa.gov> wrote:
> On 4/29/11 12:31 AM, pratik wrote:
>> On Friday 29 April 2011 12:56 PM, dileep kunjaai wrote:
>>> Dear sir,
>>> I am trying to make an array of varies from -60 to 90 with difference
>>> 0.25. I tried the following command ...
>
>>> >>import numpy as N
>>> lat=N.array(xrange(-6000, 9000, 25), dtype=float)
>>> print lat/100
>
> xrange() (or range(), or np.arange()) is almost never the right solution
> for floating point ranges, due to the intricacies of floating point
> precision.
>
>> lat =numpy.mgrid[-60:90:.25]
>
> or np.linspace:
>
> np.linspace(-60,90,((60.+90.)*4. + 1))
>
> ((60.+90.)*4. + 1) is the number of points you want -- the +1 because
> you want both end points.
>
> mgrid is usually used for 2-d (or higher) grids, though it looks like it
> makes sense for this use, too, though note that it doesn't give you both
> endpoints in this case. From the docs:
>
> """If the step length is not a
> complex number, then the stop is not inclusive.
> """
>
> and an example:
>
> In [15]: np.mgrid[-1:3:.25]
> Out[15]:
> array([-1. , -0.75, -0.5 , -0.25, 0. , 0.25, 0.5 , 0.75, 1. ,
> 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 , 2.75])
>
> I think this is too bad, actually, because we're back to range()-type
> tricks to get the end point:
>
> In [20]: np.mgrid[-1:3.25:.25]
> Out[20]:
> array([-1. , -0.75, -0.5 , -0.25, 0. , 0.25, 0.5 , 0.75, 1. ,
> 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 , 2.75, 3. ])
>
>
Just for completeness, note this paragraph from the mgrid docs:
However, if the step length is a *complex number* (e.g. 5j), then the
integer part of its magnitude is interpreted as specifying the number
of points to create between the start and stop values, where the stop
value *is inclusive*.
-Sebastian Haase
More information about the NumPy-Discussion
mailing list