/* Bisection Algorithm */
#include "stdio.h"
#include "math.h"
float Root(float left, float right, float tol, int *count);
int num;
float f(float x);
/* The root of the function f is found to within tol.
The actual bisection algorithm is contained in a function
called Root */
main()
{
float left, right, tol, root;
printf("Enter the left end point \n");
scanf("%f", &left);
printf("Enter the right end point \n");
scanf("%f", &right);
printf("Enter the tolerance \n");
scanf("%f", &tol);
if(f(left)*f(right) >=0)
{printf("function values at end points have the same sign \n");
printf("Run the program again with another choice of end points \n");
return;}
num=0;
root=Root(left, right, tol, &num);
printf("The root is %f to within %f \n", root, tol);
printf("The number of iterations is %d \n", num);
}
float Root(float left, float right, float tol, int *count)
{
float p;
/* the root is bracketed by the values of left and right.
The value of p is the midpoint of this interval.
The variable count measures the number of times the algorithm
executes */
while(fabs(left-right) > tol) /* program stops when the interval < tol */
{
p=(left+right)/2.;
if(f(p) ==0) return p;
if(f(p)*f(right) < 0) left=p; else right=p;
(*count)++;
}
return p;
}
float f(float x)
{
return (50/x)*(pow(1+.01*x,360)-1)-600;
}
/*units are in thousands of dollars
and x is the monthly interest rate measured in percent */
Newton's Algorithm
/* Bisection Algorithm */
#include
#include
int num;
float f(float x);
float df(float x);
/* The root of the function f is found to within tol
via Newton's method. The function is contained in f
and the derivative is contained in df
*/
main()
{
/* xnew contains the latest iterations of Newton
and xold contains the next to the latest iteration of Newton */
float xold, xnew, temp, tol;
int num;
printf("Enter an initial starting point \n");
scanf("%f", &xold);
printf("Enter the tolerance \n");
scanf("%f", &tol);
xnew=xold;
num=0; /* num is a counter index to check how many times the algorithm executes */
do
{
xold=xnew; /* this step updates the algorithm for the next iteration */
if(df(xold) == 0) /* check to make sure there is no divide by zero */
{printf("choose a new starting value and re-run the program \n");
return;}
xnew=xold-(f(xold))/(df(xold));
num++;
if(num > 20) {printf("too many iterations \n"); return;}
}
while(fabs(xold-xnew) > tol); /* program stops when the interval < tol */
printf("The root is %f to within %f \n", xnew, tol);
printf("The number of iterations is %d \n", num);
}
float f(float x)
{
return (50/x)*(pow(1+.01*x,360)-1)-600;
}
float df(float x)
{
return -(50/(x*x))*(pow(1+.01*x,360)-1)+(180/x)*(pow(1+.01*x,359));
}
/* The monthly interest rate is 0.576354 % */ /* The root of the polynomial x^3+x-1=0 is 0.6823278 */
Last updated 9/21/95