2 from test
import test_support
8 # Used for lazy formatting of failure messages
10 def __init__(self
, format
, *args
):
15 return self
.format
% self
.args
17 # SHIFT should match the value in longintrepr.h for best testing.
18 SHIFT
= sys
.long_info
.bits_per_digit
21 KARATSUBA_CUTOFF
= 70 # from longobject.c
23 # Max number of base BASE digits to use in test cases. Doubling
24 # this will more than double the runtime.
27 # build some special values
28 special
= map(long, [0, 1, 2, BASE
, BASE
>> 1])
29 special
.append(0x5555555555555555L
)
30 special
.append(0xaaaaaaaaaaaaaaaaL
)
31 # some solid strings of one bits
32 p2
= 4L # 0 and 1 already added
33 for i
in range(2*SHIFT
):
34 special
.append(p2
- 1)
37 # add complements & negations
38 special
= special
+ map(lambda x
: ~x
, special
) + \
39 map(lambda x
: -x
, special
)
51 (' \t\t 314 \t\t ', 314),
52 (repr(sys
.maxint
), sys
.maxint
),
55 (' 1\02 ', ValueError),
58 (' \t\t ', ValueError)
60 if test_support
.have_unicode
:
67 (unicode('100'), 100),
68 (unicode('314'), 314),
69 (unicode(' 314'), 314),
70 (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
71 (unicode(' \t\t 314 \t\t '), 314),
72 (unicode(' 1x'), ValueError),
74 (unicode(' 1\02 '), ValueError),
75 (unicode(''), ValueError),
76 (unicode(' '), ValueError),
77 (unicode(' \t\t '), ValueError),
78 (unichr(0x200), ValueError),
82 class LongTest(unittest
.TestCase
):
84 # Get quasi-random long consisting of ndigits digits (in base BASE).
85 # quasi == the most-significant digit will not be 0, and the number
86 # is constructed to contain long strings of 0 and 1 bits. These are
87 # more likely than random bits to provoke digit-boundary errors.
88 # The sign of the number is also random.
90 def getran(self
, ndigits
):
91 self
.assertTrue(ndigits
> 0)
92 nbits_hi
= ndigits
* SHIFT
93 nbits_lo
= nbits_hi
- SHIFT
+ 1
96 r
= int(random
.random() * (SHIFT
* 2)) |
1 # force 1 bits to start
97 while nbits
< nbits_lo
:
99 bits
= min(bits
, nbits_hi
- nbits
)
100 self
.assertTrue(1 <= bits
<= SHIFT
)
102 answer
= answer
<< bits
104 answer
= answer |
((1 << bits
) - 1)
105 r
= int(random
.random() * (SHIFT
* 2))
106 self
.assertTrue(nbits_lo
<= nbits
<= nbits_hi
)
107 if random
.random() < 0.5:
111 # Get random long consisting of ndigits random digits (relative to base
112 # BASE). The sign bit is also random.
114 def getran2(ndigits
):
116 for i
in xrange(ndigits
):
117 answer
= (answer
<< SHIFT
) | random
.randint(0, MASK
)
118 if random
.random() < 0.5:
122 def check_division(self
, x
, y
):
123 eq
= self
.assertEqual
127 eq(pab
, pba
, Frm("multiplication does not commute for %r and %r", x
, y
))
128 eq(q
, q2
, Frm("divmod returns different quotient than / for %r and %r", x
, y
))
129 eq(r
, r2
, Frm("divmod returns different mod than %% for %r and %r", x
, y
))
130 eq(x
, q
*y
+ r
, Frm("x != q*y + r after divmod on x=%r, y=%r", x
, y
))
132 self
.assertTrue(0 <= r
< y
, Frm("bad mod from divmod on %r and %r", x
, y
))
134 self
.assertTrue(y
< r
<= 0, Frm("bad mod from divmod on %r and %r", x
, y
))
136 def test_division(self
):
137 digits
= range(1, MAXDIGITS
+1) + range(KARATSUBA_CUTOFF
,
138 KARATSUBA_CUTOFF
+ 14)
139 digits
.append(KARATSUBA_CUTOFF
* 3)
141 x
= self
.getran(lenx
)
143 y
= self
.getran(leny
) or 1L
144 self
.check_division(x
, y
)
146 # specific numbers chosen to exercise corner cases of the
147 # current long division implementation
149 # 30-bit cases involving a quotient digit estimate of BASE+1
150 self
.check_division(1231948412290879395966702881L,
151 1147341367131428698L)
152 self
.check_division(815427756481275430342312021515587883L,
154 self
.check_division(627976073697012820849443363563599041L,
156 self
.check_division(1115141373653752303710932756325578065L,
157 1038556335171453937726882627L)
158 # 30-bit cases that require the post-subtraction correction step
159 self
.check_division(922498905405436751940989320930368494L,
160 949985870686786135626943396L)
161 self
.check_division(768235853328091167204009652174031844L,
162 1091555541180371554426545266L)
164 # 15-bit cases involving a quotient digit estimate of BASE+1
165 self
.check_division(20172188947443L, 615611397L)
166 self
.check_division(1020908530270155025L, 950795710L)
167 self
.check_division(128589565723112408L, 736393718L)
168 self
.check_division(609919780285761575L, 18613274546784L)
169 # 15-bit cases that require the post-subtraction correction step
170 self
.check_division(710031681576388032L, 26769404391308L)
171 self
.check_division(1933622614268221L, 30212853348836L)
175 def test_karatsuba(self
):
176 digits
= range(1, 5) + range(KARATSUBA_CUTOFF
, KARATSUBA_CUTOFF
+ 10)
177 digits
.extend([KARATSUBA_CUTOFF
* 10, KARATSUBA_CUTOFF
* 100])
179 bits
= [digit
* SHIFT
for digit
in digits
]
181 # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
182 # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
184 a
= (1L << abits
) - 1
188 b
= (1L << bbits
) - 1
190 y
= ((1L << (abits
+ bbits
)) -
194 self
.assertEqual(x
, y
,
195 Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a
, b
, x
, y
))
197 def check_bitop_identities_1(self
, x
):
198 eq
= self
.assertEqual
199 eq(x
& 0, 0, Frm("x & 0 != 0 for x=%r", x
))
200 eq(x |
0, x
, Frm("x | 0 != x for x=%r", x
))
201 eq(x ^
0, x
, Frm("x ^ 0 != x for x=%r", x
))
202 eq(x
& -1, x
, Frm("x & -1 != x for x=%r", x
))
203 eq(x |
-1, -1, Frm("x | -1 != -1 for x=%r", x
))
204 eq(x ^
-1, ~x
, Frm("x ^ -1 != ~x for x=%r", x
))
205 eq(x
, ~~x
, Frm("x != ~~x for x=%r", x
))
206 eq(x
& x
, x
, Frm("x & x != x for x=%r", x
))
207 eq(x | x
, x
, Frm("x | x != x for x=%r", x
))
208 eq(x ^ x
, 0, Frm("x ^ x != 0 for x=%r", x
))
209 eq(x
& ~x
, 0, Frm("x & ~x != 0 for x=%r", x
))
210 eq(x | ~x
, -1, Frm("x | ~x != -1 for x=%r", x
))
211 eq(x ^ ~x
, -1, Frm("x ^ ~x != -1 for x=%r", x
))
212 eq(-x
, 1 + ~x
, Frm("not -x == 1 + ~x for x=%r", x
))
213 eq(-x
, ~
(x
-1), Frm("not -x == ~(x-1) forx =%r", x
))
214 for n
in xrange(2*SHIFT
):
217 Frm("x << n >> n != x for x=%r, n=%r", (x
, n
)))
219 Frm("x // p2 != x >> n for x=%r n=%r p2=%r", (x
, n
, p2
)))
221 Frm("x * p2 != x << n for x=%r n=%r p2=%r", (x
, n
, p2
)))
222 eq(x
& -p2
, x
>> n
<< n
,
223 Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", (x
, n
, p2
)))
224 eq(x
& -p2
, x
& ~
(p2
- 1),
225 Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", (x
, n
, p2
)))
227 def check_bitop_identities_2(self
, x
, y
):
228 eq
= self
.assertEqual
229 eq(x
& y
, y
& x
, Frm("x & y != y & x for x=%r, y=%r", (x
, y
)))
230 eq(x | y
, y | x
, Frm("x | y != y | x for x=%r, y=%r", (x
, y
)))
231 eq(x ^ y
, y ^ x
, Frm("x ^ y != y ^ x for x=%r, y=%r", (x
, y
)))
232 eq(x ^ y ^ x
, y
, Frm("x ^ y ^ x != y for x=%r, y=%r", (x
, y
)))
233 eq(x
& y
, ~
(~x | ~y
), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", (x
, y
)))
234 eq(x | y
, ~
(~x
& ~y
), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", (x
, y
)))
235 eq(x ^ y
, (x | y
) & ~
(x
& y
),
236 Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", (x
, y
)))
237 eq(x ^ y
, (x
& ~y
) |
(~x
& y
),
238 Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", (x
, y
)))
239 eq(x ^ y
, (x | y
) & (~x | ~y
),
240 Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", (x
, y
)))
242 def check_bitop_identities_3(self
, x
, y
, z
):
243 eq
= self
.assertEqual
244 eq((x
& y
) & z
, x
& (y
& z
),
245 Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", (x
, y
, z
)))
246 eq((x | y
) | z
, x |
(y | z
),
247 Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", (x
, y
, z
)))
248 eq((x ^ y
) ^ z
, x ^
(y ^ z
),
249 Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", (x
, y
, z
)))
250 eq(x
& (y | z
), (x
& y
) |
(x
& z
),
251 Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", (x
, y
, z
)))
252 eq(x |
(y
& z
), (x | y
) & (x | z
),
253 Frm("x | (y & z) != (x | y) & (x | z) for x=%r, y=%r, z=%r", (x
, y
, z
)))
255 def test_bitop_identities(self
):
257 self
.check_bitop_identities_1(x
)
258 digits
= xrange(1, MAXDIGITS
+1)
260 x
= self
.getran(lenx
)
261 self
.check_bitop_identities_1(x
)
263 y
= self
.getran(leny
)
264 self
.check_bitop_identities_2(x
, y
)
265 self
.check_bitop_identities_3(x
, y
, self
.getran((lenx
+ leny
)//2))
267 def slow_format(self
, x
, base
):
268 if (x
, base
) == (0, 8):
269 # this is an oddball!
276 x
, r
= divmod(x
, base
)
277 digits
.append(int(r
))
279 digits
= digits
or [0]
280 return '-'[:sign
] + \
281 {8: '0', 10: '', 16: '0x'}[base
] + \
282 "".join(map(lambda i
: "0123456789abcdef"[i
], digits
)) + "L"
284 def check_format_1(self
, x
):
285 for base
, mapper
in (8, oct), (10, repr), (16, hex):
287 expected
= self
.slow_format(x
, base
)
288 msg
= Frm("%s returned %r but expected %r for %r",
289 mapper
.__name
__, got
, expected
, x
)
290 self
.assertEqual(got
, expected
, msg
)
291 self
.assertEqual(long(got
, 0), x
, Frm('long("%s", 0) != %r', got
, x
))
292 # str() has to be checked a little differently since there's no
295 expected
= self
.slow_format(x
, 10)[:-1]
296 msg
= Frm("%s returned %r but expected %r for %r",
297 mapper
.__name
__, got
, expected
, x
)
298 self
.assertEqual(got
, expected
, msg
)
300 def test_format(self
):
302 self
.check_format_1(x
)
304 for lenx
in xrange(1, MAXDIGITS
+1):
305 x
= self
.getran(lenx
)
306 self
.check_format_1(x
)
309 self
.assertEqual(long(314), 314L)
310 self
.assertEqual(long(3.14), 3L)
311 self
.assertEqual(long(314L), 314L)
312 # Check that long() of basic types actually returns a long
313 self
.assertEqual(type(long(314)), long)
314 self
.assertEqual(type(long(3.14)), long)
315 self
.assertEqual(type(long(314L)), long)
316 # Check that conversion from float truncates towards zero
317 self
.assertEqual(long(-3.14), -3L)
318 self
.assertEqual(long(3.9), 3L)
319 self
.assertEqual(long(-3.9), -3L)
320 self
.assertEqual(long(3.5), 3L)
321 self
.assertEqual(long(-3.5), -3L)
322 self
.assertEqual(long("-3"), -3L)
323 self
.assertEqual(long("0b10", 2), 2L)
324 self
.assertEqual(long("0o10", 8), 8L)
325 self
.assertEqual(long("0x10", 16), 16L)
326 if test_support
.have_unicode
:
327 self
.assertEqual(long(unicode("-3")), -3L)
329 self
.assertEqual(long("10",16), 16L)
330 if test_support
.have_unicode
:
331 self
.assertEqual(long(unicode("10"),16), 16L)
332 # Check conversions from string (same test set as for int(), and then some)
334 ('1' + '0'*20, 10L**20),
335 ('1' + '0'*100, 10L**100)
338 if test_support
.have_unicode
:
340 (unicode('1') + unicode('0')*20, 10L**20),
341 (unicode('1') + unicode('0')*100, 10L**100),
344 for sign
in "", "+", "-":
345 for prefix
in "", " ", "\t", " \t\t ":
346 ss
= prefix
+ sign
+ s
348 if sign
== "-" and v
is not ValueError:
351 self
.assertEqual(long(ss
), long(vv
))
355 self
.assertRaises(ValueError, long, '123\0')
356 self
.assertRaises(ValueError, long, '53', 40)
357 self
.assertRaises(TypeError, long, 1, 12)
360 self
.assertEqual(long(' 0123 ', 0), 83)
361 self
.assertEqual(long(' 0123 ', 0), 83)
362 self
.assertEqual(long('000', 0), 0)
363 self
.assertEqual(long('0o123', 0), 83)
364 self
.assertEqual(long('0x123', 0), 291)
365 self
.assertEqual(long('0b100', 0), 4)
366 self
.assertEqual(long(' 0O123 ', 0), 83)
367 self
.assertEqual(long(' 0X123 ', 0), 291)
368 self
.assertEqual(long(' 0B100 ', 0), 4)
369 self
.assertEqual(long('0', 0), 0)
370 self
.assertEqual(long('+0', 0), 0)
371 self
.assertEqual(long('-0', 0), 0)
372 self
.assertEqual(long('00', 0), 0)
373 self
.assertRaises(ValueError, long, '08', 0)
374 self
.assertRaises(ValueError, long, '-012395', 0)
376 # SF patch #1638879: embedded NULs were not detected with
378 self
.assertRaises(ValueError, long, '123\0', 10)
379 self
.assertRaises(ValueError, long, '123\x00 245', 20)
381 self
.assertEqual(long('100000000000000000000000000000000', 2),
383 self
.assertEqual(long('102002022201221111211', 3), 4294967296)
384 self
.assertEqual(long('10000000000000000', 4), 4294967296)
385 self
.assertEqual(long('32244002423141', 5), 4294967296)
386 self
.assertEqual(long('1550104015504', 6), 4294967296)
387 self
.assertEqual(long('211301422354', 7), 4294967296)
388 self
.assertEqual(long('40000000000', 8), 4294967296)
389 self
.assertEqual(long('12068657454', 9), 4294967296)
390 self
.assertEqual(long('4294967296', 10), 4294967296)
391 self
.assertEqual(long('1904440554', 11), 4294967296)
392 self
.assertEqual(long('9ba461594', 12), 4294967296)
393 self
.assertEqual(long('535a79889', 13), 4294967296)
394 self
.assertEqual(long('2ca5b7464', 14), 4294967296)
395 self
.assertEqual(long('1a20dcd81', 15), 4294967296)
396 self
.assertEqual(long('100000000', 16), 4294967296)
397 self
.assertEqual(long('a7ffda91', 17), 4294967296)
398 self
.assertEqual(long('704he7g4', 18), 4294967296)
399 self
.assertEqual(long('4f5aff66', 19), 4294967296)
400 self
.assertEqual(long('3723ai4g', 20), 4294967296)
401 self
.assertEqual(long('281d55i4', 21), 4294967296)
402 self
.assertEqual(long('1fj8b184', 22), 4294967296)
403 self
.assertEqual(long('1606k7ic', 23), 4294967296)
404 self
.assertEqual(long('mb994ag', 24), 4294967296)
405 self
.assertEqual(long('hek2mgl', 25), 4294967296)
406 self
.assertEqual(long('dnchbnm', 26), 4294967296)
407 self
.assertEqual(long('b28jpdm', 27), 4294967296)
408 self
.assertEqual(long('8pfgih4', 28), 4294967296)
409 self
.assertEqual(long('76beigg', 29), 4294967296)
410 self
.assertEqual(long('5qmcpqg', 30), 4294967296)
411 self
.assertEqual(long('4q0jto4', 31), 4294967296)
412 self
.assertEqual(long('4000000', 32), 4294967296)
413 self
.assertEqual(long('3aokq94', 33), 4294967296)
414 self
.assertEqual(long('2qhxjli', 34), 4294967296)
415 self
.assertEqual(long('2br45qb', 35), 4294967296)
416 self
.assertEqual(long('1z141z4', 36), 4294967296)
418 self
.assertEqual(long('100000000000000000000000000000001', 2),
420 self
.assertEqual(long('102002022201221111212', 3), 4294967297)
421 self
.assertEqual(long('10000000000000001', 4), 4294967297)
422 self
.assertEqual(long('32244002423142', 5), 4294967297)
423 self
.assertEqual(long('1550104015505', 6), 4294967297)
424 self
.assertEqual(long('211301422355', 7), 4294967297)
425 self
.assertEqual(long('40000000001', 8), 4294967297)
426 self
.assertEqual(long('12068657455', 9), 4294967297)
427 self
.assertEqual(long('4294967297', 10), 4294967297)
428 self
.assertEqual(long('1904440555', 11), 4294967297)
429 self
.assertEqual(long('9ba461595', 12), 4294967297)
430 self
.assertEqual(long('535a7988a', 13), 4294967297)
431 self
.assertEqual(long('2ca5b7465', 14), 4294967297)
432 self
.assertEqual(long('1a20dcd82', 15), 4294967297)
433 self
.assertEqual(long('100000001', 16), 4294967297)
434 self
.assertEqual(long('a7ffda92', 17), 4294967297)
435 self
.assertEqual(long('704he7g5', 18), 4294967297)
436 self
.assertEqual(long('4f5aff67', 19), 4294967297)
437 self
.assertEqual(long('3723ai4h', 20), 4294967297)
438 self
.assertEqual(long('281d55i5', 21), 4294967297)
439 self
.assertEqual(long('1fj8b185', 22), 4294967297)
440 self
.assertEqual(long('1606k7id', 23), 4294967297)
441 self
.assertEqual(long('mb994ah', 24), 4294967297)
442 self
.assertEqual(long('hek2mgm', 25), 4294967297)
443 self
.assertEqual(long('dnchbnn', 26), 4294967297)
444 self
.assertEqual(long('b28jpdn', 27), 4294967297)
445 self
.assertEqual(long('8pfgih5', 28), 4294967297)
446 self
.assertEqual(long('76beigh', 29), 4294967297)
447 self
.assertEqual(long('5qmcpqh', 30), 4294967297)
448 self
.assertEqual(long('4q0jto5', 31), 4294967297)
449 self
.assertEqual(long('4000001', 32), 4294967297)
450 self
.assertEqual(long('3aokq95', 33), 4294967297)
451 self
.assertEqual(long('2qhxjlj', 34), 4294967297)
452 self
.assertEqual(long('2br45qc', 35), 4294967297)
453 self
.assertEqual(long('1z141z5', 36), 4294967297)
456 def test_conversion(self
):
458 class ClassicMissingMethods
:
460 self
.assertRaises(AttributeError, long, ClassicMissingMethods())
462 class MissingMethods(object):
464 self
.assertRaises(TypeError, long, MissingMethods())
490 self
.assertEqual(long(Foo0()), 42L)
491 self
.assertEqual(long(Foo1()), 42L)
492 self
.assertEqual(long(Foo2()), 42L)
493 self
.assertEqual(long(Foo3()), 0)
494 self
.assertEqual(long(Foo4()), 42)
495 self
.assertRaises(TypeError, long, Foo5())
499 for base
in (object, Classic
):
500 class LongOverridesTrunc(base
):
505 self
.assertEqual(long(LongOverridesTrunc()), 42)
507 class JustTrunc(base
):
510 self
.assertEqual(long(JustTrunc()), 42)
512 for trunc_result_base
in (object, Classic
):
513 class Integral(trunc_result_base
):
517 class TruncReturnsNonLong(base
):
520 self
.assertEqual(long(TruncReturnsNonLong()), 42)
522 class NonIntegral(trunc_result_base
):
524 # Check that we avoid infinite recursion.
527 class TruncReturnsNonIntegral(base
):
531 long(TruncReturnsNonIntegral())
532 except TypeError as e
:
533 self
.assertEquals(str(e
),
534 "__trunc__ returned non-Integral"
535 " (type NonIntegral)")
537 self
.fail("Failed to raise TypeError with %s" %
538 ((base
, trunc_result_base
),))
542 # check the extremes in int<->long conversion
544 hugeneg
= -hugepos
- 1
545 hugepos_aslong
= long(hugepos
)
546 hugeneg_aslong
= long(hugeneg
)
547 self
.assertEqual(hugepos
, hugepos_aslong
, "long(sys.maxint) != sys.maxint")
548 self
.assertEqual(hugeneg
, hugeneg_aslong
,
549 "long(-sys.maxint-1) != -sys.maxint-1")
551 # long -> int should not fail for hugepos_aslong or hugeneg_aslong
552 x
= int(hugepos_aslong
)
554 self
.assertEqual(x
, hugepos
,
555 "converting sys.maxint to long and back to int fails")
556 except OverflowError:
557 self
.fail("int(long(sys.maxint)) overflowed!")
558 if not isinstance(x
, int):
559 self
.fail("int(long(sys.maxint)) should have returned int")
560 x
= int(hugeneg_aslong
)
562 self
.assertEqual(x
, hugeneg
,
563 "converting -sys.maxint-1 to long and back to int fails")
564 except OverflowError:
565 self
.fail("int(long(-sys.maxint-1)) overflowed!")
566 if not isinstance(x
, int):
567 self
.fail("int(long(-sys.maxint-1)) should have returned int")
568 # but long -> int should overflow for hugepos+1 and hugeneg-1
569 x
= hugepos_aslong
+ 1
572 except OverflowError:
573 self
.fail("int(long(sys.maxint) + 1) mustn't overflow")
574 self
.assertIsInstance(y
, long,
575 "int(long(sys.maxint) + 1) should have returned long")
577 x
= hugeneg_aslong
- 1
580 except OverflowError:
581 self
.fail("int(long(-sys.maxint-1) - 1) mustn't overflow")
582 self
.assertIsInstance(y
, long,
583 "int(long(-sys.maxint-1) - 1) should have returned long")
589 self
.assertTrue(type(y
) is long,
590 "overflowing int conversion must return long not long subtype")
592 # long -> Py_ssize_t conversion
594 def __getslice__(self
, i
, j
):
597 with test_support
.check_py3k_warnings():
598 self
.assertEqual(X()[-5L:7L], (-5, 7))
599 # use the clamping effect to test the smallest and largest longs
600 # that fit a Py_ssize_t
601 slicemin
, slicemax
= X()[-2L**100:2L**100]
602 self
.assertEqual(X()[slicemin
:slicemax
], (slicemin
, slicemax
))
604 # ----------------------------------- tests of auto int->long conversion
606 def test_auto_overflow(self
):
607 special
= [0, 1, 2, 3, sys
.maxint
-1, sys
.maxint
, sys
.maxint
+1]
608 sqrt
= int(math
.sqrt(sys
.maxint
))
609 special
.extend([sqrt
-1, sqrt
, sqrt
+1])
610 special
.extend([-i
for i
in special
])
613 # Heavy use of nested scopes here!
614 self
.assertEqual(got
, expected
,
615 Frm("for %r expected %r got %r", args
, expected
, got
))
627 expected
= longx
+ longy
631 expected
= longx
- longy
635 expected
= longx
* longy
640 with test_support
.check_py3k_warnings():
641 expected
= longx
/ longy
645 expected
= longx
// longy
649 expected
= divmod(longx
, longy
)
650 got
= divmod(longx
, longy
)
651 checkit(x
, 'divmod', y
)
653 if abs(y
) < 5 and not (x
== 0 and y
< 0):
654 expected
= longx
** longy
661 expected
= pow(longx
, longy
, long(z
))
663 checkit('pow', x
, y
, '%', z
)
665 self
.assertRaises(TypeError, pow,longx
, longy
, long(z
))
667 @unittest.skipUnless(float.__getformat
__("double").startswith("IEEE"),
668 "test requires IEEE 754 doubles")
669 def test_float_conversion(self
):
671 DBL_MAX
= sys
.float_info
.max
672 DBL_MAX_EXP
= sys
.float_info
.max_exp
673 DBL_MANT_DIG
= sys
.float_info
.mant_dig
675 exact_values
= [0L, 1L, 2L,
685 for x
in exact_values
:
686 self
.assertEqual(long(float(x
)), x
)
687 self
.assertEqual(long(float(-x
)), -x
)
689 # test round-half-even
690 for x
, y
in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
692 self
.assertEqual(long(float(2L**p
*(2**53+x
))), 2L**p
*(2**53+y
))
694 for x
, y
in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
695 (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
696 (13, 12), (14, 16), (15, 16)]:
698 self
.assertEqual(long(float(2L**p
*(2**54+x
))), 2L**p
*(2**54+y
))
700 # behaviour near extremes of floating-point range
701 long_dbl_max
= long(DBL_MAX
)
702 top_power
= 2**DBL_MAX_EXP
703 halfway
= (long_dbl_max
+ top_power
)//2
704 self
.assertEqual(float(long_dbl_max
), DBL_MAX
)
705 self
.assertEqual(float(long_dbl_max
+1), DBL_MAX
)
706 self
.assertEqual(float(halfway
-1), DBL_MAX
)
707 self
.assertRaises(OverflowError, float, halfway
)
708 self
.assertEqual(float(1-halfway
), -DBL_MAX
)
709 self
.assertRaises(OverflowError, float, -halfway
)
710 self
.assertRaises(OverflowError, float, top_power
-1)
711 self
.assertRaises(OverflowError, float, top_power
)
712 self
.assertRaises(OverflowError, float, top_power
+1)
713 self
.assertRaises(OverflowError, float, 2*top_power
-1)
714 self
.assertRaises(OverflowError, float, 2*top_power
)
715 self
.assertRaises(OverflowError, float, top_power
*top_power
)
717 for p
in xrange(100):
718 x
= long(2**p
* (2**53 + 1) + 1)
719 y
= long(2**p
* (2**53+ 2))
720 self
.assertEqual(long(float(x
)), y
)
722 x
= long(2**p
* (2**53 + 1))
723 y
= long(2**p
* 2**53)
724 self
.assertEqual(long(float(x
)), y
)
726 def test_float_overflow(self
):
727 for x
in -2.0, -1.0, 0.0, 1.0, 2.0:
728 self
.assertEqual(float(long(x
)), x
)
730 shuge
= '12345' * 120
733 namespace
= {'huge': huge
, 'mhuge': mhuge
, 'shuge': shuge
, 'math': math
}
734 for test
in ["float(huge)", "float(mhuge)",
735 "complex(huge)", "complex(mhuge)",
736 "complex(huge, 1)", "complex(mhuge, 1)",
737 "complex(1, huge)", "complex(1, mhuge)",
738 "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
739 "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
740 "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
741 "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
742 "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
743 "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
744 "math.sin(huge)", "math.sin(mhuge)",
745 "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
746 "math.floor(huge)", "math.floor(mhuge)"]:
748 self
.assertRaises(OverflowError, eval, test
, namespace
)
750 # XXX Perhaps float(shuge) can raise OverflowError on some box?
751 # The comparison should not.
752 self
.assertNotEqual(float(shuge
), int(shuge
),
753 "float(shuge) should not equal int(shuge)")
756 LOG10E
= math
.log10(math
.e
)
758 for exp
in range(10) + [100, 1000, 10000]:
760 log10
= math
.log10(value
)
761 self
.assertAlmostEqual(log10
, exp
)
763 # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
765 expected
= exp
/ LOG10E
766 log
= math
.log(value
)
767 self
.assertAlmostEqual(log
, expected
)
769 for bad
in -(1L << 10000), -2L, 0L:
770 self
.assertRaises(ValueError, math
.log
, bad
)
771 self
.assertRaises(ValueError, math
.log10
, bad
)
773 def test_mixed_compares(self
):
774 eq
= self
.assertEqual
776 # We're mostly concerned with that mixing floats and longs does the
777 # right stuff, even when longs are too large to fit in a float.
778 # The safest way to check the results is to use an entirely different
779 # method, which we do here via a skeletal rational class (which
780 # represents all Python ints, longs and floats exactly).
782 def __init__(self
, value
):
783 if isinstance(value
, (int, long)):
786 elif isinstance(value
, float):
787 # Convert to exact rational equivalent.
788 f
, e
= math
.frexp(abs(value
))
789 assert f
== 0 or 0.5 <= f
< 1.0
790 # |value| = f * 2**e exactly
792 # Suck up CHUNK bits at a time; 28 is enough so that we suck
793 # up all bits in 2 iterations for all known binary double-
794 # precision formats, and small enough to fit in an int.
797 # invariant: |value| = (top + f) * 2**e exactly
799 f
= math
.ldexp(f
, CHUNK
)
801 assert digit
>> CHUNK
== 0
802 top
= (top
<< CHUNK
) | digit
804 assert 0.0 <= f
< 1.0
807 # Now |value| = top * 2**e exactly.
818 assert float(n
) / float(d
) == value
820 raise TypeError("can't deal with %r" % value
)
822 def __cmp__(self
, other
):
823 if not isinstance(other
, Rat
):
825 return cmp(self
.n
* other
.d
, self
.d
* other
.n
)
827 cases
= [0, 0.001, 0.99, 1.0, 1.5, 1e20
, 1e200
]
828 # 2**48 is an important boundary in the internals. 2**53 is an
829 # important boundary for IEEE double precision.
830 for t
in 2.0**48, 2.0**50, 2.0**53:
831 cases
.extend([t
- 1.0, t
- 0.3, t
, t
+ 0.3, t
+ 1.0,
832 long(t
-1), long(t
), long(t
+1)])
833 cases
.extend([0, 1, 2, sys
.maxint
, float(sys
.maxint
)])
834 # 1L<<20000 should exceed all double formats. long(1e200) is to
835 # check that we get equality with 1e200 above.
837 cases
.extend([0L, 1L, 2L, 1L << 20000, t
-1, t
, t
+1])
838 cases
.extend([-x
for x
in cases
])
845 eq(Rcmp
, xycmp
, Frm("%r %r %d %d", x
, y
, Rcmp
, xycmp
))
846 eq(x
== y
, Rcmp
== 0, Frm("%r == %r %d", x
, y
, Rcmp
))
847 eq(x
!= y
, Rcmp
!= 0, Frm("%r != %r %d", x
, y
, Rcmp
))
848 eq(x
< y
, Rcmp
< 0, Frm("%r < %r %d", x
, y
, Rcmp
))
849 eq(x
<= y
, Rcmp
<= 0, Frm("%r <= %r %d", x
, y
, Rcmp
))
850 eq(x
> y
, Rcmp
> 0, Frm("%r > %r %d", x
, y
, Rcmp
))
851 eq(x
>= y
, Rcmp
>= 0, Frm("%r >= %r %d", x
, y
, Rcmp
))
853 def test_nan_inf(self
):
854 self
.assertRaises(OverflowError, long, float('inf'))
855 self
.assertRaises(OverflowError, long, float('-inf'))
856 self
.assertRaises(ValueError, long, float('nan'))
858 def test_bit_length(self
):
860 for x
in xrange(-65000, 65000):
863 # Check equivalence with Python version
864 self
.assertEqual(k
, len(bin(x
).lstrip('-0b')))
865 # Behaviour as specified in the docs
867 self
.assertTrue(2**(k
-1) <= abs(x
) < 2**k
)
869 self
.assertEqual(k
, 0)
870 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
872 # When x is an exact power of 2, numeric errors can
873 # cause floor(log(x)/log(2)) to be one too small; for
874 # small x this can be fixed by adding a small quantity
875 # to the quotient before taking the floor.
876 self
.assertEqual(k
, 1 + math
.floor(
877 math
.log(abs(x
))/math
.log(2) + tiny
))
879 self
.assertEqual((0L).bit_length(), 0)
880 self
.assertEqual((1L).bit_length(), 1)
881 self
.assertEqual((-1L).bit_length(), 1)
882 self
.assertEqual((2L).bit_length(), 2)
883 self
.assertEqual((-2L).bit_length(), 2)
884 for i
in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
886 self
.assertEqual((a
-1).bit_length(), i
)
887 self
.assertEqual((1-a
).bit_length(), i
)
888 self
.assertEqual((a
).bit_length(), i
+1)
889 self
.assertEqual((-a
).bit_length(), i
+1)
890 self
.assertEqual((a
+1).bit_length(), i
+1)
891 self
.assertEqual((-a
-1).bit_length(), i
+1)
895 test_support
.run_unittest(LongTest
)
897 if __name__
== "__main__":