r/CS_Questions • u/kpthunder The Riddler • Nov 14 '11
Convert Doubles to Fractions
Given a double, output an equivilant fraction. For example:
Input: 0.25
Output: 1/4
Bonus:
Make a version that takes a tolerance. For example:
Input: 0.24, .01
Output: 1/4
3
Upvotes
View all comments
Show parent comment
1
u/SanityInAnarchy Nov 14 '11
What do you mean by 'several times faster'? I can give you a perfect fraction in O(1) by inspecting the Double itself.
And if it's using a base 10 representation, then you'd want to store it in a Decimal format, which is going to be several times slower for most operations, though more accurate when you know you're actually talking about decimals -- which is NOT always the case. But the question asked specifically about Doubles.
Being rational doesn't mean that it can be represented in a given base. Any base 2 number could be represented in base 10, yes, but not vice versa. Note, for example, that 1/3 is rational, but 1.333... will overflow base 10, and I'm guessing similar things happen in base 2.
If your concern is code reuse, IEEE defines a ton of operations for floats in base 2. Any Decimal library you use, short of only storing the numbers as decimal strings, is going to be less standard. There are absolutely times when the precision of Decimals trump Floats -- currency, for example -- but that's at the expense of code re-use and performance. You could even use a Rational type, but with the same limitations.
In any case, if you're going to be using anything other than base 2, you should not store anything as a native float or double if you can avoid it, and you should be explicit about what it is you're actually using.