-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolynomial.hpp
More file actions
41 lines (33 loc) · 1011 Bytes
/
polynomial.hpp
File metadata and controls
41 lines (33 loc) · 1011 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
37
38
39
40
41
#ifndef POLYNOMIAL_HPP
#define POLYNOMIAL_HPP
#include <Eigen/Core>
#include <cmath>
namespace polynomial {
// Evaluate polynomial using Horner's scheme
template <typename T> double eval(const Eigen::DenseBase<T>& c, double x) {
double y = 0;
for (int i = c.size()-1; i >= 0; i--)
y = c(i) + y * x;
return y;
}
// Evaluate polynomial derivative using Horner's scheme
template <typename T> double deriv(const Eigen::DenseBase<T>& c, double x) {
double yd = 0;
for (int i = c.size()-1; i > 0; i--)
yd = (i+1) * c(i) + yd * x;
return yd;
}
// Find root of polynomial using Newton's method
template <typename T> double solve(const Eigen::DenseBase<T>& c,
double x, double tol) {
double dx;
int it = 0;
do {
dx = eval(c, x) / deriv(c, x);
x -= dx;
it++;
} while (fabs(dx) > tol && it < 10);
return x;
}
}
#endif