计算方法非线性方程求根
本文最后更新于:2024年3月18日 凌晨
计算方法非线性方程求根
迭代法
算法


代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class 迭代法 { public static void main(String[] args) { int n = 11; double x0 = 1.5; double x1; double[] x = new double[n]; x[0] = x0; for (int i = 1; i < n; i++) { x1 = f(x0); x0 = x1; x[i] = x0; } for (int i = 0; i < x.length; i++) { System.out.println(i + ": " + x[i]); } }
static double f(double x) { double y = Math.pow(x + 1, 1.0 / 3); return y; }
|
牛顿迭代法
算法

代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class 牛顿迭代法 { public static void main(String[] args) { double x0 = 1; double x1; int i = 1; while (Math.abs(f(x0)) > 10e-6) { x1 = x0 - f(x0) / f2(x0); x0 = x1; System.out.print(i + ": x=" + x0); System.out.println(" y=" + (Math.abs(Math.pow(x0, 3) - 7.7 * Math.pow(x0, 2) + 19.2 * x0 - 15.3))); i++; } }
static double f(double x) { double y = Math.pow(x, 3) - 7.7 * Math.pow(x, 2) + 19.2 * x - 15.3; return y; }
static double f2(double x) { double y = 3 * Math.pow(x, 2) - 15.4 * x + 19.2; return y; } }
|
牛顿下山法
算法


正割法
算法

代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class 正割法 { public static void main(String[] args) { double x0 = 0; double x1 = x0 - f(x0) / f2(x0); double x2; int i = 1; while (Math.abs(f(x1)) > 10e-6) { x2 = x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)); x0 = x1; x1 = x2; System.out.print(i + ": x=" + x1); System.out.println(" y=" + (f(x1))); i++; } }
static double f(double x) { double y = Math.pow(x, 3) - 7.7 * Math.pow(x, 2) + 19.2 * x - 15.3; return y; }
static double f2(double x) { double y = 3 * Math.pow(x, 2) - 15.4 * x + 19.2; return y; }
|
二分法
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class 二分法 { public static void main(String[] args) { int n = 20; double low = -100; double high = 100; double mid = -1; int i; if (f(low) * f(high) < 0) { for (i = 0; i < n; i++) { mid = (low + high) / 2; if (f(mid) * f(low) < 0) { high = mid; } else { low = mid; } System.out.println(i + " " + " x = " + mid); } System.out.println(i + " x = " + mid); } else { System.out.println("函数在该定义域内无根或根在边界上!"); } }
static double f(double x) { double y = 2 * x + 1; return y; } }
|