Given a floating point number, I'm looking to get a String
representation of a rational number approximating the decimal (to within a given tolerance ε is fine). My current approach is as follows:
String rationalize(double d)
{
String s = Double.toString(d);
s = s.substring(s.indexOf('.')+1, s.length());
return s + " / " + ApintMath.pow(new Apint(10), s.length()).toString();
}
If you're unfamiliar with it, ApintMath.pow
will work even with arbitrarily long numbers, which is good because I'm attempting to convert decimals with thousands of decimal places. The performance of my algorithm is terrible.
I attribute this to two things, but there could be more:
How would you do this? Are there other areas I haven't talked about that are slowing me down?
There's a Stern–Brocot tree implementation shown here, but you'll have to profile to see which is better.
Addendum: I've had good results using org.jscience.mathematics.number.Rational
in linear systems; org.apache.commons.math.fraction.BigFraction
offers several constructors for double
that may be useful. All throw suitable exceptions for undefined values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With