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?
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).
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.
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])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With