Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using basic arithmetics for calculating Pi with arbitary precision

Tags:

algorithm

math

pi

I am looking for a formula/algorithm to calculate PI~3.14 in a given precision.

The formula/algorithm must have only very basic arithmetic as

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Divison

because I want to implement these operations in C++ and want to keep the implementation as simple as possible (no bignum library is allowed).

I have found that this formula for calculating Pi is pretty simple:

Pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...  = sum( (-1)^(k+1)/(2*k-1) , k=1..inf )

(note that (-1)^(k+1) can be implemented easily by above operators).

But the problem about this formula is the inability to specify the number of digits to calculate. In other words, there is no direct way to determine when to stop the calculation.

Maybe a workaround to this problem is calculating the difference between n-1th and nth calculated term and considering it as the current error.

Anyway, I am looking for a formula/algorithm that have these properties and also converges faster to Pi

like image 351
Isaac Avatar asked Dec 19 '10 18:12

Isaac


People also ask

How is pi precisely calculated?

The circumference of a circle is found with the formula C=πd=2πr. Thus, pi equals a circle's circumference divided by its diameter. Plug your numbers into a calculator: the result should be roughly 3.14.

What are the most efficient algorithms to calculate pi?

Ramanujan's work is the basis for the Chudnovsky algorithm, the fastest algorithms used, as of the turn of the millennium, to calculate π.

What is the algorithm to calculate pi?

The spigot algorithm for calculating the digits of π and other numbers have been invented by S. Rabinowitz in 1991 and investigate by Rabinowitz and Wagon in 1995. The algorithm generates the digits sequentially, one at a time, and does not use the digits after they are computed.


1 Answers

Codepad link:

#include <iostream>
#include <cmath>
int main()
{
    double p16 = 1, pi = 0, precision = 10;

    for(int k=0; k<=precision; k++)
    {
        pi += 1.0/p16 * (4.0/(8*k + 1) - 2.0/(8*k + 4) - 1.0/(8*k + 5) - 1.0/(8*k+6));
        p16 *= 16;
    }
    std::cout<<std::setprecision(80)<<pi<<'\n'<<M_PI;
}

Output:

3.141592653589793115997963468544185161590576171875
3.141592653589793115997963468544185161590576171875

This is actually the Bailey-Borwein-Plouffe formula, also taken from the link from wikipedia.

like image 123
Gabi Purcaru Avatar answered Dec 28 '22 10:12

Gabi Purcaru