Comparing two numbers algorithm not working c#


I´m trying to make a simple comparison in a List with ‘n’ elements that has two different types of numbers (6 and 12)

      List<double> one = new List<double>();
      List<double> two = new List<double>();
      for (int j = 0; j < lengths.Count; j++)
        if (lengths[0] == lengths[j])
      A = one;
      B = two;

For some reason, the algorithm finds just one equivalence ( comparison between 0 and itself) and all the rest of the numbers in the List are marked as different.
The logic seems to be ok to me. I don’t know if it’s a problem with the comparison operator, I also tried using .Equals and it’s not working either.
Any ideas?

Welcome to the computing world of floating-points. Especially after operations on floating point numbers you can not directly compare numbers like that. You have to do a “fuzzy equal” check instead. There are several ways to do that, the simplest one is to subtract the two numbers, take the absolute value of that result and see if that is smaller than epsilon, a small value you choose to work well enough for your purposes.

Search our forum (and the internet) for past discussions on this topic.

My favorite post on this issue is still this Mesh.Vertices accuracy seems wrong, why? Letwory, along with the reply to it.

1 Like

Also, not sure I get what you do in your list element comparison. You always check only each element to the very first of the same list?

Only compare integer types without an epsilon comparison, so you would do something like Math.Abs( lengths[0] - lengths[j] ) < epsilon Where epsilon = 1e3 or preferably the document’s tolerance epsilon = Rhino.RhinoApp.RhinoDoc.ModelAbsoluteTolerance

Thanks for the reply Nathan. Very useful information I wasn’t aware of ( obvoiusly :sweat_smile:)

1 Like

Muchas Gracias Felipe !!! :pray:

1 Like