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

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

我看见:

Fast sqrt in Java at the expense of accuracy

它只是强化了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/

但我还没有打扰过它.

解决方法

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

JIT编译器足够智能识别f2d – > Math.sqrt() – > d2f模式并用更快的sqrtss cpu指令代替sqrtsd替换它. The source.

基准:

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

结果如下:

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...