gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:18:28 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来输出给定三次方程的根。因此,我决定使用三次公式( 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;

}
}

最佳答案

来自您提到的链接

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))

最终会得到负数的sqrt,这是虚构的,但在java中

double 世界最终变成 NaN。

关于java - 使用三次公式计算三次方程的根不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39540632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com