Karen Sarmiento
Karen Sarmiento

Reputation: 85

Using cubic formula to calculate roots of cubic equation not working

I'm trying to make a program that outputs the roots of a given cubic equation. I therefore decided to make a version using the cubic formula (http://www.math.vanderbilt.edu/~schectex/courses/cubic/). This formula should be able to output the result of one of the roots.

However, it doesnt seem to work and I'm not sure if it the code or the idea that is flawed. Here the coefficients 1, -6, 11 and -6 should create an output of either 1, 2 or 3. Instead NaN is outputted. The same has applied to other coefficients I have tried to use. Thanks for all your help!

public class CubicFormula {
    public static void main(String[] args) {
        System.out.println(new CubicFormula().findRoots(1.0, -6.0, 11.0, -6.0));
    }

    public double findRoots(double a, double b, double c, double d) {
        double p = -(b)/(3*a);
        double q = Math.pow(p, 3) + (b*c - 3*a*d)/(6*Math.pow(a, 2));
        double r = c/(3*a);

        return Math.cbrt(q + Math.sqrt(Math.pow(q, 2.0) + Math.pow((r - Math.pow(p, 2.0)), 3)))
                + Math.cbrt(q - Math.sqrt(Math.pow(q, 2.0) + Math.pow((r - Math.pow(p, 2.0)), 3))) + p;

    }
}

Upvotes: 0

Views: 1712

Answers (1)

Artur Biesiadowski
Artur Biesiadowski

Reputation: 3698

From the very link you have mentioned

One reason is that we're trying to avoid teaching them about complex numbers. Complex numbers (i.e., treating points on the plane as numbers) are a more advanced topic, best left for a more advanced course. But then the only numbers we're allowed to use in calculus are real numbers (i.e., the points on the line). That imposes some restrictions on us --- for instance, we can't take the square root of a negative number. Now, Cardan's formula has the drawback that it may bring such square roots into play in intermediate steps of computation, even when those numbers do not appear in the problem or its answer.

This part

Math.sqrt(Math.pow(q, 2.0) + Math.pow((r - Math.pow(p, 2.0)), 3))

will end up being sqrt of negative number, which is imaginary, but in java

doubles world ends up being NaN.

Upvotes: 3

Related Questions