1

I want to create a while loop in python which will give an output as a list [0.00, 0.05, 0.10, 0.15,...., 1.00]

I tried doing it by following method:

alpha=0

alphalist=list()
while alpha<=1:
    alphalist.append(alpha)
    alpha+=0.05

print(alphalist)

I got the output as [0, 0.05, 0.1, 0.15000000000000002, 0.2, 0.25, 0.3, 0.35, 0.39999999999999997, 0.44999999999999996, 0.49999999999999994, 0.5499999999999999, 0.6, 0.65, 0.7000000000000001, 0.7500000000000001, 0.8000000000000002, 0.8500000000000002, 0.9000000000000002, 0.9500000000000003]

But What I want is this: [0.00, 0.05, 0.10, 0.15,...., 1.00]

Saurabh
  • 199
  • 1
  • 3
  • 11
  • 1
    Related: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – chepner Oct 18 '19 at 18:57
  • Related: [How to use a decimal range() step value?](https://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value) - see [this answer](https://stackoverflow.com/a/477513/4518341) – wjandrea Oct 18 '19 at 19:04

2 Answers2

2

This is the result of floating-point error. 0.05 isn't really the rational number 1/20 to begin with, so any arithmetic involving it may differ from what you expect.

Dividing two integers, rather than starting with a floating-point value, helps mitigate the problem.

>>> [x/100 for x in range(0, 101, 15)]
[0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0]
chepner
  • 497,756
  • 71
  • 530
  • 681
1

There are some numbers that can cause imprecisions with the floating number system computers use. You're just seeing an example of that.

What I would do, if you want to continue using the while loop this way, is to add another line with

alpha = round(alpha,2)
rasc42
  • 103
  • 1
  • 9