You can either use:
[x / 10.0 for x in range(5, 50, 15)]
or use lambda / map:
map(lambda x: x/10.0, range(5, 50, 15))
Answer from Grzegorz Rożniecki on Stack OverflowYou can either use:
[x / 10.0 for x in range(5, 50, 15)]
or use lambda / map:
map(lambda x: x/10.0, range(5, 50, 15))
I used to use numpy.arange but had some complications controlling the number of elements it returns, due to floating point errors. So now I use linspace, e.g.:
>>> import numpy
>>> numpy.linspace(0, 10, num=4)
array([ 0. , 3.33333333, 6.66666667, 10. ])
float numbers with range () function
Float contained in range - Ideas - Discussions on Python.org
Function for Range for floats in python - Stack Overflow
How to step by floats in a range function?
Hi, I have a section of code which takes a score from the user, typecasts it into a float value and saves it under the variable name "score". Then I have a line of code which reads:
while score not in range(0, 101):
However, when I input a float, I get an invalid input error message from python. I think it's because I can't use the range() function with floats. Is there a way around this? If anyone knows how to solve this, then your help would be greatly appreciated. Thank you in advance.
Convert the floating steps into integer steps. You'll get less drift from error due to rounding of floats:
def float_range(start,stop,step):
istop = int((stop-start) // step)
for i in range(int(istop)):
yield start + i * step
The main reason you're getting answers wrong is the top level if statements are wrong. You don't want to look at the boundaries when deciding which way to move. It's legal to ask for a range that has nothing in it (with e.g. stop less than start with a positive step).
Here's how I'd minimally adjust your code to work properly:
def float_range(start,stop,step):
x = start
my_list = []
if step > 0:
while x < stop:
my_list.append(x)
x += step
else: # should really be if step < 0 with an extra check for step == 0
while x > stop:
my_list.append(x)
x += step
return my_list