Skip to content

Instantly share code, notes, and snippets.

@xeno14
Created June 15, 2015 14:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeno14/6188291aedcb2cd2dc15 to your computer and use it in GitHub Desktop.
Save xeno14/6188291aedcb2cd2dc15 to your computer and use it in GitHub Desktop.
Compile-time calculation of Pi
#include <cstdio>
#include <ratio>
template <typename R, intmax_t N>
struct ratio_pow {
using prev = typename ratio_pow<R, N-1>::value;
using value = std::ratio<R::num * prev::num, R::den * prev::den>;
};
template <typename R>
struct ratio_pow<R, 0> {
using value = std::ratio<1, 1>;
};
template <typename X, intmax_t I, intmax_t N>
struct arctan_impl {
using coefficient =
std::ratio_multiply<
typename ratio_pow<std::ratio<-1, 1>, I>::value,
std::ratio<1, 2 * I + 1>
>;
using value = std::ratio_add<
std::ratio_multiply<
coefficient,
typename ratio_pow<X, 2 * I + 1>::value
>,
typename arctan_impl<X, I+1, N-1>::value
>;
};
template <typename X, intmax_t I>
struct arctan_impl<X, I, 0> {
using value = std::ratio<0, 1>;
};
template <typename X, intmax_t N>
struct arctan {
using value = typename arctan_impl<X, 0, N>::value;
};
template <class R>
void dump() {
printf("%.10lf\n", (double(R::num) / R::den));
}
using pi =
std::ratio_subtract<
std::ratio_multiply<
std::ratio<16, 1>,
typename arctan<std::ratio<1, 5>, 6>::value
>,
std::ratio_multiply<
std::ratio<4, 1>,
typename arctan<std::ratio<1, 239>, 2>::value
>
>;
int main () {
dump<pi>();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment