I would like to compute both the sine and co-sine of a value together (for example to create a rotation matrix). Of course I could compute them separately one after another like a = cos(x); b = sin(x);
, but I wonder if there is a faster way when needing both values.
Edit: To summarize the answers so far:
Vlad said, that there is the asm command
FSINCOS
computing both of them (in almost the same time as a call toFSIN
alone)Like Chi noticed, this optimization is sometimes already done by the compiler (when using optimization flags).
caf pointed out, that functions
sincos
andsincosf
are probably available and can be called directly by just includingmath.h
tanascius approach of using a look-up table is discussed controversial. (However on my computer and in a benchmark scenario it runs 3x faster than
sincos
with almost the same accuracy for 32-bit floating points.)Joel Goodwin linked to an interesting approach of an extremly fast approximation technique with quite good accuray (for me, this is even faster then the table look-up)
sinx ~ x-x^3/6
andcosx~1-x^2/4
as approximations if you care about speed more than accuracy. You can add on terms in either series as you put more weight on accuracy (en.wikipedia.org/wiki/Taylor_series scroll down to trig taylor series.) Note this is a general way to approximate any function you want that is differntiablen
times. So if you have some bigger function that that sine's and cosine's belong to you will get a much bigger speed up if you approximate it instead of the sin,cos's independently. – Trinitytrinketx
close to some pointx_0
, then expand your Taylor series aroundx_0
instead of 0. This will give you excellent accuracy nearx_0
but the farther you go the worse the results. You probably thought the accuracy sucks cause as you looked at the given asnwer and tried it for values far from0
. That answer is with sin,cos expanded around 0. – Trinitytrinket