💿🐜 Antkeeper source code https://antkeeper.com
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.

79 lines
2.1 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #ifndef ANTKEEPER_PHYSICS_ORBIT_KEPLER_HPP
  20. #define ANTKEEPER_PHYSICS_ORBIT_KEPLER_HPP
  21. #include <cmath>
  22. namespace physics {
  23. namespace orbit {
  24. /**
  25. * Iteratively solves Kepler's equation for eccentric anomaly (E).
  26. *
  27. * @param ec Eccentricity (e).
  28. * @param ma Mean anomaly (M).
  29. * @param iterations Maximum number of iterations.
  30. * @param tolerance Solution error tolerance.
  31. * @return Eccentric anomaly (E).
  32. */
  33. template <class T>
  34. T kepler_ea(T ec, T ma, std::size_t iterations, T tolerance = T(0));
  35. /**
  36. * Solves Kepler's equation for mean anomaly (M).
  37. *
  38. * @param ec Eccentricity (e).
  39. * @param ea Eccentric anomaly (E).
  40. * @return Mean anomaly (M).
  41. */
  42. template <class T>
  43. T kepler_ma(T ec, T ea);
  44. template <class T>
  45. T kepler_ea(T ec, T ma, std::size_t iterations, T tolerance)
  46. {
  47. // Approximate eccentric anomaly, E
  48. T ea0 = ma + ec * std::sin(ma) * (T(1.0) + ec * std::cos(ma));
  49. // Iteratively converge E0 and E1
  50. for (std::size_t i = 0; i < iterations; ++i)
  51. {
  52. const T ea1 = ea0 - (ea0 - ec * std::sin(ea0) - ma) / (T(1.0) - ec * std::cos(ea0));
  53. const T error = std::abs(ea1 - ea0);
  54. ea0 = ea1;
  55. if (error < tolerance)
  56. break;
  57. }
  58. return ea0;
  59. }
  60. template <class T>
  61. T kepler_ma(T ec, T ea)
  62. {
  63. return ea - ec * std::sin(ea);
  64. }
  65. } // namespace orbit
  66. } // namespace physics
  67. #endif // ANTKEEPER_PHYSICS_ORBIT_KEPLER_HPP