There are multiple ways to represent a 3D rotation. The most intuitive way is the rotation matrix – $$A=\begin{bmatrix}A_{11}&A_{12}&A_{13}\\A_{21}&A_{22}&A_{23}\\A_{31}&A_{32}&A_{33}\end{bmatrix}$$ rotates a point \$p=(x,y,z)^T\$ by left-multiplication: \$p'=Ap\$. This is however inefficient since a 3D rotation has only three degrees of freedom, so I personally prefer the quaternion representation where \$p\$ is interpreted as the quaternion \$0+xi+yj+zk\$ and then conjugated by the rotating unit quaternion \$q\$ to get \$p'=qpq^*\$. Dropping the scalar (first) part leaves the rotated 3D point.
\$A\$ can be converted to a quaternion \$q=s+ai+bj+ck\$ with the same effect as follows: $$s=\frac{\sqrt{1+A_{11}+A_{22}+A_{33}}}2$$ $$a=\frac{A_{32}-A_{23}}{4s}\qquad b=\frac{A_{13}-A_{31}}{4s}\qquad c=\frac{A_{21}-A_{12}}{4s}$$ Note that \$-q\$ has the same effect as \$q\$ by distribution of scalars in \$qpq^*\$, so the quaternion representation is not unique.
Task
Given a 3D rotation matrix – an orthogonal (to floating-point error) 3×3 real matrix with determinant 1 – output a quaternion with the same effect as that matrix to within \$10^{-6}\$ entrywise relative error.
You may use any reasonable and consistent formats for input and output, and any correct formula for the calculation (including the one in the previous section). In particular the code has to handle \$s=0\$ cases, for which alternate formulas are available from this paper: $$a=\frac{\sqrt{1+A_{11}-A_{22}-A_{33}}}2\\ b=\frac{\sqrt{1-A_{11}+A_{22}-A_{33}}}2\\ c=\frac{\sqrt{1-A_{11}-A_{22}+A_{33}}}2$$ $$b=\frac{A_{32}+A_{23}}{4c}\qquad c=\frac{A_{13}+A_{31}}{4a}\qquad a=\frac{A_{21}+A_{12}}{4b}$$
This is code-golf; fewest bytes wins.
Test cases
These are in the format \$A\to q\$. The random cases were generated through this program – you can make your own cases there too!
[[1, 0, 0], [0, 1, 0], [0, 0, 1]] -> [1.0, 0.0, 0.0, 0.0]
[[0, 0, 1], [1, 0, 0], [0, 1, 0]] -> [0.5, 0.5, 0.5, 0.5]
[[0, -1, 0], [1, 0, 0], [0, 0, 1]] -> [0.7071067811865476, 0.0, 0.0, 0.7071067811865476]
[[-1, 0, 0], [0, -1, 0], [0, 0, 1]] -> [0.0, 0.0, 0.0, 1.0]
[[0, 1, 0], [1, 0, 0], [0, 0, -1]] -> [0.0, 0.7071067811865476, 0.7071067811865476, 0.0]
[[0.1508272311227814, -0.2824279103927633, -0.9473571775117411], [-0.7156381696218376, -0.692324273056756, 0.09246140338941596], [-0.6819920501971715, 0.6640192590336603, -0.3065375459878405]] -> [0.19491370659742277, 0.7330908965072773, -0.3403623223156108, -0.5556436573799196]
[[0.13019043201085, -0.4676759473774085, -0.874259492174647], [0.4976035235357375, 0.7934932016832866, -0.35037019314894013], [0.8575786755614011, -0.3894197569808834, 0.33602242201273236]] -> [0.7516159351202696, -0.01298853643440075, -0.5760382686201726, 0.32106805677246825]
a,b,c,d
must be likea^2 = (...) / 4
because in this casea
can be either negative or positive but if we write likea = ( (...) ^ (1/2) ) / 2
thena
can be only non negative number \$\endgroup\$