Rotation.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.math3.geometry.euclidean.threed;

  18. import java.io.Serializable;

  19. import org.apache.commons.math3.exception.MathArithmeticException;
  20. import org.apache.commons.math3.exception.MathIllegalArgumentException;
  21. import org.apache.commons.math3.exception.util.LocalizedFormats;
  22. import org.apache.commons.math3.util.FastMath;
  23. import org.apache.commons.math3.util.MathArrays;

  24. /**
  25.  * This class implements rotations in a three-dimensional space.
  26.  *
  27.  * <p>Rotations can be represented by several different mathematical
  28.  * entities (matrices, axe and angle, Cardan or Euler angles,
  29.  * quaternions). This class presents an higher level abstraction, more
  30.  * user-oriented and hiding this implementation details. Well, for the
  31.  * curious, we use quaternions for the internal representation. The
  32.  * user can build a rotation from any of these representations, and
  33.  * any of these representations can be retrieved from a
  34.  * <code>Rotation</code> instance (see the various constructors and
  35.  * getters). In addition, a rotation can also be built implicitly
  36.  * from a set of vectors and their image.</p>
  37.  * <p>This implies that this class can be used to convert from one
  38.  * representation to another one. For example, converting a rotation
  39.  * matrix into a set of Cardan angles from can be done using the
  40.  * following single line of code:</p>
  41.  * <pre>
  42.  * double[] angles = new Rotation(matrix, 1.0e-10).getAngles(RotationOrder.XYZ);
  43.  * </pre>
  44.  * <p>Focus is oriented on what a rotation <em>do</em> rather than on its
  45.  * underlying representation. Once it has been built, and regardless of its
  46.  * internal representation, a rotation is an <em>operator</em> which basically
  47.  * transforms three dimensional {@link Vector3D vectors} into other three
  48.  * dimensional {@link Vector3D vectors}. Depending on the application, the
  49.  * meaning of these vectors may vary and the semantics of the rotation also.</p>
  50.  * <p>For example in an spacecraft attitude simulation tool, users will often
  51.  * consider the vectors are fixed (say the Earth direction for example) and the
  52.  * frames change. The rotation transforms the coordinates of the vector in inertial
  53.  * frame into the coordinates of the same vector in satellite frame. In this
  54.  * case, the rotation implicitly defines the relation between the two frames.</p>
  55.  * <p>Another example could be a telescope control application, where the rotation
  56.  * would transform the sighting direction at rest into the desired observing
  57.  * direction when the telescope is pointed towards an object of interest. In this
  58.  * case the rotation transforms the direction at rest in a topocentric frame
  59.  * into the sighting direction in the same topocentric frame. This implies in this
  60.  * case the frame is fixed and the vector moves.</p>
  61.  * <p>In many case, both approaches will be combined. In our telescope example,
  62.  * we will probably also need to transform the observing direction in the topocentric
  63.  * frame into the observing direction in inertial frame taking into account the observatory
  64.  * location and the Earth rotation, which would essentially be an application of the
  65.  * first approach.</p>
  66.  *
  67.  * <p>These examples show that a rotation is what the user wants it to be. This
  68.  * class does not push the user towards one specific definition and hence does not
  69.  * provide methods like <code>projectVectorIntoDestinationFrame</code> or
  70.  * <code>computeTransformedDirection</code>. It provides simpler and more generic
  71.  * methods: {@link #applyTo(Vector3D) applyTo(Vector3D)} and {@link
  72.  * #applyInverseTo(Vector3D) applyInverseTo(Vector3D)}.</p>
  73.  *
  74.  * <p>Since a rotation is basically a vectorial operator, several rotations can be
  75.  * composed together and the composite operation <code>r = r<sub>1</sub> o
  76.  * r<sub>2</sub></code> (which means that for each vector <code>u</code>,
  77.  * <code>r(u) = r<sub>1</sub>(r<sub>2</sub>(u))</code>) is also a rotation. Hence
  78.  * we can consider that in addition to vectors, a rotation can be applied to other
  79.  * rotations as well (or to itself). With our previous notations, we would say we
  80.  * can apply <code>r<sub>1</sub></code> to <code>r<sub>2</sub></code> and the result
  81.  * we get is <code>r = r<sub>1</sub> o r<sub>2</sub></code>. For this purpose, the
  82.  * class provides the methods: {@link #applyTo(Rotation) applyTo(Rotation)} and
  83.  * {@link #applyInverseTo(Rotation) applyInverseTo(Rotation)}.</p>
  84.  *
  85.  * <p>Rotations are guaranteed to be immutable objects.</p>
  86.  *
  87.  * @see Vector3D
  88.  * @see RotationOrder
  89.  * @since 1.2
  90.  */

  91. public class Rotation implements Serializable {

  92.   /** Identity rotation. */
  93.   public static final Rotation IDENTITY = new Rotation(1.0, 0.0, 0.0, 0.0, false);

  94.   /** Serializable version identifier */
  95.   private static final long serialVersionUID = -2153622329907944313L;

  96.   /** Scalar coordinate of the quaternion. */
  97.   private final double q0;

  98.   /** First coordinate of the vectorial part of the quaternion. */
  99.   private final double q1;

  100.   /** Second coordinate of the vectorial part of the quaternion. */
  101.   private final double q2;

  102.   /** Third coordinate of the vectorial part of the quaternion. */
  103.   private final double q3;

  104.   /** Build a rotation from the quaternion coordinates.
  105.    * <p>A rotation can be built from a <em>normalized</em> quaternion,
  106.    * i.e. a quaternion for which q<sub>0</sub><sup>2</sup> +
  107.    * q<sub>1</sub><sup>2</sup> + q<sub>2</sub><sup>2</sup> +
  108.    * q<sub>3</sub><sup>2</sup> = 1. If the quaternion is not normalized,
  109.    * the constructor can normalize it in a preprocessing step.</p>
  110.    * <p>Note that some conventions put the scalar part of the quaternion
  111.    * as the 4<sup>th</sup> component and the vector part as the first three
  112.    * components. This is <em>not</em> our convention. We put the scalar part
  113.    * as the first component.</p>
  114.    * @param q0 scalar part of the quaternion
  115.    * @param q1 first coordinate of the vectorial part of the quaternion
  116.    * @param q2 second coordinate of the vectorial part of the quaternion
  117.    * @param q3 third coordinate of the vectorial part of the quaternion
  118.    * @param needsNormalization if true, the coordinates are considered
  119.    * not to be normalized, a normalization preprocessing step is performed
  120.    * before using them
  121.    */
  122.   public Rotation(double q0, double q1, double q2, double q3,
  123.                   boolean needsNormalization) {

  124.     if (needsNormalization) {
  125.       // normalization preprocessing
  126.       double inv = 1.0 / FastMath.sqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
  127.       q0 *= inv;
  128.       q1 *= inv;
  129.       q2 *= inv;
  130.       q3 *= inv;
  131.     }

  132.     this.q0 = q0;
  133.     this.q1 = q1;
  134.     this.q2 = q2;
  135.     this.q3 = q3;

  136.   }

  137.   /** Build a rotation from an axis and an angle.
  138.    * <p>We use the convention that angles are oriented according to
  139.    * the effect of the rotation on vectors around the axis. That means
  140.    * that if (i, j, k) is a direct frame and if we first provide +k as
  141.    * the axis and &pi;/2 as the angle to this constructor, and then
  142.    * {@link #applyTo(Vector3D) apply} the instance to +i, we will get
  143.    * +j.</p>
  144.    * <p>Another way to represent our convention is to say that a rotation
  145.    * of angle &theta; about the unit vector (x, y, z) is the same as the
  146.    * rotation build from quaternion components { cos(-&theta;/2),
  147.    * x * sin(-&theta;/2), y * sin(-&theta;/2), z * sin(-&theta;/2) }.
  148.    * Note the minus sign on the angle!</p>
  149.    * <p>On the one hand this convention is consistent with a vectorial
  150.    * perspective (moving vectors in fixed frames), on the other hand it
  151.    * is different from conventions with a frame perspective (fixed vectors
  152.    * viewed from different frames) like the ones used for example in spacecraft
  153.    * attitude community or in the graphics community.</p>
  154.    * @param axis axis around which to rotate
  155.    * @param angle rotation angle.
  156.    * @exception MathIllegalArgumentException if the axis norm is zero
  157.    */
  158.   public Rotation(Vector3D axis, double angle) throws MathIllegalArgumentException {

  159.     double norm = axis.getNorm();
  160.     if (norm == 0) {
  161.       throw new MathIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_AXIS);
  162.     }

  163.     double halfAngle = -0.5 * angle;
  164.     double coeff = FastMath.sin(halfAngle) / norm;

  165.     q0 = FastMath.cos (halfAngle);
  166.     q1 = coeff * axis.getX();
  167.     q2 = coeff * axis.getY();
  168.     q3 = coeff * axis.getZ();

  169.   }

  170.   /** Build a rotation from a 3X3 matrix.

  171.    * <p>Rotation matrices are orthogonal matrices, i.e. unit matrices
  172.    * (which are matrices for which m.m<sup>T</sup> = I) with real
  173.    * coefficients. The module of the determinant of unit matrices is
  174.    * 1, among the orthogonal 3X3 matrices, only the ones having a
  175.    * positive determinant (+1) are rotation matrices.</p>

  176.    * <p>When a rotation is defined by a matrix with truncated values
  177.    * (typically when it is extracted from a technical sheet where only
  178.    * four to five significant digits are available), the matrix is not
  179.    * orthogonal anymore. This constructor handles this case
  180.    * transparently by using a copy of the given matrix and applying a
  181.    * correction to the copy in order to perfect its orthogonality. If
  182.    * the Frobenius norm of the correction needed is above the given
  183.    * threshold, then the matrix is considered to be too far from a
  184.    * true rotation matrix and an exception is thrown.<p>

  185.    * @param m rotation matrix
  186.    * @param threshold convergence threshold for the iterative
  187.    * orthogonality correction (convergence is reached when the
  188.    * difference between two steps of the Frobenius norm of the
  189.    * correction is below this threshold)

  190.    * @exception NotARotationMatrixException if the matrix is not a 3X3
  191.    * matrix, or if it cannot be transformed into an orthogonal matrix
  192.    * with the given threshold, or if the determinant of the resulting
  193.    * orthogonal matrix is negative

  194.    */
  195.   public Rotation(double[][] m, double threshold)
  196.     throws NotARotationMatrixException {

  197.     // dimension check
  198.     if ((m.length != 3) || (m[0].length != 3) ||
  199.         (m[1].length != 3) || (m[2].length != 3)) {
  200.       throw new NotARotationMatrixException(
  201.               LocalizedFormats.ROTATION_MATRIX_DIMENSIONS,
  202.               m.length, m[0].length);
  203.     }

  204.     // compute a "close" orthogonal matrix
  205.     double[][] ort = orthogonalizeMatrix(m, threshold);

  206.     // check the sign of the determinant
  207.     double det = ort[0][0] * (ort[1][1] * ort[2][2] - ort[2][1] * ort[1][2]) -
  208.                  ort[1][0] * (ort[0][1] * ort[2][2] - ort[2][1] * ort[0][2]) +
  209.                  ort[2][0] * (ort[0][1] * ort[1][2] - ort[1][1] * ort[0][2]);
  210.     if (det < 0.0) {
  211.       throw new NotARotationMatrixException(
  212.               LocalizedFormats.CLOSEST_ORTHOGONAL_MATRIX_HAS_NEGATIVE_DETERMINANT,
  213.               det);
  214.     }

  215.     double[] quat = mat2quat(ort);
  216.     q0 = quat[0];
  217.     q1 = quat[1];
  218.     q2 = quat[2];
  219.     q3 = quat[3];

  220.   }

  221.   /** Build the rotation that transforms a pair of vector into another pair.

  222.    * <p>Except for possible scale factors, if the instance were applied to
  223.    * the pair (u<sub>1</sub>, u<sub>2</sub>) it will produce the pair
  224.    * (v<sub>1</sub>, v<sub>2</sub>).</p>

  225.    * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is
  226.    * not the same as the angular separation between v<sub>1</sub> and
  227.    * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than
  228.    * v<sub>2</sub>, the corrected vector will be in the (v<sub>1</sub>,
  229.    * v<sub>2</sub>) plane.</p>

  230.    * @param u1 first vector of the origin pair
  231.    * @param u2 second vector of the origin pair
  232.    * @param v1 desired image of u1 by the rotation
  233.    * @param v2 desired image of u2 by the rotation
  234.    * @exception MathArithmeticException if the norm of one of the vectors is zero,
  235.    * or if one of the pair is degenerated (i.e. the vectors of the pair are colinear)
  236.    */
  237.   public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2)
  238.       throws MathArithmeticException {

  239.       // build orthonormalized base from u1, u2
  240.       // this fails when vectors are null or colinear, which is forbidden to define a rotation
  241.       final Vector3D u3 = u1.crossProduct(u2).normalize();
  242.       u2 = u3.crossProduct(u1).normalize();
  243.       u1 = u1.normalize();

  244.       // build an orthonormalized base from v1, v2
  245.       // this fails when vectors are null or colinear, which is forbidden to define a rotation
  246.       final Vector3D v3 = v1.crossProduct(v2).normalize();
  247.       v2 = v3.crossProduct(v1).normalize();
  248.       v1 = v1.normalize();

  249.       // buid a matrix transforming the first base into the second one
  250.       final double[][] m = new double[][] {
  251.           {
  252.               MathArrays.linearCombination(u1.getX(), v1.getX(), u2.getX(), v2.getX(), u3.getX(), v3.getX()),
  253.               MathArrays.linearCombination(u1.getY(), v1.getX(), u2.getY(), v2.getX(), u3.getY(), v3.getX()),
  254.               MathArrays.linearCombination(u1.getZ(), v1.getX(), u2.getZ(), v2.getX(), u3.getZ(), v3.getX())
  255.           },
  256.           {
  257.               MathArrays.linearCombination(u1.getX(), v1.getY(), u2.getX(), v2.getY(), u3.getX(), v3.getY()),
  258.               MathArrays.linearCombination(u1.getY(), v1.getY(), u2.getY(), v2.getY(), u3.getY(), v3.getY()),
  259.               MathArrays.linearCombination(u1.getZ(), v1.getY(), u2.getZ(), v2.getY(), u3.getZ(), v3.getY())
  260.           },
  261.           {
  262.               MathArrays.linearCombination(u1.getX(), v1.getZ(), u2.getX(), v2.getZ(), u3.getX(), v3.getZ()),
  263.               MathArrays.linearCombination(u1.getY(), v1.getZ(), u2.getY(), v2.getZ(), u3.getY(), v3.getZ()),
  264.               MathArrays.linearCombination(u1.getZ(), v1.getZ(), u2.getZ(), v2.getZ(), u3.getZ(), v3.getZ())
  265.           }
  266.       };

  267.       double[] quat = mat2quat(m);
  268.       q0 = quat[0];
  269.       q1 = quat[1];
  270.       q2 = quat[2];
  271.       q3 = quat[3];

  272.   }

  273.   /** Build one of the rotations that transform one vector into another one.

  274.    * <p>Except for a possible scale factor, if the instance were
  275.    * applied to the vector u it will produce the vector v. There is an
  276.    * infinite number of such rotations, this constructor choose the
  277.    * one with the smallest associated angle (i.e. the one whose axis
  278.    * is orthogonal to the (u, v) plane). If u and v are colinear, an
  279.    * arbitrary rotation axis is chosen.</p>

  280.    * @param u origin vector
  281.    * @param v desired image of u by the rotation
  282.    * @exception MathArithmeticException if the norm of one of the vectors is zero
  283.    */
  284.   public Rotation(Vector3D u, Vector3D v) throws MathArithmeticException {

  285.     double normProduct = u.getNorm() * v.getNorm();
  286.     if (normProduct == 0) {
  287.         throw new MathArithmeticException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
  288.     }

  289.     double dot = u.dotProduct(v);

  290.     if (dot < ((2.0e-15 - 1.0) * normProduct)) {
  291.       // special case u = -v: we select a PI angle rotation around
  292.       // an arbitrary vector orthogonal to u
  293.       Vector3D w = u.orthogonal();
  294.       q0 = 0.0;
  295.       q1 = -w.getX();
  296.       q2 = -w.getY();
  297.       q3 = -w.getZ();
  298.     } else {
  299.       // general case: (u, v) defines a plane, we select
  300.       // the shortest possible rotation: axis orthogonal to this plane
  301.       q0 = FastMath.sqrt(0.5 * (1.0 + dot / normProduct));
  302.       double coeff = 1.0 / (2.0 * q0 * normProduct);
  303.       Vector3D q = v.crossProduct(u);
  304.       q1 = coeff * q.getX();
  305.       q2 = coeff * q.getY();
  306.       q3 = coeff * q.getZ();
  307.     }

  308.   }

  309.   /** Build a rotation from three Cardan or Euler elementary rotations.

  310.    * <p>Cardan rotations are three successive rotations around the
  311.    * canonical axes X, Y and Z, each axis being used once. There are
  312.    * 6 such sets of rotations (XYZ, XZY, YXZ, YZX, ZXY and ZYX). Euler
  313.    * rotations are three successive rotations around the canonical
  314.    * axes X, Y and Z, the first and last rotations being around the
  315.    * same axis. There are 6 such sets of rotations (XYX, XZX, YXY,
  316.    * YZY, ZXZ and ZYZ), the most popular one being ZXZ.</p>
  317.    * <p>Beware that many people routinely use the term Euler angles even
  318.    * for what really are Cardan angles (this confusion is especially
  319.    * widespread in the aerospace business where Roll, Pitch and Yaw angles
  320.    * are often wrongly tagged as Euler angles).</p>

  321.    * @param order order of rotations to use
  322.    * @param alpha1 angle of the first elementary rotation
  323.    * @param alpha2 angle of the second elementary rotation
  324.    * @param alpha3 angle of the third elementary rotation
  325.    */
  326.   public Rotation(RotationOrder order,
  327.                   double alpha1, double alpha2, double alpha3) {
  328.       Rotation r1 = new Rotation(order.getA1(), alpha1);
  329.       Rotation r2 = new Rotation(order.getA2(), alpha2);
  330.       Rotation r3 = new Rotation(order.getA3(), alpha3);
  331.       Rotation composed = r1.applyTo(r2.applyTo(r3));
  332.       q0 = composed.q0;
  333.       q1 = composed.q1;
  334.       q2 = composed.q2;
  335.       q3 = composed.q3;
  336.   }

  337.   /** Convert an orthogonal rotation matrix to a quaternion.
  338.    * @param ort orthogonal rotation matrix
  339.    * @return quaternion corresponding to the matrix
  340.    */
  341.   private static double[] mat2quat(final double[][] ort) {

  342.       final double[] quat = new double[4];

  343.       // There are different ways to compute the quaternions elements
  344.       // from the matrix. They all involve computing one element from
  345.       // the diagonal of the matrix, and computing the three other ones
  346.       // using a formula involving a division by the first element,
  347.       // which unfortunately can be zero. Since the norm of the
  348.       // quaternion is 1, we know at least one element has an absolute
  349.       // value greater or equal to 0.5, so it is always possible to
  350.       // select the right formula and avoid division by zero and even
  351.       // numerical inaccuracy. Checking the elements in turn and using
  352.       // the first one greater than 0.45 is safe (this leads to a simple
  353.       // test since qi = 0.45 implies 4 qi^2 - 1 = -0.19)
  354.       double s = ort[0][0] + ort[1][1] + ort[2][2];
  355.       if (s > -0.19) {
  356.           // compute q0 and deduce q1, q2 and q3
  357.           quat[0] = 0.5 * FastMath.sqrt(s + 1.0);
  358.           double inv = 0.25 / quat[0];
  359.           quat[1] = inv * (ort[1][2] - ort[2][1]);
  360.           quat[2] = inv * (ort[2][0] - ort[0][2]);
  361.           quat[3] = inv * (ort[0][1] - ort[1][0]);
  362.       } else {
  363.           s = ort[0][0] - ort[1][1] - ort[2][2];
  364.           if (s > -0.19) {
  365.               // compute q1 and deduce q0, q2 and q3
  366.               quat[1] = 0.5 * FastMath.sqrt(s + 1.0);
  367.               double inv = 0.25 / quat[1];
  368.               quat[0] = inv * (ort[1][2] - ort[2][1]);
  369.               quat[2] = inv * (ort[0][1] + ort[1][0]);
  370.               quat[3] = inv * (ort[0][2] + ort[2][0]);
  371.           } else {
  372.               s = ort[1][1] - ort[0][0] - ort[2][2];
  373.               if (s > -0.19) {
  374.                   // compute q2 and deduce q0, q1 and q3
  375.                   quat[2] = 0.5 * FastMath.sqrt(s + 1.0);
  376.                   double inv = 0.25 / quat[2];
  377.                   quat[0] = inv * (ort[2][0] - ort[0][2]);
  378.                   quat[1] = inv * (ort[0][1] + ort[1][0]);
  379.                   quat[3] = inv * (ort[2][1] + ort[1][2]);
  380.               } else {
  381.                   // compute q3 and deduce q0, q1 and q2
  382.                   s = ort[2][2] - ort[0][0] - ort[1][1];
  383.                   quat[3] = 0.5 * FastMath.sqrt(s + 1.0);
  384.                   double inv = 0.25 / quat[3];
  385.                   quat[0] = inv * (ort[0][1] - ort[1][0]);
  386.                   quat[1] = inv * (ort[0][2] + ort[2][0]);
  387.                   quat[2] = inv * (ort[2][1] + ort[1][2]);
  388.               }
  389.           }
  390.       }

  391.       return quat;

  392.   }

  393.   /** Revert a rotation.
  394.    * Build a rotation which reverse the effect of another
  395.    * rotation. This means that if r(u) = v, then r.revert(v) = u. The
  396.    * instance is not changed.
  397.    * @return a new rotation whose effect is the reverse of the effect
  398.    * of the instance
  399.    */
  400.   public Rotation revert() {
  401.     return new Rotation(-q0, q1, q2, q3, false);
  402.   }

  403.   /** Get the scalar coordinate of the quaternion.
  404.    * @return scalar coordinate of the quaternion
  405.    */
  406.   public double getQ0() {
  407.     return q0;
  408.   }

  409.   /** Get the first coordinate of the vectorial part of the quaternion.
  410.    * @return first coordinate of the vectorial part of the quaternion
  411.    */
  412.   public double getQ1() {
  413.     return q1;
  414.   }

  415.   /** Get the second coordinate of the vectorial part of the quaternion.
  416.    * @return second coordinate of the vectorial part of the quaternion
  417.    */
  418.   public double getQ2() {
  419.     return q2;
  420.   }

  421.   /** Get the third coordinate of the vectorial part of the quaternion.
  422.    * @return third coordinate of the vectorial part of the quaternion
  423.    */
  424.   public double getQ3() {
  425.     return q3;
  426.   }

  427.   /** Get the normalized axis of the rotation.
  428.    * @return normalized axis of the rotation
  429.    * @see #Rotation(Vector3D, double)
  430.    */
  431.   public Vector3D getAxis() {
  432.     double squaredSine = q1 * q1 + q2 * q2 + q3 * q3;
  433.     if (squaredSine == 0) {
  434.       return new Vector3D(1, 0, 0);
  435.     } else if (q0 < 0) {
  436.       double inverse = 1 / FastMath.sqrt(squaredSine);
  437.       return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
  438.     }
  439.     double inverse = -1 / FastMath.sqrt(squaredSine);
  440.     return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
  441.   }

  442.   /** Get the angle of the rotation.
  443.    * @return angle of the rotation (between 0 and &pi;)
  444.    * @see #Rotation(Vector3D, double)
  445.    */
  446.   public double getAngle() {
  447.     if ((q0 < -0.1) || (q0 > 0.1)) {
  448.       return 2 * FastMath.asin(FastMath.sqrt(q1 * q1 + q2 * q2 + q3 * q3));
  449.     } else if (q0 < 0) {
  450.       return 2 * FastMath.acos(-q0);
  451.     }
  452.     return 2 * FastMath.acos(q0);
  453.   }

  454.   /** Get the Cardan or Euler angles corresponding to the instance.

  455.    * <p>The equations show that each rotation can be defined by two
  456.    * different values of the Cardan or Euler angles set. For example
  457.    * if Cardan angles are used, the rotation defined by the angles
  458.    * a<sub>1</sub>, a<sub>2</sub> and a<sub>3</sub> is the same as
  459.    * the rotation defined by the angles &pi; + a<sub>1</sub>, &pi;
  460.    * - a<sub>2</sub> and &pi; + a<sub>3</sub>. This method implements
  461.    * the following arbitrary choices:</p>
  462.    * <ul>
  463.    *   <li>for Cardan angles, the chosen set is the one for which the
  464.    *   second angle is between -&pi;/2 and &pi;/2 (i.e its cosine is
  465.    *   positive),</li>
  466.    *   <li>for Euler angles, the chosen set is the one for which the
  467.    *   second angle is between 0 and &pi; (i.e its sine is positive).</li>
  468.    * </ul>

  469.    * <p>Cardan and Euler angle have a very disappointing drawback: all
  470.    * of them have singularities. This means that if the instance is
  471.    * too close to the singularities corresponding to the given
  472.    * rotation order, it will be impossible to retrieve the angles. For
  473.    * Cardan angles, this is often called gimbal lock. There is
  474.    * <em>nothing</em> to do to prevent this, it is an intrinsic problem
  475.    * with Cardan and Euler representation (but not a problem with the
  476.    * rotation itself, which is perfectly well defined). For Cardan
  477.    * angles, singularities occur when the second angle is close to
  478.    * -&pi;/2 or +&pi;/2, for Euler angle singularities occur when the
  479.    * second angle is close to 0 or &pi;, this implies that the identity
  480.    * rotation is always singular for Euler angles!</p>

  481.    * @param order rotation order to use
  482.    * @return an array of three angles, in the order specified by the set
  483.    * @exception CardanEulerSingularityException if the rotation is
  484.    * singular with respect to the angles set specified
  485.    */
  486.   public double[] getAngles(RotationOrder order)
  487.     throws CardanEulerSingularityException {

  488.     if (order == RotationOrder.XYZ) {

  489.       // r (Vector3D.plusK) coordinates are :
  490.       //  sin (theta), -cos (theta) sin (phi), cos (theta) cos (phi)
  491.       // (-r) (Vector3D.plusI) coordinates are :
  492.       // cos (psi) cos (theta), -sin (psi) cos (theta), sin (theta)
  493.       // and we can choose to have theta in the interval [-PI/2 ; +PI/2]
  494.       Vector3D v1 = applyTo(Vector3D.PLUS_K);
  495.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
  496.       if  ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
  497.         throw new CardanEulerSingularityException(true);
  498.       }
  499.       return new double[] {
  500.         FastMath.atan2(-(v1.getY()), v1.getZ()),
  501.         FastMath.asin(v2.getZ()),
  502.         FastMath.atan2(-(v2.getY()), v2.getX())
  503.       };

  504.     } else if (order == RotationOrder.XZY) {

  505.       // r (Vector3D.plusJ) coordinates are :
  506.       // -sin (psi), cos (psi) cos (phi), cos (psi) sin (phi)
  507.       // (-r) (Vector3D.plusI) coordinates are :
  508.       // cos (theta) cos (psi), -sin (psi), sin (theta) cos (psi)
  509.       // and we can choose to have psi in the interval [-PI/2 ; +PI/2]
  510.       Vector3D v1 = applyTo(Vector3D.PLUS_J);
  511.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
  512.       if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
  513.         throw new CardanEulerSingularityException(true);
  514.       }
  515.       return new double[] {
  516.         FastMath.atan2(v1.getZ(), v1.getY()),
  517.        -FastMath.asin(v2.getY()),
  518.         FastMath.atan2(v2.getZ(), v2.getX())
  519.       };

  520.     } else if (order == RotationOrder.YXZ) {

  521.       // r (Vector3D.plusK) coordinates are :
  522.       //  cos (phi) sin (theta), -sin (phi), cos (phi) cos (theta)
  523.       // (-r) (Vector3D.plusJ) coordinates are :
  524.       // sin (psi) cos (phi), cos (psi) cos (phi), -sin (phi)
  525.       // and we can choose to have phi in the interval [-PI/2 ; +PI/2]
  526.       Vector3D v1 = applyTo(Vector3D.PLUS_K);
  527.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
  528.       if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
  529.         throw new CardanEulerSingularityException(true);
  530.       }
  531.       return new double[] {
  532.         FastMath.atan2(v1.getX(), v1.getZ()),
  533.        -FastMath.asin(v2.getZ()),
  534.         FastMath.atan2(v2.getX(), v2.getY())
  535.       };

  536.     } else if (order == RotationOrder.YZX) {

  537.       // r (Vector3D.plusI) coordinates are :
  538.       // cos (psi) cos (theta), sin (psi), -cos (psi) sin (theta)
  539.       // (-r) (Vector3D.plusJ) coordinates are :
  540.       // sin (psi), cos (phi) cos (psi), -sin (phi) cos (psi)
  541.       // and we can choose to have psi in the interval [-PI/2 ; +PI/2]
  542.       Vector3D v1 = applyTo(Vector3D.PLUS_I);
  543.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
  544.       if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
  545.         throw new CardanEulerSingularityException(true);
  546.       }
  547.       return new double[] {
  548.         FastMath.atan2(-(v1.getZ()), v1.getX()),
  549.         FastMath.asin(v2.getX()),
  550.         FastMath.atan2(-(v2.getZ()), v2.getY())
  551.       };

  552.     } else if (order == RotationOrder.ZXY) {

  553.       // r (Vector3D.plusJ) coordinates are :
  554.       // -cos (phi) sin (psi), cos (phi) cos (psi), sin (phi)
  555.       // (-r) (Vector3D.plusK) coordinates are :
  556.       // -sin (theta) cos (phi), sin (phi), cos (theta) cos (phi)
  557.       // and we can choose to have phi in the interval [-PI/2 ; +PI/2]
  558.       Vector3D v1 = applyTo(Vector3D.PLUS_J);
  559.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
  560.       if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
  561.         throw new CardanEulerSingularityException(true);
  562.       }
  563.       return new double[] {
  564.         FastMath.atan2(-(v1.getX()), v1.getY()),
  565.         FastMath.asin(v2.getY()),
  566.         FastMath.atan2(-(v2.getX()), v2.getZ())
  567.       };

  568.     } else if (order == RotationOrder.ZYX) {

  569.       // r (Vector3D.plusI) coordinates are :
  570.       //  cos (theta) cos (psi), cos (theta) sin (psi), -sin (theta)
  571.       // (-r) (Vector3D.plusK) coordinates are :
  572.       // -sin (theta), sin (phi) cos (theta), cos (phi) cos (theta)
  573.       // and we can choose to have theta in the interval [-PI/2 ; +PI/2]
  574.       Vector3D v1 = applyTo(Vector3D.PLUS_I);
  575.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
  576.       if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
  577.         throw new CardanEulerSingularityException(true);
  578.       }
  579.       return new double[] {
  580.         FastMath.atan2(v1.getY(), v1.getX()),
  581.        -FastMath.asin(v2.getX()),
  582.         FastMath.atan2(v2.getY(), v2.getZ())
  583.       };

  584.     } else if (order == RotationOrder.XYX) {

  585.       // r (Vector3D.plusI) coordinates are :
  586.       //  cos (theta), sin (phi1) sin (theta), -cos (phi1) sin (theta)
  587.       // (-r) (Vector3D.plusI) coordinates are :
  588.       // cos (theta), sin (theta) sin (phi2), sin (theta) cos (phi2)
  589.       // and we can choose to have theta in the interval [0 ; PI]
  590.       Vector3D v1 = applyTo(Vector3D.PLUS_I);
  591.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
  592.       if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
  593.         throw new CardanEulerSingularityException(false);
  594.       }
  595.       return new double[] {
  596.         FastMath.atan2(v1.getY(), -v1.getZ()),
  597.         FastMath.acos(v2.getX()),
  598.         FastMath.atan2(v2.getY(), v2.getZ())
  599.       };

  600.     } else if (order == RotationOrder.XZX) {

  601.       // r (Vector3D.plusI) coordinates are :
  602.       //  cos (psi), cos (phi1) sin (psi), sin (phi1) sin (psi)
  603.       // (-r) (Vector3D.plusI) coordinates are :
  604.       // cos (psi), -sin (psi) cos (phi2), sin (psi) sin (phi2)
  605.       // and we can choose to have psi in the interval [0 ; PI]
  606.       Vector3D v1 = applyTo(Vector3D.PLUS_I);
  607.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
  608.       if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
  609.         throw new CardanEulerSingularityException(false);
  610.       }
  611.       return new double[] {
  612.         FastMath.atan2(v1.getZ(), v1.getY()),
  613.         FastMath.acos(v2.getX()),
  614.         FastMath.atan2(v2.getZ(), -v2.getY())
  615.       };

  616.     } else if (order == RotationOrder.YXY) {

  617.       // r (Vector3D.plusJ) coordinates are :
  618.       //  sin (theta1) sin (phi), cos (phi), cos (theta1) sin (phi)
  619.       // (-r) (Vector3D.plusJ) coordinates are :
  620.       // sin (phi) sin (theta2), cos (phi), -sin (phi) cos (theta2)
  621.       // and we can choose to have phi in the interval [0 ; PI]
  622.       Vector3D v1 = applyTo(Vector3D.PLUS_J);
  623.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
  624.       if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
  625.         throw new CardanEulerSingularityException(false);
  626.       }
  627.       return new double[] {
  628.         FastMath.atan2(v1.getX(), v1.getZ()),
  629.         FastMath.acos(v2.getY()),
  630.         FastMath.atan2(v2.getX(), -v2.getZ())
  631.       };

  632.     } else if (order == RotationOrder.YZY) {

  633.       // r (Vector3D.plusJ) coordinates are :
  634.       //  -cos (theta1) sin (psi), cos (psi), sin (theta1) sin (psi)
  635.       // (-r) (Vector3D.plusJ) coordinates are :
  636.       // sin (psi) cos (theta2), cos (psi), sin (psi) sin (theta2)
  637.       // and we can choose to have psi in the interval [0 ; PI]
  638.       Vector3D v1 = applyTo(Vector3D.PLUS_J);
  639.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
  640.       if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
  641.         throw new CardanEulerSingularityException(false);
  642.       }
  643.       return new double[] {
  644.         FastMath.atan2(v1.getZ(), -v1.getX()),
  645.         FastMath.acos(v2.getY()),
  646.         FastMath.atan2(v2.getZ(), v2.getX())
  647.       };

  648.     } else if (order == RotationOrder.ZXZ) {

  649.       // r (Vector3D.plusK) coordinates are :
  650.       //  sin (psi1) sin (phi), -cos (psi1) sin (phi), cos (phi)
  651.       // (-r) (Vector3D.plusK) coordinates are :
  652.       // sin (phi) sin (psi2), sin (phi) cos (psi2), cos (phi)
  653.       // and we can choose to have phi in the interval [0 ; PI]
  654.       Vector3D v1 = applyTo(Vector3D.PLUS_K);
  655.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
  656.       if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
  657.         throw new CardanEulerSingularityException(false);
  658.       }
  659.       return new double[] {
  660.         FastMath.atan2(v1.getX(), -v1.getY()),
  661.         FastMath.acos(v2.getZ()),
  662.         FastMath.atan2(v2.getX(), v2.getY())
  663.       };

  664.     } else { // last possibility is ZYZ

  665.       // r (Vector3D.plusK) coordinates are :
  666.       //  cos (psi1) sin (theta), sin (psi1) sin (theta), cos (theta)
  667.       // (-r) (Vector3D.plusK) coordinates are :
  668.       // -sin (theta) cos (psi2), sin (theta) sin (psi2), cos (theta)
  669.       // and we can choose to have theta in the interval [0 ; PI]
  670.       Vector3D v1 = applyTo(Vector3D.PLUS_K);
  671.       Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
  672.       if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
  673.         throw new CardanEulerSingularityException(false);
  674.       }
  675.       return new double[] {
  676.         FastMath.atan2(v1.getY(), v1.getX()),
  677.         FastMath.acos(v2.getZ()),
  678.         FastMath.atan2(v2.getY(), -v2.getX())
  679.       };

  680.     }

  681.   }

  682.   /** Get the 3X3 matrix corresponding to the instance
  683.    * @return the matrix corresponding to the instance
  684.    */
  685.   public double[][] getMatrix() {

  686.     // products
  687.     double q0q0  = q0 * q0;
  688.     double q0q1  = q0 * q1;
  689.     double q0q2  = q0 * q2;
  690.     double q0q3  = q0 * q3;
  691.     double q1q1  = q1 * q1;
  692.     double q1q2  = q1 * q2;
  693.     double q1q3  = q1 * q3;
  694.     double q2q2  = q2 * q2;
  695.     double q2q3  = q2 * q3;
  696.     double q3q3  = q3 * q3;

  697.     // create the matrix
  698.     double[][] m = new double[3][];
  699.     m[0] = new double[3];
  700.     m[1] = new double[3];
  701.     m[2] = new double[3];

  702.     m [0][0] = 2.0 * (q0q0 + q1q1) - 1.0;
  703.     m [1][0] = 2.0 * (q1q2 - q0q3);
  704.     m [2][0] = 2.0 * (q1q3 + q0q2);

  705.     m [0][1] = 2.0 * (q1q2 + q0q3);
  706.     m [1][1] = 2.0 * (q0q0 + q2q2) - 1.0;
  707.     m [2][1] = 2.0 * (q2q3 - q0q1);

  708.     m [0][2] = 2.0 * (q1q3 - q0q2);
  709.     m [1][2] = 2.0 * (q2q3 + q0q1);
  710.     m [2][2] = 2.0 * (q0q0 + q3q3) - 1.0;

  711.     return m;

  712.   }

  713.   /** Apply the rotation to a vector.
  714.    * @param u vector to apply the rotation to
  715.    * @return a new vector which is the image of u by the rotation
  716.    */
  717.   public Vector3D applyTo(Vector3D u) {

  718.     double x = u.getX();
  719.     double y = u.getY();
  720.     double z = u.getZ();

  721.     double s = q1 * x + q2 * y + q3 * z;

  722.     return new Vector3D(2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x,
  723.                         2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y,
  724.                         2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z);

  725.   }

  726.   /** Apply the rotation to a vector stored in an array.
  727.    * @param in an array with three items which stores vector to rotate
  728.    * @param out an array with three items to put result to (it can be the same
  729.    * array as in)
  730.    */
  731.   public void applyTo(final double[] in, final double[] out) {

  732.       final double x = in[0];
  733.       final double y = in[1];
  734.       final double z = in[2];

  735.       final double s = q1 * x + q2 * y + q3 * z;

  736.       out[0] = 2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x;
  737.       out[1] = 2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y;
  738.       out[2] = 2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z;

  739.   }

  740.   /** Apply the inverse of the rotation to a vector.
  741.    * @param u vector to apply the inverse of the rotation to
  742.    * @return a new vector which such that u is its image by the rotation
  743.    */
  744.   public Vector3D applyInverseTo(Vector3D u) {

  745.     double x = u.getX();
  746.     double y = u.getY();
  747.     double z = u.getZ();

  748.     double s = q1 * x + q2 * y + q3 * z;
  749.     double m0 = -q0;

  750.     return new Vector3D(2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x,
  751.                         2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y,
  752.                         2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z);

  753.   }

  754.   /** Apply the inverse of the rotation to a vector stored in an array.
  755.    * @param in an array with three items which stores vector to rotate
  756.    * @param out an array with three items to put result to (it can be the same
  757.    * array as in)
  758.    */
  759.   public void applyInverseTo(final double[] in, final double[] out) {

  760.       final double x = in[0];
  761.       final double y = in[1];
  762.       final double z = in[2];

  763.       final double s = q1 * x + q2 * y + q3 * z;
  764.       final double m0 = -q0;

  765.       out[0] = 2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x;
  766.       out[1] = 2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y;
  767.       out[2] = 2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z;

  768.   }

  769.   /** Apply the instance to another rotation.
  770.    * Applying the instance to a rotation is computing the composition
  771.    * in an order compliant with the following rule : let u be any
  772.    * vector and v its image by r (i.e. r.applyTo(u) = v), let w be the image
  773.    * of v by the instance (i.e. applyTo(v) = w), then w = comp.applyTo(u),
  774.    * where comp = applyTo(r).
  775.    * @param r rotation to apply the rotation to
  776.    * @return a new rotation which is the composition of r by the instance
  777.    */
  778.   public Rotation applyTo(Rotation r) {
  779.     return new Rotation(r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3),
  780.                         r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2),
  781.                         r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3),
  782.                         r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1),
  783.                         false);
  784.   }

  785.   /** Apply the inverse of the instance to another rotation.
  786.    * Applying the inverse of the instance to a rotation is computing
  787.    * the composition in an order compliant with the following rule :
  788.    * let u be any vector and v its image by r (i.e. r.applyTo(u) = v),
  789.    * let w be the inverse image of v by the instance
  790.    * (i.e. applyInverseTo(v) = w), then w = comp.applyTo(u), where
  791.    * comp = applyInverseTo(r).
  792.    * @param r rotation to apply the rotation to
  793.    * @return a new rotation which is the composition of r by the inverse
  794.    * of the instance
  795.    */
  796.   public Rotation applyInverseTo(Rotation r) {
  797.     return new Rotation(-r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3),
  798.                         -r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2),
  799.                         -r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3),
  800.                         -r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1),
  801.                         false);
  802.   }

  803.   /** Perfect orthogonality on a 3X3 matrix.
  804.    * @param m initial matrix (not exactly orthogonal)
  805.    * @param threshold convergence threshold for the iterative
  806.    * orthogonality correction (convergence is reached when the
  807.    * difference between two steps of the Frobenius norm of the
  808.    * correction is below this threshold)
  809.    * @return an orthogonal matrix close to m
  810.    * @exception NotARotationMatrixException if the matrix cannot be
  811.    * orthogonalized with the given threshold after 10 iterations
  812.    */
  813.   private double[][] orthogonalizeMatrix(double[][] m, double threshold)
  814.     throws NotARotationMatrixException {
  815.     double[] m0 = m[0];
  816.     double[] m1 = m[1];
  817.     double[] m2 = m[2];
  818.     double x00 = m0[0];
  819.     double x01 = m0[1];
  820.     double x02 = m0[2];
  821.     double x10 = m1[0];
  822.     double x11 = m1[1];
  823.     double x12 = m1[2];
  824.     double x20 = m2[0];
  825.     double x21 = m2[1];
  826.     double x22 = m2[2];
  827.     double fn = 0;
  828.     double fn1;

  829.     double[][] o = new double[3][3];
  830.     double[] o0 = o[0];
  831.     double[] o1 = o[1];
  832.     double[] o2 = o[2];

  833.     // iterative correction: Xn+1 = Xn - 0.5 * (Xn.Mt.Xn - M)
  834.     int i = 0;
  835.     while (++i < 11) {

  836.       // Mt.Xn
  837.       double mx00 = m0[0] * x00 + m1[0] * x10 + m2[0] * x20;
  838.       double mx10 = m0[1] * x00 + m1[1] * x10 + m2[1] * x20;
  839.       double mx20 = m0[2] * x00 + m1[2] * x10 + m2[2] * x20;
  840.       double mx01 = m0[0] * x01 + m1[0] * x11 + m2[0] * x21;
  841.       double mx11 = m0[1] * x01 + m1[1] * x11 + m2[1] * x21;
  842.       double mx21 = m0[2] * x01 + m1[2] * x11 + m2[2] * x21;
  843.       double mx02 = m0[0] * x02 + m1[0] * x12 + m2[0] * x22;
  844.       double mx12 = m0[1] * x02 + m1[1] * x12 + m2[1] * x22;
  845.       double mx22 = m0[2] * x02 + m1[2] * x12 + m2[2] * x22;

  846.       // Xn+1
  847.       o0[0] = x00 - 0.5 * (x00 * mx00 + x01 * mx10 + x02 * mx20 - m0[0]);
  848.       o0[1] = x01 - 0.5 * (x00 * mx01 + x01 * mx11 + x02 * mx21 - m0[1]);
  849.       o0[2] = x02 - 0.5 * (x00 * mx02 + x01 * mx12 + x02 * mx22 - m0[2]);
  850.       o1[0] = x10 - 0.5 * (x10 * mx00 + x11 * mx10 + x12 * mx20 - m1[0]);
  851.       o1[1] = x11 - 0.5 * (x10 * mx01 + x11 * mx11 + x12 * mx21 - m1[1]);
  852.       o1[2] = x12 - 0.5 * (x10 * mx02 + x11 * mx12 + x12 * mx22 - m1[2]);
  853.       o2[0] = x20 - 0.5 * (x20 * mx00 + x21 * mx10 + x22 * mx20 - m2[0]);
  854.       o2[1] = x21 - 0.5 * (x20 * mx01 + x21 * mx11 + x22 * mx21 - m2[1]);
  855.       o2[2] = x22 - 0.5 * (x20 * mx02 + x21 * mx12 + x22 * mx22 - m2[2]);

  856.       // correction on each elements
  857.       double corr00 = o0[0] - m0[0];
  858.       double corr01 = o0[1] - m0[1];
  859.       double corr02 = o0[2] - m0[2];
  860.       double corr10 = o1[0] - m1[0];
  861.       double corr11 = o1[1] - m1[1];
  862.       double corr12 = o1[2] - m1[2];
  863.       double corr20 = o2[0] - m2[0];
  864.       double corr21 = o2[1] - m2[1];
  865.       double corr22 = o2[2] - m2[2];

  866.       // Frobenius norm of the correction
  867.       fn1 = corr00 * corr00 + corr01 * corr01 + corr02 * corr02 +
  868.             corr10 * corr10 + corr11 * corr11 + corr12 * corr12 +
  869.             corr20 * corr20 + corr21 * corr21 + corr22 * corr22;

  870.       // convergence test
  871.       if (FastMath.abs(fn1 - fn) <= threshold) {
  872.           return o;
  873.       }

  874.       // prepare next iteration
  875.       x00 = o0[0];
  876.       x01 = o0[1];
  877.       x02 = o0[2];
  878.       x10 = o1[0];
  879.       x11 = o1[1];
  880.       x12 = o1[2];
  881.       x20 = o2[0];
  882.       x21 = o2[1];
  883.       x22 = o2[2];
  884.       fn  = fn1;

  885.     }

  886.     // the algorithm did not converge after 10 iterations
  887.     throw new NotARotationMatrixException(
  888.             LocalizedFormats.UNABLE_TO_ORTHOGONOLIZE_MATRIX,
  889.             i - 1);
  890.   }

  891.   /** Compute the <i>distance</i> between two rotations.
  892.    * <p>The <i>distance</i> is intended here as a way to check if two
  893.    * rotations are almost similar (i.e. they transform vectors the same way)
  894.    * or very different. It is mathematically defined as the angle of
  895.    * the rotation r that prepended to one of the rotations gives the other
  896.    * one:</p>
  897.    * <pre>
  898.    *        r<sub>1</sub>(r) = r<sub>2</sub>
  899.    * </pre>
  900.    * <p>This distance is an angle between 0 and &pi;. Its value is the smallest
  901.    * possible upper bound of the angle in radians between r<sub>1</sub>(v)
  902.    * and r<sub>2</sub>(v) for all possible vectors v. This upper bound is
  903.    * reached for some v. The distance is equal to 0 if and only if the two
  904.    * rotations are identical.</p>
  905.    * <p>Comparing two rotations should always be done using this value rather
  906.    * than for example comparing the components of the quaternions. It is much
  907.    * more stable, and has a geometric meaning. Also comparing quaternions
  908.    * components is error prone since for example quaternions (0.36, 0.48, -0.48, -0.64)
  909.    * and (-0.36, -0.48, 0.48, 0.64) represent exactly the same rotation despite
  910.    * their components are different (they are exact opposites).</p>
  911.    * @param r1 first rotation
  912.    * @param r2 second rotation
  913.    * @return <i>distance</i> between r1 and r2
  914.    */
  915.   public static double distance(Rotation r1, Rotation r2) {
  916.       return r1.applyInverseTo(r2).getAngle();
  917.   }

  918. }