_basic.py 103 KB

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