m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2294 lines
71 KiB

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