Calculating Pi with PHP using the Nilakantha Series

The below code calculates pi to 13 decimals using PHP and the Nilakantha Series. We loop through the series 15468 times to get an accurate result.

<?php
$pi = 3;
$counter = 2;
$direction = 1;
for ($x = 0; $x <= 15468; $x++) {
    if ($direction == 1){
        $pi = $pi + (4 / ($counter * ($counter + 1) * ($counter + 2)));
        $counter = $counter + 2;
        $direction--;
    } else {
        $pi = $pi - (4 / ($counter * ($counter + 1) * ($counter + 2)));
        $counter = $counter + 2;
        $direction++;
    }
}
echo $pi;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>