PHP实现简单高精度的求PI方法
程序员文章站
2022-05-13 15:19:44
...
讲完最笨的,再说一个更精巧的方法,代码如下:
~~~.php
<?php
// pi = 2 + 2/3 + 2/3*2/5 + 2/3*2/5*2/7 + ...
$pi = (double)2.0; $z = (double)2.0;
$a = 1; $b = 3;
while ($z > 0.0000000000001) {
$z *= $a / $b;
$pi += $z;
$b += 2;
$a++;
}
echo $pi."\n";
echo "PHP PI() =>".pi()."\n";
~~~
源码中和PHP自带的pi()这个函数做了对比,精度一致,那猜猜pi()函数是如何实现的呢?
~~~.php
<?php
// pi = 2 + 2/3 + 2/3*2/5 + 2/3*2/5*2/7 + ...
$pi = (double)2.0; $z = (double)2.0;
$a = 1; $b = 3;
while ($z > 0.0000000000001) {
$z *= $a / $b;
$pi += $z;
$b += 2;
$a++;
}
echo $pi."\n";
echo "PHP PI() =>".pi()."\n";
~~~
源码中和PHP自带的pi()这个函数做了对比,精度一致,那猜猜pi()函数是如何实现的呢?
下一篇: 百度地图API使用方法详解_PHP