牛顿迭代法——c/java

牛顿迭代式: img

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){ // precision -> 精度 ; maxcyc -> 迭代次数
double x1,x0;
x0=*x;
for (int i = 1;i<=maxcyc;i++){
if(func(x0)==0){ // 迭代过程导数为0;
printf("迭代过程中导数为0\n");
return -1;
}
x1 = x0 - (fun(x0)/func(x0));
if (fabs(x1-x0)<precision || fabs(func(x0))<precision){
// 达到迭代结束的条件:x1-x0的绝对值小于精度或者导函数x0得值小于精度
*x = x1; // 输出求出的精度结果
printf("x附近的根为%lf\n",*x);
return 1;
}else{
x0 = x1; // 继续迭代
}

}
printf ("迭代次数超过预期\n"); // for循环结束即任为迭代到所需的精度且导函数x根不为0.
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
// 计算平方根——牛顿迭代法
// f(x)= x²-c
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;
}
// while (Math.abs(x-c/2)/2 > err) {
// x = (x+c/x)/2.0;
// }
// 无需另设y
return x;
}