开发者

Faster math ops [duplicate]

开发者 https://www.devze.com 2023-04-12 06:38 出处:网络
This question already has answers here:开发者_开发问答 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_开发问答 Closed 11 years ago.

Possible Duplicate:

Fast algorithm for polar -> cartesian conversion

I am running some pathfinding code (which is a bit slow) through jvisualvm, what I found was that 80% time is being spent in my vector implementation more specifically the part that convert cartesian to polar,

r = Math.sqrt((x * x) + (y * y));
t = Math.atan2(y,x);

are there any old school tricks that would get me some more performance?


In my experience in path finding algorithms, the problem is not those lines.

The main questions is "How many times you call these two lines?"

You should investigate your path finding algorithm.

Anyway, if you want reduce the delay of those lines, it is possible to make a pre-calculated table for sqrt and atan2 for each x and y. Or even a table that maps each (x, y) to (r, t) directly.


You should consider if you really need to use Math.atan2(). In my experience there are very few geometric computations that really need the actual angle; you can get faster, simpler, and more robust results by using more natural operations.

For example, if you want to evaluate the angle between two vectors (say, a and b), you can instead often use the dot product:

(a.x*b.x + a.y*b.y) = |a| |b| cos(angle)

and a kind of rump "cross product":

(a.x*b.y - a.y*b.x) = |a| |b| sin(angle)

This "cross product" is especially useful because the sign tells you which side of vector a the vector b points to.

If it turns out you really do need an angle (usually for human-readable output), these values are tailor made for input to atan2().

0

精彩评论

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