Home > Software engineering >  List between two numbers - definine number of steps, not step size
List between two numbers - definine number of steps, not step size

Time:04-21

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:

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.

CodePudding user response:

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])

CodePudding user response:

You can keep using the np.arange function. You just need to compute the step size from the maximum and minimum value, and the number of steps:

import numpy as np
import math

nb_steps = 3
min_val = 0
max_val = 100

step_size = math.floor((max_val-min_val)/nb_steps)
arr = np.arange(min_val,max_val,step_size)

# update last value to match max_val
# this step is needed if (max_val-min_val)/nb_steps is a decimal number
arr[-1] = max_val

You can also use numpy.linspace as pointed out in the comments:

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

https://numpy.org/doc/stable/reference/generated/numpy.linspace.html

CodePudding user response:

something like this would be good I think

even_arange = lambda n: np.arange(0, 101, 100/(n-1)).astype("int64")
even_arange(n)

OR

from functools import partial
even_arnage = partial(start=0, stop=100, dtype="int64")
even_arange(num=n)

CodePudding user response:

For pure python (without any libraries).

def generate_range(start, end, steps):
   return [start   i*(end-start)/(steps-1) for i in range(steps)]

Sample Usage

generate_range(0, 100, 4)  
# returns [0.0, 33.333333333333336, 66.66666666666667, 100.0]

generate_range(-200, 400, 5)
# returns [-200.0, -50.0, 100.0, 250.0, 400.0]

CodePudding user response:

def listWithNumberOfStep(startNumber, endNumber, nbSteps):
   listNumber = []
   delta = endNumber - startNumber
   for i in range(nbSteps   1):
      listNumber.append(startNumber   (delta/nbSteps * i))
   return listNumber
  • Related