def _eval_rewrite_as_hyper(self, *args, **kwargs): if len(args) == 1: m = args[0] return (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), m)
def _sage_(self): #XXX: SAGE doesn't have Order yet. Let's return 0 instead. return Rational(0)._sage_()
def _print_Mul(self, expr): # print complex numbers nicely in Octave if (expr.is_number and expr.is_imaginary and expr.as_coeff_Mul()[0].is_integer): return "%si" % self._print(-S.ImaginaryUnit * expr) # cribbed from str.py prec = precedence(expr) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator for item in args: if (item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative): if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec) for x in a] b_str = [self.parenthesize(x, prec) for x in b] # from here it differs from str.py to deal with "*" and ".*" def multjoin(a, a_str): # here we probably are assuming the constants will come first r = a_str[0] for i in range(1, len(a)): mulsym = '*' if a[i - 1].is_number else '.*' r = r + mulsym + a_str[i] return r if len(b) == 0: return sign + multjoin(a, a_str) elif len(b) == 1: divsym = '/' if b[0].is_number else './' return sign + multjoin(a, a_str) + divsym + b_str[0] else: divsym = '/' if all([bi.is_number for bi in b]) else './' return (sign + multjoin(a, a_str) + divsym + "(%s)" % multjoin(b, b_str))
def test_issue_3449(): #test if powers are simplified correctly #see also issue 3995 x = Symbol('x') assert ((x**Rational(1, 3))**Rational(2)) == x**Rational(2, 3) assert ((x**Rational(3))**Rational(2, 5)) == (x**Rational(3))**Rational(2, 5) a = Symbol('a', real=True) b = Symbol('b', real=True) assert (a**2)**b == (abs(a)**b)**2 assert sqrt(1 / a) != 1 / sqrt(a) # e.g. for a = -1 assert (a**3)**Rational(1, 3) != a assert (x**a)**b != x**(a * b) # e.g. x = -1, a=2, b=1/2 assert (x**.5)**b == x**(.5 * b) assert (x**.5)**.5 == x**.25 assert (x**2.5)**.5 != x**1.25 # e.g. for x = 5*I k = Symbol('k', integer=True) m = Symbol('m', integer=True) assert (x**k)**m == x**(k * m) assert Number(5)**Rational(2, 3) == Number(25)**Rational(1, 3) assert (x**.5)**2 == x**1.0 assert (x**2)**k == (x**k)**2 == x**(2 * k) a = Symbol('a', positive=True) assert (a**3)**Rational(2, 5) == a**Rational(6, 5) assert (a**2)**b == (a**b)**2 assert (a**Rational( 2, 3))**x == a**(x * Rational(2, 3)) != (a**x)**Rational(2, 3)
def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3 * I, 'exp(x)': exp(x), 'x!': factorial(x), 'x!!': factorial2(x), '(x + 1)! - 1': factorial(x + 1) - 1, '3.[3]': Rational(10, 3), '.0[3]': Rational(1, 30), '3.2[3]': Rational(97, 30), '1.3[12]': Rational(433, 330), '1 + 3.[3]': Rational(13, 3), '1 + .0[3]': Rational(31, 30), '1 + 3.2[3]': Rational(127, 30), '.[0011]': Rational(1, 909), '0.1[00102] + 1': Rational(366697, 333330), '1.[0191]': Rational(10190, 9999), '10!': 3628800, '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], 'Symbol("x").free_symbols': x.free_symbols, "S('S(3).n(n=3)')": 3.00, 'factorint(12, visual=True)': Mul(Pow(2, 2, evaluate=False), Pow(3, 1, evaluate=False), evaluate=False), 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), 'Q.even(x)': Q.even(x), } for text, result in inputs.items(): assert parse_expr(text) == result raises(TypeError, lambda: parse_expr('x', standard_transformations)) raises(TypeError, lambda: parse_expr('x', transformations=lambda x, y: 1)) raises(TypeError, lambda: parse_expr('x', transformations=(lambda x, y: 1, ))) raises(TypeError, lambda: parse_expr('x', transformations=((), ))) raises(TypeError, lambda: parse_expr('x', {}, [], [])) raises(TypeError, lambda: parse_expr('x', [], [], {})) raises(TypeError, lambda: parse_expr('x', [], [], {}))
def test_large_rational(): e = (Rational(123712**12 - 1, 7) + Rational(1, 7))**Rational(1, 3) assert e == 234232585392159195136 * (Rational(1, 7)**Rational(1, 3))
def test_issue_6782(): x = Symbol('x') assert sqrt(sin(x**3)).series(x, 0, 7) == x**Rational(3, 2) + O(x**7) assert sqrt(sin(x**4)).series(x, 0, 3) == x**2 + O(x**3)
def _eval_at_order(cls, n, m): P = legendre_poly(n, _x, polys=True).diff((_x, m)) return (-1)**m * (1 - _x**2)**Rational(m, 2) * P.as_expr()
class bernoulli(Function): r""" Bernoulli numbers / Bernoulli polynomials The Bernoulli numbers are a sequence of rational numbers defined by B_0 = 1 and the recursive relation (n > 0):: n ___ \ / n + 1 \ 0 = ) | | * B . /___ \ k / k k = 0 They are also commonly defined by their exponential generating function, which is x/(exp(x) - 1). For odd indices > 1, the Bernoulli numbers are zero. The Bernoulli polynomials satisfy the analogous formula:: n ___ \ / n \ n-k B (x) = ) | | * B * x . n /___ \ k / k k = 0 Bernoulli numbers and Bernoulli polynomials are related as B_n(0) = B_n. We compute Bernoulli numbers using Ramanujan's formula:: / n + 3 \ B = (A(n) - S(n)) / | | n \ n / where A(n) = (n+3)/3 when n = 0 or 2 (mod 6), A(n) = -(n+3)/6 when n = 4 (mod 6), and:: [n/6] ___ \ / n + 3 \ S(n) = ) | | * B /___ \ n - 6*k / n-6*k k = 1 This formula is similar to the sum given in the definition, but cuts 2/3 of the terms. For Bernoulli polynomials, we use the formula in the definition. * bernoulli(n) gives the nth Bernoulli number, B_n * bernoulli(n, x) gives the nth Bernoulli polynomial in x, B_n(x) Examples ======== >>> from sympy import bernoulli >>> [bernoulli(n) for n in range(11)] [1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66] >>> bernoulli(1000001) 0 References ========== .. [1] http://en.wikipedia.org/wiki/Bernoulli_number .. [2] http://en.wikipedia.org/wiki/Bernoulli_polynomial .. [3] http://mathworld.wolfram.com/BernoulliNumber.html .. [4] http://mathworld.wolfram.com/BernoulliPolynomial.html See Also ======== bell, catalan, euler, fibonacci, harmonic, lucas """ # Calculates B_n for positive even n @staticmethod def _calc_bernoulli(n): s = 0 a = int(binomial(n + 3, n - 6)) for j in range(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 / binomial(n + 3, n) # We implement a specialized memoization scheme to handle each # case modulo 6 separately _cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)} _highest = {0: 0, 2: 2, 4: 4} @classmethod def eval(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), int(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 range(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 range(n + 1): result.append(binomial(n, k)*cls(k)*sym**(n - k)) return Add(*result) else: raise ValueError("Bernoulli numbers are defined only" " for nonnegative integer indices.") if sym is None: if n.is_odd and (n - 1).is_positive: return S.Zero
def matrix_form(self, weylelt): """ This method takes input from the user in the form of products of the generating reflections, and returns the matrix corresponding to the element of the Weyl group. Since each element of the Weyl group is a reflection of some type, there is a corresponding matrix representation. This method uses the standard representation for all the generating reflections. Example ======= >>> from sympy.liealgebras.weyl_group import WeylGroup >>> f = WeylGroup("F4") >>> f.matrix_form('r2*r3') Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, -1], [0, 0, 1, 0]]) """ elts = list(weylelt) reflections = elts[1::3] n = self.cartan_type.rank() if self.cartan_type.series == 'A': matrixform = eye(n + 1) for elt in reflections: a = int(elt) mat = eye(n + 1) mat[a - 1, a - 1] = 0 mat[a - 1, a] = 1 mat[a, a - 1] = 1 mat[a, a] = 0 matrixform *= mat return matrixform if self.cartan_type.series == 'D': matrixform = eye(n) for elt in reflections: a = int(elt) mat = eye(n) if a < n: mat[a - 1, a - 1] = 0 mat[a - 1, a] = 1 mat[a, a - 1] = 1 mat[a, a] = 0 matrixform *= mat else: mat[n - 2, n - 1] = -1 mat[n - 2, n - 2] = 0 mat[n - 1, n - 2] = -1 mat[n - 1, n - 1] = 0 matrixform *= mat return matrixform if self.cartan_type.series == 'G': matrixform = eye(3) for elt in reflections: a = int(elt) if a == 1: gen1 = Matrix([[1, 0, 0], [0, 0, 1], [0, 1, 0]]) matrixform *= gen1 else: gen2 = Matrix( [[Rational(2, 3), Rational(2, 3), -Rational(1, 3)], [Rational(2, 3), Rational(-1, 3), Rational(2, 3)], [Rational(-1, 3), Rational(2, 3), Rational(2, 3)]]) matrixform *= gen2 return matrixform if self.cartan_type.series == 'F': matrixform = eye(4) for elt in reflections: a = int(elt) if a == 1: mat = Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) matrixform *= mat elif a == 2: mat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) matrixform *= mat elif a == 3: mat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]) matrixform *= mat else: mat = Matrix([[ Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2) ], [ Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2) ], [ Rational(1, 2), Rational(-1, 2), Rational(1, 2), Rational(-1, 2) ], [ Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2) ]]) matrixform *= mat return matrixform if self.cartan_type.series == 'E': matrixform = eye(8) for elt in reflections: a = int(elt) if a == 1: mat = Matrix([[ Rational(3, 4), Rational(1, 4), Rational(1, 4), Rational(1, 4), Rational(1, 4), Rational(1, 4), Rational(1, 4), Rational(-1, 4) ], [ Rational(1, 4), Rational(3, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4), Rational(-1, 4) ], [ Rational(1, 4), Rational(-1, 4), Rational(3, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4) ], [ Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4) ], [ Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4) ], [ Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4), Rational(-1, 4), Rational(1, 4) ], [ Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-3, 4), Rational(1, 4) ], [ Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4) ]]) matrixform *= mat elif a == 2: mat = eye(8) mat[0, 0] = 0 mat[0, 1] = -1 mat[1, 0] = -1 mat[1, 1] = 0 matrixform *= mat else: mat = eye(8) mat[a - 3, a - 3] = 0 mat[a - 3, a - 2] = 1 mat[a - 2, a - 3] = 1 mat[a - 2, a - 2] = 0 matrixform *= mat return matrixform if self.cartan_type.series == 'B' or self.cartan_type.series == 'C': matrixform = eye(n) for elt in reflections: a = int(elt) mat = eye(n) if a == 1: mat[0, 0] = -1 matrixform *= mat else: mat[a - 2, a - 2] = 0 mat[a - 2, a - 1] = 1 mat[a - 1, a - 2] = 1 mat[a - 1, a - 1] = 0 matrixform *= mat return matrixform
def fdiff(self, argindex=1): n = self.args[0] return catalan(n) * (C.polygamma(0, n + Rational(1, 2)) - C.polygamma(0, n + 2) + C.log(4))
def test_glsl_code_Rational(): assert glsl_code(Rational(3, 7)) == "3.0/7.0" assert glsl_code(Rational(18, 9)) == "2" assert glsl_code(Rational(3, -7)) == "-3.0/7.0" assert glsl_code(Rational(-3, -7)) == "3.0/7.0"
def eval(cls, arg): 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.Infinity elif arg.is_zero: return S.Pi * S.ImaginaryUnit / 2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi * S.ImaginaryUnit if arg.is_number: cst_table = { S.ImaginaryUnit: log(S.ImaginaryUnit * (1 + sqrt(2))), -S.ImaginaryUnit: log(-S.ImaginaryUnit * (1 + sqrt(2))), S.Half: S.Pi / 3, Rational(-1, 2): S.Pi * Rational(2, 3), sqrt(2) / 2: S.Pi / 4, -sqrt(2) / 2: S.Pi * Rational(3, 4), 1 / sqrt(2): S.Pi / 4, -1 / sqrt(2): S.Pi * Rational(3, 4), sqrt(3) / 2: S.Pi / 6, -sqrt(3) / 2: S.Pi * Rational(5, 6), (sqrt(3) - 1) / sqrt(2**3): S.Pi * Rational(5, 12), -(sqrt(3) - 1) / sqrt(2**3): S.Pi * Rational(7, 12), sqrt(2 + sqrt(2)) / 2: S.Pi / 8, -sqrt(2 + sqrt(2)) / 2: S.Pi * Rational(7, 8), sqrt(2 - sqrt(2)) / 2: S.Pi * Rational(3, 8), -sqrt(2 - sqrt(2)) / 2: S.Pi * Rational(5, 8), (1 + sqrt(3)) / (2 * sqrt(2)): S.Pi / 12, -(1 + sqrt(3)) / (2 * sqrt(2)): S.Pi * Rational(11, 12), (sqrt(5) + 1) / 4: S.Pi / 5, -(sqrt(5) + 1) / 4: S.Pi * Rational(4, 5) } if arg in cst_table: if arg.is_extended_real: return cst_table[arg] * S.ImaginaryUnit return cst_table[arg] if arg is S.ComplexInfinity: return S.ComplexInfinity if arg == S.ImaginaryUnit * S.Infinity: return S.Infinity + S.ImaginaryUnit * S.Pi / 2 if arg == -S.ImaginaryUnit * S.Infinity: return S.Infinity - S.ImaginaryUnit * S.Pi / 2 if arg.is_zero: return S.Pi * S.ImaginaryUnit * S.Half if isinstance(arg, cosh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: from sympy.functions.elementary.complexes import Abs return Abs(z) r, i = match_real_imag(z) if r is not None and i is not None: f = floor(i / pi) m = z - I * pi * f even = f.is_even if even is True: if r.is_nonnegative: return m elif r.is_negative: return -m elif even is False: m -= I * pi if r.is_nonpositive: return -m elif r.is_positive: return m
def _eval_rewrite_as_meijerg(self, *args, **kwargs): if len(args) == 1: m = args[0] return -meijerg(((S.Half, Rational(3, 2)), []), \ ((S.Zero,), (S.Zero,)), -m)/4
"ceil", # "": "round", # "": "trunc", # "": "fract", "Abs": "abs", "sign": "signum", # "": "is_sign_positive", # "": "is_sign_negative", # "": "mul_add", "Pow": [ (lambda base, exp: exp == -S.One, "recip", 2), # 1.0/x (lambda base, exp: exp == S.Half, "sqrt", 2), # x ** 0.5 (lambda base, exp: exp == -S.Half, "sqrt().recip", 2), # 1/(x ** 0.5) (lambda base, exp: exp == Rational(1, 3), "cbrt", 2), # x ** (1/3) (lambda base, exp: base == S.One * 2, "exp2", 3), # 2 ** x (lambda base, exp: exp.is_integer, "powi", 1), # x ** y, for i32 (lambda base, exp: not exp.is_integer, "powf", 1) ], # x ** y, for f64 "exp": [(lambda exp: True, "exp", 2)], # e ** x "log": "ln", # "": "log", # number.log(base) # "": "log2", # "": "log10", # "": "to_degrees", # "": "to_radians", "Max": "max", "Min":
def fdiff(self, argindex=1): from sympy import polygamma, log n = self.args[0] return catalan(n)*(polygamma(0, n + Rational(1, 2)) - polygamma(0, n + 2) + log(4))
def test_expand(): x = Symbol('x') assert (2**(-1 - x)).expand() == Rational(1, 2)*2**(-x)
def test_rational_powers_larger_than_one(): assert Rational(2, 3)**Rational(3, 2) == 2 * sqrt(6) / 9 assert Rational(1, 6)**Rational(9, 4) == 6**Rational(3, 4) / 216 assert Rational(3, 7)**Rational( 7, 3) == 9 * 3**Rational(1, 3) * 7**Rational(2, 3) / 343
def test_issue_6068(): x = Symbol('x') assert sqrt(sin(x)).series(x, 0, 7) == \ sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ x**Rational(13, 2)/24192 + O(x**7) assert sqrt(sin(x)).series(x, 0, 9) == \ sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ x**Rational(13, 2)/24192 - 67*x**Rational(17, 2)/29030400 + O(x**9) assert sqrt(sin(x**3)).series(x, 0, 19) == \ x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 + O(x**19) assert sqrt(sin(x**3)).series(x, 0, 20) == \ x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 - \ x**Rational(39, 2)/24192 + O(x**20)
def test_issue_3109_fail(): from sympy import root, Rational I = S.ImaginaryUnit assert sqrt(exp(5 * I)) == -exp(5 * I / 2) assert root(exp(5 * I), 3).exp == Rational(1, 3)
def test_issue_7638(): f = pi / log(sqrt(2)) assert ((1 + I)**(I * f / 2))**0.3 == (1 + I)**(0.15 * I * f) # if 1/3 -> 1.0/3 this should fail since it cannot be shown that the # sign will be +/-1; for the previous "small arg" case, it didn't matter # that this could not be proved assert (1 + I)**(4 * I * f) == ((1 + I)**(12 * I * f))**Rational(1, 3) assert (((1 + I)**(I * (1 + 7 * f)))**Rational(1, 3)).exp == Rational(1, 3) r = symbols('r', real=True) assert sqrt(r**2) == abs(r) assert cbrt(r**3) != r assert sqrt(Pow(2 * I, 5 * S.Half)) != (2 * I)**Rational(5, 4) p = symbols('p', positive=True) assert cbrt(p**2) == p**Rational(2, 3) assert NS(((0.2 + 0.7 * I)**(0.7 + 1.0 * I))**(0.5 - 0.1 * I), 1) == '0.4 + 0.2*I' assert sqrt(1 / (1 + I)) == sqrt(1 - I) / sqrt(2) # or 1/sqrt(1 + I) e = 1 / (1 - sqrt(2)) assert sqrt(e) == I / sqrt(-1 + sqrt(2)) assert e**Rational(-1, 2) == -I * sqrt(-1 + sqrt(2)) assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp in [S.Half, Rational(3, 2) + I / 2] assert sqrt(r**Rational(4, 3)) != r**Rational(2, 3) assert sqrt((p + I)**Rational(4, 3)) == (p + I)**Rational(2, 3) assert sqrt((p - p**2 * I)**2) == p - p**2 * I assert sqrt((p + r * I)**2) != p + r * I e = (1 + I / 5) assert sqrt(e**5) == e**(5 * S.Half) assert sqrt(e**6) == e**3 assert sqrt((1 + I * r)**6) != (1 + I * r)**3
def test_ccode_Rational(): assert ccode(Rational(3, 7)) == "3.0/7.0" assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(Rational(18, 9)) == "2" assert ccode(Rational(3, -7)) == "-3.0/7.0" assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L" assert ccode(Rational(-3, -7)) == "3.0/7.0" assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0" assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L" assert ccode(Rational(3, 7) * x) == "(3.0/7.0)*x" assert ccode(Rational(3, 7) * x, type_aliases={real: float80}) == "(3.0L/7.0L)*x"
def test_repeated_dot_only(): assert parse_expr('.[1]') == Rational(1, 9) assert parse_expr('1 + .[1]') == Rational(10, 9)
def _print_Mul(self, expr): prec = precedence(expr) # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = expr.args if args[0] is S.One or any( isinstance(a, Number) or a.is_Pow and all(ai.is_Integer for ai in a.args) for a in args[1:]): d, n = sift(args, lambda x: isinstance(x, Pow) and bool( x.exp.as_coeff_Mul()[0] < 0), binary=True) for i, di in enumerate(d): if di.exp.is_Number: e = -di.exp else: dargs = list(di.exp.args) dargs[0] = -dargs[0] e = Mul._from_args(dargs) d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base # don't parenthesize first factor if negative if _coeff_isneg(n[0]): pre = [str(n.pop(0))] else: pre = [] nfactors = pre + [ self.parenthesize(a, prec, strict=False) for a in n ] # don't parenthesize first of denominator unless singleton if len(d) > 1 and _coeff_isneg(d[0]): pre = [str(d.pop(0))] else: pre = [] dfactors = pre + [ self.parenthesize(a, prec, strict=False) for a in d ] n = '*'.join(nfactors) d = '*'.join(dfactors) if len(dfactors) > 1: return '%s/(%s)' % (n, d) elif dfactors: return '%s/%s' % (n, d) return n c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [ ] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator def apow(i): b, e = i.as_base_exp() eargs = list(Mul.make_args(e)) if eargs[0] is S.NegativeOne: eargs = eargs[1:] else: eargs[0] = -eargs[0] e = Mul._from_args(eargs) if isinstance(i, Pow): return i.func(b, e, evaluate=False) return i.func(e, evaluate=False) for item in args: if (item.is_commutative and isinstance(item, Pow) and bool(item.exp.as_coeff_Mul()[0] < 0)): if item.exp is not S.NegativeOne: b.append(apow(item)) else: if (len(item.args[0].args) != 1 and isinstance(item.base, Mul)): # To avoid situations like #14160 pow_paren.append(item) b.append(item.base) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec, strict=False) for x in a] b_str = [self.parenthesize(x, prec, strict=False) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] if not b: return sign + '*'.join(a_str) elif len(b) == 1: return sign + '*'.join(a_str) + "/" + b_str[0] else: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
def test_rationalize(): inputs = {'0.123': Rational(123, 1000)} transformations = standard_transformations + (rationalize, ) for text, result in inputs.items(): assert parse_expr(text, transformations=transformations) == result
def trigintegrate(f, x, conds='piecewise'): """Integrate f = Mul(trig) over x >>> from sympy import Symbol, sin, cos, tan, sec, csc, cot >>> from sympy.integrals.trigonometry import trigintegrate >>> from sympy.abc import x >>> trigintegrate(sin(x)*cos(x), x) sin(x)**2/2 >>> trigintegrate(sin(x)**2, x) x/2 - sin(x)*cos(x)/2 >>> trigintegrate(tan(x)*sec(x), x) 1/cos(x) >>> trigintegrate(sin(x)*tan(x), x) -log(sin(x) - 1)/2 + log(sin(x) + 1)/2 - sin(x) http://en.wikibooks.org/wiki/Calculus/Integration_techniques See Also ======== sympy.integrals.integrals.Integral.doit sympy.integrals.integrals.Integral """ from sympy.integrals.integrals import integrate pat, a, n, m = _pat_sincos(x) f = f.rewrite('sincos') M = f.match(pat) if M is None: return n, m = M[n], M[m] if n is S.Zero and m is S.Zero: return x zz = x if n is S.Zero else S.Zero a = M[a] if n.is_odd or m.is_odd: u = _u n_, m_ = n.is_odd, m.is_odd # take smallest n or m -- to choose simplest substitution if n_ and m_: # Make sure to choose the positive one # otherwise an incorrect integral can occur. if n < 0 and m > 0: m_ = True n_ = False elif m < 0 and n > 0: n_ = True m_ = False # Both are negative so choose the smallest n or m # in absolute value for simplest substitution. elif (n < 0 and m < 0): n_ = n > m m_ = not (n > m) # Both n and m are odd and positive else: n_ = (n < m) # NB: careful here, one of the m_ = not (n < m) # conditions *must* be true # n m u=C (n-1)/2 m # S(x) * C(x) dx --> -(1-u^2) * u du if n_: ff = -(1 - u**2)**((n - 1) / 2) * u**m uu = cos(a * x) # n m u=S n (m-1)/2 # S(x) * C(x) dx --> u * (1-u^2) du elif m_: ff = u**n * (1 - u**2)**((m - 1) / 2) uu = sin(a * x) fi = integrate(ff, u) # XXX cyclic deps fx = fi.subs(u, uu) if conds == 'piecewise': return Piecewise((fx / a, Ne(a, 0)), (zz, True)) return fx / a # n & m are both even # # 2k 2m 2l 2l # we transform S (x) * C (x) into terms with only S (x) or C (x) # # example: # 100 4 100 2 2 100 4 2 # S (x) * C (x) = S (x) * (1-S (x)) = S (x) * (1 + S (x) - 2*S (x)) # # 104 102 100 # = S (x) - 2*S (x) + S (x) # 2k # then S is integrated with recursive formula # take largest n or m -- to choose simplest substitution n_ = (abs(n) > abs(m)) m_ = (abs(m) > abs(n)) res = S.Zero if n_: # 2k 2 k i 2i # C = (1 - S ) = sum(i, (-) * B(k, i) * S ) if m > 0: for i in range(0, m // 2 + 1): res += ((-1)**i * binomial(m // 2, i) * _sin_pow_integrate(n + 2 * i, x)) elif m == 0: res = _sin_pow_integrate(n, x) else: # m < 0 , |n| > |m| # / # | # | m n # | cos (x) sin (x) dx = # | # | #/ # / # | # -1 m+1 n-1 n - 1 | m+2 n-2 # ________ cos (x) sin (x) + _______ | cos (x) sin (x) dx # | # m + 1 m + 1 | # / res = (Rational(-1, m + 1) * cos(x)**(m + 1) * sin(x)**(n - 1) + Rational(n - 1, m + 1) * trigintegrate(cos(x)**(m + 2) * sin(x)**(n - 2), x)) elif m_: # 2k 2 k i 2i # S = (1 - C ) = sum(i, (-) * B(k, i) * C ) if n > 0: # / / # | | # | m n | -m n # | cos (x)*sin (x) dx or | cos (x) * sin (x) dx # | | # / / # # |m| > |n| ; m, n >0 ; m, n belong to Z - {0} # n 2 # sin (x) term is expanded here in terms of cos (x), # and then integrated. # for i in range(0, n // 2 + 1): res += ((-1)**i * binomial(n // 2, i) * _cos_pow_integrate(m + 2 * i, x)) elif n == 0: # / # | # | 1 # | _ _ _ # | m # | cos (x) # / # res = _cos_pow_integrate(m, x) else: # n < 0 , |m| > |n| # / # | # | m n # | cos (x) sin (x) dx = # | # | #/ # / # | # 1 m-1 n+1 m - 1 | m-2 n+2 # _______ cos (x) sin (x) + _______ | cos (x) sin (x) dx # | # n + 1 n + 1 | # / res = (Rational(1, n + 1) * cos(x)**(m - 1) * sin(x)**(n + 1) + Rational(m - 1, n + 1) * trigintegrate(cos(x)**(m - 2) * sin(x)**(n + 2), x)) else: if m == n: ##Substitute sin(2x)/2 for sin(x)cos(x) and then Integrate. res = integrate((Rational(1, 2) * sin(2 * x))**m, x) elif (m == -n): if n < 0: # Same as the scheme described above. # the function argument to integrate in the end will # be 1 , this cannot be integrated by trigintegrate. # Hence use sympy.integrals.integrate. res = (Rational(1, n + 1) * cos(x)**(m - 1) * sin(x)**(n + 1) + Rational(m - 1, n + 1) * integrate(cos(x)**(m - 2) * sin(x)**(n + 2), x)) else: res = ( Rational(-1, m + 1) * cos(x)**(m + 1) * sin(x)**(n - 1) + Rational(n - 1, m + 1) * integrate(cos(x)**(m + 2) * sin(x)**(n - 2), x)) if conds == 'piecewise': return Piecewise((res.subs(x, a * x) / a, Ne(a, 0)), (zz, True)) return res.subs(x, a * x) / a
def test_jscode_Rational(): assert jscode(Rational(3, 7)) == "3/7" assert jscode(Rational(18, 9)) == "2" assert jscode(Rational(3, -7)) == "-3/7" assert jscode(Rational(-3, -7)) == "3/7"
def eval_rational(self, dx=None, dy=None, n=15): """ Return a Rational approximation of ``self`` that has real and imaginary component approximations that are within ``dx`` and ``dy`` of the true values, respectively. Alternatively, ``n`` digits of precision can be specified. The interval is refined with bisection and is sure to converge. The root bounds are updated when the refinement is complete so recalculation at the same or lesser precision will not have to repeat the refinement and should be much faster. The following example first obtains Rational approximation to 1e-8 accuracy for all roots of the 4-th order Legendre polynomial. Since the roots are all less than 1, this will ensure the decimal representation of the approximation will be correct (including rounding) to 6 digits: >>> from sympy import S, legendre_poly, Symbol >>> x = Symbol("x") >>> p = legendre_poly(4, x, polys=True) >>> r = p.real_roots()[-1] >>> r.eval_rational(10**-8).n(6) 0.861136 It is not necessary to a two-step calculation, however: the decimal representation can be computed directly: >>> r.evalf(17) 0.86113631159405258 """ dy = dy or dx if dx: rtol = None dx = dx if isinstance(dx, Rational) else Rational(str(dx)) dy = dy if isinstance(dy, Rational) else Rational(str(dy)) else: # 5 binary (or 2 decimal) digits are needed to ensure that # a given digit is correctly rounded # prec_to_dps(dps_to_prec(n) + 5) - n <= 2 (tested for # n in range(1000000) rtol = S(10)**-(n + 2) # +2 for guard digits interval = self._get_interval() while True: if self.is_real: if rtol: dx = abs(interval.center * rtol) interval = interval.refine_size(dx=dx) c = interval.center real = Rational(c) imag = S.Zero if not rtol or interval.dx < abs(c * rtol): break elif self.is_imaginary: if rtol: dy = abs(interval.center[1] * rtol) dx = 1 interval = interval.refine_size(dx=dx, dy=dy) c = interval.center[1] imag = Rational(c) real = S.Zero if not rtol or interval.dy < abs(c * rtol): break else: if rtol: dx = abs(interval.center[0] * rtol) dy = abs(interval.center[1] * rtol) interval = interval.refine_size(dx, dy) c = interval.center real, imag = map(Rational, c) if not rtol or (interval.dx < abs(c[0] * rtol) and interval.dy < abs(c[1] * rtol)): break # update the interval so we at least (for this precision or # less) don't have much work to do to recompute the root self._set_interval(interval) return real + I * imag
def test_issue_4822(): z = (-1)**Rational(1, 3) * (1 - I * sqrt(3)) assert z.is_real in [True, None]
def positive_roots(self): """ This method generates all the positive roots of A_n. This is half of all of the roots of E_n; by multiplying all the positive roots by -1 we get the negative roots. Example ====== >>> from sympy.liealgebras.cartan_type import CartanType >>> c = CartanType("A3") >>> c.positive_roots() {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0], 5: [0, 1, 0, -1], 6: [0, 0, 1, -1]} """ n = self.n if n == 6: posroots = {} k = 0 for i in range(n - 1): for j in range(i + 1, n - 1): k += 1 root = self.basic_root(i, j) posroots[k] = root k += 1 root = self.basic_root(i, j) root[i] = 1 posroots[k] = root root = [ Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2) ] for a in range(0, 2): for b in range(0, 2): for c in range(0, 2): for d in range(0, 2): for e in range(0, 2): if (a + b + c + d + e) % 2 == 0: k += 1 if a == 1: root[0] = Rational(-1, 2) if b == 1: root[1] = Rational(-1, 2) if c == 1: root[2] = Rational(-1, 2) if d == 1: root[3] = Rational(-1, 2) if e == 1: root[4] = Rational(-1, 2) posroots[k] = root return posroots if n == 7: posroots = {} k = 0 for i in range(n - 1): for j in range(i + 1, n - 1): k += 1 root = self.basic_root(i, j) posroots[k] = root k += 1 root = self.basic_root(i, j) root[i] = 1 posroots[k] = root k += 1 posroots[k] = [0, 0, 0, 0, 0, 1, 1, 0] root = [ Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2) ] for a in range(0, 2): for b in range(0, 2): for c in range(0, 2): for d in range(0, 2): for e in range(0, 2): for f in range(0, 2): if (a + b + c + d + e + f) % 2 == 0: k += 1 if a == 1: root[0] = Rational(-1, 2) if b == 1: root[1] = Rational(-1, 2) if c == 1: root[2] = Rational(-1, 2) if d == 1: root[3] = Rational(-1, 2) if e == 1: root[4] = Rational(-1, 2) if f == 1: root[5] = Rational(1, 2) posroots[k] = root return posroots if n == 8: posroots = {} k = 0 for i in range(n): for j in range(i + 1, n): k += 1 root = self.basic_root(i, j) posroots[k] = root k += 1 root = self.basic_root(i, j) root[i] = 1 posroots[k] = root root = [ Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2) ] for a in range(0, 2): for b in range(0, 2): for c in range(0, 2): for d in range(0, 2): for e in range(0, 2): for f in range(0, 2): for g in range(0, 2): if (a + b + c + d + e + f + g) % 2 == 0: k += 1 if a == 1: root[0] = Rational(-1, 2) if b == 1: root[1] = Rational(-1, 2) if c == 1: root[2] = Rational(-1, 2) if d == 1: root[3] = Rational(-1, 2) if e == 1: root[4] = Rational(-1, 2) if f == 1: root[5] = Rational(1, 2) if g == 1: root[6] = Rational(1, 2) posroots[k] = root return posroots