numbers.py 99 KB

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