In java, double takes 64 bits, but stores (or computes with) numbers unprecisely. E.g. the following code:
double a = 10.125d;
double b = 7.065d;
System.out.println(a-b);
prints out 3.0599999999999996
rather than 3.06
.
So, the question - what about utilizing those 64 bits to store two 32-bit integers (first to represent the whole part, second the decimal part)? Then calculations would be precise, right?
The naive pseudo-code implementation with unhandled decimal transfer:
primitive double {
int wholePart;
int decimalPart;
public double + (double other) {
return double (this.wholePart + other.wholePart, this.decimalPart + other.decimalPart);
}
//other methods in the same fashion
public String toString() {
return wholePart + "." + decimalPart;
}
}
Is there a reason for Java to store double unprecisely and not to use the implementation mentioned above?