为什么比较浮动在Java中不一致? [英] Why is comparing floats inconsistent in Java?

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

问题描述

  class Test {
public static void main(String [] args){
float f1 = 3.2f;
float f2 = 6.5f;

if(f1 == 3.2){
System.out.println(same);
} else {
System.out.println(different);

if(f2 == 6.5){
System.out.println(same);
} else {
System.out.println(different);




$ b

输出:

 不同
相同

为什么这样的输出?我预计相同作为第一种情况的结果。

解决方案

是6.5可以精确地表示在浮动和双重 - 而3.2不能完全表示在任何一种类型...和两个最接近的近似是不同的。 float和double之间的平等比较首先将float转换为double,然后比较两者。因此,数据丢失。




你不应该比较浮动或双打的平等;因为,你不能真正保证你分配给float或double的数字是确切的。 这个舍入误差是浮点计算的一个特性
$ b


压缩将无穷多个实数转换成有限位数
需要一个近似表示。虽然无限多
多个整数,但在大多数程序中,整数计算的结果可以存储在32位中。

相反,给定任意位数,
大部分的实数计算将产生的数量
不能用这么多位精确地表示。因此浮点计算的
结果通常必须以
的顺序四舍五入以适应其有限表示。这个舍入错误是浮点计算的
特征。

检查每个计算机科学家都应该知道的关于浮点运算的更多信息!


class Test{  
    public static void main(String[] args){  
        float f1=3.2f;  
        float f2=6.5f;  

        if(f1==3.2){
            System.out.println("same");  
        }else{
            System.out.println("different");  
        }
        if(f2==6.5){
            System.out.println("same");  
        }else{  
            System.out.println("different");  
        }
    }  
}  

output:

different
same

Why is the output like that? I expected same as the result in first case.

解决方案

The difference is that 6.5 can be represented exactly in both float and double - whereas 3.2 can't be represented exactly in either type... and the two closest approximations are different. An equality comparison between float and double first converts the float to a double and then compares the two. So the data loss.


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. This rounding error is a characteristic feature of floating-point computation.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits.

In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

Check What Every Computer Scientist Should Know About Floating-Point Arithmetic for more!

这篇关于为什么比较浮动在Java中不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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