Devvrat Chaubal
Devvrat Chaubal

Reputation: 47

Wrong Output while finding the root of the equation in C

The following is the C code for calculating the roots of an equation using the Newton-Raphson Algorithm:

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

double function(double x);
double derivative(double x);

int main(){
    double guess=3;
    for(int i=0;i<100;i++){
        double val=function(guess);
        double d=derivative(guess);
        guess=guess-val/d;
        if(abs(function(guess))<0.00005){
            printf("%lf",guess);
            break;
        }
    }
    return 0;
}

double function(double x){
    return pow(x,5)+2;  //f(x)=x^5+2
}

double derivative(double x){
    double h=0.00001;
    return (function(x+h)-function(x))/h;
}

But the output after compilation is -1.208869, which actually does not satisfy the condition that abs(f(x))<0.00005. What am I doing wrong here?

Upvotes: 1

Views: 56

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51835

Your abs(function(guess)) call returns an integer value (cppreference), which will be truncated to zero if the value is less than 1 (as it is when your program stops).

What you need is the fabs() function, to return the absolute value of its given argument as a double.

Changing your if block to use this will work:

        if (fabs(function(guess)) < 0.00005) { // Use "fabs" ... not "abs"
            printf("%lf", guess);
            break;
        }

Upvotes: 2

Related Questions