1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278 |
- #
- # Author: Travis Oliphant, 2002
- #
- from __future__ import division, print_function, absolute_import
- import operator
- import numpy as np
- import math
- from scipy._lib.six import xrange
- from numpy import (pi, asarray, floor, isscalar, iscomplex, real,
- imag, sqrt, where, mgrid, sin, place, issubdtype,
- extract, inexact, nan, zeros, sinc)
- from . import _ufuncs as ufuncs
- from ._ufuncs import (ellipkm1, mathieu_a, mathieu_b, iv, jv, gamma,
- psi, _zeta, hankel1, hankel2, yv, kv, ndtri,
- poch, binom, hyp0f1)
- from . import specfun
- from . import orthogonal
- from ._comb import _comb_int
- __all__ = ['ai_zeros', 'assoc_laguerre', 'bei_zeros', 'beip_zeros',
- 'ber_zeros', 'bernoulli', 'berp_zeros',
- 'bessel_diff_formula', 'bi_zeros', 'clpmn', 'comb',
- 'digamma', 'diric', 'ellipk', 'erf_zeros', 'erfcinv',
- 'erfinv', 'euler', 'factorial', 'factorialk', 'factorial2',
- 'fresnel_zeros', 'fresnelc_zeros', 'fresnels_zeros',
- 'gamma', 'h1vp', 'h2vp', 'hankel1', 'hankel2', 'hyp0f1',
- 'iv', 'ivp', 'jn_zeros', 'jnjnp_zeros', 'jnp_zeros',
- 'jnyn_zeros', 'jv', 'jvp', 'kei_zeros', 'keip_zeros',
- 'kelvin_zeros', 'ker_zeros', 'kerp_zeros', 'kv', 'kvp',
- 'lmbda', 'lpmn', 'lpn', 'lqmn', 'lqn', 'mathieu_a',
- 'mathieu_b', 'mathieu_even_coef', 'mathieu_odd_coef',
- 'ndtri', 'obl_cv_seq', 'pbdn_seq', 'pbdv_seq', 'pbvv_seq',
- 'perm', 'polygamma', 'pro_cv_seq', 'psi', 'riccati_jn',
- 'riccati_yn', 'sinc', 'y0_zeros', 'y1_zeros', 'y1p_zeros',
- 'yn_zeros', 'ynp_zeros', 'yv', 'yvp', 'zeta']
- def _nonneg_int_or_fail(n, var_name, strict=True):
- try:
- if strict:
- # Raises an exception if float
- n = operator.index(n)
- elif n == floor(n):
- n = int(n)
- else:
- raise ValueError()
- if n < 0:
- raise ValueError()
- except (ValueError, TypeError) as err:
- raise err.__class__("{} must be a non-negative integer".format(var_name))
- return n
- def diric(x, n):
- """Periodic sinc function, also called the Dirichlet function.
- The Dirichlet function is defined as::
- diric(x, n) = sin(x * n/2) / (n * sin(x / 2)),
- where `n` is a positive integer.
- Parameters
- ----------
- x : array_like
- Input data
- n : int
- Integer defining the periodicity.
- Returns
- -------
- diric : ndarray
- Examples
- --------
- >>> from scipy import special
- >>> import matplotlib.pyplot as plt
- >>> x = np.linspace(-8*np.pi, 8*np.pi, num=201)
- >>> plt.figure(figsize=(8, 8));
- >>> for idx, n in enumerate([2, 3, 4, 9]):
- ... plt.subplot(2, 2, idx+1)
- ... plt.plot(x, special.diric(x, n))
- ... plt.title('diric, n={}'.format(n))
- >>> plt.show()
- The following example demonstrates that `diric` gives the magnitudes
- (modulo the sign and scaling) of the Fourier coefficients of a
- rectangular pulse.
- Suppress output of values that are effectively 0:
- >>> np.set_printoptions(suppress=True)
- Create a signal `x` of length `m` with `k` ones:
- >>> m = 8
- >>> k = 3
- >>> x = np.zeros(m)
- >>> x[:k] = 1
- Use the FFT to compute the Fourier transform of `x`, and
- inspect the magnitudes of the coefficients:
- >>> np.abs(np.fft.fft(x))
- array([ 3. , 2.41421356, 1. , 0.41421356, 1. ,
- 0.41421356, 1. , 2.41421356])
- Now find the same values (up to sign) using `diric`. We multiply
- by `k` to account for the different scaling conventions of
- `numpy.fft.fft` and `diric`:
- >>> theta = np.linspace(0, 2*np.pi, m, endpoint=False)
- >>> k * special.diric(theta, k)
- array([ 3. , 2.41421356, 1. , -0.41421356, -1. ,
- -0.41421356, 1. , 2.41421356])
- """
- x, n = asarray(x), asarray(n)
- n = asarray(n + (x-x))
- x = asarray(x + (n-n))
- if issubdtype(x.dtype, inexact):
- ytype = x.dtype
- else:
- ytype = float
- y = zeros(x.shape, ytype)
- # empirical minval for 32, 64 or 128 bit float computations
- # where sin(x/2) < minval, result is fixed at +1 or -1
- if np.finfo(ytype).eps < 1e-18:
- minval = 1e-11
- elif np.finfo(ytype).eps < 1e-15:
- minval = 1e-7
- else:
- minval = 1e-3
- mask1 = (n <= 0) | (n != floor(n))
- place(y, mask1, nan)
- x = x / 2
- denom = sin(x)
- mask2 = (1-mask1) & (abs(denom) < minval)
- xsub = extract(mask2, x)
- nsub = extract(mask2, n)
- zsub = xsub / pi
- place(y, mask2, pow(-1, np.round(zsub)*(nsub-1)))
- mask = (1-mask1) & (1-mask2)
- xsub = extract(mask, x)
- nsub = extract(mask, n)
- dsub = extract(mask, denom)
- place(y, mask, sin(nsub*xsub)/(nsub*dsub))
- return y
- def jnjnp_zeros(nt):
- """Compute zeros of integer-order Bessel functions Jn and Jn'.
- Results are arranged in order of the magnitudes of the zeros.
- Parameters
- ----------
- nt : int
- Number (<=1200) of zeros to compute
- Returns
- -------
- zo[l-1] : ndarray
- Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
- n[l-1] : ndarray
- Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
- m[l-1] : ndarray
- Serial number of the zeros of Jn(x) or Jn'(x) associated
- with lth zero. Of length `nt`.
- t[l-1] : ndarray
- 0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
- length `nt`.
- See Also
- --------
- jn_zeros, jnp_zeros : to get separated arrays of zeros.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
- raise ValueError("Number must be integer <= 1200.")
- nt = int(nt)
- n, m, t, zo = specfun.jdzo(nt)
- return zo[1:nt+1], n[:nt], m[:nt], t[:nt]
- def jnyn_zeros(n, nt):
- """Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
- Returns 4 arrays of length `nt`, corresponding to the first `nt` zeros of
- Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively.
- Parameters
- ----------
- n : int
- Order of the Bessel functions
- nt : int
- Number (<=1200) of zeros to compute
- See jn_zeros, jnp_zeros, yn_zeros, ynp_zeros to get separate arrays.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(nt) and isscalar(n)):
- raise ValueError("Arguments must be scalars.")
- if (floor(n) != n) or (floor(nt) != nt):
- raise ValueError("Arguments must be integers.")
- if (nt <= 0):
- raise ValueError("nt > 0")
- return specfun.jyzo(abs(n), nt)
- def jn_zeros(n, nt):
- """Compute zeros of integer-order Bessel function Jn(x).
- Parameters
- ----------
- n : int
- Order of Bessel function
- nt : int
- Number of zeros to return
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- return jnyn_zeros(n, nt)[0]
- def jnp_zeros(n, nt):
- """Compute zeros of integer-order Bessel function derivative Jn'(x).
- Parameters
- ----------
- n : int
- Order of Bessel function
- nt : int
- Number of zeros to return
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- return jnyn_zeros(n, nt)[1]
- def yn_zeros(n, nt):
- """Compute zeros of integer-order Bessel function Yn(x).
- Parameters
- ----------
- n : int
- Order of Bessel function
- nt : int
- Number of zeros to return
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- return jnyn_zeros(n, nt)[2]
- def ynp_zeros(n, nt):
- """Compute zeros of integer-order Bessel function derivative Yn'(x).
- Parameters
- ----------
- n : int
- Order of Bessel function
- nt : int
- Number of zeros to return
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- return jnyn_zeros(n, nt)[3]
- def y0_zeros(nt, complex=False):
- """Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
- The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0.
- Parameters
- ----------
- nt : int
- Number of zeros to return
- complex : bool, default False
- Set to False to return only the real zeros; set to True to return only
- the complex zeros with negative real part and positive imaginary part.
- Note that the complex conjugates of the latter are also zeros of the
- function, but are not returned by this routine.
- Returns
- -------
- z0n : ndarray
- Location of nth zero of Y0(z)
- y0pz0n : ndarray
- Value of derivative Y0'(z0) for nth zero
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("Arguments must be scalar positive integer.")
- kf = 0
- kc = not complex
- return specfun.cyzo(nt, kf, kc)
- def y1_zeros(nt, complex=False):
- """Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
- The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1.
- Parameters
- ----------
- nt : int
- Number of zeros to return
- complex : bool, default False
- Set to False to return only the real zeros; set to True to return only
- the complex zeros with negative real part and positive imaginary part.
- Note that the complex conjugates of the latter are also zeros of the
- function, but are not returned by this routine.
- Returns
- -------
- z1n : ndarray
- Location of nth zero of Y1(z)
- y1pz1n : ndarray
- Value of derivative Y1'(z1) for nth zero
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("Arguments must be scalar positive integer.")
- kf = 1
- kc = not complex
- return specfun.cyzo(nt, kf, kc)
- def y1p_zeros(nt, complex=False):
- """Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
- The values are given by Y1(z1) at each z1 where Y1'(z1)=0.
- Parameters
- ----------
- nt : int
- Number of zeros to return
- complex : bool, default False
- Set to False to return only the real zeros; set to True to return only
- the complex zeros with negative real part and positive imaginary part.
- Note that the complex conjugates of the latter are also zeros of the
- function, but are not returned by this routine.
- Returns
- -------
- z1pn : ndarray
- Location of nth zero of Y1'(z)
- y1z1pn : ndarray
- Value of derivative Y1(z1) for nth zero
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("Arguments must be scalar positive integer.")
- kf = 2
- kc = not complex
- return specfun.cyzo(nt, kf, kc)
- def _bessel_diff_formula(v, z, n, L, phase):
- # from AMS55.
- # L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1
- # L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1
- # For K, you can pull out the exp((v-k)*pi*i) into the caller
- v = asarray(v)
- p = 1.0
- s = L(v-n, z)
- for i in xrange(1, n+1):
- p = phase * (p * (n-i+1)) / i # = choose(k, i)
- s += p*L(v-n + i*2, z)
- return s / (2.**n)
- bessel_diff_formula = np.deprecate(_bessel_diff_formula,
- message="bessel_diff_formula is a private function, do not use it!")
- def jvp(v, z, n=1):
- """Compute nth derivative of Bessel function Jv(z) with respect to `z`.
- Parameters
- ----------
- v : float
- Order of Bessel function
- z : complex
- Argument at which to evaluate the derivative
- n : int, default 1
- Order of derivative
- Notes
- -----
- The derivative is computed using the relation DLFM 10.6.7 [2]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.6.E7
- """
- n = _nonneg_int_or_fail(n, 'n')
- if n == 0:
- return jv(v, z)
- else:
- return _bessel_diff_formula(v, z, n, jv, -1)
- def yvp(v, z, n=1):
- """Compute nth derivative of Bessel function Yv(z) with respect to `z`.
- Parameters
- ----------
- v : float
- Order of Bessel function
- z : complex
- Argument at which to evaluate the derivative
- n : int, default 1
- Order of derivative
- Notes
- -----
- The derivative is computed using the relation DLFM 10.6.7 [2]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.6.E7
- """
- n = _nonneg_int_or_fail(n, 'n')
- if n == 0:
- return yv(v, z)
- else:
- return _bessel_diff_formula(v, z, n, yv, -1)
- def kvp(v, z, n=1):
- """Compute nth derivative of real-order modified Bessel function Kv(z)
- Kv(z) is the modified Bessel function of the second kind.
- Derivative is calculated with respect to `z`.
- Parameters
- ----------
- v : array_like of float
- Order of Bessel function
- z : array_like of complex
- Argument at which to evaluate the derivative
- n : int
- Order of derivative. Default is first derivative.
- Returns
- -------
- out : ndarray
- The results
- Examples
- --------
- Calculate multiple values at order 5:
- >>> from scipy.special import kvp
- >>> kvp(5, (1, 2, 3+5j))
- array([-1.84903536e+03+0.j , -2.57735387e+01+0.j ,
- -3.06627741e-02+0.08750845j])
- Calculate for a single value at multiple orders:
- >>> kvp((4, 4.5, 5), 1)
- array([ -184.0309, -568.9585, -1849.0354])
- Notes
- -----
- The derivative is computed using the relation DLFM 10.29.5 [2]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 6.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.29.E5
- """
- n = _nonneg_int_or_fail(n, 'n')
- if n == 0:
- return kv(v, z)
- else:
- return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1)
- def ivp(v, z, n=1):
- """Compute nth derivative of modified Bessel function Iv(z) with respect
- to `z`.
- Parameters
- ----------
- v : array_like of float
- Order of Bessel function
- z : array_like of complex
- Argument at which to evaluate the derivative
- n : int, default 1
- Order of derivative
- Notes
- -----
- The derivative is computed using the relation DLFM 10.29.5 [2]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 6.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.29.E5
- """
- n = _nonneg_int_or_fail(n, 'n')
- if n == 0:
- return iv(v, z)
- else:
- return _bessel_diff_formula(v, z, n, iv, 1)
- def h1vp(v, z, n=1):
- """Compute nth derivative of Hankel function H1v(z) with respect to `z`.
- Parameters
- ----------
- v : float
- Order of Hankel function
- z : complex
- Argument at which to evaluate the derivative
- n : int, default 1
- Order of derivative
- Notes
- -----
- The derivative is computed using the relation DLFM 10.6.7 [2]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.6.E7
- """
- n = _nonneg_int_or_fail(n, 'n')
- if n == 0:
- return hankel1(v, z)
- else:
- return _bessel_diff_formula(v, z, n, hankel1, -1)
- def h2vp(v, z, n=1):
- """Compute nth derivative of Hankel function H2v(z) with respect to `z`.
- Parameters
- ----------
- v : float
- Order of Hankel function
- z : complex
- Argument at which to evaluate the derivative
- n : int, default 1
- Order of derivative
- Notes
- -----
- The derivative is computed using the relation DLFM 10.6.7 [2]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 5.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.6.E7
- """
- n = _nonneg_int_or_fail(n, 'n')
- if n == 0:
- return hankel2(v, z)
- else:
- return _bessel_diff_formula(v, z, n, hankel2, -1)
- def riccati_jn(n, x):
- r"""Compute Ricatti-Bessel function of the first kind and its derivative.
- The Ricatti-Bessel function of the first kind is defined as :math:`x
- j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first
- kind of order :math:`n`.
- This function computes the value and first derivative of the
- Ricatti-Bessel function for all orders up to and including `n`.
- Parameters
- ----------
- n : int
- Maximum order of function to compute
- x : float
- Argument at which to evaluate
- Returns
- -------
- jn : ndarray
- Value of j0(x), ..., jn(x)
- jnp : ndarray
- First derivative j0'(x), ..., jn'(x)
- Notes
- -----
- The computation is carried out via backward recurrence, using the
- relation DLMF 10.51.1 [2]_.
- Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
- Jin [1]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.51.E1
- """
- if not (isscalar(n) and isscalar(x)):
- raise ValueError("arguments must be scalars.")
- n = _nonneg_int_or_fail(n, 'n', strict=False)
- if (n == 0):
- n1 = 1
- else:
- n1 = n
- nm, jn, jnp = specfun.rctj(n1, x)
- return jn[:(n+1)], jnp[:(n+1)]
- def riccati_yn(n, x):
- """Compute Ricatti-Bessel function of the second kind and its derivative.
- The Ricatti-Bessel function of the second kind is defined as :math:`x
- y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second
- kind of order :math:`n`.
- This function computes the value and first derivative of the function for
- all orders up to and including `n`.
- Parameters
- ----------
- n : int
- Maximum order of function to compute
- x : float
- Argument at which to evaluate
- Returns
- -------
- yn : ndarray
- Value of y0(x), ..., yn(x)
- ynp : ndarray
- First derivative y0'(x), ..., yn'(x)
- Notes
- -----
- The computation is carried out via ascending recurrence, using the
- relation DLMF 10.51.1 [2]_.
- Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
- Jin [1]_.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions.
- https://dlmf.nist.gov/10.51.E1
- """
- if not (isscalar(n) and isscalar(x)):
- raise ValueError("arguments must be scalars.")
- n = _nonneg_int_or_fail(n, 'n', strict=False)
- if (n == 0):
- n1 = 1
- else:
- n1 = n
- nm, jn, jnp = specfun.rcty(n1, x)
- return jn[:(n+1)], jnp[:(n+1)]
- def erfinv(y):
- """Inverse of the error function erf.
- Computes the inverse of the error function.
- In complex domain, there is no unique complex number w satisfying erf(w)=z.
- This indicates a true inverse function would have multi-value. When the domain restricts to the real, -1 < x < 1,
- there is a unique real number satisfying erf(erfinv(x)) = x.
- Parameters
- ----------
- y : ndarray
- Argument at which to evaluate. Domain: [-1, 1]
- Returns
- -------
- erfinv : ndarray
- The inverse of erf of y, element-wise
- Examples
- --------
- 1) evaluating a float number
- >>> from scipy import special
- >>> special.erfinv(0.5)
- 0.4769362762044698
- 2) evaluating a ndarray
- >>> from scipy import special
- >>> y = np.linspace(-1.0, 1.0, num=10)
- >>> special.erfinv(y)
- array([ -inf, -0.86312307, -0.5407314 , -0.30457019, -0.0987901 ,
- 0.0987901 , 0.30457019, 0.5407314 , 0.86312307, inf])
- """
- return ndtri((y+1)/2.0)/sqrt(2)
- def erfcinv(y):
- """Inverse of the complementary error function erfc.
- Computes the inverse of the complementary error function erfc.
- In complex domain, there is no unique complex number w satisfying erfc(w)=z.
- This indicates a true inverse function would have multi-value. When the domain restricts to the real, 0 < x < 2,
- there is a unique real number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).
- It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)
- Parameters
- ----------
- y : ndarray
- Argument at which to evaluate. Domain: [0, 2]
- Returns
- -------
- erfcinv : ndarray
- The inverse of erfc of y, element-wise
- Examples
- --------
- 1) evaluating a float number
- >>> from scipy import special
- >>> special.erfcinv(0.5)
- 0.4769362762044698
- 2) evaluating a ndarray
- >>> from scipy import special
- >>> y = np.linspace(0.0, 2.0, num=11)
- >>> special.erfcinv(y)
- array([ inf, 0.9061938 , 0.59511608, 0.37080716, 0.17914345,
- -0. , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,
- -inf])
- """
- return -ndtri(0.5*y)/sqrt(2)
- def erf_zeros(nt):
- """Compute the first nt zero in the first quadrant, ordered by absolute value.
- Zeros in the other quadrants can be obtained by using the symmetries erf(-z) = erf(z) and
- erf(conj(z)) = conj(erf(z)).
- Parameters
- ----------
- nt : int
- The number of zeros to compute
- Returns
- -------
- The locations of the zeros of erf : ndarray (complex)
- Complex values at which zeros of erf(z)
- Examples
- --------
- >>> from scipy import special
- >>> special.erf_zeros(1)
- array([1.45061616+1.880943j])
- Check that erf is (close to) zero for the value returned by erf_zeros
-
- >>> special.erf(special.erf_zeros(1))
- array([4.95159469e-14-1.16407394e-16j])
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
- raise ValueError("Argument must be positive scalar integer.")
- return specfun.cerzo(nt)
- def fresnelc_zeros(nt):
- """Compute nt complex zeros of cosine Fresnel integral C(z).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
- raise ValueError("Argument must be positive scalar integer.")
- return specfun.fcszo(1, nt)
- def fresnels_zeros(nt):
- """Compute nt complex zeros of sine Fresnel integral S(z).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
- raise ValueError("Argument must be positive scalar integer.")
- return specfun.fcszo(2, nt)
- def fresnel_zeros(nt):
- """Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
- raise ValueError("Argument must be positive scalar integer.")
- return specfun.fcszo(2, nt), specfun.fcszo(1, nt)
- def assoc_laguerre(x, n, k=0.0):
- """Compute the generalized (associated) Laguerre polynomial of degree n and order k.
- The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``,
- with weighting function ``exp(-x) * x**k`` with ``k > -1``.
- Notes
- -----
- `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with
- reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
- """
- return orthogonal.eval_genlaguerre(n, k, x)
- digamma = psi
- def polygamma(n, x):
- """Polygamma function n.
- This is the nth derivative of the digamma (psi) function.
- Parameters
- ----------
- n : array_like of int
- The order of the derivative of `psi`.
- x : array_like
- Where to evaluate the polygamma function.
- Returns
- -------
- polygamma : ndarray
- The result.
- Examples
- --------
- >>> from scipy import special
- >>> x = [2, 3, 25.5]
- >>> special.polygamma(1, x)
- array([ 0.64493407, 0.39493407, 0.03999467])
- >>> special.polygamma(0, x) == special.psi(x)
- array([ True, True, True], dtype=bool)
- """
- n, x = asarray(n), asarray(x)
- fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x)
- return where(n == 0, psi(x), fac2)
- def mathieu_even_coef(m, q):
- r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
- The Fourier series of the even solutions of the Mathieu differential
- equation are of the form
- .. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz
- .. math:: \mathrm{ce}_{2n+1}(z, q) = \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z
- This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even
- input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input
- m=2n+1.
- Parameters
- ----------
- m : int
- Order of Mathieu functions. Must be non-negative.
- q : float (>=0)
- Parameter of Mathieu functions. Must be non-negative.
- Returns
- -------
- Ak : ndarray
- Even or odd Fourier coefficients, corresponding to even or odd m.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions
- https://dlmf.nist.gov/28.4#i
- """
- if not (isscalar(m) and isscalar(q)):
- raise ValueError("m and q must be scalars.")
- if (q < 0):
- raise ValueError("q >=0")
- if (m != floor(m)) or (m < 0):
- raise ValueError("m must be an integer >=0.")
- if (q <= 1):
- qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
- else:
- qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
- km = int(qm + 0.5*m)
- if km > 251:
- print("Warning, too many predicted coefficients.")
- kd = 1
- m = int(floor(m))
- if m % 2:
- kd = 2
- a = mathieu_a(m, q)
- fc = specfun.fcoef(kd, m, q, a)
- return fc[:km]
- def mathieu_odd_coef(m, q):
- r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
- The Fourier series of the odd solutions of the Mathieu differential
- equation are of the form
- .. math:: \mathrm{se}_{2n+1}(z, q) = \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
- .. math:: \mathrm{se}_{2n+2}(z, q) = \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
- This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
- input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
- input m=2n+1.
- Parameters
- ----------
- m : int
- Order of Mathieu functions. Must be non-negative.
- q : float (>=0)
- Parameter of Mathieu functions. Must be non-negative.
- Returns
- -------
- Bk : ndarray
- Even or odd Fourier coefficients, corresponding to even or odd m.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(m) and isscalar(q)):
- raise ValueError("m and q must be scalars.")
- if (q < 0):
- raise ValueError("q >=0")
- if (m != floor(m)) or (m <= 0):
- raise ValueError("m must be an integer > 0")
- if (q <= 1):
- qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
- else:
- qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
- km = int(qm + 0.5*m)
- if km > 251:
- print("Warning, too many predicted coefficients.")
- kd = 4
- m = int(floor(m))
- if m % 2:
- kd = 3
- b = mathieu_b(m, q)
- fc = specfun.fcoef(kd, m, q, b)
- return fc[:km]
- def lpmn(m, n, z):
- """Sequence of associated Legendre functions of the first kind.
- Computes the associated Legendre function of the first kind of order m and
- degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
- Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
- ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
- This function takes a real argument ``z``. For complex arguments ``z``
- use clpmn instead.
- Parameters
- ----------
- m : int
- ``|m| <= n``; the order of the Legendre function.
- n : int
- where ``n >= 0``; the degree of the Legendre function. Often
- called ``l`` (lower case L) in descriptions of the associated
- Legendre function
- z : float
- Input value.
- Returns
- -------
- Pmn_z : (m+1, n+1) array
- Values for all orders 0..m and degrees 0..n
- Pmn_d_z : (m+1, n+1) array
- Derivatives for all orders 0..m and degrees 0..n
- See Also
- --------
- clpmn: associated Legendre functions of the first kind for complex z
- Notes
- -----
- In the interval (-1, 1), Ferrer's function of the first kind is
- returned. The phase convention used for the intervals (1, inf)
- and (-inf, -1) is such that the result is always real.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions
- https://dlmf.nist.gov/14.3
- """
- if not isscalar(m) or (abs(m) > n):
- raise ValueError("m must be <= n.")
- if not isscalar(n) or (n < 0):
- raise ValueError("n must be a non-negative integer.")
- if not isscalar(z):
- raise ValueError("z must be scalar.")
- if iscomplex(z):
- raise ValueError("Argument must be real. Use clpmn instead.")
- if (m < 0):
- mp = -m
- mf, nf = mgrid[0:mp+1, 0:n+1]
- with ufuncs.errstate(all='ignore'):
- if abs(z) < 1:
- # Ferrer function; DLMF 14.9.3
- fixarr = where(mf > nf, 0.0,
- (-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
- else:
- # Match to clpmn; DLMF 14.9.13
- fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
- else:
- mp = m
- p, pd = specfun.lpmn(mp, n, z)
- if (m < 0):
- p = p * fixarr
- pd = pd * fixarr
- return p, pd
- def clpmn(m, n, z, type=3):
- """Associated Legendre function of the first kind for complex arguments.
- Computes the associated Legendre function of the first kind of order m and
- degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
- Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
- ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
- Parameters
- ----------
- m : int
- ``|m| <= n``; the order of the Legendre function.
- n : int
- where ``n >= 0``; the degree of the Legendre function. Often
- called ``l`` (lower case L) in descriptions of the associated
- Legendre function
- z : float or complex
- Input value.
- type : int, optional
- takes values 2 or 3
- 2: cut on the real axis ``|x| > 1``
- 3: cut on the real axis ``-1 < x < 1`` (default)
- Returns
- -------
- Pmn_z : (m+1, n+1) array
- Values for all orders ``0..m`` and degrees ``0..n``
- Pmn_d_z : (m+1, n+1) array
- Derivatives for all orders ``0..m`` and degrees ``0..n``
- See Also
- --------
- lpmn: associated Legendre functions of the first kind for real z
- Notes
- -----
- By default, i.e. for ``type=3``, phase conventions are chosen according
- to [1]_ such that the function is analytic. The cut lies on the interval
- (-1, 1). Approaching the cut from above or below in general yields a phase
- factor with respect to Ferrer's function of the first kind
- (cf. `lpmn`).
- For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values
- on the interval (-1, 1) in the complex plane yields Ferrer's function
- of the first kind.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] NIST Digital Library of Mathematical Functions
- https://dlmf.nist.gov/14.21
- """
- if not isscalar(m) or (abs(m) > n):
- raise ValueError("m must be <= n.")
- if not isscalar(n) or (n < 0):
- raise ValueError("n must be a non-negative integer.")
- if not isscalar(z):
- raise ValueError("z must be scalar.")
- if not(type == 2 or type == 3):
- raise ValueError("type must be either 2 or 3.")
- if (m < 0):
- mp = -m
- mf, nf = mgrid[0:mp+1, 0:n+1]
- with ufuncs.errstate(all='ignore'):
- if type == 2:
- fixarr = where(mf > nf, 0.0,
- (-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
- else:
- fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
- else:
- mp = m
- p, pd = specfun.clpmn(mp, n, real(z), imag(z), type)
- if (m < 0):
- p = p * fixarr
- pd = pd * fixarr
- return p, pd
- def lqmn(m, n, z):
- """Sequence of associated Legendre functions of the second kind.
- Computes the associated Legendre function of the second kind of order m and
- degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
- Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
- ``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
- Parameters
- ----------
- m : int
- ``|m| <= n``; the order of the Legendre function.
- n : int
- where ``n >= 0``; the degree of the Legendre function. Often
- called ``l`` (lower case L) in descriptions of the associated
- Legendre function
- z : complex
- Input value.
- Returns
- -------
- Qmn_z : (m+1, n+1) array
- Values for all orders 0..m and degrees 0..n
- Qmn_d_z : (m+1, n+1) array
- Derivatives for all orders 0..m and degrees 0..n
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(m) or (m < 0):
- raise ValueError("m must be a non-negative integer.")
- if not isscalar(n) or (n < 0):
- raise ValueError("n must be a non-negative integer.")
- if not isscalar(z):
- raise ValueError("z must be scalar.")
- m = int(m)
- n = int(n)
- # Ensure neither m nor n == 0
- mm = max(1, m)
- nn = max(1, n)
- if iscomplex(z):
- q, qd = specfun.clqmn(mm, nn, z)
- else:
- q, qd = specfun.lqmn(mm, nn, z)
- return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)]
- def bernoulli(n):
- """Bernoulli numbers B0..Bn (inclusive).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(n) or (n < 0):
- raise ValueError("n must be a non-negative integer.")
- n = int(n)
- if (n < 2):
- n1 = 2
- else:
- n1 = n
- return specfun.bernob(int(n1))[:(n+1)]
- def euler(n):
- """Euler numbers E(0), E(1), ..., E(n).
- The Euler numbers [1]_ are also known as the secant numbers.
- Because ``euler(n)`` returns floating point values, it does not give
- exact values for large `n`. The first inexact value is E(22).
- Parameters
- ----------
- n : int
- The highest index of the Euler number to be returned.
- Returns
- -------
- ndarray
- The Euler numbers [E(0), E(1), ..., E(n)].
- The odd Euler numbers, which are all zero, are included.
- References
- ----------
- .. [1] Sequence A122045, The On-Line Encyclopedia of Integer Sequences,
- https://oeis.org/A122045
- .. [2] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- Examples
- --------
- >>> from scipy.special import euler
- >>> euler(6)
- array([ 1., 0., -1., 0., 5., 0., -61.])
- >>> euler(13).astype(np.int64)
- array([ 1, 0, -1, 0, 5, 0, -61,
- 0, 1385, 0, -50521, 0, 2702765, 0])
- >>> euler(22)[-1] # Exact value of E(22) is -69348874393137901.
- -69348874393137976.0
- """
- if not isscalar(n) or (n < 0):
- raise ValueError("n must be a non-negative integer.")
- n = int(n)
- if (n < 2):
- n1 = 2
- else:
- n1 = n
- return specfun.eulerb(n1)[:(n+1)]
- def lpn(n, z):
- """Legendre function of the first kind.
- Compute sequence of Legendre functions of the first kind (polynomials),
- Pn(z) and derivatives for all degrees from 0 to n (inclusive).
- See also special.legendre for polynomial class.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(n) and isscalar(z)):
- raise ValueError("arguments must be scalars.")
- n = _nonneg_int_or_fail(n, 'n', strict=False)
- if (n < 1):
- n1 = 1
- else:
- n1 = n
- if iscomplex(z):
- pn, pd = specfun.clpn(n1, z)
- else:
- pn, pd = specfun.lpn(n1, z)
- return pn[:(n+1)], pd[:(n+1)]
- def lqn(n, z):
- """Legendre function of the second kind.
- Compute sequence of Legendre functions of the second kind, Qn(z) and
- derivatives for all degrees from 0 to n (inclusive).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(n) and isscalar(z)):
- raise ValueError("arguments must be scalars.")
- n = _nonneg_int_or_fail(n, 'n', strict=False)
- if (n < 1):
- n1 = 1
- else:
- n1 = n
- if iscomplex(z):
- qn, qd = specfun.clqn(n1, z)
- else:
- qn, qd = specfun.lqnb(n1, z)
- return qn[:(n+1)], qd[:(n+1)]
- def ai_zeros(nt):
- """
- Compute `nt` zeros and values of the Airy function Ai and its derivative.
- Computes the first `nt` zeros, `a`, of the Airy function Ai(x);
- first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x);
- the corresponding values Ai(a');
- and the corresponding values Ai'(a).
- Parameters
- ----------
- nt : int
- Number of zeros to compute
- Returns
- -------
- a : ndarray
- First `nt` zeros of Ai(x)
- ap : ndarray
- First `nt` zeros of Ai'(x)
- ai : ndarray
- Values of Ai(x) evaluated at first `nt` zeros of Ai'(x)
- aip : ndarray
- Values of Ai'(x) evaluated at first `nt` zeros of Ai(x)
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- kf = 1
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be a positive integer scalar.")
- return specfun.airyzo(nt, kf)
- def bi_zeros(nt):
- """
- Compute `nt` zeros and values of the Airy function Bi and its derivative.
- Computes the first `nt` zeros, b, of the Airy function Bi(x);
- first `nt` zeros, b', of the derivative of the Airy function Bi'(x);
- the corresponding values Bi(b');
- and the corresponding values Bi'(b).
- Parameters
- ----------
- nt : int
- Number of zeros to compute
- Returns
- -------
- b : ndarray
- First `nt` zeros of Bi(x)
- bp : ndarray
- First `nt` zeros of Bi'(x)
- bi : ndarray
- Values of Bi(x) evaluated at first `nt` zeros of Bi'(x)
- bip : ndarray
- Values of Bi'(x) evaluated at first `nt` zeros of Bi(x)
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- kf = 2
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be a positive integer scalar.")
- return specfun.airyzo(nt, kf)
- def lmbda(v, x):
- r"""Jahnke-Emden Lambda function, Lambdav(x).
- This function is defined as [2]_,
- .. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v},
- where :math:`\Gamma` is the gamma function and :math:`J_v` is the
- Bessel function of the first kind.
- Parameters
- ----------
- v : float
- Order of the Lambda function
- x : float
- Value at which to evaluate the function and derivatives
- Returns
- -------
- vl : ndarray
- Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
- dl : ndarray
- Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- .. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and
- Curves" (4th ed.), Dover, 1945
- """
- if not (isscalar(v) and isscalar(x)):
- raise ValueError("arguments must be scalars.")
- if (v < 0):
- raise ValueError("argument must be > 0.")
- n = int(v)
- v0 = v - n
- if (n < 1):
- n1 = 1
- else:
- n1 = n
- v1 = n1 + v0
- if (v != floor(v)):
- vm, vl, dl = specfun.lamv(v1, x)
- else:
- vm, vl, dl = specfun.lamn(v1, x)
- return vl[:(n+1)], dl[:(n+1)]
- def pbdv_seq(v, x):
- """Parabolic cylinder functions Dv(x) and derivatives.
- Parameters
- ----------
- v : float
- Order of the parabolic cylinder function
- x : float
- Value at which to evaluate the function and derivatives
- Returns
- -------
- dv : ndarray
- Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
- dp : ndarray
- Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 13.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(v) and isscalar(x)):
- raise ValueError("arguments must be scalars.")
- n = int(v)
- v0 = v-n
- if (n < 1):
- n1 = 1
- else:
- n1 = n
- v1 = n1 + v0
- dv, dp, pdf, pdd = specfun.pbdv(v1, x)
- return dv[:n1+1], dp[:n1+1]
- def pbvv_seq(v, x):
- """Parabolic cylinder functions Vv(x) and derivatives.
- Parameters
- ----------
- v : float
- Order of the parabolic cylinder function
- x : float
- Value at which to evaluate the function and derivatives
- Returns
- -------
- dv : ndarray
- Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
- dp : ndarray
- Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 13.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(v) and isscalar(x)):
- raise ValueError("arguments must be scalars.")
- n = int(v)
- v0 = v-n
- if (n <= 1):
- n1 = 1
- else:
- n1 = n
- v1 = n1 + v0
- dv, dp, pdf, pdd = specfun.pbvv(v1, x)
- return dv[:n1+1], dp[:n1+1]
- def pbdn_seq(n, z):
- """Parabolic cylinder functions Dn(z) and derivatives.
- Parameters
- ----------
- n : int
- Order of the parabolic cylinder function
- z : complex
- Value at which to evaluate the function and derivatives
- Returns
- -------
- dv : ndarray
- Values of D_i(z), for i=0, ..., i=n.
- dp : ndarray
- Derivatives D_i'(z), for i=0, ..., i=n.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996, chapter 13.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(n) and isscalar(z)):
- raise ValueError("arguments must be scalars.")
- if (floor(n) != n):
- raise ValueError("n must be an integer.")
- if (abs(n) <= 1):
- n1 = 1
- else:
- n1 = n
- cpb, cpd = specfun.cpbdn(n1, z)
- return cpb[:n1+1], cpd[:n1+1]
- def ber_zeros(nt):
- """Compute nt zeros of the Kelvin function ber(x).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 1)
- def bei_zeros(nt):
- """Compute nt zeros of the Kelvin function bei(x).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 2)
- def ker_zeros(nt):
- """Compute nt zeros of the Kelvin function ker(x).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 3)
- def kei_zeros(nt):
- """Compute nt zeros of the Kelvin function kei(x).
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 4)
- def berp_zeros(nt):
- """Compute nt zeros of the Kelvin function ber'(x).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 5)
- def beip_zeros(nt):
- """Compute nt zeros of the Kelvin function bei'(x).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 6)
- def kerp_zeros(nt):
- """Compute nt zeros of the Kelvin function ker'(x).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 7)
- def keip_zeros(nt):
- """Compute nt zeros of the Kelvin function kei'(x).
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return specfun.klvnzo(nt, 8)
- def kelvin_zeros(nt):
- """Compute nt zeros of all Kelvin functions.
- Returned in a length-8 tuple of arrays of length nt. The tuple contains
- the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei').
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
- raise ValueError("nt must be positive integer scalar.")
- return (specfun.klvnzo(nt, 1),
- specfun.klvnzo(nt, 2),
- specfun.klvnzo(nt, 3),
- specfun.klvnzo(nt, 4),
- specfun.klvnzo(nt, 5),
- specfun.klvnzo(nt, 6),
- specfun.klvnzo(nt, 7),
- specfun.klvnzo(nt, 8))
- def pro_cv_seq(m, n, c):
- """Characteristic values for prolate spheroidal wave functions.
- Compute a sequence of characteristic values for the prolate
- spheroidal wave functions for mode m and n'=m..n and spheroidal
- parameter c.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(m) and isscalar(n) and isscalar(c)):
- raise ValueError("Arguments must be scalars.")
- if (n != floor(n)) or (m != floor(m)):
- raise ValueError("Modes must be integers.")
- if (n-m > 199):
- raise ValueError("Difference between n and m is too large.")
- maxL = n-m+1
- return specfun.segv(m, n, c, 1)[1][:maxL]
- def obl_cv_seq(m, n, c):
- """Characteristic values for oblate spheroidal wave functions.
- Compute a sequence of characteristic values for the oblate
- spheroidal wave functions for mode m and n'=m..n and spheroidal
- parameter c.
- References
- ----------
- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
- Functions", John Wiley and Sons, 1996.
- https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html
- """
- if not (isscalar(m) and isscalar(n) and isscalar(c)):
- raise ValueError("Arguments must be scalars.")
- if (n != floor(n)) or (m != floor(m)):
- raise ValueError("Modes must be integers.")
- if (n-m > 199):
- raise ValueError("Difference between n and m is too large.")
- maxL = n-m+1
- return specfun.segv(m, n, c, -1)[1][:maxL]
- def ellipk(m):
- r"""Complete elliptic integral of the first kind.
- This function is defined as
- .. math:: K(m) = \int_0^{\pi/2} [1 - m \sin(t)^2]^{-1/2} dt
- Parameters
- ----------
- m : array_like
- The parameter of the elliptic integral.
- Returns
- -------
- K : array_like
- Value of the elliptic integral.
- Notes
- -----
- For more precision around point m = 1, use `ellipkm1`, which this
- function calls.
- The parameterization in terms of :math:`m` follows that of section
- 17.2 in [1]_. Other parameterizations in terms of the
- complementary parameter :math:`1 - m`, modular angle
- :math:`\sin^2(\alpha) = m`, or modulus :math:`k^2 = m` are also
- used, so be careful that you choose the correct parameter.
- See Also
- --------
- ellipkm1 : Complete elliptic integral of the first kind around m = 1
- ellipkinc : Incomplete elliptic integral of the first kind
- ellipe : Complete elliptic integral of the second kind
- ellipeinc : Incomplete elliptic integral of the second kind
- References
- ----------
- .. [1] Milton Abramowitz and Irene A. Stegun, eds.
- Handbook of Mathematical Functions with Formulas,
- Graphs, and Mathematical Tables. New York: Dover, 1972.
- """
- return ellipkm1(1 - asarray(m))
- def comb(N, k, exact=False, repetition=False):
- """The number of combinations of N things taken k at a time.
- This is often expressed as "N choose k".
- Parameters
- ----------
- N : int, ndarray
- Number of things.
- k : int, ndarray
- Number of elements taken.
- exact : bool, optional
- If `exact` is False, then floating point precision is used, otherwise
- exact long integer is computed.
- repetition : bool, optional
- If `repetition` is True, then the number of combinations with
- repetition is computed.
- Returns
- -------
- val : int, float, ndarray
- The total number of combinations.
- See Also
- --------
- binom : Binomial coefficient ufunc
- Notes
- -----
- - Array arguments accepted only for exact=False case.
- - If k > N, N < 0, or k < 0, then a 0 is returned.
- Examples
- --------
- >>> from scipy.special import comb
- >>> k = np.array([3, 4])
- >>> n = np.array([10, 10])
- >>> comb(n, k, exact=False)
- array([ 120., 210.])
- >>> comb(10, 3, exact=True)
- 120L
- >>> comb(10, 3, exact=True, repetition=True)
- 220L
- """
- if repetition:
- return comb(N + k - 1, k, exact)
- if exact:
- return _comb_int(N, k)
- else:
- k, N = asarray(k), asarray(N)
- cond = (k <= N) & (N >= 0) & (k >= 0)
- vals = binom(N, k)
- if isinstance(vals, np.ndarray):
- vals[~cond] = 0
- elif not cond:
- vals = np.float64(0)
- return vals
- def perm(N, k, exact=False):
- """Permutations of N things taken k at a time, i.e., k-permutations of N.
- It's also known as "partial permutations".
- Parameters
- ----------
- N : int, ndarray
- Number of things.
- k : int, ndarray
- Number of elements taken.
- exact : bool, optional
- If `exact` is False, then floating point precision is used, otherwise
- exact long integer is computed.
- Returns
- -------
- val : int, ndarray
- The number of k-permutations of N.
- Notes
- -----
- - Array arguments accepted only for exact=False case.
- - If k > N, N < 0, or k < 0, then a 0 is returned.
- Examples
- --------
- >>> from scipy.special import perm
- >>> k = np.array([3, 4])
- >>> n = np.array([10, 10])
- >>> perm(n, k)
- array([ 720., 5040.])
- >>> perm(10, 3, exact=True)
- 720
- """
- if exact:
- if (k > N) or (N < 0) or (k < 0):
- return 0
- val = 1
- for i in xrange(N - k + 1, N + 1):
- val *= i
- return val
- else:
- k, N = asarray(k), asarray(N)
- cond = (k <= N) & (N >= 0) & (k >= 0)
- vals = poch(N - k + 1, k)
- if isinstance(vals, np.ndarray):
- vals[~cond] = 0
- elif not cond:
- vals = np.float64(0)
- return vals
- # https://stackoverflow.com/a/16327037
- def _range_prod(lo, hi):
- """
- Product of a range of numbers.
- Returns the product of
- lo * (lo+1) * (lo+2) * ... * (hi-2) * (hi-1) * hi
- = hi! / (lo-1)!
- Breaks into smaller products first for speed:
- _range_prod(2, 9) = ((2*3)*(4*5))*((6*7)*(8*9))
- """
- if lo + 1 < hi:
- mid = (hi + lo) // 2
- return _range_prod(lo, mid) * _range_prod(mid + 1, hi)
- if lo == hi:
- return lo
- return lo * hi
- def factorial(n, exact=False):
- """
- The factorial of a number or array of numbers.
- The factorial of non-negative integer `n` is the product of all
- positive integers less than or equal to `n`::
- n! = n * (n - 1) * (n - 2) * ... * 1
- Parameters
- ----------
- n : int or array_like of ints
- Input values. If ``n < 0``, the return value is 0.
- exact : bool, optional
- If True, calculate the answer exactly using long integer arithmetic.
- If False, result is approximated in floating point rapidly using the
- `gamma` function.
- Default is False.
- Returns
- -------
- nf : float or int or ndarray
- Factorial of `n`, as integer or float depending on `exact`.
- Notes
- -----
- For arrays with ``exact=True``, the factorial is computed only once, for
- the largest input, with each other result computed in the process.
- The output dtype is increased to ``int64`` or ``object`` if necessary.
- With ``exact=False`` the factorial is approximated using the gamma
- function:
- .. math:: n! = \\Gamma(n+1)
- Examples
- --------
- >>> from scipy.special import factorial
- >>> arr = np.array([3, 4, 5])
- >>> factorial(arr, exact=False)
- array([ 6., 24., 120.])
- >>> factorial(arr, exact=True)
- array([ 6, 24, 120])
- >>> factorial(5, exact=True)
- 120L
- """
- if exact:
- if np.ndim(n) == 0:
- return 0 if n < 0 else math.factorial(n)
- else:
- n = asarray(n)
- un = np.unique(n).astype(object)
- # Convert to object array of long ints if np.int can't handle size
- if un[-1] > 20:
- dt = object
- elif un[-1] > 12:
- dt = np.int64
- else:
- dt = np.int
- out = np.empty_like(n, dtype=dt)
- # Handle invalid/trivial values
- un = un[un > 1]
- out[n < 2] = 1
- out[n < 0] = 0
- # Calculate products of each range of numbers
- if un.size:
- val = math.factorial(un[0])
- out[n == un[0]] = val
- for i in xrange(len(un) - 1):
- prev = un[i] + 1
- current = un[i + 1]
- val *= _range_prod(prev, current)
- out[n == current] = val
- return out
- else:
- n = asarray(n)
- vals = gamma(n + 1)
- return where(n >= 0, vals, 0)
- def factorial2(n, exact=False):
- """Double factorial.
- This is the factorial with every second value skipped. E.g., ``7!! = 7 * 5
- * 3 * 1``. It can be approximated numerically as::
- n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi) n odd
- = 2**(n/2) * (n/2)! n even
- Parameters
- ----------
- n : int or array_like
- Calculate ``n!!``. Arrays are only supported with `exact` set
- to False. If ``n < 0``, the return value is 0.
- exact : bool, optional
- The result can be approximated rapidly using the gamma-formula
- above (default). If `exact` is set to True, calculate the
- answer exactly using integer arithmetic.
- Returns
- -------
- nff : float or int
- Double factorial of `n`, as an int or a float depending on
- `exact`.
- Examples
- --------
- >>> from scipy.special import factorial2
- >>> factorial2(7, exact=False)
- array(105.00000000000001)
- >>> factorial2(7, exact=True)
- 105L
- """
- if exact:
- if n < -1:
- return 0
- if n <= 0:
- return 1
- val = 1
- for k in xrange(n, 0, -2):
- val *= k
- return val
- else:
- n = asarray(n)
- vals = zeros(n.shape, 'd')
- cond1 = (n % 2) & (n >= -1)
- cond2 = (1-(n % 2)) & (n >= -1)
- oddn = extract(cond1, n)
- evenn = extract(cond2, n)
- nd2o = oddn / 2.0
- nd2e = evenn / 2.0
- place(vals, cond1, gamma(nd2o + 1) / sqrt(pi) * pow(2.0, nd2o + 0.5))
- place(vals, cond2, gamma(nd2e + 1) * pow(2.0, nd2e))
- return vals
- def factorialk(n, k, exact=True):
- """Multifactorial of n of order k, n(!!...!).
- This is the multifactorial of n skipping k values. For example,
- factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
- In particular, for any integer ``n``, we have
- factorialk(n, 1) = factorial(n)
- factorialk(n, 2) = factorial2(n)
- Parameters
- ----------
- n : int
- Calculate multifactorial. If `n` < 0, the return value is 0.
- k : int
- Order of multifactorial.
- exact : bool, optional
- If exact is set to True, calculate the answer exactly using
- integer arithmetic.
- Returns
- -------
- val : int
- Multifactorial of `n`.
- Raises
- ------
- NotImplementedError
- Raises when exact is False
- Examples
- --------
- >>> from scipy.special import factorialk
- >>> factorialk(5, 1, exact=True)
- 120L
- >>> factorialk(5, 3, exact=True)
- 10L
- """
- if exact:
- if n < 1-k:
- return 0
- if n <= 0:
- return 1
- val = 1
- for j in xrange(n, 0, -k):
- val = val*j
- return val
- else:
- raise NotImplementedError
- def zeta(x, q=None, out=None):
- r"""
- Riemann or Hurwitz zeta function.
- Parameters
- ----------
- x : array_like of float
- Input data, must be real
- q : array_like of float, optional
- Input data, must be real. Defaults to Riemann zeta.
- out : ndarray, optional
- Output array for the computed values.
- Returns
- -------
- out : array_like
- Values of zeta(x).
- Notes
- -----
- The two-argument version is the Hurwitz zeta function:
- .. math:: \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x},
- Riemann zeta function corresponds to ``q = 1``.
- See Also
- --------
- zetac
- Examples
- --------
- >>> from scipy.special import zeta, polygamma, factorial
- Some specific values:
- >>> zeta(2), np.pi**2/6
- (1.6449340668482266, 1.6449340668482264)
- >>> zeta(4), np.pi**4/90
- (1.0823232337111381, 1.082323233711138)
- Relation to the `polygamma` function:
- >>> m = 3
- >>> x = 1.25
- >>> polygamma(m, x)
- array(2.782144009188397)
- >>> (-1)**(m+1) * factorial(m) * zeta(m+1, x)
- 2.7821440091883969
- """
- if q is None:
- q = 1
- return _zeta(x, q, out)
|