From eb461904eb277c5a92a7d2672f941cb095cf1a93 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Thu, 24 Jan 2008 02:00:25 +0000 Subject: [PATCH] Minor clean-up and more tests. --- Lib/rational.py | 6 ++++-- Lib/test/test_rational.py | 11 +++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Lib/rational.py b/Lib/rational.py index 5d21a8f4874..070e593bad8 100755 --- a/Lib/rational.py +++ b/Lib/rational.py @@ -179,7 +179,9 @@ class Rational(RationalAbc): for e in reversed(seq): n, d = d, n n += e * d - return cls(n, d) + if seq: + return cls(n, d) + return cls(0) def as_continued_fraction(self): 'Return continued fraction expressed as a list' @@ -200,7 +202,7 @@ class Rational(RationalAbc): # Still needs rounding rules as specified at # http://en.wikipedia.org/wiki/Continued_fraction cf = cls.from_float(f).as_continued_fraction() - result = new = Rational(0, 1) + result = Rational(0) for i in range(1, len(cf)): new = cls.from_continued_fraction(cf[:i]) if new.denominator > max_denominator: diff --git a/Lib/test/test_rational.py b/Lib/test/test_rational.py index 76757ba03bd..0f0a48de3ae 100644 --- a/Lib/test/test_rational.py +++ b/Lib/test/test_rational.py @@ -140,12 +140,23 @@ class RationalTest(unittest.TestCase): phi = R.from_continued_fraction([1]*100) self.assertEquals(round(phi - (1 + 5 ** 0.5) / 2, 10), 0.0) + minusphi = R.from_continued_fraction([-1]*100) + self.assertEquals(round(minusphi + (1 + 5 ** 0.5) / 2, 10), 0.0) + + self.assertEquals(R.from_continued_fraction([0]), R(0)) + self.assertEquals(R.from_continued_fraction([]), R(0)) + def testAsContinuedFraction(self): self.assertEqual(R.from_float(math.pi).as_continued_fraction()[:15], [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, 3]) + self.assertEqual(R.from_float(-math.pi).as_continued_fraction()[:16], + [-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 testConversions(self): self.assertTypedEquals(-1, trunc(R(-11, 10)))