Reputation: 1549
I made this range function so I could have something other than an integer step, and it works, but I am wondering why the floats are not truncated.
def drange(start, step):
values = []
r = start
while r >= 0:
values.append(r)
r += step
return values
print drange(2, -0.2)
Upon debugging I find that instead of this printing
[2, 1.8, 1.6, 1.4, 1.2, 1.0, 0.8, 0.6, 0.4, 0.2, 0]
it instead prints
[2, 1.8, 1.6, 1.4000000000000001, 1.2000000000000002, 1.0000000000000002, 0.8000
000000000003, 0.6000000000000003, 0.4000000000000003, 0.2000000000000003, 2.7755
575615628914e-16]
Lol, no wonder my module isn't working. Why does this happen and how might I fix it?
Upvotes: 1
Views: 182
Reputation: 287865
This is correct behavior, since one cannot express 0.2 = 1/5
in base 2, just like there is no way to express 1/3
in base 10.
Use decimal
instead if you want to calculate in base 10.
Additionally, you should really use a generator, as in
def drange(start, step):
r = start
while r >= 0:
yield r
r += step
print list(drange(2, -0.2))
That allows users of drange
to iterate over the values without memory being allocated for the whole list.
Upvotes: 7