ProgrammingHardTCS NQT · Infosys

What is printed?

What is printed?
print(sum([0.1, 0.2, 0.3]) == 0.6, 0.1 + 0.2 + 0.3 == 0.6, 0.3 + 0.2 + 0.1 == 0.6)
  1. A. True True False
  2. B. False True False
  3. C. True False True
  4. D. False False True

Correct answer: C. True False True

Since Python 3.12, sum() of floats uses compensated summation, so sum([0.1, 0.2, 0.3]) returns exactly 0.6. Plain left-to-right + gives 0.6000000000000001, so 0.1 + 0.2 + 0.3 == 0.6 is False, while adding 0.3 + 0.2 first gives 0.5 and then 0.6 exactly.

More Python Programming questions

Exams that ask this topic