1

So I wrote this function to generate a list of numbers between start and stop (inclusively) at step interval:

start, stop, step, = -3, 3, 0.1
print [x * step + start for x in range(int((stop + step - start) / step))]
print 12 * 0.1 + -3

the output was:

[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7000000000000002, 1.8, 1.9, 2.0]
1.7

why is the list messing up 1.7, but when I do the same operation outside the for loop, it works just fine? How do I fix the for loop?

Jonathan
  • 303
  • 4
  • 14
  • Printing a single value in Python 2.7 uses `str(x)` which does rounding. Printing a list uses `repr(x)` which doesn't round. Both operations are returning the same value, you're just printing them differently. – Mark Ransom Aug 06 '17 at 03:46
  • @Mark Ransom that is really helpful. Thank you. So is there a way to make the values in the list exact? – Jonathan Aug 07 '17 at 12:51
  • I'm afraid there is not, that's why you were directed to the other question. If you go through all those answers you should start to understand. – Mark Ransom Aug 07 '17 at 12:55

0 Answers0