Austin Schuh | acd335a | 2017-01-01 16:20:54 -0800 | [diff] [blame] | 1 | #ifndef FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_ |
| 2 | #define FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_ |
| 3 | |
| 4 | #include <Eigen/Dense> |
| 5 | |
| 6 | namespace frc971 { |
| 7 | namespace 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. |
| 12 | template <typename F, typename T> |
| 13 | T RungeKutta(const F &fn, T X, double dt) { |
| 14 | const double half_dt = dt * 0.5; |
Austin Schuh | 92ebcbb | 2018-01-23 11:17:08 -0800 | [diff] [blame^] | 15 | 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 Schuh | acd335a | 2017-01-01 16:20:54 -0800 | [diff] [blame] | 19 | 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_ |