]> granicus.if.org Git - python/commitdiff
Fix-up signature for approximation.
authorRaymond Hettinger <python@rcn.com>
Fri, 25 Jan 2008 01:23:38 +0000 (01:23 +0000)
committerRaymond Hettinger <python@rcn.com>
Fri, 25 Jan 2008 01:23:38 +0000 (01:23 +0000)
Lib/rational.py
Lib/test/test_rational.py

index 40b91635d34266e888fa108eec3c89183f6507ec..d23f433969a1cd8f3f958c39a0e6aeeaa69bb12c 100755 (executable)
@@ -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
index 20abce26df45268bfa9fdd34421f47ba6f9ba33b..6ce7c35c37c04da2302d99427c4dca3f9bc6ef04 100644 (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)))