Finding Roots Using The Bisection Method


Devise a C program that seeks an approximate root of any function f(x), good to a tolerance of epsilon, on a prescribed interval [a,b] using the bisection method. Apply it to find an approximate root to the equation x^3 + 0.1x - 27 = 0, accurate to plus or minus 0.0001. You may use the pseudoprogram below as an outline.
Given: a function f, an interval [a,b], a tolerance epsilon

Variables: L, the left endpoint of the current interval
           M, the midpoint of the current interval
           R, the right endpoint of the current interval

L <- a
R <- b

if f(L) and f(R) have the same sign,
  then exit with error message

while R - L > epsilon:
   M <- (L+R)/2;           # compute midpoint
   if f(L) and f(M) have opposite signs, 
      then set current interval to [L,M]
      otherwise, set current interval to [M,R]

Below is an incomplete version of the program. Where you see "...", program text has been deleted. Note the way doubles are formatted for scanf. Note also the way the exit function is used. Note also the use of a very simple function, f(x) = x^3 - 27, for testing purposes.

#include <stdio.h> /* use for the "exit" function */
#include <stdlib.h>

double f( double x){
   return x*x*x  - 27.0; 


double a, b, L, M, R, epsilon;

printf(" Enter a: "); scanf( "%le", &a );
printf(" Enter b: "); scanf( "%le", &b );
printf(" Enter epsilon: "); scanf( "%lf", &epsilon );
printf(" [%lf,%lf], epsilon = %lf\n", a, b, epsilon );

L = a;
R = b;

if ( f(a)*f(b) > 0 ) {
  printf("  No sign change ... exit!\n");

while( ... ) {
printf("  [%lf,%lf]\n", L,R );


Back to syllabus
Back to Department of Mathematics, University of Utah
Last modified: Feb 21, 1995
Copyright © 1995 Department of Mathematics, University of Utah