NumPy: arange() and linspace() to generate evenly spaced values | note.nkmk.me (2024)

In NumPy, the np.arange() and np.linspace() functions generate an array (ndarray) of evenly spaced values. You can specify the interval in np.arange() and the number of values in np.linspace().

Contents

  • How to use np.arange()
  • How to use np.linspace()
    • Basic usage
    • Specify whether to include stop: endpoint
    • Get the interval: retstep
  • Convert to reverse order
  • Convert to multi-dimensional arrays

The NumPy version used in this article is as follows. Note that functionality may vary between versions.

import numpy as npprint(np.__version__)# 1.26.1

How to use np.arange()

np.arange() is similar to Python's built-in range() function. See the following article for range().

  • How to use range() in Python

Like range(), np.arange() generates an ndarray with evenly spaced values according to the specified arguments:

  • np.arange(stop)
    • 0 <= n < stop with an interval of 1
  • np.arange(start, stop)
    • start <= n < stop with an interval of 1
  • np.arange(start, stop, step)
    • start <= n < stop with an interval of step
print(np.arange(3))# [0 1 2]print(np.arange(3, 10))# [3 4 5 6 7 8 9]print(np.arange(3, 10, 2))# [3 5 7 9]

Unlike range(), floating-point numbers (float) can be specified as arguments in np.arange().

print(np.arange(0.3, 1.0, 0.2))# [0.3 0.5 0.7 0.9]

Like range(), np.arange() accepts negative values. Additionally, it produces an empty ndarray when there are no matching values.

print(np.arange(-3, 3))# [-3 -2 -1 0 1 2]print(np.arange(10, 3))# []print(np.arange(10, 3, -2))# [10 8 6 4]

While data type (dtype) is automatically selected, it can be manually specified via the dtype argument.

a = np.arange(3, 10)print(a)# [3 4 5 6 7 8 9]print(a.dtype)# int64a_float = np.arange(3, 10, dtype=float)print(a_float)# [3. 4. 5. 6. 7. 8. 9.]print(a_float.dtype)# float64

For details on data types in NumPy, refer to the following article.

  • NumPy: Cast ndarray to a specific dtype with astype()

How to use np.linspace()

Basic usage

With np.linspace(), you can specify the number of elements instead of the interval.

Specify the starting value in the first argument start, the end value in the second stop, and the number of elements in the third num. The interval is automatically calculated based on these values.

print(np.linspace(0, 10, 3))# [ 0. 5. 10.]print(np.linspace(0, 10, 4))# [ 0. 3.33333333 6.66666667 10. ]print(np.linspace(0, 10, 5))# [ 0. 2.5 5. 7.5 10. ]

It also handles the case where start > stop appropriately.

print(np.linspace(10, 0, 5))# [10. 7.5 5. 2.5 0. ]

The data type (dtype) of the generated array can be specified with the dtype argument. Note that by default, even if an array of integers is generated, it becomes floating-point numbers (float).

a = np.linspace(0, 10, 3)print(a)# [ 0. 5. 10.]print(a.dtype)# float64a_int = np.linspace(0, 10, 3, dtype=int)print(a_int)# [ 0 5 10]print(a_int.dtype)# int64

Specify whether to include stop: endpoint

By default, stop is included in the result; setting endpoint to False excludes it.

print(np.linspace(0, 10, 5))# [ 0. 2.5 5. 7.5 10. ]print(np.linspace(0, 10, 5, endpoint=False))# [0. 2. 4. 6. 8.]

The relationship between the endpoint argument and the interval (step) is as follows:

  • endpoint=True (default)
    • step = (stop - start) / (num - 1)
  • endpoint=False
    • step = (stop - start) / num

Get the interval: retstep

Setting the retstep argument to True returns a tuple (resulting_ndarray, step), where step is the interval.

result = np.linspace(0, 10, 5, retstep=True)print(result)# (array([ 0. , 2.5, 5. , 7.5, 10. ]), 2.5)print(type(result))# <class 'tuple'>print(result[0])# [ 0. 2.5 5. 7.5 10. ]print(result[1])# 2.5

If you only want to check step, you can get the second element by indexing.

print(np.linspace(0, 10, 5, retstep=True)[1])# 2.5print(np.linspace(0, 10, 5, retstep=True, endpoint=False)[1])# 2.0

Convert to reverse order

Generating a reverse order array with np.arange() requires appropriate arguments, which can be cumbersome.

print(np.arange(3, 10, 2))# [3 5 7 9]print(np.arange(9, 2, -2))# [9 7 5 3]

Using the slice [::-1] or np.flip() allows for easy reversal of the result.

  • NumPy: Slicing ndarray
  • NumPy: Flip array (np.flip, flipud, fliplr)
print(np.arange(3, 10, 2)[::-1])# [9 7 5 3]print(np.flip(np.arange(3, 10, 2)))# [9 7 5 3]

In the case of np.linspace(), simply swapping the first argument (start) with the second (stop) can easily reverse the order if endpoint=True. The same result can be achieved using the slice [::-1] or np.flip().

print(np.linspace(0, 10, 5))# [ 0. 2.5 5. 7.5 10. ]print(np.linspace(10, 0, 5))# [10. 7.5 5. 2.5 0. ]print(np.linspace(0, 10, 5)[::-1])# [10. 7.5 5. 2.5 0. ]print(np.flip(np.linspace(0, 10, 5)))# [10. 7.5 5. 2.5 0. ]

If endpoint=False, swapping the first argument (start) with the second (stop) does not reverse the order. Using the slice [::-1] or np.flip() makes it easy.

print(np.linspace(0, 10, 5, endpoint=False))# [0. 2. 4. 6. 8.]print(np.linspace(10, 0, 5, endpoint=False))# [10. 8. 6. 4. 2.]print(np.linspace(0, 10, 5, endpoint=False)[::-1])# [8. 6. 4. 2. 0.]print(np.flip(np.linspace(0, 10, 5, endpoint=False)))# [8. 6. 4. 2. 0.]

Convert to multi-dimensional arrays

To create multi-dimensional arrays, use the reshape() method, since neither np.arange() nor np.linspace() have an argument to specify the shape.

  • NumPy: reshape() to change the shape of an array
print(np.arange(12).reshape(3, 4))# [[ 0 1 2 3]# [ 4 5 6 7]# [ 8 9 10 11]]print(np.arange(24).reshape(2, 3, 4))# [[[ 0 1 2 3]# [ 4 5 6 7]# [ 8 9 10 11]]# # [[12 13 14 15]# [16 17 18 19]# [20 21 22 23]]]
print(np.linspace(0, 10, 12).reshape(3, 4))# [[ 0. 0.90909091 1.81818182 2.72727273]# [ 3.63636364 4.54545455 5.45454545 6.36363636]# [ 7.27272727 8.18181818 9.09090909 10. ]]print(np.linspace(0, 10, 24).reshape(2, 3, 4))# [[[ 0. 0.43478261 0.86956522 1.30434783]# [ 1.73913043 2.17391304 2.60869565 3.04347826]# [ 3.47826087 3.91304348 4.34782609 4.7826087 ]]# # [[ 5.2173913 5.65217391 6.08695652 6.52173913]# [ 6.95652174 7.39130435 7.82608696 8.26086957]# [ 8.69565217 9.13043478 9.56521739 10. ]]]
NumPy: arange() and linspace() to generate evenly spaced values | note.nkmk.me (2024)

FAQs

How do you generate evenly spaced numbers in NumPy? ›

NumPy's linspace() function generates an array of evenly spaced numbers over a defined interval. Here, for example, we create an array that starts at 0 and ends at 100 , throughout an interval of 5 numbers. As you can expect, it returns an array with [0, 25, 75, 100] .

What is the NumPy linspace() method? ›

linspace() function returns an array of evenly spaced values within the specified interval [start, stop]. It is similar to NumPy. arange() function but instead of a step, it uses a sample number.

How do you create an evenly spaced array in Python? ›

linspace() in Python. The numpy. linspace() function creates an array of evenly spaced values over a specified interval. It takes in parameters such as start, stop, and num, and returns an array with num equally spaced values between start and stop.

What is the main difference between linspace() and arange()? ›

arange allow you to define the size of the step. linspace allow you to define the number of steps. linspace(0,1,20) : 20 evenly spaced numbers from 0 to 1 (inclusive). arange(0, 10, 2) : however many numbers are needed to go from 0 to 10 (exclusive) in steps of 2.

How do you generate equally spaced numbers in Python? ›

linspace in Python is a function that allows you to generate a sequence of evenly spaced numbers over a specified range. You simply specify the start and end of the range and the number of steps you want in your sequence. Here's a simple example: import numpy as np sequence = np.

What is the formula for evenly spaced sets? ›

Technically, the equation for finding the number of terms in an evenly spaced set is [(High-Low)/increment] + 1, but clearly, there are 100 terms between 1 and 100. Just remember, when using this formula, we want to add one to make sure we're not leaving off the last term.

What is NumPy arange()? ›

NumPy arange() is one of the array creation routines based on numerical ranges. It creates an instance of ndarray with evenly spaced values and returns the reference to it. You can define the interval of the values contained in an array, space between them, and their type with four parameters of arange() : Python.

What is Linspace function used for? ›

The linspace function generates linearly spaced vectors. It is similar to the colon operator ":", but gives direct control over the number of points. y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and including a and b.

Does Python have Linspace? ›

The logspace() function in Python is used to return numbers which are evenly spaced on the log scale.

How do you evenly space a list in Python? ›

The most straightforward option that Python offers is the built-in range() . The function call range(10) returns an object that produces the sequence from 0 to 9 , which is an evenly spaced range of numbers.

How do you make an array equally spaced in Matlab? ›

To create an evenly spaced array, specify the start and end point by using the ':' operator. Another way to create a matrix is to use a function, such as ones, zeros or rand.

What is the NumPy eye() method? ›

eye() function in Python is used to return a two-dimensional array with ones (1) on the diagonal and zeros (0) elsewhere.

Which NumPy function generates an array of evenly spaced values over a specified range? ›

Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval [start, stop]. The endpoint of the interval can optionally be excluded.

What is the difference between NumPy array and arange? ›

The `arange()` function in Python is a NumPy function that returns an array of evenly spaced values within a given interval. It is similar to the built-in `range()` function in Python, but it returns an array instead of a list.

What is the difference between NumPy Linspace and Logspace? ›

linspace is similar to the colon operator, “ : ”, but gives direct control over the number of points and always includes the endpoints. “ lin ” in the name “ linspace ” refers to generating linearly spaced values as opposed to the sibling function logspace , which generates logarithmically spaced values.

How do you return evenly spaced numbers over a specified interval in Python? ›

To return evenly spaced numbers over a specified interval, use the numpy. linspace() method in Python Numpy. The 1st parameter is the "start" i.e. the start of the sequence. The 2nd parameter is the "end" i.e. the end of the sequence.

What is the spacing method in NumPy? ›

The distance between an input value x and the closest neighboring integer is calculated using the NumPy. spacing() function in the NumPy programming language. It gives back a scalar value that measures the separation between the input value x and the closest neighboring number.

What is the NumPy function used to create evenly spaced arrays analogous to the range () function used in Python? ›

NumPy arange() is one of the array creation routines based on numerical ranges. It creates an instance of ndarray with evenly spaced values and returns the reference to it.

References

Top Articles
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 5550

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.