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.

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
Gino Rossi günstig im Outlet kaufen | -80% bei limango
How to Change or Fake Location in Chrome, Edge, and Firefox
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
What's the Difference Between Halal and Haram Meat & Food?
R/Skinwalker
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Cubilabras
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Juego Friv Poki
Dirt Devil Ud70181 Parts Diagram
Truist Bank Open Saturday
Water Leaks in Your Car When It Rains? Common Causes & Fixes
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Drys Pharmacy
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
2024-25 ITH Season Preview: USC Trojans
Metro By T Mobile Sign In
Restored Republic December 1 2022
Lincoln Financial Field Section 110
Free Stuff Craigslist Roanoke Va
Stellaris Resolution
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 6362

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.