简体   繁体   English

浮点算术(Python 3)查询 - 比较变量的总和

[英]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?问的问题: 17:如果我们有变量 var1 = 0.1 var2 = 0.2 并且我们想将它们的总和与 var3 = 0.3 进行比较,以下哪个是正确的方法?

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

The answer was 2 but when reading up about floating arithmetic I thought it was 3. Can anyone guide me through this?答案是 2,但在阅读有关浮动算术的信息时,我认为是 3。有人可以指导我完成这个吗?

Go into your python editor: Go 进入您的 python 编辑器:

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

Returns True返回True

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

Returns False返回False

You are correct.你是对的。

Note that as of python 3.5, as per this answer , math.isclose is the practical way to compare floats.请注意,从 python 3.5 开始,根据这个答案math.isclose是比较浮点数的实用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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