快速方形双倍 [英] Quickly square a double
问题描述
我正在寻找最方便的方法( double d
)。到目前为止,我提出了两种方法:
I am looking for the fastest way to square a double (double d
). So far I came up with two approaches:
1. d*d
2. Math.pow(d, 2)
测试性能我设置了三个测试用例,每个测试用例使用三个案例的相同种子生成随机数,然后计算循环中的平方数1000000次。
To test the performance I set up three test cases, in each I generate random numbers using the same seed for the three cases and just calculate the squared number in a loop 100 000 000 times.
在第一个测试案例中,使用 random.nextDouble()
生成数字,在第二种情况下使用 random.nextDouble()* Double.MAX_VALUE
和第三个使用 random.nextDouble()* Double.MIN_VALUE
。
In the first test case numbers are generated using random.nextDouble()
, in the second case using random.nextDouble()*Double.MAX_VALUE
and in the third one using random.nextDouble()*Double.MIN_VALUE
.
一些运行的结果(近似结果,总是有一些变化,使用java 1.8运行,在Mac OSX Mavericks上为java 1.6编译)
The results of a couple of runs (approximate results, theres always some variation, run using java 1.8, compiled for java 1.6 on Mac OSX Mavericks)
Approach | Case 1 | Case 2 | Case 3
---------•--------•--------•-------
1 | ~2.16s | ~2.16s | ~2.16s
2 | ~9s | ~30s | ~60s
结论似乎是方法1更快但也 Math.pow
似乎表现得有些奇怪。
The conclusion seems to be that approach 1 is way faster but also that Math.pow
seems to behave kind of weird.
所以我有两个问题:
1 为什么 Math.pow
这么慢,为什么它与>非常相应? 1
,甚至更糟糕的是< -1
数字?
1 Why is Math.pow
so slow, and why does it cope badly with > 1
and even worse with < -1
numbers?
2 有没有办法提高性能超过我建议的方法1?我在想类似的事情:
2 Is there a way to improve the performance over what I suggested as approach 1? I was thinking about something like:
long l = Double.doubleToRawLongBits(d);
long sign = (l & (1 << 63));
Double.longBitsToDouble((l<<1)&sign);
但这是a)错误,b)与方法1的速度大致相同。
But that is a) wrong, and b) about the same speed as approach 1.
推荐答案
对数字求平方的最快方法是将其自身相乘。
The fastest way to square a number is to multiply it by itself.
为什么
Math.pow
这么慢?
实际上并非如此,但它正在执行取幂而不是简单的乘法。
It's really not, but it is performing exponentiation instead of simple multiplication.
为什么它严重处理> 1,更糟糕的是< -1个数字
and why does it cope badly with > 1 and even worse with < -1 numbers
首先,因为它算数学。来自 Javadoc 它还包含许多极端情况的测试。最后,我不会过分依赖你的微观基准。
First, because it does the math. From the Javadoc it also contains tests for many corner cases. Finally, I would not rely too much on your micro-benchmark.
这篇关于快速方形双倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!