Commons Math
  1. Commons Math
  2. MATH-1118

Complex: semantics of equals != Double equals, mismatch with hashCode

    Details

    • Type: Bug Bug
    • Status: Closed
    • Priority: Major Major
    • Resolution: Fixed
    • Affects Version/s: 3.2
    • Fix Version/s: 3.3
    • Labels:
      None
    • Environment:

      Mac OS 10.9, Java 6, 7

      Description

      Two complex numbers with real/imaginary parts 0.0d but different signs compare as equal numbers. This is according to their mathematical value; the comparison is done via

      return (real == c.real) && (imaginary == c.imaginary);

      Unfortunately, two Double values do NOT compare as equal in that case, so real.equals(c.real) would return false if the signs differ.

      This becomes a problem because for the hashCode, MathUtils.hash is used on the real and imaginary parts, which in turn uses Double.hash.

      This violates the contract on equals/hashCode, so Complex numbers cannot be used in a hashtable or similar data structure:

      Complex c1 = new Complex(0.0, 0.0);
      Complex c2 = new Complex(0.0, -0.0);
      // Checks the contract: equals-hashcode on c1 and c2
      assertTrue("Contract failed: equals-hashcode on c1 and c2", c1.equals(c2) ? c1.hashCode() == c2.hashCode() : true);

      1. Report5.java
        0.4 kB
        Cyrille Artho
      2. Report5a.java
        0.5 kB
        Cyrille Artho
      3. MATH-1118.patch
        4 kB
        Gilles
      4. MATH-1118.patch
        10 kB
        Gilles

        Activity

          People

          • Assignee:
            Unassigned
            Reporter:
            Cyrille Artho
          • Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

            Dates

            • Created:
              Updated:
              Resolved:

              Development