You are on page 1of 2

// Program to find the roots of a curve by 'Newton Raphson'(normal) method.

#include<stdio.h>
#include<math.h>
// Needed for using the fabs() function.
#define F(x) x*x*x-18
// The function (x^3)-18 defined.
#define E1 0.000001
// Threshold values.
#define E2 0.000001
// Threshold values.
#define g(x) 3*x*x
// Derivative of F(x)
float r,f0,f1,f2;
// Global variables.
float newtonraphson(float);
// Function to perform the Newton-Raphson
Method.
void check();
// Function to take in the inputs and check whet
her they are correct or not.
int main()
// main function i.e. the main body of the functio
n.
{
float root;
// The final root of the equation.
printf(" The curve F(x)=(x^3)-18\n");
check();
// Calling the check() function for taki
ng the input and checking it.
root=newtonraphson(r);
// Calling the function newtonraphson() and
getting the final root from it.
printf(" Root =%f\n",root);
return 0;
}
void check()
{
while(1)
// Loop is used so that if the input is wrong the user has a cha
nce to input values again.
{
printf(" Enter the initial approximation of roots :- "); // Ta
king input the initial approximation
scanf("%f",&r);
f0=g(r);
// Value of r in the first derivat
ive of F(x).
if(f0<E1)
// Error message in case of wrong input.
{
printf(" Wrong data!!! Enter another data \n");
continue;
}
else
break;
}
}
float newtonraphson(float r)
// Function to carry out Newton Rap
hson method and return the root.
{
int itr=0;
// Iteration variable.
float r1;
// Storing the previous result o
f the iteration.
while(1)
// Loop to carry on the Newton Raphson m
ethod.
{
itr++;
// Post incrementing the iterating variable.
r1=r;
// Storing the previous result of r in r1 .
f1=F(r);
// Value of r in the function F(x).
f2=g(r);
// Value of r in the first derivative of F
(x).
r=r-(f1/f2);
// Working formula.
if(fabs((r-r1)/r)<E2)
// Checking whether the difference between the two result is less than the thres

hold value or not.


return r;
// Returning the root.
printf(" Iteration = %d and result is %f\n",itr,r);
// Showing results after each iteration.
}
}

You might also like