Why does the BigFraction class in the Apache-Commons-Math library return incorrect division results?

Posted by Timothy Lee Russell on Stack Overflow See other posts from Stack Overflow or by Timothy Lee Russell
Published on 2010-05-14T06:45:16Z Indexed on 2010/05/14 6:54 UTC
Read the original article Hit count: 300

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

© Stack Overflow or respective owner

Related posts about apache-commons-math

Related posts about java