I have a set of numbers with varying precision. I need to create a hashkey out of them.
This code shows that the numbers are equal (at the relevant precision). So, what is a hash function that returns equal value for equal numbers?
int prec = 2;
double val=12.3456;
int digits = (int)Math.log(val);
MathContext mc = new MathContext(digits+prec);
BigDecimal bd = new BigDecimal(12.3020, mc);
System.out.println("Value A:"+bd.toString());
MathContext mcx = new MathContext(digits+prec-1);
BigDecimal bdx = new BigDecimal(12.3170, mcx);
System.out.println("Value A:"+bdx.toString());
System.out.println("Difference is:"+bdx.compareTo(bd));
System.out.println("HashCode A:"+bd.hashCode());
System.out.println("HashCode B:"+bdx.hashCode());
BTW, BigDecimal didn’t work out of the box for me, because 12.34 @ 2 precision was 12 … I need the precision to effect everything past the decimal point. (So, is there a more appropriate library class for this?)
One answer that seems to work is:
Let me know if this is somehow wrong.