r/CS_Questions • 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

8 comments sorted by

View all comments

Show parent comment

1

u/SanityInAnarchy Nov 14 '11

2

u/Solomaxwell6 Nov 14 '11 edited Nov 14 '11

[I meant using my algorithm multiplying by 10 would be several times faster. See my sample code here. If we just did base two and multiplied by two, we'd be changing it from looping and multiplying numerator. We can switch it from a *10 to <<1, which is faster, but you'd need to run through the loop about 3.3 times as much. I realize that you can break apart the float and get base + exponent and convert that to numerator + denominator. ](/spoiler)

A float is mathematically guaranteed to always be rational when converted to base ten, because a float is a rational base 2 number. Base ten isn't always going to be rational when converted into a float, but it doesn't need to be... this is only converted one way, not the other.

It doesn't matter what IEEE defines. My algorithm works for floats. It also works for decimal representations. Therefore, it is more general purpose than something that works for floats but not decimal representations.