Java資料結構:牛頓迭代法求非線性方程的解
阿新 • • 發佈:2018-12-11
根據以上思想
public class 牛頓迭代法 { static double func(double x) { //待求解方程 return x * x * x * x - 3 * x * x * x + 1.5 * x * x - 4.0; } static double dfunc(double x) { //導數方程 return 4 * x * x * x - 9 * x * x + 3 * x; } static int NewtonMethod(double x[], int maxcyc, double precision) { double x0, x1; int i; x0 = x[0]; i = 0; while (i < maxcyc) { if (dfunc(x0) == 0.0) { //如果導數為0,直接輸出,因為導數為0,無法用牛頓迭代法 System.out.println("迭代過程中導數為0"); return 0; } x1 = x0 - func(x0) / dfunc(x0); //按照公式求解 if (Math.abs(x1 - x0) < precision || Math.abs(func(x1)) < precision) { //達到了要求的精度 x[0] = x1; //得到迭代值 return 1; } else { //否則繼續迴圈,尋找迭代值 x0 = x1; } i++; //加一迴圈 } System.out.println("迭代次數超過預設值!仍沒有達到精確度!"); return 0; } public static void main(String[] args) { double precision; int maxcyc, result; double[] x = { 2.0 }; //初始值 maxcyc = 1000; precision = 0.00001; result = NewtonMethod(x, maxcyc, precision); if (result == 1) { System.out.printf("方程x*x*x*x-3*x*x*x+1.5*x*x-4.0=0\n在2.0附近的根為%f\n", x[0]); } else { System.out.println("迭代失敗!\n"); } } }