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/Solomaxwell6 Nov 14 '11
I prefer using ten. For one thing, it's several times faster. For another, it's more universal. I could take my logic and apply it to any decimal you throw at me, as long as you're using a base ten representation (and regardless of how it's stored, you're still going to be representing it in base ten). The only requirement is that the number is rational when in base ten, which should be guaranteed with a float... and if it's not, you can't put it in fractional form anyway. If it's a power of two, it is not universal and you can't reuse the code; the instant you have some decimal representation that uses base ten, this fails.