I have a method in java that returns a double number and I want to compare every double number that is returned every time I call the method(say 5 times), so that I can conclude that the number returned is almost the same every time.
How can I do this?
It depends on what you mean by similar. If you want to compare two numbers within an absolute error e.g. 1e-6 you can use epsilon. If you want to compare two
double
regardless of scale. e.g. 1.1e-20 and 1.3e-20 are not similar but 1.1e20 and 1.1e20+1e5 are you can compare the raw value.prints
Where eps is measure of equality.
Approximate equality is defined in terms of the absolute difference: if an absolute difference does not exceed a certain, presumably small, number, then you can say that the values you are comparing are "close enough".
You must be very careful to not confuse "close enough" end "equals", because the two are fundamentally different: equality is transitive (i.e. a==b and b==c together imply that a==c), while "close enough" is not transitive.
You must first decide what "almost the same" means. For example, there's a method in
java.lang.Math
called ulp() which, given a double, returns the distance between that double and the next; i.e., the smallest possible difference between that number and any other. You might simply compare the difference between the two doubles and the result of calling that method.On the other hand, maybe you want two numbers to just be within 1% of eachother. In that case, do the same computation, but use the first number multiplied by
0.01
instead ofulp()
as the largest acceptable distance.You could use Guava and
DoubleMath#fuzzyEquals
method (since version 13.0):Link to docs: https://google.github.io/guava/releases/17.0/api/docs/com/google/common/math/DoubleMath.html
What does it mean for two doubles to be "approximately equal?" It means that the doubles are within some tolerance of each other. The size of that tolerance, and whether that tolerance is expressed as an absolute number or as a percentage of the two doubles, depends on your application.
For instance, two photos displayed on a photo viewer have approximately the same width in inches if they take up the same number of pixels on the screen, so your tolerance will be an absolute number calculated based on pixel size for your screen. On the other hand, two financial firms' profits are probably "approximately equal" if they are within 0.1% of each other. These are just hypothetical examples, but the point is that it depends on your application.
Now for some implementation. Let's say your application calls for an absolute tolerance. Then you can use
to compare two doubles, and use
to compare five doubles.