when summing up values in a simple for loop, Python gives a numeric error. Any ideas what causes this behaviour?
x = 0.0
for _ in range(1000):
x += 0.1
print(x)
>>> 99.9999999999986
when summing up values in a simple for loop, Python gives a numeric error. Any ideas what causes this behaviour?
x = 0.0
for _ in range(1000):
x += 0.1
print(x)
>>> 99.9999999999986
This is just an issue with floating point numbers in general as there are certain decimal numbers that cannot be accurately represented in the float variable type. For example in JavaScript 0.1 + 0.2 = 0.30000000000000004. Python will yield a similar result as will Java with Double types.
Do note that the result is extremely close and therefore "close enough" for financial applications and almost every other application type.
Floating point errors are something you will see happen in any programming language. As kvantour said, computers cannot represent fractions so if you are adding up thirds then the computer will approximate 1/3 as 0.33 and (1/3 + 1/3 + 1/3) will turn out to be 0.99 instead of the 1 it should be.
To prevent this, in most cases, you can probably round off your final answer using the python round()
method and you'll get the 100 you're looking for. If you need to be more precise and rounding is not an option for you then you can use the python decimal module as such:
from decimal import Decimal as D
x = D(0)
for _ in range(1000):
x += D("0.1")
print(x)