Search code examples
c++algorithmmathpi

Calculation of value of Pi up to 'n' decimal places


I was trying to make a C++ program to calculate value of Pi up to 'n' decimal places using the Leibniz formula.

The number 'n' would be entered by the user. I was successful in creating the Leibniz formula but I am having trouble with the latter part i.e value precise up to 'n' places.

The trouble :- As more and more terms will continue to add to it, it's digits will keep on changing so how to tell if a particular digit has stopped changing despite the addition of more terms.

The code written so far :-

#include<iostream>
using namespace std;
int main()
{
    float s=0;
    int w=-1;
    for(float i=1;;i=i+2)
    {
        w=w*(-1);
        s=s+w*(1/i);
        cout<<s<<endl;
    }
    return 0;
}

It would be great if things would be kept simple since I am just a beginner at C++.

Thank you very much :)


Solution

  • Since you want to compute Pi up to arbitrary nth digit, you want a library for working with big float numbers; see

    C++ library for big float numbers

    the real trouble is that Leibniz formula is not useful in the context. The actual precision achieved can be estimated as the last term in the formula

      Pi / 4 = 1/1 - 1/3 + 1/5 - 1/7 + ... + (-1)**(n + 1) * 1 / (2 * n - 1) + ... 
    

    If, for intance, you want Pi up to 100th digit it means that the residual (and the last term) should be less than 1e-100:

     1 / (2 * n - 1) < 1e-100
     2 * n  - 1 > 1e100
     n > 5e99
    

    And as you can see 5e99 loops is by far too much for the modern (super-)computers