Remember to benchmark your code before using this.
If it turns out you don't need it, or it's slower on the CPU architecture you are using, then it's better to go without having this obtuse code in your project.
The Java libraries have a way to get from the float number to the raw bits.
As seen in the Javadoc for java.lang.Float
( http://docs.oracle.com/javase/6/docs/api/java/lang/Float.html ), we have the floatToIntBits
function, as well as intBitsToFloat
.
This means we can write the "fast inverse square root" in Java as follows:
public static float invSqrt(float x) {
float xhalf = 0.5f * x;
int i = Float.floatToIntBits(x);
i = 0x5f3759df - (i >> 1);
x = Float.intBitsToFloat(i);
x *= (1.5f - xhalf * x * x);
return x;
}
Here is the version for doubles:
public static double invSqrt(double x) {
double xhalf = 0.5d * x;
long i = Double.doubleToLongBits(x);
i = 0x5fe6ec85e7de30daL - (i >> 1);
x = Double.longBitsToDouble(i);
x *= (1.5d - xhalf * x * x);
return x;
}
Source: http://www.actionscript.org/forums/showthread.php3?t=142537
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…