test_math.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  1. # Python test set -- math module
  2. # XXXX Should not do tests around zero only
  3. from test.support import verbose, requires_IEEE_754
  4. from test import support
  5. import unittest
  6. import itertools
  7. import decimal
  8. import math
  9. import os
  10. import platform
  11. import random
  12. import struct
  13. import sys
  14. eps = 1E-05
  15. NAN = float('nan')
  16. INF = float('inf')
  17. NINF = float('-inf')
  18. FLOAT_MAX = sys.float_info.max
  19. FLOAT_MIN = sys.float_info.min
  20. # detect evidence of double-rounding: fsum is not always correctly
  21. # rounded on machines that suffer from double rounding.
  22. x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
  23. HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
  24. # locate file with test values
  25. if __name__ == '__main__':
  26. file = sys.argv[0]
  27. else:
  28. file = __file__
  29. test_dir = os.path.dirname(file) or os.curdir
  30. math_testcases = os.path.join(test_dir, 'math_testcases.txt')
  31. test_file = os.path.join(test_dir, 'cmath_testcases.txt')
  32. def to_ulps(x):
  33. """Convert a non-NaN float x to an integer, in such a way that
  34. adjacent floats are converted to adjacent integers. Then
  35. abs(ulps(x) - ulps(y)) gives the difference in ulps between two
  36. floats.
  37. The results from this function will only make sense on platforms
  38. where native doubles are represented in IEEE 754 binary64 format.
  39. Note: 0.0 and -0.0 are converted to 0 and -1, respectively.
  40. """
  41. n = struct.unpack('<q', struct.pack('<d', x))[0]
  42. if n < 0:
  43. n = ~(n+2**63)
  44. return n
  45. # Here's a pure Python version of the math.factorial algorithm, for
  46. # documentation and comparison purposes.
  47. #
  48. # Formula:
  49. #
  50. # factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
  51. #
  52. # where
  53. #
  54. # factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
  55. #
  56. # The outer product above is an infinite product, but once i >= n.bit_length,
  57. # (n >> i) < 1 and the corresponding term of the product is empty. So only the
  58. # finitely many terms for 0 <= i < n.bit_length() contribute anything.
  59. #
  60. # We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
  61. # product in the formula above starts at 1 for i == n.bit_length(); for each i
  62. # < n.bit_length() we get the inner product for i from that for i + 1 by
  63. # multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
  64. # this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
  65. def count_set_bits(n):
  66. """Number of '1' bits in binary expansion of a nonnnegative integer."""
  67. return 1 + count_set_bits(n & n - 1) if n else 0
  68. def partial_product(start, stop):
  69. """Product of integers in range(start, stop, 2), computed recursively.
  70. start and stop should both be odd, with start <= stop.
  71. """
  72. numfactors = (stop - start) >> 1
  73. if not numfactors:
  74. return 1
  75. elif numfactors == 1:
  76. return start
  77. else:
  78. mid = (start + numfactors) | 1
  79. return partial_product(start, mid) * partial_product(mid, stop)
  80. def py_factorial(n):
  81. """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
  82. described at http://www.luschny.de/math/factorial/binarysplitfact.html
  83. """
  84. inner = outer = 1
  85. for i in reversed(range(n.bit_length())):
  86. inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
  87. outer *= inner
  88. return outer << (n - count_set_bits(n))
  89. def ulp_abs_check(expected, got, ulp_tol, abs_tol):
  90. """Given finite floats `expected` and `got`, check that they're
  91. approximately equal to within the given number of ulps or the
  92. given absolute tolerance, whichever is bigger.
  93. Returns None on success and an error message on failure.
  94. """
  95. ulp_error = abs(to_ulps(expected) - to_ulps(got))
  96. abs_error = abs(expected - got)
  97. # Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol.
  98. if abs_error <= abs_tol or ulp_error <= ulp_tol:
  99. return None
  100. else:
  101. fmt = ("error = {:.3g} ({:d} ulps); "
  102. "permitted error = {:.3g} or {:d} ulps")
  103. return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol)
  104. def parse_mtestfile(fname):
  105. """Parse a file with test values
  106. -- starts a comment
  107. blank lines, or lines containing only a comment, are ignored
  108. other lines are expected to have the form
  109. id fn arg -> expected [flag]*
  110. """
  111. with open(fname, encoding="utf-8") as fp:
  112. for line in fp:
  113. # strip comments, and skip blank lines
  114. if '--' in line:
  115. line = line[:line.index('--')]
  116. if not line.strip():
  117. continue
  118. lhs, rhs = line.split('->')
  119. id, fn, arg = lhs.split()
  120. rhs_pieces = rhs.split()
  121. exp = rhs_pieces[0]
  122. flags = rhs_pieces[1:]
  123. yield (id, fn, float(arg), float(exp), flags)
  124. def parse_testfile(fname):
  125. """Parse a file with test values
  126. Empty lines or lines starting with -- are ignored
  127. yields id, fn, arg_real, arg_imag, exp_real, exp_imag
  128. """
  129. with open(fname, encoding="utf-8") as fp:
  130. for line in fp:
  131. # skip comment lines and blank lines
  132. if line.startswith('--') or not line.strip():
  133. continue
  134. lhs, rhs = line.split('->')
  135. id, fn, arg_real, arg_imag = lhs.split()
  136. rhs_pieces = rhs.split()
  137. exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
  138. flags = rhs_pieces[2:]
  139. yield (id, fn,
  140. float(arg_real), float(arg_imag),
  141. float(exp_real), float(exp_imag),
  142. flags)
  143. def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
  144. # Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
  145. """Compare arguments expected and got, as floats, if either
  146. is a float, using a tolerance expressed in multiples of
  147. ulp(expected) or absolutely (if given and greater).
  148. As a convenience, when neither argument is a float, and for
  149. non-finite floats, exact equality is demanded. Also, nan==nan
  150. as far as this function is concerned.
  151. Returns None on success and an error message on failure.
  152. """
  153. # Check exactly equal (applies also to strings representing exceptions)
  154. if got == expected:
  155. return None
  156. failure = "not equal"
  157. # Turn mixed float and int comparison (e.g. floor()) to all-float
  158. if isinstance(expected, float) and isinstance(got, int):
  159. got = float(got)
  160. elif isinstance(got, float) and isinstance(expected, int):
  161. expected = float(expected)
  162. if isinstance(expected, float) and isinstance(got, float):
  163. if math.isnan(expected) and math.isnan(got):
  164. # Pass, since both nan
  165. failure = None
  166. elif math.isinf(expected) or math.isinf(got):
  167. # We already know they're not equal, drop through to failure
  168. pass
  169. else:
  170. # Both are finite floats (now). Are they close enough?
  171. failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
  172. # arguments are not equal, and if numeric, are too far apart
  173. if failure is not None:
  174. fail_fmt = "expected {!r}, got {!r}"
  175. fail_msg = fail_fmt.format(expected, got)
  176. fail_msg += ' ({})'.format(failure)
  177. return fail_msg
  178. else:
  179. return None
  180. class FloatLike:
  181. def __init__(self, value):
  182. self.value = value
  183. def __float__(self):
  184. return self.value
  185. class IntSubclass(int):
  186. pass
  187. # Class providing an __index__ method.
  188. class MyIndexable(object):
  189. def __init__(self, value):
  190. self.value = value
  191. def __index__(self):
  192. return self.value
  193. class MathTests(unittest.TestCase):
  194. def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
  195. """Compare arguments expected and got, as floats, if either
  196. is a float, using a tolerance expressed in multiples of
  197. ulp(expected) or absolutely, whichever is greater.
  198. As a convenience, when neither argument is a float, and for
  199. non-finite floats, exact equality is demanded. Also, nan==nan
  200. in this function.
  201. """
  202. failure = result_check(expected, got, ulp_tol, abs_tol)
  203. if failure is not None:
  204. self.fail("{}: {}".format(name, failure))
  205. def testConstants(self):
  206. # Ref: Abramowitz & Stegun (Dover, 1965)
  207. self.ftest('pi', math.pi, 3.141592653589793238462643)
  208. self.ftest('e', math.e, 2.718281828459045235360287)
  209. self.assertEqual(math.tau, 2*math.pi)
  210. def testAcos(self):
  211. self.assertRaises(TypeError, math.acos)
  212. self.ftest('acos(-1)', math.acos(-1), math.pi)
  213. self.ftest('acos(0)', math.acos(0), math.pi/2)
  214. self.ftest('acos(1)', math.acos(1), 0)
  215. self.assertRaises(ValueError, math.acos, INF)
  216. self.assertRaises(ValueError, math.acos, NINF)
  217. self.assertRaises(ValueError, math.acos, 1 + eps)
  218. self.assertRaises(ValueError, math.acos, -1 - eps)
  219. self.assertTrue(math.isnan(math.acos(NAN)))
  220. def testAcosh(self):
  221. self.assertRaises(TypeError, math.acosh)
  222. self.ftest('acosh(1)', math.acosh(1), 0)
  223. self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
  224. self.assertRaises(ValueError, math.acosh, 0)
  225. self.assertRaises(ValueError, math.acosh, -1)
  226. self.assertEqual(math.acosh(INF), INF)
  227. self.assertRaises(ValueError, math.acosh, NINF)
  228. self.assertTrue(math.isnan(math.acosh(NAN)))
  229. def testAsin(self):
  230. self.assertRaises(TypeError, math.asin)
  231. self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
  232. self.ftest('asin(0)', math.asin(0), 0)
  233. self.ftest('asin(1)', math.asin(1), math.pi/2)
  234. self.assertRaises(ValueError, math.asin, INF)
  235. self.assertRaises(ValueError, math.asin, NINF)
  236. self.assertRaises(ValueError, math.asin, 1 + eps)
  237. self.assertRaises(ValueError, math.asin, -1 - eps)
  238. self.assertTrue(math.isnan(math.asin(NAN)))
  239. def testAsinh(self):
  240. self.assertRaises(TypeError, math.asinh)
  241. self.ftest('asinh(0)', math.asinh(0), 0)
  242. self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
  243. self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
  244. self.assertEqual(math.asinh(INF), INF)
  245. self.assertEqual(math.asinh(NINF), NINF)
  246. self.assertTrue(math.isnan(math.asinh(NAN)))
  247. def testAtan(self):
  248. self.assertRaises(TypeError, math.atan)
  249. self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
  250. self.ftest('atan(0)', math.atan(0), 0)
  251. self.ftest('atan(1)', math.atan(1), math.pi/4)
  252. self.ftest('atan(inf)', math.atan(INF), math.pi/2)
  253. self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
  254. self.assertTrue(math.isnan(math.atan(NAN)))
  255. def testAtanh(self):
  256. self.assertRaises(TypeError, math.atan)
  257. self.ftest('atanh(0)', math.atanh(0), 0)
  258. self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
  259. self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
  260. self.assertRaises(ValueError, math.atanh, 1)
  261. self.assertRaises(ValueError, math.atanh, -1)
  262. self.assertRaises(ValueError, math.atanh, INF)
  263. self.assertRaises(ValueError, math.atanh, NINF)
  264. self.assertTrue(math.isnan(math.atanh(NAN)))
  265. def testAtan2(self):
  266. self.assertRaises(TypeError, math.atan2)
  267. self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
  268. self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
  269. self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
  270. self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
  271. self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
  272. # math.atan2(0, x)
  273. self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
  274. self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
  275. self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
  276. self.assertEqual(math.atan2(0., 0.), 0.)
  277. self.assertEqual(math.atan2(0., 2.3), 0.)
  278. self.assertEqual(math.atan2(0., INF), 0.)
  279. self.assertTrue(math.isnan(math.atan2(0., NAN)))
  280. # math.atan2(-0, x)
  281. self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
  282. self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
  283. self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
  284. self.assertEqual(math.atan2(-0., 0.), -0.)
  285. self.assertEqual(math.atan2(-0., 2.3), -0.)
  286. self.assertEqual(math.atan2(-0., INF), -0.)
  287. self.assertTrue(math.isnan(math.atan2(-0., NAN)))
  288. # math.atan2(INF, x)
  289. self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
  290. self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
  291. self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
  292. self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
  293. self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
  294. self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
  295. self.assertTrue(math.isnan(math.atan2(INF, NAN)))
  296. # math.atan2(NINF, x)
  297. self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
  298. self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
  299. self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
  300. self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
  301. self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
  302. self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
  303. self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
  304. # math.atan2(+finite, x)
  305. self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
  306. self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
  307. self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
  308. self.assertEqual(math.atan2(2.3, INF), 0.)
  309. self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
  310. # math.atan2(-finite, x)
  311. self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
  312. self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
  313. self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
  314. self.assertEqual(math.atan2(-2.3, INF), -0.)
  315. self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
  316. # math.atan2(NAN, x)
  317. self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
  318. self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
  319. self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
  320. self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
  321. self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
  322. self.assertTrue(math.isnan(math.atan2(NAN, INF)))
  323. self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
  324. def testCbrt(self):
  325. self.assertRaises(TypeError, math.cbrt)
  326. self.ftest('cbrt(0)', math.cbrt(0), 0)
  327. self.ftest('cbrt(1)', math.cbrt(1), 1)
  328. self.ftest('cbrt(8)', math.cbrt(8), 2)
  329. self.ftest('cbrt(0.0)', math.cbrt(0.0), 0.0)
  330. self.ftest('cbrt(-0.0)', math.cbrt(-0.0), -0.0)
  331. self.ftest('cbrt(1.2)', math.cbrt(1.2), 1.062658569182611)
  332. self.ftest('cbrt(-2.6)', math.cbrt(-2.6), -1.375068867074141)
  333. self.ftest('cbrt(27)', math.cbrt(27), 3)
  334. self.ftest('cbrt(-1)', math.cbrt(-1), -1)
  335. self.ftest('cbrt(-27)', math.cbrt(-27), -3)
  336. self.assertEqual(math.cbrt(INF), INF)
  337. self.assertEqual(math.cbrt(NINF), NINF)
  338. self.assertTrue(math.isnan(math.cbrt(NAN)))
  339. def testCeil(self):
  340. self.assertRaises(TypeError, math.ceil)
  341. self.assertEqual(int, type(math.ceil(0.5)))
  342. self.assertEqual(math.ceil(0.5), 1)
  343. self.assertEqual(math.ceil(1.0), 1)
  344. self.assertEqual(math.ceil(1.5), 2)
  345. self.assertEqual(math.ceil(-0.5), 0)
  346. self.assertEqual(math.ceil(-1.0), -1)
  347. self.assertEqual(math.ceil(-1.5), -1)
  348. self.assertEqual(math.ceil(0.0), 0)
  349. self.assertEqual(math.ceil(-0.0), 0)
  350. #self.assertEqual(math.ceil(INF), INF)
  351. #self.assertEqual(math.ceil(NINF), NINF)
  352. #self.assertTrue(math.isnan(math.ceil(NAN)))
  353. class TestCeil:
  354. def __ceil__(self):
  355. return 42
  356. class FloatCeil(float):
  357. def __ceil__(self):
  358. return 42
  359. class TestNoCeil:
  360. pass
  361. self.assertEqual(math.ceil(TestCeil()), 42)
  362. self.assertEqual(math.ceil(FloatCeil()), 42)
  363. self.assertEqual(math.ceil(FloatLike(42.5)), 43)
  364. self.assertRaises(TypeError, math.ceil, TestNoCeil())
  365. t = TestNoCeil()
  366. t.__ceil__ = lambda *args: args
  367. self.assertRaises(TypeError, math.ceil, t)
  368. self.assertRaises(TypeError, math.ceil, t, 0)
  369. @requires_IEEE_754
  370. def testCopysign(self):
  371. self.assertEqual(math.copysign(1, 42), 1.0)
  372. self.assertEqual(math.copysign(0., 42), 0.0)
  373. self.assertEqual(math.copysign(1., -42), -1.0)
  374. self.assertEqual(math.copysign(3, 0.), 3.0)
  375. self.assertEqual(math.copysign(4., -0.), -4.0)
  376. self.assertRaises(TypeError, math.copysign)
  377. # copysign should let us distinguish signs of zeros
  378. self.assertEqual(math.copysign(1., 0.), 1.)
  379. self.assertEqual(math.copysign(1., -0.), -1.)
  380. self.assertEqual(math.copysign(INF, 0.), INF)
  381. self.assertEqual(math.copysign(INF, -0.), NINF)
  382. self.assertEqual(math.copysign(NINF, 0.), INF)
  383. self.assertEqual(math.copysign(NINF, -0.), NINF)
  384. # and of infinities
  385. self.assertEqual(math.copysign(1., INF), 1.)
  386. self.assertEqual(math.copysign(1., NINF), -1.)
  387. self.assertEqual(math.copysign(INF, INF), INF)
  388. self.assertEqual(math.copysign(INF, NINF), NINF)
  389. self.assertEqual(math.copysign(NINF, INF), INF)
  390. self.assertEqual(math.copysign(NINF, NINF), NINF)
  391. self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
  392. self.assertTrue(math.isnan(math.copysign(NAN, INF)))
  393. self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
  394. self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
  395. # copysign(INF, NAN) may be INF or it may be NINF, since
  396. # we don't know whether the sign bit of NAN is set on any
  397. # given platform.
  398. self.assertTrue(math.isinf(math.copysign(INF, NAN)))
  399. # similarly, copysign(2., NAN) could be 2. or -2.
  400. self.assertEqual(abs(math.copysign(2., NAN)), 2.)
  401. def testCos(self):
  402. self.assertRaises(TypeError, math.cos)
  403. self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=math.ulp(1))
  404. self.ftest('cos(0)', math.cos(0), 1)
  405. self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=math.ulp(1))
  406. self.ftest('cos(pi)', math.cos(math.pi), -1)
  407. try:
  408. self.assertTrue(math.isnan(math.cos(INF)))
  409. self.assertTrue(math.isnan(math.cos(NINF)))
  410. except ValueError:
  411. self.assertRaises(ValueError, math.cos, INF)
  412. self.assertRaises(ValueError, math.cos, NINF)
  413. self.assertTrue(math.isnan(math.cos(NAN)))
  414. @unittest.skipIf(sys.platform == 'win32' and platform.machine() in ('ARM', 'ARM64'),
  415. "Windows UCRT is off by 2 ULP this test requires accuracy within 1 ULP")
  416. def testCosh(self):
  417. self.assertRaises(TypeError, math.cosh)
  418. self.ftest('cosh(0)', math.cosh(0), 1)
  419. self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
  420. self.assertEqual(math.cosh(INF), INF)
  421. self.assertEqual(math.cosh(NINF), INF)
  422. self.assertTrue(math.isnan(math.cosh(NAN)))
  423. def testDegrees(self):
  424. self.assertRaises(TypeError, math.degrees)
  425. self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
  426. self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
  427. self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
  428. self.ftest('degrees(0)', math.degrees(0), 0)
  429. def testExp(self):
  430. self.assertRaises(TypeError, math.exp)
  431. self.ftest('exp(-1)', math.exp(-1), 1/math.e)
  432. self.ftest('exp(0)', math.exp(0), 1)
  433. self.ftest('exp(1)', math.exp(1), math.e)
  434. self.assertEqual(math.exp(INF), INF)
  435. self.assertEqual(math.exp(NINF), 0.)
  436. self.assertTrue(math.isnan(math.exp(NAN)))
  437. self.assertRaises(OverflowError, math.exp, 1000000)
  438. def testExp2(self):
  439. self.assertRaises(TypeError, math.exp2)
  440. self.ftest('exp2(-1)', math.exp2(-1), 0.5)
  441. self.ftest('exp2(0)', math.exp2(0), 1)
  442. self.ftest('exp2(1)', math.exp2(1), 2)
  443. self.ftest('exp2(2.3)', math.exp2(2.3), 4.924577653379665)
  444. self.assertEqual(math.exp2(INF), INF)
  445. self.assertEqual(math.exp2(NINF), 0.)
  446. self.assertTrue(math.isnan(math.exp2(NAN)))
  447. self.assertRaises(OverflowError, math.exp2, 1000000)
  448. def testFabs(self):
  449. self.assertRaises(TypeError, math.fabs)
  450. self.ftest('fabs(-1)', math.fabs(-1), 1)
  451. self.ftest('fabs(0)', math.fabs(0), 0)
  452. self.ftest('fabs(1)', math.fabs(1), 1)
  453. def testFactorial(self):
  454. self.assertEqual(math.factorial(0), 1)
  455. total = 1
  456. for i in range(1, 1000):
  457. total *= i
  458. self.assertEqual(math.factorial(i), total)
  459. self.assertEqual(math.factorial(i), py_factorial(i))
  460. self.assertRaises(ValueError, math.factorial, -1)
  461. self.assertRaises(ValueError, math.factorial, -10**100)
  462. def testFactorialNonIntegers(self):
  463. self.assertRaises(TypeError, math.factorial, 5.0)
  464. self.assertRaises(TypeError, math.factorial, 5.2)
  465. self.assertRaises(TypeError, math.factorial, -1.0)
  466. self.assertRaises(TypeError, math.factorial, -1e100)
  467. self.assertRaises(TypeError, math.factorial, decimal.Decimal('5'))
  468. self.assertRaises(TypeError, math.factorial, decimal.Decimal('5.2'))
  469. self.assertRaises(TypeError, math.factorial, "5")
  470. # Other implementations may place different upper bounds.
  471. @support.cpython_only
  472. def testFactorialHugeInputs(self):
  473. # Currently raises OverflowError for inputs that are too large
  474. # to fit into a C long.
  475. self.assertRaises(OverflowError, math.factorial, 10**100)
  476. self.assertRaises(TypeError, math.factorial, 1e100)
  477. def testFloor(self):
  478. self.assertRaises(TypeError, math.floor)
  479. self.assertEqual(int, type(math.floor(0.5)))
  480. self.assertEqual(math.floor(0.5), 0)
  481. self.assertEqual(math.floor(1.0), 1)
  482. self.assertEqual(math.floor(1.5), 1)
  483. self.assertEqual(math.floor(-0.5), -1)
  484. self.assertEqual(math.floor(-1.0), -1)
  485. self.assertEqual(math.floor(-1.5), -2)
  486. #self.assertEqual(math.ceil(INF), INF)
  487. #self.assertEqual(math.ceil(NINF), NINF)
  488. #self.assertTrue(math.isnan(math.floor(NAN)))
  489. class TestFloor:
  490. def __floor__(self):
  491. return 42
  492. class FloatFloor(float):
  493. def __floor__(self):
  494. return 42
  495. class TestNoFloor:
  496. pass
  497. self.assertEqual(math.floor(TestFloor()), 42)
  498. self.assertEqual(math.floor(FloatFloor()), 42)
  499. self.assertEqual(math.floor(FloatLike(41.9)), 41)
  500. self.assertRaises(TypeError, math.floor, TestNoFloor())
  501. t = TestNoFloor()
  502. t.__floor__ = lambda *args: args
  503. self.assertRaises(TypeError, math.floor, t)
  504. self.assertRaises(TypeError, math.floor, t, 0)
  505. def testFmod(self):
  506. self.assertRaises(TypeError, math.fmod)
  507. self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
  508. self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
  509. self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
  510. self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
  511. self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
  512. self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
  513. self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
  514. self.assertTrue(math.isnan(math.fmod(1., NAN)))
  515. self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
  516. self.assertRaises(ValueError, math.fmod, 1., 0.)
  517. self.assertRaises(ValueError, math.fmod, INF, 1.)
  518. self.assertRaises(ValueError, math.fmod, NINF, 1.)
  519. self.assertRaises(ValueError, math.fmod, INF, 0.)
  520. self.assertEqual(math.fmod(3.0, INF), 3.0)
  521. self.assertEqual(math.fmod(-3.0, INF), -3.0)
  522. self.assertEqual(math.fmod(3.0, NINF), 3.0)
  523. self.assertEqual(math.fmod(-3.0, NINF), -3.0)
  524. self.assertEqual(math.fmod(0.0, 3.0), 0.0)
  525. self.assertEqual(math.fmod(0.0, NINF), 0.0)
  526. def testFrexp(self):
  527. self.assertRaises(TypeError, math.frexp)
  528. def testfrexp(name, result, expected):
  529. (mant, exp), (emant, eexp) = result, expected
  530. if abs(mant-emant) > eps or exp != eexp:
  531. self.fail('%s returned %r, expected %r'%\
  532. (name, result, expected))
  533. testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
  534. testfrexp('frexp(0)', math.frexp(0), (0, 0))
  535. testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
  536. testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
  537. self.assertEqual(math.frexp(INF)[0], INF)
  538. self.assertEqual(math.frexp(NINF)[0], NINF)
  539. self.assertTrue(math.isnan(math.frexp(NAN)[0]))
  540. @requires_IEEE_754
  541. @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
  542. "fsum is not exact on machines with double rounding")
  543. def testFsum(self):
  544. # math.fsum relies on exact rounding for correct operation.
  545. # There's a known problem with IA32 floating-point that causes
  546. # inexact rounding in some situations, and will cause the
  547. # math.fsum tests below to fail; see issue #2937. On non IEEE
  548. # 754 platforms, and on IEEE 754 platforms that exhibit the
  549. # problem described in issue #2937, we simply skip the whole
  550. # test.
  551. # Python version of math.fsum, for comparison. Uses a
  552. # different algorithm based on frexp, ldexp and integer
  553. # arithmetic.
  554. from sys import float_info
  555. mant_dig = float_info.mant_dig
  556. etiny = float_info.min_exp - mant_dig
  557. def msum(iterable):
  558. """Full precision summation. Compute sum(iterable) without any
  559. intermediate accumulation of error. Based on the 'lsum' function
  560. at http://code.activestate.com/recipes/393090/
  561. """
  562. tmant, texp = 0, 0
  563. for x in iterable:
  564. mant, exp = math.frexp(x)
  565. mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
  566. if texp > exp:
  567. tmant <<= texp-exp
  568. texp = exp
  569. else:
  570. mant <<= exp-texp
  571. tmant += mant
  572. # Round tmant * 2**texp to a float. The original recipe
  573. # used float(str(tmant)) * 2.0**texp for this, but that's
  574. # a little unsafe because str -> float conversion can't be
  575. # relied upon to do correct rounding on all platforms.
  576. tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
  577. if tail > 0:
  578. h = 1 << (tail-1)
  579. tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
  580. texp += tail
  581. return math.ldexp(tmant, texp)
  582. test_values = [
  583. ([], 0.0),
  584. ([0.0], 0.0),
  585. ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
  586. ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
  587. ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
  588. ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
  589. ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
  590. ([1./n for n in range(1, 1001)],
  591. float.fromhex('0x1.df11f45f4e61ap+2')),
  592. ([(-1.)**n/n for n in range(1, 1001)],
  593. float.fromhex('-0x1.62a2af1bd3624p-1')),
  594. ([1e16, 1., 1e-16], 10000000000000002.0),
  595. ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
  596. # exercise code for resizing partials array
  597. ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
  598. [-2.**1022],
  599. float.fromhex('0x1.5555555555555p+970')),
  600. ]
  601. # Telescoping sum, with exact differences (due to Sterbenz)
  602. terms = [1.7**i for i in range(1001)]
  603. test_values.append((
  604. [terms[i+1] - terms[i] for i in range(1000)] + [-terms[1000]],
  605. -terms[0]
  606. ))
  607. for i, (vals, expected) in enumerate(test_values):
  608. try:
  609. actual = math.fsum(vals)
  610. except OverflowError:
  611. self.fail("test %d failed: got OverflowError, expected %r "
  612. "for math.fsum(%.100r)" % (i, expected, vals))
  613. except ValueError:
  614. self.fail("test %d failed: got ValueError, expected %r "
  615. "for math.fsum(%.100r)" % (i, expected, vals))
  616. self.assertEqual(actual, expected)
  617. from random import random, gauss, shuffle
  618. for j in range(1000):
  619. vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
  620. s = 0
  621. for i in range(200):
  622. v = gauss(0, random()) ** 7 - s
  623. s += v
  624. vals.append(v)
  625. shuffle(vals)
  626. s = msum(vals)
  627. self.assertEqual(msum(vals), math.fsum(vals))
  628. def testGcd(self):
  629. gcd = math.gcd
  630. self.assertEqual(gcd(0, 0), 0)
  631. self.assertEqual(gcd(1, 0), 1)
  632. self.assertEqual(gcd(-1, 0), 1)
  633. self.assertEqual(gcd(0, 1), 1)
  634. self.assertEqual(gcd(0, -1), 1)
  635. self.assertEqual(gcd(7, 1), 1)
  636. self.assertEqual(gcd(7, -1), 1)
  637. self.assertEqual(gcd(-23, 15), 1)
  638. self.assertEqual(gcd(120, 84), 12)
  639. self.assertEqual(gcd(84, -120), 12)
  640. self.assertEqual(gcd(1216342683557601535506311712,
  641. 436522681849110124616458784), 32)
  642. x = 434610456570399902378880679233098819019853229470286994367836600566
  643. y = 1064502245825115327754847244914921553977
  644. for c in (652560,
  645. 576559230871654959816130551884856912003141446781646602790216406874):
  646. a = x * c
  647. b = y * c
  648. self.assertEqual(gcd(a, b), c)
  649. self.assertEqual(gcd(b, a), c)
  650. self.assertEqual(gcd(-a, b), c)
  651. self.assertEqual(gcd(b, -a), c)
  652. self.assertEqual(gcd(a, -b), c)
  653. self.assertEqual(gcd(-b, a), c)
  654. self.assertEqual(gcd(-a, -b), c)
  655. self.assertEqual(gcd(-b, -a), c)
  656. self.assertEqual(gcd(), 0)
  657. self.assertEqual(gcd(120), 120)
  658. self.assertEqual(gcd(-120), 120)
  659. self.assertEqual(gcd(120, 84, 102), 6)
  660. self.assertEqual(gcd(120, 1, 84), 1)
  661. self.assertRaises(TypeError, gcd, 120.0)
  662. self.assertRaises(TypeError, gcd, 120.0, 84)
  663. self.assertRaises(TypeError, gcd, 120, 84.0)
  664. self.assertRaises(TypeError, gcd, 120, 1, 84.0)
  665. self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
  666. def testHypot(self):
  667. from decimal import Decimal
  668. from fractions import Fraction
  669. hypot = math.hypot
  670. # Test different numbers of arguments (from zero to five)
  671. # against a straightforward pure python implementation
  672. args = math.e, math.pi, math.sqrt(2.0), math.gamma(3.5), math.sin(2.1)
  673. for i in range(len(args)+1):
  674. self.assertAlmostEqual(
  675. hypot(*args[:i]),
  676. math.sqrt(sum(s**2 for s in args[:i]))
  677. )
  678. # Test allowable types (those with __float__)
  679. self.assertEqual(hypot(12.0, 5.0), 13.0)
  680. self.assertEqual(hypot(12, 5), 13)
  681. self.assertEqual(hypot(Decimal(12), Decimal(5)), 13)
  682. self.assertEqual(hypot(Fraction(12, 32), Fraction(5, 32)), Fraction(13, 32))
  683. self.assertEqual(hypot(bool(1), bool(0), bool(1), bool(1)), math.sqrt(3))
  684. # Test corner cases
  685. self.assertEqual(hypot(0.0, 0.0), 0.0) # Max input is zero
  686. self.assertEqual(hypot(-10.5), 10.5) # Negative input
  687. self.assertEqual(hypot(), 0.0) # Negative input
  688. self.assertEqual(1.0,
  689. math.copysign(1.0, hypot(-0.0)) # Convert negative zero to positive zero
  690. )
  691. self.assertEqual( # Handling of moving max to the end
  692. hypot(1.5, 1.5, 0.5),
  693. hypot(1.5, 0.5, 1.5),
  694. )
  695. # Test handling of bad arguments
  696. with self.assertRaises(TypeError): # Reject keyword args
  697. hypot(x=1)
  698. with self.assertRaises(TypeError): # Reject values without __float__
  699. hypot(1.1, 'string', 2.2)
  700. int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
  701. with self.assertRaises((ValueError, OverflowError)):
  702. hypot(1, int_too_big_for_float)
  703. # Any infinity gives positive infinity.
  704. self.assertEqual(hypot(INF), INF)
  705. self.assertEqual(hypot(0, INF), INF)
  706. self.assertEqual(hypot(10, INF), INF)
  707. self.assertEqual(hypot(-10, INF), INF)
  708. self.assertEqual(hypot(NAN, INF), INF)
  709. self.assertEqual(hypot(INF, NAN), INF)
  710. self.assertEqual(hypot(NINF, NAN), INF)
  711. self.assertEqual(hypot(NAN, NINF), INF)
  712. self.assertEqual(hypot(-INF, INF), INF)
  713. self.assertEqual(hypot(-INF, -INF), INF)
  714. self.assertEqual(hypot(10, -INF), INF)
  715. # If no infinity, any NaN gives a NaN.
  716. self.assertTrue(math.isnan(hypot(NAN)))
  717. self.assertTrue(math.isnan(hypot(0, NAN)))
  718. self.assertTrue(math.isnan(hypot(NAN, 10)))
  719. self.assertTrue(math.isnan(hypot(10, NAN)))
  720. self.assertTrue(math.isnan(hypot(NAN, NAN)))
  721. self.assertTrue(math.isnan(hypot(NAN)))
  722. # Verify scaling for extremely large values
  723. fourthmax = FLOAT_MAX / 4.0
  724. for n in range(32):
  725. self.assertTrue(math.isclose(hypot(*([fourthmax]*n)),
  726. fourthmax * math.sqrt(n)))
  727. # Verify scaling for extremely small values
  728. for exp in range(32):
  729. scale = FLOAT_MIN / 2.0 ** exp
  730. self.assertEqual(math.hypot(4*scale, 3*scale), 5*scale)
  731. @requires_IEEE_754
  732. @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
  733. "hypot() loses accuracy on machines with double rounding")
  734. def testHypotAccuracy(self):
  735. # Verify improved accuracy in cases that were known to be inaccurate.
  736. #
  737. # The new algorithm's accuracy depends on IEEE 754 arithmetic
  738. # guarantees, on having the usual ROUND HALF EVEN rounding mode, on
  739. # the system not having double rounding due to extended precision,
  740. # and on the compiler maintaining the specified order of operations.
  741. #
  742. # This test is known to succeed on most of our builds. If it fails
  743. # some build, we either need to add another skipIf if the cause is
  744. # identifiable; otherwise, we can remove this test entirely.
  745. hypot = math.hypot
  746. Decimal = decimal.Decimal
  747. high_precision = decimal.Context(prec=500)
  748. for hx, hy in [
  749. # Cases with a 1 ulp error in Python 3.7 compiled with Clang
  750. ('0x1.10e89518dca48p+29', '0x1.1970f7565b7efp+30'),
  751. ('0x1.10106eb4b44a2p+29', '0x1.ef0596cdc97f8p+29'),
  752. ('0x1.459c058e20bb7p+30', '0x1.993ca009b9178p+29'),
  753. ('0x1.378371ae67c0cp+30', '0x1.fbe6619854b4cp+29'),
  754. ('0x1.f4cd0574fb97ap+29', '0x1.50fe31669340ep+30'),
  755. ('0x1.494b2cdd3d446p+29', '0x1.212a5367b4c7cp+29'),
  756. ('0x1.f84e649f1e46dp+29', '0x1.1fa56bef8eec4p+30'),
  757. ('0x1.2e817edd3d6fap+30', '0x1.eb0814f1e9602p+29'),
  758. ('0x1.0d3a6e3d04245p+29', '0x1.32a62fea52352p+30'),
  759. ('0x1.888e19611bfc5p+29', '0x1.52b8e70b24353p+29'),
  760. # Cases with 2 ulp error in Python 3.8
  761. ('0x1.538816d48a13fp+29', '0x1.7967c5ca43e16p+29'),
  762. ('0x1.57b47b7234530p+29', '0x1.74e2c7040e772p+29'),
  763. ('0x1.821b685e9b168p+30', '0x1.677dc1c1e3dc6p+29'),
  764. ('0x1.9e8247f67097bp+29', '0x1.24bd2dc4f4baep+29'),
  765. ('0x1.b73b59e0cb5f9p+29', '0x1.da899ab784a97p+28'),
  766. ('0x1.94a8d2842a7cfp+30', '0x1.326a51d4d8d8ap+30'),
  767. ('0x1.e930b9cd99035p+29', '0x1.5a1030e18dff9p+30'),
  768. ('0x1.1592bbb0e4690p+29', '0x1.a9c337b33fb9ap+29'),
  769. ('0x1.1243a50751fd4p+29', '0x1.a5a10175622d9p+29'),
  770. ('0x1.57a8596e74722p+30', '0x1.42d1af9d04da9p+30'),
  771. # Cases with 1 ulp error in version fff3c28052e6b0
  772. ('0x1.ee7dbd9565899p+29', '0x1.7ab4d6fc6e4b4p+29'),
  773. ('0x1.5c6bfbec5c4dcp+30', '0x1.02511184b4970p+30'),
  774. ('0x1.59dcebba995cap+30', '0x1.50ca7e7c38854p+29'),
  775. ('0x1.768cdd94cf5aap+29', '0x1.9cfdc5571d38ep+29'),
  776. ('0x1.dcf137d60262ep+29', '0x1.1101621990b3ep+30'),
  777. ('0x1.3a2d006e288b0p+30', '0x1.e9a240914326cp+29'),
  778. ('0x1.62a32f7f53c61p+29', '0x1.47eb6cd72684fp+29'),
  779. ('0x1.d3bcb60748ef2p+29', '0x1.3f13c4056312cp+30'),
  780. ('0x1.282bdb82f17f3p+30', '0x1.640ba4c4eed3ap+30'),
  781. ('0x1.89d8c423ea0c6p+29', '0x1.d35dcfe902bc3p+29'),
  782. ]:
  783. x = float.fromhex(hx)
  784. y = float.fromhex(hy)
  785. with self.subTest(hx=hx, hy=hy, x=x, y=y):
  786. with decimal.localcontext(high_precision):
  787. z = float((Decimal(x)**2 + Decimal(y)**2).sqrt())
  788. self.assertEqual(hypot(x, y), z)
  789. def testDist(self):
  790. from decimal import Decimal as D
  791. from fractions import Fraction as F
  792. dist = math.dist
  793. sqrt = math.sqrt
  794. # Simple exact cases
  795. self.assertEqual(dist((1.0, 2.0, 3.0), (4.0, 2.0, -1.0)), 5.0)
  796. self.assertEqual(dist((1, 2, 3), (4, 2, -1)), 5.0)
  797. # Test different numbers of arguments (from zero to nine)
  798. # against a straightforward pure python implementation
  799. for i in range(9):
  800. for j in range(5):
  801. p = tuple(random.uniform(-5, 5) for k in range(i))
  802. q = tuple(random.uniform(-5, 5) for k in range(i))
  803. self.assertAlmostEqual(
  804. dist(p, q),
  805. sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
  806. )
  807. # Test non-tuple inputs
  808. self.assertEqual(dist([1.0, 2.0, 3.0], [4.0, 2.0, -1.0]), 5.0)
  809. self.assertEqual(dist(iter([1.0, 2.0, 3.0]), iter([4.0, 2.0, -1.0])), 5.0)
  810. # Test allowable types (those with __float__)
  811. self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0)
  812. self.assertEqual(dist((14, 1), (2, -4)), 13)
  813. self.assertEqual(dist((D(14), D(1)), (D(2), D(-4))), D(13))
  814. self.assertEqual(dist((F(14, 32), F(1, 32)), (F(2, 32), F(-4, 32))),
  815. F(13, 32))
  816. self.assertEqual(dist((True, True, False, True, False),
  817. (True, False, True, True, False)),
  818. sqrt(2.0))
  819. # Test corner cases
  820. self.assertEqual(dist((13.25, 12.5, -3.25),
  821. (13.25, 12.5, -3.25)),
  822. 0.0) # Distance with self is zero
  823. self.assertEqual(dist((), ()), 0.0) # Zero-dimensional case
  824. self.assertEqual(1.0, # Convert negative zero to positive zero
  825. math.copysign(1.0, dist((-0.0,), (0.0,)))
  826. )
  827. self.assertEqual(1.0, # Convert negative zero to positive zero
  828. math.copysign(1.0, dist((0.0,), (-0.0,)))
  829. )
  830. self.assertEqual( # Handling of moving max to the end
  831. dist((1.5, 1.5, 0.5), (0, 0, 0)),
  832. dist((1.5, 0.5, 1.5), (0, 0, 0))
  833. )
  834. # Verify tuple subclasses are allowed
  835. class T(tuple):
  836. pass
  837. self.assertEqual(dist(T((1, 2, 3)), ((4, 2, -1))), 5.0)
  838. # Test handling of bad arguments
  839. with self.assertRaises(TypeError): # Reject keyword args
  840. dist(p=(1, 2, 3), q=(4, 5, 6))
  841. with self.assertRaises(TypeError): # Too few args
  842. dist((1, 2, 3))
  843. with self.assertRaises(TypeError): # Too many args
  844. dist((1, 2, 3), (4, 5, 6), (7, 8, 9))
  845. with self.assertRaises(TypeError): # Scalars not allowed
  846. dist(1, 2)
  847. with self.assertRaises(TypeError): # Reject values without __float__
  848. dist((1.1, 'string', 2.2), (1, 2, 3))
  849. with self.assertRaises(ValueError): # Check dimension agree
  850. dist((1, 2, 3, 4), (5, 6, 7))
  851. with self.assertRaises(ValueError): # Check dimension agree
  852. dist((1, 2, 3), (4, 5, 6, 7))
  853. with self.assertRaises(TypeError): # Rejects invalid types
  854. dist("abc", "xyz")
  855. int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
  856. with self.assertRaises((ValueError, OverflowError)):
  857. dist((1, int_too_big_for_float), (2, 3))
  858. with self.assertRaises((ValueError, OverflowError)):
  859. dist((2, 3), (1, int_too_big_for_float))
  860. # Verify that the one dimensional case is equivalent to abs()
  861. for i in range(20):
  862. p, q = random.random(), random.random()
  863. self.assertEqual(dist((p,), (q,)), abs(p - q))
  864. # Test special values
  865. values = [NINF, -10.5, -0.0, 0.0, 10.5, INF, NAN]
  866. for p in itertools.product(values, repeat=3):
  867. for q in itertools.product(values, repeat=3):
  868. diffs = [px - qx for px, qx in zip(p, q)]
  869. if any(map(math.isinf, diffs)):
  870. # Any infinite difference gives positive infinity.
  871. self.assertEqual(dist(p, q), INF)
  872. elif any(map(math.isnan, diffs)):
  873. # If no infinity, any NaN gives a NaN.
  874. self.assertTrue(math.isnan(dist(p, q)))
  875. # Verify scaling for extremely large values
  876. fourthmax = FLOAT_MAX / 4.0
  877. for n in range(32):
  878. p = (fourthmax,) * n
  879. q = (0.0,) * n
  880. self.assertTrue(math.isclose(dist(p, q), fourthmax * math.sqrt(n)))
  881. self.assertTrue(math.isclose(dist(q, p), fourthmax * math.sqrt(n)))
  882. # Verify scaling for extremely small values
  883. for exp in range(32):
  884. scale = FLOAT_MIN / 2.0 ** exp
  885. p = (4*scale, 3*scale)
  886. q = (0.0, 0.0)
  887. self.assertEqual(math.dist(p, q), 5*scale)
  888. self.assertEqual(math.dist(q, p), 5*scale)
  889. def test_math_dist_leak(self):
  890. # gh-98897: Check for error handling does not leak memory
  891. with self.assertRaises(ValueError):
  892. math.dist([1, 2], [3, 4, 5])
  893. def testIsqrt(self):
  894. # Test a variety of inputs, large and small.
  895. test_values = (
  896. list(range(1000))
  897. + list(range(10**6 - 1000, 10**6 + 1000))
  898. + [2**e + i for e in range(60, 200) for i in range(-40, 40)]
  899. + [3**9999, 10**5001]
  900. )
  901. for value in test_values:
  902. with self.subTest(value=value):
  903. s = math.isqrt(value)
  904. self.assertIs(type(s), int)
  905. self.assertLessEqual(s*s, value)
  906. self.assertLess(value, (s+1)*(s+1))
  907. # Negative values
  908. with self.assertRaises(ValueError):
  909. math.isqrt(-1)
  910. # Integer-like things
  911. s = math.isqrt(True)
  912. self.assertIs(type(s), int)
  913. self.assertEqual(s, 1)
  914. s = math.isqrt(False)
  915. self.assertIs(type(s), int)
  916. self.assertEqual(s, 0)
  917. class IntegerLike(object):
  918. def __init__(self, value):
  919. self.value = value
  920. def __index__(self):
  921. return self.value
  922. s = math.isqrt(IntegerLike(1729))
  923. self.assertIs(type(s), int)
  924. self.assertEqual(s, 41)
  925. with self.assertRaises(ValueError):
  926. math.isqrt(IntegerLike(-3))
  927. # Non-integer-like things
  928. bad_values = [
  929. 3.5, "a string", decimal.Decimal("3.5"), 3.5j,
  930. 100.0, -4.0,
  931. ]
  932. for value in bad_values:
  933. with self.subTest(value=value):
  934. with self.assertRaises(TypeError):
  935. math.isqrt(value)
  936. def test_lcm(self):
  937. lcm = math.lcm
  938. self.assertEqual(lcm(0, 0), 0)
  939. self.assertEqual(lcm(1, 0), 0)
  940. self.assertEqual(lcm(-1, 0), 0)
  941. self.assertEqual(lcm(0, 1), 0)
  942. self.assertEqual(lcm(0, -1), 0)
  943. self.assertEqual(lcm(7, 1), 7)
  944. self.assertEqual(lcm(7, -1), 7)
  945. self.assertEqual(lcm(-23, 15), 345)
  946. self.assertEqual(lcm(120, 84), 840)
  947. self.assertEqual(lcm(84, -120), 840)
  948. self.assertEqual(lcm(1216342683557601535506311712,
  949. 436522681849110124616458784),
  950. 16592536571065866494401400422922201534178938447014944)
  951. x = 43461045657039990237
  952. y = 10645022458251153277
  953. for c in (652560,
  954. 57655923087165495981):
  955. a = x * c
  956. b = y * c
  957. d = x * y * c
  958. self.assertEqual(lcm(a, b), d)
  959. self.assertEqual(lcm(b, a), d)
  960. self.assertEqual(lcm(-a, b), d)
  961. self.assertEqual(lcm(b, -a), d)
  962. self.assertEqual(lcm(a, -b), d)
  963. self.assertEqual(lcm(-b, a), d)
  964. self.assertEqual(lcm(-a, -b), d)
  965. self.assertEqual(lcm(-b, -a), d)
  966. self.assertEqual(lcm(), 1)
  967. self.assertEqual(lcm(120), 120)
  968. self.assertEqual(lcm(-120), 120)
  969. self.assertEqual(lcm(120, 84, 102), 14280)
  970. self.assertEqual(lcm(120, 0, 84), 0)
  971. self.assertRaises(TypeError, lcm, 120.0)
  972. self.assertRaises(TypeError, lcm, 120.0, 84)
  973. self.assertRaises(TypeError, lcm, 120, 84.0)
  974. self.assertRaises(TypeError, lcm, 120, 0, 84.0)
  975. self.assertEqual(lcm(MyIndexable(120), MyIndexable(84)), 840)
  976. def testLdexp(self):
  977. self.assertRaises(TypeError, math.ldexp)
  978. self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
  979. self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
  980. self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
  981. self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
  982. self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
  983. self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
  984. self.assertEqual(math.ldexp(1., -1000000), 0.)
  985. self.assertEqual(math.ldexp(-1., -1000000), -0.)
  986. self.assertEqual(math.ldexp(INF, 30), INF)
  987. self.assertEqual(math.ldexp(NINF, -213), NINF)
  988. self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
  989. # large second argument
  990. for n in [10**5, 10**10, 10**20, 10**40]:
  991. self.assertEqual(math.ldexp(INF, -n), INF)
  992. self.assertEqual(math.ldexp(NINF, -n), NINF)
  993. self.assertEqual(math.ldexp(1., -n), 0.)
  994. self.assertEqual(math.ldexp(-1., -n), -0.)
  995. self.assertEqual(math.ldexp(0., -n), 0.)
  996. self.assertEqual(math.ldexp(-0., -n), -0.)
  997. self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
  998. self.assertRaises(OverflowError, math.ldexp, 1., n)
  999. self.assertRaises(OverflowError, math.ldexp, -1., n)
  1000. self.assertEqual(math.ldexp(0., n), 0.)
  1001. self.assertEqual(math.ldexp(-0., n), -0.)
  1002. self.assertEqual(math.ldexp(INF, n), INF)
  1003. self.assertEqual(math.ldexp(NINF, n), NINF)
  1004. self.assertTrue(math.isnan(math.ldexp(NAN, n)))
  1005. def testLog(self):
  1006. self.assertRaises(TypeError, math.log)
  1007. self.ftest('log(1/e)', math.log(1/math.e), -1)
  1008. self.ftest('log(1)', math.log(1), 0)
  1009. self.ftest('log(e)', math.log(math.e), 1)
  1010. self.ftest('log(32,2)', math.log(32,2), 5)
  1011. self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
  1012. self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
  1013. self.ftest('log(10**1000)', math.log(10**1000),
  1014. 2302.5850929940457)
  1015. self.assertRaises(ValueError, math.log, -1.5)
  1016. self.assertRaises(ValueError, math.log, -10**1000)
  1017. self.assertRaises(ValueError, math.log, NINF)
  1018. self.assertEqual(math.log(INF), INF)
  1019. self.assertTrue(math.isnan(math.log(NAN)))
  1020. def testLog1p(self):
  1021. self.assertRaises(TypeError, math.log1p)
  1022. for n in [2, 2**90, 2**300]:
  1023. self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
  1024. self.assertRaises(ValueError, math.log1p, -1)
  1025. self.assertEqual(math.log1p(INF), INF)
  1026. @requires_IEEE_754
  1027. def testLog2(self):
  1028. self.assertRaises(TypeError, math.log2)
  1029. # Check some integer values
  1030. self.assertEqual(math.log2(1), 0.0)
  1031. self.assertEqual(math.log2(2), 1.0)
  1032. self.assertEqual(math.log2(4), 2.0)
  1033. # Large integer values
  1034. self.assertEqual(math.log2(2**1023), 1023.0)
  1035. self.assertEqual(math.log2(2**1024), 1024.0)
  1036. self.assertEqual(math.log2(2**2000), 2000.0)
  1037. self.assertRaises(ValueError, math.log2, -1.5)
  1038. self.assertRaises(ValueError, math.log2, NINF)
  1039. self.assertTrue(math.isnan(math.log2(NAN)))
  1040. @requires_IEEE_754
  1041. # log2() is not accurate enough on Mac OS X Tiger (10.4)
  1042. @support.requires_mac_ver(10, 5)
  1043. def testLog2Exact(self):
  1044. # Check that we get exact equality for log2 of powers of 2.
  1045. actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
  1046. expected = [float(n) for n in range(-1074, 1024)]
  1047. self.assertEqual(actual, expected)
  1048. def testLog10(self):
  1049. self.assertRaises(TypeError, math.log10)
  1050. self.ftest('log10(0.1)', math.log10(0.1), -1)
  1051. self.ftest('log10(1)', math.log10(1), 0)
  1052. self.ftest('log10(10)', math.log10(10), 1)
  1053. self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
  1054. self.assertRaises(ValueError, math.log10, -1.5)
  1055. self.assertRaises(ValueError, math.log10, -10**1000)
  1056. self.assertRaises(ValueError, math.log10, NINF)
  1057. self.assertEqual(math.log(INF), INF)
  1058. self.assertTrue(math.isnan(math.log10(NAN)))
  1059. def testModf(self):
  1060. self.assertRaises(TypeError, math.modf)
  1061. def testmodf(name, result, expected):
  1062. (v1, v2), (e1, e2) = result, expected
  1063. if abs(v1-e1) > eps or abs(v2-e2):
  1064. self.fail('%s returned %r, expected %r'%\
  1065. (name, result, expected))
  1066. testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
  1067. testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
  1068. self.assertEqual(math.modf(INF), (0.0, INF))
  1069. self.assertEqual(math.modf(NINF), (-0.0, NINF))
  1070. modf_nan = math.modf(NAN)
  1071. self.assertTrue(math.isnan(modf_nan[0]))
  1072. self.assertTrue(math.isnan(modf_nan[1]))
  1073. def testPow(self):
  1074. self.assertRaises(TypeError, math.pow)
  1075. self.ftest('pow(0,1)', math.pow(0,1), 0)
  1076. self.ftest('pow(1,0)', math.pow(1,0), 1)
  1077. self.ftest('pow(2,1)', math.pow(2,1), 2)
  1078. self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
  1079. self.assertEqual(math.pow(INF, 1), INF)
  1080. self.assertEqual(math.pow(NINF, 1), NINF)
  1081. self.assertEqual((math.pow(1, INF)), 1.)
  1082. self.assertEqual((math.pow(1, NINF)), 1.)
  1083. self.assertTrue(math.isnan(math.pow(NAN, 1)))
  1084. self.assertTrue(math.isnan(math.pow(2, NAN)))
  1085. self.assertTrue(math.isnan(math.pow(0, NAN)))
  1086. self.assertEqual(math.pow(1, NAN), 1)
  1087. # pow(0., x)
  1088. self.assertEqual(math.pow(0., INF), 0.)
  1089. self.assertEqual(math.pow(0., 3.), 0.)
  1090. self.assertEqual(math.pow(0., 2.3), 0.)
  1091. self.assertEqual(math.pow(0., 2.), 0.)
  1092. self.assertEqual(math.pow(0., 0.), 1.)
  1093. self.assertEqual(math.pow(0., -0.), 1.)
  1094. self.assertRaises(ValueError, math.pow, 0., -2.)
  1095. self.assertRaises(ValueError, math.pow, 0., -2.3)
  1096. self.assertRaises(ValueError, math.pow, 0., -3.)
  1097. self.assertEqual(math.pow(0., NINF), INF)
  1098. self.assertTrue(math.isnan(math.pow(0., NAN)))
  1099. # pow(INF, x)
  1100. self.assertEqual(math.pow(INF, INF), INF)
  1101. self.assertEqual(math.pow(INF, 3.), INF)
  1102. self.assertEqual(math.pow(INF, 2.3), INF)
  1103. self.assertEqual(math.pow(INF, 2.), INF)
  1104. self.assertEqual(math.pow(INF, 0.), 1.)
  1105. self.assertEqual(math.pow(INF, -0.), 1.)
  1106. self.assertEqual(math.pow(INF, -2.), 0.)
  1107. self.assertEqual(math.pow(INF, -2.3), 0.)
  1108. self.assertEqual(math.pow(INF, -3.), 0.)
  1109. self.assertEqual(math.pow(INF, NINF), 0.)
  1110. self.assertTrue(math.isnan(math.pow(INF, NAN)))
  1111. # pow(-0., x)
  1112. self.assertEqual(math.pow(-0., INF), 0.)
  1113. self.assertEqual(math.pow(-0., 3.), -0.)
  1114. self.assertEqual(math.pow(-0., 2.3), 0.)
  1115. self.assertEqual(math.pow(-0., 2.), 0.)
  1116. self.assertEqual(math.pow(-0., 0.), 1.)
  1117. self.assertEqual(math.pow(-0., -0.), 1.)
  1118. self.assertRaises(ValueError, math.pow, -0., -2.)
  1119. self.assertRaises(ValueError, math.pow, -0., -2.3)
  1120. self.assertRaises(ValueError, math.pow, -0., -3.)
  1121. self.assertEqual(math.pow(-0., NINF), INF)
  1122. self.assertTrue(math.isnan(math.pow(-0., NAN)))
  1123. # pow(NINF, x)
  1124. self.assertEqual(math.pow(NINF, INF), INF)
  1125. self.assertEqual(math.pow(NINF, 3.), NINF)
  1126. self.assertEqual(math.pow(NINF, 2.3), INF)
  1127. self.assertEqual(math.pow(NINF, 2.), INF)
  1128. self.assertEqual(math.pow(NINF, 0.), 1.)
  1129. self.assertEqual(math.pow(NINF, -0.), 1.)
  1130. self.assertEqual(math.pow(NINF, -2.), 0.)
  1131. self.assertEqual(math.pow(NINF, -2.3), 0.)
  1132. self.assertEqual(math.pow(NINF, -3.), -0.)
  1133. self.assertEqual(math.pow(NINF, NINF), 0.)
  1134. self.assertTrue(math.isnan(math.pow(NINF, NAN)))
  1135. # pow(-1, x)
  1136. self.assertEqual(math.pow(-1., INF), 1.)
  1137. self.assertEqual(math.pow(-1., 3.), -1.)
  1138. self.assertRaises(ValueError, math.pow, -1., 2.3)
  1139. self.assertEqual(math.pow(-1., 2.), 1.)
  1140. self.assertEqual(math.pow(-1., 0.), 1.)
  1141. self.assertEqual(math.pow(-1., -0.), 1.)
  1142. self.assertEqual(math.pow(-1., -2.), 1.)
  1143. self.assertRaises(ValueError, math.pow, -1., -2.3)
  1144. self.assertEqual(math.pow(-1., -3.), -1.)
  1145. self.assertEqual(math.pow(-1., NINF), 1.)
  1146. self.assertTrue(math.isnan(math.pow(-1., NAN)))
  1147. # pow(1, x)
  1148. self.assertEqual(math.pow(1., INF), 1.)
  1149. self.assertEqual(math.pow(1., 3.), 1.)
  1150. self.assertEqual(math.pow(1., 2.3), 1.)
  1151. self.assertEqual(math.pow(1., 2.), 1.)
  1152. self.assertEqual(math.pow(1., 0.), 1.)
  1153. self.assertEqual(math.pow(1., -0.), 1.)
  1154. self.assertEqual(math.pow(1., -2.), 1.)
  1155. self.assertEqual(math.pow(1., -2.3), 1.)
  1156. self.assertEqual(math.pow(1., -3.), 1.)
  1157. self.assertEqual(math.pow(1., NINF), 1.)
  1158. self.assertEqual(math.pow(1., NAN), 1.)
  1159. # pow(x, 0) should be 1 for any x
  1160. self.assertEqual(math.pow(2.3, 0.), 1.)
  1161. self.assertEqual(math.pow(-2.3, 0.), 1.)
  1162. self.assertEqual(math.pow(NAN, 0.), 1.)
  1163. self.assertEqual(math.pow(2.3, -0.), 1.)
  1164. self.assertEqual(math.pow(-2.3, -0.), 1.)
  1165. self.assertEqual(math.pow(NAN, -0.), 1.)
  1166. # pow(x, y) is invalid if x is negative and y is not integral
  1167. self.assertRaises(ValueError, math.pow, -1., 2.3)
  1168. self.assertRaises(ValueError, math.pow, -15., -3.1)
  1169. # pow(x, NINF)
  1170. self.assertEqual(math.pow(1.9, NINF), 0.)
  1171. self.assertEqual(math.pow(1.1, NINF), 0.)
  1172. self.assertEqual(math.pow(0.9, NINF), INF)
  1173. self.assertEqual(math.pow(0.1, NINF), INF)
  1174. self.assertEqual(math.pow(-0.1, NINF), INF)
  1175. self.assertEqual(math.pow(-0.9, NINF), INF)
  1176. self.assertEqual(math.pow(-1.1, NINF), 0.)
  1177. self.assertEqual(math.pow(-1.9, NINF), 0.)
  1178. # pow(x, INF)
  1179. self.assertEqual(math.pow(1.9, INF), INF)
  1180. self.assertEqual(math.pow(1.1, INF), INF)
  1181. self.assertEqual(math.pow(0.9, INF), 0.)
  1182. self.assertEqual(math.pow(0.1, INF), 0.)
  1183. self.assertEqual(math.pow(-0.1, INF), 0.)
  1184. self.assertEqual(math.pow(-0.9, INF), 0.)
  1185. self.assertEqual(math.pow(-1.1, INF), INF)
  1186. self.assertEqual(math.pow(-1.9, INF), INF)
  1187. # pow(x, y) should work for x negative, y an integer
  1188. self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
  1189. self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
  1190. self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
  1191. self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
  1192. self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
  1193. self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
  1194. self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
  1195. self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
  1196. self.assertRaises(ValueError, math.pow, -2.0, -0.5)
  1197. self.assertRaises(ValueError, math.pow, -2.0, 0.5)
  1198. # the following tests have been commented out since they don't
  1199. # really belong here: the implementation of ** for floats is
  1200. # independent of the implementation of math.pow
  1201. #self.assertEqual(1**NAN, 1)
  1202. #self.assertEqual(1**INF, 1)
  1203. #self.assertEqual(1**NINF, 1)
  1204. #self.assertEqual(1**0, 1)
  1205. #self.assertEqual(1.**NAN, 1)
  1206. #self.assertEqual(1.**INF, 1)
  1207. #self.assertEqual(1.**NINF, 1)
  1208. #self.assertEqual(1.**0, 1)
  1209. def testRadians(self):
  1210. self.assertRaises(TypeError, math.radians)
  1211. self.ftest('radians(180)', math.radians(180), math.pi)
  1212. self.ftest('radians(90)', math.radians(90), math.pi/2)
  1213. self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
  1214. self.ftest('radians(0)', math.radians(0), 0)
  1215. @requires_IEEE_754
  1216. def testRemainder(self):
  1217. from fractions import Fraction
  1218. def validate_spec(x, y, r):
  1219. """
  1220. Check that r matches remainder(x, y) according to the IEEE 754
  1221. specification. Assumes that x, y and r are finite and y is nonzero.
  1222. """
  1223. fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
  1224. # r should not exceed y/2 in absolute value
  1225. self.assertLessEqual(abs(fr), abs(fy/2))
  1226. # x - r should be an exact integer multiple of y
  1227. n = (fx - fr) / fy
  1228. self.assertEqual(n, int(n))
  1229. if abs(fr) == abs(fy/2):
  1230. # If |r| == |y/2|, n should be even.
  1231. self.assertEqual(n/2, int(n/2))
  1232. # triples (x, y, remainder(x, y)) in hexadecimal form.
  1233. testcases = [
  1234. # Remainders modulo 1, showing the ties-to-even behaviour.
  1235. '-4.0 1 -0.0',
  1236. '-3.8 1 0.8',
  1237. '-3.0 1 -0.0',
  1238. '-2.8 1 -0.8',
  1239. '-2.0 1 -0.0',
  1240. '-1.8 1 0.8',
  1241. '-1.0 1 -0.0',
  1242. '-0.8 1 -0.8',
  1243. '-0.0 1 -0.0',
  1244. ' 0.0 1 0.0',
  1245. ' 0.8 1 0.8',
  1246. ' 1.0 1 0.0',
  1247. ' 1.8 1 -0.8',
  1248. ' 2.0 1 0.0',
  1249. ' 2.8 1 0.8',
  1250. ' 3.0 1 0.0',
  1251. ' 3.8 1 -0.8',
  1252. ' 4.0 1 0.0',
  1253. # Reductions modulo 2*pi
  1254. '0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0',
  1255. '0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0',
  1256. '0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1',
  1257. '0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
  1258. '0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1',
  1259. '0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2',
  1260. '0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0',
  1261. '0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2',
  1262. '0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
  1263. '0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1',
  1264. '0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
  1265. '0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3',
  1266. '0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0',
  1267. '0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3',
  1268. '0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
  1269. '0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
  1270. '0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
  1271. '0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1',
  1272. '0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1',
  1273. # Symmetry with respect to signs.
  1274. ' 1 0.c 0.4',
  1275. '-1 0.c -0.4',
  1276. ' 1 -0.c 0.4',
  1277. '-1 -0.c -0.4',
  1278. ' 1.4 0.c -0.4',
  1279. '-1.4 0.c 0.4',
  1280. ' 1.4 -0.c -0.4',
  1281. '-1.4 -0.c 0.4',
  1282. # Huge modulus, to check that the underlying algorithm doesn't
  1283. # rely on 2.0 * modulus being representable.
  1284. '0x1.dp+1023 0x1.4p+1023 0x0.9p+1023',
  1285. '0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023',
  1286. '0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023',
  1287. ]
  1288. for case in testcases:
  1289. with self.subTest(case=case):
  1290. x_hex, y_hex, expected_hex = case.split()
  1291. x = float.fromhex(x_hex)
  1292. y = float.fromhex(y_hex)
  1293. expected = float.fromhex(expected_hex)
  1294. validate_spec(x, y, expected)
  1295. actual = math.remainder(x, y)
  1296. # Cheap way of checking that the floats are
  1297. # as identical as we need them to be.
  1298. self.assertEqual(actual.hex(), expected.hex())
  1299. # Test tiny subnormal modulus: there's potential for
  1300. # getting the implementation wrong here (for example,
  1301. # by assuming that modulus/2 is exactly representable).
  1302. tiny = float.fromhex('1p-1074') # min +ve subnormal
  1303. for n in range(-25, 25):
  1304. if n == 0:
  1305. continue
  1306. y = n * tiny
  1307. for m in range(100):
  1308. x = m * tiny
  1309. actual = math.remainder(x, y)
  1310. validate_spec(x, y, actual)
  1311. actual = math.remainder(-x, y)
  1312. validate_spec(-x, y, actual)
  1313. # Special values.
  1314. # NaNs should propagate as usual.
  1315. for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]:
  1316. self.assertIsNaN(math.remainder(NAN, value))
  1317. self.assertIsNaN(math.remainder(value, NAN))
  1318. # remainder(x, inf) is x, for non-nan non-infinite x.
  1319. for value in [-2.3, -0.0, 0.0, 2.3]:
  1320. self.assertEqual(math.remainder(value, INF), value)
  1321. self.assertEqual(math.remainder(value, NINF), value)
  1322. # remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid
  1323. # operations according to IEEE 754-2008 7.2(f), and should raise.
  1324. for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]:
  1325. with self.assertRaises(ValueError):
  1326. math.remainder(INF, value)
  1327. with self.assertRaises(ValueError):
  1328. math.remainder(NINF, value)
  1329. with self.assertRaises(ValueError):
  1330. math.remainder(value, 0.0)
  1331. with self.assertRaises(ValueError):
  1332. math.remainder(value, -0.0)
  1333. def testSin(self):
  1334. self.assertRaises(TypeError, math.sin)
  1335. self.ftest('sin(0)', math.sin(0), 0)
  1336. self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
  1337. self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
  1338. try:
  1339. self.assertTrue(math.isnan(math.sin(INF)))
  1340. self.assertTrue(math.isnan(math.sin(NINF)))
  1341. except ValueError:
  1342. self.assertRaises(ValueError, math.sin, INF)
  1343. self.assertRaises(ValueError, math.sin, NINF)
  1344. self.assertTrue(math.isnan(math.sin(NAN)))
  1345. def testSinh(self):
  1346. self.assertRaises(TypeError, math.sinh)
  1347. self.ftest('sinh(0)', math.sinh(0), 0)
  1348. self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
  1349. self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
  1350. self.assertEqual(math.sinh(INF), INF)
  1351. self.assertEqual(math.sinh(NINF), NINF)
  1352. self.assertTrue(math.isnan(math.sinh(NAN)))
  1353. def testSqrt(self):
  1354. self.assertRaises(TypeError, math.sqrt)
  1355. self.ftest('sqrt(0)', math.sqrt(0), 0)
  1356. self.ftest('sqrt(0)', math.sqrt(0.0), 0.0)
  1357. self.ftest('sqrt(2.5)', math.sqrt(2.5), 1.5811388300841898)
  1358. self.ftest('sqrt(0.25)', math.sqrt(0.25), 0.5)
  1359. self.ftest('sqrt(25.25)', math.sqrt(25.25), 5.024937810560445)
  1360. self.ftest('sqrt(1)', math.sqrt(1), 1)
  1361. self.ftest('sqrt(4)', math.sqrt(4), 2)
  1362. self.assertEqual(math.sqrt(INF), INF)
  1363. self.assertRaises(ValueError, math.sqrt, -1)
  1364. self.assertRaises(ValueError, math.sqrt, NINF)
  1365. self.assertTrue(math.isnan(math.sqrt(NAN)))
  1366. def testTan(self):
  1367. self.assertRaises(TypeError, math.tan)
  1368. self.ftest('tan(0)', math.tan(0), 0)
  1369. self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
  1370. self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
  1371. try:
  1372. self.assertTrue(math.isnan(math.tan(INF)))
  1373. self.assertTrue(math.isnan(math.tan(NINF)))
  1374. except:
  1375. self.assertRaises(ValueError, math.tan, INF)
  1376. self.assertRaises(ValueError, math.tan, NINF)
  1377. self.assertTrue(math.isnan(math.tan(NAN)))
  1378. def testTanh(self):
  1379. self.assertRaises(TypeError, math.tanh)
  1380. self.ftest('tanh(0)', math.tanh(0), 0)
  1381. self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
  1382. abs_tol=math.ulp(1))
  1383. self.ftest('tanh(inf)', math.tanh(INF), 1)
  1384. self.ftest('tanh(-inf)', math.tanh(NINF), -1)
  1385. self.assertTrue(math.isnan(math.tanh(NAN)))
  1386. @requires_IEEE_754
  1387. def testTanhSign(self):
  1388. # check that tanh(-0.) == -0. on IEEE 754 systems
  1389. self.assertEqual(math.tanh(-0.), -0.)
  1390. self.assertEqual(math.copysign(1., math.tanh(-0.)),
  1391. math.copysign(1., -0.))
  1392. def test_trunc(self):
  1393. self.assertEqual(math.trunc(1), 1)
  1394. self.assertEqual(math.trunc(-1), -1)
  1395. self.assertEqual(type(math.trunc(1)), int)
  1396. self.assertEqual(type(math.trunc(1.5)), int)
  1397. self.assertEqual(math.trunc(1.5), 1)
  1398. self.assertEqual(math.trunc(-1.5), -1)
  1399. self.assertEqual(math.trunc(1.999999), 1)
  1400. self.assertEqual(math.trunc(-1.999999), -1)
  1401. self.assertEqual(math.trunc(-0.999999), -0)
  1402. self.assertEqual(math.trunc(-100.999), -100)
  1403. class TestTrunc:
  1404. def __trunc__(self):
  1405. return 23
  1406. class FloatTrunc(float):
  1407. def __trunc__(self):
  1408. return 23
  1409. class TestNoTrunc:
  1410. pass
  1411. self.assertEqual(math.trunc(TestTrunc()), 23)
  1412. self.assertEqual(math.trunc(FloatTrunc()), 23)
  1413. self.assertRaises(TypeError, math.trunc)
  1414. self.assertRaises(TypeError, math.trunc, 1, 2)
  1415. self.assertRaises(TypeError, math.trunc, FloatLike(23.5))
  1416. self.assertRaises(TypeError, math.trunc, TestNoTrunc())
  1417. def testIsfinite(self):
  1418. self.assertTrue(math.isfinite(0.0))
  1419. self.assertTrue(math.isfinite(-0.0))
  1420. self.assertTrue(math.isfinite(1.0))
  1421. self.assertTrue(math.isfinite(-1.0))
  1422. self.assertFalse(math.isfinite(float("nan")))
  1423. self.assertFalse(math.isfinite(float("inf")))
  1424. self.assertFalse(math.isfinite(float("-inf")))
  1425. def testIsnan(self):
  1426. self.assertTrue(math.isnan(float("nan")))
  1427. self.assertTrue(math.isnan(float("-nan")))
  1428. self.assertTrue(math.isnan(float("inf") * 0.))
  1429. self.assertFalse(math.isnan(float("inf")))
  1430. self.assertFalse(math.isnan(0.))
  1431. self.assertFalse(math.isnan(1.))
  1432. def testIsinf(self):
  1433. self.assertTrue(math.isinf(float("inf")))
  1434. self.assertTrue(math.isinf(float("-inf")))
  1435. self.assertTrue(math.isinf(1E400))
  1436. self.assertTrue(math.isinf(-1E400))
  1437. self.assertFalse(math.isinf(float("nan")))
  1438. self.assertFalse(math.isinf(0.))
  1439. self.assertFalse(math.isinf(1.))
  1440. @requires_IEEE_754
  1441. def test_nan_constant(self):
  1442. self.assertTrue(math.isnan(math.nan))
  1443. @requires_IEEE_754
  1444. def test_inf_constant(self):
  1445. self.assertTrue(math.isinf(math.inf))
  1446. self.assertGreater(math.inf, 0.0)
  1447. self.assertEqual(math.inf, float("inf"))
  1448. self.assertEqual(-math.inf, float("-inf"))
  1449. # RED_FLAG 16-Oct-2000 Tim
  1450. # While 2.0 is more consistent about exceptions than previous releases, it
  1451. # still fails this part of the test on some platforms. For now, we only
  1452. # *run* test_exceptions() in verbose mode, so that this isn't normally
  1453. # tested.
  1454. @unittest.skipUnless(verbose, 'requires verbose mode')
  1455. def test_exceptions(self):
  1456. try:
  1457. x = math.exp(-1000000000)
  1458. except:
  1459. # mathmodule.c is failing to weed out underflows from libm, or
  1460. # we've got an fp format with huge dynamic range
  1461. self.fail("underflowing exp() should not have raised "
  1462. "an exception")
  1463. if x != 0:
  1464. self.fail("underflowing exp() should have returned 0")
  1465. # If this fails, probably using a strict IEEE-754 conforming libm, and x
  1466. # is +Inf afterwards. But Python wants overflows detected by default.
  1467. try:
  1468. x = math.exp(1000000000)
  1469. except OverflowError:
  1470. pass
  1471. else:
  1472. self.fail("overflowing exp() didn't trigger OverflowError")
  1473. # If this fails, it could be a puzzle. One odd possibility is that
  1474. # mathmodule.c's macros are getting confused while comparing
  1475. # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
  1476. # as a result (and so raising OverflowError instead).
  1477. try:
  1478. x = math.sqrt(-1.0)
  1479. except ValueError:
  1480. pass
  1481. else:
  1482. self.fail("sqrt(-1) didn't raise ValueError")
  1483. @requires_IEEE_754
  1484. def test_testfile(self):
  1485. # Some tests need to be skipped on ancient OS X versions.
  1486. # See issue #27953.
  1487. SKIP_ON_TIGER = {'tan0064'}
  1488. osx_version = None
  1489. if sys.platform == 'darwin':
  1490. version_txt = platform.mac_ver()[0]
  1491. try:
  1492. osx_version = tuple(map(int, version_txt.split('.')))
  1493. except ValueError:
  1494. pass
  1495. fail_fmt = "{}: {}({!r}): {}"
  1496. failures = []
  1497. for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
  1498. # Skip if either the input or result is complex
  1499. if ai != 0.0 or ei != 0.0:
  1500. continue
  1501. if fn in ['rect', 'polar']:
  1502. # no real versions of rect, polar
  1503. continue
  1504. # Skip certain tests on OS X 10.4.
  1505. if osx_version is not None and osx_version < (10, 5):
  1506. if id in SKIP_ON_TIGER:
  1507. continue
  1508. func = getattr(math, fn)
  1509. if 'invalid' in flags or 'divide-by-zero' in flags:
  1510. er = 'ValueError'
  1511. elif 'overflow' in flags:
  1512. er = 'OverflowError'
  1513. try:
  1514. result = func(ar)
  1515. except ValueError:
  1516. result = 'ValueError'
  1517. except OverflowError:
  1518. result = 'OverflowError'
  1519. # Default tolerances
  1520. ulp_tol, abs_tol = 5, 0.0
  1521. failure = result_check(er, result, ulp_tol, abs_tol)
  1522. if failure is None:
  1523. continue
  1524. msg = fail_fmt.format(id, fn, ar, failure)
  1525. failures.append(msg)
  1526. if failures:
  1527. self.fail('Failures in test_testfile:\n ' +
  1528. '\n '.join(failures))
  1529. @requires_IEEE_754
  1530. def test_mtestfile(self):
  1531. fail_fmt = "{}: {}({!r}): {}"
  1532. failures = []
  1533. for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
  1534. func = getattr(math, fn)
  1535. if 'invalid' in flags or 'divide-by-zero' in flags:
  1536. expected = 'ValueError'
  1537. elif 'overflow' in flags:
  1538. expected = 'OverflowError'
  1539. try:
  1540. got = func(arg)
  1541. except ValueError:
  1542. got = 'ValueError'
  1543. except OverflowError:
  1544. got = 'OverflowError'
  1545. # Default tolerances
  1546. ulp_tol, abs_tol = 5, 0.0
  1547. # Exceptions to the defaults
  1548. if fn == 'gamma':
  1549. # Experimental results on one platform gave
  1550. # an accuracy of <= 10 ulps across the entire float
  1551. # domain. We weaken that to require 20 ulp accuracy.
  1552. ulp_tol = 20
  1553. elif fn == 'lgamma':
  1554. # we use a weaker accuracy test for lgamma;
  1555. # lgamma only achieves an absolute error of
  1556. # a few multiples of the machine accuracy, in
  1557. # general.
  1558. abs_tol = 1e-15
  1559. elif fn == 'erfc' and arg >= 0.0:
  1560. # erfc has less-than-ideal accuracy for large
  1561. # arguments (x ~ 25 or so), mainly due to the
  1562. # error involved in computing exp(-x*x).
  1563. #
  1564. # Observed between CPython and mpmath at 25 dp:
  1565. # x < 0 : err <= 2 ulp
  1566. # 0 <= x < 1 : err <= 10 ulp
  1567. # 1 <= x < 10 : err <= 100 ulp
  1568. # 10 <= x < 20 : err <= 300 ulp
  1569. # 20 <= x : < 600 ulp
  1570. #
  1571. if arg < 1.0:
  1572. ulp_tol = 10
  1573. elif arg < 10.0:
  1574. ulp_tol = 100
  1575. else:
  1576. ulp_tol = 1000
  1577. failure = result_check(expected, got, ulp_tol, abs_tol)
  1578. if failure is None:
  1579. continue
  1580. msg = fail_fmt.format(id, fn, arg, failure)
  1581. failures.append(msg)
  1582. if failures:
  1583. self.fail('Failures in test_mtestfile:\n ' +
  1584. '\n '.join(failures))
  1585. def test_prod(self):
  1586. prod = math.prod
  1587. self.assertEqual(prod([]), 1)
  1588. self.assertEqual(prod([], start=5), 5)
  1589. self.assertEqual(prod(list(range(2,8))), 5040)
  1590. self.assertEqual(prod(iter(list(range(2,8)))), 5040)
  1591. self.assertEqual(prod(range(1, 10), start=10), 3628800)
  1592. self.assertEqual(prod([1, 2, 3, 4, 5]), 120)
  1593. self.assertEqual(prod([1.0, 2.0, 3.0, 4.0, 5.0]), 120.0)
  1594. self.assertEqual(prod([1, 2, 3, 4.0, 5.0]), 120.0)
  1595. self.assertEqual(prod([1.0, 2.0, 3.0, 4, 5]), 120.0)
  1596. # Test overflow in fast-path for integers
  1597. self.assertEqual(prod([1, 1, 2**32, 1, 1]), 2**32)
  1598. # Test overflow in fast-path for floats
  1599. self.assertEqual(prod([1.0, 1.0, 2**32, 1, 1]), float(2**32))
  1600. self.assertRaises(TypeError, prod)
  1601. self.assertRaises(TypeError, prod, 42)
  1602. self.assertRaises(TypeError, prod, ['a', 'b', 'c'])
  1603. self.assertRaises(TypeError, prod, ['a', 'b', 'c'], start='')
  1604. self.assertRaises(TypeError, prod, [b'a', b'c'], start=b'')
  1605. values = [bytearray(b'a'), bytearray(b'b')]
  1606. self.assertRaises(TypeError, prod, values, start=bytearray(b''))
  1607. self.assertRaises(TypeError, prod, [[1], [2], [3]])
  1608. self.assertRaises(TypeError, prod, [{2:3}])
  1609. self.assertRaises(TypeError, prod, [{2:3}]*2, start={2:3})
  1610. self.assertRaises(TypeError, prod, [[1], [2], [3]], start=[])
  1611. # Some odd cases
  1612. self.assertEqual(prod([2, 3], start='ab'), 'abababababab')
  1613. self.assertEqual(prod([2, 3], start=[1, 2]), [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])
  1614. self.assertEqual(prod([], start={2: 3}), {2:3})
  1615. with self.assertRaises(TypeError):
  1616. prod([10, 20], 1) # start is a keyword-only argument
  1617. self.assertEqual(prod([0, 1, 2, 3]), 0)
  1618. self.assertEqual(prod([1, 0, 2, 3]), 0)
  1619. self.assertEqual(prod([1, 2, 3, 0]), 0)
  1620. def _naive_prod(iterable, start=1):
  1621. for elem in iterable:
  1622. start *= elem
  1623. return start
  1624. # Big integers
  1625. iterable = range(1, 10000)
  1626. self.assertEqual(prod(iterable), _naive_prod(iterable))
  1627. iterable = range(-10000, -1)
  1628. self.assertEqual(prod(iterable), _naive_prod(iterable))
  1629. iterable = range(-1000, 1000)
  1630. self.assertEqual(prod(iterable), 0)
  1631. # Big floats
  1632. iterable = [float(x) for x in range(1, 1000)]
  1633. self.assertEqual(prod(iterable), _naive_prod(iterable))
  1634. iterable = [float(x) for x in range(-1000, -1)]
  1635. self.assertEqual(prod(iterable), _naive_prod(iterable))
  1636. iterable = [float(x) for x in range(-1000, 1000)]
  1637. self.assertIsNaN(prod(iterable))
  1638. # Float tests
  1639. self.assertIsNaN(prod([1, 2, 3, float("nan"), 2, 3]))
  1640. self.assertIsNaN(prod([1, 0, float("nan"), 2, 3]))
  1641. self.assertIsNaN(prod([1, float("nan"), 0, 3]))
  1642. self.assertIsNaN(prod([1, float("inf"), float("nan"),3]))
  1643. self.assertIsNaN(prod([1, float("-inf"), float("nan"),3]))
  1644. self.assertIsNaN(prod([1, float("nan"), float("inf"),3]))
  1645. self.assertIsNaN(prod([1, float("nan"), float("-inf"),3]))
  1646. self.assertEqual(prod([1, 2, 3, float('inf'),-3,4]), float('-inf'))
  1647. self.assertEqual(prod([1, 2, 3, float('-inf'),-3,4]), float('inf'))
  1648. self.assertIsNaN(prod([1,2,0,float('inf'), -3, 4]))
  1649. self.assertIsNaN(prod([1,2,0,float('-inf'), -3, 4]))
  1650. self.assertIsNaN(prod([1, 2, 3, float('inf'), -3, 0, 3]))
  1651. self.assertIsNaN(prod([1, 2, 3, float('-inf'), -3, 0, 2]))
  1652. # Type preservation
  1653. self.assertEqual(type(prod([1, 2, 3, 4, 5, 6])), int)
  1654. self.assertEqual(type(prod([1, 2.0, 3, 4, 5, 6])), float)
  1655. self.assertEqual(type(prod(range(1, 10000))), int)
  1656. self.assertEqual(type(prod(range(1, 10000), start=1.0)), float)
  1657. self.assertEqual(type(prod([1, decimal.Decimal(2.0), 3, 4, 5, 6])),
  1658. decimal.Decimal)
  1659. def testPerm(self):
  1660. perm = math.perm
  1661. factorial = math.factorial
  1662. # Test if factorial definition is satisfied
  1663. for n in range(500):
  1664. for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)):
  1665. self.assertEqual(perm(n, k),
  1666. factorial(n) // factorial(n - k))
  1667. # Test for Pascal's identity
  1668. for n in range(1, 100):
  1669. for k in range(1, n):
  1670. self.assertEqual(perm(n, k), perm(n - 1, k - 1) * k + perm(n - 1, k))
  1671. # Test corner cases
  1672. for n in range(1, 100):
  1673. self.assertEqual(perm(n, 0), 1)
  1674. self.assertEqual(perm(n, 1), n)
  1675. self.assertEqual(perm(n, n), factorial(n))
  1676. # Test one argument form
  1677. for n in range(20):
  1678. self.assertEqual(perm(n), factorial(n))
  1679. self.assertEqual(perm(n, None), factorial(n))
  1680. # Raises TypeError if any argument is non-integer or argument count is
  1681. # not 1 or 2
  1682. self.assertRaises(TypeError, perm, 10, 1.0)
  1683. self.assertRaises(TypeError, perm, 10, decimal.Decimal(1.0))
  1684. self.assertRaises(TypeError, perm, 10, "1")
  1685. self.assertRaises(TypeError, perm, 10.0, 1)
  1686. self.assertRaises(TypeError, perm, decimal.Decimal(10.0), 1)
  1687. self.assertRaises(TypeError, perm, "10", 1)
  1688. self.assertRaises(TypeError, perm)
  1689. self.assertRaises(TypeError, perm, 10, 1, 3)
  1690. self.assertRaises(TypeError, perm)
  1691. # Raises Value error if not k or n are negative numbers
  1692. self.assertRaises(ValueError, perm, -1, 1)
  1693. self.assertRaises(ValueError, perm, -2**1000, 1)
  1694. self.assertRaises(ValueError, perm, 1, -1)
  1695. self.assertRaises(ValueError, perm, 1, -2**1000)
  1696. # Returns zero if k is greater than n
  1697. self.assertEqual(perm(1, 2), 0)
  1698. self.assertEqual(perm(1, 2**1000), 0)
  1699. n = 2**1000
  1700. self.assertEqual(perm(n, 0), 1)
  1701. self.assertEqual(perm(n, 1), n)
  1702. self.assertEqual(perm(n, 2), n * (n-1))
  1703. if support.check_impl_detail(cpython=True):
  1704. self.assertRaises(OverflowError, perm, n, n)
  1705. for n, k in (True, True), (True, False), (False, False):
  1706. self.assertEqual(perm(n, k), 1)
  1707. self.assertIs(type(perm(n, k)), int)
  1708. self.assertEqual(perm(IntSubclass(5), IntSubclass(2)), 20)
  1709. self.assertEqual(perm(MyIndexable(5), MyIndexable(2)), 20)
  1710. for k in range(3):
  1711. self.assertIs(type(perm(IntSubclass(5), IntSubclass(k))), int)
  1712. self.assertIs(type(perm(MyIndexable(5), MyIndexable(k))), int)
  1713. def testComb(self):
  1714. comb = math.comb
  1715. factorial = math.factorial
  1716. # Test if factorial definition is satisfied
  1717. for n in range(500):
  1718. for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)):
  1719. self.assertEqual(comb(n, k), factorial(n)
  1720. // (factorial(k) * factorial(n - k)))
  1721. # Test for Pascal's identity
  1722. for n in range(1, 100):
  1723. for k in range(1, n):
  1724. self.assertEqual(comb(n, k), comb(n - 1, k - 1) + comb(n - 1, k))
  1725. # Test corner cases
  1726. for n in range(100):
  1727. self.assertEqual(comb(n, 0), 1)
  1728. self.assertEqual(comb(n, n), 1)
  1729. for n in range(1, 100):
  1730. self.assertEqual(comb(n, 1), n)
  1731. self.assertEqual(comb(n, n - 1), n)
  1732. # Test Symmetry
  1733. for n in range(100):
  1734. for k in range(n // 2):
  1735. self.assertEqual(comb(n, k), comb(n, n - k))
  1736. # Raises TypeError if any argument is non-integer or argument count is
  1737. # not 2
  1738. self.assertRaises(TypeError, comb, 10, 1.0)
  1739. self.assertRaises(TypeError, comb, 10, decimal.Decimal(1.0))
  1740. self.assertRaises(TypeError, comb, 10, "1")
  1741. self.assertRaises(TypeError, comb, 10.0, 1)
  1742. self.assertRaises(TypeError, comb, decimal.Decimal(10.0), 1)
  1743. self.assertRaises(TypeError, comb, "10", 1)
  1744. self.assertRaises(TypeError, comb, 10)
  1745. self.assertRaises(TypeError, comb, 10, 1, 3)
  1746. self.assertRaises(TypeError, comb)
  1747. # Raises Value error if not k or n are negative numbers
  1748. self.assertRaises(ValueError, comb, -1, 1)
  1749. self.assertRaises(ValueError, comb, -2**1000, 1)
  1750. self.assertRaises(ValueError, comb, 1, -1)
  1751. self.assertRaises(ValueError, comb, 1, -2**1000)
  1752. # Returns zero if k is greater than n
  1753. self.assertEqual(comb(1, 2), 0)
  1754. self.assertEqual(comb(1, 2**1000), 0)
  1755. n = 2**1000
  1756. self.assertEqual(comb(n, 0), 1)
  1757. self.assertEqual(comb(n, 1), n)
  1758. self.assertEqual(comb(n, 2), n * (n-1) // 2)
  1759. self.assertEqual(comb(n, n), 1)
  1760. self.assertEqual(comb(n, n-1), n)
  1761. self.assertEqual(comb(n, n-2), n * (n-1) // 2)
  1762. if support.check_impl_detail(cpython=True):
  1763. self.assertRaises(OverflowError, comb, n, n//2)
  1764. for n, k in (True, True), (True, False), (False, False):
  1765. self.assertEqual(comb(n, k), 1)
  1766. self.assertIs(type(comb(n, k)), int)
  1767. self.assertEqual(comb(IntSubclass(5), IntSubclass(2)), 10)
  1768. self.assertEqual(comb(MyIndexable(5), MyIndexable(2)), 10)
  1769. for k in range(3):
  1770. self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int)
  1771. self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int)
  1772. @requires_IEEE_754
  1773. def test_nextafter(self):
  1774. # around 2^52 and 2^63
  1775. self.assertEqual(math.nextafter(4503599627370496.0, -INF),
  1776. 4503599627370495.5)
  1777. self.assertEqual(math.nextafter(4503599627370496.0, INF),
  1778. 4503599627370497.0)
  1779. self.assertEqual(math.nextafter(9223372036854775808.0, 0.0),
  1780. 9223372036854774784.0)
  1781. self.assertEqual(math.nextafter(-9223372036854775808.0, 0.0),
  1782. -9223372036854774784.0)
  1783. # around 1.0
  1784. self.assertEqual(math.nextafter(1.0, -INF),
  1785. float.fromhex('0x1.fffffffffffffp-1'))
  1786. self.assertEqual(math.nextafter(1.0, INF),
  1787. float.fromhex('0x1.0000000000001p+0'))
  1788. # x == y: y is returned
  1789. self.assertEqual(math.nextafter(2.0, 2.0), 2.0)
  1790. self.assertEqualSign(math.nextafter(-0.0, +0.0), +0.0)
  1791. self.assertEqualSign(math.nextafter(+0.0, -0.0), -0.0)
  1792. # around 0.0
  1793. smallest_subnormal = sys.float_info.min * sys.float_info.epsilon
  1794. self.assertEqual(math.nextafter(+0.0, INF), smallest_subnormal)
  1795. self.assertEqual(math.nextafter(-0.0, INF), smallest_subnormal)
  1796. self.assertEqual(math.nextafter(+0.0, -INF), -smallest_subnormal)
  1797. self.assertEqual(math.nextafter(-0.0, -INF), -smallest_subnormal)
  1798. self.assertEqualSign(math.nextafter(smallest_subnormal, +0.0), +0.0)
  1799. self.assertEqualSign(math.nextafter(-smallest_subnormal, +0.0), -0.0)
  1800. self.assertEqualSign(math.nextafter(smallest_subnormal, -0.0), +0.0)
  1801. self.assertEqualSign(math.nextafter(-smallest_subnormal, -0.0), -0.0)
  1802. # around infinity
  1803. largest_normal = sys.float_info.max
  1804. self.assertEqual(math.nextafter(INF, 0.0), largest_normal)
  1805. self.assertEqual(math.nextafter(-INF, 0.0), -largest_normal)
  1806. self.assertEqual(math.nextafter(largest_normal, INF), INF)
  1807. self.assertEqual(math.nextafter(-largest_normal, -INF), -INF)
  1808. # NaN
  1809. self.assertIsNaN(math.nextafter(NAN, 1.0))
  1810. self.assertIsNaN(math.nextafter(1.0, NAN))
  1811. self.assertIsNaN(math.nextafter(NAN, NAN))
  1812. @requires_IEEE_754
  1813. def test_ulp(self):
  1814. self.assertEqual(math.ulp(1.0), sys.float_info.epsilon)
  1815. # use int ** int rather than float ** int to not rely on pow() accuracy
  1816. self.assertEqual(math.ulp(2 ** 52), 1.0)
  1817. self.assertEqual(math.ulp(2 ** 53), 2.0)
  1818. self.assertEqual(math.ulp(2 ** 64), 4096.0)
  1819. # min and max
  1820. self.assertEqual(math.ulp(0.0),
  1821. sys.float_info.min * sys.float_info.epsilon)
  1822. self.assertEqual(math.ulp(FLOAT_MAX),
  1823. FLOAT_MAX - math.nextafter(FLOAT_MAX, -INF))
  1824. # special cases
  1825. self.assertEqual(math.ulp(INF), INF)
  1826. self.assertIsNaN(math.ulp(math.nan))
  1827. # negative number: ulp(-x) == ulp(x)
  1828. for x in (0.0, 1.0, 2 ** 52, 2 ** 64, INF):
  1829. with self.subTest(x=x):
  1830. self.assertEqual(math.ulp(-x), math.ulp(x))
  1831. def test_issue39871(self):
  1832. # A SystemError should not be raised if the first arg to atan2(),
  1833. # copysign(), or remainder() cannot be converted to a float.
  1834. class F:
  1835. def __float__(self):
  1836. self.converted = True
  1837. 1/0
  1838. for func in math.atan2, math.copysign, math.remainder:
  1839. y = F()
  1840. with self.assertRaises(TypeError):
  1841. func("not a number", y)
  1842. # There should not have been any attempt to convert the second
  1843. # argument to a float.
  1844. self.assertFalse(getattr(y, "converted", False))
  1845. # Custom assertions.
  1846. def assertIsNaN(self, value):
  1847. if not math.isnan(value):
  1848. self.fail("Expected a NaN, got {!r}.".format(value))
  1849. def assertEqualSign(self, x, y):
  1850. """Similar to assertEqual(), but compare also the sign with copysign().
  1851. Function useful to compare signed zeros.
  1852. """
  1853. self.assertEqual(x, y)
  1854. self.assertEqual(math.copysign(1.0, x), math.copysign(1.0, y))
  1855. class IsCloseTests(unittest.TestCase):
  1856. isclose = math.isclose # subclasses should override this
  1857. def assertIsClose(self, a, b, *args, **kwargs):
  1858. self.assertTrue(self.isclose(a, b, *args, **kwargs),
  1859. msg="%s and %s should be close!" % (a, b))
  1860. def assertIsNotClose(self, a, b, *args, **kwargs):
  1861. self.assertFalse(self.isclose(a, b, *args, **kwargs),
  1862. msg="%s and %s should not be close!" % (a, b))
  1863. def assertAllClose(self, examples, *args, **kwargs):
  1864. for a, b in examples:
  1865. self.assertIsClose(a, b, *args, **kwargs)
  1866. def assertAllNotClose(self, examples, *args, **kwargs):
  1867. for a, b in examples:
  1868. self.assertIsNotClose(a, b, *args, **kwargs)
  1869. def test_negative_tolerances(self):
  1870. # ValueError should be raised if either tolerance is less than zero
  1871. with self.assertRaises(ValueError):
  1872. self.assertIsClose(1, 1, rel_tol=-1e-100)
  1873. with self.assertRaises(ValueError):
  1874. self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
  1875. def test_identical(self):
  1876. # identical values must test as close
  1877. identical_examples = [(2.0, 2.0),
  1878. (0.1e200, 0.1e200),
  1879. (1.123e-300, 1.123e-300),
  1880. (12345, 12345.0),
  1881. (0.0, -0.0),
  1882. (345678, 345678)]
  1883. self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
  1884. def test_eight_decimal_places(self):
  1885. # examples that are close to 1e-8, but not 1e-9
  1886. eight_decimal_places_examples = [(1e8, 1e8 + 1),
  1887. (-1e-8, -1.000000009e-8),
  1888. (1.12345678, 1.12345679)]
  1889. self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
  1890. self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
  1891. def test_near_zero(self):
  1892. # values close to zero
  1893. near_zero_examples = [(1e-9, 0.0),
  1894. (-1e-9, 0.0),
  1895. (-1e-150, 0.0)]
  1896. # these should not be close to any rel_tol
  1897. self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
  1898. # these should be close to abs_tol=1e-8
  1899. self.assertAllClose(near_zero_examples, abs_tol=1e-8)
  1900. def test_identical_infinite(self):
  1901. # these are close regardless of tolerance -- i.e. they are equal
  1902. self.assertIsClose(INF, INF)
  1903. self.assertIsClose(INF, INF, abs_tol=0.0)
  1904. self.assertIsClose(NINF, NINF)
  1905. self.assertIsClose(NINF, NINF, abs_tol=0.0)
  1906. def test_inf_ninf_nan(self):
  1907. # these should never be close (following IEEE 754 rules for equality)
  1908. not_close_examples = [(NAN, NAN),
  1909. (NAN, 1e-100),
  1910. (1e-100, NAN),
  1911. (INF, NAN),
  1912. (NAN, INF),
  1913. (INF, NINF),
  1914. (INF, 1.0),
  1915. (1.0, INF),
  1916. (INF, 1e308),
  1917. (1e308, INF)]
  1918. # use largest reasonable tolerance
  1919. self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
  1920. def test_zero_tolerance(self):
  1921. # test with zero tolerance
  1922. zero_tolerance_close_examples = [(1.0, 1.0),
  1923. (-3.4, -3.4),
  1924. (-1e-300, -1e-300)]
  1925. self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
  1926. zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
  1927. (0.99999999999999, 1.0),
  1928. (1.0e200, .999999999999999e200)]
  1929. self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
  1930. def test_asymmetry(self):
  1931. # test the asymmetry example from PEP 485
  1932. self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
  1933. def test_integers(self):
  1934. # test with integer values
  1935. integer_examples = [(100000001, 100000000),
  1936. (123456789, 123456788)]
  1937. self.assertAllClose(integer_examples, rel_tol=1e-8)
  1938. self.assertAllNotClose(integer_examples, rel_tol=1e-9)
  1939. def test_decimals(self):
  1940. # test with Decimal values
  1941. from decimal import Decimal
  1942. decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
  1943. (Decimal('1.00000001e-20'), Decimal('1.0e-20')),
  1944. (Decimal('1.00000001e-100'), Decimal('1.0e-100')),
  1945. (Decimal('1.00000001e20'), Decimal('1.0e20'))]
  1946. self.assertAllClose(decimal_examples, rel_tol=1e-8)
  1947. self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
  1948. def test_fractions(self):
  1949. # test with Fraction values
  1950. from fractions import Fraction
  1951. fraction_examples = [
  1952. (Fraction(1, 100000000) + 1, Fraction(1)),
  1953. (Fraction(100000001), Fraction(100000000)),
  1954. (Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))]
  1955. self.assertAllClose(fraction_examples, rel_tol=1e-8)
  1956. self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
  1957. def load_tests(loader, tests, pattern):
  1958. from doctest import DocFileSuite
  1959. tests.addTest(DocFileSuite("ieee754.txt"))
  1960. return tests
  1961. if __name__ == '__main__':
  1962. unittest.main()