-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumericalMethods_MultipleRootsWithNewton'sMethod.cpp
119 lines (90 loc) · 1.84 KB
/
NumericalMethods_MultipleRootsWithNewton'sMethod.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/// MULTIPLE ROOTS WITH NEWTON'S METHOD
#include<bits/stdc++.h>
using namespace std;
#define EPS 0.001
typedef double dd;
dd root[100];
void printArray(dd arr[], int len)
{
for(int i=0; i<len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void getInput(dd arr[], int deg)
{
puts("Enter the value of:");
for(int i=0; i<=deg; i++)
{
cout << "a" << deg-i << ": ";
cin >> arr[i];
}
}
void deflate(dd eqn[], dd root, int newDegree)
{
dd tmp = 0;
for(int i=0; i<=newDegree; i++)
{
eqn[i] = eqn[i] + root*tmp;
tmp = eqn[i];
}
}
dd useHorner(dd arr[], dd x, dd deg)
{
dd res = arr[0];
for(int i=1; i<=deg; i++)
{
res = res*x + arr[i];
}
return res;
}
dd NewtonRhapson(dd mainEq[], dd diffEq[], dd x0, int deg)
{
int cnt = 0;
dd f1, f2, x1, err;
do
{
f1 = useHorner(mainEq, x0, deg);
f2 = useHorner(diffEq, x0, deg-1);
x1 = x0 - f1/f2;
err = fabs((x1-x0)/x1);
x0 = x1;
}
while(err >= EPS);
return x1;
}
void differenciate(dd mainEq[], dd diffEq[], int degree)
{
int i, n;
for(i=0, n=degree; n>=0; i++, n--)
{
diffEq[i] = mainEq[i] * n;
}
}
void getRootUsingNewtonsMethod(dd mainEqn[], dd diffEqn[], int degree, dd x0)
{
dd xr;
int i = 0;
while(degree>1)
{
differenciate(mainEqn, diffEqn, degree);
xr = NewtonRhapson(mainEqn, diffEqn, x0, degree);
root[i++] = xr;
deflate(mainEqn, xr, --degree);
}
root[i] = -(mainEqn[1]/mainEqn[0]);
}
int main()
{
dd mainEq[101];
dd diffEq[100];
int deg;
cout << "Enter highest degree: ";
cin >> deg;
getInput(mainEq, deg);
getRootUsingNewtonsMethod(mainEq, diffEq, deg, 0);
puts("\nRoots:");
printArray(root, deg);
return 0;
}