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
FSINCOScomputing both of them (in almost the same time as a call toFSINalone)Like Chi noticed, this optimization is sometimes already done by the compiler (when using optimization flags).
caf pointed out, that functions
sincosandsincosfare probably available and can be called directly by just includingmath.htanascius approach of using a look-up table is discussed controversial. (However on my computer and in a benchmark scenario it runs 3x faster than
sincoswith 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/6andcosx~1-x^2/4as 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 differntiablentimes. 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.xclose to some pointx_0, then expand your Taylor series aroundx_0instead of 0. This will give you excellent accuracy nearx_0but 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.