Java中的浮点数 [英] Float numbers in Java

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

问题描述



  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);

code $

$ b $ o不同
相同

解决方案

6.5有一个有限的二进制表达式:110.1

位可以完美地表示这个数字。

110.100000000000000000000(float)

= 6.5
$ b $ 110.10000000000000000000000000000000000000000000000000(双精度)

= 6.5

3.2另一方面有一个无限的二进制表示:101.0011001100110011 ...

float和double没有无限精度,因此只能接近这个数字:(

101.001100110011001100110(float)

= 3.2000000476837158203125

>

101.00110011001100110011001100110011001100110011001101(double)

= 3.20000000000000017763568394002504646778106689453125

正如您可以清楚地看到的,这些数字不是一样!

Could anyone please me why the output of the following programme is not " different different"?

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");
}

o/p :different same

解决方案

6.5 has a finite binary representation: 110.1

Any floating type with at least 4 significant bits can represent this number perfectly.

110.100000000000000000000 (float)
= 6.5

110.10000000000000000000000000000000000000000000000000 (double)
= 6.5

3.2 on the other hand has an infinite binary representation: 101.0011001100110011...

float and double don't have infinite precision and thus can only approximate this number :(

101.001100110011001100110 (float)
= 3.2000000476837158203125

101.00110011001100110011001100110011001100110011001101 (double)
= 3.20000000000000017763568394002504646778106689453125

As you can clearly see, these numbers are not the same!

这篇关于Java中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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