Performance of Cos vs. Sqrt(1 - Sin() ** 2)

1.4k views Asked by At

I am computing a lot of cos(x)'s in my program. Is it more efficient in Fortran to stick with cos(x) or to calculate sqrt(1-sin(x)**2)? Will I be sacrificing any accuracy if the sqrt method is more efficient? And, I guess, the most important question if sqrt is more efficient. Can I expect that the compiler is recognizing this anyways and changing it for me?

1

There are 1 answers

5
Bathsheba On BEST ANSWER

The first thing you should note is that you'll have to be careful to pick the correct root for sqrt(1 - sin(x)**2), otherwise you run the risk of evaluating |cos(x)|, which is not the same. That itself adds complexity.

Use cos(x) as you should avoid such perceived micro-optimisations: you'll do well to beat any optimisation approach adopted by a modern FORTRAN compiler.

Even when I was using FORTRAN, the clever FORTRAN compilers would use the trig functions available on a chipset. sqrt is still on the whole implemented with a Newton-Raphson type algorithm and its evaluation will take a handful of clock cycles.

My hunch is that the latest compilers would reverse out your identity for you and substitute cos(x): check the output assembly.

But if you are in any doubt, profile it.