PROWAREtech

articles » current » c-plus-plus » algorithms » find-pi

C++: Quickly Find/Solve PI (π)

A slightly modified Bailey–Borwein–Plouffe formula for finding π.

This version of the algorithm uses integers to find PI, and it does so without the leading 3. This is done for greater precision because the integers are only 64-bits which is, not surprisingly, still not enough for PI's infinite run.

For a C# implementation, see this article, which includes this algorithm but also includes a brute force one for finding pi.

#include <iostream>
#include <iomanip>

static unsigned long long power(unsigned long long x, unsigned long long y)
{
	unsigned long long m = 1;
	for (unsigned long long i = 0; i < y; i++)
		m *= x;
	return m;
}

double find_pi_fraction()
{
	unsigned long long pi = (unsigned long long)-3000000000000000000; // set this to zero to include the leading 3 and then divide the solved pi value by 1000000000000000000.0
	for (unsigned long long k = 0, p = power(16, k); (p > 0) & (k < 17); k++, p = power(16, k))
		pi += (4000000000000000000 / (8ULL * k + 1) - 2000000000000000000 / (8ULL * k + 4) - 1000000000000000000 / (8ULL * k + 5) - 1000000000000000000 / (8ULL * k + 6)) / p;
	return pi;
}

int main(int argc, char** argv)
{
	const double PI = 3.1415926535897932384626433832795028841971693993751;
	
	std::cout << std::fixed;
	std::cout << "3." << std::setprecision(0) << find_pi_fraction();
	std::cout.unsetf(std::ios::fixed | std::ios::scientific);
	return 0;
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE