在Java中,使用牛頓迭代法求解方程需要遵循以下步驟:
NewtonRaphson
。solveEquation
,該方法接受一個表示方程系數(shù)的一維數(shù)組coefficients
,以及一個表示方程根的二維數(shù)組roots
。coefficients
數(shù)組的第一個元素是最高次項系數(shù),最后一個元素是常數(shù)項系數(shù)。roots
數(shù)組的每個元素都是一個包含兩個整數(shù)的數(shù)組,表示方程的一個根。solveEquation
方法中,首先檢查roots
數(shù)組的大小是否等于coefficients
數(shù)組的元素個數(shù)減1。如果不等于,拋出一個異常,表示無法求解該方程。f
和導數(shù)值f'
。
b. 使用公式x1 = x0 - f(x0) / f'(x0)
更新x0
為x1
。
c. 檢查Math.abs(x1 - x0)
是否小于閾值。如果是,則將x1
添加到roots
數(shù)組中,并跳出循環(huán)。roots
數(shù)組。以下是一個使用牛頓迭代法求解二次方程的示例:
public class NewtonRaphson {
public static void main(String[] args) {
int[] coefficients = {1, -3, 2}; // 二次方程 ax^2 + bx + c = 0 的系數(shù)
int[][] roots = new int[2][2]; // 存儲兩個根
try {
int[] result = solveEquation(coefficients, roots);
System.out.println("Roots: ");
for (int i = 0; i < result.length; i++) {
System.out.println("x" + (i + 1) + " = " + result[i][0] + ", x" + (i + 1) + " = " + result[i][1]);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static int[] solveEquation(int[] coefficients, int[][] roots) throws Exception {
if (roots.length != coefficients.length - 1) {
throw new Exception("Invalid coefficients array size");
}
double[] x = new double[roots.length];
for (int i = 0; i < roots.length; i++) {
x[i] = (double) roots[i][0];
}
double[] f = new double[roots.length];
double[] f_prime = new double[roots.length];
for (int i = 0; i < roots.length; i++) {
f[i] = evaluateFunction(coefficients, x[i]);
f_prime[i] = evaluateDerivative(coefficients, x[i]);
}
double tolerance = 1e-6;
double maxIterations = 100;
int iteration = 0;
while (iteration < maxIterations) {
double[] x_new = new double[roots.length];
for (int i = 0; i < roots.length; i++) {
x_new[i] = x[i] - f[i] / f_prime[i];
}
double delta = 0;
for (int i = 0; i < roots.length; i++) {
delta += Math.abs(x_new[i] - x[i]);
}
if (delta < tolerance) {
for (int i = 0; i < roots.length; i++) {
roots[i][0] = (int) x_new[i];
roots[i][1] = (int) x_new[i];
}
return roots;
}
x = x_new;
iteration++;
}
throw new Exception("Failed to converge within the maximum number of iterations");
}
private static double evaluateFunction(int[] coefficients, double x) {
double result = 0;
for (int i = coefficients.length - 1; i >= 0; i--) {
result = result * x + coefficients[i];
}
return result;
}
private static double evaluateDerivative(int[] coefficients, double x) {
double result = 0;
for (int i = 1; i < coefficients.length; i++) {
result = result * x + coefficients[i];
}
return result;
}
}
這個示例中,我們求解了方程x^2 - 3x + 2 = 0
,得到了兩個根x = 1
和x = 2
。