Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why atan2(y,x) is faster to compute than arcsin or arccos?

I've read that when I know Y and X it's better to compute atan2(y,x) to get the angle instead of using a single value with asin and acos. I've tried to dig into math.h lib but I didn't found any formula.

Can someone explain why atan2 is better?

like image 799
Singee Avatar asked Oct 19 '22 07:10

Singee


2 Answers

I guess you are comparing two pieces of code that look mostly like this:

angle = atan2(x, y);

and

angle = acos(x / sqrt(x * x + y * y));

(I assume C code)

The first part calculates what you need directly, while the second part does it in a roundabout way - it's natural to expect that the first one is faster (unless atan2 implementation contains some variant of the second code example).

In addition, atan is a pretty "primitive" function - it "feels" more general than "acos" or "asin". x87 has a command for it, so I expect old implementations of acos to use atan2 internally. Also, I don't know enough of SSE, but it would be reasonable to expect SSE to implement atan2, even just for compatibility with x87.

like image 65
anatolyg Avatar answered Nov 15 '22 05:11

anatolyg


theta = atan2(y,x);

is more simple than:

float in = 1.0/sqrt(x*x+y*y);
theta = acos(x*in);
if(y<0)
    theta = -acos(x*in);
else
    theta = acos(y*in);

Don't you think? It's simpler, and maybe faster, depending on the implementation.

Now, if x and y are not arbitrary, but if you can assume for instance that x²+y²=1 and y>=0, then

theta = acos(x);

Is more simple, and maybe faster than atan2. But again, speed with vary with implementations. The atan2 might, or might not, be implemented with acos and asin, or using faster algorithms.

like image 25
galinette Avatar answered Nov 15 '22 07:11

galinette