test_long.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. import unittest
  2. import sys
  3. import random
  4. import math
  5. from test import test_int, test_support
  6. # Used for lazy formatting of failure messages
  7. class Frm(object):
  8. def __init__(self, format, *args):
  9. self.format = format
  10. self.args = args
  11. def __str__(self):
  12. return self.format % self.args
  13. # SHIFT should match the value in longintrepr.h for best testing.
  14. SHIFT = sys.long_info.bits_per_digit
  15. BASE = 2 ** SHIFT
  16. MASK = BASE - 1
  17. KARATSUBA_CUTOFF = 70 # from longobject.c
  18. # Max number of base BASE digits to use in test cases. Doubling
  19. # this will more than double the runtime.
  20. MAXDIGITS = 15
  21. # build some special values
  22. special = map(long, [0, 1, 2, BASE, BASE >> 1])
  23. special.append(0x5555555555555555L)
  24. special.append(0xaaaaaaaaaaaaaaaaL)
  25. # some solid strings of one bits
  26. p2 = 4L # 0 and 1 already added
  27. for i in range(2*SHIFT):
  28. special.append(p2 - 1)
  29. p2 = p2 << 1
  30. del p2
  31. # add complements & negations
  32. special = special + map(lambda x: ~x, special) + \
  33. map(lambda x: -x, special)
  34. L = [
  35. ('0', 0),
  36. ('1', 1),
  37. ('9', 9),
  38. ('10', 10),
  39. ('99', 99),
  40. ('100', 100),
  41. ('314', 314),
  42. (' 314', 314),
  43. ('314 ', 314),
  44. (' \t\t 314 \t\t ', 314),
  45. (repr(sys.maxint), sys.maxint),
  46. (' 1x', ValueError),
  47. (' 1 ', 1),
  48. (' 1\02 ', ValueError),
  49. ('', ValueError),
  50. (' ', ValueError),
  51. (' \t\t ', ValueError)
  52. ]
  53. if test_support.have_unicode:
  54. L += [
  55. (unicode('0'), 0),
  56. (unicode('1'), 1),
  57. (unicode('9'), 9),
  58. (unicode('10'), 10),
  59. (unicode('99'), 99),
  60. (unicode('100'), 100),
  61. (unicode('314'), 314),
  62. (unicode(' 314'), 314),
  63. (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
  64. (unicode(' \t\t 314 \t\t '), 314),
  65. (unicode(' 1x'), ValueError),
  66. (unicode(' 1 '), 1),
  67. (unicode(' 1\02 '), ValueError),
  68. (unicode(''), ValueError),
  69. (unicode(' '), ValueError),
  70. (unicode(' \t\t '), ValueError),
  71. (unichr(0x200), ValueError),
  72. ]
  73. class LongSubclass(long):
  74. pass
  75. class OtherLongSubclass(long):
  76. pass
  77. class LongTest(test_int.IntLongCommonTests, unittest.TestCase):
  78. ntype = long
  79. # 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.
  84. def getran(self, ndigits):
  85. self.assertGreater(ndigits, 0)
  86. nbits_hi = ndigits * SHIFT
  87. nbits_lo = nbits_hi - SHIFT + 1
  88. answer = 0L
  89. nbits = 0
  90. r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
  91. while nbits < nbits_lo:
  92. bits = (r >> 1) + 1
  93. bits = min(bits, nbits_hi - nbits)
  94. self.assertTrue(1 <= bits <= SHIFT)
  95. nbits = nbits + bits
  96. answer = answer << bits
  97. if r & 1:
  98. answer = answer | ((1 << bits) - 1)
  99. r = int(random.random() * (SHIFT * 2))
  100. self.assertTrue(nbits_lo <= nbits <= nbits_hi)
  101. if random.random() < 0.5:
  102. answer = -answer
  103. return answer
  104. # Get random long consisting of ndigits random digits (relative to base
  105. # BASE). The sign bit is also random.
  106. def getran2(ndigits):
  107. answer = 0L
  108. for i in xrange(ndigits):
  109. answer = (answer << SHIFT) | random.randint(0, MASK)
  110. if random.random() < 0.5:
  111. answer = -answer
  112. return answer
  113. def check_division(self, x, y):
  114. eq = self.assertEqual
  115. q, r = divmod(x, y)
  116. q2, r2 = x//y, x%y
  117. pab, pba = x*y, y*x
  118. eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
  119. eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
  120. eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
  121. eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
  122. if y > 0:
  123. self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
  124. else:
  125. self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
  126. def test_division(self):
  127. digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF,
  128. KARATSUBA_CUTOFF + 14)
  129. digits.append(KARATSUBA_CUTOFF * 3)
  130. for lenx in digits:
  131. x = self.getran(lenx)
  132. for leny in digits:
  133. y = self.getran(leny) or 1L
  134. self.check_division(x, y)
  135. # specific numbers chosen to exercise corner cases of the
  136. # current long division implementation
  137. # 30-bit cases involving a quotient digit estimate of BASE+1
  138. self.check_division(1231948412290879395966702881L,
  139. 1147341367131428698L)
  140. self.check_division(815427756481275430342312021515587883L,
  141. 707270836069027745L)
  142. self.check_division(627976073697012820849443363563599041L,
  143. 643588798496057020L)
  144. self.check_division(1115141373653752303710932756325578065L,
  145. 1038556335171453937726882627L)
  146. # 30-bit cases that require the post-subtraction correction step
  147. self.check_division(922498905405436751940989320930368494L,
  148. 949985870686786135626943396L)
  149. self.check_division(768235853328091167204009652174031844L,
  150. 1091555541180371554426545266L)
  151. # 15-bit cases involving a quotient digit estimate of BASE+1
  152. self.check_division(20172188947443L, 615611397L)
  153. self.check_division(1020908530270155025L, 950795710L)
  154. self.check_division(128589565723112408L, 736393718L)
  155. self.check_division(609919780285761575L, 18613274546784L)
  156. # 15-bit cases that require the post-subtraction correction step
  157. self.check_division(710031681576388032L, 26769404391308L)
  158. self.check_division(1933622614268221L, 30212853348836L)
  159. def test_karatsuba(self):
  160. digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10)
  161. digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
  162. bits = [digit * SHIFT for digit in digits]
  163. # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
  164. # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
  165. for abits in bits:
  166. a = (1L << abits) - 1
  167. for bbits in bits:
  168. if bbits < abits:
  169. continue
  170. b = (1L << bbits) - 1
  171. x = a * b
  172. y = ((1L << (abits + bbits)) -
  173. (1L << abits) -
  174. (1L << bbits) +
  175. 1)
  176. self.assertEqual(x, y,
  177. Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y))
  178. def check_bitop_identities_1(self, x):
  179. eq = self.assertEqual
  180. eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))
  181. eq(x | 0, x, Frm("x | 0 != x for x=%r", x))
  182. eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x))
  183. eq(x & -1, x, Frm("x & -1 != x for x=%r", x))
  184. eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x))
  185. eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x))
  186. eq(x, ~~x, Frm("x != ~~x for x=%r", x))
  187. eq(x & x, x, Frm("x & x != x for x=%r", x))
  188. eq(x | x, x, Frm("x | x != x for x=%r", x))
  189. eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x))
  190. eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x))
  191. eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x))
  192. eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
  193. eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
  194. eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
  195. for n in xrange(2*SHIFT):
  196. p2 = 2L ** n
  197. eq(x << n >> n, x,
  198. Frm("x << n >> n != x for x=%r, n=%r", x, n))
  199. eq(x // p2, x >> n,
  200. Frm("x // p2 != x >> n for x=%r n=%r p2=%r", x, n, p2))
  201. eq(x * p2, x << n,
  202. Frm("x * p2 != x << n for x=%r n=%r p2=%r", x, n, p2))
  203. eq(x & -p2, x >> n << n,
  204. Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", x, n, p2))
  205. eq(x & -p2, x & ~(p2 - 1),
  206. Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", x, n, p2))
  207. def check_bitop_identities_2(self, x, y):
  208. eq = self.assertEqual
  209. eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", x, y))
  210. eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", x, y))
  211. eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", x, y))
  212. eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", x, y))
  213. eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", x, y))
  214. eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", x, y))
  215. eq(x ^ y, (x | y) & ~(x & y),
  216. Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", x, y))
  217. eq(x ^ y, (x & ~y) | (~x & y),
  218. Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", x, y))
  219. eq(x ^ y, (x | y) & (~x | ~y),
  220. Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", x, y))
  221. def check_bitop_identities_3(self, x, y, z):
  222. eq = self.assertEqual
  223. eq((x & y) & z, x & (y & z),
  224. Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", x, y, z))
  225. eq((x | y) | z, x | (y | z),
  226. Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", x, y, z))
  227. eq((x ^ y) ^ z, x ^ (y ^ z),
  228. Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", x, y, z))
  229. eq(x & (y | z), (x & y) | (x & z),
  230. Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", x, y, z))
  231. eq(x | (y & z), (x | y) & (x | z),
  232. Frm("x | (y & z) != (x | y) & (x | z) for x=%r, y=%r, z=%r", x, y, z))
  233. def test_bitop_identities(self):
  234. for x in special:
  235. self.check_bitop_identities_1(x)
  236. digits = xrange(1, MAXDIGITS+1)
  237. for lenx in digits:
  238. x = self.getran(lenx)
  239. self.check_bitop_identities_1(x)
  240. for leny in digits:
  241. y = self.getran(leny)
  242. self.check_bitop_identities_2(x, y)
  243. self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
  244. def slow_format(self, x, base):
  245. if (x, base) == (0, 8):
  246. # this is an oddball!
  247. return "0L"
  248. digits = []
  249. sign = 0
  250. if x < 0:
  251. sign, x = 1, -x
  252. while x:
  253. x, r = divmod(x, base)
  254. digits.append(int(r))
  255. digits.reverse()
  256. digits = digits or [0]
  257. return '-'[:sign] + \
  258. {8: '0', 10: '', 16: '0x'}[base] + \
  259. "".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L"
  260. def check_format_1(self, x):
  261. for base, mapper in (8, oct), (10, repr), (16, hex):
  262. got = mapper(x)
  263. expected = self.slow_format(x, base)
  264. msg = Frm("%s returned %r but expected %r for %r",
  265. mapper.__name__, got, expected, x)
  266. self.assertEqual(got, expected, msg)
  267. self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x))
  268. # str() has to be checked a little differently since there's no
  269. # trailing "L"
  270. got = str(x)
  271. expected = self.slow_format(x, 10)[:-1]
  272. msg = Frm("%s returned %r but expected %r for %r",
  273. mapper.__name__, got, expected, x)
  274. self.assertEqual(got, expected, msg)
  275. def test_format(self):
  276. for x in special:
  277. self.check_format_1(x)
  278. for i in xrange(10):
  279. for lenx in xrange(1, MAXDIGITS+1):
  280. x = self.getran(lenx)
  281. self.check_format_1(x)
  282. def test_long(self):
  283. self.assertEqual(long(314), 314L)
  284. self.assertEqual(long(3.14), 3L)
  285. self.assertEqual(long(314L), 314L)
  286. # Check that long() of basic types actually returns a long
  287. self.assertEqual(type(long(314)), long)
  288. self.assertEqual(type(long(3.14)), long)
  289. self.assertEqual(type(long(314L)), long)
  290. # Check that conversion from float truncates towards zero
  291. self.assertEqual(long(-3.14), -3L)
  292. self.assertEqual(long(3.9), 3L)
  293. self.assertEqual(long(-3.9), -3L)
  294. self.assertEqual(long(3.5), 3L)
  295. self.assertEqual(long(-3.5), -3L)
  296. self.assertEqual(long("-3"), -3L)
  297. self.assertEqual(long("0b10", 2), 2L)
  298. self.assertEqual(long("0o10", 8), 8L)
  299. self.assertEqual(long("0x10", 16), 16L)
  300. if test_support.have_unicode:
  301. self.assertEqual(long(unicode("-3")), -3L)
  302. # Different base:
  303. self.assertEqual(long("10",16), 16L)
  304. if test_support.have_unicode:
  305. self.assertEqual(long(unicode("10"),16), 16L)
  306. # Check conversions from string (same test set as for int(), and then some)
  307. LL = [
  308. ('1' + '0'*20, 10L**20),
  309. ('1' + '0'*100, 10L**100)
  310. ]
  311. L2 = L[:]
  312. if test_support.have_unicode:
  313. L2 += [
  314. (unicode('1') + unicode('0')*20, 10L**20),
  315. (unicode('1') + unicode('0')*100, 10L**100),
  316. ]
  317. for s, v in L2 + LL:
  318. for sign in "", "+", "-":
  319. for prefix in "", " ", "\t", " \t\t ":
  320. ss = prefix + sign + s
  321. vv = v
  322. if sign == "-" and v is not ValueError:
  323. vv = -v
  324. try:
  325. self.assertEqual(long(ss), long(vv))
  326. except v:
  327. pass
  328. self.assertRaises(ValueError, long, '123\0')
  329. self.assertRaises(ValueError, long, '53', 40)
  330. self.assertRaises(TypeError, long, 1, 12)
  331. # tests with base 0
  332. self.assertEqual(long(' 0123 ', 0), 83)
  333. self.assertEqual(long(' 0123 ', 0), 83)
  334. self.assertEqual(long('000', 0), 0)
  335. self.assertEqual(long('0o123', 0), 83)
  336. self.assertEqual(long('0x123', 0), 291)
  337. self.assertEqual(long('0b100', 0), 4)
  338. self.assertEqual(long(' 0O123 ', 0), 83)
  339. self.assertEqual(long(' 0X123 ', 0), 291)
  340. self.assertEqual(long(' 0B100 ', 0), 4)
  341. self.assertEqual(long('0', 0), 0)
  342. self.assertEqual(long('+0', 0), 0)
  343. self.assertEqual(long('-0', 0), 0)
  344. self.assertEqual(long('00', 0), 0)
  345. self.assertRaises(ValueError, long, '08', 0)
  346. self.assertRaises(ValueError, long, '-012395', 0)
  347. # SF patch #1638879: embedded NULs were not detected with
  348. # explicit base
  349. self.assertRaises(ValueError, long, '123\0', 10)
  350. self.assertRaises(ValueError, long, '123\x00 245', 20)
  351. self.assertEqual(long('100000000000000000000000000000000', 2),
  352. 4294967296)
  353. self.assertEqual(long('102002022201221111211', 3), 4294967296)
  354. self.assertEqual(long('10000000000000000', 4), 4294967296)
  355. self.assertEqual(long('32244002423141', 5), 4294967296)
  356. self.assertEqual(long('1550104015504', 6), 4294967296)
  357. self.assertEqual(long('211301422354', 7), 4294967296)
  358. self.assertEqual(long('40000000000', 8), 4294967296)
  359. self.assertEqual(long('12068657454', 9), 4294967296)
  360. self.assertEqual(long('4294967296', 10), 4294967296)
  361. self.assertEqual(long('1904440554', 11), 4294967296)
  362. self.assertEqual(long('9ba461594', 12), 4294967296)
  363. self.assertEqual(long('535a79889', 13), 4294967296)
  364. self.assertEqual(long('2ca5b7464', 14), 4294967296)
  365. self.assertEqual(long('1a20dcd81', 15), 4294967296)
  366. self.assertEqual(long('100000000', 16), 4294967296)
  367. self.assertEqual(long('a7ffda91', 17), 4294967296)
  368. self.assertEqual(long('704he7g4', 18), 4294967296)
  369. self.assertEqual(long('4f5aff66', 19), 4294967296)
  370. self.assertEqual(long('3723ai4g', 20), 4294967296)
  371. self.assertEqual(long('281d55i4', 21), 4294967296)
  372. self.assertEqual(long('1fj8b184', 22), 4294967296)
  373. self.assertEqual(long('1606k7ic', 23), 4294967296)
  374. self.assertEqual(long('mb994ag', 24), 4294967296)
  375. self.assertEqual(long('hek2mgl', 25), 4294967296)
  376. self.assertEqual(long('dnchbnm', 26), 4294967296)
  377. self.assertEqual(long('b28jpdm', 27), 4294967296)
  378. self.assertEqual(long('8pfgih4', 28), 4294967296)
  379. self.assertEqual(long('76beigg', 29), 4294967296)
  380. self.assertEqual(long('5qmcpqg', 30), 4294967296)
  381. self.assertEqual(long('4q0jto4', 31), 4294967296)
  382. self.assertEqual(long('4000000', 32), 4294967296)
  383. self.assertEqual(long('3aokq94', 33), 4294967296)
  384. self.assertEqual(long('2qhxjli', 34), 4294967296)
  385. self.assertEqual(long('2br45qb', 35), 4294967296)
  386. self.assertEqual(long('1z141z4', 36), 4294967296)
  387. self.assertEqual(long('100000000000000000000000000000001', 2),
  388. 4294967297)
  389. self.assertEqual(long('102002022201221111212', 3), 4294967297)
  390. self.assertEqual(long('10000000000000001', 4), 4294967297)
  391. self.assertEqual(long('32244002423142', 5), 4294967297)
  392. self.assertEqual(long('1550104015505', 6), 4294967297)
  393. self.assertEqual(long('211301422355', 7), 4294967297)
  394. self.assertEqual(long('40000000001', 8), 4294967297)
  395. self.assertEqual(long('12068657455', 9), 4294967297)
  396. self.assertEqual(long('4294967297', 10), 4294967297)
  397. self.assertEqual(long('1904440555', 11), 4294967297)
  398. self.assertEqual(long('9ba461595', 12), 4294967297)
  399. self.assertEqual(long('535a7988a', 13), 4294967297)
  400. self.assertEqual(long('2ca5b7465', 14), 4294967297)
  401. self.assertEqual(long('1a20dcd82', 15), 4294967297)
  402. self.assertEqual(long('100000001', 16), 4294967297)
  403. self.assertEqual(long('a7ffda92', 17), 4294967297)
  404. self.assertEqual(long('704he7g5', 18), 4294967297)
  405. self.assertEqual(long('4f5aff67', 19), 4294967297)
  406. self.assertEqual(long('3723ai4h', 20), 4294967297)
  407. self.assertEqual(long('281d55i5', 21), 4294967297)
  408. self.assertEqual(long('1fj8b185', 22), 4294967297)
  409. self.assertEqual(long('1606k7id', 23), 4294967297)
  410. self.assertEqual(long('mb994ah', 24), 4294967297)
  411. self.assertEqual(long('hek2mgm', 25), 4294967297)
  412. self.assertEqual(long('dnchbnn', 26), 4294967297)
  413. self.assertEqual(long('b28jpdn', 27), 4294967297)
  414. self.assertEqual(long('8pfgih5', 28), 4294967297)
  415. self.assertEqual(long('76beigh', 29), 4294967297)
  416. self.assertEqual(long('5qmcpqh', 30), 4294967297)
  417. self.assertEqual(long('4q0jto5', 31), 4294967297)
  418. self.assertEqual(long('4000001', 32), 4294967297)
  419. self.assertEqual(long('3aokq95', 33), 4294967297)
  420. self.assertEqual(long('2qhxjlj', 34), 4294967297)
  421. self.assertEqual(long('2br45qc', 35), 4294967297)
  422. self.assertEqual(long('1z141z5', 36), 4294967297)
  423. def test_conversion(self):
  424. # Test __long__()
  425. class ClassicMissingMethods:
  426. pass
  427. self.assertRaises(AttributeError, long, ClassicMissingMethods())
  428. class MissingMethods(object):
  429. pass
  430. self.assertRaises(TypeError, long, MissingMethods())
  431. class Foo0:
  432. def __long__(self):
  433. return 42L
  434. class Foo1(object):
  435. def __long__(self):
  436. return 42L
  437. class Foo2(long):
  438. def __long__(self):
  439. return 42L
  440. class Foo3(long):
  441. def __long__(self):
  442. return self
  443. class Foo4(long):
  444. def __long__(self):
  445. return 42
  446. class Foo5(long):
  447. def __long__(self):
  448. return 42.
  449. self.assertEqual(long(Foo0()), 42L)
  450. self.assertEqual(long(Foo1()), 42L)
  451. self.assertEqual(long(Foo2()), 42L)
  452. self.assertEqual(long(Foo3()), 0)
  453. self.assertEqual(long(Foo4()), 42)
  454. self.assertRaises(TypeError, long, Foo5())
  455. class Classic:
  456. pass
  457. for base in (object, Classic):
  458. class LongOverridesTrunc(base):
  459. def __long__(self):
  460. return 42
  461. def __trunc__(self):
  462. return -12
  463. self.assertEqual(long(LongOverridesTrunc()), 42)
  464. class JustTrunc(base):
  465. def __trunc__(self):
  466. return 42
  467. self.assertEqual(long(JustTrunc()), 42)
  468. for trunc_result_base in (object, Classic):
  469. class Integral(trunc_result_base):
  470. def __int__(self):
  471. return 42
  472. class TruncReturnsNonLong(base):
  473. def __trunc__(self):
  474. return Integral()
  475. self.assertEqual(long(TruncReturnsNonLong()), 42)
  476. class NonIntegral(trunc_result_base):
  477. def __trunc__(self):
  478. # Check that we avoid infinite recursion.
  479. return NonIntegral()
  480. class TruncReturnsNonIntegral(base):
  481. def __trunc__(self):
  482. return NonIntegral()
  483. try:
  484. long(TruncReturnsNonIntegral())
  485. except TypeError as e:
  486. self.assertEqual(str(e),
  487. "__trunc__ returned non-Integral"
  488. " (type NonIntegral)")
  489. else:
  490. self.fail("Failed to raise TypeError with %s" %
  491. ((base, trunc_result_base),))
  492. class TruncReturnsLongSubclass(base):
  493. def __long__(self):
  494. return OtherLongSubclass(42L)
  495. good_int = TruncReturnsLongSubclass()
  496. n = long(good_int)
  497. self.assertEqual(n, 42L)
  498. self.assertIs(type(n), OtherLongSubclass)
  499. n = LongSubclass(good_int)
  500. self.assertEqual(n, 42L)
  501. self.assertIs(type(n), LongSubclass)
  502. def test_misc(self):
  503. # check the extremes in int<->long conversion
  504. hugepos = sys.maxint
  505. hugeneg = -hugepos - 1
  506. hugepos_aslong = long(hugepos)
  507. hugeneg_aslong = long(hugeneg)
  508. self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint")
  509. self.assertEqual(hugeneg, hugeneg_aslong,
  510. "long(-sys.maxint-1) != -sys.maxint-1")
  511. # long -> int should not fail for hugepos_aslong or hugeneg_aslong
  512. x = int(hugepos_aslong)
  513. try:
  514. self.assertEqual(x, hugepos,
  515. "converting sys.maxint to long and back to int fails")
  516. except OverflowError:
  517. self.fail("int(long(sys.maxint)) overflowed!")
  518. if not isinstance(x, int):
  519. self.fail("int(long(sys.maxint)) should have returned int")
  520. x = int(hugeneg_aslong)
  521. try:
  522. self.assertEqual(x, hugeneg,
  523. "converting -sys.maxint-1 to long and back to int fails")
  524. except OverflowError:
  525. self.fail("int(long(-sys.maxint-1)) overflowed!")
  526. if not isinstance(x, int):
  527. self.fail("int(long(-sys.maxint-1)) should have returned int")
  528. # but long -> int should overflow for hugepos+1 and hugeneg-1
  529. x = hugepos_aslong + 1
  530. try:
  531. y = int(x)
  532. except OverflowError:
  533. self.fail("int(long(sys.maxint) + 1) mustn't overflow")
  534. self.assertIsInstance(y, long,
  535. "int(long(sys.maxint) + 1) should have returned long")
  536. x = hugeneg_aslong - 1
  537. try:
  538. y = int(x)
  539. except OverflowError:
  540. self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow")
  541. self.assertIsInstance(y, long,
  542. "int(long(-sys.maxint-1) - 1) should have returned long")
  543. class long2(long):
  544. pass
  545. x = long2(1L<<100)
  546. y = int(x)
  547. self.assertIs(type(y), long,
  548. "overflowing int conversion must return long not long subtype")
  549. # long -> Py_ssize_t conversion
  550. class X(object):
  551. def __getslice__(self, i, j):
  552. return i, j
  553. with test_support.check_py3k_warnings():
  554. self.assertEqual(X()[-5L:7L], (-5, 7))
  555. # use the clamping effect to test the smallest and largest longs
  556. # that fit a Py_ssize_t
  557. slicemin, slicemax = X()[-2L**100:2L**100]
  558. self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
  559. def test_issue9869(self):
  560. # Issue 9869: Interpreter crash when initializing an instance
  561. # of a long subclass from an object whose __long__ method returns
  562. # a plain int.
  563. class BadLong(object):
  564. def __long__(self):
  565. return 1000000
  566. class MyLong(long):
  567. pass
  568. x = MyLong(BadLong())
  569. self.assertIsInstance(x, long)
  570. self.assertEqual(x, 1000000)
  571. # ----------------------------------- tests of auto int->long conversion
  572. def test_auto_overflow(self):
  573. special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1]
  574. sqrt = int(math.sqrt(sys.maxint))
  575. special.extend([sqrt-1, sqrt, sqrt+1])
  576. special.extend([-i for i in special])
  577. def checkit(*args):
  578. # Heavy use of nested scopes here!
  579. self.assertEqual(got, expected,
  580. Frm("for %r expected %r got %r", args, expected, got))
  581. for x in special:
  582. longx = long(x)
  583. expected = -longx
  584. got = -x
  585. checkit('-', x)
  586. for y in special:
  587. longy = long(y)
  588. expected = longx + longy
  589. got = x + y
  590. checkit(x, '+', y)
  591. expected = longx - longy
  592. got = x - y
  593. checkit(x, '-', y)
  594. expected = longx * longy
  595. got = x * y
  596. checkit(x, '*', y)
  597. if y:
  598. with test_support.check_py3k_warnings():
  599. expected = longx / longy
  600. got = x / y
  601. checkit(x, '/', y)
  602. expected = longx // longy
  603. got = x // y
  604. checkit(x, '//', y)
  605. expected = divmod(longx, longy)
  606. got = divmod(longx, longy)
  607. checkit(x, 'divmod', y)
  608. if abs(y) < 5 and not (x == 0 and y < 0):
  609. expected = longx ** longy
  610. got = x ** y
  611. checkit(x, '**', y)
  612. for z in special:
  613. if z != 0 :
  614. if y >= 0:
  615. expected = pow(longx, longy, long(z))
  616. got = pow(x, y, z)
  617. checkit('pow', x, y, '%', z)
  618. else:
  619. self.assertRaises(TypeError, pow,longx, longy, long(z))
  620. @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
  621. "test requires IEEE 754 doubles")
  622. def test_float_conversion(self):
  623. import sys
  624. DBL_MAX = sys.float_info.max
  625. DBL_MAX_EXP = sys.float_info.max_exp
  626. DBL_MANT_DIG = sys.float_info.mant_dig
  627. exact_values = [0L, 1L, 2L,
  628. long(2**53-3),
  629. long(2**53-2),
  630. long(2**53-1),
  631. long(2**53),
  632. long(2**53+2),
  633. long(2**54-4),
  634. long(2**54-2),
  635. long(2**54),
  636. long(2**54+4)]
  637. for x in exact_values:
  638. self.assertEqual(long(float(x)), x)
  639. self.assertEqual(long(float(-x)), -x)
  640. # test round-half-even
  641. for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
  642. for p in xrange(15):
  643. self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))
  644. for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
  645. (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
  646. (13, 12), (14, 16), (15, 16)]:
  647. for p in xrange(15):
  648. self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))
  649. # behaviour near extremes of floating-point range
  650. long_dbl_max = long(DBL_MAX)
  651. top_power = 2**DBL_MAX_EXP
  652. halfway = (long_dbl_max + top_power)//2
  653. self.assertEqual(float(long_dbl_max), DBL_MAX)
  654. self.assertEqual(float(long_dbl_max+1), DBL_MAX)
  655. self.assertEqual(float(halfway-1), DBL_MAX)
  656. self.assertRaises(OverflowError, float, halfway)
  657. self.assertEqual(float(1-halfway), -DBL_MAX)
  658. self.assertRaises(OverflowError, float, -halfway)
  659. self.assertRaises(OverflowError, float, top_power-1)
  660. self.assertRaises(OverflowError, float, top_power)
  661. self.assertRaises(OverflowError, float, top_power+1)
  662. self.assertRaises(OverflowError, float, 2*top_power-1)
  663. self.assertRaises(OverflowError, float, 2*top_power)
  664. self.assertRaises(OverflowError, float, top_power*top_power)
  665. for p in xrange(100):
  666. x = long(2**p * (2**53 + 1) + 1)
  667. y = long(2**p * (2**53+ 2))
  668. self.assertEqual(long(float(x)), y)
  669. x = long(2**p * (2**53 + 1))
  670. y = long(2**p * 2**53)
  671. self.assertEqual(long(float(x)), y)
  672. def test_float_overflow(self):
  673. for x in -2.0, -1.0, 0.0, 1.0, 2.0:
  674. self.assertEqual(float(long(x)), x)
  675. shuge = '12345' * 120
  676. huge = 1L << 30000
  677. mhuge = -huge
  678. namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
  679. for test in ["float(huge)", "float(mhuge)",
  680. "complex(huge)", "complex(mhuge)",
  681. "complex(huge, 1)", "complex(mhuge, 1)",
  682. "complex(1, huge)", "complex(1, mhuge)",
  683. "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
  684. "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
  685. "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
  686. "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
  687. "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
  688. "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
  689. "math.sin(huge)", "math.sin(mhuge)",
  690. "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
  691. "math.floor(huge)", "math.floor(mhuge)"]:
  692. self.assertRaises(OverflowError, eval, test, namespace)
  693. # XXX Perhaps float(shuge) can raise OverflowError on some box?
  694. # The comparison should not.
  695. self.assertNotEqual(float(shuge), int(shuge),
  696. "float(shuge) should not equal int(shuge)")
  697. def test_logs(self):
  698. LOG10E = math.log10(math.e)
  699. for exp in range(10) + [100, 1000, 10000]:
  700. value = 10 ** exp
  701. log10 = math.log10(value)
  702. self.assertAlmostEqual(log10, exp)
  703. # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
  704. # exp/LOG10E
  705. expected = exp / LOG10E
  706. log = math.log(value)
  707. self.assertAlmostEqual(log, expected)
  708. for bad in -(1L << 10000), -2L, 0L:
  709. self.assertRaises(ValueError, math.log, bad)
  710. self.assertRaises(ValueError, math.log10, bad)
  711. def test_mixed_compares(self):
  712. eq = self.assertEqual
  713. # We're mostly concerned with that mixing floats and longs does the
  714. # right stuff, even when longs are too large to fit in a float.
  715. # The safest way to check the results is to use an entirely different
  716. # method, which we do here via a skeletal rational class (which
  717. # represents all Python ints, longs and floats exactly).
  718. class Rat:
  719. def __init__(self, value):
  720. if isinstance(value, (int, long)):
  721. self.n = value
  722. self.d = 1
  723. elif isinstance(value, float):
  724. # Convert to exact rational equivalent.
  725. f, e = math.frexp(abs(value))
  726. assert f == 0 or 0.5 <= f < 1.0
  727. # |value| = f * 2**e exactly
  728. # Suck up CHUNK bits at a time; 28 is enough so that we suck
  729. # up all bits in 2 iterations for all known binary double-
  730. # precision formats, and small enough to fit in an int.
  731. CHUNK = 28
  732. top = 0
  733. # invariant: |value| = (top + f) * 2**e exactly
  734. while f:
  735. f = math.ldexp(f, CHUNK)
  736. digit = int(f)
  737. assert digit >> CHUNK == 0
  738. top = (top << CHUNK) | digit
  739. f -= digit
  740. assert 0.0 <= f < 1.0
  741. e -= CHUNK
  742. # Now |value| = top * 2**e exactly.
  743. if e >= 0:
  744. n = top << e
  745. d = 1
  746. else:
  747. n = top
  748. d = 1 << -e
  749. if value < 0:
  750. n = -n
  751. self.n = n
  752. self.d = d
  753. assert float(n) / float(d) == value
  754. else:
  755. raise TypeError("can't deal with %r" % value)
  756. def __cmp__(self, other):
  757. if not isinstance(other, Rat):
  758. other = Rat(other)
  759. return cmp(self.n * other.d, self.d * other.n)
  760. cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
  761. # 2**48 is an important boundary in the internals. 2**53 is an
  762. # important boundary for IEEE double precision.
  763. for t in 2.0**48, 2.0**50, 2.0**53:
  764. cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
  765. long(t-1), long(t), long(t+1)])
  766. cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)])
  767. # 1L<<20000 should exceed all double formats. long(1e200) is to
  768. # check that we get equality with 1e200 above.
  769. t = long(1e200)
  770. cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1])
  771. cases.extend([-x for x in cases])
  772. for x in cases:
  773. Rx = Rat(x)
  774. for y in cases:
  775. Ry = Rat(y)
  776. Rcmp = cmp(Rx, Ry)
  777. xycmp = cmp(x, y)
  778. eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
  779. eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
  780. eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
  781. eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
  782. eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
  783. eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
  784. eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
  785. def test_nan_inf(self):
  786. self.assertRaises(OverflowError, long, float('inf'))
  787. self.assertRaises(OverflowError, long, float('-inf'))
  788. self.assertRaises(ValueError, long, float('nan'))
  789. def test_bit_length(self):
  790. tiny = 1e-10
  791. for x in xrange(-65000, 65000):
  792. x = long(x)
  793. k = x.bit_length()
  794. # Check equivalence with Python version
  795. self.assertEqual(k, len(bin(x).lstrip('-0b')))
  796. # Behaviour as specified in the docs
  797. if x != 0:
  798. self.assertTrue(2**(k-1) <= abs(x) < 2**k)
  799. else:
  800. self.assertEqual(k, 0)
  801. # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
  802. if x != 0:
  803. # When x is an exact power of 2, numeric errors can
  804. # cause floor(log(x)/log(2)) to be one too small; for
  805. # small x this can be fixed by adding a small quantity
  806. # to the quotient before taking the floor.
  807. self.assertEqual(k, 1 + math.floor(
  808. math.log(abs(x))/math.log(2) + tiny))
  809. self.assertEqual((0L).bit_length(), 0)
  810. self.assertEqual((1L).bit_length(), 1)
  811. self.assertEqual((-1L).bit_length(), 1)
  812. self.assertEqual((2L).bit_length(), 2)
  813. self.assertEqual((-2L).bit_length(), 2)
  814. for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
  815. a = 2L**i
  816. self.assertEqual((a-1).bit_length(), i)
  817. self.assertEqual((1-a).bit_length(), i)
  818. self.assertEqual((a).bit_length(), i+1)
  819. self.assertEqual((-a).bit_length(), i+1)
  820. self.assertEqual((a+1).bit_length(), i+1)
  821. self.assertEqual((-a-1).bit_length(), i+1)
  822. def test_main():
  823. test_support.run_unittest(LongTest)
  824. if __name__ == "__main__":
  825. test_main()