ยปCore Development>Code coverage>Lib/test/test_fractions.py

# Python code coverage for Lib/test/test_fractions.py

#countcontent
1n/a"""Tests for Lib/fractions.py."""
2n/a
3n/afrom decimal import Decimal
4n/afrom test.support import requires_IEEE_754
5n/aimport math
6n/aimport numbers
7n/aimport operator
8n/aimport fractions
9n/aimport sys
10n/aimport unittest
11n/aimport warnings
12n/afrom copy import copy, deepcopy
13n/afrom pickle import dumps, loads
14n/aF = fractions.Fraction
15n/agcd = fractions.gcd
16n/a
17n/aclass DummyFloat(object):
18n/a """Dummy float class for testing comparisons with Fractions"""
19n/a
20n/a def __init__(self, value):
21n/a if not isinstance(value, float):
22n/a raise TypeError("DummyFloat can only be initialized from float")
23n/a self.value = value
24n/a
25n/a def _richcmp(self, other, op):
26n/a if isinstance(other, numbers.Rational):
27n/a return op(F.from_float(self.value), other)
28n/a elif isinstance(other, DummyFloat):
29n/a return op(self.value, other.value)
30n/a else:
31n/a return NotImplemented
32n/a
33n/a def __eq__(self, other): return self._richcmp(other, operator.eq)
34n/a def __le__(self, other): return self._richcmp(other, operator.le)
35n/a def __lt__(self, other): return self._richcmp(other, operator.lt)
36n/a def __ge__(self, other): return self._richcmp(other, operator.ge)
37n/a def __gt__(self, other): return self._richcmp(other, operator.gt)
38n/a
39n/a # shouldn't be calling __float__ at all when doing comparisons
40n/a def __float__(self):
41n/a assert False, "__float__ should not be invoked for comparisons"
42n/a
43n/a # same goes for subtraction
44n/a def __sub__(self, other):
45n/a assert False, "__sub__ should not be invoked for comparisons"
46n/a __rsub__ = __sub__
47n/a
48n/a
49n/aclass DummyRational(object):
50n/a """Test comparison of Fraction with a naive rational implementation."""
51n/a
52n/a def __init__(self, num, den):
53n/a g = math.gcd(num, den)
54n/a self.num = num // g
55n/a self.den = den // g
56n/a
57n/a def __eq__(self, other):
58n/a if isinstance(other, fractions.Fraction):
59n/a return (self.num == other._numerator and
60n/a self.den == other._denominator)
61n/a else:
62n/a return NotImplemented
63n/a
64n/a def __lt__(self, other):
65n/a return(self.num * other._denominator < self.den * other._numerator)
66n/a
67n/a def __gt__(self, other):
68n/a return(self.num * other._denominator > self.den * other._numerator)
69n/a
70n/a def __le__(self, other):
71n/a return(self.num * other._denominator <= self.den * other._numerator)
72n/a
73n/a def __ge__(self, other):
74n/a return(self.num * other._denominator >= self.den * other._numerator)
75n/a
76n/a # this class is for testing comparisons; conversion to float
77n/a # should never be used for a comparison, since it loses accuracy
78n/a def __float__(self):
79n/a assert False, "__float__ should not be invoked"
80n/a
81n/aclass DummyFraction(fractions.Fraction):
82n/a """Dummy Fraction subclass for copy and deepcopy testing."""
83n/a
84n/aclass GcdTest(unittest.TestCase):
85n/a
86n/a def testMisc(self):
87n/a # fractions.gcd() is deprecated
88n/a with self.assertWarnsRegex(DeprecationWarning, r'fractions\.gcd'):
89n/a gcd(1, 1)
90n/a with warnings.catch_warnings():
91n/a warnings.filterwarnings('ignore', r'fractions\.gcd',
92n/a DeprecationWarning)
93n/a self.assertEqual(0, gcd(0, 0))
94n/a self.assertEqual(1, gcd(1, 0))
95n/a self.assertEqual(-1, gcd(-1, 0))
96n/a self.assertEqual(1, gcd(0, 1))
97n/a self.assertEqual(-1, gcd(0, -1))
98n/a self.assertEqual(1, gcd(7, 1))
99n/a self.assertEqual(-1, gcd(7, -1))
100n/a self.assertEqual(1, gcd(-23, 15))
101n/a self.assertEqual(12, gcd(120, 84))
102n/a self.assertEqual(-12, gcd(84, -120))
103n/a self.assertEqual(gcd(120.0, 84), 12.0)
104n/a self.assertEqual(gcd(120, 84.0), 12.0)
105n/a self.assertEqual(gcd(F(120), F(84)), F(12))
106n/a self.assertEqual(gcd(F(120, 77), F(84, 55)), F(12, 385))
107n/a
108n/a
109n/adef _components(r):
110n/a return (r.numerator, r.denominator)
111n/a
112n/a
113n/aclass FractionTest(unittest.TestCase):
114n/a
115n/a def assertTypedEquals(self, expected, actual):
116n/a """Asserts that both the types and values are the same."""
117n/a self.assertEqual(type(expected), type(actual))
118n/a self.assertEqual(expected, actual)
119n/a
120n/a def assertRaisesMessage(self, exc_type, message,
121n/a callable, *args, **kwargs):
122n/a """Asserts that callable(*args, **kwargs) raises exc_type(message)."""
123n/a try:
124n/a callable(*args, **kwargs)
125n/a except exc_type as e:
126n/a self.assertEqual(message, str(e))
127n/a else:
128n/a self.fail("%s not raised" % exc_type.__name__)
129n/a
130n/a def testInit(self):
131n/a self.assertEqual((0, 1), _components(F()))
132n/a self.assertEqual((7, 1), _components(F(7)))
133n/a self.assertEqual((7, 3), _components(F(F(7, 3))))
134n/a
135n/a self.assertEqual((-1, 1), _components(F(-1, 1)))
136n/a self.assertEqual((-1, 1), _components(F(1, -1)))
137n/a self.assertEqual((1, 1), _components(F(-2, -2)))
138n/a self.assertEqual((1, 2), _components(F(5, 10)))
139n/a self.assertEqual((7, 15), _components(F(7, 15)))
140n/a self.assertEqual((10**23, 1), _components(F(10**23)))
141n/a
142n/a self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
143n/a self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
144n/a self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))
145n/a
146n/a self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
147n/a F, 12, 0)
148n/a self.assertRaises(TypeError, F, 1.5 + 3j)
149n/a
150n/a self.assertRaises(TypeError, F, "3/2", 3)
151n/a self.assertRaises(TypeError, F, 3, 0j)
152n/a self.assertRaises(TypeError, F, 3, 1j)
153n/a self.assertRaises(TypeError, F, 1, 2, 3)
154n/a
155n/a @requires_IEEE_754
156n/a def testInitFromFloat(self):
157n/a self.assertEqual((5, 2), _components(F(2.5)))
158n/a self.assertEqual((0, 1), _components(F(-0.0)))
159n/a self.assertEqual((3602879701896397, 36028797018963968),
160n/a _components(F(0.1)))
161n/a # bug 16469: error types should be consistent with float -> int
162n/a self.assertRaises(ValueError, F, float('nan'))
163n/a self.assertRaises(OverflowError, F, float('inf'))
164n/a self.assertRaises(OverflowError, F, float('-inf'))
165n/a
166n/a def testInitFromDecimal(self):
167n/a self.assertEqual((11, 10),
168n/a _components(F(Decimal('1.1'))))
169n/a self.assertEqual((7, 200),
170n/a _components(F(Decimal('3.5e-2'))))
171n/a self.assertEqual((0, 1),
172n/a _components(F(Decimal('.000e20'))))
173n/a # bug 16469: error types should be consistent with decimal -> int
174n/a self.assertRaises(ValueError, F, Decimal('nan'))
175n/a self.assertRaises(ValueError, F, Decimal('snan'))
176n/a self.assertRaises(OverflowError, F, Decimal('inf'))
177n/a self.assertRaises(OverflowError, F, Decimal('-inf'))
178n/a
179n/a def testFromString(self):
180n/a self.assertEqual((5, 1), _components(F("5")))
181n/a self.assertEqual((3, 2), _components(F("3/2")))
182n/a self.assertEqual((3, 2), _components(F(" \n +3/2")))
183n/a self.assertEqual((-3, 2), _components(F("-3/2 ")))
184n/a self.assertEqual((13, 2), _components(F(" 013/02 \n ")))
185n/a self.assertEqual((16, 5), _components(F(" 3.2 ")))
186n/a self.assertEqual((-16, 5), _components(F(" -3.2 ")))
187n/a self.assertEqual((-3, 1), _components(F(" -3. ")))
188n/a self.assertEqual((3, 5), _components(F(" .6 ")))
189n/a self.assertEqual((1, 3125), _components(F("32.e-5")))
190n/a self.assertEqual((1000000, 1), _components(F("1E+06")))
191n/a self.assertEqual((-12300, 1), _components(F("-1.23e4")))
192n/a self.assertEqual((0, 1), _components(F(" .0e+0\t")))
193n/a self.assertEqual((0, 1), _components(F("-0.000e0")))
194n/a
195n/a self.assertRaisesMessage(
196n/a ZeroDivisionError, "Fraction(3, 0)",
197n/a F, "3/0")
198n/a self.assertRaisesMessage(
199n/a ValueError, "Invalid literal for Fraction: '3/'",
200n/a F, "3/")
201n/a self.assertRaisesMessage(
202n/a ValueError, "Invalid literal for Fraction: '/2'",
203n/a F, "/2")
204n/a self.assertRaisesMessage(
205n/a ValueError, "Invalid literal for Fraction: '3 /2'",
206n/a F, "3 /2")
207n/a self.assertRaisesMessage(
208n/a # Denominators don't need a sign.
209n/a ValueError, "Invalid literal for Fraction: '3/+2'",
210n/a F, "3/+2")
211n/a self.assertRaisesMessage(
212n/a # Imitate float's parsing.
213n/a ValueError, "Invalid literal for Fraction: '+ 3/2'",
214n/a F, "+ 3/2")
215n/a self.assertRaisesMessage(
216n/a # Avoid treating '.' as a regex special character.
217n/a ValueError, "Invalid literal for Fraction: '3a2'",
218n/a F, "3a2")
219n/a self.assertRaisesMessage(
220n/a # Don't accept combinations of decimals and rationals.
221n/a ValueError, "Invalid literal for Fraction: '3/7.2'",
222n/a F, "3/7.2")
223n/a self.assertRaisesMessage(
224n/a # Don't accept combinations of decimals and rationals.
225n/a ValueError, "Invalid literal for Fraction: '3.2/7'",
226n/a F, "3.2/7")
227n/a self.assertRaisesMessage(
228n/a # Allow 3. and .3, but not .
229n/a ValueError, "Invalid literal for Fraction: '.'",
230n/a F, ".")
231n/a
232n/a def testImmutable(self):
233n/a r = F(7, 3)
234n/a r.__init__(2, 15)
235n/a self.assertEqual((7, 3), _components(r))
236n/a
237n/a self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
238n/a self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
239n/a self.assertEqual((7, 3), _components(r))
240n/a
241n/a # But if you _really_ need to:
242n/a r._numerator = 4
243n/a r._denominator = 2
244n/a self.assertEqual((4, 2), _components(r))
245n/a # Which breaks some important operations:
246n/a self.assertNotEqual(F(4, 2), r)
247n/a
248n/a def testFromFloat(self):
249n/a self.assertRaises(TypeError, F.from_float, 3+4j)
250n/a self.assertEqual((10, 1), _components(F.from_float(10)))
251n/a bigint = 1234567890123456789
252n/a self.assertEqual((bigint, 1), _components(F.from_float(bigint)))
253n/a self.assertEqual((0, 1), _components(F.from_float(-0.0)))
254n/a self.assertEqual((10, 1), _components(F.from_float(10.0)))
255n/a self.assertEqual((-5, 2), _components(F.from_float(-2.5)))
256n/a self.assertEqual((99999999999999991611392, 1),
257n/a _components(F.from_float(1e23)))
258n/a self.assertEqual(float(10**23), float(F.from_float(1e23)))
259n/a self.assertEqual((3602879701896397, 1125899906842624),
260n/a _components(F.from_float(3.2)))
261n/a self.assertEqual(3.2, float(F.from_float(3.2)))
262n/a
263n/a inf = 1e1000
264n/a nan = inf - inf
265n/a # bug 16469: error types should be consistent with float -> int
266n/a self.assertRaisesMessage(
267n/a OverflowError, "cannot convert Infinity to integer ratio",
268n/a F.from_float, inf)
269n/a self.assertRaisesMessage(
270n/a OverflowError, "cannot convert Infinity to integer ratio",
271n/a F.from_float, -inf)
272n/a self.assertRaisesMessage(
273n/a ValueError, "cannot convert NaN to integer ratio",
274n/a F.from_float, nan)
275n/a
276n/a def testFromDecimal(self):
277n/a self.assertRaises(TypeError, F.from_decimal, 3+4j)
278n/a self.assertEqual(F(10, 1), F.from_decimal(10))
279n/a self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
280n/a self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
281n/a self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
282n/a self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
283n/a self.assertEqual(1 - F(1, 10**30),
284n/a F.from_decimal(Decimal("0." + "9" * 30)))
285n/a
286n/a # bug 16469: error types should be consistent with decimal -> int
287n/a self.assertRaisesMessage(
288n/a OverflowError, "cannot convert Infinity to integer ratio",
289n/a F.from_decimal, Decimal("inf"))
290n/a self.assertRaisesMessage(
291n/a OverflowError, "cannot convert Infinity to integer ratio",
292n/a F.from_decimal, Decimal("-inf"))
293n/a self.assertRaisesMessage(
294n/a ValueError, "cannot convert NaN to integer ratio",
295n/a F.from_decimal, Decimal("nan"))
296n/a self.assertRaisesMessage(
297n/a ValueError, "cannot convert NaN to integer ratio",
298n/a F.from_decimal, Decimal("snan"))
299n/a
300n/a def testLimitDenominator(self):
301n/a rpi = F('3.1415926535897932')
302n/a self.assertEqual(rpi.limit_denominator(10000), F(355, 113))
303n/a self.assertEqual(-rpi.limit_denominator(10000), F(-355, 113))
304n/a self.assertEqual(rpi.limit_denominator(113), F(355, 113))
305n/a self.assertEqual(rpi.limit_denominator(112), F(333, 106))
306n/a self.assertEqual(F(201, 200).limit_denominator(100), F(1))
307n/a self.assertEqual(F(201, 200).limit_denominator(101), F(102, 101))
308n/a self.assertEqual(F(0).limit_denominator(10000), F(0))
309n/a for i in (0, -1):
310n/a self.assertRaisesMessage(
311n/a ValueError, "max_denominator should be at least 1",
312n/a F(1).limit_denominator, i)
313n/a
314n/a def testConversions(self):
315n/a self.assertTypedEquals(-1, math.trunc(F(-11, 10)))
316n/a self.assertTypedEquals(1, math.trunc(F(11, 10)))
317n/a self.assertTypedEquals(-2, math.floor(F(-11, 10)))
318n/a self.assertTypedEquals(-1, math.ceil(F(-11, 10)))
319n/a self.assertTypedEquals(-1, math.ceil(F(-10, 10)))
320n/a self.assertTypedEquals(-1, int(F(-11, 10)))
321n/a self.assertTypedEquals(0, round(F(-1, 10)))
322n/a self.assertTypedEquals(0, round(F(-5, 10)))
323n/a self.assertTypedEquals(-2, round(F(-15, 10)))
324n/a self.assertTypedEquals(-1, round(F(-7, 10)))
325n/a
326n/a self.assertEqual(False, bool(F(0, 1)))
327n/a self.assertEqual(True, bool(F(3, 2)))
328n/a self.assertTypedEquals(0.1, float(F(1, 10)))
329n/a
330n/a # Check that __float__ isn't implemented by converting the
331n/a # numerator and denominator to float before dividing.
332n/a self.assertRaises(OverflowError, float, int('2'*400+'7'))
333n/a self.assertAlmostEqual(2.0/3,
334n/a float(F(int('2'*400+'7'), int('3'*400+'1'))))
335n/a
336n/a self.assertTypedEquals(0.1+0j, complex(F(1,10)))
337n/a
338n/a def testRound(self):
339n/a self.assertTypedEquals(F(-200), round(F(-150), -2))
340n/a self.assertTypedEquals(F(-200), round(F(-250), -2))
341n/a self.assertTypedEquals(F(30), round(F(26), -1))
342n/a self.assertTypedEquals(F(-2, 10), round(F(-15, 100), 1))
343n/a self.assertTypedEquals(F(-2, 10), round(F(-25, 100), 1))
344n/a
345n/a def testArithmetic(self):
346n/a self.assertEqual(F(1, 2), F(1, 10) + F(2, 5))
347n/a self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5))
348n/a self.assertEqual(F(1, 25), F(1, 10) * F(2, 5))
349n/a self.assertEqual(F(1, 4), F(1, 10) / F(2, 5))
350n/a self.assertTypedEquals(2, F(9, 10) // F(2, 5))
351n/a self.assertTypedEquals(10**23, F(10**23, 1) // F(1))
352n/a self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2))
353n/a self.assertEqual(F(8, 27), F(2, 3) ** F(3))
354n/a self.assertEqual(F(27, 8), F(2, 3) ** F(-3))
355n/a self.assertTypedEquals(2.0, F(4) ** F(1, 2))
356n/a self.assertEqual(F(1, 1), +F(1, 1))
357n/a z = pow(F(-1), F(1, 2))
358n/a self.assertAlmostEqual(z.real, 0)
359n/a self.assertEqual(z.imag, 1)
360n/a # Regression test for #27539.
361n/a p = F(-1, 2) ** 0
362n/a self.assertEqual(p, F(1, 1))
363n/a self.assertEqual(p.numerator, 1)
364n/a self.assertEqual(p.denominator, 1)
365n/a p = F(-1, 2) ** -1
366n/a self.assertEqual(p, F(-2, 1))
367n/a self.assertEqual(p.numerator, -2)
368n/a self.assertEqual(p.denominator, 1)
369n/a p = F(-1, 2) ** -2
370n/a self.assertEqual(p, F(4, 1))
371n/a self.assertEqual(p.numerator, 4)
372n/a self.assertEqual(p.denominator, 1)
373n/a
374n/a def testMixedArithmetic(self):
375n/a self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
376n/a self.assertTypedEquals(1.1, F(1, 10) + 1.0)
377n/a self.assertTypedEquals(1.1 + 0j, F(1, 10) + (1.0 + 0j))
378n/a self.assertTypedEquals(F(11, 10), 1 + F(1, 10))
379n/a self.assertTypedEquals(1.1, 1.0 + F(1, 10))
380n/a self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + F(1, 10))
381n/a
382n/a self.assertTypedEquals(F(-9, 10), F(1, 10) - 1)
383n/a self.assertTypedEquals(-0.9, F(1, 10) - 1.0)
384n/a self.assertTypedEquals(-0.9 + 0j, F(1, 10) - (1.0 + 0j))
385n/a self.assertTypedEquals(F(9, 10), 1 - F(1, 10))
386n/a self.assertTypedEquals(0.9, 1.0 - F(1, 10))
387n/a self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - F(1, 10))
388n/a
389n/a self.assertTypedEquals(F(1, 10), F(1, 10) * 1)
390n/a self.assertTypedEquals(0.1, F(1, 10) * 1.0)
391n/a self.assertTypedEquals(0.1 + 0j, F(1, 10) * (1.0 + 0j))
392n/a self.assertTypedEquals(F(1, 10), 1 * F(1, 10))
393n/a self.assertTypedEquals(0.1, 1.0 * F(1, 10))
394n/a self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * F(1, 10))
395n/a
396n/a self.assertTypedEquals(F(1, 10), F(1, 10) / 1)
397n/a self.assertTypedEquals(0.1, F(1, 10) / 1.0)
398n/a self.assertTypedEquals(0.1 + 0j, F(1, 10) / (1.0 + 0j))
399n/a self.assertTypedEquals(F(10, 1), 1 / F(1, 10))
400n/a self.assertTypedEquals(10.0, 1.0 / F(1, 10))
401n/a self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / F(1, 10))
402n/a
403n/a self.assertTypedEquals(0, F(1, 10) // 1)
404n/a self.assertTypedEquals(0, F(1, 10) // 1.0)
405n/a self.assertTypedEquals(10, 1 // F(1, 10))
406n/a self.assertTypedEquals(10**23, 10**22 // F(1, 10))
407n/a self.assertTypedEquals(10, 1.0 // F(1, 10))
408n/a
409n/a self.assertTypedEquals(F(1, 10), F(1, 10) % 1)
410n/a self.assertTypedEquals(0.1, F(1, 10) % 1.0)
411n/a self.assertTypedEquals(F(0, 1), 1 % F(1, 10))
412n/a self.assertTypedEquals(0.0, 1.0 % F(1, 10))
413n/a
414n/a # No need for divmod since we don't override it.
415n/a
416n/a # ** has more interesting conversion rules.
417n/a self.assertTypedEquals(F(100, 1), F(1, 10) ** -2)
418n/a self.assertTypedEquals(F(100, 1), F(10, 1) ** 2)
419n/a self.assertTypedEquals(0.1, F(1, 10) ** 1.0)
420n/a self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j))
421n/a self.assertTypedEquals(4 , 2 ** F(2, 1))
422n/a z = pow(-1, F(1, 2))
423n/a self.assertAlmostEqual(0, z.real)
424n/a self.assertEqual(1, z.imag)
425n/a self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1))
426n/a self.assertTypedEquals(2.0 , 4 ** F(1, 2))
427n/a self.assertTypedEquals(0.25, 2.0 ** F(-2, 1))
428n/a self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** F(1, 10))
429n/a self.assertRaises(ZeroDivisionError, operator.pow,
430n/a F(0, 1), -2)
431n/a
432n/a def testMixingWithDecimal(self):
433n/a # Decimal refuses mixed arithmetic (but not mixed comparisons)
434n/a self.assertRaises(TypeError, operator.add,
435n/a F(3,11), Decimal('3.1415926'))
436n/a self.assertRaises(TypeError, operator.add,
437n/a Decimal('3.1415926'), F(3,11))
438n/a
439n/a def testComparisons(self):
440n/a self.assertTrue(F(1, 2) < F(2, 3))
441n/a self.assertFalse(F(1, 2) < F(1, 2))
442n/a self.assertTrue(F(1, 2) <= F(2, 3))
443n/a self.assertTrue(F(1, 2) <= F(1, 2))
444n/a self.assertFalse(F(2, 3) <= F(1, 2))
445n/a self.assertTrue(F(1, 2) == F(1, 2))
446n/a self.assertFalse(F(1, 2) == F(1, 3))
447n/a self.assertFalse(F(1, 2) != F(1, 2))
448n/a self.assertTrue(F(1, 2) != F(1, 3))
449n/a
450n/a def testComparisonsDummyRational(self):
451n/a self.assertTrue(F(1, 2) == DummyRational(1, 2))
452n/a self.assertTrue(DummyRational(1, 2) == F(1, 2))
453n/a self.assertFalse(F(1, 2) == DummyRational(3, 4))
454n/a self.assertFalse(DummyRational(3, 4) == F(1, 2))
455n/a
456n/a self.assertTrue(F(1, 2) < DummyRational(3, 4))
457n/a self.assertFalse(F(1, 2) < DummyRational(1, 2))
458n/a self.assertFalse(F(1, 2) < DummyRational(1, 7))
459n/a self.assertFalse(F(1, 2) > DummyRational(3, 4))
460n/a self.assertFalse(F(1, 2) > DummyRational(1, 2))
461n/a self.assertTrue(F(1, 2) > DummyRational(1, 7))
462n/a self.assertTrue(F(1, 2) <= DummyRational(3, 4))
463n/a self.assertTrue(F(1, 2) <= DummyRational(1, 2))
464n/a self.assertFalse(F(1, 2) <= DummyRational(1, 7))
465n/a self.assertFalse(F(1, 2) >= DummyRational(3, 4))
466n/a self.assertTrue(F(1, 2) >= DummyRational(1, 2))
467n/a self.assertTrue(F(1, 2) >= DummyRational(1, 7))
468n/a
469n/a self.assertTrue(DummyRational(1, 2) < F(3, 4))
470n/a self.assertFalse(DummyRational(1, 2) < F(1, 2))
471n/a self.assertFalse(DummyRational(1, 2) < F(1, 7))
472n/a self.assertFalse(DummyRational(1, 2) > F(3, 4))
473n/a self.assertFalse(DummyRational(1, 2) > F(1, 2))
474n/a self.assertTrue(DummyRational(1, 2) > F(1, 7))
475n/a self.assertTrue(DummyRational(1, 2) <= F(3, 4))
476n/a self.assertTrue(DummyRational(1, 2) <= F(1, 2))
477n/a self.assertFalse(DummyRational(1, 2) <= F(1, 7))
478n/a self.assertFalse(DummyRational(1, 2) >= F(3, 4))
479n/a self.assertTrue(DummyRational(1, 2) >= F(1, 2))
480n/a self.assertTrue(DummyRational(1, 2) >= F(1, 7))
481n/a
482n/a def testComparisonsDummyFloat(self):
483n/a x = DummyFloat(1./3.)
484n/a y = F(1, 3)
485n/a self.assertTrue(x != y)
486n/a self.assertTrue(x < y or x > y)
487n/a self.assertFalse(x == y)
488n/a self.assertFalse(x <= y and x >= y)
489n/a self.assertTrue(y != x)
490n/a self.assertTrue(y < x or y > x)
491n/a self.assertFalse(y == x)
492n/a self.assertFalse(y <= x and y >= x)
493n/a
494n/a def testMixedLess(self):
495n/a self.assertTrue(2 < F(5, 2))
496n/a self.assertFalse(2 < F(4, 2))
497n/a self.assertTrue(F(5, 2) < 3)
498n/a self.assertFalse(F(4, 2) < 2)
499n/a
500n/a self.assertTrue(F(1, 2) < 0.6)
501n/a self.assertFalse(F(1, 2) < 0.4)
502n/a self.assertTrue(0.4 < F(1, 2))
503n/a self.assertFalse(0.5 < F(1, 2))
504n/a
505n/a self.assertFalse(float('inf') < F(1, 2))
506n/a self.assertTrue(float('-inf') < F(0, 10))
507n/a self.assertFalse(float('nan') < F(-3, 7))
508n/a self.assertTrue(F(1, 2) < float('inf'))
509n/a self.assertFalse(F(17, 12) < float('-inf'))
510n/a self.assertFalse(F(144, -89) < float('nan'))
511n/a
512n/a def testMixedLessEqual(self):
513n/a self.assertTrue(0.5 <= F(1, 2))
514n/a self.assertFalse(0.6 <= F(1, 2))
515n/a self.assertTrue(F(1, 2) <= 0.5)
516n/a self.assertFalse(F(1, 2) <= 0.4)
517n/a self.assertTrue(2 <= F(4, 2))
518n/a self.assertFalse(2 <= F(3, 2))
519n/a self.assertTrue(F(4, 2) <= 2)
520n/a self.assertFalse(F(5, 2) <= 2)
521n/a
522n/a self.assertFalse(float('inf') <= F(1, 2))
523n/a self.assertTrue(float('-inf') <= F(0, 10))
524n/a self.assertFalse(float('nan') <= F(-3, 7))
525n/a self.assertTrue(F(1, 2) <= float('inf'))
526n/a self.assertFalse(F(17, 12) <= float('-inf'))
527n/a self.assertFalse(F(144, -89) <= float('nan'))
528n/a
529n/a def testBigFloatComparisons(self):
530n/a # Because 10**23 can't be represented exactly as a float:
531n/a self.assertFalse(F(10**23) == float(10**23))
532n/a # The first test demonstrates why these are important.
533n/a self.assertFalse(1e23 < float(F(math.trunc(1e23) + 1)))
534n/a self.assertTrue(1e23 < F(math.trunc(1e23) + 1))
535n/a self.assertFalse(1e23 <= F(math.trunc(1e23) - 1))
536n/a self.assertTrue(1e23 > F(math.trunc(1e23) - 1))
537n/a self.assertFalse(1e23 >= F(math.trunc(1e23) + 1))
538n/a
539n/a def testBigComplexComparisons(self):
540n/a self.assertFalse(F(10**23) == complex(10**23))
541n/a self.assertRaises(TypeError, operator.gt, F(10**23), complex(10**23))
542n/a self.assertRaises(TypeError, operator.le, F(10**23), complex(10**23))
543n/a
544n/a x = F(3, 8)
545n/a z = complex(0.375, 0.0)
546n/a w = complex(0.375, 0.2)
547n/a self.assertTrue(x == z)
548n/a self.assertFalse(x != z)
549n/a self.assertFalse(x == w)
550n/a self.assertTrue(x != w)
551n/a for op in operator.lt, operator.le, operator.gt, operator.ge:
552n/a self.assertRaises(TypeError, op, x, z)
553n/a self.assertRaises(TypeError, op, z, x)
554n/a self.assertRaises(TypeError, op, x, w)
555n/a self.assertRaises(TypeError, op, w, x)
556n/a
557n/a def testMixedEqual(self):
558n/a self.assertTrue(0.5 == F(1, 2))
559n/a self.assertFalse(0.6 == F(1, 2))
560n/a self.assertTrue(F(1, 2) == 0.5)
561n/a self.assertFalse(F(1, 2) == 0.4)
562n/a self.assertTrue(2 == F(4, 2))
563n/a self.assertFalse(2 == F(3, 2))
564n/a self.assertTrue(F(4, 2) == 2)
565n/a self.assertFalse(F(5, 2) == 2)
566n/a self.assertFalse(F(5, 2) == float('nan'))
567n/a self.assertFalse(float('nan') == F(3, 7))
568n/a self.assertFalse(F(5, 2) == float('inf'))
569n/a self.assertFalse(float('-inf') == F(2, 5))
570n/a
571n/a def testStringification(self):
572n/a self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
573n/a self.assertEqual("Fraction(6283185307, 2000000000)",
574n/a repr(F('3.1415926535')))
575n/a self.assertEqual("Fraction(-1, 100000000000000000000)",
576n/a repr(F(1, -10**20)))
577n/a self.assertEqual("7/3", str(F(7, 3)))
578n/a self.assertEqual("7", str(F(7, 1)))
579n/a
580n/a def testHash(self):
581n/a hmod = sys.hash_info.modulus
582n/a hinf = sys.hash_info.inf
583n/a self.assertEqual(hash(2.5), hash(F(5, 2)))
584n/a self.assertEqual(hash(10**50), hash(F(10**50)))
585n/a self.assertNotEqual(hash(float(10**23)), hash(F(10**23)))
586n/a self.assertEqual(hinf, hash(F(1, hmod)))
587n/a # Check that __hash__ produces the same value as hash(), for
588n/a # consistency with int and Decimal. (See issue #10356.)
589n/a self.assertEqual(hash(F(-1)), F(-1).__hash__())
590n/a
591n/a def testApproximatePi(self):
592n/a # Algorithm borrowed from
593n/a # http://docs.python.org/lib/decimal-recipes.html
594n/a three = F(3)
595n/a lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
596n/a while abs(s - lasts) > F(1, 10**9):
597n/a lasts = s
598n/a n, na = n+na, na+8
599n/a d, da = d+da, da+32
600n/a t = (t * n) / d
601n/a s += t
602n/a self.assertAlmostEqual(math.pi, s)
603n/a
604n/a def testApproximateCos1(self):
605n/a # Algorithm borrowed from
606n/a # http://docs.python.org/lib/decimal-recipes.html
607n/a x = F(1)
608n/a i, lasts, s, fact, num, sign = 0, 0, F(1), 1, 1, 1
609n/a while abs(s - lasts) > F(1, 10**9):
610n/a lasts = s
611n/a i += 2
612n/a fact *= i * (i-1)
613n/a num *= x * x
614n/a sign *= -1
615n/a s += num / fact * sign
616n/a self.assertAlmostEqual(math.cos(1), s)
617n/a
618n/a def test_copy_deepcopy_pickle(self):
619n/a r = F(13, 7)
620n/a dr = DummyFraction(13, 7)
621n/a self.assertEqual(r, loads(dumps(r)))
622n/a self.assertEqual(id(r), id(copy(r)))
623n/a self.assertEqual(id(r), id(deepcopy(r)))
624n/a self.assertNotEqual(id(dr), id(copy(dr)))
625n/a self.assertNotEqual(id(dr), id(deepcopy(dr)))
626n/a self.assertTypedEquals(dr, copy(dr))
627n/a self.assertTypedEquals(dr, deepcopy(dr))
628n/a
629n/a def test_slots(self):
630n/a # Issue 4998
631n/a r = F(13, 7)
632n/a self.assertRaises(AttributeError, setattr, r, 'a', 10)
633n/a
634n/aif __name__ == '__main__':
635n/a unittest.main()