比较Java中的float和double原语 [英] Comparing float and double primitives in Java

查看:87
本文介绍了比较Java中的float和double原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了Java的一个奇怪的角落。(这对我来说似乎很奇怪)

I came across a strange corner of Java.(It seems strange to me)

double dd = 3.5;          
float ff = 3.5f;
System.out.println(dd==ff);   

o / p:true

double dd = 3.2;
float ff = 3.2f;
System.out.println(dd==ff);

o / p:false

我观察到如果我们将 .5 OR .0 如3.5,234.5,645.0
然后输出 true 即两个值相等,否则输出 false 虽然它们是等于的。

I observed that if we compare any two values (a float and a double as I mentioned in the example) with .5 OR .0 like 3.5, 234.5, 645.0 then output is true i.e. two values are equal otherwise output is false though they are equals.

即使我尝试制作方法 strictfp 但没有运气。
我错过了什么。

Even I tried to make method strictfp but no luck. Am I missing out on something.

推荐答案

看看每个计算机科学家应该了解浮点数



将无限多个实数压缩成有限数量的位需要近似表示....

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation....


---编辑以显示上述报价的含义---

--- Edit to show what the above quote means ---

你不应该比较浮动或双打的平等;因为,你不能真正保证你指定给浮点数或双数的数字是准确的。

You shouldn't ever compare floats or doubles for equality; because, you can't really guarantee that the number you assign to the float or double is exact.

所以

 float x = 3.2f;

不会产生值为3.2的浮点数。它导致浮点值为3.2加上或减去一些非常小的误差。说3.19999999997f。现在很明显为什么比较不起作用。

doesn't result in a float with a value of 3.2. It results in a float with a value of 3.2 plus or minus some very small error. Say 3.19999999997f. Now it should be obvious why the comparison won't work.

为了比较浮动的平等,你需要检查值是否足够接近价值,如此

To compare floats for equality sanely, you need to check if the value is "close enough" to the same value, like so

float error = 0.000001 * second;
if ((first >= second - error) || (first <= second + error)) {
   // close enough that we'll consider the two equal
   ...
}

这篇关于比较Java中的float和double原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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