[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [Newsgroup Home]
[news.eclipse.platform.rcp] Re: compare float numbers with precision

Stella wrote:
Hi, in my rcp I need a way to compare files with floating numbers with certain precision, i.e. if difference between numbers in some place is less than precision value - don't show the difference. What is the simplest way to do it? I looked to org.eclipse.compare plugin, I don't find extension point to change a way to calculate difference.
Any suggestions for the way to do it? Thanks, Stella

Please define "simple". The most simple approach is e.g. an implemention Comparator#compare with an absolute threshold:

public class AbsToleranceComparator implements Comparator<Double> {

	private final double threshold;

	public AbsToleranceComparator(double threshold) {
		assert threshold >= 0;
		this.threshold = threshold;
	}

	@Override
	public int compare(Double o1, Double o2) {
		double diff = o1 - o2;
		return Math.abs(diff) < threshold ? 0 :
                       Double.compare(diff, 0.0);
	}

}

This is "simple", but it does not properly consider null values, overflow, NaNs and Infs. It has only a special use-case, where
absolute differences are correct, but that doesn't mean that
this is your use-case. I know many use-cases, which would be e.g.
be based on a relative difference criterion, where maybe support
for nullable values or maybe for infinities and NaNs requires
special handling.


HTH & Greetings from Bremen,

Daniel Krügler