0

When I try to add or multiply in a python3, I get an obvious error, although the operation is very simple and can be easily verified.

# for example:

a = 0.3 * 3
b = 0.3 + 0.3 + 0.3
c = 0.6 + 0.3

print('a = ',a)
print('b = ', b)
print('c = ',c)

I expect the answer to be 0.9, but it is different.

a =  0.8999999999999999
b =  0.8999999999999999
c =  0.8999999999999999

Can someone explain why this is happening. I use: Python 3.6.8 :: Anaconda custom (64-bit)

blhsing
  • 91,368
  • 6
  • 71
  • 106
Manualmsdos
  • 1,505
  • 3
  • 11
  • 22
  • 3
    [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3/tutorial/floatingpoint.html) – benvc Mar 08 '19 at 17:09

1 Answers1

1

Use the decimal module if you want precise decimals. Floats are imprecise approximations.

Alec
  • 8,529
  • 8
  • 37
  • 63