blob: 133702ec5f2e17188408522bf07a213addfa1195 [file] [log] [blame]
Walter Dörwalda0021592005-06-13 21:44:48 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003import sys
Walter Dörwalda0021592005-06-13 21:44:48 +00004
5import random
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00006import math
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00007import array
Walter Dörwalda0021592005-06-13 21:44:48 +00008
9# 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
Mark Dickinsoncbb62742009-12-27 15:09:50 +000018# decorator for skipping tests on non-IEEE 754 platforms
19requires_IEEE_754 = unittest.skipUnless(
20 float.__getformat__("double").startswith("IEEE"),
21 "test requires IEEE 754 doubles")
22
Guido van Rossum4365cab1998-08-13 14:20:17 +000023# SHIFT should match the value in longintrepr.h for best testing.
Mark Dickinsonbd792642009-03-18 20:06:12 +000024SHIFT = sys.int_info.bits_per_digit
Guido van Rossum4365cab1998-08-13 14:20:17 +000025BASE = 2 ** SHIFT
26MASK = BASE - 1
Tim Petersdaec9612004-08-30 23:18:23 +000027KARATSUBA_CUTOFF = 70 # from longobject.c
Guido van Rossum4365cab1998-08-13 14:20:17 +000028
29# Max number of base BASE digits to use in test cases. Doubling
Tim Peters28b0e2a2002-08-13 02:17:11 +000030# this will more than double the runtime.
31MAXDIGITS = 15
Guido van Rossum4365cab1998-08-13 14:20:17 +000032
Guido van Rossum4581a0c1998-10-02 01:19:48 +000033# build some special values
Guido van Rossumc1f779c2007-07-03 08:25:58 +000034special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000035# some solid strings of one bits
Guido van Rossume2a383d2007-01-15 16:59:06 +000036p2 = 4 # 0 and 1 already added
Guido van Rossum4581a0c1998-10-02 01:19:48 +000037for i in range(2*SHIFT):
38 special.append(p2 - 1)
39 p2 = p2 << 1
40del p2
41# add complements & negations
Guido van Rossumc1f779c2007-07-03 08:25:58 +000042special += [~x for x in special] + [-x for x in special]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000043
Mark Dickinsoncbb62742009-12-27 15:09:50 +000044DBL_MAX = sys.float_info.max
45DBL_MAX_EXP = sys.float_info.max_exp
46DBL_MIN_EXP = sys.float_info.min_exp
47DBL_MANT_DIG = sys.float_info.mant_dig
48DBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1)
49
50# pure Python version of correctly-rounded true division
51def truediv(a, b):
52 """Correctly-rounded true division for integers."""
53 negative = a^b < 0
54 a, b = abs(a), abs(b)
55
56 # exceptions: division by zero, overflow
57 if not b:
58 raise ZeroDivisionError("division by zero")
59 if a >= DBL_MIN_OVERFLOW * b:
60 raise OverflowError("int/int too large to represent as a float")
61
62 # find integer d satisfying 2**(d - 1) <= a/b < 2**d
63 d = a.bit_length() - b.bit_length()
64 if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
65 d += 1
66
67 # compute 2**-exp * a / b for suitable exp
68 exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
69 a, b = a << max(-exp, 0), b << max(exp, 0)
70 q, r = divmod(a, b)
71
72 # round-half-to-even: fractional part is r/b, which is > 0.5 iff
73 # 2*r > b, and == 0.5 iff 2*r == b.
74 if 2*r > b or 2*r == b and q % 2 == 1:
75 q += 1
76
Mark Dickinsona4e15062009-12-27 19:03:31 +000077 result = math.ldexp(q, exp)
Mark Dickinsoncbb62742009-12-27 15:09:50 +000078 return -result if negative else result
79
80
Walter Dörwalda0021592005-06-13 21:44:48 +000081class LongTest(unittest.TestCase):
Guido van Rossum4365cab1998-08-13 14:20:17 +000082
Walter Dörwalda0021592005-06-13 21:44:48 +000083 # Get quasi-random long consisting of ndigits digits (in base BASE).
84 # quasi == the most-significant digit will not be 0, and the number
85 # is constructed to contain long strings of 0 and 1 bits. These are
86 # more likely than random bits to provoke digit-boundary errors.
87 # The sign of the number is also random.
Guido van Rossum4365cab1998-08-13 14:20:17 +000088
Walter Dörwalda0021592005-06-13 21:44:48 +000089 def getran(self, ndigits):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000090 self.assertTrue(ndigits > 0)
Walter Dörwalda0021592005-06-13 21:44:48 +000091 nbits_hi = ndigits * SHIFT
92 nbits_lo = nbits_hi - SHIFT + 1
Guido van Rossume2a383d2007-01-15 16:59:06 +000093 answer = 0
Walter Dörwalda0021592005-06-13 21:44:48 +000094 nbits = 0
95 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
96 while nbits < nbits_lo:
97 bits = (r >> 1) + 1
98 bits = min(bits, nbits_hi - nbits)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 self.assertTrue(1 <= bits <= SHIFT)
Walter Dörwalda0021592005-06-13 21:44:48 +0000100 nbits = nbits + bits
101 answer = answer << bits
102 if r & 1:
103 answer = answer | ((1 << bits) - 1)
104 r = int(random.random() * (SHIFT * 2))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000105 self.assertTrue(nbits_lo <= nbits <= nbits_hi)
Walter Dörwalda0021592005-06-13 21:44:48 +0000106 if random.random() < 0.5:
107 answer = -answer
108 return answer
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000109
Walter Dörwalda0021592005-06-13 21:44:48 +0000110 # Get random long consisting of ndigits random digits (relative to base
111 # BASE). The sign bit is also random.
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000112
Walter Dörwalda0021592005-06-13 21:44:48 +0000113 def getran2(ndigits):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000114 answer = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000115 for i in range(ndigits):
Walter Dörwalda0021592005-06-13 21:44:48 +0000116 answer = (answer << SHIFT) | random.randint(0, MASK)
117 if random.random() < 0.5:
118 answer = -answer
119 return answer
Guido van Rossum4365cab1998-08-13 14:20:17 +0000120
Walter Dörwalda0021592005-06-13 21:44:48 +0000121 def check_division(self, x, y):
122 eq = self.assertEqual
123 q, r = divmod(x, y)
124 q2, r2 = x//y, x%y
125 pab, pba = x*y, y*x
126 eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
127 eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
128 eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
129 eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
130 if y > 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000131 self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000132 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000133 self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000134
Walter Dörwalda0021592005-06-13 21:44:48 +0000135 def test_division(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000136 digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
137 KARATSUBA_CUTOFF + 14))
Walter Dörwalda0021592005-06-13 21:44:48 +0000138 digits.append(KARATSUBA_CUTOFF * 3)
139 for lenx in digits:
140 x = self.getran(lenx)
141 for leny in digits:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000142 y = self.getran(leny) or 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000143 self.check_division(x, y)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000144
Mark Dickinsonbd792642009-03-18 20:06:12 +0000145 # specific numbers chosen to exercise corner cases of the
146 # current long division implementation
147
148 # 30-bit cases involving a quotient digit estimate of BASE+1
149 self.check_division(1231948412290879395966702881,
150 1147341367131428698)
151 self.check_division(815427756481275430342312021515587883,
152 707270836069027745)
153 self.check_division(627976073697012820849443363563599041,
154 643588798496057020)
155 self.check_division(1115141373653752303710932756325578065,
156 1038556335171453937726882627)
157 # 30-bit cases that require the post-subtraction correction step
158 self.check_division(922498905405436751940989320930368494,
159 949985870686786135626943396)
160 self.check_division(768235853328091167204009652174031844,
161 1091555541180371554426545266)
162
163 # 15-bit cases involving a quotient digit estimate of BASE+1
164 self.check_division(20172188947443, 615611397)
165 self.check_division(1020908530270155025, 950795710)
166 self.check_division(128589565723112408, 736393718)
167 self.check_division(609919780285761575, 18613274546784)
168 # 15-bit cases that require the post-subtraction correction step
169 self.check_division(710031681576388032, 26769404391308)
170 self.check_division(1933622614268221, 30212853348836)
171
172
173
Walter Dörwalda0021592005-06-13 21:44:48 +0000174 def test_karatsuba(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000175 digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
176 KARATSUBA_CUTOFF + 10))
Walter Dörwalda0021592005-06-13 21:44:48 +0000177 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:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000184 a = (1 << abits) - 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000185 for bbits in bits:
186 if bbits < abits:
187 continue
Guido van Rossume2a383d2007-01-15 16:59:06 +0000188 b = (1 << bbits) - 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000189 x = a * b
Guido van Rossume2a383d2007-01-15 16:59:06 +0000190 y = ((1 << (abits + bbits)) -
191 (1 << abits) -
192 (1 << bbits) +
Walter Dörwalda0021592005-06-13 21:44:48 +0000193 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))
Guido van Rossum805365e2007-05-07 22:24:25 +0000214 for n in range(2*SHIFT):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000215 p2 = 2 ** n
Walter Dörwalda0021592005-06-13 21:44:48 +0000216 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)
Guido van Rossum805365e2007-05-07 22:24:25 +0000258 digits = range(1, MAXDIGITS+1)
Walter Dörwalda0021592005-06-13 21:44:48 +0000259 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):
Walter Dörwalda0021592005-06-13 21:44:48 +0000268 digits = []
269 sign = 0
270 if x < 0:
271 sign, x = 1, -x
272 while x:
273 x, r = divmod(x, base)
274 digits.append(int(r))
275 digits.reverse()
276 digits = digits or [0]
277 return '-'[:sign] + \
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000278 {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
Guido van Rossumd2dbecb2006-08-18 16:29:54 +0000279 "".join(map(lambda i: "0123456789abcdef"[i], digits))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000280
Walter Dörwalda0021592005-06-13 21:44:48 +0000281 def check_format_1(self, x):
282 for base, mapper in (8, oct), (10, repr), (16, hex):
283 got = mapper(x)
284 expected = self.slow_format(x, base)
285 msg = Frm("%s returned %r but expected %r for %r",
286 mapper.__name__, got, expected, x)
287 self.assertEqual(got, expected, msg)
Mark Dickinson5c2db372009-12-05 20:28:34 +0000288 self.assertEqual(int(got, 0), x, Frm('int("%s", 0) != %r', got, x))
Walter Dörwalda0021592005-06-13 21:44:48 +0000289 # str() has to be checked a little differently since there's no
290 # trailing "L"
291 got = str(x)
Guido van Rossumd2dbecb2006-08-18 16:29:54 +0000292 expected = self.slow_format(x, 10)
Walter Dörwalda0021592005-06-13 21:44:48 +0000293 msg = Frm("%s returned %r but expected %r for %r",
294 mapper.__name__, got, expected, x)
295 self.assertEqual(got, expected, msg)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000296
Walter Dörwalda0021592005-06-13 21:44:48 +0000297 def test_format(self):
298 for x in special:
299 self.check_format_1(x)
Guido van Rossum805365e2007-05-07 22:24:25 +0000300 for i in range(10):
301 for lenx in range(1, MAXDIGITS+1):
Walter Dörwalda0021592005-06-13 21:44:48 +0000302 x = self.getran(lenx)
303 self.check_format_1(x)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000304
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000305 def test_long(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +0000306 # Check conversions from string
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000307 LL = [
308 ('1' + '0'*20, 10**20),
309 ('1' + '0'*100, 10**100)
310 ]
Mark Dickinson5c2db372009-12-05 20:28:34 +0000311 for s, v in LL:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000312 for sign in "", "+", "-":
313 for prefix in "", " ", "\t", " \t\t ":
314 ss = prefix + sign + s
315 vv = v
316 if sign == "-" and v is not ValueError:
317 vv = -v
318 try:
Mark Dickinson5c2db372009-12-05 20:28:34 +0000319 self.assertEqual(int(ss), vv)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000320 except ValueError:
321 pass
322
Mark Dickinson9ffc0202009-01-20 20:45:53 +0000323 # trailing L should no longer be accepted...
324 self.assertRaises(ValueError, int, '123L')
325 self.assertRaises(ValueError, int, '123l')
326 self.assertRaises(ValueError, int, '0L')
327 self.assertRaises(ValueError, int, '-37L')
328 self.assertRaises(ValueError, int, '0x32L', 16)
329 self.assertRaises(ValueError, int, '1L', 21)
330 # ... but it's just a normal digit if base >= 22
331 self.assertEqual(int('1L', 22), 43)
332
Mark Dickinson56544db2010-05-26 19:14:01 +0000333 # tests with base 0
334 self.assertEqual(int('000', 0), 0)
335 self.assertEqual(int('0o123', 0), 83)
336 self.assertEqual(int('0x123', 0), 291)
337 self.assertEqual(int('0b100', 0), 4)
338 self.assertEqual(int(' 0O123 ', 0), 83)
339 self.assertEqual(int(' 0X123 ', 0), 291)
340 self.assertEqual(int(' 0B100 ', 0), 4)
341 self.assertEqual(int('0', 0), 0)
342 self.assertEqual(int('+0', 0), 0)
343 self.assertEqual(int('-0', 0), 0)
344 self.assertEqual(int('00', 0), 0)
345 self.assertRaises(ValueError, int, '08', 0)
346 self.assertRaises(ValueError, int, '-012395', 0)
347
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +0000348 # invalid bases
349 invalid_bases = [-909,
350 2**31-1, 2**31, -2**31, -2**31-1,
351 2**63-1, 2**63, -2**63, -2**63-1,
352 2**100, -2**100,
353 ]
354 for base in invalid_bases:
355 self.assertRaises(ValueError, int, '42', base)
356
357
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000358 def test_conversion(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000359
Mark Dickinson5c2db372009-12-05 20:28:34 +0000360 class JustLong:
361 # test that __long__ no longer used in 3.x
362 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000363 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000364 self.assertRaises(TypeError, int, JustLong())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000365
Mark Dickinson5c2db372009-12-05 20:28:34 +0000366 class LongTrunc:
367 # __long__ should be ignored in 3.x
368 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000369 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000370 def __trunc__(self):
371 return 1729
372 self.assertEqual(int(LongTrunc()), 1729)
Tim Peters26c7fa32001-08-23 22:56:21 +0000373
Mark Dickinsonc6300392009-04-20 21:38:00 +0000374 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
375 "test requires IEEE 754 doubles")
376 def test_float_conversion(self):
Mark Dickinsonc6300392009-04-20 21:38:00 +0000377
378 exact_values = [0, 1, 2,
379 2**53-3,
380 2**53-2,
381 2**53-1,
382 2**53,
383 2**53+2,
384 2**54-4,
385 2**54-2,
386 2**54,
387 2**54+4]
388 for x in exact_values:
389 self.assertEqual(float(x), x)
390 self.assertEqual(float(-x), -x)
391
392 # test round-half-even
393 for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
394 for p in range(15):
395 self.assertEqual(int(float(2**p*(2**53+x))), 2**p*(2**53+y))
396
397 for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
398 (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
399 (13, 12), (14, 16), (15, 16)]:
400 for p in range(15):
401 self.assertEqual(int(float(2**p*(2**54+x))), 2**p*(2**54+y))
402
403 # behaviour near extremes of floating-point range
404 int_dbl_max = int(DBL_MAX)
405 top_power = 2**DBL_MAX_EXP
406 halfway = (int_dbl_max + top_power)//2
407 self.assertEqual(float(int_dbl_max), DBL_MAX)
408 self.assertEqual(float(int_dbl_max+1), DBL_MAX)
409 self.assertEqual(float(halfway-1), DBL_MAX)
410 self.assertRaises(OverflowError, float, halfway)
411 self.assertEqual(float(1-halfway), -DBL_MAX)
412 self.assertRaises(OverflowError, float, -halfway)
413 self.assertRaises(OverflowError, float, top_power-1)
414 self.assertRaises(OverflowError, float, top_power)
415 self.assertRaises(OverflowError, float, top_power+1)
416 self.assertRaises(OverflowError, float, 2*top_power-1)
417 self.assertRaises(OverflowError, float, 2*top_power)
418 self.assertRaises(OverflowError, float, top_power*top_power)
419
420 for p in range(100):
421 x = 2**p * (2**53 + 1) + 1
422 y = 2**p * (2**53 + 2)
423 self.assertEqual(int(float(x)), y)
424
425 x = 2**p * (2**53 + 1)
426 y = 2**p * 2**53
427 self.assertEqual(int(float(x)), y)
428
Walter Dörwalda0021592005-06-13 21:44:48 +0000429 def test_float_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000430 for x in -2.0, -1.0, 0.0, 1.0, 2.0:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000431 self.assertEqual(float(int(x)), x)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000432
Walter Dörwalda0021592005-06-13 21:44:48 +0000433 shuge = '12345' * 120
Guido van Rossume2a383d2007-01-15 16:59:06 +0000434 huge = 1 << 30000
Walter Dörwalda0021592005-06-13 21:44:48 +0000435 mhuge = -huge
436 namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
437 for test in ["float(huge)", "float(mhuge)",
438 "complex(huge)", "complex(mhuge)",
439 "complex(huge, 1)", "complex(mhuge, 1)",
440 "complex(1, huge)", "complex(1, mhuge)",
441 "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
442 "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
443 "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
444 "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
445 "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
446 "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
447 "math.sin(huge)", "math.sin(mhuge)",
448 "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
Guido van Rossum28bbe422007-08-24 03:46:30 +0000449 # math.floor() of an int returns an int now
450 ##"math.floor(huge)", "math.floor(mhuge)",
451 ]:
Tim Peters9fffa3e2001-09-04 05:14:19 +0000452
Walter Dörwalda0021592005-06-13 21:44:48 +0000453 self.assertRaises(OverflowError, eval, test, namespace)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000454
Mark Dickinson5c2db372009-12-05 20:28:34 +0000455 # XXX Perhaps float(shuge) can raise OverflowError on some box?
456 # The comparison should not.
457 self.assertNotEqual(float(shuge), int(shuge),
458 "float(shuge) should not equal int(shuge)")
Tim Peters83e7ccc2001-09-04 06:37:28 +0000459
Walter Dörwalda0021592005-06-13 21:44:48 +0000460 def test_logs(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000461 LOG10E = math.log10(math.e)
Tim Peters307fa782004-09-23 08:06:40 +0000462
Guido van Rossum805365e2007-05-07 22:24:25 +0000463 for exp in list(range(10)) + [100, 1000, 10000]:
Walter Dörwalda0021592005-06-13 21:44:48 +0000464 value = 10 ** exp
465 log10 = math.log10(value)
466 self.assertAlmostEqual(log10, exp)
Tim Peters78526162001-09-05 00:53:45 +0000467
Walter Dörwalda0021592005-06-13 21:44:48 +0000468 # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
469 # exp/LOG10E
470 expected = exp / LOG10E
471 log = math.log(value)
472 self.assertAlmostEqual(log, expected)
Tim Peters78526162001-09-05 00:53:45 +0000473
Guido van Rossume2a383d2007-01-15 16:59:06 +0000474 for bad in -(1 << 10000), -2, 0:
Walter Dörwalda0021592005-06-13 21:44:48 +0000475 self.assertRaises(ValueError, math.log, bad)
476 self.assertRaises(ValueError, math.log10, bad)
Tim Peters78526162001-09-05 00:53:45 +0000477
Walter Dörwalda0021592005-06-13 21:44:48 +0000478 def test_mixed_compares(self):
479 eq = self.assertEqual
Tim Peters78526162001-09-05 00:53:45 +0000480
Walter Dörwalda0021592005-06-13 21:44:48 +0000481 # We're mostly concerned with that mixing floats and longs does the
482 # right stuff, even when longs are too large to fit in a float.
483 # The safest way to check the results is to use an entirely different
484 # method, which we do here via a skeletal rational class (which
485 # represents all Python ints, longs and floats exactly).
486 class Rat:
487 def __init__(self, value):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000488 if isinstance(value, int):
Walter Dörwalda0021592005-06-13 21:44:48 +0000489 self.n = value
490 self.d = 1
491 elif isinstance(value, float):
492 # Convert to exact rational equivalent.
493 f, e = math.frexp(abs(value))
494 assert f == 0 or 0.5 <= f < 1.0
495 # |value| = f * 2**e exactly
Tim Peters78526162001-09-05 00:53:45 +0000496
Walter Dörwalda0021592005-06-13 21:44:48 +0000497 # Suck up CHUNK bits at a time; 28 is enough so that we suck
498 # up all bits in 2 iterations for all known binary double-
499 # precision formats, and small enough to fit in an int.
500 CHUNK = 28
501 top = 0
502 # invariant: |value| = (top + f) * 2**e exactly
503 while f:
504 f = math.ldexp(f, CHUNK)
505 digit = int(f)
506 assert digit >> CHUNK == 0
507 top = (top << CHUNK) | digit
508 f -= digit
509 assert 0.0 <= f < 1.0
510 e -= CHUNK
Tim Peters78526162001-09-05 00:53:45 +0000511
Walter Dörwalda0021592005-06-13 21:44:48 +0000512 # Now |value| = top * 2**e exactly.
513 if e >= 0:
514 n = top << e
515 d = 1
516 else:
517 n = top
518 d = 1 << -e
519 if value < 0:
520 n = -n
521 self.n = n
522 self.d = d
523 assert float(n) / float(d) == value
Tim Peters307fa782004-09-23 08:06:40 +0000524 else:
Georg Brandl89fad142010-03-14 10:23:39 +0000525 raise TypeError("can't deal with %r" % value)
Tim Peters307fa782004-09-23 08:06:40 +0000526
Benjamin Peterson60192082008-10-16 19:34:46 +0000527 def _cmp__(self, other):
Walter Dörwalda0021592005-06-13 21:44:48 +0000528 if not isinstance(other, Rat):
529 other = Rat(other)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000530 x, y = self.n * other.d, self.d * other.n
531 return (x > y) - (x < y)
Benjamin Peterson60192082008-10-16 19:34:46 +0000532 def __eq__(self, other):
533 return self._cmp__(other) == 0
534 def __ne__(self, other):
535 return self._cmp__(other) != 0
536 def __ge__(self, other):
537 return self._cmp__(other) >= 0
538 def __gt__(self, other):
539 return self._cmp__(other) > 0
540 def __le__(self, other):
541 return self._cmp__(other) <= 0
542 def __lt__(self, other):
543 return self._cmp__(other) < 0
Tim Peters307fa782004-09-23 08:06:40 +0000544
Walter Dörwalda0021592005-06-13 21:44:48 +0000545 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
546 # 2**48 is an important boundary in the internals. 2**53 is an
547 # important boundary for IEEE double precision.
548 for t in 2.0**48, 2.0**50, 2.0**53:
549 cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000550 int(t-1), int(t), int(t+1)])
Christian Heimesa37d4c62007-12-04 23:02:19 +0000551 cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
Mark Dickinson5c2db372009-12-05 20:28:34 +0000552 # 1 << 20000 should exceed all double formats. int(1e200) is to
Walter Dörwalda0021592005-06-13 21:44:48 +0000553 # check that we get equality with 1e200 above.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000554 t = int(1e200)
555 cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
Walter Dörwalda0021592005-06-13 21:44:48 +0000556 cases.extend([-x for x in cases])
557 for x in cases:
558 Rx = Rat(x)
559 for y in cases:
560 Ry = Rat(y)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000561 Rcmp = (Rx > Ry) - (Rx < Ry)
562 xycmp = (x > y) - (x < y)
Walter Dörwalda0021592005-06-13 21:44:48 +0000563 eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
564 eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
565 eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
566 eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
567 eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
568 eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
569 eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
Tim Peters307fa782004-09-23 08:06:40 +0000570
Eric Smith0dd1b632008-02-11 17:55:01 +0000571 def test__format__(self):
Eric Smith8c663262007-08-25 02:26:07 +0000572 self.assertEqual(format(123456789, 'd'), '123456789')
573 self.assertEqual(format(123456789, 'd'), '123456789')
574
Eric Smith185e30c2007-08-30 22:23:08 +0000575 # sign and aligning are interdependent
576 self.assertEqual(format(1, "-"), '1')
577 self.assertEqual(format(-1, "-"), '-1')
578 self.assertEqual(format(1, "-3"), ' 1')
579 self.assertEqual(format(-1, "-3"), ' -1')
580 self.assertEqual(format(1, "+3"), ' +1')
581 self.assertEqual(format(-1, "+3"), ' -1')
582 self.assertEqual(format(1, " 3"), ' 1')
583 self.assertEqual(format(-1, " 3"), ' -1')
584 self.assertEqual(format(1, " "), ' 1')
585 self.assertEqual(format(-1, " "), '-1')
586
Eric Smith8c663262007-08-25 02:26:07 +0000587 # hex
588 self.assertEqual(format(3, "x"), "3")
589 self.assertEqual(format(3, "X"), "3")
590 self.assertEqual(format(1234, "x"), "4d2")
591 self.assertEqual(format(-1234, "x"), "-4d2")
592 self.assertEqual(format(1234, "8x"), " 4d2")
Eric Smith185e30c2007-08-30 22:23:08 +0000593 self.assertEqual(format(-1234, "8x"), " -4d2")
Eric Smith8c663262007-08-25 02:26:07 +0000594 self.assertEqual(format(1234, "x"), "4d2")
595 self.assertEqual(format(-1234, "x"), "-4d2")
596 self.assertEqual(format(-3, "x"), "-3")
597 self.assertEqual(format(-3, "X"), "-3")
598 self.assertEqual(format(int('be', 16), "x"), "be")
599 self.assertEqual(format(int('be', 16), "X"), "BE")
600 self.assertEqual(format(-int('be', 16), "x"), "-be")
601 self.assertEqual(format(-int('be', 16), "X"), "-BE")
602
603 # octal
604 self.assertEqual(format(3, "b"), "11")
605 self.assertEqual(format(-3, "b"), "-11")
606 self.assertEqual(format(1234, "b"), "10011010010")
607 self.assertEqual(format(-1234, "b"), "-10011010010")
608 self.assertEqual(format(1234, "-b"), "10011010010")
609 self.assertEqual(format(-1234, "-b"), "-10011010010")
610 self.assertEqual(format(1234, " b"), " 10011010010")
611 self.assertEqual(format(-1234, " b"), "-10011010010")
612 self.assertEqual(format(1234, "+b"), "+10011010010")
613 self.assertEqual(format(-1234, "+b"), "-10011010010")
614
Eric Smith8c663262007-08-25 02:26:07 +0000615 # make sure these are errors
616 self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed
Eric Smith8c663262007-08-25 02:26:07 +0000617 self.assertRaises(ValueError, format, 3, "+c") # sign not allowed
618 # with 'c'
Eric Smithfa767ef2008-01-28 10:59:27 +0000619
620 # ensure that only int and float type specifiers work
Eric Smith7b69c6c2008-01-27 21:07:59 +0000621 for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
622 [chr(x) for x in range(ord('A'), ord('Z')+1)]):
Eric Smithfa767ef2008-01-28 10:59:27 +0000623 if not format_spec in 'bcdoxXeEfFgGn%':
Eric Smith7b69c6c2008-01-27 21:07:59 +0000624 self.assertRaises(ValueError, format, 0, format_spec)
625 self.assertRaises(ValueError, format, 1, format_spec)
626 self.assertRaises(ValueError, format, -1, format_spec)
627 self.assertRaises(ValueError, format, 2**100, format_spec)
628 self.assertRaises(ValueError, format, -(2**100), format_spec)
629
Eric Smithfa767ef2008-01-28 10:59:27 +0000630 # ensure that float type specifiers work; format converts
631 # the int to a float
Eric Smith5807c412008-05-11 21:00:57 +0000632 for format_spec in 'eEfFgG%':
Eric Smithfa767ef2008-01-28 10:59:27 +0000633 for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
634 self.assertEqual(format(value, format_spec),
635 format(float(value), format_spec))
Eric Smith8c663262007-08-25 02:26:07 +0000636
Christian Heimesa34706f2008-01-04 03:06:10 +0000637 def test_nan_inf(self):
Christian Heimes1aa7b302008-01-04 03:22:53 +0000638 self.assertRaises(OverflowError, int, float('inf'))
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000639 self.assertRaises(OverflowError, int, float('-inf'))
640 self.assertRaises(ValueError, int, float('nan'))
Christian Heimesa34706f2008-01-04 03:06:10 +0000641
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000642 def test_true_division(self):
643 huge = 1 << 40000
644 mhuge = -huge
645 self.assertEqual(huge / huge, 1.0)
646 self.assertEqual(mhuge / mhuge, 1.0)
647 self.assertEqual(huge / mhuge, -1.0)
648 self.assertEqual(mhuge / huge, -1.0)
649 self.assertEqual(1 / huge, 0.0)
650 self.assertEqual(1 / huge, 0.0)
651 self.assertEqual(1 / mhuge, 0.0)
652 self.assertEqual(1 / mhuge, 0.0)
653 self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
654 self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
655 self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
656 self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
657 self.assertEqual(huge / (huge << 1), 0.5)
658 self.assertEqual((1000000 * huge) / huge, 1000000)
659
660 namespace = {'huge': huge, 'mhuge': mhuge}
661
662 for overflow in ["float(huge)", "float(mhuge)",
663 "huge / 1", "huge / 2", "huge / -1", "huge / -2",
664 "mhuge / 100", "mhuge / 200"]:
665 self.assertRaises(OverflowError, eval, overflow, namespace)
666
667 for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
668 "100 / mhuge", "200 / mhuge"]:
669 result = eval(underflow, namespace)
670 self.assertEqual(result, 0.0,
671 "expected underflow to 0 from %r" % underflow)
672
673 for zero in ["huge / 0", "mhuge / 0"]:
674 self.assertRaises(ZeroDivisionError, eval, zero, namespace)
675
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000676 def check_truediv(self, a, b, skip_small=True):
677 """Verify that the result of a/b is correctly rounded, by
678 comparing it with a pure Python implementation of correctly
679 rounded division. b should be nonzero."""
680
681 # skip check for small a and b: in this case, the current
682 # implementation converts the arguments to float directly and
683 # then applies a float division. This can give doubly-rounded
684 # results on x87-using machines (particularly 32-bit Linux).
685 if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
686 return
687
688 try:
689 # use repr so that we can distinguish between -0.0 and 0.0
690 expected = repr(truediv(a, b))
691 except OverflowError:
692 expected = 'overflow'
693 except ZeroDivisionError:
694 expected = 'zerodivision'
695
696 try:
697 got = repr(a / b)
698 except OverflowError:
699 got = 'overflow'
700 except ZeroDivisionError:
701 got = 'zerodivision'
702
Mark Dickinson2cfda802009-12-27 21:34:05 +0000703 self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
704 "expected {}, got {}".format(a, b, expected, got))
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000705
706 @requires_IEEE_754
707 def test_correctly_rounded_true_division(self):
708 # more stringent tests than those above, checking that the
709 # result of true division of ints is always correctly rounded.
710 # This test should probably be considered CPython-specific.
711
712 # Exercise all the code paths not involving Gb-sized ints.
713 # ... divisions involving zero
714 self.check_truediv(123, 0)
715 self.check_truediv(-456, 0)
716 self.check_truediv(0, 3)
717 self.check_truediv(0, -3)
718 self.check_truediv(0, 0)
719 # ... overflow or underflow by large margin
720 self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
721 self.check_truediv(12345, 345678 * 2**(DBL_MANT_DIG - DBL_MIN_EXP))
722 # ... a much larger or smaller than b
723 self.check_truediv(12345*2**100, 98765)
724 self.check_truediv(12345*2**30, 98765*7**81)
725 # ... a / b near a boundary: one of 1, 2**DBL_MANT_DIG, 2**DBL_MIN_EXP,
726 # 2**DBL_MAX_EXP, 2**(DBL_MIN_EXP-DBL_MANT_DIG)
727 bases = (0, DBL_MANT_DIG, DBL_MIN_EXP,
728 DBL_MAX_EXP, DBL_MIN_EXP - DBL_MANT_DIG)
729 for base in bases:
730 for exp in range(base - 15, base + 15):
731 self.check_truediv(75312*2**max(exp, 0), 69187*2**max(-exp, 0))
732 self.check_truediv(69187*2**max(exp, 0), 75312*2**max(-exp, 0))
733
734 # overflow corner case
735 for m in [1, 2, 7, 17, 12345, 7**100,
736 -1, -2, -5, -23, -67891, -41**50]:
737 for n in range(-10, 10):
738 self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
739 self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
740
741 # check detection of inexactness in shifting stage
742 for n in range(250):
743 # (2**DBL_MANT_DIG+1)/(2**DBL_MANT_DIG) lies halfway
744 # between two representable floats, and would usually be
745 # rounded down under round-half-to-even. The tiniest of
746 # additions to the numerator should cause it to be rounded
747 # up instead.
748 self.check_truediv((2**DBL_MANT_DIG + 1)*12345*2**200 + 2**n,
749 2**DBL_MANT_DIG*12345)
750
751 # 1/2731 is one of the smallest division cases that's subject
752 # to double rounding on IEEE 754 machines working internally with
753 # 64-bit precision. On such machines, the next check would fail,
754 # were it not explicitly skipped in check_truediv.
755 self.check_truediv(1, 2731)
756
757 # a particularly bad case for the old algorithm: gives an
758 # error of close to 3.5 ulps.
759 self.check_truediv(295147931372582273023, 295147932265116303360)
760 for i in range(1000):
761 self.check_truediv(10**(i+1), 10**i)
762 self.check_truediv(10**i, 10**(i+1))
763
764 # test round-half-to-even behaviour, normal result
765 for m in [1, 2, 4, 7, 8, 16, 17, 32, 12345, 7**100,
766 -1, -2, -5, -23, -67891, -41**50]:
767 for n in range(-10, 10):
768 self.check_truediv(2**DBL_MANT_DIG*m + n, m)
769
770 # test round-half-to-even, subnormal result
771 for n in range(-20, 20):
772 self.check_truediv(n, 2**1076)
773
774 # largeish random divisions: a/b where |a| <= |b| <=
775 # 2*|a|; |ans| is between 0.5 and 1.0, so error should
776 # always be bounded by 2**-54 with equality possible only
777 # if the least significant bit of q=ans*2**53 is zero.
778 for M in [10**10, 10**100, 10**1000]:
779 for i in range(1000):
780 a = random.randrange(1, M)
781 b = random.randrange(a, 2*a+1)
782 self.check_truediv(a, b)
783 self.check_truediv(-a, b)
784 self.check_truediv(a, -b)
785 self.check_truediv(-a, -b)
786
787 # and some (genuinely) random tests
788 for _ in range(10000):
789 a_bits = random.randrange(1000)
790 b_bits = random.randrange(1, 1000)
791 x = random.randrange(2**a_bits)
792 y = random.randrange(1, 2**b_bits)
793 self.check_truediv(x, y)
794 self.check_truediv(x, -y)
795 self.check_truediv(-x, y)
796 self.check_truediv(-x, -y)
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000797
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000798 def test_small_ints(self):
799 for i in range(-5, 257):
800 self.assertTrue(i is i + 0)
801 self.assertTrue(i is i * 1)
802 self.assertTrue(i is i - 0)
803 self.assertTrue(i is i // 1)
804 self.assertTrue(i is i & -1)
805 self.assertTrue(i is i | 0)
806 self.assertTrue(i is i ^ 0)
807 self.assertTrue(i is ~~i)
808 self.assertTrue(i is i**1)
809 self.assertTrue(i is int(str(i)))
810 self.assertTrue(i is i<<2>>2, str(i))
811 # corner cases
812 i = 1 << 70
813 self.assertTrue(i - i is 0)
814 self.assertTrue(0 * i is 0)
815
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000816 def test_bit_length(self):
817 tiny = 1e-10
818 for x in range(-65000, 65000):
819 k = x.bit_length()
820 # Check equivalence with Python version
821 self.assertEqual(k, len(bin(x).lstrip('-0b')))
822 # Behaviour as specified in the docs
823 if x != 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000824 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000825 else:
826 self.assertEqual(k, 0)
827 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
828 if x != 0:
829 # When x is an exact power of 2, numeric errors can
830 # cause floor(log(x)/log(2)) to be one too small; for
831 # small x this can be fixed by adding a small quantity
832 # to the quotient before taking the floor.
833 self.assertEqual(k, 1 + math.floor(
834 math.log(abs(x))/math.log(2) + tiny))
835
836 self.assertEqual((0).bit_length(), 0)
837 self.assertEqual((1).bit_length(), 1)
838 self.assertEqual((-1).bit_length(), 1)
839 self.assertEqual((2).bit_length(), 2)
840 self.assertEqual((-2).bit_length(), 2)
841 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
842 a = 2**i
843 self.assertEqual((a-1).bit_length(), i)
844 self.assertEqual((1-a).bit_length(), i)
845 self.assertEqual((a).bit_length(), i+1)
846 self.assertEqual((-a).bit_length(), i+1)
847 self.assertEqual((a+1).bit_length(), i+1)
848 self.assertEqual((-a-1).bit_length(), i+1)
849
Mark Dickinson1124e712009-01-28 21:25:58 +0000850 def test_round(self):
851 # check round-half-even algorithm. For round to nearest ten;
852 # rounding map is invariant under adding multiples of 20
853 test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
854 6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
855 15:20, 16:20, 17:20, 18:20, 19:20}
856 for offset in range(-520, 520, 20):
857 for k, v in test_dict.items():
858 got = round(k+offset, -1)
859 expected = v+offset
860 self.assertEqual(got, expected)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000861 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000862
863 # larger second argument
864 self.assertEqual(round(-150, -2), -200)
865 self.assertEqual(round(-149, -2), -100)
866 self.assertEqual(round(-51, -2), -100)
867 self.assertEqual(round(-50, -2), 0)
868 self.assertEqual(round(-49, -2), 0)
869 self.assertEqual(round(-1, -2), 0)
870 self.assertEqual(round(0, -2), 0)
871 self.assertEqual(round(1, -2), 0)
872 self.assertEqual(round(49, -2), 0)
873 self.assertEqual(round(50, -2), 0)
874 self.assertEqual(round(51, -2), 100)
875 self.assertEqual(round(149, -2), 100)
876 self.assertEqual(round(150, -2), 200)
877 self.assertEqual(round(250, -2), 200)
878 self.assertEqual(round(251, -2), 300)
879 self.assertEqual(round(172500, -3), 172000)
880 self.assertEqual(round(173500, -3), 174000)
881 self.assertEqual(round(31415926535, -1), 31415926540)
882 self.assertEqual(round(31415926535, -2), 31415926500)
883 self.assertEqual(round(31415926535, -3), 31415927000)
884 self.assertEqual(round(31415926535, -4), 31415930000)
885 self.assertEqual(round(31415926535, -5), 31415900000)
886 self.assertEqual(round(31415926535, -6), 31416000000)
887 self.assertEqual(round(31415926535, -7), 31420000000)
888 self.assertEqual(round(31415926535, -8), 31400000000)
889 self.assertEqual(round(31415926535, -9), 31000000000)
890 self.assertEqual(round(31415926535, -10), 30000000000)
891 self.assertEqual(round(31415926535, -11), 0)
892 self.assertEqual(round(31415926535, -12), 0)
893 self.assertEqual(round(31415926535, -999), 0)
894
895 # should get correct results even for huge inputs
896 for k in range(10, 100):
897 got = round(10**k + 324678, -3)
898 expect = 10**k + 325000
899 self.assertEqual(got, expect)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000900 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000901
902 # nonnegative second argument: round(x, n) should just return x
903 for n in range(5):
904 for i in range(100):
905 x = random.randrange(-10000, 10000)
906 got = round(x, n)
907 self.assertEqual(got, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000908 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000909 for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
910 self.assertEqual(round(8979323, huge_n), 8979323)
911
912 # omitted second argument
913 for i in range(100):
914 x = random.randrange(-10000, 10000)
915 got = round(x)
916 self.assertEqual(got, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000917 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000918
919 # bad second argument
920 bad_exponents = ('brian', 2.0, 0j, None)
921 for e in bad_exponents:
922 self.assertRaises(TypeError, round, 3, e)
923
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000924 def test_to_bytes(self):
925 def check(tests, byteorder, signed=False):
926 for test, expected in tests.items():
927 try:
928 self.assertEqual(
929 test.to_bytes(len(expected), byteorder, signed=signed),
930 expected)
931 except Exception as err:
932 raise AssertionError(
933 "failed to convert {0} with byteorder={1} and signed={2}"
934 .format(test, byteorder, signed)) from err
935
936 # Convert integers to signed big-endian byte arrays.
937 tests1 = {
938 0: b'\x00',
939 1: b'\x01',
940 -1: b'\xff',
941 -127: b'\x81',
942 -128: b'\x80',
943 -129: b'\xff\x7f',
944 127: b'\x7f',
945 129: b'\x00\x81',
946 -255: b'\xff\x01',
947 -256: b'\xff\x00',
948 255: b'\x00\xff',
949 256: b'\x01\x00',
950 32767: b'\x7f\xff',
951 -32768: b'\xff\x80\x00',
952 65535: b'\x00\xff\xff',
953 -65536: b'\xff\x00\x00',
954 -8388608: b'\x80\x00\x00'
955 }
956 check(tests1, 'big', signed=True)
957
958 # Convert integers to signed little-endian byte arrays.
959 tests2 = {
960 0: b'\x00',
961 1: b'\x01',
962 -1: b'\xff',
963 -127: b'\x81',
964 -128: b'\x80',
965 -129: b'\x7f\xff',
966 127: b'\x7f',
967 129: b'\x81\x00',
968 -255: b'\x01\xff',
969 -256: b'\x00\xff',
970 255: b'\xff\x00',
971 256: b'\x00\x01',
972 32767: b'\xff\x7f',
973 -32768: b'\x00\x80',
974 65535: b'\xff\xff\x00',
975 -65536: b'\x00\x00\xff',
976 -8388608: b'\x00\x00\x80'
977 }
978 check(tests2, 'little', signed=True)
979
980 # Convert integers to unsigned big-endian byte arrays.
981 tests3 = {
982 0: b'\x00',
983 1: b'\x01',
984 127: b'\x7f',
985 128: b'\x80',
986 255: b'\xff',
987 256: b'\x01\x00',
988 32767: b'\x7f\xff',
989 32768: b'\x80\x00',
990 65535: b'\xff\xff',
991 65536: b'\x01\x00\x00'
992 }
993 check(tests3, 'big', signed=False)
994
995 # Convert integers to unsigned little-endian byte arrays.
996 tests4 = {
997 0: b'\x00',
998 1: b'\x01',
999 127: b'\x7f',
1000 128: b'\x80',
1001 255: b'\xff',
1002 256: b'\x00\x01',
1003 32767: b'\xff\x7f',
1004 32768: b'\x00\x80',
1005 65535: b'\xff\xff',
1006 65536: b'\x00\x00\x01'
1007 }
1008 check(tests4, 'little', signed=False)
1009
1010 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
1011 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
1012 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
1013 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
1014 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False),
1015 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
1016 self.assertEqual((0).to_bytes(0, 'big'), b'')
1017 self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
1018 self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
1019 self.assertEqual((-1).to_bytes(5, 'big', signed=True),
1020 b'\xff\xff\xff\xff\xff')
1021 self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1022
1023 def test_from_bytes(self):
1024 def check(tests, byteorder, signed=False):
1025 for test, expected in tests.items():
1026 try:
1027 self.assertEqual(
1028 int.from_bytes(test, byteorder, signed=signed),
1029 expected)
1030 except Exception as err:
1031 raise AssertionError(
1032 "failed to convert {0} with byteorder={1!r} and signed={2}"
1033 .format(test, byteorder, signed)) from err
1034
1035 # Convert signed big-endian byte arrays to integers.
1036 tests1 = {
1037 b'': 0,
1038 b'\x00': 0,
1039 b'\x00\x00': 0,
1040 b'\x01': 1,
1041 b'\x00\x01': 1,
1042 b'\xff': -1,
1043 b'\xff\xff': -1,
1044 b'\x81': -127,
1045 b'\x80': -128,
1046 b'\xff\x7f': -129,
1047 b'\x7f': 127,
1048 b'\x00\x81': 129,
1049 b'\xff\x01': -255,
1050 b'\xff\x00': -256,
1051 b'\x00\xff': 255,
1052 b'\x01\x00': 256,
1053 b'\x7f\xff': 32767,
1054 b'\x80\x00': -32768,
1055 b'\x00\xff\xff': 65535,
1056 b'\xff\x00\x00': -65536,
1057 b'\x80\x00\x00': -8388608
1058 }
1059 check(tests1, 'big', signed=True)
1060
1061 # Convert signed little-endian byte arrays to integers.
1062 tests2 = {
1063 b'': 0,
1064 b'\x00': 0,
1065 b'\x00\x00': 0,
1066 b'\x01': 1,
1067 b'\x00\x01': 256,
1068 b'\xff': -1,
1069 b'\xff\xff': -1,
1070 b'\x81': -127,
1071 b'\x80': -128,
1072 b'\x7f\xff': -129,
1073 b'\x7f': 127,
1074 b'\x81\x00': 129,
1075 b'\x01\xff': -255,
1076 b'\x00\xff': -256,
1077 b'\xff\x00': 255,
1078 b'\x00\x01': 256,
1079 b'\xff\x7f': 32767,
1080 b'\x00\x80': -32768,
1081 b'\xff\xff\x00': 65535,
1082 b'\x00\x00\xff': -65536,
1083 b'\x00\x00\x80': -8388608
1084 }
1085 check(tests2, 'little', signed=True)
1086
1087 # Convert unsigned big-endian byte arrays to integers.
1088 tests3 = {
1089 b'': 0,
1090 b'\x00': 0,
1091 b'\x01': 1,
1092 b'\x7f': 127,
1093 b'\x80': 128,
1094 b'\xff': 255,
1095 b'\x01\x00': 256,
1096 b'\x7f\xff': 32767,
1097 b'\x80\x00': 32768,
1098 b'\xff\xff': 65535,
1099 b'\x01\x00\x00': 65536,
1100 }
1101 check(tests3, 'big', signed=False)
1102
1103 # Convert integers to unsigned little-endian byte arrays.
1104 tests4 = {
1105 b'': 0,
1106 b'\x00': 0,
1107 b'\x01': 1,
1108 b'\x7f': 127,
1109 b'\x80': 128,
1110 b'\xff': 255,
1111 b'\x00\x01': 256,
1112 b'\xff\x7f': 32767,
1113 b'\x00\x80': 32768,
1114 b'\xff\xff': 65535,
1115 b'\x00\x00\x01': 65536,
1116 }
1117 check(tests4, 'little', signed=False)
1118
1119 class myint(int):
1120 pass
1121
1122 self.assertTrue(type(myint.from_bytes(b'\x00', 'big')) is myint)
1123 self.assertEqual(myint.from_bytes(b'\x01', 'big'), 1)
1124 self.assertTrue(
1125 type(myint.from_bytes(b'\x00', 'big', signed=False)) is myint)
1126 self.assertEqual(myint.from_bytes(b'\x01', 'big', signed=False), 1)
1127 self.assertTrue(type(myint.from_bytes(b'\x00', 'little')) is myint)
1128 self.assertEqual(myint.from_bytes(b'\x01', 'little'), 1)
1129 self.assertTrue(type(myint.from_bytes(
1130 b'\x00', 'little', signed=False)) is myint)
1131 self.assertEqual(myint.from_bytes(b'\x01', 'little', signed=False), 1)
1132 self.assertEqual(
1133 int.from_bytes([255, 0, 0], 'big', signed=True), -65536)
1134 self.assertEqual(
1135 int.from_bytes((255, 0, 0), 'big', signed=True), -65536)
1136 self.assertEqual(int.from_bytes(
1137 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1138 self.assertEqual(int.from_bytes(
1139 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1140 self.assertEqual(int.from_bytes(
1141 array.array('B', b'\xff\x00\x00'), 'big', signed=True), -65536)
1142 self.assertEqual(int.from_bytes(
1143 memoryview(b'\xff\x00\x00'), 'big', signed=True), -65536)
1144 self.assertRaises(ValueError, int.from_bytes, [256], 'big')
1145 self.assertRaises(ValueError, int.from_bytes, [0], 'big\x00')
1146 self.assertRaises(ValueError, int.from_bytes, [0], 'little\x00')
1147 self.assertRaises(TypeError, int.from_bytes, "", 'big')
1148 self.assertRaises(TypeError, int.from_bytes, "\x00", 'big')
1149 self.assertRaises(TypeError, int.from_bytes, 0, 'big')
1150 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1151 self.assertRaises(TypeError, myint.from_bytes, "", 'big')
1152 self.assertRaises(TypeError, myint.from_bytes, "\x00", 'big')
1153 self.assertRaises(TypeError, myint.from_bytes, 0, 'big')
1154 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
Mark Dickinson1124e712009-01-28 21:25:58 +00001155
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00001156
Walter Dörwalda0021592005-06-13 21:44:48 +00001157def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001158 support.run_unittest(LongTest)
Tim Peters307fa782004-09-23 08:06:40 +00001159
Walter Dörwalda0021592005-06-13 21:44:48 +00001160if __name__ == "__main__":
1161 test_main()