Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List between two numbers – definine number of steps, not step size

I want to create a list between two numbers, like:

import numpy as np

np.arange(0,100,10)

Output:

array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

But I dont want to define the size of the step, but the number of steps. If I define 3 steps, then I want to get this list:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array([ 0, 50, 100])

Or 4 steps:

array([0, 33, 66, 100])

And so on.


It doesn’t matter if I have to set 4 (for all values) or 2 (only for interpolated values) to get the last output or if I’m getting an array or a list. Also how it rounds/ceils doesn’t matter as well. It’s only about the logical to create such lists.

>Solution :

As mentioned in the comments, numpy.linspace returns evenly spaced numbers over a specified interval.

import numpy as np

n_steps = 3 
np.linspace(start=0, stop=100, num=n_steps)
array([  0.,  50., 100.])

n_steps = 4
np.linspace(start=0, stop=100, num=n_steps)
array([  0.        ,  33.33333333,  66.66666667, 100.        ])

Edit
If you are looking for integers, you can then cast to int data type:

import numpy as np

n_steps = 3 
np.linspace(start=0, stop=100, num=n_steps, dtype=int)
array([  0,  50, 100])

n_steps = 4
np.linspace(start=0, stop=100, num=n_steps, dtype=int)
array([  0,  33,  66, 100])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading