使用==运算符比较float / double值 [英] comparing float/double values using == operator

查看:150
本文介绍了使用==运算符比较float / double值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始比较使用相等运算符的两个浮点值时,我使用的代码审查工具与下面的投诉。什么是正确的方法和如何做到这一点?是否有帮助功能(commons- *)在那里,我可以重用?

无法使用equals(== )运算符

解释

通过使用等式(==)或不等式(!=)运算符并不总是准确,因为舍入错误。
$ b

建议



比较两个浮点值,看它们是否接近于值。

  float a; 
float b;

if(a == b)
{
..
}


解决方案

IBM有一个建议,用于比较两个浮点数,使用除法而不是减法 - 这使得选择适用于所有输入范围的epsilon变得更加容易。

  if(abs(a / b-1)ε

至于epsilon的值,我会使用 5.96e-08 ,如这个维基百科表格,或者是这个值的两倍。


The code review tool I use complains with the below when I start comparing two float values using equality operator. What is the correct way and how to do it? Is there a helper function (commons-*) out there which I can reuse?

Description

Cannot compare floating-point values using the equals (==) operator

Explanation

Comparing floating-point values by using either the equality (==) or inequality (!=) operators is not always accurate because of rounding errors.

Recommendation

Compare the two float values to see if they are close in value.

float a;
float b;

if(a==b)
{
..
}

解决方案

IBM has a recommendation for comparing two floats, using division rather than subtraction - this makes it easier to select an epsilon that works for all ranges of input.

if (abs(a/b - 1) < epsilon)

As for the value of epsilon, I would use 5.96e-08 as given in this Wikipedia table, or perhaps 2x that value.

这篇关于使用==运算符比较float / double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆