此代码以ax^2+bx+c的形式查找二次方程的两个根
我的解决方案是否具有良好的时间/空间复杂性,以及如果二次曲线有虚根,我将如何让用户看到虚根?
public function factor($a=0, $b=0, $c=0) {
$positive_solution = (-$b + sqrt($b**2-4*$a*$c))/2*$a;
$negative_solution = (-$b - sqrt($b**2-4*$a*$c))/2*$a;
if($b**2-4*$a*$c < 0) {
return "Solutions are imaginary";
}
$factor_one = $positive_solution * -1;
$factor_two = $negative_solution * -1;
$factor_one > 0 ? $factor_one = "+ " . $factor_one : $factor_one = "- " . $factor_one;
$factor_two > 0 ? $factor_two = "+ " . $factor_two : $factor_two = "- " . $factor_two;
return "Your roots are located at (0, " . $positive_solution . ")(0, " . $negative_solution . "),
Thus, the problem can be factored into (x " . $factor_one . ")(x " . $factor_two . ")";
}发布于 2021-06-10 15:26:19
if($b**2-4*$a*$c < 0)太晚了您已经使用了sqrt,因此可能会抛出域错误。如果要启动,请移动
对于虚部,只需使用
简单地说,sqrt(-($b**2-4*$a*$c))或sqrt(abs($b**2-4*$a*$c))不确定php是使用abs还是fab来进行浮动,或者您甚至不确定是否使用浮动……(已经很久没有用php编写代码了)
我会把它组合成类似这样的东西(仅仅是伪代码,因为var $会让我感到头晕: ):
q = b*b-4*a*c
d = sqrt(abs(q))
if (q<0)
{
a0 = -b/(2*a);
b0 = +d/(2*a);
a1 = -b/(2*a);
b1 = -d/(2*a);
}
else
{
a0 = (-b + d)/(2*a);
b0 = 0
a1 = (-b - d)/(2*a);
b1 = 0
}其中,a0+i*b0和a1+i*b1是2个解决方案,其中i=sqrt(-1)
https://stackoverflow.com/questions/67914693
复制相似问题