blob: 7be89fcf1609d086f3df54fd4ffbbe571fca82b0 [file] [log] [blame]
Walter Dörwalda0021592005-06-13 21:44:48 +00001import unittest
2from test import test_support
Benjamin Peterson979395b2008-05-03 21:35:18 +00003import sys
Walter Dörwalda0021592005-06-13 21:44:48 +00004
5import random
Mark Dickinson1a707982008-12-17 16:14:37 +00006import math
Walter Dörwalda0021592005-06-13 21:44:48 +00007
8# Used for lazy formatting of failure messages
9class Frm(object):
10 def __init__(self, format, *args):
11 self.format = format
12 self.args = args
13
14 def __str__(self):
15 return self.format % self.args
Guido van Rossum4365cab1998-08-13 14:20:17 +000016
17# SHIFT should match the value in longintrepr.h for best testing.
Mark Dickinsonefc82f72009-03-20 15:51:55 +000018SHIFT = sys.long_info.bits_per_digit
Guido van Rossum4365cab1998-08-13 14:20:17 +000019BASE = 2 ** SHIFT
20MASK = BASE - 1
Tim Petersdaec9612004-08-30 23:18:23 +000021KARATSUBA_CUTOFF = 70 # from longobject.c
Guido van Rossum4365cab1998-08-13 14:20:17 +000022
23# Max number of base BASE digits to use in test cases. Doubling
Tim Peters28b0e2a2002-08-13 02:17:11 +000024# this will more than double the runtime.
25MAXDIGITS = 15
Guido van Rossum4365cab1998-08-13 14:20:17 +000026
Guido van Rossum4581a0c1998-10-02 01:19:48 +000027# build some special values
28special = map(long, [0, 1, 2, BASE, BASE >> 1])
29special.append(0x5555555555555555L)
30special.append(0xaaaaaaaaaaaaaaaaL)
31# some solid strings of one bits
32p2 = 4L # 0 and 1 already added
33for i in range(2*SHIFT):
34 special.append(p2 - 1)
35 p2 = p2 << 1
36del p2
37# add complements & negations
38special = special + map(lambda x: ~x, special) + \
39 map(lambda x: -x, special)
40
Benjamin Peterson979395b2008-05-03 21:35:18 +000041L = [
42 ('0', 0),
43 ('1', 1),
44 ('9', 9),
45 ('10', 10),
46 ('99', 99),
47 ('100', 100),
48 ('314', 314),
49 (' 314', 314),
50 ('314 ', 314),
51 (' \t\t 314 \t\t ', 314),
52 (repr(sys.maxint), sys.maxint),
53 (' 1x', ValueError),
54 (' 1 ', 1),
55 (' 1\02 ', ValueError),
56 ('', ValueError),
57 (' ', ValueError),
58 (' \t\t ', ValueError)
59]
60if test_support.have_unicode:
61 L += [
62 (unicode('0'), 0),
63 (unicode('1'), 1),
64 (unicode('9'), 9),
65 (unicode('10'), 10),
66 (unicode('99'), 99),
67 (unicode('100'), 100),
68 (unicode('314'), 314),
69 (unicode(' 314'), 314),
70 (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
71 (unicode(' \t\t 314 \t\t '), 314),
72 (unicode(' 1x'), ValueError),
73 (unicode(' 1 '), 1),
74 (unicode(' 1\02 '), ValueError),
75 (unicode(''), ValueError),
76 (unicode(' '), ValueError),
77 (unicode(' \t\t '), ValueError),
78 (unichr(0x200), ValueError),
79]
80
Guido van Rossum4365cab1998-08-13 14:20:17 +000081
Walter Dörwalda0021592005-06-13 21:44:48 +000082class LongTest(unittest.TestCase):
Guido van Rossum4365cab1998-08-13 14:20:17 +000083
Walter Dörwalda0021592005-06-13 21:44:48 +000084 # Get quasi-random long consisting of ndigits digits (in base BASE).
85 # quasi == the most-significant digit will not be 0, and the number
86 # is constructed to contain long strings of 0 and 1 bits. These are
87 # more likely than random bits to provoke digit-boundary errors.
88 # The sign of the number is also random.
Guido van Rossum4365cab1998-08-13 14:20:17 +000089
Walter Dörwalda0021592005-06-13 21:44:48 +000090 def getran(self, ndigits):
Benjamin Peterson5c8da862009-06-30 22:57:08 +000091 self.assertTrue(ndigits > 0)
Walter Dörwalda0021592005-06-13 21:44:48 +000092 nbits_hi = ndigits * SHIFT
93 nbits_lo = nbits_hi - SHIFT + 1
94 answer = 0L
95 nbits = 0
96 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
97 while nbits < nbits_lo:
98 bits = (r >> 1) + 1
99 bits = min(bits, nbits_hi - nbits)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000100 self.assertTrue(1 <= bits <= SHIFT)
Walter Dörwalda0021592005-06-13 21:44:48 +0000101 nbits = nbits + bits
102 answer = answer << bits
103 if r & 1:
104 answer = answer | ((1 << bits) - 1)
105 r = int(random.random() * (SHIFT * 2))
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000106 self.assertTrue(nbits_lo <= nbits <= nbits_hi)
Walter Dörwalda0021592005-06-13 21:44:48 +0000107 if random.random() < 0.5:
108 answer = -answer
109 return answer
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000110
Walter Dörwalda0021592005-06-13 21:44:48 +0000111 # Get random long consisting of ndigits random digits (relative to base
112 # BASE). The sign bit is also random.
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000113
Walter Dörwalda0021592005-06-13 21:44:48 +0000114 def getran2(ndigits):
115 answer = 0L
116 for i in xrange(ndigits):
117 answer = (answer << SHIFT) | random.randint(0, MASK)
118 if random.random() < 0.5:
119 answer = -answer
120 return answer
Guido van Rossum4365cab1998-08-13 14:20:17 +0000121
Walter Dörwalda0021592005-06-13 21:44:48 +0000122 def check_division(self, x, y):
123 eq = self.assertEqual
124 q, r = divmod(x, y)
125 q2, r2 = x//y, x%y
126 pab, pba = x*y, y*x
127 eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
128 eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
129 eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
130 eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
131 if y > 0:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000132 self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000133 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000134 self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000135
Walter Dörwalda0021592005-06-13 21:44:48 +0000136 def test_division(self):
137 digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF,
138 KARATSUBA_CUTOFF + 14)
139 digits.append(KARATSUBA_CUTOFF * 3)
140 for lenx in digits:
141 x = self.getran(lenx)
142 for leny in digits:
143 y = self.getran(leny) or 1L
144 self.check_division(x, y)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000145
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000146 # specific numbers chosen to exercise corner cases of the
147 # current long division implementation
148
149 # 30-bit cases involving a quotient digit estimate of BASE+1
150 self.check_division(1231948412290879395966702881L,
151 1147341367131428698L)
152 self.check_division(815427756481275430342312021515587883L,
153 707270836069027745L)
154 self.check_division(627976073697012820849443363563599041L,
155 643588798496057020L)
156 self.check_division(1115141373653752303710932756325578065L,
157 1038556335171453937726882627L)
158 # 30-bit cases that require the post-subtraction correction step
159 self.check_division(922498905405436751940989320930368494L,
160 949985870686786135626943396L)
161 self.check_division(768235853328091167204009652174031844L,
162 1091555541180371554426545266L)
163
164 # 15-bit cases involving a quotient digit estimate of BASE+1
165 self.check_division(20172188947443L, 615611397L)
166 self.check_division(1020908530270155025L, 950795710L)
167 self.check_division(128589565723112408L, 736393718L)
168 self.check_division(609919780285761575L, 18613274546784L)
169 # 15-bit cases that require the post-subtraction correction step
170 self.check_division(710031681576388032L, 26769404391308L)
171 self.check_division(1933622614268221L, 30212853348836L)
172
173
174
Walter Dörwalda0021592005-06-13 21:44:48 +0000175 def test_karatsuba(self):
176 digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10)
177 digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
Guido van Rossum4365cab1998-08-13 14:20:17 +0000178
Walter Dörwalda0021592005-06-13 21:44:48 +0000179 bits = [digit * SHIFT for digit in digits]
Guido van Rossum4365cab1998-08-13 14:20:17 +0000180
Walter Dörwalda0021592005-06-13 21:44:48 +0000181 # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
182 # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
183 for abits in bits:
184 a = (1L << abits) - 1
185 for bbits in bits:
186 if bbits < abits:
187 continue
188 b = (1L << bbits) - 1
189 x = a * b
190 y = ((1L << (abits + bbits)) -
191 (1L << abits) -
192 (1L << bbits) +
193 1)
194 self.assertEqual(x, y,
195 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 +0000196
Walter Dörwalda0021592005-06-13 21:44:48 +0000197 def check_bitop_identities_1(self, x):
198 eq = self.assertEqual
199 eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))
200 eq(x | 0, x, Frm("x | 0 != x for x=%r", x))
201 eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x))
202 eq(x & -1, x, Frm("x & -1 != x for x=%r", x))
203 eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x))
204 eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x))
205 eq(x, ~~x, Frm("x != ~~x for x=%r", x))
206 eq(x & x, x, Frm("x & x != x for x=%r", x))
207 eq(x | x, x, Frm("x | x != x for x=%r", x))
208 eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x))
209 eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x))
210 eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x))
211 eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
212 eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
213 eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
214 for n in xrange(2*SHIFT):
215 p2 = 2L ** n
216 eq(x << n >> n, x,
217 Frm("x << n >> n != x for x=%r, n=%r", (x, n)))
218 eq(x // p2, x >> n,
219 Frm("x // p2 != x >> n for x=%r n=%r p2=%r", (x, n, p2)))
220 eq(x * p2, x << n,
221 Frm("x * p2 != x << n for x=%r n=%r p2=%r", (x, n, p2)))
222 eq(x & -p2, x >> n << n,
223 Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", (x, n, p2)))
224 eq(x & -p2, x & ~(p2 - 1),
225 Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", (x, n, p2)))
Tim Peters7f270ba2002-08-13 21:06:55 +0000226
Walter Dörwalda0021592005-06-13 21:44:48 +0000227 def check_bitop_identities_2(self, x, y):
228 eq = self.assertEqual
229 eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", (x, y)))
230 eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", (x, y)))
231 eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", (x, y)))
232 eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", (x, y)))
233 eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", (x, y)))
234 eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", (x, y)))
235 eq(x ^ y, (x | y) & ~(x & y),
236 Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", (x, y)))
237 eq(x ^ y, (x & ~y) | (~x & y),
238 Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", (x, y)))
239 eq(x ^ y, (x | y) & (~x | ~y),
240 Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", (x, y)))
Tim Peters7f270ba2002-08-13 21:06:55 +0000241
Walter Dörwalda0021592005-06-13 21:44:48 +0000242 def check_bitop_identities_3(self, x, y, z):
243 eq = self.assertEqual
244 eq((x & y) & z, x & (y & z),
245 Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", (x, y, z)))
246 eq((x | y) | z, x | (y | z),
247 Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", (x, y, z)))
248 eq((x ^ y) ^ z, x ^ (y ^ z),
249 Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", (x, y, z)))
250 eq(x & (y | z), (x & y) | (x & z),
251 Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", (x, y, z)))
252 eq(x | (y & z), (x | y) & (x | z),
253 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 +0000254
Walter Dörwalda0021592005-06-13 21:44:48 +0000255 def test_bitop_identities(self):
256 for x in special:
257 self.check_bitop_identities_1(x)
258 digits = xrange(1, MAXDIGITS+1)
259 for lenx in digits:
260 x = self.getran(lenx)
261 self.check_bitop_identities_1(x)
262 for leny in digits:
263 y = self.getran(leny)
264 self.check_bitop_identities_2(x, y)
265 self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000266
Walter Dörwalda0021592005-06-13 21:44:48 +0000267 def slow_format(self, x, base):
268 if (x, base) == (0, 8):
269 # this is an oddball!
270 return "0L"
271 digits = []
272 sign = 0
273 if x < 0:
274 sign, x = 1, -x
275 while x:
276 x, r = divmod(x, base)
277 digits.append(int(r))
278 digits.reverse()
279 digits = digits or [0]
280 return '-'[:sign] + \
281 {8: '0', 10: '', 16: '0x'}[base] + \
Raymond Hettinger3296e692005-06-29 23:29:56 +0000282 "".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L"
Guido van Rossum4365cab1998-08-13 14:20:17 +0000283
Walter Dörwalda0021592005-06-13 21:44:48 +0000284 def check_format_1(self, x):
285 for base, mapper in (8, oct), (10, repr), (16, hex):
286 got = mapper(x)
287 expected = self.slow_format(x, base)
288 msg = Frm("%s returned %r but expected %r for %r",
289 mapper.__name__, got, expected, x)
290 self.assertEqual(got, expected, msg)
291 self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x))
292 # str() has to be checked a little differently since there's no
293 # trailing "L"
294 got = str(x)
295 expected = self.slow_format(x, 10)[:-1]
296 msg = Frm("%s returned %r but expected %r for %r",
297 mapper.__name__, got, expected, x)
298 self.assertEqual(got, expected, msg)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000299
Walter Dörwalda0021592005-06-13 21:44:48 +0000300 def test_format(self):
301 for x in special:
302 self.check_format_1(x)
303 for i in xrange(10):
304 for lenx in xrange(1, MAXDIGITS+1):
305 x = self.getran(lenx)
306 self.check_format_1(x)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000307
Benjamin Peterson979395b2008-05-03 21:35:18 +0000308 def test_long(self):
309 self.assertEqual(long(314), 314L)
310 self.assertEqual(long(3.14), 3L)
311 self.assertEqual(long(314L), 314L)
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +0000312 # Check that long() of basic types actually returns a long
313 self.assertEqual(type(long(314)), long)
314 self.assertEqual(type(long(3.14)), long)
315 self.assertEqual(type(long(314L)), long)
Benjamin Peterson979395b2008-05-03 21:35:18 +0000316 # Check that conversion from float truncates towards zero
317 self.assertEqual(long(-3.14), -3L)
318 self.assertEqual(long(3.9), 3L)
319 self.assertEqual(long(-3.9), -3L)
320 self.assertEqual(long(3.5), 3L)
321 self.assertEqual(long(-3.5), -3L)
322 self.assertEqual(long("-3"), -3L)
Mark Dickinson20665592010-05-25 19:01:08 +0000323 self.assertEqual(long("0b10", 2), 2L)
324 self.assertEqual(long("0o10", 8), 8L)
325 self.assertEqual(long("0x10", 16), 16L)
Benjamin Peterson979395b2008-05-03 21:35:18 +0000326 if test_support.have_unicode:
327 self.assertEqual(long(unicode("-3")), -3L)
328 # Different base:
329 self.assertEqual(long("10",16), 16L)
330 if test_support.have_unicode:
331 self.assertEqual(long(unicode("10"),16), 16L)
332 # Check conversions from string (same test set as for int(), and then some)
333 LL = [
334 ('1' + '0'*20, 10L**20),
335 ('1' + '0'*100, 10L**100)
336 ]
337 L2 = L[:]
338 if test_support.have_unicode:
339 L2 += [
340 (unicode('1') + unicode('0')*20, 10L**20),
341 (unicode('1') + unicode('0')*100, 10L**100),
342 ]
343 for s, v in L2 + LL:
344 for sign in "", "+", "-":
345 for prefix in "", " ", "\t", " \t\t ":
346 ss = prefix + sign + s
347 vv = v
348 if sign == "-" and v is not ValueError:
349 vv = -v
350 try:
351 self.assertEqual(long(ss), long(vv))
352 except v:
353 pass
354
355 self.assertRaises(ValueError, long, '123\0')
356 self.assertRaises(ValueError, long, '53', 40)
357 self.assertRaises(TypeError, long, 1, 12)
358
359 # SF patch #1638879: embedded NULs were not detected with
360 # explicit base
361 self.assertRaises(ValueError, long, '123\0', 10)
362 self.assertRaises(ValueError, long, '123\x00 245', 20)
363
364 self.assertEqual(long('100000000000000000000000000000000', 2),
365 4294967296)
366 self.assertEqual(long('102002022201221111211', 3), 4294967296)
367 self.assertEqual(long('10000000000000000', 4), 4294967296)
368 self.assertEqual(long('32244002423141', 5), 4294967296)
369 self.assertEqual(long('1550104015504', 6), 4294967296)
370 self.assertEqual(long('211301422354', 7), 4294967296)
371 self.assertEqual(long('40000000000', 8), 4294967296)
372 self.assertEqual(long('12068657454', 9), 4294967296)
373 self.assertEqual(long('4294967296', 10), 4294967296)
374 self.assertEqual(long('1904440554', 11), 4294967296)
375 self.assertEqual(long('9ba461594', 12), 4294967296)
376 self.assertEqual(long('535a79889', 13), 4294967296)
377 self.assertEqual(long('2ca5b7464', 14), 4294967296)
378 self.assertEqual(long('1a20dcd81', 15), 4294967296)
379 self.assertEqual(long('100000000', 16), 4294967296)
380 self.assertEqual(long('a7ffda91', 17), 4294967296)
381 self.assertEqual(long('704he7g4', 18), 4294967296)
382 self.assertEqual(long('4f5aff66', 19), 4294967296)
383 self.assertEqual(long('3723ai4g', 20), 4294967296)
384 self.assertEqual(long('281d55i4', 21), 4294967296)
385 self.assertEqual(long('1fj8b184', 22), 4294967296)
386 self.assertEqual(long('1606k7ic', 23), 4294967296)
387 self.assertEqual(long('mb994ag', 24), 4294967296)
388 self.assertEqual(long('hek2mgl', 25), 4294967296)
389 self.assertEqual(long('dnchbnm', 26), 4294967296)
390 self.assertEqual(long('b28jpdm', 27), 4294967296)
391 self.assertEqual(long('8pfgih4', 28), 4294967296)
392 self.assertEqual(long('76beigg', 29), 4294967296)
393 self.assertEqual(long('5qmcpqg', 30), 4294967296)
394 self.assertEqual(long('4q0jto4', 31), 4294967296)
395 self.assertEqual(long('4000000', 32), 4294967296)
396 self.assertEqual(long('3aokq94', 33), 4294967296)
397 self.assertEqual(long('2qhxjli', 34), 4294967296)
398 self.assertEqual(long('2br45qb', 35), 4294967296)
399 self.assertEqual(long('1z141z4', 36), 4294967296)
400
401 self.assertEqual(long('100000000000000000000000000000001', 2),
402 4294967297)
403 self.assertEqual(long('102002022201221111212', 3), 4294967297)
404 self.assertEqual(long('10000000000000001', 4), 4294967297)
405 self.assertEqual(long('32244002423142', 5), 4294967297)
406 self.assertEqual(long('1550104015505', 6), 4294967297)
407 self.assertEqual(long('211301422355', 7), 4294967297)
408 self.assertEqual(long('40000000001', 8), 4294967297)
409 self.assertEqual(long('12068657455', 9), 4294967297)
410 self.assertEqual(long('4294967297', 10), 4294967297)
411 self.assertEqual(long('1904440555', 11), 4294967297)
412 self.assertEqual(long('9ba461595', 12), 4294967297)
413 self.assertEqual(long('535a7988a', 13), 4294967297)
414 self.assertEqual(long('2ca5b7465', 14), 4294967297)
415 self.assertEqual(long('1a20dcd82', 15), 4294967297)
416 self.assertEqual(long('100000001', 16), 4294967297)
417 self.assertEqual(long('a7ffda92', 17), 4294967297)
418 self.assertEqual(long('704he7g5', 18), 4294967297)
419 self.assertEqual(long('4f5aff67', 19), 4294967297)
420 self.assertEqual(long('3723ai4h', 20), 4294967297)
421 self.assertEqual(long('281d55i5', 21), 4294967297)
422 self.assertEqual(long('1fj8b185', 22), 4294967297)
423 self.assertEqual(long('1606k7id', 23), 4294967297)
424 self.assertEqual(long('mb994ah', 24), 4294967297)
425 self.assertEqual(long('hek2mgm', 25), 4294967297)
426 self.assertEqual(long('dnchbnn', 26), 4294967297)
427 self.assertEqual(long('b28jpdn', 27), 4294967297)
428 self.assertEqual(long('8pfgih5', 28), 4294967297)
429 self.assertEqual(long('76beigh', 29), 4294967297)
430 self.assertEqual(long('5qmcpqh', 30), 4294967297)
431 self.assertEqual(long('4q0jto5', 31), 4294967297)
432 self.assertEqual(long('4000001', 32), 4294967297)
433 self.assertEqual(long('3aokq95', 33), 4294967297)
434 self.assertEqual(long('2qhxjlj', 34), 4294967297)
435 self.assertEqual(long('2br45qc', 35), 4294967297)
436 self.assertEqual(long('1z141z5', 36), 4294967297)
437
438
439 def test_conversion(self):
440 # Test __long__()
441 class ClassicMissingMethods:
442 pass
443 self.assertRaises(AttributeError, long, ClassicMissingMethods())
444
445 class MissingMethods(object):
446 pass
447 self.assertRaises(TypeError, long, MissingMethods())
448
449 class Foo0:
450 def __long__(self):
451 return 42L
452
453 class Foo1(object):
454 def __long__(self):
455 return 42L
456
457 class Foo2(long):
458 def __long__(self):
459 return 42L
460
461 class Foo3(long):
462 def __long__(self):
463 return self
464
465 class Foo4(long):
466 def __long__(self):
467 return 42
468
469 class Foo5(long):
470 def __long__(self):
471 return 42.
472
473 self.assertEqual(long(Foo0()), 42L)
474 self.assertEqual(long(Foo1()), 42L)
475 self.assertEqual(long(Foo2()), 42L)
476 self.assertEqual(long(Foo3()), 0)
477 self.assertEqual(long(Foo4()), 42)
478 self.assertRaises(TypeError, long, Foo5())
479
480 class Classic:
481 pass
482 for base in (object, Classic):
483 class LongOverridesTrunc(base):
484 def __long__(self):
485 return 42
486 def __trunc__(self):
487 return -12
488 self.assertEqual(long(LongOverridesTrunc()), 42)
489
490 class JustTrunc(base):
491 def __trunc__(self):
492 return 42
493 self.assertEqual(long(JustTrunc()), 42)
494
495 for trunc_result_base in (object, Classic):
496 class Integral(trunc_result_base):
497 def __int__(self):
498 return 42
499
500 class TruncReturnsNonLong(base):
501 def __trunc__(self):
502 return Integral()
503 self.assertEqual(long(TruncReturnsNonLong()), 42)
504
505 class NonIntegral(trunc_result_base):
506 def __trunc__(self):
507 # Check that we avoid infinite recursion.
508 return NonIntegral()
509
510 class TruncReturnsNonIntegral(base):
511 def __trunc__(self):
512 return NonIntegral()
513 try:
514 long(TruncReturnsNonIntegral())
515 except TypeError as e:
516 self.assertEquals(str(e),
517 "__trunc__ returned non-Integral"
518 " (type NonIntegral)")
519 else:
520 self.fail("Failed to raise TypeError with %s" %
521 ((base, trunc_result_base),))
522
Walter Dörwalda0021592005-06-13 21:44:48 +0000523 def test_misc(self):
Guido van Rossum4365cab1998-08-13 14:20:17 +0000524
Walter Dörwalda0021592005-06-13 21:44:48 +0000525 # check the extremes in int<->long conversion
526 hugepos = sys.maxint
527 hugeneg = -hugepos - 1
528 hugepos_aslong = long(hugepos)
529 hugeneg_aslong = long(hugeneg)
530 self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint")
531 self.assertEqual(hugeneg, hugeneg_aslong,
532 "long(-sys.maxint-1) != -sys.maxint-1")
Guido van Rossum4365cab1998-08-13 14:20:17 +0000533
Walter Dörwalda0021592005-06-13 21:44:48 +0000534 # long -> int should not fail for hugepos_aslong or hugeneg_aslong
Armin Rigo7ccbca92006-10-04 12:17:45 +0000535 x = int(hugepos_aslong)
Walter Dörwalda0021592005-06-13 21:44:48 +0000536 try:
Armin Rigo7ccbca92006-10-04 12:17:45 +0000537 self.assertEqual(x, hugepos,
Walter Dörwalda0021592005-06-13 21:44:48 +0000538 "converting sys.maxint to long and back to int fails")
539 except OverflowError:
540 self.fail("int(long(sys.maxint)) overflowed!")
Armin Rigo7ccbca92006-10-04 12:17:45 +0000541 if not isinstance(x, int):
Georg Brandldf8a3032010-02-06 23:08:00 +0000542 self.fail("int(long(sys.maxint)) should have returned int")
Armin Rigo7ccbca92006-10-04 12:17:45 +0000543 x = int(hugeneg_aslong)
Walter Dörwalda0021592005-06-13 21:44:48 +0000544 try:
Armin Rigo7ccbca92006-10-04 12:17:45 +0000545 self.assertEqual(x, hugeneg,
Walter Dörwalda0021592005-06-13 21:44:48 +0000546 "converting -sys.maxint-1 to long and back to int fails")
547 except OverflowError:
548 self.fail("int(long(-sys.maxint-1)) overflowed!")
Armin Rigo7ccbca92006-10-04 12:17:45 +0000549 if not isinstance(x, int):
Georg Brandldf8a3032010-02-06 23:08:00 +0000550 self.fail("int(long(-sys.maxint-1)) should have returned int")
Walter Dörwalda0021592005-06-13 21:44:48 +0000551 # but long -> int should overflow for hugepos+1 and hugeneg-1
552 x = hugepos_aslong + 1
553 try:
554 y = int(x)
555 except OverflowError:
556 self.fail("int(long(sys.maxint) + 1) mustn't overflow")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000557 self.assertIsInstance(y, long,
Walter Dörwalda0021592005-06-13 21:44:48 +0000558 "int(long(sys.maxint) + 1) should have returned long")
Guido van Rossum4365cab1998-08-13 14:20:17 +0000559
Walter Dörwalda0021592005-06-13 21:44:48 +0000560 x = hugeneg_aslong - 1
561 try:
562 y = int(x)
563 except OverflowError:
564 self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000565 self.assertIsInstance(y, long,
Walter Dörwalda0021592005-06-13 21:44:48 +0000566 "int(long(-sys.maxint-1) - 1) should have returned long")
Guido van Rossum4365cab1998-08-13 14:20:17 +0000567
Walter Dörwalda0021592005-06-13 21:44:48 +0000568 class long2(long):
569 pass
570 x = long2(1L<<100)
Walter Dörwaldf1715402002-11-19 20:49:15 +0000571 y = int(x)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000572 self.assertTrue(type(y) is long,
Walter Dörwalda0021592005-06-13 21:44:48 +0000573 "overflowing int conversion must return long not long subtype")
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000574
Armin Rigo7ccbca92006-10-04 12:17:45 +0000575 # long -> Py_ssize_t conversion
576 class X(object):
577 def __getslice__(self, i, j):
578 return i, j
579
Florent Xicluna07627882010-03-21 01:14:24 +0000580 with test_support.check_py3k_warnings():
581 self.assertEqual(X()[-5L:7L], (-5, 7))
582 # use the clamping effect to test the smallest and largest longs
583 # that fit a Py_ssize_t
584 slicemin, slicemax = X()[-2L**100:2L**100]
585 self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
Armin Rigo7ccbca92006-10-04 12:17:45 +0000586
Tim Peters26c7fa32001-08-23 22:56:21 +0000587# ----------------------------------- tests of auto int->long conversion
588
Walter Dörwalda0021592005-06-13 21:44:48 +0000589 def test_auto_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000590 special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1]
591 sqrt = int(math.sqrt(sys.maxint))
592 special.extend([sqrt-1, sqrt, sqrt+1])
593 special.extend([-i for i in special])
Tim Peters26c7fa32001-08-23 22:56:21 +0000594
Walter Dörwalda0021592005-06-13 21:44:48 +0000595 def checkit(*args):
596 # Heavy use of nested scopes here!
597 self.assertEqual(got, expected,
598 Frm("for %r expected %r got %r", args, expected, got))
Tim Peters26c7fa32001-08-23 22:56:21 +0000599
Walter Dörwalda0021592005-06-13 21:44:48 +0000600 for x in special:
601 longx = long(x)
Tim Peters26c7fa32001-08-23 22:56:21 +0000602
Walter Dörwalda0021592005-06-13 21:44:48 +0000603 expected = -longx
604 got = -x
605 checkit('-', x)
Tim Peters26c7fa32001-08-23 22:56:21 +0000606
Walter Dörwalda0021592005-06-13 21:44:48 +0000607 for y in special:
608 longy = long(y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000609
Walter Dörwalda0021592005-06-13 21:44:48 +0000610 expected = longx + longy
611 got = x + y
612 checkit(x, '+', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000613
Walter Dörwalda0021592005-06-13 21:44:48 +0000614 expected = longx - longy
615 got = x - y
616 checkit(x, '-', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000617
Walter Dörwalda0021592005-06-13 21:44:48 +0000618 expected = longx * longy
619 got = x * y
620 checkit(x, '*', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000621
Walter Dörwalda0021592005-06-13 21:44:48 +0000622 if y:
Florent Xicluna07627882010-03-21 01:14:24 +0000623 with test_support.check_py3k_warnings():
624 expected = longx / longy
625 got = x / y
Walter Dörwalda0021592005-06-13 21:44:48 +0000626 checkit(x, '/', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000627
Walter Dörwalda0021592005-06-13 21:44:48 +0000628 expected = longx // longy
629 got = x // y
630 checkit(x, '//', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000631
Walter Dörwalda0021592005-06-13 21:44:48 +0000632 expected = divmod(longx, longy)
633 got = divmod(longx, longy)
634 checkit(x, 'divmod', y)
Tim Petersa3653092001-08-23 23:02:57 +0000635
Walter Dörwalda0021592005-06-13 21:44:48 +0000636 if abs(y) < 5 and not (x == 0 and y < 0):
637 expected = longx ** longy
638 got = x ** y
639 checkit(x, '**', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000640
Walter Dörwalda0021592005-06-13 21:44:48 +0000641 for z in special:
642 if z != 0 :
643 if y >= 0:
644 expected = pow(longx, longy, long(z))
645 got = pow(x, y, z)
646 checkit('pow', x, y, '%', z)
Tim Peters32f453e2001-09-03 08:35:41 +0000647 else:
Walter Dörwalda0021592005-06-13 21:44:48 +0000648 self.assertRaises(TypeError, pow,longx, longy, long(z))
Tim Peters26c7fa32001-08-23 22:56:21 +0000649
Mark Dickinson6736cf82009-04-20 21:13:33 +0000650 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
651 "test requires IEEE 754 doubles")
652 def test_float_conversion(self):
653 import sys
654 DBL_MAX = sys.float_info.max
655 DBL_MAX_EXP = sys.float_info.max_exp
656 DBL_MANT_DIG = sys.float_info.mant_dig
657
658 exact_values = [0L, 1L, 2L,
659 long(2**53-3),
660 long(2**53-2),
661 long(2**53-1),
662 long(2**53),
663 long(2**53+2),
664 long(2**54-4),
665 long(2**54-2),
666 long(2**54),
667 long(2**54+4)]
668 for x in exact_values:
669 self.assertEqual(long(float(x)), x)
670 self.assertEqual(long(float(-x)), -x)
671
672 # test round-half-even
673 for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
674 for p in xrange(15):
675 self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))
676
677 for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
678 (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
679 (13, 12), (14, 16), (15, 16)]:
680 for p in xrange(15):
681 self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))
682
683 # behaviour near extremes of floating-point range
684 long_dbl_max = long(DBL_MAX)
685 top_power = 2**DBL_MAX_EXP
Mark Dickinsona7e734f2009-04-20 21:41:04 +0000686 halfway = (long_dbl_max + top_power)//2
Mark Dickinson6736cf82009-04-20 21:13:33 +0000687 self.assertEqual(float(long_dbl_max), DBL_MAX)
688 self.assertEqual(float(long_dbl_max+1), DBL_MAX)
689 self.assertEqual(float(halfway-1), DBL_MAX)
690 self.assertRaises(OverflowError, float, halfway)
691 self.assertEqual(float(1-halfway), -DBL_MAX)
692 self.assertRaises(OverflowError, float, -halfway)
693 self.assertRaises(OverflowError, float, top_power-1)
694 self.assertRaises(OverflowError, float, top_power)
695 self.assertRaises(OverflowError, float, top_power+1)
696 self.assertRaises(OverflowError, float, 2*top_power-1)
697 self.assertRaises(OverflowError, float, 2*top_power)
698 self.assertRaises(OverflowError, float, top_power*top_power)
699
700 for p in xrange(100):
701 x = long(2**p * (2**53 + 1) + 1)
702 y = long(2**p * (2**53+ 2))
703 self.assertEqual(long(float(x)), y)
704
705 x = long(2**p * (2**53 + 1))
706 y = long(2**p * 2**53)
707 self.assertEqual(long(float(x)), y)
708
Walter Dörwalda0021592005-06-13 21:44:48 +0000709 def test_float_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000710 for x in -2.0, -1.0, 0.0, 1.0, 2.0:
711 self.assertEqual(float(long(x)), x)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000712
Walter Dörwalda0021592005-06-13 21:44:48 +0000713 shuge = '12345' * 120
714 huge = 1L << 30000
715 mhuge = -huge
716 namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
717 for test in ["float(huge)", "float(mhuge)",
718 "complex(huge)", "complex(mhuge)",
719 "complex(huge, 1)", "complex(mhuge, 1)",
720 "complex(1, huge)", "complex(1, mhuge)",
721 "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
722 "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
723 "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
724 "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
725 "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
726 "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
727 "math.sin(huge)", "math.sin(mhuge)",
728 "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000729 "math.floor(huge)", "math.floor(mhuge)"]:
Tim Peters9fffa3e2001-09-04 05:14:19 +0000730
Walter Dörwalda0021592005-06-13 21:44:48 +0000731 self.assertRaises(OverflowError, eval, test, namespace)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000732
Walter Dörwalda0021592005-06-13 21:44:48 +0000733 # XXX Perhaps float(shuge) can raise OverflowError on some box?
734 # The comparison should not.
735 self.assertNotEqual(float(shuge), int(shuge),
736 "float(shuge) should not equal int(shuge)")
Tim Peters83e7ccc2001-09-04 06:37:28 +0000737
Walter Dörwalda0021592005-06-13 21:44:48 +0000738 def test_logs(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000739 LOG10E = math.log10(math.e)
Tim Peters307fa782004-09-23 08:06:40 +0000740
Walter Dörwalda0021592005-06-13 21:44:48 +0000741 for exp in range(10) + [100, 1000, 10000]:
742 value = 10 ** exp
743 log10 = math.log10(value)
744 self.assertAlmostEqual(log10, exp)
Tim Peters78526162001-09-05 00:53:45 +0000745
Walter Dörwalda0021592005-06-13 21:44:48 +0000746 # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
747 # exp/LOG10E
748 expected = exp / LOG10E
749 log = math.log(value)
750 self.assertAlmostEqual(log, expected)
Tim Peters78526162001-09-05 00:53:45 +0000751
Walter Dörwalda0021592005-06-13 21:44:48 +0000752 for bad in -(1L << 10000), -2L, 0L:
753 self.assertRaises(ValueError, math.log, bad)
754 self.assertRaises(ValueError, math.log10, bad)
Tim Peters78526162001-09-05 00:53:45 +0000755
Walter Dörwalda0021592005-06-13 21:44:48 +0000756 def test_mixed_compares(self):
757 eq = self.assertEqual
Tim Peters78526162001-09-05 00:53:45 +0000758
Walter Dörwalda0021592005-06-13 21:44:48 +0000759 # We're mostly concerned with that mixing floats and longs does the
760 # right stuff, even when longs are too large to fit in a float.
761 # The safest way to check the results is to use an entirely different
762 # method, which we do here via a skeletal rational class (which
763 # represents all Python ints, longs and floats exactly).
764 class Rat:
765 def __init__(self, value):
766 if isinstance(value, (int, long)):
767 self.n = value
768 self.d = 1
769 elif isinstance(value, float):
770 # Convert to exact rational equivalent.
771 f, e = math.frexp(abs(value))
772 assert f == 0 or 0.5 <= f < 1.0
773 # |value| = f * 2**e exactly
Tim Peters78526162001-09-05 00:53:45 +0000774
Walter Dörwalda0021592005-06-13 21:44:48 +0000775 # Suck up CHUNK bits at a time; 28 is enough so that we suck
776 # up all bits in 2 iterations for all known binary double-
777 # precision formats, and small enough to fit in an int.
778 CHUNK = 28
779 top = 0
780 # invariant: |value| = (top + f) * 2**e exactly
781 while f:
782 f = math.ldexp(f, CHUNK)
783 digit = int(f)
784 assert digit >> CHUNK == 0
785 top = (top << CHUNK) | digit
786 f -= digit
787 assert 0.0 <= f < 1.0
788 e -= CHUNK
Tim Peters78526162001-09-05 00:53:45 +0000789
Walter Dörwalda0021592005-06-13 21:44:48 +0000790 # Now |value| = top * 2**e exactly.
791 if e >= 0:
792 n = top << e
793 d = 1
794 else:
795 n = top
796 d = 1 << -e
797 if value < 0:
798 n = -n
799 self.n = n
800 self.d = d
801 assert float(n) / float(d) == value
Tim Peters307fa782004-09-23 08:06:40 +0000802 else:
Georg Brandldf8a3032010-02-06 23:08:00 +0000803 raise TypeError("can't deal with %r" % value)
Tim Peters307fa782004-09-23 08:06:40 +0000804
Walter Dörwalda0021592005-06-13 21:44:48 +0000805 def __cmp__(self, other):
806 if not isinstance(other, Rat):
807 other = Rat(other)
808 return cmp(self.n * other.d, self.d * other.n)
Tim Peters307fa782004-09-23 08:06:40 +0000809
Walter Dörwalda0021592005-06-13 21:44:48 +0000810 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
811 # 2**48 is an important boundary in the internals. 2**53 is an
812 # important boundary for IEEE double precision.
813 for t in 2.0**48, 2.0**50, 2.0**53:
814 cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
815 long(t-1), long(t), long(t+1)])
816 cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)])
817 # 1L<<20000 should exceed all double formats. long(1e200) is to
818 # check that we get equality with 1e200 above.
819 t = long(1e200)
820 cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1])
821 cases.extend([-x for x in cases])
822 for x in cases:
823 Rx = Rat(x)
824 for y in cases:
825 Ry = Rat(y)
826 Rcmp = cmp(Rx, Ry)
827 xycmp = cmp(x, y)
828 eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
829 eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
830 eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
831 eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
832 eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
833 eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
834 eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
Tim Peters307fa782004-09-23 08:06:40 +0000835
Christian Heimes8267d1d2008-01-04 00:37:34 +0000836 def test_nan_inf(self):
837 self.assertRaises(OverflowError, long, float('inf'))
Mark Dickinsonb6467572008-08-04 21:30:09 +0000838 self.assertRaises(OverflowError, long, float('-inf'))
839 self.assertRaises(ValueError, long, float('nan'))
Christian Heimes8267d1d2008-01-04 00:37:34 +0000840
Mark Dickinson1a707982008-12-17 16:14:37 +0000841 def test_bit_length(self):
842 tiny = 1e-10
843 for x in xrange(-65000, 65000):
844 x = long(x)
845 k = x.bit_length()
846 # Check equivalence with Python version
847 self.assertEqual(k, len(bin(x).lstrip('-0b')))
848 # Behaviour as specified in the docs
849 if x != 0:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000850 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
Mark Dickinson1a707982008-12-17 16:14:37 +0000851 else:
852 self.assertEqual(k, 0)
853 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
854 if x != 0:
855 # When x is an exact power of 2, numeric errors can
856 # cause floor(log(x)/log(2)) to be one too small; for
857 # small x this can be fixed by adding a small quantity
858 # to the quotient before taking the floor.
859 self.assertEqual(k, 1 + math.floor(
860 math.log(abs(x))/math.log(2) + tiny))
861
862 self.assertEqual((0L).bit_length(), 0)
863 self.assertEqual((1L).bit_length(), 1)
864 self.assertEqual((-1L).bit_length(), 1)
865 self.assertEqual((2L).bit_length(), 2)
866 self.assertEqual((-2L).bit_length(), 2)
867 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
868 a = 2L**i
869 self.assertEqual((a-1).bit_length(), i)
870 self.assertEqual((1-a).bit_length(), i)
871 self.assertEqual((a).bit_length(), i+1)
872 self.assertEqual((-a).bit_length(), i+1)
873 self.assertEqual((a+1).bit_length(), i+1)
874 self.assertEqual((-a-1).bit_length(), i+1)
875
876
Walter Dörwalda0021592005-06-13 21:44:48 +0000877def test_main():
878 test_support.run_unittest(LongTest)
Tim Peters307fa782004-09-23 08:06:40 +0000879
Walter Dörwalda0021592005-06-13 21:44:48 +0000880if __name__ == "__main__":
881 test_main()