二分法求方程解

一、此法要求函数连续,在给定区间内仅有一个根,通过循环十几次即可获得精度要求较高的根(0.00001),精度可自己设定

理论依据为函数连续性,在根附近有:f(start) * f(end) < 0

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define E 2.718
float f(float);

int main(){
float start, end, mid, precision;
int i, count;

//三个初值,每次都要赋值
start = 0; //区间左起点
end = 1; //右起点
precision =1e-5; //精度

//获取需要循环次数
count = ceil((log(end - start)-log(2*precision))/log(2));
for(i=0; i<count; i++){
mid =0.5*(start + end);
if(f(mid)*f(start)<0){
end = mid;
}
else if(f(mid)*f(start)>0){
start = mid;
}else{
//等于0,即为 mid 值,直接退出
printf("%.4f 循环次数%d\n", mid, count);
exit(0);
}
}

mid =0.5*(start + end);
printf("解为%.4f,循环次数%d\n", mid, count);

return 0;
}

//待判断的函数表达式,每次都要修改
float f(float x){
//return (x*x*x - 2*x*x -4*x -7);
//return (x*x - x - 1);
//return (x*x*x - x - 1);
//return (x*x*x - 2);
//return (x - pow(2, -x));
return (pow(E, x) - x*x + 3*x - 2);
}



Stay hungry Stay foolish
原文地址:https://www.cnblogs.com/xiangzi888/p/2241345.html