def eval(cls, n, z): n, z = list(map(sympify, (n, z))) from sympy import unpolarify if n.is_integer: if n.is_nonnegative: nz = unpolarify(z) if z != nz: return polygamma(n, nz) if n == -1: return loggamma(z) else: if z.is_Number: if z is S.NaN: return S.NaN elif z is S.Infinity: if n.is_Number: if n is S.Zero: return S.Infinity else: return S.Zero elif z.is_Integer: if z.is_nonpositive: return S.ComplexInfinity else: if n is S.Zero: return -S.EulerGamma + C.harmonic(z - 1, 1) elif n.is_odd: return (-1) ** (n + 1) * C.factorial(n) * zeta(n + 1, z) if n == 0: if z is S.NaN: return S.NaN elif z.is_Rational: # TODO actually *any* n/m can be done, but that is messy lookup = { S(1) / 2: -2 * log(2) - S.EulerGamma, S(1) / 3: -S.Pi / 2 / sqrt(3) - 3 * log(3) / 2 - S.EulerGamma, S(1) / 4: -S.Pi / 2 - 3 * log(2) - S.EulerGamma, S(3) / 4: -3 * log(2) - S.EulerGamma + S.Pi / 2, S(2) / 3: -3 * log(3) / 2 + S.Pi / 2 / sqrt(3) - S.EulerGamma, } if z > 0: n = floor(z) z0 = z - n if z0 in lookup: return lookup[z0] + Add(*[1 / (z0 + k) for k in range(n)]) elif z < 0: n = floor(1 - z) z0 = z + n if z0 in lookup: return lookup[z0] - Add(*[1 / (z0 - 1 - k) for k in range(n)]) elif z in (S.Infinity, S.NegativeInfinity): return S.Infinity else: t = z.extract_multiplicatively(S.ImaginaryUnit) if t in (S.Infinity, S.NegativeInfinity): return S.Infinity
def test_issue_8413(): x = Symbol('x', real=True) # we can't evaluate in general because non-reals are not # comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError assert Min(floor(x), x) == floor(x) assert Min(ceiling(x), x) == x assert Max(floor(x), x) == x assert Max(ceiling(x), x) == ceiling(x)
def test_slicing(): assert X[1:5, 2:4] == MatrixSlice(X, (1, 5), (2, 4)) assert X[1, 2:4] == MatrixSlice(X, 1, (2, 4)) assert X[1:5, :].shape == (4, X.shape[1]) assert X[:, 1:5].shape == (X.shape[0], 4) assert X[::2, ::2].shape == (floor(n/2), floor(m/2)) assert X[2, :] == MatrixSlice(X, 2, (0, m))
def as_relational(self, x): """Rewrite a Range in terms of equalities and logic operators. """ from sympy.functions.elementary.integers import floor return And( Eq(x, floor(x)), x >= self.inf if self.inf in self else x > self.inf, x <= self.sup if self.sup in self else x < self.sup)
def real_root(arg, n=None): """Return the real nth-root of arg if possible. If n is omitted then all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this will only create a real root of a principle root -- the presence of other factors may cause the result to not be real. Examples ======== >>> from sympy import root, real_root, Rational >>> from sympy.abc import x, n >>> real_root(-8, 3) -2 >>> root(-8, 3) 2*(-1)**(1/3) >>> real_root(_) -2 If one creates a non-principle root and applies real_root, the result will not be real (so use with caution): >>> root(-8, 3, 2) -2*(-1)**(2/3) >>> real_root(_) -2*(-1)**(2/3) See Also ======== sympy.polys.rootoftools.rootof sympy.core.power.integer_nthroot root, sqrt """ from sympy import im, Piecewise if n is not None: try: n = as_int(n) arg = sympify(arg) if arg.is_positive or arg.is_negative: rv = root(arg, n) else: raise ValueError except ValueError: return root(arg, n)*Piecewise( (S.One, ~Equality(im(arg), 0)), (Pow(S.NegativeOne, S.One/n)**(2*floor(n/2)), And( Equality(n % 2, 1), arg < 0)), (S.One, True)) else: rv = sympify(arg) n1pow = Transform(lambda x: -(-x.base)**x.exp, lambda x: x.is_Pow and x.base.is_negative and x.exp.is_Rational and x.exp.p == 1 and x.exp.q % 2) return rv.xreplace(n1pow)
def _eval_rewrite_as_polynomial(self, n, m, x, **kwargs): from sympy import Sum k = Dummy("k") kern = factorial(2 * n - 2 * k) / ( 2**n * factorial(n - k) * factorial(k) * factorial(n - 2 * k - m)) * (-1)**k * x**(n - m - 2 * k) return (1 - x**2)**(m / 2) * Sum(kern, (k, 0, floor((n - m) * S.Half)))
def test_tribonacci(): assert [tribonacci(n) for n in range(8)] == [0, 1, 1, 2, 4, 7, 13, 24] assert tribonacci(100) == 98079530178586034536500564 assert tribonacci(0, x) == 0 assert tribonacci(1, x) == 1 assert tribonacci(2, x) == x**2 assert tribonacci(3, x) == x**4 + x assert tribonacci(4, x) == x**6 + 2 * x**3 + 1 assert tribonacci(5, x) == x**8 + 3 * x**5 + 3 * x**2 n = Dummy('n') assert tribonacci(n).limit(n, S.Infinity) is S.Infinity w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2 a = (1 + cbrt(19 + 3 * sqrt(33)) + cbrt(19 - 3 * sqrt(33))) / 3 b = (1 + w * cbrt(19 + 3 * sqrt(33)) + w**2 * cbrt(19 - 3 * sqrt(33))) / 3 c = (1 + w**2 * cbrt(19 + 3 * sqrt(33)) + w * cbrt(19 - 3 * sqrt(33))) / 3 assert tribonacci(n).rewrite(sqrt) == \ (a**(n + 1)/((a - b)*(a - c)) + b**(n + 1)/((b - a)*(b - c)) + c**(n + 1)/((c - a)*(c - b))) assert tribonacci(n).rewrite(sqrt).subs(n, 4).simplify() == tribonacci(4) assert tribonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \ tribonacci(10) assert tribonacci(n).rewrite(TribonacciConstant) == floor( 3 * TribonacciConstant**n * (102 * sqrt(33) + 586)**Rational(1, 3) / (-2 * (102 * sqrt(33) + 586)**Rational(1, 3) + 4 + (102 * sqrt(33) + 586)**Rational(2, 3)) + S.Half) raises(ValueError, lambda: tribonacci(-1, x))
def _eval_expand_func(self, **hints): from sympy import Sum n = self.args[0] m = self.args[1] if len(self.args) == 2 else 1 if m == S.One: if n.is_Add: off = n.args[0] nnew = n - off if off.is_Integer and off.is_positive: result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)] return Add(*result) elif off.is_Integer and off.is_negative: result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)] return Add(*result) if n.is_Rational: # Expansions for harmonic numbers at general rational arguments (u + p/q) # Split n as u + p/q with p < q p, q = n.as_numer_denom() u = p // q p = p - u * q if u.is_nonnegative and p.is_positive and q.is_positive and p < q: k = Dummy("k") t1 = q * Sum(1 / (q * k + p), (k, 0, u)) t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) * log(sin((pi * k) / S(q))), (k, 1, floor((q - 1) / S(2)))) t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q) return t1 + t2 - t3 return self
def _eval_expand_func(self, **hints): from sympy import Sum n = self.args[0] m = self.args[1] if len(self.args) == 2 else 1 if m == S.One: if n.is_Add: off = n.args[0] nnew = n - off if off.is_Integer and off.is_positive: result = [S.One / (nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)] return Add(*result) elif off.is_Integer and off.is_negative: result = [-S.One / (nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)] return Add(*result) if n.is_Rational: # Expansions for harmonic numbers at general rational arguments (u + p/q) # Split n as u + p/q with p < q p, q = n.as_numer_denom() u = p // q p = p - u * q if u.is_nonnegative and p.is_positive and q.is_positive and p < q: k = Dummy("k") t1 = q * Sum(1 / (q * k + p), (k, 0, u)) t2 = 2 * Sum( cos((2 * pi * p * k) / S(q)) * log(sin( (pi * k) / S(q))), (k, 1, floor((q - 1) / S(2)))) t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q) return t1 + t2 - t3 return self
def real_root(arg, n=None): """Return the real nth-root of arg if possible. If n is omitted then all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this will only create a real root of a principle root -- the presence of other factors may cause the result to not be real. Examples ======== >>> from sympy import root, real_root, Rational >>> from sympy.abc import x, n >>> real_root(-8, 3) -2 >>> root(-8, 3) 2*(-1)**(1/3) >>> real_root(_) -2 If one creates a non-principle root and applies real_root, the result will not be real (so use with caution): >>> root(-8, 3, 2) -2*(-1)**(2/3) >>> real_root(_) -2*(-1)**(2/3) See Also ======== sympy.polys.rootoftools.RootOf sympy.core.power.integer_nthroot root, sqrt """ from sympy import im, Piecewise if n is not None: try: n = as_int(n) arg = sympify(arg) if arg.is_positive or arg.is_negative: rv = root(arg, n) else: raise ValueError except ValueError: return root(arg, n)*Piecewise( (S.One, ~Equality(im(arg), 0)), (Pow(S.NegativeOne, S.One/n)**(2*floor(n/2)), And( Equality(n % 2, 1), arg < 0)), (S.One, True)) else: rv = sympify(arg) n1pow = Transform(lambda x: -(-x.base)**x.exp, lambda x: x.is_Pow and x.base.is_negative and x.exp.is_Rational and x.exp.p == 1 and x.exp.q % 2) return rv.xreplace(n1pow)
def _intersect(self, other): from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.elementary.miscellaneous import Min, Max if other.is_Interval: osup = other.sup oinf = other.inf # if other is [0, 10) we can only go up to 9 if osup.is_integer and other.right_open: osup -= 1 if oinf.is_integer and other.left_open: oinf += 1 # Take the most restrictive of the bounds set by the two sets # round inwards inf = ceiling(Max(self.inf, oinf)) sup = floor(Min(self.sup, osup)) # if we are off the sequence, get back on if inf.is_finite and self.inf.is_finite: off = (inf - self.inf) % self.step else: off = S.Zero if off: inf += self.step - off return Range(inf, sup + 1, self.step) if other == S.Naturals: return self._intersect(Interval(1, S.Infinity)) if other == S.Integers: return self return None
def sample(self): """ A random realization from the distribution """ icdf = self._inverse_cdf_expression() while True: sample_ = floor(list(icdf(random.uniform(0, 1)))[0]) if sample_ >= self.set.inf: return sample_
def test_issue_17681(): class identity_func(Function): def _eval_evalf(self, *args, **kwargs): return self.args[0].evalf(*args, **kwargs) assert floor(identity_func(S(0))) == 0 assert get_integer_part(S(0), 1, {}, True) == (0, 0)
def _intersect(self, other): from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.elementary.miscellaneous import Min, Max if other.is_Interval: osup = other.sup oinf = other.inf # if other is [0, 10) we can only go up to 9 if osup.is_integer and other.right_open: osup -= 1 if oinf.is_integer and other.left_open: oinf += 1 # Take the most restrictive of the bounds set by the two sets # round inwards inf = ceiling(Max(self.inf, oinf)) sup = floor(Min(self.sup, osup)) # if we are off the sequence, get back on off = (inf - self.inf) % self.step if off: inf += self.step - off return Range(inf, sup + 1, self.step) if other == S.Naturals: return self._intersect(Interval(1, S.Infinity)) if other == S.Integers: return self return None
def _intersect(self, other): if other.is_Interval: osup = other.sup oinf = other.inf # if other is [0, 10) we can only go up to 9 if osup.is_integer and other.right_open: osup -= 1 if oinf.is_integer and other.left_open: oinf += 1 # Take the most restrictive of the bounds set by the two sets # round inwards inf = ceiling(Max(self.inf, oinf)) sup = floor(Min(self.sup, osup)) # if we are off the sequence, get back on off = (inf - self.inf) % self.step if off: inf += self.step - off return Range(inf, sup + 1, self.step) if other == S.Naturals: return self._intersect(Interval(1, oo)) if other == S.Integers: return self return None
def test_floor_requires_robust_assumptions(): assert limit(floor(sin(x)), x, 0, "+") == 0 assert limit(floor(sin(x)), x, 0, "-") == -1 assert limit(floor(cos(x)), x, 0, "+") == 0 assert limit(floor(cos(x)), x, 0, "-") == 0 assert limit(floor(5 + sin(x)), x, 0, "+") == 5 assert limit(floor(5 + sin(x)), x, 0, "-") == 4 assert limit(floor(5 + cos(x)), x, 0, "+") == 5 assert limit(floor(5 + cos(x)), x, 0, "-") == 5
def _intersect(self, other): from sympy.functions.elementary.integers import floor, ceiling if other is Interval(S.NegativeInfinity, S.Infinity) or other is S.Reals: return self elif other.is_Interval: s = Range(ceiling(other.left), floor(other.right) + 1) return s.intersect(other) # take out endpoints if open interval return None
def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy import Sum k = Dummy("k") kern = ( (-1) ** k / (factorial(k) * factorial(n - 2 * k)) * (2 * x) ** (n - 2 * k) ) return factorial(n) * Sum(kern, (k, 0, floor(n / 2)))
def _intlike_interval(a, b): try: if b._inf is S.NegativeInfinity and b._sup is S.Infinity: return a s = Range(max(a.inf, ceiling(b.left)), floor(b.right) + 1) return intersection_sets(s, b) # take out endpoints if open interval except ValueError: return None
def _eval_expand_func(self, **hints): n, z = self.args if n.is_Integer and n.is_nonnegative: if z.is_Add: coeff = z.args[0] if coeff.is_Integer: e = -(n + 1) if coeff > 0: tail = Add(*[Pow( z - i, e) for i in range(1, int(coeff) + 1)]) else: tail = -Add(*[Pow( z + i, e) for i in range(0, int(-coeff))]) return polygamma(n, z - coeff) + (-1)**n*factorial(n)*tail elif z.is_Mul: coeff, z = z.as_two_terms() if coeff.is_Integer and coeff.is_positive: tail = [ polygamma(n, z + Rational( i, coeff)) for i in range(0, int(coeff)) ] if n == 0: return Add(*tail)/coeff + log(coeff) else: return Add(*tail)/coeff**(n + 1) z *= coeff if n == 0 and z.is_Rational: p, q = z.as_numer_denom() # Reference: # Values of the polygamma functions at rational arguments, J. Choi, 2007 part_1 = -S.EulerGamma - pi * cot(p * pi / q) / 2 - log(q) + Add( *[cos(2 * k * pi * p / q) * log(2 * sin(k * pi / q)) for k in range(1, q)]) if z > 0: n = floor(z) z0 = z - n return part_1 + Add(*[1 / (z0 + k) for k in range(n)]) elif z < 0: n = floor(1 - z) z0 = z + n return part_1 - Add(*[1 / (z0 - 1 - k) for k in range(n)]) return polygamma(n, z)
def intersection_sets(a, b): try: from sympy.functions.elementary.integers import floor, ceiling if b._inf is S.NegativeInfinity and b._sup is S.Infinity: return a s = Range(ceiling(b.left), floor(b.right) + 1) return intersection_sets(s, b) # take out endpoints if open interval except ValueError: return None
def size(self): if self.start == self.stop: return S.Zero dif = self.stop - self.start n = dif / self.step if n.is_infinite: return S.Infinity if n.is_extended_nonnegative and all(i.is_integer for i in self.args): return abs(floor(n)) raise ValueError('Invalid method for symbolic Range')
def apply(n): X = Symbol.X(integer=True, random=True) if n.is_even: return Equality(Expectation[X:DieDistribution(n)](X | (X > n / 2)), (3 * n + 2) / 4) elif n.is_odd: return Equality(Expectation[X:DieDistribution(n)](X | (X > n / 2)), (3 * n + 1) / 4) else: return Equality(Expectation[X:DieDistribution(n)](X | (X > n / 2)), n / 2 + floor(n / 2) / 2)
def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy import Sum k = Dummy("k") kern = ( S.NegativeOne ** k * factorial(n - k) * (2 * x) ** (n - 2 * k) / (factorial(k) * factorial(n - 2 * k)) ) return Sum(kern, (k, 0, floor(n / 2)))
def sample(self, size=(1, ), library='scipy'): """ A random realization from the distribution""" if hasattr(self, '_sample_scipy') and import_module('scipy'): return self._sample_scipy(size=size) icdf = self._inverse_cdf_expression() samp_list = [] while True: sample_ = floor(list(icdf(random.uniform(0, 1)))[0]) if sample_ >= self.set.inf: samp_list.append(sample_) if len(samp_list) == size: return samp_list
def test_gegenbauer(): n = Symbol("n") a = Symbol("a") assert gegenbauer(0, a, x) == 1 assert gegenbauer(1, a, x) == 2 * a * x assert gegenbauer(2, a, x) == -a + x**2 * (2 * a**2 + 2 * a) assert gegenbauer(3, a, x) == \ x**3*(4*a**3/3 + 4*a**2 + a*Rational(8, 3)) + x*(-2*a**2 - 2*a) assert gegenbauer(-1, a, x) == 0 assert gegenbauer(n, S.Half, x) == legendre(n, x) assert gegenbauer(n, 1, x) == chebyshevu(n, x) assert gegenbauer(n, -1, x) == 0 X = gegenbauer(n, a, x) assert isinstance(X, gegenbauer) assert gegenbauer(n, a, -x) == (-1)**n * gegenbauer(n, a, x) assert gegenbauer(n, a, 0) == 2**n*sqrt(pi) * \ gamma(a + n/2)/(gamma(a)*gamma(-n/2 + S.Half)*gamma(n + 1)) assert gegenbauer(n, a, 1) == gamma(2 * a + n) / (gamma(2 * a) * gamma(n + 1)) assert gegenbauer(n, Rational(3, 4), -1) is zoo assert gegenbauer(n, Rational(1, 4), -1) == (sqrt(2) * cos(pi * (n + S.One / 4)) * gamma(n + S.Half) / (sqrt(pi) * gamma(n + 1))) m = Symbol("m", positive=True) assert gegenbauer(m, a, oo) == oo * RisingFactorial(a, m) assert unchanged(gegenbauer, n, a, oo) assert conjugate(gegenbauer(n, a, x)) == gegenbauer(n, conjugate(a), conjugate(x)) _k = Dummy('k') assert diff(gegenbauer(n, a, x), n) == Derivative(gegenbauer(n, a, x), n) assert diff(gegenbauer(n, a, x), a).dummy_eq( Sum((2 * (-1)**(-_k + n) + 2) * (_k + a) * gegenbauer(_k, a, x) / ((-_k + n) * (_k + 2 * a + n)) + ((2 * _k + 2) / ((_k + 2 * a) * (2 * _k + 2 * a + 1)) + 2 / (_k + 2 * a + n)) * gegenbauer(n, a, x), (_k, 0, n - 1))) assert diff(gegenbauer(n, a, x), x) == 2 * a * gegenbauer(n - 1, a + 1, x) assert gegenbauer(n, a, x).rewrite('polynomial').dummy_eq( Sum((-1)**_k * (2 * x)**(-2 * _k + n) * RisingFactorial(a, -_k + n) / (factorial(_k) * factorial(-2 * _k + n)), (_k, 0, floor(n / 2)))) raises(ArgumentIndexError, lambda: gegenbauer(n, a, x).fdiff(4))
def _compute_slice_size(idx: Any, axis_size: Any) -> Any: # noqa: R701 if idx is None: return axis_size if not isinstance(idx, sp.Tuple): return 1 start, stop, step = idx if stop is None and axis_size is None: return None size = stop - start size = size if step == 1 or step is None else floor(size / step) if axis_size is not None and (size > axis_size) == True: # noqa: E712 return axis_size return size
def test_assoc_legendre(): Plm = assoc_legendre Q = sqrt(1 - x**2) assert Plm(0, 0, x) == 1 assert Plm(1, 0, x) == x assert Plm(1, 1, x) == -Q assert Plm(2, 0, x) == (3 * x**2 - 1) / 2 assert Plm(2, 1, x) == -3 * x * Q assert Plm(2, 2, x) == 3 * Q**2 assert Plm(3, 0, x) == (5 * x**3 - 3 * x) / 2 assert Plm(3, 1, x).expand() == ((3 * (1 - 5 * x**2) / 2).expand() * Q).expand() assert Plm(3, 2, x) == 15 * x * Q**2 assert Plm(3, 3, x) == -15 * Q**3 # negative m assert Plm(1, -1, x) == -Plm(1, 1, x) / 2 assert Plm(2, -2, x) == Plm(2, 2, x) / 24 assert Plm(2, -1, x) == -Plm(2, 1, x) / 6 assert Plm(3, -3, x) == -Plm(3, 3, x) / 720 assert Plm(3, -2, x) == Plm(3, 2, x) / 120 assert Plm(3, -1, x) == -Plm(3, 1, x) / 12 n = Symbol("n") m = Symbol("m") X = Plm(n, m, x) assert isinstance(X, assoc_legendre) assert Plm(n, 0, x) == legendre(n, x) assert Plm(n, m, 0) == 2**m * sqrt(pi) / (gamma(-m / 2 - n / 2 + S.Half) * gamma(-m / 2 + n / 2 + 1)) assert diff(Plm(m, n, x), x) == (m * x * assoc_legendre(m, n, x) - (m + n) * assoc_legendre(m - 1, n, x)) / (x**2 - 1) _k = Dummy('k') assert Plm(m, n, x).rewrite("polynomial").dummy_eq( (1 - x**2)**(n / 2) * Sum( (-1)**_k * 2**(-m) * x**(-2 * _k + m - n) * factorial(-2 * _k + 2 * m) / (factorial(_k) * factorial(-_k + m) * factorial(-2 * _k + m - n)), (_k, 0, floor(m / 2 - n / 2)))) assert conjugate(assoc_legendre(n, m, x)) == \ assoc_legendre(n, conjugate(m), conjugate(x)) raises(ValueError, lambda: Plm(0, 1, x)) raises(ValueError, lambda: Plm(-1, 1, x)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(1)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(2)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(4))
def eval(cls, arg): from sympy import atan arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg is S.One: return S.Infinity elif arg is S.NegativeOne: return S.NegativeInfinity elif arg is S.Infinity: return -S.ImaginaryUnit * atan(arg) elif arg is S.NegativeInfinity: return S.ImaginaryUnit * atan(-arg) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: from sympy.calculus.util import AccumBounds return S.ImaginaryUnit * AccumBounds(-S.Pi / 2, S.Pi / 2) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * atan(i_coeff) else: if _coeff_isneg(arg): return -cls(-arg) if arg.is_zero: return S.Zero if isinstance(arg, tanh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor(2 * i / pi) even = f.is_even m = z - I * f * pi / 2 if even is True: return m elif even is False: return m - I * pi / 2
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_expand_func(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] if arg.is_Add: coeff, tail = arg.as_coeff_add() if coeff and coeff.q != 1: tail = (C.Rational(1, coeff.q), ) + tail coeff = floor(coeff) tail = arg._new_rawargs(*tail, **dict(reeval=False)) return gamma(tail) * C.RisingFactorial(tail, coeff) return self.func(*self.args)
def compute_cdf(self, **kwargs): """ Compute the CDF from the PDF. Returns a Lambda. """ x = symbols('x', integer=True, cls=Dummy) z = symbols('z', real=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, floor(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 _eval_expand_func(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] if arg.is_Add: coeff, tail = arg.as_coeff_add() if coeff and coeff.q != 1: tail = (C.Rational(1, coeff.q),) + tail coeff = floor(coeff) tail = arg._new_rawargs(*tail, **dict(reeval=False)) return gamma(tail)*C.RisingFactorial(tail, coeff) return self.func(*self.args)
def test_evalf_integer_parts(): a = floor(log(8) / log(2) - exp(-1000), evaluate=False) b = floor(log(8) / log(2), evaluate=False) assert a.evalf() == 3 assert b.evalf() == 3 # equals, as a fallback, can still fail but it might succeed as here assert ceiling(10 * (sin(1)**2 + cos(1)**2)) == 10 assert int(floor(factorial(50)/E, evaluate=False).evalf(70)) == \ int(11188719610782480504630258070757734324011354208865721592720336800) assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \ int(11188719610782480504630258070757734324011354208865721592720336801) assert int(floor(GoldenRatio**999 / sqrt(5) + S.Half).evalf(1000)) == fibonacci(999) assert int(floor(GoldenRatio**1000 / sqrt(5) + S.Half).evalf(1000)) == fibonacci(1000) assert ceiling(x).evalf(subs={x: 3}) == 3 assert ceiling(x).evalf(subs={x: 3 * I}) == 3.0 * I assert ceiling(x).evalf(subs={x: 2 + 3 * I}) == 2.0 + 3.0 * I assert ceiling(x).evalf(subs={x: 3.}) == 3 assert ceiling(x).evalf(subs={x: 3. * I}) == 3.0 * I assert ceiling(x).evalf(subs={x: 2. + 3 * I}) == 2.0 + 3.0 * I assert float((floor(1.5, evaluate=False) + 1 / 9).evalf()) == 1 + 1 / 9 assert float((floor(0.5, evaluate=False) + 20).evalf()) == 20 # issue 19991 n = 1169809367327212570704813632106852886389036911 r = 744723773141314414542111064094745678855643068 assert floor(n / (pi / 2)) == r assert floor(80782 * sqrt(2)) == 114242 # issue 20076 assert 260515 - floor(260515 / pi + 1 / 2) * pi == atan(tan(260515))
def eval(cls, arg): from sympy import asin arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.NegativeInfinity elif arg.is_zero: return S.Zero elif arg is S.One: return log(sqrt(2) + 1) elif arg is S.NegativeOne: return log(sqrt(2) - 1) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.is_zero: return S.Zero i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * asin(i_coeff) else: if _coeff_isneg(arg): return -cls(-arg) if isinstance(arg, sinh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor((i + pi / 2) / pi) m = z - I * pi * f even = f.is_even if even is True: return m elif even is False: return -m
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 test_issue9474(): mods = [None, 'math'] if numpy: mods.append('numpy') if mpmath: mods.append('mpmath') for mod in mods: f = lambdify(x, S.One / x, modules=mod) assert f(2) == 0.5 f = lambdify(x, floor(S.One / x), modules=mod) assert f(2) == 0 for absfunc, modules in product([Abs, abs], mods): f = lambdify(x, absfunc(x), modules=modules) assert f(-1) == 1 assert f(1) == 1 assert f(3 + 4j) == 5
def intersection_sets(a, b): # noqa:F811 from sympy.functions.elementary.integers import floor, ceiling if not all(i.is_number for i in b.args[:2]): return # In case of null Range, return an EmptySet. if a.size == 0: return S.EmptySet # trim down to self's size, and represent # as a Range with step 1. start = ceiling(max(b.inf, a.inf)) if start not in b: start += 1 end = floor(min(b.sup, a.sup)) if end not in b: end -= 1 return intersection_sets(a, Range(start, end + 1))
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 else: raise NotImplementedError(filldedent('''Probability for the domain %s cannot be calculated.'''%(_domain)))
def _eval_expand_func(self, **hints): arg = self.args[0] if arg.is_Rational: if abs(arg.p) > arg.q: x = Dummy("x") n = arg.p // arg.q p = arg.p - n * arg.q return gamma(x + n)._eval_expand_func().subs(x, Rational(p, arg.q)) if arg.is_Add: coeff, tail = arg.as_coeff_add() if coeff and coeff.q != 1: intpart = floor(coeff) tail = (coeff - intpart,) + tail coeff = intpart tail = arg._new_rawargs(*tail, reeval=False) return gamma(tail) * C.RisingFactorial(tail, coeff) return self.func(*self.args)
def intersection_sets(a, b): from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.elementary.miscellaneous import Min, Max if not all(i.is_number for i in b.args[:2]): return # In case of null Range, return an EmptySet. if a.size == 0: return S.EmptySet # trim down to self's size, and represent # as a Range with step 1. start = ceiling(max(b.inf, a.inf)) if start not in b: start += 1 end = floor(min(b.sup, a.sup)) if end not in b: end -= 1 return intersection_sets(a, Range(start, end + 1))
def update(self): filled_length = round(self.width * self.progress, self.tenths) filled_length_int = floor(self.width * self.progress) _int = round(filled_length - filled_length_int, self.tenths) phase = self.nphases[_int] #print(filled_length) #print(filled_length_int) #print(_int) #print(phase) percent = "{:.0%} ".format(self.progress) empty_length = round(self.width - filled_length, 1) message = self.message if filled_length == 0: bar = ' ' else: bar = self.COLOR.format('█'* int(filled_length)+ phase) empty = ' ' * int(empty_length) #suffix = self.suffix line = ''.join([message, percent, self.bar_prefix, bar, empty, self.bar_prefix]) self.file.writelines(line) self.file.flush()
def _eval_is_positive(self): x = self.args[0] if x.is_positive: return True elif x.is_noninteger: return floor(x).is_even
def _eval_rewrite_as_polynomial(self, n, x): from sympy import Sum k = Dummy("k") kern = (-1)**k / (factorial(k)*factorial(n - 2*k)) * (2*x)**(n - 2*k) return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
def test_issue_8623(): assert integrate((1 + cos(2*x)) / (3 - 2*cos(2*x)), (x, 0, pi)) == -pi/2 + sqrt(5)*pi/2 assert integrate((1 + cos(2*x))/(3 - 2*cos(2*x))) == -x/2 + sqrt(5)*(atan(sqrt(5)*tan(x)) + \ pi*floor((x - pi/2)/pi))/2
def _intersect(self, other): if other.is_Interval: s = FiniteSet(range(ceiling(other.left), floor(other.right) + 1)) return s.intersect(other) # take out endpoints if open interval return None
def _eval_rewrite_as_polynomial(self, n, x): from sympy import Sum k = Dummy("k") kern = S.NegativeOne**k * factorial( n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k)) return Sum(kern, (k, 0, floor(n/2)))
def _eval_rewrite_as_polynomial(self, n, m, x): from sympy import Sum k = Dummy("k") kern = factorial(2*n - 2*k)/(2**n*factorial(n - k)*factorial( k)*factorial(n - 2*k - m))*(-1)**k*x**(n - m - 2*k) return (1 - x**2)**(m/2) * Sum(kern, (k, 0, floor((n - m)*S.Half)))
def shape(self): rows = self.rowslice[1] - self.rowslice[0] rows = rows if self.rowslice[2] == 1 else floor(rows/self.rowslice[2]) cols = self.colslice[1] - self.colslice[0] cols = cols if self.colslice[2] == 1 else floor(cols/self.colslice[2]) return rows, cols
def _eval_rewrite_as_polynomial(self, n, x): from sympy import Sum k = Dummy("k") kern = binomial(n, 2*k) * (x**2 - 1)**k * x**(n - 2*k) return Sum(kern, (k, 0, floor(n/2)))
def rsolve_hypergeometric(f, x, P, Q, k, m): """Solves RE of hypergeometric type. Attempts to solve RE of the form Q(k)*a(k + m) - P(k)*a(k) Transformations that preserve Hypergeometric type: a. x**n*f(x): b(k + m) = R(k - n)*b(k) b. f(A*x): b(k + m) = A**m*R(k)*b(k) c. f(x**n): b(k + n*m) = R(k/n)*b(k) d. f(x**(1/m)): b(k + 1) = R(k*m)*b(k) e. f'(x): b(k + m) = ((k + m + 1)/(k + 1))*R(k + 1)*b(k) Some of these transformations have been used to solve the RE. Returns ======= formula : Expr ind : Expr Independent terms. order : int Examples ======== >>> from sympy import exp, ln, S >>> from sympy.series.formal import rsolve_hypergeometric as rh >>> from sympy.abc import x, k >>> rh(exp(x), x, -S.One, (k + 1), k, 1) (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1) >>> rh(ln(1 + x), x, k**2, k*(k + 1), k, 1) (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1), Eq(Mod(k, 1), 0)), (0, True)), x, 2) References ========== .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf .. [2] Power Series in Computer Algebra - Wolfram Koepf """ result = _rsolve_hypergeometric(f, x, P, Q, k, m) if result is None: return None sol_list, ind, mp = result sol_dict = defaultdict(lambda: S.Zero) for res, cond in sol_list: j, mk = cond.as_coeff_Add() c = mk.coeff(k) if j.is_integer is False: res *= x**frac(j) j = floor(j) res = res.subs(k, (k - j) / c) cond = Eq(k % c, j % c) sol_dict[cond] += res # Group together formula for same conditions sol = [] for cond, res in sol_dict.items(): sol.append((res, cond)) sol.append((S.Zero, True)) sol = Piecewise(*sol) if mp is -oo: s = S.Zero elif mp.is_integer is False: s = ceiling(mp) else: s = mp + 1 # save all the terms of # form 1/x**k in ind if s < 0: ind += sum(sequence(sol * x**k, (k, s, -1))) s = S.Zero return (sol, ind, s)
def _intersect(self, other): if other.is_Interval and other.measure < oo: s = Range(ceiling(other.left), floor(other.right) + 1) return s.intersect(other) # take out endpoints if open interval return None
def _intersect(self, other): from sympy.functions.elementary.integers import floor, ceiling if other.is_Interval and other.measure < S.Infinity: s = Range(ceiling(other.left), floor(other.right) + 1) return s.intersect(other) # take out endpoints if open interval return None
def test_sympy__functions__elementary__integers__floor(): from sympy.functions.elementary.integers import floor assert _test_args(floor(x))
def test_issue_13749(): assert integrate(1 / (2 + cos(x)), (x, 0, pi)) == pi/sqrt(3) assert integrate(1/(2 + cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)/3) + pi*floor((x/2 - pi/2)/pi))/3
def _intersect(self, other): from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.complexes import sign if other is S.Naturals: return self._intersect(Interval(1, S.Infinity)) if other is S.Integers: return self if other.is_Interval: if not all(i.is_number for i in other.args[:2]): return # In case of null Range, return an EmptySet. if self.size == 0: return S.EmptySet # trim down to self's size, and represent # as a Range with step 1. start = ceiling(max(other.inf, self.inf)) if start not in other: start += 1 end = floor(min(other.sup, self.sup)) if end not in other: end -= 1 return self.intersect(Range(start, end + 1)) if isinstance(other, Range): from sympy.solvers.diophantine import diop_linear from sympy.core.numbers import ilcm # non-overlap quick exits if not other: return S.EmptySet if not self: return S.EmptySet if other.sup < self.inf: return S.EmptySet if other.inf > self.sup: return S.EmptySet # work with finite end at the start r1 = self if r1.start.is_infinite: r1 = r1.reversed r2 = other if r2.start.is_infinite: r2 = r2.reversed # this equation represents the values of the Range; # it's a linear equation eq = lambda r, i: r.start + i*r.step # we want to know when the two equations might # have integer solutions so we use the diophantine # solver a, b = diop_linear(eq(r1, Dummy()) - eq(r2, Dummy())) # check for no solution no_solution = a is None and b is None if no_solution: return S.EmptySet # there is a solution # ------------------- # find the coincident point, c a0 = a.as_coeff_Add()[0] c = eq(r1, a0) # find the first point, if possible, in each range # since c may not be that point def _first_finite_point(r1, c): if c == r1.start: return c # st is the signed step we need to take to # get from c to r1.start st = sign(r1.start - c)*step # use Range to calculate the first point: # we want to get as close as possible to # r1.start; the Range will not be null since # it will at least contain c s1 = Range(c, r1.start + st, st)[-1] if s1 == r1.start: pass else: # if we didn't hit r1.start then, if the # sign of st didn't match the sign of r1.step # we are off by one and s1 is not in r1 if sign(r1.step) != sign(st): s1 -= st if s1 not in r1: return return s1 # calculate the step size of the new Range step = abs(ilcm(r1.step, r2.step)) s1 = _first_finite_point(r1, c) if s1 is None: return S.EmptySet s2 = _first_finite_point(r2, c) if s2 is None: return S.EmptySet # replace the corresponding start or stop in # the original Ranges with these points; the # result must have at least one point since # we know that s1 and s2 are in the Ranges def _updated_range(r, first): st = sign(r.step)*step if r.start.is_finite: rv = Range(first, r.stop, st) else: rv = Range(r.start, first + st, st) return rv r1 = _updated_range(self, s1) r2 = _updated_range(other, s2) # work with them both in the increasing direction if sign(r1.step) < 0: r1 = r1.reversed if sign(r2.step) < 0: r2 = r2.reversed # return clipped Range with positive step; it # can't be empty at this point start = max(r1.start, r2.start) stop = min(r1.stop, r2.stop) return Range(start, stop, step) else: return
def _eval_rewrite_as_polynomial(self, n, a, x): from sympy import Sum k = Dummy("k") kern = ((-1)**k * RisingFactorial(a, n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k))) return Sum(kern, (k, 0, floor(n/2)))