0

Long story is I'm trying to draw some of the trigonometric graphs, but I'm incrementing a value by 0.1 to get a precise turning point, however when incrementing it's incrementing by 0.100000000006 or some value similar to that, so I'm unable to check if it's equal to another value

I ran a test on a different file to check if the problem was due to some of the sine conversions, incase of a memory leak or something (I'm not sure) and I had the same problem in another file which was just a for loop.

import math
xNum = 0
for x in range(180):
    print(xNum)
    xNum = 0.1 + xNum

And when printing xNum I'm getting values like 0.40000000006 that I'm not sure why it isn't incrementing xnum by 0.1. i used xNum += 0.1 but there seems to be no difference in output

  • See this question: https://stackoverflow.com/questions/588004/is-floating-point-math-broken If you need more precision use [decimal](https://docs.python.org/3.7/library/decimal.html) or [fractions](https://docs.python.org/3.7/library/fractions.html). – zvone Jun 10 '19 at 20:23

1 Answers1

2

You can read about float point issues in official documentation.

As quick fix to your code, you can use decimal module from standard library:

from decimal import Decimal

xNum = 0
for x in range(180):
    print(xNum)
    xNum = Decimal('0.1') + xNum

This prints:

0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
..etc.
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91