付宁远23373125 2

基于C语言实现求解算法

#include <stdio.h>  
#include <math.h>  
  
double f(double x) {  
    return exp(x) - 2;  
}  
  
int main() {  
    double a = 0.0;  
    double b = 1.0;  
    double c, fa, fb, fc;  
    int iter = 0;  
    double tolerance = 1e-15;  
    int min_iter = 10;  
    int max_iter = 100;  
	
    fa = f(a);  
    fb = f(b);  
	
    if (fa * fb >= 0) {  
        printf("Error: [0, 1]内无根.\n");  
        return 1;  
    }  
	
    while (iter < min_iter || (b - a) > tolerance) {  
        if (iter >= max_iter) {  
            printf("达到最大迭代次数,但未收敛。\n");  
            break;  
        }  
        iter++;  
        c = (a + b) / 2;  
        fc = f(c);  
		
        if (fa * fc < 0) {  
            b = c;  
            fb = fc;  
        } else {  
            a = c;  
            fa = fc;  
        }  
		
        printf("迭代次数 %d: 根 = %.15f, f(c) = %.15f\n", iter, c, fc);  
    }  
	
    c = (a + b) / 2;  
    printf("\n最终根: %.15f\n", c);  
    printf("迭代次数: %d\n", iter);  
    printf("f(c) = %.15f\n", f(c));  
    printf("ln(2)理论值: %.15f\n", log(2.0));  
    return 0;  
}

给出用双精度浮点数求解此方程所能达到的最高精度的根

0.693147180559945

Built with MDFriday ❤️