ocean #6313(2008/05/21 05:42 GMT) [ Python ] Rating0/0=0.00
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
def gcd(m, n): assert m > 0 assert n > 0 while n: m, n = n, m % n assert m > 0 return m class Rational: def __init__(self, b, c): g = gcd(b, c) self.b = b // g self.c = c // g def __repr__(self): return "%d/%d" % (self.b, self.c) def __cmp__(self, that): return self.b * that.c - self.c * that.b def value(self): return float(self.b) / self.c def rationalize(a): rationals = [] for c in xrange(1, 10): b = int(a * c + 0.5) r = Rational(b, c) if r.b == b: rationals.append(r) rationals.sort(key=lambda r: abs(a - r.value())) return rationals def solve(a): print "a = %f" % a, " ".join(repr(r) for r in rationalize(a)) def main(): solve(1.732051) solve(3.141593) solve(1920.0 / 1080) if __name__ == '__main__': main()
Rating0/0=0.00-0+
[ reply ]
ocean
#6313()
[
Python
]
Rating0/0=0.00
Rating0/0=0.00-0+
[ reply ]