牛顿迭代法——c/java
牛顿迭代式: 
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include <stdio.h> #include <stdlib.h> #include <math.h>
double fun (double x){ return x*x*x*x+3*x*x*x+2*x; }
double func (double x){ return 4*x*x*x+9*x*x+2; }
int newton (double *x,int precision,int maxcyc){ double x1,x0; x0=*x; for (int i = 1;i<=maxcyc;i++){ if(func(x0)==0){ printf("迭代过程中导数为0\n"); return -1; } x1 = x0 - (fun(x0)/func(x0)); if (fabs(x1-x0)<precision || fabs(func(x0))<precision){ *x = x1; printf("x附近的根为%lf\n",*x); return 1; }else{ x0 = x1; }
} printf ("迭代次数超过预期\n"); return -1;
}
int main (){ double maxcyc,x; int precision; printf("请输入初始x值:\n"); scanf("%lf",&x); printf("请输入需要精度:\n"); scanf("%d",&precision); printf("请输入迭代的次数:\n"); scanf("%lf",&maxcyc); newton(&x,precision,maxcyc); system("pause"); return 0; }
|
java中的平方根问题
java代码实现开平方的牛顿迭代法。
求c(c>0)的算数平方根就是求f(x)=x²-c的正根,得到迭代公式:Xn+1=(Xn+c/Xn)/2,代码中取初始值c,误差为1✖10(-15次方)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class newton { public static double sqrt (double c) { if (c<0) { return Double.NaN; } double err =1e-15; double x = c; double y = (x+c/x)/2; while (Math.abs(x-y)>err) { x = y ; y = (x+c/x)/2; }
return x; }
|