-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnonlinear.cpp
More file actions
36 lines (30 loc) · 887 Bytes
/
nonlinear.cpp
File metadata and controls
36 lines (30 loc) · 887 Bytes
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
#include "nonlinear.h"
#include <cmath>
std::pair<float, float> NONLIN::interval_bisection(float a, float b, std::function<float(float)> f, float tol) {
while((b - a) > tol) {
auto m = a + (b - a) / 2;
if((f(a) > 0 && f(m) > 0) || (f(a) < 0 && f(m) < 0)) {
a = m;
} else {
b = m;
}
}
return std::make_pair(a, b);
}
float NONLIN::secant_method(float a, float b, std::function<float(float)> f, float tol) {
while(fabs(f(a)) > tol) {
auto t = b - f(b) * ((b - a) / (f(b) - f(a)));
b = a;
a = t;
}
return b;
}
float NONLIN::midpoint_integral(float a, float b, std::function<float(float)> f, float h) {
int k = (b - a) / h;
float I = 0;
for(int i = 1; i <= k; ++i) {
float m = (h / 2) * (f(a + i * h) + f(a + (i - 1) * h));
I += m;
}
return I;
}