php自定义函数求取平方根

时间:2021-03-30 07:02:41

<?php
function sqare($a, $left, $right){
  $mid = ($left + $right)/2;
  if($mid * $mid == $a || (abs($mid * $mid - $a) < 0.000000000001)){
    echo $mid;
  }elseif($mid * $mid > $a){
    $right = $mid;
    sqare($a, $left, $right);
  }else{
    $left = $mid;
    sqare($a, $left, $right);
  }
}
sqare(3, 0, 3);

输出结果:1.7320508075686

使用说明:

1.求3的平方分 sqare(3, 0, 3);

2.求取的结果为一个近似值 0.000000000001用于调节精度