chen870647924 / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Doubles/Float: methods with error margin #864

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I think a few new methods would make a small but nice addition to the primitive 
API. It's often useful not to compare two doubles, but check if they have 
similarities up to a degree. This is based on the fact that the double and 
floats are not precise enough and after some computing the values may be 
different from what we expect, such as the following methods:

double d = 0.0;
for (int i = 0; i < 10; i++) {
  d -= 0.1;
}
assertTrue(1.0 == d); // fails.

Suggested methods:

int Doubles.compare(double a, double b, double errorMargin)
boolean Doubles.contains(double[] array, double target, double errorMargin)
boolean Doubles.equal(double a, double b, double errorMargin)

int Floats.compare(float a, float b, float errorMargin)
boolean Floats.contains(float[] array, float target, float errorMargin)
boolean Floats.equal(float a, float b, float errorMargin)

There is still the question about which double/float-comparison to use: the 
primitive one or the wrapper one (which are different from a NaN point of view).

Original issue reported on code.google.com by ogregoire on 11 Jan 2012 at 2:10

GoogleCodeExporter commented 9 years ago
Sorry, the code presented should read

double d = 0.0;
for (int i = 0; i < 10; i++) {
  d += 0.1;
}
assertTrue(1.0 == d); // fails.

A typo when manually copying the code.

Original comment by ogregoire on 11 Jan 2012 at 2:24

GoogleCodeExporter commented 9 years ago
This issue is already pending...on choosing good method names.  (The hardest 
part of API design.)

Original comment by wasserman.louis on 11 Jan 2012 at 5:09

GoogleCodeExporter commented 9 years ago
This issue is already pending...on choosing good method names.  (The hardest 
part of API design.)

Original comment by wasserman.louis on 11 Jan 2012 at 5:09

GoogleCodeExporter commented 9 years ago
Sorry for that, I searched on "compare", but nothing similar showed up... I 
should have been more thorough.

Original comment by ogregoire on 11 Jan 2012 at 5:13

GoogleCodeExporter commented 9 years ago
A dup every now and then is *really* not a big problem :-)

Original comment by kevinb@google.com on 13 Jan 2012 at 5:32

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:14

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:09