views:

1197

answers:

10

I want to make a function in C that can return PI to X places..

I'm just not sure how... Thanks

Edit: I don't care how slow it is I really just want an algorithm that will return PI at X decimal... Iv been looking at http://bellard.org/pi/ but I don't understand how to get the nth of Pi from this. Thanks

+16  A: 

There are many algorithms for numeric approximation of π.

James McNellis
+15  A: 

In calculus there is a thing called Taylor Series which provides an easy way to calculate many irrational values to arbitrary precision.

Pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
(from http://www.math.hmc.edu/funfacts/ffiles/30001.1-3.shtml )

Keep adding those terms until the number of digits of precision you want stabilize.

Taylor's theorem is a powerful tool, but the derivation of this series using the theorem is beyond the scope of the question. It's standard first-year university calculus and is easily googlable if you're interested in more detail.

Edit: I didn't mean to imply that this is the most practical method to calculate pi. That would depend on why you really need to do it. For practical purposes, you should just copy as many digits as you need from one of the many published versions. I was suggesting this as a simple introduction of how irrational values can be equated to infinite series.

Alan
What happens when I want to go pas the limit of int64 (double) ?
Milo
Also, how can I tell to what accuracy I receive ex: 1 decimal per 500 iterations....
Milo
This taylor series is probably one of the worst ways to generate PI on a computer. You have to have huge precision on your calculations and it'll take many billions of iterations to get past 3.14159. Go ahead, try and see. Or here's a web site that talks about it: http://www.cygnus-software.com/misc/pidigits.htm
indiv
I remember writing this in C++ and QuickBasic and discovering the QuickBasic version actually generated PI faster :/
SLC
on x86 (x87 actually) use a type long double. This is a 10 byte number. You can also use a BigDecimal-like class. Interestingly enough, x86 has the instructions `fldpi` that loads pi into the fpu and `fstp tword MEM_LOC` can be used to store to a 10 byte memory location.
KitsuneYMG
@kts: That still doesn't change the fact that you need **billions** of iterations for any reasonably accurate answer.
Billy ONeal
@user146780:Simple. Notice that the terms are getting successively smaller and are alternately added and subtracted. So when you add a term, you are **certainly** above the real **π**. When you subtract, you are certainly below. So the last two partial sums provide an upper and lower bound for the true value.
slacker
@indiv: there are certainly many series that converge faster. But this one is simple and may be more appropriate for an idle programming exercise, which I assumed was the purpose of the question. @user146780: if I've misinterpreted your meaning and you intend to use this in production code. Do not do this. Grab as many digits as you need off a published version on the net and save that.
Alan
@Alan: OK, but the question clearly says he's trying to write a function that can compute PI to X places... Anyway, I implemented this taylor series and after 1 billion iterations you have "3.14159265". After 3 billion iterations you have the next digit. The digit after that comes after 99 billion iterations. 99 billion.
indiv
Yes, if you want n decimal digits of precision, you'll need something on the order of 10^n iterations. I'm not disputing that it converges slowly. The OP seems to be interested in a learning exercise, not something of practical use.
Alan
A: 

You can tell the precision based on the last term you added (or subtracted). Since the amplitude of each term in Alan's sequence is always decreasing and each term alternates in sign, the sum won't change more than the last term.

Translating that babble: After adding 1/5, the sum won't change more than 1/5, so you are precise to within 1/5. Of course, you'll have to multiply this by 4, so you're really only precise to 4/5.

Unfortunately, math doesn't always translate easily into decimal digits.

Mashmagar
haha! way to go..
Egon
+2  A: 

Are you willing to look up values instead of computing them?

Since you didn't explicitly specify that your function has to calculate values, here's a possible solution if you are willing to have an upper limit on the number of digits it can "calculate":

// Initialize pis as far out as you want. 
// There are lots of places you can look up pi out to a specific # of digits.
double pis[] = {3.0, 3.1, 3.14, 3.141, 3.1416}; 

/* 
 * A function that returns pi out to a number of digits (up to a point)
 */
double CalcPi(int x)
{
    // NOTE: Should add range checking here. For now, do not access past end of pis[]
    return pis[x]; 
}

int main()
{
    // Loop through all the values of "pi at x digits" that we have.
    for (int ii=0; ii<(int)sizeof(pis)/sizeof(double); ii++)
    {
        double piAtXdigits = CalcPi(ii);
    }
}

Writing CalcPi() this way (if it meets your needs) has a side benefit of being equally screaming fast for any value of X within your upper limit.

JeffH
This solution could be coupled to a "computing solution": the array could be declared in a .hpp and defined (i.e. filled) by a metaprogram generating the corresponding .cpp file. The metaprogram would be parameterized by the maximum number of digits needed, and would compute the values to set them into the array.
Luc Touraille
+5  A: 

Latest formula: http://en.wikipedia.org/wiki/Bellard%27s_formula

el.pescado
+2  A: 

Try this algorithm. It's probably the fastest known algorithm that doesn't require arbitrary (read huge) precision floats, and can give you the result directly in base 10 (or any other).

slacker
+5  A: 

As an alternative to JeffH's method of storing every variation, you can just store the maximum number of digits and cut off what you don't need:

#include <string>
#include <iostream>
using std::cout; using std::endl; using std::string;

// The first 99 decimal digits taken from:
// http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html
// Add more as needed.
const string pi =
  "1415926535"
  "8979323846"
  "2643383279"
  "5028841971"
  "6939937510"
  "5820974944"
  "5923078164"
  "0628620899"
  "8628034825"
  "342117067";

// A function in C++ that returns pi to X places
string CalcPi(const size_t decimalDigitsCount) 
{
  string returnValue = "3";
  if (decimalDigitsCount > 0)
  {
    returnValue += "." + pi.substr(0, decimalDigitsCount);
  }
  return returnValue;
} 

int main()
{
  // Loop through all the values of "pi at x digits" that we have. 
  for (size_t i = 0; i <= pi.size(); ++i) 
  {
    cout << "pi(" << i << "): " << CalcPi(i) << endl;
  } 
}

http://codepad.org/6mqDa1zj

Bill
Given that pi is not going to change and that 43 digits is enough precision to calculate the circumference of the universe to a tolerance of the width of *1* proton, this is a pretty reasonable. Unfortunately, the question is about calculating the X'th digit and does not necessarily mean you have to get the digits before digit X and it wouldn't really be a solution here as X could be *anything*!
Neil Trodden
+7  A: 
PI

                                    char
                                _3141592654[3141
      ],__3141[3141];_314159[31415],_3141[31415];main(){register char*
      _3_141,*_3_1415, *_3__1415; register int _314,_31415,__31415,*_31,
    _3_14159,__3_1415;*_3141592654=__31415=2,_3141592654[0][_3141592654
   -1]=1[__3141]=5;__3_1415=1;do{_3_14159=_314=0,__31415++;for( _31415
  =0;_31415<(3,14-4)*__31415;_31415++)_31415[_3141]=_314159[_31415]= -
1;_3141[*_314159=_3_14159]=_314;_3_141=_3141592654+__3_1415;_3_1415=
__3_1415    +__3141;for         (_31415 = 3141-
       __3_1415  ;          _31415;_31415--
       ,_3_141 ++,          _3_1415++){_314
       +=_314<<2 ;          _314<<=1;_314+=
      *_3_1415;_31           =_314159+_314;
      if(!(*_31+1)           )* _31 =_314 /
      __31415,_314           [_3141]=_314 %
      __31415 ;* (           _3__1415=_3_141
     )+= *_3_1415             = *_31;while(*
     _3__1415 >=              31415/3141 ) *
     _3__1415+= -             10,(*--_3__1415
    )++;_314=_314             [_3141]; if ( !
    _3_14159 && *             _3_1415)_3_14159
    =1,__3_1415 =             3141-_31415;}if(
    _314+(__31415              >>1)>=__31415 )
    while ( ++ *               _3_141==3141/314
       )*_3_141--=0            ;}while(_3_14159
       ) ; { char *            __3_14= "3.1415";
       write((3,1),            (--*__3_14,__3_14
       ),(_3_14159              ++,++_3_14159))+
      3.1415926; }              for ( _31415 = 1;
     _31415<3141-               1;_31415++)write(
    31415% 314-(                3,14),_3141592654[
  _31415    ] +                "0123456789","314"
  [ 3]+1)-_314;                puts((*_3141592654=0
,_3141592654))                  ;_314= *"3.141592";}

(copied from: here)

Ritsaert Hornstra
Ohh simple as that!
M28
A: 

Here's a paper (PDF) which explores the curious relationship between a sequence of points on the complex plane and how computing their "Mandelbrot number" (for lack a better term ... the number of iterations required to determine that the points in the sequence are not members of the Mandelbrot set) relates to PI.

Practical? Probably not.

Unexpected and interesting? I think so.

andand
A: 

I believe the algorithm you're looking for is what's known as a "Spigot Algorithm." One particular kind is the BBP (Bailey-Borwein-Plouffe) formula.

I believe that's what you're looking for.

Sagekilla