Last Updated: February 25, 2016
·
7.66K
· donutdan4114

Calculating Pi using PHP

The world of mathematical programming does not lie solely in the hands of C programmers and other lower level languages.

Using PHP we can also calculate Pi, albeit very slowly.

$pi = 4; $top = 4; $bot = 3; $minus = TRUE;
$accuracy = 1000000;

for($i = 0; $i < $accuracy; $i++)
{
  $pi += ( $minus ? -($top/$bot) : ($top/$bot) );
  $minus = ( $minus ? FALSE : TRUE);
  $bot += 2;
}
print "Pi ~=: " . $pi;

This method of calculating Pi is slow, but it is easy to read code.
You can read more about this method here:
http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80

If you increase the $accuracy variable, Pi will be calculated more and more accurately. Depending on how fast your web server is, you can calculate the first 6 digits of Pi fairly quickly.

The time it takes to calculate each succeeding number goes up exponentially however. To calculate 20 digits of Pi using this method method could take years.