#!/usr/bin/ruby -w TARGET_FREQ = ARGV.shift.to_f NATIVE_FREQ = 50.0 CLOCK_WIDTH = 5 best = nil best_mult = nil best_div = nil 1.upto(2**CLOCK_WIDTH) do | mult | 1.upto(2**CLOCK_WIDTH) do | div | new = NATIVE_FREQ * mult / div if not best or (new - TARGET_FREQ).abs < (best - TARGET_FREQ).abs or ((new - TARGET_FREQ).abs == (best - TARGET_FREQ).abs and (mult + div) < (best_mult + best_div)) best = new best_mult = mult best_div = div end end end error = (best - TARGET_FREQ).abs / TARGET_FREQ $stdout.write("Closest I can get is #{best}: *#{best_mult} /#{best_div} (#{(error * 100).round}% error)\n")