Question No. 1
‘A’
You next task is to develop a ‘C’ program to find a root using Secant Method. You’ll have to perform the five iterations to obtain the smallest positive root of the equation f(x) = cos x – xex = 0,, verify your answer with the program written by you.
Answer
/* Root Using Secant Method*/
#include <stdio.h>
#include <math.h>
#define f(x) (exp(x)*log(x)-x*x)
main()
/* Main program to use the Secant Method to find the root of
f(x)=exp(x)*ln(x)-x*x=0. Copyright © Tao Pang 1997. */
{
int istep;
double dl=1e-6;
double a,b,xi,xf,di,df;
void secant ();
a = 1; b = 2;
di = (b-a)/10;
xi = (a+b)/2;
secant (dl,xi,di,&xf,&df,&istep);
printf(“%4d %16.8lf %16.8lf\n”, istep,xf,df);
}
void secant (dl,xi,di,xf,df,istep)
/* Subroutine for the root of f(x)=0 with the secant method.
Copyright © Tao Pang 1997. */
int *istep;
double dl,xi,di;
double *xf,*df;
{
double x0,x1,x2,d;
x0 = xi;
x1 = xi+di;
*df = di;
*istep = 0;
while (fabs(*df) > dl)
{
d = f(x1)-f(x0);
x2 = x1-f(x1)*(x1-x0)/d;
x0 = x1;
x1 = x2;
*df = x1-x0;
*istep = *istep+1;
}
*xf = x0;
}