Страницы

Поиск по вопросам

среда, 26 февраля 2020 г.

Как получить значение числа ПИ во время компиляции?

#cpp


Как получить значение числа ПИ с заданной точностью во время компиляции?
    


Ответы

Ответ 1



В основном взято отсюда Добавлено только ограничение точности. #include #include // Generic exponent compile-time calculations. Pow<2,3>::result == 2^3 template struct Pow { static constexpr double result = B * Pow::result; }; template struct Pow { static constexpr double result = 1; }; // Bailey-Borwein-Plouffe formula for calculating pi // http://en.wikipedia.org/wiki/Bailey-Borwein-Plouffe_formula template struct CalculatePi { static constexpr double pi = ( 1.0 / Pow<16, N>::result * ( 4.0 / (8 * N + 1.0) - 2.0 / (8 * N + 4.0) - 1.0 / (8 * N + 5.0) - 1.0 / (8 * N + 6.0) ) ) + CalculatePi::pi; ; }; template <> struct CalculatePi<-1> { static constexpr double pi = 0.0; }; template struct Pecision : public CalculatePi { static constexpr double value = (long long)(CalculatePi::pi * Pow <10, N>::result) / Pow <10, N>::result; }; template <> struct Pecision<0> { static constexpr double value = 0.0; }; // main program. Print pi, calculated from 10 iterations of // the BBP formula above int main() { std::cout.precision(std::numeric_limits::digits10); std::cout << "pi: " << Pecision <10>::value << std::endl; return 0; }

Ответ 2



Например с помощью серий Грэгори. // Example program #include #include template T calculatePi(int depth) { T pi = 0; bool sign = true; // true: +, false: - for (int i = 1; i < depth; i += 2) { if (sign) pi += 1/static_cast(i); else pi -= 1/static_cast(i); sign = !sign; } return pi*4; } int main() { std::cout << calculatePi(10000); }

Комментариев нет:

Отправить комментарий