Если вы хотите найти корни кубического полинома в Java, вы можете легко это сделать, используя метод Ньютона-Рафсона.
Алгоритм -
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)