blob: 480405494d4d80e7c10ab42139eed58b6137c3c4 [file] [log] [blame]
Austin Schuhacd335a2017-01-01 16:20:54 -08001#ifndef FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_
2#define FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_
3
4#include <Eigen/Dense>
5
6namespace frc971 {
7namespace control_loops {
8
9// Implements Runge Kutta integration (4th order). fn is the function to
10// integrate. It must take 1 argument of type T. The integration starts at an
11// initial value X, and integrates for dt.
12template <typename F, typename T>
13T RungeKutta(const F &fn, T X, double dt) {
14 const double half_dt = dt * 0.5;
Austin Schuh92ebcbb2018-01-23 11:17:08 -080015 T k1 = fn(X);
16 T k2 = fn(X + half_dt * k1);
17 T k3 = fn(X + half_dt * k2);
18 T k4 = fn(X + dt * k3);
Austin Schuhacd335a2017-01-01 16:20:54 -080019 return X + dt / 6.0 * (k1 + 2.0 * k2 + 2.0 * k3 + k4);
20}
21
22} // namespace control_loops
23} // namespace frc971
24
25#endif // FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_