Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a list of evenly spaced numbers in a certain range in python

Tags:

python

list

range

What is a pythonic way of making list of arbitrary length containing evenly spaced numbers (not just whole integers) between given bounds? For instance:

my_func(0,5,10) # ( lower_bound , upper_bound , length ) # [ 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5 ]  

Note the Range() function only deals with integers. And this:

def my_func(low,up,leng):     list = []     step = (up - low) / float(leng)     for i in range(leng):         list.append(low)         low = low + step     return list 

seems too complicated. Any ideas?

like image 333
Double AA Avatar asked Jul 13 '11 18:07

Double AA


People also ask

How do you make a list of numbers evenly spaced in Python?

This puzzle is about the useful function linspace. In particular, linspace(start, stop, num) returns evenly spaced numbers over a given interval [start, stop] , with stop included. For example, linspace(0,3,4) returns the numpy array sequence 0,1,2,3 (i.e., 4 evenly spaced numbers).

How do I create a Numpy array with equal spacing?

NumPy has a built-in method called arange() which is capable of creating an array of a given integer type(in bytes), with equal spacing between the numbers. Parameters: start: This is a default parameter. The value of the first number of the element, the default value of this parameter is 0.


2 Answers

Given numpy, you could use linspace:

Including the right endpoint (5):

In [46]: import numpy as np In [47]: np.linspace(0,5,10) Out[47]:  array([ 0.        ,  0.55555556,  1.11111111,  1.66666667,  2.22222222,         2.77777778,  3.33333333,  3.88888889,  4.44444444,  5.        ]) 

Excluding the right endpoint:

In [48]: np.linspace(0,5,10,endpoint=False) Out[48]: array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5]) 
like image 164
unutbu Avatar answered Oct 09 '22 23:10

unutbu


You can use the following approach:

[lower + x*(upper-lower)/length for x in range(length)] 

lower and/or upper must be assigned as floats for this approach to work.

like image 21
Howard Avatar answered Oct 09 '22 23:10

Howard