Search code examples
phploopspi

Using PHP to calculate Pi


Okay this is just something me and my coworker are playing with. We know PHP has it's own PI function but this came forth out of a theory and curiosity.

So we were wondering if and how PHP was able to calculate pi.
Formule of pi = π= 4/1 - 4/3 + 4/5 - 4/7 + 4/9...

Here is what we did:

$theValue = 100;// the max
   for ($i=1; $i<$theValue; $i++){
   if ($i % 2 == 1){
       $iWaardes[] =  4 / $i; // divide 4 by all uneven numbers and store them in an array
    }
}
// Use the array's $keys as incrementing numbers to calculate the $values.
for ($a=0, $b=1, $c=2; $a<$theValue; $a+=3, $b+=3, $c+=3 ){
    echo ($iWaardes[$a] - $iWaardes[$b] + $iWaardes[$c]).'<br>';
}

So now we have a loop that calculated the first series of 4/1 - 4/3 + 4/5 but it stops after that and starts over with the following 3 sequences. How can we make it run the entire $theValue and calculate the whole series?

Please keep in mind that this is nothing serious and just a fun experiment for us.


Solution

  • Just use one loop. Have a $bottom variable that you add 2 on each iteration, divide by it, and add it/subtract it depending on the modulo:

    $theValue = 10000; // the max
    $bottom = 1;
    $pi = 0;
    for ($i = 1; $i < $theValue; $i++) {
        if ($i % 2 == 1) {
            $pi += 4 / $bottom;
        } else {
            $pi -= 4 / $bottom;
        }
        $bottom += 2;
    }
    var_dump($pi); // 3.14169266359
    

    Demo

    What's wrong with your code (other than not dividing by the appropriate number) is the second loop. You're for some reason printing out the stored numbers 3 by 3. This, until $a, that increases by 3, is lower than $theValue which is much higher. So, for example, if $theValue is 10, you only need 2 loops before you start getting out of bound errors.