PHP - Calculate pi
From Global Programming Syntax
Pi is a never ending number unless you use an inaccurate formula. Below is an example of a php script to calculate pi using Vieta's Pi Formula. To use this script, it will take at least 3 minutes to get a decent result of pi for the below script and if you are not worried about cpu usage then you can remove the 2 lines with the sleep functions for much faster performance. You will find when using this script, it will keep on re-displaying pi but each time pi is redisplayed, it will usually append a digit or two.
<?
set_time_limit(0);
echo str_repeat(' ', 64).'<br>';
$digits=600;
$pival='1';
$str1='';
while ($pirow<2000)
{
$pirow+=1;
$tempval='0';
for ($pisubrow=0;$pisubrow<$pirow;$pisubrow++)
{
$tempval=bcsqrt(bcadd('2',$tempval,$digits),$digits);
if (($pisubrow/2)==round($pisubrow/2)) { sleep(1); }
}
$tempval=bcdiv('2',$tempval,$digits);
$pival=bcmul($tempval,$pival,$digits);
unset($tempval);
$tempval=bcmul('2',$pival,$digits);
$common = array();
$length = (strlen($str1) >= strlen($tempval)) ? strlen($str1) : strlen($tempval);
for($x=0;$x<$length;$x++){
if($str1[$x] == $tempval[$x]){
$common[] = $str1[$x];
}else{
break;
}
}
if ($pirow>5)
{
echo 'pi='.substr(join('',$common),0,-2).'<p>';
}
unset($str1);
$str1=$tempval;
unset($tempval);
flush();
sleep(1);
}
$pival=bcmul($pival,'2',$digits);
unset($pirow);
?>
The first 490 digits are: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
82148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446
12847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925
40917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623
799627495673518857527248912279
