python - Why is my range function printing untruncated floats? -
i made range function have other integer step, , works, wondering why floats 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 find instead of 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 module isn't working. why happen , how might fix it?
this correct behavior, since 1 cannot express 0.2 = 1/5
in base 2, there no way express 1/3
in base 10.
use decimal
instead if want calculate in base 10.
additionally, should use generator, 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
iterate on values without memory being allocated whole list.
Comments
Post a Comment