用PHP计算Pi

问题描述 投票:3回答:3

好吧,这只是我和我的同事正在玩的东西。我们知道PHP有它自己的PI功能,但这是出于理论和好奇心。

所以我们想知道PHP是否以及如何计算pipi = π= 4/1 - 4/3 + 4/5 - 4/7 + 4/9...的配方

这是我们做的:

$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>';
}

所以现在我们有一个循环来计算第一个4/1 - 4/3 + 4/5系列,但它在此之后停止并从以下3个序列开始。我们如何让它运行整个$theValue并计算整个系列?

请记住,这不是什么严重的事情,对我们来说只是一个有趣的实验。

php loops pi
3个回答
2
投票

只需使用一个循环。有一个$bottom变量,你在每次迭代时加2,除以它,并根据模数加/减它:

$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

你的代码有什么问题(除了没有用适当的数字除外)是第二个循环。您出于某种原因打印出存储的数字3乘以3.这直到$a增加3,低于$theValue,这要高得多。因此,例如,如果$theValue为10,则在开始出现绑定错误之前只需要2个循环。


4
投票

你是在思考这个问题。只需使用模数来决定是否要添加或减去并在适当的位置执行。

$theValue = 100;// the max
$pi = 0;
for ($i=1; $i<$theValue; $i++){
    if ($i % 2 == 1){
        $pi += 4.0 / ($i * 2 - 1);
    } else {
        $pi -= 4.0 / ($i * 2 - 1);
    }
}

0
投票

pi()返回pi的近似值。返回的float有一个基于php.ini中的precision指令的精度,默认为14.另外,你可以使用M_PI常量,它产生与pi()相同的结果

source

使用PHP我们也可以计算Pi,虽然非常慢。

$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;

这种计算Pi的方法很慢,但是很容易读取代码。您可以在此处阅读有关此方法的更多信息:http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80

如果增加$ accuracy变量,Pi将被越来越准确地计算。根据您的Web服务器的速度,您可以相当快地计算Pi的前6位数。

然而,计算每个后续数字所花费的时间呈指数增长。要使用此方法计算Pi的20位数,可能需要数年时间。

© www.soinside.com 2019 - 2024. All rights reserved.