|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
求根的二分法
在微积分中,您已经学习了中值定理,其中指出:
令 f (x) 是区间 [a, b] 上的连续函数。如果 d 是 [f (a), f (b)] 中的一个值,那么 [a, b] 中存在一个值 c,使得 f (c) = d。
该定理的一个推论是:如果 f (x) 是区间 [a, b] 上的连续函数,使得 f (a) 和 f (b) 符号相反,则 [ a, b] 使得 f (c) = 0。这意味着您可以在区间 [a, b] 内找到 f (x) 的至少一个根。
中值定理不仅保证了方程 f (x) = 0 的解,而且​​还提供了一种在数值上逼近任意精度的解的方法,这被称为二分法。二分法由以下过程描述。
使用二分法的算法编写一个 c 程序,以找到 f (x) = x – e-x = 0 的根,其中 δ= 10-5 。
注意 f(0)= -1<0 和 f(1)>0,所以我们知道根必须在 x=0 & x=1 之间。
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
double my_function(double x)
{ return x - dexp(-x); }
double bisection(double a, double b, double err)
{
int iter=0; //the number of iterations
double fa = my_function(a);
double fb = my_function(b);
if (fa>0) { printf("sorry, f(a) must be <0\n"); return 1.0d9; } //return a very large number so that we know
if (fb<0) {printf("sorry, f(b) must be >0\n"); return 1.0d9; } //something is wrong
double c, fc, er= dabs(b-a);
while (er > err) { //err is the pre-set tolerance
}
printf("Bisection method found root at %f after %d iterations\n", c, iter);
return c;
}
void main()
{
double a=0.0, b=1.0, err=1.0e-5;
double c=bisection(a, b, err);
printf("Bisection method found root at %f with tolerance %f\n", c, err);
}
|
|