我必须编写一个程序,在其中写入 a、b c、d(方程 3 次的系数),结果我应该得到 X1、X2、X3(方程的解)。为此,我必须使用 Viete 的公式和 BigDecimal,因为我的讲师要求我使用它。
我得出的结论是我必须求解以下方程组:
x1+x2+x3=-b/a
x1*x2+x1*x3+x2*x3=c/a
x1*x2*x3=-d/a
我不知道如何用 Java 做到这一点。 我尝试使用 JAMA 包,但我认为我不能用它来求解这样的方程组。 我怎样才能做到这一点?
最佳答案
如果您想在 Java 中求三次多项式的根,您可以使用 Newton-Raphson 方法轻松完成。
算法 -
1. Input: initial x, func(x), derivFunc(x)
Output: Root of Func()
2. Compute values of func(x) and derivFunc(x) for given initial x
3. Compute h: h = func(x) / derivFunc(x)
4. While h is greater than allowed error ε
- h = func(x) / derivFunc(x)
- x = x – h
这是求解三次方程 x^3-x^2+2 的演示
class XYZ {
static final double EPSILON = 0.001;
// An example function whose solution
// is determined using Bisection Method.
// The function is x^3 - x^2 + 2
static double func(double x)
{
return x * x * x - x * x + 2;
}
// Derivative of the above function
// which is 3*x^x - 2*x
static double derivFunc(double x)
{
return 3 * x * x - 2 * x;
}
// Function to find the root
static void newtonRaphson(double x)
{
double h = func(x) / derivFunc(x);
while (Math.abs(h) >= EPSILON)
{
h = func(x) / derivFunc(x);
// x(i+1) = x(i) - f(x) / f'(x)
x = x - h;
}
System.out.print("The value of the"
+ " root is : "
+ Math.round(x * 100.0) / 100.0);
}
// Driver code
public static void main (String[] args)
{
// Initial values assumed
double x0 = -20;
newtonRaphson(x0);
}
}
输出 - root 的值为:-1.00
要按照自己的方式进行操作,您必须求解非线性方程组,这比较困难,但可以使用牛顿拉夫逊多元方法来完成。你可能想查一下。另请注意,这是一种近似方法,在您输入自己的初始“猜测”后会猜测根(在本例中为 -20)
关于java - 如何使用Java中的Vietea公式计算三次函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505856/