C Program for Bisection Method (with Output)

Table of Contents

This program implements Bisection Method for finding real root of nonlinear equation in C programming language.

In this C program, x0 & x1 are two initial guesses, e is tolerable error and f(x) is actual function whose root is being obtained using bisection method.

C Source Code: Bisection Method

 
/* Program: Finding real roots of nonlinear
   equation using Bisection Method
   Author: CodeSansar
   Date: November 18, 2018 */
/* Header Files */
#include<stdio.h>
#include<conio.h>
#include<math.h>
/*
 Defining equation to be solved.
 Change this equation to solve another problem.
*/
#define f(x) cos(x) - x * exp(x)

void main()
{
	 float x0, x1, x2, f0, f1, f2, e;
	 int step = 1;
	 clrscr();
	 /* Inputs */
	 up:
	 printf("\nEnter two initial guesses:\n");
	 scanf("%f%f", &x0, &x1);
	 printf("Enter tolerable error:\n");
	 scanf("%f", &e);
	 /* Calculating Functional Value */
	 f0 = f(x0);
	 f1 = f(x1);
	 /* Checking whether given guesses brackets the root or not. */
	 if( f0 * f1 > 0.0)
	 {
		  printf("Incorrect Initial Guesses.\n");
		  goto up;
	 }
   /* Implementing Bisection Method */
	 printf("\nStep\t\tx0\t\tx1\t\tx2\t\tf(x2)\n");
	 do
	 {
		  x2 = (x0 + x1)/2;
		  f2 = f(x2);
		
		  printf("%d\t\t%f\t%f\t%f\t%f\n",step, x0, x1, x2, f2);
		
		  if( f0 * f2 < 0)
		  {
			   x1 = x2;
			   f1 = f2;
		  }
		  else
		  {
			   x0 = x2;
			   f0 = f2;
		  }
		  step = step + 1;
	 }while(fabs(f2)>e);
	 printf("\nRoot is: %f", x2);
	 getch();
}

Bisection Method C Program Output

Enter two initial guesses:
0
1
Enter tolerable error:
0.0001

Step     x0              x1            x2            f(x2)
1       0.000000        1.000000        0.500000        0.053222
2       0.500000        1.000000        0.750000        -0.856061
3       0.500000        0.750000        0.625000        -0.356691
4       0.500000        0.625000        0.562500        -0.141294
5       0.500000        0.562500        0.531250        -0.041512
6       0.500000        0.531250        0.515625        0.006475
7       0.515625        0.531250        0.523438        -0.017362
8       0.515625        0.523438        0.519531        -0.005404
9       0.515625        0.519531        0.517578        0.000545
10      0.517578        0.519531        0.518555        -0.002427
11      0.517578        0.518555        0.518066        -0.000940
12      0.517578        0.518066        0.517822        -0.000197
13      0.517578        0.517822        0.517700        0.000174
14      0.517700        0.517822        0.517761        -0.000012

Root is: 0.517761