0

The question asked: 17: If we have variables var1 = 0.1 var2 = 0.2 and we want to compare their sum with var3 = 0.3, which of the following is the correct way to do it?

  1. (var1 + var2) == var3
  2. round(var1,1) + round(var2, 1 ) == round(var3,1)
  3. round(var1+ var2, 10) == round(var3, 10)

The answer was 2 but when reading up about floating arithmetic I thought it was 3. Can anyone guide me through this?

1 Answers1

0

Go into your python editor:

print(round(var1 + var2, 10) == round(var3, 1))

Returns True

print(round(var1,1) + round(var2, 1 ) == round(var3,1))

Returns False

You are correct.

Note that as of python 3.5, as per this answer, math.isclose is the practical way to compare floats.

Kraigolas
  • 5,121
  • 3
  • 12
  • 37