-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlsBisect.hpp
60 lines (47 loc) · 1.33 KB
/
lsBisect.hpp
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
#pragma once
#include <lsMessage.hpp>
template <class FUNC> class lsBisect {
FUNC function;
double a;
double b;
double result;
unsigned numIter = 0;
double eps = 1e-6;
unsigned maxIterations = 100;
public:
lsBisect() {}
lsBisect(FUNC &func, double lower = 0., double upper = 1.)
: function(func), a(lower), b(upper) {}
void setFunc(FUNC &func) { function = func; }
void setLimits(double lower, double upper) {
a = lower;
b = upper;
}
/// Set the x-accuracy to which the algorithm should go to
/// before finishing. Defaults to 1e-6
void setCriterion(double epsilon) { eps = epsilon; }
/// Maximum number of iterations before aborting to not create
/// infinite loop. Defaults to 100
void setMaxIterations(unsigned maximumIterations) {
maxIterations = maximumIterations;
}
double getRoot() const { return result; }
void apply() {
double funcA = function(a);
if (funcA * function(b) > 0) {
lsMessage::getInstance().addError(
"There is no sign change between lower and upper limit!");
}
result = a;
for (; numIter < maxIterations && (b - a) > eps; ++numIter) {
// take middle
result = (a + b) / 2.;
if (function(result) * funcA < 0) {
b = result;
} else {
a = result;
funcA = function(a);
}
}
}
};