blob: 5b8b4dc4a99a356d13832a855055d9a6ad77840b [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
Guido van Rossum4365cab1998-08-13 14:20:17 +000010# SHIFT should match the value in longintrepr.h for best testing.
Mark Dickinsonbd792642009-03-18 20:06:12 +000011SHIFT = sys.int_info.bits_per_digit
Guido van Rossum4365cab1998-08-13 14:20:17 +000012BASE = 2 ** SHIFT
13MASK = BASE - 1
Tim Petersdaec9612004-08-30 23:18:23 +000014KARATSUBA_CUTOFF = 70 # from longobject.c
Guido van Rossum4365cab1998-08-13 14:20:17 +000015
16# Max number of base BASE digits to use in test cases. Doubling
Tim Peters28b0e2a2002-08-13 02:17:11 +000017# this will more than double the runtime.
18MAXDIGITS = 15
Guido van Rossum4365cab1998-08-13 14:20:17 +000019
Guido van Rossum4581a0c1998-10-02 01:19:48 +000020# build some special values
Guido van Rossumc1f779c2007-07-03 08:25:58 +000021special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000022# some solid strings of one bits
Guido van Rossume2a383d2007-01-15 16:59:06 +000023p2 = 4 # 0 and 1 already added
Guido van Rossum4581a0c1998-10-02 01:19:48 +000024for i in range(2*SHIFT):
25 special.append(p2 - 1)
26 p2 = p2 << 1
27del p2
28# add complements & negations
Guido van Rossumc1f779c2007-07-03 08:25:58 +000029special += [~x for x in special] + [-x for x in special]
Guido van Rossum4581a0c1998-10-02 01:19:48 +000030
Mark Dickinsoncbb62742009-12-27 15:09:50 +000031DBL_MAX = sys.float_info.max
32DBL_MAX_EXP = sys.float_info.max_exp
33DBL_MIN_EXP = sys.float_info.min_exp
34DBL_MANT_DIG = sys.float_info.mant_dig
35DBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1)
36
Mark Dickinson30970e92011-10-23 20:07:13 +010037
38# Pure Python version of correctly-rounded integer-to-float conversion.
39def int_to_float(n):
40 """
41 Correctly-rounded integer-to-float conversion.
42
43 """
44 # Constants, depending only on the floating-point format in use.
45 # We use an extra 2 bits of precision for rounding purposes.
46 PRECISION = sys.float_info.mant_dig + 2
47 SHIFT_MAX = sys.float_info.max_exp - PRECISION
48 Q_MAX = 1 << PRECISION
49 ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1]
50
51 # Reduce to the case where n is positive.
52 if n == 0:
53 return 0.0
54 elif n < 0:
55 return -int_to_float(-n)
56
57 # Convert n to a 'floating-point' number q * 2**shift, where q is an
58 # integer with 'PRECISION' significant bits. When shifting n to create q,
59 # the least significant bit of q is treated as 'sticky'. That is, the
60 # least significant bit of q is set if either the corresponding bit of n
61 # was already set, or any one of the bits of n lost in the shift was set.
62 shift = n.bit_length() - PRECISION
63 q = n << -shift if shift < 0 else (n >> shift) | bool(n & ~(-1 << shift))
64
65 # Round half to even (actually rounds to the nearest multiple of 4,
66 # rounding ties to a multiple of 8).
67 q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7]
68
69 # Detect overflow.
70 if shift + (q == Q_MAX) > SHIFT_MAX:
71 raise OverflowError("integer too large to convert to float")
72
73 # Checks: q is exactly representable, and q**2**shift doesn't overflow.
74 assert q % 4 == 0 and q // 4 <= 2**(sys.float_info.mant_dig)
75 assert q * 2**shift <= sys.float_info.max
76
77 # Some circularity here, since float(q) is doing an int-to-float
78 # conversion. But here q is of bounded size, and is exactly representable
79 # as a float. In a low-level C-like language, this operation would be a
80 # simple cast (e.g., from unsigned long long to double).
81 return math.ldexp(float(q), shift)
82
83
Mark Dickinsoncbb62742009-12-27 15:09:50 +000084# pure Python version of correctly-rounded true division
85def truediv(a, b):
86 """Correctly-rounded true division for integers."""
87 negative = a^b < 0
88 a, b = abs(a), abs(b)
89
90 # exceptions: division by zero, overflow
91 if not b:
92 raise ZeroDivisionError("division by zero")
93 if a >= DBL_MIN_OVERFLOW * b:
94 raise OverflowError("int/int too large to represent as a float")
95
96 # find integer d satisfying 2**(d - 1) <= a/b < 2**d
97 d = a.bit_length() - b.bit_length()
98 if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
99 d += 1
100
101 # compute 2**-exp * a / b for suitable exp
102 exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
103 a, b = a << max(-exp, 0), b << max(exp, 0)
104 q, r = divmod(a, b)
105
106 # round-half-to-even: fractional part is r/b, which is > 0.5 iff
107 # 2*r > b, and == 0.5 iff 2*r == b.
108 if 2*r > b or 2*r == b and q % 2 == 1:
109 q += 1
110
Mark Dickinsona4e15062009-12-27 19:03:31 +0000111 result = math.ldexp(q, exp)
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000112 return -result if negative else result
113
114
Walter Dörwalda0021592005-06-13 21:44:48 +0000115class LongTest(unittest.TestCase):
Guido van Rossum4365cab1998-08-13 14:20:17 +0000116
Walter Dörwalda0021592005-06-13 21:44:48 +0000117 # Get quasi-random long consisting of ndigits digits (in base BASE).
118 # quasi == the most-significant digit will not be 0, and the number
119 # is constructed to contain long strings of 0 and 1 bits. These are
120 # more likely than random bits to provoke digit-boundary errors.
121 # The sign of the number is also random.
Guido van Rossum4365cab1998-08-13 14:20:17 +0000122
Walter Dörwalda0021592005-06-13 21:44:48 +0000123 def getran(self, ndigits):
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200124 self.assertGreater(ndigits, 0)
Walter Dörwalda0021592005-06-13 21:44:48 +0000125 nbits_hi = ndigits * SHIFT
126 nbits_lo = nbits_hi - SHIFT + 1
Guido van Rossume2a383d2007-01-15 16:59:06 +0000127 answer = 0
Walter Dörwalda0021592005-06-13 21:44:48 +0000128 nbits = 0
129 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
130 while nbits < nbits_lo:
131 bits = (r >> 1) + 1
132 bits = min(bits, nbits_hi - nbits)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000133 self.assertTrue(1 <= bits <= SHIFT)
Walter Dörwalda0021592005-06-13 21:44:48 +0000134 nbits = nbits + bits
135 answer = answer << bits
136 if r & 1:
137 answer = answer | ((1 << bits) - 1)
138 r = int(random.random() * (SHIFT * 2))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000139 self.assertTrue(nbits_lo <= nbits <= nbits_hi)
Walter Dörwalda0021592005-06-13 21:44:48 +0000140 if random.random() < 0.5:
141 answer = -answer
142 return answer
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000143
Walter Dörwalda0021592005-06-13 21:44:48 +0000144 # Get random long consisting of ndigits random digits (relative to base
145 # BASE). The sign bit is also random.
Guido van Rossum4581a0c1998-10-02 01:19:48 +0000146
Walter Dörwalda0021592005-06-13 21:44:48 +0000147 def getran2(ndigits):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000148 answer = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000149 for i in range(ndigits):
Walter Dörwalda0021592005-06-13 21:44:48 +0000150 answer = (answer << SHIFT) | random.randint(0, MASK)
151 if random.random() < 0.5:
152 answer = -answer
153 return answer
Guido van Rossum4365cab1998-08-13 14:20:17 +0000154
Walter Dörwalda0021592005-06-13 21:44:48 +0000155 def check_division(self, x, y):
156 eq = self.assertEqual
Martin Pantercbe16ae2015-09-25 23:50:47 +0000157 with self.subTest(x=x, y=y):
158 q, r = divmod(x, y)
159 q2, r2 = x//y, x%y
160 pab, pba = x*y, y*x
161 eq(pab, pba, "multiplication does not commute")
162 eq(q, q2, "divmod returns different quotient than /")
163 eq(r, r2, "divmod returns different mod than %")
164 eq(x, q*y + r, "x != q*y + r after divmod")
165 if y > 0:
166 self.assertTrue(0 <= r < y, "bad mod from divmod")
167 else:
168 self.assertTrue(y < r <= 0, "bad mod from divmod")
Guido van Rossum4365cab1998-08-13 14:20:17 +0000169
Walter Dörwalda0021592005-06-13 21:44:48 +0000170 def test_division(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000171 digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
172 KARATSUBA_CUTOFF + 14))
Walter Dörwalda0021592005-06-13 21:44:48 +0000173 digits.append(KARATSUBA_CUTOFF * 3)
174 for lenx in digits:
175 x = self.getran(lenx)
176 for leny in digits:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000177 y = self.getran(leny) or 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000178 self.check_division(x, y)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000179
Mark Dickinsonbd792642009-03-18 20:06:12 +0000180 # specific numbers chosen to exercise corner cases of the
181 # current long division implementation
182
183 # 30-bit cases involving a quotient digit estimate of BASE+1
184 self.check_division(1231948412290879395966702881,
185 1147341367131428698)
186 self.check_division(815427756481275430342312021515587883,
187 707270836069027745)
188 self.check_division(627976073697012820849443363563599041,
189 643588798496057020)
190 self.check_division(1115141373653752303710932756325578065,
191 1038556335171453937726882627)
192 # 30-bit cases that require the post-subtraction correction step
193 self.check_division(922498905405436751940989320930368494,
194 949985870686786135626943396)
195 self.check_division(768235853328091167204009652174031844,
196 1091555541180371554426545266)
197
198 # 15-bit cases involving a quotient digit estimate of BASE+1
199 self.check_division(20172188947443, 615611397)
200 self.check_division(1020908530270155025, 950795710)
201 self.check_division(128589565723112408, 736393718)
202 self.check_division(609919780285761575, 18613274546784)
203 # 15-bit cases that require the post-subtraction correction step
204 self.check_division(710031681576388032, 26769404391308)
205 self.check_division(1933622614268221, 30212853348836)
206
207
208
Walter Dörwalda0021592005-06-13 21:44:48 +0000209 def test_karatsuba(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000210 digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
211 KARATSUBA_CUTOFF + 10))
Walter Dörwalda0021592005-06-13 21:44:48 +0000212 digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
Guido van Rossum4365cab1998-08-13 14:20:17 +0000213
Walter Dörwalda0021592005-06-13 21:44:48 +0000214 bits = [digit * SHIFT for digit in digits]
Guido van Rossum4365cab1998-08-13 14:20:17 +0000215
Walter Dörwalda0021592005-06-13 21:44:48 +0000216 # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
217 # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
218 for abits in bits:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000219 a = (1 << abits) - 1
Walter Dörwalda0021592005-06-13 21:44:48 +0000220 for bbits in bits:
221 if bbits < abits:
222 continue
Martin Pantercbe16ae2015-09-25 23:50:47 +0000223 with self.subTest(abits=abits, bbits=bbits):
224 b = (1 << bbits) - 1
225 x = a * b
226 y = ((1 << (abits + bbits)) -
227 (1 << abits) -
228 (1 << bbits) +
229 1)
230 self.assertEqual(x, y)
Tim Peters7f270ba2002-08-13 21:06:55 +0000231
Walter Dörwalda0021592005-06-13 21:44:48 +0000232 def check_bitop_identities_1(self, x):
233 eq = self.assertEqual
Martin Pantercbe16ae2015-09-25 23:50:47 +0000234 with self.subTest(x=x):
235 eq(x & 0, 0)
236 eq(x | 0, x)
237 eq(x ^ 0, x)
238 eq(x & -1, x)
239 eq(x | -1, -1)
240 eq(x ^ -1, ~x)
241 eq(x, ~~x)
242 eq(x & x, x)
243 eq(x | x, x)
244 eq(x ^ x, 0)
245 eq(x & ~x, 0)
246 eq(x | ~x, -1)
247 eq(x ^ ~x, -1)
248 eq(-x, 1 + ~x)
249 eq(-x, ~(x-1))
Guido van Rossum805365e2007-05-07 22:24:25 +0000250 for n in range(2*SHIFT):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000251 p2 = 2 ** n
Martin Pantercbe16ae2015-09-25 23:50:47 +0000252 with self.subTest(x=x, n=n, p2=p2):
253 eq(x << n >> n, x)
254 eq(x // p2, x >> n)
255 eq(x * p2, x << n)
256 eq(x & -p2, x >> n << n)
257 eq(x & -p2, x & ~(p2 - 1))
Tim Peters7f270ba2002-08-13 21:06:55 +0000258
Walter Dörwalda0021592005-06-13 21:44:48 +0000259 def check_bitop_identities_2(self, x, y):
260 eq = self.assertEqual
Martin Pantercbe16ae2015-09-25 23:50:47 +0000261 with self.subTest(x=x, y=y):
262 eq(x & y, y & x)
263 eq(x | y, y | x)
264 eq(x ^ y, y ^ x)
265 eq(x ^ y ^ x, y)
266 eq(x & y, ~(~x | ~y))
267 eq(x | y, ~(~x & ~y))
268 eq(x ^ y, (x | y) & ~(x & y))
269 eq(x ^ y, (x & ~y) | (~x & y))
270 eq(x ^ y, (x | y) & (~x | ~y))
Tim Peters7f270ba2002-08-13 21:06:55 +0000271
Walter Dörwalda0021592005-06-13 21:44:48 +0000272 def check_bitop_identities_3(self, x, y, z):
273 eq = self.assertEqual
Martin Pantercbe16ae2015-09-25 23:50:47 +0000274 with self.subTest(x=x, y=y, z=z):
275 eq((x & y) & z, x & (y & z))
276 eq((x | y) | z, x | (y | z))
277 eq((x ^ y) ^ z, x ^ (y ^ z))
278 eq(x & (y | z), (x & y) | (x & z))
279 eq(x | (y & z), (x | y) & (x | z))
Tim Peters7f270ba2002-08-13 21:06:55 +0000280
Walter Dörwalda0021592005-06-13 21:44:48 +0000281 def test_bitop_identities(self):
282 for x in special:
283 self.check_bitop_identities_1(x)
Guido van Rossum805365e2007-05-07 22:24:25 +0000284 digits = range(1, MAXDIGITS+1)
Walter Dörwalda0021592005-06-13 21:44:48 +0000285 for lenx in digits:
286 x = self.getran(lenx)
287 self.check_bitop_identities_1(x)
288 for leny in digits:
289 y = self.getran(leny)
290 self.check_bitop_identities_2(x, y)
291 self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
Guido van Rossum4365cab1998-08-13 14:20:17 +0000292
Walter Dörwalda0021592005-06-13 21:44:48 +0000293 def slow_format(self, x, base):
Walter Dörwalda0021592005-06-13 21:44:48 +0000294 digits = []
295 sign = 0
296 if x < 0:
297 sign, x = 1, -x
298 while x:
299 x, r = divmod(x, base)
300 digits.append(int(r))
301 digits.reverse()
302 digits = digits or [0]
303 return '-'[:sign] + \
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000304 {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
Georg Brandlcbd2ab12010-12-04 10:39:14 +0000305 "".join("0123456789abcdef"[i] for i in digits)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000306
Walter Dörwalda0021592005-06-13 21:44:48 +0000307 def check_format_1(self, x):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300308 for base, mapper in (2, bin), (8, oct), (10, str), (10, repr), (16, hex):
Walter Dörwalda0021592005-06-13 21:44:48 +0000309 got = mapper(x)
Martin Pantercbe16ae2015-09-25 23:50:47 +0000310 with self.subTest(x=x, mapper=mapper.__name__):
311 expected = self.slow_format(x, base)
312 self.assertEqual(got, expected)
313 with self.subTest(got=got):
314 self.assertEqual(int(got, 0), x)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000315
Walter Dörwalda0021592005-06-13 21:44:48 +0000316 def test_format(self):
317 for x in special:
318 self.check_format_1(x)
Guido van Rossum805365e2007-05-07 22:24:25 +0000319 for i in range(10):
320 for lenx in range(1, MAXDIGITS+1):
Walter Dörwalda0021592005-06-13 21:44:48 +0000321 x = self.getran(lenx)
322 self.check_format_1(x)
Guido van Rossum4365cab1998-08-13 14:20:17 +0000323
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000324 def test_long(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +0000325 # Check conversions from string
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000326 LL = [
327 ('1' + '0'*20, 10**20),
328 ('1' + '0'*100, 10**100)
329 ]
Mark Dickinson5c2db372009-12-05 20:28:34 +0000330 for s, v in LL:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000331 for sign in "", "+", "-":
332 for prefix in "", " ", "\t", " \t\t ":
333 ss = prefix + sign + s
334 vv = v
335 if sign == "-" and v is not ValueError:
336 vv = -v
337 try:
Mark Dickinson5c2db372009-12-05 20:28:34 +0000338 self.assertEqual(int(ss), vv)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000339 except ValueError:
340 pass
341
Mark Dickinson9ffc0202009-01-20 20:45:53 +0000342 # trailing L should no longer be accepted...
343 self.assertRaises(ValueError, int, '123L')
344 self.assertRaises(ValueError, int, '123l')
345 self.assertRaises(ValueError, int, '0L')
346 self.assertRaises(ValueError, int, '-37L')
347 self.assertRaises(ValueError, int, '0x32L', 16)
348 self.assertRaises(ValueError, int, '1L', 21)
349 # ... but it's just a normal digit if base >= 22
350 self.assertEqual(int('1L', 22), 43)
351
Mark Dickinson56544db2010-05-26 19:14:01 +0000352 # tests with base 0
353 self.assertEqual(int('000', 0), 0)
354 self.assertEqual(int('0o123', 0), 83)
355 self.assertEqual(int('0x123', 0), 291)
356 self.assertEqual(int('0b100', 0), 4)
357 self.assertEqual(int(' 0O123 ', 0), 83)
358 self.assertEqual(int(' 0X123 ', 0), 291)
359 self.assertEqual(int(' 0B100 ', 0), 4)
360 self.assertEqual(int('0', 0), 0)
361 self.assertEqual(int('+0', 0), 0)
362 self.assertEqual(int('-0', 0), 0)
363 self.assertEqual(int('00', 0), 0)
364 self.assertRaises(ValueError, int, '08', 0)
365 self.assertRaises(ValueError, int, '-012395', 0)
366
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +0000367 # invalid bases
368 invalid_bases = [-909,
369 2**31-1, 2**31, -2**31, -2**31-1,
370 2**63-1, 2**63, -2**63, -2**63-1,
371 2**100, -2**100,
372 ]
373 for base in invalid_bases:
374 self.assertRaises(ValueError, int, '42', base)
375
376
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000377 def test_conversion(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000378
Mark Dickinson5c2db372009-12-05 20:28:34 +0000379 class JustLong:
380 # test that __long__ no longer used in 3.x
381 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000382 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000383 self.assertRaises(TypeError, int, JustLong())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000384
Mark Dickinson5c2db372009-12-05 20:28:34 +0000385 class LongTrunc:
386 # __long__ should be ignored in 3.x
387 def __long__(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000388 return 42
Mark Dickinson5c2db372009-12-05 20:28:34 +0000389 def __trunc__(self):
390 return 1729
391 self.assertEqual(int(LongTrunc()), 1729)
Tim Peters26c7fa32001-08-23 22:56:21 +0000392
Mark Dickinson30970e92011-10-23 20:07:13 +0100393 def check_float_conversion(self, n):
394 # Check that int -> float conversion behaviour matches
395 # that of the pure Python version above.
396 try:
397 actual = float(n)
398 except OverflowError:
399 actual = 'overflow'
400
401 try:
402 expected = int_to_float(n)
403 except OverflowError:
404 expected = 'overflow'
405
406 msg = ("Error in conversion of integer {} to float. "
407 "Got {}, expected {}.".format(n, actual, expected))
408 self.assertEqual(actual, expected, msg)
409
Eric Smith3ab08ca2010-12-04 15:17:38 +0000410 @support.requires_IEEE_754
Mark Dickinsonc6300392009-04-20 21:38:00 +0000411 def test_float_conversion(self):
Mark Dickinsonc6300392009-04-20 21:38:00 +0000412
413 exact_values = [0, 1, 2,
414 2**53-3,
415 2**53-2,
416 2**53-1,
417 2**53,
418 2**53+2,
419 2**54-4,
420 2**54-2,
421 2**54,
422 2**54+4]
423 for x in exact_values:
424 self.assertEqual(float(x), x)
425 self.assertEqual(float(-x), -x)
426
427 # test round-half-even
428 for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
429 for p in range(15):
430 self.assertEqual(int(float(2**p*(2**53+x))), 2**p*(2**53+y))
431
432 for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
433 (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
434 (13, 12), (14, 16), (15, 16)]:
435 for p in range(15):
436 self.assertEqual(int(float(2**p*(2**54+x))), 2**p*(2**54+y))
437
438 # behaviour near extremes of floating-point range
439 int_dbl_max = int(DBL_MAX)
440 top_power = 2**DBL_MAX_EXP
441 halfway = (int_dbl_max + top_power)//2
442 self.assertEqual(float(int_dbl_max), DBL_MAX)
443 self.assertEqual(float(int_dbl_max+1), DBL_MAX)
444 self.assertEqual(float(halfway-1), DBL_MAX)
445 self.assertRaises(OverflowError, float, halfway)
446 self.assertEqual(float(1-halfway), -DBL_MAX)
447 self.assertRaises(OverflowError, float, -halfway)
448 self.assertRaises(OverflowError, float, top_power-1)
449 self.assertRaises(OverflowError, float, top_power)
450 self.assertRaises(OverflowError, float, top_power+1)
451 self.assertRaises(OverflowError, float, 2*top_power-1)
452 self.assertRaises(OverflowError, float, 2*top_power)
453 self.assertRaises(OverflowError, float, top_power*top_power)
454
455 for p in range(100):
456 x = 2**p * (2**53 + 1) + 1
457 y = 2**p * (2**53 + 2)
458 self.assertEqual(int(float(x)), y)
459
460 x = 2**p * (2**53 + 1)
461 y = 2**p * 2**53
462 self.assertEqual(int(float(x)), y)
463
Mark Dickinson30970e92011-10-23 20:07:13 +0100464 # Compare builtin float conversion with pure Python int_to_float
465 # function above.
466 test_values = [
467 int_dbl_max-1, int_dbl_max, int_dbl_max+1,
468 halfway-1, halfway, halfway + 1,
469 top_power-1, top_power, top_power+1,
470 2*top_power-1, 2*top_power, top_power*top_power,
471 ]
472 test_values.extend(exact_values)
473 for p in range(-4, 8):
474 for x in range(-128, 128):
475 test_values.append(2**(p+53) + x)
476 for value in test_values:
477 self.check_float_conversion(value)
478 self.check_float_conversion(-value)
479
Walter Dörwalda0021592005-06-13 21:44:48 +0000480 def test_float_overflow(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000481 for x in -2.0, -1.0, 0.0, 1.0, 2.0:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000482 self.assertEqual(float(int(x)), x)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000483
Walter Dörwalda0021592005-06-13 21:44:48 +0000484 shuge = '12345' * 120
Guido van Rossume2a383d2007-01-15 16:59:06 +0000485 huge = 1 << 30000
Walter Dörwalda0021592005-06-13 21:44:48 +0000486 mhuge = -huge
487 namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
488 for test in ["float(huge)", "float(mhuge)",
489 "complex(huge)", "complex(mhuge)",
490 "complex(huge, 1)", "complex(mhuge, 1)",
491 "complex(1, huge)", "complex(1, mhuge)",
492 "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
493 "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
494 "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
495 "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
496 "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
497 "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
498 "math.sin(huge)", "math.sin(mhuge)",
499 "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
Guido van Rossum28bbe422007-08-24 03:46:30 +0000500 # math.floor() of an int returns an int now
501 ##"math.floor(huge)", "math.floor(mhuge)",
502 ]:
Tim Peters9fffa3e2001-09-04 05:14:19 +0000503
Walter Dörwalda0021592005-06-13 21:44:48 +0000504 self.assertRaises(OverflowError, eval, test, namespace)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000505
Mark Dickinson5c2db372009-12-05 20:28:34 +0000506 # XXX Perhaps float(shuge) can raise OverflowError on some box?
507 # The comparison should not.
508 self.assertNotEqual(float(shuge), int(shuge),
509 "float(shuge) should not equal int(shuge)")
Tim Peters83e7ccc2001-09-04 06:37:28 +0000510
Walter Dörwalda0021592005-06-13 21:44:48 +0000511 def test_logs(self):
Walter Dörwalda0021592005-06-13 21:44:48 +0000512 LOG10E = math.log10(math.e)
Tim Peters307fa782004-09-23 08:06:40 +0000513
Guido van Rossum805365e2007-05-07 22:24:25 +0000514 for exp in list(range(10)) + [100, 1000, 10000]:
Walter Dörwalda0021592005-06-13 21:44:48 +0000515 value = 10 ** exp
516 log10 = math.log10(value)
517 self.assertAlmostEqual(log10, exp)
Tim Peters78526162001-09-05 00:53:45 +0000518
Walter Dörwalda0021592005-06-13 21:44:48 +0000519 # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
520 # exp/LOG10E
521 expected = exp / LOG10E
522 log = math.log(value)
523 self.assertAlmostEqual(log, expected)
Tim Peters78526162001-09-05 00:53:45 +0000524
Guido van Rossume2a383d2007-01-15 16:59:06 +0000525 for bad in -(1 << 10000), -2, 0:
Walter Dörwalda0021592005-06-13 21:44:48 +0000526 self.assertRaises(ValueError, math.log, bad)
527 self.assertRaises(ValueError, math.log10, bad)
Tim Peters78526162001-09-05 00:53:45 +0000528
Walter Dörwalda0021592005-06-13 21:44:48 +0000529 def test_mixed_compares(self):
530 eq = self.assertEqual
Tim Peters78526162001-09-05 00:53:45 +0000531
Serhiy Storchaka95949422013-08-27 19:40:23 +0300532 # We're mostly concerned with that mixing floats and ints does the
533 # right stuff, even when ints are too large to fit in a float.
Walter Dörwalda0021592005-06-13 21:44:48 +0000534 # The safest way to check the results is to use an entirely different
535 # method, which we do here via a skeletal rational class (which
Serhiy Storchaka95949422013-08-27 19:40:23 +0300536 # represents all Python ints and floats exactly).
Walter Dörwalda0021592005-06-13 21:44:48 +0000537 class Rat:
538 def __init__(self, value):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000539 if isinstance(value, int):
Walter Dörwalda0021592005-06-13 21:44:48 +0000540 self.n = value
541 self.d = 1
542 elif isinstance(value, float):
543 # Convert to exact rational equivalent.
544 f, e = math.frexp(abs(value))
545 assert f == 0 or 0.5 <= f < 1.0
546 # |value| = f * 2**e exactly
Tim Peters78526162001-09-05 00:53:45 +0000547
Walter Dörwalda0021592005-06-13 21:44:48 +0000548 # Suck up CHUNK bits at a time; 28 is enough so that we suck
549 # up all bits in 2 iterations for all known binary double-
550 # precision formats, and small enough to fit in an int.
551 CHUNK = 28
552 top = 0
553 # invariant: |value| = (top + f) * 2**e exactly
554 while f:
555 f = math.ldexp(f, CHUNK)
556 digit = int(f)
557 assert digit >> CHUNK == 0
558 top = (top << CHUNK) | digit
559 f -= digit
560 assert 0.0 <= f < 1.0
561 e -= CHUNK
Tim Peters78526162001-09-05 00:53:45 +0000562
Walter Dörwalda0021592005-06-13 21:44:48 +0000563 # Now |value| = top * 2**e exactly.
564 if e >= 0:
565 n = top << e
566 d = 1
567 else:
568 n = top
569 d = 1 << -e
570 if value < 0:
571 n = -n
572 self.n = n
573 self.d = d
574 assert float(n) / float(d) == value
Tim Peters307fa782004-09-23 08:06:40 +0000575 else:
Georg Brandl89fad142010-03-14 10:23:39 +0000576 raise TypeError("can't deal with %r" % value)
Tim Peters307fa782004-09-23 08:06:40 +0000577
Benjamin Peterson60192082008-10-16 19:34:46 +0000578 def _cmp__(self, other):
Walter Dörwalda0021592005-06-13 21:44:48 +0000579 if not isinstance(other, Rat):
580 other = Rat(other)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000581 x, y = self.n * other.d, self.d * other.n
582 return (x > y) - (x < y)
Benjamin Peterson60192082008-10-16 19:34:46 +0000583 def __eq__(self, other):
584 return self._cmp__(other) == 0
Benjamin Peterson60192082008-10-16 19:34:46 +0000585 def __ge__(self, other):
586 return self._cmp__(other) >= 0
587 def __gt__(self, other):
588 return self._cmp__(other) > 0
589 def __le__(self, other):
590 return self._cmp__(other) <= 0
591 def __lt__(self, other):
592 return self._cmp__(other) < 0
Tim Peters307fa782004-09-23 08:06:40 +0000593
Walter Dörwalda0021592005-06-13 21:44:48 +0000594 cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
595 # 2**48 is an important boundary in the internals. 2**53 is an
596 # important boundary for IEEE double precision.
597 for t in 2.0**48, 2.0**50, 2.0**53:
598 cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000599 int(t-1), int(t), int(t+1)])
Christian Heimesa37d4c62007-12-04 23:02:19 +0000600 cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
Mark Dickinson5c2db372009-12-05 20:28:34 +0000601 # 1 << 20000 should exceed all double formats. int(1e200) is to
Walter Dörwalda0021592005-06-13 21:44:48 +0000602 # check that we get equality with 1e200 above.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000603 t = int(1e200)
604 cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
Walter Dörwalda0021592005-06-13 21:44:48 +0000605 cases.extend([-x for x in cases])
606 for x in cases:
607 Rx = Rat(x)
608 for y in cases:
609 Ry = Rat(y)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000610 Rcmp = (Rx > Ry) - (Rx < Ry)
Martin Pantercbe16ae2015-09-25 23:50:47 +0000611 with self.subTest(x=x, y=y, Rcmp=Rcmp):
612 xycmp = (x > y) - (x < y)
613 eq(Rcmp, xycmp)
614 eq(x == y, Rcmp == 0)
615 eq(x != y, Rcmp != 0)
616 eq(x < y, Rcmp < 0)
617 eq(x <= y, Rcmp <= 0)
618 eq(x > y, Rcmp > 0)
619 eq(x >= y, Rcmp >= 0)
Tim Peters307fa782004-09-23 08:06:40 +0000620
Eric Smith0dd1b632008-02-11 17:55:01 +0000621 def test__format__(self):
Eric Smith8c663262007-08-25 02:26:07 +0000622 self.assertEqual(format(123456789, 'd'), '123456789')
623 self.assertEqual(format(123456789, 'd'), '123456789')
624
Eric Smith185e30c2007-08-30 22:23:08 +0000625 # sign and aligning are interdependent
626 self.assertEqual(format(1, "-"), '1')
627 self.assertEqual(format(-1, "-"), '-1')
628 self.assertEqual(format(1, "-3"), ' 1')
629 self.assertEqual(format(-1, "-3"), ' -1')
630 self.assertEqual(format(1, "+3"), ' +1')
631 self.assertEqual(format(-1, "+3"), ' -1')
632 self.assertEqual(format(1, " 3"), ' 1')
633 self.assertEqual(format(-1, " 3"), ' -1')
634 self.assertEqual(format(1, " "), ' 1')
635 self.assertEqual(format(-1, " "), '-1')
636
Eric Smith8c663262007-08-25 02:26:07 +0000637 # hex
638 self.assertEqual(format(3, "x"), "3")
639 self.assertEqual(format(3, "X"), "3")
640 self.assertEqual(format(1234, "x"), "4d2")
641 self.assertEqual(format(-1234, "x"), "-4d2")
642 self.assertEqual(format(1234, "8x"), " 4d2")
Eric Smith185e30c2007-08-30 22:23:08 +0000643 self.assertEqual(format(-1234, "8x"), " -4d2")
Eric Smith8c663262007-08-25 02:26:07 +0000644 self.assertEqual(format(1234, "x"), "4d2")
645 self.assertEqual(format(-1234, "x"), "-4d2")
646 self.assertEqual(format(-3, "x"), "-3")
647 self.assertEqual(format(-3, "X"), "-3")
648 self.assertEqual(format(int('be', 16), "x"), "be")
649 self.assertEqual(format(int('be', 16), "X"), "BE")
650 self.assertEqual(format(-int('be', 16), "x"), "-be")
651 self.assertEqual(format(-int('be', 16), "X"), "-BE")
652
653 # octal
654 self.assertEqual(format(3, "b"), "11")
655 self.assertEqual(format(-3, "b"), "-11")
656 self.assertEqual(format(1234, "b"), "10011010010")
657 self.assertEqual(format(-1234, "b"), "-10011010010")
658 self.assertEqual(format(1234, "-b"), "10011010010")
659 self.assertEqual(format(-1234, "-b"), "-10011010010")
660 self.assertEqual(format(1234, " b"), " 10011010010")
661 self.assertEqual(format(-1234, " b"), "-10011010010")
662 self.assertEqual(format(1234, "+b"), "+10011010010")
663 self.assertEqual(format(-1234, "+b"), "-10011010010")
664
Eric Smith8c663262007-08-25 02:26:07 +0000665 # make sure these are errors
666 self.assertRaises(ValueError, format, 3, "1.3") # precision disallowed
Eric Smith8c663262007-08-25 02:26:07 +0000667 self.assertRaises(ValueError, format, 3, "+c") # sign not allowed
668 # with 'c'
Eric Smithfa767ef2008-01-28 10:59:27 +0000669
670 # ensure that only int and float type specifiers work
Eric Smith7b69c6c2008-01-27 21:07:59 +0000671 for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
672 [chr(x) for x in range(ord('A'), ord('Z')+1)]):
Eric Smithfa767ef2008-01-28 10:59:27 +0000673 if not format_spec in 'bcdoxXeEfFgGn%':
Eric Smith7b69c6c2008-01-27 21:07:59 +0000674 self.assertRaises(ValueError, format, 0, format_spec)
675 self.assertRaises(ValueError, format, 1, format_spec)
676 self.assertRaises(ValueError, format, -1, format_spec)
677 self.assertRaises(ValueError, format, 2**100, format_spec)
678 self.assertRaises(ValueError, format, -(2**100), format_spec)
679
Eric Smithfa767ef2008-01-28 10:59:27 +0000680 # ensure that float type specifiers work; format converts
681 # the int to a float
Eric Smith5807c412008-05-11 21:00:57 +0000682 for format_spec in 'eEfFgG%':
Eric Smithfa767ef2008-01-28 10:59:27 +0000683 for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
684 self.assertEqual(format(value, format_spec),
685 format(float(value), format_spec))
Eric Smith8c663262007-08-25 02:26:07 +0000686
Christian Heimesa34706f2008-01-04 03:06:10 +0000687 def test_nan_inf(self):
Christian Heimes1aa7b302008-01-04 03:22:53 +0000688 self.assertRaises(OverflowError, int, float('inf'))
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000689 self.assertRaises(OverflowError, int, float('-inf'))
690 self.assertRaises(ValueError, int, float('nan'))
Christian Heimesa34706f2008-01-04 03:06:10 +0000691
Yury Selivanove0b23092016-02-11 10:26:27 -0500692 def test_mod_division(self):
693 with self.assertRaises(ZeroDivisionError):
694 _ = 1 % 0
695
696 self.assertEqual(13 % 10, 3)
697 self.assertEqual(-13 % 10, 7)
698 self.assertEqual(13 % -10, -7)
699 self.assertEqual(-13 % -10, -3)
700
701 self.assertEqual(12 % 4, 0)
702 self.assertEqual(-12 % 4, 0)
703 self.assertEqual(12 % -4, 0)
704 self.assertEqual(-12 % -4, 0)
705
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000706 def test_true_division(self):
707 huge = 1 << 40000
708 mhuge = -huge
709 self.assertEqual(huge / huge, 1.0)
710 self.assertEqual(mhuge / mhuge, 1.0)
711 self.assertEqual(huge / mhuge, -1.0)
712 self.assertEqual(mhuge / huge, -1.0)
713 self.assertEqual(1 / huge, 0.0)
714 self.assertEqual(1 / huge, 0.0)
715 self.assertEqual(1 / mhuge, 0.0)
716 self.assertEqual(1 / mhuge, 0.0)
717 self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
718 self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
719 self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
720 self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
721 self.assertEqual(huge / (huge << 1), 0.5)
722 self.assertEqual((1000000 * huge) / huge, 1000000)
723
724 namespace = {'huge': huge, 'mhuge': mhuge}
725
726 for overflow in ["float(huge)", "float(mhuge)",
727 "huge / 1", "huge / 2", "huge / -1", "huge / -2",
728 "mhuge / 100", "mhuge / 200"]:
729 self.assertRaises(OverflowError, eval, overflow, namespace)
730
731 for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
732 "100 / mhuge", "200 / mhuge"]:
733 result = eval(underflow, namespace)
734 self.assertEqual(result, 0.0,
735 "expected underflow to 0 from %r" % underflow)
736
737 for zero in ["huge / 0", "mhuge / 0"]:
738 self.assertRaises(ZeroDivisionError, eval, zero, namespace)
739
Yury Selivanove0b23092016-02-11 10:26:27 -0500740 def test_floordiv(self):
741 with self.assertRaises(ZeroDivisionError):
742 _ = 1 // 0
743
744 self.assertEqual(2 // 3, 0)
745 self.assertEqual(2 // -3, -1)
746 self.assertEqual(-2 // 3, -1)
747 self.assertEqual(-2 // -3, 0)
748
749 self.assertEqual(-11 // -3, 3)
750 self.assertEqual(-11 // 3, -4)
751 self.assertEqual(11 // -3, -4)
752 self.assertEqual(11 // 3, 3)
753
754 self.assertEqual(-12 // -3, 4)
755 self.assertEqual(-12 // 3, -4)
756 self.assertEqual(12 // -3, -4)
757 self.assertEqual(12 // 3, 4)
758
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000759 def check_truediv(self, a, b, skip_small=True):
760 """Verify that the result of a/b is correctly rounded, by
761 comparing it with a pure Python implementation of correctly
762 rounded division. b should be nonzero."""
763
764 # skip check for small a and b: in this case, the current
765 # implementation converts the arguments to float directly and
766 # then applies a float division. This can give doubly-rounded
767 # results on x87-using machines (particularly 32-bit Linux).
768 if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
769 return
770
771 try:
772 # use repr so that we can distinguish between -0.0 and 0.0
773 expected = repr(truediv(a, b))
774 except OverflowError:
775 expected = 'overflow'
776 except ZeroDivisionError:
777 expected = 'zerodivision'
778
779 try:
780 got = repr(a / b)
781 except OverflowError:
782 got = 'overflow'
783 except ZeroDivisionError:
784 got = 'zerodivision'
785
Mark Dickinson2cfda802009-12-27 21:34:05 +0000786 self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
787 "expected {}, got {}".format(a, b, expected, got))
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000788
Eric Smith3ab08ca2010-12-04 15:17:38 +0000789 @support.requires_IEEE_754
Mark Dickinsoncbb62742009-12-27 15:09:50 +0000790 def test_correctly_rounded_true_division(self):
791 # more stringent tests than those above, checking that the
792 # result of true division of ints is always correctly rounded.
793 # This test should probably be considered CPython-specific.
794
795 # Exercise all the code paths not involving Gb-sized ints.
796 # ... divisions involving zero
797 self.check_truediv(123, 0)
798 self.check_truediv(-456, 0)
799 self.check_truediv(0, 3)
800 self.check_truediv(0, -3)
801 self.check_truediv(0, 0)
802 # ... overflow or underflow by large margin
803 self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
804 self.check_truediv(12345, 345678 * 2**(DBL_MANT_DIG - DBL_MIN_EXP))
805 # ... a much larger or smaller than b
806 self.check_truediv(12345*2**100, 98765)
807 self.check_truediv(12345*2**30, 98765*7**81)
808 # ... a / b near a boundary: one of 1, 2**DBL_MANT_DIG, 2**DBL_MIN_EXP,
809 # 2**DBL_MAX_EXP, 2**(DBL_MIN_EXP-DBL_MANT_DIG)
810 bases = (0, DBL_MANT_DIG, DBL_MIN_EXP,
811 DBL_MAX_EXP, DBL_MIN_EXP - DBL_MANT_DIG)
812 for base in bases:
813 for exp in range(base - 15, base + 15):
814 self.check_truediv(75312*2**max(exp, 0), 69187*2**max(-exp, 0))
815 self.check_truediv(69187*2**max(exp, 0), 75312*2**max(-exp, 0))
816
817 # overflow corner case
818 for m in [1, 2, 7, 17, 12345, 7**100,
819 -1, -2, -5, -23, -67891, -41**50]:
820 for n in range(-10, 10):
821 self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
822 self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
823
824 # check detection of inexactness in shifting stage
825 for n in range(250):
826 # (2**DBL_MANT_DIG+1)/(2**DBL_MANT_DIG) lies halfway
827 # between two representable floats, and would usually be
828 # rounded down under round-half-to-even. The tiniest of
829 # additions to the numerator should cause it to be rounded
830 # up instead.
831 self.check_truediv((2**DBL_MANT_DIG + 1)*12345*2**200 + 2**n,
832 2**DBL_MANT_DIG*12345)
833
834 # 1/2731 is one of the smallest division cases that's subject
835 # to double rounding on IEEE 754 machines working internally with
836 # 64-bit precision. On such machines, the next check would fail,
837 # were it not explicitly skipped in check_truediv.
838 self.check_truediv(1, 2731)
839
840 # a particularly bad case for the old algorithm: gives an
841 # error of close to 3.5 ulps.
842 self.check_truediv(295147931372582273023, 295147932265116303360)
843 for i in range(1000):
844 self.check_truediv(10**(i+1), 10**i)
845 self.check_truediv(10**i, 10**(i+1))
846
847 # test round-half-to-even behaviour, normal result
848 for m in [1, 2, 4, 7, 8, 16, 17, 32, 12345, 7**100,
849 -1, -2, -5, -23, -67891, -41**50]:
850 for n in range(-10, 10):
851 self.check_truediv(2**DBL_MANT_DIG*m + n, m)
852
853 # test round-half-to-even, subnormal result
854 for n in range(-20, 20):
855 self.check_truediv(n, 2**1076)
856
857 # largeish random divisions: a/b where |a| <= |b| <=
858 # 2*|a|; |ans| is between 0.5 and 1.0, so error should
859 # always be bounded by 2**-54 with equality possible only
860 # if the least significant bit of q=ans*2**53 is zero.
861 for M in [10**10, 10**100, 10**1000]:
862 for i in range(1000):
863 a = random.randrange(1, M)
864 b = random.randrange(a, 2*a+1)
865 self.check_truediv(a, b)
866 self.check_truediv(-a, b)
867 self.check_truediv(a, -b)
868 self.check_truediv(-a, -b)
869
870 # and some (genuinely) random tests
871 for _ in range(10000):
872 a_bits = random.randrange(1000)
873 b_bits = random.randrange(1, 1000)
874 x = random.randrange(2**a_bits)
875 y = random.randrange(1, 2**b_bits)
876 self.check_truediv(x, y)
877 self.check_truediv(x, -y)
878 self.check_truediv(-x, y)
879 self.check_truediv(-x, -y)
Benjamin Peterson875d4c02008-07-13 17:44:16 +0000880
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000881 def test_small_ints(self):
882 for i in range(-5, 257):
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200883 self.assertIs(i, i + 0)
884 self.assertIs(i, i * 1)
885 self.assertIs(i, i - 0)
886 self.assertIs(i, i // 1)
887 self.assertIs(i, i & -1)
888 self.assertIs(i, i | 0)
889 self.assertIs(i, i ^ 0)
890 self.assertIs(i, ~~i)
891 self.assertIs(i, i**1)
892 self.assertIs(i, int(str(i)))
893 self.assertIs(i, i<<2>>2, str(i))
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000894 # corner cases
895 i = 1 << 70
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200896 self.assertIs(i - i, 0)
897 self.assertIs(0 * i, 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +0000898
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000899 def test_bit_length(self):
900 tiny = 1e-10
901 for x in range(-65000, 65000):
902 k = x.bit_length()
903 # Check equivalence with Python version
904 self.assertEqual(k, len(bin(x).lstrip('-0b')))
905 # Behaviour as specified in the docs
906 if x != 0:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000907 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000908 else:
909 self.assertEqual(k, 0)
910 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
911 if x != 0:
912 # When x is an exact power of 2, numeric errors can
913 # cause floor(log(x)/log(2)) to be one too small; for
914 # small x this can be fixed by adding a small quantity
915 # to the quotient before taking the floor.
916 self.assertEqual(k, 1 + math.floor(
917 math.log(abs(x))/math.log(2) + tiny))
918
919 self.assertEqual((0).bit_length(), 0)
920 self.assertEqual((1).bit_length(), 1)
921 self.assertEqual((-1).bit_length(), 1)
922 self.assertEqual((2).bit_length(), 2)
923 self.assertEqual((-2).bit_length(), 2)
924 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
925 a = 2**i
926 self.assertEqual((a-1).bit_length(), i)
927 self.assertEqual((1-a).bit_length(), i)
928 self.assertEqual((a).bit_length(), i+1)
929 self.assertEqual((-a).bit_length(), i+1)
930 self.assertEqual((a+1).bit_length(), i+1)
931 self.assertEqual((-a-1).bit_length(), i+1)
932
Mark Dickinson1124e712009-01-28 21:25:58 +0000933 def test_round(self):
934 # check round-half-even algorithm. For round to nearest ten;
935 # rounding map is invariant under adding multiples of 20
936 test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
937 6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
938 15:20, 16:20, 17:20, 18:20, 19:20}
939 for offset in range(-520, 520, 20):
940 for k, v in test_dict.items():
941 got = round(k+offset, -1)
942 expected = v+offset
943 self.assertEqual(got, expected)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200944 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000945
946 # larger second argument
947 self.assertEqual(round(-150, -2), -200)
948 self.assertEqual(round(-149, -2), -100)
949 self.assertEqual(round(-51, -2), -100)
950 self.assertEqual(round(-50, -2), 0)
951 self.assertEqual(round(-49, -2), 0)
952 self.assertEqual(round(-1, -2), 0)
953 self.assertEqual(round(0, -2), 0)
954 self.assertEqual(round(1, -2), 0)
955 self.assertEqual(round(49, -2), 0)
956 self.assertEqual(round(50, -2), 0)
957 self.assertEqual(round(51, -2), 100)
958 self.assertEqual(round(149, -2), 100)
959 self.assertEqual(round(150, -2), 200)
960 self.assertEqual(round(250, -2), 200)
961 self.assertEqual(round(251, -2), 300)
962 self.assertEqual(round(172500, -3), 172000)
963 self.assertEqual(round(173500, -3), 174000)
964 self.assertEqual(round(31415926535, -1), 31415926540)
965 self.assertEqual(round(31415926535, -2), 31415926500)
966 self.assertEqual(round(31415926535, -3), 31415927000)
967 self.assertEqual(round(31415926535, -4), 31415930000)
968 self.assertEqual(round(31415926535, -5), 31415900000)
969 self.assertEqual(round(31415926535, -6), 31416000000)
970 self.assertEqual(round(31415926535, -7), 31420000000)
971 self.assertEqual(round(31415926535, -8), 31400000000)
972 self.assertEqual(round(31415926535, -9), 31000000000)
973 self.assertEqual(round(31415926535, -10), 30000000000)
974 self.assertEqual(round(31415926535, -11), 0)
975 self.assertEqual(round(31415926535, -12), 0)
976 self.assertEqual(round(31415926535, -999), 0)
977
978 # should get correct results even for huge inputs
979 for k in range(10, 100):
980 got = round(10**k + 324678, -3)
981 expect = 10**k + 325000
982 self.assertEqual(got, expect)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200983 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000984
985 # nonnegative second argument: round(x, n) should just return x
986 for n in range(5):
987 for i in range(100):
988 x = random.randrange(-10000, 10000)
989 got = round(x, n)
990 self.assertEqual(got, x)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +0200991 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +0000992 for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
993 self.assertEqual(round(8979323, huge_n), 8979323)
994
995 # omitted second argument
996 for i in range(100):
997 x = random.randrange(-10000, 10000)
998 got = round(x)
999 self.assertEqual(got, x)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001000 self.assertIs(type(got), int)
Mark Dickinson1124e712009-01-28 21:25:58 +00001001
1002 # bad second argument
1003 bad_exponents = ('brian', 2.0, 0j, None)
1004 for e in bad_exponents:
1005 self.assertRaises(TypeError, round, 3, e)
1006
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001007 def test_to_bytes(self):
1008 def check(tests, byteorder, signed=False):
1009 for test, expected in tests.items():
1010 try:
1011 self.assertEqual(
1012 test.to_bytes(len(expected), byteorder, signed=signed),
1013 expected)
1014 except Exception as err:
1015 raise AssertionError(
1016 "failed to convert {0} with byteorder={1} and signed={2}"
1017 .format(test, byteorder, signed)) from err
1018
1019 # Convert integers to signed big-endian byte arrays.
1020 tests1 = {
1021 0: b'\x00',
1022 1: b'\x01',
1023 -1: b'\xff',
1024 -127: b'\x81',
1025 -128: b'\x80',
1026 -129: b'\xff\x7f',
1027 127: b'\x7f',
1028 129: b'\x00\x81',
1029 -255: b'\xff\x01',
1030 -256: b'\xff\x00',
1031 255: b'\x00\xff',
1032 256: b'\x01\x00',
1033 32767: b'\x7f\xff',
1034 -32768: b'\xff\x80\x00',
1035 65535: b'\x00\xff\xff',
1036 -65536: b'\xff\x00\x00',
1037 -8388608: b'\x80\x00\x00'
1038 }
1039 check(tests1, 'big', signed=True)
1040
1041 # Convert integers to signed little-endian byte arrays.
1042 tests2 = {
1043 0: b'\x00',
1044 1: b'\x01',
1045 -1: b'\xff',
1046 -127: b'\x81',
1047 -128: b'\x80',
1048 -129: b'\x7f\xff',
1049 127: b'\x7f',
1050 129: b'\x81\x00',
1051 -255: b'\x01\xff',
1052 -256: b'\x00\xff',
1053 255: b'\xff\x00',
1054 256: b'\x00\x01',
1055 32767: b'\xff\x7f',
1056 -32768: b'\x00\x80',
1057 65535: b'\xff\xff\x00',
1058 -65536: b'\x00\x00\xff',
1059 -8388608: b'\x00\x00\x80'
1060 }
1061 check(tests2, 'little', signed=True)
1062
1063 # Convert integers to unsigned big-endian byte arrays.
1064 tests3 = {
1065 0: b'\x00',
1066 1: b'\x01',
1067 127: b'\x7f',
1068 128: b'\x80',
1069 255: b'\xff',
1070 256: b'\x01\x00',
1071 32767: b'\x7f\xff',
1072 32768: b'\x80\x00',
1073 65535: b'\xff\xff',
1074 65536: b'\x01\x00\x00'
1075 }
1076 check(tests3, 'big', signed=False)
1077
1078 # Convert integers to unsigned little-endian byte arrays.
1079 tests4 = {
1080 0: b'\x00',
1081 1: b'\x01',
1082 127: b'\x7f',
1083 128: b'\x80',
1084 255: b'\xff',
1085 256: b'\x00\x01',
1086 32767: b'\xff\x7f',
1087 32768: b'\x00\x80',
1088 65535: b'\xff\xff',
1089 65536: b'\x00\x00\x01'
1090 }
1091 check(tests4, 'little', signed=False)
1092
1093 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
1094 self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
1095 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
1096 self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
Victor Stinner3fa1aae2013-03-26 01:14:08 +01001097 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001098 self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
1099 self.assertEqual((0).to_bytes(0, 'big'), b'')
1100 self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
1101 self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
1102 self.assertEqual((-1).to_bytes(5, 'big', signed=True),
1103 b'\xff\xff\xff\xff\xff')
1104 self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1105
1106 def test_from_bytes(self):
1107 def check(tests, byteorder, signed=False):
1108 for test, expected in tests.items():
1109 try:
1110 self.assertEqual(
1111 int.from_bytes(test, byteorder, signed=signed),
1112 expected)
1113 except Exception as err:
1114 raise AssertionError(
1115 "failed to convert {0} with byteorder={1!r} and signed={2}"
1116 .format(test, byteorder, signed)) from err
1117
1118 # Convert signed big-endian byte arrays to integers.
1119 tests1 = {
1120 b'': 0,
1121 b'\x00': 0,
1122 b'\x00\x00': 0,
1123 b'\x01': 1,
1124 b'\x00\x01': 1,
1125 b'\xff': -1,
1126 b'\xff\xff': -1,
1127 b'\x81': -127,
1128 b'\x80': -128,
1129 b'\xff\x7f': -129,
1130 b'\x7f': 127,
1131 b'\x00\x81': 129,
1132 b'\xff\x01': -255,
1133 b'\xff\x00': -256,
1134 b'\x00\xff': 255,
1135 b'\x01\x00': 256,
1136 b'\x7f\xff': 32767,
1137 b'\x80\x00': -32768,
1138 b'\x00\xff\xff': 65535,
1139 b'\xff\x00\x00': -65536,
1140 b'\x80\x00\x00': -8388608
1141 }
1142 check(tests1, 'big', signed=True)
1143
1144 # Convert signed little-endian byte arrays to integers.
1145 tests2 = {
1146 b'': 0,
1147 b'\x00': 0,
1148 b'\x00\x00': 0,
1149 b'\x01': 1,
1150 b'\x00\x01': 256,
1151 b'\xff': -1,
1152 b'\xff\xff': -1,
1153 b'\x81': -127,
1154 b'\x80': -128,
1155 b'\x7f\xff': -129,
1156 b'\x7f': 127,
1157 b'\x81\x00': 129,
1158 b'\x01\xff': -255,
1159 b'\x00\xff': -256,
1160 b'\xff\x00': 255,
1161 b'\x00\x01': 256,
1162 b'\xff\x7f': 32767,
1163 b'\x00\x80': -32768,
1164 b'\xff\xff\x00': 65535,
1165 b'\x00\x00\xff': -65536,
1166 b'\x00\x00\x80': -8388608
1167 }
1168 check(tests2, 'little', signed=True)
1169
1170 # Convert unsigned big-endian byte arrays to integers.
1171 tests3 = {
1172 b'': 0,
1173 b'\x00': 0,
1174 b'\x01': 1,
1175 b'\x7f': 127,
1176 b'\x80': 128,
1177 b'\xff': 255,
1178 b'\x01\x00': 256,
1179 b'\x7f\xff': 32767,
1180 b'\x80\x00': 32768,
1181 b'\xff\xff': 65535,
1182 b'\x01\x00\x00': 65536,
1183 }
1184 check(tests3, 'big', signed=False)
1185
1186 # Convert integers to unsigned little-endian byte arrays.
1187 tests4 = {
1188 b'': 0,
1189 b'\x00': 0,
1190 b'\x01': 1,
1191 b'\x7f': 127,
1192 b'\x80': 128,
1193 b'\xff': 255,
1194 b'\x00\x01': 256,
1195 b'\xff\x7f': 32767,
1196 b'\x00\x80': 32768,
1197 b'\xff\xff': 65535,
1198 b'\x00\x00\x01': 65536,
1199 }
1200 check(tests4, 'little', signed=False)
1201
1202 class myint(int):
1203 pass
1204
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001205 self.assertIs(type(myint.from_bytes(b'\x00', 'big')), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001206 self.assertEqual(myint.from_bytes(b'\x01', 'big'), 1)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001207 self.assertIs(
1208 type(myint.from_bytes(b'\x00', 'big', signed=False)), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001209 self.assertEqual(myint.from_bytes(b'\x01', 'big', signed=False), 1)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001210 self.assertIs(type(myint.from_bytes(b'\x00', 'little')), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001211 self.assertEqual(myint.from_bytes(b'\x01', 'little'), 1)
Serhiy Storchaka3a20a5d2014-02-08 14:28:33 +02001212 self.assertIs(type(myint.from_bytes(
1213 b'\x00', 'little', signed=False)), myint)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00001214 self.assertEqual(myint.from_bytes(b'\x01', 'little', signed=False), 1)
1215 self.assertEqual(
1216 int.from_bytes([255, 0, 0], 'big', signed=True), -65536)
1217 self.assertEqual(
1218 int.from_bytes((255, 0, 0), 'big', signed=True), -65536)
1219 self.assertEqual(int.from_bytes(
1220 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1221 self.assertEqual(int.from_bytes(
1222 bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1223 self.assertEqual(int.from_bytes(
1224 array.array('B', b'\xff\x00\x00'), 'big', signed=True), -65536)
1225 self.assertEqual(int.from_bytes(
1226 memoryview(b'\xff\x00\x00'), 'big', signed=True), -65536)
1227 self.assertRaises(ValueError, int.from_bytes, [256], 'big')
1228 self.assertRaises(ValueError, int.from_bytes, [0], 'big\x00')
1229 self.assertRaises(ValueError, int.from_bytes, [0], 'little\x00')
1230 self.assertRaises(TypeError, int.from_bytes, "", 'big')
1231 self.assertRaises(TypeError, int.from_bytes, "\x00", 'big')
1232 self.assertRaises(TypeError, int.from_bytes, 0, 'big')
1233 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1234 self.assertRaises(TypeError, myint.from_bytes, "", 'big')
1235 self.assertRaises(TypeError, myint.from_bytes, "\x00", 'big')
1236 self.assertRaises(TypeError, myint.from_bytes, 0, 'big')
1237 self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
Mark Dickinson1124e712009-01-28 21:25:58 +00001238
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +01001239 def test_access_to_nonexistent_digit_0(self):
1240 # http://bugs.python.org/issue14630: A bug in _PyLong_Copy meant that
1241 # ob_digit[0] was being incorrectly accessed for instances of a
1242 # subclass of int, with value 0.
1243 class Integer(int):
1244 def __new__(cls, value=0):
1245 self = int.__new__(cls, value)
1246 self.foo = 'foo'
1247 return self
1248
1249 integers = [Integer(0) for i in range(1000)]
1250 for n in map(int, integers):
1251 self.assertEqual(n, 0)
1252
Victor Stinner7fe10492014-05-12 22:35:40 +02001253 def test_shift_bool(self):
1254 # Issue #21422: ensure that bool << int and bool >> int return int
1255 for value in (True, False):
1256 for shift in (0, 2):
1257 self.assertEqual(type(value << shift), int)
1258 self.assertEqual(type(value >> shift), int)
1259
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00001260
Walter Dörwalda0021592005-06-13 21:44:48 +00001261if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -05001262 unittest.main()