开发者

Fastest way to get Power by 2

The question is simple; I need the fastest way to calculate power 2. I need that for this formula which calculates distance between 2 points.

var Dist:int = Math.sqrt(开发者_JAVA百科  (mmx - ox) * (mmx - ox)  +  (mmy - oy) * (mmy - oy)  );

Any idea?


The fastest way is often a lookup table, provided you can limit your input values to a small enough range, such as with (pseudo-code):

int sqr_arr[] = {0, 1, 4, 9, 16, 25, 36, ...}
def sqr(n):
    if n < 0:
        return sqr(-n)
    if n >= len(sqr_arr):
        return n * n
    return sqr_arr[n]

This allows a high speed table lookup for lower values but reverts to the (probably) slower method if you try to use an argument not in your table.

But, as Mitch Wheat stated in a comment, speeding up the multiplication will not have much of an effect when the real bottleneck is the square root.

And remember: measure, don't guess! I consider myself reasonably adept at optimisation strategies but you should treat all advice (including mine) with the same circumspection as you would an alcoholic in the gutter, telling you how to live a long and successful life.


If you want to calc sqrt for positive number a, take a recursive sequense

x_0 = a
x_n+1 = 1/2 * (x_n + a / x_n)

x_n goes to sqrt(a) with n -> infinity. first several iterations should be fast enough.

Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜