_basic.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020
  1. #
  2. # Author: Travis Oliphant, 2002
  3. #
  4. import operator
  5. import numpy as np
  6. import math
  7. import warnings
  8. from numpy import (pi, asarray, floor, isscalar, iscomplex, real,
  9. imag, sqrt, where, mgrid, sin, place, issubdtype,
  10. extract, inexact, nan, zeros, sinc)
  11. from . import _ufuncs
  12. from ._ufuncs import (mathieu_a, mathieu_b, iv, jv, gamma,
  13. psi, hankel1, hankel2, yv, kv, poch, binom)
  14. from . import _specfun
  15. from ._comb import _comb_int
  16. __all__ = [
  17. 'ai_zeros',
  18. 'assoc_laguerre',
  19. 'bei_zeros',
  20. 'beip_zeros',
  21. 'ber_zeros',
  22. 'bernoulli',
  23. 'berp_zeros',
  24. 'bi_zeros',
  25. 'clpmn',
  26. 'comb',
  27. 'digamma',
  28. 'diric',
  29. 'erf_zeros',
  30. 'euler',
  31. 'factorial',
  32. 'factorial2',
  33. 'factorialk',
  34. 'fresnel_zeros',
  35. 'fresnelc_zeros',
  36. 'fresnels_zeros',
  37. 'h1vp',
  38. 'h2vp',
  39. 'ivp',
  40. 'jn_zeros',
  41. 'jnjnp_zeros',
  42. 'jnp_zeros',
  43. 'jnyn_zeros',
  44. 'jvp',
  45. 'kei_zeros',
  46. 'keip_zeros',
  47. 'kelvin_zeros',
  48. 'ker_zeros',
  49. 'kerp_zeros',
  50. 'kvp',
  51. 'lmbda',
  52. 'lpmn',
  53. 'lpn',
  54. 'lqmn',
  55. 'lqn',
  56. 'mathieu_even_coef',
  57. 'mathieu_odd_coef',
  58. 'obl_cv_seq',
  59. 'pbdn_seq',
  60. 'pbdv_seq',
  61. 'pbvv_seq',
  62. 'perm',
  63. 'polygamma',
  64. 'pro_cv_seq',
  65. 'riccati_jn',
  66. 'riccati_yn',
  67. 'sinc',
  68. 'y0_zeros',
  69. 'y1_zeros',
  70. 'y1p_zeros',
  71. 'yn_zeros',
  72. 'ynp_zeros',
  73. 'yvp',
  74. 'zeta'
  75. ]
  76. def _nonneg_int_or_fail(n, var_name, strict=True):
  77. try:
  78. if strict:
  79. # Raises an exception if float
  80. n = operator.index(n)
  81. elif n == floor(n):
  82. n = int(n)
  83. else:
  84. raise ValueError()
  85. if n < 0:
  86. raise ValueError()
  87. except (ValueError, TypeError) as err:
  88. raise err.__class__("{} must be a non-negative integer".format(var_name)) from err
  89. return n
  90. def diric(x, n):
  91. """Periodic sinc function, also called the Dirichlet function.
  92. The Dirichlet function is defined as::
  93. diric(x, n) = sin(x * n/2) / (n * sin(x / 2)),
  94. where `n` is a positive integer.
  95. Parameters
  96. ----------
  97. x : array_like
  98. Input data
  99. n : int
  100. Integer defining the periodicity.
  101. Returns
  102. -------
  103. diric : ndarray
  104. Examples
  105. --------
  106. >>> import numpy as np
  107. >>> from scipy import special
  108. >>> import matplotlib.pyplot as plt
  109. >>> x = np.linspace(-8*np.pi, 8*np.pi, num=201)
  110. >>> plt.figure(figsize=(8, 8));
  111. >>> for idx, n in enumerate([2, 3, 4, 9]):
  112. ... plt.subplot(2, 2, idx+1)
  113. ... plt.plot(x, special.diric(x, n))
  114. ... plt.title('diric, n={}'.format(n))
  115. >>> plt.show()
  116. The following example demonstrates that `diric` gives the magnitudes
  117. (modulo the sign and scaling) of the Fourier coefficients of a
  118. rectangular pulse.
  119. Suppress output of values that are effectively 0:
  120. >>> np.set_printoptions(suppress=True)
  121. Create a signal `x` of length `m` with `k` ones:
  122. >>> m = 8
  123. >>> k = 3
  124. >>> x = np.zeros(m)
  125. >>> x[:k] = 1
  126. Use the FFT to compute the Fourier transform of `x`, and
  127. inspect the magnitudes of the coefficients:
  128. >>> np.abs(np.fft.fft(x))
  129. array([ 3. , 2.41421356, 1. , 0.41421356, 1. ,
  130. 0.41421356, 1. , 2.41421356])
  131. Now find the same values (up to sign) using `diric`. We multiply
  132. by `k` to account for the different scaling conventions of
  133. `numpy.fft.fft` and `diric`:
  134. >>> theta = np.linspace(0, 2*np.pi, m, endpoint=False)
  135. >>> k * special.diric(theta, k)
  136. array([ 3. , 2.41421356, 1. , -0.41421356, -1. ,
  137. -0.41421356, 1. , 2.41421356])
  138. """
  139. x, n = asarray(x), asarray(n)
  140. n = asarray(n + (x-x))
  141. x = asarray(x + (n-n))
  142. if issubdtype(x.dtype, inexact):
  143. ytype = x.dtype
  144. else:
  145. ytype = float
  146. y = zeros(x.shape, ytype)
  147. # empirical minval for 32, 64 or 128 bit float computations
  148. # where sin(x/2) < minval, result is fixed at +1 or -1
  149. if np.finfo(ytype).eps < 1e-18:
  150. minval = 1e-11
  151. elif np.finfo(ytype).eps < 1e-15:
  152. minval = 1e-7
  153. else:
  154. minval = 1e-3
  155. mask1 = (n <= 0) | (n != floor(n))
  156. place(y, mask1, nan)
  157. x = x / 2
  158. denom = sin(x)
  159. mask2 = (1-mask1) & (abs(denom) < minval)
  160. xsub = extract(mask2, x)
  161. nsub = extract(mask2, n)
  162. zsub = xsub / pi
  163. place(y, mask2, pow(-1, np.round(zsub)*(nsub-1)))
  164. mask = (1-mask1) & (1-mask2)
  165. xsub = extract(mask, x)
  166. nsub = extract(mask, n)
  167. dsub = extract(mask, denom)
  168. place(y, mask, sin(nsub*xsub)/(nsub*dsub))
  169. return y
  170. def jnjnp_zeros(nt):
  171. """Compute zeros of integer-order Bessel functions Jn and Jn'.
  172. Results are arranged in order of the magnitudes of the zeros.
  173. Parameters
  174. ----------
  175. nt : int
  176. Number (<=1200) of zeros to compute
  177. Returns
  178. -------
  179. zo[l-1] : ndarray
  180. Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
  181. n[l-1] : ndarray
  182. Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
  183. m[l-1] : ndarray
  184. Serial number of the zeros of Jn(x) or Jn'(x) associated
  185. with lth zero. Of length `nt`.
  186. t[l-1] : ndarray
  187. 0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
  188. length `nt`.
  189. See Also
  190. --------
  191. jn_zeros, jnp_zeros : to get separated arrays of zeros.
  192. References
  193. ----------
  194. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  195. Functions", John Wiley and Sons, 1996, chapter 5.
  196. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  197. """
  198. if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
  199. raise ValueError("Number must be integer <= 1200.")
  200. nt = int(nt)
  201. n, m, t, zo = _specfun.jdzo(nt)
  202. return zo[1:nt+1], n[:nt], m[:nt], t[:nt]
  203. def jnyn_zeros(n, nt):
  204. """Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
  205. Returns 4 arrays of length `nt`, corresponding to the first `nt`
  206. zeros of Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively. The zeros
  207. are returned in ascending order.
  208. Parameters
  209. ----------
  210. n : int
  211. Order of the Bessel functions
  212. nt : int
  213. Number (<=1200) of zeros to compute
  214. Returns
  215. -------
  216. Jn : ndarray
  217. First `nt` zeros of Jn
  218. Jnp : ndarray
  219. First `nt` zeros of Jn'
  220. Yn : ndarray
  221. First `nt` zeros of Yn
  222. Ynp : ndarray
  223. First `nt` zeros of Yn'
  224. See Also
  225. --------
  226. jn_zeros, jnp_zeros, yn_zeros, ynp_zeros
  227. References
  228. ----------
  229. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  230. Functions", John Wiley and Sons, 1996, chapter 5.
  231. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  232. Examples
  233. --------
  234. Compute the first three roots of :math:`J_1`, :math:`J_1'`,
  235. :math:`Y_1` and :math:`Y_1'`.
  236. >>> from scipy.special import jnyn_zeros
  237. >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
  238. >>> jn_roots, yn_roots
  239. (array([ 3.83170597, 7.01558667, 10.17346814]),
  240. array([2.19714133, 5.42968104, 8.59600587]))
  241. Plot :math:`J_1`, :math:`J_1'`, :math:`Y_1`, :math:`Y_1'` and their roots.
  242. >>> import numpy as np
  243. >>> import matplotlib.pyplot as plt
  244. >>> from scipy.special import jnyn_zeros, jvp, jn, yvp, yn
  245. >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
  246. >>> fig, ax = plt.subplots()
  247. >>> xmax= 11
  248. >>> x = np.linspace(0, xmax)
  249. >>> ax.plot(x, jn(1, x), label=r"$J_1$", c='r')
  250. >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$", c='b')
  251. >>> ax.plot(x, yn(1, x), label=r"$Y_1$", c='y')
  252. >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$", c='c')
  253. >>> zeros = np.zeros((3, ))
  254. >>> ax.scatter(jn_roots, zeros, s=30, c='r', zorder=5,
  255. ... label=r"$J_1$ roots")
  256. >>> ax.scatter(jnp_roots, zeros, s=30, c='b', zorder=5,
  257. ... label=r"$J_1'$ roots")
  258. >>> ax.scatter(yn_roots, zeros, s=30, c='y', zorder=5,
  259. ... label=r"$Y_1$ roots")
  260. >>> ax.scatter(ynp_roots, zeros, s=30, c='c', zorder=5,
  261. ... label=r"$Y_1'$ roots")
  262. >>> ax.hlines(0, 0, xmax, color='k')
  263. >>> ax.set_ylim(-0.6, 0.6)
  264. >>> ax.set_xlim(0, xmax)
  265. >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
  266. >>> plt.tight_layout()
  267. >>> plt.show()
  268. """
  269. if not (isscalar(nt) and isscalar(n)):
  270. raise ValueError("Arguments must be scalars.")
  271. if (floor(n) != n) or (floor(nt) != nt):
  272. raise ValueError("Arguments must be integers.")
  273. if (nt <= 0):
  274. raise ValueError("nt > 0")
  275. return _specfun.jyzo(abs(n), nt)
  276. def jn_zeros(n, nt):
  277. r"""Compute zeros of integer-order Bessel functions Jn.
  278. Compute `nt` zeros of the Bessel functions :math:`J_n(x)` on the
  279. interval :math:`(0, \infty)`. The zeros are returned in ascending
  280. order. Note that this interval excludes the zero at :math:`x = 0`
  281. that exists for :math:`n > 0`.
  282. Parameters
  283. ----------
  284. n : int
  285. Order of Bessel function
  286. nt : int
  287. Number of zeros to return
  288. Returns
  289. -------
  290. ndarray
  291. First `nt` zeros of the Bessel function.
  292. See Also
  293. --------
  294. jv: Real-order Bessel functions of the first kind
  295. jnp_zeros: Zeros of :math:`Jn'`
  296. References
  297. ----------
  298. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  299. Functions", John Wiley and Sons, 1996, chapter 5.
  300. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  301. Examples
  302. --------
  303. Compute the first four positive roots of :math:`J_3`.
  304. >>> from scipy.special import jn_zeros
  305. >>> jn_zeros(3, 4)
  306. array([ 6.3801619 , 9.76102313, 13.01520072, 16.22346616])
  307. Plot :math:`J_3` and its first four positive roots. Note
  308. that the root located at 0 is not returned by `jn_zeros`.
  309. >>> import numpy as np
  310. >>> import matplotlib.pyplot as plt
  311. >>> from scipy.special import jn, jn_zeros
  312. >>> j3_roots = jn_zeros(3, 4)
  313. >>> xmax = 18
  314. >>> xmin = -1
  315. >>> x = np.linspace(xmin, xmax, 500)
  316. >>> fig, ax = plt.subplots()
  317. >>> ax.plot(x, jn(3, x), label=r'$J_3$')
  318. >>> ax.scatter(j3_roots, np.zeros((4, )), s=30, c='r',
  319. ... label=r"$J_3$_Zeros", zorder=5)
  320. >>> ax.scatter(0, 0, s=30, c='k',
  321. ... label=r"Root at 0", zorder=5)
  322. >>> ax.hlines(0, 0, xmax, color='k')
  323. >>> ax.set_xlim(xmin, xmax)
  324. >>> plt.legend()
  325. >>> plt.show()
  326. """
  327. return jnyn_zeros(n, nt)[0]
  328. def jnp_zeros(n, nt):
  329. r"""Compute zeros of integer-order Bessel function derivatives Jn'.
  330. Compute `nt` zeros of the functions :math:`J_n'(x)` on the
  331. interval :math:`(0, \infty)`. The zeros are returned in ascending
  332. order. Note that this interval excludes the zero at :math:`x = 0`
  333. that exists for :math:`n > 1`.
  334. Parameters
  335. ----------
  336. n : int
  337. Order of Bessel function
  338. nt : int
  339. Number of zeros to return
  340. Returns
  341. -------
  342. ndarray
  343. First `nt` zeros of the Bessel function.
  344. See Also
  345. --------
  346. jvp: Derivatives of integer-order Bessel functions of the first kind
  347. jv: Float-order Bessel functions of the first kind
  348. References
  349. ----------
  350. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  351. Functions", John Wiley and Sons, 1996, chapter 5.
  352. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  353. Examples
  354. --------
  355. Compute the first four roots of :math:`J_2'`.
  356. >>> from scipy.special import jnp_zeros
  357. >>> jnp_zeros(2, 4)
  358. array([ 3.05423693, 6.70613319, 9.96946782, 13.17037086])
  359. As `jnp_zeros` yields the roots of :math:`J_n'`, it can be used to
  360. compute the locations of the peaks of :math:`J_n`. Plot
  361. :math:`J_2`, :math:`J_2'` and the locations of the roots of :math:`J_2'`.
  362. >>> import numpy as np
  363. >>> import matplotlib.pyplot as plt
  364. >>> from scipy.special import jn, jnp_zeros, jvp
  365. >>> j2_roots = jnp_zeros(2, 4)
  366. >>> xmax = 15
  367. >>> x = np.linspace(0, xmax, 500)
  368. >>> fig, ax = plt.subplots()
  369. >>> ax.plot(x, jn(2, x), label=r'$J_2$')
  370. >>> ax.plot(x, jvp(2, x, 1), label=r"$J_2'$")
  371. >>> ax.hlines(0, 0, xmax, color='k')
  372. >>> ax.scatter(j2_roots, np.zeros((4, )), s=30, c='r',
  373. ... label=r"Roots of $J_2'$", zorder=5)
  374. >>> ax.set_ylim(-0.4, 0.8)
  375. >>> ax.set_xlim(0, xmax)
  376. >>> plt.legend()
  377. >>> plt.show()
  378. """
  379. return jnyn_zeros(n, nt)[1]
  380. def yn_zeros(n, nt):
  381. r"""Compute zeros of integer-order Bessel function Yn(x).
  382. Compute `nt` zeros of the functions :math:`Y_n(x)` on the interval
  383. :math:`(0, \infty)`. The zeros are returned in ascending order.
  384. Parameters
  385. ----------
  386. n : int
  387. Order of Bessel function
  388. nt : int
  389. Number of zeros to return
  390. Returns
  391. -------
  392. ndarray
  393. First `nt` zeros of the Bessel function.
  394. See Also
  395. --------
  396. yn: Bessel function of the second kind for integer order
  397. yv: Bessel function of the second kind for real order
  398. References
  399. ----------
  400. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  401. Functions", John Wiley and Sons, 1996, chapter 5.
  402. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  403. Examples
  404. --------
  405. Compute the first four roots of :math:`Y_2`.
  406. >>> from scipy.special import yn_zeros
  407. >>> yn_zeros(2, 4)
  408. array([ 3.38424177, 6.79380751, 10.02347798, 13.20998671])
  409. Plot :math:`Y_2` and its first four roots.
  410. >>> import numpy as np
  411. >>> import matplotlib.pyplot as plt
  412. >>> from scipy.special import yn, yn_zeros
  413. >>> xmin = 2
  414. >>> xmax = 15
  415. >>> x = np.linspace(xmin, xmax, 500)
  416. >>> fig, ax = plt.subplots()
  417. >>> ax.hlines(0, xmin, xmax, color='k')
  418. >>> ax.plot(x, yn(2, x), label=r'$Y_2$')
  419. >>> ax.scatter(yn_zeros(2, 4), np.zeros((4, )), s=30, c='r',
  420. ... label='Roots', zorder=5)
  421. >>> ax.set_ylim(-0.4, 0.4)
  422. >>> ax.set_xlim(xmin, xmax)
  423. >>> plt.legend()
  424. >>> plt.show()
  425. """
  426. return jnyn_zeros(n, nt)[2]
  427. def ynp_zeros(n, nt):
  428. r"""Compute zeros of integer-order Bessel function derivatives Yn'(x).
  429. Compute `nt` zeros of the functions :math:`Y_n'(x)` on the
  430. interval :math:`(0, \infty)`. The zeros are returned in ascending
  431. order.
  432. Parameters
  433. ----------
  434. n : int
  435. Order of Bessel function
  436. nt : int
  437. Number of zeros to return
  438. Returns
  439. -------
  440. ndarray
  441. First `nt` zeros of the Bessel derivative function.
  442. See Also
  443. --------
  444. yvp
  445. References
  446. ----------
  447. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  448. Functions", John Wiley and Sons, 1996, chapter 5.
  449. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  450. Examples
  451. --------
  452. Compute the first four roots of the first derivative of the
  453. Bessel function of second kind for order 0 :math:`Y_0'`.
  454. >>> from scipy.special import ynp_zeros
  455. >>> ynp_zeros(0, 4)
  456. array([ 2.19714133, 5.42968104, 8.59600587, 11.74915483])
  457. Plot :math:`Y_0`, :math:`Y_0'` and confirm visually that the roots of
  458. :math:`Y_0'` are located at local extrema of :math:`Y_0`.
  459. >>> import numpy as np
  460. >>> import matplotlib.pyplot as plt
  461. >>> from scipy.special import yn, ynp_zeros, yvp
  462. >>> zeros = ynp_zeros(0, 4)
  463. >>> xmax = 13
  464. >>> x = np.linspace(0, xmax, 500)
  465. >>> fig, ax = plt.subplots()
  466. >>> ax.plot(x, yn(0, x), label=r'$Y_0$')
  467. >>> ax.plot(x, yvp(0, x, 1), label=r"$Y_0'$")
  468. >>> ax.scatter(zeros, np.zeros((4, )), s=30, c='r',
  469. ... label=r"Roots of $Y_0'$", zorder=5)
  470. >>> for root in zeros:
  471. ... y0_extremum = yn(0, root)
  472. ... lower = min(0, y0_extremum)
  473. ... upper = max(0, y0_extremum)
  474. ... ax.vlines(root, lower, upper, color='r')
  475. >>> ax.hlines(0, 0, xmax, color='k')
  476. >>> ax.set_ylim(-0.6, 0.6)
  477. >>> ax.set_xlim(0, xmax)
  478. >>> plt.legend()
  479. >>> plt.show()
  480. """
  481. return jnyn_zeros(n, nt)[3]
  482. def y0_zeros(nt, complex=False):
  483. """Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
  484. The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0.
  485. Parameters
  486. ----------
  487. nt : int
  488. Number of zeros to return
  489. complex : bool, default False
  490. Set to False to return only the real zeros; set to True to return only
  491. the complex zeros with negative real part and positive imaginary part.
  492. Note that the complex conjugates of the latter are also zeros of the
  493. function, but are not returned by this routine.
  494. Returns
  495. -------
  496. z0n : ndarray
  497. Location of nth zero of Y0(z)
  498. y0pz0n : ndarray
  499. Value of derivative Y0'(z0) for nth zero
  500. References
  501. ----------
  502. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  503. Functions", John Wiley and Sons, 1996, chapter 5.
  504. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  505. Examples
  506. --------
  507. Compute the first 4 real roots and the derivatives at the roots of
  508. :math:`Y_0`:
  509. >>> import numpy as np
  510. >>> from scipy.special import y0_zeros
  511. >>> zeros, grads = y0_zeros(4)
  512. >>> with np.printoptions(precision=5):
  513. ... print(f"Roots: {zeros}")
  514. ... print(f"Gradients: {grads}")
  515. Roots: [ 0.89358+0.j 3.95768+0.j 7.08605+0.j 10.22235+0.j]
  516. Gradients: [-0.87942+0.j 0.40254+0.j -0.3001 +0.j 0.2497 +0.j]
  517. Plot the real part of :math:`Y_0` and the first four computed roots.
  518. >>> import matplotlib.pyplot as plt
  519. >>> from scipy.special import y0
  520. >>> xmin = 0
  521. >>> xmax = 11
  522. >>> x = np.linspace(xmin, xmax, 500)
  523. >>> fig, ax = plt.subplots()
  524. >>> ax.hlines(0, xmin, xmax, color='k')
  525. >>> ax.plot(x, y0(x), label=r'$Y_0$')
  526. >>> zeros, grads = y0_zeros(4)
  527. >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
  528. ... label=r'$Y_0$_zeros', zorder=5)
  529. >>> ax.set_ylim(-0.5, 0.6)
  530. >>> ax.set_xlim(xmin, xmax)
  531. >>> plt.legend(ncol=2)
  532. >>> plt.show()
  533. Compute the first 4 complex roots and the derivatives at the roots of
  534. :math:`Y_0` by setting ``complex=True``:
  535. >>> y0_zeros(4, True)
  536. (array([ -2.40301663+0.53988231j, -5.5198767 +0.54718001j,
  537. -8.6536724 +0.54841207j, -11.79151203+0.54881912j]),
  538. array([ 0.10074769-0.88196771j, -0.02924642+0.5871695j ,
  539. 0.01490806-0.46945875j, -0.00937368+0.40230454j]))
  540. """
  541. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  542. raise ValueError("Arguments must be scalar positive integer.")
  543. kf = 0
  544. kc = not complex
  545. return _specfun.cyzo(nt, kf, kc)
  546. def y1_zeros(nt, complex=False):
  547. """Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
  548. The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1.
  549. Parameters
  550. ----------
  551. nt : int
  552. Number of zeros to return
  553. complex : bool, default False
  554. Set to False to return only the real zeros; set to True to return only
  555. the complex zeros with negative real part and positive imaginary part.
  556. Note that the complex conjugates of the latter are also zeros of the
  557. function, but are not returned by this routine.
  558. Returns
  559. -------
  560. z1n : ndarray
  561. Location of nth zero of Y1(z)
  562. y1pz1n : ndarray
  563. Value of derivative Y1'(z1) for nth zero
  564. References
  565. ----------
  566. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  567. Functions", John Wiley and Sons, 1996, chapter 5.
  568. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  569. Examples
  570. --------
  571. Compute the first 4 real roots and the derivatives at the roots of
  572. :math:`Y_1`:
  573. >>> import numpy as np
  574. >>> from scipy.special import y1_zeros
  575. >>> zeros, grads = y1_zeros(4)
  576. >>> with np.printoptions(precision=5):
  577. ... print(f"Roots: {zeros}")
  578. ... print(f"Gradients: {grads}")
  579. Roots: [ 2.19714+0.j 5.42968+0.j 8.59601+0.j 11.74915+0.j]
  580. Gradients: [ 0.52079+0.j -0.34032+0.j 0.27146+0.j -0.23246+0.j]
  581. Extract the real parts:
  582. >>> realzeros = zeros.real
  583. >>> realzeros
  584. array([ 2.19714133, 5.42968104, 8.59600587, 11.74915483])
  585. Plot :math:`Y_1` and the first four computed roots.
  586. >>> import matplotlib.pyplot as plt
  587. >>> from scipy.special import y1
  588. >>> xmin = 0
  589. >>> xmax = 13
  590. >>> x = np.linspace(xmin, xmax, 500)
  591. >>> zeros, grads = y1_zeros(4)
  592. >>> fig, ax = plt.subplots()
  593. >>> ax.hlines(0, xmin, xmax, color='k')
  594. >>> ax.plot(x, y1(x), label=r'$Y_1$')
  595. >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
  596. ... label=r'$Y_1$_zeros', zorder=5)
  597. >>> ax.set_ylim(-0.5, 0.5)
  598. >>> ax.set_xlim(xmin, xmax)
  599. >>> plt.legend()
  600. >>> plt.show()
  601. Compute the first 4 complex roots and the derivatives at the roots of
  602. :math:`Y_1` by setting ``complex=True``:
  603. >>> y1_zeros(4, True)
  604. (array([ -0.50274327+0.78624371j, -3.83353519+0.56235654j,
  605. -7.01590368+0.55339305j, -10.17357383+0.55127339j]),
  606. array([-0.45952768+1.31710194j, 0.04830191-0.69251288j,
  607. -0.02012695+0.51864253j, 0.011614 -0.43203296j]))
  608. """
  609. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  610. raise ValueError("Arguments must be scalar positive integer.")
  611. kf = 1
  612. kc = not complex
  613. return _specfun.cyzo(nt, kf, kc)
  614. def y1p_zeros(nt, complex=False):
  615. """Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
  616. The values are given by Y1(z1) at each z1 where Y1'(z1)=0.
  617. Parameters
  618. ----------
  619. nt : int
  620. Number of zeros to return
  621. complex : bool, default False
  622. Set to False to return only the real zeros; set to True to return only
  623. the complex zeros with negative real part and positive imaginary part.
  624. Note that the complex conjugates of the latter are also zeros of the
  625. function, but are not returned by this routine.
  626. Returns
  627. -------
  628. z1pn : ndarray
  629. Location of nth zero of Y1'(z)
  630. y1z1pn : ndarray
  631. Value of derivative Y1(z1) for nth zero
  632. References
  633. ----------
  634. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  635. Functions", John Wiley and Sons, 1996, chapter 5.
  636. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  637. Examples
  638. --------
  639. Compute the first four roots of :math:`Y_1'` and the values of
  640. :math:`Y_1` at these roots.
  641. >>> import numpy as np
  642. >>> from scipy.special import y1p_zeros
  643. >>> y1grad_roots, y1_values = y1p_zeros(4)
  644. >>> with np.printoptions(precision=5):
  645. ... print(f"Y1' Roots: {y1grad_roots}")
  646. ... print(f"Y1 values: {y1_values}")
  647. Y1' Roots: [ 3.68302+0.j 6.9415 +0.j 10.1234 +0.j 13.28576+0.j]
  648. Y1 values: [ 0.41673+0.j -0.30317+0.j 0.25091+0.j -0.21897+0.j]
  649. `y1p_zeros` can be used to calculate the extremal points of :math:`Y_1`
  650. directly. Here we plot :math:`Y_1` and the first four extrema.
  651. >>> import matplotlib.pyplot as plt
  652. >>> from scipy.special import y1, yvp
  653. >>> y1_roots, y1_values_at_roots = y1p_zeros(4)
  654. >>> real_roots = y1_roots.real
  655. >>> xmax = 15
  656. >>> x = np.linspace(0, xmax, 500)
  657. >>> fig, ax = plt.subplots()
  658. >>> ax.plot(x, y1(x), label=r'$Y_1$')
  659. >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
  660. >>> ax.scatter(real_roots, np.zeros((4, )), s=30, c='r',
  661. ... label=r"Roots of $Y_1'$", zorder=5)
  662. >>> ax.scatter(real_roots, y1_values_at_roots.real, s=30, c='k',
  663. ... label=r"Extrema of $Y_1$", zorder=5)
  664. >>> ax.hlines(0, 0, xmax, color='k')
  665. >>> ax.set_ylim(-0.5, 0.5)
  666. >>> ax.set_xlim(0, xmax)
  667. >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
  668. >>> plt.tight_layout()
  669. >>> plt.show()
  670. """
  671. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  672. raise ValueError("Arguments must be scalar positive integer.")
  673. kf = 2
  674. kc = not complex
  675. return _specfun.cyzo(nt, kf, kc)
  676. def _bessel_diff_formula(v, z, n, L, phase):
  677. # from AMS55.
  678. # L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1
  679. # L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1
  680. # For K, you can pull out the exp((v-k)*pi*i) into the caller
  681. v = asarray(v)
  682. p = 1.0
  683. s = L(v-n, z)
  684. for i in range(1, n+1):
  685. p = phase * (p * (n-i+1)) / i # = choose(k, i)
  686. s += p*L(v-n + i*2, z)
  687. return s / (2.**n)
  688. def jvp(v, z, n=1):
  689. """Compute derivatives of Bessel functions of the first kind.
  690. Compute the nth derivative of the Bessel function `Jv` with
  691. respect to `z`.
  692. Parameters
  693. ----------
  694. v : array_like or float
  695. Order of Bessel function
  696. z : complex
  697. Argument at which to evaluate the derivative; can be real or
  698. complex.
  699. n : int, default 1
  700. Order of derivative. For 0 returns the Bessel function `jv` itself.
  701. Returns
  702. -------
  703. scalar or ndarray
  704. Values of the derivative of the Bessel function.
  705. Notes
  706. -----
  707. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  708. References
  709. ----------
  710. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  711. Functions", John Wiley and Sons, 1996, chapter 5.
  712. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  713. .. [2] NIST Digital Library of Mathematical Functions.
  714. https://dlmf.nist.gov/10.6.E7
  715. Examples
  716. --------
  717. Compute the Bessel function of the first kind of order 0 and
  718. its first two derivatives at 1.
  719. >>> from scipy.special import jvp
  720. >>> jvp(0, 1, 0), jvp(0, 1, 1), jvp(0, 1, 2)
  721. (0.7651976865579666, -0.44005058574493355, -0.3251471008130331)
  722. Compute the first derivative of the Bessel function of the first
  723. kind for several orders at 1 by providing an array for `v`.
  724. >>> jvp([0, 1, 2], 1, 1)
  725. array([-0.44005059, 0.3251471 , 0.21024362])
  726. Compute the first derivative of the Bessel function of the first
  727. kind of order 0 at several points by providing an array for `z`.
  728. >>> import numpy as np
  729. >>> points = np.array([0., 1.5, 3.])
  730. >>> jvp(0, points, 1)
  731. array([-0. , -0.55793651, -0.33905896])
  732. Plot the Bessel function of the first kind of order 1 and its
  733. first three derivatives.
  734. >>> import matplotlib.pyplot as plt
  735. >>> x = np.linspace(-10, 10, 1000)
  736. >>> fig, ax = plt.subplots()
  737. >>> ax.plot(x, jvp(1, x, 0), label=r"$J_1$")
  738. >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$")
  739. >>> ax.plot(x, jvp(1, x, 2), label=r"$J_1''$")
  740. >>> ax.plot(x, jvp(1, x, 3), label=r"$J_1'''$")
  741. >>> plt.legend()
  742. >>> plt.show()
  743. """
  744. n = _nonneg_int_or_fail(n, 'n')
  745. if n == 0:
  746. return jv(v, z)
  747. else:
  748. return _bessel_diff_formula(v, z, n, jv, -1)
  749. def yvp(v, z, n=1):
  750. """Compute derivatives of Bessel functions of the second kind.
  751. Compute the nth derivative of the Bessel function `Yv` with
  752. respect to `z`.
  753. Parameters
  754. ----------
  755. v : array_like of float
  756. Order of Bessel function
  757. z : complex
  758. Argument at which to evaluate the derivative
  759. n : int, default 1
  760. Order of derivative. For 0 returns the BEssel function `yv`
  761. See Also
  762. --------
  763. yv
  764. Returns
  765. -------
  766. scalar or ndarray
  767. nth derivative of the Bessel function.
  768. Notes
  769. -----
  770. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  771. References
  772. ----------
  773. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  774. Functions", John Wiley and Sons, 1996, chapter 5.
  775. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  776. .. [2] NIST Digital Library of Mathematical Functions.
  777. https://dlmf.nist.gov/10.6.E7
  778. Examples
  779. --------
  780. Compute the Bessel function of the second kind of order 0 and
  781. its first two derivatives at 1.
  782. >>> from scipy.special import yvp
  783. >>> yvp(0, 1, 0), yvp(0, 1, 1), yvp(0, 1, 2)
  784. (0.088256964215677, 0.7812128213002889, -0.8694697855159659)
  785. Compute the first derivative of the Bessel function of the second
  786. kind for several orders at 1 by providing an array for `v`.
  787. >>> yvp([0, 1, 2], 1, 1)
  788. array([0.78121282, 0.86946979, 2.52015239])
  789. Compute the first derivative of the Bessel function of the
  790. second kind of order 0 at several points by providing an array for `z`.
  791. >>> import numpy as np
  792. >>> points = np.array([0.5, 1.5, 3.])
  793. >>> yvp(0, points, 1)
  794. array([ 1.47147239, 0.41230863, -0.32467442])
  795. Plot the Bessel function of the second kind of order 1 and its
  796. first three derivatives.
  797. >>> import matplotlib.pyplot as plt
  798. >>> x = np.linspace(0, 5, 1000)
  799. >>> fig, ax = plt.subplots()
  800. >>> ax.plot(x, yvp(1, x, 0), label=r"$Y_1$")
  801. >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
  802. >>> ax.plot(x, yvp(1, x, 2), label=r"$Y_1''$")
  803. >>> ax.plot(x, yvp(1, x, 3), label=r"$Y_1'''$")
  804. >>> ax.set_ylim(-10, 10)
  805. >>> plt.legend()
  806. >>> plt.show()
  807. """
  808. n = _nonneg_int_or_fail(n, 'n')
  809. if n == 0:
  810. return yv(v, z)
  811. else:
  812. return _bessel_diff_formula(v, z, n, yv, -1)
  813. def kvp(v, z, n=1):
  814. """Compute derivatives of real-order modified Bessel function Kv(z)
  815. Kv(z) is the modified Bessel function of the second kind.
  816. Derivative is calculated with respect to `z`.
  817. Parameters
  818. ----------
  819. v : array_like of float
  820. Order of Bessel function
  821. z : array_like of complex
  822. Argument at which to evaluate the derivative
  823. n : int, default 1
  824. Order of derivative. For 0 returns the Bessel function `kv` itself.
  825. Returns
  826. -------
  827. out : ndarray
  828. The results
  829. See Also
  830. --------
  831. kv
  832. Notes
  833. -----
  834. The derivative is computed using the relation DLFM 10.29.5 [2]_.
  835. References
  836. ----------
  837. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  838. Functions", John Wiley and Sons, 1996, chapter 6.
  839. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  840. .. [2] NIST Digital Library of Mathematical Functions.
  841. https://dlmf.nist.gov/10.29.E5
  842. Examples
  843. --------
  844. Compute the modified bessel function of the second kind of order 0 and
  845. its first two derivatives at 1.
  846. >>> from scipy.special import kvp
  847. >>> kvp(0, 1, 0), kvp(0, 1, 1), kvp(0, 1, 2)
  848. (0.42102443824070834, -0.6019072301972346, 1.0229316684379428)
  849. Compute the first derivative of the modified Bessel function of the second
  850. kind for several orders at 1 by providing an array for `v`.
  851. >>> kvp([0, 1, 2], 1, 1)
  852. array([-0.60190723, -1.02293167, -3.85158503])
  853. Compute the first derivative of the modified Bessel function of the
  854. second kind of order 0 at several points by providing an array for `z`.
  855. >>> import numpy as np
  856. >>> points = np.array([0.5, 1.5, 3.])
  857. >>> kvp(0, points, 1)
  858. array([-1.65644112, -0.2773878 , -0.04015643])
  859. Plot the modified bessel function of the second kind and its
  860. first three derivatives.
  861. >>> import matplotlib.pyplot as plt
  862. >>> x = np.linspace(0, 5, 1000)
  863. >>> fig, ax = plt.subplots()
  864. >>> ax.plot(x, kvp(1, x, 0), label=r"$K_1$")
  865. >>> ax.plot(x, kvp(1, x, 1), label=r"$K_1'$")
  866. >>> ax.plot(x, kvp(1, x, 2), label=r"$K_1''$")
  867. >>> ax.plot(x, kvp(1, x, 3), label=r"$K_1'''$")
  868. >>> ax.set_ylim(-2.5, 2.5)
  869. >>> plt.legend()
  870. >>> plt.show()
  871. """
  872. n = _nonneg_int_or_fail(n, 'n')
  873. if n == 0:
  874. return kv(v, z)
  875. else:
  876. return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1)
  877. def ivp(v, z, n=1):
  878. """Compute derivatives of modified Bessel functions of the first kind.
  879. Compute the nth derivative of the modified Bessel function `Iv`
  880. with respect to `z`.
  881. Parameters
  882. ----------
  883. v : array_like or float
  884. Order of Bessel function
  885. z : array_like
  886. Argument at which to evaluate the derivative; can be real or
  887. complex.
  888. n : int, default 1
  889. Order of derivative. For 0, returns the Bessel function `iv` itself.
  890. Returns
  891. -------
  892. scalar or ndarray
  893. nth derivative of the modified Bessel function.
  894. See Also
  895. --------
  896. iv
  897. Notes
  898. -----
  899. The derivative is computed using the relation DLFM 10.29.5 [2]_.
  900. References
  901. ----------
  902. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  903. Functions", John Wiley and Sons, 1996, chapter 6.
  904. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  905. .. [2] NIST Digital Library of Mathematical Functions.
  906. https://dlmf.nist.gov/10.29.E5
  907. Examples
  908. --------
  909. Compute the modified Bessel function of the first kind of order 0 and
  910. its first two derivatives at 1.
  911. >>> from scipy.special import ivp
  912. >>> ivp(0, 1, 0), ivp(0, 1, 1), ivp(0, 1, 2)
  913. (1.2660658777520084, 0.565159103992485, 0.7009067737595233)
  914. Compute the first derivative of the modified Bessel function of the first
  915. kind for several orders at 1 by providing an array for `v`.
  916. >>> ivp([0, 1, 2], 1, 1)
  917. array([0.5651591 , 0.70090677, 0.29366376])
  918. Compute the first derivative of the modified Bessel function of the
  919. first kind of order 0 at several points by providing an array for `z`.
  920. >>> import numpy as np
  921. >>> points = np.array([0., 1.5, 3.])
  922. >>> ivp(0, points, 1)
  923. array([0. , 0.98166643, 3.95337022])
  924. Plot the modified Bessel function of the first kind of order 1 and its
  925. first three derivatives.
  926. >>> import matplotlib.pyplot as plt
  927. >>> x = np.linspace(-5, 5, 1000)
  928. >>> fig, ax = plt.subplots()
  929. >>> ax.plot(x, ivp(1, x, 0), label=r"$I_1$")
  930. >>> ax.plot(x, ivp(1, x, 1), label=r"$I_1'$")
  931. >>> ax.plot(x, ivp(1, x, 2), label=r"$I_1''$")
  932. >>> ax.plot(x, ivp(1, x, 3), label=r"$I_1'''$")
  933. >>> plt.legend()
  934. >>> plt.show()
  935. """
  936. n = _nonneg_int_or_fail(n, 'n')
  937. if n == 0:
  938. return iv(v, z)
  939. else:
  940. return _bessel_diff_formula(v, z, n, iv, 1)
  941. def h1vp(v, z, n=1):
  942. """Compute derivatives of Hankel function H1v(z) with respect to `z`.
  943. Parameters
  944. ----------
  945. v : array_like
  946. Order of Hankel function
  947. z : array_like
  948. Argument at which to evaluate the derivative. Can be real or
  949. complex.
  950. n : int, default 1
  951. Order of derivative. For 0 returns the Hankel function `h1v` itself.
  952. Returns
  953. -------
  954. scalar or ndarray
  955. Values of the derivative of the Hankel function.
  956. See Also
  957. --------
  958. hankel1
  959. Notes
  960. -----
  961. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  962. References
  963. ----------
  964. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  965. Functions", John Wiley and Sons, 1996, chapter 5.
  966. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  967. .. [2] NIST Digital Library of Mathematical Functions.
  968. https://dlmf.nist.gov/10.6.E7
  969. Examples
  970. --------
  971. Compute the Hankel function of the first kind of order 0 and
  972. its first two derivatives at 1.
  973. >>> from scipy.special import h1vp
  974. >>> h1vp(0, 1, 0), h1vp(0, 1, 1), h1vp(0, 1, 2)
  975. ((0.7651976865579664+0.088256964215677j),
  976. (-0.44005058574493355+0.7812128213002889j),
  977. (-0.3251471008130329-0.8694697855159659j))
  978. Compute the first derivative of the Hankel function of the first kind
  979. for several orders at 1 by providing an array for `v`.
  980. >>> h1vp([0, 1, 2], 1, 1)
  981. array([-0.44005059+0.78121282j, 0.3251471 +0.86946979j,
  982. 0.21024362+2.52015239j])
  983. Compute the first derivative of the Hankel function of the first kind
  984. of order 0 at several points by providing an array for `z`.
  985. >>> import numpy as np
  986. >>> points = np.array([0.5, 1.5, 3.])
  987. >>> h1vp(0, points, 1)
  988. array([-0.24226846+1.47147239j, -0.55793651+0.41230863j,
  989. -0.33905896-0.32467442j])
  990. """
  991. n = _nonneg_int_or_fail(n, 'n')
  992. if n == 0:
  993. return hankel1(v, z)
  994. else:
  995. return _bessel_diff_formula(v, z, n, hankel1, -1)
  996. def h2vp(v, z, n=1):
  997. """Compute derivatives of Hankel function H2v(z) with respect to `z`.
  998. Parameters
  999. ----------
  1000. v : array_like
  1001. Order of Hankel function
  1002. z : array_like
  1003. Argument at which to evaluate the derivative. Can be real or
  1004. complex.
  1005. n : int, default 1
  1006. Order of derivative. For 0 returns the Hankel function `h2v` itself.
  1007. Returns
  1008. -------
  1009. scalar or ndarray
  1010. Values of the derivative of the Hankel function.
  1011. See Also
  1012. --------
  1013. hankel2
  1014. Notes
  1015. -----
  1016. The derivative is computed using the relation DLFM 10.6.7 [2]_.
  1017. References
  1018. ----------
  1019. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1020. Functions", John Wiley and Sons, 1996, chapter 5.
  1021. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1022. .. [2] NIST Digital Library of Mathematical Functions.
  1023. https://dlmf.nist.gov/10.6.E7
  1024. Examples
  1025. --------
  1026. Compute the Hankel function of the second kind of order 0 and
  1027. its first two derivatives at 1.
  1028. >>> from scipy.special import h2vp
  1029. >>> h2vp(0, 1, 0), h2vp(0, 1, 1), h2vp(0, 1, 2)
  1030. ((0.7651976865579664-0.088256964215677j),
  1031. (-0.44005058574493355-0.7812128213002889j),
  1032. (-0.3251471008130329+0.8694697855159659j))
  1033. Compute the first derivative of the Hankel function of the second kind
  1034. for several orders at 1 by providing an array for `v`.
  1035. >>> h2vp([0, 1, 2], 1, 1)
  1036. array([-0.44005059-0.78121282j, 0.3251471 -0.86946979j,
  1037. 0.21024362-2.52015239j])
  1038. Compute the first derivative of the Hankel function of the second kind
  1039. of order 0 at several points by providing an array for `z`.
  1040. >>> import numpy as np
  1041. >>> points = np.array([0.5, 1.5, 3.])
  1042. >>> h2vp(0, points, 1)
  1043. array([-0.24226846-1.47147239j, -0.55793651-0.41230863j,
  1044. -0.33905896+0.32467442j])
  1045. """
  1046. n = _nonneg_int_or_fail(n, 'n')
  1047. if n == 0:
  1048. return hankel2(v, z)
  1049. else:
  1050. return _bessel_diff_formula(v, z, n, hankel2, -1)
  1051. def riccati_jn(n, x):
  1052. r"""Compute Ricatti-Bessel function of the first kind and its derivative.
  1053. The Ricatti-Bessel function of the first kind is defined as :math:`x
  1054. j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first
  1055. kind of order :math:`n`.
  1056. This function computes the value and first derivative of the
  1057. Ricatti-Bessel function for all orders up to and including `n`.
  1058. Parameters
  1059. ----------
  1060. n : int
  1061. Maximum order of function to compute
  1062. x : float
  1063. Argument at which to evaluate
  1064. Returns
  1065. -------
  1066. jn : ndarray
  1067. Value of j0(x), ..., jn(x)
  1068. jnp : ndarray
  1069. First derivative j0'(x), ..., jn'(x)
  1070. Notes
  1071. -----
  1072. The computation is carried out via backward recurrence, using the
  1073. relation DLMF 10.51.1 [2]_.
  1074. Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
  1075. Jin [1]_.
  1076. References
  1077. ----------
  1078. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1079. Functions", John Wiley and Sons, 1996.
  1080. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1081. .. [2] NIST Digital Library of Mathematical Functions.
  1082. https://dlmf.nist.gov/10.51.E1
  1083. """
  1084. if not (isscalar(n) and isscalar(x)):
  1085. raise ValueError("arguments must be scalars.")
  1086. n = _nonneg_int_or_fail(n, 'n', strict=False)
  1087. if (n == 0):
  1088. n1 = 1
  1089. else:
  1090. n1 = n
  1091. nm, jn, jnp = _specfun.rctj(n1, x)
  1092. return jn[:(n+1)], jnp[:(n+1)]
  1093. def riccati_yn(n, x):
  1094. """Compute Ricatti-Bessel function of the second kind and its derivative.
  1095. The Ricatti-Bessel function of the second kind is defined as :math:`x
  1096. y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second
  1097. kind of order :math:`n`.
  1098. This function computes the value and first derivative of the function for
  1099. all orders up to and including `n`.
  1100. Parameters
  1101. ----------
  1102. n : int
  1103. Maximum order of function to compute
  1104. x : float
  1105. Argument at which to evaluate
  1106. Returns
  1107. -------
  1108. yn : ndarray
  1109. Value of y0(x), ..., yn(x)
  1110. ynp : ndarray
  1111. First derivative y0'(x), ..., yn'(x)
  1112. Notes
  1113. -----
  1114. The computation is carried out via ascending recurrence, using the
  1115. relation DLMF 10.51.1 [2]_.
  1116. Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
  1117. Jin [1]_.
  1118. References
  1119. ----------
  1120. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1121. Functions", John Wiley and Sons, 1996.
  1122. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1123. .. [2] NIST Digital Library of Mathematical Functions.
  1124. https://dlmf.nist.gov/10.51.E1
  1125. """
  1126. if not (isscalar(n) and isscalar(x)):
  1127. raise ValueError("arguments must be scalars.")
  1128. n = _nonneg_int_or_fail(n, 'n', strict=False)
  1129. if (n == 0):
  1130. n1 = 1
  1131. else:
  1132. n1 = n
  1133. nm, jn, jnp = _specfun.rcty(n1, x)
  1134. return jn[:(n+1)], jnp[:(n+1)]
  1135. def erf_zeros(nt):
  1136. """Compute the first nt zero in the first quadrant, ordered by absolute value.
  1137. Zeros in the other quadrants can be obtained by using the symmetries erf(-z) = erf(z) and
  1138. erf(conj(z)) = conj(erf(z)).
  1139. Parameters
  1140. ----------
  1141. nt : int
  1142. The number of zeros to compute
  1143. Returns
  1144. -------
  1145. The locations of the zeros of erf : ndarray (complex)
  1146. Complex values at which zeros of erf(z)
  1147. Examples
  1148. --------
  1149. >>> from scipy import special
  1150. >>> special.erf_zeros(1)
  1151. array([1.45061616+1.880943j])
  1152. Check that erf is (close to) zero for the value returned by erf_zeros
  1153. >>> special.erf(special.erf_zeros(1))
  1154. array([4.95159469e-14-1.16407394e-16j])
  1155. References
  1156. ----------
  1157. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1158. Functions", John Wiley and Sons, 1996.
  1159. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1160. """
  1161. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  1162. raise ValueError("Argument must be positive scalar integer.")
  1163. return _specfun.cerzo(nt)
  1164. def fresnelc_zeros(nt):
  1165. """Compute nt complex zeros of cosine Fresnel integral C(z).
  1166. References
  1167. ----------
  1168. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1169. Functions", John Wiley and Sons, 1996.
  1170. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1171. """
  1172. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  1173. raise ValueError("Argument must be positive scalar integer.")
  1174. return _specfun.fcszo(1, nt)
  1175. def fresnels_zeros(nt):
  1176. """Compute nt complex zeros of sine Fresnel integral S(z).
  1177. References
  1178. ----------
  1179. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1180. Functions", John Wiley and Sons, 1996.
  1181. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1182. """
  1183. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  1184. raise ValueError("Argument must be positive scalar integer.")
  1185. return _specfun.fcszo(2, nt)
  1186. def fresnel_zeros(nt):
  1187. """Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
  1188. References
  1189. ----------
  1190. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1191. Functions", John Wiley and Sons, 1996.
  1192. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1193. """
  1194. if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
  1195. raise ValueError("Argument must be positive scalar integer.")
  1196. return _specfun.fcszo(2, nt), _specfun.fcszo(1, nt)
  1197. def assoc_laguerre(x, n, k=0.0):
  1198. """Compute the generalized (associated) Laguerre polynomial of degree n and order k.
  1199. The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``,
  1200. with weighting function ``exp(-x) * x**k`` with ``k > -1``.
  1201. Notes
  1202. -----
  1203. `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with
  1204. reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
  1205. """
  1206. return _ufuncs.eval_genlaguerre(n, k, x)
  1207. digamma = psi
  1208. def polygamma(n, x):
  1209. r"""Polygamma functions.
  1210. Defined as :math:`\psi^{(n)}(x)` where :math:`\psi` is the
  1211. `digamma` function. See [dlmf]_ for details.
  1212. Parameters
  1213. ----------
  1214. n : array_like
  1215. The order of the derivative of the digamma function; must be
  1216. integral
  1217. x : array_like
  1218. Real valued input
  1219. Returns
  1220. -------
  1221. ndarray
  1222. Function results
  1223. See Also
  1224. --------
  1225. digamma
  1226. References
  1227. ----------
  1228. .. [dlmf] NIST, Digital Library of Mathematical Functions,
  1229. https://dlmf.nist.gov/5.15
  1230. Examples
  1231. --------
  1232. >>> from scipy import special
  1233. >>> x = [2, 3, 25.5]
  1234. >>> special.polygamma(1, x)
  1235. array([ 0.64493407, 0.39493407, 0.03999467])
  1236. >>> special.polygamma(0, x) == special.psi(x)
  1237. array([ True, True, True], dtype=bool)
  1238. """
  1239. n, x = asarray(n), asarray(x)
  1240. fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x)
  1241. return where(n == 0, psi(x), fac2)
  1242. def mathieu_even_coef(m, q):
  1243. r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
  1244. The Fourier series of the even solutions of the Mathieu differential
  1245. equation are of the form
  1246. .. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz
  1247. .. math:: \mathrm{ce}_{2n+1}(z, q) = \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z
  1248. This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even
  1249. input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input
  1250. m=2n+1.
  1251. Parameters
  1252. ----------
  1253. m : int
  1254. Order of Mathieu functions. Must be non-negative.
  1255. q : float (>=0)
  1256. Parameter of Mathieu functions. Must be non-negative.
  1257. Returns
  1258. -------
  1259. Ak : ndarray
  1260. Even or odd Fourier coefficients, corresponding to even or odd m.
  1261. References
  1262. ----------
  1263. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1264. Functions", John Wiley and Sons, 1996.
  1265. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1266. .. [2] NIST Digital Library of Mathematical Functions
  1267. https://dlmf.nist.gov/28.4#i
  1268. """
  1269. if not (isscalar(m) and isscalar(q)):
  1270. raise ValueError("m and q must be scalars.")
  1271. if (q < 0):
  1272. raise ValueError("q >=0")
  1273. if (m != floor(m)) or (m < 0):
  1274. raise ValueError("m must be an integer >=0.")
  1275. if (q <= 1):
  1276. qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
  1277. else:
  1278. qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
  1279. km = int(qm + 0.5*m)
  1280. if km > 251:
  1281. warnings.warn("Too many predicted coefficients.", RuntimeWarning, 2)
  1282. kd = 1
  1283. m = int(floor(m))
  1284. if m % 2:
  1285. kd = 2
  1286. a = mathieu_a(m, q)
  1287. fc = _specfun.fcoef(kd, m, q, a)
  1288. return fc[:km]
  1289. def mathieu_odd_coef(m, q):
  1290. r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
  1291. The Fourier series of the odd solutions of the Mathieu differential
  1292. equation are of the form
  1293. .. math:: \mathrm{se}_{2n+1}(z, q) = \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
  1294. .. math:: \mathrm{se}_{2n+2}(z, q) = \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
  1295. This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
  1296. input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
  1297. input m=2n+1.
  1298. Parameters
  1299. ----------
  1300. m : int
  1301. Order of Mathieu functions. Must be non-negative.
  1302. q : float (>=0)
  1303. Parameter of Mathieu functions. Must be non-negative.
  1304. Returns
  1305. -------
  1306. Bk : ndarray
  1307. Even or odd Fourier coefficients, corresponding to even or odd m.
  1308. References
  1309. ----------
  1310. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1311. Functions", John Wiley and Sons, 1996.
  1312. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1313. """
  1314. if not (isscalar(m) and isscalar(q)):
  1315. raise ValueError("m and q must be scalars.")
  1316. if (q < 0):
  1317. raise ValueError("q >=0")
  1318. if (m != floor(m)) or (m <= 0):
  1319. raise ValueError("m must be an integer > 0")
  1320. if (q <= 1):
  1321. qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
  1322. else:
  1323. qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
  1324. km = int(qm + 0.5*m)
  1325. if km > 251:
  1326. warnings.warn("Too many predicted coefficients.", RuntimeWarning, 2)
  1327. kd = 4
  1328. m = int(floor(m))
  1329. if m % 2:
  1330. kd = 3
  1331. b = mathieu_b(m, q)
  1332. fc = _specfun.fcoef(kd, m, q, b)
  1333. return fc[:km]
  1334. def lpmn(m, n, z):
  1335. """Sequence of associated Legendre functions of the first kind.
  1336. Computes the associated Legendre function of the first kind of order m and
  1337. degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
  1338. Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
  1339. ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
  1340. This function takes a real argument ``z``. For complex arguments ``z``
  1341. use clpmn instead.
  1342. Parameters
  1343. ----------
  1344. m : int
  1345. ``|m| <= n``; the order of the Legendre function.
  1346. n : int
  1347. where ``n >= 0``; the degree of the Legendre function. Often
  1348. called ``l`` (lower case L) in descriptions of the associated
  1349. Legendre function
  1350. z : float
  1351. Input value.
  1352. Returns
  1353. -------
  1354. Pmn_z : (m+1, n+1) array
  1355. Values for all orders 0..m and degrees 0..n
  1356. Pmn_d_z : (m+1, n+1) array
  1357. Derivatives for all orders 0..m and degrees 0..n
  1358. See Also
  1359. --------
  1360. clpmn: associated Legendre functions of the first kind for complex z
  1361. Notes
  1362. -----
  1363. In the interval (-1, 1), Ferrer's function of the first kind is
  1364. returned. The phase convention used for the intervals (1, inf)
  1365. and (-inf, -1) is such that the result is always real.
  1366. References
  1367. ----------
  1368. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1369. Functions", John Wiley and Sons, 1996.
  1370. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1371. .. [2] NIST Digital Library of Mathematical Functions
  1372. https://dlmf.nist.gov/14.3
  1373. """
  1374. if not isscalar(m) or (abs(m) > n):
  1375. raise ValueError("m must be <= n.")
  1376. if not isscalar(n) or (n < 0):
  1377. raise ValueError("n must be a non-negative integer.")
  1378. if not isscalar(z):
  1379. raise ValueError("z must be scalar.")
  1380. if iscomplex(z):
  1381. raise ValueError("Argument must be real. Use clpmn instead.")
  1382. if (m < 0):
  1383. mp = -m
  1384. mf, nf = mgrid[0:mp+1, 0:n+1]
  1385. with _ufuncs.errstate(all='ignore'):
  1386. if abs(z) < 1:
  1387. # Ferrer function; DLMF 14.9.3
  1388. fixarr = where(mf > nf, 0.0,
  1389. (-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
  1390. else:
  1391. # Match to clpmn; DLMF 14.9.13
  1392. fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
  1393. else:
  1394. mp = m
  1395. p, pd = _specfun.lpmn(mp, n, z)
  1396. if (m < 0):
  1397. p = p * fixarr
  1398. pd = pd * fixarr
  1399. return p, pd
  1400. def clpmn(m, n, z, type=3):
  1401. """Associated Legendre function of the first kind for complex arguments.
  1402. Computes the associated Legendre function of the first kind of order m and
  1403. degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
  1404. Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
  1405. ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
  1406. Parameters
  1407. ----------
  1408. m : int
  1409. ``|m| <= n``; the order of the Legendre function.
  1410. n : int
  1411. where ``n >= 0``; the degree of the Legendre function. Often
  1412. called ``l`` (lower case L) in descriptions of the associated
  1413. Legendre function
  1414. z : float or complex
  1415. Input value.
  1416. type : int, optional
  1417. takes values 2 or 3
  1418. 2: cut on the real axis ``|x| > 1``
  1419. 3: cut on the real axis ``-1 < x < 1`` (default)
  1420. Returns
  1421. -------
  1422. Pmn_z : (m+1, n+1) array
  1423. Values for all orders ``0..m`` and degrees ``0..n``
  1424. Pmn_d_z : (m+1, n+1) array
  1425. Derivatives for all orders ``0..m`` and degrees ``0..n``
  1426. See Also
  1427. --------
  1428. lpmn: associated Legendre functions of the first kind for real z
  1429. Notes
  1430. -----
  1431. By default, i.e. for ``type=3``, phase conventions are chosen according
  1432. to [1]_ such that the function is analytic. The cut lies on the interval
  1433. (-1, 1). Approaching the cut from above or below in general yields a phase
  1434. factor with respect to Ferrer's function of the first kind
  1435. (cf. `lpmn`).
  1436. For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values
  1437. on the interval (-1, 1) in the complex plane yields Ferrer's function
  1438. of the first kind.
  1439. References
  1440. ----------
  1441. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1442. Functions", John Wiley and Sons, 1996.
  1443. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1444. .. [2] NIST Digital Library of Mathematical Functions
  1445. https://dlmf.nist.gov/14.21
  1446. """
  1447. if not isscalar(m) or (abs(m) > n):
  1448. raise ValueError("m must be <= n.")
  1449. if not isscalar(n) or (n < 0):
  1450. raise ValueError("n must be a non-negative integer.")
  1451. if not isscalar(z):
  1452. raise ValueError("z must be scalar.")
  1453. if not (type == 2 or type == 3):
  1454. raise ValueError("type must be either 2 or 3.")
  1455. if (m < 0):
  1456. mp = -m
  1457. mf, nf = mgrid[0:mp+1, 0:n+1]
  1458. with _ufuncs.errstate(all='ignore'):
  1459. if type == 2:
  1460. fixarr = where(mf > nf, 0.0,
  1461. (-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
  1462. else:
  1463. fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
  1464. else:
  1465. mp = m
  1466. p, pd = _specfun.clpmn(mp, n, real(z), imag(z), type)
  1467. if (m < 0):
  1468. p = p * fixarr
  1469. pd = pd * fixarr
  1470. return p, pd
  1471. def lqmn(m, n, z):
  1472. """Sequence of associated Legendre functions of the second kind.
  1473. Computes the associated Legendre function of the second kind of order m and
  1474. degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
  1475. Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
  1476. ``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
  1477. Parameters
  1478. ----------
  1479. m : int
  1480. ``|m| <= n``; the order of the Legendre function.
  1481. n : int
  1482. where ``n >= 0``; the degree of the Legendre function. Often
  1483. called ``l`` (lower case L) in descriptions of the associated
  1484. Legendre function
  1485. z : complex
  1486. Input value.
  1487. Returns
  1488. -------
  1489. Qmn_z : (m+1, n+1) array
  1490. Values for all orders 0..m and degrees 0..n
  1491. Qmn_d_z : (m+1, n+1) array
  1492. Derivatives for all orders 0..m and degrees 0..n
  1493. References
  1494. ----------
  1495. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1496. Functions", John Wiley and Sons, 1996.
  1497. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1498. """
  1499. if not isscalar(m) or (m < 0):
  1500. raise ValueError("m must be a non-negative integer.")
  1501. if not isscalar(n) or (n < 0):
  1502. raise ValueError("n must be a non-negative integer.")
  1503. if not isscalar(z):
  1504. raise ValueError("z must be scalar.")
  1505. m = int(m)
  1506. n = int(n)
  1507. # Ensure neither m nor n == 0
  1508. mm = max(1, m)
  1509. nn = max(1, n)
  1510. if iscomplex(z):
  1511. q, qd = _specfun.clqmn(mm, nn, z)
  1512. else:
  1513. q, qd = _specfun.lqmn(mm, nn, z)
  1514. return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)]
  1515. def bernoulli(n):
  1516. """Bernoulli numbers B0..Bn (inclusive).
  1517. Parameters
  1518. ----------
  1519. n : int
  1520. Indicated the number of terms in the Bernoulli series to generate.
  1521. Returns
  1522. -------
  1523. ndarray
  1524. The Bernoulli numbers ``[B(0), B(1), ..., B(n)]``.
  1525. References
  1526. ----------
  1527. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1528. Functions", John Wiley and Sons, 1996.
  1529. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1530. .. [2] "Bernoulli number", Wikipedia, https://en.wikipedia.org/wiki/Bernoulli_number
  1531. Examples
  1532. --------
  1533. >>> import numpy as np
  1534. >>> from scipy.special import bernoulli, zeta
  1535. >>> bernoulli(4)
  1536. array([ 1. , -0.5 , 0.16666667, 0. , -0.03333333])
  1537. The Wikipedia article ([2]_) points out the relationship between the
  1538. Bernoulli numbers and the zeta function, ``B_n^+ = -n * zeta(1 - n)``
  1539. for ``n > 0``:
  1540. >>> n = np.arange(1, 5)
  1541. >>> -n * zeta(1 - n)
  1542. array([ 0.5 , 0.16666667, -0. , -0.03333333])
  1543. Note that, in the notation used in the wikipedia article,
  1544. `bernoulli` computes ``B_n^-`` (i.e. it used the convention that
  1545. ``B_1`` is -1/2). The relation given above is for ``B_n^+``, so the
  1546. sign of 0.5 does not match the output of ``bernoulli(4)``.
  1547. """
  1548. if not isscalar(n) or (n < 0):
  1549. raise ValueError("n must be a non-negative integer.")
  1550. n = int(n)
  1551. if (n < 2):
  1552. n1 = 2
  1553. else:
  1554. n1 = n
  1555. return _specfun.bernob(int(n1))[:(n+1)]
  1556. def euler(n):
  1557. """Euler numbers E(0), E(1), ..., E(n).
  1558. The Euler numbers [1]_ are also known as the secant numbers.
  1559. Because ``euler(n)`` returns floating point values, it does not give
  1560. exact values for large `n`. The first inexact value is E(22).
  1561. Parameters
  1562. ----------
  1563. n : int
  1564. The highest index of the Euler number to be returned.
  1565. Returns
  1566. -------
  1567. ndarray
  1568. The Euler numbers [E(0), E(1), ..., E(n)].
  1569. The odd Euler numbers, which are all zero, are included.
  1570. References
  1571. ----------
  1572. .. [1] Sequence A122045, The On-Line Encyclopedia of Integer Sequences,
  1573. https://oeis.org/A122045
  1574. .. [2] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1575. Functions", John Wiley and Sons, 1996.
  1576. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1577. Examples
  1578. --------
  1579. >>> import numpy as np
  1580. >>> from scipy.special import euler
  1581. >>> euler(6)
  1582. array([ 1., 0., -1., 0., 5., 0., -61.])
  1583. >>> euler(13).astype(np.int64)
  1584. array([ 1, 0, -1, 0, 5, 0, -61,
  1585. 0, 1385, 0, -50521, 0, 2702765, 0])
  1586. >>> euler(22)[-1] # Exact value of E(22) is -69348874393137901.
  1587. -69348874393137976.0
  1588. """
  1589. if not isscalar(n) or (n < 0):
  1590. raise ValueError("n must be a non-negative integer.")
  1591. n = int(n)
  1592. if (n < 2):
  1593. n1 = 2
  1594. else:
  1595. n1 = n
  1596. return _specfun.eulerb(n1)[:(n+1)]
  1597. def lpn(n, z):
  1598. """Legendre function of the first kind.
  1599. Compute sequence of Legendre functions of the first kind (polynomials),
  1600. Pn(z) and derivatives for all degrees from 0 to n (inclusive).
  1601. See also special.legendre for polynomial class.
  1602. References
  1603. ----------
  1604. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1605. Functions", John Wiley and Sons, 1996.
  1606. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1607. """
  1608. if not (isscalar(n) and isscalar(z)):
  1609. raise ValueError("arguments must be scalars.")
  1610. n = _nonneg_int_or_fail(n, 'n', strict=False)
  1611. if (n < 1):
  1612. n1 = 1
  1613. else:
  1614. n1 = n
  1615. if iscomplex(z):
  1616. pn, pd = _specfun.clpn(n1, z)
  1617. else:
  1618. pn, pd = _specfun.lpn(n1, z)
  1619. return pn[:(n+1)], pd[:(n+1)]
  1620. def lqn(n, z):
  1621. """Legendre function of the second kind.
  1622. Compute sequence of Legendre functions of the second kind, Qn(z) and
  1623. derivatives for all degrees from 0 to n (inclusive).
  1624. References
  1625. ----------
  1626. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1627. Functions", John Wiley and Sons, 1996.
  1628. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1629. """
  1630. if not (isscalar(n) and isscalar(z)):
  1631. raise ValueError("arguments must be scalars.")
  1632. n = _nonneg_int_or_fail(n, 'n', strict=False)
  1633. if (n < 1):
  1634. n1 = 1
  1635. else:
  1636. n1 = n
  1637. if iscomplex(z):
  1638. qn, qd = _specfun.clqn(n1, z)
  1639. else:
  1640. qn, qd = _specfun.lqnb(n1, z)
  1641. return qn[:(n+1)], qd[:(n+1)]
  1642. def ai_zeros(nt):
  1643. """
  1644. Compute `nt` zeros and values of the Airy function Ai and its derivative.
  1645. Computes the first `nt` zeros, `a`, of the Airy function Ai(x);
  1646. first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x);
  1647. the corresponding values Ai(a');
  1648. and the corresponding values Ai'(a).
  1649. Parameters
  1650. ----------
  1651. nt : int
  1652. Number of zeros to compute
  1653. Returns
  1654. -------
  1655. a : ndarray
  1656. First `nt` zeros of Ai(x)
  1657. ap : ndarray
  1658. First `nt` zeros of Ai'(x)
  1659. ai : ndarray
  1660. Values of Ai(x) evaluated at first `nt` zeros of Ai'(x)
  1661. aip : ndarray
  1662. Values of Ai'(x) evaluated at first `nt` zeros of Ai(x)
  1663. Examples
  1664. --------
  1665. >>> from scipy import special
  1666. >>> a, ap, ai, aip = special.ai_zeros(3)
  1667. >>> a
  1668. array([-2.33810741, -4.08794944, -5.52055983])
  1669. >>> ap
  1670. array([-1.01879297, -3.24819758, -4.82009921])
  1671. >>> ai
  1672. array([ 0.53565666, -0.41901548, 0.38040647])
  1673. >>> aip
  1674. array([ 0.70121082, -0.80311137, 0.86520403])
  1675. References
  1676. ----------
  1677. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1678. Functions", John Wiley and Sons, 1996.
  1679. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1680. """
  1681. kf = 1
  1682. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1683. raise ValueError("nt must be a positive integer scalar.")
  1684. return _specfun.airyzo(nt, kf)
  1685. def bi_zeros(nt):
  1686. """
  1687. Compute `nt` zeros and values of the Airy function Bi and its derivative.
  1688. Computes the first `nt` zeros, b, of the Airy function Bi(x);
  1689. first `nt` zeros, b', of the derivative of the Airy function Bi'(x);
  1690. the corresponding values Bi(b');
  1691. and the corresponding values Bi'(b).
  1692. Parameters
  1693. ----------
  1694. nt : int
  1695. Number of zeros to compute
  1696. Returns
  1697. -------
  1698. b : ndarray
  1699. First `nt` zeros of Bi(x)
  1700. bp : ndarray
  1701. First `nt` zeros of Bi'(x)
  1702. bi : ndarray
  1703. Values of Bi(x) evaluated at first `nt` zeros of Bi'(x)
  1704. bip : ndarray
  1705. Values of Bi'(x) evaluated at first `nt` zeros of Bi(x)
  1706. Examples
  1707. --------
  1708. >>> from scipy import special
  1709. >>> b, bp, bi, bip = special.bi_zeros(3)
  1710. >>> b
  1711. array([-1.17371322, -3.2710933 , -4.83073784])
  1712. >>> bp
  1713. array([-2.29443968, -4.07315509, -5.51239573])
  1714. >>> bi
  1715. array([-0.45494438, 0.39652284, -0.36796916])
  1716. >>> bip
  1717. array([ 0.60195789, -0.76031014, 0.83699101])
  1718. References
  1719. ----------
  1720. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1721. Functions", John Wiley and Sons, 1996.
  1722. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1723. """
  1724. kf = 2
  1725. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1726. raise ValueError("nt must be a positive integer scalar.")
  1727. return _specfun.airyzo(nt, kf)
  1728. def lmbda(v, x):
  1729. r"""Jahnke-Emden Lambda function, Lambdav(x).
  1730. This function is defined as [2]_,
  1731. .. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v},
  1732. where :math:`\Gamma` is the gamma function and :math:`J_v` is the
  1733. Bessel function of the first kind.
  1734. Parameters
  1735. ----------
  1736. v : float
  1737. Order of the Lambda function
  1738. x : float
  1739. Value at which to evaluate the function and derivatives
  1740. Returns
  1741. -------
  1742. vl : ndarray
  1743. Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1744. dl : ndarray
  1745. Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1746. References
  1747. ----------
  1748. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1749. Functions", John Wiley and Sons, 1996.
  1750. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1751. .. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and
  1752. Curves" (4th ed.), Dover, 1945
  1753. """
  1754. if not (isscalar(v) and isscalar(x)):
  1755. raise ValueError("arguments must be scalars.")
  1756. if (v < 0):
  1757. raise ValueError("argument must be > 0.")
  1758. n = int(v)
  1759. v0 = v - n
  1760. if (n < 1):
  1761. n1 = 1
  1762. else:
  1763. n1 = n
  1764. v1 = n1 + v0
  1765. if (v != floor(v)):
  1766. vm, vl, dl = _specfun.lamv(v1, x)
  1767. else:
  1768. vm, vl, dl = _specfun.lamn(v1, x)
  1769. return vl[:(n+1)], dl[:(n+1)]
  1770. def pbdv_seq(v, x):
  1771. """Parabolic cylinder functions Dv(x) and derivatives.
  1772. Parameters
  1773. ----------
  1774. v : float
  1775. Order of the parabolic cylinder function
  1776. x : float
  1777. Value at which to evaluate the function and derivatives
  1778. Returns
  1779. -------
  1780. dv : ndarray
  1781. Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1782. dp : ndarray
  1783. Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1784. References
  1785. ----------
  1786. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1787. Functions", John Wiley and Sons, 1996, chapter 13.
  1788. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1789. """
  1790. if not (isscalar(v) and isscalar(x)):
  1791. raise ValueError("arguments must be scalars.")
  1792. n = int(v)
  1793. v0 = v-n
  1794. if (n < 1):
  1795. n1 = 1
  1796. else:
  1797. n1 = n
  1798. v1 = n1 + v0
  1799. dv, dp, pdf, pdd = _specfun.pbdv(v1, x)
  1800. return dv[:n1+1], dp[:n1+1]
  1801. def pbvv_seq(v, x):
  1802. """Parabolic cylinder functions Vv(x) and derivatives.
  1803. Parameters
  1804. ----------
  1805. v : float
  1806. Order of the parabolic cylinder function
  1807. x : float
  1808. Value at which to evaluate the function and derivatives
  1809. Returns
  1810. -------
  1811. dv : ndarray
  1812. Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1813. dp : ndarray
  1814. Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
  1815. References
  1816. ----------
  1817. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1818. Functions", John Wiley and Sons, 1996, chapter 13.
  1819. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1820. """
  1821. if not (isscalar(v) and isscalar(x)):
  1822. raise ValueError("arguments must be scalars.")
  1823. n = int(v)
  1824. v0 = v-n
  1825. if (n <= 1):
  1826. n1 = 1
  1827. else:
  1828. n1 = n
  1829. v1 = n1 + v0
  1830. dv, dp, pdf, pdd = _specfun.pbvv(v1, x)
  1831. return dv[:n1+1], dp[:n1+1]
  1832. def pbdn_seq(n, z):
  1833. """Parabolic cylinder functions Dn(z) and derivatives.
  1834. Parameters
  1835. ----------
  1836. n : int
  1837. Order of the parabolic cylinder function
  1838. z : complex
  1839. Value at which to evaluate the function and derivatives
  1840. Returns
  1841. -------
  1842. dv : ndarray
  1843. Values of D_i(z), for i=0, ..., i=n.
  1844. dp : ndarray
  1845. Derivatives D_i'(z), for i=0, ..., i=n.
  1846. References
  1847. ----------
  1848. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1849. Functions", John Wiley and Sons, 1996, chapter 13.
  1850. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1851. """
  1852. if not (isscalar(n) and isscalar(z)):
  1853. raise ValueError("arguments must be scalars.")
  1854. if (floor(n) != n):
  1855. raise ValueError("n must be an integer.")
  1856. if (abs(n) <= 1):
  1857. n1 = 1
  1858. else:
  1859. n1 = n
  1860. cpb, cpd = _specfun.cpbdn(n1, z)
  1861. return cpb[:n1+1], cpd[:n1+1]
  1862. def ber_zeros(nt):
  1863. """Compute nt zeros of the Kelvin function ber.
  1864. Parameters
  1865. ----------
  1866. nt : int
  1867. Number of zeros to compute. Must be positive.
  1868. Returns
  1869. -------
  1870. ndarray
  1871. First `nt` zeros of the Kelvin function.
  1872. See Also
  1873. --------
  1874. ber
  1875. References
  1876. ----------
  1877. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1878. Functions", John Wiley and Sons, 1996.
  1879. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1880. """
  1881. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1882. raise ValueError("nt must be positive integer scalar.")
  1883. return _specfun.klvnzo(nt, 1)
  1884. def bei_zeros(nt):
  1885. """Compute nt zeros of the Kelvin function bei.
  1886. Parameters
  1887. ----------
  1888. nt : int
  1889. Number of zeros to compute. Must be positive.
  1890. Returns
  1891. -------
  1892. ndarray
  1893. First `nt` zeros of the Kelvin function.
  1894. See Also
  1895. --------
  1896. bei
  1897. References
  1898. ----------
  1899. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1900. Functions", John Wiley and Sons, 1996.
  1901. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1902. """
  1903. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1904. raise ValueError("nt must be positive integer scalar.")
  1905. return _specfun.klvnzo(nt, 2)
  1906. def ker_zeros(nt):
  1907. """Compute nt zeros of the Kelvin function ker.
  1908. Parameters
  1909. ----------
  1910. nt : int
  1911. Number of zeros to compute. Must be positive.
  1912. Returns
  1913. -------
  1914. ndarray
  1915. First `nt` zeros of the Kelvin function.
  1916. See Also
  1917. --------
  1918. ker
  1919. References
  1920. ----------
  1921. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1922. Functions", John Wiley and Sons, 1996.
  1923. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1924. """
  1925. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1926. raise ValueError("nt must be positive integer scalar.")
  1927. return _specfun.klvnzo(nt, 3)
  1928. def kei_zeros(nt):
  1929. """Compute nt zeros of the Kelvin function kei.
  1930. Parameters
  1931. ----------
  1932. nt : int
  1933. Number of zeros to compute. Must be positive.
  1934. Returns
  1935. -------
  1936. ndarray
  1937. First `nt` zeros of the Kelvin function.
  1938. See Also
  1939. --------
  1940. kei
  1941. References
  1942. ----------
  1943. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1944. Functions", John Wiley and Sons, 1996.
  1945. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1946. """
  1947. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1948. raise ValueError("nt must be positive integer scalar.")
  1949. return _specfun.klvnzo(nt, 4)
  1950. def berp_zeros(nt):
  1951. """Compute nt zeros of the derivative of the Kelvin function ber.
  1952. Parameters
  1953. ----------
  1954. nt : int
  1955. Number of zeros to compute. Must be positive.
  1956. Returns
  1957. -------
  1958. ndarray
  1959. First `nt` zeros of the derivative of the Kelvin function.
  1960. See Also
  1961. --------
  1962. ber, berp
  1963. References
  1964. ----------
  1965. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1966. Functions", John Wiley and Sons, 1996.
  1967. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1968. """
  1969. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1970. raise ValueError("nt must be positive integer scalar.")
  1971. return _specfun.klvnzo(nt, 5)
  1972. def beip_zeros(nt):
  1973. """Compute nt zeros of the derivative of the Kelvin function bei.
  1974. Parameters
  1975. ----------
  1976. nt : int
  1977. Number of zeros to compute. Must be positive.
  1978. Returns
  1979. -------
  1980. ndarray
  1981. First `nt` zeros of the derivative of the Kelvin function.
  1982. See Also
  1983. --------
  1984. bei, beip
  1985. References
  1986. ----------
  1987. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  1988. Functions", John Wiley and Sons, 1996.
  1989. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  1990. """
  1991. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  1992. raise ValueError("nt must be positive integer scalar.")
  1993. return _specfun.klvnzo(nt, 6)
  1994. def kerp_zeros(nt):
  1995. """Compute nt zeros of the derivative of the Kelvin function ker.
  1996. Parameters
  1997. ----------
  1998. nt : int
  1999. Number of zeros to compute. Must be positive.
  2000. Returns
  2001. -------
  2002. ndarray
  2003. First `nt` zeros of the derivative of the Kelvin function.
  2004. See Also
  2005. --------
  2006. ker, kerp
  2007. References
  2008. ----------
  2009. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  2010. Functions", John Wiley and Sons, 1996.
  2011. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  2012. """
  2013. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  2014. raise ValueError("nt must be positive integer scalar.")
  2015. return _specfun.klvnzo(nt, 7)
  2016. def keip_zeros(nt):
  2017. """Compute nt zeros of the derivative of the Kelvin function kei.
  2018. Parameters
  2019. ----------
  2020. nt : int
  2021. Number of zeros to compute. Must be positive.
  2022. Returns
  2023. -------
  2024. ndarray
  2025. First `nt` zeros of the derivative of the Kelvin function.
  2026. See Also
  2027. --------
  2028. kei, keip
  2029. References
  2030. ----------
  2031. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  2032. Functions", John Wiley and Sons, 1996.
  2033. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  2034. """
  2035. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  2036. raise ValueError("nt must be positive integer scalar.")
  2037. return _specfun.klvnzo(nt, 8)
  2038. def kelvin_zeros(nt):
  2039. """Compute nt zeros of all Kelvin functions.
  2040. Returned in a length-8 tuple of arrays of length nt. The tuple contains
  2041. the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei').
  2042. References
  2043. ----------
  2044. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  2045. Functions", John Wiley and Sons, 1996.
  2046. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  2047. """
  2048. if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
  2049. raise ValueError("nt must be positive integer scalar.")
  2050. return (_specfun.klvnzo(nt, 1),
  2051. _specfun.klvnzo(nt, 2),
  2052. _specfun.klvnzo(nt, 3),
  2053. _specfun.klvnzo(nt, 4),
  2054. _specfun.klvnzo(nt, 5),
  2055. _specfun.klvnzo(nt, 6),
  2056. _specfun.klvnzo(nt, 7),
  2057. _specfun.klvnzo(nt, 8))
  2058. def pro_cv_seq(m, n, c):
  2059. """Characteristic values for prolate spheroidal wave functions.
  2060. Compute a sequence of characteristic values for the prolate
  2061. spheroidal wave functions for mode m and n'=m..n and spheroidal
  2062. parameter c.
  2063. References
  2064. ----------
  2065. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  2066. Functions", John Wiley and Sons, 1996.
  2067. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  2068. """
  2069. if not (isscalar(m) and isscalar(n) and isscalar(c)):
  2070. raise ValueError("Arguments must be scalars.")
  2071. if (n != floor(n)) or (m != floor(m)):
  2072. raise ValueError("Modes must be integers.")
  2073. if (n-m > 199):
  2074. raise ValueError("Difference between n and m is too large.")
  2075. maxL = n-m+1
  2076. return _specfun.segv(m, n, c, 1)[1][:maxL]
  2077. def obl_cv_seq(m, n, c):
  2078. """Characteristic values for oblate spheroidal wave functions.
  2079. Compute a sequence of characteristic values for the oblate
  2080. spheroidal wave functions for mode m and n'=m..n and spheroidal
  2081. parameter c.
  2082. References
  2083. ----------
  2084. .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
  2085. Functions", John Wiley and Sons, 1996.
  2086. https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
  2087. """
  2088. if not (isscalar(m) and isscalar(n) and isscalar(c)):
  2089. raise ValueError("Arguments must be scalars.")
  2090. if (n != floor(n)) or (m != floor(m)):
  2091. raise ValueError("Modes must be integers.")
  2092. if (n-m > 199):
  2093. raise ValueError("Difference between n and m is too large.")
  2094. maxL = n-m+1
  2095. return _specfun.segv(m, n, c, -1)[1][:maxL]
  2096. def comb(N, k, exact=False, repetition=False, legacy=True):
  2097. """The number of combinations of N things taken k at a time.
  2098. This is often expressed as "N choose k".
  2099. Parameters
  2100. ----------
  2101. N : int, ndarray
  2102. Number of things.
  2103. k : int, ndarray
  2104. Number of elements taken.
  2105. exact : bool, optional
  2106. For integers, if `exact` is False, then floating point precision is
  2107. used, otherwise the result is computed exactly. For non-integers, if
  2108. `exact` is True, the inputs are currently cast to integers, though
  2109. this behavior is deprecated (see below).
  2110. repetition : bool, optional
  2111. If `repetition` is True, then the number of combinations with
  2112. repetition is computed.
  2113. legacy : bool, optional
  2114. If `legacy` is True and `exact` is True, then non-integral arguments
  2115. are cast to ints; if `legacy` is False, the result for non-integral
  2116. arguments is unaffected by the value of `exact`.
  2117. .. deprecated:: 1.9.0
  2118. Non-integer arguments are currently being cast to integers when
  2119. `exact=True`. This behaviour is deprecated and the default will
  2120. change to avoid the cast in SciPy 1.11.0. To opt into the future
  2121. behavior set `legacy=False`. If you want to keep the
  2122. argument-casting but silence this warning, cast your inputs
  2123. directly, e.g. ``comb(int(your_N), int(your_k), exact=True)``.
  2124. Returns
  2125. -------
  2126. val : int, float, ndarray
  2127. The total number of combinations.
  2128. See Also
  2129. --------
  2130. binom : Binomial coefficient considered as a function of two real
  2131. variables.
  2132. Notes
  2133. -----
  2134. - Array arguments accepted only for exact=False case.
  2135. - If N < 0, or k < 0, then 0 is returned.
  2136. - If k > N and repetition=False, then 0 is returned.
  2137. Examples
  2138. --------
  2139. >>> import numpy as np
  2140. >>> from scipy.special import comb
  2141. >>> k = np.array([3, 4])
  2142. >>> n = np.array([10, 10])
  2143. >>> comb(n, k, exact=False)
  2144. array([ 120., 210.])
  2145. >>> comb(10, 3, exact=True)
  2146. 120
  2147. >>> comb(10, 3, exact=True, repetition=True)
  2148. 220
  2149. """
  2150. if repetition:
  2151. return comb(N + k - 1, k, exact, legacy=legacy)
  2152. if exact:
  2153. if int(N) != N or int(k) != k:
  2154. if legacy:
  2155. warnings.warn(
  2156. "Non-integer arguments are currently being cast to "
  2157. "integers when exact=True. This behaviour is "
  2158. "deprecated and the default will change to avoid the cast "
  2159. "in SciPy 1.11.0. To opt into the future behavior set "
  2160. "legacy=False. If you want to keep the argument-casting "
  2161. "but silence this warning, cast your inputs directly, "
  2162. "e.g. comb(int(your_N), int(your_k), exact=True).",
  2163. DeprecationWarning, stacklevel=2
  2164. )
  2165. else:
  2166. return comb(N, k)
  2167. # _comb_int casts inputs to integers
  2168. return _comb_int(N, k)
  2169. else:
  2170. k, N = asarray(k), asarray(N)
  2171. cond = (k <= N) & (N >= 0) & (k >= 0)
  2172. vals = binom(N, k)
  2173. if isinstance(vals, np.ndarray):
  2174. vals[~cond] = 0
  2175. elif not cond:
  2176. vals = np.float64(0)
  2177. return vals
  2178. def perm(N, k, exact=False):
  2179. """Permutations of N things taken k at a time, i.e., k-permutations of N.
  2180. It's also known as "partial permutations".
  2181. Parameters
  2182. ----------
  2183. N : int, ndarray
  2184. Number of things.
  2185. k : int, ndarray
  2186. Number of elements taken.
  2187. exact : bool, optional
  2188. If `exact` is False, then floating point precision is used, otherwise
  2189. exact long integer is computed.
  2190. Returns
  2191. -------
  2192. val : int, ndarray
  2193. The number of k-permutations of N.
  2194. Notes
  2195. -----
  2196. - Array arguments accepted only for exact=False case.
  2197. - If k > N, N < 0, or k < 0, then a 0 is returned.
  2198. Examples
  2199. --------
  2200. >>> import numpy as np
  2201. >>> from scipy.special import perm
  2202. >>> k = np.array([3, 4])
  2203. >>> n = np.array([10, 10])
  2204. >>> perm(n, k)
  2205. array([ 720., 5040.])
  2206. >>> perm(10, 3, exact=True)
  2207. 720
  2208. """
  2209. if exact:
  2210. if (k > N) or (N < 0) or (k < 0):
  2211. return 0
  2212. val = 1
  2213. for i in range(N - k + 1, N + 1):
  2214. val *= i
  2215. return val
  2216. else:
  2217. k, N = asarray(k), asarray(N)
  2218. cond = (k <= N) & (N >= 0) & (k >= 0)
  2219. vals = poch(N - k + 1, k)
  2220. if isinstance(vals, np.ndarray):
  2221. vals[~cond] = 0
  2222. elif not cond:
  2223. vals = np.float64(0)
  2224. return vals
  2225. # https://stackoverflow.com/a/16327037
  2226. def _range_prod(lo, hi):
  2227. """
  2228. Product of a range of numbers.
  2229. Returns the product of
  2230. lo * (lo+1) * (lo+2) * ... * (hi-2) * (hi-1) * hi
  2231. = hi! / (lo-1)!
  2232. Breaks into smaller products first for speed:
  2233. _range_prod(2, 9) = ((2*3)*(4*5))*((6*7)*(8*9))
  2234. """
  2235. if lo + 1 < hi:
  2236. mid = (hi + lo) // 2
  2237. return _range_prod(lo, mid) * _range_prod(mid + 1, hi)
  2238. if lo == hi:
  2239. return lo
  2240. return lo * hi
  2241. def factorial(n, exact=False):
  2242. """
  2243. The factorial of a number or array of numbers.
  2244. The factorial of non-negative integer `n` is the product of all
  2245. positive integers less than or equal to `n`::
  2246. n! = n * (n - 1) * (n - 2) * ... * 1
  2247. Parameters
  2248. ----------
  2249. n : int or array_like of ints
  2250. Input values. If ``n < 0``, the return value is 0.
  2251. exact : bool, optional
  2252. If True, calculate the answer exactly using long integer arithmetic.
  2253. If False, result is approximated in floating point rapidly using the
  2254. `gamma` function.
  2255. Default is False.
  2256. Returns
  2257. -------
  2258. nf : float or int or ndarray
  2259. Factorial of `n`, as integer or float depending on `exact`.
  2260. Notes
  2261. -----
  2262. For arrays with ``exact=True``, the factorial is computed only once, for
  2263. the largest input, with each other result computed in the process.
  2264. The output dtype is increased to ``int64`` or ``object`` if necessary.
  2265. With ``exact=False`` the factorial is approximated using the gamma
  2266. function:
  2267. .. math:: n! = \\Gamma(n+1)
  2268. Examples
  2269. --------
  2270. >>> import numpy as np
  2271. >>> from scipy.special import factorial
  2272. >>> arr = np.array([3, 4, 5])
  2273. >>> factorial(arr, exact=False)
  2274. array([ 6., 24., 120.])
  2275. >>> factorial(arr, exact=True)
  2276. array([ 6, 24, 120])
  2277. >>> factorial(5, exact=True)
  2278. 120
  2279. """
  2280. if exact:
  2281. if np.ndim(n) == 0:
  2282. if np.isnan(n):
  2283. return n
  2284. return 0 if n < 0 else math.factorial(n)
  2285. else:
  2286. n = asarray(n)
  2287. un = np.unique(n).astype(object)
  2288. # Convert to object array of long ints if np.int_ can't handle size
  2289. if np.isnan(n).any():
  2290. dt = float
  2291. elif un[-1] > 20:
  2292. dt = object
  2293. elif un[-1] > 12:
  2294. dt = np.int64
  2295. else:
  2296. dt = np.int_
  2297. out = np.empty_like(n, dtype=dt)
  2298. # Handle invalid/trivial values
  2299. # Ignore runtime warning when less operator used w/np.nan
  2300. with np.errstate(all='ignore'):
  2301. un = un[un > 1]
  2302. out[n < 2] = 1
  2303. out[n < 0] = 0
  2304. # Calculate products of each range of numbers
  2305. if un.size:
  2306. val = math.factorial(un[0])
  2307. out[n == un[0]] = val
  2308. for i in range(len(un) - 1):
  2309. prev = un[i] + 1
  2310. current = un[i + 1]
  2311. val *= _range_prod(prev, current)
  2312. out[n == current] = val
  2313. if np.isnan(n).any():
  2314. out = out.astype(np.float64)
  2315. out[np.isnan(n)] = n[np.isnan(n)]
  2316. return out
  2317. else:
  2318. out = _ufuncs._factorial(n)
  2319. return out
  2320. def factorial2(n, exact=False):
  2321. """Double factorial.
  2322. This is the factorial with every second value skipped. E.g., ``7!! = 7 * 5
  2323. * 3 * 1``. It can be approximated numerically as::
  2324. n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi) n odd
  2325. = 2**(n/2) * (n/2)! n even
  2326. Parameters
  2327. ----------
  2328. n : int or array_like
  2329. Calculate ``n!!``. Arrays are only supported with `exact` set
  2330. to False. If ``n < -1``, the return value is 0.
  2331. Otherwise if ``n <= 0``, the return value is 1.
  2332. exact : bool, optional
  2333. The result can be approximated rapidly using the gamma-formula
  2334. above (default). If `exact` is set to True, calculate the
  2335. answer exactly using integer arithmetic.
  2336. Returns
  2337. -------
  2338. nff : float or int
  2339. Double factorial of `n`, as an int or a float depending on
  2340. `exact`.
  2341. Examples
  2342. --------
  2343. >>> from scipy.special import factorial2
  2344. >>> factorial2(7, exact=False)
  2345. array(105.00000000000001)
  2346. >>> factorial2(7, exact=True)
  2347. 105
  2348. """
  2349. if exact:
  2350. if n < -1:
  2351. return 0
  2352. if n <= 0:
  2353. return 1
  2354. val = 1
  2355. for k in range(n, 0, -2):
  2356. val *= k
  2357. return val
  2358. else:
  2359. n = asarray(n)
  2360. vals = zeros(n.shape, 'd')
  2361. cond1 = (n % 2) & (n >= -1)
  2362. cond2 = (1-(n % 2)) & (n >= -1)
  2363. oddn = extract(cond1, n)
  2364. evenn = extract(cond2, n)
  2365. nd2o = oddn / 2.0
  2366. nd2e = evenn / 2.0
  2367. place(vals, cond1, gamma(nd2o + 1) / sqrt(pi) * pow(2.0, nd2o + 0.5))
  2368. place(vals, cond2, gamma(nd2e + 1) * pow(2.0, nd2e))
  2369. return vals
  2370. def factorialk(n, k, exact=True):
  2371. """Multifactorial of n of order k, n(!!...!).
  2372. This is the multifactorial of n skipping k values. For example,
  2373. factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
  2374. In particular, for any integer ``n``, we have
  2375. factorialk(n, 1) = factorial(n)
  2376. factorialk(n, 2) = factorial2(n)
  2377. Parameters
  2378. ----------
  2379. n : int
  2380. Calculate multifactorial. If ``n < 1 - k``, the return value is 0.
  2381. Otherwise if ``n <= 0``, the return value is 1.
  2382. k : int
  2383. Order of multifactorial.
  2384. exact : bool, optional
  2385. If exact is set to True, calculate the answer exactly using
  2386. integer arithmetic.
  2387. Returns
  2388. -------
  2389. val : int
  2390. Multifactorial of `n`.
  2391. Raises
  2392. ------
  2393. NotImplementedError
  2394. Raises when exact is False
  2395. Examples
  2396. --------
  2397. >>> from scipy.special import factorialk
  2398. >>> factorialk(5, 1, exact=True)
  2399. 120
  2400. >>> factorialk(5, 3, exact=True)
  2401. 10
  2402. """
  2403. if exact:
  2404. if n < 1-k:
  2405. return 0
  2406. if n <= 0:
  2407. return 1
  2408. val = 1
  2409. for j in range(n, 0, -k):
  2410. val = val*j
  2411. return val
  2412. else:
  2413. raise NotImplementedError
  2414. def zeta(x, q=None, out=None):
  2415. r"""
  2416. Riemann or Hurwitz zeta function.
  2417. Parameters
  2418. ----------
  2419. x : array_like of float
  2420. Input data, must be real
  2421. q : array_like of float, optional
  2422. Input data, must be real. Defaults to Riemann zeta.
  2423. out : ndarray, optional
  2424. Output array for the computed values.
  2425. Returns
  2426. -------
  2427. out : array_like
  2428. Values of zeta(x).
  2429. Notes
  2430. -----
  2431. The two-argument version is the Hurwitz zeta function
  2432. .. math::
  2433. \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x};
  2434. see [dlmf]_ for details. The Riemann zeta function corresponds to
  2435. the case when ``q = 1``.
  2436. See Also
  2437. --------
  2438. zetac
  2439. References
  2440. ----------
  2441. .. [dlmf] NIST, Digital Library of Mathematical Functions,
  2442. https://dlmf.nist.gov/25.11#i
  2443. Examples
  2444. --------
  2445. >>> import numpy as np
  2446. >>> from scipy.special import zeta, polygamma, factorial
  2447. Some specific values:
  2448. >>> zeta(2), np.pi**2/6
  2449. (1.6449340668482266, 1.6449340668482264)
  2450. >>> zeta(4), np.pi**4/90
  2451. (1.0823232337111381, 1.082323233711138)
  2452. Relation to the `polygamma` function:
  2453. >>> m = 3
  2454. >>> x = 1.25
  2455. >>> polygamma(m, x)
  2456. array(2.782144009188397)
  2457. >>> (-1)**(m+1) * factorial(m) * zeta(m+1, x)
  2458. 2.7821440091883969
  2459. """
  2460. if q is None:
  2461. return _ufuncs._riemann_zeta(x, out)
  2462. else:
  2463. return _ufuncs._zeta(x, q, out)