本文介绍了如何实现“快速倒数平方根”在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过快倒数平方根,,我想把它放在我的Java程序(仅用于研究目的,所以忽略任何有关本机库的更快)。

我正在查看代码,C代码直接将 float 转换为一个带有一些C指针魔术的 int 。如果你试图在Java中通过强制转换来做到这一点,那么它将不起作用:java截断了float(就像你所期望的那样),并且你不能得到原语的指针(就像在C中一样)。
所以你怎么做到这一点?

解决方案

b
$ b

如果事实证明你并不需要它,或者在你使用的CPU架构上速度较慢,那么最好不要在你的项目中使用这个笨拙的代码。






Java库有一个从浮点数到原始位数的方法。

在Javadoc中可以看到 java.lang.Float (),我们有 floatToIntBits 函数以及 intBitsToFloat



意味着我们可以在Java中编写快倒数平方根,如下所示:

  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;

$ / code $ / $ p

这里是双打版本:

  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;

资料来源:


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;
}

Source: http://www.actionscript.org/forums/showthread.php3?t=142537

这篇关于如何实现“快速倒数平方根”在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:05