newton rapson

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

ASSIGNMENT NO.

: 02
STATEMENT : FINDING THE ROOT OF A POLYNOMIAL EQUATION USING NEWTON-
RAPHSON METHOD.
ALGORITHM :
Input: Taking an equation 3*x - cos(x) – 1 as the input and differentiating it we get, 3 + sin(x),
taking it as a input as well.And minimum tolerable error and the number of itterations from the user.

Output: Approximate value of the root derived the from the equation.
Declaring a macro f(x) for the equation 3*x - cos(x) – 1 and another macro g(x) for the
differentiated equation 3 + sin(x).
Steps:
1. START.
2. Declaring all the float(x0,x1,f0,f1,g0,e) and integer(N, step = 1[initialized]) variables in the main()
function.
3. Ask the user to put the values of the initial guess , minimum tolerable error and number of
itterations and storing them in x0,e and N respectively.
4. Print step, x0, f(x0), x1 and f(x1) in a table format.
5. Repeat the steps while fabs(f1) > e.
5.1. Set g0 = g(x0) and f0 = f(x0).
5.2. Check if g0 = 0.0
a. Print a suitable message for mathematical error.
b. Exit function.
[End of If]
5.3. Set x1 = x0 – f0/g0.
5.4. Print the values of step, x0, f0, x1 and f1 respectively.
5.5. Set x0 = x1.
5.6. Check if step > N
a. Print a suitable message for non convergence.
b. Exit function.
[End of If]
5.7. Set f1 = f(x1).
[End of loop]
6. Print the root/the value of x1.
7. END.
__________________________________________________________________________________

SOURCE CODE :
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define f(x) 3*x - cos(x) -1
#define g(x) 3 + sin(x)
void main()
{
float x0, x1, f0, f1, g0, e;
int step = 1, N;
printf("\nEnter initial guess: ");
scanf("%f", &x0);
printf("\nEnter tolerable error: ");
scanf("%f", &e);
printf("\nEnter maximum iteration: ");
scanf("%d", &N);
printf("\nStep\t\tx0\t\tf(x0)\t\tx1\t\tf(x1)\n");
do
{
g0 = g(x0);
f0 = f(x0);
if(g0 == 0.0)
{
printf("\nMathematical Error.\n");
exit(0);
}
x1 = x0 - f0/g0;
printf("%d\t\t%f\t%f\t%f\t%f\n",step,x0,f0,x1,f1);
x0 = x1;
step = step+1;
if(step > N)
{
printf("\nNot Convergent.\n");
exit(0);
}
f1 = f(x1);
}while(fabs(f1)>e);
printf("\nRoot is: %f", x1);
exit(0);
}
__________________________________________________________________________________

OUTPUT :

Enter initial guess: 1


Enter tolerable error: 0.0001

Enter maximum iteration: 10

Step x0 f(x0) x1 f(x1)


1 1.000000 1.459698 0.620016 0.000000
2 0.620016 0.046179 0.607121 0.046179

Root is: 0.607121


--------------------------------
Process exited after 50.36 seconds with return value 0
Press any key to continue . . .

Enter initial guess: 1

Enter tolerable error: 0.0001

Enter maximum iteration: 12

Step x0 f(x0) x1 f(x1)


1 1.000000 1.459698 0.620016 0.000000
2 0.620016 0.046179 0.607121 0.046179

Root is: 0.607121


--------------------------------

__________________________________________

SIGNATURE OF THE TEACHER

You might also like