Search code examples
javamathcomparisoncomparablequaternions

Quaternion Comparison?


Is quaternion comparison possible? I'm writing a Java class of Quaternions and I want to implement the Comparable interface to use the Collections.sort(List<Quaternion>) facility. I'm not expert at math, I really don't understand the things I read about Quaternions. So, can anyone tell me can I override the compareTo method for Quaternions and how?

My class declarition:

public class Quaternion implements Serializable, Comparable<Quaternion> {

    private double s; // scalar part
    private double i, j, k; // vectorel part


    public Quaternion() {
        super();
    }

    public Quaternion(double s, double i, double j, double k) {
        super();
        this.s = s;
        this.i = i;
        this.j = j;
        this.k = k;
    }

Solution

  • There is no reason why you can't compare two quaternions. Assuming that you want to compare magnitudes, compute and compare the Quaternion Norms. Your Quaternion class should have a norm (magnitude) method allowing a toCompare to be something like the following:

    int compareTo(Quaternion o){
      return (int)(this.norm() - o.norm());
    }
    

    A better version would be:

    int compareTo(Quaternion o){
      // return (int)(this.norm() - o.norm());
      double tNorm = this.norm;
      double oNorm = o.norm;
      int retVal = 0;
    
      if (tNorm < oNorm){
        retVal = -1;
      } else if (tNorm > oNorm){
        retVal = 1;
      }
    
      return retVal;
    }