test_mpmath.py 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  1. """
  2. Test SciPy functions versus mpmath, if available.
  3. """
  4. import numpy as np
  5. from numpy.testing import assert_, assert_allclose
  6. from numpy import pi
  7. import pytest
  8. import itertools
  9. from scipy._lib import _pep440
  10. import scipy.special as sc
  11. from scipy.special._testutils import (
  12. MissingModule, check_version, FuncData,
  13. assert_func_equal)
  14. from scipy.special._mptestutils import (
  15. Arg, FixedArg, ComplexArg, IntArg, assert_mpmath_equal,
  16. nonfunctional_tooslow, trace_args, time_limited, exception_to_nan,
  17. inf_to_nan)
  18. from scipy.special._ufuncs import (
  19. _sinpi, _cospi, _lgam1p, _lanczos_sum_expg_scaled, _log1pmx,
  20. _igam_fac)
  21. try:
  22. import mpmath
  23. except ImportError:
  24. mpmath = MissingModule('mpmath')
  25. # ------------------------------------------------------------------------------
  26. # expi
  27. # ------------------------------------------------------------------------------
  28. @check_version(mpmath, '0.10')
  29. def test_expi_complex():
  30. dataset = []
  31. for r in np.logspace(-99, 2, 10):
  32. for p in np.linspace(0, 2*np.pi, 30):
  33. z = r*np.exp(1j*p)
  34. dataset.append((z, complex(mpmath.ei(z))))
  35. dataset = np.array(dataset, dtype=np.complex_)
  36. FuncData(sc.expi, dataset, 0, 1).check()
  37. # ------------------------------------------------------------------------------
  38. # expn
  39. # ------------------------------------------------------------------------------
  40. @check_version(mpmath, '0.19')
  41. def test_expn_large_n():
  42. # Test the transition to the asymptotic regime of n.
  43. dataset = []
  44. for n in [50, 51]:
  45. for x in np.logspace(0, 4, 200):
  46. with mpmath.workdps(100):
  47. dataset.append((n, x, float(mpmath.expint(n, x))))
  48. dataset = np.asarray(dataset)
  49. FuncData(sc.expn, dataset, (0, 1), 2, rtol=1e-13).check()
  50. # ------------------------------------------------------------------------------
  51. # hyp0f1
  52. # ------------------------------------------------------------------------------
  53. @check_version(mpmath, '0.19')
  54. def test_hyp0f1_gh5764():
  55. # Do a small and somewhat systematic test that runs quickly
  56. dataset = []
  57. axis = [-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]
  58. for v in axis:
  59. for x in axis:
  60. for y in axis:
  61. z = x + 1j*y
  62. # mpmath computes the answer correctly at dps ~ 17 but
  63. # fails for 20 < dps < 120 (uses a different method);
  64. # set the dps high enough that this isn't an issue
  65. with mpmath.workdps(120):
  66. res = complex(mpmath.hyp0f1(v, z))
  67. dataset.append((v, z, res))
  68. dataset = np.array(dataset)
  69. FuncData(lambda v, z: sc.hyp0f1(v.real, z), dataset, (0, 1), 2,
  70. rtol=1e-13).check()
  71. @check_version(mpmath, '0.19')
  72. def test_hyp0f1_gh_1609():
  73. # this is a regression test for gh-1609
  74. vv = np.linspace(150, 180, 21)
  75. af = sc.hyp0f1(vv, 0.5)
  76. mf = np.array([mpmath.hyp0f1(v, 0.5) for v in vv])
  77. assert_allclose(af, mf.astype(float), rtol=1e-12)
  78. # ------------------------------------------------------------------------------
  79. # hyperu
  80. # ------------------------------------------------------------------------------
  81. @check_version(mpmath, '1.1.0')
  82. def test_hyperu_around_0():
  83. dataset = []
  84. # DLMF 13.2.14-15 test points.
  85. for n in np.arange(-5, 5):
  86. for b in np.linspace(-5, 5, 20):
  87. a = -n
  88. dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
  89. a = -n + b - 1
  90. dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
  91. # DLMF 13.2.16-22 test points.
  92. for a in [-10.5, -1.5, -0.5, 0, 0.5, 1, 10]:
  93. for b in [-1.0, -0.5, 0, 0.5, 1, 1.5, 2, 2.5]:
  94. dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
  95. dataset = np.array(dataset)
  96. FuncData(sc.hyperu, dataset, (0, 1, 2), 3, rtol=1e-15, atol=5e-13).check()
  97. # ------------------------------------------------------------------------------
  98. # hyp2f1
  99. # ------------------------------------------------------------------------------
  100. @check_version(mpmath, '1.0.0')
  101. def test_hyp2f1_strange_points():
  102. pts = [
  103. (2, -1, -1, 0.7), # expected: 2.4
  104. (2, -2, -2, 0.7), # expected: 3.87
  105. ]
  106. pts += list(itertools.product([2, 1, -0.7, -1000], repeat=4))
  107. pts = [
  108. (a, b, c, x) for a, b, c, x in pts
  109. if b == c and round(b) == b and b < 0 and b != -1000
  110. ]
  111. kw = dict(eliminate=True)
  112. dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts]
  113. dataset = np.array(dataset, dtype=np.float_)
  114. FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
  115. @check_version(mpmath, '0.13')
  116. def test_hyp2f1_real_some_points():
  117. pts = [
  118. (1, 2, 3, 0),
  119. (1./3, 2./3, 5./6, 27./32),
  120. (1./4, 1./2, 3./4, 80./81),
  121. (2,-2, -3, 3),
  122. (2, -3, -2, 3),
  123. (2, -1.5, -1.5, 3),
  124. (1, 2, 3, 0),
  125. (0.7235, -1, -5, 0.3),
  126. (0.25, 1./3, 2, 0.999),
  127. (0.25, 1./3, 2, -1),
  128. (2, 3, 5, 0.99),
  129. (3./2, -0.5, 3, 0.99),
  130. (2, 2.5, -3.25, 0.999),
  131. (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001),
  132. (-10, 900, -10.5, 0.99),
  133. (-10, 900, 10.5, 0.99),
  134. (-1, 2, 1, 1.0),
  135. (-1, 2, 1, -1.0),
  136. (-3, 13, 5, 1.0),
  137. (-3, 13, 5, -1.0),
  138. (0.5, 1 - 270.5, 1.5, 0.999**2), # from issue 1561
  139. ]
  140. dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
  141. dataset = np.array(dataset, dtype=np.float_)
  142. with np.errstate(invalid='ignore'):
  143. FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
  144. @check_version(mpmath, '0.14')
  145. def test_hyp2f1_some_points_2():
  146. # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but
  147. # was fixed in their SVN since then
  148. pts = [
  149. (112, (51,10), (-9,10), -0.99999),
  150. (10,-900,10.5,0.99),
  151. (10,-900,-10.5,0.99),
  152. ]
  153. def fev(x):
  154. if isinstance(x, tuple):
  155. return float(x[0]) / x[1]
  156. else:
  157. return x
  158. dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts]
  159. dataset = np.array(dataset, dtype=np.float_)
  160. FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
  161. @check_version(mpmath, '0.13')
  162. def test_hyp2f1_real_some():
  163. dataset = []
  164. for a in [-10, -5, -1.8, 1.8, 5, 10]:
  165. for b in [-2.5, -1, 1, 7.4]:
  166. for c in [-9, -1.8, 5, 20.4]:
  167. for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
  168. try:
  169. v = float(mpmath.hyp2f1(a, b, c, z))
  170. except Exception:
  171. continue
  172. dataset.append((a, b, c, z, v))
  173. dataset = np.array(dataset, dtype=np.float_)
  174. with np.errstate(invalid='ignore'):
  175. FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9,
  176. ignore_inf_sign=True).check()
  177. @check_version(mpmath, '0.12')
  178. @pytest.mark.slow
  179. def test_hyp2f1_real_random():
  180. npoints = 500
  181. dataset = np.zeros((npoints, 5), np.float_)
  182. np.random.seed(1234)
  183. dataset[:, 0] = np.random.pareto(1.5, npoints)
  184. dataset[:, 1] = np.random.pareto(1.5, npoints)
  185. dataset[:, 2] = np.random.pareto(1.5, npoints)
  186. dataset[:, 3] = 2*np.random.rand(npoints) - 1
  187. dataset[:, 0] *= (-1)**np.random.randint(2, npoints)
  188. dataset[:, 1] *= (-1)**np.random.randint(2, npoints)
  189. dataset[:, 2] *= (-1)**np.random.randint(2, npoints)
  190. for ds in dataset:
  191. if mpmath.__version__ < '0.14':
  192. # mpmath < 0.14 fails for c too much smaller than a, b
  193. if abs(ds[:2]).max() > abs(ds[2]):
  194. ds[2] = abs(ds[:2]).max()
  195. ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4])))
  196. FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check()
  197. # ------------------------------------------------------------------------------
  198. # erf (complex)
  199. # ------------------------------------------------------------------------------
  200. @check_version(mpmath, '0.14')
  201. def test_erf_complex():
  202. # need to increase mpmath precision for this test
  203. old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
  204. try:
  205. mpmath.mp.dps = 70
  206. x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11))
  207. x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11))
  208. points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(), y2.ravel()]
  209. assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points,
  210. vectorized=False, rtol=1e-13)
  211. assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points,
  212. vectorized=False, rtol=1e-13)
  213. finally:
  214. mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
  215. # ------------------------------------------------------------------------------
  216. # lpmv
  217. # ------------------------------------------------------------------------------
  218. @check_version(mpmath, '0.15')
  219. def test_lpmv():
  220. pts = []
  221. for x in [-0.99, -0.557, 1e-6, 0.132, 1]:
  222. pts.extend([
  223. (1, 1, x),
  224. (1, -1, x),
  225. (-1, 1, x),
  226. (-1, -2, x),
  227. (1, 1.7, x),
  228. (1, -1.7, x),
  229. (-1, 1.7, x),
  230. (-1, -2.7, x),
  231. (1, 10, x),
  232. (1, 11, x),
  233. (3, 8, x),
  234. (5, 11, x),
  235. (-3, 8, x),
  236. (-5, 11, x),
  237. (3, -8, x),
  238. (5, -11, x),
  239. (-3, -8, x),
  240. (-5, -11, x),
  241. (3, 8.3, x),
  242. (5, 11.3, x),
  243. (-3, 8.3, x),
  244. (-5, 11.3, x),
  245. (3, -8.3, x),
  246. (5, -11.3, x),
  247. (-3, -8.3, x),
  248. (-5, -11.3, x),
  249. ])
  250. def mplegenp(nu, mu, x):
  251. if mu == int(mu) and x == 1:
  252. # mpmath 0.17 gets this wrong
  253. if mu == 0:
  254. return 1
  255. else:
  256. return 0
  257. return mpmath.legenp(nu, mu, x)
  258. dataset = [p + (mplegenp(p[1], p[0], p[2]),) for p in pts]
  259. dataset = np.array(dataset, dtype=np.float_)
  260. def evf(mu, nu, x):
  261. return sc.lpmv(mu.astype(int), nu, x)
  262. with np.errstate(invalid='ignore'):
  263. FuncData(evf, dataset, (0,1,2), 3, rtol=1e-10, atol=1e-14).check()
  264. # ------------------------------------------------------------------------------
  265. # beta
  266. # ------------------------------------------------------------------------------
  267. @check_version(mpmath, '0.15')
  268. def test_beta():
  269. np.random.seed(1234)
  270. b = np.r_[np.logspace(-200, 200, 4),
  271. np.logspace(-10, 10, 4),
  272. np.logspace(-1, 1, 4),
  273. np.arange(-10, 11, 1),
  274. np.arange(-10, 11, 1) + 0.5,
  275. -1, -2.3, -3, -100.3, -10003.4]
  276. a = b
  277. ab = np.array(np.broadcast_arrays(a[:,None], b[None,:])).reshape(2, -1).T
  278. old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
  279. try:
  280. mpmath.mp.dps = 400
  281. assert_func_equal(sc.beta,
  282. lambda a, b: float(mpmath.beta(a, b)),
  283. ab,
  284. vectorized=False,
  285. rtol=1e-10,
  286. ignore_inf_sign=True)
  287. assert_func_equal(
  288. sc.betaln,
  289. lambda a, b: float(mpmath.log(abs(mpmath.beta(a, b)))),
  290. ab,
  291. vectorized=False,
  292. rtol=1e-10)
  293. finally:
  294. mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
  295. # ------------------------------------------------------------------------------
  296. # loggamma
  297. # ------------------------------------------------------------------------------
  298. LOGGAMMA_TAYLOR_RADIUS = 0.2
  299. @check_version(mpmath, '0.19')
  300. def test_loggamma_taylor_transition():
  301. # Make sure there isn't a big jump in accuracy when we move from
  302. # using the Taylor series to using the recurrence relation.
  303. r = LOGGAMMA_TAYLOR_RADIUS + np.array([-0.1, -0.01, 0, 0.01, 0.1])
  304. theta = np.linspace(0, 2*np.pi, 20)
  305. r, theta = np.meshgrid(r, theta)
  306. dz = r*np.exp(1j*theta)
  307. z = np.r_[1 + dz, 2 + dz].flatten()
  308. dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
  309. dataset = np.array(dataset)
  310. FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
  311. @check_version(mpmath, '0.19')
  312. def test_loggamma_taylor():
  313. # Test around the zeros at z = 1, 2.
  314. r = np.logspace(-16, np.log10(LOGGAMMA_TAYLOR_RADIUS), 10)
  315. theta = np.linspace(0, 2*np.pi, 20)
  316. r, theta = np.meshgrid(r, theta)
  317. dz = r*np.exp(1j*theta)
  318. z = np.r_[1 + dz, 2 + dz].flatten()
  319. dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
  320. dataset = np.array(dataset)
  321. FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
  322. # ------------------------------------------------------------------------------
  323. # rgamma
  324. # ------------------------------------------------------------------------------
  325. @check_version(mpmath, '0.19')
  326. @pytest.mark.slow
  327. def test_rgamma_zeros():
  328. # Test around the zeros at z = 0, -1, -2, ..., -169. (After -169 we
  329. # get values that are out of floating point range even when we're
  330. # within 0.1 of the zero.)
  331. # Can't use too many points here or the test takes forever.
  332. dx = np.r_[-np.logspace(-1, -13, 3), 0, np.logspace(-13, -1, 3)]
  333. dy = dx.copy()
  334. dx, dy = np.meshgrid(dx, dy)
  335. dz = dx + 1j*dy
  336. zeros = np.arange(0, -170, -1).reshape(1, 1, -1)
  337. z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
  338. with mpmath.workdps(100):
  339. dataset = [(z0, complex(mpmath.rgamma(z0))) for z0 in z]
  340. dataset = np.array(dataset)
  341. FuncData(sc.rgamma, dataset, 0, 1, rtol=1e-12).check()
  342. # ------------------------------------------------------------------------------
  343. # digamma
  344. # ------------------------------------------------------------------------------
  345. @check_version(mpmath, '0.19')
  346. @pytest.mark.slow
  347. def test_digamma_roots():
  348. # Test the special-cased roots for digamma.
  349. root = mpmath.findroot(mpmath.digamma, 1.5)
  350. roots = [float(root)]
  351. root = mpmath.findroot(mpmath.digamma, -0.5)
  352. roots.append(float(root))
  353. roots = np.array(roots)
  354. # If we test beyond a radius of 0.24 mpmath will take forever.
  355. dx = np.r_[-0.24, -np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10), 0.24]
  356. dy = dx.copy()
  357. dx, dy = np.meshgrid(dx, dy)
  358. dz = dx + 1j*dy
  359. z = (roots + np.dstack((dz,)*roots.size)).flatten()
  360. with mpmath.workdps(30):
  361. dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
  362. dataset = np.array(dataset)
  363. FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check()
  364. @check_version(mpmath, '0.19')
  365. def test_digamma_negreal():
  366. # Test digamma around the negative real axis. Don't do this in
  367. # TestSystematic because the points need some jiggering so that
  368. # mpmath doesn't take forever.
  369. digamma = exception_to_nan(mpmath.digamma)
  370. x = -np.logspace(300, -30, 100)
  371. y = np.r_[-np.logspace(0, -3, 5), 0, np.logspace(-3, 0, 5)]
  372. x, y = np.meshgrid(x, y)
  373. z = (x + 1j*y).flatten()
  374. with mpmath.workdps(40):
  375. dataset = [(z0, complex(digamma(z0))) for z0 in z]
  376. dataset = np.asarray(dataset)
  377. FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
  378. @check_version(mpmath, '0.19')
  379. def test_digamma_boundary():
  380. # Check that there isn't a jump in accuracy when we switch from
  381. # using the asymptotic series to the reflection formula.
  382. x = -np.logspace(300, -30, 100)
  383. y = np.array([-6.1, -5.9, 5.9, 6.1])
  384. x, y = np.meshgrid(x, y)
  385. z = (x + 1j*y).flatten()
  386. with mpmath.workdps(30):
  387. dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
  388. dataset = np.asarray(dataset)
  389. FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
  390. # ------------------------------------------------------------------------------
  391. # gammainc
  392. # ------------------------------------------------------------------------------
  393. @check_version(mpmath, '0.19')
  394. @pytest.mark.slow
  395. def test_gammainc_boundary():
  396. # Test the transition to the asymptotic series.
  397. small = 20
  398. a = np.linspace(0.5*small, 2*small, 50)
  399. x = a.copy()
  400. a, x = np.meshgrid(a, x)
  401. a, x = a.flatten(), x.flatten()
  402. with mpmath.workdps(100):
  403. dataset = [(a0, x0, float(mpmath.gammainc(a0, b=x0, regularized=True)))
  404. for a0, x0 in zip(a, x)]
  405. dataset = np.array(dataset)
  406. FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-12).check()
  407. # ------------------------------------------------------------------------------
  408. # spence
  409. # ------------------------------------------------------------------------------
  410. @check_version(mpmath, '0.19')
  411. @pytest.mark.slow
  412. def test_spence_circle():
  413. # The trickiest region for spence is around the circle |z - 1| = 1,
  414. # so test that region carefully.
  415. def spence(z):
  416. return complex(mpmath.polylog(2, 1 - z))
  417. r = np.linspace(0.5, 1.5)
  418. theta = np.linspace(0, 2*pi)
  419. z = (1 + np.outer(r, np.exp(1j*theta))).flatten()
  420. dataset = np.asarray([(z0, spence(z0)) for z0 in z])
  421. FuncData(sc.spence, dataset, 0, 1, rtol=1e-14).check()
  422. # ------------------------------------------------------------------------------
  423. # sinpi and cospi
  424. # ------------------------------------------------------------------------------
  425. @check_version(mpmath, '0.19')
  426. def test_sinpi_zeros():
  427. eps = np.finfo(float).eps
  428. dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
  429. dy = dx.copy()
  430. dx, dy = np.meshgrid(dx, dy)
  431. dz = dx + 1j*dy
  432. zeros = np.arange(-100, 100, 1).reshape(1, 1, -1)
  433. z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
  434. dataset = np.asarray([(z0, complex(mpmath.sinpi(z0)))
  435. for z0 in z])
  436. FuncData(_sinpi, dataset, 0, 1, rtol=2*eps).check()
  437. @check_version(mpmath, '0.19')
  438. def test_cospi_zeros():
  439. eps = np.finfo(float).eps
  440. dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
  441. dy = dx.copy()
  442. dx, dy = np.meshgrid(dx, dy)
  443. dz = dx + 1j*dy
  444. zeros = (np.arange(-100, 100, 1) + 0.5).reshape(1, 1, -1)
  445. z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
  446. dataset = np.asarray([(z0, complex(mpmath.cospi(z0)))
  447. for z0 in z])
  448. FuncData(_cospi, dataset, 0, 1, rtol=2*eps).check()
  449. # ------------------------------------------------------------------------------
  450. # ellipj
  451. # ------------------------------------------------------------------------------
  452. @check_version(mpmath, '0.19')
  453. def test_dn_quarter_period():
  454. def dn(u, m):
  455. return sc.ellipj(u, m)[2]
  456. def mpmath_dn(u, m):
  457. return float(mpmath.ellipfun("dn", u=u, m=m))
  458. m = np.linspace(0, 1, 20)
  459. du = np.r_[-np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10)]
  460. dataset = []
  461. for m0 in m:
  462. u0 = float(mpmath.ellipk(m0))
  463. for du0 in du:
  464. p = u0 + du0
  465. dataset.append((p, m0, mpmath_dn(p, m0)))
  466. dataset = np.asarray(dataset)
  467. FuncData(dn, dataset, (0, 1), 2, rtol=1e-10).check()
  468. # ------------------------------------------------------------------------------
  469. # Wright Omega
  470. # ------------------------------------------------------------------------------
  471. def _mpmath_wrightomega(z, dps):
  472. with mpmath.workdps(dps):
  473. z = mpmath.mpc(z)
  474. unwind = mpmath.ceil((z.imag - mpmath.pi)/(2*mpmath.pi))
  475. res = mpmath.lambertw(mpmath.exp(z), unwind)
  476. return res
  477. @pytest.mark.slow
  478. @check_version(mpmath, '0.19')
  479. def test_wrightomega_branch():
  480. x = -np.logspace(10, 0, 25)
  481. picut_above = [np.nextafter(np.pi, np.inf)]
  482. picut_below = [np.nextafter(np.pi, -np.inf)]
  483. npicut_above = [np.nextafter(-np.pi, np.inf)]
  484. npicut_below = [np.nextafter(-np.pi, -np.inf)]
  485. for i in range(50):
  486. picut_above.append(np.nextafter(picut_above[-1], np.inf))
  487. picut_below.append(np.nextafter(picut_below[-1], -np.inf))
  488. npicut_above.append(np.nextafter(npicut_above[-1], np.inf))
  489. npicut_below.append(np.nextafter(npicut_below[-1], -np.inf))
  490. y = np.hstack((picut_above, picut_below, npicut_above, npicut_below))
  491. x, y = np.meshgrid(x, y)
  492. z = (x + 1j*y).flatten()
  493. dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
  494. for z0 in z])
  495. FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-8).check()
  496. @pytest.mark.slow
  497. @check_version(mpmath, '0.19')
  498. def test_wrightomega_region1():
  499. # This region gets less coverage in the TestSystematic test
  500. x = np.linspace(-2, 1)
  501. y = np.linspace(1, 2*np.pi)
  502. x, y = np.meshgrid(x, y)
  503. z = (x + 1j*y).flatten()
  504. dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
  505. for z0 in z])
  506. FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
  507. @pytest.mark.slow
  508. @check_version(mpmath, '0.19')
  509. def test_wrightomega_region2():
  510. # This region gets less coverage in the TestSystematic test
  511. x = np.linspace(-2, 1)
  512. y = np.linspace(-2*np.pi, -1)
  513. x, y = np.meshgrid(x, y)
  514. z = (x + 1j*y).flatten()
  515. dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
  516. for z0 in z])
  517. FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
  518. # ------------------------------------------------------------------------------
  519. # lambertw
  520. # ------------------------------------------------------------------------------
  521. @pytest.mark.slow
  522. @check_version(mpmath, '0.19')
  523. def test_lambertw_smallz():
  524. x, y = np.linspace(-1, 1, 25), np.linspace(-1, 1, 25)
  525. x, y = np.meshgrid(x, y)
  526. z = (x + 1j*y).flatten()
  527. dataset = np.asarray([(z0, complex(mpmath.lambertw(z0)))
  528. for z0 in z])
  529. FuncData(sc.lambertw, dataset, 0, 1, rtol=1e-13).check()
  530. # ------------------------------------------------------------------------------
  531. # Systematic tests
  532. # ------------------------------------------------------------------------------
  533. HYPERKW = dict(maxprec=200, maxterms=200)
  534. @pytest.mark.slow
  535. @check_version(mpmath, '0.17')
  536. class TestSystematic:
  537. def test_airyai(self):
  538. # oscillating function, limit range
  539. assert_mpmath_equal(lambda z: sc.airy(z)[0],
  540. mpmath.airyai,
  541. [Arg(-1e8, 1e8)],
  542. rtol=1e-5)
  543. assert_mpmath_equal(lambda z: sc.airy(z)[0],
  544. mpmath.airyai,
  545. [Arg(-1e3, 1e3)])
  546. def test_airyai_complex(self):
  547. assert_mpmath_equal(lambda z: sc.airy(z)[0],
  548. mpmath.airyai,
  549. [ComplexArg()])
  550. def test_airyai_prime(self):
  551. # oscillating function, limit range
  552. assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
  553. mpmath.airyai(z, derivative=1),
  554. [Arg(-1e8, 1e8)],
  555. rtol=1e-5)
  556. assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
  557. mpmath.airyai(z, derivative=1),
  558. [Arg(-1e3, 1e3)])
  559. def test_airyai_prime_complex(self):
  560. assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
  561. mpmath.airyai(z, derivative=1),
  562. [ComplexArg()])
  563. def test_airybi(self):
  564. # oscillating function, limit range
  565. assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
  566. mpmath.airybi(z),
  567. [Arg(-1e8, 1e8)],
  568. rtol=1e-5)
  569. assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
  570. mpmath.airybi(z),
  571. [Arg(-1e3, 1e3)])
  572. def test_airybi_complex(self):
  573. assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
  574. mpmath.airybi(z),
  575. [ComplexArg()])
  576. def test_airybi_prime(self):
  577. # oscillating function, limit range
  578. assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
  579. mpmath.airybi(z, derivative=1),
  580. [Arg(-1e8, 1e8)],
  581. rtol=1e-5)
  582. assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
  583. mpmath.airybi(z, derivative=1),
  584. [Arg(-1e3, 1e3)])
  585. def test_airybi_prime_complex(self):
  586. assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
  587. mpmath.airybi(z, derivative=1),
  588. [ComplexArg()])
  589. def test_bei(self):
  590. assert_mpmath_equal(sc.bei,
  591. exception_to_nan(lambda z: mpmath.bei(0, z, **HYPERKW)),
  592. [Arg(-1e3, 1e3)])
  593. def test_ber(self):
  594. assert_mpmath_equal(sc.ber,
  595. exception_to_nan(lambda z: mpmath.ber(0, z, **HYPERKW)),
  596. [Arg(-1e3, 1e3)])
  597. def test_bernoulli(self):
  598. assert_mpmath_equal(lambda n: sc.bernoulli(int(n))[int(n)],
  599. lambda n: float(mpmath.bernoulli(int(n))),
  600. [IntArg(0, 13000)],
  601. rtol=1e-9, n=13000)
  602. def test_besseli(self):
  603. assert_mpmath_equal(sc.iv,
  604. exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
  605. [Arg(-1e100, 1e100), Arg()],
  606. atol=1e-270)
  607. def test_besseli_complex(self):
  608. assert_mpmath_equal(lambda v, z: sc.iv(v.real, z),
  609. exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
  610. [Arg(-1e100, 1e100), ComplexArg()])
  611. def test_besselj(self):
  612. assert_mpmath_equal(sc.jv,
  613. exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
  614. [Arg(-1e100, 1e100), Arg(-1e3, 1e3)],
  615. ignore_inf_sign=True)
  616. # loss of precision at large arguments due to oscillation
  617. assert_mpmath_equal(sc.jv,
  618. exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
  619. [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
  620. ignore_inf_sign=True,
  621. rtol=1e-5)
  622. def test_besselj_complex(self):
  623. assert_mpmath_equal(lambda v, z: sc.jv(v.real, z),
  624. exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
  625. [Arg(), ComplexArg()])
  626. def test_besselk(self):
  627. assert_mpmath_equal(sc.kv,
  628. mpmath.besselk,
  629. [Arg(-200, 200), Arg(0, np.inf)],
  630. nan_ok=False, rtol=1e-12)
  631. def test_besselk_int(self):
  632. assert_mpmath_equal(sc.kn,
  633. mpmath.besselk,
  634. [IntArg(-200, 200), Arg(0, np.inf)],
  635. nan_ok=False, rtol=1e-12)
  636. def test_besselk_complex(self):
  637. assert_mpmath_equal(lambda v, z: sc.kv(v.real, z),
  638. exception_to_nan(lambda v, z: mpmath.besselk(v, z, **HYPERKW)),
  639. [Arg(-1e100, 1e100), ComplexArg()])
  640. def test_bessely(self):
  641. def mpbessely(v, x):
  642. r = float(mpmath.bessely(v, x, **HYPERKW))
  643. if abs(r) > 1e305:
  644. # overflowing to inf a bit earlier is OK
  645. r = np.inf * np.sign(r)
  646. if abs(r) == 0 and x == 0:
  647. # invalid result from mpmath, point x=0 is a divergence
  648. return np.nan
  649. return r
  650. assert_mpmath_equal(sc.yv,
  651. exception_to_nan(mpbessely),
  652. [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
  653. n=5000)
  654. def test_bessely_complex(self):
  655. def mpbessely(v, x):
  656. r = complex(mpmath.bessely(v, x, **HYPERKW))
  657. if abs(r) > 1e305:
  658. # overflowing to inf a bit earlier is OK
  659. with np.errstate(invalid='ignore'):
  660. r = np.inf * np.sign(r)
  661. return r
  662. assert_mpmath_equal(lambda v, z: sc.yv(v.real, z),
  663. exception_to_nan(mpbessely),
  664. [Arg(), ComplexArg()],
  665. n=15000)
  666. def test_bessely_int(self):
  667. def mpbessely(v, x):
  668. r = float(mpmath.bessely(v, x))
  669. if abs(r) == 0 and x == 0:
  670. # invalid result from mpmath, point x=0 is a divergence
  671. return np.nan
  672. return r
  673. assert_mpmath_equal(lambda v, z: sc.yn(int(v), z),
  674. exception_to_nan(mpbessely),
  675. [IntArg(-1000, 1000), Arg(-1e8, 1e8)])
  676. def test_beta(self):
  677. bad_points = []
  678. def beta(a, b, nonzero=False):
  679. if a < -1e12 or b < -1e12:
  680. # Function is defined here only at integers, but due
  681. # to loss of precision this is numerically
  682. # ill-defined. Don't compare values here.
  683. return np.nan
  684. if (a < 0 or b < 0) and (abs(float(a + b)) % 1) == 0:
  685. # close to a zero of the function: mpmath and scipy
  686. # will not round here the same, so the test needs to be
  687. # run with an absolute tolerance
  688. if nonzero:
  689. bad_points.append((float(a), float(b)))
  690. return np.nan
  691. return mpmath.beta(a, b)
  692. assert_mpmath_equal(sc.beta,
  693. lambda a, b: beta(a, b, nonzero=True),
  694. [Arg(), Arg()],
  695. dps=400,
  696. ignore_inf_sign=True)
  697. assert_mpmath_equal(sc.beta,
  698. beta,
  699. np.array(bad_points),
  700. dps=400,
  701. ignore_inf_sign=True,
  702. atol=1e-11)
  703. def test_betainc(self):
  704. assert_mpmath_equal(sc.betainc,
  705. time_limited()(exception_to_nan(lambda a, b, x: mpmath.betainc(a, b, 0, x, regularized=True))),
  706. [Arg(), Arg(), Arg()])
  707. def test_binom(self):
  708. bad_points = []
  709. def binomial(n, k, nonzero=False):
  710. if abs(k) > 1e8*(abs(n) + 1):
  711. # The binomial is rapidly oscillating in this region,
  712. # and the function is numerically ill-defined. Don't
  713. # compare values here.
  714. return np.nan
  715. if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15:
  716. # close to a zero of the function: mpmath and scipy
  717. # will not round here the same, so the test needs to be
  718. # run with an absolute tolerance
  719. if nonzero:
  720. bad_points.append((float(n), float(k)))
  721. return np.nan
  722. return mpmath.binomial(n, k)
  723. assert_mpmath_equal(sc.binom,
  724. lambda n, k: binomial(n, k, nonzero=True),
  725. [Arg(), Arg()],
  726. dps=400)
  727. assert_mpmath_equal(sc.binom,
  728. binomial,
  729. np.array(bad_points),
  730. dps=400,
  731. atol=1e-14)
  732. def test_chebyt_int(self):
  733. assert_mpmath_equal(lambda n, x: sc.eval_chebyt(int(n), x),
  734. exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)),
  735. [IntArg(), Arg()], dps=50)
  736. @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
  737. def test_chebyt(self):
  738. assert_mpmath_equal(sc.eval_chebyt,
  739. lambda n, x: time_limited()(exception_to_nan(mpmath.chebyt))(n, x, **HYPERKW),
  740. [Arg(-101, 101), Arg()], n=10000)
  741. def test_chebyu_int(self):
  742. assert_mpmath_equal(lambda n, x: sc.eval_chebyu(int(n), x),
  743. exception_to_nan(lambda n, x: mpmath.chebyu(n, x, **HYPERKW)),
  744. [IntArg(), Arg()], dps=50)
  745. @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
  746. def test_chebyu(self):
  747. assert_mpmath_equal(sc.eval_chebyu,
  748. lambda n, x: time_limited()(exception_to_nan(mpmath.chebyu))(n, x, **HYPERKW),
  749. [Arg(-101, 101), Arg()])
  750. def test_chi(self):
  751. def chi(x):
  752. return sc.shichi(x)[1]
  753. assert_mpmath_equal(chi, mpmath.chi, [Arg()])
  754. # check asymptotic series cross-over
  755. assert_mpmath_equal(chi, mpmath.chi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
  756. def test_chi_complex(self):
  757. def chi(z):
  758. return sc.shichi(z)[1]
  759. # chi oscillates as Im[z] -> +- inf, so limit range
  760. assert_mpmath_equal(chi,
  761. mpmath.chi,
  762. [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
  763. rtol=1e-12)
  764. def test_ci(self):
  765. def ci(x):
  766. return sc.sici(x)[1]
  767. # oscillating function: limit range
  768. assert_mpmath_equal(ci,
  769. mpmath.ci,
  770. [Arg(-1e8, 1e8)])
  771. def test_ci_complex(self):
  772. def ci(z):
  773. return sc.sici(z)[1]
  774. # ci oscillates as Re[z] -> +- inf, so limit range
  775. assert_mpmath_equal(ci,
  776. mpmath.ci,
  777. [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
  778. rtol=1e-8)
  779. def test_cospi(self):
  780. eps = np.finfo(float).eps
  781. assert_mpmath_equal(_cospi,
  782. mpmath.cospi,
  783. [Arg()], nan_ok=False, rtol=2*eps)
  784. def test_cospi_complex(self):
  785. assert_mpmath_equal(_cospi,
  786. mpmath.cospi,
  787. [ComplexArg()], nan_ok=False, rtol=1e-13)
  788. def test_digamma(self):
  789. assert_mpmath_equal(sc.digamma,
  790. exception_to_nan(mpmath.digamma),
  791. [Arg()], rtol=1e-12, dps=50)
  792. def test_digamma_complex(self):
  793. # Test on a cut plane because mpmath will hang. See
  794. # test_digamma_negreal for tests on the negative real axis.
  795. def param_filter(z):
  796. return np.where((z.real < 0) & (np.abs(z.imag) < 1.12), False, True)
  797. assert_mpmath_equal(sc.digamma,
  798. exception_to_nan(mpmath.digamma),
  799. [ComplexArg()], rtol=1e-13, dps=40,
  800. param_filter=param_filter)
  801. def test_e1(self):
  802. assert_mpmath_equal(sc.exp1,
  803. mpmath.e1,
  804. [Arg()], rtol=1e-14)
  805. def test_e1_complex(self):
  806. # E_1 oscillates as Im[z] -> +- inf, so limit range
  807. assert_mpmath_equal(sc.exp1,
  808. mpmath.e1,
  809. [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
  810. rtol=1e-11)
  811. # Check cross-over region
  812. assert_mpmath_equal(sc.exp1,
  813. mpmath.e1,
  814. (np.linspace(-50, 50, 171)[:, None] +
  815. np.r_[0, np.logspace(-3, 2, 61),
  816. -np.logspace(-3, 2, 11)]*1j).ravel(),
  817. rtol=1e-11)
  818. assert_mpmath_equal(sc.exp1,
  819. mpmath.e1,
  820. (np.linspace(-50, -35, 10000) + 0j),
  821. rtol=1e-11)
  822. def test_exprel(self):
  823. assert_mpmath_equal(sc.exprel,
  824. lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
  825. [Arg(a=-np.log(np.finfo(np.double).max), b=np.log(np.finfo(np.double).max))])
  826. assert_mpmath_equal(sc.exprel,
  827. lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
  828. np.array([1e-12, 1e-24, 0, 1e12, 1e24, np.inf]), rtol=1e-11)
  829. assert_(np.isinf(sc.exprel(np.inf)))
  830. assert_(sc.exprel(-np.inf) == 0)
  831. def test_expm1_complex(self):
  832. # Oscillates as a function of Im[z], so limit range to avoid loss of precision
  833. assert_mpmath_equal(sc.expm1,
  834. mpmath.expm1,
  835. [ComplexArg(complex(-np.inf, -1e7), complex(np.inf, 1e7))])
  836. def test_log1p_complex(self):
  837. assert_mpmath_equal(sc.log1p,
  838. lambda x: mpmath.log(x+1),
  839. [ComplexArg()], dps=60)
  840. def test_log1pmx(self):
  841. assert_mpmath_equal(_log1pmx,
  842. lambda x: mpmath.log(x + 1) - x,
  843. [Arg()], dps=60, rtol=1e-14)
  844. def test_ei(self):
  845. assert_mpmath_equal(sc.expi,
  846. mpmath.ei,
  847. [Arg()],
  848. rtol=1e-11)
  849. def test_ei_complex(self):
  850. # Ei oscillates as Im[z] -> +- inf, so limit range
  851. assert_mpmath_equal(sc.expi,
  852. mpmath.ei,
  853. [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
  854. rtol=1e-9)
  855. def test_ellipe(self):
  856. assert_mpmath_equal(sc.ellipe,
  857. mpmath.ellipe,
  858. [Arg(b=1.0)])
  859. def test_ellipeinc(self):
  860. assert_mpmath_equal(sc.ellipeinc,
  861. mpmath.ellipe,
  862. [Arg(-1e3, 1e3), Arg(b=1.0)])
  863. def test_ellipeinc_largephi(self):
  864. assert_mpmath_equal(sc.ellipeinc,
  865. mpmath.ellipe,
  866. [Arg(), Arg()])
  867. def test_ellipf(self):
  868. assert_mpmath_equal(sc.ellipkinc,
  869. mpmath.ellipf,
  870. [Arg(-1e3, 1e3), Arg()])
  871. def test_ellipf_largephi(self):
  872. assert_mpmath_equal(sc.ellipkinc,
  873. mpmath.ellipf,
  874. [Arg(), Arg()])
  875. def test_ellipk(self):
  876. assert_mpmath_equal(sc.ellipk,
  877. mpmath.ellipk,
  878. [Arg(b=1.0)])
  879. assert_mpmath_equal(sc.ellipkm1,
  880. lambda m: mpmath.ellipk(1 - m),
  881. [Arg(a=0.0)],
  882. dps=400)
  883. def test_ellipkinc(self):
  884. def ellipkinc(phi, m):
  885. return mpmath.ellippi(0, phi, m)
  886. assert_mpmath_equal(sc.ellipkinc,
  887. ellipkinc,
  888. [Arg(-1e3, 1e3), Arg(b=1.0)],
  889. ignore_inf_sign=True)
  890. def test_ellipkinc_largephi(self):
  891. def ellipkinc(phi, m):
  892. return mpmath.ellippi(0, phi, m)
  893. assert_mpmath_equal(sc.ellipkinc,
  894. ellipkinc,
  895. [Arg(), Arg(b=1.0)],
  896. ignore_inf_sign=True)
  897. def test_ellipfun_sn(self):
  898. def sn(u, m):
  899. # mpmath doesn't get the zero at u = 0--fix that
  900. if u == 0:
  901. return 0
  902. else:
  903. return mpmath.ellipfun("sn", u=u, m=m)
  904. # Oscillating function --- limit range of first argument; the
  905. # loss of precision there is an expected numerical feature
  906. # rather than an actual bug
  907. assert_mpmath_equal(lambda u, m: sc.ellipj(u, m)[0],
  908. sn,
  909. [Arg(-1e6, 1e6), Arg(a=0, b=1)],
  910. rtol=1e-8)
  911. def test_ellipfun_cn(self):
  912. # see comment in ellipfun_sn
  913. assert_mpmath_equal(lambda u, m: sc.ellipj(u, m)[1],
  914. lambda u, m: mpmath.ellipfun("cn", u=u, m=m),
  915. [Arg(-1e6, 1e6), Arg(a=0, b=1)],
  916. rtol=1e-8)
  917. def test_ellipfun_dn(self):
  918. # see comment in ellipfun_sn
  919. assert_mpmath_equal(lambda u, m: sc.ellipj(u, m)[2],
  920. lambda u, m: mpmath.ellipfun("dn", u=u, m=m),
  921. [Arg(-1e6, 1e6), Arg(a=0, b=1)],
  922. rtol=1e-8)
  923. def test_erf(self):
  924. assert_mpmath_equal(sc.erf,
  925. lambda z: mpmath.erf(z),
  926. [Arg()])
  927. def test_erf_complex(self):
  928. assert_mpmath_equal(sc.erf,
  929. lambda z: mpmath.erf(z),
  930. [ComplexArg()], n=200)
  931. def test_erfc(self):
  932. assert_mpmath_equal(sc.erfc,
  933. exception_to_nan(lambda z: mpmath.erfc(z)),
  934. [Arg()], rtol=1e-13)
  935. def test_erfc_complex(self):
  936. assert_mpmath_equal(sc.erfc,
  937. exception_to_nan(lambda z: mpmath.erfc(z)),
  938. [ComplexArg()], n=200)
  939. def test_erfi(self):
  940. assert_mpmath_equal(sc.erfi,
  941. mpmath.erfi,
  942. [Arg()], n=200)
  943. def test_erfi_complex(self):
  944. assert_mpmath_equal(sc.erfi,
  945. mpmath.erfi,
  946. [ComplexArg()], n=200)
  947. def test_ndtr(self):
  948. assert_mpmath_equal(sc.ndtr,
  949. exception_to_nan(lambda z: mpmath.ncdf(z)),
  950. [Arg()], n=200)
  951. def test_ndtr_complex(self):
  952. assert_mpmath_equal(sc.ndtr,
  953. lambda z: mpmath.erfc(-z/np.sqrt(2.))/2.,
  954. [ComplexArg(a=complex(-10000, -10000), b=complex(10000, 10000))], n=400)
  955. def test_log_ndtr(self):
  956. assert_mpmath_equal(sc.log_ndtr,
  957. exception_to_nan(lambda z: mpmath.log(mpmath.ncdf(z))),
  958. [Arg()], n=600, dps=300, rtol=1e-13)
  959. def test_log_ndtr_complex(self):
  960. assert_mpmath_equal(sc.log_ndtr,
  961. exception_to_nan(lambda z: mpmath.log(mpmath.erfc(-z/np.sqrt(2.))/2.)),
  962. [ComplexArg(a=complex(-10000, -100),
  963. b=complex(10000, 100))], n=200, dps=300)
  964. def test_eulernum(self):
  965. assert_mpmath_equal(lambda n: sc.euler(n)[-1],
  966. mpmath.eulernum,
  967. [IntArg(1, 10000)], n=10000)
  968. def test_expint(self):
  969. assert_mpmath_equal(sc.expn,
  970. mpmath.expint,
  971. [IntArg(0, 200), Arg(0, np.inf)],
  972. rtol=1e-13, dps=160)
  973. def test_fresnels(self):
  974. def fresnels(x):
  975. return sc.fresnel(x)[0]
  976. assert_mpmath_equal(fresnels,
  977. mpmath.fresnels,
  978. [Arg()])
  979. def test_fresnelc(self):
  980. def fresnelc(x):
  981. return sc.fresnel(x)[1]
  982. assert_mpmath_equal(fresnelc,
  983. mpmath.fresnelc,
  984. [Arg()])
  985. def test_gamma(self):
  986. assert_mpmath_equal(sc.gamma,
  987. exception_to_nan(mpmath.gamma),
  988. [Arg()])
  989. def test_gamma_complex(self):
  990. assert_mpmath_equal(sc.gamma,
  991. exception_to_nan(mpmath.gamma),
  992. [ComplexArg()], rtol=5e-13)
  993. def test_gammainc(self):
  994. # Larger arguments are tested in test_data.py:test_local
  995. assert_mpmath_equal(sc.gammainc,
  996. lambda z, b: mpmath.gammainc(z, b=b, regularized=True),
  997. [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
  998. nan_ok=False, rtol=1e-11)
  999. def test_gammaincc(self):
  1000. # Larger arguments are tested in test_data.py:test_local
  1001. assert_mpmath_equal(sc.gammaincc,
  1002. lambda z, a: mpmath.gammainc(z, a=a, regularized=True),
  1003. [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
  1004. nan_ok=False, rtol=1e-11)
  1005. def test_gammaln(self):
  1006. # The real part of loggamma is log(|gamma(z)|).
  1007. def f(z):
  1008. return mpmath.loggamma(z).real
  1009. assert_mpmath_equal(sc.gammaln, exception_to_nan(f), [Arg()])
  1010. @pytest.mark.xfail(run=False)
  1011. def test_gegenbauer(self):
  1012. assert_mpmath_equal(sc.eval_gegenbauer,
  1013. exception_to_nan(mpmath.gegenbauer),
  1014. [Arg(-1e3, 1e3), Arg(), Arg()])
  1015. def test_gegenbauer_int(self):
  1016. # Redefine functions to deal with numerical + mpmath issues
  1017. def gegenbauer(n, a, x):
  1018. # Avoid overflow at large `a` (mpmath would need an even larger
  1019. # dps to handle this correctly, so just skip this region)
  1020. if abs(a) > 1e100:
  1021. return np.nan
  1022. # Deal with n=0, n=1 correctly; mpmath 0.17 doesn't do these
  1023. # always correctly
  1024. if n == 0:
  1025. r = 1.0
  1026. elif n == 1:
  1027. r = 2*a*x
  1028. else:
  1029. r = mpmath.gegenbauer(n, a, x)
  1030. # Mpmath 0.17 gives wrong results (spurious zero) in some cases, so
  1031. # compute the value by perturbing the result
  1032. if float(r) == 0 and a < -1 and float(a) == int(float(a)):
  1033. r = mpmath.gegenbauer(n, a + mpmath.mpf('1e-50'), x)
  1034. if abs(r) < mpmath.mpf('1e-50'):
  1035. r = mpmath.mpf('0.0')
  1036. # Differing overflow thresholds in scipy vs. mpmath
  1037. if abs(r) > 1e270:
  1038. return np.inf
  1039. return r
  1040. def sc_gegenbauer(n, a, x):
  1041. r = sc.eval_gegenbauer(int(n), a, x)
  1042. # Differing overflow thresholds in scipy vs. mpmath
  1043. if abs(r) > 1e270:
  1044. return np.inf
  1045. return r
  1046. assert_mpmath_equal(sc_gegenbauer,
  1047. exception_to_nan(gegenbauer),
  1048. [IntArg(0, 100), Arg(-1e9, 1e9), Arg()],
  1049. n=40000, dps=100,
  1050. ignore_inf_sign=True, rtol=1e-6)
  1051. # Check the small-x expansion
  1052. assert_mpmath_equal(sc_gegenbauer,
  1053. exception_to_nan(gegenbauer),
  1054. [IntArg(0, 100), Arg(), FixedArg(np.logspace(-30, -4, 30))],
  1055. dps=100,
  1056. ignore_inf_sign=True)
  1057. @pytest.mark.xfail(run=False)
  1058. def test_gegenbauer_complex(self):
  1059. assert_mpmath_equal(lambda n, a, x: sc.eval_gegenbauer(int(n), a.real, x),
  1060. exception_to_nan(mpmath.gegenbauer),
  1061. [IntArg(0, 100), Arg(), ComplexArg()])
  1062. @nonfunctional_tooslow
  1063. def test_gegenbauer_complex_general(self):
  1064. assert_mpmath_equal(lambda n, a, x: sc.eval_gegenbauer(n.real, a.real, x),
  1065. exception_to_nan(mpmath.gegenbauer),
  1066. [Arg(-1e3, 1e3), Arg(), ComplexArg()])
  1067. def test_hankel1(self):
  1068. assert_mpmath_equal(sc.hankel1,
  1069. exception_to_nan(lambda v, x: mpmath.hankel1(v, x,
  1070. **HYPERKW)),
  1071. [Arg(-1e20, 1e20), Arg()])
  1072. def test_hankel2(self):
  1073. assert_mpmath_equal(sc.hankel2,
  1074. exception_to_nan(lambda v, x: mpmath.hankel2(v, x, **HYPERKW)),
  1075. [Arg(-1e20, 1e20), Arg()])
  1076. @pytest.mark.xfail(run=False, reason="issues at intermediately large orders")
  1077. def test_hermite(self):
  1078. assert_mpmath_equal(lambda n, x: sc.eval_hermite(int(n), x),
  1079. exception_to_nan(mpmath.hermite),
  1080. [IntArg(0, 10000), Arg()])
  1081. # hurwitz: same as zeta
  1082. def test_hyp0f1(self):
  1083. # mpmath reports no convergence unless maxterms is large enough
  1084. KW = dict(maxprec=400, maxterms=1500)
  1085. # n=500 (non-xslow default) fails for one bad point
  1086. assert_mpmath_equal(sc.hyp0f1,
  1087. lambda a, x: mpmath.hyp0f1(a, x, **KW),
  1088. [Arg(-1e7, 1e7), Arg(0, 1e5)],
  1089. n=5000)
  1090. # NB: The range of the second parameter ("z") is limited from below
  1091. # because of an overflow in the intermediate calculations. The way
  1092. # for fix it is to implement an asymptotic expansion for Bessel J
  1093. # (similar to what is implemented for Bessel I here).
  1094. def test_hyp0f1_complex(self):
  1095. assert_mpmath_equal(lambda a, z: sc.hyp0f1(a.real, z),
  1096. exception_to_nan(lambda a, x: mpmath.hyp0f1(a, x, **HYPERKW)),
  1097. [Arg(-10, 10), ComplexArg(complex(-120, -120), complex(120, 120))])
  1098. # NB: The range of the first parameter ("v") are limited by an overflow
  1099. # in the intermediate calculations. Can be fixed by implementing an
  1100. # asymptotic expansion for Bessel functions for large order.
  1101. def test_hyp1f1(self):
  1102. def mpmath_hyp1f1(a, b, x):
  1103. try:
  1104. return mpmath.hyp1f1(a, b, x)
  1105. except ZeroDivisionError:
  1106. return np.inf
  1107. assert_mpmath_equal(
  1108. sc.hyp1f1,
  1109. mpmath_hyp1f1,
  1110. [Arg(-50, 50), Arg(1, 50, inclusive_a=False), Arg(-50, 50)],
  1111. n=500,
  1112. nan_ok=False
  1113. )
  1114. @pytest.mark.xfail(run=False)
  1115. def test_hyp1f1_complex(self):
  1116. assert_mpmath_equal(inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)),
  1117. exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
  1118. [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()],
  1119. n=2000)
  1120. @nonfunctional_tooslow
  1121. def test_hyp2f1_complex(self):
  1122. # SciPy's hyp2f1 seems to have performance and accuracy problems
  1123. assert_mpmath_equal(lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x),
  1124. exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)),
  1125. [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()],
  1126. n=10)
  1127. @pytest.mark.xfail(run=False)
  1128. def test_hyperu(self):
  1129. assert_mpmath_equal(sc.hyperu,
  1130. exception_to_nan(lambda a, b, x: mpmath.hyperu(a, b, x, **HYPERKW)),
  1131. [Arg(), Arg(), Arg()])
  1132. @pytest.mark.xfail_on_32bit("mpmath issue gh-342: unsupported operand mpz, long for pow")
  1133. def test_igam_fac(self):
  1134. def mp_igam_fac(a, x):
  1135. return mpmath.power(x, a)*mpmath.exp(-x)/mpmath.gamma(a)
  1136. assert_mpmath_equal(_igam_fac,
  1137. mp_igam_fac,
  1138. [Arg(0, 1e14, inclusive_a=False), Arg(0, 1e14)],
  1139. rtol=1e-10)
  1140. def test_j0(self):
  1141. # The Bessel function at large arguments is j0(x) ~ cos(x + phi)/sqrt(x)
  1142. # and at large arguments the phase of the cosine loses precision.
  1143. #
  1144. # This is numerically expected behavior, so we compare only up to
  1145. # 1e8 = 1e15 * 1e-7
  1146. assert_mpmath_equal(sc.j0,
  1147. mpmath.j0,
  1148. [Arg(-1e3, 1e3)])
  1149. assert_mpmath_equal(sc.j0,
  1150. mpmath.j0,
  1151. [Arg(-1e8, 1e8)],
  1152. rtol=1e-5)
  1153. def test_j1(self):
  1154. # See comment in test_j0
  1155. assert_mpmath_equal(sc.j1,
  1156. mpmath.j1,
  1157. [Arg(-1e3, 1e3)])
  1158. assert_mpmath_equal(sc.j1,
  1159. mpmath.j1,
  1160. [Arg(-1e8, 1e8)],
  1161. rtol=1e-5)
  1162. @pytest.mark.xfail(run=False)
  1163. def test_jacobi(self):
  1164. assert_mpmath_equal(sc.eval_jacobi,
  1165. exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
  1166. [Arg(), Arg(), Arg(), Arg()])
  1167. assert_mpmath_equal(lambda n, b, c, x: sc.eval_jacobi(int(n), b, c, x),
  1168. exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
  1169. [IntArg(), Arg(), Arg(), Arg()])
  1170. def test_jacobi_int(self):
  1171. # Redefine functions to deal with numerical + mpmath issues
  1172. def jacobi(n, a, b, x):
  1173. # Mpmath does not handle n=0 case always correctly
  1174. if n == 0:
  1175. return 1.0
  1176. return mpmath.jacobi(n, a, b, x)
  1177. assert_mpmath_equal(lambda n, a, b, x: sc.eval_jacobi(int(n), a, b, x),
  1178. lambda n, a, b, x: exception_to_nan(jacobi)(n, a, b, x, **HYPERKW),
  1179. [IntArg(), Arg(), Arg(), Arg()],
  1180. n=20000, dps=50)
  1181. def test_kei(self):
  1182. def kei(x):
  1183. if x == 0:
  1184. # work around mpmath issue at x=0
  1185. return -pi/4
  1186. return exception_to_nan(mpmath.kei)(0, x, **HYPERKW)
  1187. assert_mpmath_equal(sc.kei,
  1188. kei,
  1189. [Arg(-1e30, 1e30)], n=1000)
  1190. def test_ker(self):
  1191. assert_mpmath_equal(sc.ker,
  1192. exception_to_nan(lambda x: mpmath.ker(0, x, **HYPERKW)),
  1193. [Arg(-1e30, 1e30)], n=1000)
  1194. @nonfunctional_tooslow
  1195. def test_laguerre(self):
  1196. assert_mpmath_equal(trace_args(sc.eval_laguerre),
  1197. lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
  1198. [Arg(), Arg()])
  1199. def test_laguerre_int(self):
  1200. assert_mpmath_equal(lambda n, x: sc.eval_laguerre(int(n), x),
  1201. lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
  1202. [IntArg(), Arg()], n=20000)
  1203. @pytest.mark.xfail_on_32bit("see gh-3551 for bad points")
  1204. def test_lambertw_real(self):
  1205. assert_mpmath_equal(lambda x, k: sc.lambertw(x, int(k.real)),
  1206. lambda x, k: mpmath.lambertw(x, int(k.real)),
  1207. [ComplexArg(-np.inf, np.inf), IntArg(0, 10)],
  1208. rtol=1e-13, nan_ok=False)
  1209. def test_lanczos_sum_expg_scaled(self):
  1210. maxgamma = 171.624376956302725
  1211. e = np.exp(1)
  1212. g = 6.024680040776729583740234375
  1213. def gamma(x):
  1214. with np.errstate(over='ignore'):
  1215. fac = ((x + g - 0.5)/e)**(x - 0.5)
  1216. if fac != np.inf:
  1217. res = fac*_lanczos_sum_expg_scaled(x)
  1218. else:
  1219. fac = ((x + g - 0.5)/e)**(0.5*(x - 0.5))
  1220. res = fac*_lanczos_sum_expg_scaled(x)
  1221. res *= fac
  1222. return res
  1223. assert_mpmath_equal(gamma,
  1224. mpmath.gamma,
  1225. [Arg(0, maxgamma, inclusive_a=False)],
  1226. rtol=1e-13)
  1227. @nonfunctional_tooslow
  1228. def test_legendre(self):
  1229. assert_mpmath_equal(sc.eval_legendre,
  1230. mpmath.legendre,
  1231. [Arg(), Arg()])
  1232. def test_legendre_int(self):
  1233. assert_mpmath_equal(lambda n, x: sc.eval_legendre(int(n), x),
  1234. lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
  1235. [IntArg(), Arg()],
  1236. n=20000)
  1237. # Check the small-x expansion
  1238. assert_mpmath_equal(lambda n, x: sc.eval_legendre(int(n), x),
  1239. lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
  1240. [IntArg(), FixedArg(np.logspace(-30, -4, 20))])
  1241. def test_legenp(self):
  1242. def lpnm(n, m, z):
  1243. try:
  1244. v = sc.lpmn(m, n, z)[0][-1,-1]
  1245. except ValueError:
  1246. return np.nan
  1247. if abs(v) > 1e306:
  1248. # harmonize overflow to inf
  1249. v = np.inf * np.sign(v.real)
  1250. return v
  1251. def lpnm_2(n, m, z):
  1252. v = sc.lpmv(m, n, z)
  1253. if abs(v) > 1e306:
  1254. # harmonize overflow to inf
  1255. v = np.inf * np.sign(v.real)
  1256. return v
  1257. def legenp(n, m, z):
  1258. if (z == 1 or z == -1) and int(n) == n:
  1259. # Special case (mpmath may give inf, we take the limit by
  1260. # continuity)
  1261. if m == 0:
  1262. if n < 0:
  1263. n = -n - 1
  1264. return mpmath.power(mpmath.sign(z), n)
  1265. else:
  1266. return 0
  1267. if abs(z) < 1e-15:
  1268. # mpmath has bad performance here
  1269. return np.nan
  1270. typ = 2 if abs(z) < 1 else 3
  1271. v = exception_to_nan(mpmath.legenp)(n, m, z, type=typ)
  1272. if abs(v) > 1e306:
  1273. # harmonize overflow to inf
  1274. v = mpmath.inf * mpmath.sign(v.real)
  1275. return v
  1276. assert_mpmath_equal(lpnm,
  1277. legenp,
  1278. [IntArg(-100, 100), IntArg(-100, 100), Arg()])
  1279. assert_mpmath_equal(lpnm_2,
  1280. legenp,
  1281. [IntArg(-100, 100), Arg(-100, 100), Arg(-1, 1)],
  1282. atol=1e-10)
  1283. def test_legenp_complex_2(self):
  1284. def clpnm(n, m, z):
  1285. try:
  1286. return sc.clpmn(m.real, n.real, z, type=2)[0][-1,-1]
  1287. except ValueError:
  1288. return np.nan
  1289. def legenp(n, m, z):
  1290. if abs(z) < 1e-15:
  1291. # mpmath has bad performance here
  1292. return np.nan
  1293. return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=2)
  1294. # mpmath is quite slow here
  1295. x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
  1296. y = np.array([-1e3, -0.5, 0.5, 1.3])
  1297. z = (x[:,None] + 1j*y[None,:]).ravel()
  1298. assert_mpmath_equal(clpnm,
  1299. legenp,
  1300. [FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg(z)],
  1301. rtol=1e-6,
  1302. n=500)
  1303. def test_legenp_complex_3(self):
  1304. def clpnm(n, m, z):
  1305. try:
  1306. return sc.clpmn(m.real, n.real, z, type=3)[0][-1,-1]
  1307. except ValueError:
  1308. return np.nan
  1309. def legenp(n, m, z):
  1310. if abs(z) < 1e-15:
  1311. # mpmath has bad performance here
  1312. return np.nan
  1313. return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=3)
  1314. # mpmath is quite slow here
  1315. x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
  1316. y = np.array([-1e3, -0.5, 0.5, 1.3])
  1317. z = (x[:,None] + 1j*y[None,:]).ravel()
  1318. assert_mpmath_equal(clpnm,
  1319. legenp,
  1320. [FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg(z)],
  1321. rtol=1e-6,
  1322. n=500)
  1323. @pytest.mark.xfail(run=False, reason="apparently picks wrong function at |z| > 1")
  1324. def test_legenq(self):
  1325. def lqnm(n, m, z):
  1326. return sc.lqmn(m, n, z)[0][-1,-1]
  1327. def legenq(n, m, z):
  1328. if abs(z) < 1e-15:
  1329. # mpmath has bad performance here
  1330. return np.nan
  1331. return exception_to_nan(mpmath.legenq)(n, m, z, type=2)
  1332. assert_mpmath_equal(lqnm,
  1333. legenq,
  1334. [IntArg(0, 100), IntArg(0, 100), Arg()])
  1335. @nonfunctional_tooslow
  1336. def test_legenq_complex(self):
  1337. def lqnm(n, m, z):
  1338. return sc.lqmn(int(m.real), int(n.real), z)[0][-1,-1]
  1339. def legenq(n, m, z):
  1340. if abs(z) < 1e-15:
  1341. # mpmath has bad performance here
  1342. return np.nan
  1343. return exception_to_nan(mpmath.legenq)(int(n.real), int(m.real), z, type=2)
  1344. assert_mpmath_equal(lqnm,
  1345. legenq,
  1346. [IntArg(0, 100), IntArg(0, 100), ComplexArg()],
  1347. n=100)
  1348. def test_lgam1p(self):
  1349. def param_filter(x):
  1350. # Filter the poles
  1351. return np.where((np.floor(x) == x) & (x <= 0), False, True)
  1352. def mp_lgam1p(z):
  1353. # The real part of loggamma is log(|gamma(z)|)
  1354. return mpmath.loggamma(1 + z).real
  1355. assert_mpmath_equal(_lgam1p,
  1356. mp_lgam1p,
  1357. [Arg()], rtol=1e-13, dps=100,
  1358. param_filter=param_filter)
  1359. def test_loggamma(self):
  1360. def mpmath_loggamma(z):
  1361. try:
  1362. res = mpmath.loggamma(z)
  1363. except ValueError:
  1364. res = complex(np.nan, np.nan)
  1365. return res
  1366. assert_mpmath_equal(sc.loggamma,
  1367. mpmath_loggamma,
  1368. [ComplexArg()], nan_ok=False,
  1369. distinguish_nan_and_inf=False, rtol=5e-14)
  1370. @pytest.mark.xfail(run=False)
  1371. def test_pcfd(self):
  1372. def pcfd(v, x):
  1373. return sc.pbdv(v, x)[0]
  1374. assert_mpmath_equal(pcfd,
  1375. exception_to_nan(lambda v, x: mpmath.pcfd(v, x, **HYPERKW)),
  1376. [Arg(), Arg()])
  1377. @pytest.mark.xfail(run=False, reason="it's not the same as the mpmath function --- maybe different definition?")
  1378. def test_pcfv(self):
  1379. def pcfv(v, x):
  1380. return sc.pbvv(v, x)[0]
  1381. assert_mpmath_equal(pcfv,
  1382. lambda v, x: time_limited()(exception_to_nan(mpmath.pcfv))(v, x, **HYPERKW),
  1383. [Arg(), Arg()], n=1000)
  1384. def test_pcfw(self):
  1385. def pcfw(a, x):
  1386. return sc.pbwa(a, x)[0]
  1387. def dpcfw(a, x):
  1388. return sc.pbwa(a, x)[1]
  1389. def mpmath_dpcfw(a, x):
  1390. return mpmath.diff(mpmath.pcfw, (a, x), (0, 1))
  1391. # The Zhang and Jin implementation only uses Taylor series and
  1392. # is thus accurate in only a very small range.
  1393. assert_mpmath_equal(pcfw,
  1394. mpmath.pcfw,
  1395. [Arg(-5, 5), Arg(-5, 5)], rtol=2e-8, n=100)
  1396. assert_mpmath_equal(dpcfw,
  1397. mpmath_dpcfw,
  1398. [Arg(-5, 5), Arg(-5, 5)], rtol=2e-9, n=100)
  1399. @pytest.mark.xfail(run=False, reason="issues at large arguments (atol OK, rtol not) and <eps-close to z=0")
  1400. def test_polygamma(self):
  1401. assert_mpmath_equal(sc.polygamma,
  1402. time_limited()(exception_to_nan(mpmath.polygamma)),
  1403. [IntArg(0, 1000), Arg()])
  1404. def test_rgamma(self):
  1405. assert_mpmath_equal(
  1406. sc.rgamma,
  1407. mpmath.rgamma,
  1408. [Arg(-8000, np.inf)],
  1409. n=5000,
  1410. nan_ok=False,
  1411. ignore_inf_sign=True,
  1412. )
  1413. def test_rgamma_complex(self):
  1414. assert_mpmath_equal(sc.rgamma,
  1415. exception_to_nan(mpmath.rgamma),
  1416. [ComplexArg()], rtol=5e-13)
  1417. @pytest.mark.xfail(reason=("see gh-3551 for bad points on 32 bit "
  1418. "systems and gh-8095 for another bad "
  1419. "point"))
  1420. def test_rf(self):
  1421. if _pep440.parse(mpmath.__version__) >= _pep440.Version("1.0.0"):
  1422. # no workarounds needed
  1423. mppoch = mpmath.rf
  1424. else:
  1425. def mppoch(a, m):
  1426. # deal with cases where the result in double precision
  1427. # hits exactly a non-positive integer, but the
  1428. # corresponding extended-precision mpf floats don't
  1429. if float(a + m) == int(a + m) and float(a + m) <= 0:
  1430. a = mpmath.mpf(a)
  1431. m = int(a + m) - a
  1432. return mpmath.rf(a, m)
  1433. assert_mpmath_equal(sc.poch,
  1434. mppoch,
  1435. [Arg(), Arg()],
  1436. dps=400)
  1437. def test_sinpi(self):
  1438. eps = np.finfo(float).eps
  1439. assert_mpmath_equal(_sinpi, mpmath.sinpi,
  1440. [Arg()], nan_ok=False, rtol=2*eps)
  1441. def test_sinpi_complex(self):
  1442. assert_mpmath_equal(_sinpi, mpmath.sinpi,
  1443. [ComplexArg()], nan_ok=False, rtol=2e-14)
  1444. def test_shi(self):
  1445. def shi(x):
  1446. return sc.shichi(x)[0]
  1447. assert_mpmath_equal(shi, mpmath.shi, [Arg()])
  1448. # check asymptotic series cross-over
  1449. assert_mpmath_equal(shi, mpmath.shi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
  1450. def test_shi_complex(self):
  1451. def shi(z):
  1452. return sc.shichi(z)[0]
  1453. # shi oscillates as Im[z] -> +- inf, so limit range
  1454. assert_mpmath_equal(shi,
  1455. mpmath.shi,
  1456. [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
  1457. rtol=1e-12)
  1458. def test_si(self):
  1459. def si(x):
  1460. return sc.sici(x)[0]
  1461. assert_mpmath_equal(si, mpmath.si, [Arg()])
  1462. def test_si_complex(self):
  1463. def si(z):
  1464. return sc.sici(z)[0]
  1465. # si oscillates as Re[z] -> +- inf, so limit range
  1466. assert_mpmath_equal(si,
  1467. mpmath.si,
  1468. [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
  1469. rtol=1e-12)
  1470. def test_spence(self):
  1471. # mpmath uses a different convention for the dilogarithm
  1472. def dilog(x):
  1473. return mpmath.polylog(2, 1 - x)
  1474. # Spence has a branch cut on the negative real axis
  1475. assert_mpmath_equal(sc.spence,
  1476. exception_to_nan(dilog),
  1477. [Arg(0, np.inf)], rtol=1e-14)
  1478. def test_spence_complex(self):
  1479. def dilog(z):
  1480. return mpmath.polylog(2, 1 - z)
  1481. assert_mpmath_equal(sc.spence,
  1482. exception_to_nan(dilog),
  1483. [ComplexArg()], rtol=1e-14)
  1484. def test_spherharm(self):
  1485. def spherharm(l, m, theta, phi):
  1486. if m > l:
  1487. return np.nan
  1488. return sc.sph_harm(m, l, phi, theta)
  1489. assert_mpmath_equal(spherharm,
  1490. mpmath.spherharm,
  1491. [IntArg(0, 100), IntArg(0, 100),
  1492. Arg(a=0, b=pi), Arg(a=0, b=2*pi)],
  1493. atol=1e-8, n=6000,
  1494. dps=150)
  1495. def test_struveh(self):
  1496. assert_mpmath_equal(sc.struve,
  1497. exception_to_nan(mpmath.struveh),
  1498. [Arg(-1e4, 1e4), Arg(0, 1e4)],
  1499. rtol=5e-10)
  1500. def test_struvel(self):
  1501. def mp_struvel(v, z):
  1502. if v < 0 and z < -v and abs(v) > 1000:
  1503. # larger DPS needed for correct results
  1504. old_dps = mpmath.mp.dps
  1505. try:
  1506. mpmath.mp.dps = 300
  1507. return mpmath.struvel(v, z)
  1508. finally:
  1509. mpmath.mp.dps = old_dps
  1510. return mpmath.struvel(v, z)
  1511. assert_mpmath_equal(sc.modstruve,
  1512. exception_to_nan(mp_struvel),
  1513. [Arg(-1e4, 1e4), Arg(0, 1e4)],
  1514. rtol=5e-10,
  1515. ignore_inf_sign=True)
  1516. def test_wrightomega_real(self):
  1517. def mpmath_wrightomega_real(x):
  1518. return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
  1519. # For x < -1000 the Wright Omega function is just 0 to double
  1520. # precision, and for x > 1e21 it is just x to double
  1521. # precision.
  1522. assert_mpmath_equal(
  1523. sc.wrightomega,
  1524. mpmath_wrightomega_real,
  1525. [Arg(-1000, 1e21)],
  1526. rtol=5e-15,
  1527. atol=0,
  1528. nan_ok=False,
  1529. )
  1530. def test_wrightomega(self):
  1531. assert_mpmath_equal(sc.wrightomega,
  1532. lambda z: _mpmath_wrightomega(z, 25),
  1533. [ComplexArg()], rtol=1e-14, nan_ok=False)
  1534. def test_hurwitz_zeta(self):
  1535. assert_mpmath_equal(sc.zeta,
  1536. exception_to_nan(mpmath.zeta),
  1537. [Arg(a=1, b=1e10, inclusive_a=False),
  1538. Arg(a=0, inclusive_a=False)])
  1539. def test_riemann_zeta(self):
  1540. assert_mpmath_equal(
  1541. sc.zeta,
  1542. lambda x: mpmath.zeta(x) if x != 1 else mpmath.inf,
  1543. [Arg(-100, 100)],
  1544. nan_ok=False,
  1545. rtol=5e-13,
  1546. )
  1547. def test_zetac(self):
  1548. assert_mpmath_equal(sc.zetac,
  1549. lambda x: (mpmath.zeta(x) - 1
  1550. if x != 1 else mpmath.inf),
  1551. [Arg(-100, 100)],
  1552. nan_ok=False, dps=45, rtol=5e-13)
  1553. def test_boxcox(self):
  1554. def mp_boxcox(x, lmbda):
  1555. x = mpmath.mp.mpf(x)
  1556. lmbda = mpmath.mp.mpf(lmbda)
  1557. if lmbda == 0:
  1558. return mpmath.mp.log(x)
  1559. else:
  1560. return mpmath.mp.powm1(x, lmbda) / lmbda
  1561. assert_mpmath_equal(sc.boxcox,
  1562. exception_to_nan(mp_boxcox),
  1563. [Arg(a=0, inclusive_a=False), Arg()],
  1564. n=200,
  1565. dps=60,
  1566. rtol=1e-13)
  1567. def test_boxcox1p(self):
  1568. def mp_boxcox1p(x, lmbda):
  1569. x = mpmath.mp.mpf(x)
  1570. lmbda = mpmath.mp.mpf(lmbda)
  1571. one = mpmath.mp.mpf(1)
  1572. if lmbda == 0:
  1573. return mpmath.mp.log(one + x)
  1574. else:
  1575. return mpmath.mp.powm1(one + x, lmbda) / lmbda
  1576. assert_mpmath_equal(sc.boxcox1p,
  1577. exception_to_nan(mp_boxcox1p),
  1578. [Arg(a=-1, inclusive_a=False), Arg()],
  1579. n=200,
  1580. dps=60,
  1581. rtol=1e-13)
  1582. def test_spherical_jn(self):
  1583. def mp_spherical_jn(n, z):
  1584. arg = mpmath.mpmathify(z)
  1585. out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
  1586. mpmath.sqrt(2*arg/mpmath.pi))
  1587. if arg.imag == 0:
  1588. return out.real
  1589. else:
  1590. return out
  1591. assert_mpmath_equal(lambda n, z: sc.spherical_jn(int(n), z),
  1592. exception_to_nan(mp_spherical_jn),
  1593. [IntArg(0, 200), Arg(-1e8, 1e8)],
  1594. dps=300)
  1595. def test_spherical_jn_complex(self):
  1596. def mp_spherical_jn(n, z):
  1597. arg = mpmath.mpmathify(z)
  1598. out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
  1599. mpmath.sqrt(2*arg/mpmath.pi))
  1600. if arg.imag == 0:
  1601. return out.real
  1602. else:
  1603. return out
  1604. assert_mpmath_equal(lambda n, z: sc.spherical_jn(int(n.real), z),
  1605. exception_to_nan(mp_spherical_jn),
  1606. [IntArg(0, 200), ComplexArg()])
  1607. def test_spherical_yn(self):
  1608. def mp_spherical_yn(n, z):
  1609. arg = mpmath.mpmathify(z)
  1610. out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
  1611. mpmath.sqrt(2*arg/mpmath.pi))
  1612. if arg.imag == 0:
  1613. return out.real
  1614. else:
  1615. return out
  1616. assert_mpmath_equal(lambda n, z: sc.spherical_yn(int(n), z),
  1617. exception_to_nan(mp_spherical_yn),
  1618. [IntArg(0, 200), Arg(-1e10, 1e10)],
  1619. dps=100)
  1620. def test_spherical_yn_complex(self):
  1621. def mp_spherical_yn(n, z):
  1622. arg = mpmath.mpmathify(z)
  1623. out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
  1624. mpmath.sqrt(2*arg/mpmath.pi))
  1625. if arg.imag == 0:
  1626. return out.real
  1627. else:
  1628. return out
  1629. assert_mpmath_equal(lambda n, z: sc.spherical_yn(int(n.real), z),
  1630. exception_to_nan(mp_spherical_yn),
  1631. [IntArg(0, 200), ComplexArg()])
  1632. def test_spherical_in(self):
  1633. def mp_spherical_in(n, z):
  1634. arg = mpmath.mpmathify(z)
  1635. out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
  1636. mpmath.sqrt(2*arg/mpmath.pi))
  1637. if arg.imag == 0:
  1638. return out.real
  1639. else:
  1640. return out
  1641. assert_mpmath_equal(lambda n, z: sc.spherical_in(int(n), z),
  1642. exception_to_nan(mp_spherical_in),
  1643. [IntArg(0, 200), Arg()],
  1644. dps=200, atol=10**(-278))
  1645. def test_spherical_in_complex(self):
  1646. def mp_spherical_in(n, z):
  1647. arg = mpmath.mpmathify(z)
  1648. out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
  1649. mpmath.sqrt(2*arg/mpmath.pi))
  1650. if arg.imag == 0:
  1651. return out.real
  1652. else:
  1653. return out
  1654. assert_mpmath_equal(lambda n, z: sc.spherical_in(int(n.real), z),
  1655. exception_to_nan(mp_spherical_in),
  1656. [IntArg(0, 200), ComplexArg()])
  1657. def test_spherical_kn(self):
  1658. def mp_spherical_kn(n, z):
  1659. out = (mpmath.besselk(n + mpmath.mpf(1)/2, z) *
  1660. mpmath.sqrt(mpmath.pi/(2*mpmath.mpmathify(z))))
  1661. if mpmath.mpmathify(z).imag == 0:
  1662. return out.real
  1663. else:
  1664. return out
  1665. assert_mpmath_equal(lambda n, z: sc.spherical_kn(int(n), z),
  1666. exception_to_nan(mp_spherical_kn),
  1667. [IntArg(0, 150), Arg()],
  1668. dps=100)
  1669. @pytest.mark.xfail(run=False, reason="Accuracy issues near z = -1 inherited from kv.")
  1670. def test_spherical_kn_complex(self):
  1671. def mp_spherical_kn(n, z):
  1672. arg = mpmath.mpmathify(z)
  1673. out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) /
  1674. mpmath.sqrt(2*arg/mpmath.pi))
  1675. if arg.imag == 0:
  1676. return out.real
  1677. else:
  1678. return out
  1679. assert_mpmath_equal(lambda n, z: sc.spherical_kn(int(n.real), z),
  1680. exception_to_nan(mp_spherical_kn),
  1681. [IntArg(0, 200), ComplexArg()],
  1682. dps=200)