2011年7月9日 星期六

Java 浮點數內部格式

Java 浮點數內部格式採用 IEEE 754 二進位浮點數算術標準

浮點數而又分為單精度 (float) 與倍精度 (double) :單精度為 32bits,倍精度為 64bits

float 變數內部格式




double 變數內部格式




例如 :  -12.625 使用 IEEE 754 單精度 表示浮點數

第一步驟:不管正負號直接將數值轉為二進制
12.625 => 1100.101 = 1.100101 × 2^3

第二步驟:計算指數
127+3=130 => 10000010

第三步驟:填入數值置於浮點數規格中
S E      M
1 10000010 100101 0000 0000 0000 0000 0


撰寫研究程式 1 - MyIEEE754.java

public class MyIEEE754 {
    public static void main(String[] args) { 
        System.out.println(Integer.toHexString(Float.floatToRawIntBits(2.25f)));
        System.out.println(Integer.toHexString(Float.floatToRawIntBits(5.625f))) 
    }
}

程式中 Float.floatToRawIntBits(2.25f) 會將 float 浮點數內部格式, 以 int 傳回, 然後以十六進位格式顯示, 以下為執行結果 :

40100000
40b40000

執行結果, 使用下圖為你解釋 :


1. 先計算指數部份 : 128-127=1 (如是 double, 則減去 1023)
2. 移動小數點 : 指數為正數 1, 所以向右移動一位
3. 計算整數 : 小數點左邊為 10 (二進位), 2*1+2*0 = 2
4. 計算小數 : 查表得知 小數點右邊  01 (二進位) 為 0.25
5. 將整數加上小數得到結果 : 2 + 0.25 = 2.25

撰寫研究程式 2 - MyIEEE754_2.java
public class MyIEEE754_2 {
    public static void main(String[] args) {
        System.out.println(Float.toHexString(1.0f));
        System.out.println(Float.toHexString(5.25f));
        System.out.println(Float.toHexString(0.625f));
        System.out.println(Float.toHexString(5.3f));
        System.out.println(Float.toHexString(-5.25f));           
    }
}

以下為執行結果 :

0x1.0p0
0x1.5p2
0x1.4p-1
0x1.533334p2
-0x1.5p2

No Response to "Java 浮點數內部格式"

張貼留言