Skip to content
Numerical Method , home
Menu

Forum Numerical Method Linear Algebra

Vector.equals()

  1. kevinsunParticipant 2010-05-03 at 4:11 am

    Could anyone tell me how Vector.equals() checks the entries? Is there any precision tolerance for doubles?

    I have a problem here: A, B are Vector of doubles, for the code: assertTrue(A.toString().equals(B.toString())); assertTrue(A.equals(B)); I got True for the first line but False for the second.

    Any thought? Thx

  2. Haksun LiModerator 2010-05-04 at 2:20 pm

    The way you do eqality checking for Vector is wrong.

    To check to see if two vectors are absolutely equal, you may do as follows.

    <br />
            Vector v1 = new Vector(new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});<br />
            Vector v2 = new Vector(new double[]{11, 12, 13});<br />
            v1.set(1, v2);<br />
            assertEquals(new Vector(new double[]{11, 12, 13, 4, 5, 6, 7, 8, 9, 10}), v1);<br />
    

    Note that the numerical values must have exactly the same binary representations in memory for this to work. The equality check method is essentially an override of

    <br />
           Object.equals(Object obj)<br />
    

    To allow a precision parameter in the “equality” checking, which is most often the case in numerical computing, you may do:

    <br />
            Vector v1 = new Vector(1, 2, 3);<br />
            Vector v2 = new Vector(1 + 1e-20, 2, 3);<br />
            assertTrue(VectorOp.equal(v1, v2, 1e-15));<br />
    
  3. Haksun LiModerator 2010-05-08 at 5:26 pm

    The method to check [tt:1n1cmq34]Matrix[/tt:1n1cmq34] equality with a precision is:

    public static boolean equal(DoubleMatrix< ?> A1, DoubleMatrix< ?> A2, double epsilon)

    Check the equality of two matrices. Two matrices are equal iff 1.the dimensions are the same; 2.all entries are equal Parameters: A1 – a matrix A2 – a matrix epsilon – a precision parameter: when a number |x| ≤ ε, it is considered 0 Returns: true iff all entries are equal, entry by entry

    For example, in JUnit test cases, we write:

    <br />
    assertTrue(Are.equal(Aexpected, A, 1e-14));<br />