Quadratic formula code

Can someone explain to me what the top of this code does? It says if a==0 and if b==0 answer is -1, else answer is -c/b? What is the significance of this? If both a and b are 0, shouldnt the answer be 0? Also why -c/b?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double bigQuadraticRoot(double a, double b, double c){
    double answer;
    if (a == 0.0)
        if (b == 0.0)
            answer = -1.0;
        else
            answer = -c/b;
    else {
        answer = -b;
        double rad = b*b-4*a*c;
        if (rad > 0)
            if (a > 0)
               answer += sqrt(rad);
            else
               answer -= sqrt(rad);
        answer /= 2*a;
    }
    return answer;
}
If both a and b are 0, shouldn't the answer be 0?
If both a and b are 0, it means you have something like y = 3, a horizontal line that never intersects the x-axis, so no, 0 wouldn't be appropriate here.

This function is probably using "-1.0" to represent an error, although I don't really agree with this, since a legitimate root could be x = -1.0.

If a is 0, but b is not 0, it means you have an equation like y = 3x + 1. This is a linear equation, and its root can be found in a much more simple way.
 y = b * x + c
 0 = b * x + c
-c = b * x
-c / b = x 
* note this is not C++, just showing some math
Last edited on
This is somewhat wrong:
1
2
3
4
            if (a > 0)
               answer += sqrt(rad);
            else
               answer -= sqrt(rad);


This prototype would be more appropriate:
1
2
//Returns number of solutions. >= 0: that number of solutions; < 0: entire domain (y = 0)
int quadratic_roots(double solutions[2], double coeffs[3]);
Last edited on
Topic archived. No new replies allowed.