Home > Software design >  What is wrong with the following C code for Bisection method, it doesn't show the actual root,
What is wrong with the following C code for Bisection method, it doesn't show the actual root,

Time:09-20

For some reason, I'm not sure what, it isn't showing the approx root, the avg which should be printed as a non-zero floating point is rather giving 0 as it's value at the end, I'm also not sure if fabs is necessary here or not. Please help me out, p.s- my first question here.

// C program for bisection method
#include<stdio.h>
#include<math.h>
#define F(x) (x*x*x-9*x 1)



int main(int argc, char const *argv[])
{
    double guess_1, guess_2,func, avg;
    
    printf("Enter values of 1st guess and 2nd guess : ");  //assumes the initial 2 values from user
    scanf("%lf%lf",&guess_1,&guess_2);

    for (int i = 1; fabs(F(avg)) < 0.001; i  )
    {
        avg=(guess_1 guess_2)/2;
        if (F(guess_1)*F(avg)<0)
        {
            guess_2=avg;
        }else
        {
            guess_1=avg;

        }
        
        
    }
    
printf("approximate root is : %lf",avg);

    return 0;
}

CodePudding user response:

You have 2 main issues:

  1. avg is not initialized as Weather Vane pointed out in comment.

  2. Your condition to terminate to loop is incorrect. You loop until you error gets too large. The opposite should be the case.

A fixed version is below:

// C program for bisection method
#include<stdio.h>
#include<math.h>

#define F(x) ((x)*(x)*(x)-9*(x) 1)

int main(void)
{
    double guess_1, guess_2, avg;
    
    printf("Enter values of 1st guess and 2nd guess : ");  //assumes the initial 2 values from user
    scanf("%lf%lf",&guess_1,&guess_2);
    // TODO: Check if result == 2

    avg=(guess_1 guess_2)/2;
    while (fabs(F(avg)) > 0.001)
    {
        avg=(guess_1 guess_2)/2;
        if (F(guess_1)*F(avg)<0)
        {
            guess_2=avg;
        }else
        {
            guess_1=avg;
        }
    }
    
    printf("approximate root is : %lf",avg);
    return 0;
}

Output:

a)
Enter values of 1st guess and 2nd guess : 2.3 3.5
approximate root is : 2.942810

b)
Enter values of 1st guess and 2nd guess : -1.0 1.0
approximate root is : 0.111328

Further improvements:

  • Removed unused variables
  • Changed for loop to while loop.
  • Wrapped x in brackets in macro definition.
  •  Tags:  
  • c
  • Related