Why does the BigFraction class in the Apache-Commons-Math library return incorrect division results?
- by Timothy Lee Russell
In the spirit of using existing, tested and stable libraries of code, I started using the Apache-Commons-Math library and its BigFraction class to perform some rational calculations for an Android app I'm writing called RationalCalc.
It works great for every task that I have thrown at it, except for one nagging problem. When dividing certain BigFraction values, I am getting incorrect results.
If I create a BigFraction with the inverse of the divisor and multiply instead, I get the same incorrect answer but perhaps that is what the library is doing internally anyway.
Does anyone know what I am doing wrong?
The division works correctly with a BigFraction of 2.5 but not 2.51, 2.49, etc...
// *** incorrect! ***
BigFraction one = new BigFraction(1.524);
//one: 1715871458028159 / 1125899906842624
BigFraction two = new BigFraction(2.51);
//two: 1413004383087493 / 562949953421312
BigFraction three = one.divide(two);
//three: 0
Log.i("solve", three.toString());
//should be 0.607171315 ??
//returns 0
// *** correct! ****
BigFraction four = new BigFraction(1.524);
//four: 1715871458028159 / 1125899906842624
BigFraction five = new BigFraction(2.5);
//five: 5 / 2
BigFraction six = four.divide(five);
//six: 1715871458028159 / 2814749767106560
Log.i("solve", six.toString());
//should be 0.6096 ??
//returns 0.6096