Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating a range of an exact number of values in Python

Tags:

python

list

range

I'm building a range between two numbers (floats) and I'd like this range to be of an exact fixed length (no more, no less). range and arange work with steps, instead. To put things into pseudo Python, this is what I'd like to achieve:

start_value = -7.5
end_value = 0.1
my_range = my_range_function(star_value, end_value, length=6)

print my_range
[-7.50,-5.98,-4.46,-2.94,-1.42,0.10]

This is essentially equivalent to the R function seq which can specify a sequence of a given length. Is this possible in Python?

Thanks.

like image 207
Einar Avatar asked Dec 10 '22 16:12

Einar


2 Answers

Use linspace() from NumPy.

>>> from numpy import linspace
>>> linspace(-7.5, 0.1, 6)
array([-7.5 , -5.98, -4.46, -2.94, -1.42,  0.1])
>>> linspace(-7.5, 0.1, 6).tolist()
[-7.5, -5.9800000000000004, -4.46, -2.9399999999999995, -1.4199999999999999, 0.10000000000000001]

It should be the most efficient and accurate.

like image 67
Leonid Shvechikov Avatar answered May 16 '23 01:05

Leonid Shvechikov


See Recipe 66472: frange(), a range function with float increments (Python) with various float implementations, their pros and cons.

Alternatively, if precision is important to you, work with decimal.Decimal instead of float (convert to and then back) as answered in Python decimal range() step value.

like image 32
van Avatar answered May 16 '23 01:05

van