-
Notifications
You must be signed in to change notification settings - Fork 2
/
secant.h
56 lines (39 loc) · 1.55 KB
/
secant.h
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
#ifndef SECANT_H
#define SECANT_H
#include "iteration.h"
class Secant : public Iteration {
public:
Secant(double epsilon, const std::function<double (double)> &f) : Iteration(epsilon), mf(f) {}
double solve(double a, double b) override {
resetNumberOfIterations();
fmt::print("Secant -> [{:}, {:}]\n", a, b);
fmt::print("{:<5}|{:<20}|{:<20}|{:<20}|{:<20}\n", "K", "a", "b", "f(a)", "f(b)");
fmt::print("--------------------------------------------------------------------------------------\n");
if(mf(a) > mf(b)) {
std::swap(a,b);
}
double x = b;
double lastX = a;
double fx = mf(b);
double lastFx = mf(a);
fmt::print("{:<5}|{:<20.15f}|{:<20.15f}|{:<20.15f}|{:<20.15f}\n", incrementNumberOfIterations(), x, lastX, fx, lastFx);
while(fabs(fx) >= epsilon()) {
const double x_tmp = calculateX(x, lastX, fx, lastFx);
lastFx = fx;
lastX = x;
x = x_tmp;
fx = mf(x);
fmt::print("{:<5}|{:<20.15f}|{:<20.15f}|{:<20.15f}|{:<20.15f}\n", incrementNumberOfIterations(), x, lastX, fx, lastFx);
}
fmt::print("\n");
return x;
}
private:
static double calculateX(double x, double lastX, double fx, double lastFx) {
const double functionDifference = fx - lastFx;
assert(fabs(functionDifference) >= std::numeric_limits<double>::min());
return x - fx*(x-lastX)/functionDifference;
}
const std::function<double (double)> &mf;
};
#endif