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 contained in range - Ideas - Discussions on Python.org
float numbers with range () function
How to step by floats in a range function?
floating point - Find range between floats in python - Stack Overflow
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.
The range function does not handle floats
I am trying to convert something from PHP to Python, but came across a problem since the range function can only step by integers.
I will divide a circle into 16 parts. In PHP I have written:
for ($degrees = 0; $degrees < 360; $degrees += 22.5) {
...I was going to write it like this in Python:
for degrees in range(0, 360, 22.5):
...What is the easiest / nicest way to achieve this?
if 0.5 <= x < 3.5:
pass
You might want to change the inequality signs depending on whether you want the ends to be inclusive or exclusive.
A "range" in Python is not an abstract mathematical notion of "all the numbers between these two numbers", but either an actual list of numbers (range() in Python 2) or a generator which is capable of producing a sequence of numbers (xrange() in Python 2 or range() in Python 3). Since there are infinitely many real numbers between two given numbers, it's impossible to generate such a list/sequence on a computer. Even if you restrict yourselves to floating-point numbers, there might be millions or billions of numbers in your range.
For the same reason, even though your code would have worked for integers (but only in Python 2), it would have been terribly inefficient if your endpoints were far apart: it would first generate a list of all integers in the range (consuming both time and memory), and then traverse the list to see if x is contained in it.
If you ever try to do a similar thing in other languages: most languages don't allow double comparisons like this, and would instead require you to do something like if 0.5 < x and x < 3.5.
if 0.5 < x < 3.5:
pass
I don't think you need a function at all here.