Tip // Little-known transcendental functions
sincos – Most modern CPUs have a built-in instruction
called sincos(x)
that returns both the sine and the cosine of x
.
In scientific computations, often you need both in your computation. So instead of calling sin
and cos
separately, see if your programming language supports the sincos
function, which is often just a thin wrapper to the processor intrinsic function. If it does, you can get a 2x speedup in your trig calls for free.
exp2 – If you are raising 2 to a power, exp2(x)
is much faster than pow(2,x)
.
expm1, log1p – For arguments close to 1, exp(x)-1
and log(1+x)
suffer from significant loss of precision. To avoid this, you can use expm1(x)
and log1p(x)
, respectively, instead, both of which compute the same thing using a different approximation with better error properties for values of x
close to 1.
atan2 – If you are taking the arctangent of a ratio, atan(y/x)
, then you cannot distinguish between y/x
and -y/(-x)
or -y/x
and y/(-x)
. If you need to separate out all four quadrants, then you can use atan2(y, x)
which gives you the correct sign of the angle considering all four quadrants.