0
Float range in Python
Something maybe wrong in my code, but I couldn't find it. Please help me. I don't want '1' at the end. https://code.sololearn.com/c928VP2ApVtD/?ref=app
2 Answers
+ 3
When you use addition to calculate the next value you accumulate an error related to discrete representation of a number in floating point variable. After 6 additions the accumulated error becomes 6 times bigger. As result your code outputs 1.0 (it is 0.999999... rounded up to 1.0).
Use multiplication to reduce an error, for example, like this:
def frange(start, stop, step):
i = 0
while True:
n = start + i * step
if n >= stop:
break;
i += 1
yield(n)
f_list=frange(0.5, 1.0, 0.1)
for i in f_list :
print(i)
Also you can use
numpy.arange()
which does what you want
+ 2
From your description, it sounds like you are trying to use a float to create a range.
A range will create an iteration, so whole numbers are required.( integers)
A float will be trying to create a partial iteration which is not possible.
Please share your code as HonFu suggested to get more accurate assistance