Here's a good learning point. Be aware that Groovy additionally makes some object changes to what you're probably assuming are primitive doubles.
There's a consequence that isn't blatantly obvious in the two snippets below:
... new BigDecimal(a, mathContext) ...
... new BigDecimal(b, mathContext) ...
There is no constructor for BigDecimal that takes a (BigDecimal, MathContext)!!! Why isn't this throwing an exception? Groovy is automatically changing types under the covers for... um... convenience. Let's look at example to see what kinds of things Groovy does under the covers.
Consider the following code:
MathContext mathContext = new MathContext(5, RoundingMode.DOWN)
println 5.6789
println new BigDecimal(5.6789)
println new BigDecimal(5.6789, mathContext)
In the first print line, Groovy automatically treats 5.6789 as a BigDecimal under the covers. You can confirm this with
println ((5.6789).class) which will print out that the type is BigDecimal.
In the second print line, we now know that the 5.6789 is already a BigDecimal. However, there is no constructor for BigDecimal that accepts another BigDecimal... so Groovy forces our value into a double to satisfy the constructor. This sends the precision into absolute craziness and we get 5.67889999999999961488583721802569925785064697265625 in the console.
The third print line is where things get dangerous because the MathContext is going to hide the precision craziness we saw from line 2. It prints 5.6788 - which is .0001 off from what we expected.
So what could be done differently in your code?
Notice that I went straight for a.divide and b.divide.
Also, I'm using a little trick to make Groovy treat my 100 values as BigDecimals. If I hadn't done this, Groovy would have treated them as BigInteger. I code have alternatively made them 100.0 (with the decimal) and Groovy would have treated them as BigDecimal automatically.
Tricky, huh?
