Data_Structure/作業/unit1/binary-search-solves-equation/main.c

80 lines
1.6 KiB
C
Raw Normal View History

2025-01-20 21:25:33 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
2025-01-20 21:30:53 +08:00
//#define f(x) (x+sin(x)-1)
2025-01-20 21:25:33 +08:00
//#define f(x) ((x)*(x))
2025-01-20 21:30:53 +08:00
#define f(x) ((x)*exp(x)*(x)*exp(x))
2025-01-20 21:25:33 +08:00
int main() {
int count = 1000 , i=0;
double precision = 1e-10 ;
//num<75><6D><EFBFBD><EFBFBD><EFBFBD>ܸѭ<DCB8><D1AD>Ӥ<EFBFBD><D3A4>{<7B><>
2025-01-20 21:30:53 +08:00
double mid , lower=-20 , upper=100, num=2;
2025-01-20 21:25:33 +08:00
if(f(num)==(num+sin(num)-1)){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
printf("#%d\t[%.10f,%.10f]\t<EFBFBD><EFBFBD>=%.10f\n",i+1,lower,upper,mid);
if (fabs(f(mid)) < precision) {
break;
}
i++;
if ( f(mid) * f(lower) < 0) {
upper = mid;
} else {
lower = mid;
}
}
}
if(f(num)==(num*num)){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
2025-01-20 21:30:53 +08:00
printf("\n#%d\t[%.10f,%.10f]\t<EFBFBD><EFBFBD>=%.10f\n",i+1,lower,upper,mid);
printf("\nf(mid)=%f, f(lower)=%f, f(upper)=%f\n",f(mid),f(lower),f(upper));
2025-01-20 21:25:33 +08:00
if (fabs(f(mid)) < precision) {
break;
}
i++;
if ( f(mid) > precision) {
if(mid>0){
upper = mid;
} else if(mid<0){
lower = mid;
}
}
}
}
if(f(num)==((num)*exp(num)*(num)*exp(num))){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
2025-01-20 21:30:53 +08:00
2025-01-20 21:25:33 +08:00
printf("#%d\t[%.10f,%.10f]\t<EFBFBD><EFBFBD>=%.10f\n",i+1,lower,upper,mid);
// printf("mid=%.10f,f(mid)=%.10f\n",mid,f(mid));
if (fabs(f(mid)) < precision) {
break;
}
i++;
if ( f(mid) > precision) {
if(mid>0){
upper = mid;
} else if(mid<0){
lower = mid;
}
}
}
}
2025-01-20 21:30:53 +08:00
printf("\n<EFBFBD><EFBFBD><EFBFBD>׬<EFBFBD>%f",mid);
2025-01-20 21:25:33 +08:00
return 0;
}