While doing the multiplication
1.4*0.8 in a python program, I got the result as
Why didn't I get
In C programming language, the same expression gives
Computer Science Stack Exchange is a question and answer site for students, researchers and practitioners of computer science. It only takes a minute to sign up.Sign up to join this community
$1.4$ and $0.8$ cannot be represented exactly in a IEEE floating point number.
This means that the actual number stored and operated on is really $1.4+\epsilon$ and $0.8+\epsilon$ where $\epsilon$ is the rounding error and when you multiply those two ends up as $1.12 + 2.2\epsilon+\epsilon^2$.
This rounding error propagation can bite you in the *** at the weirdest times (like making a platform drift slowly upwards enough to allow niche players to shave off a specific button press) and make the results at the end completely wrong if enough operations align to make the error significant enough to matter. One of the major operations to watch out for in this regard is subtraction of nearly equal numbers so the mathematical result becomes close to the error on the inputs.
The other answers explain why you're not getting 1.12 exactly (in brief, this is because floating point numbers can only exactly represent rationals whose denominator is a power of 2).
The result of the multiplication is probably the same in both languages. What is different is how these results are printed. The C routine seems to round the result more aggressively.
This is a known issue that people have struggled with for a while, (I used to struggle with it too). Here's some python documentation on the subject 14. Floating Point Arithmetic
"It’s easy to forget that the stored value is an approximation to the original decimal fraction, because of the way that floats are displayed at the interpreter prompt. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display"
But to actually solve this issue, you can use the round function to prevent this from happening.
This should give you the same number rounded to 2 decimal places. While this isn't very good for certain situations using floating point variables, it at least gets the job done. I recommend rounding to 5 decimal places.
The broader answer is to consider the suitability of floating point numbers for your purpose. As the other answers have said, floating point calculations are inherently inexact. If you need an exact answer (for example, if you're writing a financial balance sheet) you shouldn't use them. If you don't need an exact answer, you shouldn't be complaining about the difference between 1.2 and 1.1999999...