math.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright 2016 The Cartographer Authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef CARTOGRAPHER_COMMON_MATH_H_
  17. #define CARTOGRAPHER_COMMON_MATH_H_
  18. #include <cmath>
  19. #include <vector>
  20. #include "Eigen/Core"
  21. #include "port.h"
  22. #include "ceres/ceres.h"
  23. namespace common {
  24. // Clamps 'value' to be in the range ['min', 'max'].
  25. template <typename T>
  26. T Clamp(const T value, const T min, const T max) {
  27. if (value > max) {
  28. return max;
  29. }
  30. if (value < min) {
  31. return min;
  32. }
  33. return value;
  34. }
  35. // Calculates 'base'^'exponent'.
  36. template <typename T>
  37. constexpr T Power(T base, int exponent) {
  38. return (exponent != 0) ? base * Power(base, exponent - 1) : T(1);
  39. }
  40. // Calculates a^2.
  41. template <typename T>
  42. constexpr T Pow2(T a) {
  43. return Power(a, 2);
  44. }
  45. // Converts from degrees to radians.
  46. constexpr double DegToRad(double deg) { return M_PI * deg / 180.; }
  47. // Converts form radians to degrees.
  48. constexpr double RadToDeg(double rad) { return 180. * rad / M_PI; }
  49. // Bring the 'difference' between two angles into [-pi; pi].
  50. template <typename T>
  51. T NormalizeAngleDifference(T difference) {
  52. const T kPi = T(M_PI);
  53. while (difference > kPi) difference -= 2. * kPi;
  54. while (difference < -kPi) difference += 2. * kPi;
  55. return difference;
  56. }
  57. template <typename T>
  58. T atan2(const Eigen::Matrix<T, 2, 1>& vector) {
  59. return ceres::atan2(vector.y(), vector.x());
  60. }
  61. template <typename T>
  62. inline void QuaternionProduct(const double* const z, const T* const w,
  63. T* const zw) {
  64. zw[0] = z[0] * w[0] - z[1] * w[1] - z[2] * w[2] - z[3] * w[3];
  65. zw[1] = z[0] * w[1] + z[1] * w[0] + z[2] * w[3] - z[3] * w[2];
  66. zw[2] = z[0] * w[2] - z[1] * w[3] + z[2] * w[0] + z[3] * w[1];
  67. zw[3] = z[0] * w[3] + z[1] * w[2] - z[2] * w[1] + z[3] * w[0];
  68. }
  69. } // namespace common
  70. #endif // CARTOGRAPHER_COMMON_MATH_H_