blob: 6c30fed7c9421cfd12f7d89cbbecbeeab51dd451 [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):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000133 self.assertTrue(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
602 def __ne__(self, other):
603 return self._cmp__(other) != 0
604 def __ge__(self, other):
605 return self._cmp__(other) >= 0
606 def __gt__(self, other):
607 return self._cmp__(other) > 0
608 def __le__(self, other):
609 return self._cmp__(other) <= 0
610 def __lt__(self, other):
611 return self._cmp__(other) < 0
Tim Peters307fa782004-09-23 08:06:40 +0000612
Walter Dörwalda0021592005-06-13 21:44:48 +0000613 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
614 # 2**48 is an important boundary in the internals. 2**53 is an
615 # important boundary for IEEE double precision.
616 for t in 2.0**48, 2.0**50, 2.0**53:
617 cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000618 int(t-1), int(t), int(t+1)])
Christian Heimesa37d4c62007-12-04 23:02:19 +0000619 cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
Mark Dickinson5c2db372009-12-05 20:28:34 +0000620 # 1 << 20000 should exceed all double formats. int(1e200) is to
Walter Dörwalda0021592005-06-13 21:44:48 +0000621 # check that we get equality with 1e200 above.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000622 t = int(1e200)
623 cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
Walter Dörwalda0021592005-06-13 21:44:48 +0000624 cases.extend([-x for x in cases])
625 for x in cases:
626 Rx = Rat(x)
627 for y in cases:
628 Ry = Rat(y)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000629 Rcmp = (Rx > Ry) - (Rx < Ry)
630 xycmp = (x > y) - (x < y)
Walter Dörwalda0021592005-06-13 21:44:48 +0000631 eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
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))
636 eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
637 eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
Tim Peters307fa782004-09-23 08:06:40 +0000638
Eric Smith0dd1b632008-02-11 17:55:01 +0000639 def test__format__(self):
Eric Smith8c663262007-08-25 02:26:07 +0000640 self.assertEqual(format(123456789, 'd'), '123456789')
641 self.assertEqual(format(123456789, 'd'), '123456789')
642
Eric Smith185e30c2007-08-30 22:23:08 +0000643 # sign and aligning are interdependent
644 self.assertEqual(format(1, "-"), '1')
645 self.assertEqual(format(-1, "-"), '-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, " 3"), ' 1')
651 self.assertEqual(format(-1, " 3"), ' -1')
652 self.assertEqual(format(1, " "), ' 1')
653 self.assertEqual(format(-1, " "), '-1')
654
Eric Smith8c663262007-08-25 02:26:07 +0000655 # hex
656 self.assertEqual(format(3, "x"), "3")
657 self.assertEqual(format(3, "X"), "3")
658 self.assertEqual(format(1234, "x"), "4d2")
659 self.assertEqual(format(-1234, "x"), "-4d2")
660 self.assertEqual(format(1234, "8x"), " 4d2")
Eric Smith185e30c2007-08-30 22:23:08 +0000661 self.assertEqual(format(-1234, "8x"), " -4d2")
Eric Smith8c663262007-08-25 02:26:07 +0000662 self.assertEqual(format(1234, "x"), "4d2")
663 self.assertEqual(format(-1234, "x"), "-4d2")
664 self.assertEqual(format(-3, "x"), "-3")
665 self.assertEqual(format(-3, "X"), "-3")
666 self.assertEqual(format(int('be', 16), "x"), "be")
667 self.assertEqual(format(int('be', 16), "X"), "BE")
668 self.assertEqual(format(-int('be', 16), "x"), "-be")
669 self.assertEqual(format(-int('be', 16), "X"), "-BE")
670
671 # octal
672 self.assertEqual(format(3, "b"), "11")
673 self.assertEqual(format(-3, "b"), "-11")
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 self.assertEqual(format(1234, "+b"), "+10011010010")
681 self.assertEqual(format(-1234, "+b"), "-10011010010")
682
Eric Smith8c663262007-08-25 02:26:07 +0000683 # make sure these are errors
684 self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed
Eric Smith8c663262007-08-25 02:26:07 +0000685 self.assertRaises(ValueError, format, 3, "+c") # sign not allowed
686 # with 'c'
Eric Smithfa767ef2008-01-28 10:59:27 +0000687
688 # ensure that only int and float type specifiers work
Eric Smith7b69c6c2008-01-27 21:07:59 +0000689 for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
690 [chr(x) for x in range(ord('A'), ord('Z')+1)]):
Eric Smithfa767ef2008-01-28 10:59:27 +0000691 if not format_spec in 'bcdoxXeEfFgGn%':
Eric Smith7b69c6c2008-01-27 21:07:59 +0000692 self.assertRaises(ValueError, format, 0, format_spec)
693 self.assertRaises(ValueError, format, 1, format_spec)
694 self.assertRaises(ValueError, format, -1, format_spec)
695 self.assertRaises(ValueError, format, 2**100, format_spec)
696 self.assertRaises(ValueError, format, -(2**100), format_spec)
697
Eric Smithfa767ef2008-01-28 10:59:27 +0000698 # ensure that float type specifiers work; format converts
699 # the int to a float
Eric Smith5807c412008-05-11 21:00:57 +0000700 for format_spec in 'eEfFgG%':
Eric Smithfa767ef2008-01-28 10:59:27 +0000701 for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
702 self.assertEqual(format(value, format_spec),
703 format(float(value), format_spec))
Eric Smith8c663262007-08-25 02:26:07 +0000704
Christian Heimesa34706f2008-01-04 03:06:10 +0000705 def test_nan_inf(self):
Christian Heimes1aa7b302008-01-04 03:22:53 +0000706 self.assertRaises(OverflowError, int, float('inf'))
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000707 self.assertRaises(OverflowError, int, float('-inf'))
708 self.assertRaises(ValueError, int, float('nan'))
Christian Heimesa34706f2008-01-04 03:06:10 +0000709
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000710 def test_true_division(self):
711 huge = 1 << 40000
712 mhuge = -huge
713 self.assertEqual(huge / huge, 1.0)
714 self.assertEqual(mhuge / mhuge, 1.0)
715 self.assertEqual(huge / mhuge, -1.0)
716 self.assertEqual(mhuge / huge, -1.0)
717 self.assertEqual(1 / huge, 0.0)
718 self.assertEqual(1 / huge, 0.0)
719 self.assertEqual(1 / mhuge, 0.0)
720 self.assertEqual(1 / mhuge, 0.0)
721 self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
722 self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
723 self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
724 self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
725 self.assertEqual(huge / (huge << 1), 0.5)
726 self.assertEqual((1000000 * huge) / huge, 1000000)
727
728 namespace = {'huge': huge, 'mhuge': mhuge}
729
730 for overflow in ["float(huge)", "float(mhuge)",
731 "huge / 1", "huge / 2", "huge / -1", "huge / -2",
732 "mhuge / 100", "mhuge / 200"]:
733 self.assertRaises(OverflowError, eval, overflow, namespace)
734
735 for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
736 "100 / mhuge", "200 / mhuge"]:
737 result = eval(underflow, namespace)
738 self.assertEqual(result, 0.0,
739 "expected underflow to 0 from %r" % underflow)
740
741 for zero in ["huge / 0", "mhuge / 0"]:
742 self.assertRaises(ZeroDivisionError, eval, zero, namespace)
743
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000744 def check_truediv(self, a, b, skip_small=True):
745 """Verify that the result of a/b is correctly rounded, by
746 comparing it with a pure Python implementation of correctly
747 rounded division. b should be nonzero."""
748
749 # skip check for small a and b: in this case, the current
750 # implementation converts the arguments to float directly and
751 # then applies a float division. This can give doubly-rounded
752 # results on x87-using machines (particularly 32-bit Linux).
753 if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
754 return
755
756 try:
757 # use repr so that we can distinguish between -0.0 and 0.0
758 expected = repr(truediv(a, b))
759 except OverflowError:
760 expected = 'overflow'
761 except ZeroDivisionError:
762 expected = 'zerodivision'
763
764 try:
765 got = repr(a / b)
766 except OverflowError:
767 got = 'overflow'
768 except ZeroDivisionError:
769 got = 'zerodivision'
770
Mark Dickinson2cfda802009-12-27 21:34:05 +0000771 self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
772 "expected {}, got {}".format(a, b, expected, got))
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000773
Eric Smith3ab08ca2010-12-04 15:17:38 +0000774 @support.requires_IEEE_754
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000775 def test_correctly_rounded_true_division(self):
776 # more stringent tests than those above, checking that the
777 # result of true division of ints is always correctly rounded.
778 # This test should probably be considered CPython-specific.
779
780 # Exercise all the code paths not involving Gb-sized ints.
781 # ... divisions involving zero
782 self.check_truediv(123, 0)
783 self.check_truediv(-456, 0)
784 self.check_truediv(0, 3)
785 self.check_truediv(0, -3)
786 self.check_truediv(0, 0)
787 # ... overflow or underflow by large margin
788 self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
789 self.check_truediv(12345, 345678 * 2**(DBL_MANT_DIG - DBL_MIN_EXP))
790 # ... a much larger or smaller than b
791 self.check_truediv(12345*2**100, 98765)
792 self.check_truediv(12345*2**30, 98765*7**81)
793 # ... a / b near a boundary: one of 1, 2**DBL_MANT_DIG, 2**DBL_MIN_EXP,
794 # 2**DBL_MAX_EXP, 2**(DBL_MIN_EXP-DBL_MANT_DIG)
795 bases = (0, DBL_MANT_DIG, DBL_MIN_EXP,
796 DBL_MAX_EXP, DBL_MIN_EXP - DBL_MANT_DIG)
797 for base in bases:
798 for exp in range(base - 15, base + 15):
799 self.check_truediv(75312*2**max(exp, 0), 69187*2**max(-exp, 0))
800 self.check_truediv(69187*2**max(exp, 0), 75312*2**max(-exp, 0))
801
802 # overflow corner case
803 for m in [1, 2, 7, 17, 12345, 7**100,
804 -1, -2, -5, -23, -67891, -41**50]:
805 for n in range(-10, 10):
806 self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
807 self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
808
809 # check detection of inexactness in shifting stage
810 for n in range(250):
811 # (2**DBL_MANT_DIG+1)/(2**DBL_MANT_DIG) lies halfway
812 # between two representable floats, and would usually be
813 # rounded down under round-half-to-even. The tiniest of
814 # additions to the numerator should cause it to be rounded
815 # up instead.
816 self.check_truediv((2**DBL_MANT_DIG + 1)*12345*2**200 + 2**n,
817 2**DBL_MANT_DIG*12345)
818
819 # 1/2731 is one of the smallest division cases that's subject
820 # to double rounding on IEEE 754 machines working internally with
821 # 64-bit precision. On such machines, the next check would fail,
822 # were it not explicitly skipped in check_truediv.
823 self.check_truediv(1, 2731)
824
825 # a particularly bad case for the old algorithm: gives an
826 # error of close to 3.5 ulps.
827 self.check_truediv(295147931372582273023, 295147932265116303360)
828 for i in range(1000):
829 self.check_truediv(10**(i+1), 10**i)
830 self.check_truediv(10**i, 10**(i+1))
831
832 # test round-half-to-even behaviour, normal result
833 for m in [1, 2, 4, 7, 8, 16, 17, 32, 12345, 7**100,
834 -1, -2, -5, -23, -67891, -41**50]:
835 for n in range(-10, 10):
836 self.check_truediv(2**DBL_MANT_DIG*m + n, m)
837
838 # test round-half-to-even, subnormal result
839 for n in range(-20, 20):
840 self.check_truediv(n, 2**1076)
841
842 # largeish random divisions: a/b where |a| <= |b| <=
843 # 2*|a|; |ans| is between 0.5 and 1.0, so error should
844 # always be bounded by 2**-54 with equality possible only
845 # if the least significant bit of q=ans*2**53 is zero.
846 for M in [10**10, 10**100, 10**1000]:
847 for i in range(1000):
848 a = random.randrange(1, M)
849 b = random.randrange(a, 2*a+1)
850 self.check_truediv(a, b)
851 self.check_truediv(-a, b)
852 self.check_truediv(a, -b)
853 self.check_truediv(-a, -b)
854
855 # and some (genuinely) random tests
856 for _ in range(10000):
857 a_bits = random.randrange(1000)
858 b_bits = random.randrange(1, 1000)
859 x = random.randrange(2**a_bits)
860 y = random.randrange(1, 2**b_bits)
861 self.check_truediv(x, y)
862 self.check_truediv(x, -y)
863 self.check_truediv(-x, y)
864 self.check_truediv(-x, -y)
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000865
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000866 def test_small_ints(self):
867 for i in range(-5, 257):
868 self.assertTrue(i is i + 0)
869 self.assertTrue(i is i * 1)
870 self.assertTrue(i is i - 0)
871 self.assertTrue(i is i // 1)
872 self.assertTrue(i is i & -1)
873 self.assertTrue(i is i | 0)
874 self.assertTrue(i is i ^ 0)
875 self.assertTrue(i is ~~i)
876 self.assertTrue(i is i**1)
877 self.assertTrue(i is int(str(i)))
878 self.assertTrue(i is i<<2>>2, str(i))
879 # corner cases
880 i = 1 << 70
881 self.assertTrue(i - i is 0)
882 self.assertTrue(0 * i is 0)
883
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000884 def test_bit_length(self):
885 tiny = 1e-10
886 for x in range(-65000, 65000):
887 k = x.bit_length()
888 # Check equivalence with Python version
889 self.assertEqual(k, len(bin(x).lstrip('-0b')))
890 # Behaviour as specified in the docs
891 if x != 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000892 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000893 else:
894 self.assertEqual(k, 0)
895 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
896 if x != 0:
897 # When x is an exact power of 2, numeric errors can
898 # cause floor(log(x)/log(2)) to be one too small; for
899 # small x this can be fixed by adding a small quantity
900 # to the quotient before taking the floor.
901 self.assertEqual(k, 1 + math.floor(
902 math.log(abs(x))/math.log(2) + tiny))
903
904 self.assertEqual((0).bit_length(), 0)
905 self.assertEqual((1).bit_length(), 1)
906 self.assertEqual((-1).bit_length(), 1)
907 self.assertEqual((2).bit_length(), 2)
908 self.assertEqual((-2).bit_length(), 2)
909 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
910 a = 2**i
911 self.assertEqual((a-1).bit_length(), i)
912 self.assertEqual((1-a).bit_length(), i)
913 self.assertEqual((a).bit_length(), i+1)
914 self.assertEqual((-a).bit_length(), i+1)
915 self.assertEqual((a+1).bit_length(), i+1)
916 self.assertEqual((-a-1).bit_length(), i+1)
917
Mark Dickinson1124e712009-01-28 21:25:58 +0000918 def test_round(self):
919 # check round-half-even algorithm. For round to nearest ten;
920 # rounding map is invariant under adding multiples of 20
921 test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
922 6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
923 15:20, 16:20, 17:20, 18:20, 19:20}
924 for offset in range(-520, 520, 20):
925 for k, v in test_dict.items():
926 got = round(k+offset, -1)
927 expected = v+offset
928 self.assertEqual(got, expected)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000929 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000930
931 # larger second argument
932 self.assertEqual(round(-150, -2), -200)
933 self.assertEqual(round(-149, -2), -100)
934 self.assertEqual(round(-51, -2), -100)
935 self.assertEqual(round(-50, -2), 0)
936 self.assertEqual(round(-49, -2), 0)
937 self.assertEqual(round(-1, -2), 0)
938 self.assertEqual(round(0, -2), 0)
939 self.assertEqual(round(1, -2), 0)
940 self.assertEqual(round(49, -2), 0)
941 self.assertEqual(round(50, -2), 0)
942 self.assertEqual(round(51, -2), 100)
943 self.assertEqual(round(149, -2), 100)
944 self.assertEqual(round(150, -2), 200)
945 self.assertEqual(round(250, -2), 200)
946 self.assertEqual(round(251, -2), 300)
947 self.assertEqual(round(172500, -3), 172000)
948 self.assertEqual(round(173500, -3), 174000)
949 self.assertEqual(round(31415926535, -1), 31415926540)
950 self.assertEqual(round(31415926535, -2), 31415926500)
951 self.assertEqual(round(31415926535, -3), 31415927000)
952 self.assertEqual(round(31415926535, -4), 31415930000)
953 self.assertEqual(round(31415926535, -5), 31415900000)
954 self.assertEqual(round(31415926535, -6), 31416000000)
955 self.assertEqual(round(31415926535, -7), 31420000000)
956 self.assertEqual(round(31415926535, -8), 31400000000)
957 self.assertEqual(round(31415926535, -9), 31000000000)
958 self.assertEqual(round(31415926535, -10), 30000000000)
959 self.assertEqual(round(31415926535, -11), 0)
960 self.assertEqual(round(31415926535, -12), 0)
961 self.assertEqual(round(31415926535, -999), 0)
962
963 # should get correct results even for huge inputs
964 for k in range(10, 100):
965 got = round(10**k + 324678, -3)
966 expect = 10**k + 325000
967 self.assertEqual(got, expect)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000968 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000969
970 # nonnegative second argument: round(x, n) should just return x
971 for n in range(5):
972 for i in range(100):
973 x = random.randrange(-10000, 10000)
974 got = round(x, n)
975 self.assertEqual(got, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000976 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000977 for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
978 self.assertEqual(round(8979323, huge_n), 8979323)
979
980 # omitted second argument
981 for i in range(100):
982 x = random.randrange(-10000, 10000)
983 got = round(x)
984 self.assertEqual(got, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000985 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000986
987 # bad second argument
988 bad_exponents = ('brian', 2.0, 0j, None)
989 for e in bad_exponents:
990 self.assertRaises(TypeError, round, 3, e)
991
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000992 def test_to_bytes(self):
993 def check(tests, byteorder, signed=False):
994 for test, expected in tests.items():
995 try:
996 self.assertEqual(
997 test.to_bytes(len(expected), byteorder, signed=signed),
998 expected)
999 except Exception as err:
1000 raise AssertionError(
1001 "failed to convert {0} with byteorder={1} and signed={2}"
1002 .format(test, byteorder, signed)) from err
1003
1004 # Convert integers to signed big-endian byte arrays.
1005 tests1 = {
1006 0: b'\x00',
1007 1: b'\x01',
1008 -1: b'\xff',
1009 -127: b'\x81',
1010 -128: b'\x80',
1011 -129: b'\xff\x7f',
1012 127: b'\x7f',
1013 129: b'\x00\x81',
1014 -255: b'\xff\x01',
1015 -256: b'\xff\x00',
1016 255: b'\x00\xff',
1017 256: b'\x01\x00',
1018 32767: b'\x7f\xff',
1019 -32768: b'\xff\x80\x00',
1020 65535: b'\x00\xff\xff',
1021 -65536: b'\xff\x00\x00',
1022 -8388608: b'\x80\x00\x00'
1023 }
1024 check(tests1, 'big', signed=True)
1025
1026 # Convert integers to signed little-endian byte arrays.
1027 tests2 = {
1028 0: b'\x00',
1029 1: b'\x01',
1030 -1: b'\xff',
1031 -127: b'\x81',
1032 -128: b'\x80',
1033 -129: b'\x7f\xff',
1034 127: b'\x7f',
1035 129: b'\x81\x00',
1036 -255: b'\x01\xff',
1037 -256: b'\x00\xff',
1038 255: b'\xff\x00',
1039 256: b'\x00\x01',
1040 32767: b'\xff\x7f',
1041 -32768: b'\x00\x80',
1042 65535: b'\xff\xff\x00',
1043 -65536: b'\x00\x00\xff',
1044 -8388608: b'\x00\x00\x80'
1045 }
1046 check(tests2, 'little', signed=True)
1047
1048 # Convert integers to unsigned big-endian byte arrays.
1049 tests3 = {
1050 0: b'\x00',
1051 1: b'\x01',
1052 127: b'\x7f',
1053 128: b'\x80',
1054 255: b'\xff',
1055 256: b'\x01\x00',
1056 32767: b'\x7f\xff',
1057 32768: b'\x80\x00',
1058 65535: b'\xff\xff',
1059 65536: b'\x01\x00\x00'
1060 }
1061 check(tests3, 'big', signed=False)
1062
1063 # Convert integers to unsigned little-endian byte arrays.
1064 tests4 = {
1065 0: b'\x00',
1066 1: b'\x01',
1067 127: b'\x7f',
1068 128: b'\x80',
1069 255: b'\xff',
1070 256: b'\x00\x01',
1071 32767: b'\xff\x7f',
1072 32768: b'\x00\x80',
1073 65535: b'\xff\xff',
1074 65536: b'\x00\x00\x01'
1075 }
1076 check(tests4, 'little', signed=False)
1077
1078 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
1079 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
1080 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
1081 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
Victor Stinner3fa1aae2013-03-26 01:14:08 +01001082 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001083 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
1084 self.assertEqual((0).to_bytes(0, 'big'), b'')
1085 self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
1086 self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
1087 self.assertEqual((-1).to_bytes(5, 'big', signed=True),
1088 b'\xff\xff\xff\xff\xff')
1089 self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1090
1091 def test_from_bytes(self):
1092 def check(tests, byteorder, signed=False):
1093 for test, expected in tests.items():
1094 try:
1095 self.assertEqual(
1096 int.from_bytes(test, byteorder, signed=signed),
1097 expected)
1098 except Exception as err:
1099 raise AssertionError(
1100 "failed to convert {0} with byteorder={1!r} and signed={2}"
1101 .format(test, byteorder, signed)) from err
1102
1103 # Convert signed big-endian byte arrays to integers.
1104 tests1 = {
1105 b'': 0,
1106 b'\x00': 0,
1107 b'\x00\x00': 0,
1108 b'\x01': 1,
1109 b'\x00\x01': 1,
1110 b'\xff': -1,
1111 b'\xff\xff': -1,
1112 b'\x81': -127,
1113 b'\x80': -128,
1114 b'\xff\x7f': -129,
1115 b'\x7f': 127,
1116 b'\x00\x81': 129,
1117 b'\xff\x01': -255,
1118 b'\xff\x00': -256,
1119 b'\x00\xff': 255,
1120 b'\x01\x00': 256,
1121 b'\x7f\xff': 32767,
1122 b'\x80\x00': -32768,
1123 b'\x00\xff\xff': 65535,
1124 b'\xff\x00\x00': -65536,
1125 b'\x80\x00\x00': -8388608
1126 }
1127 check(tests1, 'big', signed=True)
1128
1129 # Convert signed little-endian byte arrays to integers.
1130 tests2 = {
1131 b'': 0,
1132 b'\x00': 0,
1133 b'\x00\x00': 0,
1134 b'\x01': 1,
1135 b'\x00\x01': 256,
1136 b'\xff': -1,
1137 b'\xff\xff': -1,
1138 b'\x81': -127,
1139 b'\x80': -128,
1140 b'\x7f\xff': -129,
1141 b'\x7f': 127,
1142 b'\x81\x00': 129,
1143 b'\x01\xff': -255,
1144 b'\x00\xff': -256,
1145 b'\xff\x00': 255,
1146 b'\x00\x01': 256,
1147 b'\xff\x7f': 32767,
1148 b'\x00\x80': -32768,
1149 b'\xff\xff\x00': 65535,
1150 b'\x00\x00\xff': -65536,
1151 b'\x00\x00\x80': -8388608
1152 }
1153 check(tests2, 'little', signed=True)
1154
1155 # Convert unsigned big-endian byte arrays to integers.
1156 tests3 = {
1157 b'': 0,
1158 b'\x00': 0,
1159 b'\x01': 1,
1160 b'\x7f': 127,
1161 b'\x80': 128,
1162 b'\xff': 255,
1163 b'\x01\x00': 256,
1164 b'\x7f\xff': 32767,
1165 b'\x80\x00': 32768,
1166 b'\xff\xff': 65535,
1167 b'\x01\x00\x00': 65536,
1168 }
1169 check(tests3, 'big', signed=False)
1170
1171 # Convert integers to unsigned little-endian byte arrays.
1172 tests4 = {
1173 b'': 0,
1174 b'\x00': 0,
1175 b'\x01': 1,
1176 b'\x7f': 127,
1177 b'\x80': 128,
1178 b'\xff': 255,
1179 b'\x00\x01': 256,
1180 b'\xff\x7f': 32767,
1181 b'\x00\x80': 32768,
1182 b'\xff\xff': 65535,
1183 b'\x00\x00\x01': 65536,
1184 }
1185 check(tests4, 'little', signed=False)
1186
1187 class myint(int):
1188 pass
1189
1190 self.assertTrue(type(myint.from_bytes(b'\x00', 'big')) is myint)
1191 self.assertEqual(myint.from_bytes(b'\x01', 'big'), 1)
1192 self.assertTrue(
1193 type(myint.from_bytes(b'\x00', 'big', signed=False)) is myint)
1194 self.assertEqual(myint.from_bytes(b'\x01', 'big', signed=False), 1)
1195 self.assertTrue(type(myint.from_bytes(b'\x00', 'little')) is myint)
1196 self.assertEqual(myint.from_bytes(b'\x01', 'little'), 1)
1197 self.assertTrue(type(myint.from_bytes(
1198 b'\x00', 'little', signed=False)) is myint)
1199 self.assertEqual(myint.from_bytes(b'\x01', 'little', signed=False), 1)
1200 self.assertEqual(
1201 int.from_bytes([255, 0, 0], 'big', signed=True), -65536)
1202 self.assertEqual(
1203 int.from_bytes((255, 0, 0), '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 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1208 self.assertEqual(int.from_bytes(
1209 array.array('B', b'\xff\x00\x00'), 'big', signed=True), -65536)
1210 self.assertEqual(int.from_bytes(
1211 memoryview(b'\xff\x00\x00'), 'big', signed=True), -65536)
1212 self.assertRaises(ValueError, int.from_bytes, [256], 'big')
1213 self.assertRaises(ValueError, int.from_bytes, [0], 'big\x00')
1214 self.assertRaises(ValueError, int.from_bytes, [0], 'little\x00')
1215 self.assertRaises(TypeError, int.from_bytes, "", 'big')
1216 self.assertRaises(TypeError, int.from_bytes, "\x00", 'big')
1217 self.assertRaises(TypeError, int.from_bytes, 0, 'big')
1218 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1219 self.assertRaises(TypeError, myint.from_bytes, "", 'big')
1220 self.assertRaises(TypeError, myint.from_bytes, "\x00", 'big')
1221 self.assertRaises(TypeError, myint.from_bytes, 0, 'big')
1222 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
Mark Dickinson1124e712009-01-28 21:25:58 +00001223
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +01001224 def test_access_to_nonexistent_digit_0(self):
1225 # http://bugs.python.org/issue14630: A bug in _PyLong_Copy meant that
1226 # ob_digit[0] was being incorrectly accessed for instances of a
1227 # subclass of int, with value 0.
1228 class Integer(int):
1229 def __new__(cls, value=0):
1230 self = int.__new__(cls, value)
1231 self.foo = 'foo'
1232 return self
1233
1234 integers = [Integer(0) for i in range(1000)]
1235 for n in map(int, integers):
1236 self.assertEqual(n, 0)
1237
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00001238
Walter Dörwalda0021592005-06-13 21:44:48 +00001239def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001240 support.run_unittest(LongTest)
Tim Peters307fa782004-09-23 08:06:40 +00001241
Walter Dörwalda0021592005-06-13 21:44:48 +00001242if __name__ == "__main__":
1243 test_main()