blob: 04066ec1e79a5f28fea6bb55225bcf1c37a44254 [file] [log] [blame]
Walter Dörwalda0021592005-06-13 21:44:48 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Eric Smith3ab08ca2010-12-04 15:17:38 +00003
Christian Heimes81ee3ef2008-05-04 22:42:01 +00004import sys
Walter Dörwalda0021592005-06-13 21:44:48 +00005
6import random
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00007import math
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00008import array
Walter Dörwalda0021592005-06-13 21:44:48 +00009
10# Used for lazy formatting of failure messages
11class Frm(object):
12 def __init__(self, format, *args):
13 self.format = format
14 self.args = args
15
16 def __str__(self):
17 return self.format % self.args
Guido van Rossum4365cab1998-08-13 14:20:17 +000018
19# SHIFT should match the value in longintrepr.h for best testing.
Mark Dickinsonbd792642009-03-18 20:06:12 +000020SHIFT = sys.int_info.bits_per_digit
Guido van Rossum4365cab1998-08-13 14:20:17 +000021BASE = 2 ** SHIFT
22MASK = BASE - 1
Tim Petersdaec9612004-08-30 23:18:23 +000023KARATSUBA_CUTOFF = 70 # from longobject.c
Guido van Rossum4365cab1998-08-13 14:20:17 +000024
25# Max number of base BASE digits to use in test cases. Doubling
Tim Peters28b0e2a2002-08-13 02:17:11 +000026# this will more than double the runtime.
27MAXDIGITS = 15
Guido van Rossum4365cab1998-08-13 14:20:17 +000028
Guido van Rossum4581a0c1998-10-02 01:19:48 +000029# build some special values
Guido van Rossumc1f779c2007-07-03 08:25:58 +000030special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000031# some solid strings of one bits
Guido van Rossume2a383d2007-01-15 16:59:06 +000032p2 = 4 # 0 and 1 already added
Guido van Rossum4581a0c1998-10-02 01:19:48 +000033for i in range(2*SHIFT):
34 special.append(p2 - 1)
35 p2 = p2 << 1
36del p2
37# add complements & negations
Guido van Rossumc1f779c2007-07-03 08:25:58 +000038special += [~x for x in special] + [-x for x in special]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000039
Mark Dickinsoncbb62742009-12-27 15:09:50 +000040DBL_MAX = sys.float_info.max
41DBL_MAX_EXP = sys.float_info.max_exp
42DBL_MIN_EXP = sys.float_info.min_exp
43DBL_MANT_DIG = sys.float_info.mant_dig
44DBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1)
45
46# pure Python version of correctly-rounded true division
47def truediv(a, b):
48 """Correctly-rounded true division for integers."""
49 negative = a^b < 0
50 a, b = abs(a), abs(b)
51
52 # exceptions: division by zero, overflow
53 if not b:
54 raise ZeroDivisionError("division by zero")
55 if a >= DBL_MIN_OVERFLOW * b:
56 raise OverflowError("int/int too large to represent as a float")
57
58 # find integer d satisfying 2**(d - 1) <= a/b < 2**d
59 d = a.bit_length() - b.bit_length()
60 if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
61 d += 1
62
63 # compute 2**-exp * a / b for suitable exp
64 exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
65 a, b = a << max(-exp, 0), b << max(exp, 0)
66 q, r = divmod(a, b)
67
68 # round-half-to-even: fractional part is r/b, which is > 0.5 iff
69 # 2*r > b, and == 0.5 iff 2*r == b.
70 if 2*r > b or 2*r == b and q % 2 == 1:
71 q += 1
72
Mark Dickinsona4e15062009-12-27 19:03:31 +000073 result = math.ldexp(q, exp)
Mark Dickinsoncbb62742009-12-27 15:09:50 +000074 return -result if negative else result
75
76
Walter Dörwalda0021592005-06-13 21:44:48 +000077class LongTest(unittest.TestCase):
Guido van Rossum4365cab1998-08-13 14:20:17 +000078
Walter Dörwalda0021592005-06-13 21:44:48 +000079 # Get quasi-random long consisting of ndigits digits (in base BASE).
80 # quasi == the most-significant digit will not be 0, and the number
81 # is constructed to contain long strings of 0 and 1 bits. These are
82 # more likely than random bits to provoke digit-boundary errors.
83 # The sign of the number is also random.
Guido van Rossum4365cab1998-08-13 14:20:17 +000084
Walter Dörwalda0021592005-06-13 21:44:48 +000085 def getran(self, ndigits):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000086 self.assertTrue(ndigits > 0)
Walter Dörwalda0021592005-06-13 21:44:48 +000087 nbits_hi = ndigits * SHIFT
88 nbits_lo = nbits_hi - SHIFT + 1
Guido van Rossume2a383d2007-01-15 16:59:06 +000089 answer = 0
Walter Dörwalda0021592005-06-13 21:44:48 +000090 nbits = 0
91 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
92 while nbits < nbits_lo:
93 bits = (r >> 1) + 1
94 bits = min(bits, nbits_hi - nbits)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000095 self.assertTrue(1 <= bits <= SHIFT)
Walter Dörwalda0021592005-06-13 21:44:48 +000096 nbits = nbits + bits
97 answer = answer << bits
98 if r & 1:
99 answer = answer | ((1 << bits) - 1)
100 r = int(random.random() * (SHIFT * 2))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000101 self.assertTrue(nbits_lo <= nbits <= nbits_hi)
Walter Dörwalda0021592005-06-13 21:44:48 +0000102 if random.random() < 0.5:
103 answer = -answer
104 return answer
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000105
Walter Dörwalda0021592005-06-13 21:44:48 +0000106 # Get random long consisting of ndigits random digits (relative to base
107 # BASE). The sign bit is also random.
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000108
Walter Dörwalda0021592005-06-13 21:44:48 +0000109 def getran2(ndigits):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000110 answer = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000111 for i in range(ndigits):
Walter Dörwalda0021592005-06-13 21:44:48 +0000112 answer = (answer << SHIFT) | random.randint(0, MASK)
113 if random.random() < 0.5:
114 answer = -answer
115 return answer
Guido van Rossum4365cab1998-08-13 14:20:17 +0000116
Walter Dörwalda0021592005-06-13 21:44:48 +0000117 def check_division(self, x, y):
118 eq = self.assertEqual
119 q, r = divmod(x, y)
120 q2, r2 = x//y, x%y
121 pab, pba = x*y, y*x
122 eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
123 eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
124 eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
125 eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
126 if y > 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000127 self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
Walter Dörwalda0021592005-06-13 21:44:48 +0000128 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000129 self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000130
Walter Dörwalda0021592005-06-13 21:44:48 +0000131 def test_division(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000132 digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
133 KARATSUBA_CUTOFF + 14))
Walter Dörwalda0021592005-06-13 21:44:48 +0000134 digits.append(KARATSUBA_CUTOFF * 3)
135 for lenx in digits:
136 x = self.getran(lenx)
137 for leny in digits:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000138 y = self.getran(leny) or 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000139 self.check_division(x, y)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000140
Mark Dickinsonbd792642009-03-18 20:06:12 +0000141 # specific numbers chosen to exercise corner cases of the
142 # current long division implementation
143
144 # 30-bit cases involving a quotient digit estimate of BASE+1
145 self.check_division(1231948412290879395966702881,
146 1147341367131428698)
147 self.check_division(815427756481275430342312021515587883,
148 707270836069027745)
149 self.check_division(627976073697012820849443363563599041,
150 643588798496057020)
151 self.check_division(1115141373653752303710932756325578065,
152 1038556335171453937726882627)
153 # 30-bit cases that require the post-subtraction correction step
154 self.check_division(922498905405436751940989320930368494,
155 949985870686786135626943396)
156 self.check_division(768235853328091167204009652174031844,
157 1091555541180371554426545266)
158
159 # 15-bit cases involving a quotient digit estimate of BASE+1
160 self.check_division(20172188947443, 615611397)
161 self.check_division(1020908530270155025, 950795710)
162 self.check_division(128589565723112408, 736393718)
163 self.check_division(609919780285761575, 18613274546784)
164 # 15-bit cases that require the post-subtraction correction step
165 self.check_division(710031681576388032, 26769404391308)
166 self.check_division(1933622614268221, 30212853348836)
167
168
169
Walter Dörwalda0021592005-06-13 21:44:48 +0000170 def test_karatsuba(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000171 digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
172 KARATSUBA_CUTOFF + 10))
Walter Dörwalda0021592005-06-13 21:44:48 +0000173 digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
Guido van Rossum4365cab1998-08-13 14:20:17 +0000174
Walter Dörwalda0021592005-06-13 21:44:48 +0000175 bits = [digit * SHIFT for digit in digits]
Guido van Rossum4365cab1998-08-13 14:20:17 +0000176
Walter Dörwalda0021592005-06-13 21:44:48 +0000177 # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
178 # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
179 for abits in bits:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000180 a = (1 << abits) - 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000181 for bbits in bits:
182 if bbits < abits:
183 continue
Guido van Rossume2a383d2007-01-15 16:59:06 +0000184 b = (1 << bbits) - 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000185 x = a * b
Guido van Rossume2a383d2007-01-15 16:59:06 +0000186 y = ((1 << (abits + bbits)) -
187 (1 << abits) -
188 (1 << bbits) +
Walter Dörwalda0021592005-06-13 21:44:48 +0000189 1)
190 self.assertEqual(x, y,
191 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 +0000192
Walter Dörwalda0021592005-06-13 21:44:48 +0000193 def check_bitop_identities_1(self, x):
194 eq = self.assertEqual
195 eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))
196 eq(x | 0, x, Frm("x | 0 != x for x=%r", x))
197 eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x))
198 eq(x & -1, x, Frm("x & -1 != x for x=%r", x))
199 eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x))
200 eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x))
201 eq(x, ~~x, Frm("x != ~~x for x=%r", x))
202 eq(x & x, x, Frm("x & x != x for x=%r", x))
203 eq(x | x, x, Frm("x | x != x for x=%r", x))
204 eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x))
205 eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x))
206 eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x))
207 eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
208 eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
209 eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
Guido van Rossum805365e2007-05-07 22:24:25 +0000210 for n in range(2*SHIFT):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000211 p2 = 2 ** n
Walter Dörwalda0021592005-06-13 21:44:48 +0000212 eq(x << n >> n, x,
213 Frm("x << n >> n != x for x=%r, n=%r", (x, n)))
214 eq(x // p2, x >> n,
215 Frm("x // p2 != x >> n for x=%r n=%r p2=%r", (x, n, p2)))
216 eq(x * p2, x << n,
217 Frm("x * p2 != x << n for x=%r n=%r p2=%r", (x, n, p2)))
218 eq(x & -p2, x >> n << n,
219 Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", (x, n, p2)))
220 eq(x & -p2, x & ~(p2 - 1),
221 Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", (x, n, p2)))
Tim Peters7f270ba2002-08-13 21:06:55 +0000222
Walter Dörwalda0021592005-06-13 21:44:48 +0000223 def check_bitop_identities_2(self, x, y):
224 eq = self.assertEqual
225 eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", (x, y)))
226 eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", (x, y)))
227 eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", (x, y)))
228 eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", (x, y)))
229 eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", (x, y)))
230 eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", (x, y)))
231 eq(x ^ y, (x | y) & ~(x & y),
232 Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", (x, y)))
233 eq(x ^ y, (x & ~y) | (~x & y),
234 Frm("x ^ y == (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)))
Tim Peters7f270ba2002-08-13 21:06:55 +0000237
Walter Dörwalda0021592005-06-13 21:44:48 +0000238 def check_bitop_identities_3(self, x, y, z):
239 eq = self.assertEqual
240 eq((x & y) & z, x & (y & z),
241 Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", (x, y, z)))
242 eq((x | y) | z, x | (y | z),
243 Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", (x, y, z)))
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) | (x & z),
247 Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", (x, y, z)))
248 eq(x | (y & z), (x | y) & (x | z),
249 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 +0000250
Walter Dörwalda0021592005-06-13 21:44:48 +0000251 def test_bitop_identities(self):
252 for x in special:
253 self.check_bitop_identities_1(x)
Guido van Rossum805365e2007-05-07 22:24:25 +0000254 digits = range(1, MAXDIGITS+1)
Walter Dörwalda0021592005-06-13 21:44:48 +0000255 for lenx in digits:
256 x = self.getran(lenx)
257 self.check_bitop_identities_1(x)
258 for leny in digits:
259 y = self.getran(leny)
260 self.check_bitop_identities_2(x, y)
261 self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000262
Walter Dörwalda0021592005-06-13 21:44:48 +0000263 def slow_format(self, x, base):
Walter Dörwalda0021592005-06-13 21:44:48 +0000264 digits = []
265 sign = 0
266 if x < 0:
267 sign, x = 1, -x
268 while x:
269 x, r = divmod(x, base)
270 digits.append(int(r))
271 digits.reverse()
272 digits = digits or [0]
273 return '-'[:sign] + \
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000274 {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
Georg Brandlcbd2ab12010-12-04 10:39:14 +0000275 "".join("0123456789abcdef"[i] for i in digits)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000276
Walter Dörwalda0021592005-06-13 21:44:48 +0000277 def check_format_1(self, x):
278 for base, mapper in (8, oct), (10, repr), (16, hex):
279 got = mapper(x)
280 expected = self.slow_format(x, base)
281 msg = Frm("%s returned %r but expected %r for %r",
282 mapper.__name__, got, expected, x)
283 self.assertEqual(got, expected, msg)
Mark Dickinson5c2db372009-12-05 20:28:34 +0000284 self.assertEqual(int(got, 0), x, Frm('int("%s", 0) != %r', got, x))
Walter Dörwalda0021592005-06-13 21:44:48 +0000285 # str() has to be checked a little differently since there's no
286 # trailing "L"
287 got = str(x)
Guido van Rossumd2dbecb2006-08-18 16:29:54 +0000288 expected = self.slow_format(x, 10)
Walter Dörwalda0021592005-06-13 21:44:48 +0000289 msg = Frm("%s returned %r but expected %r for %r",
290 mapper.__name__, got, expected, x)
291 self.assertEqual(got, expected, msg)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000292
Walter Dörwalda0021592005-06-13 21:44:48 +0000293 def test_format(self):
294 for x in special:
295 self.check_format_1(x)
Guido van Rossum805365e2007-05-07 22:24:25 +0000296 for i in range(10):
297 for lenx in range(1, MAXDIGITS+1):
Walter Dörwalda0021592005-06-13 21:44:48 +0000298 x = self.getran(lenx)
299 self.check_format_1(x)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000300
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000301 def test_long(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +0000302 # Check conversions from string
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000303 LL = [
304 ('1' + '0'*20, 10**20),
305 ('1' + '0'*100, 10**100)
306 ]
Mark Dickinson5c2db372009-12-05 20:28:34 +0000307 for s, v in LL:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000308 for sign in "", "+", "-":
309 for prefix in "", " ", "\t", " \t\t ":
310 ss = prefix + sign + s
311 vv = v
312 if sign == "-" and v is not ValueError:
313 vv = -v
314 try:
Mark Dickinson5c2db372009-12-05 20:28:34 +0000315 self.assertEqual(int(ss), vv)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000316 except ValueError:
317 pass
318
Mark Dickinson9ffc0202009-01-20 20:45:53 +0000319 # trailing L should no longer be accepted...
320 self.assertRaises(ValueError, int, '123L')
321 self.assertRaises(ValueError, int, '123l')
322 self.assertRaises(ValueError, int, '0L')
323 self.assertRaises(ValueError, int, '-37L')
324 self.assertRaises(ValueError, int, '0x32L', 16)
325 self.assertRaises(ValueError, int, '1L', 21)
326 # ... but it's just a normal digit if base >= 22
327 self.assertEqual(int('1L', 22), 43)
328
Mark Dickinson56544db2010-05-26 19:14:01 +0000329 # tests with base 0
330 self.assertEqual(int('000', 0), 0)
331 self.assertEqual(int('0o123', 0), 83)
332 self.assertEqual(int('0x123', 0), 291)
333 self.assertEqual(int('0b100', 0), 4)
334 self.assertEqual(int(' 0O123 ', 0), 83)
335 self.assertEqual(int(' 0X123 ', 0), 291)
336 self.assertEqual(int(' 0B100 ', 0), 4)
337 self.assertEqual(int('0', 0), 0)
338 self.assertEqual(int('+0', 0), 0)
339 self.assertEqual(int('-0', 0), 0)
340 self.assertEqual(int('00', 0), 0)
341 self.assertRaises(ValueError, int, '08', 0)
342 self.assertRaises(ValueError, int, '-012395', 0)
343
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +0000344 # invalid bases
345 invalid_bases = [-909,
346 2**31-1, 2**31, -2**31, -2**31-1,
347 2**63-1, 2**63, -2**63, -2**63-1,
348 2**100, -2**100,
349 ]
350 for base in invalid_bases:
351 self.assertRaises(ValueError, int, '42', base)
352
353
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000354 def test_conversion(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000355
Mark Dickinson5c2db372009-12-05 20:28:34 +0000356 class JustLong:
357 # test that __long__ no longer used in 3.x
358 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000359 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000360 self.assertRaises(TypeError, int, JustLong())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000361
Mark Dickinson5c2db372009-12-05 20:28:34 +0000362 class LongTrunc:
363 # __long__ should be ignored in 3.x
364 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000365 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000366 def __trunc__(self):
367 return 1729
368 self.assertEqual(int(LongTrunc()), 1729)
Tim Peters26c7fa32001-08-23 22:56:21 +0000369
Eric Smith3ab08ca2010-12-04 15:17:38 +0000370 @support.requires_IEEE_754
Mark Dickinsonc6300392009-04-20 21:38:00 +0000371 def test_float_conversion(self):
Mark Dickinsonc6300392009-04-20 21:38:00 +0000372
373 exact_values = [0, 1, 2,
374 2**53-3,
375 2**53-2,
376 2**53-1,
377 2**53,
378 2**53+2,
379 2**54-4,
380 2**54-2,
381 2**54,
382 2**54+4]
383 for x in exact_values:
384 self.assertEqual(float(x), x)
385 self.assertEqual(float(-x), -x)
386
387 # test round-half-even
388 for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
389 for p in range(15):
390 self.assertEqual(int(float(2**p*(2**53+x))), 2**p*(2**53+y))
391
392 for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
393 (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
394 (13, 12), (14, 16), (15, 16)]:
395 for p in range(15):
396 self.assertEqual(int(float(2**p*(2**54+x))), 2**p*(2**54+y))
397
398 # behaviour near extremes of floating-point range
399 int_dbl_max = int(DBL_MAX)
400 top_power = 2**DBL_MAX_EXP
401 halfway = (int_dbl_max + top_power)//2
402 self.assertEqual(float(int_dbl_max), DBL_MAX)
403 self.assertEqual(float(int_dbl_max+1), DBL_MAX)
404 self.assertEqual(float(halfway-1), DBL_MAX)
405 self.assertRaises(OverflowError, float, halfway)
406 self.assertEqual(float(1-halfway), -DBL_MAX)
407 self.assertRaises(OverflowError, float, -halfway)
408 self.assertRaises(OverflowError, float, top_power-1)
409 self.assertRaises(OverflowError, float, top_power)
410 self.assertRaises(OverflowError, float, top_power+1)
411 self.assertRaises(OverflowError, float, 2*top_power-1)
412 self.assertRaises(OverflowError, float, 2*top_power)
413 self.assertRaises(OverflowError, float, top_power*top_power)
414
415 for p in range(100):
416 x = 2**p * (2**53 + 1) + 1
417 y = 2**p * (2**53 + 2)
418 self.assertEqual(int(float(x)), y)
419
420 x = 2**p * (2**53 + 1)
421 y = 2**p * 2**53
422 self.assertEqual(int(float(x)), y)
423
Walter Dörwalda0021592005-06-13 21:44:48 +0000424 def test_float_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000425 for x in -2.0, -1.0, 0.0, 1.0, 2.0:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000426 self.assertEqual(float(int(x)), x)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000427
Walter Dörwalda0021592005-06-13 21:44:48 +0000428 shuge = '12345' * 120
Guido van Rossume2a383d2007-01-15 16:59:06 +0000429 huge = 1 << 30000
Walter Dörwalda0021592005-06-13 21:44:48 +0000430 mhuge = -huge
431 namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
432 for test in ["float(huge)", "float(mhuge)",
433 "complex(huge)", "complex(mhuge)",
434 "complex(huge, 1)", "complex(mhuge, 1)",
435 "complex(1, huge)", "complex(1, mhuge)",
436 "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
437 "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
438 "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
439 "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
440 "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
441 "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
442 "math.sin(huge)", "math.sin(mhuge)",
443 "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
Guido van Rossum28bbe422007-08-24 03:46:30 +0000444 # math.floor() of an int returns an int now
445 ##"math.floor(huge)", "math.floor(mhuge)",
446 ]:
Tim Peters9fffa3e2001-09-04 05:14:19 +0000447
Walter Dörwalda0021592005-06-13 21:44:48 +0000448 self.assertRaises(OverflowError, eval, test, namespace)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000449
Mark Dickinson5c2db372009-12-05 20:28:34 +0000450 # XXX Perhaps float(shuge) can raise OverflowError on some box?
451 # The comparison should not.
452 self.assertNotEqual(float(shuge), int(shuge),
453 "float(shuge) should not equal int(shuge)")
Tim Peters83e7ccc2001-09-04 06:37:28 +0000454
Walter Dörwalda0021592005-06-13 21:44:48 +0000455 def test_logs(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000456 LOG10E = math.log10(math.e)
Tim Peters307fa782004-09-23 08:06:40 +0000457
Guido van Rossum805365e2007-05-07 22:24:25 +0000458 for exp in list(range(10)) + [100, 1000, 10000]:
Walter Dörwalda0021592005-06-13 21:44:48 +0000459 value = 10 ** exp
460 log10 = math.log10(value)
461 self.assertAlmostEqual(log10, exp)
Tim Peters78526162001-09-05 00:53:45 +0000462
Walter Dörwalda0021592005-06-13 21:44:48 +0000463 # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
464 # exp/LOG10E
465 expected = exp / LOG10E
466 log = math.log(value)
467 self.assertAlmostEqual(log, expected)
Tim Peters78526162001-09-05 00:53:45 +0000468
Guido van Rossume2a383d2007-01-15 16:59:06 +0000469 for bad in -(1 << 10000), -2, 0:
Walter Dörwalda0021592005-06-13 21:44:48 +0000470 self.assertRaises(ValueError, math.log, bad)
471 self.assertRaises(ValueError, math.log10, bad)
Tim Peters78526162001-09-05 00:53:45 +0000472
Walter Dörwalda0021592005-06-13 21:44:48 +0000473 def test_mixed_compares(self):
474 eq = self.assertEqual
Tim Peters78526162001-09-05 00:53:45 +0000475
Walter Dörwalda0021592005-06-13 21:44:48 +0000476 # We're mostly concerned with that mixing floats and longs does the
477 # right stuff, even when longs are too large to fit in a float.
478 # The safest way to check the results is to use an entirely different
479 # method, which we do here via a skeletal rational class (which
480 # represents all Python ints, longs and floats exactly).
481 class Rat:
482 def __init__(self, value):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000483 if isinstance(value, int):
Walter Dörwalda0021592005-06-13 21:44:48 +0000484 self.n = value
485 self.d = 1
486 elif isinstance(value, float):
487 # Convert to exact rational equivalent.
488 f, e = math.frexp(abs(value))
489 assert f == 0 or 0.5 <= f < 1.0
490 # |value| = f * 2**e exactly
Tim Peters78526162001-09-05 00:53:45 +0000491
Walter Dörwalda0021592005-06-13 21:44:48 +0000492 # Suck up CHUNK bits at a time; 28 is enough so that we suck
493 # up all bits in 2 iterations for all known binary double-
494 # precision formats, and small enough to fit in an int.
495 CHUNK = 28
496 top = 0
497 # invariant: |value| = (top + f) * 2**e exactly
498 while f:
499 f = math.ldexp(f, CHUNK)
500 digit = int(f)
501 assert digit >> CHUNK == 0
502 top = (top << CHUNK) | digit
503 f -= digit
504 assert 0.0 <= f < 1.0
505 e -= CHUNK
Tim Peters78526162001-09-05 00:53:45 +0000506
Walter Dörwalda0021592005-06-13 21:44:48 +0000507 # Now |value| = top * 2**e exactly.
508 if e >= 0:
509 n = top << e
510 d = 1
511 else:
512 n = top
513 d = 1 << -e
514 if value < 0:
515 n = -n
516 self.n = n
517 self.d = d
518 assert float(n) / float(d) == value
Tim Peters307fa782004-09-23 08:06:40 +0000519 else:
Georg Brandl89fad142010-03-14 10:23:39 +0000520 raise TypeError("can't deal with %r" % value)
Tim Peters307fa782004-09-23 08:06:40 +0000521
Benjamin Peterson60192082008-10-16 19:34:46 +0000522 def _cmp__(self, other):
Walter Dörwalda0021592005-06-13 21:44:48 +0000523 if not isinstance(other, Rat):
524 other = Rat(other)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000525 x, y = self.n * other.d, self.d * other.n
526 return (x > y) - (x < y)
Benjamin Peterson60192082008-10-16 19:34:46 +0000527 def __eq__(self, other):
528 return self._cmp__(other) == 0
529 def __ne__(self, other):
530 return self._cmp__(other) != 0
531 def __ge__(self, other):
532 return self._cmp__(other) >= 0
533 def __gt__(self, other):
534 return self._cmp__(other) > 0
535 def __le__(self, other):
536 return self._cmp__(other) <= 0
537 def __lt__(self, other):
538 return self._cmp__(other) < 0
Tim Peters307fa782004-09-23 08:06:40 +0000539
Walter Dörwalda0021592005-06-13 21:44:48 +0000540 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
541 # 2**48 is an important boundary in the internals. 2**53 is an
542 # important boundary for IEEE double precision.
543 for t in 2.0**48, 2.0**50, 2.0**53:
544 cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000545 int(t-1), int(t), int(t+1)])
Christian Heimesa37d4c62007-12-04 23:02:19 +0000546 cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
Mark Dickinson5c2db372009-12-05 20:28:34 +0000547 # 1 << 20000 should exceed all double formats. int(1e200) is to
Walter Dörwalda0021592005-06-13 21:44:48 +0000548 # check that we get equality with 1e200 above.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000549 t = int(1e200)
550 cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
Walter Dörwalda0021592005-06-13 21:44:48 +0000551 cases.extend([-x for x in cases])
552 for x in cases:
553 Rx = Rat(x)
554 for y in cases:
555 Ry = Rat(y)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000556 Rcmp = (Rx > Ry) - (Rx < Ry)
557 xycmp = (x > y) - (x < y)
Walter Dörwalda0021592005-06-13 21:44:48 +0000558 eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
559 eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
560 eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
561 eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
562 eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
563 eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
564 eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
Tim Peters307fa782004-09-23 08:06:40 +0000565
Eric Smith0dd1b632008-02-11 17:55:01 +0000566 def test__format__(self):
Eric Smith8c663262007-08-25 02:26:07 +0000567 self.assertEqual(format(123456789, 'd'), '123456789')
568 self.assertEqual(format(123456789, 'd'), '123456789')
569
Eric Smith185e30c2007-08-30 22:23:08 +0000570 # sign and aligning are interdependent
571 self.assertEqual(format(1, "-"), '1')
572 self.assertEqual(format(-1, "-"), '-1')
573 self.assertEqual(format(1, "-3"), ' 1')
574 self.assertEqual(format(-1, "-3"), ' -1')
575 self.assertEqual(format(1, "+3"), ' +1')
576 self.assertEqual(format(-1, "+3"), ' -1')
577 self.assertEqual(format(1, " 3"), ' 1')
578 self.assertEqual(format(-1, " 3"), ' -1')
579 self.assertEqual(format(1, " "), ' 1')
580 self.assertEqual(format(-1, " "), '-1')
581
Eric Smith8c663262007-08-25 02:26:07 +0000582 # hex
583 self.assertEqual(format(3, "x"), "3")
584 self.assertEqual(format(3, "X"), "3")
585 self.assertEqual(format(1234, "x"), "4d2")
586 self.assertEqual(format(-1234, "x"), "-4d2")
587 self.assertEqual(format(1234, "8x"), " 4d2")
Eric Smith185e30c2007-08-30 22:23:08 +0000588 self.assertEqual(format(-1234, "8x"), " -4d2")
Eric Smith8c663262007-08-25 02:26:07 +0000589 self.assertEqual(format(1234, "x"), "4d2")
590 self.assertEqual(format(-1234, "x"), "-4d2")
591 self.assertEqual(format(-3, "x"), "-3")
592 self.assertEqual(format(-3, "X"), "-3")
593 self.assertEqual(format(int('be', 16), "x"), "be")
594 self.assertEqual(format(int('be', 16), "X"), "BE")
595 self.assertEqual(format(-int('be', 16), "x"), "-be")
596 self.assertEqual(format(-int('be', 16), "X"), "-BE")
597
598 # octal
599 self.assertEqual(format(3, "b"), "11")
600 self.assertEqual(format(-3, "b"), "-11")
601 self.assertEqual(format(1234, "b"), "10011010010")
602 self.assertEqual(format(-1234, "b"), "-10011010010")
603 self.assertEqual(format(1234, "-b"), "10011010010")
604 self.assertEqual(format(-1234, "-b"), "-10011010010")
605 self.assertEqual(format(1234, " b"), " 10011010010")
606 self.assertEqual(format(-1234, " b"), "-10011010010")
607 self.assertEqual(format(1234, "+b"), "+10011010010")
608 self.assertEqual(format(-1234, "+b"), "-10011010010")
609
Eric Smith8c663262007-08-25 02:26:07 +0000610 # make sure these are errors
611 self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed
Eric Smith8c663262007-08-25 02:26:07 +0000612 self.assertRaises(ValueError, format, 3, "+c") # sign not allowed
613 # with 'c'
Eric Smithfa767ef2008-01-28 10:59:27 +0000614
615 # ensure that only int and float type specifiers work
Eric Smith7b69c6c2008-01-27 21:07:59 +0000616 for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
617 [chr(x) for x in range(ord('A'), ord('Z')+1)]):
Eric Smithfa767ef2008-01-28 10:59:27 +0000618 if not format_spec in 'bcdoxXeEfFgGn%':
Eric Smith7b69c6c2008-01-27 21:07:59 +0000619 self.assertRaises(ValueError, format, 0, format_spec)
620 self.assertRaises(ValueError, format, 1, format_spec)
621 self.assertRaises(ValueError, format, -1, format_spec)
622 self.assertRaises(ValueError, format, 2**100, format_spec)
623 self.assertRaises(ValueError, format, -(2**100), format_spec)
624
Eric Smithfa767ef2008-01-28 10:59:27 +0000625 # ensure that float type specifiers work; format converts
626 # the int to a float
Eric Smith5807c412008-05-11 21:00:57 +0000627 for format_spec in 'eEfFgG%':
Eric Smithfa767ef2008-01-28 10:59:27 +0000628 for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
629 self.assertEqual(format(value, format_spec),
630 format(float(value), format_spec))
Eric Smith8c663262007-08-25 02:26:07 +0000631
Christian Heimesa34706f2008-01-04 03:06:10 +0000632 def test_nan_inf(self):
Christian Heimes1aa7b302008-01-04 03:22:53 +0000633 self.assertRaises(OverflowError, int, float('inf'))
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000634 self.assertRaises(OverflowError, int, float('-inf'))
635 self.assertRaises(ValueError, int, float('nan'))
Christian Heimesa34706f2008-01-04 03:06:10 +0000636
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000637 def test_true_division(self):
638 huge = 1 << 40000
639 mhuge = -huge
640 self.assertEqual(huge / huge, 1.0)
641 self.assertEqual(mhuge / mhuge, 1.0)
642 self.assertEqual(huge / mhuge, -1.0)
643 self.assertEqual(mhuge / huge, -1.0)
644 self.assertEqual(1 / huge, 0.0)
645 self.assertEqual(1 / huge, 0.0)
646 self.assertEqual(1 / mhuge, 0.0)
647 self.assertEqual(1 / mhuge, 0.0)
648 self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
649 self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
650 self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
651 self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
652 self.assertEqual(huge / (huge << 1), 0.5)
653 self.assertEqual((1000000 * huge) / huge, 1000000)
654
655 namespace = {'huge': huge, 'mhuge': mhuge}
656
657 for overflow in ["float(huge)", "float(mhuge)",
658 "huge / 1", "huge / 2", "huge / -1", "huge / -2",
659 "mhuge / 100", "mhuge / 200"]:
660 self.assertRaises(OverflowError, eval, overflow, namespace)
661
662 for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
663 "100 / mhuge", "200 / mhuge"]:
664 result = eval(underflow, namespace)
665 self.assertEqual(result, 0.0,
666 "expected underflow to 0 from %r" % underflow)
667
668 for zero in ["huge / 0", "mhuge / 0"]:
669 self.assertRaises(ZeroDivisionError, eval, zero, namespace)
670
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000671 def check_truediv(self, a, b, skip_small=True):
672 """Verify that the result of a/b is correctly rounded, by
673 comparing it with a pure Python implementation of correctly
674 rounded division. b should be nonzero."""
675
676 # skip check for small a and b: in this case, the current
677 # implementation converts the arguments to float directly and
678 # then applies a float division. This can give doubly-rounded
679 # results on x87-using machines (particularly 32-bit Linux).
680 if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
681 return
682
683 try:
684 # use repr so that we can distinguish between -0.0 and 0.0
685 expected = repr(truediv(a, b))
686 except OverflowError:
687 expected = 'overflow'
688 except ZeroDivisionError:
689 expected = 'zerodivision'
690
691 try:
692 got = repr(a / b)
693 except OverflowError:
694 got = 'overflow'
695 except ZeroDivisionError:
696 got = 'zerodivision'
697
Mark Dickinson2cfda802009-12-27 21:34:05 +0000698 self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
699 "expected {}, got {}".format(a, b, expected, got))
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000700
Eric Smith3ab08ca2010-12-04 15:17:38 +0000701 @support.requires_IEEE_754
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000702 def test_correctly_rounded_true_division(self):
703 # more stringent tests than those above, checking that the
704 # result of true division of ints is always correctly rounded.
705 # This test should probably be considered CPython-specific.
706
707 # Exercise all the code paths not involving Gb-sized ints.
708 # ... divisions involving zero
709 self.check_truediv(123, 0)
710 self.check_truediv(-456, 0)
711 self.check_truediv(0, 3)
712 self.check_truediv(0, -3)
713 self.check_truediv(0, 0)
714 # ... overflow or underflow by large margin
715 self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
716 self.check_truediv(12345, 345678 * 2**(DBL_MANT_DIG - DBL_MIN_EXP))
717 # ... a much larger or smaller than b
718 self.check_truediv(12345*2**100, 98765)
719 self.check_truediv(12345*2**30, 98765*7**81)
720 # ... a / b near a boundary: one of 1, 2**DBL_MANT_DIG, 2**DBL_MIN_EXP,
721 # 2**DBL_MAX_EXP, 2**(DBL_MIN_EXP-DBL_MANT_DIG)
722 bases = (0, DBL_MANT_DIG, DBL_MIN_EXP,
723 DBL_MAX_EXP, DBL_MIN_EXP - DBL_MANT_DIG)
724 for base in bases:
725 for exp in range(base - 15, base + 15):
726 self.check_truediv(75312*2**max(exp, 0), 69187*2**max(-exp, 0))
727 self.check_truediv(69187*2**max(exp, 0), 75312*2**max(-exp, 0))
728
729 # overflow corner case
730 for m in [1, 2, 7, 17, 12345, 7**100,
731 -1, -2, -5, -23, -67891, -41**50]:
732 for n in range(-10, 10):
733 self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
734 self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
735
736 # check detection of inexactness in shifting stage
737 for n in range(250):
738 # (2**DBL_MANT_DIG+1)/(2**DBL_MANT_DIG) lies halfway
739 # between two representable floats, and would usually be
740 # rounded down under round-half-to-even. The tiniest of
741 # additions to the numerator should cause it to be rounded
742 # up instead.
743 self.check_truediv((2**DBL_MANT_DIG + 1)*12345*2**200 + 2**n,
744 2**DBL_MANT_DIG*12345)
745
746 # 1/2731 is one of the smallest division cases that's subject
747 # to double rounding on IEEE 754 machines working internally with
748 # 64-bit precision. On such machines, the next check would fail,
749 # were it not explicitly skipped in check_truediv.
750 self.check_truediv(1, 2731)
751
752 # a particularly bad case for the old algorithm: gives an
753 # error of close to 3.5 ulps.
754 self.check_truediv(295147931372582273023, 295147932265116303360)
755 for i in range(1000):
756 self.check_truediv(10**(i+1), 10**i)
757 self.check_truediv(10**i, 10**(i+1))
758
759 # test round-half-to-even behaviour, normal result
760 for m in [1, 2, 4, 7, 8, 16, 17, 32, 12345, 7**100,
761 -1, -2, -5, -23, -67891, -41**50]:
762 for n in range(-10, 10):
763 self.check_truediv(2**DBL_MANT_DIG*m + n, m)
764
765 # test round-half-to-even, subnormal result
766 for n in range(-20, 20):
767 self.check_truediv(n, 2**1076)
768
769 # largeish random divisions: a/b where |a| <= |b| <=
770 # 2*|a|; |ans| is between 0.5 and 1.0, so error should
771 # always be bounded by 2**-54 with equality possible only
772 # if the least significant bit of q=ans*2**53 is zero.
773 for M in [10**10, 10**100, 10**1000]:
774 for i in range(1000):
775 a = random.randrange(1, M)
776 b = random.randrange(a, 2*a+1)
777 self.check_truediv(a, b)
778 self.check_truediv(-a, b)
779 self.check_truediv(a, -b)
780 self.check_truediv(-a, -b)
781
782 # and some (genuinely) random tests
783 for _ in range(10000):
784 a_bits = random.randrange(1000)
785 b_bits = random.randrange(1, 1000)
786 x = random.randrange(2**a_bits)
787 y = random.randrange(1, 2**b_bits)
788 self.check_truediv(x, y)
789 self.check_truediv(x, -y)
790 self.check_truediv(-x, y)
791 self.check_truediv(-x, -y)
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000792
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000793 def test_small_ints(self):
794 for i in range(-5, 257):
795 self.assertTrue(i is i + 0)
796 self.assertTrue(i is i * 1)
797 self.assertTrue(i is i - 0)
798 self.assertTrue(i is i // 1)
799 self.assertTrue(i is i & -1)
800 self.assertTrue(i is i | 0)
801 self.assertTrue(i is i ^ 0)
802 self.assertTrue(i is ~~i)
803 self.assertTrue(i is i**1)
804 self.assertTrue(i is int(str(i)))
805 self.assertTrue(i is i<<2>>2, str(i))
806 # corner cases
807 i = 1 << 70
808 self.assertTrue(i - i is 0)
809 self.assertTrue(0 * i is 0)
810
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000811 def test_bit_length(self):
812 tiny = 1e-10
813 for x in range(-65000, 65000):
814 k = x.bit_length()
815 # Check equivalence with Python version
816 self.assertEqual(k, len(bin(x).lstrip('-0b')))
817 # Behaviour as specified in the docs
818 if x != 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000819 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000820 else:
821 self.assertEqual(k, 0)
822 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
823 if x != 0:
824 # When x is an exact power of 2, numeric errors can
825 # cause floor(log(x)/log(2)) to be one too small; for
826 # small x this can be fixed by adding a small quantity
827 # to the quotient before taking the floor.
828 self.assertEqual(k, 1 + math.floor(
829 math.log(abs(x))/math.log(2) + tiny))
830
831 self.assertEqual((0).bit_length(), 0)
832 self.assertEqual((1).bit_length(), 1)
833 self.assertEqual((-1).bit_length(), 1)
834 self.assertEqual((2).bit_length(), 2)
835 self.assertEqual((-2).bit_length(), 2)
836 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
837 a = 2**i
838 self.assertEqual((a-1).bit_length(), i)
839 self.assertEqual((1-a).bit_length(), i)
840 self.assertEqual((a).bit_length(), i+1)
841 self.assertEqual((-a).bit_length(), i+1)
842 self.assertEqual((a+1).bit_length(), i+1)
843 self.assertEqual((-a-1).bit_length(), i+1)
844
Mark Dickinson1124e712009-01-28 21:25:58 +0000845 def test_round(self):
846 # check round-half-even algorithm. For round to nearest ten;
847 # rounding map is invariant under adding multiples of 20
848 test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
849 6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
850 15:20, 16:20, 17:20, 18:20, 19:20}
851 for offset in range(-520, 520, 20):
852 for k, v in test_dict.items():
853 got = round(k+offset, -1)
854 expected = v+offset
855 self.assertEqual(got, expected)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000856 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000857
858 # larger second argument
859 self.assertEqual(round(-150, -2), -200)
860 self.assertEqual(round(-149, -2), -100)
861 self.assertEqual(round(-51, -2), -100)
862 self.assertEqual(round(-50, -2), 0)
863 self.assertEqual(round(-49, -2), 0)
864 self.assertEqual(round(-1, -2), 0)
865 self.assertEqual(round(0, -2), 0)
866 self.assertEqual(round(1, -2), 0)
867 self.assertEqual(round(49, -2), 0)
868 self.assertEqual(round(50, -2), 0)
869 self.assertEqual(round(51, -2), 100)
870 self.assertEqual(round(149, -2), 100)
871 self.assertEqual(round(150, -2), 200)
872 self.assertEqual(round(250, -2), 200)
873 self.assertEqual(round(251, -2), 300)
874 self.assertEqual(round(172500, -3), 172000)
875 self.assertEqual(round(173500, -3), 174000)
876 self.assertEqual(round(31415926535, -1), 31415926540)
877 self.assertEqual(round(31415926535, -2), 31415926500)
878 self.assertEqual(round(31415926535, -3), 31415927000)
879 self.assertEqual(round(31415926535, -4), 31415930000)
880 self.assertEqual(round(31415926535, -5), 31415900000)
881 self.assertEqual(round(31415926535, -6), 31416000000)
882 self.assertEqual(round(31415926535, -7), 31420000000)
883 self.assertEqual(round(31415926535, -8), 31400000000)
884 self.assertEqual(round(31415926535, -9), 31000000000)
885 self.assertEqual(round(31415926535, -10), 30000000000)
886 self.assertEqual(round(31415926535, -11), 0)
887 self.assertEqual(round(31415926535, -12), 0)
888 self.assertEqual(round(31415926535, -999), 0)
889
890 # should get correct results even for huge inputs
891 for k in range(10, 100):
892 got = round(10**k + 324678, -3)
893 expect = 10**k + 325000
894 self.assertEqual(got, expect)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000895 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000896
897 # nonnegative second argument: round(x, n) should just return x
898 for n in range(5):
899 for i in range(100):
900 x = random.randrange(-10000, 10000)
901 got = round(x, n)
902 self.assertEqual(got, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000903 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000904 for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
905 self.assertEqual(round(8979323, huge_n), 8979323)
906
907 # omitted second argument
908 for i in range(100):
909 x = random.randrange(-10000, 10000)
910 got = round(x)
911 self.assertEqual(got, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000912 self.assertTrue(type(got) is int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000913
914 # bad second argument
915 bad_exponents = ('brian', 2.0, 0j, None)
916 for e in bad_exponents:
917 self.assertRaises(TypeError, round, 3, e)
918
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000919 def test_to_bytes(self):
920 def check(tests, byteorder, signed=False):
921 for test, expected in tests.items():
922 try:
923 self.assertEqual(
924 test.to_bytes(len(expected), byteorder, signed=signed),
925 expected)
926 except Exception as err:
927 raise AssertionError(
928 "failed to convert {0} with byteorder={1} and signed={2}"
929 .format(test, byteorder, signed)) from err
930
931 # Convert integers to signed big-endian byte arrays.
932 tests1 = {
933 0: b'\x00',
934 1: b'\x01',
935 -1: b'\xff',
936 -127: b'\x81',
937 -128: b'\x80',
938 -129: b'\xff\x7f',
939 127: b'\x7f',
940 129: b'\x00\x81',
941 -255: b'\xff\x01',
942 -256: b'\xff\x00',
943 255: b'\x00\xff',
944 256: b'\x01\x00',
945 32767: b'\x7f\xff',
946 -32768: b'\xff\x80\x00',
947 65535: b'\x00\xff\xff',
948 -65536: b'\xff\x00\x00',
949 -8388608: b'\x80\x00\x00'
950 }
951 check(tests1, 'big', signed=True)
952
953 # Convert integers to signed little-endian byte arrays.
954 tests2 = {
955 0: b'\x00',
956 1: b'\x01',
957 -1: b'\xff',
958 -127: b'\x81',
959 -128: b'\x80',
960 -129: b'\x7f\xff',
961 127: b'\x7f',
962 129: b'\x81\x00',
963 -255: b'\x01\xff',
964 -256: b'\x00\xff',
965 255: b'\xff\x00',
966 256: b'\x00\x01',
967 32767: b'\xff\x7f',
968 -32768: b'\x00\x80',
969 65535: b'\xff\xff\x00',
970 -65536: b'\x00\x00\xff',
971 -8388608: b'\x00\x00\x80'
972 }
973 check(tests2, 'little', signed=True)
974
975 # Convert integers to unsigned big-endian byte arrays.
976 tests3 = {
977 0: b'\x00',
978 1: b'\x01',
979 127: b'\x7f',
980 128: b'\x80',
981 255: b'\xff',
982 256: b'\x01\x00',
983 32767: b'\x7f\xff',
984 32768: b'\x80\x00',
985 65535: b'\xff\xff',
986 65536: b'\x01\x00\x00'
987 }
988 check(tests3, 'big', signed=False)
989
990 # Convert integers to unsigned little-endian byte arrays.
991 tests4 = {
992 0: b'\x00',
993 1: b'\x01',
994 127: b'\x7f',
995 128: b'\x80',
996 255: b'\xff',
997 256: b'\x00\x01',
998 32767: b'\xff\x7f',
999 32768: b'\x00\x80',
1000 65535: b'\xff\xff',
1001 65536: b'\x00\x00\x01'
1002 }
1003 check(tests4, 'little', signed=False)
1004
1005 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
1006 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
1007 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
1008 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
1009 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False),
1010 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
1011 self.assertEqual((0).to_bytes(0, 'big'), b'')
1012 self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
1013 self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
1014 self.assertEqual((-1).to_bytes(5, 'big', signed=True),
1015 b'\xff\xff\xff\xff\xff')
1016 self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1017
1018 def test_from_bytes(self):
1019 def check(tests, byteorder, signed=False):
1020 for test, expected in tests.items():
1021 try:
1022 self.assertEqual(
1023 int.from_bytes(test, byteorder, signed=signed),
1024 expected)
1025 except Exception as err:
1026 raise AssertionError(
1027 "failed to convert {0} with byteorder={1!r} and signed={2}"
1028 .format(test, byteorder, signed)) from err
1029
1030 # Convert signed big-endian byte arrays to integers.
1031 tests1 = {
1032 b'': 0,
1033 b'\x00': 0,
1034 b'\x00\x00': 0,
1035 b'\x01': 1,
1036 b'\x00\x01': 1,
1037 b'\xff': -1,
1038 b'\xff\xff': -1,
1039 b'\x81': -127,
1040 b'\x80': -128,
1041 b'\xff\x7f': -129,
1042 b'\x7f': 127,
1043 b'\x00\x81': 129,
1044 b'\xff\x01': -255,
1045 b'\xff\x00': -256,
1046 b'\x00\xff': 255,
1047 b'\x01\x00': 256,
1048 b'\x7f\xff': 32767,
1049 b'\x80\x00': -32768,
1050 b'\x00\xff\xff': 65535,
1051 b'\xff\x00\x00': -65536,
1052 b'\x80\x00\x00': -8388608
1053 }
1054 check(tests1, 'big', signed=True)
1055
1056 # Convert signed little-endian byte arrays to integers.
1057 tests2 = {
1058 b'': 0,
1059 b'\x00': 0,
1060 b'\x00\x00': 0,
1061 b'\x01': 1,
1062 b'\x00\x01': 256,
1063 b'\xff': -1,
1064 b'\xff\xff': -1,
1065 b'\x81': -127,
1066 b'\x80': -128,
1067 b'\x7f\xff': -129,
1068 b'\x7f': 127,
1069 b'\x81\x00': 129,
1070 b'\x01\xff': -255,
1071 b'\x00\xff': -256,
1072 b'\xff\x00': 255,
1073 b'\x00\x01': 256,
1074 b'\xff\x7f': 32767,
1075 b'\x00\x80': -32768,
1076 b'\xff\xff\x00': 65535,
1077 b'\x00\x00\xff': -65536,
1078 b'\x00\x00\x80': -8388608
1079 }
1080 check(tests2, 'little', signed=True)
1081
1082 # Convert unsigned big-endian byte arrays to integers.
1083 tests3 = {
1084 b'': 0,
1085 b'\x00': 0,
1086 b'\x01': 1,
1087 b'\x7f': 127,
1088 b'\x80': 128,
1089 b'\xff': 255,
1090 b'\x01\x00': 256,
1091 b'\x7f\xff': 32767,
1092 b'\x80\x00': 32768,
1093 b'\xff\xff': 65535,
1094 b'\x01\x00\x00': 65536,
1095 }
1096 check(tests3, 'big', signed=False)
1097
1098 # Convert integers to unsigned little-endian byte arrays.
1099 tests4 = {
1100 b'': 0,
1101 b'\x00': 0,
1102 b'\x01': 1,
1103 b'\x7f': 127,
1104 b'\x80': 128,
1105 b'\xff': 255,
1106 b'\x00\x01': 256,
1107 b'\xff\x7f': 32767,
1108 b'\x00\x80': 32768,
1109 b'\xff\xff': 65535,
1110 b'\x00\x00\x01': 65536,
1111 }
1112 check(tests4, 'little', signed=False)
1113
1114 class myint(int):
1115 pass
1116
1117 self.assertTrue(type(myint.from_bytes(b'\x00', 'big')) is myint)
1118 self.assertEqual(myint.from_bytes(b'\x01', 'big'), 1)
1119 self.assertTrue(
1120 type(myint.from_bytes(b'\x00', 'big', signed=False)) is myint)
1121 self.assertEqual(myint.from_bytes(b'\x01', 'big', signed=False), 1)
1122 self.assertTrue(type(myint.from_bytes(b'\x00', 'little')) is myint)
1123 self.assertEqual(myint.from_bytes(b'\x01', 'little'), 1)
1124 self.assertTrue(type(myint.from_bytes(
1125 b'\x00', 'little', signed=False)) is myint)
1126 self.assertEqual(myint.from_bytes(b'\x01', 'little', signed=False), 1)
1127 self.assertEqual(
1128 int.from_bytes([255, 0, 0], 'big', signed=True), -65536)
1129 self.assertEqual(
1130 int.from_bytes((255, 0, 0), 'big', signed=True), -65536)
1131 self.assertEqual(int.from_bytes(
1132 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1133 self.assertEqual(int.from_bytes(
1134 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1135 self.assertEqual(int.from_bytes(
1136 array.array('B', b'\xff\x00\x00'), 'big', signed=True), -65536)
1137 self.assertEqual(int.from_bytes(
1138 memoryview(b'\xff\x00\x00'), 'big', signed=True), -65536)
1139 self.assertRaises(ValueError, int.from_bytes, [256], 'big')
1140 self.assertRaises(ValueError, int.from_bytes, [0], 'big\x00')
1141 self.assertRaises(ValueError, int.from_bytes, [0], 'little\x00')
1142 self.assertRaises(TypeError, int.from_bytes, "", 'big')
1143 self.assertRaises(TypeError, int.from_bytes, "\x00", 'big')
1144 self.assertRaises(TypeError, int.from_bytes, 0, 'big')
1145 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1146 self.assertRaises(TypeError, myint.from_bytes, "", 'big')
1147 self.assertRaises(TypeError, myint.from_bytes, "\x00", 'big')
1148 self.assertRaises(TypeError, myint.from_bytes, 0, 'big')
1149 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
Mark Dickinson1124e712009-01-28 21:25:58 +00001150
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00001151
Walter Dörwalda0021592005-06-13 21:44:48 +00001152def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001153 support.run_unittest(LongTest)
Tim Peters307fa782004-09-23 08:06:40 +00001154
Walter Dörwalda0021592005-06-13 21:44:48 +00001155if __name__ == "__main__":
1156 test_main()