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.
numpy.arange
Section titled “numpy.arange”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:
| Parameter | Description |
|---|---|
| start | Optional. The starting value of the interval. Defaults to 0 if not provided. |
| stop | The 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. |
| step | Optional. The spacing between consecutive values. Defaults to 1. |
| dtype | Optional. 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:
Example 1: Basic usage
Section titled “Example 1: Basic usage”import numpy as np
# Create an array with values from 0 up to (but not including) 5x = np.arange(5)print(x)Output:
[0 1 2 3 4]Example 2: Specifying data type
Section titled “Example 2: Specifying data type”import numpy as np
# Create an array with float valuesx = 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 2x = 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.
numpy.linspace
Section titled “numpy.linspace”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:
| Parameter | Description |
|---|---|
| start | The starting value of the sequence. |
| stop | The end value of the sequence. By default, this value is included in the array. |
| num | Optional. The number of evenly spaced samples to generate. Defaults to 50. |
| endpoint | Optional. If True (default), stop is the last sample. If False, stop is not included. |
| retstep | Optional. If True, returns a tuple (samples, step), where step is the calculated spacing between samples. |
| dtype | Optional. 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. ]Example 2: Exclude the endpoint
Section titled “Example 2: Exclude the endpoint”import numpy as np
# Generate 5 points, excluding the endpoint 20x = np.linspace(10, 20, 5, endpoint=False)print(x)Output:
[10. 12. 14. 16. 18.]Example 3: Return the step size
Section titled “Example 3: Return the step size”import numpy as np
# Generate 5 points between 1 and 2, and get the step sizex, 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.25Application: 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.
numpy.logspace
Section titled “numpy.logspace”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:
| Parameter | Description |
|---|---|
| start | The starting exponent: base ** start is the first value. |
| stop | The ending exponent: base ** stop is the last value (if endpoint=True). |
| num | Optional. Number of samples to generate. Default is 50. |
| endpoint | Optional. If True (default), stop exponent is included. |
| base | Optional. The base of the logarithm. Default is 10.0. |
| dtype | Optional. Data type of the output array. If not given, inferred (usually float64). |
Explore these examples:
Example 1: Default base 10
Section titled “Example 1: Default base 10”import numpy as np
# Generate 10 samples from 10^1 to 10^2a = 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. ]Example 2: Using base 2
Section titled “Example 2: Using base 2”import numpy as np
# Generate 10 samples from 2^1 to 2^10a = 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.