使用三次公式计算三次方程的根不起作用

Using cubic formula to calculate roots of cubic equation not working

我正在尝试编写一个程序来输出给定三次方程的根。因此,我决定使用三次公式 (http://www.math.vanderbilt.edu/~schectex/courses/cubic/) 制作一个版本。这个公式应该可以输出其中一个根的结果。

但是,它似乎不起作用,我不确定是代码还是想法有缺陷。这里系数 1、-6、11 和 -6 应该创建 1、2 或 3 的输出。而是输出 NaN。这同样适用于我尝试使用的其他系数。感谢您的帮助!

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;

    }
}

从您提到的 link 开始

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.

这部分

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

将最终成为负数的平方根,这是虚构的,但在 java

doubles world 最终为 NaN。