1

I am trying to get series of numbers starting from zero by increasing it by 0.001 by coding it in python. It is giving results correctly till 0.008. In the next iteration, the value must be exactly 0.009 but the output gives 0.009000000000000001. This kind of error could be seen in further iterations also. The code for the following:

t = 0.000
dt = 0.001
timemax = 0.012
while(t<timemax):
    print(t)
    t = t + dt
    if(t>= timemax):
        exit()

The output is as follows:

0.0
0.001
0.002
0.003
0.004
0.005
0.006
0.007
0.008
0.009000000000000001
0.010000000000000002
0.011000000000000003

The error could even be seen when the value of dt = 0.01 and timemax = 0.12. Code for it is as follows:

t = 0.000
dt = 0.01
timemax = 0.12
while(t<timemax):
    print(t)
    t = t + dt
    if(t>= timemax):
        exit()

Output:

0.0
0.01
0.02
0.03
0.04
0.05
0.060000000000000005
0.07
0.08
0.09
0.09999999999999999
0.10999999999999999
0.11999999999999998

Why is this happening? What measures we could take to resolve this?.

Avii
  • 164
  • 12
  • See https://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value?rq=1. In there, this https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html is linked. – Nikolaos Chatzis Sep 29 '21 at 18:52

2 Answers2

1

This is a consequence of how real numbers are represented in the computer (Google floating point arithmetic).

The error rarely matters. In cases when it does, consider rounding appropriately.

Or, use integers instead, like this:

t = 0
dt = 10 # ms
timemax = 120
while(t<timemax):
    print(t)
    t = t + dt
    if(t>= timemax):
        print(f"{t/1000} seconds")
        exit()

If you are not actually modelling a continuum of values, but rather discrete distinct values, this last approach is often preferable.

0

Python's float objects use 64-bit, so there's only a finite amount of numbers it can represent. Hence you'll see these small deviations from what you'd expect from "real" math. For more information, please refer to this question.

If you need to represent decimal values exactly, there's the decimal module from the standard library.

There's also the mpmath project, which allows for arbitrary-precision floating point arithmetic.

a_guest
  • 34,165
  • 12
  • 64
  • 118