java 倒数,如何实现“快速倒数平方根”在Java中?

I've heard of the "fast inverse square root", discussed here, and I wanted to put it in my Java program (just for research purposes, so ignore anything about the native libraries being faster).

I was looking at the code, and the C code directly converts the float into an int with some C pointer magic. If you try to do this in Java with casts, it doesn't work: java truncates the float (as you would expect), and you can't get the pointer of a primitive (as you can in C).

So how do you do this?

解决方案

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值