Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to compare two arrays or lists of doubles to see if one list has any of the other list's numbers within some tolerance say 0.005...What is the fastest way to do this? A small example would be great!
Thanks!

What I have tried:

I haven't tried anything which is why I'm asking
Posted
Updated 29-Mar-16 0:31am
Comments
Patrice T 28-Mar-16 13:20pm    
Read your question with the spirit of someone that have no clue on the problem, is it clear ?
Use Improve question to update your question.

You could try to create a custom made extension method to check a number in a list with tolerance:
C#
public static class Utility
{
   public static bool HasApproachingValue(this double[] array, double value, double precision) {
      bool result = false;
      for (int i = 0; i < array.Length; i++) {
         if (Math.Abs(array[i] - value) < precision) {
            result = true;
            break;
         }
      }
      return result;
   }
}

Which you could use like that:
C#
double[] firstList;
double[] secondList; // These list should be initialized with values
double precision = 0.005d;
for (int i = 0; i < firstList.Length; i++) {
   if (secondList.HasApproachingValue(firstList[i], precision)) {
      // Here's a match
      break;
   }
}

The worst-case scenario will be when there is no match, as there will be (firstList.Length * secondList.Length) occurrences.
Hope this helps.
 
Share this answer
 
Here's an example as a function. This is exclusive, but you can change that if need be.

C#
bool IsTolerant(double[] array1, double[] array2)
{
    for (int i = 0; i < array1.Length; i++)
    {
         for (int j = 0; j < array2.Length; j++)
         {
              double dif = Math.Abs(array1[i] - array2[j]);
              if (dif < 0.005)
              {
                  return true;
              }
          }
    }

    return false;
}


Edit: Misread question.
 
Share this answer
 
v7
Comments
Patrice T 29-Mar-16 0:33am    
The function don't compare 2 lists !
[no name] 29-Mar-16 7:50am    
First I also thought this is wrong. After reading the question again, I think this is correct.

"....to see if one list has __any__ of the other list's numbers ..."
Patrice T 29-Mar-16 7:57am    
possible bad wording.
Also saying "I want to compare two arrays or lists"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900