回 帖 发 新 帖 刷新版面

主题:浮点数有效位

public class Test
{
    public static void main(String args[])
    {
        
        float d=1.88888888888888888888f; 
        System.out.println(d);
    }
}
输出为1.8888888

改为double d=1.88888888888888888888; 
输出1.8888888888888888
float的有效位数是多少    
double的有效位数是多少
有效位算不算小数点,输出最后一位属不属于有效位    

回复列表 (共2个回复)

沙发

public class Test
{
    public static void main(String args[])
    {
        int i=1;
        double d=1.000000000000001; //小数点后15位
        System.out.println(d==i);
    }
    
}
输出false
改为double d=1.0000000000000001;  //小数点后16位或更多位
输出true

板凳

[quote]Q. When I do floating-point operation, why some unwanted result comes out?

// Example, why the red extra comes out?
double x = 27.475;
double y = 7.22; 
System.out.println(x - y); // 20.255000000000003 

A:
That is a famous floating-point phenomenon. Your number is represented in decimal, and your computer represents them in binary, some discrepancy will happen with that conversion back-and-forth. It is normal since Machine Language / Assembly / Fortran time. If you go to an interview, someone ask you this question, you don't know the answer, and inexperienced programmer situation will be exposed to the interviewer immediately.

When you output, format it to what you desired.How the precision changed? This is no easy job.

You need understand what is radix.
Radix for decimal is 10
Radix for binary is 2 29.3 in decimal is actually

2 * 101 + 9 * 100 + 3 * 10-1 In binary
11101.010011001.............

Do the same thing, but replace 10 to 2. However, the number will never end. You will find out something is short in decimal may become infinite long in binary. And the opposite will not be infinite long, but possible longer then the computer system allowed.

Computer cannot allow infinite long number, it must be truncated to fit the precision of the floating-point number in the system. Therefore, the value of some floating-point number changes in the conversion from one radix to another radix back-and-forth.

If 29.125 in decimal is converted to binary, there are no problems. It will be 11101.001 in binary precisely, since 0.125 is 2-3 or 1/8

This is mostly math in computing problem. Real numbers in math are continuous. However, real numbers in computer must be discrete. Therefor, we don't call them real numbers, but float and double.

Theoretically, this kind unwanted results are inavoidable, no matter how accurate your computer is or will be in the future. You'd better understand it. Thanks!
[/quote]

Better and easier read here
[url]http://bobcat.webappcabaret.net/javachina/faq/08.htm#math_Q18[/url]

我来回复

您尚未登录,请登录后再回复。点此登录或注册