1 #include<bits/stdc++.h> 2 using namespace std; 3 4 5 /*(x+2)^2 +1 6 -2(x-1)^2+7 7 8 */ 9 double f(double x){ 10 return 4-x- pow(2,x); 11 } 12 double df(double x){ 13 return -1 - pow(2,x)*log(2); 14 } 15 16 //二分法 17 void binary_search(double l,double r,double e){ 18 19 double mid = (l+r)/2; 20 int manN = 1000; 21 int k = 1; 22 int flag = 0; 23 while(1){ 24 mid = (l+r)/2; 25 if(fabs(f(mid)) < e){ 26 flag = 1; 27 break; 28 } 29 if(k>=manN){ 30 flag = 0; 31 break; 32 } 33 if(f(l)*f(mid)<0){ 34 r = mid; 35 }else if(f(mid)*f(r)<0){ 36 l = mid; 37 } 38 k++; 39 } 40 if(flag){ 41 printf("二分次数是:%d,解为:%.8lf ",k,mid); 42 } 43 } 44 45 void NewTon(double x0,double e,int N){ 46 //牛顿法求根,起始点x0开始 47 //N是最大迭代次数 48 int flag = 0; //1是奇异 2是找到了 3是失败 49 double x1,result; 50 int k = 1; 51 while(1){ 52 if(df(x0) == 0){ 53 flag = 1; 54 break; 55 } 56 x1 = x0 - f(x0)/df(x0); 57 if(fabs(x1-x0) < e){ 58 result = x1; 59 flag = 2; 60 break; 61 } 62 if(k == N){ 63 flag = 3; 64 break; 65 } 66 k++; 67 //printf("%lf ",x0); 68 x0 = x1; 69 70 } 71 if(flag == 2){ 72 printf("找到了,并且迭代次数是:%d,根为:%.8lf ",k,result); 73 }else if(flag == 1){ 74 printf("函数不可导"); 75 }else if(flag == 3){ 76 printf("超出局部收敛范围,迭代失败! "); 77 }else{ 78 printf("return!"); 79 } 80 return; 81 } 82 int main(){ 83 84 // double x0; 85 // double e; 86 // int N = 100; 87 // //while(1){ 88 // printf("输入起始点、精度、最大迭代次数:"); 89 // cin>>x0>>e>>N; 90 // NewTon(x0,e,N); 91 // 92 // 93 // printf("------------- "); 94 // printf("请输入二分法左右区间、精度:"); 95 // double l,r,e1; 96 // cin>>l>>r>>e1; 97 // binary_search(l,r,e1); 98 double x = 1.38616943; 99 printf("%.10lf",f(x)); 100 101 }