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

31st Mar 2020, 7:03 PM
Azam Raza
Azam Raza - avatar
2 Respostas
+ 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
31st Mar 2020, 7:52 PM
andriy kan
andriy kan - avatar
+ 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
31st Mar 2020, 7:19 PM
Rik Wittkopp
Rik Wittkopp - avatar