You are on page 1of 4

\\1.

Finding root
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x1,x2,xn,fx1,fx2,fxn,dx2,dxn,con=-99;
int i=0;
clrscr();
printf("enter the value of x1:");
scanf("%f",&x1);
printf("enter the value of x2:");
scanf("%f",&x2);
fx1=pow(x1,3)+3*x1*x1-3;
fx2=pow(x2,3)+3*x2*x2-3;
printf("fx1 : %.4f\nfx2 : %.4f\n",fx1,fx2);
if(x1>x2)
dx2=3*x2*x2+6*x2;
else
{
dx2=3*x1*x1+6*x1;
x2=x1;
fx2=fx1;
}
while(fabs(con-x2)>.0001)
{
i=i+1;
if(i>15)
goto last;
con=x2;
xn=x2-(fx2/dx2);
fxn=pow(xn,3)+3*xn*xn-3;
dxn=3*xn*xn+6*xn;
printf("x%d : %f\tfx%d : %f\n",i+1,xn,i+1,fxn);
x2=xn;
fx2=fxn;
dx2=dxn;
}
last:
printf("Root of equation : %f",xn);
getch();
}

2.

I'm a numerical methods and modeling engineer so I should understand the Newton-
Raphson Method to be:
j( i+1 ) = j( i ) - [ j( i )^2 - 2 ] / [ 2*j( i ) ] for the function f( j ) = (j
*j - 2).
So, you should step i forward until f( j ) is within your tolerance of 0. Then y
our answer should be your last j.
Here's some pseudocode:
i = 0
while( absoluteValue( f( j ) ) > toleranceValue)
{
j = j - [ f( j ) ] / [ df( j ) ];
i++;
}
printOut("Root of Function is at %g After %d Iterations" j, i );

3.
#include <iostream>
02 #include <cmath>
03 using namespace std;
04
05 double find_root(double num, int root)
06 {
07 double x = 0.0;
08 double xn = 0.0;
09 double val;
10 int repeat = 0;
11 int i;
12
13 for (i = 0; i <= num; i++)
14 {
15 val = i*i-num;
16 if (val > 0.0)
17 {
18 xn = (i+(i-1))/2.0;
19 break;
20 }
21 }
22
23 while (!(repeat++ >= 100 || x == xn))
24 {
25 x = xn;
26 xn = x - (pow(x, (double)root) - num) / (root * pow(x, (double)root-1
));
27 }
28
29 return xn;
30 }
31
32 int main()
33 {
34 double num;
35 int root;
36 string root_name;
37
38 cout << "Enter a number: ";
39 cin >> num;
40 cout << "Enter the number of the root you want to find for this number: "
;
41 cin >> root;
42
43 if (root <= 1)
44 {
45 cout << "The root must be greater than 1.\n";
46 system ("pause");
47 return 0;
48 }
49 if (root == 2) root_name = "nd";
50 if (root == 3) root_name = "rd";
51 if (root > 3) root_name = "th";
52
53 cout << "The " << root << root_name << " root of " << num << " is " << fi
nd_root(num, root) << ".\n";
54
55 system ("pause");
56 return 0;
57 }

You might also like