Why is the implementation of computing both sine and cosine at the same time about the same speed as just computing one of them?

185 viewsMathematicsOther

Was messing around with C and found this quirk. How does this function work so quickly? How is it implemented?

In: Mathematics

3 Answers

Anonymous 0 Comments

Be aware that at least the Intel x86 architecture has an FSINCOS instruction. The ELI5 of that is that the CPU does the hard work in a single operation, meaning the C function isn’t doing anything interesting. FSINCOS is faster than running both FSIN and FCOS.

Of course the CPU isn’t magic and must be doing similar things internally to what a C function would be doing, although more efficiently. There is some commonality in computing the sine and cosine which both CPU instructions of C functions can take advantage of. The details depend on how they’re implemented.

Anonymous 0 Comments

Most implementations use a Taylor series expansion (cos = 1 – x^2 /2! + x^4 /4! – x^6 /6! …, sin = x – x^3 /3! + x^5 /5! – …) or lookup table. Cos and Sin are the same, just pi/2 out of phase, so you only need to do it once.

Anonymous 0 Comments

The ELI5 answer is because sin and cos have the same values just 90 degrees out of phase. Just look at a graph of sin and a graph of cos to see what I mean.