Java浮动意外圆了 [英] Java float unexpectedly rounded

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

问题描述

我正在使用一个float常量,并在下面的float常量中设置一个对象私有浮点变量,但是当对象输出它设置的值时,它将浮点数最后一位数字加起来。 b
$ b

  private final float RF_FREQUENCY = 956.35625f; 
Object o = new Object();
o.setRFFrequency(RF_FREQUENCY);
System.out.println(o.getRFFrequency);

输出:956.35626

该对象被声明为 protected float rfFrequency; 和下面是getters和setters。

  public float getRFFrequency(){
return rfFrequency;
}
public void setRFFrequency(float value){
this.rfFrequency = value;





$ b

任何想法为什么发生这种情况?
<因为单精度IEEE754浮点数只有23位的精度(24位,包括隐含的1位在开始)。

解决方案

b $ b

这相当于大约七位小数,你可以看到你的号码有八位数字。



所有这一切发生的事情是,计算机正在选择最接近你所要求的数字,它可以代表。



如果你需要更多的精度,使用双精度。这给你52/53位,相当于约15位十进制数字。


I'm using a float constant and setting a objects private float variable to the float constant below, but when the object outputs the value it was set to, it's rounding up the last digit in the float.

private final float RF_FREQUENCY = 956.35625f;
Object o = new Object();
o.setRFFrequency(RF_FREQUENCY);
System.out.println(o.getRFFrequency);

Output: 956.35626

The variable in the object is declared as protected float rfFrequency; and below are the getters and setters.

public float getRFFrequency() {
        return rfFrequency;
    }
public void setRFFrequency(float value) {
        this.rfFrequency = value;
    }

Any idea why this is happening?

解决方案

Because single precision IEEE754 floating point numbers only have 23 bits of precision (24 including the implicit 1 bit at the start).

That equates to roughly seven decimal digits and you can see that your number has eight digits in it.

All that's happening is that the computer is choosing the closest number to what you asked for that it can represent.

If you need more precision, use a double. That gives you 52/53 bits which equates to about 15 decimal digits.

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

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