def test_inconsistent(): # cf. issues 5795 and 5545 raises(InconsistentAssumptions, lambda: Symbol('x', real=True, commutative=False))
def test_issue1263(): neg = Symbol('neg', negative=True) nonneg = Symbol('nonneg', nonnegative=True) any = Symbol('any') num, den = sqrt(1 / neg).as_numer_denom() assert num == sqrt(-1) assert den == sqrt(-neg) num, den = sqrt(1 / nonneg).as_numer_denom() assert num == 1 assert den == sqrt(nonneg) num, den = sqrt(1 / any).as_numer_denom() assert num == sqrt(1 / any) assert den == 1 def eqn(num, den, pow): return (num / den)**pow npos = 1 nneg = -1 dpos = 2 - sqrt(3) dneg = 1 - sqrt(3) assert dpos > 0 and dneg < 0 and npos > 0 and nneg < 0 # pos or neg integer eq = eqn(npos, dpos, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq = eqn(npos, dneg, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq = eqn(nneg, dpos, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq = eqn(nneg, dneg, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq = eqn(npos, dpos, -2) assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq = eqn(npos, dneg, -2) assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) eq = eqn(nneg, dpos, -2) assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq = eqn(nneg, dneg, -2) assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) # pos or neg rational pow = S.Half eq = eqn(npos, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq = eqn(npos, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) eq = eqn(nneg, dpos, pow) assert not eq.is_Pow or eq.as_numer_denom() == (nneg**pow, dpos**pow) eq = eqn(nneg, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq = eqn(npos, dpos, -pow) assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, npos**pow) eq = eqn(npos, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow) eq = eqn(nneg, dpos, -pow) assert not eq.is_Pow or eq.as_numer_denom() == (dpos**pow, nneg**pow) eq = eqn(nneg, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) # unknown exponent pow = 2 * any eq = eqn(npos, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq = eqn(npos, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) eq = eqn(nneg, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (nneg**pow, dpos**pow) eq = eqn(nneg, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq = eqn(npos, dpos, -pow) assert eq.as_numer_denom() == (dpos**pow, npos**pow) eq = eqn(npos, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow) eq = eqn(nneg, dpos, -pow) assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, nneg**pow) eq = eqn(nneg, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) x = Symbol('x') y = Symbol('y') assert ((1 / (1 + x / 3))**(-S.One)).as_numer_denom() == (3 + x, 3) notp = Symbol('notp', positive=False) # not positive does not imply real b = ((1 + x / notp)**-2) assert (b**(-y)).as_numer_denom() == (1, b**y) assert (b**(-S.One)).as_numer_denom() == ((notp + x)**2, notp**2) nonp = Symbol('nonp', nonpositive=True) assert (((1 + x / nonp)**-2)**(-S.One)).as_numer_denom() == ((-nonp - x)**2, nonp**2) n = Symbol('n', negative=True) assert (x**n).as_numer_denom() == (1, x**-n) assert sqrt(1 / n).as_numer_denom() == (S.ImaginaryUnit, sqrt(-n)) n = Symbol('0 or neg', nonpositive=True) # if x and n are split up without negating each term and n is negative # then the answer might be wrong; if n is 0 it won't matter since # 1/oo and 1/zoo are both zero as is sqrt(0)/sqrt(-x) unless x is also # zero (in which case the negative sign doesn't matter): # 1/sqrt(1/-1) = -I but sqrt(-1)/sqrt(1) = I assert (1 / sqrt(x / n)).as_numer_denom() == (sqrt(-n), sqrt(-x)) c = Symbol('c', complex=True) e = sqrt(1 / c) assert e.as_numer_denom() == (e, 1) i = Symbol('i', integer=True) assert (((1 + x / y)**i)).as_numer_denom() == ((x + y)**i, y**i)
def test_issue_7663(): x = Symbol('x') e = '2*(x+1)' assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False) assert parse_expr(e, evaluate=0).equals(2 * (x + 1))
def test_issue_3554(): x = Symbol('x') assert (1 / sqrt(1 + cos(x) * sin(x**2))).series(x, 0, 7) == \ 1 - x**2/2 + 5*x**4/8 - 5*x**6/8 + O(x**7) assert (1 / sqrt(1 + cos(x) * sin(x**2))).series(x, 0, 8) == \ 1 - x**2/2 + 5*x**4/8 - 5*x**6/8 + O(x**8)
def test_expand(): x = Symbol('x') assert (2**(-1 - x)).expand() == Rational(1, 2) * 2**(-x)
def test_expand(): x = Symbol('x') assert (2**(-1 - x)).expand() == S.Half * 2**(-x)
def test_pow_as_base_exp(): x = Symbol('x') assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x) assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2) p = S.Half**x assert p.base, p.exp == p.as_base_exp() == (S(2), -x)
def test_pow_as_base_exp(): x = Symbol('x') assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x) assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2)
def test_issue1263(): neg = Symbol('neg', negative=True) nonneg = Symbol('nonneg', negative=False) any = Symbol('any') num, den = sqrt(1/neg).as_numer_denom() assert num == sqrt(-1) assert den == sqrt(-neg) num, den = sqrt(1/nonneg).as_numer_denom() assert num == 1 assert den == sqrt(nonneg) num, den = sqrt(1/any).as_numer_denom() assert num == sqrt(1/any) assert den == 1 def eqn(num, den, pow): return (num/den)**pow npos=1 nneg=-1 dpos=2-sqrt(3) dneg=1-sqrt(3) I = S.ImaginaryUnit assert dpos > 0 and dneg < 0 and npos > 0 and nneg < 0 # pos or neg integer eq=eqn(npos, dpos, 2);assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq=eqn(npos, dneg, 2);assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq=eqn(nneg, dpos, 2);assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq=eqn(nneg, dneg, 2);assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq=eqn(npos, dpos, -2);assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq=eqn(npos, dneg, -2);assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) eq=eqn(nneg, dpos, -2);assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq=eqn(nneg, dneg, -2);assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) # pos or neg rational pow = S.Half eq=eqn(npos, dpos, pow);assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq=eqn(npos, dneg, pow);assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) eq=eqn(nneg, dpos, pow);assert not eq.is_Pow or eq.as_numer_denom() == (nneg**pow, dpos**pow) eq=eqn(nneg, dneg, pow);assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq=eqn(npos, dpos, -pow);assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, npos**pow) eq=eqn(npos, dneg, -pow);assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow) eq=eqn(nneg, dpos, -pow);assert not eq.is_Pow or eq.as_numer_denom() == (dpos**pow, nneg**pow) eq=eqn(nneg, dneg, -pow);assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) # unknown exponent pow = 2*any eq=eqn(npos, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq=eqn(npos, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == (eq, 1) eq=eqn(nneg, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (nneg**pow, dpos**pow) eq=eqn(nneg, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq=eqn(npos, dpos, -pow) assert eq.as_numer_denom() == (dpos**pow, npos**pow) eq=eqn(npos, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == (1, eq.base**pow) eq=eqn(nneg, dpos, -pow) assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, nneg**pow) eq=eqn(nneg, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) x = Symbol('x') assert ((1/(1 + x/3))**(-S.One)).as_numer_denom() == (3 + x, 3) np = Symbol('np',positive=False) assert (((1 + x/np)**-2)**(-S.One)).as_numer_denom() == ((np + x)**2, np**2)
def test_FreeGroupElm_letter_form(): assert (x**3).letter_form == (Symbol('x'), Symbol('x'), Symbol('x')) assert (x**2*z**-2*x).letter_form == \ (Symbol('x'), Symbol('x'), -Symbol('z'), -Symbol('z'), Symbol('x'))
def test_FreeGroupElm_ext_rep(): assert (x**2*z**-2*x).ext_rep == \ (Symbol('x'), 2, Symbol('z'), -2, Symbol('x'), 1) assert (x**-2 * y**-1).ext_rep == (Symbol('x'), -2, Symbol('y'), -1) assert (x * z).ext_rep == (Symbol('x'), 1, Symbol('z'), 1)
def test_FreeGroupElm_array_form(): assert (x * z).array_form == ((Symbol('x'), 1), (Symbol('z'), 1)) assert (x**2*z*y*x**-2).array_form == \ ((Symbol('x'), 2), (Symbol('z'), 1), (Symbol('y'), 1), (Symbol('x'), -2)) assert (x**-2 * y**-1).array_form == ((Symbol('x'), -2), (Symbol('y'), -1))
def test_issue_7899(): x = Symbol('x', real=True) assert (I * x).is_real is None assert ((x - I) * (x - 1)).is_zero is None assert ((x - I) * (x - 1)).is_real is None
def test_issue_2920(): n = Symbol('n', negative=True) assert sqrt(n).is_imaginary
def test_issue_6653(): x = Symbol('x') assert (1 / sqrt(1 + sin(x**2))).series(x, 0, 3) == 1 - x**2 / 2 + O(x**3)
def test_Pow_Expr_args(): x = Symbol('x') bases = [Basic(), Poly(x, x), FiniteSet(x)] for base in bases: with warns_deprecated_sympy(): Pow(base, S.One)
def test_issue_8650(): n = Symbol('n', integer=True, nonnegative=True) assert (n**n).is_positive is True x = 5 * n + 5 assert (x**(5 * (n + 1))).is_positive is True
def test_issue_6990(): x = Symbol('x') a = Symbol('a') b = Symbol('b') assert (sqrt(a + b*x + x**2)).series(x, 0, 3).removeO() == \ sqrt(a)*x**2*(1/(2*a) - b**2/(8*a**2)) + sqrt(a) + b*x/(2*sqrt(a))
def test_power_with_noncommutative_mul_as_base(): x = Symbol('x', commutative=False) y = Symbol('y', commutative=False) assert not (x * y)**3 == x**3 * y**3 assert (2 * x * y)**3 == 8 * (x * y)**3
def eval(cls, *_args, **kwargs): """.""" if not _args: return if not len(_args) == 1: raise ValueError('Expecting one argument') expr = _args[0] code = kwargs.pop('code', None) if isinstance(expr, Add): args = [cls.eval(a, code=code) for a in expr.args] v = Add(*args) return v elif isinstance(expr, Mul): args = [cls.eval(a, code=code) for a in expr.args] v = Mul(*args) return v elif isinstance(expr, Pow): b = expr.base e = expr.exp v = Pow(cls.eval(b, code=code), e) return v elif isinstance(expr, _coeffs_registery): return expr elif isinstance(expr, (list, tuple, Tuple)): expr = [cls.eval(a, code=code) for a in expr] return Tuple(*expr) elif isinstance(expr, (Matrix, ImmutableDenseMatrix)): lines = [] n_row, n_col = expr.shape for i_row in range(0, n_row): line = [] for i_col in range(0, n_col): line.append(cls.eval(expr[i_row, i_col], code=code)) lines.append(line) return type(expr)(lines) elif isinstance(expr, (ScalarField, ScalarTestFunction, VectorField, VectorTestFunction)): if code: name = '{name}_{code}'.format(name=expr.name, code=code) else: name = str(expr.name) return Symbol(name) elif isinstance(expr, (PlusInterfaceOperator, MinusInterfaceOperator)): return cls.eval(expr.args[0], code=code) elif isinstance(expr, Indexed): base = expr.base if isinstance(base, Mapping): if expr.indices[0] == 0: name = 'x' elif expr.indices[0] == 1: name = 'y' elif expr.indices[0] == 2: name = 'z' else: raise ValueError('Wrong index') else: name = '{base}_{i}'.format(base=base.name, i=expr.indices[0]) if code: name = '{name}_{code}'.format(name=name, code=code) return Symbol(name) elif isinstance(expr, _partial_derivatives): atom = get_atom_derivatives(expr) indices = get_index_derivatives_atom(expr, atom) code = None if indices: index = indices[0] code = '' index = OrderedDict(sorted(index.items())) for k, n in list(index.items()): code += k * n return cls.eval(atom, code=code) elif isinstance(expr, _logical_partial_derivatives): atom = get_atom_logical_derivatives(expr) indices = get_index_logical_derivatives_atom(expr, atom) code = None if indices: index = indices[0] code = '' index = OrderedDict(sorted(index.items())) for k, n in list(index.items()): code += k * n return cls.eval(atom, code=code) elif isinstance(expr, Mapping): return Symbol(expr.name) # ... this must be done here, otherwise codegen for FEM will not work elif isinstance(expr, Symbol): return expr elif isinstance(expr, IndexedBase): return expr elif isinstance(expr, Indexed): return expr elif isinstance(expr, Idx): return expr elif isinstance(expr, Function): args = [cls.eval(a, code=code) for a in expr.args] return type(expr)(*args) elif isinstance(expr, ImaginaryUnit): return expr elif isinstance(expr, SymbolicWeightedVolume): mapping = expr.args[0] if isinstance(mapping, InterfaceMapping): mapping = mapping.minus name = 'wvol_{mapping}'.format(mapping=mapping) return Symbol(name) elif isinstance(expr, SymbolicDeterminant): name = 'det_{}'.format(str(expr.args[0])) return Symbol(name) elif isinstance(expr, PullBack): return cls.eval(expr.expr, code=code) # Expression must always be translated to Sympy! # TODO: check if we should use 'sympy.sympify(expr)' instead else: raise NotImplementedError( 'Cannot translate to Sympy: {}'.format(expr))
def test_issue_3683(): x = Symbol('x') assert sqrt(sin(x**3)).series(x, 0, 7) == x**(S(3) / 2) + O(x**7) assert sqrt(sin(x**4)).series(x, 0, 3) == x**2 + O(x**3)
def __new__(cls, name, rdim=None, coordinates=None, **kwargs): if isinstance(rdim, (tuple, list, Tuple)): if not len(rdim) == 1: raise ValueError( '> Expecting a tuple, list, Tuple of length 1') rdim = rdim[0] elif rdim is None: rdim = cls._rdim obj = IndexedBase.__new__(cls, name, shape=(rdim)) if coordinates is None: _coordinates = [Symbol(name) for name in ['x', 'y', 'z'][:rdim]] else: if not isinstance(coordinates, (list, tuple, Tuple)): raise TypeError('> Expecting list, tuple, Tuple') for a in coordinates: if not isinstance(a, (str, Symbol)): raise TypeError('> Expecting str or Symbol') _coordinates = [Symbol(name) for name in coordinates] obj._name = name obj._rdim = rdim obj._coordinates = _coordinates obj._jacobian = kwargs.pop('jacobian', JacobianSymbol(obj)) lcoords = ['x1', 'x2', 'x3'][:rdim] lcoords = [Symbol(i) for i in lcoords] obj._logical_coordinates = Tuple(*lcoords) # ... if not (obj._expressions is None): coords = ['x', 'y', 'z'][:rdim] # ... args = [] for i in coords: x = obj._expressions[i] x = sympify(x) args.append(x) args = Tuple(*args) # ... zero_coords = ['x1', 'x2', 'x3'][rdim:] for i in zero_coords: x = sympify(i) args = args.subs(x, 0) # ... constants = list(set(args.free_symbols) - set(lcoords)) # subs constants as Constant objects instead of Symbol d = {} for i in constants: # TODO shall we add the type? # by default it is real if i.name in kwargs: d[i] = kwargs[i.name] else: d[i] = Constant(i.name) args = args.subs(d) # ... obj._expressions = args # ... return obj
def test_issue_3554s(): x = Symbol('x') assert (1 / sqrt(1 + cos(x) * sin(x**2))).series(x, 0, 15) == \ 1 - x**2/2 + 5*x**4/8 - 5*x**6/8 + 4039*x**8/5760 - 5393*x**10/6720 + \ 13607537*x**12/14515200 - 532056047*x**14/479001600 + O(x**15)
from __future__ import print_function, division from sympy.core import Symbol, Integer x = Symbol('x') i3 = Integer(3) def timeit_x_is_integer(): x.is_integer def timeit_Integer_is_irrational(): i3.is_irrational
def test_negative_one(): x = Symbol('x', complex=True) y = Symbol('y', complex=True) assert 1 / x**y == x**(-y)
from mpmath import bernfrac, workprec from mpmath.libmp import ifib as _ifib def _product(a, b): p = 1 for k in range(a, b + 1): p *= k return p from sympy.utilities.memoization import recurrence_memo # Dummy symbol used for computing polynomial sequences _sym = Symbol('x') _symbols = Function('x') #----------------------------------------------------------------------------# # # # Fibonacci numbers # # # #----------------------------------------------------------------------------# class fibonacci(Function): r""" Fibonacci numbers / Fibonacci polynomials The Fibonacci numbers are the integer sequence defined by the initial terms F_0 = 0, F_1 = 1 and the two-term recurrence
def test_global_dict(): global_dict = {'Symbol': Symbol} inputs = {'Q & S': And(Symbol('Q'), Symbol('S'))} for text, result in inputs.items(): assert parse_expr(text, global_dict=global_dict) == result
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 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='-'), } 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_other_symbol(): x = Symbol('x', integer=True) assert x.is_integer is True assert x.is_real is True x = Symbol('x', integer=True, nonnegative=True) assert x.is_integer is True assert x.is_nonnegative is True assert x.is_negative is False assert x.is_positive is None x = Symbol('x', integer=True, nonpositive=True) assert x.is_integer is True assert x.is_nonpositive is True assert x.is_positive is False assert x.is_negative is None x = Symbol('x', odd=True) assert x.is_odd is True assert x.is_even is False assert x.is_integer is True x = Symbol('x', odd=False) assert x.is_odd is False assert x.is_even is None assert x.is_integer is None x = Symbol('x', even=True) assert x.is_even is True assert x.is_odd is False assert x.is_integer is True x = Symbol('x', even=False) assert x.is_even is False assert x.is_odd is None assert x.is_integer is None x = Symbol('x', integer=True, nonnegative=True) assert x.is_integer is True assert x.is_nonnegative is True x = Symbol('x', integer=True, nonpositive=True) assert x.is_integer is True assert x.is_nonpositive is True with raises(AttributeError): x.is_real = False x = Symbol('x', algebraic=True) assert x.is_transcendental is False x = Symbol('x', transcendental=True) assert x.is_algebraic is False assert x.is_rational is False assert x.is_integer is False