使用 == 运算符比较浮点/双精度值 [英] comparing float/double values using == operator

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

问题描述

当我开始使用相等运算符比较两个浮点值时,我使用的代码审查工具会出现以下问题.什么是正确的方法以及如何去做?是否有我可以重用的辅助函数(commons-*)?

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?

说明

无法使用等号 (==) 运算符比较浮点值

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

说明

由于舍入误差,使用等式 (==) 或不等式 (!=) 运算符来比较浮点值并不总是准确的.

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

推荐

比较两个浮点值,看看它们的值是否接近.

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

float a;
float b;

if(a==b)
{
..
}

推荐答案

IBM 建议 使用除法而不是减法来比较两个浮点数 - 这样可以更轻松地选择适用于所有输入范围的 epsilon.

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)

至于 epsilon 的值,我将使用 5.96e-08,如这个维基百科表格,或者可能是那个值的 2 倍.

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

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

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