#!/usr/bin/python
"""This little guy figures out the best ratio of integers to achieve some rational number.
This is useful for machines without floating point, or for designing digital phase locked loops.

Pat Beirne, (c) 2009
released under GPL2
"""

import os, cgi, cgitb
form = cgi.FieldStorage()

print("Content-type: text/html\n")
print("<html><head><title>results</title></head><body>")
print("<h2>Results</h2>")

# just testing..........
#f = 3.1415926535897932384626433832

f = float(form.getvalue('ratio'))
max_i = int(form.getvalue('max_i'))

e_max = 1
e_2nd_max = 1
i_hit = -1
d_hit = -1

# check every denominator
for i in range(2,max_i):
  m = f*i
  d = round(m)
  e = abs((m-d)/m)
  if (e<e_max-1e-12):
    # save 2nd best
    i_2nd_best = i_hit
    d_2nd_best = d_hit
    # copy the new candidate into the _hit variables
    i_hit = i
    d_hit = d
    e_max = e
  
print("<h3>Best match</h3>")
print("<table>")
print("<tr><td>Target ratio: </td><td>%.10f</td></tr>" % f)
print("<tr><td>Best integer ratio: </td><td>%d / %d</td></tr>" % (d_hit, i_hit))
print("<tr><td>Integer ratio: </td><td>%.10f (%f%% error from target)</td></tr></table>" % (float(d_hit)/float(i_hit), e_max*100))

if i_2nd_best != -1:
  print("<h3>2nd best match</h3>")
  print("<p><table>")
  print("<tr><td>Target ratio: </td><td>%.10f</td></tr>" % f)
  print("<tr><td>2nd best integer ratio: </td><td>%d / %d</td></tr>" % (d_2nd_best,i_2nd_best))
  e = abs(1-float(d_2nd_best)/float(i_2nd_best)/f)
  print("<tr><td>Integer ratio: </td><td>%.10f (%f%% error from target)</td></tr></table>" % (float(d_2nd_best)/float(i_2nd_best), e*100))

            
print("</body></html>")
            