Java:Math. 32-bit FP implementation of sqrt()

Standard math Sqrt () method seems to be quite fast in Java, but it has an inherent disadvantage that it always involves 64 bit operations, and it only slows down when processing 32-bit floating-point values Can a custom method that uses float as a parameter do better, only perform 32-bit operations and return a float as the result?

I see: @ h_ 419_ 3@

Fast sqrt in Java at the expense of accuracy@H_419_3 @

It just reinforces math Sqrt () is often a difficult concept to beat I saw it too: @ h_ 419_ 3@

http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi @H_ 419_ 3@

This shows me a bunch of interesting C / ASM hackers. I'm too ignorant to transplant directly to Java Although sqrt14 may be interesting as part of a JNI call@ H_ 419_ 3@

I also checked Apache Commons fastmath, but it seems that the library defaults to standard math Sqrt (), so it doesn't help Then yepp!:@ H_ 419_ 3@

http://www.yeppp.info/ @H_ 419_ 3@

But I haven't disturbed it yet@ H_ 419_ 3@

Solution

You don't need to speed up sqrt. For 32-bit values The hotspot JVM will do it for you automatically

The JIT compiler is smart enough to recognize F2D – > math Sqrt() – > D2f mode and replace it with a faster sqrtss CPU instruction instead of sqrtsd The source.@ H_ 419_ 3@

Datum: @ h_ 419_ 3@

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

The results are as follows: @ h_ 419_ 3@

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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>