While trying out constexpr I was wondering what else can I get compiler to compute. I can pretty much do any integral computation with both C++ Template Metaprogramming and constexpr, but can I do some floating point computations? It appears I can!!

So I set out to compute exp(z), using Taylor series implementation for exp:

// can't deal with negative powers!!
//
constexpr double pow(double x, int y)
{
return y == 0 ? 1.0 : x * pow(x, y-1);
}
constexpr int factorial(int x)
{
return x == 0 ? 1 : x * factorial(x-1);
}
constexpr double exp(double x)
{
return 1.0 + x + pow(x,2)/factorial(2) + pow(x, 3)/factorial(3)
+ pow(x, 4)/factorial(4) + pow(x, 5)/factorial(5)
+ pow(x,6)/factorial(6) + pow(x, 7)/factorial(7)
+ pow(x, 8)/factorial(8) + pow(x, 9)/factorial(9);
}
int main()
{
constexpr double exp1 = exp(1.0);
return 0;
}

In here I have pow function to compute powers of a floating point number, mine is bit limited as it can do integral powers only; factorial is pretty straight forward. exp function function goes to 10 component evaluation. With exp(1) I do see value of *2.7182815255731922* in debug window while cout prints it to be *2.71828*. Since this is floating point value I can’t do static_assert.

Now what’s the proof that it was all compile time rather than runtime evaluation, the only way to confirm is to look at what is executed by processor, that’s right assembly:

Continue reading →

#### Sharing Options: