1

In run the follow code:

k = 0
while k <= 1:
    print(k)
    k += 0.1

And get result:

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

However, the expected output is

0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

How to make the result of python output same as in math?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
MarioKZZ
  • 141
  • 2
  • 8

4 Answers4

3

Incrementing by a step size that's not exactly 0.1 (since that can't be represented as fixed point binary number) will continually increase your error. The float that the literal 0.1 gets translated to is not exactly 0.1. Computing the nearest binary approximation of the correct fraction is a better way to go:

k = 0
while k <= 10:
    print(k / 10)
    k += 1

k / 10 will not be an exact representation of the numbers you want except for 0.0, 0.5, 1.0, but since it will be the closest available float, it will print correctly.

As an aside, switching to integers allows you to rewrite your loop more idiomatically as

for k in range(11):
    print(k / 10)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

Just use round method with a precision of 1:

In [1217]: k = 0
      ...: while k<=1:
      ...:     print(round(k,1))
      ...:     k += 0.1
      ...: 
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
0

You can do with format() function as below:

k = 0
while k<=1:
    print('{0:.2g}'.format(k))
    k += 0.1
berkayln
  • 935
  • 1
  • 8
  • 14
0

An alternative to your code is initialize a variable i with 0 and increment it in each loop. You then set k = 0.1 * i

You thereby avoid cumulative rounding errors.

Tarik
  • 10,810
  • 2
  • 26
  • 40
  • 1
    `k = i / 10`. `0.1` will be converted into the wrong float. – Mad Physicist Apr 03 '21 at 06:48
  • @MadPhysicist AFAIK, the result of multiplying an int and a float is float. Show me otherwise. – Tarik Apr 03 '21 at 07:45
  • 3
    @Tarik: Try printing `0.1 * 3` and `3 / 10`. On my machine (and I suspect on yours, too), those give `0.30000000000000004` and `0.3` respectively. The issue is that the expression `0.1 * i` involves two roundings (one to convert the numeric literal "0.1" to a binary float, and a second one from the multiplication), while `i / 10` involves only a single rounding step, so will always give the closest float to the one the OP wants. And because it's the closest float, Python's float repr will produce the desired "shortest-string" result. – Mark Dickinson Apr 03 '21 at 08:10
  • @MarkDickinson Thanks for your response, sincerely! You taught me something today. – Tarik Apr 04 '21 at 16:22