lishunli / projectlombok

Automatically exported from code.google.com/p/projectlombok
0 stars 0 forks source link

@EqualsAndHashCode comparing double values that are equal to the nth digit #517

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Create a class having a double instance variable
2. Add @EqualsAndHashCode to the class
3. Compare two objects having double values that are identical up to the 13th 
digit after the decimal but differ on the 14th digit.

What is the expected output? What do you see instead?

equals returns false even though I want both double values to be considered 
equal as long as they are identical down to, say, the 10th digit after the 
decimal point.

What version of the product are you using? On what operating system?
Latest on Windows

Please provide any additional information below.

I suggest adding the doublePrecision=XX optional argument to the 
@EqualsAndHashCode annotation, where XX is the number of digits after the 
decimal point up to which two double values should be checked for equality.

When the option is not provided, Lombok would continue using Double.compare, 
and when the option is set it would generate something like this:

public static final double PRECISION_TOLERANCE = 1e-10;
public static boolean equals(double d1, double d2) {
    return (((d1 + PRECISION_TOLERANCE) > d2) && ((d1 - PRECISION_TOLERANCE) < d2));
  }

The 10 in 1e-10 in the example above would be set to the XX parameter provided 
in the annotation.

Original issue reported on code.google.com by ube...@gmail.com on 14 May 2013 at 2:28

GoogleCodeExporter commented 9 years ago
base-10 tolerance doesn't work, obviously - computers count in binary. But, a 
maximum difference would be fine (something like 
@EqualsAndHashCode(tolerance=0.000001) or @EqualsAndHashCode(tolerance=1e-10)).

We'd then generate (pseudocode): if (Math.abs(a-b) < tolerance) 
concludeAandBareEffectivelyEqual();

Sounds probably okay, but, it's a rarely used setting. There are a lot of these 
tiny cornercase situations, and if we allow for a setting on all of them, then 
at some point @EqAHC has 35 settings, and I think the current situation is 
better than that. Even if just because supporting all those options would 
become an issue.

Furthermore, the general idea behind equals and hashCode implementations is 
that you will use instances of this class in hashmaps or hashsets and the like. 
Putting doubles/floats in objects that are intended to be keys in maps/sets 
just seems like a really bad idea, which is why I'm not so sure we'd even want 
this.

Unfortunately, we've got a list of feature requests as long as my leg, and I 
don't think this one is going to make the cut.

Original comment by reini...@gmail.com on 16 May 2013 at 5:43