What is the difference between np.linspace and np.arange?

40,698

np.linspace allows you to define how many values you get including the specified min and max value. It infers the stepsize:

>>> np.linspace(0,1,11)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

np.arange allows you to define the stepsize and infers the number of steps(the number of values you get).

>>> np.arange(0,1,.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

contributions from user2357112:

np.arange excludes the maximum value unless rounding error makes it do otherwise.

For example, the following results occur due to rounding error:

>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])

You can exclude the stop value (in our case 1.3) using endpoint=False:

>>> numpy.linspace(1, 1.3, 3, endpoint=False)
array([1. , 1.1, 1.2])
Share:
40,698

Related videos on Youtube

Sabito 錆兎 stands with Ukraine
Author by

Sabito 錆兎 stands with Ukraine

:)

Updated on February 09, 2021

Comments

  • Sabito 錆兎 stands with Ukraine
    Sabito 錆兎 stands with Ukraine over 3 years

    I have always used np.arange. I recently came across np.linspace. I am wondering what exactly is the difference between them... Looking at their documentation:

    np.arange:

    Return evenly spaced values within a given interval.

    np.linspace:

    Return evenly spaced numbers over a specified interval.

    The only difference I can see is linspace having more options... Like choosing to include the last element.

    Which one of these two would you recommend and why? And in which cases is np.linspace superior?

    • warped
      warped almost 4 years
      arange allow you to define the size of the step. linspace allow you to define the number of steps.
    • Niklas Mertsch
      Niklas Mertsch almost 4 years
      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.
    • hpaulj
      hpaulj almost 4 years
      The big difference is that one uses a step value, the other a count. arange follows the behavior of the python range, and is best for creating an array of integers. It's docs recommend linspace for floats.
  • user2357112
    user2357112 almost 4 years
    "It excludes the maximum value" - unless rounding error makes it do otherwise, so stick with linspace. You can specify endpoint=False if you want to exclude the right endpoint with linspace.
  • user2357112
    user2357112 almost 4 years
    For example, numpy.arange(1, 1.3, 0.1) gives array([1. , 1.1, 1.2, 1.3]) due to rounding error, while numpy.linspace(1, 1.3, 3, endpoint=False) gives array([1. , 1.1, 1.2]).
  • warped
    warped almost 4 years
    @user2357112 supports Monica agreed. See edits to my post (and feel free to edit)