简体   繁体   中英

Floating Point Arithmetic (Python 3) Query - Comparing sums of variables

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM