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

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

Re: GMP precision problem - only getting 15 places of PI


From: mensanator
Subject: Re: GMP precision problem - only getting 15 places of PI
Date: 18 Sep 2005 21:40:10 -0700
User-agent: G2/0.2

nmenuj@gmail.com wrote:
> David Kastrup wrote:
> > nmenuj@gmail.com writes:
> >
> > > 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);
> >                          ^^^^^^^ Uh, oh!
>
> Thanks David! I won't be able to test it just yet, but I'm sure that's
> it.
> Also, my compliments to the developers of GMP, the speed is most
> impressive!

You might also want to make all of your constants mpf's.
If you don't, they will get converted automatically, but that
conversion takes time, especially when the constant is used
inside a loop.

The speed will be even more impressive when you use GMP eficiently.

>
> >
> > >         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;
> > > }
> > 
> > -- 
> > David Kastrup, Kriemhildstr. 15, 44793 Bochum


reply via email to

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