While there is no standard C++ library function, you can define a template function pretty quickly:
template <class S>
std::pair<S,S> sincos(S arg) { return { std::sin(arg), std::cos(arg) }; }
You can then get the result on a single line (with C++ 17) with:
auto [s, c] = sincos(arg);
It's very convenient if you are doing this often, saves space, and is self-documenting, so I would highly recommend it.
If you're worried about performance, don't. When compiled with optimizations, it should produce the exact same code as calling sin and cos separately. You can confirm this is the case with clang++ -std=c++17 -S -o - -c -O3 sincos.cpp
on the following test code:
#include <cmath>
#include <utility>
#include <iostream>
template <class S>
std::pair<S,S> sincos(S arg) { return { std::sin(arg), std::cos(arg) }; }
void testPair(double a) {
auto [s,c] = sincos(a);
std::cout << s << ", " << c << '\n';
}
void testSeparate(double a) {
double s = std::sin(a);
double c = std::cos(a);
std::cout << s << ", " << c << '\n';
}
On MacOS with clang, both test functions compile to the exact same assembly (minus the name changes) that call ___sincos_stret
to perform the combined computation (see https://mcmap.net/q/588734/-___sincos_stret-undefined-symbol-when-linking).
-O1
) and, in general-Ofast
will do this for you. godbolt.org/z/jCiTDo – Presidentelectstd::exp(I * angle)
, or look at what code it generates - hopefully a (possibly internal) optimizedsincos
function. In any case, it won't be any worse than separate calls tosin
andcos
, and should avoid the numerical instabilities in trying to derive one from the other by trig identities. – Squirmy