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

Python code coverage for Lib/test/test_long.py

#countcontent
1n/aimport unittest
2n/afrom test import support
3n/a
4n/aimport sys
5n/a
6n/aimport random
7n/aimport math
8n/aimport array
9n/a
10n/a# SHIFT should match the value in longintrepr.h for best testing.
11n/aSHIFT = sys.int_info.bits_per_digit
12n/aBASE = 2 ** SHIFT
13n/aMASK = BASE - 1
14n/aKARATSUBA_CUTOFF = 70 # from longobject.c
15n/a
16n/a# Max number of base BASE digits to use in test cases. Doubling
17n/a# this will more than double the runtime.
18n/aMAXDIGITS = 15
19n/a
20n/a# build some special values
21n/aspecial = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
22n/a# some solid strings of one bits
23n/ap2 = 4 # 0 and 1 already added
24n/afor i in range(2*SHIFT):
25n/a special.append(p2 - 1)
26n/a p2 = p2 << 1
27n/adel p2
28n/a# add complements & negations
29n/aspecial += [~x for x in special] + [-x for x in special]
30n/a
31n/aDBL_MAX = sys.float_info.max
32n/aDBL_MAX_EXP = sys.float_info.max_exp
33n/aDBL_MIN_EXP = sys.float_info.min_exp
34n/aDBL_MANT_DIG = sys.float_info.mant_dig
35n/aDBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1)
36n/a
37n/a
38n/a# Pure Python version of correctly-rounded integer-to-float conversion.
39n/adef int_to_float(n):
40n/a """
41n/a Correctly-rounded integer-to-float conversion.
42n/a
43n/a """
44n/a # Constants, depending only on the floating-point format in use.
45n/a # We use an extra 2 bits of precision for rounding purposes.
46n/a PRECISION = sys.float_info.mant_dig + 2
47n/a SHIFT_MAX = sys.float_info.max_exp - PRECISION
48n/a Q_MAX = 1 << PRECISION
49n/a ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1]
50n/a
51n/a # Reduce to the case where n is positive.
52n/a if n == 0:
53n/a return 0.0
54n/a elif n < 0:
55n/a return -int_to_float(-n)
56n/a
57n/a # Convert n to a 'floating-point' number q * 2**shift, where q is an
58n/a # integer with 'PRECISION' significant bits. When shifting n to create q,
59n/a # the least significant bit of q is treated as 'sticky'. That is, the
60n/a # least significant bit of q is set if either the corresponding bit of n
61n/a # was already set, or any one of the bits of n lost in the shift was set.
62n/a shift = n.bit_length() - PRECISION
63n/a q = n << -shift if shift < 0 else (n >> shift) | bool(n & ~(-1 << shift))
64n/a
65n/a # Round half to even (actually rounds to the nearest multiple of 4,
66n/a # rounding ties to a multiple of 8).
67n/a q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7]
68n/a
69n/a # Detect overflow.
70n/a if shift + (q == Q_MAX) > SHIFT_MAX:
71n/a raise OverflowError("integer too large to convert to float")
72n/a
73n/a # Checks: q is exactly representable, and q**2**shift doesn't overflow.
74n/a assert q % 4 == 0 and q // 4 <= 2**(sys.float_info.mant_dig)
75n/a assert q * 2**shift <= sys.float_info.max
76n/a
77n/a # Some circularity here, since float(q) is doing an int-to-float
78n/a # conversion. But here q is of bounded size, and is exactly representable
79n/a # as a float. In a low-level C-like language, this operation would be a
80n/a # simple cast (e.g., from unsigned long long to double).
81n/a return math.ldexp(float(q), shift)
82n/a
83n/a
84n/a# pure Python version of correctly-rounded true division
85n/adef truediv(a, b):
86n/a """Correctly-rounded true division for integers."""
87n/a negative = a^b < 0
88n/a a, b = abs(a), abs(b)
89n/a
90n/a # exceptions: division by zero, overflow
91n/a if not b:
92n/a raise ZeroDivisionError("division by zero")
93n/a if a >= DBL_MIN_OVERFLOW * b:
94n/a raise OverflowError("int/int too large to represent as a float")
95n/a
96n/a # find integer d satisfying 2**(d - 1) <= a/b < 2**d
97n/a d = a.bit_length() - b.bit_length()
98n/a if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
99n/a d += 1
100n/a
101n/a # compute 2**-exp * a / b for suitable exp
102n/a exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
103n/a a, b = a << max(-exp, 0), b << max(exp, 0)
104n/a q, r = divmod(a, b)
105n/a
106n/a # round-half-to-even: fractional part is r/b, which is > 0.5 iff
107n/a # 2*r > b, and == 0.5 iff 2*r == b.
108n/a if 2*r > b or 2*r == b and q % 2 == 1:
109n/a q += 1
110n/a
111n/a result = math.ldexp(q, exp)
112n/a return -result if negative else result
113n/a
114n/a
115n/aclass LongTest(unittest.TestCase):
116n/a
117n/a # Get quasi-random long consisting of ndigits digits (in base BASE).
118n/a # quasi == the most-significant digit will not be 0, and the number
119n/a # is constructed to contain long strings of 0 and 1 bits. These are
120n/a # more likely than random bits to provoke digit-boundary errors.
121n/a # The sign of the number is also random.
122n/a
123n/a def getran(self, ndigits):
124n/a self.assertGreater(ndigits, 0)
125n/a nbits_hi = ndigits * SHIFT
126n/a nbits_lo = nbits_hi - SHIFT + 1
127n/a answer = 0
128n/a nbits = 0
129n/a r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
130n/a while nbits < nbits_lo:
131n/a bits = (r >> 1) + 1
132n/a bits = min(bits, nbits_hi - nbits)
133n/a self.assertTrue(1 <= bits <= SHIFT)
134n/a nbits = nbits + bits
135n/a answer = answer << bits
136n/a if r & 1:
137n/a answer = answer | ((1 << bits) - 1)
138n/a r = int(random.random() * (SHIFT * 2))
139n/a self.assertTrue(nbits_lo <= nbits <= nbits_hi)
140n/a if random.random() < 0.5:
141n/a answer = -answer
142n/a return answer
143n/a
144n/a # Get random long consisting of ndigits random digits (relative to base
145n/a # BASE). The sign bit is also random.
146n/a
147n/a def getran2(ndigits):
148n/a answer = 0
149n/a for i in range(ndigits):
150n/a answer = (answer << SHIFT) | random.randint(0, MASK)
151n/a if random.random() < 0.5:
152n/a answer = -answer
153n/a return answer
154n/a
155n/a def check_division(self, x, y):
156n/a eq = self.assertEqual
157n/a with self.subTest(x=x, y=y):
158n/a q, r = divmod(x, y)
159n/a q2, r2 = x//y, x%y
160n/a pab, pba = x*y, y*x
161n/a eq(pab, pba, "multiplication does not commute")
162n/a eq(q, q2, "divmod returns different quotient than /")
163n/a eq(r, r2, "divmod returns different mod than %")
164n/a eq(x, q*y + r, "x != q*y + r after divmod")
165n/a if y > 0:
166n/a self.assertTrue(0 <= r < y, "bad mod from divmod")
167n/a else:
168n/a self.assertTrue(y < r <= 0, "bad mod from divmod")
169n/a
170n/a def test_division(self):
171n/a digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
172n/a KARATSUBA_CUTOFF + 14))
173n/a digits.append(KARATSUBA_CUTOFF * 3)
174n/a for lenx in digits:
175n/a x = self.getran(lenx)
176n/a for leny in digits:
177n/a y = self.getran(leny) or 1
178n/a self.check_division(x, y)
179n/a
180n/a # specific numbers chosen to exercise corner cases of the
181n/a # current long division implementation
182n/a
183n/a # 30-bit cases involving a quotient digit estimate of BASE+1
184n/a self.check_division(1231948412290879395966702881,
185n/a 1147341367131428698)
186n/a self.check_division(815427756481275430342312021515587883,
187n/a 707270836069027745)
188n/a self.check_division(627976073697012820849443363563599041,
189n/a 643588798496057020)
190n/a self.check_division(1115141373653752303710932756325578065,
191n/a 1038556335171453937726882627)
192n/a # 30-bit cases that require the post-subtraction correction step
193n/a self.check_division(922498905405436751940989320930368494,
194n/a 949985870686786135626943396)
195n/a self.check_division(768235853328091167204009652174031844,
196n/a 1091555541180371554426545266)
197n/a
198n/a # 15-bit cases involving a quotient digit estimate of BASE+1
199n/a self.check_division(20172188947443, 615611397)
200n/a self.check_division(1020908530270155025, 950795710)
201n/a self.check_division(128589565723112408, 736393718)
202n/a self.check_division(609919780285761575, 18613274546784)
203n/a # 15-bit cases that require the post-subtraction correction step
204n/a self.check_division(710031681576388032, 26769404391308)
205n/a self.check_division(1933622614268221, 30212853348836)
206n/a
207n/a
208n/a
209n/a def test_karatsuba(self):
210n/a digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
211n/a KARATSUBA_CUTOFF + 10))
212n/a digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
213n/a
214n/a bits = [digit * SHIFT for digit in digits]
215n/a
216n/a # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
217n/a # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
218n/a for abits in bits:
219n/a a = (1 << abits) - 1
220n/a for bbits in bits:
221n/a if bbits < abits:
222n/a continue
223n/a with self.subTest(abits=abits, bbits=bbits):
224n/a b = (1 << bbits) - 1
225n/a x = a * b
226n/a y = ((1 << (abits + bbits)) -
227n/a (1 << abits) -
228n/a (1 << bbits) +
229n/a 1)
230n/a self.assertEqual(x, y)
231n/a
232n/a def check_bitop_identities_1(self, x):
233n/a eq = self.assertEqual
234n/a with self.subTest(x=x):
235n/a eq(x & 0, 0)
236n/a eq(x | 0, x)
237n/a eq(x ^ 0, x)
238n/a eq(x & -1, x)
239n/a eq(x | -1, -1)
240n/a eq(x ^ -1, ~x)
241n/a eq(x, ~~x)
242n/a eq(x & x, x)
243n/a eq(x | x, x)
244n/a eq(x ^ x, 0)
245n/a eq(x & ~x, 0)
246n/a eq(x | ~x, -1)
247n/a eq(x ^ ~x, -1)
248n/a eq(-x, 1 + ~x)
249n/a eq(-x, ~(x-1))
250n/a for n in range(2*SHIFT):
251n/a p2 = 2 ** n
252n/a with self.subTest(x=x, n=n, p2=p2):
253n/a eq(x << n >> n, x)
254n/a eq(x // p2, x >> n)
255n/a eq(x * p2, x << n)
256n/a eq(x & -p2, x >> n << n)
257n/a eq(x & -p2, x & ~(p2 - 1))
258n/a
259n/a def check_bitop_identities_2(self, x, y):
260n/a eq = self.assertEqual
261n/a with self.subTest(x=x, y=y):
262n/a eq(x & y, y & x)
263n/a eq(x | y, y | x)
264n/a eq(x ^ y, y ^ x)
265n/a eq(x ^ y ^ x, y)
266n/a eq(x & y, ~(~x | ~y))
267n/a eq(x | y, ~(~x & ~y))
268n/a eq(x ^ y, (x | y) & ~(x & y))
269n/a eq(x ^ y, (x & ~y) | (~x & y))
270n/a eq(x ^ y, (x | y) & (~x | ~y))
271n/a
272n/a def check_bitop_identities_3(self, x, y, z):
273n/a eq = self.assertEqual
274n/a with self.subTest(x=x, y=y, z=z):
275n/a eq((x & y) & z, x & (y & z))
276n/a eq((x | y) | z, x | (y | z))
277n/a eq((x ^ y) ^ z, x ^ (y ^ z))
278n/a eq(x & (y | z), (x & y) | (x & z))
279n/a eq(x | (y & z), (x | y) & (x | z))
280n/a
281n/a def test_bitop_identities(self):
282n/a for x in special:
283n/a self.check_bitop_identities_1(x)
284n/a digits = range(1, MAXDIGITS+1)
285n/a for lenx in digits:
286n/a x = self.getran(lenx)
287n/a self.check_bitop_identities_1(x)
288n/a for leny in digits:
289n/a y = self.getran(leny)
290n/a self.check_bitop_identities_2(x, y)
291n/a self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
292n/a
293n/a def slow_format(self, x, base):
294n/a digits = []
295n/a sign = 0
296n/a if x < 0:
297n/a sign, x = 1, -x
298n/a while x:
299n/a x, r = divmod(x, base)
300n/a digits.append(int(r))
301n/a digits.reverse()
302n/a digits = digits or [0]
303n/a return '-'[:sign] + \
304n/a {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
305n/a "".join("0123456789abcdef"[i] for i in digits)
306n/a
307n/a def check_format_1(self, x):
308n/a for base, mapper in (2, bin), (8, oct), (10, str), (10, repr), (16, hex):
309n/a got = mapper(x)
310n/a with self.subTest(x=x, mapper=mapper.__name__):
311n/a expected = self.slow_format(x, base)
312n/a self.assertEqual(got, expected)
313n/a with self.subTest(got=got):
314n/a self.assertEqual(int(got, 0), x)
315n/a
316n/a def test_format(self):
317n/a for x in special:
318n/a self.check_format_1(x)
319n/a for i in range(10):
320n/a for lenx in range(1, MAXDIGITS+1):
321n/a x = self.getran(lenx)
322n/a self.check_format_1(x)
323n/a
324n/a def test_long(self):
325n/a # Check conversions from string
326n/a LL = [
327n/a ('1' + '0'*20, 10**20),
328n/a ('1' + '0'*100, 10**100)
329n/a ]
330n/a for s, v in LL:
331n/a for sign in "", "+", "-":
332n/a for prefix in "", " ", "\t", " \t\t ":
333n/a ss = prefix + sign + s
334n/a vv = v
335n/a if sign == "-" and v is not ValueError:
336n/a vv = -v
337n/a try:
338n/a self.assertEqual(int(ss), vv)
339n/a except ValueError:
340n/a pass
341n/a
342n/a # trailing L should no longer be accepted...
343n/a self.assertRaises(ValueError, int, '123L')
344n/a self.assertRaises(ValueError, int, '123l')
345n/a self.assertRaises(ValueError, int, '0L')
346n/a self.assertRaises(ValueError, int, '-37L')
347n/a self.assertRaises(ValueError, int, '0x32L', 16)
348n/a self.assertRaises(ValueError, int, '1L', 21)
349n/a # ... but it's just a normal digit if base >= 22
350n/a self.assertEqual(int('1L', 22), 43)
351n/a
352n/a # tests with base 0
353n/a self.assertEqual(int('000', 0), 0)
354n/a self.assertEqual(int('0o123', 0), 83)
355n/a self.assertEqual(int('0x123', 0), 291)
356n/a self.assertEqual(int('0b100', 0), 4)
357n/a self.assertEqual(int(' 0O123 ', 0), 83)
358n/a self.assertEqual(int(' 0X123 ', 0), 291)
359n/a self.assertEqual(int(' 0B100 ', 0), 4)
360n/a self.assertEqual(int('0', 0), 0)
361n/a self.assertEqual(int('+0', 0), 0)
362n/a self.assertEqual(int('-0', 0), 0)
363n/a self.assertEqual(int('00', 0), 0)
364n/a self.assertRaises(ValueError, int, '08', 0)
365n/a self.assertRaises(ValueError, int, '-012395', 0)
366n/a
367n/a # invalid bases
368n/a invalid_bases = [-909,
369n/a 2**31-1, 2**31, -2**31, -2**31-1,
370n/a 2**63-1, 2**63, -2**63, -2**63-1,
371n/a 2**100, -2**100,
372n/a ]
373n/a for base in invalid_bases:
374n/a self.assertRaises(ValueError, int, '42', base)
375n/a
376n/a
377n/a def test_conversion(self):
378n/a
379n/a class JustLong:
380n/a # test that __long__ no longer used in 3.x
381n/a def __long__(self):
382n/a return 42
383n/a self.assertRaises(TypeError, int, JustLong())
384n/a
385n/a class LongTrunc:
386n/a # __long__ should be ignored in 3.x
387n/a def __long__(self):
388n/a return 42
389n/a def __trunc__(self):
390n/a return 1729
391n/a self.assertEqual(int(LongTrunc()), 1729)
392n/a
393n/a def check_float_conversion(self, n):
394n/a # Check that int -> float conversion behaviour matches
395n/a # that of the pure Python version above.
396n/a try:
397n/a actual = float(n)
398n/a except OverflowError:
399n/a actual = 'overflow'
400n/a
401n/a try:
402n/a expected = int_to_float(n)
403n/a except OverflowError:
404n/a expected = 'overflow'
405n/a
406n/a msg = ("Error in conversion of integer {} to float. "
407n/a "Got {}, expected {}.".format(n, actual, expected))
408n/a self.assertEqual(actual, expected, msg)
409n/a
410n/a @support.requires_IEEE_754
411n/a def test_float_conversion(self):
412n/a
413n/a exact_values = [0, 1, 2,
414n/a 2**53-3,
415n/a 2**53-2,
416n/a 2**53-1,
417n/a 2**53,
418n/a 2**53+2,
419n/a 2**54-4,
420n/a 2**54-2,
421n/a 2**54,
422n/a 2**54+4]
423n/a for x in exact_values:
424n/a self.assertEqual(float(x), x)
425n/a self.assertEqual(float(-x), -x)
426n/a
427n/a # test round-half-even
428n/a for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
429n/a for p in range(15):
430n/a self.assertEqual(int(float(2**p*(2**53+x))), 2**p*(2**53+y))
431n/a
432n/a for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
433n/a (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
434n/a (13, 12), (14, 16), (15, 16)]:
435n/a for p in range(15):
436n/a self.assertEqual(int(float(2**p*(2**54+x))), 2**p*(2**54+y))
437n/a
438n/a # behaviour near extremes of floating-point range
439n/a int_dbl_max = int(DBL_MAX)
440n/a top_power = 2**DBL_MAX_EXP
441n/a halfway = (int_dbl_max + top_power)//2
442n/a self.assertEqual(float(int_dbl_max), DBL_MAX)
443n/a self.assertEqual(float(int_dbl_max+1), DBL_MAX)
444n/a self.assertEqual(float(halfway-1), DBL_MAX)
445n/a self.assertRaises(OverflowError, float, halfway)
446n/a self.assertEqual(float(1-halfway), -DBL_MAX)
447n/a self.assertRaises(OverflowError, float, -halfway)
448n/a self.assertRaises(OverflowError, float, top_power-1)
449n/a self.assertRaises(OverflowError, float, top_power)
450n/a self.assertRaises(OverflowError, float, top_power+1)
451n/a self.assertRaises(OverflowError, float, 2*top_power-1)
452n/a self.assertRaises(OverflowError, float, 2*top_power)
453n/a self.assertRaises(OverflowError, float, top_power*top_power)
454n/a
455n/a for p in range(100):
456n/a x = 2**p * (2**53 + 1) + 1
457n/a y = 2**p * (2**53 + 2)
458n/a self.assertEqual(int(float(x)), y)
459n/a
460n/a x = 2**p * (2**53 + 1)
461n/a y = 2**p * 2**53
462n/a self.assertEqual(int(float(x)), y)
463n/a
464n/a # Compare builtin float conversion with pure Python int_to_float
465n/a # function above.
466n/a test_values = [
467n/a int_dbl_max-1, int_dbl_max, int_dbl_max+1,
468n/a halfway-1, halfway, halfway + 1,
469n/a top_power-1, top_power, top_power+1,
470n/a 2*top_power-1, 2*top_power, top_power*top_power,
471n/a ]
472n/a test_values.extend(exact_values)
473n/a for p in range(-4, 8):
474n/a for x in range(-128, 128):
475n/a test_values.append(2**(p+53) + x)
476n/a for value in test_values:
477n/a self.check_float_conversion(value)
478n/a self.check_float_conversion(-value)
479n/a
480n/a def test_float_overflow(self):
481n/a for x in -2.0, -1.0, 0.0, 1.0, 2.0:
482n/a self.assertEqual(float(int(x)), x)
483n/a
484n/a shuge = '12345' * 120
485n/a huge = 1 << 30000
486n/a mhuge = -huge
487n/a namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
488n/a for test in ["float(huge)", "float(mhuge)",
489n/a "complex(huge)", "complex(mhuge)",
490n/a "complex(huge, 1)", "complex(mhuge, 1)",
491n/a "complex(1, huge)", "complex(1, mhuge)",
492n/a "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
493n/a "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
494n/a "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
495n/a "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
496n/a "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
497n/a "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
498n/a "math.sin(huge)", "math.sin(mhuge)",
499n/a "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
500n/a # math.floor() of an int returns an int now
501n/a ##"math.floor(huge)", "math.floor(mhuge)",
502n/a ]:
503n/a
504n/a self.assertRaises(OverflowError, eval, test, namespace)
505n/a
506n/a # XXX Perhaps float(shuge) can raise OverflowError on some box?
507n/a # The comparison should not.
508n/a self.assertNotEqual(float(shuge), int(shuge),
509n/a "float(shuge) should not equal int(shuge)")
510n/a
511n/a def test_logs(self):
512n/a LOG10E = math.log10(math.e)
513n/a
514n/a for exp in list(range(10)) + [100, 1000, 10000]:
515n/a value = 10 ** exp
516n/a log10 = math.log10(value)
517n/a self.assertAlmostEqual(log10, exp)
518n/a
519n/a # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
520n/a # exp/LOG10E
521n/a expected = exp / LOG10E
522n/a log = math.log(value)
523n/a self.assertAlmostEqual(log, expected)
524n/a
525n/a for bad in -(1 << 10000), -2, 0:
526n/a self.assertRaises(ValueError, math.log, bad)
527n/a self.assertRaises(ValueError, math.log10, bad)
528n/a
529n/a def test_mixed_compares(self):
530n/a eq = self.assertEqual
531n/a
532n/a # We're mostly concerned with that mixing floats and ints does the
533n/a # right stuff, even when ints are too large to fit in a float.
534n/a # The safest way to check the results is to use an entirely different
535n/a # method, which we do here via a skeletal rational class (which
536n/a # represents all Python ints and floats exactly).
537n/a class Rat:
538n/a def __init__(self, value):
539n/a if isinstance(value, int):
540n/a self.n = value
541n/a self.d = 1
542n/a elif isinstance(value, float):
543n/a # Convert to exact rational equivalent.
544n/a f, e = math.frexp(abs(value))
545n/a assert f == 0 or 0.5 <= f < 1.0
546n/a # |value| = f * 2**e exactly
547n/a
548n/a # Suck up CHUNK bits at a time; 28 is enough so that we suck
549n/a # up all bits in 2 iterations for all known binary double-
550n/a # precision formats, and small enough to fit in an int.
551n/a CHUNK = 28
552n/a top = 0
553n/a # invariant: |value| = (top + f) * 2**e exactly
554n/a while f:
555n/a f = math.ldexp(f, CHUNK)
556n/a digit = int(f)
557n/a assert digit >> CHUNK == 0
558n/a top = (top << CHUNK) | digit
559n/a f -= digit
560n/a assert 0.0 <= f < 1.0
561n/a e -= CHUNK
562n/a
563n/a # Now |value| = top * 2**e exactly.
564n/a if e >= 0:
565n/a n = top << e
566n/a d = 1
567n/a else:
568n/a n = top
569n/a d = 1 << -e
570n/a if value < 0:
571n/a n = -n
572n/a self.n = n
573n/a self.d = d
574n/a assert float(n) / float(d) == value
575n/a else:
576n/a raise TypeError("can't deal with %r" % value)
577n/a
578n/a def _cmp__(self, other):
579n/a if not isinstance(other, Rat):
580n/a other = Rat(other)
581n/a x, y = self.n * other.d, self.d * other.n
582n/a return (x > y) - (x < y)
583n/a def __eq__(self, other):
584n/a return self._cmp__(other) == 0
585n/a def __ge__(self, other):
586n/a return self._cmp__(other) >= 0
587n/a def __gt__(self, other):
588n/a return self._cmp__(other) > 0
589n/a def __le__(self, other):
590n/a return self._cmp__(other) <= 0
591n/a def __lt__(self, other):
592n/a return self._cmp__(other) < 0
593n/a
594n/a cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
595n/a # 2**48 is an important boundary in the internals. 2**53 is an
596n/a # important boundary for IEEE double precision.
597n/a for t in 2.0**48, 2.0**50, 2.0**53:
598n/a cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
599n/a int(t-1), int(t), int(t+1)])
600n/a cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
601n/a # 1 << 20000 should exceed all double formats. int(1e200) is to
602n/a # check that we get equality with 1e200 above.
603n/a t = int(1e200)
604n/a cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
605n/a cases.extend([-x for x in cases])
606n/a for x in cases:
607n/a Rx = Rat(x)
608n/a for y in cases:
609n/a Ry = Rat(y)
610n/a Rcmp = (Rx > Ry) - (Rx < Ry)
611n/a with self.subTest(x=x, y=y, Rcmp=Rcmp):
612n/a xycmp = (x > y) - (x < y)
613n/a eq(Rcmp, xycmp)
614n/a eq(x == y, Rcmp == 0)
615n/a eq(x != y, Rcmp != 0)
616n/a eq(x < y, Rcmp < 0)
617n/a eq(x <= y, Rcmp <= 0)
618n/a eq(x > y, Rcmp > 0)
619n/a eq(x >= y, Rcmp >= 0)
620n/a
621n/a def test__format__(self):
622n/a self.assertEqual(format(123456789, 'd'), '123456789')
623n/a self.assertEqual(format(123456789, 'd'), '123456789')
624n/a self.assertEqual(format(123456789, ','), '123,456,789')
625n/a self.assertEqual(format(123456789, '_'), '123_456_789')
626n/a
627n/a # sign and aligning are interdependent
628n/a self.assertEqual(format(1, "-"), '1')
629n/a self.assertEqual(format(-1, "-"), '-1')
630n/a self.assertEqual(format(1, "-3"), ' 1')
631n/a self.assertEqual(format(-1, "-3"), ' -1')
632n/a self.assertEqual(format(1, "+3"), ' +1')
633n/a self.assertEqual(format(-1, "+3"), ' -1')
634n/a self.assertEqual(format(1, " 3"), ' 1')
635n/a self.assertEqual(format(-1, " 3"), ' -1')
636n/a self.assertEqual(format(1, " "), ' 1')
637n/a self.assertEqual(format(-1, " "), '-1')
638n/a
639n/a # hex
640n/a self.assertEqual(format(3, "x"), "3")
641n/a self.assertEqual(format(3, "X"), "3")
642n/a self.assertEqual(format(1234, "x"), "4d2")
643n/a self.assertEqual(format(-1234, "x"), "-4d2")
644n/a self.assertEqual(format(1234, "8x"), " 4d2")
645n/a self.assertEqual(format(-1234, "8x"), " -4d2")
646n/a self.assertEqual(format(1234, "x"), "4d2")
647n/a self.assertEqual(format(-1234, "x"), "-4d2")
648n/a self.assertEqual(format(-3, "x"), "-3")
649n/a self.assertEqual(format(-3, "X"), "-3")
650n/a self.assertEqual(format(int('be', 16), "x"), "be")
651n/a self.assertEqual(format(int('be', 16), "X"), "BE")
652n/a self.assertEqual(format(-int('be', 16), "x"), "-be")
653n/a self.assertEqual(format(-int('be', 16), "X"), "-BE")
654n/a self.assertRaises(ValueError, format, 1234567890, ',x')
655n/a self.assertEqual(format(1234567890, '_x'), '4996_02d2')
656n/a self.assertEqual(format(1234567890, '_X'), '4996_02D2')
657n/a
658n/a # octal
659n/a self.assertEqual(format(3, "o"), "3")
660n/a self.assertEqual(format(-3, "o"), "-3")
661n/a self.assertEqual(format(1234, "o"), "2322")
662n/a self.assertEqual(format(-1234, "o"), "-2322")
663n/a self.assertEqual(format(1234, "-o"), "2322")
664n/a self.assertEqual(format(-1234, "-o"), "-2322")
665n/a self.assertEqual(format(1234, " o"), " 2322")
666n/a self.assertEqual(format(-1234, " o"), "-2322")
667n/a self.assertEqual(format(1234, "+o"), "+2322")
668n/a self.assertEqual(format(-1234, "+o"), "-2322")
669n/a self.assertRaises(ValueError, format, 1234567890, ',o')
670n/a self.assertEqual(format(1234567890, '_o'), '111_4540_1322')
671n/a
672n/a # binary
673n/a self.assertEqual(format(3, "b"), "11")
674n/a self.assertEqual(format(-3, "b"), "-11")
675n/a self.assertEqual(format(1234, "b"), "10011010010")
676n/a self.assertEqual(format(-1234, "b"), "-10011010010")
677n/a self.assertEqual(format(1234, "-b"), "10011010010")
678n/a self.assertEqual(format(-1234, "-b"), "-10011010010")
679n/a self.assertEqual(format(1234, " b"), " 10011010010")
680n/a self.assertEqual(format(-1234, " b"), "-10011010010")
681n/a self.assertEqual(format(1234, "+b"), "+10011010010")
682n/a self.assertEqual(format(-1234, "+b"), "-10011010010")
683n/a self.assertRaises(ValueError, format, 1234567890, ',b')
684n/a self.assertEqual(format(12345, '_b'), '11_0000_0011_1001')
685n/a
686n/a # make sure these are errors
687n/a self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed
688n/a self.assertRaises(ValueError, format, 3, "_c") # underscore,
689n/a self.assertRaises(ValueError, format, 3, ",c") # comma, and
690n/a self.assertRaises(ValueError, format, 3, "+c") # sign not allowed
691n/a # with 'c'
692n/a
693n/a self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, '_,')
694n/a self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, ',_')
695n/a self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, '_,d')
696n/a self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, ',_d')
697n/a
698n/a # ensure that only int and float type specifiers work
699n/a for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
700n/a [chr(x) for x in range(ord('A'), ord('Z')+1)]):
701n/a if not format_spec in 'bcdoxXeEfFgGn%':
702n/a self.assertRaises(ValueError, format, 0, format_spec)
703n/a self.assertRaises(ValueError, format, 1, format_spec)
704n/a self.assertRaises(ValueError, format, -1, format_spec)
705n/a self.assertRaises(ValueError, format, 2**100, format_spec)
706n/a self.assertRaises(ValueError, format, -(2**100), format_spec)
707n/a
708n/a # ensure that float type specifiers work; format converts
709n/a # the int to a float
710n/a for format_spec in 'eEfFgG%':
711n/a for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
712n/a self.assertEqual(format(value, format_spec),
713n/a format(float(value), format_spec))
714n/a
715n/a def test_nan_inf(self):
716n/a self.assertRaises(OverflowError, int, float('inf'))
717n/a self.assertRaises(OverflowError, int, float('-inf'))
718n/a self.assertRaises(ValueError, int, float('nan'))
719n/a
720n/a def test_mod_division(self):
721n/a with self.assertRaises(ZeroDivisionError):
722n/a _ = 1 % 0
723n/a
724n/a self.assertEqual(13 % 10, 3)
725n/a self.assertEqual(-13 % 10, 7)
726n/a self.assertEqual(13 % -10, -7)
727n/a self.assertEqual(-13 % -10, -3)
728n/a
729n/a self.assertEqual(12 % 4, 0)
730n/a self.assertEqual(-12 % 4, 0)
731n/a self.assertEqual(12 % -4, 0)
732n/a self.assertEqual(-12 % -4, 0)
733n/a
734n/a def test_true_division(self):
735n/a huge = 1 << 40000
736n/a mhuge = -huge
737n/a self.assertEqual(huge / huge, 1.0)
738n/a self.assertEqual(mhuge / mhuge, 1.0)
739n/a self.assertEqual(huge / mhuge, -1.0)
740n/a self.assertEqual(mhuge / huge, -1.0)
741n/a self.assertEqual(1 / huge, 0.0)
742n/a self.assertEqual(1 / huge, 0.0)
743n/a self.assertEqual(1 / mhuge, 0.0)
744n/a self.assertEqual(1 / mhuge, 0.0)
745n/a self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
746n/a self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
747n/a self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
748n/a self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
749n/a self.assertEqual(huge / (huge << 1), 0.5)
750n/a self.assertEqual((1000000 * huge) / huge, 1000000)
751n/a
752n/a namespace = {'huge': huge, 'mhuge': mhuge}
753n/a
754n/a for overflow in ["float(huge)", "float(mhuge)",
755n/a "huge / 1", "huge / 2", "huge / -1", "huge / -2",
756n/a "mhuge / 100", "mhuge / 200"]:
757n/a self.assertRaises(OverflowError, eval, overflow, namespace)
758n/a
759n/a for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
760n/a "100 / mhuge", "200 / mhuge"]:
761n/a result = eval(underflow, namespace)
762n/a self.assertEqual(result, 0.0,
763n/a "expected underflow to 0 from %r" % underflow)
764n/a
765n/a for zero in ["huge / 0", "mhuge / 0"]:
766n/a self.assertRaises(ZeroDivisionError, eval, zero, namespace)
767n/a
768n/a def test_floordiv(self):
769n/a with self.assertRaises(ZeroDivisionError):
770n/a _ = 1 // 0
771n/a
772n/a self.assertEqual(2 // 3, 0)
773n/a self.assertEqual(2 // -3, -1)
774n/a self.assertEqual(-2 // 3, -1)
775n/a self.assertEqual(-2 // -3, 0)
776n/a
777n/a self.assertEqual(-11 // -3, 3)
778n/a self.assertEqual(-11 // 3, -4)
779n/a self.assertEqual(11 // -3, -4)
780n/a self.assertEqual(11 // 3, 3)
781n/a
782n/a self.assertEqual(-12 // -3, 4)
783n/a self.assertEqual(-12 // 3, -4)
784n/a self.assertEqual(12 // -3, -4)
785n/a self.assertEqual(12 // 3, 4)
786n/a
787n/a def check_truediv(self, a, b, skip_small=True):
788n/a """Verify that the result of a/b is correctly rounded, by
789n/a comparing it with a pure Python implementation of correctly
790n/a rounded division. b should be nonzero."""
791n/a
792n/a # skip check for small a and b: in this case, the current
793n/a # implementation converts the arguments to float directly and
794n/a # then applies a float division. This can give doubly-rounded
795n/a # results on x87-using machines (particularly 32-bit Linux).
796n/a if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
797n/a return
798n/a
799n/a try:
800n/a # use repr so that we can distinguish between -0.0 and 0.0
801n/a expected = repr(truediv(a, b))
802n/a except OverflowError:
803n/a expected = 'overflow'
804n/a except ZeroDivisionError:
805n/a expected = 'zerodivision'
806n/a
807n/a try:
808n/a got = repr(a / b)
809n/a except OverflowError:
810n/a got = 'overflow'
811n/a except ZeroDivisionError:
812n/a got = 'zerodivision'
813n/a
814n/a self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
815n/a "expected {}, got {}".format(a, b, expected, got))
816n/a
817n/a @support.requires_IEEE_754
818n/a def test_correctly_rounded_true_division(self):
819n/a # more stringent tests than those above, checking that the
820n/a # result of true division of ints is always correctly rounded.
821n/a # This test should probably be considered CPython-specific.
822n/a
823n/a # Exercise all the code paths not involving Gb-sized ints.
824n/a # ... divisions involving zero
825n/a self.check_truediv(123, 0)
826n/a self.check_truediv(-456, 0)
827n/a self.check_truediv(0, 3)
828n/a self.check_truediv(0, -3)
829n/a self.check_truediv(0, 0)
830n/a # ... overflow or underflow by large margin
831n/a self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
832n/a self.check_truediv(12345, 345678 * 2**(DBL_MANT_DIG - DBL_MIN_EXP))
833n/a # ... a much larger or smaller than b
834n/a self.check_truediv(12345*2**100, 98765)
835n/a self.check_truediv(12345*2**30, 98765*7**81)
836n/a # ... a / b near a boundary: one of 1, 2**DBL_MANT_DIG, 2**DBL_MIN_EXP,
837n/a # 2**DBL_MAX_EXP, 2**(DBL_MIN_EXP-DBL_MANT_DIG)
838n/a bases = (0, DBL_MANT_DIG, DBL_MIN_EXP,
839n/a DBL_MAX_EXP, DBL_MIN_EXP - DBL_MANT_DIG)
840n/a for base in bases:
841n/a for exp in range(base - 15, base + 15):
842n/a self.check_truediv(75312*2**max(exp, 0), 69187*2**max(-exp, 0))
843n/a self.check_truediv(69187*2**max(exp, 0), 75312*2**max(-exp, 0))
844n/a
845n/a # overflow corner case
846n/a for m in [1, 2, 7, 17, 12345, 7**100,
847n/a -1, -2, -5, -23, -67891, -41**50]:
848n/a for n in range(-10, 10):
849n/a self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
850n/a self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
851n/a
852n/a # check detection of inexactness in shifting stage
853n/a for n in range(250):
854n/a # (2**DBL_MANT_DIG+1)/(2**DBL_MANT_DIG) lies halfway
855n/a # between two representable floats, and would usually be
856n/a # rounded down under round-half-to-even. The tiniest of
857n/a # additions to the numerator should cause it to be rounded
858n/a # up instead.
859n/a self.check_truediv((2**DBL_MANT_DIG + 1)*12345*2**200 + 2**n,
860n/a 2**DBL_MANT_DIG*12345)
861n/a
862n/a # 1/2731 is one of the smallest division cases that's subject
863n/a # to double rounding on IEEE 754 machines working internally with
864n/a # 64-bit precision. On such machines, the next check would fail,
865n/a # were it not explicitly skipped in check_truediv.
866n/a self.check_truediv(1, 2731)
867n/a
868n/a # a particularly bad case for the old algorithm: gives an
869n/a # error of close to 3.5 ulps.
870n/a self.check_truediv(295147931372582273023, 295147932265116303360)
871n/a for i in range(1000):
872n/a self.check_truediv(10**(i+1), 10**i)
873n/a self.check_truediv(10**i, 10**(i+1))
874n/a
875n/a # test round-half-to-even behaviour, normal result
876n/a for m in [1, 2, 4, 7, 8, 16, 17, 32, 12345, 7**100,
877n/a -1, -2, -5, -23, -67891, -41**50]:
878n/a for n in range(-10, 10):
879n/a self.check_truediv(2**DBL_MANT_DIG*m + n, m)
880n/a
881n/a # test round-half-to-even, subnormal result
882n/a for n in range(-20, 20):
883n/a self.check_truediv(n, 2**1076)
884n/a
885n/a # largeish random divisions: a/b where |a| <= |b| <=
886n/a # 2*|a|; |ans| is between 0.5 and 1.0, so error should
887n/a # always be bounded by 2**-54 with equality possible only
888n/a # if the least significant bit of q=ans*2**53 is zero.
889n/a for M in [10**10, 10**100, 10**1000]:
890n/a for i in range(1000):
891n/a a = random.randrange(1, M)
892n/a b = random.randrange(a, 2*a+1)
893n/a self.check_truediv(a, b)
894n/a self.check_truediv(-a, b)
895n/a self.check_truediv(a, -b)
896n/a self.check_truediv(-a, -b)
897n/a
898n/a # and some (genuinely) random tests
899n/a for _ in range(10000):
900n/a a_bits = random.randrange(1000)
901n/a b_bits = random.randrange(1, 1000)
902n/a x = random.randrange(2**a_bits)
903n/a y = random.randrange(1, 2**b_bits)
904n/a self.check_truediv(x, y)
905n/a self.check_truediv(x, -y)
906n/a self.check_truediv(-x, y)
907n/a self.check_truediv(-x, -y)
908n/a
909n/a def test_lshift_of_zero(self):
910n/a self.assertEqual(0 << 0, 0)
911n/a self.assertEqual(0 << 10, 0)
912n/a with self.assertRaises(ValueError):
913n/a 0 << -1
914n/a
915n/a @support.cpython_only
916n/a def test_huge_lshift_of_zero(self):
917n/a # Shouldn't try to allocate memory for a huge shift. See issue #27870.
918n/a # Other implementations may have a different boundary for overflow,
919n/a # or not raise at all.
920n/a self.assertEqual(0 << sys.maxsize, 0)
921n/a with self.assertRaises(OverflowError):
922n/a 0 << (sys.maxsize + 1)
923n/a
924n/a def test_small_ints(self):
925n/a for i in range(-5, 257):
926n/a self.assertIs(i, i + 0)
927n/a self.assertIs(i, i * 1)
928n/a self.assertIs(i, i - 0)
929n/a self.assertIs(i, i // 1)
930n/a self.assertIs(i, i & -1)
931n/a self.assertIs(i, i | 0)
932n/a self.assertIs(i, i ^ 0)
933n/a self.assertIs(i, ~~i)
934n/a self.assertIs(i, i**1)
935n/a self.assertIs(i, int(str(i)))
936n/a self.assertIs(i, i<<2>>2, str(i))
937n/a # corner cases
938n/a i = 1 << 70
939n/a self.assertIs(i - i, 0)
940n/a self.assertIs(0 * i, 0)
941n/a
942n/a def test_bit_length(self):
943n/a tiny = 1e-10
944n/a for x in range(-65000, 65000):
945n/a k = x.bit_length()
946n/a # Check equivalence with Python version
947n/a self.assertEqual(k, len(bin(x).lstrip('-0b')))
948n/a # Behaviour as specified in the docs
949n/a if x != 0:
950n/a self.assertTrue(2**(k-1) <= abs(x) < 2**k)
951n/a else:
952n/a self.assertEqual(k, 0)
953n/a # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
954n/a if x != 0:
955n/a # When x is an exact power of 2, numeric errors can
956n/a # cause floor(log(x)/log(2)) to be one too small; for
957n/a # small x this can be fixed by adding a small quantity
958n/a # to the quotient before taking the floor.
959n/a self.assertEqual(k, 1 + math.floor(
960n/a math.log(abs(x))/math.log(2) + tiny))
961n/a
962n/a self.assertEqual((0).bit_length(), 0)
963n/a self.assertEqual((1).bit_length(), 1)
964n/a self.assertEqual((-1).bit_length(), 1)
965n/a self.assertEqual((2).bit_length(), 2)
966n/a self.assertEqual((-2).bit_length(), 2)
967n/a for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
968n/a a = 2**i
969n/a self.assertEqual((a-1).bit_length(), i)
970n/a self.assertEqual((1-a).bit_length(), i)
971n/a self.assertEqual((a).bit_length(), i+1)
972n/a self.assertEqual((-a).bit_length(), i+1)
973n/a self.assertEqual((a+1).bit_length(), i+1)
974n/a self.assertEqual((-a-1).bit_length(), i+1)
975n/a
976n/a def test_round(self):
977n/a # check round-half-even algorithm. For round to nearest ten;
978n/a # rounding map is invariant under adding multiples of 20
979n/a test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
980n/a 6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
981n/a 15:20, 16:20, 17:20, 18:20, 19:20}
982n/a for offset in range(-520, 520, 20):
983n/a for k, v in test_dict.items():
984n/a got = round(k+offset, -1)
985n/a expected = v+offset
986n/a self.assertEqual(got, expected)
987n/a self.assertIs(type(got), int)
988n/a
989n/a # larger second argument
990n/a self.assertEqual(round(-150, -2), -200)
991n/a self.assertEqual(round(-149, -2), -100)
992n/a self.assertEqual(round(-51, -2), -100)
993n/a self.assertEqual(round(-50, -2), 0)
994n/a self.assertEqual(round(-49, -2), 0)
995n/a self.assertEqual(round(-1, -2), 0)
996n/a self.assertEqual(round(0, -2), 0)
997n/a self.assertEqual(round(1, -2), 0)
998n/a self.assertEqual(round(49, -2), 0)
999n/a self.assertEqual(round(50, -2), 0)
1000n/a self.assertEqual(round(51, -2), 100)
1001n/a self.assertEqual(round(149, -2), 100)
1002n/a self.assertEqual(round(150, -2), 200)
1003n/a self.assertEqual(round(250, -2), 200)
1004n/a self.assertEqual(round(251, -2), 300)
1005n/a self.assertEqual(round(172500, -3), 172000)
1006n/a self.assertEqual(round(173500, -3), 174000)
1007n/a self.assertEqual(round(31415926535, -1), 31415926540)
1008n/a self.assertEqual(round(31415926535, -2), 31415926500)
1009n/a self.assertEqual(round(31415926535, -3), 31415927000)
1010n/a self.assertEqual(round(31415926535, -4), 31415930000)
1011n/a self.assertEqual(round(31415926535, -5), 31415900000)
1012n/a self.assertEqual(round(31415926535, -6), 31416000000)
1013n/a self.assertEqual(round(31415926535, -7), 31420000000)
1014n/a self.assertEqual(round(31415926535, -8), 31400000000)
1015n/a self.assertEqual(round(31415926535, -9), 31000000000)
1016n/a self.assertEqual(round(31415926535, -10), 30000000000)
1017n/a self.assertEqual(round(31415926535, -11), 0)
1018n/a self.assertEqual(round(31415926535, -12), 0)
1019n/a self.assertEqual(round(31415926535, -999), 0)
1020n/a
1021n/a # should get correct results even for huge inputs
1022n/a for k in range(10, 100):
1023n/a got = round(10**k + 324678, -3)
1024n/a expect = 10**k + 325000
1025n/a self.assertEqual(got, expect)
1026n/a self.assertIs(type(got), int)
1027n/a
1028n/a # nonnegative second argument: round(x, n) should just return x
1029n/a for n in range(5):
1030n/a for i in range(100):
1031n/a x = random.randrange(-10000, 10000)
1032n/a got = round(x, n)
1033n/a self.assertEqual(got, x)
1034n/a self.assertIs(type(got), int)
1035n/a for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
1036n/a self.assertEqual(round(8979323, huge_n), 8979323)
1037n/a
1038n/a # omitted second argument
1039n/a for i in range(100):
1040n/a x = random.randrange(-10000, 10000)
1041n/a got = round(x)
1042n/a self.assertEqual(got, x)
1043n/a self.assertIs(type(got), int)
1044n/a
1045n/a # bad second argument
1046n/a bad_exponents = ('brian', 2.0, 0j)
1047n/a for e in bad_exponents:
1048n/a self.assertRaises(TypeError, round, 3, e)
1049n/a
1050n/a def test_to_bytes(self):
1051n/a def check(tests, byteorder, signed=False):
1052n/a for test, expected in tests.items():
1053n/a try:
1054n/a self.assertEqual(
1055n/a test.to_bytes(len(expected), byteorder, signed=signed),
1056n/a expected)
1057n/a except Exception as err:
1058n/a raise AssertionError(
1059n/a "failed to convert {0} with byteorder={1} and signed={2}"
1060n/a .format(test, byteorder, signed)) from err
1061n/a
1062n/a # Convert integers to signed big-endian byte arrays.
1063n/a tests1 = {
1064n/a 0: b'\x00',
1065n/a 1: b'\x01',
1066n/a -1: b'\xff',
1067n/a -127: b'\x81',
1068n/a -128: b'\x80',
1069n/a -129: b'\xff\x7f',
1070n/a 127: b'\x7f',
1071n/a 129: b'\x00\x81',
1072n/a -255: b'\xff\x01',
1073n/a -256: b'\xff\x00',
1074n/a 255: b'\x00\xff',
1075n/a 256: b'\x01\x00',
1076n/a 32767: b'\x7f\xff',
1077n/a -32768: b'\xff\x80\x00',
1078n/a 65535: b'\x00\xff\xff',
1079n/a -65536: b'\xff\x00\x00',
1080n/a -8388608: b'\x80\x00\x00'
1081n/a }
1082n/a check(tests1, 'big', signed=True)
1083n/a
1084n/a # Convert integers to signed little-endian byte arrays.
1085n/a tests2 = {
1086n/a 0: b'\x00',
1087n/a 1: b'\x01',
1088n/a -1: b'\xff',
1089n/a -127: b'\x81',
1090n/a -128: b'\x80',
1091n/a -129: b'\x7f\xff',
1092n/a 127: b'\x7f',
1093n/a 129: b'\x81\x00',
1094n/a -255: b'\x01\xff',
1095n/a -256: b'\x00\xff',
1096n/a 255: b'\xff\x00',
1097n/a 256: b'\x00\x01',
1098n/a 32767: b'\xff\x7f',
1099n/a -32768: b'\x00\x80',
1100n/a 65535: b'\xff\xff\x00',
1101n/a -65536: b'\x00\x00\xff',
1102n/a -8388608: b'\x00\x00\x80'
1103n/a }
1104n/a check(tests2, 'little', signed=True)
1105n/a
1106n/a # Convert integers to unsigned big-endian byte arrays.
1107n/a tests3 = {
1108n/a 0: b'\x00',
1109n/a 1: b'\x01',
1110n/a 127: b'\x7f',
1111n/a 128: b'\x80',
1112n/a 255: b'\xff',
1113n/a 256: b'\x01\x00',
1114n/a 32767: b'\x7f\xff',
1115n/a 32768: b'\x80\x00',
1116n/a 65535: b'\xff\xff',
1117n/a 65536: b'\x01\x00\x00'
1118n/a }
1119n/a check(tests3, 'big', signed=False)
1120n/a
1121n/a # Convert integers to unsigned little-endian byte arrays.
1122n/a tests4 = {
1123n/a 0: b'\x00',
1124n/a 1: b'\x01',
1125n/a 127: b'\x7f',
1126n/a 128: b'\x80',
1127n/a 255: b'\xff',
1128n/a 256: b'\x00\x01',
1129n/a 32767: b'\xff\x7f',
1130n/a 32768: b'\x00\x80',
1131n/a 65535: b'\xff\xff',
1132n/a 65536: b'\x00\x00\x01'
1133n/a }
1134n/a check(tests4, 'little', signed=False)
1135n/a
1136n/a self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
1137n/a self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
1138n/a self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
1139n/a self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
1140n/a self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False)
1141n/a self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
1142n/a self.assertEqual((0).to_bytes(0, 'big'), b'')
1143n/a self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
1144n/a self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
1145n/a self.assertEqual((-1).to_bytes(5, 'big', signed=True),
1146n/a b'\xff\xff\xff\xff\xff')
1147n/a self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1148n/a
1149n/a def test_from_bytes(self):
1150n/a def check(tests, byteorder, signed=False):
1151n/a for test, expected in tests.items():
1152n/a try:
1153n/a self.assertEqual(
1154n/a int.from_bytes(test, byteorder, signed=signed),
1155n/a expected)
1156n/a except Exception as err:
1157n/a raise AssertionError(
1158n/a "failed to convert {0} with byteorder={1!r} and signed={2}"
1159n/a .format(test, byteorder, signed)) from err
1160n/a
1161n/a # Convert signed big-endian byte arrays to integers.
1162n/a tests1 = {
1163n/a b'': 0,
1164n/a b'\x00': 0,
1165n/a b'\x00\x00': 0,
1166n/a b'\x01': 1,
1167n/a b'\x00\x01': 1,
1168n/a b'\xff': -1,
1169n/a b'\xff\xff': -1,
1170n/a b'\x81': -127,
1171n/a b'\x80': -128,
1172n/a b'\xff\x7f': -129,
1173n/a b'\x7f': 127,
1174n/a b'\x00\x81': 129,
1175n/a b'\xff\x01': -255,
1176n/a b'\xff\x00': -256,
1177n/a b'\x00\xff': 255,
1178n/a b'\x01\x00': 256,
1179n/a b'\x7f\xff': 32767,
1180n/a b'\x80\x00': -32768,
1181n/a b'\x00\xff\xff': 65535,
1182n/a b'\xff\x00\x00': -65536,
1183n/a b'\x80\x00\x00': -8388608
1184n/a }
1185n/a check(tests1, 'big', signed=True)
1186n/a
1187n/a # Convert signed little-endian byte arrays to integers.
1188n/a tests2 = {
1189n/a b'': 0,
1190n/a b'\x00': 0,
1191n/a b'\x00\x00': 0,
1192n/a b'\x01': 1,
1193n/a b'\x00\x01': 256,
1194n/a b'\xff': -1,
1195n/a b'\xff\xff': -1,
1196n/a b'\x81': -127,
1197n/a b'\x80': -128,
1198n/a b'\x7f\xff': -129,
1199n/a b'\x7f': 127,
1200n/a b'\x81\x00': 129,
1201n/a b'\x01\xff': -255,
1202n/a b'\x00\xff': -256,
1203n/a b'\xff\x00': 255,
1204n/a b'\x00\x01': 256,
1205n/a b'\xff\x7f': 32767,
1206n/a b'\x00\x80': -32768,
1207n/a b'\xff\xff\x00': 65535,
1208n/a b'\x00\x00\xff': -65536,
1209n/a b'\x00\x00\x80': -8388608
1210n/a }
1211n/a check(tests2, 'little', signed=True)
1212n/a
1213n/a # Convert unsigned big-endian byte arrays to integers.
1214n/a tests3 = {
1215n/a b'': 0,
1216n/a b'\x00': 0,
1217n/a b'\x01': 1,
1218n/a b'\x7f': 127,
1219n/a b'\x80': 128,
1220n/a b'\xff': 255,
1221n/a b'\x01\x00': 256,
1222n/a b'\x7f\xff': 32767,
1223n/a b'\x80\x00': 32768,
1224n/a b'\xff\xff': 65535,
1225n/a b'\x01\x00\x00': 65536,
1226n/a }
1227n/a check(tests3, 'big', signed=False)
1228n/a
1229n/a # Convert integers to unsigned little-endian byte arrays.
1230n/a tests4 = {
1231n/a b'': 0,
1232n/a b'\x00': 0,
1233n/a b'\x01': 1,
1234n/a b'\x7f': 127,
1235n/a b'\x80': 128,
1236n/a b'\xff': 255,
1237n/a b'\x00\x01': 256,
1238n/a b'\xff\x7f': 32767,
1239n/a b'\x00\x80': 32768,
1240n/a b'\xff\xff': 65535,
1241n/a b'\x00\x00\x01': 65536,
1242n/a }
1243n/a check(tests4, 'little', signed=False)
1244n/a
1245n/a class myint(int):
1246n/a pass
1247n/a
1248n/a self.assertIs(type(myint.from_bytes(b'\x00', 'big')), myint)
1249n/a self.assertEqual(myint.from_bytes(b'\x01', 'big'), 1)
1250n/a self.assertIs(
1251n/a type(myint.from_bytes(b'\x00', 'big', signed=False)), myint)
1252n/a self.assertEqual(myint.from_bytes(b'\x01', 'big', signed=False), 1)
1253n/a self.assertIs(type(myint.from_bytes(b'\x00', 'little')), myint)
1254n/a self.assertEqual(myint.from_bytes(b'\x01', 'little'), 1)
1255n/a self.assertIs(type(myint.from_bytes(
1256n/a b'\x00', 'little', signed=False)), myint)
1257n/a self.assertEqual(myint.from_bytes(b'\x01', 'little', signed=False), 1)
1258n/a self.assertEqual(
1259n/a int.from_bytes([255, 0, 0], 'big', signed=True), -65536)
1260n/a self.assertEqual(
1261n/a int.from_bytes((255, 0, 0), 'big', signed=True), -65536)
1262n/a self.assertEqual(int.from_bytes(
1263n/a bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1264n/a self.assertEqual(int.from_bytes(
1265n/a bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1266n/a self.assertEqual(int.from_bytes(
1267n/a array.array('B', b'\xff\x00\x00'), 'big', signed=True), -65536)
1268n/a self.assertEqual(int.from_bytes(
1269n/a memoryview(b'\xff\x00\x00'), 'big', signed=True), -65536)
1270n/a self.assertRaises(ValueError, int.from_bytes, [256], 'big')
1271n/a self.assertRaises(ValueError, int.from_bytes, [0], 'big\x00')
1272n/a self.assertRaises(ValueError, int.from_bytes, [0], 'little\x00')
1273n/a self.assertRaises(TypeError, int.from_bytes, "", 'big')
1274n/a self.assertRaises(TypeError, int.from_bytes, "\x00", 'big')
1275n/a self.assertRaises(TypeError, int.from_bytes, 0, 'big')
1276n/a self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1277n/a self.assertRaises(TypeError, myint.from_bytes, "", 'big')
1278n/a self.assertRaises(TypeError, myint.from_bytes, "\x00", 'big')
1279n/a self.assertRaises(TypeError, myint.from_bytes, 0, 'big')
1280n/a self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1281n/a
1282n/a class myint2(int):
1283n/a def __new__(cls, value):
1284n/a return int.__new__(cls, value + 1)
1285n/a
1286n/a i = myint2.from_bytes(b'\x01', 'big')
1287n/a self.assertIs(type(i), myint2)
1288n/a self.assertEqual(i, 2)
1289n/a
1290n/a class myint3(int):
1291n/a def __init__(self, value):
1292n/a self.foo = 'bar'
1293n/a
1294n/a i = myint3.from_bytes(b'\x01', 'big')
1295n/a self.assertIs(type(i), myint3)
1296n/a self.assertEqual(i, 1)
1297n/a self.assertEqual(getattr(i, 'foo', 'none'), 'bar')
1298n/a
1299n/a def test_access_to_nonexistent_digit_0(self):
1300n/a # http://bugs.python.org/issue14630: A bug in _PyLong_Copy meant that
1301n/a # ob_digit[0] was being incorrectly accessed for instances of a
1302n/a # subclass of int, with value 0.
1303n/a class Integer(int):
1304n/a def __new__(cls, value=0):
1305n/a self = int.__new__(cls, value)
1306n/a self.foo = 'foo'
1307n/a return self
1308n/a
1309n/a integers = [Integer(0) for i in range(1000)]
1310n/a for n in map(int, integers):
1311n/a self.assertEqual(n, 0)
1312n/a
1313n/a def test_shift_bool(self):
1314n/a # Issue #21422: ensure that bool << int and bool >> int return int
1315n/a for value in (True, False):
1316n/a for shift in (0, 2):
1317n/a self.assertEqual(type(value << shift), int)
1318n/a self.assertEqual(type(value >> shift), int)
1319n/a
1320n/a
1321n/aif __name__ == "__main__":
1322n/a unittest.main()