2

when i try to add 1 to answer python adds 10^-16 to the answer tried printing in different ways but i think it will not help. Any answers ?

x = 0.8475
print(1 + x)
print(1 + 0.8475)
print(1.0 + 0.8475)
y = 1 + x
print(y)

output :

1.8475000000000001
1.8475000000000001
1.8475000000000001
1.8475000000000001
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Nitish
  • 565
  • 4
  • 16
  • This *kind of thing* is something you will have to get used to when programming computers. It can cause a variety of problems and takes a little while getting used to. It happens for different reasons, because inside the computer numbers are in binary not in decimal and because there are roundoff or floating point errors as mentioned in [this answer](https://stackoverflow.com/a/54021194/3904031). – uhoh Jan 03 '19 at 11:40

1 Answers1

2

Its called a floating point error, and isn't specific to python. A float can't represent all values perfectly accurately, so you get these weird inaccuracies like you're seeing.

Use Decimal instead of float if you need your numbers to be that accurate. In most cases though, its acceptable to just round your answer to a few decimal places.

https://docs.python.org/2/library/decimal.html

lbenedetto
  • 2,022
  • 1
  • 21
  • 39