Pseudocode for Secant Method
1. Start
2. Define function as f(x)
3. Input:
a. Initial guess x0, x1
b. Tolerable Error e
c. Maximum Iteration N
4. Initialize iteration counter step = 1
5. Do
If f(x0) = f(x1)
Print "Mathematical Error"
Stop
End If
x2 = x1 - (x1 - x0) * f(x1) / ( f(x1) - f(x0) )
x0 = x1
x1 = x2
step = step + 1
If step > N
Print "Not Convergent"
Stop
End If
While abs f(x2) > e
6. Print root as x2
7. Stop
C Source Code: Secant Method
#include<stdio.h>
#include<math.h>
/* Defining equation to be solved.
Change this equation to solve another problem. */
#define f(x) x*x*x - 2*x - 5
void main()
{
float x0, x1, x2, f0, f1, f2, e;
int step = 1, N;
clrscr();
/* Inputs */
printf("\nEnter initial guesses:\n");
scanf("%f%f", &x0, &x1);
printf("Enter tolerable error:\n");
scanf("%f", &e);
printf("Enter maximum iteration:\n");
scanf("%d", &N);
/* Implementing Secant Method */
printf("\nStep\t\tx0\t\tx1\t\tx2\t\tf(x2)\n");
do
{
f0 = f(x0);
f1 = f(x1);
if(f0 == f1)
{
printf("Mathematical Error.");
exit(0);
}
x2 = (x0*f1- x1*f0)/(f1-f0);
f2 = f(x2);
printf("%d\t\t%f\t%f\t%f\t%f\n",step,x0,x1,x2, f2);
x0 = x1;
f0 = f1;
x1 = x2;
f1 = f2;
step = step + 1;
if(step > N)
{
printf("Not Convergent.");
exit(0);
}
}while(fabs(f2)>e);
printf("\nRoot is: %f", x2);
getch();
}
C Program Output: Secant Method
Enter initial guesses:
1
2
Enter tolerable error:
0.00001
Enter maximum iteration:
10
Step x0 x1 x2 f(x2)
1 1.000000 2.000000 2.200000 1.248001
2 2.000000 2.200000 2.088968 -0.062124
3 2.200000 2.088968 2.094233 -0.003554
4 2.088968 2.094233 2.094553 0.000012
5 2.094233 2.094553 2.094552 0.000001
Root is: 2.094552