def _calc_bernoulli(n): s = 0 a = int(C.Binomial(n + 3, n - 6)) for j in xrange(1, n // 6 + 1): s += a * bernoulli(n - 6 * j) # Avoid computing each binomial coefficient from scratch a *= _product(n - 6 - 6 * j + 1, n - 6 * j) a //= _product(6 * j + 4, 6 * j + 9) if n % 6 == 4: s = -Rational(n + 3, 6) - s else: s = Rational(n + 3, 3) - s return s / C.Binomial(n + 3, n)
def canonize(cls, n, sym=None): if n.is_Number: if n.is_Integer and n.is_nonnegative: if n is S.Zero: return S.One elif n is S.One: if sym is None: return -S.Half else: return sym - S.Half # Bernoulli numbers elif sym is None: if n.is_odd: return S.Zero n = int(n) # Use mpmath for enormous Bernoulli numbers if n > 500: p, q = bernfrac(n) return Rational(int(p), q) case = n % 6 highest_cached = cls._highest[case] if n <= highest_cached: return cls._cache[n] # To avoid excessive recursion when, say, bernoulli(1000) is # requested, calculate and cache the entire sequence ... B_988, # B_994, B_1000 in increasing order for i in xrange(highest_cached + 6, n + 6, 6): b = cls._calc_bernoulli(i) cls._cache[i] = b cls._highest[case] = i return b # Bernoulli polynomials else: n, result = int(n), [] for k in xrange(n + 1): result.append(C.Binomial(n, k) * cls(k) * sym**(n - k)) return C.Add(*result) else: raise ValueError("Bernoulli numbers are defined only" " for nonnegative integer indices.")