Ingo said:
Hi,
Patricia said:
Anyone who thinks they are equivalent objects, try running this:
import java.math.BigDecimal;
public class TestBigDecimal {
public static void main(String[] args) {
System.out.println(new BigDecimal("1.0").
divide(new BigDecimal(3),BigDecimal.ROUND_HALF_EVEN));
System.out.println(new BigDecimal("1.00").
divide(new BigDecimal(3),BigDecimal.ROUND_HALF_EVEN));
}
}
If they really were equivalent, I would expect them to do the same for
anything other than the identity related operations, == comparison and
System.identityHashCode().
OK, that's perfectly right. But perhaps, only the specification of the
method divide() is not consistent. Perhaps it would have been better if
you would have been forced to explicitely name the scale of the result:
BigDecimal devide(BigDecimal d, RoundingMode r, scale s) {...}
So, I am not convinced that equals is implemented/specified
mathematically correct.
Or am I missing something?
You may be missing something that people have been missing, at times,
for at least 50 years.
The original Fortran type for floating point was called "REAL".
Unfortunately, this encouraged programmers to think of its arithmetic as
real arithmetic, instead of floating point arithmetic. Sometimes, that
got them into trouble because floating point arithmetic differs from
real arithmetic in some critical properties. For example, real addition
is always associative, floating point addition isn't.
You are confusing BigDecimal arithmetic with decimal fraction
arithmetic, and don't like it they turn out to be different, essentially
the same problem as confusing floating point and real arithmetic, and
being disturbed whenever (a+b)+c is different from a+(b+c).
If a BigDecimal were simply a decimal fraction, you would be right about
1.0 == 1.00, and the number would not have a scale attribute, so no
operation results would depend on scale.
A BigDecimal is not just a decimal fraction. BigDecimal is a different,
equally valid, system of arithmetic in which each number has a scale,
and results of arithmetic operations can depend on the scale. The scale
is a guide to the intended precision of the calculation, so it makes
sense to have options to round according to the current scale.
It is not a matter of "mathematically correct" because mathematics, no
matter how much it has to say about decimal fraction arithmetic, says
nothing about java.math.BigDecimal arithmetic. It is a matter of
defining an arithmetic system that is useful for certain purposes.
Of course, to some extent BigDecimal is a model of decimal fraction
arithmetic, but it has its own rules, designed to be useful in a range
of contexts.
Patricia