There are a few NumPy functions that are similar in application, but which
provide slightly different results, which may cause confusion if one is not sure
when and how to use them. The following guide aims to list these functions and
describe their recommended usage.
Both numpy.linspace and numpy.arange provide ways to partition an interval
(a 1D domain) into equal-length subintervals. These partitions will vary
depending on the chosen starting and ending points, and the step (the length
of the subintervals).
numpy.arange relies on step size to determine how many elements are in the
returned array, which excludes the endpoint. This is determined through the
step argument to arange.
The arguments start and stop should be integer or real, but not
complex numbers. numpy.arange is similar to the Python built-in
range.
Floating-point inaccuracies can make arange results with floating-point
numbers confusing. In this case, you should use numpy.linspace instead.
Usenumpy.linspaceif you want the endpoint to be included in the
result, or if you are using a non-integer step size.
numpy.linspacecan include the endpoint and determines step size from the
num argument, which specifies the number of elements in the returned
array.
The inclusion of the endpoint is determined by an optional boolean
argument endpoint, which defaults to True. Note that selecting
endpoint=False will change the step size computation, and the subsequent
output for the function.
Example:
>>> np
Other examples
Unexpected results may happen if floating point values are used as step
in numpy.arange. To avoid this, make sure all floating point conversion
happens after the computation of results. For example, replace
>>> list(np.arange(0.1,0.4,0.1).round(1))[0.1, 0.2, 0.3, 0.4] # endpoint should not be included!
geomspace and logspace
numpy.geomspace is similar to numpy.linspace, but with numbers spaced
evenly on a log scale (a geometric progression). The endpoint is included in the
result.
Similar to numpy.mgrid, numpy.ogrid returns an open multidimensional
meshgrid. This means that when it is indexed, only one dimension of each
returned array is greater than 1. This avoids repeating the data and thus saves
memory, which is often desirable.
These sparse coordinate grids are intended to be used with Broadcasting.
When all coordinates are used in an expression, broadcasting still leads to a
fully-dimensional result array.
These differ because of numeric noise. When using floating point values, it
is possible that 0+0.04*28<1.12, and so 1.12 is in the
interval. In fact, this is exactly the case:
>>> 1.12/0.0428.000000000000004
But 0+0.04*27>=1.08 so that 1.08 is excluded:
>>> 1.08/0.0427.0
Alternatively, you could use np.arange(0,28)*0.04 which would always
give you precise control of the end point since it is integral: