NEWTON RAPHSON METHOD
July 22, 2022
Finding The Roots Of The Given Equation By Using Newton Raphson Method
Source code :-
// Solve by Newton Raphson method [ X^3-3X^2+2X-5=0 ]
#include <stdio.h>
#include <math.h>
float f(float x)
{
return (pow(x, 3) - 3 * x * x + 2 * x - 5); // Replace With given Equation
}
float fd(float x)
{
return (3 * pow(x, 2) - 6 * x + 2); // Replace With given Equation
}
float fdd(float x)
{
return (6 * x - 6); // Replace With given Equation
}
int main()
{
float h, x, y, err;
int n = 0, d;
do
{
printf("Enter an approximate root: ");
scanf("%f", &x);
if (fabs(f(x) * fdd(x)) < (fd(x) * fd(x)))
break;
else
printf("\nWrong value entered!!!try again...\n");
} while (1);
printf("\nEnter the correction upto decimal place: ");
scanf("%d", &d);
err = (5.0 / pow(10, d));
printf("\nIter\t Xn\t\t f(Xn)\t\t f'(Xn)\t Hn\t\tXn+1=Xn+Hn\n");
printf("----------------------------------------------------------------------------------\n");
y = x;
h = f(x) / fd(x);
x = x - h;
printf(" %2d\t%+f\t%+f\t%+f\t%+f\t%+f\n", ++n, y, f(y), fd(y), h, x);
while (fabs(x - y) >= err)
{
y = x;
h = f(x) / fd(x);
x = x - h;
printf(" %2d\t%+f\t%+f\t%+f\t%+f\t%+f\n", ++n, y, f(y), fd(y), h, x);
}
printf("\n\nThe root is: %f", x);
return 1;
}
Input-Output :-
abhi@hp-15q-laptop:~$ gcc raphson.cabhi@hp-15q-laptop:~$ ./a.out
Enter an approximate root: 4
Enter the correction upto decimal place: 5
Iter Xn f(Xn) f'(Xn) Hn Xn+1=Xn+Hn---------------------------------------------------------------------------------- 1 +4.000000 +19.000000 +26.000000 +0.730769 +3.269231 2 +3.269231 +4.415967 +14.448226 +0.305641 +2.963590 3 +2.963590 +0.607399 +10.567060 +0.057480 +2.906110 4 +2.906110 +0.019273 +9.899764 +0.001947 +2.904163 5 +2.904163 +0.000022 +9.877510 +0.000002 +2.904161
The root is: 2.904161