How to extract fraction from a floating point number I'm making some tests with float type (floating point number) with programming and in some of my tests I need to extract the fraction that originates the float value.
Let $ x $ be a floating point number, and $ a, b \in \mathbb{Z} $, where $ x \approxeq \frac{a}{b} $, I want to discover $ a $ and $ b $.
e.g., if I have $ 0.5 $, I need a method (maybe numerical?) that gives me $ \frac{1}{2} $ or some of its multiples.
If there's more than one method, I would like the fastest or simples to implement with a programming languagg.
 A: My favorite method would be continued fractions.
If the fraction is exact the process will (should! ;-)) converge :
(illustrations using the free pari/gp)

contfrac(0.14285)
  = [0, 7, 2857]

with the exact answer : $0+\dfrac 1{7+\dfrac 1{2857}}=\dfrac{2857}{20000}$
else you'll get a large integer after some terms (the difficult part is to decide when the number becomes large!) and should just ignore it (and the next terms) :

contfrac(0.142857142)
  = [0, 7, 23809523, 1, 2]

so that the answer will be nearly $\;0+\dfrac 17$
A: Let $P=10^n$ where $10^{-n}$ denotes the precision of the floating point number. Compute the greatest common divisor of $G=Gcd(P\cdot F,P)$, where $F$ is the floating point number. 
Then the answer is $\displaystyle\frac{F/G}{P/G}$.
A: If you are given $0.5$, you are really given $0.5000000000000$. You can find what fraction this is simply by writing the fraction
$$\frac{5000000000000}{10000000000000} = \frac{5}{10} = \frac12$$
A: If your decimal is terminating, you only have to take it's number as the numerator and the respective power as the denominator. If it is recurring, but 1 complete set of recurring digits is given, there is a simple method given here. Your program may have to identify the no. of digits being repeated first. If even 1 complete set of recurring digits is not given, you can assume it to be terminating and give an approximate fraction (equal to the visible digits of the decimal).
