鱼C论坛

 找回密码
 立即注册
查看: 1255|回复: 1

求大神教写二分法

[复制链接]
发表于 2021-11-13 07:10:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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);
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-11-13 18:13:57 | 显示全部楼层
本帖最后由 jhq999 于 2021-11-13 18:14 编辑
#include <stdlib.h>
#include <math.h>

double my_function(double x)
{   return  x - exp(-x);  }
int main ()
{
            double i=0.5,j=.25,f=0,max=1,min=0;
                
                while (1)
                {
                        
                        if (my_function(i)>0)
                        {
                                if(i<max)max=i;
                                i=max-j;

                                
                        }
                        else
                        {
                                if(i>min)min=i;
                                i=min+j;
                        }
                        if(max-min<0.000000001)break;
                        j*=.5;
                        
                }
                printf("%.7lf,%.7lf",max,my_function(max));
        return 0;
}
0.5671433,0.0000000
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-27 06:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表