def test_arithmetic_sums(): assert summation(1, (n, a, b)) == b-a+1 assert summation(1, (n, 1, 10)) == 10 assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000 assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2 assert summation(cos(n), (n, -2, 1)) == cos(-2)+cos(-1)+cos(0)+cos(1)
def test_polynomial_sums(): assert summation(n**2, (n, 3, 8)) == 199 assert summation(n, (n, a, b)) == \ ((a + b)*(b - a + 1)/2).expand() assert summation(n**2, (n, 1, b)) == \ ((2*b**3 + 3*b**2 + b)/6).expand() assert summation(n**3, (n, 1, b)) == \ ((b**4 + 2*b**3 + b**2)/4).expand() assert summation(n**6, (n, 1, b)) == \ ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand()
def test_arithmetic_sums(): assert summation(1, (n, a, b)) == b - a + 1 assert Sum(S.NaN, (n, a, b)) is S.NaN assert Sum(x, (n, a, a)).doit() == x assert Sum(x, (x, a, a)).doit() == a assert Sum(x, (n, 1, a)).doit() == a*x assert Sum(x, (x, Range(1, 11))).doit() == 55 assert Sum(x, (x, Range(1, 11, 2))).doit() == 25 assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2))) lo, hi = 1, 2 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 3 and s2.doit() == 0 lo, hi = x, x + 1 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 2*x + 1 and s2.doit() == 0 assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \ y**2 + 2 assert summation(1, (n, 1, 10)) == 10 assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000 assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2 assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1) assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2) assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum) assert summation(k, (k, 0, oo)) == oo assert summation(k, (k, Range(1, 11))) == 55
def test_geometric_sums(): assert summation(pi**n, (n, 0, b)) == (1-pi**(b+1)) / (1-pi) assert summation(2 * 3**n, (n, 0, b)) == 3**(b+1) - 1 assert summation(Rational(1,2)**n, (n, 1, oo)) == 1 assert summation(2**n, (n, 0, b)) == 2**(b+1) - 1 assert summation(2**n, (n, 1, oo)) == oo assert summation(2**(-n), (n, 1, oo)) == 1 assert summation(3**(-n), (n, 4, oo)) == Rational(1,54) assert summation(2**(-4*n+3), (n, 1, oo)) == Rational(8,15) assert summation(2**(n+1), (n, 1, b)).expand() == 4*(2**b-1)
def test_hypersum(): from sympy import simplify, sin, hyper assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n+1)/factorial(2*n+1), (n, 3, oo))) \ == -x + sin(x) + x**3/6 - x**5/120 # TODO to get this without hyper need to improve hyperexpand assert summation(1/(n+2)**3, (n, 1, oo)) == \ hyper([3, 3, 3, 1], [4, 4, 4], 1)/27 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1-1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1)
def __init__(self, states, interval, differential_order): """ :param states: tuple of states in beginning and end of interval :param interval: time interval (tuple) :param differential_order: grade of differential flatness :math:`\\gamma` """ self.yd = states self.t0 = interval[0] self.t1 = interval[1] self.dt = interval[1] - interval[0] gamma = differential_order # + 1 # TODO check this against notes # setup symbolic expressions tau, k = sp.symbols('tau, k') alpha = sp.factorial(2 * gamma + 1) f = sp.binomial(gamma, k) * (-1) ** k * tau ** (gamma + k + 1) / (gamma + k + 1) phi = alpha / sp.factorial(gamma) ** 2 * sp.summation(f, (k, 0, gamma)) # differentiate phi(tau), index in list corresponds to order dphi_sym = [phi] # init with phi(tau) for order in range(differential_order): dphi_sym.append(dphi_sym[-1].diff(tau)) # lambdify self.dphi_num = [] for der in dphi_sym: self.dphi_num.append(sp.lambdify(tau, der, 'numpy'))
def test_totient(): assert [totient(k) for k in range(1, 12)] == \ [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10] assert totient(5005) == 2880 assert totient(5006) == 2502 assert totient(5009) == 5008 assert totient(2**100) == 2**99 raises(ValueError, lambda: totient(30.1)) raises(ValueError, lambda: totient(20.001)) m = Symbol("m", integer=True) assert totient(m) assert totient(m).subs(m, 3**10) == 3**10 - 3**9 assert summation(totient(m), (m, 1, 11)) == 42 n = Symbol("n", integer=True, positive=True) assert totient(n).is_integer x=Symbol("x", integer=False) raises(ValueError, lambda: totient(x)) y=Symbol("y", positive=False) raises(ValueError, lambda: totient(y)) z=Symbol("z", positive=True, integer=True) raises(ValueError, lambda: totient(2**(-z)))
def expectation(self, expr, var, evaluate=True, **kwargs): """ Expectation of expression over distribution """ # TODO: support discrete sets with non integer stepsizes if evaluate: try: p = poly(expr, var) t = Dummy('t', real=True) mgf = self.moment_generating_function(t) deg = p.degree() taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t) result = 0 for k in range(deg+1): result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k) return result except PolynomialError: return summation(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs) else: return Sum(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs)
def repeated(n, i, e, a, b): # let n_a = n; n_{a+k+1} = e(n=n_{a+k}, i=a+k+1) # return n_b if e.has(i): if e.has(n): if not (e - n).has(n): term = e - n return n + sympy.summation(term, (i, a, b)) raise NotImplementedError("has i and n") else: return e.subs(i, b) else: if e.has(n): if not (e - n).has(n): term = e - n return n + term * (b - a + 1) c, args = e.as_coeff_add(n) arg, = args if not (arg / n).simplify().has(n): coeff = arg / n # print("Coefficient is %s, iterations is %s" % # (coeff, (b-a+1))) return n * coeff ** (b - a + 1) raise NotImplementedError else: return e
def to_sympy(self, expr, **kwargs): if expr.has_form('Sum', 2) and expr.leaves[1].has_form('List', 3): index = expr.leaves[1] result = sympy.summation(expr.leaves[0].to_sympy(), ( index.leaves[0].to_sympy(), index.leaves[1].to_sympy(), index.leaves[2].to_sympy())) return result
def to_sympy(self, expr, **kwargs): if expr.has_form('Sum', 2) and expr.leaves[1].has_form('List', 3): index = expr.leaves[1] arg = expr.leaves[0].to_sympy() bounds = (index.leaves[0].to_sympy(), index.leaves[1].to_sympy(), index.leaves[2].to_sympy()) if arg is not None and None not in bounds: return sympy.summation(arg, bounds)
def test_Sum_doit(): assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3 assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \ 3*Integral(a**2) assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2) # test nested sum evaluation s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n)) assert 0 == (s.doit() - n*(n+1)*(n-1)).factor() assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3 assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \ 3*Piecewise((1, And(S(1) <= k, k <= 3)), (0, True)) assert Sum(f(n)*Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \ f(1) + f(2) + f(3) assert Sum(f(n)*Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \ Sum(Piecewise((f(n), n >= 0), (0, True)), (n, 1, oo)) l = Symbol('l', integer=True, positive=True) assert Sum(f(l)*Sum(KroneckerDelta(m, l), (m, 0, oo)), (l, 1, oo)).doit() == \ Sum(f(l), (l, 1, oo)) # issue 2597 nmax = symbols('N', integer=True, positive=True) pw = Piecewise((1, And(S(1) <= n, n <= nmax)), (0, True)) assert Sum(pw, (n, 1, nmax)).doit() == Sum(pw, (n, 1, nmax))
def test_Sum_doit(): assert Sum(n * Integral(a ** 2), (n, 0, 2)).doit() == a ** 3 assert Sum(n * Integral(a ** 2), (n, 0, 2)).doit(deep=False) == 3 * Integral(a ** 2) assert summation(n * Integral(a ** 2), (n, 0, 2)) == 3 * Integral(a ** 2) # test nested sum evaluation S = Sum(Sum(Sum(2, (z, 1, n + 1)), (y, x + 1, n)), (x, 1, n)) assert 0 == (S.doit() - n * (n + 1) * (n - 1)).factor()
def expectation(self, expr, var, evaluate=True, **kwargs): """ Expectation of expression over distribution """ # TODO: support discrete sets with non integer stepsizes if evaluate: return summation(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs) else: return Sum(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs)
def compute_characteristic_function(self, **kwargs): """ Compute the characteristic function from the PDF Returns a Lambda """ x, t = symbols('x, t', real=True, finite=True, cls=Dummy) pdf = self.pdf(x) cf = summation(exp(I*t*x)*pdf, (x, self.set.inf, self.set.sup)) return Lambda(t, cf)
def test_Sum_interface(): assert isinstance(Sum(0, (n, 0, 2)), Sum) assert Sum(nan, (n, 0, 2)) is nan assert Sum(nan, (n, 0, oo)) is nan assert Sum(0, (n, 0, 2)).doit() == 0 assert isinstance(Sum(0, (n, 0, oo)), Sum) assert Sum(0, (n, 0, oo)).doit() == 0 raises(ValueError, lambda: Sum(1)) raises(ValueError, lambda: summation(1))
def test_composite_sums(): f = Rational(1, 2)*(7 - 6*n + Rational(1, 7)*n**3) s = summation(f, (n, a, b)) assert not isinstance(s, Sum) A = 0 for i in range(-3, 5): A += f.subs(n, i) B = s.subs(a, -3).subs(b, 4) assert A == B
def _eval_product(self, a, n, term): from sympy import summation, Sum k = self.index if not term.has(k): return term**(n-a+1) elif term.is_polynomial(k): poly = term.as_poly(k) A = B = Q = S.One C_= poly.LC() all_roots = roots(poly, multiple=True) for r in all_roots: A *= C.RisingFactorial(a-r, n-a+1) Q *= n - r if len(all_roots) < poly.degree(): B = Product(quo(poly, Q.as_poly(k)), (k, a, n)) return poly.LC()**(n-a+1) * A * B elif term.is_Add: p, q = term.as_numer_denom() p = self._eval_product(a, n, p) q = self._eval_product(a, n, q) return p / q elif term.is_Mul: exclude, include = [], [] for t in term.args: p = self._eval_product(a, n, t) if p is not None: exclude.append(p) else: include.append(t) if not exclude: return None else: A, B = Mul(*exclude), term._new_rawargs(*include) return A * Product(B, (k, a, n)) elif term.is_Pow: if not term.base.has(k): s = summation(term.exp, (k, a, n)) if not isinstance(s, Sum): return term.base**s elif not term.exp.has(k): p = self._eval_product(a, n, term.base) if p is not None: return p**term.exp
def grow_function_sym(N = Symbol("N"),k = 0): """ @type k int """ from sympy import factorial,summation,combsimp ksym = Symbol("ksym") def C(k,n): return factorial(n) / (factorial(k)*factorial(n-k)) return combsimp(summation(C(ksym,N),(ksym,0,k-1)))
def compute_quantile(self, **kwargs): """ Compute the Quantile from the PDF Returns a Lambda """ x = symbols('x', integer=True, finite=True, cls=Dummy) p = symbols('p', real=True, finite=True, cls=Dummy) left_bound = self.set.inf pdf = self.pdf(x) cdf = summation(pdf, (x, left_bound, x), **kwargs) set = ((x, p <= cdf), ) return Lambda(p, Piecewise(*set))
def test_totient(): assert [totient(k) for k in range(1, 12)] == \ [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10] assert totient(5005) == 2880 assert totient(5006) == 2502 assert totient(5009) == 5008 assert totient(2**100) == 2**99 m = Symbol("m", integer=True) assert totient(m) assert totient(m).subs(m, 3**10) == 3**10 - 3**9 assert summation(totient(m), (m, 1, 11)) == 42
def test_primeomega(): assert primeomega(2) == 1 assert primeomega(2 * 2) == 2 assert primeomega(2 * 2 * 3) == 3 assert primeomega(3 * 25) == primeomega(3) + primeomega(25) assert [primeomega(p) for p in primerange(1, 10)] == [1, 1, 1, 1] assert primeomega(fac(50)) == 108 assert primeomega(2 ** 9941 - 1) == 1 n = Symbol('n', integer=True) assert primeomega(n) assert primeomega(n).subs(n, 2 ** 31 - 1) == 1 assert summation(primeomega(n), (n, 2, 30)) == 59
def compute_cdf(self, **kwargs): """ Compute the CDF from the PDF Returns a Lambda """ x, z = symbols('x, z', integer=True, finite=True, cls=Dummy) left_bound = self.set.inf # CDF is integral of PDF from left bound to z pdf = self.pdf(x) cdf = summation(pdf, (x, left_bound, z), **kwargs) # CDF Ensure that CDF left of left_bound is zero cdf = Piecewise((cdf, z >= left_bound), (0, True)) return Lambda(z, cdf)
def test_reduced_totient(): assert [reduced_totient(k) for k in range(1, 16)] == \ [1, 1, 2, 2, 4, 2, 6, 2, 6, 4, 10, 2, 12, 6, 4] assert reduced_totient(5005) == 60 assert reduced_totient(5006) == 2502 assert reduced_totient(5009) == 5008 assert reduced_totient(2**100) == 2**98 m = Symbol("m", integer=True) assert reduced_totient(m) assert reduced_totient(m).subs(m, 2**3*3**10) == 3**10 - 3**9 assert summation(reduced_totient(m), (m, 1, 16)) == 68 n = Symbol("n", integer=True, positive=True) assert reduced_totient(n).is_integer
def test_divisor_sigma(): assert [divisor_sigma(k) for k in range(1, 12)] == [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12] assert [divisor_sigma(k, 2) for k in range(1, 12)] == [1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122] assert divisor_sigma(23450) == 50592 assert divisor_sigma(23450, 0) == 24 assert divisor_sigma(23450, 1) == 50592 assert divisor_sigma(23450, 2) == 730747500 assert divisor_sigma(23450, 3) == 14666785333344 m = Symbol("m", integer=True) k = Symbol("k", integer=True) assert divisor_sigma(m) assert divisor_sigma(m, k) assert divisor_sigma(m).subs(m, 3 ** 10) == 88573 assert divisor_sigma(m, k).subs([(m, 3 ** 10), (k, 3)]) == 213810021790597 assert summation(divisor_sigma(m), (m, 1, 11)) == 99
def test_udivisor_sigma(): assert [udivisor_sigma(k) for k in range(1, 12)] == [1, 3, 4, 5, 6, 12, 8, 9, 10, 18, 12] assert [udivisor_sigma(k, 3) for k in range(1, 12)] == [1, 9, 28, 65, 126, 252, 344, 513, 730, 1134, 1332] assert udivisor_sigma(23450) == 42432 assert udivisor_sigma(23450, 0) == 16 assert udivisor_sigma(23450, 1) == 42432 assert udivisor_sigma(23450, 2) == 702685000 assert udivisor_sigma(23450, 4) == 321426961814978248 m = Symbol("m", integer=True) k = Symbol("k", integer=True) assert udivisor_sigma(m) assert udivisor_sigma(m, k) assert udivisor_sigma(m).subs(m, 4 ** 9) == 262145 assert udivisor_sigma(m, k).subs([(m, 4 ** 9), (k, 2)]) == 68719476737 assert summation(udivisor_sigma(m), (m, 2, 15)) == 169
def eval_prob(self, _domain): if isinstance(_domain, Range): n = symbols('n') inf, sup, step = (r for r in _domain.args) summand = ((self.pdf).replace( self.symbol, inf + n*step)) rv = summation(summand, (n, 0, floor((sup - inf)/step - 1))).doit() return rv elif isinstance(_domain, FiniteSet): pdf = Lambda(self.symbol, self.pdf) rv = sum(pdf(x) for x in _domain) return rv elif isinstance(_domain, Union): rv = sum(self.eval_prob(x) for x in _domain.args) return rv
def eval_prob(self, _domain): sym = list(self.symbols)[0] if isinstance(_domain, Range): n = symbols('n', integer=True, finite=True) inf, sup, step = (r for r in _domain.args) summand = ((self.pdf).replace( sym, n*step)) rv = summation(summand, (n, inf/step, (sup)/step - 1)).doit() return rv elif isinstance(_domain, FiniteSet): pdf = Lambda(sym, self.pdf) rv = sum(pdf(x) for x in _domain) return rv elif isinstance(_domain, Union): rv = sum(self.eval_prob(x) for x in _domain.args) return rv
def integrate(self, expr, rvs=None, **kwargs): rvs = rvs or (self.value,) if self.value not in rvs: return expr expr = expr.xreplace(dict((rv, rv.symbol) for rv in rvs)) x = self.value.symbol try: return self.distribution.expectation(expr, x, **kwargs) except: evaluate = kwargs.pop('evaluate', True) if evaluate: return summation(expr * self.pdf, (x, self.set.inf, self.set.sup), **kwargs) else: return Sum(expr * self.pdf, (x, self.set.inf, self.set.sup), **kwargs)
def test_hypersum(): from sympy import simplify, sin, hyper assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n + 1) / factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120 assert summation(1/(n + 2)**3, (n, 1, oo)) == -S(9)/8 + zeta(3) assert summation(1/n**4, (n, 1, oo)) == pi**4/90 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1) m = Symbol('n', integer=True, positive=True) assert summation(binomial(m, k), (k, 0, m)) == 2**m
def add_single_resonance(self, j, k, l, indexIn=1, indexOut=2): """ Add a single term associated the j:j-k MMR between planets 'indexIn' and 'indexOut'. Inputs: indexIn - index of the inner planet indexOut - index of the outer planet j - together with k specifies the MMR j:j-k k - order of the resonance l - picks out the eIn^(l) * eOut^(k-l) subterm """ # Canonical variables assert indexOut == indexIn + 1, "Only resonances for adjacent pairs are currently supported" G = symbols('G') mIn, MIn, LambdaIn, lambdaIn, XIn, YIn = symbols( 'm{0},M{0},Lambda{0},lambda{0},X{0},Y{0}'.format(indexIn)) mOut, MOut, LambdaOut, lambdaOut, XOut, YOut = symbols( 'm{0},M{0},Lambda{0},lambda{0},X{0},Y{0}'.format(indexOut)) #mIn, MIn, muIn, LambdaIn,lambdaIn,XIn,YIn = self._get_symbols(indexIn) #mOut, MOut, muOut, LambdaOut,lambdaOut,XOut,YOut = self._get_symbols(indexOut) # Resonance index assert l <= k, "Invalid resonance term, l must be less than or equal to k." alpha = self.particles[indexIn].a / self.state.particles[indexOut].a # Resonance components # Cjkl = symbols("C_{0}\,{1}\,{2}".format(j, k, l)) self.Hparams[Cjkl] = general_order_coefficient(j, k, l, alpha) # i = symbols('i') lBy2 = int(np.floor(l / 2.)) k_l = k - l k_lBy2 = int(np.floor((k_l) / 2.)) if l > 0: z_to_p_In_re = summation( binomial(l, (2 * i)) * XIn**(l - (2 * i)) * YIn**(2 * i) * (-1)**(i), (i, 0, lBy2)) z_to_p_In_im = summation( binomial(l, (2 * i + 1)) * XIn**(l - (2 * i + 1)) * YIn**(2 * i + 1) * (-1)**(i), (i, 0, lBy2)) else: z_to_p_In_re = 1 z_to_p_In_im = 0 if k_l > 0: z_to_p_Out_re = summation( binomial(k_l, (2 * i)) * XOut**(k_l - (2 * i)) * YOut**(2 * i) * (-1)**(i), (i, 0, k_lBy2)) z_to_p_Out_im = summation( binomial(k_l, (2 * i + 1)) * XOut**(k_l - (2 * i + 1)) * YOut**(2 * i + 1) * (-1)**(i), (i, 0, k_lBy2)) else: z_to_p_Out_re = 1 z_to_p_Out_im = 0 reFactor = (z_to_p_In_re * z_to_p_Out_re - z_to_p_In_im * z_to_p_Out_im) / sqrt(LambdaIn)**l / sqrt(LambdaOut)**k_l imFactor = (z_to_p_In_im * z_to_p_Out_re + z_to_p_In_re * z_to_p_Out_im) / sqrt(LambdaIn)**l / sqrt(LambdaOut)**k_l # Keep track of resonances self.resonance_indices.append((indexIn, indexOut, (j, k, l))) # Update internal Hamiltonian prefactor = -G**2 * MOut**2 * mOut**3 * (mIn / MIn) / (LambdaOut**2) costerm = cos(j * lambdaOut - (j - k) * lambdaIn) sinterm = sin(j * lambdaOut - (j - k) * lambdaIn) self.H += prefactor * Cjkl * (reFactor * costerm - imFactor * sinterm) self._update() # update polar Hamiltonian GammaIn, gammaIn, GammaOut, gammaOut = symbols( 'Gamma{0},gamma{0},Gamma{1},gamma{1}'.format(indexIn, indexOut)) eccIn = sqrt(2 * GammaIn / LambdaIn) eccOut = sqrt(2 * GammaOut / LambdaOut) # costerm = cos(j * lambdaOut - (j - k) * lambdaIn + l * gammaIn + (k - l) * gammaOut) # self.Hpolar += prefactor * Cjkl * (eccIn**l) * (eccOut **(k - l)) * costerm
import sympy as sp from sympy.core.sympify import SympifyError def input_reader(): try: expr1 = sp.sympify(input('Enter the n-th term of a series: ')) n = int(input('Enter n: ')) return expr1, n except (SympifyError, ValueError) as e: print(e) exit(1) if __name__ == '__main__': exp, num = input_reader() assert (num > 0) n = sp.Symbol('n') series = sp.summation(exp, (n, 1, num)) sp.pprint(series)
def _eval_product(self, term, limits): from sympy import summation (k, a, n) = limits if k not in term.free_symbols: return term**(n - a + 1) if a == n: return term.subs(k, a) dif = n - a if dif.is_Integer: return Mul(*[term.subs(k, a + i) for i in xrange(dif + 1)]) elif term.is_polynomial(k): poly = term.as_poly(k) A = B = Q = S.One all_roots = roots(poly, multiple=True) for r in all_roots: A *= C.RisingFactorial(a - r, n - a + 1) Q *= n - r if len(all_roots) < poly.degree(): arg = quo(poly, Q.as_poly(k)) B = Product(arg, (k, a, n)).doit() return poly.LC()**(n - a + 1) * A * B elif term.is_Add: p, q = term.as_numer_denom() p = self._eval_product(p, (k, a, n)) q = self._eval_product(q, (k, a, n)) return p / q elif term.is_Mul: exclude, include = [], [] for t in term.args: p = self._eval_product(t, (k, a, n)) if p is not None: exclude.append(p) else: include.append(t) if not exclude: return None else: arg = term._new_rawargs(*include) A = Mul(*exclude) B = Product(arg, (k, a, n)).doit() return A * B elif term.is_Pow: if not term.base.has(k): s = summation(term.exp, (k, a, n)) return term.base**s elif not term.exp.has(k): p = self._eval_product(term.base, (k, a, n)) if p is not None: return p**term.exp elif isinstance(term, Product): evaluated = term.doit() f = self._eval_product(evaluated, limits) if f is None: return Product(evaluated, limits) else: return f
def bench_sum(): x, i = symbols('x i') summation(x**i / i, (i, 1, 400))
arr = np.array(l) print(sum(arr)) #list2 from numpy import inf l = [] for i in range(1, 100000): a = (1 - 1 / i)**(2 * i) l.append(a) print(l[99998]) #ndarray2 import numpy as np from numpy import inf l = [] for i in range(1, 100000): a = (1 - 1 / i)**(2 * i) l.append(a) arr = np.array(l) print(arr[99998]) #sympy import sympy from sympy import * n = Symbol('n') s = (1 - (1 / n))**(2 * n) print(limit(s, n, oo)) i = sympy.symbols('i', integer=True) a = float( sympy.summation((((-1)**(i + 1)) / i) * ((6.0 / 7.0)**i), (i, 1, sympy.oo))) print(a)
print(degree(result)) syntelestes = result.coeffs() syntelestes = syntelestes[::-1] Lista2 = list() for i in range(0, degree(result)): temp = syntelestes[i] * ((ff(b + 1, i + 1)) - ff(a, i + 1)) Lista2.append(temp) p3 = 0 for i in range(0, len(Lista2)): p3 = p3 + Lista2[i] print('\n' '\n') p3 = Poly(p3, a, b) print('\n', p3) c = p3.coeffs() c = np.array(c) for i in range(0, len(c)): c[i] = Rational(c[i]).limit_denominator() ## # Εκτυπώνουμε ξανά τους συντελεστές στη σωστή μορφή όπως θα έδινε η summation, # ο όρος μηδέν αντιπροσωπεύει το συντελεστή του a^3 και b^3 ο οποίος λύπει απο τη summation # και παραθέτουμε και την επαλήθευσή της ## print('\n', c) print('\n', simplify(summation(p, (x, a, b))))
z = S.Symbol('z') a = S.Symbol('a') b = S.Symbol('b') c = S.Symbol('c') fx = -4 * x**2 + 2 * x + 1 # 解一元二次方程 print(S.solve(fx, x)) # 平方根 print(S.sqrt(2) * S.sqrt(3)) # 去括号 print(S.expand((a + b)**2)) # 方程组 print(S.solve([x + y - 1, x - y - 3]), [x, y]) # 求和式 i = S.Symbol('i', integer=True) fx = S.summation(x, (i, 1, 5)) + 10 * x - 15 print(S.solve(fx, x)) # 解一元二次方程 print(S.solve(x**2 - 2, x)) f = S.solve(x * S.log(4, 3) - 2, x) print(f) #print(S.log(S.E)) #print(S.log(1000,10)) print(S.expand_log(S.log(x * y), force=True)) #约分 fx = (x**2 + 3 * x + 2) / (x**2 + x) print(S.cancel(fx)) #三角函数 print(S.solve([S.sin(x - y), S.cos(x + y)], [x, y]))
def test_other_sums(): f = m**2 + m*exp(m) g = 3*exp(S(3)/2)/2 + exp(S(1)/2)/2 - exp(-S(1)/2)/2 - 3*exp(-S(3)/2)/2 + 5 assert summation(f, (m, -S(3)/2, S(3)/2)).expand() == g assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10)
def test_issue_4171(): assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) == oo assert summation(2*k + 1, (k, 0, oo)) == oo
def test_issue_7097(): assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400))
def test_issue_4170(): assert summation(1 / factorial(k), (k, 0, oo)) == E
def test_hypergeometric_sums(): assert summation(binomial(2 * k, k) / 4**k, (k, 0, n)) == (1 + 2 * n) * binomial(2 * n, n) / 4**n
def test_harmonic_sums(): assert summation(1 / k, (k, 0, n)) == Sum(1 / k, (k, 0, n)) assert summation(1 / k, (k, 1, n)) == harmonic(n) assert summation(n / k, (k, 1, n)) == n * harmonic(n) assert summation(1 / k, (k, 5, n)) == harmonic(n) - harmonic(4)
def plot_and_save(name): tmp_file = TmpFileManager.tmp_file x = Symbol('x') y = Symbol('y') z = Symbol('z') ### # Examples from the 'introduction' notebook ### p = plot(x) p = plot(x * sin(x), x * cos(x)) p.extend(p) p[0].line_color = lambda a: a p[1].line_color = 'b' p.title = 'Big title' p.xlabel = 'the x axis' p[1].label = 'straight line' p.legend = True p.aspect_ratio = (1, 1) p.xlim = (-15, 20) p.save(tmp_file('%s_basic_options_and_colors' % name)) p.extend(plot(x + 1)) p.append(plot(x + 3, x**2)[1]) p.save(tmp_file('%s_plot_extend_append' % name)) p[2] = plot(x**2, (x, -2, 3)) p.save(tmp_file('%s_plot_setitem' % name)) p = plot(sin(x), (x, -2 * pi, 4 * pi)) p.save(tmp_file('%s_line_explicit' % name)) p = plot(sin(x)) p.save(tmp_file('%s_line_default_range' % name)) p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3))) p.save(tmp_file('%s_line_multiple_range' % name)) raises(ValueError, lambda: plot(x, y)) #parametric 2d plots. #Single plot with default range. plot_parametric(sin(x), cos(x)).save(tmp_file()) #Single plot with range. p = plot_parametric(sin(x), cos(x), (x, -5, 5)) p.save(tmp_file('%s_parametric_range' % name)) #Multiple plots with same range. p = plot_parametric((sin(x), cos(x)), (x, sin(x))) p.save(tmp_file('%s_parametric_multiple' % name)) #Multiple plots with different ranges. p = plot_parametric((sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5))) p.save(tmp_file('%s_parametric_multiple_ranges' % name)) #depth of recursion specified. p = plot_parametric(x, sin(x), depth=13) p.save(tmp_file('%s_recursion_depth' % name)) #No adaptive sampling. p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500) p.save(tmp_file('%s_adaptive' % name)) #3d parametric plots p = plot3d_parametric_line(sin(x), cos(x), x) p.save(tmp_file('%s_3d_line' % name)) p = plot3d_parametric_line((sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3))) p.save(tmp_file('%s_3d_line_multiple' % name)) p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30) p.save(tmp_file('%s_3d_line_points' % name)) # 3d surface single plot. p = plot3d(x * y) p.save(tmp_file('%s_surface' % name)) # Multiple 3D plots with same range. p = plot3d(-x * y, x * y, (x, -5, 5)) p.save(tmp_file('%s_surface_multiple' % name)) # Multiple 3D plots with different ranges. p = plot3d((x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3))) p.save(tmp_file('%s_surface_multiple_ranges' % name)) # Single Parametric 3D plot p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y) p.save(tmp_file('%s_parametric_surface' % name)) # Multiple Parametric 3D plots. p = plot3d_parametric_surface( (x * sin(z), x * cos(z), z, (x, -5, 5), (z, -5, 5)), (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5))) p.save(tmp_file('%s_parametric_surface' % name)) ### # Examples from the 'colors' notebook ### p = plot(sin(x)) p[0].line_color = lambda a: a p.save(tmp_file('%s_colors_line_arity1' % name)) p[0].line_color = lambda a, b: b p.save(tmp_file('%s_colors_line_arity2' % name)) p = plot(x * sin(x), x * cos(x), (x, 0, 10)) p[0].line_color = lambda a: a p.save(tmp_file('%s_colors_param_line_arity1' % name)) p[0].line_color = lambda a, b: a p.save(tmp_file('%s_colors_param_line_arity2a' % name)) p[0].line_color = lambda a, b: b p.save(tmp_file('%s_colors_param_line_arity2b' % name)) p = plot3d_parametric_line( sin(x) + 0.1 * sin(x) * cos(7 * x), cos(x) + 0.1 * cos(x) * cos(7 * x), 0.1 * sin(7 * x), (x, 0, 2 * pi)) p[0].line_color = lambda a: sin(4 * a) p.save(tmp_file('%s_colors_3d_line_arity1' % name)) p[0].line_color = lambda a, b: b p.save(tmp_file('%s_colors_3d_line_arity2' % name)) p[0].line_color = lambda a, b, c: c p.save(tmp_file('%s_colors_3d_line_arity3' % name)) p = plot3d(sin(x) * y, (x, 0, 6 * pi), (y, -5, 5)) p[0].surface_color = lambda a: a p.save(tmp_file('%s_colors_surface_arity1' % name)) p[0].surface_color = lambda a, b: b p.save(tmp_file('%s_colors_surface_arity2' % name)) p[0].surface_color = lambda a, b, c: c p.save(tmp_file('%s_colors_surface_arity3a' % name)) p[0].surface_color = lambda a, b, c: sqrt((a - 3 * pi)**2 + b**2) p.save(tmp_file('%s_colors_surface_arity3b' % name)) p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y, (x, -1, 1), (y, -1, 1)) p[0].surface_color = lambda a: a p.save(tmp_file('%s_colors_param_surf_arity1' % name)) p[0].surface_color = lambda a, b: a * b p.save(tmp_file('%s_colors_param_surf_arity2' % name)) p[0].surface_color = lambda a, b, c: sqrt(a**2 + b**2 + c**2) p.save(tmp_file('%s_colors_param_surf_arity3' % name)) ### # Examples from the 'advanced' notebook ### i = Integral(log((sin(x)**2 + 1) * sqrt(x**2 + 1)), (x, 0, y)) p = plot(i, (y, 1, 5)) p.save(tmp_file('%s_advanced_integral' % name)) s = summation(1 / x**y, (x, 1, oo)) p = plot(s, (y, 2, 10)) p.save(tmp_file('%s_advanced_inf_sum' % name)) p = plot(summation(1 / x, (x, 1, y)), (y, 2, 10), show=False) p[0].only_integers = True p[0].steps = True p.save(tmp_file('%s_advanced_fin_sum' % name)) ### # Test expressions that can not be translated to np and generate complex # results. ### plot(sin(x) + I * cos(x)).save(tmp_file()) plot(sqrt(sqrt(-x))).save(tmp_file()) plot(LambertW(x)).save(tmp_file()) plot(sqrt(LambertW(x))).save(tmp_file()) #Characteristic function of a StudentT distribution with nu=10 plot((meijerg( ((1 / 2, ), ()), ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(-I * pi) / 2) + meijerg( ((1 / 2, ), ()), ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(I * pi) / 2)) / (48 * pi), (x, 1e-6, 1e-2)).save(tmp_file())
def _eval_rewrite_as_factorial(self, arg, **kwargs): from sympy import summation i = Dummy('i') f = S.NegativeOne**i / factorial(i) return factorial(arg) * summation(f, (i, 0, arg))
def test_issue_15852(): assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo))
def test_geometric_sums(): assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi) assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1 assert summation(Rational(1, 2)**n, (n, 1, oo)) == 1 assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1 assert summation(2**n, (n, 1, oo)) == oo assert summation(2**(-n), (n, 1, oo)) == 1 assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54) assert summation(2**(-4 * n + 3), (n, 1, oo)) == Rational(8, 15) assert summation(2**(n + 1), (n, 1, b)).expand() == 4 * (2**b - 1) # issue 6664: assert summation(x**n, (n, 0, oo)) == \ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True)) assert summation(-2**n, (n, 0, oo)) == -oo assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo)) # issue 6802: assert summation((-1)**(2 * x + 2), (x, 0, n)) == n + 1 assert summation((-2)**(2 * x + 2), (x, 0, n)) == 4 * 4**(n + 1) / S(3) - S(4) / 3 assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1) / S(2) + S(1) / 2 assert summation(y**x, (x, a, b)) == \ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True)) assert summation((-2)**(y*x + 2), (x, 0, n)) == \ 4*Piecewise((n + 1, Eq((-2)**y, 1)), ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True))
def test_Sum(): assert str(summation(cos(3 * z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))" assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ "Sum(x*y**2, (x, -2, 2), (y, -5, 5))"
print(sym.diff((6*x**3) + (5*x**2)+(4))) f1 = diff(sin(x), x) print(f1) f2 = diff(sin(2*x), x) print(f2) SeriesExp1 = cos(x).series(x,0,15) print(SeriesExp1) print(summation(2*i - 1, (i, 1, n))) print(summation(i,(i, 0, 2))) integral1 = integrate(7*x**5) print(integral1) integral2 = integrate(log(x)) print(integral2) f = Function('f') f(x).diff(x,x)+f(x) print(dsolve(f(x).diff(x,x) + f(x), f(x)))
def compute_moment_generating_function(self, **kwargs): t = Dummy('t', real=True) x = Dummy('x', integer=True) pdf = self.pdf(x) mgf = summation(exp(t*x)*pdf, (x, self.set.inf, self.set.sup)) return Lambda(t, mgf)
def find_sum(n_term, num_terms): n = Symbol("n") s = summation(n_term, (n, 1, num_terms)) pprint(s)
""" from sympy.plotting import plot import sympy as sym import xlsxwriter from xlrd import open_workbook from sympy.plotting import plot3d #Exercise one : x = sym.Symbol('x') y, i, n, a, b, z = sym.symbols('y i n a b z') expr = x**2 + x**3 + 21 * x**4 + 10 * x + 1 print(expr.subs(x, 7)) print(sym.expand(x + y)**2) print(sym.simplify(4 * x**3 + 21 * x**2 + 10 * x + 12)) print(sym.limit(1 / (x**2), x, sym.oo)) print(sym.summation(2 * i + i - 1, (i, 5, n))) print(sym.integrate(sym.sin(x) + sym.exp(x) * sym.cos(x) + sym.tan(x), x)) print(sym.factor(x**3 + 12 * x * y * z + 3 * y**2 * z)) print(sym.solveset(x - 4, x)) m1 = sym.Matrix([[5, 12, 40], [30, 70, 2]]) m2 = sym.Matrix([2, 1, 0]) print(m1 * m2) plot(x**3 + 3, (x, -10, 10)) f = x**2 * y**3 plot3d(f, (x, -6, 6), (y, -6, 6)) #============================================================================== #Exercise two : workbook = xlsxwriter.Workbook('test1.xlsx') worksheet = workbook.add_worksheet() worksheet.autofilter('A1:A5') data = ["This is Example", "My first export example", 1, 2, 3]
n = sym.Symbol("n") x = sym.Symbol("x") formula_p = input("n回目のゲームに勝つ確率は? ※サンクトペテルブルクのパラドックスなら (1/2)**n:") formula_x = input("n回目のゲームに勝ったときの賞金Xは? ※サンクトペテルブルクのパラドックスなら 2**n:") formula_p = sym.sympify(formula_p) formula_x = sym.sympify(formula_x) formula_n = sym.solve(formula_x - x, n) formula_n = sym.sympify(formula_n[0]) formula = formula_p.subs(n, formula_n) def temp(x1): return formula_x.subs(n, x1) print( f"求める確率分布の式は:{formula}\nただし、X=({temp(1)},{temp(2)},{temp(3)},...,{formula_x},...)" ) dis_x = [temp(i) for i in range(1, 11, 1)] dis_y = [formula.subs(x, j) for j in dis_x] plt.scatter(dis_x, dis_y) # plot(formula,(x,1,10),title="Expected value distribution") plt.show() formula_cul = formula_p * formula_x result = sym.summation(formula_cul, (n, 1, oo)) print(f"期待値は、一般項{formula_cul}の無限級数の総和を求めて、{result}")
def find_sum(nth_term,num_terms): n=symbols('n') s=summation(nth_term,(n,1,num_terms)) pprint(s)
def discrete_fourier_sympy(expr, n, k, N): foo = expr * sym.exp(-2 * j * pi * n * k / N) result = sym.summation(foo, (n, 0, N - 1)) return result
def compute_moment_generating_function(self, **kwargs): x, t = symbols('x, t', real=True, finite=True, cls=Dummy) pdf = self.pdf(x) mgf = summation(exp(t * x) * pdf, (x, self.set.inf, self.set.sup)) return Lambda(t, mgf)
def test_issue_1072(): k = Symbol("k") assert summation(factorial(2 * k + 1) / factorial(2 * k), (k, 0, oo)) == oo
def test_Sum_doit(): assert Sum(n * Integral(a**2), (n, 0, 2)).doit() == a**3 assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep = False) == \ 3*Integral(a**2) assert summation(n * Integral(a**2), (n, 0, 2)) == 3 * Integral(a**2)
def test_geometric_sums(): assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi) assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1 assert summation(Rational(1, 2)**n, (n, 1, oo)) == 1 assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1 assert summation(2**n, (n, 1, oo)) == oo assert summation(2**(-n), (n, 1, oo)) == 1 assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54) assert summation(2**(-4 * n + 3), (n, 1, oo)) == Rational(8, 15) assert summation(2**(n + 1), (n, 1, b)).expand() == 4 * (2**b - 1) # issue 6664: assert summation(x**n, (n, 0, oo)) == \ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True)) assert summation(-2**n, (n, 0, oo)) == -oo assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo)) # issue 6802: assert summation((-1)**(2 * x + 2), (x, 0, n)) == n + 1 assert summation((-2)**(2 * x + 2), (x, 0, n)) == 4 * 4**(n + 1) / S(3) - S(4) / 3 assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1) / S(2) + S(1) / 2 assert summation(y**x, (x, a, b)) == \ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True)) assert summation((-2)**(y*x + 2), (x, 0, n)) == \ 4*Piecewise((n + 1, Eq((-2)**y, 1)), ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True)) # issue 8251: assert summation((1 / (n + 1)**2) * n**2, (n, 0, oo)) == oo #issue 9908: assert Sum(1 / (n**3 - 1), (n, -oo, -2)).doit() == summation(1 / (n**3 - 1), (n, -oo, -2)) #issue 11642: result = Sum(0.5**n, (n, 1, oo)).doit() assert result == 1 assert result.is_Float result = Sum(0.25**n, (n, 1, oo)).doit() assert result == S(1) / 3 assert result.is_Float result = Sum(0.99999**n, (n, 1, oo)).doit() assert result == 99999 assert result.is_Float result = Sum(Rational(1, 2)**n, (n, 1, oo)).doit() assert result == 1 assert not result.is_Float result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit() assert result == S(3) / 2 assert not result.is_Float assert Sum(1.0**n, (n, 1, oo)).doit() == oo assert Sum(2.43**n, (n, 1, oo)).doit() == oo
def test_issue_4668(): assert summation(1/n, (n, 2, oo)) == oo