Skip to content

Array From Numerical Ranges

NumPy - Creating Arrays from Numerical Ranges

Section titled “NumPy - Creating Arrays from Numerical Ranges”

NumPy provides several convenient functions to create arrays initialized with numerical sequences. This chapter explores the most common ones: numpy.arange, numpy.linspace, and numpy.logspace.

The numpy.arange function returns an ndarray containing evenly spaced values within a specified interval. It’s similar to Python’s built-in range function but returns a NumPy array.

numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)

Key parameters:

ParameterDescription
startOptional. The starting value of the interval. Defaults to 0 if not provided.
stopThe end value of the interval. The interval does not include this value, except in some cases where step is not an integer and floating-point inaccuracies affect the result.
stepOptional. The spacing between consecutive values. Defaults to 1.
dtypeOptional. The desired data type for the array elements. If not specified, NumPy infers the type from the other input arguments (usually int64 or float64).

Note: Using floating-point numbers for the step parameter can sometimes lead to unexpected results due to the limitations of floating-point precision. For cases requiring precise non-integer steps, numpy.linspace is often a better choice.

Let’s look at some examples:

import numpy as np
# Create an array with values from 0 up to (but not including) 5
x = np.arange(5)
print(x)

Output:

[0 1 2 3 4]
import numpy as np
# Create an array with float values
x = np.arange(5, dtype=np.float64)
print(x)

Output:

[0. 1. 2. 3. 4.]

Example 3: Specifying start, stop, and step

Section titled “Example 3: Specifying start, stop, and step”
import numpy as np
# Create an array starting at 10, ending before 20, with a step of 2
x = np.arange(10, 20, 2)
print(x)

Output:

[10 12 14 16 18]

Application: arange is useful for generating sequences for indexing, iteration, or defining coordinates with a fixed step size.

For more details, see the official numpy.arange documentation.

The numpy.linspace function creates an array with a specified number of evenly spaced values over a defined interval. Unlike arange, where you define the step, here you define the total number of elements you want.

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

Key parameters:

ParameterDescription
startThe starting value of the sequence.
stopThe end value of the sequence. By default, this value is included in the array.
numOptional. The number of evenly spaced samples to generate. Defaults to 50.
endpointOptional. If True (default), stop is the last sample. If False, stop is not included.
retstepOptional. If True, returns a tuple (samples, step), where step is the calculated spacing between samples.
dtypeOptional. The data type of the output array. If not given, it’s inferred (usually float64).

Let’s see linspace in action:

Example 1: Generate 5 samples between 10 and 20

Section titled “Example 1: Generate 5 samples between 10 and 20”
import numpy as np
# Generate 5 evenly spaced points between 10 and 20 (inclusive)
x = np.linspace(10, 20, 5)
print(x)

Output:

[10. 12.5 15. 17.5 20. ]
import numpy as np
# Generate 5 points, excluding the endpoint 20
x = np.linspace(10, 20, 5, endpoint=False)
print(x)

Output:

[10. 12. 14. 16. 18.]
import numpy as np
# Generate 5 points between 1 and 2, and get the step size
x, step = np.linspace(1, 2, 5, retstep=True)
print(f"Array: {x}")
print(f"Step size: {step}")

Output:

Array: [1. 1.25 1.5 1.75 2. ]
Step size: 0.25

Application: linspace is ideal for generating sample points for plotting functions, creating coordinate grids, or when you need a specific number of elements within a range.

Find more information in the official numpy.linspace documentation.

The numpy.logspace function creates an array with numbers that are evenly spaced on a logarithmic scale. You specify the start and stop exponents, and the base (usually 10).

numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)

Key parameters:

ParameterDescription
startThe starting exponent: base ** start is the first value.
stopThe ending exponent: base ** stop is the last value (if endpoint=True).
numOptional. Number of samples to generate. Default is 50.
endpointOptional. If True (default), stop exponent is included.
baseOptional. The base of the logarithm. Default is 10.0.
dtypeOptional. Data type of the output array. If not given, inferred (usually float64).

Explore these examples:

import numpy as np
# Generate 10 samples from 10^1 to 10^2
a = np.logspace(1.0, 2.0, num=10)
print(a)

Output (values may vary slightly due to floating point representation):

[ 10. 12.91549665 16.68100537 21.5443469 27.82559402
35.93813664 46.41588834 59.94842503 77.42636827 100. ]
import numpy as np
# Generate 10 samples from 2^1 to 2^10
a = np.logspace(1, 10, num=10, base=2.0)
print(a)

Output:

[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]

Application: logspace is commonly used when dealing with data spanning several orders of magnitude, such as frequency sweeps in signal processing or setting axis limits for logarithmic plots.

Consult the official numpy.logspace documentation for further details.