Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I found the same paper that Matt referenced, and I took a second and implemented it in Python. Maybe seeing the same idea in code will make it clearer. Granted, you requested an answer in C# and I'm giving it to you in Python, but it's a fairly trivial program, and I'm sure it would be easy to translate. The parameters are <code>num</code> (the decimal number you'd like to convert to a rational) and <code>epsilon</code> (the maximum allowed difference between <code>num</code> and the calculated rational). Some quick test runs find that it usually only takes two or three iterations to converge when <code>epsilon</code> is around 1e-4.</p> <pre><code>def dec2frac(num, epsilon, max_iter=20): d = [0, 1] + ([0] * max_iter) z = num n = 1 t = 1 while num and t &lt; max_iter and abs(n/d[t] - num) &gt; epsilon: t += 1 z = 1/(z - int(z)) d[t] = d[t-1] * int(z) + d[t-2] # int(x + 0.5) is equivalent to rounding x. n = int(num * d[t] + 0.5) return n, d[t] </code></pre> <p>Edit: I just noticed your note about wanting them to work with recurring decimals. I don't know any languages that have syntax to support recurring decimals, so I'm not sure how one would go about handling them, but running 0.6666666 and 0.166666 through this method return the correct results (2/3 and 1/6, respectively).</p> <p>Another Edit (I didn't think this would be so interesting!): If you want to know more about the theory behind this algorithm, <a href="http://en.wikipedia.org/wiki/Euclidean_algorithm" rel="noreferrer">Wikipedia has an excellent page on the Euclidian algorithm</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload