views:

206

answers:

4

Hi all,

I wanted to calculate the angle between two vectors but I have seen these inverse trig operations such as acos and atan uses lots of cpu cycles. Is there a way where I can get this calculation done without using these functions? Also, does these really hit you when you in your optimization?

+2  A: 

This is totally implementation defined. Of course, you could use a third-paty implementation, or an approximation, but first you should profile and determine what your bottlenecks are.

Matthew Flaschen
+8  A: 

There are no such functions in the STL; those are in the math library.

Also, are you sure it's important to be efficient here? Have you profiled to see if there's function calls like this in the hot spots? Do you know that the performance is bad when using these functions? You should always answer these questions before diving into such microoptimizations.

In order to give advice, what are you going to do with it? How accurate does it have to be?

If you need the actual angle to a high precision, you probably can't do better. If you need it for some comparison, you can use absolute values and the dot product to get the cosine of the angle. If you don't need precision, you can do that and use an acos lookup table. If you're using it as input for another calculation, you might be able to use a little geometry or maybe a trig identity to avoid having to find an arccosine or arctangent.

In any case, once you've done what optimization you're going to do, do before and after timing runs to see if you've made any significant difference.

David Thornley
+1 for correcting the source of the math library, and mentioning about profiling and precision.
Xavier Ho
++ Right on, and I like the point about using the dot product, though I imagine you want the sine of the angle for doing comparisons.
Mike Dunlavey
+1  A: 

If these functions are indeed the bottleneck, and you only need an approximation, you can try using the few first terms of the Taylor series expansion of those functions. The magnitude of the next unused term represents the error in your approximation.

Arccos Taylor series

Arctan Taylor series

Emile Cormier
Anyone else here blown away by Wolfram Alpha? You can ask it anything! Try "What is the airspeed velocity of an unladen European swallow?".
Emile Cormier
+1  A: 

The implementations of atan and acos depend on the compiler and the optimization settings. Many implementations will use a table and interpolate to get the nearest value.

Try these things first:

  1. Profile the application to find the where most of the execution time is spent.
  2. Redesign this area for better performance.
  3. Consider Data Driven Design techniques to speed up your program.
  4. Change logic to reduce branches and if statements, consider using Karnaugh maps to simplify the logic.
Thomas Matthews