⽜顿法的C 语⾔实现(数值分析经典算法)
旅游公司经营范围⽜顿法的C 语⾔实现
算法理论
设已知⽅程有近似根,(假定,将函数在点展开,有 故⽅程可近似地表⽰为 为⼀个线性⽅程,记其根为,则的计算公式为:
代码实现
f (x )=0x k f (x )=′k 0f (x )x k f (x )≈f (x )+k f (x )(x −′k x )k f (x )=0f (x )+k f (x )(x −′k x )=k 0x k +1x k +1x =k +1x −k ,k =f (x )′k f (x )
医院财务工作总结k 0,1,⋯#include <stdio .h >#include <math .h >#include <stdbool .h >#define EPS 0.00005 /* 绝对误差上限 */#define MAX_ITERATION 1000 /* 叠代次数上限,避免死循环 */#define ZERO 0.000000001 /* 当⼀个正数⼩于ZERO 就认为该数是0 */bool Newton_Root (double (*f )(double x ), double (*diff_f )(double x ), double a , double b , double *r ){ double x_k ; int k = 0; while (k <MAX_ITERATION ) { x_k = *r ; *r = x_k - f (x_k )/diff_f (x_k ); if ((*r <a )||(*r >b )) return false ; if ((fabs (f (*r ))<ZERO )&&(fabs (*r -x_k )<EPS )) return true ; k ++; }
return false ;}double f1( double x ){ return sin (x );}double diff_f1( double x ){ return cos (x );}double f2( double x ){ return x *x -1;}double diff_f2( double x ){ return x +x ;}double f3( double x ){ return x *x ;}
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英文qq签名
48
49
50
double diff_f3( double x ){ return x +x ;}int main () /* 此裁判程序仅检查3个函数求根的典型情况 */{ double root ; root = 3.0; if (Newton_Root (f1, diff_f1, 0.5, 6.0, &root )) printf ("%.4lf\n", root ); else printf ("Wrong Answer\n"); /* 应能正确求出根 */ root = 0.5; if (Newton_Root (f1, diff_f1, 0.5, 6.0, &root )) printf ("Wrong Answer\n"); else printf ("No Convergence\n"); /* 初值不好应导致算
法失败 */ root = 6.0; if (Newton_Root (f1, diff_f1, 0.5, 6.0, &root )) printf ("Wrong Answer\n"); else printf ("No Convergence\n"); /* 初值不好应导致算法失败 */ root = -2.0; if (Newton_Root (f2, diff_f2, -2.0, 0.0, &root )) printf ("%.4lf\n", root ); else printf ("Wrong Answer\n"); /* 应能正确求出根 */ root = 2.0; if (Newton_Root (f2, diff_f2, 0.0, 2.0, &root )) printf ("%.4lf\n", root ); else printf ("Wrong Answer\n"); /* 应能正确求出根 */ root = 0.0; if (Newton_Root (f2, diff_f2, -2.0, 0.5, &root )) printf ("Wrong Answer\n"); else printf ("No Convergence\n"); /* 初值点导数为0,算法应中断 */ root = 1.0; if (Newton_Root (f3, diff_f3, -1.0, 1.0, &root )) printf ("%.4lf\n", root ); else printf ("Wrong Answer\n"); /* 应能正确求出根 */ return 0;
}50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论