Java:Math.sqrt()的32位fp实现

use*_*373 7 java math performance 32-bit

标准Math.sqrt()方法在Java中看起来相当快,但它有一个固有的缺点,它总是涉及64位操作,它只会在处理32位float值时降低速度.是否可以使用自定义方法做得更好,该方法使用a float作为参数,仅执行32位操作,并返回float结果?

我看见:

Java中的快速sqrt以牺牲精度为代价

它只是强化了Math.sqrt()通常难以击败的概念.我也看到了:

http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi

这向我展示了一堆有趣的C++/ASM黑客,我根本无法直接移植到Java.虽然sqrt14作为JNI调用的一部分可能很有趣...

我还查看了Apache Commons FastMath,但看起来该库默认为标准的Math.sqrt(),所以没有帮助.然后是Yeppp!:

http://www.yeppp.info/

但我还没有打扰过它.

apa*_*gin 6

您无需sqrt为32位值加速.HotSpot JVM会自动为您完成.

JIT编译器足够智能识别f2d -> Math.sqrt() -> d2f模式并用更快的sqrtssCPU指令代替它sqrtsd.来源.

基准:

@State(Scope.Benchmark)
public class Sqrt {
    double d = Math.random();
    float f = (float) d;

    @Benchmark
    public double sqrtD() {
        return Math.sqrt(d);
    }

    @Benchmark
    public float sqrtF() {
        return (float) Math.sqrt(f);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

Benchmark    Mode  Cnt       Score      Error   Units
Sqrt.sqrtD  thrpt    5  145501,072 ± 2211,666  ops/ms
Sqrt.sqrtF  thrpt    5  223657,110 ± 2268,735  ops/ms
Run Code Online (Sandbox Code Playgroud)