C program for solving equation using bisection method

Nitin picture Nitin · Aug 27, 2015 · Viewed 10.1k times · Source

this program is for solving equation using bisection method gives error "function show return a value".

In this method we are given a function f(x) and we approximate 2 roots a and b for the function such that f(a).f(b)<0.

Then we find another point

c=(a+b)/2

if f(c)==0

then root=c;

else

if f(a).f(c)<0

b=c;

if f(b).f(c)<0

a=c;

and we repeat these steps for the given number of iterations

#include<stdio.h>
#include<math.h>
#define e 0.000001/*e is the prescribed accuracy*/
main()
{
   double g1,g2,g,v,v1,v2,prev;
   int found=0,converged=0,i=0;
   double f(double);
   printf("We apply Bisection method to find a real root of the non-linear equation f(x) = 0, where f(x) = x^(2.7182818)-3cosx+1n");
   while(found==0)/*This loop will continue until a range is found in between which a real root lies*/
  {
    printf("nEnter the first guess : ");
    scanf("%lf",&g1);
    v1=f(g1);
    printf("nEnter the second guess : ");
    scanf("%lf",&g2);
    v2=f(g2);

 if(v1*v2>0)
   {
       found=0;
       g1++;
       printf("nRoot does not lie in [%lf,%lf].n",g1-1,g2);
       printf("nn..Enter two new guesses..nn");/*Previous two guesses are inappropriate*/
    }
else
      found=1;
  }
     printf("nThere is a real root which lies in [%lf,%lf].n",g1,g2);   
   while(converged==0)/*This loop will continue until a real root is found*/
   {
      printf("nnIteration = %dnn",i); 
      printf("a[%d](-ve)tb[%d](+ve)tbbx[%d]=(a[%d]+b[%d])/2tf(x[%d])n",i,i,i+1,i,i,i+1);
      printf("%lft",g1);
      printf("%lft",g2);
      g=(g1+g2)/2;
      v=f(g);
      printf("%lft",g);
      printf("t%lf",v);
  if(v<0)
      g1=g;
  else
      g2=g;
if(fabs(prev-v)<e)
    converged=1;
else
    prev=v;
    i=i+1;
   }
   printf("nnThe approximate value of the root is : %lfn",g);
}
/*This function returns values of f(x)*/
double f(double x)
{
   return pow(2.7182818,x)-3*cos(x)+1;
}

Answer

Rishikesh Raje picture Rishikesh Raje · Aug 27, 2015

When tested with initial values of 1, and 2 and an iteration of 20, the result comes out to 1.154172. which is a root of the system.

When tested with inital values of 1, 1, and iteration of 20, the result comes out to 1.0000, which is wrong.

You should check that the initial conditions for the roots are met, i.e. f(a) * f(b) < 0.

f(1) = -1, f(1)* f(1) = +1, therefore the initial conditions are not satisfied in the second case.