Question

This quadratic equation will not return negative numbers in the string that I've determined it to return. Here's the equation:

public class QuadraticEquation  {

    String final0;
    public String calculate(int a, int b, int c) {
        double done1 = ((-1 * b) + Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
        double done2 = ((-1 * b) - Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
        final0 = "x = " + (done1) + " or x = " + (done2);

        return final0;
    }
}

imagine an equation with a, b, and c values like -3, 13, and -4. The returning value of this would be -0.3(repeating) and -4. But this equation only returns positives, so in this case it would return 0.3(repeating) and 4. Why is this, and what can I do to fix it?

Note: I do believe that this is a Java error and not a math error. If it is a math error, let me know in the comments and I will promptly put it in the proper forums. Thanks.

Was it helpful?

Solution

public static void main(String[] args) {

    String final0 = calculate(-3, 13, -4);
    System.out.println(final0);

}
public static String calculate(int a, int b, int c) {
    String final0 ;
    int i = -1 * b; // -1 * 13 = -13
    System.out.println(i);

    int j = 4 * a * c; // 4 * -3 * -4  = 4 * 12  = 48
    System.out.println(j);

    double sqrt = Math.sqrt((b * b) - j); // sqrt ((13 * 13) - 48) = sqrt(169 - 48) = sqrt(121) = 11
    System.out.println(sqrt);

    double d = i + sqrt; // -13 + 11 = -2
    System.out.println(d);

    int k = 2 * a; // 2* -3 = -6
    System.out.println(k);

    double done1 = d / k; // -2 / -6 = 1/3 = 0.3333333333
    System.out.println(done1);

    double done2 = (i - sqrt) / k;
    final0 = "x = " + (done1) + " or x = " + (done2);

    return final0;
}

If you decompose your method to more local variables, you will see that math in java works correctly.

OTHER TIPS

I would have thought

-3*x^2 + 13 *x + -4 = -3 * (x - 0.33333) * (x - 4) = 0

so two positive answers is correct.

Try instead

1 * x^2 + 0 * x -1 = (x - 1) * (x + 1) = 0

i.e. x = -1 or +1


Here is how I would write it.

public static String calculate(int a, int b, int c) {
    double sqrt = Math.sqrt((b * b) - (4 * a * c));
    double done1 = (-b + sqrt) / (2 * a);
    double done2 = (-b - sqrt) / (2 * a);
    return "x = " + (done1) + " or x = " + (done2);
}

The code is working correctly with your input. If you changed b to be -13 for example, you would get

x = -4.0 or x = -0.3333333333333333

Math.sqrt will always return a positive number ignoring complex numbers. But that is somewhat besides the point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top