numbers.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563
  1. """
  2. This module implements some special functions that commonly appear in
  3. combinatorial contexts (e.g. in power series); in particular,
  4. sequences of rational numbers such as Bernoulli and Fibonacci numbers.
  5. Factorials, binomial coefficients and related functions are located in
  6. the separate 'factorials' module.
  7. """
  8. from math import prod
  9. from collections import defaultdict
  10. from typing import Tuple as tTuple
  11. from sympy.core import S, Symbol, Add, Dummy
  12. from sympy.core.cache import cacheit
  13. from sympy.core.expr import Expr
  14. from sympy.core.function import ArgumentIndexError, Function, expand_mul
  15. from sympy.core.logic import fuzzy_not
  16. from sympy.core.mul import Mul
  17. from sympy.core.numbers import E, I, pi, oo, Rational, Integer
  18. from sympy.core.relational import Eq, is_le, is_gt
  19. from sympy.external.gmpy import SYMPY_INTS
  20. from sympy.functions.combinatorial.factorials import (binomial,
  21. factorial, subfactorial)
  22. from sympy.functions.elementary.exponential import log
  23. from sympy.functions.elementary.piecewise import Piecewise
  24. from sympy.ntheory.primetest import isprime, is_square
  25. from sympy.polys.appellseqs import bernoulli_poly, euler_poly, genocchi_poly
  26. from sympy.utilities.enumerative import MultisetPartitionTraverser
  27. from sympy.utilities.exceptions import sympy_deprecation_warning
  28. from sympy.utilities.iterables import multiset, multiset_derangements, iterable
  29. from sympy.utilities.memoization import recurrence_memo
  30. from sympy.utilities.misc import as_int
  31. from mpmath import mp, workprec
  32. from mpmath.libmp import ifib as _ifib
  33. def _product(a, b):
  34. return prod(range(a, b + 1))
  35. # Dummy symbol used for computing polynomial sequences
  36. _sym = Symbol('x')
  37. #----------------------------------------------------------------------------#
  38. # #
  39. # Carmichael numbers #
  40. # #
  41. #----------------------------------------------------------------------------#
  42. def _divides(p, n):
  43. return n % p == 0
  44. class carmichael(Function):
  45. r"""
  46. Carmichael Numbers:
  47. Certain cryptographic algorithms make use of big prime numbers.
  48. However, checking whether a big number is prime is not so easy.
  49. Randomized prime number checking tests exist that offer a high degree of
  50. confidence of accurate determination at low cost, such as the Fermat test.
  51. Let 'a' be a random number between $2$ and $n - 1$, where $n$ is the
  52. number whose primality we are testing. Then, $n$ is probably prime if it
  53. satisfies the modular arithmetic congruence relation:
  54. .. math :: a^{n-1} = 1 \pmod{n}
  55. (where mod refers to the modulo operation)
  56. If a number passes the Fermat test several times, then it is prime with a
  57. high probability.
  58. Unfortunately, certain composite numbers (non-primes) still pass the Fermat
  59. test with every number smaller than themselves.
  60. These numbers are called Carmichael numbers.
  61. A Carmichael number will pass a Fermat primality test to every base $b$
  62. relatively prime to the number, even though it is not actually prime.
  63. This makes tests based on Fermat's Little Theorem less effective than
  64. strong probable prime tests such as the Baillie-PSW primality test and
  65. the Miller-Rabin primality test.
  66. Examples
  67. ========
  68. >>> from sympy import carmichael
  69. >>> carmichael.find_first_n_carmichaels(5)
  70. [561, 1105, 1729, 2465, 2821]
  71. >>> carmichael.find_carmichael_numbers_in_range(0, 562)
  72. [561]
  73. >>> carmichael.find_carmichael_numbers_in_range(0,1000)
  74. [561]
  75. >>> carmichael.find_carmichael_numbers_in_range(0,2000)
  76. [561, 1105, 1729]
  77. References
  78. ==========
  79. .. [1] https://en.wikipedia.org/wiki/Carmichael_number
  80. .. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
  81. .. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
  82. """
  83. @staticmethod
  84. def is_perfect_square(n):
  85. sympy_deprecation_warning(
  86. """
  87. is_perfect_square is just a wrapper around sympy.ntheory.primetest.is_square
  88. so use that directly instead.
  89. """,
  90. deprecated_since_version="1.11",
  91. active_deprecations_target='deprecated-carmichael-static-methods',
  92. )
  93. return is_square(n)
  94. @staticmethod
  95. def divides(p, n):
  96. sympy_deprecation_warning(
  97. """
  98. divides can be replaced by directly testing n % p == 0.
  99. """,
  100. deprecated_since_version="1.11",
  101. active_deprecations_target='deprecated-carmichael-static-methods',
  102. )
  103. return n % p == 0
  104. @staticmethod
  105. def is_prime(n):
  106. sympy_deprecation_warning(
  107. """
  108. is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that
  109. directly instead.
  110. """,
  111. deprecated_since_version="1.11",
  112. active_deprecations_target='deprecated-carmichael-static-methods',
  113. )
  114. return isprime(n)
  115. @staticmethod
  116. def is_carmichael(n):
  117. if n >= 0:
  118. if (n == 1) or isprime(n) or (n % 2 == 0):
  119. return False
  120. divisors = [1, n]
  121. # get divisors
  122. divisors.extend([i for i in range(3, n // 2 + 1, 2) if n % i == 0])
  123. for i in divisors:
  124. if is_square(i) and i != 1:
  125. return False
  126. if isprime(i):
  127. if not _divides(i - 1, n - 1):
  128. return False
  129. return True
  130. else:
  131. raise ValueError('The provided number must be greater than or equal to 0')
  132. @staticmethod
  133. def find_carmichael_numbers_in_range(x, y):
  134. if 0 <= x <= y:
  135. if x % 2 == 0:
  136. return [i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)]
  137. else:
  138. return [i for i in range(x, y, 2) if carmichael.is_carmichael(i)]
  139. else:
  140. raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
  141. @staticmethod
  142. def find_first_n_carmichaels(n):
  143. i = 1
  144. carmichaels = []
  145. while len(carmichaels) < n:
  146. if carmichael.is_carmichael(i):
  147. carmichaels.append(i)
  148. i += 2
  149. return carmichaels
  150. #----------------------------------------------------------------------------#
  151. # #
  152. # Fibonacci numbers #
  153. # #
  154. #----------------------------------------------------------------------------#
  155. class fibonacci(Function):
  156. r"""
  157. Fibonacci numbers / Fibonacci polynomials
  158. The Fibonacci numbers are the integer sequence defined by the
  159. initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence
  160. relation `F_n = F_{n-1} + F_{n-2}`. This definition
  161. extended to arbitrary real and complex arguments using
  162. the formula
  163. .. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}
  164. The Fibonacci polynomials are defined by `F_1(x) = 1`,
  165. `F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
  166. For all positive integers `n`, `F_n(1) = F_n`.
  167. * ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
  168. * ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`
  169. Examples
  170. ========
  171. >>> from sympy import fibonacci, Symbol
  172. >>> [fibonacci(x) for x in range(11)]
  173. [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
  174. >>> fibonacci(5, Symbol('t'))
  175. t**4 + 3*t**2 + 1
  176. See Also
  177. ========
  178. bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci
  179. References
  180. ==========
  181. .. [1] https://en.wikipedia.org/wiki/Fibonacci_number
  182. .. [2] https://mathworld.wolfram.com/FibonacciNumber.html
  183. """
  184. @staticmethod
  185. def _fib(n):
  186. return _ifib(n)
  187. @staticmethod
  188. @recurrence_memo([None, S.One, _sym])
  189. def _fibpoly(n, prev):
  190. return (prev[-2] + _sym*prev[-1]).expand()
  191. @classmethod
  192. def eval(cls, n, sym=None):
  193. if n is S.Infinity:
  194. return S.Infinity
  195. if n.is_Integer:
  196. if sym is None:
  197. n = int(n)
  198. if n < 0:
  199. return S.NegativeOne**(n + 1) * fibonacci(-n)
  200. else:
  201. return Integer(cls._fib(n))
  202. else:
  203. if n < 1:
  204. raise ValueError("Fibonacci polynomials are defined "
  205. "only for positive integer indices.")
  206. return cls._fibpoly(n).subs(_sym, sym)
  207. def _eval_rewrite_as_sqrt(self, n, **kwargs):
  208. from sympy.functions.elementary.miscellaneous import sqrt
  209. return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
  210. def _eval_rewrite_as_GoldenRatio(self,n, **kwargs):
  211. return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1)
  212. #----------------------------------------------------------------------------#
  213. # #
  214. # Lucas numbers #
  215. # #
  216. #----------------------------------------------------------------------------#
  217. class lucas(Function):
  218. """
  219. Lucas numbers
  220. Lucas numbers satisfy a recurrence relation similar to that of
  221. the Fibonacci sequence, in which each term is the sum of the
  222. preceding two. They are generated by choosing the initial
  223. values `L_0 = 2` and `L_1 = 1`.
  224. * ``lucas(n)`` gives the `n^{th}` Lucas number
  225. Examples
  226. ========
  227. >>> from sympy import lucas
  228. >>> [lucas(x) for x in range(11)]
  229. [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
  230. See Also
  231. ========
  232. bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci
  233. References
  234. ==========
  235. .. [1] https://en.wikipedia.org/wiki/Lucas_number
  236. .. [2] https://mathworld.wolfram.com/LucasNumber.html
  237. """
  238. @classmethod
  239. def eval(cls, n):
  240. if n is S.Infinity:
  241. return S.Infinity
  242. if n.is_Integer:
  243. return fibonacci(n + 1) + fibonacci(n - 1)
  244. def _eval_rewrite_as_sqrt(self, n, **kwargs):
  245. from sympy.functions.elementary.miscellaneous import sqrt
  246. return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n)
  247. #----------------------------------------------------------------------------#
  248. # #
  249. # Tribonacci numbers #
  250. # #
  251. #----------------------------------------------------------------------------#
  252. class tribonacci(Function):
  253. r"""
  254. Tribonacci numbers / Tribonacci polynomials
  255. The Tribonacci numbers are the integer sequence defined by the
  256. initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
  257. recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.
  258. The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
  259. `T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
  260. for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`.
  261. * ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
  262. * ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`
  263. Examples
  264. ========
  265. >>> from sympy import tribonacci, Symbol
  266. >>> [tribonacci(x) for x in range(11)]
  267. [0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
  268. >>> tribonacci(5, Symbol('t'))
  269. t**8 + 3*t**5 + 3*t**2
  270. See Also
  271. ========
  272. bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition
  273. References
  274. ==========
  275. .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
  276. .. [2] https://mathworld.wolfram.com/TribonacciNumber.html
  277. .. [3] https://oeis.org/A000073
  278. """
  279. @staticmethod
  280. @recurrence_memo([S.Zero, S.One, S.One])
  281. def _trib(n, prev):
  282. return (prev[-3] + prev[-2] + prev[-1])
  283. @staticmethod
  284. @recurrence_memo([S.Zero, S.One, _sym**2])
  285. def _tribpoly(n, prev):
  286. return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand()
  287. @classmethod
  288. def eval(cls, n, sym=None):
  289. if n is S.Infinity:
  290. return S.Infinity
  291. if n.is_Integer:
  292. n = int(n)
  293. if n < 0:
  294. raise ValueError("Tribonacci polynomials are defined "
  295. "only for non-negative integer indices.")
  296. if sym is None:
  297. return Integer(cls._trib(n))
  298. else:
  299. return cls._tribpoly(n).subs(_sym, sym)
  300. def _eval_rewrite_as_sqrt(self, n, **kwargs):
  301. from sympy.functions.elementary.miscellaneous import cbrt, sqrt
  302. w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
  303. a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
  304. b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
  305. c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
  306. Tn = (a**(n + 1)/((a - b)*(a - c))
  307. + b**(n + 1)/((b - a)*(b - c))
  308. + c**(n + 1)/((c - a)*(c - b)))
  309. return Tn
  310. def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs):
  311. from sympy.functions.elementary.integers import floor
  312. from sympy.functions.elementary.miscellaneous import cbrt, sqrt
  313. b = cbrt(586 + 102*sqrt(33))
  314. Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4)
  315. return floor(Tn + S.Half)
  316. #----------------------------------------------------------------------------#
  317. # #
  318. # Bernoulli numbers #
  319. # #
  320. #----------------------------------------------------------------------------#
  321. class bernoulli(Function):
  322. r"""
  323. Bernoulli numbers / Bernoulli polynomials / Bernoulli function
  324. The Bernoulli numbers are a sequence of rational numbers
  325. defined by `B_0 = 1` and the recursive relation (`n > 0`):
  326. .. math :: n+1 = \sum_{k=0}^n \binom{n+1}{k} B_k
  327. They are also commonly defined by their exponential generating
  328. function, which is `\frac{x}{1 - e^{-x}}`. For odd indices > 1,
  329. the Bernoulli numbers are zero.
  330. The Bernoulli polynomials satisfy the analogous formula:
  331. .. math :: B_n(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} B_k x^{n-k}
  332. Bernoulli numbers and Bernoulli polynomials are related as
  333. `B_n(1) = B_n`.
  334. The generalized Bernoulli function `\operatorname{B}(s, a)`
  335. is defined for any complex `s` and `a`, except where `a` is a
  336. nonpositive integer and `s` is not a nonnegative integer. It is
  337. an entire function of `s` for fixed `a`, related to the Hurwitz
  338. zeta function by
  339. .. math:: \operatorname{B}(s, a) = \begin{cases}
  340. -s \zeta(1-s, a) & s \ne 0 \\ 1 & s = 0 \end{cases}
  341. When `s` is a nonnegative integer this function reduces to the
  342. Bernoulli polynomials: `\operatorname{B}(n, x) = B_n(x)`. When
  343. `a` is omitted it is assumed to be 1, yielding the (ordinary)
  344. Bernoulli function which interpolates the Bernoulli numbers and is
  345. related to the Riemann zeta function.
  346. We compute Bernoulli numbers using Ramanujan's formula:
  347. .. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}
  348. where:
  349. .. math :: A(n) = \begin{cases} \frac{n+3}{3} &
  350. n \equiv 0\ \text{or}\ 2 \pmod{6} \\
  351. -\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}
  352. and:
  353. .. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}
  354. This formula is similar to the sum given in the definition, but
  355. cuts `\frac{2}{3}` of the terms. For Bernoulli polynomials, we use
  356. Appell sequences.
  357. For `n` a nonnegative integer and `s`, `a`, `x` arbitrary complex numbers,
  358. * ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
  359. * ``bernoulli(s)`` gives the Bernoulli function `\operatorname{B}(s)`
  360. * ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
  361. * ``bernoulli(s, a)`` gives the generalized Bernoulli function
  362. `\operatorname{B}(s, a)`
  363. .. versionchanged:: 1.12
  364. ``bernoulli(1)`` gives `+\frac{1}{2}` instead of `-\frac{1}{2}`.
  365. This choice of value confers several theoretical advantages [5]_,
  366. including the extension to complex parameters described above
  367. which this function now implements. The previous behavior, defined
  368. only for nonnegative integers `n`, can be obtained with
  369. ``(-1)**n*bernoulli(n)``.
  370. Examples
  371. ========
  372. >>> from sympy import bernoulli
  373. >>> from sympy.abc import x
  374. >>> [bernoulli(n) for n in range(11)]
  375. [1, 1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
  376. >>> bernoulli(1000001)
  377. 0
  378. >>> bernoulli(3, x)
  379. x**3 - 3*x**2/2 + x/2
  380. See Also
  381. ========
  382. andre, bell, catalan, euler, fibonacci, harmonic, lucas, genocchi,
  383. partition, tribonacci, sympy.polys.appellseqs.bernoulli_poly
  384. References
  385. ==========
  386. .. [1] https://en.wikipedia.org/wiki/Bernoulli_number
  387. .. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
  388. .. [3] https://mathworld.wolfram.com/BernoulliNumber.html
  389. .. [4] https://mathworld.wolfram.com/BernoulliPolynomial.html
  390. .. [5] Peter Luschny, "The Bernoulli Manifesto",
  391. https://luschny.de/math/zeta/The-Bernoulli-Manifesto.html
  392. .. [6] Peter Luschny, "An introduction to the Bernoulli function",
  393. https://arxiv.org/abs/2009.06743
  394. """
  395. args: tTuple[Integer]
  396. # Calculates B_n for positive even n
  397. @staticmethod
  398. def _calc_bernoulli(n):
  399. s = 0
  400. a = int(binomial(n + 3, n - 6))
  401. for j in range(1, n//6 + 1):
  402. s += a * bernoulli(n - 6*j)
  403. # Avoid computing each binomial coefficient from scratch
  404. a *= _product(n - 6 - 6*j + 1, n - 6*j)
  405. a //= _product(6*j + 4, 6*j + 9)
  406. if n % 6 == 4:
  407. s = -Rational(n + 3, 6) - s
  408. else:
  409. s = Rational(n + 3, 3) - s
  410. return s / binomial(n + 3, n)
  411. # We implement a specialized memoization scheme to handle each
  412. # case modulo 6 separately
  413. _cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)}
  414. _highest = {0: 0, 2: 2, 4: 4}
  415. @classmethod
  416. def eval(cls, n, x=None):
  417. if x is S.One:
  418. return cls(n)
  419. elif n.is_zero:
  420. return S.One
  421. elif n.is_integer is False or n.is_nonnegative is False:
  422. if x is not None and x.is_Integer and x.is_nonpositive:
  423. return S.NaN
  424. return
  425. # Bernoulli numbers
  426. elif x is None:
  427. if n is S.One:
  428. return S.Half
  429. elif n.is_odd and (n-1).is_positive:
  430. return S.Zero
  431. elif n.is_Number:
  432. n = int(n)
  433. # Use mpmath for enormous Bernoulli numbers
  434. if n > 500:
  435. p, q = mp.bernfrac(n)
  436. return Rational(int(p), int(q))
  437. case = n % 6
  438. highest_cached = cls._highest[case]
  439. if n <= highest_cached:
  440. return cls._cache[n]
  441. # To avoid excessive recursion when, say, bernoulli(1000) is
  442. # requested, calculate and cache the entire sequence ... B_988,
  443. # B_994, B_1000 in increasing order
  444. for i in range(highest_cached + 6, n + 6, 6):
  445. b = cls._calc_bernoulli(i)
  446. cls._cache[i] = b
  447. cls._highest[case] = i
  448. return b
  449. # Bernoulli polynomials
  450. elif n.is_Number:
  451. return bernoulli_poly(n, x)
  452. def _eval_rewrite_as_zeta(self, n, x=1, **kwargs):
  453. from sympy.functions.special.zeta_functions import zeta
  454. return Piecewise((1, Eq(n, 0)), (-n * zeta(1-n, x), True))
  455. def _eval_evalf(self, prec):
  456. if not all(x.is_number for x in self.args):
  457. return
  458. n = self.args[0]._to_mpmath(prec)
  459. x = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
  460. with workprec(prec):
  461. if n == 0:
  462. res = mp.mpf(1)
  463. elif n == 1:
  464. res = x - mp.mpf(0.5)
  465. elif mp.isint(n) and n >= 0:
  466. res = mp.bernoulli(n) if x == 1 else mp.bernpoly(n, x)
  467. else:
  468. res = -n * mp.zeta(1-n, x)
  469. return Expr._from_mpmath(res, prec)
  470. #----------------------------------------------------------------------------#
  471. # #
  472. # Bell numbers #
  473. # #
  474. #----------------------------------------------------------------------------#
  475. class bell(Function):
  476. r"""
  477. Bell numbers / Bell polynomials
  478. The Bell numbers satisfy `B_0 = 1` and
  479. .. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.
  480. They are also given by:
  481. .. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
  482. The Bell polynomials are given by `B_0(x) = 1` and
  483. .. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).
  484. The second kind of Bell polynomials (are sometimes called "partial" Bell
  485. polynomials or incomplete Bell polynomials) are defined as
  486. .. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
  487. \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
  488. \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
  489. \left(\frac{x_1}{1!} \right)^{j_1}
  490. \left(\frac{x_2}{2!} \right)^{j_2} \dotsb
  491. \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
  492. * ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
  493. * ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
  494. * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
  495. `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
  496. Notes
  497. =====
  498. Not to be confused with Bernoulli numbers and Bernoulli polynomials,
  499. which use the same notation.
  500. Examples
  501. ========
  502. >>> from sympy import bell, Symbol, symbols
  503. >>> [bell(n) for n in range(11)]
  504. [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
  505. >>> bell(30)
  506. 846749014511809332450147
  507. >>> bell(4, Symbol('t'))
  508. t**4 + 6*t**3 + 7*t**2 + t
  509. >>> bell(6, 2, symbols('x:6')[1:])
  510. 6*x1*x5 + 15*x2*x4 + 10*x3**2
  511. See Also
  512. ========
  513. bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
  514. References
  515. ==========
  516. .. [1] https://en.wikipedia.org/wiki/Bell_number
  517. .. [2] https://mathworld.wolfram.com/BellNumber.html
  518. .. [3] https://mathworld.wolfram.com/BellPolynomial.html
  519. """
  520. @staticmethod
  521. @recurrence_memo([1, 1])
  522. def _bell(n, prev):
  523. s = 1
  524. a = 1
  525. for k in range(1, n):
  526. a = a * (n - k) // k
  527. s += a * prev[k]
  528. return s
  529. @staticmethod
  530. @recurrence_memo([S.One, _sym])
  531. def _bell_poly(n, prev):
  532. s = 1
  533. a = 1
  534. for k in range(2, n + 1):
  535. a = a * (n - k + 1) // (k - 1)
  536. s += a * prev[k - 1]
  537. return expand_mul(_sym * s)
  538. @staticmethod
  539. def _bell_incomplete_poly(n, k, symbols):
  540. r"""
  541. The second kind of Bell polynomials (incomplete Bell polynomials).
  542. Calculated by recurrence formula:
  543. .. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
  544. \sum_{m=1}^{n-k+1}
  545. \x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})
  546. where
  547. `B_{0,0} = 1;`
  548. `B_{n,0} = 0; for n \ge 1`
  549. `B_{0,k} = 0; for k \ge 1`
  550. """
  551. if (n == 0) and (k == 0):
  552. return S.One
  553. elif (n == 0) or (k == 0):
  554. return S.Zero
  555. s = S.Zero
  556. a = S.One
  557. for m in range(1, n - k + 2):
  558. s += a * bell._bell_incomplete_poly(
  559. n - m, k - 1, symbols) * symbols[m - 1]
  560. a = a * (n - m) / m
  561. return expand_mul(s)
  562. @classmethod
  563. def eval(cls, n, k_sym=None, symbols=None):
  564. if n is S.Infinity:
  565. if k_sym is None:
  566. return S.Infinity
  567. else:
  568. raise ValueError("Bell polynomial is not defined")
  569. if n.is_negative or n.is_integer is False:
  570. raise ValueError("a non-negative integer expected")
  571. if n.is_Integer and n.is_nonnegative:
  572. if k_sym is None:
  573. return Integer(cls._bell(int(n)))
  574. elif symbols is None:
  575. return cls._bell_poly(int(n)).subs(_sym, k_sym)
  576. else:
  577. r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
  578. return r
  579. def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs):
  580. from sympy.concrete.summations import Sum
  581. if (k_sym is not None) or (symbols is not None):
  582. return self
  583. # Dobinski's formula
  584. if not n.is_nonnegative:
  585. return self
  586. k = Dummy('k', integer=True, nonnegative=True)
  587. return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity))
  588. #----------------------------------------------------------------------------#
  589. # #
  590. # Harmonic numbers #
  591. # #
  592. #----------------------------------------------------------------------------#
  593. class harmonic(Function):
  594. r"""
  595. Harmonic numbers
  596. The nth harmonic number is given by `\operatorname{H}_{n} =
  597. 1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
  598. More generally:
  599. .. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
  600. As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
  601. the Riemann zeta function.
  602. * ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`
  603. * ``harmonic(n, m)`` gives the nth generalized harmonic number
  604. of order `m`, `\operatorname{H}_{n,m}`, where
  605. ``harmonic(n) == harmonic(n, 1)``
  606. This function can be extended to complex `n` and `m` where `n` is not a
  607. negative integer or `m` is a nonpositive integer as
  608. .. math:: \operatorname{H}_{n,m} = \begin{cases} \zeta(m) - \zeta(m, n+1)
  609. & m \ne 1 \\ \psi(n+1) + \gamma & m = 1 \end{cases}
  610. Examples
  611. ========
  612. >>> from sympy import harmonic, oo
  613. >>> [harmonic(n) for n in range(6)]
  614. [0, 1, 3/2, 11/6, 25/12, 137/60]
  615. >>> [harmonic(n, 2) for n in range(6)]
  616. [0, 1, 5/4, 49/36, 205/144, 5269/3600]
  617. >>> harmonic(oo, 2)
  618. pi**2/6
  619. >>> from sympy import Symbol, Sum
  620. >>> n = Symbol("n")
  621. >>> harmonic(n).rewrite(Sum)
  622. Sum(1/_k, (_k, 1, n))
  623. We can evaluate harmonic numbers for all integral and positive
  624. rational arguments:
  625. >>> from sympy import S, expand_func, simplify
  626. >>> harmonic(8)
  627. 761/280
  628. >>> harmonic(11)
  629. 83711/27720
  630. >>> H = harmonic(1/S(3))
  631. >>> H
  632. harmonic(1/3)
  633. >>> He = expand_func(H)
  634. >>> He
  635. -log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
  636. + 3*Sum(1/(3*_k + 1), (_k, 0, 0))
  637. >>> He.doit()
  638. -log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
  639. >>> H = harmonic(25/S(7))
  640. >>> He = simplify(expand_func(H).doit())
  641. >>> He
  642. log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900
  643. >>> He.n(40)
  644. 1.983697455232980674869851942390639915940
  645. >>> harmonic(25/S(7)).n(40)
  646. 1.983697455232980674869851942390639915940
  647. We can rewrite harmonic numbers in terms of polygamma functions:
  648. >>> from sympy import digamma, polygamma
  649. >>> m = Symbol("m", integer=True, positive=True)
  650. >>> harmonic(n).rewrite(digamma)
  651. polygamma(0, n + 1) + EulerGamma
  652. >>> harmonic(n).rewrite(polygamma)
  653. polygamma(0, n + 1) + EulerGamma
  654. >>> harmonic(n,3).rewrite(polygamma)
  655. polygamma(2, n + 1)/2 + zeta(3)
  656. >>> simplify(harmonic(n,m).rewrite(polygamma))
  657. Piecewise((polygamma(0, n + 1) + EulerGamma, Eq(m, 1)),
  658. (-(-1)**m*polygamma(m - 1, n + 1)/factorial(m - 1) + zeta(m), True))
  659. Integer offsets in the argument can be pulled out:
  660. >>> from sympy import expand_func
  661. >>> expand_func(harmonic(n+4))
  662. harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
  663. >>> expand_func(harmonic(n-4))
  664. harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
  665. Some limits can be computed as well:
  666. >>> from sympy import limit, oo
  667. >>> limit(harmonic(n), n, oo)
  668. oo
  669. >>> limit(harmonic(n, 2), n, oo)
  670. pi**2/6
  671. >>> limit(harmonic(n, 3), n, oo)
  672. zeta(3)
  673. For `m > 1`, `H_{n,m}` tends to `\zeta(m)` in the limit of infinite `n`:
  674. >>> m = Symbol("m", positive=True)
  675. >>> limit(harmonic(n, m+1), n, oo)
  676. zeta(m + 1)
  677. See Also
  678. ========
  679. bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci
  680. References
  681. ==========
  682. .. [1] https://en.wikipedia.org/wiki/Harmonic_number
  683. .. [2] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
  684. .. [3] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/
  685. """
  686. @classmethod
  687. def eval(cls, n, m=None):
  688. from sympy.functions.special.zeta_functions import zeta
  689. if m is S.One:
  690. return cls(n)
  691. if m is None:
  692. m = S.One
  693. if n.is_zero:
  694. return S.Zero
  695. elif m.is_zero:
  696. return n
  697. elif n is S.Infinity:
  698. if m.is_negative:
  699. return S.NaN
  700. elif is_le(m, S.One):
  701. return S.Infinity
  702. elif is_gt(m, S.One):
  703. return zeta(m)
  704. elif m.is_Integer and m.is_nonpositive:
  705. return (bernoulli(1-m, n+1) - bernoulli(1-m)) / (1-m)
  706. elif n.is_Integer:
  707. if n.is_negative and (m.is_integer is False or m.is_nonpositive is False):
  708. return S.ComplexInfinity if m is S.One else S.NaN
  709. if n.is_nonnegative:
  710. return Add(*(k**(-m) for k in range(1, int(n)+1)))
  711. def _eval_rewrite_as_polygamma(self, n, m=S.One, **kwargs):
  712. from sympy.functions.special.gamma_functions import gamma, polygamma
  713. if m.is_integer and m.is_positive:
  714. return Piecewise((polygamma(0, n+1) + S.EulerGamma, Eq(m, 1)),
  715. (S.NegativeOne**m * (polygamma(m-1, 1) - polygamma(m-1, n+1)) /
  716. gamma(m), True))
  717. def _eval_rewrite_as_digamma(self, n, m=1, **kwargs):
  718. from sympy.functions.special.gamma_functions import polygamma
  719. return self.rewrite(polygamma)
  720. def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs):
  721. from sympy.functions.special.gamma_functions import polygamma
  722. return self.rewrite(polygamma)
  723. def _eval_rewrite_as_Sum(self, n, m=None, **kwargs):
  724. from sympy.concrete.summations import Sum
  725. k = Dummy("k", integer=True)
  726. if m is None:
  727. m = S.One
  728. return Sum(k**(-m), (k, 1, n))
  729. def _eval_rewrite_as_zeta(self, n, m=S.One, **kwargs):
  730. from sympy.functions.special.zeta_functions import zeta
  731. from sympy.functions.special.gamma_functions import digamma
  732. return Piecewise((digamma(n + 1) + S.EulerGamma, Eq(m, 1)),
  733. (zeta(m) - zeta(m, n+1), True))
  734. def _eval_expand_func(self, **hints):
  735. from sympy.concrete.summations import Sum
  736. n = self.args[0]
  737. m = self.args[1] if len(self.args) == 2 else 1
  738. if m == S.One:
  739. if n.is_Add:
  740. off = n.args[0]
  741. nnew = n - off
  742. if off.is_Integer and off.is_positive:
  743. result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)]
  744. return Add(*result)
  745. elif off.is_Integer and off.is_negative:
  746. result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)]
  747. return Add(*result)
  748. if n.is_Rational:
  749. # Expansions for harmonic numbers at general rational arguments (u + p/q)
  750. # Split n as u + p/q with p < q
  751. p, q = n.as_numer_denom()
  752. u = p // q
  753. p = p - u * q
  754. if u.is_nonnegative and p.is_positive and q.is_positive and p < q:
  755. from sympy.functions.elementary.exponential import log
  756. from sympy.functions.elementary.integers import floor
  757. from sympy.functions.elementary.trigonometric import sin, cos, cot
  758. k = Dummy("k")
  759. t1 = q * Sum(1 / (q * k + p), (k, 0, u))
  760. t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) *
  761. log(sin((pi * k) / S(q))),
  762. (k, 1, floor((q - 1) / S(2))))
  763. t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q)
  764. return t1 + t2 - t3
  765. return self
  766. def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs):
  767. from sympy.functions.special.zeta_functions import zeta
  768. from sympy.functions.special.gamma_functions import polygamma
  769. pg = self.rewrite(polygamma)
  770. if not isinstance(pg, harmonic):
  771. return pg.rewrite("tractable", deep=True)
  772. arg = m - S.One
  773. if arg.is_nonzero:
  774. return (zeta(m) - zeta(m, n+1)).rewrite("tractable", deep=True)
  775. def _eval_evalf(self, prec):
  776. if not all(x.is_number for x in self.args):
  777. return
  778. n = self.args[0]._to_mpmath(prec)
  779. m = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
  780. if mp.isint(n) and n < 0:
  781. return S.NaN
  782. with workprec(prec):
  783. if m == 1:
  784. res = mp.harmonic(n)
  785. else:
  786. res = mp.zeta(m) - mp.zeta(m, n+1)
  787. return Expr._from_mpmath(res, prec)
  788. def fdiff(self, argindex=1):
  789. from sympy.functions.special.zeta_functions import zeta
  790. if len(self.args) == 2:
  791. n, m = self.args
  792. else:
  793. n, m = self.args + (1,)
  794. if argindex == 1:
  795. return m * zeta(m+1, n+1)
  796. else:
  797. raise ArgumentIndexError
  798. #----------------------------------------------------------------------------#
  799. # #
  800. # Euler numbers #
  801. # #
  802. #----------------------------------------------------------------------------#
  803. class euler(Function):
  804. r"""
  805. Euler numbers / Euler polynomials / Euler function
  806. The Euler numbers are given by:
  807. .. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
  808. \frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}
  809. .. math:: E_{2n+1} = 0
  810. Euler numbers and Euler polynomials are related by
  811. .. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).
  812. We compute symbolic Euler polynomials using Appell sequences,
  813. but numerical evaluation of the Euler polynomial is computed
  814. more efficiently (and more accurately) using the mpmath library.
  815. The Euler polynomials are special cases of the generalized Euler function,
  816. related to the Genocchi function as
  817. .. math:: \operatorname{E}(s, a) = -\frac{\operatorname{G}(s+1, a)}{s+1}
  818. with the limit of `\psi\left(\frac{a+1}{2}\right) - \psi\left(\frac{a}{2}\right)`
  819. being taken when `s = -1`. The (ordinary) Euler function interpolating
  820. the Euler numbers is then obtained as
  821. `\operatorname{E}(s) = 2^s \operatorname{E}\left(s, \frac{1}{2}\right)`.
  822. * ``euler(n)`` gives the nth Euler number `E_n`.
  823. * ``euler(s)`` gives the Euler function `\operatorname{E}(s)`.
  824. * ``euler(n, x)`` gives the nth Euler polynomial `E_n(x)`.
  825. * ``euler(s, a)`` gives the generalized Euler function `\operatorname{E}(s, a)`.
  826. Examples
  827. ========
  828. >>> from sympy import euler, Symbol, S
  829. >>> [euler(n) for n in range(10)]
  830. [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
  831. >>> [2**n*euler(n,1) for n in range(10)]
  832. [1, 1, 0, -2, 0, 16, 0, -272, 0, 7936]
  833. >>> n = Symbol("n")
  834. >>> euler(n + 2*n)
  835. euler(3*n)
  836. >>> x = Symbol("x")
  837. >>> euler(n, x)
  838. euler(n, x)
  839. >>> euler(0, x)
  840. 1
  841. >>> euler(1, x)
  842. x - 1/2
  843. >>> euler(2, x)
  844. x**2 - x
  845. >>> euler(3, x)
  846. x**3 - 3*x**2/2 + 1/4
  847. >>> euler(4, x)
  848. x**4 - 2*x**3 + x
  849. >>> euler(12, S.Half)
  850. 2702765/4096
  851. >>> euler(12)
  852. 2702765
  853. See Also
  854. ========
  855. andre, bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi,
  856. partition, tribonacci, sympy.polys.appellseqs.euler_poly
  857. References
  858. ==========
  859. .. [1] https://en.wikipedia.org/wiki/Euler_numbers
  860. .. [2] https://mathworld.wolfram.com/EulerNumber.html
  861. .. [3] https://en.wikipedia.org/wiki/Alternating_permutation
  862. .. [4] https://mathworld.wolfram.com/AlternatingPermutation.html
  863. """
  864. @classmethod
  865. def eval(cls, n, x=None):
  866. if n.is_zero:
  867. return S.One
  868. elif n is S.NegativeOne:
  869. if x is None:
  870. return S.Pi/2
  871. from sympy.functions.special.gamma_functions import digamma
  872. return digamma((x+1)/2) - digamma(x/2)
  873. elif n.is_integer is False or n.is_nonnegative is False:
  874. return
  875. # Euler numbers
  876. elif x is None:
  877. if n.is_odd and n.is_positive:
  878. return S.Zero
  879. elif n.is_Number:
  880. from mpmath import mp
  881. n = n._to_mpmath(mp.prec)
  882. res = mp.eulernum(n, exact=True)
  883. return Integer(res)
  884. # Euler polynomials
  885. elif n.is_Number:
  886. return euler_poly(n, x)
  887. def _eval_rewrite_as_Sum(self, n, x=None, **kwargs):
  888. from sympy.concrete.summations import Sum
  889. if x is None and n.is_even:
  890. k = Dummy("k", integer=True)
  891. j = Dummy("j", integer=True)
  892. n = n / 2
  893. Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j *
  894. (k - 2*j)**(2*n + 1)) /
  895. (2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1)))
  896. return Em
  897. if x:
  898. k = Dummy("k", integer=True)
  899. return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n))
  900. def _eval_rewrite_as_genocchi(self, n, x=None, **kwargs):
  901. if x is None:
  902. return Piecewise((S.Pi/2, Eq(n, -1)),
  903. (-2**n * genocchi(n+1, S.Half) / (n+1), True))
  904. from sympy.functions.special.gamma_functions import digamma
  905. return Piecewise((digamma((x+1)/2) - digamma(x/2), Eq(n, -1)),
  906. (-genocchi(n+1, x) / (n+1), True))
  907. def _eval_evalf(self, prec):
  908. if not all(i.is_number for i in self.args):
  909. return
  910. from mpmath import mp
  911. m, x = (self.args[0], None) if len(self.args) == 1 else self.args
  912. m = m._to_mpmath(prec)
  913. if x is not None:
  914. x = x._to_mpmath(prec)
  915. with workprec(prec):
  916. if mp.isint(m) and m >= 0:
  917. res = mp.eulernum(m) if x is None else mp.eulerpoly(m, x)
  918. else:
  919. if m == -1:
  920. res = mp.pi if x is None else mp.digamma((x+1)/2) - mp.digamma(x/2)
  921. else:
  922. y = 0.5 if x is None else x
  923. res = 2 * (mp.zeta(-m, y) - 2**(m+1) * mp.zeta(-m, (y+1)/2))
  924. if x is None:
  925. res *= 2**m
  926. return Expr._from_mpmath(res, prec)
  927. #----------------------------------------------------------------------------#
  928. # #
  929. # Catalan numbers #
  930. # #
  931. #----------------------------------------------------------------------------#
  932. class catalan(Function):
  933. r"""
  934. Catalan numbers
  935. The `n^{th}` catalan number is given by:
  936. .. math :: C_n = \frac{1}{n+1} \binom{2n}{n}
  937. * ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`
  938. Examples
  939. ========
  940. >>> from sympy import (Symbol, binomial, gamma, hyper,
  941. ... catalan, diff, combsimp, Rational, I)
  942. >>> [catalan(i) for i in range(1,10)]
  943. [1, 2, 5, 14, 42, 132, 429, 1430, 4862]
  944. >>> n = Symbol("n", integer=True)
  945. >>> catalan(n)
  946. catalan(n)
  947. Catalan numbers can be transformed into several other, identical
  948. expressions involving other mathematical functions
  949. >>> catalan(n).rewrite(binomial)
  950. binomial(2*n, n)/(n + 1)
  951. >>> catalan(n).rewrite(gamma)
  952. 4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))
  953. >>> catalan(n).rewrite(hyper)
  954. hyper((1 - n, -n), (2,), 1)
  955. For some non-integer values of n we can get closed form
  956. expressions by rewriting in terms of gamma functions:
  957. >>> catalan(Rational(1, 2)).rewrite(gamma)
  958. 8/(3*pi)
  959. We can differentiate the Catalan numbers C(n) interpreted as a
  960. continuous real function in n:
  961. >>> diff(catalan(n), n)
  962. (polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)
  963. As a more advanced example consider the following ratio
  964. between consecutive numbers:
  965. >>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
  966. 2*(2*n + 1)/(n + 2)
  967. The Catalan numbers can be generalized to complex numbers:
  968. >>> catalan(I).rewrite(gamma)
  969. 4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))
  970. and evaluated with arbitrary precision:
  971. >>> catalan(I).evalf(20)
  972. 0.39764993382373624267 - 0.020884341620842555705*I
  973. See Also
  974. ========
  975. andre, bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi,
  976. partition, tribonacci, sympy.functions.combinatorial.factorials.binomial
  977. References
  978. ==========
  979. .. [1] https://en.wikipedia.org/wiki/Catalan_number
  980. .. [2] https://mathworld.wolfram.com/CatalanNumber.html
  981. .. [3] https://functions.wolfram.com/GammaBetaErf/CatalanNumber/
  982. .. [4] http://geometer.org/mathcircles/catalan.pdf
  983. """
  984. @classmethod
  985. def eval(cls, n):
  986. from sympy.functions.special.gamma_functions import gamma
  987. if (n.is_Integer and n.is_nonnegative) or \
  988. (n.is_noninteger and n.is_negative):
  989. return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
  990. if (n.is_integer and n.is_negative):
  991. if (n + 1).is_negative:
  992. return S.Zero
  993. if (n + 1).is_zero:
  994. return Rational(-1, 2)
  995. def fdiff(self, argindex=1):
  996. from sympy.functions.elementary.exponential import log
  997. from sympy.functions.special.gamma_functions import polygamma
  998. n = self.args[0]
  999. return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4))
  1000. def _eval_rewrite_as_binomial(self, n, **kwargs):
  1001. return binomial(2*n, n)/(n + 1)
  1002. def _eval_rewrite_as_factorial(self, n, **kwargs):
  1003. return factorial(2*n) / (factorial(n+1) * factorial(n))
  1004. def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
  1005. from sympy.functions.special.gamma_functions import gamma
  1006. # The gamma function allows to generalize Catalan numbers to complex n
  1007. return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
  1008. def _eval_rewrite_as_hyper(self, n, **kwargs):
  1009. from sympy.functions.special.hyper import hyper
  1010. return hyper([1 - n, -n], [2], 1)
  1011. def _eval_rewrite_as_Product(self, n, **kwargs):
  1012. from sympy.concrete.products import Product
  1013. if not (n.is_integer and n.is_nonnegative):
  1014. return self
  1015. k = Dummy('k', integer=True, positive=True)
  1016. return Product((n + k) / k, (k, 2, n))
  1017. def _eval_is_integer(self):
  1018. if self.args[0].is_integer and self.args[0].is_nonnegative:
  1019. return True
  1020. def _eval_is_positive(self):
  1021. if self.args[0].is_nonnegative:
  1022. return True
  1023. def _eval_is_composite(self):
  1024. if self.args[0].is_integer and (self.args[0] - 3).is_positive:
  1025. return True
  1026. def _eval_evalf(self, prec):
  1027. from sympy.functions.special.gamma_functions import gamma
  1028. if self.args[0].is_number:
  1029. return self.rewrite(gamma)._eval_evalf(prec)
  1030. #----------------------------------------------------------------------------#
  1031. # #
  1032. # Genocchi numbers #
  1033. # #
  1034. #----------------------------------------------------------------------------#
  1035. class genocchi(Function):
  1036. r"""
  1037. Genocchi numbers / Genocchi polynomials / Genocchi function
  1038. The Genocchi numbers are a sequence of integers `G_n` that satisfy the
  1039. relation:
  1040. .. math:: \frac{-2t}{1 + e^{-t}} = \sum_{n=0}^\infty \frac{G_n t^n}{n!}
  1041. They are related to the Bernoulli numbers by
  1042. .. math:: G_n = 2 (1 - 2^n) B_n
  1043. and generalize like the Bernoulli numbers to the Genocchi polynomials and
  1044. function as
  1045. .. math:: \operatorname{G}(s, a) = 2 \left(\operatorname{B}(s, a) -
  1046. 2^s \operatorname{B}\left(s, \frac{a+1}{2}\right)\right)
  1047. .. versionchanged:: 1.12
  1048. ``genocchi(1)`` gives `-1` instead of `1`.
  1049. Examples
  1050. ========
  1051. >>> from sympy import genocchi, Symbol
  1052. >>> [genocchi(n) for n in range(9)]
  1053. [0, -1, -1, 0, 1, 0, -3, 0, 17]
  1054. >>> n = Symbol('n', integer=True, positive=True)
  1055. >>> genocchi(2*n + 1)
  1056. 0
  1057. >>> x = Symbol('x')
  1058. >>> genocchi(4, x)
  1059. -4*x**3 + 6*x**2 - 1
  1060. See Also
  1061. ========
  1062. bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
  1063. sympy.polys.appellseqs.genocchi_poly
  1064. References
  1065. ==========
  1066. .. [1] https://en.wikipedia.org/wiki/Genocchi_number
  1067. .. [2] https://mathworld.wolfram.com/GenocchiNumber.html
  1068. .. [3] Peter Luschny, "An introduction to the Bernoulli function",
  1069. https://arxiv.org/abs/2009.06743
  1070. """
  1071. @classmethod
  1072. def eval(cls, n, x=None):
  1073. if x is S.One:
  1074. return cls(n)
  1075. elif n.is_integer is False or n.is_nonnegative is False:
  1076. return
  1077. # Genocchi numbers
  1078. elif x is None:
  1079. if n.is_odd and (n-1).is_positive:
  1080. return S.Zero
  1081. elif n.is_Number:
  1082. return 2 * (1-S(2)**n) * bernoulli(n)
  1083. # Genocchi polynomials
  1084. elif n.is_Number:
  1085. return genocchi_poly(n, x)
  1086. def _eval_rewrite_as_bernoulli(self, n, x=1, **kwargs):
  1087. if x == 1 and n.is_integer and n.is_nonnegative:
  1088. return 2 * (1-S(2)**n) * bernoulli(n)
  1089. return 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
  1090. def _eval_rewrite_as_dirichlet_eta(self, n, x=1, **kwargs):
  1091. from sympy.functions.special.zeta_functions import dirichlet_eta
  1092. return -2*n * dirichlet_eta(1-n, x)
  1093. def _eval_is_integer(self):
  1094. if len(self.args) > 1 and self.args[1] != 1:
  1095. return
  1096. n = self.args[0]
  1097. if n.is_integer and n.is_nonnegative:
  1098. return True
  1099. def _eval_is_negative(self):
  1100. if len(self.args) > 1 and self.args[1] != 1:
  1101. return
  1102. n = self.args[0]
  1103. if n.is_integer and n.is_nonnegative:
  1104. if n.is_odd:
  1105. return fuzzy_not((n-1).is_positive)
  1106. return (n/2).is_odd
  1107. def _eval_is_positive(self):
  1108. if len(self.args) > 1 and self.args[1] != 1:
  1109. return
  1110. n = self.args[0]
  1111. if n.is_integer and n.is_nonnegative:
  1112. if n.is_zero or n.is_odd:
  1113. return False
  1114. return (n/2).is_even
  1115. def _eval_is_even(self):
  1116. if len(self.args) > 1 and self.args[1] != 1:
  1117. return
  1118. n = self.args[0]
  1119. if n.is_integer and n.is_nonnegative:
  1120. if n.is_even:
  1121. return n.is_zero
  1122. return (n-1).is_positive
  1123. def _eval_is_odd(self):
  1124. if len(self.args) > 1 and self.args[1] != 1:
  1125. return
  1126. n = self.args[0]
  1127. if n.is_integer and n.is_nonnegative:
  1128. if n.is_even:
  1129. return fuzzy_not(n.is_zero)
  1130. return fuzzy_not((n-1).is_positive)
  1131. def _eval_is_prime(self):
  1132. if len(self.args) > 1 and self.args[1] != 1:
  1133. return
  1134. n = self.args[0]
  1135. # only G_6 = -3 and G_8 = 17 are prime,
  1136. # but SymPy does not consider negatives as prime
  1137. # so only n=8 is tested
  1138. return (n-8).is_zero
  1139. def _eval_evalf(self, prec):
  1140. if all(i.is_number for i in self.args):
  1141. return self.rewrite(bernoulli)._eval_evalf(prec)
  1142. #----------------------------------------------------------------------------#
  1143. # #
  1144. # Andre numbers #
  1145. # #
  1146. #----------------------------------------------------------------------------#
  1147. class andre(Function):
  1148. r"""
  1149. Andre numbers / Andre function
  1150. The Andre number `\mathcal{A}_n` is Luschny's name for half the number of
  1151. *alternating permutations* on `n` elements, where a permutation is alternating
  1152. if adjacent elements alternately compare "greater" and "smaller" going from
  1153. left to right. For example, `2 < 3 > 1 < 4` is an alternating permutation.
  1154. This sequence is A000111 in the OEIS, which assigns the names *up/down numbers*
  1155. and *Euler zigzag numbers*. It satisfies a recurrence relation similar to that
  1156. for the Catalan numbers, with `\mathcal{A}_0 = 1` and
  1157. .. math:: 2 \mathcal{A}_{n+1} = \sum_{k=0}^n \binom{n}{k} \mathcal{A}_k \mathcal{A}_{n-k}
  1158. The Bernoulli and Euler numbers are signed transformations of the odd- and
  1159. even-indexed elements of this sequence respectively:
  1160. .. math :: \operatorname{B}_{2k} = \frac{2k \mathcal{A}_{2k-1}}{(-4)^k - (-16)^k}
  1161. .. math :: \operatorname{E}_{2k} = (-1)^k \mathcal{A}_{2k}
  1162. Like the Bernoulli and Euler numbers, the Andre numbers are interpolated by the
  1163. entire Andre function:
  1164. .. math :: \mathcal{A}(s) = (-i)^{s+1} \operatorname{Li}_{-s}(i) +
  1165. i^{s+1} \operatorname{Li}_{-s}(-i) = \\ \frac{2 \Gamma(s+1)}{(2\pi)^{s+1}}
  1166. (\zeta(s+1, 1/4) - \zeta(s+1, 3/4) \cos{\pi s})
  1167. Examples
  1168. ========
  1169. >>> from sympy import andre, euler, bernoulli
  1170. >>> [andre(n) for n in range(11)]
  1171. [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
  1172. >>> [(-1)**k * andre(2*k) for k in range(7)]
  1173. [1, -1, 5, -61, 1385, -50521, 2702765]
  1174. >>> [euler(2*k) for k in range(7)]
  1175. [1, -1, 5, -61, 1385, -50521, 2702765]
  1176. >>> [andre(2*k-1) * (2*k) / ((-4)**k - (-16)**k) for k in range(1, 8)]
  1177. [1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
  1178. >>> [bernoulli(2*k) for k in range(1, 8)]
  1179. [1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
  1180. See Also
  1181. ========
  1182. bernoulli, catalan, euler, sympy.polys.appellseqs.andre_poly
  1183. References
  1184. ==========
  1185. .. [1] https://en.wikipedia.org/wiki/Alternating_permutation
  1186. .. [2] https://mathworld.wolfram.com/EulerZigzagNumber.html
  1187. .. [3] Peter Luschny, "An introduction to the Bernoulli function",
  1188. https://arxiv.org/abs/2009.06743
  1189. """
  1190. @classmethod
  1191. def eval(cls, n):
  1192. if n is S.NaN:
  1193. return S.NaN
  1194. elif n is S.Infinity:
  1195. return S.Infinity
  1196. if n.is_zero:
  1197. return S.One
  1198. elif n == -1:
  1199. return -log(2)
  1200. elif n == -2:
  1201. return -2*S.Catalan
  1202. elif n.is_Integer:
  1203. if n.is_nonnegative and n.is_even:
  1204. return abs(euler(n))
  1205. elif n.is_odd:
  1206. from sympy.functions.special.zeta_functions import zeta
  1207. m = -n-1
  1208. return I**m * Rational(1-2**m, 4**m) * zeta(-n)
  1209. def _eval_rewrite_as_zeta(self, s, **kwargs):
  1210. from sympy.functions.elementary.trigonometric import cos
  1211. from sympy.functions.special.gamma_functions import gamma
  1212. from sympy.functions.special.zeta_functions import zeta
  1213. return 2 * gamma(s+1) / (2*pi)**(s+1) * \
  1214. (zeta(s+1, S.One/4) - cos(pi*s) * zeta(s+1, S(3)/4))
  1215. def _eval_rewrite_as_polylog(self, s, **kwargs):
  1216. from sympy.functions.special.zeta_functions import polylog
  1217. return (-I)**(s+1) * polylog(-s, I) + I**(s+1) * polylog(-s, -I)
  1218. def _eval_is_integer(self):
  1219. n = self.args[0]
  1220. if n.is_integer and n.is_nonnegative:
  1221. return True
  1222. def _eval_is_positive(self):
  1223. if self.args[0].is_nonnegative:
  1224. return True
  1225. def _eval_evalf(self, prec):
  1226. if not self.args[0].is_number:
  1227. return
  1228. s = self.args[0]._to_mpmath(prec+12)
  1229. with workprec(prec+12):
  1230. sp, cp = mp.sinpi(s/2), mp.cospi(s/2)
  1231. res = 2*mp.dirichlet(-s, (-sp, cp, sp, -cp))
  1232. return Expr._from_mpmath(res, prec)
  1233. #----------------------------------------------------------------------------#
  1234. # #
  1235. # Partition numbers #
  1236. # #
  1237. #----------------------------------------------------------------------------#
  1238. _npartition = [1, 1]
  1239. class partition(Function):
  1240. r"""
  1241. Partition numbers
  1242. The Partition numbers are a sequence of integers `p_n` that represent the
  1243. number of distinct ways of representing `n` as a sum of natural numbers
  1244. (with order irrelevant). The generating function for `p_n` is given by:
  1245. .. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}
  1246. Examples
  1247. ========
  1248. >>> from sympy import partition, Symbol
  1249. >>> [partition(n) for n in range(9)]
  1250. [1, 1, 2, 3, 5, 7, 11, 15, 22]
  1251. >>> n = Symbol('n', integer=True, negative=True)
  1252. >>> partition(n)
  1253. 0
  1254. See Also
  1255. ========
  1256. bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci
  1257. References
  1258. ==========
  1259. .. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
  1260. .. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem
  1261. """
  1262. @staticmethod
  1263. def _partition(n):
  1264. L = len(_npartition)
  1265. if n < L:
  1266. return _npartition[n]
  1267. # lengthen cache
  1268. for _n in range(L, n + 1):
  1269. v, p, i = 0, 0, 0
  1270. while 1:
  1271. s = 0
  1272. p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ...
  1273. if _n >= p:
  1274. s += _npartition[_n - p]
  1275. i += 1
  1276. gp = p + i # gp = generalized pentagonal: 2, 7, 15, ...
  1277. if _n >= gp:
  1278. s += _npartition[_n - gp]
  1279. if s == 0:
  1280. break
  1281. else:
  1282. v += s if i%2 == 1 else -s
  1283. _npartition.append(v)
  1284. return v
  1285. @classmethod
  1286. def eval(cls, n):
  1287. is_int = n.is_integer
  1288. if is_int == False:
  1289. raise ValueError("Partition numbers are defined only for "
  1290. "integers")
  1291. elif is_int:
  1292. if n.is_negative:
  1293. return S.Zero
  1294. if n.is_zero or (n - 1).is_zero:
  1295. return S.One
  1296. if n.is_Integer:
  1297. return Integer(cls._partition(n))
  1298. def _eval_is_integer(self):
  1299. if self.args[0].is_integer:
  1300. return True
  1301. def _eval_is_negative(self):
  1302. if self.args[0].is_integer:
  1303. return False
  1304. def _eval_is_positive(self):
  1305. n = self.args[0]
  1306. if n.is_nonnegative and n.is_integer:
  1307. return True
  1308. #######################################################################
  1309. ###
  1310. ### Functions for enumerating partitions, permutations and combinations
  1311. ###
  1312. #######################################################################
  1313. class _MultisetHistogram(tuple):
  1314. pass
  1315. _N = -1
  1316. _ITEMS = -2
  1317. _M = slice(None, _ITEMS)
  1318. def _multiset_histogram(n):
  1319. """Return tuple used in permutation and combination counting. Input
  1320. is a dictionary giving items with counts as values or a sequence of
  1321. items (which need not be sorted).
  1322. The data is stored in a class deriving from tuple so it is easily
  1323. recognized and so it can be converted easily to a list.
  1324. """
  1325. if isinstance(n, dict): # item: count
  1326. if not all(isinstance(v, int) and v >= 0 for v in n.values()):
  1327. raise ValueError
  1328. tot = sum(n.values())
  1329. items = sum(1 for k in n if n[k] > 0)
  1330. return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot])
  1331. else:
  1332. n = list(n)
  1333. s = set(n)
  1334. lens = len(s)
  1335. lenn = len(n)
  1336. if lens == lenn:
  1337. n = [1]*lenn + [lenn, lenn]
  1338. return _MultisetHistogram(n)
  1339. m = dict(zip(s, range(lens)))
  1340. d = dict(zip(range(lens), (0,)*lens))
  1341. for i in n:
  1342. d[m[i]] += 1
  1343. return _multiset_histogram(d)
  1344. def nP(n, k=None, replacement=False):
  1345. """Return the number of permutations of ``n`` items taken ``k`` at a time.
  1346. Possible values for ``n``:
  1347. integer - set of length ``n``
  1348. sequence - converted to a multiset internally
  1349. multiset - {element: multiplicity}
  1350. If ``k`` is None then the total of all permutations of length 0
  1351. through the number of items represented by ``n`` will be returned.
  1352. If ``replacement`` is True then a given item can appear more than once
  1353. in the ``k`` items. (For example, for 'ab' permutations of 2 would
  1354. include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
  1355. ``n`` is ignored when ``replacement`` is True but the total number
  1356. of elements is considered since no element can appear more times than
  1357. the number of elements in ``n``.
  1358. Examples
  1359. ========
  1360. >>> from sympy.functions.combinatorial.numbers import nP
  1361. >>> from sympy.utilities.iterables import multiset_permutations, multiset
  1362. >>> nP(3, 2)
  1363. 6
  1364. >>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
  1365. True
  1366. >>> nP('aab', 2)
  1367. 3
  1368. >>> nP([1, 2, 2], 2)
  1369. 3
  1370. >>> [nP(3, i) for i in range(4)]
  1371. [1, 3, 6, 6]
  1372. >>> nP(3) == sum(_)
  1373. True
  1374. When ``replacement`` is True, each item can have multiplicity
  1375. equal to the length represented by ``n``:
  1376. >>> nP('aabc', replacement=True)
  1377. 121
  1378. >>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
  1379. [1, 3, 9, 27, 81]
  1380. >>> sum(_)
  1381. 121
  1382. See Also
  1383. ========
  1384. sympy.utilities.iterables.multiset_permutations
  1385. References
  1386. ==========
  1387. .. [1] https://en.wikipedia.org/wiki/Permutation
  1388. """
  1389. try:
  1390. n = as_int(n)
  1391. except ValueError:
  1392. return Integer(_nP(_multiset_histogram(n), k, replacement))
  1393. return Integer(_nP(n, k, replacement))
  1394. @cacheit
  1395. def _nP(n, k=None, replacement=False):
  1396. if k == 0:
  1397. return 1
  1398. if isinstance(n, SYMPY_INTS): # n different items
  1399. # assert n >= 0
  1400. if k is None:
  1401. return sum(_nP(n, i, replacement) for i in range(n + 1))
  1402. elif replacement:
  1403. return n**k
  1404. elif k > n:
  1405. return 0
  1406. elif k == n:
  1407. return factorial(k)
  1408. elif k == 1:
  1409. return n
  1410. else:
  1411. # assert k >= 0
  1412. return _product(n - k + 1, n)
  1413. elif isinstance(n, _MultisetHistogram):
  1414. if k is None:
  1415. return sum(_nP(n, i, replacement) for i in range(n[_N] + 1))
  1416. elif replacement:
  1417. return n[_ITEMS]**k
  1418. elif k == n[_N]:
  1419. return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1])
  1420. elif k > n[_N]:
  1421. return 0
  1422. elif k == 1:
  1423. return n[_ITEMS]
  1424. else:
  1425. # assert k >= 0
  1426. tot = 0
  1427. n = list(n)
  1428. for i in range(len(n[_M])):
  1429. if not n[i]:
  1430. continue
  1431. n[_N] -= 1
  1432. if n[i] == 1:
  1433. n[i] = 0
  1434. n[_ITEMS] -= 1
  1435. tot += _nP(_MultisetHistogram(n), k - 1)
  1436. n[_ITEMS] += 1
  1437. n[i] = 1
  1438. else:
  1439. n[i] -= 1
  1440. tot += _nP(_MultisetHistogram(n), k - 1)
  1441. n[i] += 1
  1442. n[_N] += 1
  1443. return tot
  1444. @cacheit
  1445. def _AOP_product(n):
  1446. """for n = (m1, m2, .., mk) return the coefficients of the polynomial,
  1447. prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
  1448. of the product of AOPs (all-one polynomials) or order given in n. The
  1449. resulting coefficient corresponding to x**r is the number of r-length
  1450. combinations of sum(n) elements with multiplicities given in n.
  1451. The coefficients are given as a default dictionary (so if a query is made
  1452. for a key that is not present, 0 will be returned).
  1453. Examples
  1454. ========
  1455. >>> from sympy.functions.combinatorial.numbers import _AOP_product
  1456. >>> from sympy.abc import x
  1457. >>> n = (2, 2, 3) # e.g. aabbccc
  1458. >>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
  1459. >>> c = _AOP_product(n); dict(c)
  1460. {0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
  1461. >>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
  1462. True
  1463. The generating poly used here is the same as that listed in
  1464. https://tinyurl.com/cep849r, but in a refactored form.
  1465. """
  1466. n = list(n)
  1467. ord = sum(n)
  1468. need = (ord + 2)//2
  1469. rv = [1]*(n.pop() + 1)
  1470. rv.extend((0,) * (need - len(rv)))
  1471. rv = rv[:need]
  1472. while n:
  1473. ni = n.pop()
  1474. N = ni + 1
  1475. was = rv[:]
  1476. for i in range(1, min(N, len(rv))):
  1477. rv[i] += rv[i - 1]
  1478. for i in range(N, need):
  1479. rv[i] += rv[i - 1] - was[i - N]
  1480. rev = list(reversed(rv))
  1481. if ord % 2:
  1482. rv = rv + rev
  1483. else:
  1484. rv[-1:] = rev
  1485. d = defaultdict(int)
  1486. for i, r in enumerate(rv):
  1487. d[i] = r
  1488. return d
  1489. def nC(n, k=None, replacement=False):
  1490. """Return the number of combinations of ``n`` items taken ``k`` at a time.
  1491. Possible values for ``n``:
  1492. integer - set of length ``n``
  1493. sequence - converted to a multiset internally
  1494. multiset - {element: multiplicity}
  1495. If ``k`` is None then the total of all combinations of length 0
  1496. through the number of items represented in ``n`` will be returned.
  1497. If ``replacement`` is True then a given item can appear more than once
  1498. in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
  1499. 'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
  1500. ``replacement`` is True but the total number of elements is considered
  1501. since no element can appear more times than the number of elements in
  1502. ``n``.
  1503. Examples
  1504. ========
  1505. >>> from sympy.functions.combinatorial.numbers import nC
  1506. >>> from sympy.utilities.iterables import multiset_combinations
  1507. >>> nC(3, 2)
  1508. 3
  1509. >>> nC('abc', 2)
  1510. 3
  1511. >>> nC('aab', 2)
  1512. 2
  1513. When ``replacement`` is True, each item can have multiplicity
  1514. equal to the length represented by ``n``:
  1515. >>> nC('aabc', replacement=True)
  1516. 35
  1517. >>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
  1518. [1, 3, 6, 10, 15]
  1519. >>> sum(_)
  1520. 35
  1521. If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
  1522. then the total of all combinations of length 0 through ``k`` is the
  1523. product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
  1524. of each item is 1 (i.e., k unique items) then there are 2**k
  1525. combinations. For example, if there are 4 unique items, the total number
  1526. of combinations is 16:
  1527. >>> sum(nC(4, i) for i in range(5))
  1528. 16
  1529. See Also
  1530. ========
  1531. sympy.utilities.iterables.multiset_combinations
  1532. References
  1533. ==========
  1534. .. [1] https://en.wikipedia.org/wiki/Combination
  1535. .. [2] https://tinyurl.com/cep849r
  1536. """
  1537. if isinstance(n, SYMPY_INTS):
  1538. if k is None:
  1539. if not replacement:
  1540. return 2**n
  1541. return sum(nC(n, i, replacement) for i in range(n + 1))
  1542. if k < 0:
  1543. raise ValueError("k cannot be negative")
  1544. if replacement:
  1545. return binomial(n + k - 1, k)
  1546. return binomial(n, k)
  1547. if isinstance(n, _MultisetHistogram):
  1548. N = n[_N]
  1549. if k is None:
  1550. if not replacement:
  1551. return prod(m + 1 for m in n[_M])
  1552. return sum(nC(n, i, replacement) for i in range(N + 1))
  1553. elif replacement:
  1554. return nC(n[_ITEMS], k, replacement)
  1555. # assert k >= 0
  1556. elif k in (1, N - 1):
  1557. return n[_ITEMS]
  1558. elif k in (0, N):
  1559. return 1
  1560. return _AOP_product(tuple(n[_M]))[k]
  1561. else:
  1562. return nC(_multiset_histogram(n), k, replacement)
  1563. def _eval_stirling1(n, k):
  1564. if n == k == 0:
  1565. return S.One
  1566. if 0 in (n, k):
  1567. return S.Zero
  1568. # some special values
  1569. if n == k:
  1570. return S.One
  1571. elif k == n - 1:
  1572. return binomial(n, 2)
  1573. elif k == n - 2:
  1574. return (3*n - 1)*binomial(n, 3)/4
  1575. elif k == n - 3:
  1576. return binomial(n, 2)*binomial(n, 4)
  1577. return _stirling1(n, k)
  1578. @cacheit
  1579. def _stirling1(n, k):
  1580. row = [0, 1]+[0]*(k-1) # for n = 1
  1581. for i in range(2, n+1):
  1582. for j in range(min(k,i), 0, -1):
  1583. row[j] = (i-1) * row[j] + row[j-1]
  1584. return Integer(row[k])
  1585. def _eval_stirling2(n, k):
  1586. if n == k == 0:
  1587. return S.One
  1588. if 0 in (n, k):
  1589. return S.Zero
  1590. # some special values
  1591. if n == k:
  1592. return S.One
  1593. elif k == n - 1:
  1594. return binomial(n, 2)
  1595. elif k == 1:
  1596. return S.One
  1597. elif k == 2:
  1598. return Integer(2**(n - 1) - 1)
  1599. return _stirling2(n, k)
  1600. @cacheit
  1601. def _stirling2(n, k):
  1602. row = [0, 1]+[0]*(k-1) # for n = 1
  1603. for i in range(2, n+1):
  1604. for j in range(min(k,i), 0, -1):
  1605. row[j] = j * row[j] + row[j-1]
  1606. return Integer(row[k])
  1607. def stirling(n, k, d=None, kind=2, signed=False):
  1608. r"""Return Stirling number $S(n, k)$ of the first or second (default) kind.
  1609. The sum of all Stirling numbers of the second kind for $k = 1$
  1610. through $n$ is ``bell(n)``. The recurrence relationship for these numbers
  1611. is:
  1612. .. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;
  1613. .. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}
  1614. where $j$ is:
  1615. $n$ for Stirling numbers of the first kind,
  1616. $-n$ for signed Stirling numbers of the first kind,
  1617. $k$ for Stirling numbers of the second kind.
  1618. The first kind of Stirling number counts the number of permutations of
  1619. ``n`` distinct items that have ``k`` cycles; the second kind counts the
  1620. ways in which ``n`` distinct items can be partitioned into ``k`` parts.
  1621. If ``d`` is given, the "reduced Stirling number of the second kind" is
  1622. returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
  1623. (This counts the ways to partition $n$ consecutive integers into $k$
  1624. groups with no pairwise difference less than $d$. See example below.)
  1625. To obtain the signed Stirling numbers of the first kind, use keyword
  1626. ``signed=True``. Using this keyword automatically sets ``kind`` to 1.
  1627. Examples
  1628. ========
  1629. >>> from sympy.functions.combinatorial.numbers import stirling, bell
  1630. >>> from sympy.combinatorics import Permutation
  1631. >>> from sympy.utilities.iterables import multiset_partitions, permutations
  1632. First kind (unsigned by default):
  1633. >>> [stirling(6, i, kind=1) for i in range(7)]
  1634. [0, 120, 274, 225, 85, 15, 1]
  1635. >>> perms = list(permutations(range(4)))
  1636. >>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
  1637. [0, 6, 11, 6, 1]
  1638. >>> [stirling(4, i, kind=1) for i in range(5)]
  1639. [0, 6, 11, 6, 1]
  1640. First kind (signed):
  1641. >>> [stirling(4, i, signed=True) for i in range(5)]
  1642. [0, -6, 11, -6, 1]
  1643. Second kind:
  1644. >>> [stirling(10, i) for i in range(12)]
  1645. [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
  1646. >>> sum(_) == bell(10)
  1647. True
  1648. >>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
  1649. True
  1650. Reduced second kind:
  1651. >>> from sympy import subsets, oo
  1652. >>> def delta(p):
  1653. ... if len(p) == 1:
  1654. ... return oo
  1655. ... return min(abs(i[0] - i[1]) for i in subsets(p, 2))
  1656. >>> parts = multiset_partitions(range(5), 3)
  1657. >>> d = 2
  1658. >>> sum(1 for p in parts if all(delta(i) >= d for i in p))
  1659. 7
  1660. >>> stirling(5, 3, 2)
  1661. 7
  1662. See Also
  1663. ========
  1664. sympy.utilities.iterables.multiset_partitions
  1665. References
  1666. ==========
  1667. .. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
  1668. .. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
  1669. """
  1670. # TODO: make this a class like bell()
  1671. n = as_int(n)
  1672. k = as_int(k)
  1673. if n < 0:
  1674. raise ValueError('n must be nonnegative')
  1675. if k > n:
  1676. return S.Zero
  1677. if d:
  1678. # assert k >= d
  1679. # kind is ignored -- only kind=2 is supported
  1680. return _eval_stirling2(n - d + 1, k - d + 1)
  1681. elif signed:
  1682. # kind is ignored -- only kind=1 is supported
  1683. return S.NegativeOne**(n - k)*_eval_stirling1(n, k)
  1684. if kind == 1:
  1685. return _eval_stirling1(n, k)
  1686. elif kind == 2:
  1687. return _eval_stirling2(n, k)
  1688. else:
  1689. raise ValueError('kind must be 1 or 2, not %s' % k)
  1690. @cacheit
  1691. def _nT(n, k):
  1692. """Return the partitions of ``n`` items into ``k`` parts. This
  1693. is used by ``nT`` for the case when ``n`` is an integer."""
  1694. # really quick exits
  1695. if k > n or k < 0:
  1696. return 0
  1697. if k in (1, n):
  1698. return 1
  1699. if k == 0:
  1700. return 0
  1701. # exits that could be done below but this is quicker
  1702. if k == 2:
  1703. return n//2
  1704. d = n - k
  1705. if d <= 3:
  1706. return d
  1707. # quick exit
  1708. if 3*k >= n: # or, equivalently, 2*k >= d
  1709. # all the information needed in this case
  1710. # will be in the cache needed to calculate
  1711. # partition(d), so...
  1712. # update cache
  1713. tot = partition._partition(d)
  1714. # and correct for values not needed
  1715. if d - k > 0:
  1716. tot -= sum(_npartition[:d - k])
  1717. return tot
  1718. # regular exit
  1719. # nT(n, k) = Sum(nT(n - k, m), (m, 1, k));
  1720. # calculate needed nT(i, j) values
  1721. p = [1]*d
  1722. for i in range(2, k + 1):
  1723. for m in range(i + 1, d):
  1724. p[m] += p[m - i]
  1725. d -= 1
  1726. # if p[0] were appended to the end of p then the last
  1727. # k values of p are the nT(n, j) values for 0 < j < k in reverse
  1728. # order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of
  1729. # putting the 1 from p[0] there, however, it is simply added to
  1730. # the sum below which is valid for 1 < k <= n//2
  1731. return (1 + sum(p[1 - k:]))
  1732. def nT(n, k=None):
  1733. """Return the number of ``k``-sized partitions of ``n`` items.
  1734. Possible values for ``n``:
  1735. integer - ``n`` identical items
  1736. sequence - converted to a multiset internally
  1737. multiset - {element: multiplicity}
  1738. Note: the convention for ``nT`` is different than that of ``nC`` and
  1739. ``nP`` in that
  1740. here an integer indicates ``n`` *identical* items instead of a set of
  1741. length ``n``; this is in keeping with the ``partitions`` function which
  1742. treats its integer-``n`` input like a list of ``n`` 1s. One can use
  1743. ``range(n)`` for ``n`` to indicate ``n`` distinct items.
  1744. If ``k`` is None then the total number of ways to partition the elements
  1745. represented in ``n`` will be returned.
  1746. Examples
  1747. ========
  1748. >>> from sympy.functions.combinatorial.numbers import nT
  1749. Partitions of the given multiset:
  1750. >>> [nT('aabbc', i) for i in range(1, 7)]
  1751. [1, 8, 11, 5, 1, 0]
  1752. >>> nT('aabbc') == sum(_)
  1753. True
  1754. >>> [nT("mississippi", i) for i in range(1, 12)]
  1755. [1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]
  1756. Partitions when all items are identical:
  1757. >>> [nT(5, i) for i in range(1, 6)]
  1758. [1, 2, 2, 1, 1]
  1759. >>> nT('1'*5) == sum(_)
  1760. True
  1761. When all items are different:
  1762. >>> [nT(range(5), i) for i in range(1, 6)]
  1763. [1, 15, 25, 10, 1]
  1764. >>> nT(range(5)) == sum(_)
  1765. True
  1766. Partitions of an integer expressed as a sum of positive integers:
  1767. >>> from sympy import partition
  1768. >>> partition(4)
  1769. 5
  1770. >>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
  1771. 5
  1772. >>> nT('1'*4)
  1773. 5
  1774. See Also
  1775. ========
  1776. sympy.utilities.iterables.partitions
  1777. sympy.utilities.iterables.multiset_partitions
  1778. sympy.functions.combinatorial.numbers.partition
  1779. References
  1780. ==========
  1781. .. [1] https://web.archive.org/web/20210507012732/https://teaching.csse.uwa.edu.au/units/CITS7209/partition.pdf
  1782. """
  1783. if isinstance(n, SYMPY_INTS):
  1784. # n identical items
  1785. if k is None:
  1786. return partition(n)
  1787. if isinstance(k, SYMPY_INTS):
  1788. n = as_int(n)
  1789. k = as_int(k)
  1790. return Integer(_nT(n, k))
  1791. if not isinstance(n, _MultisetHistogram):
  1792. try:
  1793. # if n contains hashable items there is some
  1794. # quick handling that can be done
  1795. u = len(set(n))
  1796. if u <= 1:
  1797. return nT(len(n), k)
  1798. elif u == len(n):
  1799. n = range(u)
  1800. raise TypeError
  1801. except TypeError:
  1802. n = _multiset_histogram(n)
  1803. N = n[_N]
  1804. if k is None and N == 1:
  1805. return 1
  1806. if k in (1, N):
  1807. return 1
  1808. if k == 2 or N == 2 and k is None:
  1809. m, r = divmod(N, 2)
  1810. rv = sum(nC(n, i) for i in range(1, m + 1))
  1811. if not r:
  1812. rv -= nC(n, m)//2
  1813. if k is None:
  1814. rv += 1 # for k == 1
  1815. return rv
  1816. if N == n[_ITEMS]:
  1817. # all distinct
  1818. if k is None:
  1819. return bell(N)
  1820. return stirling(N, k)
  1821. m = MultisetPartitionTraverser()
  1822. if k is None:
  1823. return m.count_partitions(n[_M])
  1824. # MultisetPartitionTraverser does not have a range-limited count
  1825. # method, so need to enumerate and count
  1826. tot = 0
  1827. for discard in m.enum_range(n[_M], k-1, k):
  1828. tot += 1
  1829. return tot
  1830. #-----------------------------------------------------------------------------#
  1831. # #
  1832. # Motzkin numbers #
  1833. # #
  1834. #-----------------------------------------------------------------------------#
  1835. class motzkin(Function):
  1836. """
  1837. The nth Motzkin number is the number
  1838. of ways of drawing non-intersecting chords
  1839. between n points on a circle (not necessarily touching
  1840. every point by a chord). The Motzkin numbers are named
  1841. after Theodore Motzkin and have diverse applications
  1842. in geometry, combinatorics and number theory.
  1843. Motzkin numbers are the integer sequence defined by the
  1844. initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
  1845. `M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`.
  1846. Examples
  1847. ========
  1848. >>> from sympy import motzkin
  1849. >>> motzkin.is_motzkin(5)
  1850. False
  1851. >>> motzkin.find_motzkin_numbers_in_range(2,300)
  1852. [2, 4, 9, 21, 51, 127]
  1853. >>> motzkin.find_motzkin_numbers_in_range(2,900)
  1854. [2, 4, 9, 21, 51, 127, 323, 835]
  1855. >>> motzkin.find_first_n_motzkins(10)
  1856. [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
  1857. References
  1858. ==========
  1859. .. [1] https://en.wikipedia.org/wiki/Motzkin_number
  1860. .. [2] https://mathworld.wolfram.com/MotzkinNumber.html
  1861. """
  1862. @staticmethod
  1863. def is_motzkin(n):
  1864. try:
  1865. n = as_int(n)
  1866. except ValueError:
  1867. return False
  1868. if n > 0:
  1869. if n in (1, 2):
  1870. return True
  1871. tn1 = 1
  1872. tn = 2
  1873. i = 3
  1874. while tn < n:
  1875. a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
  1876. i += 1
  1877. tn1 = tn
  1878. tn = a
  1879. if tn == n:
  1880. return True
  1881. else:
  1882. return False
  1883. else:
  1884. return False
  1885. @staticmethod
  1886. def find_motzkin_numbers_in_range(x, y):
  1887. if 0 <= x <= y:
  1888. motzkins = []
  1889. if x <= 1 <= y:
  1890. motzkins.append(1)
  1891. tn1 = 1
  1892. tn = 2
  1893. i = 3
  1894. while tn <= y:
  1895. if tn >= x:
  1896. motzkins.append(tn)
  1897. a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
  1898. i += 1
  1899. tn1 = tn
  1900. tn = int(a)
  1901. return motzkins
  1902. else:
  1903. raise ValueError('The provided range is not valid. This condition should satisfy x <= y')
  1904. @staticmethod
  1905. def find_first_n_motzkins(n):
  1906. try:
  1907. n = as_int(n)
  1908. except ValueError:
  1909. raise ValueError('The provided number must be a positive integer')
  1910. if n < 0:
  1911. raise ValueError('The provided number must be a positive integer')
  1912. motzkins = [1]
  1913. if n >= 1:
  1914. motzkins.append(1)
  1915. tn1 = 1
  1916. tn = 2
  1917. i = 3
  1918. while i <= n:
  1919. motzkins.append(tn)
  1920. a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
  1921. i += 1
  1922. tn1 = tn
  1923. tn = int(a)
  1924. return motzkins
  1925. @staticmethod
  1926. @recurrence_memo([S.One, S.One])
  1927. def _motzkin(n, prev):
  1928. return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2)
  1929. @classmethod
  1930. def eval(cls, n):
  1931. try:
  1932. n = as_int(n)
  1933. except ValueError:
  1934. raise ValueError('The provided number must be a positive integer')
  1935. if n < 0:
  1936. raise ValueError('The provided number must be a positive integer')
  1937. return Integer(cls._motzkin(n - 1))
  1938. def nD(i=None, brute=None, *, n=None, m=None):
  1939. """return the number of derangements for: ``n`` unique items, ``i``
  1940. items (as a sequence or multiset), or multiplicities, ``m`` given
  1941. as a sequence or multiset.
  1942. Examples
  1943. ========
  1944. >>> from sympy.utilities.iterables import generate_derangements as enum
  1945. >>> from sympy.functions.combinatorial.numbers import nD
  1946. A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``:
  1947. >>> set([''.join(i) for i in enum('abc')])
  1948. {'bca', 'cab'}
  1949. >>> nD('abc')
  1950. 2
  1951. Input as iterable or dictionary (multiset form) is accepted:
  1952. >>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3})
  1953. By default, a brute-force enumeration and count of multiset permutations
  1954. is only done if there are fewer than 9 elements. There may be cases when
  1955. there is high multiplicity with few unique elements that will benefit
  1956. from a brute-force enumeration, too. For this reason, the `brute`
  1957. keyword (default None) is provided. When False, the brute-force
  1958. enumeration will never be used. When True, it will always be used.
  1959. >>> nD('1111222233', brute=True)
  1960. 44
  1961. For convenience, one may specify ``n`` distinct items using the
  1962. ``n`` keyword:
  1963. >>> assert nD(n=3) == nD('abc') == 2
  1964. Since the number of derangments depends on the multiplicity of the
  1965. elements and not the elements themselves, it may be more convenient
  1966. to give a list or multiset of multiplicities using keyword ``m``:
  1967. >>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2
  1968. """
  1969. from sympy.integrals.integrals import integrate
  1970. from sympy.functions.special.polynomials import laguerre
  1971. from sympy.abc import x
  1972. def ok(x):
  1973. if not isinstance(x, SYMPY_INTS):
  1974. raise TypeError('expecting integer values')
  1975. if x < 0:
  1976. raise ValueError('value must not be negative')
  1977. return True
  1978. if (i, n, m).count(None) != 2:
  1979. raise ValueError('enter only 1 of i, n, or m')
  1980. if i is not None:
  1981. if isinstance(i, SYMPY_INTS):
  1982. raise TypeError('items must be a list or dictionary')
  1983. if not i:
  1984. return S.Zero
  1985. if type(i) is not dict:
  1986. s = list(i)
  1987. ms = multiset(s)
  1988. elif type(i) is dict:
  1989. all(ok(_) for _ in i.values())
  1990. ms = {k: v for k, v in i.items() if v}
  1991. s = None
  1992. if not ms:
  1993. return S.Zero
  1994. N = sum(ms.values())
  1995. counts = multiset(ms.values())
  1996. nkey = len(ms)
  1997. elif n is not None:
  1998. ok(n)
  1999. if not n:
  2000. return S.Zero
  2001. return subfactorial(n)
  2002. elif m is not None:
  2003. if isinstance(m, dict):
  2004. all(ok(i) and ok(j) for i, j in m.items())
  2005. counts = {k: v for k, v in m.items() if k*v}
  2006. elif iterable(m) or isinstance(m, str):
  2007. m = list(m)
  2008. all(ok(i) for i in m)
  2009. counts = multiset([i for i in m if i])
  2010. else:
  2011. raise TypeError('expecting iterable')
  2012. if not counts:
  2013. return S.Zero
  2014. N = sum(k*v for k, v in counts.items())
  2015. nkey = sum(counts.values())
  2016. s = None
  2017. big = int(max(counts))
  2018. if big == 1: # no repetition
  2019. return subfactorial(nkey)
  2020. nval = len(counts)
  2021. if big*2 > N:
  2022. return S.Zero
  2023. if big*2 == N:
  2024. if nkey == 2 and nval == 1:
  2025. return S.One # aaabbb
  2026. if nkey - 1 == big: # one element repeated
  2027. return factorial(big) # e.g. abc part of abcddd
  2028. if N < 9 and brute is None or brute:
  2029. # for all possibilities, this was found to be faster
  2030. if s is None:
  2031. s = []
  2032. i = 0
  2033. for m, v in counts.items():
  2034. for j in range(v):
  2035. s.extend([i]*m)
  2036. i += 1
  2037. return Integer(sum(1 for i in multiset_derangements(s)))
  2038. from sympy.functions.elementary.exponential import exp
  2039. return Integer(abs(integrate(exp(-x)*Mul(*[
  2040. laguerre(i, x)**m for i, m in counts.items()]), (x, 0, oo))))