You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
1.8KB

  1. #pragma once
  2. namespace rack {
  3. namespace ode {
  4. /** The callback function `f` in each of these stepping functions must have the signature
  5. void f(float t, const float x[], float dxdt[])
  6. A capturing lambda is ideal for this.
  7. For example, the following solves the system x''(t) = -x(t) using a fixed timestep of 0.01 and initial conditions x(0) = 1, x'(0) = 0.
  8. float x[2] = {1.f, 0.f};
  9. float dt = 0.01f;
  10. for (float t = 0.f; t < 1.f; t += dt) {
  11. rack::ode::stepRK4(t, dt, x, 2, [&](float t, const float x[], float dxdt[]) {
  12. dxdt[0] = x[1];
  13. dxdt[1] = -x[0];
  14. });
  15. printf("%f\n", x[0]);
  16. }
  17. */
  18. /** Solves an ODE system using the 1st order Euler method */
  19. template<typename F>
  20. void stepEuler(float t, float dt, float x[], int len, F f) {
  21. float k[len];
  22. f(t, x, k);
  23. for (int i = 0; i < len; i++) {
  24. x[i] += dt * k[i];
  25. }
  26. }
  27. /** Solves an ODE system using the 2nd order Runge-Kutta method */
  28. template<typename F>
  29. void stepRK2(float t, float dt, float x[], int len, F f) {
  30. float k1[len];
  31. float k2[len];
  32. float yi[len];
  33. f(t, x, k1);
  34. for (int i = 0; i < len; i++) {
  35. yi[i] = x[i] + k1[i] * dt / 2.f;
  36. }
  37. f(t + dt / 2.f, yi, k2);
  38. for (int i = 0; i < len; i++) {
  39. x[i] += dt * k2[i];
  40. }
  41. }
  42. /** Solves an ODE system using the 4th order Runge-Kutta method */
  43. template<typename F>
  44. void stepRK4(float t, float dt, float x[], int len, F f) {
  45. float k1[len];
  46. float k2[len];
  47. float k3[len];
  48. float k4[len];
  49. float yi[len];
  50. f(t, x, k1);
  51. for (int i = 0; i < len; i++) {
  52. yi[i] = x[i] + k1[i] * dt / 2.f;
  53. }
  54. f(t + dt / 2.f, yi, k2);
  55. for (int i = 0; i < len; i++) {
  56. yi[i] = x[i] + k2[i] * dt / 2.f;
  57. }
  58. f(t + dt / 2.f, yi, k3);
  59. for (int i = 0; i < len; i++) {
  60. yi[i] = x[i] + k3[i] * dt;
  61. }
  62. f(t + dt, yi, k4);
  63. for (int i = 0; i < len; i++) {
  64. x[i] += dt * (k1[i] + 2.f * k2[i] + 2.f * k3[i] + k4[i]) / 6.f;
  65. }
  66. }
  67. } // namespace ode
  68. } // namespace rack