random_quaternion.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "random_quaternion.h"
  9. template <typename Scalar>
  10. IGL_INLINE Eigen::Quaternion<Scalar> igl::random_quaternion()
  11. {
  12. // http://mathproofs.blogspot.com/2005/05/uniformly-distributed-random-unit.html
  13. const auto & unit_rand = []()->Scalar
  14. {
  15. return ((Scalar)rand() / (Scalar)RAND_MAX);
  16. };
  17. const Scalar t0 = 2.*M_PI*unit_rand();
  18. const Scalar t1 = acos(1.-2.*unit_rand());
  19. const Scalar t2 = 0.5*(M_PI*unit_rand() + acos(unit_rand()));
  20. return Eigen::Quaternion<Scalar>(
  21. 1.*sin(t0)*sin(t1)*sin(t2),
  22. 1.*cos(t0)*sin(t1)*sin(t2),
  23. 1.*cos(t1)*sin(t2),
  24. 1.*cos(t2));
  25. }
  26. #ifdef IGL_STATIC_LIBRARY
  27. // Explicit template specialization
  28. template Eigen::Quaternion<double, 0> igl::random_quaternion<double>();
  29. #endif