basic.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  1. #
  2. # Author: Travis Oliphant, 2002
  3. #
  4. from __future__ import division, print_function, absolute_import
  5. import operator
  6. import numpy as np
  7. import math
  8. from scipy._lib.six import xrange
  9. from numpy import (pi, asarray, floor, isscalar, iscomplex, real,
  10. imag, sqrt, where, mgrid, sin, place, issubdtype,
  11. extract, inexact, nan, zeros, sinc)
  12. from . import _ufuncs as ufuncs
  13. from ._ufuncs import (ellipkm1, mathieu_a, mathieu_b, iv, jv, gamma,
  14. psi, _zeta, hankel1, hankel2, yv, kv, ndtri,
  15. poch, binom, hyp0f1)
  16. from . import specfun
  17. from . import orthogonal
  18. from ._comb import _comb_int
  19. __all__ = ['ai_zeros', 'assoc_laguerre', 'bei_zeros', 'beip_zeros',
  20. 'ber_zeros', 'bernoulli', 'berp_zeros',
  21. 'bessel_diff_formula', 'bi_zeros', 'clpmn', 'comb',
  22. 'digamma', 'diric', 'ellipk', 'erf_zeros', 'erfcinv',
  23. 'erfinv', 'euler', 'factorial', 'factorialk', 'factorial2',
  24. 'fresnel_zeros', 'fresnelc_zeros', 'fresnels_zeros',
  25. 'gamma', 'h1vp', 'h2vp', 'hankel1', 'hankel2', 'hyp0f1',
  26. 'iv', 'ivp', 'jn_zeros', 'jnjnp_zeros', 'jnp_zeros',
  27. 'jnyn_zeros', 'jv', 'jvp', 'kei_zeros', 'keip_zeros',
  28. 'kelvin_zeros', 'ker_zeros', 'kerp_zeros', 'kv', 'kvp',
  29. 'lmbda', 'lpmn', 'lpn', 'lqmn', 'lqn', 'mathieu_a',
  30. 'mathieu_b', 'mathieu_even_coef', 'mathieu_odd_coef',
  31. 'ndtri', 'obl_cv_seq', 'pbdn_seq', 'pbdv_seq', 'pbvv_seq',
  32. 'perm', 'polygamma', 'pro_cv_seq', 'psi', 'riccati_jn',
  33. 'riccati_yn', 'sinc', 'y0_zeros', 'y1_zeros', 'y1p_zeros',
  34. 'yn_zeros', 'ynp_zeros', 'yv', 'yvp', 'zeta']
  35. def _nonneg_int_or_fail(n, var_name, strict=True):
  36. try:
  37. if strict:
  38. # Raises an exception if float
  39. n = operator.index(n)
  40. elif n == floor(n):
  41. n = int(n)
  42. else:
  43. raise ValueError()
  44. if n < 0:
  45. raise ValueError()
  46. except (ValueError, TypeError) as err:
  47. raise err.__class__("{} must be a non-negative integer".format(var_name))
  48. return n
  49. def diric(x, n):
  50. """Periodic sinc function, also called the Dirichlet function.
  51. The Dirichlet function is defined as::
  52. diric(x, n) = sin(x * n/2) / (n * sin(x / 2)),
  53. where `n` is a positive integer.
  54. Parameters
  55. ----------
  56. x : array_like
  57. Input data
  58. n : int
  59. Integer defining the periodicity.
  60. Returns
  61. -------
  62. diric : ndarray
  63. Examples
  64. --------
  65. >>> from scipy import special
  66. >>> import matplotlib.pyplot as plt
  67. >>> x = np.linspace(-8*np.pi, 8*np.pi, num=201)
  68. >>> plt.figure(figsize=(8, 8));
  69. >>> for idx, n in enumerate([2, 3, 4, 9]):
  70. ... plt.subplot(2, 2, idx+1)
  71. ... plt.plot(x, special.diric(x, n))
  72. ... plt.title('diric, n={}'.format(n))
  73. >>> plt.show()
  74. The following example demonstrates that `diric` gives the magnitudes
  75. (modulo the sign and scaling) of the Fourier coefficients of a
  76. rectangular pulse.
  77. Suppress output of values that are effectively 0:
  78. >>> np.set_printoptions(suppress=True)
  79. Create a signal `x` of length `m` with `k` ones:
  80. >>> m = 8
  81. >>> k = 3
  82. >>> x = np.zeros(m)
  83. >>> x[:k] = 1
  84. Use the FFT to compute the Fourier transform of `x`, and
  85. inspect the magnitudes of the coefficients:
  86. >>> np.abs(np.fft.fft(x))
  87. array([ 3. , 2.41421356, 1. , 0.41421356, 1. ,
  88. 0.41421356, 1. , 2.41421356])
  89. Now find the same values (up to sign) using `diric`. We multiply
  90. by `k` to account for the different scaling conventions of
  91. `numpy.fft.fft` and `diric`:
  92. >>> theta = np.linspace(0, 2*np.pi, m, endpoint=False)
  93. >>> k * special.diric(theta, k)
  94. array([ 3. , 2.41421356, 1. , -0.41421356, -1. ,
  95. -0.41421356, 1. , 2.41421356])
  96. """
  97. x, n = asarray(x), asarray(n)
  98. n = asarray(n + (x-x))
  99. x = asarray(x + (n-n))
  100. if issubdtype(x.dtype, inexact):
  101. ytype = x.dtype
  102. else:
  103. ytype = float
  104. y = zeros(x.shape, ytype)
  105. # empirical minval for 32, 64 or 128 bit float computations
  106. # where sin(x/2) < minval, result is fixed at +1 or -1
  107. if np.finfo(ytype).eps < 1e-18:
  108. minval = 1e-11
  109. elif np.finfo(ytype).eps < 1e-15:
  110. minval = 1e-7
  111. else:
  112. minval = 1e-3
  113. mask1 = (n <= 0) | (n != floor(n))
  114. place(y, mask1, nan)
  115. x = x / 2
  116. denom = sin(x)
  117. mask2 = (1-mask1) & (abs(denom) < minval)
  118. xsub = extract(mask2, x)
  119. nsub = extract(mask2, n)
  120. zsub = xsub / pi
  121. place(y, mask2, pow(-1, np.round(zsub)*(nsub-1)))
  122. mask = (1-mask1) & (1-mask2)
  123. xsub = extract(mask, x)
  124. nsub = extract(mask, n)
  125. dsub = extract(mask, denom)
  126. place(y, mask, sin(nsub*xsub)/(nsub*dsub))
  127. return y
  128. def jnjnp_zeros(nt):
  129. """Compute zeros of integer-order Bessel functions Jn and Jn'.
  130. Results are arranged in order of the magnitudes of the zeros.
  131. Parameters
  132. ----------
  133. nt : int
  134. Number (<=1200) of zeros to compute
  135. Returns
  136. -------
  137. zo[l-1] : ndarray
  138. Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
  139. n[l-1] : ndarray
  140. Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
  141. m[l-1] : ndarray
  142. Serial number of the zeros of Jn(x) or Jn'(x) associated
  143. with lth zero. Of length `nt`.
  144. t[l-1] : ndarray
  145. 0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
  146. length `nt`.
  147. See Also
  148. --------
  149. jn_zeros, jnp_zeros : to get separated arrays of zeros.
  150. References
  151. ----------
  152. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  153. Functions", John Wiley and Sons, 1996, chapter 5.
  154. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  155. """
  156. if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
  157. raise ValueError("Number must be integer <= 1200.")
  158. nt = int(nt)
  159. n, m, t, zo = specfun.jdzo(nt)
  160. return zo[1:nt+1], n[:nt], m[:nt], t[:nt]
  161. def jnyn_zeros(n, nt):
  162. """Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
  163. Returns 4 arrays of length `nt`, corresponding to the first `nt` zeros of
  164. Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively.
  165. Parameters
  166. ----------
  167. n : int
  168. Order of the Bessel functions
  169. nt : int
  170. Number (<=1200) of zeros to compute
  171. See jn_zeros, jnp_zeros, yn_zeros, ynp_zeros to get separate arrays.
  172. References
  173. ----------
  174. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  175. Functions", John Wiley and Sons, 1996, chapter 5.
  176. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  177. """
  178. if not (isscalar(nt) and isscalar(n)):
  179. raise ValueError("Arguments must be scalars.")
  180. if (floor(n) != n) or (floor(nt) != nt):
  181. raise ValueError("Arguments must be integers.")
  182. if (nt <= 0):
  183. raise ValueError("nt > 0")
  184. return specfun.jyzo(abs(n), nt)
  185. def jn_zeros(n, nt):
  186. """Compute zeros of integer-order Bessel function Jn(x).
  187. Parameters
  188. ----------
  189. n : int
  190. Order of Bessel function
  191. nt : int
  192. Number of zeros to return
  193. References
  194. ----------
  195. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  196. Functions", John Wiley and Sons, 1996, chapter 5.
  197. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  198. """
  199. return jnyn_zeros(n, nt)[0]
  200. def jnp_zeros(n, nt):
  201. """Compute zeros of integer-order Bessel function derivative Jn'(x).
  202. Parameters
  203. ----------
  204. n : int
  205. Order of Bessel function
  206. nt : int
  207. Number of zeros to return
  208. References
  209. ----------
  210. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  211. Functions", John Wiley and Sons, 1996, chapter 5.
  212. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  213. """
  214. return jnyn_zeros(n, nt)[1]
  215. def yn_zeros(n, nt):
  216. """Compute zeros of integer-order Bessel function Yn(x).
  217. Parameters
  218. ----------
  219. n : int
  220. Order of Bessel function
  221. nt : int
  222. Number of zeros to return
  223. References
  224. ----------
  225. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  226. Functions", John Wiley and Sons, 1996, chapter 5.
  227. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  228. """
  229. return jnyn_zeros(n, nt)[2]
  230. def ynp_zeros(n, nt):
  231. """Compute zeros of integer-order Bessel function derivative Yn'(x).
  232. Parameters
  233. ----------
  234. n : int
  235. Order of Bessel function
  236. nt : int
  237. Number of zeros to return
  238. References
  239. ----------
  240. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  241. Functions", John Wiley and Sons, 1996, chapter 5.
  242. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  243. """
  244. return jnyn_zeros(n, nt)[3]
  245. def y0_zeros(nt, complex=False):
  246. """Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
  247. The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0.
  248. Parameters
  249. ----------
  250. nt : int
  251. Number of zeros to return
  252. complex : bool, default False
  253. Set to False to return only the real zeros; set to True to return only
  254. the complex zeros with negative real part and positive imaginary part.
  255. Note that the complex conjugates of the latter are also zeros of the
  256. function, but are not returned by this routine.
  257. Returns
  258. -------
  259. z0n : ndarray
  260. Location of nth zero of Y0(z)
  261. y0pz0n : ndarray
  262. Value of derivative Y0'(z0) for nth zero
  263. References
  264. ----------
  265. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  266. Functions", John Wiley and Sons, 1996, chapter 5.
  267. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  268. """
  269. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  270. raise ValueError("Arguments must be scalar positive integer.")
  271. kf = 0
  272. kc = not complex
  273. return specfun.cyzo(nt, kf, kc)
  274. def y1_zeros(nt, complex=False):
  275. """Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
  276. The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1.
  277. Parameters
  278. ----------
  279. nt : int
  280. Number of zeros to return
  281. complex : bool, default False
  282. Set to False to return only the real zeros; set to True to return only
  283. the complex zeros with negative real part and positive imaginary part.
  284. Note that the complex conjugates of the latter are also zeros of the
  285. function, but are not returned by this routine.
  286. Returns
  287. -------
  288. z1n : ndarray
  289. Location of nth zero of Y1(z)
  290. y1pz1n : ndarray
  291. Value of derivative Y1'(z1) for nth zero
  292. References
  293. ----------
  294. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  295. Functions", John Wiley and Sons, 1996, chapter 5.
  296. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  297. """
  298. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  299. raise ValueError("Arguments must be scalar positive integer.")
  300. kf = 1
  301. kc = not complex
  302. return specfun.cyzo(nt, kf, kc)
  303. def y1p_zeros(nt, complex=False):
  304. """Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
  305. The values are given by Y1(z1) at each z1 where Y1'(z1)=0.
  306. Parameters
  307. ----------
  308. nt : int
  309. Number of zeros to return
  310. complex : bool, default False
  311. Set to False to return only the real zeros; set to True to return only
  312. the complex zeros with negative real part and positive imaginary part.
  313. Note that the complex conjugates of the latter are also zeros of the
  314. function, but are not returned by this routine.
  315. Returns
  316. -------
  317. z1pn : ndarray
  318. Location of nth zero of Y1'(z)
  319. y1z1pn : ndarray
  320. Value of derivative Y1(z1) for nth zero
  321. References
  322. ----------
  323. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  324. Functions", John Wiley and Sons, 1996, chapter 5.
  325. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  326. """
  327. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  328. raise ValueError("Arguments must be scalar positive integer.")
  329. kf = 2
  330. kc = not complex
  331. return specfun.cyzo(nt, kf, kc)
  332. def _bessel_diff_formula(v, z, n, L, phase):
  333. # from AMS55.
  334. # L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1
  335. # L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1
  336. # For K, you can pull out the exp((v-k)*pi*i) into the caller
  337. v = asarray(v)
  338. p = 1.0
  339. s = L(v-n, z)
  340. for i in xrange(1, n+1):
  341. p = phase * (p * (n-i+1)) / i # = choose(k, i)
  342. s += p*L(v-n + i*2, z)
  343. return s / (2.**n)
  344. bessel_diff_formula = np.deprecate(_bessel_diff_formula,
  345. message="bessel_diff_formula is a private function, do not use it!")
  346. def jvp(v, z, n=1):
  347. """Compute nth derivative of Bessel function Jv(z) with respect to `z`.
  348. Parameters
  349. ----------
  350. v : float
  351. Order of Bessel function
  352. z : complex
  353. Argument at which to evaluate the derivative
  354. n : int, default 1
  355. Order of derivative
  356. Notes
  357. -----
  358. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  359. References
  360. ----------
  361. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  362. Functions", John Wiley and Sons, 1996, chapter 5.
  363. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  364. .. [2] NIST Digital Library of Mathematical Functions.
  365. https://dlmf.nist.gov/10.6.E7
  366. """
  367. n = _nonneg_int_or_fail(n, 'n')
  368. if n == 0:
  369. return jv(v, z)
  370. else:
  371. return _bessel_diff_formula(v, z, n, jv, -1)
  372. def yvp(v, z, n=1):
  373. """Compute nth derivative of Bessel function Yv(z) with respect to `z`.
  374. Parameters
  375. ----------
  376. v : float
  377. Order of Bessel function
  378. z : complex
  379. Argument at which to evaluate the derivative
  380. n : int, default 1
  381. Order of derivative
  382. Notes
  383. -----
  384. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  385. References
  386. ----------
  387. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  388. Functions", John Wiley and Sons, 1996, chapter 5.
  389. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  390. .. [2] NIST Digital Library of Mathematical Functions.
  391. https://dlmf.nist.gov/10.6.E7
  392. """
  393. n = _nonneg_int_or_fail(n, 'n')
  394. if n == 0:
  395. return yv(v, z)
  396. else:
  397. return _bessel_diff_formula(v, z, n, yv, -1)
  398. def kvp(v, z, n=1):
  399. """Compute nth derivative of real-order modified Bessel function Kv(z)
  400. Kv(z) is the modified Bessel function of the second kind.
  401. Derivative is calculated with respect to `z`.
  402. Parameters
  403. ----------
  404. v : array_like of float
  405. Order of Bessel function
  406. z : array_like of complex
  407. Argument at which to evaluate the derivative
  408. n : int
  409. Order of derivative. Default is first derivative.
  410. Returns
  411. -------
  412. out : ndarray
  413. The results
  414. Examples
  415. --------
  416. Calculate multiple values at order 5:
  417. >>> from scipy.special import kvp
  418. >>> kvp(5, (1, 2, 3+5j))
  419. array([-1.84903536e+03+0.j , -2.57735387e+01+0.j ,
  420. -3.06627741e-02+0.08750845j])
  421. Calculate for a single value at multiple orders:
  422. >>> kvp((4, 4.5, 5), 1)
  423. array([ -184.0309, -568.9585, -1849.0354])
  424. Notes
  425. -----
  426. The derivative is computed using the relation DLFM 10.29.5 [2]_.
  427. References
  428. ----------
  429. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  430. Functions", John Wiley and Sons, 1996, chapter 6.
  431. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  432. .. [2] NIST Digital Library of Mathematical Functions.
  433. https://dlmf.nist.gov/10.29.E5
  434. """
  435. n = _nonneg_int_or_fail(n, 'n')
  436. if n == 0:
  437. return kv(v, z)
  438. else:
  439. return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1)
  440. def ivp(v, z, n=1):
  441. """Compute nth derivative of modified Bessel function Iv(z) with respect
  442. to `z`.
  443. Parameters
  444. ----------
  445. v : array_like of float
  446. Order of Bessel function
  447. z : array_like of complex
  448. Argument at which to evaluate the derivative
  449. n : int, default 1
  450. Order of derivative
  451. Notes
  452. -----
  453. The derivative is computed using the relation DLFM 10.29.5 [2]_.
  454. References
  455. ----------
  456. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  457. Functions", John Wiley and Sons, 1996, chapter 6.
  458. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  459. .. [2] NIST Digital Library of Mathematical Functions.
  460. https://dlmf.nist.gov/10.29.E5
  461. """
  462. n = _nonneg_int_or_fail(n, 'n')
  463. if n == 0:
  464. return iv(v, z)
  465. else:
  466. return _bessel_diff_formula(v, z, n, iv, 1)
  467. def h1vp(v, z, n=1):
  468. """Compute nth derivative of Hankel function H1v(z) with respect to `z`.
  469. Parameters
  470. ----------
  471. v : float
  472. Order of Hankel function
  473. z : complex
  474. Argument at which to evaluate the derivative
  475. n : int, default 1
  476. Order of derivative
  477. Notes
  478. -----
  479. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  480. References
  481. ----------
  482. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  483. Functions", John Wiley and Sons, 1996, chapter 5.
  484. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  485. .. [2] NIST Digital Library of Mathematical Functions.
  486. https://dlmf.nist.gov/10.6.E7
  487. """
  488. n = _nonneg_int_or_fail(n, 'n')
  489. if n == 0:
  490. return hankel1(v, z)
  491. else:
  492. return _bessel_diff_formula(v, z, n, hankel1, -1)
  493. def h2vp(v, z, n=1):
  494. """Compute nth derivative of Hankel function H2v(z) with respect to `z`.
  495. Parameters
  496. ----------
  497. v : float
  498. Order of Hankel function
  499. z : complex
  500. Argument at which to evaluate the derivative
  501. n : int, default 1
  502. Order of derivative
  503. Notes
  504. -----
  505. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  506. References
  507. ----------
  508. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  509. Functions", John Wiley and Sons, 1996, chapter 5.
  510. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  511. .. [2] NIST Digital Library of Mathematical Functions.
  512. https://dlmf.nist.gov/10.6.E7
  513. """
  514. n = _nonneg_int_or_fail(n, 'n')
  515. if n == 0:
  516. return hankel2(v, z)
  517. else:
  518. return _bessel_diff_formula(v, z, n, hankel2, -1)
  519. def riccati_jn(n, x):
  520. r"""Compute Ricatti-Bessel function of the first kind and its derivative.
  521. The Ricatti-Bessel function of the first kind is defined as :math:`x
  522. j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first
  523. kind of order :math:`n`.
  524. This function computes the value and first derivative of the
  525. Ricatti-Bessel function for all orders up to and including `n`.
  526. Parameters
  527. ----------
  528. n : int
  529. Maximum order of function to compute
  530. x : float
  531. Argument at which to evaluate
  532. Returns
  533. -------
  534. jn : ndarray
  535. Value of j0(x), ..., jn(x)
  536. jnp : ndarray
  537. First derivative j0'(x), ..., jn'(x)
  538. Notes
  539. -----
  540. The computation is carried out via backward recurrence, using the
  541. relation DLMF 10.51.1 [2]_.
  542. Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
  543. Jin [1]_.
  544. References
  545. ----------
  546. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  547. Functions", John Wiley and Sons, 1996.
  548. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  549. .. [2] NIST Digital Library of Mathematical Functions.
  550. https://dlmf.nist.gov/10.51.E1
  551. """
  552. if not (isscalar(n) and isscalar(x)):
  553. raise ValueError("arguments must be scalars.")
  554. n = _nonneg_int_or_fail(n, 'n', strict=False)
  555. if (n == 0):
  556. n1 = 1
  557. else:
  558. n1 = n
  559. nm, jn, jnp = specfun.rctj(n1, x)
  560. return jn[:(n+1)], jnp[:(n+1)]
  561. def riccati_yn(n, x):
  562. """Compute Ricatti-Bessel function of the second kind and its derivative.
  563. The Ricatti-Bessel function of the second kind is defined as :math:`x
  564. y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second
  565. kind of order :math:`n`.
  566. This function computes the value and first derivative of the function for
  567. all orders up to and including `n`.
  568. Parameters
  569. ----------
  570. n : int
  571. Maximum order of function to compute
  572. x : float
  573. Argument at which to evaluate
  574. Returns
  575. -------
  576. yn : ndarray
  577. Value of y0(x), ..., yn(x)
  578. ynp : ndarray
  579. First derivative y0'(x), ..., yn'(x)
  580. Notes
  581. -----
  582. The computation is carried out via ascending recurrence, using the
  583. relation DLMF 10.51.1 [2]_.
  584. Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
  585. Jin [1]_.
  586. References
  587. ----------
  588. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  589. Functions", John Wiley and Sons, 1996.
  590. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  591. .. [2] NIST Digital Library of Mathematical Functions.
  592. https://dlmf.nist.gov/10.51.E1
  593. """
  594. if not (isscalar(n) and isscalar(x)):
  595. raise ValueError("arguments must be scalars.")
  596. n = _nonneg_int_or_fail(n, 'n', strict=False)
  597. if (n == 0):
  598. n1 = 1
  599. else:
  600. n1 = n
  601. nm, jn, jnp = specfun.rcty(n1, x)
  602. return jn[:(n+1)], jnp[:(n+1)]
  603. def erfinv(y):
  604. """Inverse of the error function erf.
  605. Computes the inverse of the error function.
  606. In complex domain, there is no unique complex number w satisfying erf(w)=z.
  607. This indicates a true inverse function would have multi-value. When the domain restricts to the real, -1 < x < 1,
  608. there is a unique real number satisfying erf(erfinv(x)) = x.
  609. Parameters
  610. ----------
  611. y : ndarray
  612. Argument at which to evaluate. Domain: [-1, 1]
  613. Returns
  614. -------
  615. erfinv : ndarray
  616. The inverse of erf of y, element-wise
  617. Examples
  618. --------
  619. 1) evaluating a float number
  620. >>> from scipy import special
  621. >>> special.erfinv(0.5)
  622. 0.4769362762044698
  623. 2) evaluating a ndarray
  624. >>> from scipy import special
  625. >>> y = np.linspace(-1.0, 1.0, num=10)
  626. >>> special.erfinv(y)
  627. array([ -inf, -0.86312307, -0.5407314 , -0.30457019, -0.0987901 ,
  628. 0.0987901 , 0.30457019, 0.5407314 , 0.86312307, inf])
  629. """
  630. return ndtri((y+1)/2.0)/sqrt(2)
  631. def erfcinv(y):
  632. """Inverse of the complementary error function erfc.
  633. Computes the inverse of the complementary error function erfc.
  634. In complex domain, there is no unique complex number w satisfying erfc(w)=z.
  635. This indicates a true inverse function would have multi-value. When the domain restricts to the real, 0 < x < 2,
  636. there is a unique real number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).
  637. It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)
  638. Parameters
  639. ----------
  640. y : ndarray
  641. Argument at which to evaluate. Domain: [0, 2]
  642. Returns
  643. -------
  644. erfcinv : ndarray
  645. The inverse of erfc of y, element-wise
  646. Examples
  647. --------
  648. 1) evaluating a float number
  649. >>> from scipy import special
  650. >>> special.erfcinv(0.5)
  651. 0.4769362762044698
  652. 2) evaluating a ndarray
  653. >>> from scipy import special
  654. >>> y = np.linspace(0.0, 2.0, num=11)
  655. >>> special.erfcinv(y)
  656. array([ inf, 0.9061938 , 0.59511608, 0.37080716, 0.17914345,
  657. -0. , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,
  658. -inf])
  659. """
  660. return -ndtri(0.5*y)/sqrt(2)
  661. def erf_zeros(nt):
  662. """Compute the first nt zero in the first quadrant, ordered by absolute value.
  663. Zeros in the other quadrants can be obtained by using the symmetries erf(-z) = erf(z) and
  664. erf(conj(z)) = conj(erf(z)).
  665. Parameters
  666. ----------
  667. nt : int
  668. The number of zeros to compute
  669. Returns
  670. -------
  671. The locations of the zeros of erf : ndarray (complex)
  672. Complex values at which zeros of erf(z)
  673. Examples
  674. --------
  675. >>> from scipy import special
  676. >>> special.erf_zeros(1)
  677. array([1.45061616+1.880943j])
  678. Check that erf is (close to) zero for the value returned by erf_zeros
  679. >>> special.erf(special.erf_zeros(1))
  680. array([4.95159469e-14-1.16407394e-16j])
  681. References
  682. ----------
  683. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  684. Functions", John Wiley and Sons, 1996.
  685. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  686. """
  687. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  688. raise ValueError("Argument must be positive scalar integer.")
  689. return specfun.cerzo(nt)
  690. def fresnelc_zeros(nt):
  691. """Compute nt complex zeros of cosine Fresnel integral C(z).
  692. References
  693. ----------
  694. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  695. Functions", John Wiley and Sons, 1996.
  696. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  697. """
  698. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  699. raise ValueError("Argument must be positive scalar integer.")
  700. return specfun.fcszo(1, nt)
  701. def fresnels_zeros(nt):
  702. """Compute nt complex zeros of sine Fresnel integral S(z).
  703. References
  704. ----------
  705. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  706. Functions", John Wiley and Sons, 1996.
  707. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  708. """
  709. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  710. raise ValueError("Argument must be positive scalar integer.")
  711. return specfun.fcszo(2, nt)
  712. def fresnel_zeros(nt):
  713. """Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
  714. References
  715. ----------
  716. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  717. Functions", John Wiley and Sons, 1996.
  718. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  719. """
  720. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  721. raise ValueError("Argument must be positive scalar integer.")
  722. return specfun.fcszo(2, nt), specfun.fcszo(1, nt)
  723. def assoc_laguerre(x, n, k=0.0):
  724. """Compute the generalized (associated) Laguerre polynomial of degree n and order k.
  725. The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``,
  726. with weighting function ``exp(-x) * x**k`` with ``k > -1``.
  727. Notes
  728. -----
  729. `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with
  730. reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
  731. """
  732. return orthogonal.eval_genlaguerre(n, k, x)
  733. digamma = psi
  734. def polygamma(n, x):
  735. """Polygamma function n.
  736. This is the nth derivative of the digamma (psi) function.
  737. Parameters
  738. ----------
  739. n : array_like of int
  740. The order of the derivative of `psi`.
  741. x : array_like
  742. Where to evaluate the polygamma function.
  743. Returns
  744. -------
  745. polygamma : ndarray
  746. The result.
  747. Examples
  748. --------
  749. >>> from scipy import special
  750. >>> x = [2, 3, 25.5]
  751. >>> special.polygamma(1, x)
  752. array([ 0.64493407, 0.39493407, 0.03999467])
  753. >>> special.polygamma(0, x) == special.psi(x)
  754. array([ True, True, True], dtype=bool)
  755. """
  756. n, x = asarray(n), asarray(x)
  757. fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x)
  758. return where(n == 0, psi(x), fac2)
  759. def mathieu_even_coef(m, q):
  760. r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
  761. The Fourier series of the even solutions of the Mathieu differential
  762. equation are of the form
  763. .. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz
  764. .. math:: \mathrm{ce}_{2n+1}(z, q) = \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z
  765. This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even
  766. input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input
  767. m=2n+1.
  768. Parameters
  769. ----------
  770. m : int
  771. Order of Mathieu functions. Must be non-negative.
  772. q : float (>=0)
  773. Parameter of Mathieu functions. Must be non-negative.
  774. Returns
  775. -------
  776. Ak : ndarray
  777. Even or odd Fourier coefficients, corresponding to even or odd m.
  778. References
  779. ----------
  780. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  781. Functions", John Wiley and Sons, 1996.
  782. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  783. .. [2] NIST Digital Library of Mathematical Functions
  784. https://dlmf.nist.gov/28.4#i
  785. """
  786. if not (isscalar(m) and isscalar(q)):
  787. raise ValueError("m and q must be scalars.")
  788. if (q < 0):
  789. raise ValueError("q >=0")
  790. if (m != floor(m)) or (m < 0):
  791. raise ValueError("m must be an integer >=0.")
  792. if (q <= 1):
  793. qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
  794. else:
  795. qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
  796. km = int(qm + 0.5*m)
  797. if km > 251:
  798. print("Warning, too many predicted coefficients.")
  799. kd = 1
  800. m = int(floor(m))
  801. if m % 2:
  802. kd = 2
  803. a = mathieu_a(m, q)
  804. fc = specfun.fcoef(kd, m, q, a)
  805. return fc[:km]
  806. def mathieu_odd_coef(m, q):
  807. r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
  808. The Fourier series of the odd solutions of the Mathieu differential
  809. equation are of the form
  810. .. math:: \mathrm{se}_{2n+1}(z, q) = \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
  811. .. math:: \mathrm{se}_{2n+2}(z, q) = \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
  812. This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
  813. input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
  814. input m=2n+1.
  815. Parameters
  816. ----------
  817. m : int
  818. Order of Mathieu functions. Must be non-negative.
  819. q : float (>=0)
  820. Parameter of Mathieu functions. Must be non-negative.
  821. Returns
  822. -------
  823. Bk : ndarray
  824. Even or odd Fourier coefficients, corresponding to even or odd m.
  825. References
  826. ----------
  827. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  828. Functions", John Wiley and Sons, 1996.
  829. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  830. """
  831. if not (isscalar(m) and isscalar(q)):
  832. raise ValueError("m and q must be scalars.")
  833. if (q < 0):
  834. raise ValueError("q >=0")
  835. if (m != floor(m)) or (m <= 0):
  836. raise ValueError("m must be an integer > 0")
  837. if (q <= 1):
  838. qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
  839. else:
  840. qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
  841. km = int(qm + 0.5*m)
  842. if km > 251:
  843. print("Warning, too many predicted coefficients.")
  844. kd = 4
  845. m = int(floor(m))
  846. if m % 2:
  847. kd = 3
  848. b = mathieu_b(m, q)
  849. fc = specfun.fcoef(kd, m, q, b)
  850. return fc[:km]
  851. def lpmn(m, n, z):
  852. """Sequence of associated Legendre functions of the first kind.
  853. Computes the associated Legendre function of the first kind of order m and
  854. degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
  855. Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
  856. ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
  857. This function takes a real argument ``z``. For complex arguments ``z``
  858. use clpmn instead.
  859. Parameters
  860. ----------
  861. m : int
  862. ``|m| <= n``; the order of the Legendre function.
  863. n : int
  864. where ``n >= 0``; the degree of the Legendre function. Often
  865. called ``l`` (lower case L) in descriptions of the associated
  866. Legendre function
  867. z : float
  868. Input value.
  869. Returns
  870. -------
  871. Pmn_z : (m+1, n+1) array
  872. Values for all orders 0..m and degrees 0..n
  873. Pmn_d_z : (m+1, n+1) array
  874. Derivatives for all orders 0..m and degrees 0..n
  875. See Also
  876. --------
  877. clpmn: associated Legendre functions of the first kind for complex z
  878. Notes
  879. -----
  880. In the interval (-1, 1), Ferrer's function of the first kind is
  881. returned. The phase convention used for the intervals (1, inf)
  882. and (-inf, -1) is such that the result is always real.
  883. References
  884. ----------
  885. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  886. Functions", John Wiley and Sons, 1996.
  887. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  888. .. [2] NIST Digital Library of Mathematical Functions
  889. https://dlmf.nist.gov/14.3
  890. """
  891. if not isscalar(m) or (abs(m) > n):
  892. raise ValueError("m must be <= n.")
  893. if not isscalar(n) or (n < 0):
  894. raise ValueError("n must be a non-negative integer.")
  895. if not isscalar(z):
  896. raise ValueError("z must be scalar.")
  897. if iscomplex(z):
  898. raise ValueError("Argument must be real. Use clpmn instead.")
  899. if (m < 0):
  900. mp = -m
  901. mf, nf = mgrid[0:mp+1, 0:n+1]
  902. with ufuncs.errstate(all='ignore'):
  903. if abs(z) < 1:
  904. # Ferrer function; DLMF 14.9.3
  905. fixarr = where(mf > nf, 0.0,
  906. (-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
  907. else:
  908. # Match to clpmn; DLMF 14.9.13
  909. fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
  910. else:
  911. mp = m
  912. p, pd = specfun.lpmn(mp, n, z)
  913. if (m < 0):
  914. p = p * fixarr
  915. pd = pd * fixarr
  916. return p, pd
  917. def clpmn(m, n, z, type=3):
  918. """Associated Legendre function of the first kind for complex arguments.
  919. Computes the associated Legendre function of the first kind of order m and
  920. degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
  921. Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
  922. ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
  923. Parameters
  924. ----------
  925. m : int
  926. ``|m| <= n``; the order of the Legendre function.
  927. n : int
  928. where ``n >= 0``; the degree of the Legendre function. Often
  929. called ``l`` (lower case L) in descriptions of the associated
  930. Legendre function
  931. z : float or complex
  932. Input value.
  933. type : int, optional
  934. takes values 2 or 3
  935. 2: cut on the real axis ``|x| > 1``
  936. 3: cut on the real axis ``-1 < x < 1`` (default)
  937. Returns
  938. -------
  939. Pmn_z : (m+1, n+1) array
  940. Values for all orders ``0..m`` and degrees ``0..n``
  941. Pmn_d_z : (m+1, n+1) array
  942. Derivatives for all orders ``0..m`` and degrees ``0..n``
  943. See Also
  944. --------
  945. lpmn: associated Legendre functions of the first kind for real z
  946. Notes
  947. -----
  948. By default, i.e. for ``type=3``, phase conventions are chosen according
  949. to [1]_ such that the function is analytic. The cut lies on the interval
  950. (-1, 1). Approaching the cut from above or below in general yields a phase
  951. factor with respect to Ferrer's function of the first kind
  952. (cf. `lpmn`).
  953. For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values
  954. on the interval (-1, 1) in the complex plane yields Ferrer's function
  955. of the first kind.
  956. References
  957. ----------
  958. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  959. Functions", John Wiley and Sons, 1996.
  960. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  961. .. [2] NIST Digital Library of Mathematical Functions
  962. https://dlmf.nist.gov/14.21
  963. """
  964. if not isscalar(m) or (abs(m) > n):
  965. raise ValueError("m must be <= n.")
  966. if not isscalar(n) or (n < 0):
  967. raise ValueError("n must be a non-negative integer.")
  968. if not isscalar(z):
  969. raise ValueError("z must be scalar.")
  970. if not(type == 2 or type == 3):
  971. raise ValueError("type must be either 2 or 3.")
  972. if (m < 0):
  973. mp = -m
  974. mf, nf = mgrid[0:mp+1, 0:n+1]
  975. with ufuncs.errstate(all='ignore'):
  976. if type == 2:
  977. fixarr = where(mf > nf, 0.0,
  978. (-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
  979. else:
  980. fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
  981. else:
  982. mp = m
  983. p, pd = specfun.clpmn(mp, n, real(z), imag(z), type)
  984. if (m < 0):
  985. p = p * fixarr
  986. pd = pd * fixarr
  987. return p, pd
  988. def lqmn(m, n, z):
  989. """Sequence of associated Legendre functions of the second kind.
  990. Computes the associated Legendre function of the second kind of order m and
  991. degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
  992. Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
  993. ``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
  994. Parameters
  995. ----------
  996. m : int
  997. ``|m| <= n``; the order of the Legendre function.
  998. n : int
  999. where ``n >= 0``; the degree of the Legendre function. Often
  1000. called ``l`` (lower case L) in descriptions of the associated
  1001. Legendre function
  1002. z : complex
  1003. Input value.
  1004. Returns
  1005. -------
  1006. Qmn_z : (m+1, n+1) array
  1007. Values for all orders 0..m and degrees 0..n
  1008. Qmn_d_z : (m+1, n+1) array
  1009. Derivatives for all orders 0..m and degrees 0..n
  1010. References
  1011. ----------
  1012. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1013. Functions", John Wiley and Sons, 1996.
  1014. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1015. """
  1016. if not isscalar(m) or (m < 0):
  1017. raise ValueError("m must be a non-negative integer.")
  1018. if not isscalar(n) or (n < 0):
  1019. raise ValueError("n must be a non-negative integer.")
  1020. if not isscalar(z):
  1021. raise ValueError("z must be scalar.")
  1022. m = int(m)
  1023. n = int(n)
  1024. # Ensure neither m nor n == 0
  1025. mm = max(1, m)
  1026. nn = max(1, n)
  1027. if iscomplex(z):
  1028. q, qd = specfun.clqmn(mm, nn, z)
  1029. else:
  1030. q, qd = specfun.lqmn(mm, nn, z)
  1031. return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)]
  1032. def bernoulli(n):
  1033. """Bernoulli numbers B0..Bn (inclusive).
  1034. References
  1035. ----------
  1036. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1037. Functions", John Wiley and Sons, 1996.
  1038. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1039. """
  1040. if not isscalar(n) or (n < 0):
  1041. raise ValueError("n must be a non-negative integer.")
  1042. n = int(n)
  1043. if (n < 2):
  1044. n1 = 2
  1045. else:
  1046. n1 = n
  1047. return specfun.bernob(int(n1))[:(n+1)]
  1048. def euler(n):
  1049. """Euler numbers E(0), E(1), ..., E(n).
  1050. The Euler numbers [1]_ are also known as the secant numbers.
  1051. Because ``euler(n)`` returns floating point values, it does not give
  1052. exact values for large `n`. The first inexact value is E(22).
  1053. Parameters
  1054. ----------
  1055. n : int
  1056. The highest index of the Euler number to be returned.
  1057. Returns
  1058. -------
  1059. ndarray
  1060. The Euler numbers [E(0), E(1), ..., E(n)].
  1061. The odd Euler numbers, which are all zero, are included.
  1062. References
  1063. ----------
  1064. .. [1] Sequence A122045, The On-Line Encyclopedia of Integer Sequences,
  1065. https://oeis.org/A122045
  1066. .. [2] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1067. Functions", John Wiley and Sons, 1996.
  1068. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1069. Examples
  1070. --------
  1071. >>> from scipy.special import euler
  1072. >>> euler(6)
  1073. array([ 1., 0., -1., 0., 5., 0., -61.])
  1074. >>> euler(13).astype(np.int64)
  1075. array([ 1, 0, -1, 0, 5, 0, -61,
  1076. 0, 1385, 0, -50521, 0, 2702765, 0])
  1077. >>> euler(22)[-1] # Exact value of E(22) is -69348874393137901.
  1078. -69348874393137976.0
  1079. """
  1080. if not isscalar(n) or (n < 0):
  1081. raise ValueError("n must be a non-negative integer.")
  1082. n = int(n)
  1083. if (n < 2):
  1084. n1 = 2
  1085. else:
  1086. n1 = n
  1087. return specfun.eulerb(n1)[:(n+1)]
  1088. def lpn(n, z):
  1089. """Legendre function of the first kind.
  1090. Compute sequence of Legendre functions of the first kind (polynomials),
  1091. Pn(z) and derivatives for all degrees from 0 to n (inclusive).
  1092. See also special.legendre for polynomial class.
  1093. References
  1094. ----------
  1095. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1096. Functions", John Wiley and Sons, 1996.
  1097. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1098. """
  1099. if not (isscalar(n) and isscalar(z)):
  1100. raise ValueError("arguments must be scalars.")
  1101. n = _nonneg_int_or_fail(n, 'n', strict=False)
  1102. if (n < 1):
  1103. n1 = 1
  1104. else:
  1105. n1 = n
  1106. if iscomplex(z):
  1107. pn, pd = specfun.clpn(n1, z)
  1108. else:
  1109. pn, pd = specfun.lpn(n1, z)
  1110. return pn[:(n+1)], pd[:(n+1)]
  1111. def lqn(n, z):
  1112. """Legendre function of the second kind.
  1113. Compute sequence of Legendre functions of the second kind, Qn(z) and
  1114. derivatives for all degrees from 0 to n (inclusive).
  1115. References
  1116. ----------
  1117. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1118. Functions", John Wiley and Sons, 1996.
  1119. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1120. """
  1121. if not (isscalar(n) and isscalar(z)):
  1122. raise ValueError("arguments must be scalars.")
  1123. n = _nonneg_int_or_fail(n, 'n', strict=False)
  1124. if (n < 1):
  1125. n1 = 1
  1126. else:
  1127. n1 = n
  1128. if iscomplex(z):
  1129. qn, qd = specfun.clqn(n1, z)
  1130. else:
  1131. qn, qd = specfun.lqnb(n1, z)
  1132. return qn[:(n+1)], qd[:(n+1)]
  1133. def ai_zeros(nt):
  1134. """
  1135. Compute `nt` zeros and values of the Airy function Ai and its derivative.
  1136. Computes the first `nt` zeros, `a`, of the Airy function Ai(x);
  1137. first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x);
  1138. the corresponding values Ai(a');
  1139. and the corresponding values Ai'(a).
  1140. Parameters
  1141. ----------
  1142. nt : int
  1143. Number of zeros to compute
  1144. Returns
  1145. -------
  1146. a : ndarray
  1147. First `nt` zeros of Ai(x)
  1148. ap : ndarray
  1149. First `nt` zeros of Ai'(x)
  1150. ai : ndarray
  1151. Values of Ai(x) evaluated at first `nt` zeros of Ai'(x)
  1152. aip : ndarray
  1153. Values of Ai'(x) evaluated at first `nt` zeros of Ai(x)
  1154. References
  1155. ----------
  1156. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1157. Functions", John Wiley and Sons, 1996.
  1158. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1159. """
  1160. kf = 1
  1161. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1162. raise ValueError("nt must be a positive integer scalar.")
  1163. return specfun.airyzo(nt, kf)
  1164. def bi_zeros(nt):
  1165. """
  1166. Compute `nt` zeros and values of the Airy function Bi and its derivative.
  1167. Computes the first `nt` zeros, b, of the Airy function Bi(x);
  1168. first `nt` zeros, b', of the derivative of the Airy function Bi'(x);
  1169. the corresponding values Bi(b');
  1170. and the corresponding values Bi'(b).
  1171. Parameters
  1172. ----------
  1173. nt : int
  1174. Number of zeros to compute
  1175. Returns
  1176. -------
  1177. b : ndarray
  1178. First `nt` zeros of Bi(x)
  1179. bp : ndarray
  1180. First `nt` zeros of Bi'(x)
  1181. bi : ndarray
  1182. Values of Bi(x) evaluated at first `nt` zeros of Bi'(x)
  1183. bip : ndarray
  1184. Values of Bi'(x) evaluated at first `nt` zeros of Bi(x)
  1185. References
  1186. ----------
  1187. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1188. Functions", John Wiley and Sons, 1996.
  1189. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1190. """
  1191. kf = 2
  1192. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1193. raise ValueError("nt must be a positive integer scalar.")
  1194. return specfun.airyzo(nt, kf)
  1195. def lmbda(v, x):
  1196. r"""Jahnke-Emden Lambda function, Lambdav(x).
  1197. This function is defined as [2]_,
  1198. .. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v},
  1199. where :math:`\Gamma` is the gamma function and :math:`J_v` is the
  1200. Bessel function of the first kind.
  1201. Parameters
  1202. ----------
  1203. v : float
  1204. Order of the Lambda function
  1205. x : float
  1206. Value at which to evaluate the function and derivatives
  1207. Returns
  1208. -------
  1209. vl : ndarray
  1210. Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1211. dl : ndarray
  1212. Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1213. References
  1214. ----------
  1215. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1216. Functions", John Wiley and Sons, 1996.
  1217. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1218. .. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and
  1219. Curves" (4th ed.), Dover, 1945
  1220. """
  1221. if not (isscalar(v) and isscalar(x)):
  1222. raise ValueError("arguments must be scalars.")
  1223. if (v < 0):
  1224. raise ValueError("argument must be > 0.")
  1225. n = int(v)
  1226. v0 = v - n
  1227. if (n < 1):
  1228. n1 = 1
  1229. else:
  1230. n1 = n
  1231. v1 = n1 + v0
  1232. if (v != floor(v)):
  1233. vm, vl, dl = specfun.lamv(v1, x)
  1234. else:
  1235. vm, vl, dl = specfun.lamn(v1, x)
  1236. return vl[:(n+1)], dl[:(n+1)]
  1237. def pbdv_seq(v, x):
  1238. """Parabolic cylinder functions Dv(x) and derivatives.
  1239. Parameters
  1240. ----------
  1241. v : float
  1242. Order of the parabolic cylinder function
  1243. x : float
  1244. Value at which to evaluate the function and derivatives
  1245. Returns
  1246. -------
  1247. dv : ndarray
  1248. Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1249. dp : ndarray
  1250. Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1251. References
  1252. ----------
  1253. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1254. Functions", John Wiley and Sons, 1996, chapter 13.
  1255. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1256. """
  1257. if not (isscalar(v) and isscalar(x)):
  1258. raise ValueError("arguments must be scalars.")
  1259. n = int(v)
  1260. v0 = v-n
  1261. if (n < 1):
  1262. n1 = 1
  1263. else:
  1264. n1 = n
  1265. v1 = n1 + v0
  1266. dv, dp, pdf, pdd = specfun.pbdv(v1, x)
  1267. return dv[:n1+1], dp[:n1+1]
  1268. def pbvv_seq(v, x):
  1269. """Parabolic cylinder functions Vv(x) and derivatives.
  1270. Parameters
  1271. ----------
  1272. v : float
  1273. Order of the parabolic cylinder function
  1274. x : float
  1275. Value at which to evaluate the function and derivatives
  1276. Returns
  1277. -------
  1278. dv : ndarray
  1279. Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1280. dp : ndarray
  1281. Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1282. References
  1283. ----------
  1284. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1285. Functions", John Wiley and Sons, 1996, chapter 13.
  1286. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1287. """
  1288. if not (isscalar(v) and isscalar(x)):
  1289. raise ValueError("arguments must be scalars.")
  1290. n = int(v)
  1291. v0 = v-n
  1292. if (n <= 1):
  1293. n1 = 1
  1294. else:
  1295. n1 = n
  1296. v1 = n1 + v0
  1297. dv, dp, pdf, pdd = specfun.pbvv(v1, x)
  1298. return dv[:n1+1], dp[:n1+1]
  1299. def pbdn_seq(n, z):
  1300. """Parabolic cylinder functions Dn(z) and derivatives.
  1301. Parameters
  1302. ----------
  1303. n : int
  1304. Order of the parabolic cylinder function
  1305. z : complex
  1306. Value at which to evaluate the function and derivatives
  1307. Returns
  1308. -------
  1309. dv : ndarray
  1310. Values of D_i(z), for i=0, ..., i=n.
  1311. dp : ndarray
  1312. Derivatives D_i'(z), for i=0, ..., i=n.
  1313. References
  1314. ----------
  1315. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1316. Functions", John Wiley and Sons, 1996, chapter 13.
  1317. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1318. """
  1319. if not (isscalar(n) and isscalar(z)):
  1320. raise ValueError("arguments must be scalars.")
  1321. if (floor(n) != n):
  1322. raise ValueError("n must be an integer.")
  1323. if (abs(n) <= 1):
  1324. n1 = 1
  1325. else:
  1326. n1 = n
  1327. cpb, cpd = specfun.cpbdn(n1, z)
  1328. return cpb[:n1+1], cpd[:n1+1]
  1329. def ber_zeros(nt):
  1330. """Compute nt zeros of the Kelvin function ber(x).
  1331. References
  1332. ----------
  1333. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1334. Functions", John Wiley and Sons, 1996.
  1335. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1336. """
  1337. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1338. raise ValueError("nt must be positive integer scalar.")
  1339. return specfun.klvnzo(nt, 1)
  1340. def bei_zeros(nt):
  1341. """Compute nt zeros of the Kelvin function bei(x).
  1342. References
  1343. ----------
  1344. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1345. Functions", John Wiley and Sons, 1996.
  1346. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1347. """
  1348. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1349. raise ValueError("nt must be positive integer scalar.")
  1350. return specfun.klvnzo(nt, 2)
  1351. def ker_zeros(nt):
  1352. """Compute nt zeros of the Kelvin function ker(x).
  1353. References
  1354. ----------
  1355. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1356. Functions", John Wiley and Sons, 1996.
  1357. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1358. """
  1359. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1360. raise ValueError("nt must be positive integer scalar.")
  1361. return specfun.klvnzo(nt, 3)
  1362. def kei_zeros(nt):
  1363. """Compute nt zeros of the Kelvin function kei(x).
  1364. """
  1365. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1366. raise ValueError("nt must be positive integer scalar.")
  1367. return specfun.klvnzo(nt, 4)
  1368. def berp_zeros(nt):
  1369. """Compute nt zeros of the Kelvin function ber'(x).
  1370. References
  1371. ----------
  1372. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1373. Functions", John Wiley and Sons, 1996.
  1374. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1375. """
  1376. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1377. raise ValueError("nt must be positive integer scalar.")
  1378. return specfun.klvnzo(nt, 5)
  1379. def beip_zeros(nt):
  1380. """Compute nt zeros of the Kelvin function bei'(x).
  1381. References
  1382. ----------
  1383. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1384. Functions", John Wiley and Sons, 1996.
  1385. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1386. """
  1387. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1388. raise ValueError("nt must be positive integer scalar.")
  1389. return specfun.klvnzo(nt, 6)
  1390. def kerp_zeros(nt):
  1391. """Compute nt zeros of the Kelvin function ker'(x).
  1392. References
  1393. ----------
  1394. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1395. Functions", John Wiley and Sons, 1996.
  1396. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1397. """
  1398. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1399. raise ValueError("nt must be positive integer scalar.")
  1400. return specfun.klvnzo(nt, 7)
  1401. def keip_zeros(nt):
  1402. """Compute nt zeros of the Kelvin function kei'(x).
  1403. References
  1404. ----------
  1405. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1406. Functions", John Wiley and Sons, 1996.
  1407. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1408. """
  1409. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1410. raise ValueError("nt must be positive integer scalar.")
  1411. return specfun.klvnzo(nt, 8)
  1412. def kelvin_zeros(nt):
  1413. """Compute nt zeros of all Kelvin functions.
  1414. Returned in a length-8 tuple of arrays of length nt. The tuple contains
  1415. the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei').
  1416. References
  1417. ----------
  1418. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1419. Functions", John Wiley and Sons, 1996.
  1420. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1421. """
  1422. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1423. raise ValueError("nt must be positive integer scalar.")
  1424. return (specfun.klvnzo(nt, 1),
  1425. specfun.klvnzo(nt, 2),
  1426. specfun.klvnzo(nt, 3),
  1427. specfun.klvnzo(nt, 4),
  1428. specfun.klvnzo(nt, 5),
  1429. specfun.klvnzo(nt, 6),
  1430. specfun.klvnzo(nt, 7),
  1431. specfun.klvnzo(nt, 8))
  1432. def pro_cv_seq(m, n, c):
  1433. """Characteristic values for prolate spheroidal wave functions.
  1434. Compute a sequence of characteristic values for the prolate
  1435. spheroidal wave functions for mode m and n'=m..n and spheroidal
  1436. parameter c.
  1437. References
  1438. ----------
  1439. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1440. Functions", John Wiley and Sons, 1996.
  1441. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1442. """
  1443. if not (isscalar(m) and isscalar(n) and isscalar(c)):
  1444. raise ValueError("Arguments must be scalars.")
  1445. if (n != floor(n)) or (m != floor(m)):
  1446. raise ValueError("Modes must be integers.")
  1447. if (n-m > 199):
  1448. raise ValueError("Difference between n and m is too large.")
  1449. maxL = n-m+1
  1450. return specfun.segv(m, n, c, 1)[1][:maxL]
  1451. def obl_cv_seq(m, n, c):
  1452. """Characteristic values for oblate spheroidal wave functions.
  1453. Compute a sequence of characteristic values for the oblate
  1454. spheroidal wave functions for mode m and n'=m..n and spheroidal
  1455. parameter c.
  1456. References
  1457. ----------
  1458. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1459. Functions", John Wiley and Sons, 1996.
  1460. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
  1461. """
  1462. if not (isscalar(m) and isscalar(n) and isscalar(c)):
  1463. raise ValueError("Arguments must be scalars.")
  1464. if (n != floor(n)) or (m != floor(m)):
  1465. raise ValueError("Modes must be integers.")
  1466. if (n-m > 199):
  1467. raise ValueError("Difference between n and m is too large.")
  1468. maxL = n-m+1
  1469. return specfun.segv(m, n, c, -1)[1][:maxL]
  1470. def ellipk(m):
  1471. r"""Complete elliptic integral of the first kind.
  1472. This function is defined as
  1473. .. math:: K(m) = \int_0^{\pi/2} [1 - m \sin(t)^2]^{-1/2} dt
  1474. Parameters
  1475. ----------
  1476. m : array_like
  1477. The parameter of the elliptic integral.
  1478. Returns
  1479. -------
  1480. K : array_like
  1481. Value of the elliptic integral.
  1482. Notes
  1483. -----
  1484. For more precision around point m = 1, use `ellipkm1`, which this
  1485. function calls.
  1486. The parameterization in terms of :math:`m` follows that of section
  1487. 17.2 in [1]_. Other parameterizations in terms of the
  1488. complementary parameter :math:`1 - m`, modular angle
  1489. :math:`\sin^2(\alpha) = m`, or modulus :math:`k^2 = m` are also
  1490. used, so be careful that you choose the correct parameter.
  1491. See Also
  1492. --------
  1493. ellipkm1 : Complete elliptic integral of the first kind around m = 1
  1494. ellipkinc : Incomplete elliptic integral of the first kind
  1495. ellipe : Complete elliptic integral of the second kind
  1496. ellipeinc : Incomplete elliptic integral of the second kind
  1497. References
  1498. ----------
  1499. .. [1] Milton Abramowitz and Irene A. Stegun, eds.
  1500. Handbook of Mathematical Functions with Formulas,
  1501. Graphs, and Mathematical Tables. New York: Dover, 1972.
  1502. """
  1503. return ellipkm1(1 - asarray(m))
  1504. def comb(N, k, exact=False, repetition=False):
  1505. """The number of combinations of N things taken k at a time.
  1506. This is often expressed as "N choose k".
  1507. Parameters
  1508. ----------
  1509. N : int, ndarray
  1510. Number of things.
  1511. k : int, ndarray
  1512. Number of elements taken.
  1513. exact : bool, optional
  1514. If `exact` is False, then floating point precision is used, otherwise
  1515. exact long integer is computed.
  1516. repetition : bool, optional
  1517. If `repetition` is True, then the number of combinations with
  1518. repetition is computed.
  1519. Returns
  1520. -------
  1521. val : int, float, ndarray
  1522. The total number of combinations.
  1523. See Also
  1524. --------
  1525. binom : Binomial coefficient ufunc
  1526. Notes
  1527. -----
  1528. - Array arguments accepted only for exact=False case.
  1529. - If k > N, N < 0, or k < 0, then a 0 is returned.
  1530. Examples
  1531. --------
  1532. >>> from scipy.special import comb
  1533. >>> k = np.array([3, 4])
  1534. >>> n = np.array([10, 10])
  1535. >>> comb(n, k, exact=False)
  1536. array([ 120., 210.])
  1537. >>> comb(10, 3, exact=True)
  1538. 120L
  1539. >>> comb(10, 3, exact=True, repetition=True)
  1540. 220L
  1541. """
  1542. if repetition:
  1543. return comb(N + k - 1, k, exact)
  1544. if exact:
  1545. return _comb_int(N, k)
  1546. else:
  1547. k, N = asarray(k), asarray(N)
  1548. cond = (k <= N) & (N >= 0) & (k >= 0)
  1549. vals = binom(N, k)
  1550. if isinstance(vals, np.ndarray):
  1551. vals[~cond] = 0
  1552. elif not cond:
  1553. vals = np.float64(0)
  1554. return vals
  1555. def perm(N, k, exact=False):
  1556. """Permutations of N things taken k at a time, i.e., k-permutations of N.
  1557. It's also known as "partial permutations".
  1558. Parameters
  1559. ----------
  1560. N : int, ndarray
  1561. Number of things.
  1562. k : int, ndarray
  1563. Number of elements taken.
  1564. exact : bool, optional
  1565. If `exact` is False, then floating point precision is used, otherwise
  1566. exact long integer is computed.
  1567. Returns
  1568. -------
  1569. val : int, ndarray
  1570. The number of k-permutations of N.
  1571. Notes
  1572. -----
  1573. - Array arguments accepted only for exact=False case.
  1574. - If k > N, N < 0, or k < 0, then a 0 is returned.
  1575. Examples
  1576. --------
  1577. >>> from scipy.special import perm
  1578. >>> k = np.array([3, 4])
  1579. >>> n = np.array([10, 10])
  1580. >>> perm(n, k)
  1581. array([ 720., 5040.])
  1582. >>> perm(10, 3, exact=True)
  1583. 720
  1584. """
  1585. if exact:
  1586. if (k > N) or (N < 0) or (k < 0):
  1587. return 0
  1588. val = 1
  1589. for i in xrange(N - k + 1, N + 1):
  1590. val *= i
  1591. return val
  1592. else:
  1593. k, N = asarray(k), asarray(N)
  1594. cond = (k <= N) & (N >= 0) & (k >= 0)
  1595. vals = poch(N - k + 1, k)
  1596. if isinstance(vals, np.ndarray):
  1597. vals[~cond] = 0
  1598. elif not cond:
  1599. vals = np.float64(0)
  1600. return vals
  1601. # https://stackoverflow.com/a/16327037
  1602. def _range_prod(lo, hi):
  1603. """
  1604. Product of a range of numbers.
  1605. Returns the product of
  1606. lo * (lo+1) * (lo+2) * ... * (hi-2) * (hi-1) * hi
  1607. = hi! / (lo-1)!
  1608. Breaks into smaller products first for speed:
  1609. _range_prod(2, 9) = ((2*3)*(4*5))*((6*7)*(8*9))
  1610. """
  1611. if lo + 1 < hi:
  1612. mid = (hi + lo) // 2
  1613. return _range_prod(lo, mid) * _range_prod(mid + 1, hi)
  1614. if lo == hi:
  1615. return lo
  1616. return lo * hi
  1617. def factorial(n, exact=False):
  1618. """
  1619. The factorial of a number or array of numbers.
  1620. The factorial of non-negative integer `n` is the product of all
  1621. positive integers less than or equal to `n`::
  1622. n! = n * (n - 1) * (n - 2) * ... * 1
  1623. Parameters
  1624. ----------
  1625. n : int or array_like of ints
  1626. Input values. If ``n < 0``, the return value is 0.
  1627. exact : bool, optional
  1628. If True, calculate the answer exactly using long integer arithmetic.
  1629. If False, result is approximated in floating point rapidly using the
  1630. `gamma` function.
  1631. Default is False.
  1632. Returns
  1633. -------
  1634. nf : float or int or ndarray
  1635. Factorial of `n`, as integer or float depending on `exact`.
  1636. Notes
  1637. -----
  1638. For arrays with ``exact=True``, the factorial is computed only once, for
  1639. the largest input, with each other result computed in the process.
  1640. The output dtype is increased to ``int64`` or ``object`` if necessary.
  1641. With ``exact=False`` the factorial is approximated using the gamma
  1642. function:
  1643. .. math:: n! = \\Gamma(n+1)
  1644. Examples
  1645. --------
  1646. >>> from scipy.special import factorial
  1647. >>> arr = np.array([3, 4, 5])
  1648. >>> factorial(arr, exact=False)
  1649. array([ 6., 24., 120.])
  1650. >>> factorial(arr, exact=True)
  1651. array([ 6, 24, 120])
  1652. >>> factorial(5, exact=True)
  1653. 120L
  1654. """
  1655. if exact:
  1656. if np.ndim(n) == 0:
  1657. return 0 if n < 0 else math.factorial(n)
  1658. else:
  1659. n = asarray(n)
  1660. un = np.unique(n).astype(object)
  1661. # Convert to object array of long ints if np.int can't handle size
  1662. if un[-1] > 20:
  1663. dt = object
  1664. elif un[-1] > 12:
  1665. dt = np.int64
  1666. else:
  1667. dt = np.int
  1668. out = np.empty_like(n, dtype=dt)
  1669. # Handle invalid/trivial values
  1670. un = un[un > 1]
  1671. out[n < 2] = 1
  1672. out[n < 0] = 0
  1673. # Calculate products of each range of numbers
  1674. if un.size:
  1675. val = math.factorial(un[0])
  1676. out[n == un[0]] = val
  1677. for i in xrange(len(un) - 1):
  1678. prev = un[i] + 1
  1679. current = un[i + 1]
  1680. val *= _range_prod(prev, current)
  1681. out[n == current] = val
  1682. return out
  1683. else:
  1684. n = asarray(n)
  1685. vals = gamma(n + 1)
  1686. return where(n >= 0, vals, 0)
  1687. def factorial2(n, exact=False):
  1688. """Double factorial.
  1689. This is the factorial with every second value skipped. E.g., ``7!! = 7 * 5
  1690. * 3 * 1``. It can be approximated numerically as::
  1691. n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi) n odd
  1692. = 2**(n/2) * (n/2)! n even
  1693. Parameters
  1694. ----------
  1695. n : int or array_like
  1696. Calculate ``n!!``. Arrays are only supported with `exact` set
  1697. to False. If ``n < 0``, the return value is 0.
  1698. exact : bool, optional
  1699. The result can be approximated rapidly using the gamma-formula
  1700. above (default). If `exact` is set to True, calculate the
  1701. answer exactly using integer arithmetic.
  1702. Returns
  1703. -------
  1704. nff : float or int
  1705. Double factorial of `n`, as an int or a float depending on
  1706. `exact`.
  1707. Examples
  1708. --------
  1709. >>> from scipy.special import factorial2
  1710. >>> factorial2(7, exact=False)
  1711. array(105.00000000000001)
  1712. >>> factorial2(7, exact=True)
  1713. 105L
  1714. """
  1715. if exact:
  1716. if n < -1:
  1717. return 0
  1718. if n <= 0:
  1719. return 1
  1720. val = 1
  1721. for k in xrange(n, 0, -2):
  1722. val *= k
  1723. return val
  1724. else:
  1725. n = asarray(n)
  1726. vals = zeros(n.shape, 'd')
  1727. cond1 = (n % 2) & (n >= -1)
  1728. cond2 = (1-(n % 2)) & (n >= -1)
  1729. oddn = extract(cond1, n)
  1730. evenn = extract(cond2, n)
  1731. nd2o = oddn / 2.0
  1732. nd2e = evenn / 2.0
  1733. place(vals, cond1, gamma(nd2o + 1) / sqrt(pi) * pow(2.0, nd2o + 0.5))
  1734. place(vals, cond2, gamma(nd2e + 1) * pow(2.0, nd2e))
  1735. return vals
  1736. def factorialk(n, k, exact=True):
  1737. """Multifactorial of n of order k, n(!!...!).
  1738. This is the multifactorial of n skipping k values. For example,
  1739. factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
  1740. In particular, for any integer ``n``, we have
  1741. factorialk(n, 1) = factorial(n)
  1742. factorialk(n, 2) = factorial2(n)
  1743. Parameters
  1744. ----------
  1745. n : int
  1746. Calculate multifactorial. If `n` < 0, the return value is 0.
  1747. k : int
  1748. Order of multifactorial.
  1749. exact : bool, optional
  1750. If exact is set to True, calculate the answer exactly using
  1751. integer arithmetic.
  1752. Returns
  1753. -------
  1754. val : int
  1755. Multifactorial of `n`.
  1756. Raises
  1757. ------
  1758. NotImplementedError
  1759. Raises when exact is False
  1760. Examples
  1761. --------
  1762. >>> from scipy.special import factorialk
  1763. >>> factorialk(5, 1, exact=True)
  1764. 120L
  1765. >>> factorialk(5, 3, exact=True)
  1766. 10L
  1767. """
  1768. if exact:
  1769. if n < 1-k:
  1770. return 0
  1771. if n <= 0:
  1772. return 1
  1773. val = 1
  1774. for j in xrange(n, 0, -k):
  1775. val = val*j
  1776. return val
  1777. else:
  1778. raise NotImplementedError
  1779. def zeta(x, q=None, out=None):
  1780. r"""
  1781. Riemann or Hurwitz zeta function.
  1782. Parameters
  1783. ----------
  1784. x : array_like of float
  1785. Input data, must be real
  1786. q : array_like of float, optional
  1787. Input data, must be real. Defaults to Riemann zeta.
  1788. out : ndarray, optional
  1789. Output array for the computed values.
  1790. Returns
  1791. -------
  1792. out : array_like
  1793. Values of zeta(x).
  1794. Notes
  1795. -----
  1796. The two-argument version is the Hurwitz zeta function:
  1797. .. math:: \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x},
  1798. Riemann zeta function corresponds to ``q = 1``.
  1799. See Also
  1800. --------
  1801. zetac
  1802. Examples
  1803. --------
  1804. >>> from scipy.special import zeta, polygamma, factorial
  1805. Some specific values:
  1806. >>> zeta(2), np.pi**2/6
  1807. (1.6449340668482266, 1.6449340668482264)
  1808. >>> zeta(4), np.pi**4/90
  1809. (1.0823232337111381, 1.082323233711138)
  1810. Relation to the `polygamma` function:
  1811. >>> m = 3
  1812. >>> x = 1.25
  1813. >>> polygamma(m, x)
  1814. array(2.782144009188397)
  1815. >>> (-1)**(m+1) * factorial(m) * zeta(m+1, x)
  1816. 2.7821440091883969
  1817. """
  1818. if q is None:
  1819. q = 1
  1820. return _zeta(x, q, out)