在 Java 中使用 == 比较浮点数有什么问题? [英] What's wrong with using == to compare floats in Java?

查看:21
本文介绍了在 Java 中使用 == 比较浮点数有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个java.sun页面 == 是 Java 中浮点数的相等比较运算符.

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

但是,当我输入此代码时:

However, when I type this code:

if(sectionID == currentSectionID)

进入我的编辑器并运行静态分析,我得到:JAVA0078 与 == 相比的浮点值"

into my editor and run static analysis, I get: "JAVA0078 Floating point values compared with =="

使用 == 比较浮点值有什么问题?正确的做法是什么? 

What is wrong with using == to compare floating point values? What is the correct way to do it? 

推荐答案

测试浮点数是否相等"的正确方法是:

the correct way to test floats for 'equality' is:

if(Math.abs(sectionID - currentSectionID) < epsilon)

其中 epsilon 是一个非常小的数字,例如 0.00000001,具体取决于所需的精度.

where epsilon is a very small number like 0.00000001, depending on the desired precision.

这篇关于在 Java 中使用 == 比较浮点数有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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