2

I have a method to check for equality of 2 double[]'s with a tolerance between each element. I'd like to make this faster and am wondering if there is a way to do this without a for loop. I've been searching but can't find something that does this. The Arrays.equals() or deepEquals() doesn't seem to take a tolerance for double equality. Any suggestions? This is what I have currently:

private boolean myEquals(double[] array1, double[] array2)
   {
    if(array1.length == array2.length)
    {
       for(int i = 0; i < array1.length; i++)
       {
        if(Math.abs(array1[i] - array2[i]) > 0.01)
        {
           return false;
        }
       }
    }
    else
    {
       return false;
    }
    return true;
   }
Steve W
  • 1,108
  • 3
  • 13
  • 35
  • 1
    https://stackoverflow.com/questions/9090500/how-to-compare-that-sequence-of-doubles-are-all-approximately-equal-in-java – assylias Jan 18 '18 at 12:08

1 Answers1

0

I don't see how you can avoid iterating over all elements. Look at Arrays.equals(), this is exactly how it's done there... However, you should also check for nullity of each of the arrays, otherwise you may get NullPointerException

Lior Chaga
  • 1,424
  • 2
  • 21
  • 35
  • I wondered if maybe there is some way to do an element wise subtraction of one array from the other, then sum the absolute values in the resulting array and compare that answer to the tolerance. – Steve W Jan 18 '18 at 12:23
  • Unfortunately it won't work for you. The minimum iterations you would have to do is O(n). If you try any kind of summing the values and comparing the results you won't have any guarantees. As @Lion Chaga said you have to check for null values as well. – dbl Jan 18 '18 at 13:18
  • Also if you consider replacing the for-loop with streams make sure you do a research on the topic. Here is just a starter link ;) GL! https://jaxenter.com/java-performance-tutorial-how-fast-are-the-java-8-streams-118830.html – dbl Jan 18 '18 at 13:22