c++ libstd compute sin and cos simultaneously

Is there no such function in c++ standard library?

No, unfortunately there isn't.

In C library math.h, there was a sincos function

On Linux, it is available as GNU Extension. It's not standard in C either.


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://stackoverflow.com/a/19017286/973580).


Just use sin and cos separately and turn on optimizations. C compilers are pretty good at optimizing, and they will probably realize that you are computing both the sine and cosine of the same variable. If you want to make sure, you can allways inspect the resulting assembly (for gcc use the -S option) and see what did it generate.

The compiler will probably optimize away any calls to sin or cos in favour of simply using SSE intructions to calculate it. I'm not sure SSE has a sincos opcode but even calculating them separatly is faster than calling any sincos function that the compiler won't optimize out.