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)

References

Top Articles
Dodger Stadium Seating Chart: Best Seats & Where to Sit Guide
Who's running in Wyoming? These state house races are key to 2024 election.
Wmaz 13
Missing 2023 Showtimes Near Amc Classic Florence 12
Craigslist Placer County
Puss In Boots: The Last Wish Showtimes Near Fox Berkshire
Jikatabi Thothub
What is international trade and explain its types?
Creative Fall Bloxburg House Ideas For A Cozy Season
Www. Kdarchitects .Net
United Dual Complete Providers
Chelsea Marie Boutique
Jera Gardens
Craigslist Louisville Com
Big Lots $99 Fireplace
Wells Fargo Banks In Florida
50 Shades Of Grey Movie 123Movies
Anon Rotten Tomatoes
Walmart Careers Stocker
Fungal Symbiote Terraria
91 Freeway news - Today’s latest updates
Webmail.unt.edu
Pull And Pay Middletown Ohio
Twitter Jeff Grubb
How To Pause Tamagotchi Gen 2
11000, EVV Compliance Reviews | Texas Health and Human Services
Don Wallence Auto Sales Reviews
Search results for: Kert\u00E9sz, Andr\u00E9, page 1
Bank Of America Financial Center Irvington Photos
Dfw Rainfall Last 72 Hours
Keci News
Cbs Sportsline Fantasy Rankings
Boostmaster Lin Yupoo
Fx Channel On Optimum
Candy Land Santa Ana
Youravon Comcom
FedEx zoekt een Linehaul Supervisor in Duiven | LinkedIn
Cars for Sale by Owner in San Francisco, CA
Ewing Irrigation Prd
Optum Director Salary
Burkes Outlet Credit Card Sign In
Leuke tips & bezienswaardigheden voor een dagje Wijk bij Duurstede
Hourly Weather Forecast for Amsterdam, North Holland, Netherlands - The Weather Channel | Weather.com
Sallisaw Bin Store
What Are Cluster B Personality Disorders?
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Goldthroat Goldie
What is 9xMovies - Everything You Need to Know with Best Alternatives 2023-LDPlayer's Choice-LDPlayer
Christina Cox Measurements
Empire Of Light Showtimes Near Santikos Entertainment Palladium
Roselli's Pizza Coupons
Corn And Tater Fest 2023
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 5580

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.