D.1
Determining the Root of a Function


The following program is an example program to find the root of the function x^3 + x^2 - 3x - 3. The program uses the bisection method starting at the two x coordinates specified by the user. For this example to work correctly one number must be negative and the other one must be positive.

//Assuming that f(x1) and f(x2) are of opposite sign

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

//PROTOTYPES
double f(double);
int opposite_sign(double, double);

main()
{
  double x1=0, x2=0, x3=0;
  double Precision=.00001;

  cout <<"f(x) = x^3 + x^2 - 3x - 3"<<endl;
  cout <<"Please enter the starting point and end point of the function\n" << endl;
  cout <<"Example:    -10 20"<<endl<<"> ";
  cin>>x1;
  cin>>x2;

  while(.5*fabs(x1-x2)>=Precision)
  {
    x3=(x1+x2)/2;
    cout<< "f(" << x3 <<") = " << f(x3) << endl;
    if(opposite_sign(f(x3), f(x1)))
      x2=x3;
    else
      x1=x3;
  }//WHILE

  cout << "At " << x3 << " f(x) equals zero."<<endl;
  return 0;
 }//MAIN

double f(double X)
{
  double Y = 0.0;
  Y=(X*X*X)+(X*X)-(3*X)-3;
  return (Y);

}//F

int opposite_sign(double x3, double x1)
{
  if(x3<0 && x1>0)
    return 1;
  if(x3>0 && x1<0)
    return 1;
  else
    return 0;
}//OPPOSITE_SIGN