blob: b65d24cd9418913a8f496a10cc1c34b284f9c413 [file] [log] [blame]
Walter Dörwalda0021592005-06-13 21:44:48 +00001import unittest
Benjamin Peterson979395b2008-05-03 21:35:18 +00002import sys
Walter Dörwalda0021592005-06-13 21:44:48 +00003
4import random
Mark Dickinson1a707982008-12-17 16:14:37 +00005import math
Walter Dörwalda0021592005-06-13 21:44:48 +00006
Chris Jerdonek6f70fe82012-12-27 12:53:29 -08007from test import test_int, test_support
8
Walter Dörwalda0021592005-06-13 21:44:48 +00009# Used for lazy formatting of failure messages
10class Frm(object):
11 def __init__(self, format, *args):
12 self.format = format
13 self.args = args
14
15 def __str__(self):
16 return self.format % self.args
Guido van Rossum4365cab1998-08-13 14:20:17 +000017
18# SHIFT should match the value in longintrepr.h for best testing.
Mark Dickinsonefc82f72009-03-20 15:51:55 +000019SHIFT = sys.long_info.bits_per_digit
Guido van Rossum4365cab1998-08-13 14:20:17 +000020BASE = 2 ** SHIFT
21MASK = BASE - 1
Tim Petersdaec9612004-08-30 23:18:23 +000022KARATSUBA_CUTOFF = 70 # from longobject.c
Guido van Rossum4365cab1998-08-13 14:20:17 +000023
24# Max number of base BASE digits to use in test cases. Doubling
Tim Peters28b0e2a2002-08-13 02:17:11 +000025# this will more than double the runtime.
26MAXDIGITS = 15
Guido van Rossum4365cab1998-08-13 14:20:17 +000027
Guido van Rossum4581a0c1998-10-02 01:19:48 +000028# build some special values
29special = map(long, [0, 1, 2, BASE, BASE >> 1])
30special.append(0x5555555555555555L)
31special.append(0xaaaaaaaaaaaaaaaaL)
32# some solid strings of one bits
33p2 = 4L # 0 and 1 already added
34for i in range(2*SHIFT):
35 special.append(p2 - 1)
36 p2 = p2 << 1
37del p2
38# add complements & negations
39special = special + map(lambda x: ~x, special) + \
40 map(lambda x: -x, special)
41
Benjamin Peterson979395b2008-05-03 21:35:18 +000042L = [
43 ('0', 0),
44 ('1', 1),
45 ('9', 9),
46 ('10', 10),
47 ('99', 99),
48 ('100', 100),
49 ('314', 314),
50 (' 314', 314),
51 ('314 ', 314),
52 (' \t\t 314 \t\t ', 314),
53 (repr(sys.maxint), sys.maxint),
54 (' 1x', ValueError),
55 (' 1 ', 1),
56 (' 1\02 ', ValueError),
57 ('', ValueError),
58 (' ', ValueError),
59 (' \t\t ', ValueError)
60]
61if test_support.have_unicode:
62 L += [
63 (unicode('0'), 0),
64 (unicode('1'), 1),
65 (unicode('9'), 9),
66 (unicode('10'), 10),
67 (unicode('99'), 99),
68 (unicode('100'), 100),
69 (unicode('314'), 314),
70 (unicode(' 314'), 314),
71 (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
72 (unicode(' \t\t 314 \t\t '), 314),
73 (unicode(' 1x'), ValueError),
74 (unicode(' 1 '), 1),
75 (unicode(' 1\02 '), ValueError),
76 (unicode(''), ValueError),
77 (unicode(' '), ValueError),
78 (unicode(' \t\t '), ValueError),
79 (unichr(0x200), ValueError),
80]
81
Serhiy Storchaka8d30ad72015-11-25 15:55:54 +020082class LongSubclass(long):
83 pass
84
85class OtherLongSubclass(long):
86 pass
87
Chris Jerdonek6f70fe82012-12-27 12:53:29 -080088class LongTest(test_int.IntLongCommonTests, unittest.TestCase):
Guido van Rossum4365cab1998-08-13 14:20:17 +000089
Chris Jerdonek6f70fe82012-12-27 12:53:29 -080090 ntype = long
Guido van Rossum4365cab1998-08-13 14:20:17 +000091
Walter Dörwalda0021592005-06-13 21:44:48 +000092 # Get quasi-random long consisting of ndigits digits (in base BASE).
93 # quasi == the most-significant digit will not be 0, and the number
94 # is constructed to contain long strings of 0 and 1 bits. These are
95 # more likely than random bits to provoke digit-boundary errors.
96 # The sign of the number is also random.
Guido van Rossum4365cab1998-08-13 14:20:17 +000097
Walter Dörwalda0021592005-06-13 21:44:48 +000098 def getran(self, ndigits):
Serhiy Storchaka708a5ea2014-02-08 14:28:20 +020099 self.assertGreater(ndigits, 0)
Walter Dörwalda0021592005-06-13 21:44:48 +0000100 nbits_hi = ndigits * SHIFT
101 nbits_lo = nbits_hi - SHIFT + 1
102 answer = 0L
103 nbits = 0
104 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
105 while nbits < nbits_lo:
106 bits = (r >> 1) + 1
107 bits = min(bits, nbits_hi - nbits)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000108 self.assertTrue(1 <= bits <= SHIFT)
Walter Dörwalda0021592005-06-13 21:44:48 +0000109 nbits = nbits + bits
110 answer = answer << bits
111 if r & 1:
112 answer = answer | ((1 << bits) - 1)
113 r = int(random.random() * (SHIFT * 2))
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000114 self.assertTrue(nbits_lo <= nbits <= nbits_hi)
Walter Dörwalda0021592005-06-13 21:44:48 +0000115 if random.random() < 0.5:
116 answer = -answer
117 return answer
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000118
Walter Dörwalda0021592005-06-13 21:44:48 +0000119 # Get random long consisting of ndigits random digits (relative to base
120 # BASE). The sign bit is also random.
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000121
Walter Dörwalda0021592005-06-13 21:44:48 +0000122 def getran2(ndigits):
123 answer = 0L
124 for i in xrange(ndigits):
125 answer = (answer << SHIFT) | random.randint(0, MASK)
126 if random.random() < 0.5:
127 answer = -answer
128 return answer
Guido van Rossum4365cab1998-08-13 14:20:17 +0000129
Walter Dörwalda0021592005-06-13 21:44:48 +0000130 def check_division(self, x, y):
131 eq = self.assertEqual
132 q, r = divmod(x, y)
133 q2, r2 = x//y, x%y
134 pab, pba = x*y, y*x
135 eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
136 eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
137 eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
138 eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
139 if y > 0:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000140 self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000141 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000142 self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000143
Walter Dörwalda0021592005-06-13 21:44:48 +0000144 def test_division(self):
145 digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF,
146 KARATSUBA_CUTOFF + 14)
147 digits.append(KARATSUBA_CUTOFF * 3)
148 for lenx in digits:
149 x = self.getran(lenx)
150 for leny in digits:
151 y = self.getran(leny) or 1L
152 self.check_division(x, y)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000153
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000154 # specific numbers chosen to exercise corner cases of the
155 # current long division implementation
156
157 # 30-bit cases involving a quotient digit estimate of BASE+1
158 self.check_division(1231948412290879395966702881L,
159 1147341367131428698L)
160 self.check_division(815427756481275430342312021515587883L,
161 707270836069027745L)
162 self.check_division(627976073697012820849443363563599041L,
163 643588798496057020L)
164 self.check_division(1115141373653752303710932756325578065L,
165 1038556335171453937726882627L)
166 # 30-bit cases that require the post-subtraction correction step
167 self.check_division(922498905405436751940989320930368494L,
168 949985870686786135626943396L)
169 self.check_division(768235853328091167204009652174031844L,
170 1091555541180371554426545266L)
171
172 # 15-bit cases involving a quotient digit estimate of BASE+1
173 self.check_division(20172188947443L, 615611397L)
174 self.check_division(1020908530270155025L, 950795710L)
175 self.check_division(128589565723112408L, 736393718L)
176 self.check_division(609919780285761575L, 18613274546784L)
177 # 15-bit cases that require the post-subtraction correction step
178 self.check_division(710031681576388032L, 26769404391308L)
179 self.check_division(1933622614268221L, 30212853348836L)
180
181
182
Walter Dörwalda0021592005-06-13 21:44:48 +0000183 def test_karatsuba(self):
184 digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10)
185 digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
Guido van Rossum4365cab1998-08-13 14:20:17 +0000186
Walter Dörwalda0021592005-06-13 21:44:48 +0000187 bits = [digit * SHIFT for digit in digits]
Guido van Rossum4365cab1998-08-13 14:20:17 +0000188
Walter Dörwalda0021592005-06-13 21:44:48 +0000189 # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
190 # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
191 for abits in bits:
192 a = (1L << abits) - 1
193 for bbits in bits:
194 if bbits < abits:
195 continue
196 b = (1L << bbits) - 1
197 x = a * b
198 y = ((1L << (abits + bbits)) -
199 (1L << abits) -
200 (1L << bbits) +
201 1)
202 self.assertEqual(x, y,
203 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 +0000204
Walter Dörwalda0021592005-06-13 21:44:48 +0000205 def check_bitop_identities_1(self, x):
206 eq = self.assertEqual
207 eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))
208 eq(x | 0, x, Frm("x | 0 != x for x=%r", x))
209 eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x))
210 eq(x & -1, x, Frm("x & -1 != x for x=%r", x))
211 eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x))
212 eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x))
213 eq(x, ~~x, Frm("x != ~~x for x=%r", x))
214 eq(x & x, x, Frm("x & x != x for x=%r", x))
215 eq(x | x, x, Frm("x | x != x for x=%r", x))
216 eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x))
217 eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x))
218 eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x))
219 eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
220 eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
221 eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
222 for n in xrange(2*SHIFT):
223 p2 = 2L ** n
224 eq(x << n >> n, x,
Martin Panter2bc50d72015-09-24 00:19:42 +0000225 Frm("x << n >> n != x for x=%r, n=%r", x, n))
Walter Dörwalda0021592005-06-13 21:44:48 +0000226 eq(x // p2, x >> n,
Martin Panter2bc50d72015-09-24 00:19:42 +0000227 Frm("x // p2 != x >> n for x=%r n=%r p2=%r", x, n, p2))
Walter Dörwalda0021592005-06-13 21:44:48 +0000228 eq(x * p2, x << n,
Martin Panter2bc50d72015-09-24 00:19:42 +0000229 Frm("x * p2 != x << n for x=%r n=%r p2=%r", x, n, p2))
Walter Dörwalda0021592005-06-13 21:44:48 +0000230 eq(x & -p2, x >> n << n,
Martin Panter2bc50d72015-09-24 00:19:42 +0000231 Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", x, n, p2))
Walter Dörwalda0021592005-06-13 21:44:48 +0000232 eq(x & -p2, x & ~(p2 - 1),
Martin Panter2bc50d72015-09-24 00:19:42 +0000233 Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", x, n, p2))
Tim Peters7f270ba2002-08-13 21:06:55 +0000234
Walter Dörwalda0021592005-06-13 21:44:48 +0000235 def check_bitop_identities_2(self, x, y):
236 eq = self.assertEqual
Martin Panter2bc50d72015-09-24 00:19:42 +0000237 eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", x, y))
238 eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", x, y))
239 eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", x, y))
240 eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", x, y))
241 eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", x, y))
242 eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000243 eq(x ^ y, (x | y) & ~(x & y),
Martin Panter2bc50d72015-09-24 00:19:42 +0000244 Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000245 eq(x ^ y, (x & ~y) | (~x & y),
Martin Panter2bc50d72015-09-24 00:19:42 +0000246 Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000247 eq(x ^ y, (x | y) & (~x | ~y),
Martin Panter2bc50d72015-09-24 00:19:42 +0000248 Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", x, y))
Tim Peters7f270ba2002-08-13 21:06:55 +0000249
Walter Dörwalda0021592005-06-13 21:44:48 +0000250 def check_bitop_identities_3(self, x, y, z):
251 eq = self.assertEqual
252 eq((x & y) & z, x & (y & z),
Martin Panter2bc50d72015-09-24 00:19:42 +0000253 Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", x, y, z))
Walter Dörwalda0021592005-06-13 21:44:48 +0000254 eq((x | y) | z, x | (y | z),
Martin Panter2bc50d72015-09-24 00:19:42 +0000255 Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", x, y, z))
Walter Dörwalda0021592005-06-13 21:44:48 +0000256 eq((x ^ y) ^ z, x ^ (y ^ z),
Martin Panter2bc50d72015-09-24 00:19:42 +0000257 Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", x, y, z))
Walter Dörwalda0021592005-06-13 21:44:48 +0000258 eq(x & (y | z), (x & y) | (x & z),
Martin Panter2bc50d72015-09-24 00:19:42 +0000259 Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", x, y, z))
Walter Dörwalda0021592005-06-13 21:44:48 +0000260 eq(x | (y & z), (x | y) & (x | z),
Martin Panter2bc50d72015-09-24 00:19:42 +0000261 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 +0000262
Walter Dörwalda0021592005-06-13 21:44:48 +0000263 def test_bitop_identities(self):
264 for x in special:
265 self.check_bitop_identities_1(x)
266 digits = xrange(1, MAXDIGITS+1)
267 for lenx in digits:
268 x = self.getran(lenx)
269 self.check_bitop_identities_1(x)
270 for leny in digits:
271 y = self.getran(leny)
272 self.check_bitop_identities_2(x, y)
273 self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000274
Walter Dörwalda0021592005-06-13 21:44:48 +0000275 def slow_format(self, x, base):
276 if (x, base) == (0, 8):
277 # this is an oddball!
278 return "0L"
279 digits = []
280 sign = 0
281 if x < 0:
282 sign, x = 1, -x
283 while x:
284 x, r = divmod(x, base)
285 digits.append(int(r))
286 digits.reverse()
287 digits = digits or [0]
288 return '-'[:sign] + \
289 {8: '0', 10: '', 16: '0x'}[base] + \
Raymond Hettinger3296e692005-06-29 23:29:56 +0000290 "".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L"
Guido van Rossum4365cab1998-08-13 14:20:17 +0000291
Walter Dörwalda0021592005-06-13 21:44:48 +0000292 def check_format_1(self, x):
293 for base, mapper in (8, oct), (10, repr), (16, hex):
294 got = mapper(x)
295 expected = self.slow_format(x, base)
296 msg = Frm("%s returned %r but expected %r for %r",
297 mapper.__name__, got, expected, x)
298 self.assertEqual(got, expected, msg)
299 self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x))
300 # str() has to be checked a little differently since there's no
301 # trailing "L"
302 got = str(x)
303 expected = self.slow_format(x, 10)[:-1]
304 msg = Frm("%s returned %r but expected %r for %r",
305 mapper.__name__, got, expected, x)
306 self.assertEqual(got, expected, msg)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000307
Walter Dörwalda0021592005-06-13 21:44:48 +0000308 def test_format(self):
309 for x in special:
310 self.check_format_1(x)
311 for i in xrange(10):
312 for lenx in xrange(1, MAXDIGITS+1):
313 x = self.getran(lenx)
314 self.check_format_1(x)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000315
Benjamin Peterson979395b2008-05-03 21:35:18 +0000316 def test_long(self):
317 self.assertEqual(long(314), 314L)
318 self.assertEqual(long(3.14), 3L)
319 self.assertEqual(long(314L), 314L)
Amaury Forgeot d'Arcd3ffb892008-09-09 07:24:30 +0000320 # Check that long() of basic types actually returns a long
321 self.assertEqual(type(long(314)), long)
322 self.assertEqual(type(long(3.14)), long)
323 self.assertEqual(type(long(314L)), long)
Benjamin Peterson979395b2008-05-03 21:35:18 +0000324 # Check that conversion from float truncates towards zero
325 self.assertEqual(long(-3.14), -3L)
326 self.assertEqual(long(3.9), 3L)
327 self.assertEqual(long(-3.9), -3L)
328 self.assertEqual(long(3.5), 3L)
329 self.assertEqual(long(-3.5), -3L)
330 self.assertEqual(long("-3"), -3L)
Mark Dickinson20665592010-05-25 19:01:08 +0000331 self.assertEqual(long("0b10", 2), 2L)
332 self.assertEqual(long("0o10", 8), 8L)
333 self.assertEqual(long("0x10", 16), 16L)
Benjamin Peterson979395b2008-05-03 21:35:18 +0000334 if test_support.have_unicode:
335 self.assertEqual(long(unicode("-3")), -3L)
336 # Different base:
337 self.assertEqual(long("10",16), 16L)
338 if test_support.have_unicode:
339 self.assertEqual(long(unicode("10"),16), 16L)
340 # Check conversions from string (same test set as for int(), and then some)
341 LL = [
342 ('1' + '0'*20, 10L**20),
343 ('1' + '0'*100, 10L**100)
344 ]
345 L2 = L[:]
346 if test_support.have_unicode:
347 L2 += [
348 (unicode('1') + unicode('0')*20, 10L**20),
349 (unicode('1') + unicode('0')*100, 10L**100),
350 ]
351 for s, v in L2 + LL:
352 for sign in "", "+", "-":
353 for prefix in "", " ", "\t", " \t\t ":
354 ss = prefix + sign + s
355 vv = v
356 if sign == "-" and v is not ValueError:
357 vv = -v
358 try:
359 self.assertEqual(long(ss), long(vv))
360 except v:
361 pass
362
363 self.assertRaises(ValueError, long, '123\0')
364 self.assertRaises(ValueError, long, '53', 40)
365 self.assertRaises(TypeError, long, 1, 12)
366
Mark Dickinson784a47f2010-05-26 19:06:33 +0000367 # tests with base 0
368 self.assertEqual(long(' 0123 ', 0), 83)
369 self.assertEqual(long(' 0123 ', 0), 83)
370 self.assertEqual(long('000', 0), 0)
371 self.assertEqual(long('0o123', 0), 83)
372 self.assertEqual(long('0x123', 0), 291)
373 self.assertEqual(long('0b100', 0), 4)
374 self.assertEqual(long(' 0O123 ', 0), 83)
375 self.assertEqual(long(' 0X123 ', 0), 291)
376 self.assertEqual(long(' 0B100 ', 0), 4)
377 self.assertEqual(long('0', 0), 0)
378 self.assertEqual(long('+0', 0), 0)
379 self.assertEqual(long('-0', 0), 0)
380 self.assertEqual(long('00', 0), 0)
381 self.assertRaises(ValueError, long, '08', 0)
382 self.assertRaises(ValueError, long, '-012395', 0)
383
Benjamin Peterson979395b2008-05-03 21:35:18 +0000384 # SF patch #1638879: embedded NULs were not detected with
385 # explicit base
386 self.assertRaises(ValueError, long, '123\0', 10)
387 self.assertRaises(ValueError, long, '123\x00 245', 20)
388
389 self.assertEqual(long('100000000000000000000000000000000', 2),
390 4294967296)
391 self.assertEqual(long('102002022201221111211', 3), 4294967296)
392 self.assertEqual(long('10000000000000000', 4), 4294967296)
393 self.assertEqual(long('32244002423141', 5), 4294967296)
394 self.assertEqual(long('1550104015504', 6), 4294967296)
395 self.assertEqual(long('211301422354', 7), 4294967296)
396 self.assertEqual(long('40000000000', 8), 4294967296)
397 self.assertEqual(long('12068657454', 9), 4294967296)
398 self.assertEqual(long('4294967296', 10), 4294967296)
399 self.assertEqual(long('1904440554', 11), 4294967296)
400 self.assertEqual(long('9ba461594', 12), 4294967296)
401 self.assertEqual(long('535a79889', 13), 4294967296)
402 self.assertEqual(long('2ca5b7464', 14), 4294967296)
403 self.assertEqual(long('1a20dcd81', 15), 4294967296)
404 self.assertEqual(long('100000000', 16), 4294967296)
405 self.assertEqual(long('a7ffda91', 17), 4294967296)
406 self.assertEqual(long('704he7g4', 18), 4294967296)
407 self.assertEqual(long('4f5aff66', 19), 4294967296)
408 self.assertEqual(long('3723ai4g', 20), 4294967296)
409 self.assertEqual(long('281d55i4', 21), 4294967296)
410 self.assertEqual(long('1fj8b184', 22), 4294967296)
411 self.assertEqual(long('1606k7ic', 23), 4294967296)
412 self.assertEqual(long('mb994ag', 24), 4294967296)
413 self.assertEqual(long('hek2mgl', 25), 4294967296)
414 self.assertEqual(long('dnchbnm', 26), 4294967296)
415 self.assertEqual(long('b28jpdm', 27), 4294967296)
416 self.assertEqual(long('8pfgih4', 28), 4294967296)
417 self.assertEqual(long('76beigg', 29), 4294967296)
418 self.assertEqual(long('5qmcpqg', 30), 4294967296)
419 self.assertEqual(long('4q0jto4', 31), 4294967296)
420 self.assertEqual(long('4000000', 32), 4294967296)
421 self.assertEqual(long('3aokq94', 33), 4294967296)
422 self.assertEqual(long('2qhxjli', 34), 4294967296)
423 self.assertEqual(long('2br45qb', 35), 4294967296)
424 self.assertEqual(long('1z141z4', 36), 4294967296)
425
426 self.assertEqual(long('100000000000000000000000000000001', 2),
427 4294967297)
428 self.assertEqual(long('102002022201221111212', 3), 4294967297)
429 self.assertEqual(long('10000000000000001', 4), 4294967297)
430 self.assertEqual(long('32244002423142', 5), 4294967297)
431 self.assertEqual(long('1550104015505', 6), 4294967297)
432 self.assertEqual(long('211301422355', 7), 4294967297)
433 self.assertEqual(long('40000000001', 8), 4294967297)
434 self.assertEqual(long('12068657455', 9), 4294967297)
435 self.assertEqual(long('4294967297', 10), 4294967297)
436 self.assertEqual(long('1904440555', 11), 4294967297)
437 self.assertEqual(long('9ba461595', 12), 4294967297)
438 self.assertEqual(long('535a7988a', 13), 4294967297)
439 self.assertEqual(long('2ca5b7465', 14), 4294967297)
440 self.assertEqual(long('1a20dcd82', 15), 4294967297)
441 self.assertEqual(long('100000001', 16), 4294967297)
442 self.assertEqual(long('a7ffda92', 17), 4294967297)
443 self.assertEqual(long('704he7g5', 18), 4294967297)
444 self.assertEqual(long('4f5aff67', 19), 4294967297)
445 self.assertEqual(long('3723ai4h', 20), 4294967297)
446 self.assertEqual(long('281d55i5', 21), 4294967297)
447 self.assertEqual(long('1fj8b185', 22), 4294967297)
448 self.assertEqual(long('1606k7id', 23), 4294967297)
449 self.assertEqual(long('mb994ah', 24), 4294967297)
450 self.assertEqual(long('hek2mgm', 25), 4294967297)
451 self.assertEqual(long('dnchbnn', 26), 4294967297)
452 self.assertEqual(long('b28jpdn', 27), 4294967297)
453 self.assertEqual(long('8pfgih5', 28), 4294967297)
454 self.assertEqual(long('76beigh', 29), 4294967297)
455 self.assertEqual(long('5qmcpqh', 30), 4294967297)
456 self.assertEqual(long('4q0jto5', 31), 4294967297)
457 self.assertEqual(long('4000001', 32), 4294967297)
458 self.assertEqual(long('3aokq95', 33), 4294967297)
459 self.assertEqual(long('2qhxjlj', 34), 4294967297)
460 self.assertEqual(long('2br45qc', 35), 4294967297)
461 self.assertEqual(long('1z141z5', 36), 4294967297)
462
463
464 def test_conversion(self):
465 # Test __long__()
466 class ClassicMissingMethods:
467 pass
468 self.assertRaises(AttributeError, long, ClassicMissingMethods())
469
470 class MissingMethods(object):
471 pass
472 self.assertRaises(TypeError, long, MissingMethods())
473
474 class Foo0:
475 def __long__(self):
476 return 42L
477
478 class Foo1(object):
479 def __long__(self):
480 return 42L
481
482 class Foo2(long):
483 def __long__(self):
484 return 42L
485
486 class Foo3(long):
487 def __long__(self):
488 return self
489
490 class Foo4(long):
491 def __long__(self):
492 return 42
493
494 class Foo5(long):
495 def __long__(self):
496 return 42.
497
498 self.assertEqual(long(Foo0()), 42L)
499 self.assertEqual(long(Foo1()), 42L)
500 self.assertEqual(long(Foo2()), 42L)
501 self.assertEqual(long(Foo3()), 0)
502 self.assertEqual(long(Foo4()), 42)
503 self.assertRaises(TypeError, long, Foo5())
504
505 class Classic:
506 pass
507 for base in (object, Classic):
508 class LongOverridesTrunc(base):
509 def __long__(self):
510 return 42
511 def __trunc__(self):
512 return -12
513 self.assertEqual(long(LongOverridesTrunc()), 42)
514
515 class JustTrunc(base):
516 def __trunc__(self):
517 return 42
518 self.assertEqual(long(JustTrunc()), 42)
519
520 for trunc_result_base in (object, Classic):
521 class Integral(trunc_result_base):
522 def __int__(self):
523 return 42
524
525 class TruncReturnsNonLong(base):
526 def __trunc__(self):
527 return Integral()
528 self.assertEqual(long(TruncReturnsNonLong()), 42)
529
530 class NonIntegral(trunc_result_base):
531 def __trunc__(self):
532 # Check that we avoid infinite recursion.
533 return NonIntegral()
534
535 class TruncReturnsNonIntegral(base):
536 def __trunc__(self):
537 return NonIntegral()
538 try:
539 long(TruncReturnsNonIntegral())
540 except TypeError as e:
Ezio Melotti2623a372010-11-21 13:34:58 +0000541 self.assertEqual(str(e),
542 "__trunc__ returned non-Integral"
543 " (type NonIntegral)")
Benjamin Peterson979395b2008-05-03 21:35:18 +0000544 else:
545 self.fail("Failed to raise TypeError with %s" %
546 ((base, trunc_result_base),))
547
Serhiy Storchaka8d30ad72015-11-25 15:55:54 +0200548 class TruncReturnsLongSubclass(base):
549 def __long__(self):
550 return OtherLongSubclass(42L)
551 good_int = TruncReturnsLongSubclass()
552 n = long(good_int)
553 self.assertEqual(n, 42L)
554 self.assertIs(type(n), OtherLongSubclass)
555 n = LongSubclass(good_int)
556 self.assertEqual(n, 42L)
557 self.assertIs(type(n), LongSubclass)
558
Walter Dörwalda0021592005-06-13 21:44:48 +0000559 def test_misc(self):
Guido van Rossum4365cab1998-08-13 14:20:17 +0000560
Walter Dörwalda0021592005-06-13 21:44:48 +0000561 # check the extremes in int<->long conversion
562 hugepos = sys.maxint
563 hugeneg = -hugepos - 1
564 hugepos_aslong = long(hugepos)
565 hugeneg_aslong = long(hugeneg)
566 self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint")
567 self.assertEqual(hugeneg, hugeneg_aslong,
568 "long(-sys.maxint-1) != -sys.maxint-1")
Guido van Rossum4365cab1998-08-13 14:20:17 +0000569
Walter Dörwalda0021592005-06-13 21:44:48 +0000570 # long -> int should not fail for hugepos_aslong or hugeneg_aslong
Armin Rigo7ccbca92006-10-04 12:17:45 +0000571 x = int(hugepos_aslong)
Walter Dörwalda0021592005-06-13 21:44:48 +0000572 try:
Armin Rigo7ccbca92006-10-04 12:17:45 +0000573 self.assertEqual(x, hugepos,
Walter Dörwalda0021592005-06-13 21:44:48 +0000574 "converting sys.maxint to long and back to int fails")
575 except OverflowError:
576 self.fail("int(long(sys.maxint)) overflowed!")
Armin Rigo7ccbca92006-10-04 12:17:45 +0000577 if not isinstance(x, int):
Georg Brandldf8a3032010-02-06 23:08:00 +0000578 self.fail("int(long(sys.maxint)) should have returned int")
Armin Rigo7ccbca92006-10-04 12:17:45 +0000579 x = int(hugeneg_aslong)
Walter Dörwalda0021592005-06-13 21:44:48 +0000580 try:
Armin Rigo7ccbca92006-10-04 12:17:45 +0000581 self.assertEqual(x, hugeneg,
Walter Dörwalda0021592005-06-13 21:44:48 +0000582 "converting -sys.maxint-1 to long and back to int fails")
583 except OverflowError:
584 self.fail("int(long(-sys.maxint-1)) overflowed!")
Armin Rigo7ccbca92006-10-04 12:17:45 +0000585 if not isinstance(x, int):
Georg Brandldf8a3032010-02-06 23:08:00 +0000586 self.fail("int(long(-sys.maxint-1)) should have returned int")
Walter Dörwalda0021592005-06-13 21:44:48 +0000587 # but long -> int should overflow for hugepos+1 and hugeneg-1
588 x = hugepos_aslong + 1
589 try:
590 y = int(x)
591 except OverflowError:
592 self.fail("int(long(sys.maxint) + 1) mustn't overflow")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000593 self.assertIsInstance(y, long,
Walter Dörwalda0021592005-06-13 21:44:48 +0000594 "int(long(sys.maxint) + 1) should have returned long")
Guido van Rossum4365cab1998-08-13 14:20:17 +0000595
Walter Dörwalda0021592005-06-13 21:44:48 +0000596 x = hugeneg_aslong - 1
597 try:
598 y = int(x)
599 except OverflowError:
600 self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000601 self.assertIsInstance(y, long,
Walter Dörwalda0021592005-06-13 21:44:48 +0000602 "int(long(-sys.maxint-1) - 1) should have returned long")
Guido van Rossum4365cab1998-08-13 14:20:17 +0000603
Walter Dörwalda0021592005-06-13 21:44:48 +0000604 class long2(long):
605 pass
606 x = long2(1L<<100)
Walter Dörwaldf1715402002-11-19 20:49:15 +0000607 y = int(x)
Serhiy Storchaka708a5ea2014-02-08 14:28:20 +0200608 self.assertIs(type(y), long,
Walter Dörwalda0021592005-06-13 21:44:48 +0000609 "overflowing int conversion must return long not long subtype")
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000610
Armin Rigo7ccbca92006-10-04 12:17:45 +0000611 # long -> Py_ssize_t conversion
612 class X(object):
613 def __getslice__(self, i, j):
614 return i, j
615
Florent Xicluna07627882010-03-21 01:14:24 +0000616 with test_support.check_py3k_warnings():
617 self.assertEqual(X()[-5L:7L], (-5, 7))
618 # use the clamping effect to test the smallest and largest longs
619 # that fit a Py_ssize_t
620 slicemin, slicemax = X()[-2L**100:2L**100]
621 self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
Armin Rigo7ccbca92006-10-04 12:17:45 +0000622
Mark Dickinsoncb61e5d2010-09-26 10:37:12 +0000623 def test_issue9869(self):
624 # Issue 9869: Interpreter crash when initializing an instance
625 # of a long subclass from an object whose __long__ method returns
626 # a plain int.
627 class BadLong(object):
628 def __long__(self):
629 return 1000000
630
631 class MyLong(long):
632 pass
633
634 x = MyLong(BadLong())
635 self.assertIsInstance(x, long)
636 self.assertEqual(x, 1000000)
637
638
Tim Peters26c7fa32001-08-23 22:56:21 +0000639# ----------------------------------- tests of auto int->long conversion
640
Walter Dörwalda0021592005-06-13 21:44:48 +0000641 def test_auto_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000642 special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1]
643 sqrt = int(math.sqrt(sys.maxint))
644 special.extend([sqrt-1, sqrt, sqrt+1])
645 special.extend([-i for i in special])
Tim Peters26c7fa32001-08-23 22:56:21 +0000646
Walter Dörwalda0021592005-06-13 21:44:48 +0000647 def checkit(*args):
648 # Heavy use of nested scopes here!
649 self.assertEqual(got, expected,
650 Frm("for %r expected %r got %r", args, expected, got))
Tim Peters26c7fa32001-08-23 22:56:21 +0000651
Walter Dörwalda0021592005-06-13 21:44:48 +0000652 for x in special:
653 longx = long(x)
Tim Peters26c7fa32001-08-23 22:56:21 +0000654
Walter Dörwalda0021592005-06-13 21:44:48 +0000655 expected = -longx
656 got = -x
657 checkit('-', x)
Tim Peters26c7fa32001-08-23 22:56:21 +0000658
Walter Dörwalda0021592005-06-13 21:44:48 +0000659 for y in special:
660 longy = long(y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000661
Walter Dörwalda0021592005-06-13 21:44:48 +0000662 expected = longx + longy
663 got = x + y
664 checkit(x, '+', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000665
Walter Dörwalda0021592005-06-13 21:44:48 +0000666 expected = longx - longy
667 got = x - y
668 checkit(x, '-', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000669
Walter Dörwalda0021592005-06-13 21:44:48 +0000670 expected = longx * longy
671 got = x * y
672 checkit(x, '*', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000673
Walter Dörwalda0021592005-06-13 21:44:48 +0000674 if y:
Florent Xicluna07627882010-03-21 01:14:24 +0000675 with test_support.check_py3k_warnings():
676 expected = longx / longy
677 got = x / y
Walter Dörwalda0021592005-06-13 21:44:48 +0000678 checkit(x, '/', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000679
Walter Dörwalda0021592005-06-13 21:44:48 +0000680 expected = longx // longy
681 got = x // y
682 checkit(x, '//', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000683
Walter Dörwalda0021592005-06-13 21:44:48 +0000684 expected = divmod(longx, longy)
685 got = divmod(longx, longy)
686 checkit(x, 'divmod', y)
Tim Petersa3653092001-08-23 23:02:57 +0000687
Walter Dörwalda0021592005-06-13 21:44:48 +0000688 if abs(y) < 5 and not (x == 0 and y < 0):
689 expected = longx ** longy
690 got = x ** y
691 checkit(x, '**', y)
Tim Peters26c7fa32001-08-23 22:56:21 +0000692
Walter Dörwalda0021592005-06-13 21:44:48 +0000693 for z in special:
694 if z != 0 :
695 if y >= 0:
696 expected = pow(longx, longy, long(z))
697 got = pow(x, y, z)
698 checkit('pow', x, y, '%', z)
Tim Peters32f453e2001-09-03 08:35:41 +0000699 else:
Walter Dörwalda0021592005-06-13 21:44:48 +0000700 self.assertRaises(TypeError, pow,longx, longy, long(z))
Tim Peters26c7fa32001-08-23 22:56:21 +0000701
Mark Dickinson6736cf82009-04-20 21:13:33 +0000702 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
703 "test requires IEEE 754 doubles")
704 def test_float_conversion(self):
705 import sys
706 DBL_MAX = sys.float_info.max
707 DBL_MAX_EXP = sys.float_info.max_exp
708 DBL_MANT_DIG = sys.float_info.mant_dig
709
710 exact_values = [0L, 1L, 2L,
711 long(2**53-3),
712 long(2**53-2),
713 long(2**53-1),
714 long(2**53),
715 long(2**53+2),
716 long(2**54-4),
717 long(2**54-2),
718 long(2**54),
719 long(2**54+4)]
720 for x in exact_values:
721 self.assertEqual(long(float(x)), x)
722 self.assertEqual(long(float(-x)), -x)
723
724 # test round-half-even
725 for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
726 for p in xrange(15):
727 self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))
728
729 for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
730 (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
731 (13, 12), (14, 16), (15, 16)]:
732 for p in xrange(15):
733 self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))
734
735 # behaviour near extremes of floating-point range
736 long_dbl_max = long(DBL_MAX)
737 top_power = 2**DBL_MAX_EXP
Mark Dickinsona7e734f2009-04-20 21:41:04 +0000738 halfway = (long_dbl_max + top_power)//2
Mark Dickinson6736cf82009-04-20 21:13:33 +0000739 self.assertEqual(float(long_dbl_max), DBL_MAX)
740 self.assertEqual(float(long_dbl_max+1), DBL_MAX)
741 self.assertEqual(float(halfway-1), DBL_MAX)
742 self.assertRaises(OverflowError, float, halfway)
743 self.assertEqual(float(1-halfway), -DBL_MAX)
744 self.assertRaises(OverflowError, float, -halfway)
745 self.assertRaises(OverflowError, float, top_power-1)
746 self.assertRaises(OverflowError, float, top_power)
747 self.assertRaises(OverflowError, float, top_power+1)
748 self.assertRaises(OverflowError, float, 2*top_power-1)
749 self.assertRaises(OverflowError, float, 2*top_power)
750 self.assertRaises(OverflowError, float, top_power*top_power)
751
752 for p in xrange(100):
753 x = long(2**p * (2**53 + 1) + 1)
754 y = long(2**p * (2**53+ 2))
755 self.assertEqual(long(float(x)), y)
756
757 x = long(2**p * (2**53 + 1))
758 y = long(2**p * 2**53)
759 self.assertEqual(long(float(x)), y)
760
Walter Dörwalda0021592005-06-13 21:44:48 +0000761 def test_float_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000762 for x in -2.0, -1.0, 0.0, 1.0, 2.0:
763 self.assertEqual(float(long(x)), x)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000764
Walter Dörwalda0021592005-06-13 21:44:48 +0000765 shuge = '12345' * 120
766 huge = 1L << 30000
767 mhuge = -huge
768 namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
769 for test in ["float(huge)", "float(mhuge)",
770 "complex(huge)", "complex(mhuge)",
771 "complex(huge, 1)", "complex(mhuge, 1)",
772 "complex(1, huge)", "complex(1, mhuge)",
773 "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
774 "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
775 "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
776 "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
777 "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
778 "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
779 "math.sin(huge)", "math.sin(mhuge)",
780 "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000781 "math.floor(huge)", "math.floor(mhuge)"]:
Tim Peters9fffa3e2001-09-04 05:14:19 +0000782
Walter Dörwalda0021592005-06-13 21:44:48 +0000783 self.assertRaises(OverflowError, eval, test, namespace)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000784
Walter Dörwalda0021592005-06-13 21:44:48 +0000785 # XXX Perhaps float(shuge) can raise OverflowError on some box?
786 # The comparison should not.
787 self.assertNotEqual(float(shuge), int(shuge),
788 "float(shuge) should not equal int(shuge)")
Tim Peters83e7ccc2001-09-04 06:37:28 +0000789
Walter Dörwalda0021592005-06-13 21:44:48 +0000790 def test_logs(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000791 LOG10E = math.log10(math.e)
Tim Peters307fa782004-09-23 08:06:40 +0000792
Walter Dörwalda0021592005-06-13 21:44:48 +0000793 for exp in range(10) + [100, 1000, 10000]:
794 value = 10 ** exp
795 log10 = math.log10(value)
796 self.assertAlmostEqual(log10, exp)
Tim Peters78526162001-09-05 00:53:45 +0000797
Walter Dörwalda0021592005-06-13 21:44:48 +0000798 # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
799 # exp/LOG10E
800 expected = exp / LOG10E
801 log = math.log(value)
802 self.assertAlmostEqual(log, expected)
Tim Peters78526162001-09-05 00:53:45 +0000803
Walter Dörwalda0021592005-06-13 21:44:48 +0000804 for bad in -(1L << 10000), -2L, 0L:
805 self.assertRaises(ValueError, math.log, bad)
806 self.assertRaises(ValueError, math.log10, bad)
Tim Peters78526162001-09-05 00:53:45 +0000807
Walter Dörwalda0021592005-06-13 21:44:48 +0000808 def test_mixed_compares(self):
809 eq = self.assertEqual
Tim Peters78526162001-09-05 00:53:45 +0000810
Walter Dörwalda0021592005-06-13 21:44:48 +0000811 # We're mostly concerned with that mixing floats and longs does the
812 # right stuff, even when longs are too large to fit in a float.
813 # The safest way to check the results is to use an entirely different
814 # method, which we do here via a skeletal rational class (which
815 # represents all Python ints, longs and floats exactly).
816 class Rat:
817 def __init__(self, value):
818 if isinstance(value, (int, long)):
819 self.n = value
820 self.d = 1
821 elif isinstance(value, float):
822 # Convert to exact rational equivalent.
823 f, e = math.frexp(abs(value))
824 assert f == 0 or 0.5 <= f < 1.0
825 # |value| = f * 2**e exactly
Tim Peters78526162001-09-05 00:53:45 +0000826
Walter Dörwalda0021592005-06-13 21:44:48 +0000827 # Suck up CHUNK bits at a time; 28 is enough so that we suck
828 # up all bits in 2 iterations for all known binary double-
829 # precision formats, and small enough to fit in an int.
830 CHUNK = 28
831 top = 0
832 # invariant: |value| = (top + f) * 2**e exactly
833 while f:
834 f = math.ldexp(f, CHUNK)
835 digit = int(f)
836 assert digit >> CHUNK == 0
837 top = (top << CHUNK) | digit
838 f -= digit
839 assert 0.0 <= f < 1.0
840 e -= CHUNK
Tim Peters78526162001-09-05 00:53:45 +0000841
Walter Dörwalda0021592005-06-13 21:44:48 +0000842 # Now |value| = top * 2**e exactly.
843 if e >= 0:
844 n = top << e
845 d = 1
846 else:
847 n = top
848 d = 1 << -e
849 if value < 0:
850 n = -n
851 self.n = n
852 self.d = d
853 assert float(n) / float(d) == value
Tim Peters307fa782004-09-23 08:06:40 +0000854 else:
Georg Brandldf8a3032010-02-06 23:08:00 +0000855 raise TypeError("can't deal with %r" % value)
Tim Peters307fa782004-09-23 08:06:40 +0000856
Walter Dörwalda0021592005-06-13 21:44:48 +0000857 def __cmp__(self, other):
858 if not isinstance(other, Rat):
859 other = Rat(other)
860 return cmp(self.n * other.d, self.d * other.n)
Tim Peters307fa782004-09-23 08:06:40 +0000861
Walter Dörwalda0021592005-06-13 21:44:48 +0000862 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
863 # 2**48 is an important boundary in the internals. 2**53 is an
864 # important boundary for IEEE double precision.
865 for t in 2.0**48, 2.0**50, 2.0**53:
866 cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
867 long(t-1), long(t), long(t+1)])
868 cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)])
869 # 1L<<20000 should exceed all double formats. long(1e200) is to
870 # check that we get equality with 1e200 above.
871 t = long(1e200)
872 cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1])
873 cases.extend([-x for x in cases])
874 for x in cases:
875 Rx = Rat(x)
876 for y in cases:
877 Ry = Rat(y)
878 Rcmp = cmp(Rx, Ry)
879 xycmp = cmp(x, y)
880 eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
881 eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
882 eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
883 eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
884 eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
885 eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
886 eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
Tim Peters307fa782004-09-23 08:06:40 +0000887
Christian Heimes8267d1d2008-01-04 00:37:34 +0000888 def test_nan_inf(self):
889 self.assertRaises(OverflowError, long, float('inf'))
Mark Dickinsonb6467572008-08-04 21:30:09 +0000890 self.assertRaises(OverflowError, long, float('-inf'))
891 self.assertRaises(ValueError, long, float('nan'))
Christian Heimes8267d1d2008-01-04 00:37:34 +0000892
Mark Dickinson1a707982008-12-17 16:14:37 +0000893 def test_bit_length(self):
894 tiny = 1e-10
895 for x in xrange(-65000, 65000):
896 x = long(x)
897 k = x.bit_length()
898 # Check equivalence with Python version
899 self.assertEqual(k, len(bin(x).lstrip('-0b')))
900 # Behaviour as specified in the docs
901 if x != 0:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000902 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
Mark Dickinson1a707982008-12-17 16:14:37 +0000903 else:
904 self.assertEqual(k, 0)
905 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
906 if x != 0:
907 # When x is an exact power of 2, numeric errors can
908 # cause floor(log(x)/log(2)) to be one too small; for
909 # small x this can be fixed by adding a small quantity
910 # to the quotient before taking the floor.
911 self.assertEqual(k, 1 + math.floor(
912 math.log(abs(x))/math.log(2) + tiny))
913
914 self.assertEqual((0L).bit_length(), 0)
915 self.assertEqual((1L).bit_length(), 1)
916 self.assertEqual((-1L).bit_length(), 1)
917 self.assertEqual((2L).bit_length(), 2)
918 self.assertEqual((-2L).bit_length(), 2)
919 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
920 a = 2L**i
921 self.assertEqual((a-1).bit_length(), i)
922 self.assertEqual((1-a).bit_length(), i)
923 self.assertEqual((a).bit_length(), i+1)
924 self.assertEqual((-a).bit_length(), i+1)
925 self.assertEqual((a+1).bit_length(), i+1)
926 self.assertEqual((-a-1).bit_length(), i+1)
927
928
Walter Dörwalda0021592005-06-13 21:44:48 +0000929def test_main():
930 test_support.run_unittest(LongTest)
Tim Peters307fa782004-09-23 08:06:40 +0000931
Walter Dörwalda0021592005-06-13 21:44:48 +0000932if __name__ == "__main__":
933 test_main()