ExamVeda
Login
Home
Data Types and Numeric Types
?

What is the output of print 0.1 + 0.2 == 0.3?

Answer & Solution
Correct Answer: Option B
When we talk about numbers with decimal points (like 0.1, 0.2, 0.3) in computers, we call them "floating-point numbers".

Computers work with a system of 0s and 1s (called binary). It's very easy for them to represent whole numbers (like 1, 2, 10). But when it comes to decimal fractions, it can be a bit tricky.

Think of it like trying to write 1/3 as a decimal number. You get 0.33333... and it goes on forever! You can never write it *exactly* with a finite number of digits.

The same thing happens in computers with numbers like 0.1, 0.2, and 0.3 when they try to represent them in binary. They can't represent them *exactly*. Instead, they store a very, very close approximation.

So, when you do 0.1 + 0.2:
1. The computer takes its *approximation* of 0.1.
2. It takes its *approximation* of 0.2.
3. It adds these two approximations together. The result is an *approximation* of 0.3.

Now, when you compare this sum (the approximation of 0.1 + approximation of 0.2) with the computer's *approximation* of 0.3 using ==, Python checks for exact equality. Because of those tiny, tiny differences in the approximations, the sum of approximations of 0.1 and 0.2 is usually not *exactly* equal to the approximation of 0.3.

It's like saying 0.333 is exactly equal to 0.334 – they are very close, but not exactly the same.

Therefore, the expression 0.1 + 0.2 == 0.3 evaluates to False.

This is a common behavior with floating-point numbers in most programming languages, not just Python. It's important to remember this when dealing with financial calculations or anything that requires extreme precision with decimals.
Examveda
Question posted by Examveda
Community

Join the Discussion

1 Comment
Govind Patel
Govind Patel 1 month ago
* Float representation: Python stores decimal floating-point numbers using the IEEE 754 binary floating-point format.
* Binary conversion: Computers store numbers in binary (base 2). Values such as 0.1, 0.2, and 0.3 cannot be represented exactly in binary floating-point.
* Approximate storage: Python stores the nearest representable values for these numbers rather than their exact decimal values.
* Addition result: When Python calculates 0.1 + 0.2, the result is approximately 0.30000000000000004
* Equlity comparison: Python compares this result with the stored value of 0.3. Because the two floating-point values are different, == returns False.
* It is not an addition error: Python performs the calculation correctly according to floating-point arithmetic rules. The difference comes from how the numbers are represented.