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 | |
Austin Schuh | 268a94f | 2018-02-17 17:10:19 -0800 | [diff] [blame] | 22 | // Implements Runge Kutta integration (4th order). fn is the function to |
| 23 | // integrate. It must take 1 argument of type T. The integration starts at an |
| 24 | // initial value X, and integrates for dt. |
| 25 | template <typename F, typename T, typename Tu> |
Austin Schuh | 9edb5df | 2018-12-23 09:03:15 +1100 | [diff] [blame^] | 26 | T RungeKuttaU(const F &fn, T X, Tu U, double dt) { |
Austin Schuh | 268a94f | 2018-02-17 17:10:19 -0800 | [diff] [blame] | 27 | const double half_dt = dt * 0.5; |
| 28 | T k1 = fn(X, U); |
| 29 | T k2 = fn(X + half_dt * k1, U); |
| 30 | T k3 = fn(X + half_dt * k2, U); |
| 31 | T k4 = fn(X + dt * k3, U); |
| 32 | return X + dt / 6.0 * (k1 + 2.0 * k2 + 2.0 * k3 + k4); |
| 33 | } |
| 34 | |
Austin Schuh | acd335a | 2017-01-01 16:20:54 -0800 | [diff] [blame] | 35 | } // namespace control_loops |
| 36 | } // namespace frc971 |
| 37 | |
| 38 | #endif // FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_ |