Search code examples
c++eigen

Eigen::Quaternion FromTwoVectors() does not return a valid quaternion


I have two vectors in 3D space and I'm trying to use the function of Eigen::Quaternion FromTwoVectors() to calculate the rotation between them. Despite the fact that there is no unique solution to this problem, I'm getting a quaternion with almost 4 zero values (probably just numerical errors) e.g.: 6.95251e-310, 6.90758e-310, 9.88131e-324, 6.90758e-310. And this is certainly not a valid quaternion.

Eigen::Vector3d normal1;
Eigen::Vector3d normal2;
Eigen::Quaterniond quat;
quat.FromTwoVectors(normal1, normal2);
std::cout << quat.x() << quat.y() << quat.z() << quat.w() << std::endl;

Using the same vectors to compute AngleAxis and then converting to a quaternion gives valid values:

Eigen::Vector3d axis = normal1.cross(normal2);
axis.normalize()
double angle = acos(normal1.dot(normal2));
Eigen::AngleAxisd aa(angle,axis);
Eigen::Quaterniond quat(aa);
std::cout << quat.x() << quat.y() << quat.z() << quat.w() << std::endl;

0.000407447, 0.00621866, 0.0035146, 0.999974

What is going wrong here?


Solution

  • See the documentation for FromTwoVectors https://eigen.tuxfamily.org/dox/classEigen_1_1Quaternion.html#title13

    FromTwoVectors appears to be a static method. So you need to look at the return value. You should get correct answer if you tried Eigen::Quaterniond out = Eigen::Quaterniond::FromTwoVectors(normal1, normal2).