Repository navigation
Expand file tree
/
Copy pathIterativeMethod.cpp
More file actions
89 lines (76 loc) · 2.47 KB
/
Copy pathIterativeMethod.cpp
File metadata and controls
89 lines (76 loc) · 2.47 KB
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
#include "IterativeMethod.h"
NormalIterativeMethod::NormalIterativeMethod(double sta, double prec, double(*function)(double)) :start(sta), precision(prec), f(function)
{
calculateTheRoot();
}
void NormalIterativeMethod::calculateTheRoot()
{
double xCurrent(start), xNext;
size_t iterT(1);
while (1)
{
xNext = f(xCurrent);
if (abs(xNext - xCurrent) <= precision)break;
xCurrent = xNext;
++iterT;
if (iterT > 100000)break;
}
iterateTime = iterT;
root = xNext;
}
ostream &operator<< (ostream&os, const NormalIterativeMethod&item)
{
os << "The root is " << item.root << " , the iteration times are " << item.iterateTime << " ." << endl;
return os;
}
NewtonIterativeMethod::NewtonIterativeMethod(double sta, double prec, double(*function)(double), double(*functionDerivative)(double))
:start(sta), precision(prec), f(function), f_d(functionDerivative)
{
calculateTheRoot();
}
void NewtonIterativeMethod::calculateTheRoot(){
double xCurrent(start), xNext(start);
double f_d_value;
size_t iterT(1);
while (1){
f_d_value = f_d(xCurrent);
if (!f_d_value){ condition = -1; break; }
xNext = xCurrent - f(xCurrent) / f_d_value;
if (abs(xNext - xCurrent) <= precision){ condition = 0; break; }
xCurrent = xNext;
iterT++;
if (iterT >= 100000){ condition = 1; break; }
}
iteraterTime = iterT;
root = xNext;
}
ostream &operator<<(ostream&os, const NewtonIterativeMethod&item){
if (!item.condition)os << "The root is " << item.root << " , the iteration times are " << item.iteraterTime << " ." << endl;
else if (item.condition == -1) os << "break in the iteration because of zero-value of f_d." << endl;
else if (item.condition == 1) os << "break in the iteration because the iterative times are out of range" << "The root is "
<< item.root << " , the iteration times are " << item.iteraterTime << " ." << endl;
return os;
}
AitkenSpeedUpIterativeMethod::AitkenSpeedUpIterativeMethod(double sta, double prec, double(*function)(double))
:NormalIterativeMethod(sta, prec, function)
{
calculateTheRoot();
}
void AitkenSpeedUpIterativeMethod::calculateTheRoot()
{
double xCurrent(start), xNext;
double yk, zk;
size_t iterT(0);
while (1)
{
yk = f(xCurrent);
zk = f(yk);
xNext = xCurrent - pow(yk - xCurrent, 2) / (zk - 2 * yk + xCurrent);
if (abs(xNext - xCurrent) <= precision)break;
xCurrent = xNext;
++iterT;
if (iterT > 100000)break;
}
iterateTime = iterT;
root = xNext;
}