On Sun, 13 Sep 2015 22:13:21 +0200, mark wrote:
> On 2015-09-13 21:24, Marcel Mueller wrote:
>> Is there some work around to get a constexpr version of trigonometric
>> math functions like sin, cos?
>
> I don't think there is a 'sane' possibility. But, you if you don't care
> about sanity, you can evaluate a taylor series as constexpr:
>
http://prosepoetrycode.potterpcs.net/2015/07/more-fun-with-constexpr/
FWIW, here's a complete implementation of such:
#include <cmath>
namespace {
static const int terms = 20;
constexpr double alternate(double x2, int i, int k, double xn, long long nf)
{
return (i > terms) ? 0.0 :
(k*xn/nf + alternate(x2, i+2, -k, xn*x2, nf*(i+1)*(i+2)));
}
}
namespace taylor {
constexpr double sin(double x)
{
return alternate(x*x, 1, 1, x, 1);
}
constexpr double cos(double x)
{
return 1.0 + alternate(x*x, 2, -1, x*x, 2);
}
}
It doesn't always agree with libc's sin/cos, but any difference appears to
be limited to the last bit. sin() differs in ~15% of cases, cos() in ~30%.