gnu-misc-discuss
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

GMP precision problem - only getting 15 places of PI


From: nmenuj
Subject: GMP precision problem - only getting 15 places of PI
Date: 18 Sep 2005 09:47:01 -0700
User-agent: G2/0.2

I installed the GNU MP package only today, and wanted to experiment
with the C++ interface. Can someone tell me why I am unable to get more
than 15 correct digits of PI with the following simple program? I
experimented with the PREC variable and the loop upper bounds, but no
luck - the bad digits start at the exact same spot.

If someone has another multi-precision library installed, I request
that you check the code against your library, to rule out a bug in the
program. I suspect the problem is with a temporary assuming a smaller
precision, but the mpf_set_default_prec should have addressed that...

#include <iostream>
#include <gmpxx.h>

using namespace std;
const int PREC=20000;

mpf_class pival(0.0, PREC);
mpf_class d2(1.0, PREC), d3(1.0,PREC);
int main()
{
        int i = 0;
        mpf_set_default_prec(PREC);
        d2 = mpf_class(1.0/2.0,PREC);
        pival = d2 - (d2/4.0)/3.0;
        for (i=5;i<10000;i+=4)
        {
                d2 /= 16.0;
                pival = pival + d2/i;
                pival = pival - (d2/4.0)/(i + 2);
        }
        cout << "def prec " << mpf_get_default_prec() << '\n';
        d3 = mpf_class(1.0/3.0, PREC);
        pival = pival +  d3 - (d3/9.0)/3.0;
        for (i=5;i<10000;i+=4)
        {
                d3 /= 81.0;
                pival = pival + d3/i;
                pival = pival - (d3/9.0)/(i + 2);
        }
        cout.precision(100);
        cout << pival * 4.0 << '\n';
        return 0; 
}


reply via email to

[Prev in Thread] Current Thread [Next in Thread]