2015-05-21 57 views

回答

5

可以使用Java標準的數學庫計算這一點,使用基本規則的對數的變化:

public static final int log2(float f) 
{ 
    return (int)Math.floor(Math.log(f)/Math.log(2.0)); 
} 

或者你也可以利用這個信息是IEEE 754浮點數內顯式存儲的事實:

Taken from en.wikipedia.org/wiki/File:Float_example.svg

指數實際上包含您正在尋找的答案,您所要做的就是將它一直移到右邊並從中減去127。當然,某些浮點值的指數爲-127(表示爲零)。這些被稱爲低於正常值的值,並且提取它們的對數有點棘手。這是使用查找表發現:

private static final int[] logTable = new int[256]; 

static 
{ 
    logTable[0] = logTable[1] = 0; 
    for (int i=2; i<256; i++) logTable[i] = 1 + logTable[i/2]; 
    logTable[0] = -1; 
} 

public static final int log2(float f) 
{ 
    int x = Float.floatToIntBits(f); 
    int c = x >> 23; 

    if (c != 0) return c - 127; //Compute directly from exponent. 
    else //Subnormal, must compute from mantissa. 
    { 
     int t = x >> 16; 
     if (t != 0) return logTable[t] - 133; 
     else return (x >> 8 != 0) ? logTable[t] - 141 : logTable[x] - 149; 
    } 
} 

該解決方案,改編自here,比前一個快了不少。這兩種方法都會對負值或無限值,零和NaN產生未定義的結果 - 除非您在複雜的空間中工作,否則它們應該如此。

+0

值得注意的是,有一個'Math.getExponent(float)'方法可以爲你做第一部分(從float獲取指數)。 – RealSkeptic