简体   繁体   中英

How would I find the imaginary roots given a quadratic?

This code finds the two roots of a quadratic equation in the form ax^2+bx+c

Is my solution good time/space-complexity wise, and how I would go about allowing users to see the imaginary roots if the quadratic has any?

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 . ")";    
}
  1. the if($b**2-4*$a*$c < 0) is too late

    You already used the sqrt so domain error might be thrown move the if to start

  2. for imaginary part you just use negation or abs value

    simply sqrt(-($b**2-4*$a*$c)) or sqrt(abs($b**2-4*$a*$c)) not sure if php uses abs or fabs for floats or if you even use floats... (havent code in php for ages)

I would combine this to something like this (just pseudo code as the var $ makes me dizzy:) ):

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
  }

Where a0+i*b0 and a1+i*b1 are the 2 solutions where i=sqrt(-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM