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))
def frange(x, y, jump):
while x < y:
yield x
x += jump
---
As the comments mention, this could produce unpredictable results like:
>>> list(frange(0, 100, 0.1))[-1]
99.9999999999986
To get the expected result, you can use one of the other answers in this question, or as @Tadhg mentioned, you can use decimal.Decimal as the jump argument. Make sure to initialize it with a string rather than a float.
>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]
Decimal('99.9')
Or even:
import decimal
def drange(x, y, jump):
while x < y:
yield float(x)
x += decimal.Decimal(jump)
And then:
>>> list(drange(0, 100, '0.1'))[-1]
99.9
[editor's not: if you only use positive jump and integer start and stop (x and y) , this works fine. For a more general solution see here.]
python - How do I use a decimal step value for range()? - Stack Overflow
float numbers with range () function
Float contained in range - Ideas - Discussions on Python.org
python - For loop using range as float object - Stack Overflow
Videos
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
Use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
If you really want to use a floating-point step value, use numpy.arange:
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
range() can only do integers, not floating point.
Use a list comprehension instead to obtain a list of steps:
[x * 0.1 for x in range(0, 10)]
More generally, a generator comprehension minimizes memory allocations:
xs = (x * 0.1 for x in range(0, 10))
for x in xs:
print(x)
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.
You can't use the built in to do float/decimal increments but it is fairly easy to construct your own generator:
def decimal_range(start, stop, increment):
while start < stop: # and not math.isclose(start, stop): Py>3.5
yield start
start += increment
for i in decimal_range(Rangelow, Rangehigh, Delta):
...
Or you could use numpy but this feels like a sledgehammer cracking a nut:
import numpy as np
for i in np.arange(Rangelow, Rangehigh, Delta):
...
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import decimal
def range_decimal(start, stop, step, stop_inclusive=False):
""" The Python range() function, using decimals. A decimal loop_value generator.
Note: The decimal math (addition) defines the rounding.
If the stop is None, then:
stop = start
start = 0 (zero)
If the step is 0 (zero) or None, then:
if (stop < start) then step = -1 (minus one)
if (stop >= start) then step = 1 (one)
Example:
for index in range_decimal(0, 1.0, '.1', stop_inclusive=True):
print(index)
:param start: The loop start value
:param stop: The loop stop value
:param step: The loop step value
:param stop_inclusive: Include the stop value in the loop's yield generator: False = excluded ; True = included
:return: The loop generator's yield increment value (decimal)
"""
try:
# Input argument(s) error check
zero = decimal.Decimal('0')
if start is None:
start = zero
if not isinstance(start, decimal.Decimal):
start = decimal.Decimal(f'{start}')
if stop is None:
stop = start
start = zero
if not isinstance(stop, decimal.Decimal):
stop = decimal.Decimal(f'{stop}')
if step is None:
step = decimal.Decimal('-1' if stop < start else '1')
if not isinstance(step, decimal.Decimal):
step = decimal.Decimal(f'{step}')
if step == zero:
step = decimal.Decimal('-1' if stop < start else '1')
# Check for valid loop conditions
if start == stop or (start < stop and step < zero) or (start > stop and step > zero):
return # Not valid: no loop
# Case: increment step ( > 0 )
if step > zero:
while start < stop: # Yield the decimal loop points (stop value excluded)
yield start
start += step
# Case: decrement step ( < 0 )
else:
while start > stop: # Yield the decimal loop points (stop value excluded)
yield start
start += step
# Yield the stop value (inclusive)
if stop_inclusive:
yield stop
except (ValueError, decimal.DecimalException) as ex:
raise ValueError(f'{__name__}.range_decimal() error: {ex}')
This is a Python range() equivalent function, using decimals.
The yielded values are exact.
Rangelow = 36
Rangehigh = 37
Delta = 0.1
print("Celsius to Fahrenheit by", Delta)
for i in range_decimal(Rangelow, Rangehigh, Delta, stop_inclusive=True):
print(f'{i:.1f} {i * 9 / 5 + 32}')
Celsius to Fahrenheit by 0.1
36.0 96.8
36.1 96.98
36.2 97.16
36.3 97.34
36.4 97.52
36.5 97.7
36.6 97.88
36.7 98.06
36.8 98.24
36.9 98.42
37.0 98.6
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?