Fix-up signature for approximation.

This commit is contained in:
Raymond Hettinger 2008-01-25 01:23:38 +00:00
parent 7ea82253ea
commit 9c6d81f5dd
2 changed files with 10 additions and 9 deletions

View File

@ -195,16 +195,17 @@ class Rational(RationalAbc):
n, d = d, n
return cf
@classmethod
def approximate_from_float(cls, f, max_denominator):
'Best rational approximation to f with a denominator <= max_denominator'
def approximate(self, max_denominator):
'Best rational approximation with a denominator <= max_denominator'
# XXX First cut at algorithm
# Still needs rounding rules as specified at
# http://en.wikipedia.org/wiki/Continued_fraction
cf = cls.from_float(f).as_continued_fraction()
if self.denominator <= max_denominator:
return self
cf = self.as_continued_fraction()
result = Rational(0)
for i in range(1, len(cf)):
new = cls.from_continued_fraction(cf[:i])
new = self.from_continued_fraction(cf[:i])
if new.denominator > max_denominator:
break
result = new

View File

@ -155,10 +155,10 @@ class RationalTest(unittest.TestCase):
[-4, 1, 6, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, 3])
self.assertEqual(R(0).as_continued_fraction(), [0])
def testApproximateFromFloat(self):
self.assertEqual(R.approximate_from_float(math.pi, 10000), R(355, 113))
self.assertEqual(R.approximate_from_float(-math.pi, 10000), R(-355, 113))
self.assertEqual(R.approximate_from_float(0.0, 10000), R(0))
def testApproximateFrom(self):
self.assertEqual(R.from_float(math.pi).approximate(10000), R(355, 113))
self.assertEqual(R.from_float(-math.pi).approximate(10000), R(-355, 113))
self.assertEqual(R.from_float(0.0).approximate(10000), R(0))
def testConversions(self):
self.assertTypedEquals(-1, trunc(R(-11, 10)))