开发者

Imaginary numbers

I have a method that takes 3 doubles and calculates the roots via the Quadratic Formula:

public static double[] quadraticFormula(double a, double b, double c) throws ArithmeticException 开发者_开发问答{
    double root1 = 0;
    double root2 = 0;

    //sqrt(b^2 - 4ac)
    double discriminant = (b * b) - (4 * a * c);

    if (Double.isNaN(discriminant)) {
        throw new ArithmeticException(discriminant + " is not a number!");
    }

    if (discriminant > 0) {
        //Two roots
        root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
        root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
    } else if (discriminant == 0) {
        //One root
        root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
    } else if (discriminant < 0) {
        //Imaginary roots
    }

    return new double[] { root1, root2 };
}

I want to expand on this and add support for imaginary numbers. How would I accomplish this? My first thought was, in else if (discriminant < 0), I would get the absolute value of the discriminant and factor the radical. I am going to output the roots to the user, so don't bother with the i, I have a String parser that knows exactly where to put the i. Any ideas on a more efficient method?


If you really want to get going on Complex/Imaginary numbers I would suggest to implement a class that represents a complex number.

An example for that can be found here: http://www.math.ksu.edu/~bennett/jomacg/c.html

If you somehow build your calculations of a mixture of doubles, arrays and strings it will definetely get messy after a while.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜