Is there a numpy function that allows you to specify the start, step and number?

We are all familiar with np.linspace , which creates an array with start , stop and num elements:

 In [1]: import numpy as np In [2]: np.linspace(0, 10, 9) Out[2]: array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75, 10. ]) 

Similarly, who could forget np.arange , which creates an array with the parameters start , stop and step :

 In [4]: np.arange(0, 10, 1.25) Out[4]: array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75]) 

But is there a function that allows you to specify start , step and num elements, omitting stop ? It must be.

+4
source share
4 answers

The remote answer states that linspace accepts the endpoint parameter.

Thus, 2 examples cited in other answers can be written as:

 In [955]: np.linspace(0, 0+(0.1*3),3,endpoint=False) Out[955]: array([ 0. , 0.1, 0.2]) In [956]: np.linspace(0, 0+(5*3),3,endpoint=False) Out[956]: array([ 0., 5., 10.]) In [957]: np.linspace(0, 0+(1.25*9),9,endpoint=False) Out[957]: array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75, 10. ]) 

Take a look at the functions defined in numpy.lib.index_tricks for other ideas on how to create ranges and / or meshes. For example, np.ogrid[0:10:9j] behaves like a linspace .

 def altspace(start, step, count, endpoint=False, **kwargs): stop = start+(step*count) return np.linspace(start, stop, count, endpoint=endpoint, **kwargs) 
+4
source
 def by_num_ele(start,step,n_elements): return numpy.arange(start,start+step*n_elements,step) 

may be?

+3
source

Thanks for this question. I had the same problem. (from my point of view) the shortest and most elegant way:

 import numpy as np start=0 step=1.25 num=9 result=np.arange(0,num)*step+start print(result) 

returns

 [ 0. 1.25 2.5 3.75 5. 6.25 7.5 8.75 10. ] 
+2
source

Here is one that should always work with floats.

 >>> import numpy as np >>> import itertools >>> def my_range(start, step, num): ... return np.fromiter(itertools.count(start, step), np.float, num) ... >>> my_range(0, 0.1, 3) array([ 0. , 0.1, 0.2]) 

You can do np.float arg (or kwarg) if you want to use it with something other than floats:

 >>> import numpy as np >>> import itertools >>> def my_range(start, step, num, dtype=np.float): ... return np.fromiter(itertools.count(start, step), dtype, num) ... >>> my_range(0, 5, 3) array([ 0., 5., 10.]) >>> my_range(0, 5, 3, dtype=np.int) array([ 0, 5, 10]) 
+1
source

All Articles