NM First Practical
NM First Practical
NM First Practical
int main()
{
float x0,x1,x2,f0,f1,f2,e;
int step=1;
up:
printf("Enter two intial guesses:\n");
scanf("%f %f",&x0,&x1);
printf("Enter tolerable error.\n");
scanf("%f",&e);
f0= f(x0);
f1= f(x1);
if(f0*f1>0.0){
printf("Incorrect initial guesses.\n");
goto up;
}
printf("\nStep\t\tx0\t\tx1\t\tx2\t\tf(x2)\n");
do
{
x2 = (x0 + x1)/2;
f2 = f(x2);
}
Output:
Practical :2
Objective:
To implement and understand the Secant Method for solving nonlinear
equations using the Numerical Methods approach.
Theory:
The Secant Method is an iterative numerical method used to
approximate the root of a nonlinear equation. It is an improvement
over the Bisection Method and the Newton-Raphson Method. The
Secant Method requires two initial guesses, and it uses a linear
interpolation between these two points to approximate the root.
Given an equation f(x) = 0, the Secant Method can be applied using the
following iterative formula:
where x_n and x_(n-1) are the current and previous approximations of
the root, respectively, and x_(n+1) is the next approximation.
Algorithm:
1 Input initial guesses x0 and x1, the tolerance error e, and the
maximum number of steps n.
2 Compute f0 = f(x0) and f1 = f(x1), where f(x) is the function for which
we want to find the root.
3 Set step = 2.
4 Repeat steps 5-9 while step ≤ n.
5 Calculate x2 using the secant formula:
x2 = x1 - ((f1 * (x1 - x0)) / (f1 - f0))
6 Compute f2 = f(x2).
7 Check if |f2| ≤ e. If true, x2 is the root. Terminate the loop.
8 Update x0 = x1, x1 = x2, f0 = f1, and f1 = f2.
9 Increment step by 1.
10 If the loop ends without finding a suitable root, print "Method failed
after n steps."
11 Print the root x2 as the solution.
Source code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
float x0, x1, x2, f0, f1, f2, e;
int step = 1, N;
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);
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);