Reputation: 2072
I'm reading a Introductory programming book by Robert Sedgewick and Kevin Wayne.
In one of the examples they implement a quadratic class as follows:
public class Quadratic
{
public static void main(String[] args)
{
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
double discriminant = b * b - 4.0 * c;
double d = Math.sqrt(discriminant);
System.out.println((-b + d) / 2.0);
System.out.println((-b - d) / 2.0);
}
}
The author omits the 'a' coefficient of the quadratic formula. Is this because the 'a' coefficient can be cancelled out (numerator / denominator)?
Based on the feedback… Would the following be the correct solution:
public static void main(String[] args)
{
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
double a = Double.parseDouble(args[2]);
double discriminant = b * b - 4.0 * a * c;
double d = Math.sqrt(discriminant);
System.out.println((-b + d) / (2.0 * a));
System.out.println((-b - d) / (2.0 * a));
}
Upvotes: 0
Views: 394
Reputation: 19168
No, the author might have implemented that algorithm differently. Assuming the general case, a
can't get cancelled as -b
factor doesn't consist of a.
Formula for finding the roots of a quadratic equation is :-
roots = (-b +(-) sqrt((b^2) - (4*a*c))) / (2*a).
// here - alongwith + represents how to find second root.
I'd suggest you to go through the commonly used way. If the author has used different conventions, then please don't follow that.
Please follow the standard/common way. It is easy to understand.
Based on the feedback… Would the following be the correct solution:..
The solution which you have added to the question as an edit appears correct. So, I'd suggest you to go that way.
Upvotes: 4
Reputation: 129577
I think the authors are assuming a certain normalization wherein the leading coefficient of the quadratic equation is 1.
So, for instance:
2x2 + 4x + 8 = 0
would be represented as
x2 + 2x + 4 = 0
These are both the same equation, it's just that one has been normalized, so to speak.
Upvotes: 3