blob: 57847d88f74802177645a6546c339bb269975152 [file] [log] [blame]
Walter Dörwalda0021592005-06-13 21:44:48 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Eric Smith3ab08ca2010-12-04 15:17:38 +00003
Christian Heimes81ee3ef2008-05-04 22:42:01 +00004import sys
Walter Dörwalda0021592005-06-13 21:44:48 +00005
6import random
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00007import math
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00008import array
Walter Dörwalda0021592005-06-13 21:44:48 +00009
10# Used for lazy formatting of failure messages
11class Frm(object):
12 def __init__(self, format, *args):
13 self.format = format
14 self.args = args
15
16 def __str__(self):
17 return self.format % self.args
Guido van Rossum4365cab1998-08-13 14:20:17 +000018
19# SHIFT should match the value in longintrepr.h for best testing.
Mark Dickinsonbd792642009-03-18 20:06:12 +000020SHIFT = sys.int_info.bits_per_digit
Guido van Rossum4365cab1998-08-13 14:20:17 +000021BASE = 2 ** SHIFT
22MASK = BASE - 1
Tim Petersdaec9612004-08-30 23:18:23 +000023KARATSUBA_CUTOFF = 70 # from longobject.c
Guido van Rossum4365cab1998-08-13 14:20:17 +000024
25# Max number of base BASE digits to use in test cases. Doubling
Tim Peters28b0e2a2002-08-13 02:17:11 +000026# this will more than double the runtime.
27MAXDIGITS = 15
Guido van Rossum4365cab1998-08-13 14:20:17 +000028
Guido van Rossum4581a0c1998-10-02 01:19:48 +000029# build some special values
Guido van Rossumc1f779c2007-07-03 08:25:58 +000030special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000031# some solid strings of one bits
Guido van Rossume2a383d2007-01-15 16:59:06 +000032p2 = 4 # 0 and 1 already added
Guido van Rossum4581a0c1998-10-02 01:19:48 +000033for i in range(2*SHIFT):
34 special.append(p2 - 1)
35 p2 = p2 << 1
36del p2
37# add complements & negations
Guido van Rossumc1f779c2007-07-03 08:25:58 +000038special += [~x for x in special] + [-x for x in special]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000039
Mark Dickinsoncbb62742009-12-27 15:09:50 +000040DBL_MAX = sys.float_info.max
41DBL_MAX_EXP = sys.float_info.max_exp
42DBL_MIN_EXP = sys.float_info.min_exp
43DBL_MANT_DIG = sys.float_info.mant_dig
44DBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1)
45
Mark Dickinson30970e92011-10-23 20:07:13 +010046
47# Pure Python version of correctly-rounded integer-to-float conversion.
48def int_to_float(n):
49 """
50 Correctly-rounded integer-to-float conversion.
51
52 """
53 # Constants, depending only on the floating-point format in use.
54 # We use an extra 2 bits of precision for rounding purposes.
55 PRECISION = sys.float_info.mant_dig + 2
56 SHIFT_MAX = sys.float_info.max_exp - PRECISION
57 Q_MAX = 1 << PRECISION
58 ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1]
59
60 # Reduce to the case where n is positive.
61 if n == 0:
62 return 0.0
63 elif n < 0:
64 return -int_to_float(-n)
65
66 # Convert n to a 'floating-point' number q * 2**shift, where q is an
67 # integer with 'PRECISION' significant bits. When shifting n to create q,
68 # the least significant bit of q is treated as 'sticky'. That is, the
69 # least significant bit of q is set if either the corresponding bit of n
70 # was already set, or any one of the bits of n lost in the shift was set.
71 shift = n.bit_length() - PRECISION
72 q = n << -shift if shift < 0 else (n >> shift) | bool(n & ~(-1 << shift))
73
74 # Round half to even (actually rounds to the nearest multiple of 4,
75 # rounding ties to a multiple of 8).
76 q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7]
77
78 # Detect overflow.
79 if shift + (q == Q_MAX) > SHIFT_MAX:
80 raise OverflowError("integer too large to convert to float")
81
82 # Checks: q is exactly representable, and q**2**shift doesn't overflow.
83 assert q % 4 == 0 and q // 4 <= 2**(sys.float_info.mant_dig)
84 assert q * 2**shift <= sys.float_info.max
85
86 # Some circularity here, since float(q) is doing an int-to-float
87 # conversion. But here q is of bounded size, and is exactly representable
88 # as a float. In a low-level C-like language, this operation would be a
89 # simple cast (e.g., from unsigned long long to double).
90 return math.ldexp(float(q), shift)
91
92
Mark Dickinsoncbb62742009-12-27 15:09:50 +000093# pure Python version of correctly-rounded true division
94def truediv(a, b):
95 """Correctly-rounded true division for integers."""
96 negative = a^b < 0
97 a, b = abs(a), abs(b)
98
99 # exceptions: division by zero, overflow
100 if not b:
101 raise ZeroDivisionError("division by zero")
102 if a >= DBL_MIN_OVERFLOW * b:
103 raise OverflowError("int/int too large to represent as a float")
104
105 # find integer d satisfying 2**(d - 1) <= a/b < 2**d
106 d = a.bit_length() - b.bit_length()
107 if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
108 d += 1
109
110 # compute 2**-exp * a / b for suitable exp
111 exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
112 a, b = a << max(-exp, 0), b << max(exp, 0)
113 q, r = divmod(a, b)
114
115 # round-half-to-even: fractional part is r/b, which is > 0.5 iff
116 # 2*r > b, and == 0.5 iff 2*r == b.
117 if 2*r > b or 2*r == b and q % 2 == 1:
118 q += 1
119
Mark Dickinsona4e15062009-12-27 19:03:31 +0000120 result = math.ldexp(q, exp)
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000121 return -result if negative else result
122
123
Walter Dörwalda0021592005-06-13 21:44:48 +0000124class LongTest(unittest.TestCase):
Guido van Rossum4365cab1998-08-13 14:20:17 +0000125
Walter Dörwalda0021592005-06-13 21:44:48 +0000126 # Get quasi-random long consisting of ndigits digits (in base BASE).
127 # quasi == the most-significant digit will not be 0, and the number
128 # is constructed to contain long strings of 0 and 1 bits. These are
129 # more likely than random bits to provoke digit-boundary errors.
130 # The sign of the number is also random.
Guido van Rossum4365cab1998-08-13 14:20:17 +0000131
Walter Dörwalda0021592005-06-13 21:44:48 +0000132 def getran(self, ndigits):
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200133 self.assertGreater(ndigits, 0)
Walter Dörwalda0021592005-06-13 21:44:48 +0000134 nbits_hi = ndigits * SHIFT
135 nbits_lo = nbits_hi - SHIFT + 1
Guido van Rossume2a383d2007-01-15 16:59:06 +0000136 answer = 0
Walter Dörwalda0021592005-06-13 21:44:48 +0000137 nbits = 0
138 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
139 while nbits < nbits_lo:
140 bits = (r >> 1) + 1
141 bits = min(bits, nbits_hi - nbits)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000142 self.assertTrue(1 <= bits <= SHIFT)
Walter Dörwalda0021592005-06-13 21:44:48 +0000143 nbits = nbits + bits
144 answer = answer << bits
145 if r & 1:
146 answer = answer | ((1 << bits) - 1)
147 r = int(random.random() * (SHIFT * 2))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000148 self.assertTrue(nbits_lo <= nbits <= nbits_hi)
Walter Dörwalda0021592005-06-13 21:44:48 +0000149 if random.random() < 0.5:
150 answer = -answer
151 return answer
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000152
Walter Dörwalda0021592005-06-13 21:44:48 +0000153 # Get random long consisting of ndigits random digits (relative to base
154 # BASE). The sign bit is also random.
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000155
Walter Dörwalda0021592005-06-13 21:44:48 +0000156 def getran2(ndigits):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000157 answer = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000158 for i in range(ndigits):
Walter Dörwalda0021592005-06-13 21:44:48 +0000159 answer = (answer << SHIFT) | random.randint(0, MASK)
160 if random.random() < 0.5:
161 answer = -answer
162 return answer
Guido van Rossum4365cab1998-08-13 14:20:17 +0000163
Walter Dörwalda0021592005-06-13 21:44:48 +0000164 def check_division(self, x, y):
165 eq = self.assertEqual
166 q, r = divmod(x, y)
167 q2, r2 = x//y, x%y
168 pab, pba = x*y, y*x
169 eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
170 eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
171 eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
172 eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
173 if y > 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000174 self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000175 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000176 self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000177
Walter Dörwalda0021592005-06-13 21:44:48 +0000178 def test_division(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000179 digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
180 KARATSUBA_CUTOFF + 14))
Walter Dörwalda0021592005-06-13 21:44:48 +0000181 digits.append(KARATSUBA_CUTOFF * 3)
182 for lenx in digits:
183 x = self.getran(lenx)
184 for leny in digits:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000185 y = self.getran(leny) or 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000186 self.check_division(x, y)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000187
Mark Dickinsonbd792642009-03-18 20:06:12 +0000188 # specific numbers chosen to exercise corner cases of the
189 # current long division implementation
190
191 # 30-bit cases involving a quotient digit estimate of BASE+1
192 self.check_division(1231948412290879395966702881,
193 1147341367131428698)
194 self.check_division(815427756481275430342312021515587883,
195 707270836069027745)
196 self.check_division(627976073697012820849443363563599041,
197 643588798496057020)
198 self.check_division(1115141373653752303710932756325578065,
199 1038556335171453937726882627)
200 # 30-bit cases that require the post-subtraction correction step
201 self.check_division(922498905405436751940989320930368494,
202 949985870686786135626943396)
203 self.check_division(768235853328091167204009652174031844,
204 1091555541180371554426545266)
205
206 # 15-bit cases involving a quotient digit estimate of BASE+1
207 self.check_division(20172188947443, 615611397)
208 self.check_division(1020908530270155025, 950795710)
209 self.check_division(128589565723112408, 736393718)
210 self.check_division(609919780285761575, 18613274546784)
211 # 15-bit cases that require the post-subtraction correction step
212 self.check_division(710031681576388032, 26769404391308)
213 self.check_division(1933622614268221, 30212853348836)
214
215
216
Walter Dörwalda0021592005-06-13 21:44:48 +0000217 def test_karatsuba(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000218 digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
219 KARATSUBA_CUTOFF + 10))
Walter Dörwalda0021592005-06-13 21:44:48 +0000220 digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
Guido van Rossum4365cab1998-08-13 14:20:17 +0000221
Walter Dörwalda0021592005-06-13 21:44:48 +0000222 bits = [digit * SHIFT for digit in digits]
Guido van Rossum4365cab1998-08-13 14:20:17 +0000223
Walter Dörwalda0021592005-06-13 21:44:48 +0000224 # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
225 # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
226 for abits in bits:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000227 a = (1 << abits) - 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000228 for bbits in bits:
229 if bbits < abits:
230 continue
Guido van Rossume2a383d2007-01-15 16:59:06 +0000231 b = (1 << bbits) - 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000232 x = a * b
Guido van Rossume2a383d2007-01-15 16:59:06 +0000233 y = ((1 << (abits + bbits)) -
234 (1 << abits) -
235 (1 << bbits) +
Walter Dörwalda0021592005-06-13 21:44:48 +0000236 1)
237 self.assertEqual(x, y,
238 Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y))
Tim Peters7f270ba2002-08-13 21:06:55 +0000239
Walter Dörwalda0021592005-06-13 21:44:48 +0000240 def check_bitop_identities_1(self, x):
241 eq = self.assertEqual
242 eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))
243 eq(x | 0, x, Frm("x | 0 != x for x=%r", x))
244 eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x))
245 eq(x & -1, x, Frm("x & -1 != x for x=%r", x))
246 eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x))
247 eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x))
248 eq(x, ~~x, Frm("x != ~~x for x=%r", x))
249 eq(x & x, x, Frm("x & x != x for x=%r", x))
250 eq(x | x, x, Frm("x | x != x for x=%r", x))
251 eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x))
252 eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x))
253 eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x))
254 eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
255 eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
256 eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
Guido van Rossum805365e2007-05-07 22:24:25 +0000257 for n in range(2*SHIFT):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000258 p2 = 2 ** n
Walter Dörwalda0021592005-06-13 21:44:48 +0000259 eq(x << n >> n, x,
260 Frm("x << n >> n != x for x=%r, n=%r", (x, n)))
261 eq(x // p2, x >> n,
262 Frm("x // p2 != x >> n for x=%r n=%r p2=%r", (x, n, p2)))
263 eq(x * p2, x << n,
264 Frm("x * p2 != x << n for x=%r n=%r p2=%r", (x, n, p2)))
265 eq(x & -p2, x >> n << n,
266 Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", (x, n, p2)))
267 eq(x & -p2, x & ~(p2 - 1),
268 Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", (x, n, p2)))
Tim Peters7f270ba2002-08-13 21:06:55 +0000269
Walter Dörwalda0021592005-06-13 21:44:48 +0000270 def check_bitop_identities_2(self, x, y):
271 eq = self.assertEqual
272 eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", (x, y)))
273 eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", (x, y)))
274 eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", (x, y)))
275 eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", (x, y)))
276 eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", (x, y)))
277 eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", (x, y)))
278 eq(x ^ y, (x | y) & ~(x & y),
279 Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", (x, y)))
280 eq(x ^ y, (x & ~y) | (~x & y),
281 Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", (x, y)))
282 eq(x ^ y, (x | y) & (~x | ~y),
283 Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", (x, y)))
Tim Peters7f270ba2002-08-13 21:06:55 +0000284
Walter Dörwalda0021592005-06-13 21:44:48 +0000285 def check_bitop_identities_3(self, x, y, z):
286 eq = self.assertEqual
287 eq((x & y) & z, x & (y & z),
288 Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", (x, y, z)))
289 eq((x | y) | z, x | (y | z),
290 Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", (x, y, z)))
291 eq((x ^ y) ^ z, x ^ (y ^ z),
292 Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", (x, y, z)))
293 eq(x & (y | z), (x & y) | (x & z),
294 Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", (x, y, z)))
295 eq(x | (y & z), (x | y) & (x | z),
296 Frm("x | (y & z) != (x | y) & (x | z) for x=%r, y=%r, z=%r", (x, y, z)))
Tim Peters7f270ba2002-08-13 21:06:55 +0000297
Walter Dörwalda0021592005-06-13 21:44:48 +0000298 def test_bitop_identities(self):
299 for x in special:
300 self.check_bitop_identities_1(x)
Guido van Rossum805365e2007-05-07 22:24:25 +0000301 digits = range(1, MAXDIGITS+1)
Walter Dörwalda0021592005-06-13 21:44:48 +0000302 for lenx in digits:
303 x = self.getran(lenx)
304 self.check_bitop_identities_1(x)
305 for leny in digits:
306 y = self.getran(leny)
307 self.check_bitop_identities_2(x, y)
308 self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000309
Walter Dörwalda0021592005-06-13 21:44:48 +0000310 def slow_format(self, x, base):
Walter Dörwalda0021592005-06-13 21:44:48 +0000311 digits = []
312 sign = 0
313 if x < 0:
314 sign, x = 1, -x
315 while x:
316 x, r = divmod(x, base)
317 digits.append(int(r))
318 digits.reverse()
319 digits = digits or [0]
320 return '-'[:sign] + \
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000321 {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
Georg Brandlcbd2ab12010-12-04 10:39:14 +0000322 "".join("0123456789abcdef"[i] for i in digits)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000323
Walter Dörwalda0021592005-06-13 21:44:48 +0000324 def check_format_1(self, x):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300325 for base, mapper in (2, bin), (8, oct), (10, str), (10, repr), (16, hex):
Walter Dörwalda0021592005-06-13 21:44:48 +0000326 got = mapper(x)
327 expected = self.slow_format(x, base)
328 msg = Frm("%s returned %r but expected %r for %r",
329 mapper.__name__, got, expected, x)
330 self.assertEqual(got, expected, msg)
Mark Dickinson5c2db372009-12-05 20:28:34 +0000331 self.assertEqual(int(got, 0), x, Frm('int("%s", 0) != %r', got, x))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000332
Walter Dörwalda0021592005-06-13 21:44:48 +0000333 def test_format(self):
334 for x in special:
335 self.check_format_1(x)
Guido van Rossum805365e2007-05-07 22:24:25 +0000336 for i in range(10):
337 for lenx in range(1, MAXDIGITS+1):
Walter Dörwalda0021592005-06-13 21:44:48 +0000338 x = self.getran(lenx)
339 self.check_format_1(x)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000340
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000341 def test_long(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +0000342 # Check conversions from string
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000343 LL = [
344 ('1' + '0'*20, 10**20),
345 ('1' + '0'*100, 10**100)
346 ]
Mark Dickinson5c2db372009-12-05 20:28:34 +0000347 for s, v in LL:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000348 for sign in "", "+", "-":
349 for prefix in "", " ", "\t", " \t\t ":
350 ss = prefix + sign + s
351 vv = v
352 if sign == "-" and v is not ValueError:
353 vv = -v
354 try:
Mark Dickinson5c2db372009-12-05 20:28:34 +0000355 self.assertEqual(int(ss), vv)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000356 except ValueError:
357 pass
358
Mark Dickinson9ffc0202009-01-20 20:45:53 +0000359 # trailing L should no longer be accepted...
360 self.assertRaises(ValueError, int, '123L')
361 self.assertRaises(ValueError, int, '123l')
362 self.assertRaises(ValueError, int, '0L')
363 self.assertRaises(ValueError, int, '-37L')
364 self.assertRaises(ValueError, int, '0x32L', 16)
365 self.assertRaises(ValueError, int, '1L', 21)
366 # ... but it's just a normal digit if base >= 22
367 self.assertEqual(int('1L', 22), 43)
368
Mark Dickinson56544db2010-05-26 19:14:01 +0000369 # tests with base 0
370 self.assertEqual(int('000', 0), 0)
371 self.assertEqual(int('0o123', 0), 83)
372 self.assertEqual(int('0x123', 0), 291)
373 self.assertEqual(int('0b100', 0), 4)
374 self.assertEqual(int(' 0O123 ', 0), 83)
375 self.assertEqual(int(' 0X123 ', 0), 291)
376 self.assertEqual(int(' 0B100 ', 0), 4)
377 self.assertEqual(int('0', 0), 0)
378 self.assertEqual(int('+0', 0), 0)
379 self.assertEqual(int('-0', 0), 0)
380 self.assertEqual(int('00', 0), 0)
381 self.assertRaises(ValueError, int, '08', 0)
382 self.assertRaises(ValueError, int, '-012395', 0)
383
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +0000384 # invalid bases
385 invalid_bases = [-909,
386 2**31-1, 2**31, -2**31, -2**31-1,
387 2**63-1, 2**63, -2**63, -2**63-1,
388 2**100, -2**100,
389 ]
390 for base in invalid_bases:
391 self.assertRaises(ValueError, int, '42', base)
392
393
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000394 def test_conversion(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000395
Mark Dickinson5c2db372009-12-05 20:28:34 +0000396 class JustLong:
397 # test that __long__ no longer used in 3.x
398 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000399 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000400 self.assertRaises(TypeError, int, JustLong())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000401
Mark Dickinson5c2db372009-12-05 20:28:34 +0000402 class LongTrunc:
403 # __long__ should be ignored in 3.x
404 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000405 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000406 def __trunc__(self):
407 return 1729
408 self.assertEqual(int(LongTrunc()), 1729)
Tim Peters26c7fa32001-08-23 22:56:21 +0000409
Mark Dickinson30970e92011-10-23 20:07:13 +0100410 def check_float_conversion(self, n):
411 # Check that int -> float conversion behaviour matches
412 # that of the pure Python version above.
413 try:
414 actual = float(n)
415 except OverflowError:
416 actual = 'overflow'
417
418 try:
419 expected = int_to_float(n)
420 except OverflowError:
421 expected = 'overflow'
422
423 msg = ("Error in conversion of integer {} to float. "
424 "Got {}, expected {}.".format(n, actual, expected))
425 self.assertEqual(actual, expected, msg)
426
Eric Smith3ab08ca2010-12-04 15:17:38 +0000427 @support.requires_IEEE_754
Mark Dickinsonc6300392009-04-20 21:38:00 +0000428 def test_float_conversion(self):
Mark Dickinsonc6300392009-04-20 21:38:00 +0000429
430 exact_values = [0, 1, 2,
431 2**53-3,
432 2**53-2,
433 2**53-1,
434 2**53,
435 2**53+2,
436 2**54-4,
437 2**54-2,
438 2**54,
439 2**54+4]
440 for x in exact_values:
441 self.assertEqual(float(x), x)
442 self.assertEqual(float(-x), -x)
443
444 # test round-half-even
445 for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
446 for p in range(15):
447 self.assertEqual(int(float(2**p*(2**53+x))), 2**p*(2**53+y))
448
449 for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
450 (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
451 (13, 12), (14, 16), (15, 16)]:
452 for p in range(15):
453 self.assertEqual(int(float(2**p*(2**54+x))), 2**p*(2**54+y))
454
455 # behaviour near extremes of floating-point range
456 int_dbl_max = int(DBL_MAX)
457 top_power = 2**DBL_MAX_EXP
458 halfway = (int_dbl_max + top_power)//2
459 self.assertEqual(float(int_dbl_max), DBL_MAX)
460 self.assertEqual(float(int_dbl_max+1), DBL_MAX)
461 self.assertEqual(float(halfway-1), DBL_MAX)
462 self.assertRaises(OverflowError, float, halfway)
463 self.assertEqual(float(1-halfway), -DBL_MAX)
464 self.assertRaises(OverflowError, float, -halfway)
465 self.assertRaises(OverflowError, float, top_power-1)
466 self.assertRaises(OverflowError, float, top_power)
467 self.assertRaises(OverflowError, float, top_power+1)
468 self.assertRaises(OverflowError, float, 2*top_power-1)
469 self.assertRaises(OverflowError, float, 2*top_power)
470 self.assertRaises(OverflowError, float, top_power*top_power)
471
472 for p in range(100):
473 x = 2**p * (2**53 + 1) + 1
474 y = 2**p * (2**53 + 2)
475 self.assertEqual(int(float(x)), y)
476
477 x = 2**p * (2**53 + 1)
478 y = 2**p * 2**53
479 self.assertEqual(int(float(x)), y)
480
Mark Dickinson30970e92011-10-23 20:07:13 +0100481 # Compare builtin float conversion with pure Python int_to_float
482 # function above.
483 test_values = [
484 int_dbl_max-1, int_dbl_max, int_dbl_max+1,
485 halfway-1, halfway, halfway + 1,
486 top_power-1, top_power, top_power+1,
487 2*top_power-1, 2*top_power, top_power*top_power,
488 ]
489 test_values.extend(exact_values)
490 for p in range(-4, 8):
491 for x in range(-128, 128):
492 test_values.append(2**(p+53) + x)
493 for value in test_values:
494 self.check_float_conversion(value)
495 self.check_float_conversion(-value)
496
Walter Dörwalda0021592005-06-13 21:44:48 +0000497 def test_float_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000498 for x in -2.0, -1.0, 0.0, 1.0, 2.0:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000499 self.assertEqual(float(int(x)), x)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000500
Walter Dörwalda0021592005-06-13 21:44:48 +0000501 shuge = '12345' * 120
Guido van Rossume2a383d2007-01-15 16:59:06 +0000502 huge = 1 << 30000
Walter Dörwalda0021592005-06-13 21:44:48 +0000503 mhuge = -huge
504 namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
505 for test in ["float(huge)", "float(mhuge)",
506 "complex(huge)", "complex(mhuge)",
507 "complex(huge, 1)", "complex(mhuge, 1)",
508 "complex(1, huge)", "complex(1, mhuge)",
509 "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
510 "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
511 "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
512 "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
513 "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
514 "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
515 "math.sin(huge)", "math.sin(mhuge)",
516 "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
Guido van Rossum28bbe422007-08-24 03:46:30 +0000517 # math.floor() of an int returns an int now
518 ##"math.floor(huge)", "math.floor(mhuge)",
519 ]:
Tim Peters9fffa3e2001-09-04 05:14:19 +0000520
Walter Dörwalda0021592005-06-13 21:44:48 +0000521 self.assertRaises(OverflowError, eval, test, namespace)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000522
Mark Dickinson5c2db372009-12-05 20:28:34 +0000523 # XXX Perhaps float(shuge) can raise OverflowError on some box?
524 # The comparison should not.
525 self.assertNotEqual(float(shuge), int(shuge),
526 "float(shuge) should not equal int(shuge)")
Tim Peters83e7ccc2001-09-04 06:37:28 +0000527
Walter Dörwalda0021592005-06-13 21:44:48 +0000528 def test_logs(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000529 LOG10E = math.log10(math.e)
Tim Peters307fa782004-09-23 08:06:40 +0000530
Guido van Rossum805365e2007-05-07 22:24:25 +0000531 for exp in list(range(10)) + [100, 1000, 10000]:
Walter Dörwalda0021592005-06-13 21:44:48 +0000532 value = 10 ** exp
533 log10 = math.log10(value)
534 self.assertAlmostEqual(log10, exp)
Tim Peters78526162001-09-05 00:53:45 +0000535
Walter Dörwalda0021592005-06-13 21:44:48 +0000536 # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
537 # exp/LOG10E
538 expected = exp / LOG10E
539 log = math.log(value)
540 self.assertAlmostEqual(log, expected)
Tim Peters78526162001-09-05 00:53:45 +0000541
Guido van Rossume2a383d2007-01-15 16:59:06 +0000542 for bad in -(1 << 10000), -2, 0:
Walter Dörwalda0021592005-06-13 21:44:48 +0000543 self.assertRaises(ValueError, math.log, bad)
544 self.assertRaises(ValueError, math.log10, bad)
Tim Peters78526162001-09-05 00:53:45 +0000545
Walter Dörwalda0021592005-06-13 21:44:48 +0000546 def test_mixed_compares(self):
547 eq = self.assertEqual
Tim Peters78526162001-09-05 00:53:45 +0000548
Serhiy Storchaka95949422013-08-27 19:40:23 +0300549 # We're mostly concerned with that mixing floats and ints does the
550 # right stuff, even when ints are too large to fit in a float.
Walter Dörwalda0021592005-06-13 21:44:48 +0000551 # The safest way to check the results is to use an entirely different
552 # method, which we do here via a skeletal rational class (which
Serhiy Storchaka95949422013-08-27 19:40:23 +0300553 # represents all Python ints and floats exactly).
Walter Dörwalda0021592005-06-13 21:44:48 +0000554 class Rat:
555 def __init__(self, value):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000556 if isinstance(value, int):
Walter Dörwalda0021592005-06-13 21:44:48 +0000557 self.n = value
558 self.d = 1
559 elif isinstance(value, float):
560 # Convert to exact rational equivalent.
561 f, e = math.frexp(abs(value))
562 assert f == 0 or 0.5 <= f < 1.0
563 # |value| = f * 2**e exactly
Tim Peters78526162001-09-05 00:53:45 +0000564
Walter Dörwalda0021592005-06-13 21:44:48 +0000565 # Suck up CHUNK bits at a time; 28 is enough so that we suck
566 # up all bits in 2 iterations for all known binary double-
567 # precision formats, and small enough to fit in an int.
568 CHUNK = 28
569 top = 0
570 # invariant: |value| = (top + f) * 2**e exactly
571 while f:
572 f = math.ldexp(f, CHUNK)
573 digit = int(f)
574 assert digit >> CHUNK == 0
575 top = (top << CHUNK) | digit
576 f -= digit
577 assert 0.0 <= f < 1.0
578 e -= CHUNK
Tim Peters78526162001-09-05 00:53:45 +0000579
Walter Dörwalda0021592005-06-13 21:44:48 +0000580 # Now |value| = top * 2**e exactly.
581 if e >= 0:
582 n = top << e
583 d = 1
584 else:
585 n = top
586 d = 1 << -e
587 if value < 0:
588 n = -n
589 self.n = n
590 self.d = d
591 assert float(n) / float(d) == value
Tim Peters307fa782004-09-23 08:06:40 +0000592 else:
Georg Brandl89fad142010-03-14 10:23:39 +0000593 raise TypeError("can't deal with %r" % value)
Tim Peters307fa782004-09-23 08:06:40 +0000594
Benjamin Peterson60192082008-10-16 19:34:46 +0000595 def _cmp__(self, other):
Walter Dörwalda0021592005-06-13 21:44:48 +0000596 if not isinstance(other, Rat):
597 other = Rat(other)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000598 x, y = self.n * other.d, self.d * other.n
599 return (x > y) - (x < y)
Benjamin Peterson60192082008-10-16 19:34:46 +0000600 def __eq__(self, other):
601 return self._cmp__(other) == 0
Benjamin Peterson60192082008-10-16 19:34:46 +0000602 def __ge__(self, other):
603 return self._cmp__(other) >= 0
604 def __gt__(self, other):
605 return self._cmp__(other) > 0
606 def __le__(self, other):
607 return self._cmp__(other) <= 0
608 def __lt__(self, other):
609 return self._cmp__(other) < 0
Tim Peters307fa782004-09-23 08:06:40 +0000610
Walter Dörwalda0021592005-06-13 21:44:48 +0000611 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
612 # 2**48 is an important boundary in the internals. 2**53 is an
613 # important boundary for IEEE double precision.
614 for t in 2.0**48, 2.0**50, 2.0**53:
615 cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000616 int(t-1), int(t), int(t+1)])
Christian Heimesa37d4c62007-12-04 23:02:19 +0000617 cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
Mark Dickinson5c2db372009-12-05 20:28:34 +0000618 # 1 << 20000 should exceed all double formats. int(1e200) is to
Walter Dörwalda0021592005-06-13 21:44:48 +0000619 # check that we get equality with 1e200 above.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000620 t = int(1e200)
621 cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
Walter Dörwalda0021592005-06-13 21:44:48 +0000622 cases.extend([-x for x in cases])
623 for x in cases:
624 Rx = Rat(x)
625 for y in cases:
626 Ry = Rat(y)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000627 Rcmp = (Rx > Ry) - (Rx < Ry)
628 xycmp = (x > y) - (x < y)
Walter Dörwalda0021592005-06-13 21:44:48 +0000629 eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
630 eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
631 eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
632 eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
633 eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
634 eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
635 eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
Tim Peters307fa782004-09-23 08:06:40 +0000636
Eric Smith0dd1b632008-02-11 17:55:01 +0000637 def test__format__(self):
Eric Smith8c663262007-08-25 02:26:07 +0000638 self.assertEqual(format(123456789, 'd'), '123456789')
639 self.assertEqual(format(123456789, 'd'), '123456789')
640
Eric Smith185e30c2007-08-30 22:23:08 +0000641 # sign and aligning are interdependent
642 self.assertEqual(format(1, "-"), '1')
643 self.assertEqual(format(-1, "-"), '-1')
644 self.assertEqual(format(1, "-3"), ' 1')
645 self.assertEqual(format(-1, "-3"), ' -1')
646 self.assertEqual(format(1, "+3"), ' +1')
647 self.assertEqual(format(-1, "+3"), ' -1')
648 self.assertEqual(format(1, " 3"), ' 1')
649 self.assertEqual(format(-1, " 3"), ' -1')
650 self.assertEqual(format(1, " "), ' 1')
651 self.assertEqual(format(-1, " "), '-1')
652
Eric Smith8c663262007-08-25 02:26:07 +0000653 # hex
654 self.assertEqual(format(3, "x"), "3")
655 self.assertEqual(format(3, "X"), "3")
656 self.assertEqual(format(1234, "x"), "4d2")
657 self.assertEqual(format(-1234, "x"), "-4d2")
658 self.assertEqual(format(1234, "8x"), " 4d2")
Eric Smith185e30c2007-08-30 22:23:08 +0000659 self.assertEqual(format(-1234, "8x"), " -4d2")
Eric Smith8c663262007-08-25 02:26:07 +0000660 self.assertEqual(format(1234, "x"), "4d2")
661 self.assertEqual(format(-1234, "x"), "-4d2")
662 self.assertEqual(format(-3, "x"), "-3")
663 self.assertEqual(format(-3, "X"), "-3")
664 self.assertEqual(format(int('be', 16), "x"), "be")
665 self.assertEqual(format(int('be', 16), "X"), "BE")
666 self.assertEqual(format(-int('be', 16), "x"), "-be")
667 self.assertEqual(format(-int('be', 16), "X"), "-BE")
668
669 # octal
670 self.assertEqual(format(3, "b"), "11")
671 self.assertEqual(format(-3, "b"), "-11")
672 self.assertEqual(format(1234, "b"), "10011010010")
673 self.assertEqual(format(-1234, "b"), "-10011010010")
674 self.assertEqual(format(1234, "-b"), "10011010010")
675 self.assertEqual(format(-1234, "-b"), "-10011010010")
676 self.assertEqual(format(1234, " b"), " 10011010010")
677 self.assertEqual(format(-1234, " b"), "-10011010010")
678 self.assertEqual(format(1234, "+b"), "+10011010010")
679 self.assertEqual(format(-1234, "+b"), "-10011010010")
680
Eric Smith8c663262007-08-25 02:26:07 +0000681 # make sure these are errors
682 self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed
Eric Smith8c663262007-08-25 02:26:07 +0000683 self.assertRaises(ValueError, format, 3, "+c") # sign not allowed
684 # with 'c'
Eric Smithfa767ef2008-01-28 10:59:27 +0000685
686 # ensure that only int and float type specifiers work
Eric Smith7b69c6c2008-01-27 21:07:59 +0000687 for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
688 [chr(x) for x in range(ord('A'), ord('Z')+1)]):
Eric Smithfa767ef2008-01-28 10:59:27 +0000689 if not format_spec in 'bcdoxXeEfFgGn%':
Eric Smith7b69c6c2008-01-27 21:07:59 +0000690 self.assertRaises(ValueError, format, 0, format_spec)
691 self.assertRaises(ValueError, format, 1, format_spec)
692 self.assertRaises(ValueError, format, -1, format_spec)
693 self.assertRaises(ValueError, format, 2**100, format_spec)
694 self.assertRaises(ValueError, format, -(2**100), format_spec)
695
Eric Smithfa767ef2008-01-28 10:59:27 +0000696 # ensure that float type specifiers work; format converts
697 # the int to a float
Eric Smith5807c412008-05-11 21:00:57 +0000698 for format_spec in 'eEfFgG%':
Eric Smithfa767ef2008-01-28 10:59:27 +0000699 for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
700 self.assertEqual(format(value, format_spec),
701 format(float(value), format_spec))
Eric Smith8c663262007-08-25 02:26:07 +0000702
Christian Heimesa34706f2008-01-04 03:06:10 +0000703 def test_nan_inf(self):
Christian Heimes1aa7b302008-01-04 03:22:53 +0000704 self.assertRaises(OverflowError, int, float('inf'))
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000705 self.assertRaises(OverflowError, int, float('-inf'))
706 self.assertRaises(ValueError, int, float('nan'))
Christian Heimesa34706f2008-01-04 03:06:10 +0000707
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000708 def test_true_division(self):
709 huge = 1 << 40000
710 mhuge = -huge
711 self.assertEqual(huge / huge, 1.0)
712 self.assertEqual(mhuge / mhuge, 1.0)
713 self.assertEqual(huge / mhuge, -1.0)
714 self.assertEqual(mhuge / huge, -1.0)
715 self.assertEqual(1 / huge, 0.0)
716 self.assertEqual(1 / huge, 0.0)
717 self.assertEqual(1 / mhuge, 0.0)
718 self.assertEqual(1 / mhuge, 0.0)
719 self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
720 self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
721 self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
722 self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
723 self.assertEqual(huge / (huge << 1), 0.5)
724 self.assertEqual((1000000 * huge) / huge, 1000000)
725
726 namespace = {'huge': huge, 'mhuge': mhuge}
727
728 for overflow in ["float(huge)", "float(mhuge)",
729 "huge / 1", "huge / 2", "huge / -1", "huge / -2",
730 "mhuge / 100", "mhuge / 200"]:
731 self.assertRaises(OverflowError, eval, overflow, namespace)
732
733 for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
734 "100 / mhuge", "200 / mhuge"]:
735 result = eval(underflow, namespace)
736 self.assertEqual(result, 0.0,
737 "expected underflow to 0 from %r" % underflow)
738
739 for zero in ["huge / 0", "mhuge / 0"]:
740 self.assertRaises(ZeroDivisionError, eval, zero, namespace)
741
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000742 def check_truediv(self, a, b, skip_small=True):
743 """Verify that the result of a/b is correctly rounded, by
744 comparing it with a pure Python implementation of correctly
745 rounded division. b should be nonzero."""
746
747 # skip check for small a and b: in this case, the current
748 # implementation converts the arguments to float directly and
749 # then applies a float division. This can give doubly-rounded
750 # results on x87-using machines (particularly 32-bit Linux).
751 if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
752 return
753
754 try:
755 # use repr so that we can distinguish between -0.0 and 0.0
756 expected = repr(truediv(a, b))
757 except OverflowError:
758 expected = 'overflow'
759 except ZeroDivisionError:
760 expected = 'zerodivision'
761
762 try:
763 got = repr(a / b)
764 except OverflowError:
765 got = 'overflow'
766 except ZeroDivisionError:
767 got = 'zerodivision'
768
Mark Dickinson2cfda802009-12-27 21:34:05 +0000769 self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
770 "expected {}, got {}".format(a, b, expected, got))
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000771
Eric Smith3ab08ca2010-12-04 15:17:38 +0000772 @support.requires_IEEE_754
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000773 def test_correctly_rounded_true_division(self):
774 # more stringent tests than those above, checking that the
775 # result of true division of ints is always correctly rounded.
776 # This test should probably be considered CPython-specific.
777
778 # Exercise all the code paths not involving Gb-sized ints.
779 # ... divisions involving zero
780 self.check_truediv(123, 0)
781 self.check_truediv(-456, 0)
782 self.check_truediv(0, 3)
783 self.check_truediv(0, -3)
784 self.check_truediv(0, 0)
785 # ... overflow or underflow by large margin
786 self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
787 self.check_truediv(12345, 345678 * 2**(DBL_MANT_DIG - DBL_MIN_EXP))
788 # ... a much larger or smaller than b
789 self.check_truediv(12345*2**100, 98765)
790 self.check_truediv(12345*2**30, 98765*7**81)
791 # ... a / b near a boundary: one of 1, 2**DBL_MANT_DIG, 2**DBL_MIN_EXP,
792 # 2**DBL_MAX_EXP, 2**(DBL_MIN_EXP-DBL_MANT_DIG)
793 bases = (0, DBL_MANT_DIG, DBL_MIN_EXP,
794 DBL_MAX_EXP, DBL_MIN_EXP - DBL_MANT_DIG)
795 for base in bases:
796 for exp in range(base - 15, base + 15):
797 self.check_truediv(75312*2**max(exp, 0), 69187*2**max(-exp, 0))
798 self.check_truediv(69187*2**max(exp, 0), 75312*2**max(-exp, 0))
799
800 # overflow corner case
801 for m in [1, 2, 7, 17, 12345, 7**100,
802 -1, -2, -5, -23, -67891, -41**50]:
803 for n in range(-10, 10):
804 self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
805 self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
806
807 # check detection of inexactness in shifting stage
808 for n in range(250):
809 # (2**DBL_MANT_DIG+1)/(2**DBL_MANT_DIG) lies halfway
810 # between two representable floats, and would usually be
811 # rounded down under round-half-to-even. The tiniest of
812 # additions to the numerator should cause it to be rounded
813 # up instead.
814 self.check_truediv((2**DBL_MANT_DIG + 1)*12345*2**200 + 2**n,
815 2**DBL_MANT_DIG*12345)
816
817 # 1/2731 is one of the smallest division cases that's subject
818 # to double rounding on IEEE 754 machines working internally with
819 # 64-bit precision. On such machines, the next check would fail,
820 # were it not explicitly skipped in check_truediv.
821 self.check_truediv(1, 2731)
822
823 # a particularly bad case for the old algorithm: gives an
824 # error of close to 3.5 ulps.
825 self.check_truediv(295147931372582273023, 295147932265116303360)
826 for i in range(1000):
827 self.check_truediv(10**(i+1), 10**i)
828 self.check_truediv(10**i, 10**(i+1))
829
830 # test round-half-to-even behaviour, normal result
831 for m in [1, 2, 4, 7, 8, 16, 17, 32, 12345, 7**100,
832 -1, -2, -5, -23, -67891, -41**50]:
833 for n in range(-10, 10):
834 self.check_truediv(2**DBL_MANT_DIG*m + n, m)
835
836 # test round-half-to-even, subnormal result
837 for n in range(-20, 20):
838 self.check_truediv(n, 2**1076)
839
840 # largeish random divisions: a/b where |a| <= |b| <=
841 # 2*|a|; |ans| is between 0.5 and 1.0, so error should
842 # always be bounded by 2**-54 with equality possible only
843 # if the least significant bit of q=ans*2**53 is zero.
844 for M in [10**10, 10**100, 10**1000]:
845 for i in range(1000):
846 a = random.randrange(1, M)
847 b = random.randrange(a, 2*a+1)
848 self.check_truediv(a, b)
849 self.check_truediv(-a, b)
850 self.check_truediv(a, -b)
851 self.check_truediv(-a, -b)
852
853 # and some (genuinely) random tests
854 for _ in range(10000):
855 a_bits = random.randrange(1000)
856 b_bits = random.randrange(1, 1000)
857 x = random.randrange(2**a_bits)
858 y = random.randrange(1, 2**b_bits)
859 self.check_truediv(x, y)
860 self.check_truediv(x, -y)
861 self.check_truediv(-x, y)
862 self.check_truediv(-x, -y)
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000863
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000864 def test_small_ints(self):
865 for i in range(-5, 257):
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200866 self.assertIs(i, i + 0)
867 self.assertIs(i, i * 1)
868 self.assertIs(i, i - 0)
869 self.assertIs(i, i // 1)
870 self.assertIs(i, i & -1)
871 self.assertIs(i, i | 0)
872 self.assertIs(i, i ^ 0)
873 self.assertIs(i, ~~i)
874 self.assertIs(i, i**1)
875 self.assertIs(i, int(str(i)))
876 self.assertIs(i, i<<2>>2, str(i))
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000877 # corner cases
878 i = 1 << 70
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200879 self.assertIs(i - i, 0)
880 self.assertIs(0 * i, 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000881
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000882 def test_bit_length(self):
883 tiny = 1e-10
884 for x in range(-65000, 65000):
885 k = x.bit_length()
886 # Check equivalence with Python version
887 self.assertEqual(k, len(bin(x).lstrip('-0b')))
888 # Behaviour as specified in the docs
889 if x != 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000890 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000891 else:
892 self.assertEqual(k, 0)
893 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
894 if x != 0:
895 # When x is an exact power of 2, numeric errors can
896 # cause floor(log(x)/log(2)) to be one too small; for
897 # small x this can be fixed by adding a small quantity
898 # to the quotient before taking the floor.
899 self.assertEqual(k, 1 + math.floor(
900 math.log(abs(x))/math.log(2) + tiny))
901
902 self.assertEqual((0).bit_length(), 0)
903 self.assertEqual((1).bit_length(), 1)
904 self.assertEqual((-1).bit_length(), 1)
905 self.assertEqual((2).bit_length(), 2)
906 self.assertEqual((-2).bit_length(), 2)
907 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
908 a = 2**i
909 self.assertEqual((a-1).bit_length(), i)
910 self.assertEqual((1-a).bit_length(), i)
911 self.assertEqual((a).bit_length(), i+1)
912 self.assertEqual((-a).bit_length(), i+1)
913 self.assertEqual((a+1).bit_length(), i+1)
914 self.assertEqual((-a-1).bit_length(), i+1)
915
Mark Dickinson1124e712009-01-28 21:25:58 +0000916 def test_round(self):
917 # check round-half-even algorithm. For round to nearest ten;
918 # rounding map is invariant under adding multiples of 20
919 test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
920 6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
921 15:20, 16:20, 17:20, 18:20, 19:20}
922 for offset in range(-520, 520, 20):
923 for k, v in test_dict.items():
924 got = round(k+offset, -1)
925 expected = v+offset
926 self.assertEqual(got, expected)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200927 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000928
929 # larger second argument
930 self.assertEqual(round(-150, -2), -200)
931 self.assertEqual(round(-149, -2), -100)
932 self.assertEqual(round(-51, -2), -100)
933 self.assertEqual(round(-50, -2), 0)
934 self.assertEqual(round(-49, -2), 0)
935 self.assertEqual(round(-1, -2), 0)
936 self.assertEqual(round(0, -2), 0)
937 self.assertEqual(round(1, -2), 0)
938 self.assertEqual(round(49, -2), 0)
939 self.assertEqual(round(50, -2), 0)
940 self.assertEqual(round(51, -2), 100)
941 self.assertEqual(round(149, -2), 100)
942 self.assertEqual(round(150, -2), 200)
943 self.assertEqual(round(250, -2), 200)
944 self.assertEqual(round(251, -2), 300)
945 self.assertEqual(round(172500, -3), 172000)
946 self.assertEqual(round(173500, -3), 174000)
947 self.assertEqual(round(31415926535, -1), 31415926540)
948 self.assertEqual(round(31415926535, -2), 31415926500)
949 self.assertEqual(round(31415926535, -3), 31415927000)
950 self.assertEqual(round(31415926535, -4), 31415930000)
951 self.assertEqual(round(31415926535, -5), 31415900000)
952 self.assertEqual(round(31415926535, -6), 31416000000)
953 self.assertEqual(round(31415926535, -7), 31420000000)
954 self.assertEqual(round(31415926535, -8), 31400000000)
955 self.assertEqual(round(31415926535, -9), 31000000000)
956 self.assertEqual(round(31415926535, -10), 30000000000)
957 self.assertEqual(round(31415926535, -11), 0)
958 self.assertEqual(round(31415926535, -12), 0)
959 self.assertEqual(round(31415926535, -999), 0)
960
961 # should get correct results even for huge inputs
962 for k in range(10, 100):
963 got = round(10**k + 324678, -3)
964 expect = 10**k + 325000
965 self.assertEqual(got, expect)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200966 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000967
968 # nonnegative second argument: round(x, n) should just return x
969 for n in range(5):
970 for i in range(100):
971 x = random.randrange(-10000, 10000)
972 got = round(x, n)
973 self.assertEqual(got, x)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200974 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000975 for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
976 self.assertEqual(round(8979323, huge_n), 8979323)
977
978 # omitted second argument
979 for i in range(100):
980 x = random.randrange(-10000, 10000)
981 got = round(x)
982 self.assertEqual(got, x)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200983 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000984
985 # bad second argument
986 bad_exponents = ('brian', 2.0, 0j, None)
987 for e in bad_exponents:
988 self.assertRaises(TypeError, round, 3, e)
989
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000990 def test_to_bytes(self):
991 def check(tests, byteorder, signed=False):
992 for test, expected in tests.items():
993 try:
994 self.assertEqual(
995 test.to_bytes(len(expected), byteorder, signed=signed),
996 expected)
997 except Exception as err:
998 raise AssertionError(
999 "failed to convert {0} with byteorder={1} and signed={2}"
1000 .format(test, byteorder, signed)) from err
1001
1002 # Convert integers to signed big-endian byte arrays.
1003 tests1 = {
1004 0: b'\x00',
1005 1: b'\x01',
1006 -1: b'\xff',
1007 -127: b'\x81',
1008 -128: b'\x80',
1009 -129: b'\xff\x7f',
1010 127: b'\x7f',
1011 129: b'\x00\x81',
1012 -255: b'\xff\x01',
1013 -256: b'\xff\x00',
1014 255: b'\x00\xff',
1015 256: b'\x01\x00',
1016 32767: b'\x7f\xff',
1017 -32768: b'\xff\x80\x00',
1018 65535: b'\x00\xff\xff',
1019 -65536: b'\xff\x00\x00',
1020 -8388608: b'\x80\x00\x00'
1021 }
1022 check(tests1, 'big', signed=True)
1023
1024 # Convert integers to signed little-endian byte arrays.
1025 tests2 = {
1026 0: b'\x00',
1027 1: b'\x01',
1028 -1: b'\xff',
1029 -127: b'\x81',
1030 -128: b'\x80',
1031 -129: b'\x7f\xff',
1032 127: b'\x7f',
1033 129: b'\x81\x00',
1034 -255: b'\x01\xff',
1035 -256: b'\x00\xff',
1036 255: b'\xff\x00',
1037 256: b'\x00\x01',
1038 32767: b'\xff\x7f',
1039 -32768: b'\x00\x80',
1040 65535: b'\xff\xff\x00',
1041 -65536: b'\x00\x00\xff',
1042 -8388608: b'\x00\x00\x80'
1043 }
1044 check(tests2, 'little', signed=True)
1045
1046 # Convert integers to unsigned big-endian byte arrays.
1047 tests3 = {
1048 0: b'\x00',
1049 1: b'\x01',
1050 127: b'\x7f',
1051 128: b'\x80',
1052 255: b'\xff',
1053 256: b'\x01\x00',
1054 32767: b'\x7f\xff',
1055 32768: b'\x80\x00',
1056 65535: b'\xff\xff',
1057 65536: b'\x01\x00\x00'
1058 }
1059 check(tests3, 'big', signed=False)
1060
1061 # Convert integers to unsigned little-endian byte arrays.
1062 tests4 = {
1063 0: b'\x00',
1064 1: b'\x01',
1065 127: b'\x7f',
1066 128: b'\x80',
1067 255: b'\xff',
1068 256: b'\x00\x01',
1069 32767: b'\xff\x7f',
1070 32768: b'\x00\x80',
1071 65535: b'\xff\xff',
1072 65536: b'\x00\x00\x01'
1073 }
1074 check(tests4, 'little', signed=False)
1075
1076 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
1077 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
1078 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
1079 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
Victor Stinner3fa1aae2013-03-26 01:14:08 +01001080 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001081 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
1082 self.assertEqual((0).to_bytes(0, 'big'), b'')
1083 self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
1084 self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
1085 self.assertEqual((-1).to_bytes(5, 'big', signed=True),
1086 b'\xff\xff\xff\xff\xff')
1087 self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1088
1089 def test_from_bytes(self):
1090 def check(tests, byteorder, signed=False):
1091 for test, expected in tests.items():
1092 try:
1093 self.assertEqual(
1094 int.from_bytes(test, byteorder, signed=signed),
1095 expected)
1096 except Exception as err:
1097 raise AssertionError(
1098 "failed to convert {0} with byteorder={1!r} and signed={2}"
1099 .format(test, byteorder, signed)) from err
1100
1101 # Convert signed big-endian byte arrays to integers.
1102 tests1 = {
1103 b'': 0,
1104 b'\x00': 0,
1105 b'\x00\x00': 0,
1106 b'\x01': 1,
1107 b'\x00\x01': 1,
1108 b'\xff': -1,
1109 b'\xff\xff': -1,
1110 b'\x81': -127,
1111 b'\x80': -128,
1112 b'\xff\x7f': -129,
1113 b'\x7f': 127,
1114 b'\x00\x81': 129,
1115 b'\xff\x01': -255,
1116 b'\xff\x00': -256,
1117 b'\x00\xff': 255,
1118 b'\x01\x00': 256,
1119 b'\x7f\xff': 32767,
1120 b'\x80\x00': -32768,
1121 b'\x00\xff\xff': 65535,
1122 b'\xff\x00\x00': -65536,
1123 b'\x80\x00\x00': -8388608
1124 }
1125 check(tests1, 'big', signed=True)
1126
1127 # Convert signed little-endian byte arrays to integers.
1128 tests2 = {
1129 b'': 0,
1130 b'\x00': 0,
1131 b'\x00\x00': 0,
1132 b'\x01': 1,
1133 b'\x00\x01': 256,
1134 b'\xff': -1,
1135 b'\xff\xff': -1,
1136 b'\x81': -127,
1137 b'\x80': -128,
1138 b'\x7f\xff': -129,
1139 b'\x7f': 127,
1140 b'\x81\x00': 129,
1141 b'\x01\xff': -255,
1142 b'\x00\xff': -256,
1143 b'\xff\x00': 255,
1144 b'\x00\x01': 256,
1145 b'\xff\x7f': 32767,
1146 b'\x00\x80': -32768,
1147 b'\xff\xff\x00': 65535,
1148 b'\x00\x00\xff': -65536,
1149 b'\x00\x00\x80': -8388608
1150 }
1151 check(tests2, 'little', signed=True)
1152
1153 # Convert unsigned big-endian byte arrays to integers.
1154 tests3 = {
1155 b'': 0,
1156 b'\x00': 0,
1157 b'\x01': 1,
1158 b'\x7f': 127,
1159 b'\x80': 128,
1160 b'\xff': 255,
1161 b'\x01\x00': 256,
1162 b'\x7f\xff': 32767,
1163 b'\x80\x00': 32768,
1164 b'\xff\xff': 65535,
1165 b'\x01\x00\x00': 65536,
1166 }
1167 check(tests3, 'big', signed=False)
1168
1169 # Convert integers to unsigned little-endian byte arrays.
1170 tests4 = {
1171 b'': 0,
1172 b'\x00': 0,
1173 b'\x01': 1,
1174 b'\x7f': 127,
1175 b'\x80': 128,
1176 b'\xff': 255,
1177 b'\x00\x01': 256,
1178 b'\xff\x7f': 32767,
1179 b'\x00\x80': 32768,
1180 b'\xff\xff': 65535,
1181 b'\x00\x00\x01': 65536,
1182 }
1183 check(tests4, 'little', signed=False)
1184
1185 class myint(int):
1186 pass
1187
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001188 self.assertIs(type(myint.from_bytes(b'\x00', 'big')), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001189 self.assertEqual(myint.from_bytes(b'\x01', 'big'), 1)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001190 self.assertIs(
1191 type(myint.from_bytes(b'\x00', 'big', signed=False)), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001192 self.assertEqual(myint.from_bytes(b'\x01', 'big', signed=False), 1)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001193 self.assertIs(type(myint.from_bytes(b'\x00', 'little')), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001194 self.assertEqual(myint.from_bytes(b'\x01', 'little'), 1)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001195 self.assertIs(type(myint.from_bytes(
1196 b'\x00', 'little', signed=False)), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001197 self.assertEqual(myint.from_bytes(b'\x01', 'little', signed=False), 1)
1198 self.assertEqual(
1199 int.from_bytes([255, 0, 0], 'big', signed=True), -65536)
1200 self.assertEqual(
1201 int.from_bytes((255, 0, 0), 'big', signed=True), -65536)
1202 self.assertEqual(int.from_bytes(
1203 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1204 self.assertEqual(int.from_bytes(
1205 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1206 self.assertEqual(int.from_bytes(
1207 array.array('B', b'\xff\x00\x00'), 'big', signed=True), -65536)
1208 self.assertEqual(int.from_bytes(
1209 memoryview(b'\xff\x00\x00'), 'big', signed=True), -65536)
1210 self.assertRaises(ValueError, int.from_bytes, [256], 'big')
1211 self.assertRaises(ValueError, int.from_bytes, [0], 'big\x00')
1212 self.assertRaises(ValueError, int.from_bytes, [0], 'little\x00')
1213 self.assertRaises(TypeError, int.from_bytes, "", 'big')
1214 self.assertRaises(TypeError, int.from_bytes, "\x00", 'big')
1215 self.assertRaises(TypeError, int.from_bytes, 0, 'big')
1216 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1217 self.assertRaises(TypeError, myint.from_bytes, "", 'big')
1218 self.assertRaises(TypeError, myint.from_bytes, "\x00", 'big')
1219 self.assertRaises(TypeError, myint.from_bytes, 0, 'big')
1220 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
Mark Dickinson1124e712009-01-28 21:25:58 +00001221
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +01001222 def test_access_to_nonexistent_digit_0(self):
1223 # http://bugs.python.org/issue14630: A bug in _PyLong_Copy meant that
1224 # ob_digit[0] was being incorrectly accessed for instances of a
1225 # subclass of int, with value 0.
1226 class Integer(int):
1227 def __new__(cls, value=0):
1228 self = int.__new__(cls, value)
1229 self.foo = 'foo'
1230 return self
1231
1232 integers = [Integer(0) for i in range(1000)]
1233 for n in map(int, integers):
1234 self.assertEqual(n, 0)
1235
Victor Stinner7fe10492014-05-12 22:35:40 +02001236 def test_shift_bool(self):
1237 # Issue #21422: ensure that bool << int and bool >> int return int
1238 for value in (True, False):
1239 for shift in (0, 2):
1240 self.assertEqual(type(value << shift), int)
1241 self.assertEqual(type(value >> shift), int)
1242
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00001243
Walter Dörwalda0021592005-06-13 21:44:48 +00001244def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001245 support.run_unittest(LongTest)
Tim Peters307fa782004-09-23 08:06:40 +00001246
Walter Dörwalda0021592005-06-13 21:44:48 +00001247if __name__ == "__main__":
1248 test_main()