1

I am adding a float value in an integer using loops but the answer is different. Here is my code:

import time
test = 0
while True:
    test += 0.0001
    print(test)
    time.sleep(0.3)

When I ran it I should have got:

0.0001
0.0002
0.0003
0.0004
0.0005
.........

But I got:

0.0001
0.0002
0.00030000000000000003
0.0004
0.0005
0.0006000000000000001
0.0007000000000000001
0.0008000000000000001
0.0009000000000000002
0.0010000000000000002
0.0011000000000000003
0.0012000000000000003

Why it is so and how to solve this problem?

Nouman
  • 6,947
  • 7
  • 32
  • 60
  • 1
    Possible duplicate of [How to avoid floating point errors?](https://stackoverflow.com/questions/19473770/how-to-avoid-floating-point-errors) – awesoon Dec 02 '17 at 05:41
  • [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – kindall Dec 02 '17 at 05:45

3 Answers3

1

You can set the output precision using {:.4f} to keep four digits .

>>> pi
3.141592653589793
>>> print("{}".format(pi))
3.141592653589793
>>> print("{:.3f}".format(pi))
3.142
>>> print("{:.4f}".format(pi))
3.1416
>>> print("{:.5f}".format(pi))
3.14159
Kinght 金
  • 17,681
  • 4
  • 60
  • 74
0

You solve the problem by seeking a deeper understanding of the inexact representation of rational, base 10 numbers by base 2 hardware.

See What Every Programmer Should Know About Floating-Point Arithmetic for a starter.

Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46
0

It is inherent to the way binary floating-point are handled in operating systems. Have look here and here.

One of the possible solutions is to round the results to the decimal you want, here round to .4.

Elliot
  • 308
  • 1
  • 8