虚数

发布于 2024-11-28 01:10:30 字数 966 浏览 2 评论 0原文

我有一个需要 3 个 double 并通过二次公式计算根的方法:

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 };
}

我想对此进行扩展并添加对虚数的支持。我将如何实现这个目标?我的第一个想法是,否则 if (discriminant < 0),我会得到判别式的绝对值并分解根式。我将把根输出给用户,所以不用担心 i,我有一个字符串解析器,它确切地知道将 i 放在哪里。关于更有效的方法有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

计㈡愣 2024-12-05 01:10:30

如果您确实想继续处理复数/虚数,我建议实现一个表示复数的类。

可以在这里找到一个例子:
http://www.math.ksu.edu/~bennett/jomacg/c .html

如果你以某种方式构建双精度数、数组和字符串的混合计算,一段时间后它肯定会变得混乱。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文