Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
893 B
1
Indexable
Never
#include<stdio.h>
#include<math.h>

double f(double x){
    return 3*x*x-6*x+2;
}

double bisection(double a, double b, double error){
    if(f(a)*f(b)>=0){
        printf("error: one must be negative");
        return NAN;
    }
    
    double c = a;
    while( (b-a)/b >= error ){
        c=(a+b)/2;
        if(f(c)==0.0){
            break;
        }
        else if( f(c) * f(a) < 0){
            b=c;
        }
        else{
            a=c;
        }
    }
    
    return c;
}

int main(){
    double a, b, error;
    printf("Enter interval [a, b] where the root lies:\n");
    printf("a :");
    scanf("%lf", &a);
    printf("b :");
    scanf("%lf", &b);
    printf("error pression :");
    scanf("%lf", &error);
    
    double root = bisection(a,b,error);
    if(!isnan(root)){
        printf("root = %lf", root);
    }
    else{
        printf("error");
    }
    
    return 0;
}
Leave a Comment