-1

When I run the below code in python3

a = 4.1
b = 1000000
c = 0
result = (a * b) + c
print(result)

I got this result

4099999.9999999995

Could you please tell me how to correct this calculation?

PS. This is a known issue in python?

Ar Aui
  • 392
  • 1
  • 7
  • 17
  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Phylogenesis Aug 16 '17 at 09:38
  • @Phylogenesis I see thank you so much! Could you please suggest me how to correct the calculation? – Ar Aui Aug 16 '17 at 09:44
  • 1
    Yes. This is a known issue in Python. And an issue with all the programming languages that support fixed length floating point numbers. And with all the hardware that supports fixed length floating point numbers. Let's say it's a sad fact of life... Having a finite amount of space you can encode a finite number of numbers, while reals are uncountable. — On the other hand, an error on the 16th digit is equivalent to an error in the order of 10 μm when you are measuring the Earth-Sun distance. If you need more precision when you are using a computer, you can have it. But it's uncommon. – gboffi Aug 16 '17 at 09:47
  • @gboffi Thank you for your comments! – Ar Aui Aug 16 '17 at 10:01
  • 1
    _"Could you please suggest me how to correct the calculation? "_ If for you 4.1 means `41/10` then `41*1_000_000/10` does the trick. – gboffi Aug 16 '17 at 10:16

1 Answers1

1

this is a known behaviour on python2 but also python3.
The documentation suggests rounding the values or using the decimal module.

peyo
  • 442
  • 3
  • 9