algorithm to calculate pi

May 14, 2010 at 2:26am
i'm working on an implementation of the gauss-legendre algorithm to calculate pi and all runs quite smoothly but i was wondering how to get more digits outputted, cout.precision() seems to top out at 17?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    bool run=true;
    double a=1, aa, b=pow(2,-.5), t=.25, p=1, r;
    int iterations, exit;
    cin >> iterations;
    while(run)
    {
         for(int i=0;i<iterations;i++)
         {
             aa=(a+b)/2;
             b=pow((a*b),.5);
             t=t-p*pow((a-aa),2);
             p=2*p;
             r=(pow((a+b),2))/(4*t);
             a=aa;
         }
         cout.precision(17);
         cout << r;
         cin >> a;
         run=false;
    }
    return 0;
}

i was thinking maybe some sort set of conditionals that will kick it over to another variable or maybe an use an array to hold each digit seperately. any ideas?
May 14, 2010 at 2:33am
precision is not topping out. The capacity for 'double' is.

doubles can only hold so much information. The more decimal places you put on a number, the more information you need. 17 digits requires a lot of memory for a single primitive type. It's more than double can offer you.

You have the following options:

1) accept that double can't get any more precise and settle on a 17 digit value for pi

2) upgrade to 'long double' and get a few more digits for precision

3) abandon primitive types and use something like a bignum library
May 14, 2010 at 3:02am
Thanks, what would you suggest for a bignum library?
May 14, 2010 at 4:29am
I've never used any as I haven't had the need.

But this one sounds good:

http://gmplib.org/

It's also the first hit on google for "bignum" (well, 2nd... the first was wikipedia) ;P
May 14, 2010 at 12:40pm
GNU MP Bignum +1

It has a C++ class interface to the system, which makes it really easy to use in C++.

[edit] BTW, please #include <cmath>
Last edited on May 14, 2010 at 12:41pm
Topic archived. No new replies allowed.