TITLE: Conversion of rotation matrix to quaternion
QUESTION [18 upvotes]: We use unit length Quaternion to represent rotations. Following is a general rotation matrix obtained ${\begin{bmatrix}m_{00} & m_{01}&m_{02} \\ m_{10} & m_{11}&m_{12}\\  m_{20} & m_{21}&m_{22}\end{bmatrix}}_{3\times 3}\tag 1 $. 
How do I accurately calculate quaternion $q = q_1i+q_2j+q_3k+q_4$for this matrix?Means   how can we write $q_i$s interms of given $m_{ij}$  accurately?

REPLY [4 votes]: there is a solution in https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2015/01/matrix-to-quat.pdf
in summary, it's final code is as below:
if (m22 < 0) {
    if (m00 >m11) {
        t = 1 + m00 -m11 -m22;
        q = Quaternion( t, m01+m10, m20+m02, m12-m21 );
    }
    else {
        t = 1 -m00 + m11 -m22;
        q = Quaternion( m01+m10, t, m12+m21, m20-m02 );
    }
}
else {
    if (m00 < -m11) {
        t = 1 -m00 -m11 + m22;
        q = Quaternion( m20+m02, m12+m21, t, m01-m10 );
    }
    else {
        t = 1 + m00 + m11 + m22;
        q = Quaternion( m12-m21, m20-m02, m01-m10, t );
    }
}
q *= 0.5 / Sqrt(t);