# 分享 PHP 中开立方根 Cubic Root 的几种算法

PHP 中有自带的平方根函数，但是没有立方根函数，所以我们只有自己用算法/函数实现了，其实这些算法在网上也有，我们无需了解其运行的原理，只要会用就可以了。

## 二分猜测法

``````function croot(\$num){
\$num=\$root=floatval(\$num);
\$gap=abs(\$num);
\$loop=50;

for(\$i=0;\$i<\$loop;\$i++){
\$gap/=2;
\$powered=\$root*\$root*\$root;
if(\$powered>\$num)
\$root-=\$gap;
elseif(\$powered<\$num)
\$root+=\$gap;
else
return \$root;
}
return \$root;
}``````

``````function croot(\$num){
\$num=\$root=floatval(\$num);
\$gap=abs(\$num);
while(true){
\$gap/=2;
\$powered=\$root*\$root*\$root;
if(abs(\$powered-\$num)<0.000000000001){
return \$root;
}else{
if(\$powered>\$num){
\$root-=\$gap;
}elseif(\$powered<\$num){
\$root+=\$gap;
}else{
return \$root;
}
}
}
}``````

## 牛顿-拉佛孙法

### 递归版本

\$guess 为任意初始值，\$x 为需求根的乘方值

``````function croot2(\$guess,\$x){
\$try=abs(\$guess*\$guess*\$guess-\$x);
if(\$try<0.0000000001){
return \$guess;
}else{
return croot2((\$x/\$guess/\$guess+2*\$guess)/3,\$x);
}
}``````

### 循环版本

``````function croot3(\$num){
\$guess=\$num/3;
while(abs(\$guess*\$guess*\$guess-\$num)>=0.0000000001){
\$guess=(\$num/\$guess/\$guess+2*\$guess)/3;
}
return \$guess;
}``````

## 哈雷法

``````function croot4(\$num){
\$guess=\$num/3;
while(true){
\$try=\$guess*\$guess*\$guess;
if(abs(\$try-\$num)>=0.0000000001)
\$guess=\$guess*((\$try+2*\$num)/(2*\$try+\$num));
else
return \$guess;
}
}``````

JSmiles

0 文章
0 评论
84935 人气