0

I try to calculate the following product in python:

4.6*400

The answer should be 1840, however, python answers 1839.999....

This works fine

4.6*40*10

Is this a bug in python, or expected behaviour?

Vasco
  • 1,177
  • 11
  • 28

1 Answers1

2

This is not a bug.

>>> 1.2-1.0
0.199999999999999996

Floating point numbers only have 32 or 64 bits of precision, so the digits are cut off at some point, and the resulting number is 0.199999999999999996 in decimal, not 0.2.

For more information you can read the old Python FAQ article Why are floating point calculations so inaccurate? at effbot.org.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • not mine but adding a link is not how to answer a question on SO – Padraic Cunningham Jul 16 '15 at 11:23
  • 1
    Link only answers are often frowned upon. If the question was not a duplicate, I would suggest you amend it with more information. – Roman Luštrik Jul 16 '15 at 11:23
  • ok, thanks.. i will try to give more detailed answers at the future – omri_saadon Jul 16 '15 at 11:25
  • 2
    Also just note for the future if the question is "weird floating point issue", "my dictionary won't stay ordered", "Boolean not working" it's probably a duplicate. – kylieCatt Jul 16 '15 at 11:42
  • 2
    Please read [Your answer is in another castle: when is an answer not an answer?](http://meta.stackexchange.com/q/225370). It's great that you say you "will try to give more detailed answers at the future" but you also _need_ to fix **this** answer ASAP. Otherwise, it'll keep attracting down-votes. – PM 2Ring Jul 16 '15 at 12:58
  • 1
    Thankyou! That's _much_ better! – PM 2Ring Jul 16 '15 at 13:35