hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
096f63b5c21616255fceb3af9c46d6996913f8fc42de50ddd2a9965e7593afa2 | from typing import Tuple as tTuple
from .expr_with_intlimits import ExprWithIntLimits
from .summations import Sum, summation, _dummy_with_inherited_properties_concrete
from sympy.core.expr import Expr
from sympy.core.exprtools import factor_terms
from sympy.core.function import Derivative
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol
from sympy.functions.combinatorial.factorials import RisingFactorial
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.polys import quo, roots
class Product(ExprWithIntLimits):
r"""
Represents unevaluated products.
Explanation
===========
``Product`` represents a finite or infinite product, with the first
argument being the general form of terms in the series, and the second
argument being ``(dummy_variable, start, end)``, with ``dummy_variable``
taking all integer values from ``start`` through ``end``. In accordance
with long-standing mathematical convention, the end term is included in
the product.
Finite products
===============
For finite products (and products with symbolic limits assumed to be finite)
we follow the analogue of the summation convention described by Karr [1],
especially definition 3 of section 1.4. The product:
.. math::
\prod_{m \leq i < n} f(i)
has *the obvious meaning* for `m < n`, namely:
.. math::
\prod_{m \leq i < n} f(i) = f(m) f(m+1) \cdot \ldots \cdot f(n-2) f(n-1)
with the upper limit value `f(n)` excluded. The product over an empty set is
one if and only if `m = n`:
.. math::
\prod_{m \leq i < n} f(i) = 1 \quad \mathrm{for} \quad m = n
Finally, for all other products over empty sets we assume the following
definition:
.. math::
\prod_{m \leq i < n} f(i) = \frac{1}{\prod_{n \leq i < m} f(i)} \quad \mathrm{for} \quad m > n
It is important to note that above we define all products with the upper
limit being exclusive. This is in contrast to the usual mathematical notation,
but does not affect the product convention. Indeed we have:
.. math::
\prod_{m \leq i < n} f(i) = \prod_{i = m}^{n - 1} f(i)
where the difference in notation is intentional to emphasize the meaning,
with limits typeset on the top being inclusive.
Examples
========
>>> from sympy.abc import a, b, i, k, m, n, x
>>> from sympy import Product, oo
>>> Product(k, (k, 1, m))
Product(k, (k, 1, m))
>>> Product(k, (k, 1, m)).doit()
factorial(m)
>>> Product(k**2,(k, 1, m))
Product(k**2, (k, 1, m))
>>> Product(k**2,(k, 1, m)).doit()
factorial(m)**2
Wallis' product for pi:
>>> W = Product(2*i/(2*i-1) * 2*i/(2*i+1), (i, 1, oo))
>>> W
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
Direct computation currently fails:
>>> W.doit()
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
But we can approach the infinite product by a limit of finite products:
>>> from sympy import limit
>>> W2 = Product(2*i/(2*i-1)*2*i/(2*i+1), (i, 1, n))
>>> W2
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, n))
>>> W2e = W2.doit()
>>> W2e
4**n*factorial(n)**2/(2**(2*n)*RisingFactorial(1/2, n)*RisingFactorial(3/2, n))
>>> limit(W2e, n, oo)
pi/2
By the same formula we can compute sin(pi/2):
>>> from sympy import combsimp, pi, gamma, simplify
>>> P = pi * x * Product(1 - x**2/k**2, (k, 1, n))
>>> P = P.subs(x, pi/2)
>>> P
pi**2*Product(1 - pi**2/(4*k**2), (k, 1, n))/2
>>> Pe = P.doit()
>>> Pe
pi**2*RisingFactorial(1 - pi/2, n)*RisingFactorial(1 + pi/2, n)/(2*factorial(n)**2)
>>> limit(Pe, n, oo).gammasimp()
sin(pi**2/2)
>>> Pe.rewrite(gamma)
(-1)**n*pi**2*gamma(pi/2)*gamma(n + 1 + pi/2)/(2*gamma(1 + pi/2)*gamma(-n + pi/2)*gamma(n + 1)**2)
Products with the lower limit being larger than the upper one:
>>> Product(1/i, (i, 6, 1)).doit()
120
>>> Product(i, (i, 2, 5)).doit()
120
The empty product:
>>> Product(i, (i, n, n-1)).doit()
1
An example showing that the symbolic result of a product is still
valid for seemingly nonsensical values of the limits. Then the Karr
convention allows us to give a perfectly valid interpretation to
those products by interchanging the limits according to the above rules:
>>> P = Product(2, (i, 10, n)).doit()
>>> P
2**(n - 9)
>>> P.subs(n, 5)
1/16
>>> Product(2, (i, 10, 5)).doit()
1/16
>>> 1/Product(2, (i, 6, 9)).doit()
1/16
An explicit example of the Karr summation convention applied to products:
>>> P1 = Product(x, (i, a, b)).doit()
>>> P1
x**(-a + b + 1)
>>> P2 = Product(x, (i, b+1, a-1)).doit()
>>> P2
x**(a - b - 1)
>>> simplify(P1 * P2)
1
And another one:
>>> P1 = Product(i, (i, b, a)).doit()
>>> P1
RisingFactorial(b, a - b + 1)
>>> P2 = Product(i, (i, a+1, b-1)).doit()
>>> P2
RisingFactorial(a + 1, -a + b - 1)
>>> P1 * P2
RisingFactorial(b, a - b + 1)*RisingFactorial(a + 1, -a + b - 1)
>>> combsimp(P1 * P2)
1
See Also
========
Sum, summation
product
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
.. [2] https://en.wikipedia.org/wiki/Multiplication#Capital_Pi_notation
.. [3] https://en.wikipedia.org/wiki/Empty_product
"""
__slots__ = ()
limits: tTuple[tTuple[Symbol, Expr, Expr]]
def __new__(cls, function, *symbols, **assumptions):
obj = ExprWithIntLimits.__new__(cls, function, *symbols, **assumptions)
return obj
def _eval_rewrite_as_Sum(self, *args, **kwargs):
return exp(Sum(log(self.function), *self.limits))
@property
def term(self):
return self._args[0]
function = term
def _eval_is_zero(self):
if self.has_empty_sequence:
return False
z = self.term.is_zero
if z is True:
return True
if self.has_finite_limits:
# A Product is zero only if its term is zero assuming finite limits.
return z
def _eval_is_extended_real(self):
if self.has_empty_sequence:
return True
return self.function.is_extended_real
def _eval_is_positive(self):
if self.has_empty_sequence:
return True
if self.function.is_positive and self.has_finite_limits:
return True
def _eval_is_nonnegative(self):
if self.has_empty_sequence:
return True
if self.function.is_nonnegative and self.has_finite_limits:
return True
def _eval_is_extended_nonnegative(self):
if self.has_empty_sequence:
return True
if self.function.is_extended_nonnegative:
return True
def _eval_is_extended_nonpositive(self):
if self.has_empty_sequence:
return True
def _eval_is_finite(self):
if self.has_finite_limits and self.function.is_finite:
return True
def doit(self, **hints):
# first make sure any definite limits have product
# variables with matching assumptions
reps = {}
for xab in self.limits:
d = _dummy_with_inherited_properties_concrete(xab)
if d:
reps[xab[0]] = d
if reps:
undo = {v: k for k, v in reps.items()}
did = self.xreplace(reps).doit(**hints)
if isinstance(did, tuple): # when separate=True
did = tuple([i.xreplace(undo) for i in did])
else:
did = did.xreplace(undo)
return did
from sympy.simplify.powsimp import powsimp
f = self.function
for index, limit in enumerate(self.limits):
i, a, b = limit
dif = b - a
if dif.is_integer and dif.is_negative:
a, b = b + 1, a - 1
f = 1 / f
g = self._eval_product(f, (i, a, b))
if g in (None, S.NaN):
return self.func(powsimp(f), *self.limits[index:])
else:
f = g
if hints.get('deep', True):
return f.doit(**hints)
else:
return powsimp(f)
def _eval_adjoint(self):
if self.is_commutative:
return self.func(self.function.adjoint(), *self.limits)
return None
def _eval_conjugate(self):
return self.func(self.function.conjugate(), *self.limits)
def _eval_product(self, term, limits):
(k, a, n) = limits
if k not in term.free_symbols:
if (term - 1).is_zero:
return S.One
return term**(n - a + 1)
if a == n:
return term.subs(k, a)
from .delta import deltaproduct, _has_simple_delta
if term.has(KroneckerDelta) and _has_simple_delta(term, limits[0]):
return deltaproduct(term, limits)
dif = n - a
definite = dif.is_Integer
if definite and (dif < 100):
return self._eval_product_direct(term, limits)
elif term.is_polynomial(k):
poly = term.as_poly(k)
A = B = Q = S.One
all_roots = roots(poly)
M = 0
for r, m in all_roots.items():
M += m
A *= RisingFactorial(a - r, n - a + 1)**m
Q *= (n - r)**m
if M < poly.degree():
arg = quo(poly, Q.as_poly(k))
B = self.func(arg, (k, a, n)).doit()
return poly.LC()**(n - a + 1) * A * B
elif term.is_Add:
factored = factor_terms(term, fraction=True)
if factored.is_Mul:
return self._eval_product(factored, (k, a, n))
elif term.is_Mul:
# Factor in part without the summation variable and part with
without_k, with_k = term.as_coeff_mul(k)
if len(with_k) >= 2:
# More than one term including k, so still a multiplication
exclude, include = [], []
for t in with_k:
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 = self.func(arg, (k, a, n)).doit()
return without_k**(n - a + 1)*A * B
else:
# Just a single term
p = self._eval_product(with_k[0], (k, a, n))
if p is None:
p = self.func(with_k[0], (k, a, n)).doit()
return without_k**(n - a + 1)*p
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 self.func(evaluated, limits)
else:
return f
if definite:
return self._eval_product_direct(term, limits)
def _eval_simplify(self, **kwargs):
from sympy.simplify.simplify import product_simplify
rv = product_simplify(self, **kwargs)
return rv.doit() if kwargs['doit'] else rv
def _eval_transpose(self):
if self.is_commutative:
return self.func(self.function.transpose(), *self.limits)
return None
def _eval_product_direct(self, term, limits):
(k, a, n) = limits
return Mul(*[term.subs(k, a + i) for i in range(n - a + 1)])
def _eval_derivative(self, x):
if isinstance(x, Symbol) and x not in self.free_symbols:
return S.Zero
f, limits = self.function, list(self.limits)
limit = limits.pop(-1)
if limits:
f = self.func(f, *limits)
i, a, b = limit
if x in a.free_symbols or x in b.free_symbols:
return None
h = Dummy()
rv = Sum( Product(f, (i, a, h - 1)) * Product(f, (i, h + 1, b)) * Derivative(f, x, evaluate=True).subs(i, h), (h, a, b))
return rv
def is_convergent(self):
r"""
See docs of :obj:`.Sum.is_convergent()` for explanation of convergence
in SymPy.
Explanation
===========
The infinite product:
.. math::
\prod_{1 \leq i < \infty} f(i)
is defined by the sequence of partial products:
.. math::
\prod_{i=1}^{n} f(i) = f(1) f(2) \cdots f(n)
as n increases without bound. The product converges to a non-zero
value if and only if the sum:
.. math::
\sum_{1 \leq i < \infty} \log{f(n)}
converges.
Examples
========
>>> from sympy import Product, Symbol, cos, pi, exp, oo
>>> n = Symbol('n', integer=True)
>>> Product(n/(n + 1), (n, 1, oo)).is_convergent()
False
>>> Product(1/n**2, (n, 1, oo)).is_convergent()
False
>>> Product(cos(pi/n), (n, 1, oo)).is_convergent()
True
>>> Product(exp(-n**2), (n, 1, oo)).is_convergent()
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Infinite_product
"""
sequence_term = self.function
log_sum = log(sequence_term)
lim = self.limits
try:
is_conv = Sum(log_sum, *lim).is_convergent()
except NotImplementedError:
if Sum(sequence_term - 1, *lim).is_absolutely_convergent() is S.true:
return S.true
raise NotImplementedError("The algorithm to find the product convergence of %s "
"is not yet implemented" % (sequence_term))
return is_conv
def reverse_order(expr, *indices):
"""
Reverse the order of a limit in a Product.
Explanation
===========
``reverse_order(expr, *indices)`` reverses some limits in the expression
``expr`` which can be either a ``Sum`` or a ``Product``. The selectors in
the argument ``indices`` specify some indices whose limits get reversed.
These selectors are either variable names or numerical indices counted
starting from the inner-most limit tuple.
Examples
========
>>> from sympy import gamma, Product, simplify, Sum
>>> from sympy.abc import x, y, a, b, c, d
>>> P = Product(x, (x, a, b))
>>> Pr = P.reverse_order(x)
>>> Pr
Product(1/x, (x, b + 1, a - 1))
>>> Pr = Pr.doit()
>>> Pr
1/RisingFactorial(b + 1, a - b - 1)
>>> simplify(Pr.rewrite(gamma))
Piecewise((gamma(b + 1)/gamma(a), b > -1), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
>>> P = P.doit()
>>> P
RisingFactorial(a, -a + b + 1)
>>> simplify(P.rewrite(gamma))
Piecewise((gamma(b + 1)/gamma(a), a > 0), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
While one should prefer variable names when specifying which limits
to reverse, the index counting notation comes in handy in case there
are several symbols with the same name.
>>> S = Sum(x*y, (x, a, b), (y, c, d))
>>> S
Sum(x*y, (x, a, b), (y, c, d))
>>> S0 = S.reverse_order(0)
>>> S0
Sum(-x*y, (x, b + 1, a - 1), (y, c, d))
>>> S1 = S0.reverse_order(1)
>>> S1
Sum(x*y, (x, b + 1, a - 1), (y, d + 1, c - 1))
Of course we can mix both notations:
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
See Also
========
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index,
reorder_limit,
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
"""
l_indices = list(indices)
for i, indx in enumerate(l_indices):
if not isinstance(indx, int):
l_indices[i] = expr.index(indx)
e = 1
limits = []
for i, limit in enumerate(expr.limits):
l = limit
if i in l_indices:
e = -e
l = (limit[0], limit[2] + 1, limit[1] - 1)
limits.append(l)
return Product(expr.function ** e, *limits)
def product(*args, **kwargs):
r"""
Compute the product.
Explanation
===========
The notation for symbols is similar to the notation used in Sum or
Integral. product(f, (i, a, b)) computes the product of f with
respect to i from a to b, i.e.,
::
b
_____
product(f(n), (i, a, b)) = | | f(n)
| |
i = a
If it cannot compute the product, it returns an unevaluated Product object.
Repeated products can be computed by introducing additional symbols tuples::
Examples
========
>>> from sympy import product, symbols
>>> i, n, m, k = symbols('i n m k', integer=True)
>>> product(i, (i, 1, k))
factorial(k)
>>> product(m, (i, 1, k))
m**k
>>> product(i, (i, 1, k), (k, 1, n))
Product(factorial(k), (k, 1, n))
"""
prod = Product(*args, **kwargs)
if isinstance(prod, Product):
return prod.doit(deep=False)
else:
return prod
|
08ea1003e60418e7f4cd1145795334cf5aa610b1abbed59e75798f10861e2b44 | from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import AppliedUndef, UndefinedFunction
from sympy.core.mul import Mul
from sympy.core.relational import Equality, Relational
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, Dummy
from sympy.core.sympify import sympify
from sympy.functions.elementary.piecewise import (piecewise_fold,
Piecewise)
from sympy.logic.boolalg import BooleanFunction
from sympy.matrices.matrices import MatrixBase
from sympy.sets.sets import Interval, Set
from sympy.sets.fancysets import Range
from sympy.tensor.indexed import Idx
from sympy.utilities import flatten
from sympy.utilities.iterables import sift, is_sequence
from sympy.utilities.exceptions import sympy_deprecation_warning
def _common_new(cls, function, *symbols, discrete, **assumptions):
"""Return either a special return value or the tuple,
(function, limits, orientation). This code is common to
both ExprWithLimits and AddWithLimits."""
function = sympify(function)
if isinstance(function, Equality):
# This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y))
# but that is only valid for definite integrals.
limits, orientation = _process_limits(*symbols, discrete=discrete)
if not (limits and all(len(limit) == 3 for limit in limits)):
sympy_deprecation_warning(
"""
Creating a indefinite integral with an Eq() argument is
deprecated.
This is because indefinite integrals do not preserve equality
due to the arbitrary constants. If you want an equality of
indefinite integrals, use Eq(Integral(a, x), Integral(b, x))
explicitly.
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-indefinite-integral-eq",
stacklevel=5,
)
lhs = function.lhs
rhs = function.rhs
return Equality(cls(lhs, *symbols, **assumptions), \
cls(rhs, *symbols, **assumptions))
if function is S.NaN:
return S.NaN
if symbols:
limits, orientation = _process_limits(*symbols, discrete=discrete)
for i, li in enumerate(limits):
if len(li) == 4:
function = function.subs(li[0], li[-1])
limits[i] = Tuple(*li[:-1])
else:
# symbol not provided -- we can still try to compute a general form
free = function.free_symbols
if len(free) != 1:
raise ValueError(
"specify dummy variables for %s" % function)
limits, orientation = [Tuple(s) for s in free], 1
# denest any nested calls
while cls == type(function):
limits = list(function.limits) + limits
function = function.function
# Any embedded piecewise functions need to be brought out to the
# top level. We only fold Piecewise that contain the integration
# variable.
reps = {}
symbols_of_integration = {i[0] for i in limits}
for p in function.atoms(Piecewise):
if not p.has(*symbols_of_integration):
reps[p] = Dummy()
# mask off those that don't
function = function.xreplace(reps)
# do the fold
function = piecewise_fold(function)
# remove the masking
function = function.xreplace({v: k for k, v in reps.items()})
return function, limits, orientation
def _process_limits(*symbols, discrete=None):
"""Process the list of symbols and convert them to canonical limits,
storing them as Tuple(symbol, lower, upper). The orientation of
the function is also returned when the upper limit is missing
so (x, 1, None) becomes (x, None, 1) and the orientation is changed.
In the case that a limit is specified as (symbol, Range), a list of
length 4 may be returned if a change of variables is needed; the
expression that should replace the symbol in the expression is
the fourth element in the list.
"""
limits = []
orientation = 1
if discrete is None:
err_msg = 'discrete must be True or False'
elif discrete:
err_msg = 'use Range, not Interval or Relational'
else:
err_msg = 'use Interval or Relational, not Range'
for V in symbols:
if isinstance(V, (Relational, BooleanFunction)):
if discrete:
raise TypeError(err_msg)
variable = V.atoms(Symbol).pop()
V = (variable, V.as_set())
elif isinstance(V, Symbol) or getattr(V, '_diff_wrt', False):
if isinstance(V, Idx):
if V.lower is None or V.upper is None:
limits.append(Tuple(V))
else:
limits.append(Tuple(V, V.lower, V.upper))
else:
limits.append(Tuple(V))
continue
if is_sequence(V) and not isinstance(V, Set):
if len(V) == 2 and isinstance(V[1], Set):
V = list(V)
if isinstance(V[1], Interval): # includes Reals
if discrete:
raise TypeError(err_msg)
V[1:] = V[1].inf, V[1].sup
elif isinstance(V[1], Range):
if not discrete:
raise TypeError(err_msg)
lo = V[1].inf
hi = V[1].sup
dx = abs(V[1].step) # direction doesn't matter
if dx == 1:
V[1:] = [lo, hi]
else:
if lo is not S.NegativeInfinity:
V = [V[0]] + [0, (hi - lo)//dx, dx*V[0] + lo]
else:
V = [V[0]] + [0, S.Infinity, -dx*V[0] + hi]
else:
# more complicated sets would require splitting, e.g.
# Union(Interval(1, 3), interval(6,10))
raise NotImplementedError(
'expecting Range' if discrete else
'Relational or single Interval' )
V = sympify(flatten(V)) # list of sympified elements/None
if isinstance(V[0], (Symbol, Idx)) or getattr(V[0], '_diff_wrt', False):
newsymbol = V[0]
if len(V) == 3:
# general case
if V[2] is None and V[1] is not None:
orientation *= -1
V = [newsymbol] + [i for i in V[1:] if i is not None]
lenV = len(V)
if not isinstance(newsymbol, Idx) or lenV == 3:
if lenV == 4:
limits.append(Tuple(*V))
continue
if lenV == 3:
if isinstance(newsymbol, Idx):
# Idx represents an integer which may have
# specified values it can take on; if it is
# given such a value, an error is raised here
# if the summation would try to give it a larger
# or smaller value than permitted. None and Symbolic
# values will not raise an error.
lo, hi = newsymbol.lower, newsymbol.upper
try:
if lo is not None and not bool(V[1] >= lo):
raise ValueError("Summation will set Idx value too low.")
except TypeError:
pass
try:
if hi is not None and not bool(V[2] <= hi):
raise ValueError("Summation will set Idx value too high.")
except TypeError:
pass
limits.append(Tuple(*V))
continue
if lenV == 1 or (lenV == 2 and V[1] is None):
limits.append(Tuple(newsymbol))
continue
elif lenV == 2:
limits.append(Tuple(newsymbol, V[1]))
continue
raise ValueError('Invalid limits given: %s' % str(symbols))
return limits, orientation
class ExprWithLimits(Expr):
__slots__ = ('is_commutative',)
def __new__(cls, function, *symbols, **assumptions):
from sympy.concrete.products import Product
pre = _common_new(cls, function, *symbols,
discrete=issubclass(cls, Product), **assumptions)
if isinstance(pre, tuple):
function, limits, _ = pre
else:
return pre
# limits must have upper and lower bounds; the indefinite form
# is not supported. This restriction does not apply to AddWithLimits
if any(len(l) != 3 or None in l for l in limits):
raise ValueError('ExprWithLimits requires values for lower and upper bounds.')
obj = Expr.__new__(cls, **assumptions)
arglist = [function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
@property
def function(self):
"""Return the function applied across limits.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x
>>> Integral(x**2, (x,)).function
x**2
See Also
========
limits, variables, free_symbols
"""
return self._args[0]
@property
def kind(self):
return self.function.kind
@property
def limits(self):
"""Return the limits of expression.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, i
>>> Integral(x**i, (i, 1, 3)).limits
((i, 1, 3),)
See Also
========
function, variables, free_symbols
"""
return self._args[1:]
@property
def variables(self):
"""Return a list of the limit variables.
>>> from sympy import Sum
>>> from sympy.abc import x, i
>>> Sum(x**i, (i, 1, 3)).variables
[i]
See Also
========
function, limits, free_symbols
as_dummy : Rename dummy variables
sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
"""
return [l[0] for l in self.limits]
@property
def bound_symbols(self):
"""Return only variables that are dummy variables.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, i, j, k
>>> Integral(x**i, (i, 1, 3), (j, 2), k).bound_symbols
[i, j]
See Also
========
function, limits, free_symbols
as_dummy : Rename dummy variables
sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
"""
return [l[0] for l in self.limits if len(l) != 1]
@property
def free_symbols(self):
"""
This method returns the symbols in the object, excluding those
that take on a specific value (i.e. the dummy symbols).
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y
>>> Sum(x, (x, y, 1)).free_symbols
{y}
"""
# don't test for any special values -- nominal free symbols
# should be returned, e.g. don't return set() if the
# function is zero -- treat it like an unevaluated expression.
function, limits = self.function, self.limits
# mask off non-symbol integration variables that have
# more than themself as a free symbol
reps = {i[0]: i[0] if i[0].free_symbols == {i[0]} else Dummy()
for i in self.limits}
function = function.xreplace(reps)
isyms = function.free_symbols
for xab in limits:
v = reps[xab[0]]
if len(xab) == 1:
isyms.add(v)
continue
# take out the target symbol
if v in isyms:
isyms.remove(v)
# add in the new symbols
for i in xab[1:]:
isyms.update(i.free_symbols)
reps = {v: k for k, v in reps.items()}
return set([reps.get(_, _) for _ in isyms])
@property
def is_number(self):
"""Return True if the Sum has no free symbols, else False."""
return not self.free_symbols
def _eval_interval(self, x, a, b):
limits = [(i if i[0] != x else (x, a, b)) for i in self.limits]
integrand = self.function
return self.func(integrand, *limits)
def _eval_subs(self, old, new):
"""
Perform substitutions over non-dummy variables
of an expression with limits. Also, can be used
to specify point-evaluation of an abstract antiderivative.
Examples
========
>>> from sympy import Sum, oo
>>> from sympy.abc import s, n
>>> Sum(1/n**s, (n, 1, oo)).subs(s, 2)
Sum(n**(-2), (n, 1, oo))
>>> from sympy import Integral
>>> from sympy.abc import x, a
>>> Integral(a*x**2, x).subs(x, 4)
Integral(a*x**2, (x, 4))
See Also
========
variables : Lists the integration variables
transform : Perform mapping on the dummy variable for integrals
change_index : Perform mapping on the sum and product dummy variables
"""
func, limits = self.function, list(self.limits)
# If one of the expressions we are replacing is used as a func index
# one of two things happens.
# - the old variable first appears as a free variable
# so we perform all free substitutions before it becomes
# a func index.
# - the old variable first appears as a func index, in
# which case we ignore. See change_index.
# Reorder limits to match standard mathematical practice for scoping
limits.reverse()
if not isinstance(old, Symbol) or \
old.free_symbols.intersection(self.free_symbols):
sub_into_func = True
for i, xab in enumerate(limits):
if 1 == len(xab) and old == xab[0]:
if new._diff_wrt:
xab = (new,)
else:
xab = (old, old)
limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0:
sub_into_func = False
break
if isinstance(old, (AppliedUndef, UndefinedFunction)):
sy2 = set(self.variables).intersection(set(new.atoms(Symbol)))
sy1 = set(self.variables).intersection(set(old.args))
if not sy2.issubset(sy1):
raise ValueError(
"substitution cannot create dummy dependencies")
sub_into_func = True
if sub_into_func:
func = func.subs(old, new)
else:
# old is a Symbol and a dummy variable of some limit
for i, xab in enumerate(limits):
if len(xab) == 3:
limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
if old == xab[0]:
break
# simplify redundant limits (x, x) to (x, )
for i, xab in enumerate(limits):
if len(xab) == 2 and (xab[0] - xab[1]).is_zero:
limits[i] = Tuple(xab[0], )
# Reorder limits back to representation-form
limits.reverse()
return self.func(func, *limits)
@property
def has_finite_limits(self):
"""
Returns True if the limits are known to be finite, either by the
explicit bounds, assumptions on the bounds, or assumptions on the
variables. False if known to be infinite, based on the bounds.
None if not enough information is available to determine.
Examples
========
>>> from sympy import Sum, Integral, Product, oo, Symbol
>>> x = Symbol('x')
>>> Sum(x, (x, 1, 8)).has_finite_limits
True
>>> Integral(x, (x, 1, oo)).has_finite_limits
False
>>> M = Symbol('M')
>>> Sum(x, (x, 1, M)).has_finite_limits
>>> N = Symbol('N', integer=True)
>>> Product(x, (x, 1, N)).has_finite_limits
True
See Also
========
has_reversed_limits
"""
ret_None = False
for lim in self.limits:
if len(lim) == 3:
if any(l.is_infinite for l in lim[1:]):
# Any of the bounds are +/-oo
return False
elif any(l.is_infinite is None for l in lim[1:]):
# Maybe there are assumptions on the variable?
if lim[0].is_infinite is None:
ret_None = True
else:
if lim[0].is_infinite is None:
ret_None = True
if ret_None:
return None
return True
@property
def has_reversed_limits(self):
"""
Returns True if the limits are known to be in reversed order, either
by the explicit bounds, assumptions on the bounds, or assumptions on the
variables. False if known to be in normal order, based on the bounds.
None if not enough information is available to determine.
Examples
========
>>> from sympy import Sum, Integral, Product, oo, Symbol
>>> x = Symbol('x')
>>> Sum(x, (x, 8, 1)).has_reversed_limits
True
>>> Sum(x, (x, 1, oo)).has_reversed_limits
False
>>> M = Symbol('M')
>>> Integral(x, (x, 1, M)).has_reversed_limits
>>> N = Symbol('N', integer=True, positive=True)
>>> Sum(x, (x, 1, N)).has_reversed_limits
False
>>> Product(x, (x, 2, N)).has_reversed_limits
>>> Product(x, (x, 2, N)).subs(N, N + 2).has_reversed_limits
False
See Also
========
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.has_empty_sequence
"""
ret_None = False
for lim in self.limits:
if len(lim) == 3:
var, a, b = lim
dif = b - a
if dif.is_extended_negative:
return True
elif dif.is_extended_nonnegative:
continue
else:
ret_None = True
else:
return None
if ret_None:
return None
return False
class AddWithLimits(ExprWithLimits):
r"""Represents unevaluated oriented additions.
Parent class for Integral and Sum.
"""
__slots__ = ()
def __new__(cls, function, *symbols, **assumptions):
from sympy.concrete.summations import Sum
pre = _common_new(cls, function, *symbols,
discrete=issubclass(cls, Sum), **assumptions)
if isinstance(pre, tuple):
function, limits, orientation = pre
else:
return pre
obj = Expr.__new__(cls, **assumptions)
arglist = [orientation*function] # orientation not used in ExprWithLimits
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
def _eval_adjoint(self):
if all(x.is_real for x in flatten(self.limits)):
return self.func(self.function.adjoint(), *self.limits)
return None
def _eval_conjugate(self):
if all(x.is_real for x in flatten(self.limits)):
return self.func(self.function.conjugate(), *self.limits)
return None
def _eval_transpose(self):
if all(x.is_real for x in flatten(self.limits)):
return self.func(self.function.transpose(), *self.limits)
return None
def _eval_factor(self, **hints):
if 1 == len(self.limits):
summand = self.function.factor(**hints)
if summand.is_Mul:
out = sift(summand.args, lambda w: w.is_commutative \
and not set(self.variables) & w.free_symbols)
return Mul(*out[True])*self.func(Mul(*out[False]), \
*self.limits)
else:
summand = self.func(self.function, *self.limits[0:-1]).factor()
if not summand.has(self.variables[-1]):
return self.func(1, [self.limits[-1]]).doit()*summand
elif isinstance(summand, Mul):
return self.func(summand, self.limits[-1]).factor()
return self
def _eval_expand_basic(self, **hints):
summand = self.function.expand(**hints)
force = hints.get('force', False)
if (summand.is_Add and (force or summand.is_commutative and
self.has_finite_limits is not False)):
return Add(*[self.func(i, *self.limits) for i in summand.args])
elif isinstance(summand, MatrixBase):
return summand.applyfunc(lambda x: self.func(x, *self.limits))
elif summand != self.function:
return self.func(summand, *self.limits)
return self
|
1d9a5ac568f6e6df23450c1fd38de61fd6f384891acbd0cb73ffcbff1a877423 | from typing import Tuple as tTuple
from sympy.calculus.singularities import is_decreasing
from sympy.calculus.accumulationbounds import AccumulationBounds
from .expr_with_intlimits import ExprWithIntLimits
from .expr_with_limits import AddWithLimits
from .gosper import gosper_sum
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import Derivative, expand
from sympy.core.mul import Mul
from sympy.core.numbers import Float, _illegal
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy, Wild, Symbol, symbols
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import cot, csc
from sympy.functions.special.hyper import hyper
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.zeta_functions import zeta
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import And
from sympy.polys.partfrac import apart
from sympy.polys.polyerrors import PolynomialError, PolificationFailed
from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor
from sympy.polys.rationaltools import together
from sympy.series.limitseq import limit_seq
from sympy.series.order import O
from sympy.series.residues import residue
from sympy.sets.sets import FiniteSet, Interval
from sympy.utilities.iterables import sift
import itertools
class Sum(AddWithLimits, ExprWithIntLimits):
r"""
Represents unevaluated summation.
Explanation
===========
``Sum`` represents a finite or infinite series, with the first argument
being the general form of terms in the series, and the second argument
being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking
all integer values from ``start`` through ``end``. In accordance with
long-standing mathematical convention, the end term is included in the
summation.
Finite sums
===========
For finite sums (and sums with symbolic limits assumed to be finite) we
follow the summation convention described by Karr [1], especially
definition 3 of section 1.4. The sum:
.. math::
\sum_{m \leq i < n} f(i)
has *the obvious meaning* for `m < n`, namely:
.. math::
\sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1)
with the upper limit value `f(n)` excluded. The sum over an empty set is
zero if and only if `m = n`:
.. math::
\sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n
Finally, for all other sums over empty sets we assume the following
definition:
.. math::
\sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n
It is important to note that Karr defines all sums with the upper
limit being exclusive. This is in contrast to the usual mathematical notation,
but does not affect the summation convention. Indeed we have:
.. math::
\sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i)
where the difference in notation is intentional to emphasize the meaning,
with limits typeset on the top being inclusive.
Examples
========
>>> from sympy.abc import i, k, m, n, x
>>> from sympy import Sum, factorial, oo, IndexedBase, Function
>>> Sum(k, (k, 1, m))
Sum(k, (k, 1, m))
>>> Sum(k, (k, 1, m)).doit()
m**2/2 + m/2
>>> Sum(k**2, (k, 1, m))
Sum(k**2, (k, 1, m))
>>> Sum(k**2, (k, 1, m)).doit()
m**3/3 + m**2/2 + m/6
>>> Sum(x**k, (k, 0, oo))
Sum(x**k, (k, 0, oo))
>>> Sum(x**k, (k, 0, oo)).doit()
Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
>>> Sum(x**k/factorial(k), (k, 0, oo)).doit()
exp(x)
Here are examples to do summation with symbolic indices. You
can use either Function of IndexedBase classes:
>>> f = Function('f')
>>> Sum(f(n), (n, 0, 3)).doit()
f(0) + f(1) + f(2) + f(3)
>>> Sum(f(n), (n, 0, oo)).doit()
Sum(f(n), (n, 0, oo))
>>> f = IndexedBase('f')
>>> Sum(f[n]**2, (n, 0, 3)).doit()
f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2
An example showing that the symbolic result of a summation is still
valid for seemingly nonsensical values of the limits. Then the Karr
convention allows us to give a perfectly valid interpretation to
those sums by interchanging the limits according to the above rules:
>>> S = Sum(i, (i, 1, n)).doit()
>>> S
n**2/2 + n/2
>>> S.subs(n, -4)
6
>>> Sum(i, (i, 1, -4)).doit()
6
>>> Sum(-i, (i, -3, 0)).doit()
6
An explicit example of the Karr summation convention:
>>> S1 = Sum(i**2, (i, m, m+n-1)).doit()
>>> S1
m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6
>>> S2 = Sum(i**2, (i, m+n, m-1)).doit()
>>> S2
-m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6
>>> S1 + S2
0
>>> S3 = Sum(i, (i, m, m-1)).doit()
>>> S3
0
See Also
========
summation
Product, sympy.concrete.products.product
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
.. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation
.. [3] https://en.wikipedia.org/wiki/Empty_sum
"""
__slots__ = ()
limits: tTuple[tTuple[Symbol, Expr, Expr]]
def __new__(cls, function, *symbols, **assumptions):
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
if not hasattr(obj, 'limits'):
return obj
if any(len(l) != 3 or None in l for l in obj.limits):
raise ValueError('Sum requires values for lower and upper bounds.')
return obj
def _eval_is_zero(self):
# a Sum is only zero if its function is zero or if all terms
# cancel out. This only answers whether the summand is zero; if
# not then None is returned since we don't analyze whether all
# terms cancel out.
if self.function.is_zero or self.has_empty_sequence:
return True
def _eval_is_extended_real(self):
if self.has_empty_sequence:
return True
return self.function.is_extended_real
def _eval_is_positive(self):
if self.has_finite_limits and self.has_reversed_limits is False:
return self.function.is_positive
def _eval_is_negative(self):
if self.has_finite_limits and self.has_reversed_limits is False:
return self.function.is_negative
def _eval_is_finite(self):
if self.has_finite_limits and self.function.is_finite:
return True
def doit(self, **hints):
if hints.get('deep', True):
f = self.function.doit(**hints)
else:
f = self.function
# first make sure any definite limits have summation
# variables with matching assumptions
reps = {}
for xab in self.limits:
d = _dummy_with_inherited_properties_concrete(xab)
if d:
reps[xab[0]] = d
if reps:
undo = {v: k for k, v in reps.items()}
did = self.xreplace(reps).doit(**hints)
if isinstance(did, tuple): # when separate=True
did = tuple([i.xreplace(undo) for i in did])
elif did is not None:
did = did.xreplace(undo)
else:
did = self
return did
if self.function.is_Matrix:
expanded = self.expand()
if self != expanded:
return expanded.doit()
return _eval_matrix_sum(self)
for n, limit in enumerate(self.limits):
i, a, b = limit
dif = b - a
if dif == -1:
# Any summation over an empty set is zero
return S.Zero
if dif.is_integer and dif.is_negative:
a, b = b + 1, a - 1
f = -f
newf = eval_sum(f, (i, a, b))
if newf is None:
if f == self.function:
zeta_function = self.eval_zeta_function(f, (i, a, b))
if zeta_function is not None:
return zeta_function
return self
else:
return self.func(f, *self.limits[n:])
f = newf
if hints.get('deep', True):
# eval_sum could return partially unevaluated
# result with Piecewise. In this case we won't
# doit() recursively.
if not isinstance(f, Piecewise):
return f.doit(**hints)
return f
def eval_zeta_function(self, f, limits):
"""
Check whether the function matches with the zeta function.
If it matches, then return a `Piecewise` expression because
zeta function does not converge unless `s > 1` and `q > 0`
"""
i, a, b = limits
w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i])
result = f.match((w * i + y) ** (-z))
if result is not None and b is S.Infinity:
coeff = 1 / result[w] ** result[z]
s = result[z]
q = result[y] / result[w] + a
return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True))
def _eval_derivative(self, x):
"""
Differentiate wrt x as long as x is not in the free symbols of any of
the upper or lower limits.
Explanation
===========
Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a`
since the value of the sum is discontinuous in `a`. In a case
involving a limit variable, the unevaluated derivative is returned.
"""
# diff already confirmed that x is in the free symbols of self, but we
# don't want to differentiate wrt any free symbol in the upper or lower
# limits
# XXX remove this test for free_symbols when the default _eval_derivative is in
if isinstance(x, Symbol) and x not in self.free_symbols:
return S.Zero
# get limits and the function
f, limits = self.function, list(self.limits)
limit = limits.pop(-1)
if limits: # f is the argument to a Sum
f = self.func(f, *limits)
_, a, b = limit
if x in a.free_symbols or x in b.free_symbols:
return None
df = Derivative(f, x, evaluate=True)
rv = self.func(df, limit)
return rv
def _eval_difference_delta(self, n, step):
k, _, upper = self.args[-1]
new_upper = upper.subs(n, n + step)
if len(self.args) == 2:
f = self.args[0]
else:
f = self.func(*self.args[:-1])
return Sum(f, (k, upper + 1, new_upper)).doit()
def _eval_simplify(self, **kwargs):
function = self.function
if kwargs.get('deep', True):
function = function.simplify(**kwargs)
# split the function into adds
terms = Add.make_args(expand(function))
s_t = [] # Sum Terms
o_t = [] # Other Terms
for term in terms:
if term.has(Sum):
# if there is an embedded sum here
# it is of the form x * (Sum(whatever))
# hence we make a Mul out of it, and simplify all interior sum terms
subterms = Mul.make_args(expand(term))
out_terms = []
for subterm in subterms:
# go through each term
if isinstance(subterm, Sum):
# if it's a sum, simplify it
out_terms.append(subterm._eval_simplify(**kwargs))
else:
# otherwise, add it as is
out_terms.append(subterm)
# turn it back into a Mul
s_t.append(Mul(*out_terms))
else:
o_t.append(term)
# next try to combine any interior sums for further simplification
from sympy.simplify.simplify import factor_sum, sum_combine
result = Add(sum_combine(s_t), *o_t)
return factor_sum(result, limits=self.limits)
def is_convergent(self):
r"""
Checks for the convergence of a Sum.
Explanation
===========
We divide the study of convergence of infinite sums and products in
two parts.
First Part:
One part is the question whether all the terms are well defined, i.e.,
they are finite in a sum and also non-zero in a product. Zero
is the analogy of (minus) infinity in products as
:math:`e^{-\infty} = 0`.
Second Part:
The second part is the question of convergence after infinities,
and zeros in products, have been omitted assuming that their number
is finite. This means that we only consider the tail of the sum or
product, starting from some point after which all terms are well
defined.
For example, in a sum of the form:
.. math::
\sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}
where a and b are numbers. The routine will return true, even if there
are infinities in the term sequence (at most two). An analogous
product would be:
.. math::
\prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}
This is how convergence is interpreted. It is concerned with what
happens at the limit. Finding the bad terms is another independent
matter.
Note: It is responsibility of user to see that the sum or product
is well defined.
There are various tests employed to check the convergence like
divergence test, root test, integral test, alternating series test,
comparison tests, Dirichlet tests. It returns true if Sum is convergent
and false if divergent and NotImplementedError if it cannot be checked.
References
==========
.. [1] https://en.wikipedia.org/wiki/Convergence_tests
Examples
========
>>> from sympy import factorial, S, Sum, Symbol, oo
>>> n = Symbol('n', integer=True)
>>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
True
>>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
False
>>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
False
>>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
True
See Also
========
Sum.is_absolutely_convergent()
sympy.concrete.products.Product.is_convergent()
"""
p, q, r = symbols('p q r', cls=Wild)
sym = self.limits[0][0]
lower_limit = self.limits[0][1]
upper_limit = self.limits[0][2]
sequence_term = self.function.simplify()
if len(sequence_term.free_symbols) > 1:
raise NotImplementedError("convergence checking for more than one symbol "
"containing series is not handled")
if lower_limit.is_finite and upper_limit.is_finite:
return S.true
# transform sym -> -sym and swap the upper_limit = S.Infinity
# and lower_limit = - upper_limit
if lower_limit is S.NegativeInfinity:
if upper_limit is S.Infinity:
return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
from sympy.simplify.simplify import simplify
sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
lower_limit = -upper_limit
upper_limit = S.Infinity
sym_ = Dummy(sym.name, integer=True, positive=True)
sequence_term = sequence_term.xreplace({sym: sym_})
sym = sym_
interval = Interval(lower_limit, upper_limit)
# Piecewise function handle
if sequence_term.is_Piecewise:
for func, cond in sequence_term.args:
# see if it represents something going to oo
if cond == True or cond.as_set().sup is S.Infinity:
s = Sum(func, (sym, lower_limit, upper_limit))
return s.is_convergent()
return S.true
### -------- Divergence test ----------- ###
try:
lim_val = limit_seq(sequence_term, sym)
if lim_val is not None and lim_val.is_zero is False:
return S.false
except NotImplementedError:
pass
try:
lim_val_abs = limit_seq(abs(sequence_term), sym)
if lim_val_abs is not None and lim_val_abs.is_zero is False:
return S.false
except NotImplementedError:
pass
order = O(sequence_term, (sym, S.Infinity))
### --------- p-series test (1/n**p) ---------- ###
p_series_test = order.expr.match(sym**p)
if p_series_test is not None:
if p_series_test[p] < -1:
return S.true
if p_series_test[p] >= -1:
return S.false
### ------------- comparison test ------------- ###
# 1/(n**p*log(n)**q*log(log(n))**r) comparison
n_log_test = (order.expr.match(1/(sym**p*log(1/sym)**q*log(-log(1/sym))**r)) or
order.expr.match(1/(sym**p*(-log(1/sym))**q*log(-log(1/sym))**r)))
if n_log_test is not None:
if (n_log_test[p] > 1 or
(n_log_test[p] == 1 and n_log_test[q] > 1) or
(n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)):
return S.true
return S.false
### ------------- Limit comparison test -----------###
# (1/n) comparison
try:
lim_comp = limit_seq(sym*sequence_term, sym)
if lim_comp is not None and lim_comp.is_number and lim_comp > 0:
return S.false
except NotImplementedError:
pass
### ----------- ratio test ---------------- ###
next_sequence_term = sequence_term.xreplace({sym: sym + 1})
from sympy.simplify.combsimp import combsimp
from sympy.simplify.powsimp import powsimp
ratio = combsimp(powsimp(next_sequence_term/sequence_term))
try:
lim_ratio = limit_seq(ratio, sym)
if lim_ratio is not None and lim_ratio.is_number:
if abs(lim_ratio) > 1:
return S.false
if abs(lim_ratio) < 1:
return S.true
except NotImplementedError:
lim_ratio = None
### ---------- Raabe's test -------------- ###
if lim_ratio == 1: # ratio test inconclusive
test_val = sym*(sequence_term/
sequence_term.subs(sym, sym + 1) - 1)
test_val = test_val.gammasimp()
try:
lim_val = limit_seq(test_val, sym)
if lim_val is not None and lim_val.is_number:
if lim_val > 1:
return S.true
if lim_val < 1:
return S.false
except NotImplementedError:
pass
### ----------- root test ---------------- ###
# lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
try:
lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym)
if lim_evaluated is not None and lim_evaluated.is_number:
if lim_evaluated < 1:
return S.true
if lim_evaluated > 1:
return S.false
except NotImplementedError:
pass
### ------------- alternating series test ----------- ###
dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q)
if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
return S.true
### ------------- integral test -------------- ###
check_interval = None
from sympy.solvers.solveset import solveset
maxima = solveset(sequence_term.diff(sym), sym, interval)
if not maxima:
check_interval = interval
elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
check_interval = Interval(maxima.sup, interval.sup)
if (check_interval is not None and
(is_decreasing(sequence_term, check_interval) or
is_decreasing(-sequence_term, check_interval))):
integral_val = Integral(
sequence_term, (sym, lower_limit, upper_limit))
try:
integral_val_evaluated = integral_val.doit()
if integral_val_evaluated.is_number:
return S(integral_val_evaluated.is_finite)
except NotImplementedError:
pass
### ----- Dirichlet and bounded times convergent tests ----- ###
# TODO
#
# Dirichlet_test
# https://en.wikipedia.org/wiki/Dirichlet%27s_test
#
# Bounded times convergent test
# It is based on comparison theorems for series.
# In particular, if the general term of a series can
# be written as a product of two terms a_n and b_n
# and if a_n is bounded and if Sum(b_n) is absolutely
# convergent, then the original series Sum(a_n * b_n)
# is absolutely convergent and so convergent.
#
# The following code can grows like 2**n where n is the
# number of args in order.expr
# Possibly combined with the potentially slow checks
# inside the loop, could make this test extremely slow
# for larger summation expressions.
if order.expr.is_Mul:
args = order.expr.args
argset = set(args)
### -------------- Dirichlet tests -------------- ###
m = Dummy('m', integer=True)
def _dirichlet_test(g_n):
try:
ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m)
if ing_val is not None and ing_val.is_finite:
return S.true
except NotImplementedError:
pass
### -------- bounded times convergent test ---------###
def _bounded_convergent_test(g1_n, g2_n):
try:
lim_val = limit_seq(g1_n, sym)
if lim_val is not None and (lim_val.is_finite or (
isinstance(lim_val, AccumulationBounds)
and (lim_val.max - lim_val.min).is_finite)):
if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent():
return S.true
except NotImplementedError:
pass
for n in range(1, len(argset)):
for a_tuple in itertools.combinations(args, n):
b_set = argset - set(a_tuple)
a_n = Mul(*a_tuple)
b_n = Mul(*b_set)
if is_decreasing(a_n, interval):
dirich = _dirichlet_test(b_n)
if dirich is not None:
return dirich
bc_test = _bounded_convergent_test(a_n, b_n)
if bc_test is not None:
return bc_test
_sym = self.limits[0][0]
sequence_term = sequence_term.xreplace({sym: _sym})
raise NotImplementedError("The algorithm to find the Sum convergence of %s "
"is not yet implemented" % (sequence_term))
def is_absolutely_convergent(self):
"""
Checks for the absolute convergence of an infinite series.
Same as checking convergence of absolute value of sequence_term of
an infinite series.
References
==========
.. [1] https://en.wikipedia.org/wiki/Absolute_convergence
Examples
========
>>> from sympy import Sum, Symbol, oo
>>> n = Symbol('n', integer=True)
>>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent()
False
>>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent()
True
See Also
========
Sum.is_convergent()
"""
return Sum(abs(self.function), self.limits).is_convergent()
def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True):
"""
Return an Euler-Maclaurin approximation of self, where m is the
number of leading terms to sum directly and n is the number of
terms in the tail.
With m = n = 0, this is simply the corresponding integral
plus a first-order endpoint correction.
Returns (s, e) where s is the Euler-Maclaurin approximation
and e is the estimated error (taken to be the magnitude of
the first omitted term in the tail):
>>> from sympy.abc import k, a, b
>>> from sympy import Sum
>>> Sum(1/k, (k, 2, 5)).doit().evalf()
1.28333333333333
>>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin()
>>> s
-log(2) + 7/20 + log(5)
>>> from sympy import sstr
>>> print(sstr((s.evalf(), e.evalf()), full_prec=True))
(1.26629073187415, 0.0175000000000000)
The endpoints may be symbolic:
>>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin()
>>> s
-log(a) + log(b) + 1/(2*b) + 1/(2*a)
>>> e
Abs(1/(12*b**2) - 1/(12*a**2))
If the function is a polynomial of degree at most 2n+1, the
Euler-Maclaurin formula becomes exact (and e = 0 is returned):
>>> Sum(k, (k, 2, b)).euler_maclaurin()
(b**2/2 + b/2 - 1, 0)
>>> Sum(k, (k, 2, b)).doit()
b**2/2 + b/2 - 1
With a nonzero eps specified, the summation is ended
as soon as the remainder term is less than the epsilon.
"""
m = int(m)
n = int(n)
f = self.function
if len(self.limits) != 1:
raise ValueError("More than 1 limit")
i, a, b = self.limits[0]
if (a > b) == True:
if a - b == 1:
return S.Zero, S.Zero
a, b = b + 1, a - 1
f = -f
s = S.Zero
if m:
if b.is_Integer and a.is_Integer:
m = min(m, b - a + 1)
if not eps or f.is_polynomial(i):
s = Add(*[f.subs(i, a + k) for k in range(m)])
else:
term = f.subs(i, a)
if term:
test = abs(term.evalf(3)) < eps
if test == True:
return s, abs(term)
elif not (test == False):
# a symbolic Relational class, can't go further
return term, S.Zero
s = term
for k in range(1, m):
term = f.subs(i, a + k)
if abs(term.evalf(3)) < eps and term != 0:
return s, abs(term)
s += term
if b - a + 1 == m:
return s, S.Zero
a += m
x = Dummy('x')
I = Integral(f.subs(i, x), (x, a, b))
if eval_integral:
I = I.doit()
s += I
def fpoint(expr):
if b is S.Infinity:
return expr.subs(i, a), 0
return expr.subs(i, a), expr.subs(i, b)
fa, fb = fpoint(f)
iterm = (fa + fb)/2
g = f.diff(i)
for k in range(1, n + 2):
ga, gb = fpoint(g)
term = bernoulli(2*k)/factorial(2*k)*(gb - ga)
if k > n:
break
if eps and term:
term_evalf = term.evalf(3)
if term_evalf is S.NaN:
return S.NaN, S.NaN
if abs(term_evalf) < eps:
break
s += term
g = g.diff(i, 2, simplify=False)
return s + iterm, abs(term)
def reverse_order(self, *indices):
"""
Reverse the order of a limit in a Sum.
Explanation
===========
``reverse_order(self, *indices)`` reverses some limits in the expression
``self`` which can be either a ``Sum`` or a ``Product``. The selectors in
the argument ``indices`` specify some indices whose limits get reversed.
These selectors are either variable names or numerical indices counted
starting from the inner-most limit tuple.
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y, a, b, c, d
>>> Sum(x, (x, 0, 3)).reverse_order(x)
Sum(-x, (x, 4, -1))
>>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y)
Sum(x*y, (x, 6, 0), (y, 7, -1))
>>> Sum(x, (x, a, b)).reverse_order(x)
Sum(-x, (x, b + 1, a - 1))
>>> Sum(x, (x, a, b)).reverse_order(0)
Sum(-x, (x, b + 1, a - 1))
While one should prefer variable names when specifying which limits
to reverse, the index counting notation comes in handy in case there
are several symbols with the same name.
>>> S = Sum(x**2, (x, a, b), (x, c, d))
>>> S
Sum(x**2, (x, a, b), (x, c, d))
>>> S0 = S.reverse_order(0)
>>> S0
Sum(-x**2, (x, b + 1, a - 1), (x, c, d))
>>> S1 = S0.reverse_order(1)
>>> S1
Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1))
Of course we can mix both notations:
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
See Also
========
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit,
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
"""
l_indices = list(indices)
for i, indx in enumerate(l_indices):
if not isinstance(indx, int):
l_indices[i] = self.index(indx)
e = 1
limits = []
for i, limit in enumerate(self.limits):
l = limit
if i in l_indices:
e = -e
l = (limit[0], limit[2] + 1, limit[1] - 1)
limits.append(l)
return Sum(e * self.function, *limits)
def _eval_rewrite_as_Product(self, *args, **kwargs):
from sympy.concrete.products import Product
if self.function.is_extended_real:
return log(Product(exp(self.function), *self.limits))
def summation(f, *symbols, **kwargs):
r"""
Compute the summation of f with respect to symbols.
Explanation
===========
The notation for symbols is similar to the notation used in Integral.
summation(f, (i, a, b)) computes the sum of f with respect to i from a to b,
i.e.,
::
b
____
\ `
summation(f, (i, a, b)) = ) f
/___,
i = a
If it cannot compute the sum, it returns an unevaluated Sum object.
Repeated sums can be computed by introducing additional symbols tuples::
Examples
========
>>> from sympy import summation, oo, symbols, log
>>> i, n, m = symbols('i n m', integer=True)
>>> summation(2*i - 1, (i, 1, n))
n**2
>>> summation(1/2**i, (i, 0, oo))
2
>>> summation(1/log(n)**n, (n, 2, oo))
Sum(log(n)**(-n), (n, 2, oo))
>>> summation(i, (i, 0, n), (n, 0, m))
m**3/6 + m**2/2 + m/3
>>> from sympy.abc import x
>>> from sympy import factorial
>>> summation(x**n/factorial(n), (n, 0, oo))
exp(x)
See Also
========
Sum
Product, sympy.concrete.products.product
"""
return Sum(f, *symbols, **kwargs).doit(deep=False)
def telescopic_direct(L, R, n, limits):
"""
Returns the direct summation of the terms of a telescopic sum
Explanation
===========
L is the term with lower index
R is the term with higher index
n difference between the indexes of L and R
Examples
========
>>> from sympy.concrete.summations import telescopic_direct
>>> from sympy.abc import k, a, b
>>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b))
-1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a
"""
(i, a, b) = limits
return Add(*[L.subs(i, a + m) + R.subs(i, b - m) for m in range(n)])
def telescopic(L, R, limits):
'''
Tries to perform the summation using the telescopic property.
Return None if not possible.
'''
(i, a, b) = limits
if L.is_Add or R.is_Add:
return None
# We want to solve(L.subs(i, i + m) + R, m)
# First we try a simple match since this does things that
# solve doesn't do, e.g. solve(cos(k+m)-cos(k), m) gives
# a more complicated solution than m == 0.
k = Wild("k")
sol = (-R).match(L.subs(i, i + k))
s = None
if sol and k in sol:
s = sol[k]
if not (s.is_Integer and L.subs(i, i + s) + R == 0):
# invalid match or match didn't work
s = None
# But there are things that match doesn't do that solve
# can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1
if s is None:
m = Dummy('m')
try:
from sympy.solvers.solvers import solve
sol = solve(L.subs(i, i + m) + R, m) or []
except NotImplementedError:
return None
sol = [si for si in sol if si.is_Integer and
(L.subs(i, i + si) + R).expand().is_zero]
if len(sol) != 1:
return None
s = sol[0]
if s < 0:
return telescopic_direct(R, L, abs(s), (i, a, b))
elif s > 0:
return telescopic_direct(L, R, s, (i, a, b))
def eval_sum(f, limits):
(i, a, b) = limits
if f.is_zero:
return S.Zero
if i not in f.free_symbols:
return f*(b - a + 1)
if a == b:
return f.subs(i, a)
if isinstance(f, Piecewise):
if not any(i in arg.args[1].free_symbols for arg in f.args):
# Piecewise conditions do not depend on the dummy summation variable,
# therefore we can fold: Sum(Piecewise((e, c), ...), limits)
# --> Piecewise((Sum(e, limits), c), ...)
newargs = []
for arg in f.args:
newexpr = eval_sum(arg.expr, limits)
if newexpr is None:
return None
newargs.append((newexpr, arg.cond))
return f.func(*newargs)
if f.has(KroneckerDelta):
from .delta import deltasummation, _has_simple_delta
f = f.replace(
lambda x: isinstance(x, Sum),
lambda x: x.factor()
)
if _has_simple_delta(f, limits[0]):
return deltasummation(f, limits)
dif = b - a
definite = dif.is_Integer
# Doing it directly may be faster if there are very few terms.
if definite and (dif < 100):
return eval_sum_direct(f, (i, a, b))
if isinstance(f, Piecewise):
return None
# Try to do it symbolically. Even when the number of terms is
# known, this can save time when b-a is big.
value = eval_sum_symbolic(f.expand(), (i, a, b))
if value is not None:
return value
# Do it directly
if definite:
return eval_sum_direct(f, (i, a, b))
def eval_sum_direct(expr, limits):
"""
Evaluate expression directly, but perform some simple checks first
to possibly result in a smaller expression and faster execution.
"""
(i, a, b) = limits
dif = b - a
# Linearity
if expr.is_Mul:
# Try factor out everything not including i
without_i, with_i = expr.as_independent(i)
if without_i != 1:
s = eval_sum_direct(with_i, (i, a, b))
if s:
r = without_i*s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = expr.as_two_terms()
if not L.has(i):
sR = eval_sum_direct(R, (i, a, b))
if sR:
return L*sR
if not R.has(i):
sL = eval_sum_direct(L, (i, a, b))
if sL:
return sL*R
# do this whether its an Add or Mul
# e.g. apart(1/(25*i**2 + 45*i + 14)) and
# apart(1/((5*i + 2)*(5*i + 7))) ->
# -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
try:
expr = apart(expr, i) # see if it becomes an Add
except PolynomialError:
pass
if expr.is_Add:
# Try factor out everything not including i
without_i, with_i = expr.as_independent(i)
if without_i != 0:
s = eval_sum_direct(with_i, (i, a, b))
if s:
r = without_i*(dif + 1) + s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = expr.as_two_terms()
lsum = eval_sum_direct(L, (i, a, b))
rsum = eval_sum_direct(R, (i, a, b))
if None not in (lsum, rsum):
r = lsum + rsum
if r is not S.NaN:
return r
return Add(*[expr.subs(i, a + j) for j in range(dif + 1)])
def eval_sum_symbolic(f, limits):
f_orig = f
(i, a, b) = limits
if not f.has(i):
return f*(b - a + 1)
# Linearity
if f.is_Mul:
# Try factor out everything not including i
without_i, with_i = f.as_independent(i)
if without_i != 1:
s = eval_sum_symbolic(with_i, (i, a, b))
if s:
r = without_i*s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = f.as_two_terms()
if not L.has(i):
sR = eval_sum_symbolic(R, (i, a, b))
if sR:
return L*sR
if not R.has(i):
sL = eval_sum_symbolic(L, (i, a, b))
if sL:
return sL*R
# do this whether its an Add or Mul
# e.g. apart(1/(25*i**2 + 45*i + 14)) and
# apart(1/((5*i + 2)*(5*i + 7))) ->
# -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
try:
f = apart(f, i)
except PolynomialError:
pass
if f.is_Add:
L, R = f.as_two_terms()
lrsum = telescopic(L, R, (i, a, b))
if lrsum:
return lrsum
# Try factor out everything not including i
without_i, with_i = f.as_independent(i)
if without_i != 0:
s = eval_sum_symbolic(with_i, (i, a, b))
if s:
r = without_i*(b - a + 1) + s
if r is not S.NaN:
return r
else:
# Try term by term
lsum = eval_sum_symbolic(L, (i, a, b))
rsum = eval_sum_symbolic(R, (i, a, b))
if None not in (lsum, rsum):
r = lsum + rsum
if r is not S.NaN:
return r
# Polynomial terms with Faulhaber's formula
n = Wild('n')
result = f.match(i**n)
if result is not None:
n = result[n]
if n.is_Integer:
if n >= 0:
if (b is S.Infinity and a is not S.NegativeInfinity) or \
(a is S.NegativeInfinity and b is not S.Infinity):
return S.Infinity
return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand()
elif a.is_Integer and a >= 1:
if n == -1:
return harmonic(b) - harmonic(a - 1)
else:
return harmonic(b, abs(n)) - harmonic(a - 1, abs(n))
if not (a.has(S.Infinity, S.NegativeInfinity) or
b.has(S.Infinity, S.NegativeInfinity)):
# Geometric terms
c1 = Wild('c1', exclude=[i])
c2 = Wild('c2', exclude=[i])
c3 = Wild('c3', exclude=[i])
wexp = Wild('wexp')
# Here we first attempt powsimp on f for easier matching with the
# exponential pattern, and attempt expansion on the exponent for easier
# matching with the linear pattern.
e = f.powsimp().match(c1 ** wexp)
if e is not None:
e_exp = e.pop(wexp).expand().match(c2*i + c3)
if e_exp is not None:
e.update(e_exp)
p = (c1**c3).subs(e)
q = (c1**c2).subs(e)
r = p*(q**a - q**(b + 1))/(1 - q)
l = p*(b - a + 1)
return Piecewise((l, Eq(q, S.One)), (r, True))
r = gosper_sum(f, (i, a, b))
if isinstance(r, (Mul,Add)):
from sympy.simplify.radsimp import denom
from sympy.solvers.solvers import solve
non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols
den = denom(together(r))
den_sym = non_limit & den.free_symbols
args = []
for v in ordered(den_sym):
try:
s = solve(den, v)
m = Eq(v, s[0]) if s else S.false
if m != False:
args.append((Sum(f_orig.subs(*m.args), limits).doit(), m))
break
except NotImplementedError:
continue
args.append((r, True))
return Piecewise(*args)
if r not in (None, S.NaN):
return r
h = eval_sum_hyper(f_orig, (i, a, b))
if h is not None:
return h
r = eval_sum_residue(f_orig, (i, a, b))
if r is not None:
return r
factored = f_orig.factor()
if factored != f_orig:
return eval_sum_symbolic(factored, (i, a, b))
def _eval_sum_hyper(f, i, a):
""" Returns (res, cond). Sums from a to oo. """
if a != 0:
return _eval_sum_hyper(f.subs(i, i + a), i, 0)
if f.subs(i, 0) == 0:
from sympy.simplify.simplify import simplify
if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0:
return S.Zero, True
return _eval_sum_hyper(f.subs(i, i + 1), i, 0)
from sympy.simplify.simplify import hypersimp
hs = hypersimp(f, i)
if hs is None:
return None
if isinstance(hs, Float):
from sympy.simplify.simplify import nsimplify
hs = nsimplify(hs)
from sympy.simplify.combsimp import combsimp
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.radsimp import fraction
numer, denom = fraction(factor(hs))
top, topl = numer.as_coeff_mul(i)
bot, botl = denom.as_coeff_mul(i)
ab = [top, bot]
factors = [topl, botl]
params = [[], []]
for k in range(2):
for fac in factors[k]:
mul = 1
if fac.is_Pow:
mul = fac.exp
fac = fac.base
if not mul.is_Integer:
return None
p = Poly(fac, i)
if p.degree() != 1:
return None
m, n = p.all_coeffs()
ab[k] *= m**mul
params[k] += [n/m]*mul
# Add "1" to numerator parameters, to account for implicit n! in
# hypergeometric series.
ap = params[0] + [1]
bq = params[1]
x = ab[0]/ab[1]
h = hyper(ap, bq, x)
f = combsimp(f)
return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
def eval_sum_hyper(f, i_a_b):
i, a, b = i_a_b
if f.is_hypergeometric(i) is False:
return
if (b - a).is_Integer:
# We are never going to do better than doing the sum in the obvious way
return None
old_sum = Sum(f, (i, a, b))
if b != S.Infinity:
if a is S.NegativeInfinity:
res = _eval_sum_hyper(f.subs(i, -i), i, -b)
if res is not None:
return Piecewise(res, (old_sum, True))
else:
n_illegal = lambda x: sum(x.count(_) for _ in _illegal)
had = n_illegal(f)
# check that no extra illegals are introduced
res1 = _eval_sum_hyper(f, i, a)
if res1 is None or n_illegal(res1) > had:
return
res2 = _eval_sum_hyper(f, i, b + 1)
if res2 is None or n_illegal(res2) > had:
return
(res1, cond1), (res2, cond2) = res1, res2
cond = And(cond1, cond2)
if cond == False:
return None
return Piecewise((res1 - res2, cond), (old_sum, True))
if a is S.NegativeInfinity:
res1 = _eval_sum_hyper(f.subs(i, -i), i, 1)
res2 = _eval_sum_hyper(f, i, 0)
if res1 is None or res2 is None:
return None
res1, cond1 = res1
res2, cond2 = res2
cond = And(cond1, cond2)
if cond == False or cond.as_set() == S.EmptySet:
return None
return Piecewise((res1 + res2, cond), (old_sum, True))
# Now b == oo, a != -oo
res = _eval_sum_hyper(f, i, a)
if res is not None:
r, c = res
if c == False:
if r.is_number:
f = f.subs(i, Dummy('i', integer=True, positive=True) + a)
if f.is_positive or f.is_zero:
return S.Infinity
elif f.is_negative:
return S.NegativeInfinity
return None
return Piecewise(res, (old_sum, True))
def eval_sum_residue(f, i_a_b):
r"""Compute the infinite summation with residues
Notes
=====
If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$,
some infinite summations can be computed by the following residue
evaluations.
.. math::
\sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} =
-\pi \sum_{\alpha|g(\alpha)=0}
\text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha)
.. math::
\sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} =
-\pi \sum_{\alpha|g(\alpha)=0}
\text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha)
Examples
========
>>> from sympy import Sum, oo, Symbol
>>> x = Symbol('x')
Doubly infinite series of rational functions.
>>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit()
pi/tanh(pi)
Doubly infinite alternating series of rational functions.
>>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit()
pi/sinh(pi)
Infinite series of even rational functions.
>>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit()
1/2 + pi/(2*tanh(pi))
Infinite series of alternating even rational functions.
>>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit()
pi/(2*sinh(pi)) + 1/2
This also have heuristics to transform arbitrarily shifted summand or
arbitrarily shifted summation range to the canonical problem the
formula can handle.
>>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit()
1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit()
1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit()
-1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit()
-1 + pi/(2*tanh(pi))
References
==========
.. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf
.. [#] Asmar N.H., Grafakos L. (2018) Residue Theory.
In: Complex Analysis with Applications.
Undergraduate Texts in Mathematics. Springer, Cham.
https://doi.org/10.1007/978-3-319-94063-2_5
"""
i, a, b = i_a_b
def is_even_function(numer, denom):
"""Test if the rational function is an even function"""
numer_even = all(i % 2 == 0 for (i,) in numer.monoms())
denom_even = all(i % 2 == 0 for (i,) in denom.monoms())
numer_odd = all(i % 2 == 1 for (i,) in numer.monoms())
denom_odd = all(i % 2 == 1 for (i,) in denom.monoms())
return (numer_even and denom_even) or (numer_odd and denom_odd)
def match_rational(f, i):
numer, denom = f.as_numer_denom()
try:
(numer, denom), opt = parallel_poly_from_expr((numer, denom), i)
except (PolificationFailed, PolynomialError):
return None
return numer, denom
def get_poles(denom):
roots = denom.sqf_part().all_roots()
roots = sift(roots, lambda x: x.is_integer)
if None in roots:
return None
int_roots, nonint_roots = roots[True], roots[False]
return int_roots, nonint_roots
def get_shift(denom):
n = denom.degree(i)
a = denom.coeff_monomial(i**n)
b = denom.coeff_monomial(i**(n-1))
shift = - b / a / n
return shift
#Need a dummy symbol with no assumptions set for get_residue_factor
z = Dummy('z')
def get_residue_factor(numer, denom, alternating):
residue_factor = (numer.as_expr() / denom.as_expr()).subs(i, z)
if not alternating:
residue_factor *= cot(S.Pi * z)
else:
residue_factor *= csc(S.Pi * z)
return residue_factor
# We don't know how to deal with symbolic constants in summand
if f.free_symbols - set([i]):
return None
if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)):
return None
if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)):
return None
# Quick exit heuristic for the sums which doesn't have infinite range
if a != S.NegativeInfinity and b != S.Infinity:
return None
match = match_rational(f, i)
if match:
alternating = False
numer, denom = match
else:
match = match_rational(f / S.NegativeOne**i, i)
if match:
alternating = True
numer, denom = match
else:
return None
if denom.degree(i) - numer.degree(i) < 2:
return None
if (a, b) == (S.NegativeInfinity, S.Infinity):
poles = get_poles(denom)
if poles is None:
return None
int_roots, nonint_roots = poles
if int_roots:
return None
residue_factor = get_residue_factor(numer, denom, alternating)
residues = [residue(residue_factor, z, root) for root in nonint_roots]
return -S.Pi * sum(residues)
if not (a.is_finite and b is S.Infinity):
return None
if not is_even_function(numer, denom):
# Try shifting summation and check if the summand can be made
# and even function from the origin.
# Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s))
shift = get_shift(denom)
if not shift.is_Integer:
return None
if shift == 0:
return None
numer = numer.shift(shift)
denom = denom.shift(shift)
if not is_even_function(numer, denom):
return None
if alternating:
f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr())
else:
f = numer.as_expr() / denom.as_expr()
return eval_sum_residue(f, (i, a-shift, b-shift))
poles = get_poles(denom)
if poles is None:
return None
int_roots, nonint_roots = poles
if int_roots:
int_roots = [int(root) for root in int_roots]
int_roots_max = max(int_roots)
int_roots_min = min(int_roots)
# Integer valued poles must be next to each other
# and also symmetric from origin (Because the function is even)
if not len(int_roots) == int_roots_max - int_roots_min + 1:
return None
# Check whether the summation indices contain poles
if a <= max(int_roots):
return None
residue_factor = get_residue_factor(numer, denom, alternating)
residues = [residue(residue_factor, z, root) for root in int_roots + nonint_roots]
full_sum = -S.Pi * sum(residues)
if not int_roots:
# Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation
# at the origin.
half_sum = (full_sum + f.xreplace({i: 0})) / 2
# Add and subtract extraneous evaluations
extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)]
extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))]
result = half_sum + sum(extraneous_neg) - sum(extraneous_pos)
return result
# Compute Sum(f, (i, min(poles) + 1, oo))
half_sum = full_sum / 2
# Subtract extraneous evaluations
extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))]
result = half_sum - sum(extraneous)
return result
def _eval_matrix_sum(expression):
f = expression.function
for n, limit in enumerate(expression.limits):
i, a, b = limit
dif = b - a
if dif.is_Integer:
if (dif < 0) == True:
a, b = b + 1, a - 1
f = -f
newf = eval_sum_direct(f, (i, a, b))
if newf is not None:
return newf.doit()
def _dummy_with_inherited_properties_concrete(limits):
"""
Return a Dummy symbol that inherits as many assumptions as possible
from the provided symbol and limits.
If the symbol already has all True assumption shared by the limits
then return None.
"""
x, a, b = limits
l = [a, b]
assumptions_to_consider = ['extended_nonnegative', 'nonnegative',
'extended_nonpositive', 'nonpositive',
'extended_positive', 'positive',
'extended_negative', 'negative',
'integer', 'rational', 'finite',
'zero', 'real', 'extended_real']
assumptions_to_keep = {}
assumptions_to_add = {}
for assum in assumptions_to_consider:
assum_true = x._assumptions.get(assum, None)
if assum_true:
assumptions_to_keep[assum] = True
elif all(getattr(i, 'is_' + assum) for i in l):
assumptions_to_add[assum] = True
if assumptions_to_add:
assumptions_to_keep.update(assumptions_to_add)
return Dummy('d', **assumptions_to_keep)
|
784d3e7fba1c0b10e653330eadfcc297ad96c660e7c275a51950797612c21244 | """
Limits
======
Implemented according to the PhD thesis
http://www.cybertester.com/data/gruntz.pdf, which contains very thorough
descriptions of the algorithm including many examples. We summarize here
the gist of it.
All functions are sorted according to how rapidly varying they are at
infinity using the following rules. Any two functions f and g can be
compared using the properties of L:
L=lim log|f(x)| / log|g(x)| (for x -> oo)
We define >, < ~ according to::
1. f > g .... L=+-oo
we say that:
- f is greater than any power of g
- f is more rapidly varying than g
- f goes to infinity/zero faster than g
2. f < g .... L=0
we say that:
- f is lower than any power of g
3. f ~ g .... L!=0, +-oo
we say that:
- both f and g are bounded from above and below by suitable integral
powers of the other
Examples
========
::
2 < x < exp(x) < exp(x**2) < exp(exp(x))
2 ~ 3 ~ -5
x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x
exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x))
f ~ 1/f
So we can divide all the functions into comparability classes (x and x^2
belong to one class, exp(x) and exp(-x) belong to some other class). In
principle, we could compare any two functions, but in our algorithm, we
do not compare anything below the class 2~3~-5 (for example log(x) is
below this), so we set 2~3~-5 as the lowest comparability class.
Given the function f, we find the list of most rapidly varying (mrv set)
subexpressions of it. This list belongs to the same comparability class.
Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an
element "w" (either from the list or a new one) from the same
comparability class which goes to zero at infinity. In our example we
set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We
rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it
into f. Then we expand f into a series in w::
f = c0*w^e0 + c1*w^e1 + ... + O(w^en), where e0<e1<...<en, c0!=0
but for x->oo, lim f = lim c0*w^e0, because all the other terms go to zero,
because w goes to zero faster than the ci and ei. So::
for e0>0, lim f = 0
for e0<0, lim f = +-oo (the sign depends on the sign of c0)
for e0=0, lim f = lim c0
We need to recursively compute limits at several places of the algorithm, but
as is shown in the PhD thesis, it always finishes.
Important functions from the implementation:
compare(a, b, x) compares "a" and "b" by computing the limit L.
mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e"
rewrite(e, Omega, x, wsym) rewrites "e" in terms of w
leadterm(f, x) returns the lowest power term in the series of f
mrv_leadterm(e, x) returns the lead term (c0, e0) for e
limitinf(e, x) computes lim e (for x->oo)
limit(e, z, z0) computes any limit by converting it to the case x->oo
All the functions are really simple and straightforward except
rewrite(), which is the most difficult/complex part of the algorithm.
When the algorithm fails, the bugs are usually in the series expansion
(i.e. in SymPy) or in rewrite.
This code is almost exact rewrite of the Maple code inside the Gruntz
thesis.
Debugging
---------
Because the gruntz algorithm is highly recursive, it's difficult to
figure out what went wrong inside a debugger. Instead, turn on nice
debug prints by defining the environment variable SYMPY_DEBUG. For
example:
[user@localhost]: SYMPY_DEBUG=True ./bin/isympy
In [1]: limit(sin(x)/x, x, 0)
limitinf(_x*sin(1/_x), _x) = 1
+-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0)
| +-mrv(_x*sin(1/_x), _x) = set([_x])
| | +-mrv(_x, _x) = set([_x])
| | +-mrv(sin(1/_x), _x) = set([_x])
| | +-mrv(1/_x, _x) = set([_x])
| | +-mrv(_x, _x) = set([_x])
| +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0)
| +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x)
| +-sign(_x, _x) = 1
| +-mrv_leadterm(1, _x) = (1, 0)
+-sign(0, _x) = 0
+-limitinf(1, _x) = 1
And check manually which line is wrong. Then go to the source code and
debug this function to figure out the exact problem.
"""
from functools import reduce
from sympy.core import Basic, S, Mul, PoleError, expand_mul
from sympy.core.cache import cacheit
from sympy.core.numbers import ilcm, I, oo
from sympy.core.symbol import Dummy, Wild
from sympy.core.traversal import bottom_up
from sympy.functions import log, exp, sign as _sign
from sympy.series.order import Order
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.misc import debug_decorator as debug
from sympy.utilities.timeutils import timethis
timeit = timethis('gruntz')
def compare(a, b, x):
"""Returns "<" if a<b, "=" for a == b, ">" for a>b"""
# log(exp(...)) must always be simplified here for termination
la, lb = log(a), log(b)
if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)):
la = a.exp
if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)):
lb = b.exp
c = limitinf(la/lb, x)
if c == 0:
return "<"
elif c.is_infinite:
return ">"
else:
return "="
class SubsSet(dict):
"""
Stores (expr, dummy) pairs, and how to rewrite expr-s.
Explanation
===========
The gruntz algorithm needs to rewrite certain expressions in term of a new
variable w. We cannot use subs, because it is just too smart for us. For
example::
> Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
> O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
> e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
> e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
-1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))
is really not what we want!
So we do it the hard way and keep track of all the things we potentially
want to substitute by dummy variables. Consider the expression::
exp(x - exp(-x)) + exp(x) + x.
The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
We introduce corresponding dummy variables d1, d2, d3 and rewrite::
d3 + d1 + x.
This class first of all keeps track of the mapping expr->variable, i.e.
will at this stage be a dictionary::
{exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.
[It turns out to be more convenient this way round.]
But sometimes expressions in the mrv set have other expressions from the
mrv set as subexpressions, and we need to keep track of that as well. In
this case, d3 is really exp(x - d2), so rewrites at this stage is::
{d3: exp(x-d2)}.
The function rewrite uses all this information to correctly rewrite our
expression in terms of w. In this case w can be chosen to be exp(-x),
i.e. d2. The correct rewriting then is::
exp(-w)/w + 1/w + x.
"""
def __init__(self):
self.rewrites = {}
def __repr__(self):
return super().__repr__() + ', ' + self.rewrites.__repr__()
def __getitem__(self, key):
if key not in self:
self[key] = Dummy()
return dict.__getitem__(self, key)
def do_subs(self, e):
"""Substitute the variables with expressions"""
for expr, var in self.items():
e = e.xreplace({var: expr})
return e
def meets(self, s2):
"""Tell whether or not self and s2 have non-empty intersection"""
return set(self.keys()).intersection(list(s2.keys())) != set()
def union(self, s2, exps=None):
"""Compute the union of self and s2, adjusting exps"""
res = self.copy()
tr = {}
for expr, var in s2.items():
if expr in self:
if exps:
exps = exps.xreplace({var: res[expr]})
tr[var] = res[expr]
else:
res[expr] = var
for var, rewr in s2.rewrites.items():
res.rewrites[var] = rewr.xreplace(tr)
return res, exps
def copy(self):
"""Create a shallow copy of SubsSet"""
r = SubsSet()
r.rewrites = self.rewrites.copy()
for expr, var in self.items():
r[expr] = var
return r
@debug
def mrv(e, x):
"""Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
and e rewritten in terms of these"""
from sympy.simplify.powsimp import powsimp
e = powsimp(e, deep=True, combine='exp')
if not isinstance(e, Basic):
raise TypeError("e should be an instance of Basic")
if not e.has(x):
return SubsSet(), e
elif e == x:
s = SubsSet()
return s, s[x]
elif e.is_Mul or e.is_Add:
i, d = e.as_independent(x) # throw away x-independent terms
if d.func != e.func:
s, expr = mrv(d, x)
return s, e.func(i, expr)
a, b = d.as_two_terms()
s1, e1 = mrv(a, x)
s2, e2 = mrv(b, x)
return mrv_max1(s1, s2, e.func(i, e1, e2), x)
elif e.is_Pow and e.base != S.Exp1:
e1 = S.One
while e.is_Pow:
b1 = e.base
e1 *= e.exp
e = b1
if b1 == 1:
return SubsSet(), b1
if e1.has(x):
base_lim = limitinf(b1, x)
if base_lim is S.One:
return mrv(exp(e1 * (b1 - 1)), x)
return mrv(exp(e1 * log(b1)), x)
else:
s, expr = mrv(b1, x)
return s, expr**e1
elif isinstance(e, log):
s, expr = mrv(e.args[0], x)
return s, log(expr)
elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1):
# We know from the theory of this algorithm that exp(log(...)) may always
# be simplified here, and doing so is vital for termination.
if isinstance(e.exp, log):
return mrv(e.exp.args[0], x)
# if a product has an infinite factor the result will be
# infinite if there is no zero, otherwise NaN; here, we
# consider the result infinite if any factor is infinite
li = limitinf(e.exp, x)
if any(_.is_infinite for _ in Mul.make_args(li)):
s1 = SubsSet()
e1 = s1[e]
s2, e2 = mrv(e.exp, x)
su = s1.union(s2)[0]
su.rewrites[e1] = exp(e2)
return mrv_max3(s1, e1, s2, exp(e2), su, e1, x)
else:
s, expr = mrv(e.exp, x)
return s, exp(expr)
elif e.is_Function:
l = [mrv(a, x) for a in e.args]
l2 = [s for (s, _) in l if s != SubsSet()]
if len(l2) != 1:
# e.g. something like BesselJ(x, x)
raise NotImplementedError("MRV set computation for functions in"
" several variables not implemented.")
s, ss = l2[0], SubsSet()
args = [ss.do_subs(x[1]) for x in l]
return s, e.func(*args)
elif e.is_Derivative:
raise NotImplementedError("MRV set computation for derviatives"
" not implemented yet.")
raise NotImplementedError(
"Don't know how to calculate the mrv of '%s'" % e)
def mrv_max3(f, expsf, g, expsg, union, expsboth, x):
"""
Computes the maximum of two sets of expressions f and g, which
are in the same comparability class, i.e. max() compares (two elements of)
f and g and returns either (f, expsf) [if f is larger], (g, expsg)
[if g is larger] or (union, expsboth) [if f, g are of the same class].
"""
if not isinstance(f, SubsSet):
raise TypeError("f should be an instance of SubsSet")
if not isinstance(g, SubsSet):
raise TypeError("g should be an instance of SubsSet")
if f == SubsSet():
return g, expsg
elif g == SubsSet():
return f, expsf
elif f.meets(g):
return union, expsboth
c = compare(list(f.keys())[0], list(g.keys())[0], x)
if c == ">":
return f, expsf
elif c == "<":
return g, expsg
else:
if c != "=":
raise ValueError("c should be =")
return union, expsboth
def mrv_max1(f, g, exps, x):
"""Computes the maximum of two sets of expressions f and g, which
are in the same comparability class, i.e. mrv_max1() compares (two elements of)
f and g and returns the set, which is in the higher comparability class
of the union of both, if they have the same order of variation.
Also returns exps, with the appropriate substitutions made.
"""
u, b = f.union(g, exps)
return mrv_max3(f, g.do_subs(exps), g, f.do_subs(exps),
u, b, x)
@debug
@cacheit
@timeit
def sign(e, x):
"""
Returns a sign of an expression e(x) for x->oo.
::
e > 0 for x sufficiently large ... 1
e == 0 for x sufficiently large ... 0
e < 0 for x sufficiently large ... -1
The result of this function is currently undefined if e changes sign
arbitrarily often for arbitrarily large x (e.g. sin(x)).
Note that this returns zero only if e is *constantly* zero
for x sufficiently large. [If e is constant, of course, this is just
the same thing as the sign of e.]
"""
if not isinstance(e, Basic):
raise TypeError("e should be an instance of Basic")
if e.is_positive:
return 1
elif e.is_negative:
return -1
elif e.is_zero:
return 0
elif not e.has(x):
from sympy.simplify import logcombine
e = logcombine(e)
return _sign(e)
elif e == x:
return 1
elif e.is_Mul:
a, b = e.as_two_terms()
sa = sign(a, x)
if not sa:
return 0
return sa * sign(b, x)
elif isinstance(e, exp):
return 1
elif e.is_Pow:
if e.base == S.Exp1:
return 1
s = sign(e.base, x)
if s == 1:
return 1
if e.exp.is_Integer:
return s**e.exp
elif isinstance(e, log):
return sign(e.args[0] - 1, x)
# if all else fails, do it the hard way
c0, e0 = mrv_leadterm(e, x)
return sign(c0, x)
@debug
@timeit
@cacheit
def limitinf(e, x):
"""Limit e(x) for x-> oo."""
# rewrite e in terms of tractable functions only
old = e
if not e.has(x):
return e # e is a constant
from sympy.simplify.powsimp import powdenest
from sympy.calculus.util import AccumBounds
if e.has(Order):
e = e.expand().removeO()
if not x.is_positive or x.is_integer:
# We make sure that x.is_positive is True and x.is_integer is None
# so we get all the correct mathematical behavior from the expression.
# We need a fresh variable.
p = Dummy('p', positive=True)
e = e.subs(x, p)
x = p
e = e.rewrite('tractable', deep=True, limitvar=x)
e = powdenest(e)
if isinstance(e, AccumBounds):
if mrv_leadterm(e.min, x) != mrv_leadterm(e.max, x):
raise NotImplementedError
c0, e0 = mrv_leadterm(e.min, x)
else:
c0, e0 = mrv_leadterm(e, x)
sig = sign(e0, x)
if sig == 1:
return S.Zero # e0>0: lim f = 0
elif sig == -1: # e0<0: lim f = +-oo (the sign depends on the sign of c0)
if c0.match(I*Wild("a", exclude=[I])):
return c0*oo
s = sign(c0, x)
# the leading term shouldn't be 0:
if s == 0:
raise ValueError("Leading term should not be 0")
return s*oo
elif sig == 0:
if c0 == old:
c0 = c0.cancel()
return limitinf(c0, x) # e0=0: lim f = lim c0
else:
raise ValueError("{} could not be evaluated".format(sig))
def moveup2(s, x):
r = SubsSet()
for expr, var in s.items():
r[expr.xreplace({x: exp(x)})] = var
for var, expr in s.rewrites.items():
r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)})
return r
def moveup(l, x):
return [e.xreplace({x: exp(x)}) for e in l]
@debug
@timeit
def calculate_series(e, x, logx=None):
""" Calculates at least one term of the series of ``e`` in ``x``.
This is a place that fails most often, so it is in its own function.
"""
SymPyDeprecationWarning(
feature="calculate_series",
useinstead="series() with suitable n, or as_leading_term",
issue=21838,
deprecated_since_version="1.12"
).warn()
from sympy.simplify.powsimp import powdenest
for t in e.lseries(x, logx=logx):
# bottom_up function is required for a specific case - when e is
# -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p)
t = bottom_up(t, lambda w:
getattr(w, 'normal', lambda: w)())
# And the expression
# `(-sin(1/x) + sin((x + exp(x))*exp(-x)/x))*exp(x)`
# from the first test of test_gruntz_eval_special needs to
# be expanded. But other forms need to be have at least
# factor_terms applied. `factor` accomplishes both and is
# faster than using `factor_terms` for the gruntz suite. It
# does not appear that use of `cancel` is necessary.
# t = cancel(t, expand=False)
t = t.factor()
if t.has(exp) and t.has(log):
t = powdenest(t)
if not t.is_zero:
break
return t
@debug
@timeit
@cacheit
def mrv_leadterm(e, x):
"""Returns (c0, e0) for e."""
Omega = SubsSet()
if not e.has(x):
return (e, S.Zero)
if Omega == SubsSet():
Omega, exps = mrv(e, x)
if not Omega:
# e really does not depend on x after simplification
return exps, S.Zero
if x in Omega:
# move the whole omega up (exponentiate each term):
Omega_up = moveup2(Omega, x)
exps_up = moveup([exps], x)[0]
# NOTE: there is no need to move this down!
Omega = Omega_up
exps = exps_up
#
# The positive dummy, w, is used here so log(w*2) etc. will expand;
# a unique dummy is needed in this algorithm
#
# For limits of complex functions, the algorithm would have to be
# improved, or just find limits of Re and Im components separately.
#
w = Dummy("w", positive=True)
f, logw = rewrite(exps, Omega, x, w)
try:
lt = f.leadterm(w, logx=logw)
except (NotImplementedError, PoleError, ValueError):
n0 = 1
_series = Order(1)
incr = S.One
while _series.is_Order:
_series = f._eval_nseries(w, n=n0+incr, logx=logw)
incr *= 2
series = _series.expand().removeO()
try:
lt = series.leadterm(w, logx=logw)
except (NotImplementedError, PoleError, ValueError):
lt = f.as_coeff_exponent(w)
if lt[0].has(w):
base = f.as_base_exp()[0].as_coeff_exponent(w)
ex = f.as_base_exp()[1]
lt = (base[0]**ex, base[1]*ex)
return (lt[0].subs(log(w), logw), lt[1])
def build_expression_tree(Omega, rewrites):
r""" Helper function for rewrite.
We need to sort Omega (mrv set) so that we replace an expression before
we replace any expression in terms of which it has to be rewritten::
e1 ---> e2 ---> e3
\
-> e4
Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
To do this we assemble the nodes into a tree, and sort them by height.
This function builds the tree, rewrites then sorts the nodes.
"""
class Node:
def __init__(self):
self.before = []
self.expr = None
self.var = None
def ht(self):
return reduce(lambda x, y: x + y,
[x.ht() for x in self.before], 1)
nodes = {}
for expr, v in Omega:
n = Node()
n.var = v
n.expr = expr
nodes[v] = n
for _, v in Omega:
if v in rewrites:
n = nodes[v]
r = rewrites[v]
for _, v2 in Omega:
if r.has(v2):
n.before.append(nodes[v2])
return nodes
@debug
@timeit
def rewrite(e, Omega, x, wsym):
"""e(x) ... the function
Omega ... the mrv set
wsym ... the symbol which is going to be used for w
Returns the rewritten e in terms of w and log(w). See test_rewrite1()
for examples and correct results.
"""
from sympy import AccumBounds
if not isinstance(Omega, SubsSet):
raise TypeError("Omega should be an instance of SubsSet")
if len(Omega) == 0:
raise ValueError("Length cannot be 0")
# all items in Omega must be exponentials
for t in Omega.keys():
if not isinstance(t, exp):
raise ValueError("Value should be exp")
rewrites = Omega.rewrites
Omega = list(Omega.items())
nodes = build_expression_tree(Omega, rewrites)
Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
# make sure we know the sign of each exp() term; after the loop,
# g is going to be the "w" - the simplest one in the mrv set
for g, _ in Omega:
sig = sign(g.exp, x)
if sig != 1 and sig != -1 and not sig.has(AccumBounds):
raise NotImplementedError('Result depends on the sign of %s' % sig)
if sig == 1:
wsym = 1/wsym # if g goes to oo, substitute 1/w
# O2 is a list, which results by rewriting each item in Omega using "w"
O2 = []
denominators = []
for f, var in Omega:
c = limitinf(f.exp/g.exp, x)
if c.is_Rational:
denominators.append(c.q)
arg = f.exp
if var in rewrites:
if not isinstance(rewrites[var], exp):
raise ValueError("Value should be exp")
arg = rewrites[var].args[0]
O2.append((var, exp((arg - c*g.exp).expand())*wsym**c))
# Remember that Omega contains subexpressions of "e". So now we find
# them in "e" and substitute them for our rewriting, stored in O2
# the following powsimp is necessary to automatically combine exponentials,
# so that the .xreplace() below succeeds:
# TODO this should not be necessary
from sympy.simplify.powsimp import powsimp
f = powsimp(e, deep=True, combine='exp')
for a, b in O2:
f = f.xreplace({a: b})
for _, var in Omega:
assert not f.has(var)
# finally compute the logarithm of w (logw).
logw = g.exp
if sig == 1:
logw = -logw # log(w)->log(1/w)=-log(w)
# Some parts of SymPy have difficulty computing series expansions with
# non-integral exponents. The following heuristic improves the situation:
exponent = reduce(ilcm, denominators, 1)
f = f.subs({wsym: wsym**exponent})
logw /= exponent
# bottom_up function is required for a specific case - when f is
# -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p). No current simplification
# methods reduce this to 0 while not expanding polynomials.
f = bottom_up(f, lambda w: getattr(w, 'normal', lambda: w)())
f = expand_mul(f)
return f, logw
def gruntz(e, z, z0, dir="+"):
"""
Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
Explanation
===========
``z0`` can be any expression, including oo and -oo.
For ``dir="+"`` (default) it calculates the limit from the right
(z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
(oo or -oo), the dir argument does not matter.
This algorithm is fully described in the module docstring in the gruntz.py
file. It relies heavily on the series expansion. Most frequently, gruntz()
is only used if the faster limit() function (which uses heuristics) fails.
"""
if not z.is_symbol:
raise NotImplementedError("Second argument must be a Symbol")
# convert all limits to the limit z->oo; sign of z is handled in limitinf
r = None
if z0 in (oo, I*oo):
e0 = e
elif z0 in (-oo, -I*oo):
e0 = e.subs(z, -z)
else:
if str(dir) == "-":
e0 = e.subs(z, z0 - 1/z)
elif str(dir) == "+":
e0 = e.subs(z, z0 + 1/z)
else:
raise NotImplementedError("dir must be '+' or '-'")
r = limitinf(e0, z)
# This is a bit of a heuristic for nice results... we always rewrite
# tractable functions in terms of familiar intractable ones.
# It might be nicer to rewrite the exactly to what they were initially,
# but that would take some work to implement.
return r.rewrite('intractable', deep=True)
|
840672f803b6bacc0effd6d65f915738eb36bbf0c4c68031bf7404d06af7f46d | from sympy.calculus.accumulationbounds import AccumBounds
from sympy.core import S, Symbol, Add, sympify, Expr, PoleError, Mul
from sympy.core.exprtools import factor_terms
from sympy.core.numbers import Float, _illegal
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (Abs, sign, arg, re)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.special.gamma_functions import gamma
from sympy.polys import PolynomialError, factor
from sympy.series.order import Order
from .gruntz import gruntz
def limit(e, z, z0, dir="+"):
"""Computes the limit of ``e(z)`` at the point ``z0``.
Parameters
==========
e : expression, the limit of which is to be taken
z : symbol representing the variable in the limit.
Other symbols are treated as constants. Multivariate limits
are not supported.
z0 : the value toward which ``z`` tends. Can be any expression,
including ``oo`` and ``-oo``.
dir : string, optional (default: "+")
The limit is bi-directional if ``dir="+-"``, from the right
(z->z0+) if ``dir="+"``, and from the left (z->z0-) if
``dir="-"``. For infinite ``z0`` (``oo`` or ``-oo``), the ``dir``
argument is determined from the direction of the infinity
(i.e., ``dir="-"`` for ``oo``).
Examples
========
>>> from sympy import limit, sin, oo
>>> from sympy.abc import x
>>> limit(sin(x)/x, x, 0)
1
>>> limit(1/x, x, 0) # default dir='+'
oo
>>> limit(1/x, x, 0, dir="-")
-oo
>>> limit(1/x, x, 0, dir='+-')
zoo
>>> limit(1/x, x, oo)
0
Notes
=====
First we try some heuristics for easy and frequent cases like "x", "1/x",
"x**2" and similar, so that it's fast. For all other cases, we use the
Gruntz algorithm (see the gruntz() function).
See Also
========
limit_seq : returns the limit of a sequence.
"""
return Limit(e, z, z0, dir).doit(deep=False)
def heuristics(e, z, z0, dir):
"""Computes the limit of an expression term-wise.
Parameters are the same as for the ``limit`` function.
Works with the arguments of expression ``e`` one by one, computing
the limit of each and then combining the results. This approach
works only for simple limits, but it is fast.
"""
rv = None
if z0 is S.Infinity:
rv = limit(e.subs(z, 1/z), z, S.Zero, "+")
if isinstance(rv, Limit):
return
elif e.is_Mul or e.is_Add or e.is_Pow or e.is_Function:
r = []
from sympy.simplify.simplify import together
for a in e.args:
l = limit(a, z, z0, dir)
if l.has(S.Infinity) and l.is_finite is None:
if isinstance(e, Add):
m = factor_terms(e)
if not isinstance(m, Mul): # try together
m = together(m)
if not isinstance(m, Mul): # try factor if the previous methods failed
m = factor(e)
if isinstance(m, Mul):
return heuristics(m, z, z0, dir)
return
return
elif isinstance(l, Limit):
return
elif l is S.NaN:
return
else:
r.append(l)
if r:
rv = e.func(*r)
if rv is S.NaN and e.is_Mul and any(isinstance(rr, AccumBounds) for rr in r):
r2 = []
e2 = []
for ii, rval in enumerate(r):
if isinstance(rval, AccumBounds):
r2.append(rval)
else:
e2.append(e.args[ii])
if len(e2) > 0:
e3 = Mul(*e2).simplify()
l = limit(e3, z, z0, dir)
rv = l * Mul(*r2)
if rv is S.NaN:
try:
from sympy.simplify.ratsimp import ratsimp
rat_e = ratsimp(e)
except PolynomialError:
return
if rat_e is S.NaN or rat_e == e:
return
return limit(rat_e, z, z0, dir)
return rv
class Limit(Expr):
"""Represents an unevaluated limit.
Examples
========
>>> from sympy import Limit, sin
>>> from sympy.abc import x
>>> Limit(sin(x)/x, x, 0)
Limit(sin(x)/x, x, 0)
>>> Limit(1/x, x, 0, dir="-")
Limit(1/x, x, 0, dir='-')
"""
def __new__(cls, e, z, z0, dir="+"):
e = sympify(e)
z = sympify(z)
z0 = sympify(z0)
if z0 in (S.Infinity, S.ImaginaryUnit*S.Infinity):
dir = "-"
elif z0 in (S.NegativeInfinity, S.ImaginaryUnit*S.NegativeInfinity):
dir = "+"
if(z0.has(z)):
raise NotImplementedError("Limits approaching a variable point are"
" not supported (%s -> %s)" % (z, z0))
if isinstance(dir, str):
dir = Symbol(dir)
elif not isinstance(dir, Symbol):
raise TypeError("direction must be of type basestring or "
"Symbol, not %s" % type(dir))
if str(dir) not in ('+', '-', '+-'):
raise ValueError("direction must be one of '+', '-' "
"or '+-', not %s" % dir)
obj = Expr.__new__(cls)
obj._args = (e, z, z0, dir)
return obj
@property
def free_symbols(self):
e = self.args[0]
isyms = e.free_symbols
isyms.difference_update(self.args[1].free_symbols)
isyms.update(self.args[2].free_symbols)
return isyms
def pow_heuristics(self, e):
_, z, z0, _ = self.args
b1, e1 = e.base, e.exp
if not b1.has(z):
res = limit(e1*log(b1), z, z0)
return exp(res)
ex_lim = limit(e1, z, z0)
base_lim = limit(b1, z, z0)
if base_lim is S.One:
if ex_lim in (S.Infinity, S.NegativeInfinity):
res = limit(e1*(b1 - 1), z, z0)
return exp(res)
if base_lim is S.NegativeInfinity and ex_lim is S.Infinity:
return S.ComplexInfinity
def doit(self, **hints):
"""Evaluates the limit.
Parameters
==========
deep : bool, optional (default: True)
Invoke the ``doit`` method of the expressions involved before
taking the limit.
hints : optional keyword arguments
To be passed to ``doit`` methods; only used if deep is True.
"""
e, z, z0, dir = self.args
if str(dir) == '+-':
r = limit(e, z, z0, dir='+')
l = limit(e, z, z0, dir='-')
if isinstance(r, Limit) and isinstance(l, Limit):
if r.args[0] == l.args[0]:
return self
if r == l:
return l
if r.is_infinite and l.is_infinite:
return S.ComplexInfinity
raise ValueError("The limit does not exist since "
"left hand limit = %s and right hand limit = %s"
% (l, r))
if z0 is S.ComplexInfinity:
raise NotImplementedError("Limits at complex "
"infinity are not implemented")
if z0.is_infinite:
cdir = sign(z0)
cdir = cdir/abs(cdir)
e = e.subs(z, cdir*z)
dir = "-"
z0 = S.Infinity
if hints.get('deep', True):
e = e.doit(**hints)
z = z.doit(**hints)
z0 = z0.doit(**hints)
if e == z:
return z0
if not e.has(z):
return e
if z0 is S.NaN:
return S.NaN
if e.has(*_illegal):
return self
if e.is_Order:
return Order(limit(e.expr, z, z0), *e.args[1:])
cdir = 0
if str(dir) == "+":
cdir = 1
elif str(dir) == "-":
cdir = -1
def set_signs(expr):
if not expr.args:
return expr
newargs = tuple(set_signs(arg) for arg in expr.args)
if newargs != expr.args:
expr = expr.func(*newargs)
abs_flag = isinstance(expr, Abs)
arg_flag = isinstance(expr, arg)
sign_flag = isinstance(expr, sign)
if abs_flag or sign_flag or arg_flag:
sig = limit(expr.args[0], z, z0, dir)
if sig.is_zero:
sig = limit(1/expr.args[0], z, z0, dir)
if sig.is_extended_real:
if (sig < 0) == True:
return (-expr.args[0] if abs_flag else
S.NegativeOne if sign_flag else S.Pi)
elif (sig > 0) == True:
return (expr.args[0] if abs_flag else
S.One if sign_flag else S.Zero)
return expr
if e.has(Float):
# Convert floats like 0.5 to exact SymPy numbers like S.Half, to
# prevent rounding errors which can lead to unexpected execution
# of conditional blocks that work on comparisons
# Also see comments in https://github.com/sympy/sympy/issues/19453
from sympy.simplify.simplify import nsimplify
e = nsimplify(e)
e = set_signs(e)
if e.is_meromorphic(z, z0):
if z0 is S.Infinity:
newe = e.subs(z, 1/z)
# cdir changes sign as oo- should become 0+
cdir = -cdir
else:
newe = e.subs(z, z + z0)
try:
coeff, ex = newe.leadterm(z, cdir=cdir)
except ValueError:
pass
else:
if ex > 0:
return S.Zero
elif ex == 0:
return coeff
if cdir == 1 or not(int(ex) & 1):
return S.Infinity*sign(coeff)
elif cdir == -1:
return S.NegativeInfinity*sign(coeff)
else:
return S.ComplexInfinity
if z0 is S.Infinity:
if e.is_Mul:
e = factor_terms(e)
newe = e.subs(z, 1/z)
# cdir changes sign as oo- should become 0+
cdir = -cdir
else:
newe = e.subs(z, z + z0)
try:
coeff, ex = newe.leadterm(z, cdir=cdir)
except (ValueError, NotImplementedError, PoleError):
# The NotImplementedError catching is for custom functions
from sympy.simplify.powsimp import powsimp
e = powsimp(e)
if e.is_Pow:
r = self.pow_heuristics(e)
if r is not None:
return r
try:
coeff = newe.as_leading_term(z, cdir=cdir)
if coeff != newe and coeff.has(exp):
return gruntz(coeff, z, 0, "-" if re(cdir).is_negative else "+")
except (ValueError, NotImplementedError, PoleError):
pass
else:
if isinstance(coeff, AccumBounds) and ex == S.Zero:
return coeff
if coeff.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
return self
if not coeff.has(z):
if ex.is_positive:
return S.Zero
elif ex == 0:
return coeff
elif ex.is_negative:
if ex.is_integer:
if cdir == 1 or ex.is_even:
return S.Infinity*sign(coeff)
elif cdir == -1:
return S.NegativeInfinity*sign(coeff)
else:
return S.ComplexInfinity
else:
if cdir == 1:
return S.Infinity*sign(coeff)
elif cdir == -1:
return S.Infinity*sign(coeff)*S.NegativeOne**ex
else:
return S.ComplexInfinity
else:
raise NotImplementedError("Not sure of sign of %s" % ex)
# gruntz fails on factorials but works with the gamma function
# If no factorial term is present, e should remain unchanged.
# factorial is defined to be zero for negative inputs (which
# differs from gamma) so only rewrite for positive z0.
if z0.is_extended_positive:
e = e.rewrite(factorial, gamma)
l = None
try:
r = gruntz(e, z, z0, dir)
if r is S.NaN or l is S.NaN:
raise PoleError()
except (PoleError, ValueError):
if l is not None:
raise
r = heuristics(e, z, z0, dir)
if r is None:
return self
return r
|
35a04792601a9e20f135ca69a5ad488a87f69d55309d4023201db7710a4fb335 | from collections import defaultdict
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core import (Basic, S, Add, Mul, Pow, Symbol, sympify,
expand_func, Function, Dummy, Expr, factor_terms,
expand_power_exp, Eq)
from sympy.core.exprtools import factor_nc
from sympy.core.parameters import global_parameters
from sympy.core.function import (expand_log, count_ops, _mexpand,
nfloat, expand_mul, expand)
from sympy.core.numbers import Float, I, pi, Rational
from sympy.core.relational import Relational
from sympy.core.rules import Transform
from sympy.core.sorting import ordered
from sympy.core.sympify import _sympify
from sympy.core.traversal import bottom_up as _bottom_up, walk as _walk
from sympy.functions import gamma, exp, sqrt, log, exp_polar, re
from sympy.functions.combinatorial.factorials import CombinatorialFunction
from sympy.functions.elementary.complexes import unpolarify, Abs, sign
from sympy.functions.elementary.exponential import ExpBase
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold,
piecewise_simplify)
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.functions.special.bessel import (BesselBase, besselj, besseli,
besselk, bessely, jn)
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.integrals.integrals import Integral
from sympy.matrices.expressions import (MatrixExpr, MatAdd, MatMul,
MatPow, MatrixSymbol)
from sympy.polys import together, cancel, factor
from sympy.polys.numberfields.minpoly import _is_sum_surds, _minimal_polynomial_sq
from sympy.simplify.combsimp import combsimp
from sympy.simplify.cse_opts import sub_pre, sub_post
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import radsimp, fraction, collect_abs
from sympy.simplify.sqrtdenest import sqrtdenest
from sympy.simplify.trigsimp import trigsimp, exptrigsimp
from sympy.utilities.decorator import deprecated
from sympy.utilities.iterables import has_variety, sift, subsets, iterable
from sympy.utilities.misc import as_int
import mpmath
def separatevars(expr, symbols=[], dict=False, force=False):
"""
Separates variables in an expression, if possible. By
default, it separates with respect to all symbols in an
expression and collects constant coefficients that are
independent of symbols.
Explanation
===========
If ``dict=True`` then the separated terms will be returned
in a dictionary keyed to their corresponding symbols.
By default, all symbols in the expression will appear as
keys; if symbols are provided, then all those symbols will
be used as keys, and any terms in the expression containing
other symbols or non-symbols will be returned keyed to the
string 'coeff'. (Passing None for symbols will return the
expression in a dictionary keyed to 'coeff'.)
If ``force=True``, then bases of powers will be separated regardless
of assumptions on the symbols involved.
Notes
=====
The order of the factors is determined by Mul, so that the
separated expressions may not necessarily be grouped together.
Although factoring is necessary to separate variables in some
expressions, it is not necessary in all cases, so one should not
count on the returned factors being factored.
Examples
========
>>> from sympy.abc import x, y, z, alpha
>>> from sympy import separatevars, sin
>>> separatevars((x*y)**y)
(x*y)**y
>>> separatevars((x*y)**y, force=True)
x**y*y**y
>>> e = 2*x**2*z*sin(y)+2*z*x**2
>>> separatevars(e)
2*x**2*z*(sin(y) + 1)
>>> separatevars(e, symbols=(x, y), dict=True)
{'coeff': 2*z, x: x**2, y: sin(y) + 1}
>>> separatevars(e, [x, y, alpha], dict=True)
{'coeff': 2*z, alpha: 1, x: x**2, y: sin(y) + 1}
If the expression is not really separable, or is only partially
separable, separatevars will do the best it can to separate it
by using factoring.
>>> separatevars(x + x*y - 3*x**2)
-x*(3*x - y - 1)
If the expression is not separable then expr is returned unchanged
or (if dict=True) then None is returned.
>>> eq = 2*x + y*sin(x)
>>> separatevars(eq) == eq
True
>>> separatevars(2*x + y*sin(x), symbols=(x, y), dict=True) is None
True
"""
expr = sympify(expr)
if dict:
return _separatevars_dict(_separatevars(expr, force), symbols)
else:
return _separatevars(expr, force)
def _separatevars(expr, force):
if isinstance(expr, Abs):
arg = expr.args[0]
if arg.is_Mul and not arg.is_number:
s = separatevars(arg, dict=True, force=force)
if s is not None:
return Mul(*map(expr.func, s.values()))
else:
return expr
if len(expr.free_symbols) < 2:
return expr
# don't destroy a Mul since much of the work may already be done
if expr.is_Mul:
args = list(expr.args)
changed = False
for i, a in enumerate(args):
args[i] = separatevars(a, force)
changed = changed or args[i] != a
if changed:
expr = expr.func(*args)
return expr
# get a Pow ready for expansion
if expr.is_Pow and expr.base != S.Exp1:
expr = Pow(separatevars(expr.base, force=force), expr.exp)
# First try other expansion methods
expr = expr.expand(mul=False, multinomial=False, force=force)
_expr, reps = posify(expr) if force else (expr, {})
expr = factor(_expr).subs(reps)
if not expr.is_Add:
return expr
# Find any common coefficients to pull out
args = list(expr.args)
commonc = args[0].args_cnc(cset=True, warn=False)[0]
for i in args[1:]:
commonc &= i.args_cnc(cset=True, warn=False)[0]
commonc = Mul(*commonc)
commonc = commonc.as_coeff_Mul()[1] # ignore constants
commonc_set = commonc.args_cnc(cset=True, warn=False)[0]
# remove them
for i, a in enumerate(args):
c, nc = a.args_cnc(cset=True, warn=False)
c = c - commonc_set
args[i] = Mul(*c)*Mul(*nc)
nonsepar = Add(*args)
if len(nonsepar.free_symbols) > 1:
_expr = nonsepar
_expr, reps = posify(_expr) if force else (_expr, {})
_expr = (factor(_expr)).subs(reps)
if not _expr.is_Add:
nonsepar = _expr
return commonc*nonsepar
def _separatevars_dict(expr, symbols):
if symbols:
if not all(t.is_Atom for t in symbols):
raise ValueError("symbols must be Atoms.")
symbols = list(symbols)
elif symbols is None:
return {'coeff': expr}
else:
symbols = list(expr.free_symbols)
if not symbols:
return None
ret = {i: [] for i in symbols + ['coeff']}
for i in Mul.make_args(expr):
expsym = i.free_symbols
intersection = set(symbols).intersection(expsym)
if len(intersection) > 1:
return None
if len(intersection) == 0:
# There are no symbols, so it is part of the coefficient
ret['coeff'].append(i)
else:
ret[intersection.pop()].append(i)
# rebuild
for k, v in ret.items():
ret[k] = Mul(*v)
return ret
def posify(eq):
"""Return ``eq`` (with generic symbols made positive) and a
dictionary containing the mapping between the old and new
symbols.
Explanation
===========
Any symbol that has positive=None will be replaced with a positive dummy
symbol having the same name. This replacement will allow more symbolic
processing of expressions, especially those involving powers and
logarithms.
A dictionary that can be sent to subs to restore ``eq`` to its original
symbols is also returned.
>>> from sympy import posify, Symbol, log, solve
>>> from sympy.abc import x
>>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True))
(_x + n + p, {_x: x})
>>> eq = 1/x
>>> log(eq).expand()
log(1/x)
>>> log(posify(eq)[0]).expand()
-log(_x)
>>> p, rep = posify(eq)
>>> log(p).expand().subs(rep)
-log(x)
It is possible to apply the same transformations to an iterable
of expressions:
>>> eq = x**2 - 4
>>> solve(eq, x)
[-2, 2]
>>> eq_x, reps = posify([eq, x]); eq_x
[_x**2 - 4, _x]
>>> solve(*eq_x)
[2]
"""
eq = sympify(eq)
if iterable(eq):
f = type(eq)
eq = list(eq)
syms = set()
for e in eq:
syms = syms.union(e.atoms(Symbol))
reps = {}
for s in syms:
reps.update({v: k for k, v in posify(s)[1].items()})
for i, e in enumerate(eq):
eq[i] = e.subs(reps)
return f(eq), {r: s for s, r in reps.items()}
reps = {s: Dummy(s.name, positive=True, **s.assumptions0)
for s in eq.free_symbols if s.is_positive is None}
eq = eq.subs(reps)
return eq, {r: s for s, r in reps.items()}
def hypersimp(f, k):
"""Given combinatorial term f(k) simplify its consecutive term ratio
i.e. f(k+1)/f(k). The input term can be composed of functions and
integer sequences which have equivalent representation in terms
of gamma special function.
Explanation
===========
The algorithm performs three basic steps:
1. Rewrite all functions in terms of gamma, if possible.
2. Rewrite all occurrences of gamma in terms of products
of gamma and rising factorial with integer, absolute
constant exponent.
3. Perform simplification of nested fractions, powers
and if the resulting expression is a quotient of
polynomials, reduce their total degree.
If f(k) is hypergeometric then as result we arrive with a
quotient of polynomials of minimal degree. Otherwise None
is returned.
For more information on the implemented algorithm refer to:
1. W. Koepf, Algorithms for m-fold Hypergeometric Summation,
Journal of Symbolic Computation (1995) 20, 399-417
"""
f = sympify(f)
g = f.subs(k, k + 1) / f
g = g.rewrite(gamma)
if g.has(Piecewise):
g = piecewise_fold(g)
g = g.args[-1][0]
g = expand_func(g)
g = powsimp(g, deep=True, combine='exp')
if g.is_rational_function(k):
return simplify(g, ratio=S.Infinity)
else:
return None
def hypersimilar(f, g, k):
"""
Returns True if ``f`` and ``g`` are hyper-similar.
Explanation
===========
Similarity in hypergeometric sense means that a quotient of
f(k) and g(k) is a rational function in ``k``. This procedure
is useful in solving recurrence relations.
For more information see hypersimp().
"""
f, g = list(map(sympify, (f, g)))
h = (f/g).rewrite(gamma)
h = h.expand(func=True, basic=False)
return h.is_rational_function(k)
def signsimp(expr, evaluate=None):
"""Make all Add sub-expressions canonical wrt sign.
Explanation
===========
If an Add subexpression, ``a``, can have a sign extracted,
as determined by could_extract_minus_sign, it is replaced
with Mul(-1, a, evaluate=False). This allows signs to be
extracted from powers and products.
Examples
========
>>> from sympy import signsimp, exp, symbols
>>> from sympy.abc import x, y
>>> i = symbols('i', odd=True)
>>> n = -1 + 1/x
>>> n/x/(-n)**2 - 1/n/x
(-1 + 1/x)/(x*(1 - 1/x)**2) - 1/(x*(-1 + 1/x))
>>> signsimp(_)
0
>>> x*n + x*-n
x*(-1 + 1/x) + x*(1 - 1/x)
>>> signsimp(_)
0
Since powers automatically handle leading signs
>>> (-2)**i
-2**i
signsimp can be used to put the base of a power with an integer
exponent into canonical form:
>>> n**i
(-1 + 1/x)**i
By default, signsimp does not leave behind any hollow simplification:
if making an Add canonical wrt sign didn't change the expression, the
original Add is restored. If this is not desired then the keyword
``evaluate`` can be set to False:
>>> e = exp(y - x)
>>> signsimp(e) == e
True
>>> signsimp(e, evaluate=False)
exp(-(x - y))
"""
if evaluate is None:
evaluate = global_parameters.evaluate
expr = sympify(expr)
if not isinstance(expr, (Expr, Relational)) or expr.is_Atom:
return expr
# get rid of an pre-existing unevaluation regarding sign
e = expr.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x))
e = sub_post(sub_pre(e))
if not isinstance(e, (Expr, Relational)) or e.is_Atom:
return e
if e.is_Add:
rv = e.func(*[signsimp(a) for a in e.args])
if not evaluate and isinstance(rv, Add
) and rv.could_extract_minus_sign():
return Mul(S.NegativeOne, -rv, evaluate=False)
return rv
if evaluate:
e = e.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x))
return e
def simplify(expr, ratio=1.7, measure=count_ops, rational=False, inverse=False, doit=True, **kwargs):
"""Simplifies the given expression.
Explanation
===========
Simplification is not a well defined term and the exact strategies
this function tries can change in the future versions of SymPy. If
your algorithm relies on "simplification" (whatever it is), try to
determine what you need exactly - is it powsimp()?, radsimp()?,
together()?, logcombine()?, or something else? And use this particular
function directly, because those are well defined and thus your algorithm
will be robust.
Nonetheless, especially for interactive use, or when you do not know
anything about the structure of the expression, simplify() tries to apply
intelligent heuristics to make the input expression "simpler". For
example:
>>> from sympy import simplify, cos, sin
>>> from sympy.abc import x, y
>>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
>>> a
(x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
>>> simplify(a)
x + 1
Note that we could have obtained the same result by using specific
simplification functions:
>>> from sympy import trigsimp, cancel
>>> trigsimp(a)
(x**2 + x)/x
>>> cancel(_)
x + 1
In some cases, applying :func:`simplify` may actually result in some more
complicated expression. The default ``ratio=1.7`` prevents more extreme
cases: if (result length)/(input length) > ratio, then input is returned
unmodified. The ``measure`` parameter lets you specify the function used
to determine how complex an expression is. The function should take a
single argument as an expression and return a number such that if
expression ``a`` is more complex than expression ``b``, then
``measure(a) > measure(b)``. The default measure function is
:func:`~.count_ops`, which returns the total number of operations in the
expression.
For example, if ``ratio=1``, ``simplify`` output cannot be longer
than input.
::
>>> from sympy import sqrt, simplify, count_ops, oo
>>> root = 1/(sqrt(2)+3)
Since ``simplify(root)`` would result in a slightly longer expression,
root is returned unchanged instead::
>>> simplify(root, ratio=1) == root
True
If ``ratio=oo``, simplify will be applied anyway::
>>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
True
Note that the shortest expression is not necessary the simplest, so
setting ``ratio`` to 1 may not be a good idea.
Heuristically, the default value ``ratio=1.7`` seems like a reasonable
choice.
You can easily define your own measure function based on what you feel
should represent the "size" or "complexity" of the input expression. Note
that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
good metrics, but have other problems (in this case, the measure function
may slow down simplify too much for very large expressions). If you do not
know what a good metric would be, the default, ``count_ops``, is a good
one.
For example:
>>> from sympy import symbols, log
>>> a, b = symbols('a b', positive=True)
>>> g = log(a) + log(b) + log(a)*log(1/b)
>>> h = simplify(g)
>>> h
log(a*b**(1 - log(a)))
>>> count_ops(g)
8
>>> count_ops(h)
5
So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
However, we may not like how ``simplify`` (in this case, using
``logcombine``) has created the ``b**(log(1/a) + 1)`` term. A simple way
to reduce this would be to give more weight to powers as operations in
``count_ops``. We can do this by using the ``visual=True`` option:
>>> print(count_ops(g, visual=True))
2*ADD + DIV + 4*LOG + MUL
>>> print(count_ops(h, visual=True))
2*LOG + MUL + POW + SUB
>>> from sympy import Symbol, S
>>> def my_measure(expr):
... POW = Symbol('POW')
... # Discourage powers by giving POW a weight of 10
... count = count_ops(expr, visual=True).subs(POW, 10)
... # Every other operation gets a weight of 1 (the default)
... count = count.replace(Symbol, type(S.One))
... return count
>>> my_measure(g)
8
>>> my_measure(h)
14
>>> 15./8 > 1.7 # 1.7 is the default ratio
True
>>> simplify(g, measure=my_measure)
-log(a)*log(b) + log(a) + log(b)
Note that because ``simplify()`` internally tries many different
simplification strategies and then compares them using the measure
function, we get a completely different result that is still different
from the input expression by doing this.
If ``rational=True``, Floats will be recast as Rationals before simplification.
If ``rational=None``, Floats will be recast as Rationals but the result will
be recast as Floats. If rational=False(default) then nothing will be done
to the Floats.
If ``inverse=True``, it will be assumed that a composition of inverse
functions, such as sin and asin, can be cancelled in any order.
For example, ``asin(sin(x))`` will yield ``x`` without checking whether
x belongs to the set where this relation is true. The default is
False.
Note that ``simplify()`` automatically calls ``doit()`` on the final
expression. You can avoid this behavior by passing ``doit=False`` as
an argument.
Also, it should be noted that simplifying the boolian expression is not
well defined. If the expression prefers automatic evaluation (such as
:obj:`~.Eq()` or :obj:`~.Or()`), simplification will return ``True`` or
``False`` if truth value can be determined. If the expression is not
evaluated by default (such as :obj:`~.Predicate()`), simplification will
not reduce it and you should use :func:`~.refine()` or :func:`~.ask()`
function. This inconsistency will be resolved in future version.
See Also
========
sympy.assumptions.refine.refine : Simplification using assumptions.
sympy.assumptions.ask.ask : Query for boolean expressions using assumptions.
"""
def shorter(*choices):
"""
Return the choice that has the fewest ops. In case of a tie,
the expression listed first is selected.
"""
if not has_variety(choices):
return choices[0]
return min(choices, key=measure)
def done(e):
rv = e.doit() if doit else e
return shorter(rv, collect_abs(rv))
expr = sympify(expr, rational=rational)
kwargs = dict(
ratio=kwargs.get('ratio', ratio),
measure=kwargs.get('measure', measure),
rational=kwargs.get('rational', rational),
inverse=kwargs.get('inverse', inverse),
doit=kwargs.get('doit', doit))
# no routine for Expr needs to check for is_zero
if isinstance(expr, Expr) and expr.is_zero:
return S.Zero if not expr.is_Number else expr
_eval_simplify = getattr(expr, '_eval_simplify', None)
if _eval_simplify is not None:
return _eval_simplify(**kwargs)
original_expr = expr = collect_abs(signsimp(expr))
if not isinstance(expr, Basic) or not expr.args: # XXX: temporary hack
return expr
if inverse and expr.has(Function):
expr = inversecombine(expr)
if not expr.args: # simplified to atomic
return expr
# do deep simplification
handled = Add, Mul, Pow, ExpBase
expr = expr.replace(
# here, checking for x.args is not enough because Basic has
# args but Basic does not always play well with replace, e.g.
# when simultaneous is True found expressions will be masked
# off with a Dummy but not all Basic objects in an expression
# can be replaced with a Dummy
lambda x: isinstance(x, Expr) and x.args and not isinstance(
x, handled),
lambda x: x.func(*[simplify(i, **kwargs) for i in x.args]),
simultaneous=False)
if not isinstance(expr, handled):
return done(expr)
if not expr.is_commutative:
expr = nc_simplify(expr)
# TODO: Apply different strategies, considering expression pattern:
# is it a purely rational function? Is there any trigonometric function?...
# See also https://github.com/sympy/sympy/pull/185.
# rationalize Floats
floats = False
if rational is not False and expr.has(Float):
floats = True
expr = nsimplify(expr, rational=True)
expr = _bottom_up(expr, lambda w: getattr(w, 'normal', lambda: w)())
expr = Mul(*powsimp(expr).as_content_primitive())
_e = cancel(expr)
expr1 = shorter(_e, _mexpand(_e).cancel()) # issue 6829
expr2 = shorter(together(expr, deep=True), together(expr1, deep=True))
if ratio is S.Infinity:
expr = expr2
else:
expr = shorter(expr2, expr1, expr)
if not isinstance(expr, Basic): # XXX: temporary hack
return expr
expr = factor_terms(expr, sign=False)
# must come before `Piecewise` since this introduces more `Piecewise` terms
if expr.has(sign):
expr = expr.rewrite(Abs)
# Deal with Piecewise separately to avoid recursive growth of expressions
if expr.has(Piecewise):
# Fold into a single Piecewise
expr = piecewise_fold(expr)
# Apply doit, if doit=True
expr = done(expr)
# Still a Piecewise?
if expr.has(Piecewise):
# Fold into a single Piecewise, in case doit lead to some
# expressions being Piecewise
expr = piecewise_fold(expr)
# kroneckersimp also affects Piecewise
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
# Still a Piecewise?
if expr.has(Piecewise):
# Do not apply doit on the segments as it has already
# been done above, but simplify
expr = piecewise_simplify(expr, deep=True, doit=False)
# Still a Piecewise?
if expr.has(Piecewise):
# Try factor common terms
expr = shorter(expr, factor_terms(expr))
# As all expressions have been simplified above with the
# complete simplify, nothing more needs to be done here
return expr
# hyperexpand automatically only works on hypergeometric terms
# Do this after the Piecewise part to avoid recursive expansion
expr = hyperexpand(expr)
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
if expr.has(BesselBase):
expr = besselsimp(expr)
if expr.has(TrigonometricFunction, HyperbolicFunction):
expr = trigsimp(expr, deep=True)
if expr.has(log):
expr = shorter(expand_log(expr, deep=True), logcombine(expr))
if expr.has(CombinatorialFunction, gamma):
# expression with gamma functions or non-integer arguments is
# automatically passed to gammasimp
expr = combsimp(expr)
if expr.has(Sum):
expr = sum_simplify(expr, **kwargs)
if expr.has(Integral):
expr = expr.xreplace({
i: factor_terms(i) for i in expr.atoms(Integral)})
if expr.has(Product):
expr = product_simplify(expr, **kwargs)
from sympy.physics.units import Quantity
if expr.has(Quantity):
from sympy.physics.units.util import quantity_simplify
expr = quantity_simplify(expr)
short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)
short = shorter(short, cancel(short))
short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))
if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase, exp):
short = exptrigsimp(short)
# get rid of hollow 2-arg Mul factorization
hollow_mul = Transform(
lambda x: Mul(*x.args),
lambda x:
x.is_Mul and
len(x.args) == 2 and
x.args[0].is_Number and
x.args[1].is_Add and
x.is_commutative)
expr = short.xreplace(hollow_mul)
numer, denom = expr.as_numer_denom()
if denom.is_Add:
n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1))
if n is not S.One:
expr = (numer*n).expand()/d
if expr.could_extract_minus_sign():
n, d = fraction(expr)
if d != 0:
expr = signsimp(-n/(-d))
if measure(expr) > ratio*measure(original_expr):
expr = original_expr
# restore floats
if floats and rational is None:
expr = nfloat(expr, exponent=False)
return done(expr)
def sum_simplify(s, **kwargs):
"""Main function for Sum simplification"""
if not isinstance(s, Add):
s = s.xreplace({a: sum_simplify(a, **kwargs)
for a in s.atoms(Add) if a.has(Sum)})
s = expand(s)
if not isinstance(s, Add):
return s
terms = s.args
s_t = [] # Sum Terms
o_t = [] # Other Terms
for term in terms:
sum_terms, other = sift(Mul.make_args(term),
lambda i: isinstance(i, Sum), binary=True)
if not sum_terms:
o_t.append(term)
continue
other = [Mul(*other)]
s_t.append(Mul(*(other + [s._eval_simplify(**kwargs) for s in sum_terms])))
result = Add(sum_combine(s_t), *o_t)
return result
def sum_combine(s_t):
"""Helper function for Sum simplification
Attempts to simplify a list of sums, by combining limits / sum function's
returns the simplified sum
"""
used = [False] * len(s_t)
for method in range(2):
for i, s_term1 in enumerate(s_t):
if not used[i]:
for j, s_term2 in enumerate(s_t):
if not used[j] and i != j:
temp = sum_add(s_term1, s_term2, method)
if isinstance(temp, (Sum, Mul)):
s_t[i] = temp
s_term1 = s_t[i]
used[j] = True
result = S.Zero
for i, s_term in enumerate(s_t):
if not used[i]:
result = Add(result, s_term)
return result
def factor_sum(self, limits=None, radical=False, clear=False, fraction=False, sign=True):
"""Return Sum with constant factors extracted.
If ``limits`` is specified then ``self`` is the summand; the other
keywords are passed to ``factor_terms``.
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y
>>> from sympy.simplify.simplify import factor_sum
>>> s = Sum(x*y, (x, 1, 3))
>>> factor_sum(s)
y*Sum(x, (x, 1, 3))
>>> factor_sum(s.function, s.limits)
y*Sum(x, (x, 1, 3))
"""
# XXX deprecate in favor of direct call to factor_terms
kwargs = dict(radical=radical, clear=clear,
fraction=fraction, sign=sign)
expr = Sum(self, *limits) if limits else self
return factor_terms(expr, **kwargs)
def sum_add(self, other, method=0):
"""Helper function for Sum simplification"""
#we know this is something in terms of a constant * a sum
#so we temporarily put the constants inside for simplification
#then simplify the result
def __refactor(val):
args = Mul.make_args(val)
sumv = next(x for x in args if isinstance(x, Sum))
constant = Mul(*[x for x in args if x != sumv])
return Sum(constant * sumv.function, *sumv.limits)
if isinstance(self, Mul):
rself = __refactor(self)
else:
rself = self
if isinstance(other, Mul):
rother = __refactor(other)
else:
rother = other
if type(rself) is type(rother):
if method == 0:
if rself.limits == rother.limits:
return factor_sum(Sum(rself.function + rother.function, *rself.limits))
elif method == 1:
if simplify(rself.function - rother.function) == 0:
if len(rself.limits) == len(rother.limits) == 1:
i = rself.limits[0][0]
x1 = rself.limits[0][1]
y1 = rself.limits[0][2]
j = rother.limits[0][0]
x2 = rother.limits[0][1]
y2 = rother.limits[0][2]
if i == j:
if x2 == y1 + 1:
return factor_sum(Sum(rself.function, (i, x1, y2)))
elif x1 == y2 + 1:
return factor_sum(Sum(rself.function, (i, x2, y1)))
return Add(self, other)
def product_simplify(s, **kwargs):
"""Main function for Product simplification"""
terms = Mul.make_args(s)
p_t = [] # Product Terms
o_t = [] # Other Terms
deep = kwargs.get('deep', True)
for term in terms:
if isinstance(term, Product):
if deep:
p_t.append(Product(term.function.simplify(**kwargs),
*term.limits))
else:
p_t.append(term)
else:
o_t.append(term)
used = [False] * len(p_t)
for method in range(2):
for i, p_term1 in enumerate(p_t):
if not used[i]:
for j, p_term2 in enumerate(p_t):
if not used[j] and i != j:
tmp_prod = product_mul(p_term1, p_term2, method)
if isinstance(tmp_prod, Product):
p_t[i] = tmp_prod
used[j] = True
result = Mul(*o_t)
for i, p_term in enumerate(p_t):
if not used[i]:
result = Mul(result, p_term)
return result
def product_mul(self, other, method=0):
"""Helper function for Product simplification"""
if type(self) is type(other):
if method == 0:
if self.limits == other.limits:
return Product(self.function * other.function, *self.limits)
elif method == 1:
if simplify(self.function - other.function) == 0:
if len(self.limits) == len(other.limits) == 1:
i = self.limits[0][0]
x1 = self.limits[0][1]
y1 = self.limits[0][2]
j = other.limits[0][0]
x2 = other.limits[0][1]
y2 = other.limits[0][2]
if i == j:
if x2 == y1 + 1:
return Product(self.function, (i, x1, y2))
elif x1 == y2 + 1:
return Product(self.function, (i, x2, y1))
return Mul(self, other)
def _nthroot_solve(p, n, prec):
"""
helper function for ``nthroot``
It denests ``p**Rational(1, n)`` using its minimal polynomial
"""
from sympy.solvers import solve
while n % 2 == 0:
p = sqrtdenest(sqrt(p))
n = n // 2
if n == 1:
return p
pn = p**Rational(1, n)
x = Symbol('x')
f = _minimal_polynomial_sq(p, n, x)
if f is None:
return None
sols = solve(f, x)
for sol in sols:
if abs(sol - pn).n() < 1./10**prec:
sol = sqrtdenest(sol)
if _mexpand(sol**n) == p:
return sol
def logcombine(expr, force=False):
"""
Takes logarithms and combines them using the following rules:
- log(x) + log(y) == log(x*y) if both are positive
- a*log(x) == log(x**a) if x is positive and a is real
If ``force`` is ``True`` then the assumptions above will be assumed to hold if
there is no assumption already in place on a quantity. For example, if
``a`` is imaginary or the argument negative, force will not perform a
combination but if ``a`` is a symbol with no assumptions the change will
take place.
Examples
========
>>> from sympy import Symbol, symbols, log, logcombine, I
>>> from sympy.abc import a, x, y, z
>>> logcombine(a*log(x) + log(y) - log(z))
a*log(x) + log(y) - log(z)
>>> logcombine(a*log(x) + log(y) - log(z), force=True)
log(x**a*y/z)
>>> x,y,z = symbols('x,y,z', positive=True)
>>> a = Symbol('a', real=True)
>>> logcombine(a*log(x) + log(y) - log(z))
log(x**a*y/z)
The transformation is limited to factors and/or terms that
contain logs, so the result depends on the initial state of
expansion:
>>> eq = (2 + 3*I)*log(x)
>>> logcombine(eq, force=True) == eq
True
>>> logcombine(eq.expand(), force=True)
log(x**2) + I*log(x**3)
See Also
========
posify: replace all symbols with symbols having positive assumptions
sympy.core.function.expand_log: expand the logarithms of products
and powers; the opposite of logcombine
"""
def f(rv):
if not (rv.is_Add or rv.is_Mul):
return rv
def gooda(a):
# bool to tell whether the leading ``a`` in ``a*log(x)``
# could appear as log(x**a)
return (a is not S.NegativeOne and # -1 *could* go, but we disallow
(a.is_extended_real or force and a.is_extended_real is not False))
def goodlog(l):
# bool to tell whether log ``l``'s argument can combine with others
a = l.args[0]
return a.is_positive or force and a.is_nonpositive is not False
other = []
logs = []
log1 = defaultdict(list)
for a in Add.make_args(rv):
if isinstance(a, log) and goodlog(a):
log1[()].append(([], a))
elif not a.is_Mul:
other.append(a)
else:
ot = []
co = []
lo = []
for ai in a.args:
if ai.is_Rational and ai < 0:
ot.append(S.NegativeOne)
co.append(-ai)
elif isinstance(ai, log) and goodlog(ai):
lo.append(ai)
elif gooda(ai):
co.append(ai)
else:
ot.append(ai)
if len(lo) > 1:
logs.append((ot, co, lo))
elif lo:
log1[tuple(ot)].append((co, lo[0]))
else:
other.append(a)
# if there is only one log in other, put it with the
# good logs
if len(other) == 1 and isinstance(other[0], log):
log1[()].append(([], other.pop()))
# if there is only one log at each coefficient and none have
# an exponent to place inside the log then there is nothing to do
if not logs and all(len(log1[k]) == 1 and log1[k][0] == [] for k in log1):
return rv
# collapse multi-logs as far as possible in a canonical way
# TODO: see if x*log(a)+x*log(a)*log(b) -> x*log(a)*(1+log(b))?
# -- in this case, it's unambiguous, but if it were were a log(c) in
# each term then it's arbitrary whether they are grouped by log(a) or
# by log(c). So for now, just leave this alone; it's probably better to
# let the user decide
for o, e, l in logs:
l = list(ordered(l))
e = log(l.pop(0).args[0]**Mul(*e))
while l:
li = l.pop(0)
e = log(li.args[0]**e)
c, l = Mul(*o), e
if isinstance(l, log): # it should be, but check to be sure
log1[(c,)].append(([], l))
else:
other.append(c*l)
# logs that have the same coefficient can multiply
for k in list(log1.keys()):
log1[Mul(*k)] = log(logcombine(Mul(*[
l.args[0]**Mul(*c) for c, l in log1.pop(k)]),
force=force), evaluate=False)
# logs that have oppositely signed coefficients can divide
for k in ordered(list(log1.keys())):
if k not in log1: # already popped as -k
continue
if -k in log1:
# figure out which has the minus sign; the one with
# more op counts should be the one
num, den = k, -k
if num.count_ops() > den.count_ops():
num, den = den, num
other.append(
num*log(log1.pop(num).args[0]/log1.pop(den).args[0],
evaluate=False))
else:
other.append(k*log1.pop(k))
return Add(*other)
return _bottom_up(expr, f)
def inversecombine(expr):
"""Simplify the composition of a function and its inverse.
Explanation
===========
No attention is paid to whether the inverse is a left inverse or a
right inverse; thus, the result will in general not be equivalent
to the original expression.
Examples
========
>>> from sympy.simplify.simplify import inversecombine
>>> from sympy import asin, sin, log, exp
>>> from sympy.abc import x
>>> inversecombine(asin(sin(x)))
x
>>> inversecombine(2*log(exp(3*x)))
6*x
"""
def f(rv):
if isinstance(rv, log):
if isinstance(rv.args[0], exp) or (rv.args[0].is_Pow and rv.args[0].base == S.Exp1):
rv = rv.args[0].exp
elif rv.is_Function and hasattr(rv, "inverse"):
if (len(rv.args) == 1 and len(rv.args[0].args) == 1 and
isinstance(rv.args[0], rv.inverse(argindex=1))):
rv = rv.args[0].args[0]
if rv.is_Pow and rv.base == S.Exp1:
if isinstance(rv.exp, log):
rv = rv.exp.args[0]
return rv
return _bottom_up(expr, f)
def kroneckersimp(expr):
"""
Simplify expressions with KroneckerDelta.
The only simplification currently attempted is to identify multiplicative cancellation:
Examples
========
>>> from sympy import KroneckerDelta, kroneckersimp
>>> from sympy.abc import i
>>> kroneckersimp(1 + KroneckerDelta(0, i) * KroneckerDelta(1, i))
1
"""
def args_cancel(args1, args2):
for i1 in range(2):
for i2 in range(2):
a1 = args1[i1]
a2 = args2[i2]
a3 = args1[(i1 + 1) % 2]
a4 = args2[(i2 + 1) % 2]
if Eq(a1, a2) is S.true and Eq(a3, a4) is S.false:
return True
return False
def cancel_kronecker_mul(m):
args = m.args
deltas = [a for a in args if isinstance(a, KroneckerDelta)]
for delta1, delta2 in subsets(deltas, 2):
args1 = delta1.args
args2 = delta2.args
if args_cancel(args1, args2):
return S.Zero * m # In case of oo etc
return m
if not expr.has(KroneckerDelta):
return expr
if expr.has(Piecewise):
expr = expr.rewrite(KroneckerDelta)
newexpr = expr
expr = None
while newexpr != expr:
expr = newexpr
newexpr = expr.replace(lambda e: isinstance(e, Mul), cancel_kronecker_mul)
return expr
def besselsimp(expr):
"""
Simplify bessel-type functions.
Explanation
===========
This routine tries to simplify bessel-type functions. Currently it only
works on the Bessel J and I functions, however. It works by looking at all
such functions in turn, and eliminating factors of "I" and "-1" (actually
their polar equivalents) in front of the argument. Then, functions of
half-integer order are rewritten using strigonometric functions and
functions of integer order (> 1) are rewritten using functions
of low order. Finally, if the expression was changed, compute
factorization of the result with factor().
>>> from sympy import besselj, besseli, besselsimp, polar_lift, I, S
>>> from sympy.abc import z, nu
>>> besselsimp(besselj(nu, z*polar_lift(-1)))
exp(I*pi*nu)*besselj(nu, z)
>>> besselsimp(besseli(nu, z*polar_lift(-I)))
exp(-I*pi*nu/2)*besselj(nu, z)
>>> besselsimp(besseli(S(-1)/2, z))
sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
>>> besselsimp(z*besseli(0, z) + z*(besseli(2, z))/2 + besseli(1, z))
3*z*besseli(0, z)/2
"""
# TODO
# - better algorithm?
# - simplify (cos(pi*b)*besselj(b,z) - besselj(-b,z))/sin(pi*b) ...
# - use contiguity relations?
def replacer(fro, to, factors):
factors = set(factors)
def repl(nu, z):
if factors.intersection(Mul.make_args(z)):
return to(nu, z)
return fro(nu, z)
return repl
def torewrite(fro, to):
def tofunc(nu, z):
return fro(nu, z).rewrite(to)
return tofunc
def tominus(fro):
def tofunc(nu, z):
return exp(I*pi*nu)*fro(nu, exp_polar(-I*pi)*z)
return tofunc
orig_expr = expr
ifactors = [I, exp_polar(I*pi/2), exp_polar(-I*pi/2)]
expr = expr.replace(
besselj, replacer(besselj,
torewrite(besselj, besseli), ifactors))
expr = expr.replace(
besseli, replacer(besseli,
torewrite(besseli, besselj), ifactors))
minusfactors = [-1, exp_polar(I*pi)]
expr = expr.replace(
besselj, replacer(besselj, tominus(besselj), minusfactors))
expr = expr.replace(
besseli, replacer(besseli, tominus(besseli), minusfactors))
z0 = Dummy('z')
def expander(fro):
def repl(nu, z):
if (nu % 1) == S.Half:
return simplify(trigsimp(unpolarify(
fro(nu, z0).rewrite(besselj).rewrite(jn).expand(
func=True)).subs(z0, z)))
elif nu.is_Integer and nu > 1:
return fro(nu, z).expand(func=True)
return fro(nu, z)
return repl
expr = expr.replace(besselj, expander(besselj))
expr = expr.replace(bessely, expander(bessely))
expr = expr.replace(besseli, expander(besseli))
expr = expr.replace(besselk, expander(besselk))
def _bessel_simp_recursion(expr):
def _use_recursion(bessel, expr):
while True:
bessels = expr.find(lambda x: isinstance(x, bessel))
try:
for ba in sorted(bessels, key=lambda x: re(x.args[0])):
a, x = ba.args
bap1 = bessel(a+1, x)
bap2 = bessel(a+2, x)
if expr.has(bap1) and expr.has(bap2):
expr = expr.subs(ba, 2*(a+1)/x*bap1 - bap2)
break
else:
return expr
except (ValueError, TypeError):
return expr
if expr.has(besselj):
expr = _use_recursion(besselj, expr)
if expr.has(bessely):
expr = _use_recursion(bessely, expr)
return expr
expr = _bessel_simp_recursion(expr)
if expr != orig_expr:
expr = expr.factor()
return expr
def nthroot(expr, n, max_len=4, prec=15):
"""
Compute a real nth-root of a sum of surds.
Parameters
==========
expr : sum of surds
n : integer
max_len : maximum number of surds passed as constants to ``nsimplify``
Algorithm
=========
First ``nsimplify`` is used to get a candidate root; if it is not a
root the minimal polynomial is computed; the answer is one of its
roots.
Examples
========
>>> from sympy.simplify.simplify import nthroot
>>> from sympy import sqrt
>>> nthroot(90 + 34*sqrt(7), 3)
sqrt(7) + 3
"""
expr = sympify(expr)
n = sympify(n)
p = expr**Rational(1, n)
if not n.is_integer:
return p
if not _is_sum_surds(expr):
return p
surds = []
coeff_muls = [x.as_coeff_Mul() for x in expr.args]
for x, y in coeff_muls:
if not x.is_rational:
return p
if y is S.One:
continue
if not (y.is_Pow and y.exp == S.Half and y.base.is_integer):
return p
surds.append(y)
surds.sort()
surds = surds[:max_len]
if expr < 0 and n % 2 == 1:
p = (-expr)**Rational(1, n)
a = nsimplify(p, constants=surds)
res = a if _mexpand(a**n) == _mexpand(-expr) else p
return -res
a = nsimplify(p, constants=surds)
if _mexpand(a) is not _mexpand(p) and _mexpand(a**n) == _mexpand(expr):
return _mexpand(a)
expr = _nthroot_solve(expr, n, prec)
if expr is None:
return p
return expr
def nsimplify(expr, constants=(), tolerance=None, full=False, rational=None,
rational_conversion='base10'):
"""
Find a simple representation for a number or, if there are free symbols or
if ``rational=True``, then replace Floats with their Rational equivalents. If
no change is made and rational is not False then Floats will at least be
converted to Rationals.
Explanation
===========
For numerical expressions, a simple formula that numerically matches the
given numerical expression is sought (and the input should be possible
to evalf to a precision of at least 30 digits).
Optionally, a list of (rationally independent) constants to
include in the formula may be given.
A lower tolerance may be set to find less exact matches. If no tolerance
is given then the least precise value will set the tolerance (e.g. Floats
default to 15 digits of precision, so would be tolerance=10**-15).
With ``full=True``, a more extensive search is performed
(this is useful to find simpler numbers when the tolerance
is set low).
When converting to rational, if rational_conversion='base10' (the default), then
convert floats to rationals using their base-10 (string) representation.
When rational_conversion='exact' it uses the exact, base-2 representation.
Examples
========
>>> from sympy import nsimplify, sqrt, GoldenRatio, exp, I, pi
>>> nsimplify(4/(1+sqrt(5)), [GoldenRatio])
-2 + 2*GoldenRatio
>>> nsimplify((1/(exp(3*pi*I/5)+1)))
1/2 - I*sqrt(sqrt(5)/10 + 1/4)
>>> nsimplify(I**I, [pi])
exp(-pi/2)
>>> nsimplify(pi, tolerance=0.01)
22/7
>>> nsimplify(0.333333333333333, rational=True, rational_conversion='exact')
6004799503160655/18014398509481984
>>> nsimplify(0.333333333333333, rational=True)
1/3
See Also
========
sympy.core.function.nfloat
"""
try:
return sympify(as_int(expr))
except (TypeError, ValueError):
pass
expr = sympify(expr).xreplace({
Float('inf'): S.Infinity,
Float('-inf'): S.NegativeInfinity,
})
if expr is S.Infinity or expr is S.NegativeInfinity:
return expr
if rational or expr.free_symbols:
return _real_to_rational(expr, tolerance, rational_conversion)
# SymPy's default tolerance for Rationals is 15; other numbers may have
# lower tolerances set, so use them to pick the largest tolerance if None
# was given
if tolerance is None:
tolerance = 10**-min([15] +
[mpmath.libmp.libmpf.prec_to_dps(n._prec)
for n in expr.atoms(Float)])
# XXX should prec be set independent of tolerance or should it be computed
# from tolerance?
prec = 30
bprec = int(prec*3.33)
constants_dict = {}
for constant in constants:
constant = sympify(constant)
v = constant.evalf(prec)
if not v.is_Float:
raise ValueError("constants must be real-valued")
constants_dict[str(constant)] = v._to_mpmath(bprec)
exprval = expr.evalf(prec, chop=True)
re, im = exprval.as_real_imag()
# safety check to make sure that this evaluated to a number
if not (re.is_Number and im.is_Number):
return expr
def nsimplify_real(x):
orig = mpmath.mp.dps
xv = x._to_mpmath(bprec)
try:
# We'll be happy with low precision if a simple fraction
if not (tolerance or full):
mpmath.mp.dps = 15
rat = mpmath.pslq([xv, 1])
if rat is not None:
return Rational(-int(rat[1]), int(rat[0]))
mpmath.mp.dps = prec
newexpr = mpmath.identify(xv, constants=constants_dict,
tol=tolerance, full=full)
if not newexpr:
raise ValueError
if full:
newexpr = newexpr[0]
expr = sympify(newexpr)
if x and not expr: # don't let x become 0
raise ValueError
if expr.is_finite is False and xv not in [mpmath.inf, mpmath.ninf]:
raise ValueError
return expr
finally:
# even though there are returns above, this is executed
# before leaving
mpmath.mp.dps = orig
try:
if re:
re = nsimplify_real(re)
if im:
im = nsimplify_real(im)
except ValueError:
if rational is None:
return _real_to_rational(expr, rational_conversion=rational_conversion)
return expr
rv = re + im*S.ImaginaryUnit
# if there was a change or rational is explicitly not wanted
# return the value, else return the Rational representation
if rv != expr or rational is False:
return rv
return _real_to_rational(expr, rational_conversion=rational_conversion)
def _real_to_rational(expr, tolerance=None, rational_conversion='base10'):
"""
Replace all reals in expr with rationals.
Examples
========
>>> from sympy.simplify.simplify import _real_to_rational
>>> from sympy.abc import x
>>> _real_to_rational(.76 + .1*x**.5)
sqrt(x)/10 + 19/25
If rational_conversion='base10', this uses the base-10 string. If
rational_conversion='exact', the exact, base-2 representation is used.
>>> _real_to_rational(0.333333333333333, rational_conversion='exact')
6004799503160655/18014398509481984
>>> _real_to_rational(0.333333333333333)
1/3
"""
expr = _sympify(expr)
inf = Float('inf')
p = expr
reps = {}
reduce_num = None
if tolerance is not None and tolerance < 1:
reduce_num = ceiling(1/tolerance)
for fl in p.atoms(Float):
key = fl
if reduce_num is not None:
r = Rational(fl).limit_denominator(reduce_num)
elif (tolerance is not None and tolerance >= 1 and
fl.is_Integer is False):
r = Rational(tolerance*round(fl/tolerance)
).limit_denominator(int(tolerance))
else:
if rational_conversion == 'exact':
r = Rational(fl)
reps[key] = r
continue
elif rational_conversion != 'base10':
raise ValueError("rational_conversion must be 'base10' or 'exact'")
r = nsimplify(fl, rational=False)
# e.g. log(3).n() -> log(3) instead of a Rational
if fl and not r:
r = Rational(fl)
elif not r.is_Rational:
if fl in (inf, -inf):
r = S.ComplexInfinity
elif fl < 0:
fl = -fl
d = Pow(10, int(mpmath.log(fl)/mpmath.log(10)))
r = -Rational(str(fl/d))*d
elif fl > 0:
d = Pow(10, int(mpmath.log(fl)/mpmath.log(10)))
r = Rational(str(fl/d))*d
else:
r = S.Zero
reps[key] = r
return p.subs(reps, simultaneous=True)
def clear_coefficients(expr, rhs=S.Zero):
"""Return `p, r` where `p` is the expression obtained when Rational
additive and multiplicative coefficients of `expr` have been stripped
away in a naive fashion (i.e. without simplification). The operations
needed to remove the coefficients will be applied to `rhs` and returned
as `r`.
Examples
========
>>> from sympy.simplify.simplify import clear_coefficients
>>> from sympy.abc import x, y
>>> from sympy import Dummy
>>> expr = 4*y*(6*x + 3)
>>> clear_coefficients(expr - 2)
(y*(2*x + 1), 1/6)
When solving 2 or more expressions like `expr = a`,
`expr = b`, etc..., it is advantageous to provide a Dummy symbol
for `rhs` and simply replace it with `a`, `b`, etc... in `r`.
>>> rhs = Dummy('rhs')
>>> clear_coefficients(expr, rhs)
(y*(2*x + 1), _rhs/12)
>>> _[1].subs(rhs, 2)
1/6
"""
was = None
free = expr.free_symbols
if expr.is_Rational:
return (S.Zero, rhs - expr)
while expr and was != expr:
was = expr
m, expr = (
expr.as_content_primitive()
if free else
factor_terms(expr).as_coeff_Mul(rational=True))
rhs /= m
c, expr = expr.as_coeff_Add(rational=True)
rhs -= c
expr = signsimp(expr, evaluate = False)
if expr.could_extract_minus_sign():
expr = -expr
rhs = -rhs
return expr, rhs
def nc_simplify(expr, deep=True):
'''
Simplify a non-commutative expression composed of multiplication
and raising to a power by grouping repeated subterms into one power.
Priority is given to simplifications that give the fewest number
of arguments in the end (for example, in a*b*a*b*c*a*b*c simplifying
to (a*b)**2*c*a*b*c gives 5 arguments while a*b*(a*b*c)**2 has 3).
If ``expr`` is a sum of such terms, the sum of the simplified terms
is returned.
Keyword argument ``deep`` controls whether or not subexpressions
nested deeper inside the main expression are simplified. See examples
below. Setting `deep` to `False` can save time on nested expressions
that do not need simplifying on all levels.
Examples
========
>>> from sympy import symbols
>>> from sympy.simplify.simplify import nc_simplify
>>> a, b, c = symbols("a b c", commutative=False)
>>> nc_simplify(a*b*a*b*c*a*b*c)
a*b*(a*b*c)**2
>>> expr = a**2*b*a**4*b*a**4
>>> nc_simplify(expr)
a**2*(b*a**4)**2
>>> nc_simplify(a*b*a*b*c**2*(a*b)**2*c**2)
((a*b)**2*c**2)**2
>>> nc_simplify(a*b*a*b + 2*a*c*a**2*c*a**2*c*a)
(a*b)**2 + 2*(a*c*a)**3
>>> nc_simplify(b**-1*a**-1*(a*b)**2)
a*b
>>> nc_simplify(a**-1*b**-1*c*a)
(b*a)**(-1)*c*a
>>> expr = (a*b*a*b)**2*a*c*a*c
>>> nc_simplify(expr)
(a*b)**4*(a*c)**2
>>> nc_simplify(expr, deep=False)
(a*b*a*b)**2*(a*c)**2
'''
if isinstance(expr, MatrixExpr):
expr = expr.doit(inv_expand=False)
_Add, _Mul, _Pow, _Symbol = MatAdd, MatMul, MatPow, MatrixSymbol
else:
_Add, _Mul, _Pow, _Symbol = Add, Mul, Pow, Symbol
# =========== Auxiliary functions ========================
def _overlaps(args):
# Calculate a list of lists m such that m[i][j] contains the lengths
# of all possible overlaps between args[:i+1] and args[i+1+j:].
# An overlap is a suffix of the prefix that matches a prefix
# of the suffix.
# For example, let expr=c*a*b*a*b*a*b*a*b. Then m[3][0] contains
# the lengths of overlaps of c*a*b*a*b with a*b*a*b. The overlaps
# are a*b*a*b, a*b and the empty word so that m[3][0]=[4,2,0].
# All overlaps rather than only the longest one are recorded
# because this information helps calculate other overlap lengths.
m = [[([1, 0] if a == args[0] else [0]) for a in args[1:]]]
for i in range(1, len(args)):
overlaps = []
j = 0
for j in range(len(args) - i - 1):
overlap = []
for v in m[i-1][j+1]:
if j + i + 1 + v < len(args) and args[i] == args[j+i+1+v]:
overlap.append(v + 1)
overlap += [0]
overlaps.append(overlap)
m.append(overlaps)
return m
def _reduce_inverses(_args):
# replace consecutive negative powers by an inverse
# of a product of positive powers, e.g. a**-1*b**-1*c
# will simplify to (a*b)**-1*c;
# return that new args list and the number of negative
# powers in it (inv_tot)
inv_tot = 0 # total number of inverses
inverses = []
args = []
for arg in _args:
if isinstance(arg, _Pow) and arg.args[1] < 0:
inverses = [arg**-1] + inverses
inv_tot += 1
else:
if len(inverses) == 1:
args.append(inverses[0]**-1)
elif len(inverses) > 1:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
inverses = []
args.append(arg)
if inverses:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
return inv_tot, tuple(args)
def get_score(s):
# compute the number of arguments of s
# (including in nested expressions) overall
# but ignore exponents
if isinstance(s, _Pow):
return get_score(s.args[0])
elif isinstance(s, (_Add, _Mul)):
return sum([get_score(a) for a in s.args])
return 1
def compare(s, alt_s):
# compare two possible simplifications and return a
# "better" one
if s != alt_s and get_score(alt_s) < get_score(s):
return alt_s
return s
# ========================================================
if not isinstance(expr, (_Add, _Mul, _Pow)) or expr.is_commutative:
return expr
args = expr.args[:]
if isinstance(expr, _Pow):
if deep:
return _Pow(nc_simplify(args[0]), args[1]).doit()
else:
return expr
elif isinstance(expr, _Add):
return _Add(*[nc_simplify(a, deep=deep) for a in args]).doit()
else:
# get the non-commutative part
c_args, args = expr.args_cnc()
com_coeff = Mul(*c_args)
if com_coeff != 1:
return com_coeff*nc_simplify(expr/com_coeff, deep=deep)
inv_tot, args = _reduce_inverses(args)
# if most arguments are negative, work with the inverse
# of the expression, e.g. a**-1*b*a**-1*c**-1 will become
# (c*a*b**-1*a)**-1 at the end so can work with c*a*b**-1*a
invert = False
if inv_tot > len(args)/2:
invert = True
args = [a**-1 for a in args[::-1]]
if deep:
args = tuple(nc_simplify(a) for a in args)
m = _overlaps(args)
# simps will be {subterm: end} where `end` is the ending
# index of a sequence of repetitions of subterm;
# this is for not wasting time with subterms that are part
# of longer, already considered sequences
simps = {}
post = 1
pre = 1
# the simplification coefficient is the number of
# arguments by which contracting a given sequence
# would reduce the word; e.g. in a*b*a*b*c*a*b*c,
# contracting a*b*a*b to (a*b)**2 removes 3 arguments
# while a*b*c*a*b*c to (a*b*c)**2 removes 6. It's
# better to contract the latter so simplification
# with a maximum simplification coefficient will be chosen
max_simp_coeff = 0
simp = None # information about future simplification
for i in range(1, len(args)):
simp_coeff = 0
l = 0 # length of a subterm
p = 0 # the power of a subterm
if i < len(args) - 1:
rep = m[i][0]
start = i # starting index of the repeated sequence
end = i+1 # ending index of the repeated sequence
if i == len(args)-1 or rep == [0]:
# no subterm is repeated at this stage, at least as
# far as the arguments are concerned - there may be
# a repetition if powers are taken into account
if (isinstance(args[i], _Pow) and
not isinstance(args[i].args[0], _Symbol)):
subterm = args[i].args[0].args
l = len(subterm)
if args[i-l:i] == subterm:
# e.g. a*b in a*b*(a*b)**2 is not repeated
# in args (= [a, b, (a*b)**2]) but it
# can be matched here
p += 1
start -= l
if args[i+1:i+1+l] == subterm:
# e.g. a*b in (a*b)**2*a*b
p += 1
end += l
if p:
p += args[i].args[1]
else:
continue
else:
l = rep[0] # length of the longest repeated subterm at this point
start -= l - 1
subterm = args[start:end]
p = 2
end += l
if subterm in simps and simps[subterm] >= start:
# the subterm is part of a sequence that
# has already been considered
continue
# count how many times it's repeated
while end < len(args):
if l in m[end-1][0]:
p += 1
end += l
elif isinstance(args[end], _Pow) and args[end].args[0].args == subterm:
# for cases like a*b*a*b*(a*b)**2*a*b
p += args[end].args[1]
end += 1
else:
break
# see if another match can be made, e.g.
# for b*a**2 in b*a**2*b*a**3 or a*b in
# a**2*b*a*b
pre_exp = 0
pre_arg = 1
if start - l >= 0 and args[start-l+1:start] == subterm[1:]:
if isinstance(subterm[0], _Pow):
pre_arg = subterm[0].args[0]
exp = subterm[0].args[1]
else:
pre_arg = subterm[0]
exp = 1
if isinstance(args[start-l], _Pow) and args[start-l].args[0] == pre_arg:
pre_exp = args[start-l].args[1] - exp
start -= l
p += 1
elif args[start-l] == pre_arg:
pre_exp = 1 - exp
start -= l
p += 1
post_exp = 0
post_arg = 1
if end + l - 1 < len(args) and args[end:end+l-1] == subterm[:-1]:
if isinstance(subterm[-1], _Pow):
post_arg = subterm[-1].args[0]
exp = subterm[-1].args[1]
else:
post_arg = subterm[-1]
exp = 1
if isinstance(args[end+l-1], _Pow) and args[end+l-1].args[0] == post_arg:
post_exp = args[end+l-1].args[1] - exp
end += l
p += 1
elif args[end+l-1] == post_arg:
post_exp = 1 - exp
end += l
p += 1
# Consider a*b*a**2*b*a**2*b*a:
# b*a**2 is explicitly repeated, but note
# that in this case a*b*a is also repeated
# so there are two possible simplifications:
# a*(b*a**2)**3*a**-1 or (a*b*a)**3
# The latter is obviously simpler.
# But in a*b*a**2*b**2*a**2 the simplifications are
# a*(b*a**2)**2 and (a*b*a)**3*a in which case
# it's better to stick with the shorter subterm
if post_exp and exp % 2 == 0 and start > 0:
exp = exp/2
_pre_exp = 1
_post_exp = 1
if isinstance(args[start-1], _Pow) and args[start-1].args[0] == post_arg:
_post_exp = post_exp + exp
_pre_exp = args[start-1].args[1] - exp
elif args[start-1] == post_arg:
_post_exp = post_exp + exp
_pre_exp = 1 - exp
if _pre_exp == 0 or _post_exp == 0:
if not pre_exp:
start -= 1
post_exp = _post_exp
pre_exp = _pre_exp
pre_arg = post_arg
subterm = (post_arg**exp,) + subterm[:-1] + (post_arg**exp,)
simp_coeff += end-start
if post_exp:
simp_coeff -= 1
if pre_exp:
simp_coeff -= 1
simps[subterm] = end
if simp_coeff > max_simp_coeff:
max_simp_coeff = simp_coeff
simp = (start, _Mul(*subterm), p, end, l)
pre = pre_arg**pre_exp
post = post_arg**post_exp
if simp:
subterm = _Pow(nc_simplify(simp[1], deep=deep), simp[2])
pre = nc_simplify(_Mul(*args[:simp[0]])*pre, deep=deep)
post = post*nc_simplify(_Mul(*args[simp[3]:]), deep=deep)
simp = pre*subterm*post
if pre != 1 or post != 1:
# new simplifications may be possible but no need
# to recurse over arguments
simp = nc_simplify(simp, deep=False)
else:
simp = _Mul(*args)
if invert:
simp = _Pow(simp, -1)
# see if factor_nc(expr) is simplified better
if not isinstance(expr, MatrixExpr):
f_expr = factor_nc(expr)
if f_expr != expr:
alt_simp = nc_simplify(f_expr, deep=deep)
simp = compare(simp, alt_simp)
else:
simp = simp.doit(inv_expand=False)
return simp
def dotprodsimp(expr, withsimp=False):
"""Simplification for a sum of products targeted at the kind of blowup that
occurs during summation of products. Intended to reduce expression blowup
during matrix multiplication or other similar operations. Only works with
algebraic expressions and does not recurse into non.
Parameters
==========
withsimp : bool, optional
Specifies whether a flag should be returned along with the expression
to indicate roughly whether simplification was successful. It is used
in ``MatrixArithmetic._eval_pow_by_recursion`` to avoid attempting to
simplify an expression repetitively which does not simplify.
"""
def count_ops_alg(expr):
"""Optimized count algebraic operations with no recursion into
non-algebraic args that ``core.function.count_ops`` does. Also returns
whether rational functions may be present according to negative
exponents of powers or non-number fractions.
Returns
=======
ops, ratfunc : int, bool
``ops`` is the number of algebraic operations starting at the top
level expression (not recursing into non-alg children). ``ratfunc``
specifies whether the expression MAY contain rational functions
which ``cancel`` MIGHT optimize.
"""
ops = 0
args = [expr]
ratfunc = False
while args:
a = args.pop()
if not isinstance(a, Basic):
continue
if a.is_Rational:
if a is not S.One: # -1/3 = NEG + DIV
ops += bool (a.p < 0) + bool (a.q != 1)
elif a.is_Mul:
if a.could_extract_minus_sign():
ops += 1
if a.args[0] is S.NegativeOne:
a = a.as_two_terms()[1]
else:
a = -a
n, d = fraction(a)
if n.is_Integer:
ops += 1 + bool (n < 0)
args.append(d) # won't be -Mul but could be Add
elif d is not S.One:
if not d.is_Integer:
args.append(d)
ratfunc=True
ops += 1
args.append(n) # could be -Mul
else:
ops += len(a.args) - 1
args.extend(a.args)
elif a.is_Add:
laargs = len(a.args)
negs = 0
for ai in a.args:
if ai.could_extract_minus_sign():
negs += 1
ai = -ai
args.append(ai)
ops += laargs - (negs != laargs) # -x - y = NEG + SUB
elif a.is_Pow:
ops += 1
args.append(a.base)
if not ratfunc:
ratfunc = a.exp.is_negative is not False
return ops, ratfunc
def nonalg_subs_dummies(expr, dummies):
"""Substitute dummy variables for non-algebraic expressions to avoid
evaluation of non-algebraic terms that ``polys.polytools.cancel`` does.
"""
if not expr.args:
return expr
if expr.is_Add or expr.is_Mul or expr.is_Pow:
args = None
for i, a in enumerate(expr.args):
c = nonalg_subs_dummies(a, dummies)
if c is a:
continue
if args is None:
args = list(expr.args)
args[i] = c
if args is None:
return expr
return expr.func(*args)
return dummies.setdefault(expr, Dummy())
simplified = False # doesn't really mean simplified, rather "can simplify again"
if isinstance(expr, Basic) and (expr.is_Add or expr.is_Mul or expr.is_Pow):
expr2 = expr.expand(deep=True, modulus=None, power_base=False,
power_exp=False, mul=True, log=False, multinomial=True, basic=False)
if expr2 != expr:
expr = expr2
simplified = True
exprops, ratfunc = count_ops_alg(expr)
if exprops >= 6: # empirically tested cutoff for expensive simplification
if ratfunc:
dummies = {}
expr2 = nonalg_subs_dummies(expr, dummies)
if expr2 is expr or count_ops_alg(expr2)[0] >= 6: # check again after substitution
expr3 = cancel(expr2)
if expr3 != expr2:
expr = expr3.subs([(d, e) for e, d in dummies.items()])
simplified = True
# very special case: x/(x-1) - 1/(x-1) -> 1
elif (exprops == 5 and expr.is_Add and expr.args [0].is_Mul and
expr.args [1].is_Mul and expr.args [0].args [-1].is_Pow and
expr.args [1].args [-1].is_Pow and
expr.args [0].args [-1].exp is S.NegativeOne and
expr.args [1].args [-1].exp is S.NegativeOne):
expr2 = together (expr)
expr2ops = count_ops_alg(expr2)[0]
if expr2ops < exprops:
expr = expr2
simplified = True
else:
simplified = True
return (expr, simplified) if withsimp else expr
bottom_up = deprecated(
"""
Using bottom_up from the sympy.simplify.simplify submodule is
deprecated.
Instead, use bottom_up from the top-level sympy namespace, like
sympy.bottom_up
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved",
)(_bottom_up)
# XXX: This function really should either be private API or exported in the
# top-level sympy/__init__.py
walk = deprecated(
"""
Using walk from the sympy.simplify.simplify submodule is
deprecated.
Instead, use walk from sympy.core.traversal.walk
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved",
)(_walk)
|
eeca1ed624ae5f29cde60a55af8007eba7ec9b61dec2b6ab31f97a88a0e9bdba | """
Types used to represent a full function/module as an Abstract Syntax Tree.
Most types are small, and are merely used as tokens in the AST. A tree diagram
has been included below to illustrate the relationships between the AST types.
AST Type Tree
-------------
::
*Basic*
|
|
CodegenAST
|
|--->AssignmentBase
| |--->Assignment
| |--->AugmentedAssignment
| |--->AddAugmentedAssignment
| |--->SubAugmentedAssignment
| |--->MulAugmentedAssignment
| |--->DivAugmentedAssignment
| |--->ModAugmentedAssignment
|
|--->CodeBlock
|
|
|--->Token
|--->Attribute
|--->For
|--->String
| |--->QuotedString
| |--->Comment
|--->Type
| |--->IntBaseType
| | |--->_SizedIntType
| | |--->SignedIntType
| | |--->UnsignedIntType
| |--->FloatBaseType
| |--->FloatType
| |--->ComplexBaseType
| |--->ComplexType
|--->Node
| |--->Variable
| | |---> Pointer
| |--->FunctionPrototype
| |--->FunctionDefinition
|--->Element
|--->Declaration
|--->While
|--->Scope
|--->Stream
|--->Print
|--->FunctionCall
|--->BreakToken
|--->ContinueToken
|--->NoneToken
|--->Return
Predefined types
----------------
A number of ``Type`` instances are provided in the ``sympy.codegen.ast`` module
for convenience. Perhaps the two most common ones for code-generation (of numeric
codes) are ``float32`` and ``float64`` (known as single and double precision respectively).
There are also precision generic versions of Types (for which the codeprinters selects the
underlying data type at time of printing): ``real``, ``integer``, ``complex_``, ``bool_``.
The other ``Type`` instances defined are:
- ``intc``: Integer type used by C's "int".
- ``intp``: Integer type used by C's "unsigned".
- ``int8``, ``int16``, ``int32``, ``int64``: n-bit integers.
- ``uint8``, ``uint16``, ``uint32``, ``uint64``: n-bit unsigned integers.
- ``float80``: known as "extended precision" on modern x86/amd64 hardware.
- ``complex64``: Complex number represented by two ``float32`` numbers
- ``complex128``: Complex number represented by two ``float64`` numbers
Using the nodes
---------------
It is possible to construct simple algorithms using the AST nodes. Let's construct a loop applying
Newton's method::
>>> from sympy import symbols, cos
>>> from sympy.codegen.ast import While, Assignment, aug_assign, Print
>>> t, dx, x = symbols('tol delta val')
>>> expr = cos(x) - x**3
>>> whl = While(abs(dx) > t, [
... Assignment(dx, -expr/expr.diff(x)),
... aug_assign(x, '+', dx),
... Print([x])
... ])
>>> from sympy import pycode
>>> py_str = pycode(whl)
>>> print(py_str)
while (abs(delta) > tol):
delta = (val**3 - math.cos(val))/(-3*val**2 - math.sin(val))
val += delta
print(val)
>>> import math
>>> tol, val, delta = 1e-5, 0.5, float('inf')
>>> exec(py_str)
1.1121416371
0.909672693737
0.867263818209
0.865477135298
0.865474033111
>>> print('%3.1g' % (math.cos(val) - val**3))
-3e-11
If we want to generate Fortran code for the same while loop we simple call ``fcode``::
>>> from sympy import fcode
>>> print(fcode(whl, standard=2003, source_format='free'))
do while (abs(delta) > tol)
delta = (val**3 - cos(val))/(-3*val**2 - sin(val))
val = val + delta
print *, val
end do
There is a function constructing a loop (or a complete function) like this in
:mod:`sympy.codegen.algorithms`.
"""
from typing import Any, Dict as tDict, List, Tuple as tTuple
from collections import defaultdict
from sympy.core.relational import (Ge, Gt, Le, Lt)
from sympy.core import Symbol, Tuple, Dummy
from sympy.core.basic import Basic
from sympy.core.expr import Expr, Atom
from sympy.core.numbers import Float, Integer, oo
from sympy.core.sympify import _sympify, sympify, SympifyError
from sympy.utilities.iterables import (iterable, topological_sort,
numbered_symbols, filter_symbols)
def _mk_Tuple(args):
"""
Create a SymPy Tuple object from an iterable, converting Python strings to
AST strings.
Parameters
==========
args: iterable
Arguments to :class:`sympy.Tuple`.
Returns
=======
sympy.Tuple
"""
args = [String(arg) if isinstance(arg, str) else arg for arg in args]
return Tuple(*args)
class CodegenAST(Basic):
__slots__ = ()
class Token(CodegenAST):
""" Base class for the AST types.
Explanation
===========
Defining fields are set in ``_fields``. Attributes (defined in _fields)
are only allowed to contain instances of Basic (unless atomic, see
``String``). The arguments to ``__new__()`` correspond to the attributes in
the order defined in ``_fields`. The ``defaults`` class attribute is a
dictionary mapping attribute names to their default values.
Subclasses should not need to override the ``__new__()`` method. They may
define a class or static method named ``_construct_<attr>`` for each
attribute to process the value passed to ``__new__()``. Attributes listed
in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`.
"""
__slots__ = _fields = () # type: tTuple[str, ...]
defaults = {} # type: tDict[str, Any]
not_in_args = [] # type: List[str]
indented_args = ['body']
@property
def is_Atom(self):
return len(self._fields) == 0
@classmethod
def _get_constructor(cls, attr):
""" Get the constructor function for an attribute by name. """
return getattr(cls, '_construct_%s' % attr, lambda x: x)
@classmethod
def _construct(cls, attr, arg):
""" Construct an attribute value from argument passed to ``__new__()``. """
# arg may be ``NoneToken()``, so comparation is done using == instead of ``is`` operator
if arg == None:
return cls.defaults.get(attr, none)
else:
if isinstance(arg, Dummy): # SymPy's replace uses Dummy instances
return arg
else:
return cls._get_constructor(attr)(arg)
def __new__(cls, *args, **kwargs):
# Pass through existing instances when given as sole argument
if len(args) == 1 and not kwargs and isinstance(args[0], cls):
return args[0]
if len(args) > len(cls._fields):
raise ValueError("Too many arguments (%d), expected at most %d" % (len(args), len(cls._fields)))
attrvals = []
# Process positional arguments
for attrname, argval in zip(cls._fields, args):
if attrname in kwargs:
raise TypeError('Got multiple values for attribute %r' % attrname)
attrvals.append(cls._construct(attrname, argval))
# Process keyword arguments
for attrname in cls._fields[len(args):]:
if attrname in kwargs:
argval = kwargs.pop(attrname)
elif attrname in cls.defaults:
argval = cls.defaults[attrname]
else:
raise TypeError('No value for %r given and attribute has no default' % attrname)
attrvals.append(cls._construct(attrname, argval))
if kwargs:
raise ValueError("Unknown keyword arguments: %s" % ' '.join(kwargs))
# Parent constructor
basic_args = [
val for attr, val in zip(cls._fields, attrvals)
if attr not in cls.not_in_args
]
obj = CodegenAST.__new__(cls, *basic_args)
# Set attributes
for attr, arg in zip(cls._fields, attrvals):
setattr(obj, attr, arg)
return obj
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
for attr in self._fields:
if getattr(self, attr) != getattr(other, attr):
return False
return True
def _hashable_content(self):
return tuple([getattr(self, attr) for attr in self._fields])
def __hash__(self):
return super().__hash__()
def _joiner(self, k, indent_level):
return (',\n' + ' '*indent_level) if k in self.indented_args else ', '
def _indented(self, printer, k, v, *args, **kwargs):
il = printer._context['indent_level']
def _print(arg):
if isinstance(arg, Token):
return printer._print(arg, *args, joiner=self._joiner(k, il), **kwargs)
else:
return printer._print(arg, *args, **kwargs)
if isinstance(v, Tuple):
joined = self._joiner(k, il).join([_print(arg) for arg in v.args])
if k in self.indented_args:
return '(\n' + ' '*il + joined + ',\n' + ' '*(il - 4) + ')'
else:
return ('({0},)' if len(v.args) == 1 else '({0})').format(joined)
else:
return _print(v)
def _sympyrepr(self, printer, *args, joiner=', ', **kwargs):
from sympy.printing.printer import printer_context
exclude = kwargs.get('exclude', ())
values = [getattr(self, k) for k in self._fields]
indent_level = printer._context.get('indent_level', 0)
arg_reprs = []
for i, (attr, value) in enumerate(zip(self._fields, values)):
if attr in exclude:
continue
# Skip attributes which have the default value
if attr in self.defaults and value == self.defaults[attr]:
continue
ilvl = indent_level + 4 if attr in self.indented_args else 0
with printer_context(printer, indent_level=ilvl):
indented = self._indented(printer, attr, value, *args, **kwargs)
arg_reprs.append(('{1}' if i == 0 else '{0}={1}').format(attr, indented.lstrip()))
return "{}({})".format(self.__class__.__name__, joiner.join(arg_reprs))
_sympystr = _sympyrepr
def __repr__(self): # sympy.core.Basic.__repr__ uses sstr
from sympy.printing import srepr
return srepr(self)
def kwargs(self, exclude=(), apply=None):
""" Get instance's attributes as dict of keyword arguments.
Parameters
==========
exclude : collection of str
Collection of keywords to exclude.
apply : callable, optional
Function to apply to all values.
"""
kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude}
if apply is not None:
return {k: apply(v) for k, v in kwargs.items()}
else:
return kwargs
class BreakToken(Token):
""" Represents 'break' in C/Python ('exit' in Fortran).
Use the premade instance ``break_`` or instantiate manually.
Examples
========
>>> from sympy import ccode, fcode
>>> from sympy.codegen.ast import break_
>>> ccode(break_)
'break'
>>> fcode(break_, source_format='free')
'exit'
"""
break_ = BreakToken()
class ContinueToken(Token):
""" Represents 'continue' in C/Python ('cycle' in Fortran)
Use the premade instance ``continue_`` or instantiate manually.
Examples
========
>>> from sympy import ccode, fcode
>>> from sympy.codegen.ast import continue_
>>> ccode(continue_)
'continue'
>>> fcode(continue_, source_format='free')
'cycle'
"""
continue_ = ContinueToken()
class NoneToken(Token):
""" The AST equivalence of Python's NoneType
The corresponding instance of Python's ``None`` is ``none``.
Examples
========
>>> from sympy.codegen.ast import none, Variable
>>> from sympy import pycode
>>> print(pycode(Variable('x').as_Declaration(value=none)))
x = None
"""
def __eq__(self, other):
return other is None or isinstance(other, NoneToken)
def _hashable_content(self):
return ()
def __hash__(self):
return super().__hash__()
none = NoneToken()
class AssignmentBase(CodegenAST):
""" Abstract base class for Assignment and AugmentedAssignment.
Attributes:
===========
op : str
Symbol for assignment operator, e.g. "=", "+=", etc.
"""
def __new__(cls, lhs, rhs):
lhs = _sympify(lhs)
rhs = _sympify(rhs)
cls._check_args(lhs, rhs)
return super().__new__(cls, lhs, rhs)
@property
def lhs(self):
return self.args[0]
@property
def rhs(self):
return self.args[1]
@classmethod
def _check_args(cls, lhs, rhs):
""" Check arguments to __new__ and raise exception if any problems found.
Derived classes may wish to override this.
"""
from sympy.matrices.expressions.matexpr import (
MatrixElement, MatrixSymbol)
from sympy.tensor.indexed import Indexed
from sympy.tensor.array.expressions import ArrayElement
# Tuple of things that can be on the lhs of an assignment
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Element, Variable,
ArrayElement)
if not isinstance(lhs, assignable):
raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
# Indexed types implement shape, but don't define it until later. This
# causes issues in assignment validation. For now, matrices are defined
# as anything with a shape that is not an Indexed
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
# If lhs and rhs have same structure, then this assignment is ok
if lhs_is_mat:
if not rhs_is_mat:
raise ValueError("Cannot assign a scalar to a matrix.")
elif lhs.shape != rhs.shape:
raise ValueError("Dimensions of lhs and rhs do not align.")
elif rhs_is_mat and not lhs_is_mat:
raise ValueError("Cannot assign a matrix to a scalar.")
class Assignment(AssignmentBase):
"""
Represents variable assignment for code generation.
Parameters
==========
lhs : Expr
SymPy object representing the lhs of the expression. These should be
singular objects, such as one would use in writing code. Notable types
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
subclass these types are also supported.
rhs : Expr
SymPy object representing the rhs of the expression. This can be any
type, provided its shape corresponds to that of the lhs. For example,
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
the dimensions will not align.
Examples
========
>>> from sympy import symbols, MatrixSymbol, Matrix
>>> from sympy.codegen.ast import Assignment
>>> x, y, z = symbols('x, y, z')
>>> Assignment(x, y)
Assignment(x, y)
>>> Assignment(x, 0)
Assignment(x, 0)
>>> A = MatrixSymbol('A', 1, 3)
>>> mat = Matrix([x, y, z]).T
>>> Assignment(A, mat)
Assignment(A, Matrix([[x, y, z]]))
>>> Assignment(A[0, 1], x)
Assignment(A[0, 1], x)
"""
op = ':='
class AugmentedAssignment(AssignmentBase):
"""
Base class for augmented assignments.
Attributes:
===========
binop : str
Symbol for binary operation being applied in the assignment, such as "+",
"*", etc.
"""
binop = None # type: str
@property
def op(self):
return self.binop + '='
class AddAugmentedAssignment(AugmentedAssignment):
binop = '+'
class SubAugmentedAssignment(AugmentedAssignment):
binop = '-'
class MulAugmentedAssignment(AugmentedAssignment):
binop = '*'
class DivAugmentedAssignment(AugmentedAssignment):
binop = '/'
class ModAugmentedAssignment(AugmentedAssignment):
binop = '%'
# Mapping from binary op strings to AugmentedAssignment subclasses
augassign_classes = {
cls.binop: cls for cls in [
AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment,
DivAugmentedAssignment, ModAugmentedAssignment
]
}
def aug_assign(lhs, op, rhs):
"""
Create 'lhs op= rhs'.
Explanation
===========
Represents augmented variable assignment for code generation. This is a
convenience function. You can also use the AugmentedAssignment classes
directly, like AddAugmentedAssignment(x, y).
Parameters
==========
lhs : Expr
SymPy object representing the lhs of the expression. These should be
singular objects, such as one would use in writing code. Notable types
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
subclass these types are also supported.
op : str
Operator (+, -, /, \\*, %).
rhs : Expr
SymPy object representing the rhs of the expression. This can be any
type, provided its shape corresponds to that of the lhs. For example,
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
the dimensions will not align.
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import aug_assign
>>> x, y = symbols('x, y')
>>> aug_assign(x, '+', y)
AddAugmentedAssignment(x, y)
"""
if op not in augassign_classes:
raise ValueError("Unrecognized operator %s" % op)
return augassign_classes[op](lhs, rhs)
class CodeBlock(CodegenAST):
"""
Represents a block of code.
Explanation
===========
For now only assignments are supported. This restriction will be lifted in
the future.
Useful attributes on this object are:
``left_hand_sides``:
Tuple of left-hand sides of assignments, in order.
``left_hand_sides``:
Tuple of right-hand sides of assignments, in order.
``free_symbols``: Free symbols of the expressions in the right-hand sides
which do not appear in the left-hand side of an assignment.
Useful methods on this object are:
``topological_sort``:
Class method. Return a CodeBlock with assignments
sorted so that variables are assigned before they
are used.
``cse``:
Return a new CodeBlock with common subexpressions eliminated and
pulled out as assignments.
Examples
========
>>> from sympy import symbols, ccode
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y = symbols('x y')
>>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1))
>>> print(ccode(c))
x = 1;
y = x + 1;
"""
def __new__(cls, *args):
left_hand_sides = []
right_hand_sides = []
for i in args:
if isinstance(i, Assignment):
lhs, rhs = i.args
left_hand_sides.append(lhs)
right_hand_sides.append(rhs)
obj = CodegenAST.__new__(cls, *args)
obj.left_hand_sides = Tuple(*left_hand_sides)
obj.right_hand_sides = Tuple(*right_hand_sides)
return obj
def __iter__(self):
return iter(self.args)
def _sympyrepr(self, printer, *args, **kwargs):
il = printer._context.get('indent_level', 0)
joiner = ',\n' + ' '*il
joined = joiner.join(map(printer._print, self.args))
return ('{}(\n'.format(' '*(il-4) + self.__class__.__name__,) +
' '*il + joined + '\n' + ' '*(il - 4) + ')')
_sympystr = _sympyrepr
@property
def free_symbols(self):
return super().free_symbols - set(self.left_hand_sides)
@classmethod
def topological_sort(cls, assignments):
"""
Return a CodeBlock with topologically sorted assignments so that
variables are assigned before they are used.
Examples
========
The existing order of assignments is preserved as much as possible.
This function assumes that variables are assigned to only once.
This is a class constructor so that the default constructor for
CodeBlock can error when variables are used before they are assigned.
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y, z = symbols('x y z')
>>> assignments = [
... Assignment(x, y + z),
... Assignment(y, z + 1),
... Assignment(z, 2),
... ]
>>> CodeBlock.topological_sort(assignments)
CodeBlock(
Assignment(z, 2),
Assignment(y, z + 1),
Assignment(x, y + z)
)
"""
if not all(isinstance(i, Assignment) for i in assignments):
# Will support more things later
raise NotImplementedError("CodeBlock.topological_sort only supports Assignments")
if any(isinstance(i, AugmentedAssignment) for i in assignments):
raise NotImplementedError("CodeBlock.topological_sort does not yet work with AugmentedAssignments")
# Create a graph where the nodes are assignments and there is a directed edge
# between nodes that use a variable and nodes that assign that
# variable, like
# [(x := 1, y := x + 1), (x := 1, z := y + z), (y := x + 1, z := y + z)]
# If we then topologically sort these nodes, they will be in
# assignment order, like
# x := 1
# y := x + 1
# z := y + z
# A = The nodes
#
# enumerate keeps nodes in the same order they are already in if
# possible. It will also allow us to handle duplicate assignments to
# the same variable when those are implemented.
A = list(enumerate(assignments))
# var_map = {variable: [nodes for which this variable is assigned to]}
# like {x: [(1, x := y + z), (4, x := 2 * w)], ...}
var_map = defaultdict(list)
for node in A:
i, a = node
var_map[a.lhs].append(node)
# E = Edges in the graph
E = []
for dst_node in A:
i, a = dst_node
for s in a.rhs.free_symbols:
for src_node in var_map[s]:
E.append((src_node, dst_node))
ordered_assignments = topological_sort([A, E])
# De-enumerate the result
return cls(*[a for i, a in ordered_assignments])
def cse(self, symbols=None, optimizations=None, postprocess=None,
order='canonical'):
"""
Return a new code block with common subexpressions eliminated.
Explanation
===========
See the docstring of :func:`sympy.simplify.cse_main.cse` for more
information.
Examples
========
>>> from sympy import symbols, sin
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y, z = symbols('x y z')
>>> c = CodeBlock(
... Assignment(x, 1),
... Assignment(y, sin(x) + 1),
... Assignment(z, sin(x) - 1),
... )
...
>>> c.cse()
CodeBlock(
Assignment(x, 1),
Assignment(x0, sin(x)),
Assignment(y, x0 + 1),
Assignment(z, x0 - 1)
)
"""
from sympy.simplify.cse_main import cse
# Check that the CodeBlock only contains assignments to unique variables
if not all(isinstance(i, Assignment) for i in self.args):
# Will support more things later
raise NotImplementedError("CodeBlock.cse only supports Assignments")
if any(isinstance(i, AugmentedAssignment) for i in self.args):
raise NotImplementedError("CodeBlock.cse does not yet work with AugmentedAssignments")
for i, lhs in enumerate(self.left_hand_sides):
if lhs in self.left_hand_sides[:i]:
raise NotImplementedError("Duplicate assignments to the same "
"variable are not yet supported (%s)" % lhs)
# Ensure new symbols for subexpressions do not conflict with existing
existing_symbols = self.atoms(Symbol)
if symbols is None:
symbols = numbered_symbols()
symbols = filter_symbols(symbols, existing_symbols)
replacements, reduced_exprs = cse(list(self.right_hand_sides),
symbols=symbols, optimizations=optimizations, postprocess=postprocess,
order=order)
new_block = [Assignment(var, expr) for var, expr in
zip(self.left_hand_sides, reduced_exprs)]
new_assignments = [Assignment(var, expr) for var, expr in replacements]
return self.topological_sort(new_assignments + new_block)
class For(Token):
"""Represents a 'for-loop' in the code.
Expressions are of the form:
"for target in iter:
body..."
Parameters
==========
target : symbol
iter : iterable
body : CodeBlock or iterable
! When passed an iterable it is used to instantiate a CodeBlock.
Examples
========
>>> from sympy import symbols, Range
>>> from sympy.codegen.ast import aug_assign, For
>>> x, i, j, k = symbols('x i j k')
>>> for_i = For(i, Range(10), [aug_assign(x, '+', i*j*k)])
>>> for_i # doctest: -NORMALIZE_WHITESPACE
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
>>> for_ji = For(j, Range(7), [for_i])
>>> for_ji # doctest: -NORMALIZE_WHITESPACE
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
))
>>> for_kji =For(k, Range(5), [for_ji])
>>> for_kji # doctest: -NORMALIZE_WHITESPACE
For(k, iterable=Range(0, 5, 1), body=CodeBlock(
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
))
))
"""
__slots__ = _fields = ('target', 'iterable', 'body')
_construct_target = staticmethod(_sympify)
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
@classmethod
def _construct_iterable(cls, itr):
if not iterable(itr):
raise TypeError("iterable must be an iterable")
if isinstance(itr, list): # _sympify errors on lists because they are mutable
itr = tuple(itr)
return _sympify(itr)
class String(Atom, Token):
""" SymPy object representing a string.
Atomic object which is not an expression (as opposed to Symbol).
Parameters
==========
text : str
Examples
========
>>> from sympy.codegen.ast import String
>>> f = String('foo')
>>> f
foo
>>> str(f)
'foo'
>>> f.text
'foo'
>>> print(repr(f))
String('foo')
"""
__slots__ = _fields = ('text',)
not_in_args = ['text']
is_Atom = True
@classmethod
def _construct_text(cls, text):
if not isinstance(text, str):
raise TypeError("Argument text is not a string type.")
return text
def _sympystr(self, printer, *args, **kwargs):
return self.text
def kwargs(self, exclude = (), apply = None):
return {}
#to be removed when Atom is given a suitable func
@property
def func(self):
return lambda: self
def _latex(self, printer):
from sympy.printing.latex import latex_escape
return r'\texttt{{"{}"}}'.format(latex_escape(self.text))
class QuotedString(String):
""" Represents a string which should be printed with quotes. """
class Comment(String):
""" Represents a comment. """
class Node(Token):
""" Subclass of Token, carrying the attribute 'attrs' (Tuple)
Examples
========
>>> from sympy.codegen.ast import Node, value_const, pointer_const
>>> n1 = Node([value_const])
>>> n1.attr_params('value_const') # get the parameters of attribute (by name)
()
>>> from sympy.codegen.fnodes import dimension
>>> n2 = Node([value_const, dimension(5, 3)])
>>> n2.attr_params(value_const) # get the parameters of attribute (by Attribute instance)
()
>>> n2.attr_params('dimension') # get the parameters of attribute (by name)
(5, 3)
>>> n2.attr_params(pointer_const) is None
True
"""
__slots__ = _fields = ('attrs',) # type: tTuple[str, ...]
defaults = {'attrs': Tuple()} # type: tDict[str, Any]
_construct_attrs = staticmethod(_mk_Tuple)
def attr_params(self, looking_for):
""" Returns the parameters of the Attribute with name ``looking_for`` in self.attrs """
for attr in self.attrs:
if str(attr.name) == str(looking_for):
return attr.parameters
class Type(Token):
""" Represents a type.
Explanation
===========
The naming is a super-set of NumPy naming. Type has a classmethod
``from_expr`` which offer type deduction. It also has a method
``cast_check`` which casts the argument to its type, possibly raising an
exception if rounding error is not within tolerances, or if the value is not
representable by the underlying data type (e.g. unsigned integers).
Parameters
==========
name : str
Name of the type, e.g. ``object``, ``int16``, ``float16`` (where the latter two
would use the ``Type`` sub-classes ``IntType`` and ``FloatType`` respectively).
If a ``Type`` instance is given, the said instance is returned.
Examples
========
>>> from sympy.codegen.ast import Type
>>> t = Type.from_expr(42)
>>> t
integer
>>> print(repr(t))
IntBaseType(String('integer'))
>>> from sympy.codegen.ast import uint8
>>> uint8.cast_check(-1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Minimum value for data type bigger than new value.
>>> from sympy.codegen.ast import float32
>>> v6 = 0.123456
>>> float32.cast_check(v6)
0.123456
>>> v10 = 12345.67894
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> boost_mp50 = Type('boost::multiprecision::cpp_dec_float_50')
>>> from sympy import cxxcode
>>> from sympy.codegen.ast import Declaration, Variable
>>> cxxcode(Declaration(Variable('x', type=boost_mp50)))
'boost::multiprecision::cpp_dec_float_50 x'
References
==========
.. [1] https://docs.scipy.org/doc/numpy/user/basics.types.html
"""
__slots__ = _fields = ('name',) # type: tTuple[str, ...]
_construct_name = String
def _sympystr(self, printer, *args, **kwargs):
return str(self.name)
@classmethod
def from_expr(cls, expr):
""" Deduces type from an expression or a ``Symbol``.
Parameters
==========
expr : number or SymPy object
The type will be deduced from type or properties.
Examples
========
>>> from sympy.codegen.ast import Type, integer, complex_
>>> Type.from_expr(2) == integer
True
>>> from sympy import Symbol
>>> Type.from_expr(Symbol('z', complex=True)) == complex_
True
>>> Type.from_expr(sum) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Could not deduce type from expr.
Raises
======
ValueError when type deduction fails.
"""
if isinstance(expr, (float, Float)):
return real
if isinstance(expr, (int, Integer)) or getattr(expr, 'is_integer', False):
return integer
if getattr(expr, 'is_real', False):
return real
if isinstance(expr, complex) or getattr(expr, 'is_complex', False):
return complex_
if isinstance(expr, bool) or getattr(expr, 'is_Relational', False):
return bool_
else:
raise ValueError("Could not deduce type from expr.")
def _check(self, value):
pass
def cast_check(self, value, rtol=None, atol=0, precision_targets=None):
""" Casts a value to the data type of the instance.
Parameters
==========
value : number
rtol : floating point number
Relative tolerance. (will be deduced if not given).
atol : floating point number
Absolute tolerance (in addition to ``rtol``).
type_aliases : dict
Maps substitutions for Type, e.g. {integer: int64, real: float32}
Examples
========
>>> from sympy.codegen.ast import integer, float32, int8
>>> integer.cast_check(3.0) == 3
True
>>> float32.cast_check(1e-40) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Minimum value for data type bigger than new value.
>>> int8.cast_check(256) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Maximum value for data type smaller than new value.
>>> v10 = 12345.67894
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> from sympy.codegen.ast import float64
>>> float64.cast_check(v10)
12345.67894
>>> from sympy import Float
>>> v18 = Float('0.123456789012345646')
>>> float64.cast_check(v18)
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> from sympy.codegen.ast import float80
>>> float80.cast_check(v18)
0.123456789012345649
"""
val = sympify(value)
ten = Integer(10)
exp10 = getattr(self, 'decimal_dig', None)
if rtol is None:
rtol = 1e-15 if exp10 is None else 2.0*ten**(-exp10)
def tol(num):
return atol + rtol*abs(num)
new_val = self.cast_nocheck(value)
self._check(new_val)
delta = new_val - val
if abs(delta) > tol(val): # rounding, e.g. int(3.5) != 3.5
raise ValueError("Casting gives a significantly different value.")
return new_val
def _latex(self, printer):
from sympy.printing.latex import latex_escape
type_name = latex_escape(self.__class__.__name__)
name = latex_escape(self.name.text)
return r"\text{{{}}}\left(\texttt{{{}}}\right)".format(type_name, name)
class IntBaseType(Type):
""" Integer base type, contains no size information. """
__slots__ = ()
cast_nocheck = lambda self, i: Integer(int(i))
class _SizedIntType(IntBaseType):
__slots__ = ('nbits',)
_fields = Type._fields + __slots__
_construct_nbits = Integer
def _check(self, value):
if value < self.min:
raise ValueError("Value is too small: %d < %d" % (value, self.min))
if value > self.max:
raise ValueError("Value is too big: %d > %d" % (value, self.max))
class SignedIntType(_SizedIntType):
""" Represents a signed integer type. """
__slots__ = ()
@property
def min(self):
return -2**(self.nbits-1)
@property
def max(self):
return 2**(self.nbits-1) - 1
class UnsignedIntType(_SizedIntType):
""" Represents an unsigned integer type. """
__slots__ = ()
@property
def min(self):
return 0
@property
def max(self):
return 2**self.nbits - 1
two = Integer(2)
class FloatBaseType(Type):
""" Represents a floating point number type. """
__slots__ = ()
cast_nocheck = Float
class FloatType(FloatBaseType):
""" Represents a floating point type with fixed bit width.
Base 2 & one sign bit is assumed.
Parameters
==========
name : str
Name of the type.
nbits : integer
Number of bits used (storage).
nmant : integer
Number of bits used to represent the mantissa.
nexp : integer
Number of bits used to represent the mantissa.
Examples
========
>>> from sympy import S
>>> from sympy.codegen.ast import FloatType
>>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5)
>>> half_precision.max
65504
>>> half_precision.tiny == S(2)**-14
True
>>> half_precision.eps == S(2)**-10
True
>>> half_precision.dig == 3
True
>>> half_precision.decimal_dig == 5
True
>>> half_precision.cast_check(1.0)
1.0
>>> half_precision.cast_check(1e5) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Maximum value for data type smaller than new value.
"""
__slots__ = ('nbits', 'nmant', 'nexp',)
_fields = Type._fields + __slots__
_construct_nbits = _construct_nmant = _construct_nexp = Integer
@property
def max_exponent(self):
""" The largest positive number n, such that 2**(n - 1) is a representable finite value. """
# cf. C++'s ``std::numeric_limits::max_exponent``
return two**(self.nexp - 1)
@property
def min_exponent(self):
""" The lowest negative number n, such that 2**(n - 1) is a valid normalized number. """
# cf. C++'s ``std::numeric_limits::min_exponent``
return 3 - self.max_exponent
@property
def max(self):
""" Maximum value representable. """
return (1 - two**-(self.nmant+1))*two**self.max_exponent
@property
def tiny(self):
""" The minimum positive normalized value. """
# See C macros: FLT_MIN, DBL_MIN, LDBL_MIN
# or C++'s ``std::numeric_limits::min``
# or numpy.finfo(dtype).tiny
return two**(self.min_exponent - 1)
@property
def eps(self):
""" Difference between 1.0 and the next representable value. """
return two**(-self.nmant)
@property
def dig(self):
""" Number of decimal digits that are guaranteed to be preserved in text.
When converting text -> float -> text, you are guaranteed that at least ``dig``
number of digits are preserved with respect to rounding or overflow.
"""
from sympy.functions import floor, log
return floor(self.nmant * log(2)/log(10))
@property
def decimal_dig(self):
""" Number of digits needed to store & load without loss.
Explanation
===========
Number of decimal digits needed to guarantee that two consecutive conversions
(float -> text -> float) to be idempotent. This is useful when one do not want
to loose precision due to rounding errors when storing a floating point value
as text.
"""
from sympy.functions import ceiling, log
return ceiling((self.nmant + 1) * log(2)/log(10) + 1)
def cast_nocheck(self, value):
""" Casts without checking if out of bounds or subnormal. """
if value == oo: # float(oo) or oo
return float(oo)
elif value == -oo: # float(-oo) or -oo
return float(-oo)
return Float(str(sympify(value).evalf(self.decimal_dig)), self.decimal_dig)
def _check(self, value):
if value < -self.max:
raise ValueError("Value is too small: %d < %d" % (value, -self.max))
if value > self.max:
raise ValueError("Value is too big: %d > %d" % (value, self.max))
if abs(value) < self.tiny:
raise ValueError("Smallest (absolute) value for data type bigger than new value.")
class ComplexBaseType(FloatBaseType):
__slots__ = ()
def cast_nocheck(self, value):
""" Casts without checking if out of bounds or subnormal. """
from sympy.functions import re, im
return (
super().cast_nocheck(re(value)) +
super().cast_nocheck(im(value))*1j
)
def _check(self, value):
from sympy.functions import re, im
super()._check(re(value))
super()._check(im(value))
class ComplexType(ComplexBaseType, FloatType):
""" Represents a complex floating point number. """
__slots__ = ()
# NumPy types:
intc = IntBaseType('intc')
intp = IntBaseType('intp')
int8 = SignedIntType('int8', 8)
int16 = SignedIntType('int16', 16)
int32 = SignedIntType('int32', 32)
int64 = SignedIntType('int64', 64)
uint8 = UnsignedIntType('uint8', 8)
uint16 = UnsignedIntType('uint16', 16)
uint32 = UnsignedIntType('uint32', 32)
uint64 = UnsignedIntType('uint64', 64)
float16 = FloatType('float16', 16, nexp=5, nmant=10) # IEEE 754 binary16, Half precision
float32 = FloatType('float32', 32, nexp=8, nmant=23) # IEEE 754 binary32, Single precision
float64 = FloatType('float64', 64, nexp=11, nmant=52) # IEEE 754 binary64, Double precision
float80 = FloatType('float80', 80, nexp=15, nmant=63) # x86 extended precision (1 integer part bit), "long double"
float128 = FloatType('float128', 128, nexp=15, nmant=112) # IEEE 754 binary128, Quadruple precision
float256 = FloatType('float256', 256, nexp=19, nmant=236) # IEEE 754 binary256, Octuple precision
complex64 = ComplexType('complex64', nbits=64, **float32.kwargs(exclude=('name', 'nbits')))
complex128 = ComplexType('complex128', nbits=128, **float64.kwargs(exclude=('name', 'nbits')))
# Generic types (precision may be chosen by code printers):
untyped = Type('untyped')
real = FloatBaseType('real')
integer = IntBaseType('integer')
complex_ = ComplexBaseType('complex')
bool_ = Type('bool')
class Attribute(Token):
""" Attribute (possibly parametrized)
For use with :class:`sympy.codegen.ast.Node` (which takes instances of
``Attribute`` as ``attrs``).
Parameters
==========
name : str
parameters : Tuple
Examples
========
>>> from sympy.codegen.ast import Attribute
>>> volatile = Attribute('volatile')
>>> volatile
volatile
>>> print(repr(volatile))
Attribute(String('volatile'))
>>> a = Attribute('foo', [1, 2, 3])
>>> a
foo(1, 2, 3)
>>> a.parameters == (1, 2, 3)
True
"""
__slots__ = _fields = ('name', 'parameters')
defaults = {'parameters': Tuple()}
_construct_name = String
_construct_parameters = staticmethod(_mk_Tuple)
def _sympystr(self, printer, *args, **kwargs):
result = str(self.name)
if self.parameters:
result += '(%s)' % ', '.join(map(lambda arg: printer._print(
arg, *args, **kwargs), self.parameters))
return result
value_const = Attribute('value_const')
pointer_const = Attribute('pointer_const')
class Variable(Node):
""" Represents a variable.
Parameters
==========
symbol : Symbol
type : Type (optional)
Type of the variable.
attrs : iterable of Attribute instances
Will be stored as a Tuple.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Variable, float32, integer
>>> x = Symbol('x')
>>> v = Variable(x, type=float32)
>>> v.attrs
()
>>> v == Variable('x')
False
>>> v == Variable('x', type=float32)
True
>>> v
Variable(x, type=float32)
One may also construct a ``Variable`` instance with the type deduced from
assumptions about the symbol using the ``deduced`` classmethod:
>>> i = Symbol('i', integer=True)
>>> v = Variable.deduced(i)
>>> v.type == integer
True
>>> v == Variable('i')
False
>>> from sympy.codegen.ast import value_const
>>> value_const in v.attrs
False
>>> w = Variable('w', attrs=[value_const])
>>> w
Variable(w, attrs=(value_const,))
>>> value_const in w.attrs
True
>>> w.as_Declaration(value=42)
Declaration(Variable(w, value=42, attrs=(value_const,)))
"""
__slots__ = ('symbol', 'type', 'value')
_fields = __slots__ + Node._fields
defaults = Node.defaults.copy()
defaults.update({'type': untyped, 'value': none})
_construct_symbol = staticmethod(sympify)
_construct_value = staticmethod(sympify)
@classmethod
def deduced(cls, symbol, value=None, attrs=Tuple(), cast_check=True):
""" Alt. constructor with type deduction from ``Type.from_expr``.
Deduces type primarily from ``symbol``, secondarily from ``value``.
Parameters
==========
symbol : Symbol
value : expr
(optional) value of the variable.
attrs : iterable of Attribute instances
cast_check : bool
Whether to apply ``Type.cast_check`` on ``value``.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Variable, complex_
>>> n = Symbol('n', integer=True)
>>> str(Variable.deduced(n).type)
'integer'
>>> x = Symbol('x', real=True)
>>> v = Variable.deduced(x)
>>> v.type
real
>>> z = Symbol('z', complex=True)
>>> Variable.deduced(z).type == complex_
True
"""
if isinstance(symbol, Variable):
return symbol
try:
type_ = Type.from_expr(symbol)
except ValueError:
type_ = Type.from_expr(value)
if value is not None and cast_check:
value = type_.cast_check(value)
return cls(symbol, type=type_, value=value, attrs=attrs)
def as_Declaration(self, **kwargs):
""" Convenience method for creating a Declaration instance.
Explanation
===========
If the variable of the Declaration need to wrap a modified
variable keyword arguments may be passed (overriding e.g.
the ``value`` of the Variable instance).
Examples
========
>>> from sympy.codegen.ast import Variable, NoneToken
>>> x = Variable('x')
>>> decl1 = x.as_Declaration()
>>> # value is special NoneToken() which must be tested with == operator
>>> decl1.variable.value is None # won't work
False
>>> decl1.variable.value == None # not PEP-8 compliant
True
>>> decl1.variable.value == NoneToken() # OK
True
>>> decl2 = x.as_Declaration(value=42.0)
>>> decl2.variable.value == 42
True
"""
kw = self.kwargs()
kw.update(kwargs)
return Declaration(self.func(**kw))
def _relation(self, rhs, op):
try:
rhs = _sympify(rhs)
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, rhs))
return op(self, rhs, evaluate=False)
__lt__ = lambda self, other: self._relation(other, Lt)
__le__ = lambda self, other: self._relation(other, Le)
__ge__ = lambda self, other: self._relation(other, Ge)
__gt__ = lambda self, other: self._relation(other, Gt)
class Pointer(Variable):
""" Represents a pointer. See ``Variable``.
Examples
========
Can create instances of ``Element``:
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Pointer
>>> i = Symbol('i', integer=True)
>>> p = Pointer('x')
>>> p[i+1]
Element(x, indices=(i + 1,))
"""
__slots__ = ()
def __getitem__(self, key):
try:
return Element(self.symbol, key)
except TypeError:
return Element(self.symbol, (key,))
class Element(Token):
""" Element in (a possibly N-dimensional) array.
Examples
========
>>> from sympy.codegen.ast import Element
>>> elem = Element('x', 'ijk')
>>> elem.symbol.name == 'x'
True
>>> elem.indices
(i, j, k)
>>> from sympy import ccode
>>> ccode(elem)
'x[i][j][k]'
>>> ccode(Element('x', 'ijk', strides='lmn', offset='o'))
'x[i*l + j*m + k*n + o]'
"""
__slots__ = _fields = ('symbol', 'indices', 'strides', 'offset')
defaults = {'strides': none, 'offset': none}
_construct_symbol = staticmethod(sympify)
_construct_indices = staticmethod(lambda arg: Tuple(*arg))
_construct_strides = staticmethod(lambda arg: Tuple(*arg))
_construct_offset = staticmethod(sympify)
class Declaration(Token):
""" Represents a variable declaration
Parameters
==========
variable : Variable
Examples
========
>>> from sympy.codegen.ast import Declaration, NoneToken, untyped
>>> z = Declaration('z')
>>> z.variable.type == untyped
True
>>> # value is special NoneToken() which must be tested with == operator
>>> z.variable.value is None # won't work
False
>>> z.variable.value == None # not PEP-8 compliant
True
>>> z.variable.value == NoneToken() # OK
True
"""
__slots__ = _fields = ('variable',)
_construct_variable = Variable
class While(Token):
""" Represents a 'for-loop' in the code.
Expressions are of the form:
"while condition:
body..."
Parameters
==========
condition : expression convertible to Boolean
body : CodeBlock or iterable
When passed an iterable it is used to instantiate a CodeBlock.
Examples
========
>>> from sympy import symbols, Gt, Abs
>>> from sympy.codegen import aug_assign, Assignment, While
>>> x, dx = symbols('x dx')
>>> expr = 1 - x**2
>>> whl = While(Gt(Abs(dx), 1e-9), [
... Assignment(dx, -expr/expr.diff(x)),
... aug_assign(x, '+', dx)
... ])
"""
__slots__ = _fields = ('condition', 'body')
_construct_condition = staticmethod(lambda cond: _sympify(cond))
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class Scope(Token):
""" Represents a scope in the code.
Parameters
==========
body : CodeBlock or iterable
When passed an iterable it is used to instantiate a CodeBlock.
"""
__slots__ = _fields = ('body',)
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class Stream(Token):
""" Represents a stream.
There are two predefined Stream instances ``stdout`` & ``stderr``.
Parameters
==========
name : str
Examples
========
>>> from sympy import pycode, Symbol
>>> from sympy.codegen.ast import Print, stderr, QuotedString
>>> print(pycode(Print(['x'], file=stderr)))
print(x, file=sys.stderr)
>>> x = Symbol('x')
>>> print(pycode(Print([QuotedString('x')], file=stderr))) # print literally "x"
print("x", file=sys.stderr)
"""
__slots__ = _fields = ('name',)
_construct_name = String
stdout = Stream('stdout')
stderr = Stream('stderr')
class Print(Token):
""" Represents print command in the code.
Parameters
==========
formatstring : str
*args : Basic instances (or convertible to such through sympify)
Examples
========
>>> from sympy.codegen.ast import Print
>>> from sympy import pycode
>>> print(pycode(Print('x y'.split(), "coordinate: %12.5g %12.5g")))
print("coordinate: %12.5g %12.5g" % (x, y))
"""
__slots__ = _fields = ('print_args', 'format_string', 'file')
defaults = {'format_string': none, 'file': none}
_construct_print_args = staticmethod(_mk_Tuple)
_construct_format_string = QuotedString
_construct_file = Stream
class FunctionPrototype(Node):
""" Represents a function prototype
Allows the user to generate forward declaration in e.g. C/C++.
Parameters
==========
return_type : Type
name : str
parameters: iterable of Variable instances
attrs : iterable of Attribute instances
Examples
========
>>> from sympy import ccode, symbols
>>> from sympy.codegen.ast import real, FunctionPrototype
>>> x, y = symbols('x y', real=True)
>>> fp = FunctionPrototype(real, 'foo', [x, y])
>>> ccode(fp)
'double foo(double x, double y)'
"""
__slots__ = ('return_type', 'name', 'parameters')
_fields = __slots__ + Node._fields # type: tTuple[str, ...]
_construct_return_type = Type
_construct_name = String
@staticmethod
def _construct_parameters(args):
def _var(arg):
if isinstance(arg, Declaration):
return arg.variable
elif isinstance(arg, Variable):
return arg
else:
return Variable.deduced(arg)
return Tuple(*map(_var, args))
@classmethod
def from_FunctionDefinition(cls, func_def):
if not isinstance(func_def, FunctionDefinition):
raise TypeError("func_def is not an instance of FunctionDefiniton")
return cls(**func_def.kwargs(exclude=('body',)))
class FunctionDefinition(FunctionPrototype):
""" Represents a function definition in the code.
Parameters
==========
return_type : Type
name : str
parameters: iterable of Variable instances
body : CodeBlock or iterable
attrs : iterable of Attribute instances
Examples
========
>>> from sympy import ccode, symbols
>>> from sympy.codegen.ast import real, FunctionPrototype
>>> x, y = symbols('x y', real=True)
>>> fp = FunctionPrototype(real, 'foo', [x, y])
>>> ccode(fp)
'double foo(double x, double y)'
>>> from sympy.codegen.ast import FunctionDefinition, Return
>>> body = [Return(x*y)]
>>> fd = FunctionDefinition.from_FunctionPrototype(fp, body)
>>> print(ccode(fd))
double foo(double x, double y){
return x*y;
}
"""
__slots__ = ('body', )
_fields = FunctionPrototype._fields[:-1] + __slots__ + Node._fields
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
@classmethod
def from_FunctionPrototype(cls, func_proto, body):
if not isinstance(func_proto, FunctionPrototype):
raise TypeError("func_proto is not an instance of FunctionPrototype")
return cls(body=body, **func_proto.kwargs())
class Return(Token):
""" Represents a return command in the code.
Parameters
==========
return : Basic
Examples
========
>>> from sympy.codegen.ast import Return
>>> from sympy.printing.pycode import pycode
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> print(pycode(Return(x)))
return x
"""
__slots__ = _fields = ('return',)
_construct_return=staticmethod(_sympify)
class FunctionCall(Token, Expr):
""" Represents a call to a function in the code.
Parameters
==========
name : str
function_args : Tuple
Examples
========
>>> from sympy.codegen.ast import FunctionCall
>>> from sympy import pycode
>>> fcall = FunctionCall('foo', 'bar baz'.split())
>>> print(pycode(fcall))
foo(bar, baz)
"""
__slots__ = _fields = ('name', 'function_args')
_construct_name = String
_construct_function_args = staticmethod(lambda args: Tuple(*args))
|
7f19db55b66bb841d74310790da4130ba935422f01ad6690dcbc01b92659af29 | """A functions module, includes all the standard functions.
Combinatorial - factorial, fibonacci, harmonic, bernoulli...
Elementary - hyperbolic, trigonometric, exponential, floor and ceiling, sqrt...
Special - gamma, zeta,spherical harmonics...
"""
from sympy.functions.combinatorial.factorials import (factorial, factorial2,
rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial)
from sympy.functions.combinatorial.numbers import (carmichael, fibonacci, lucas, tribonacci,
harmonic, bernoulli, bell, euler, catalan, genocchi, andre, partition, motzkin)
from sympy.functions.elementary.miscellaneous import (sqrt, root, Min, Max,
Id, real_root, cbrt, Rem)
from sympy.functions.elementary.complexes import (re, im, sign, Abs,
conjugate, arg, polar_lift, periodic_argument, unbranched_argument,
principal_branch, transpose, adjoint, polarify, unpolarify)
from sympy.functions.elementary.trigonometric import (sin, cos, tan,
sec, csc, cot, sinc, asin, acos, atan, asec, acsc, acot, atan2)
from sympy.functions.elementary.exponential import (exp_polar, exp, log,
LambertW)
from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
from sympy.functions.elementary.integers import floor, ceiling, frac
from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold,
piecewise_exclusive)
from sympy.functions.special.error_functions import (erf, erfc, erfi, erf2,
erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
fresnels, fresnelc)
from sympy.functions.special.gamma_functions import (gamma, lowergamma,
uppergamma, polygamma, loggamma, digamma, trigamma, multigamma)
from sympy.functions.special.zeta_functions import (dirichlet_eta, zeta,
lerchphi, polylog, stieltjes, riemann_xi)
from sympy.functions.special.tensor_functions import (Eijk, LeviCivita,
KroneckerDelta)
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set, interpolating_spline
from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq)
from sympy.functions.special.hyper import hyper, meijerg, appellf1
from sympy.functions.special.polynomials import (legendre, assoc_legendre,
hermite, hermite_prob, chebyshevt, chebyshevu, chebyshevu_root,
chebyshevt_root, laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized)
from sympy.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
from sympy.functions.special.elliptic_integrals import (elliptic_k,
elliptic_f, elliptic_e, elliptic_pi)
from sympy.functions.special.beta_functions import beta, betainc, betainc_regularized
from sympy.functions.special.mathieu_functions import (mathieus, mathieuc,
mathieusprime, mathieucprime)
ln = log
__all__ = [
'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
'FallingFactorial', 'subfactorial',
'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic',
'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'andre', 'partition',
'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'cbrt', 'Rem',
're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
'periodic_argument', 'unbranched_argument', 'principal_branch',
'transpose', 'adjoint', 'polarify', 'unpolarify',
'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan',
'asec', 'acsc', 'acot', 'atan2',
'exp_polar', 'exp', 'ln', 'log', 'LambertW',
'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
'acoth', 'asech', 'acsch',
'floor', 'ceiling', 'frac',
'Piecewise', 'piecewise_fold', 'piecewise_exclusive',
'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei',
'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels',
'fresnelc',
'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma',
'trigamma', 'multigamma',
'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'riemann_xi',
'Eijk', 'LeviCivita', 'KroneckerDelta',
'SingularityFunction',
'DiracDelta', 'Heaviside',
'bspline_basis', 'bspline_basis_set', 'interpolating_spline',
'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn',
'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
'airybiprime', 'marcumq',
'hyper', 'meijerg', 'appellf1',
'legendre', 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt',
'chebyshevu', 'chebyshevu_root', 'chebyshevt_root', 'laguerre',
'assoc_laguerre', 'gegenbauer', 'jacobi', 'jacobi_normalized',
'Ynm', 'Ynm_c', 'Znm',
'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi',
'beta', 'betainc', 'betainc_regularized',
'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
]
|
88ba9b08ebf7be6561340088b9ad8d092bd7e4c43771efb7ce4a7bd60c44c99a | """
This module contain solvers for all kinds of equations:
- algebraic or transcendental, use solve()
- recurrence, use rsolve()
- differential, use dsolve()
- nonlinear (numerically), use nsolve()
(you will need a good starting point)
"""
from sympy.core import (S, Add, Symbol, Dummy, Expr, Mul)
from sympy.core.assumptions import check_assumptions
from sympy.core.exprtools import factor_terms
from sympy.core.function import (expand_mul, expand_log, Derivative,
AppliedUndef, UndefinedFunction, nfloat,
Function, expand_power_exp, _mexpand, expand,
expand_func)
from sympy.core.logic import fuzzy_not
from sympy.core.numbers import ilcm, Float, Rational, _illegal
from sympy.core.power import integer_log, Pow
from sympy.core.relational import Eq, Ne
from sympy.core.sorting import ordered, default_sort_key
from sympy.core.sympify import sympify, _sympify
from sympy.core.traversal import preorder_traversal
from sympy.logic.boolalg import And, BooleanAtom
from sympy.functions import (log, exp, LambertW, cos, sin, tan, acos, asin, atan,
Abs, re, im, arg, sqrt, atan2)
from sympy.functions.combinatorial.factorials import binomial
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.piecewise import piecewise_fold, Piecewise
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.integrals.integrals import Integral
from sympy.ntheory.factor_ import divisors
from sympy.simplify import (simplify, collect, powsimp, posify, # type: ignore
powdenest, nsimplify, denom, logcombine, sqrtdenest, fraction,
separatevars)
from sympy.simplify.sqrtdenest import sqrt_depth
from sympy.simplify.fu import TR1, TR2i
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.matrices import Matrix, zeros
from sympy.polys import roots, cancel, factor, Poly
from sympy.polys.polyerrors import GeneratorsNeeded, PolynomialError
from sympy.polys.solvers import sympy_eqs_to_ring, solve_lin_sys
from sympy.utilities.lambdify import lambdify
from sympy.utilities.misc import filldedent, debug
from sympy.utilities.iterables import (connected_components,
generate_bell, uniq, iterable, is_sequence, subsets, flatten)
from sympy.utilities.decorator import conserve_mpmath_dps
from mpmath import findroot
from sympy.solvers.polysys import solve_poly_system
from types import GeneratorType
from collections import defaultdict
from itertools import combinations, product
import warnings
def recast_to_symbols(eqs, symbols):
"""
Return (e, s, d) where e and s are versions of *eqs* and
*symbols* in which any non-Symbol objects in *symbols* have
been replaced with generic Dummy symbols and d is a dictionary
that can be used to restore the original expressions.
Examples
========
>>> from sympy.solvers.solvers import recast_to_symbols
>>> from sympy import symbols, Function
>>> x, y = symbols('x y')
>>> fx = Function('f')(x)
>>> eqs, syms = [fx + 1, x, y], [fx, y]
>>> e, s, d = recast_to_symbols(eqs, syms); (e, s, d)
([_X0 + 1, x, y], [_X0, y], {_X0: f(x)})
The original equations and symbols can be restored using d:
>>> assert [i.xreplace(d) for i in eqs] == eqs
>>> assert [d.get(i, i) for i in s] == syms
"""
if not iterable(eqs) and iterable(symbols):
raise ValueError('Both eqs and symbols must be iterable')
orig = list(symbols)
symbols = list(ordered(symbols))
swap_sym = {}
i = 0
for j, s in enumerate(symbols):
if not isinstance(s, Symbol) and s not in swap_sym:
swap_sym[s] = Dummy('X%d' % i)
i += 1
new_f = []
for i in eqs:
isubs = getattr(i, 'subs', None)
if isubs is not None:
new_f.append(isubs(swap_sym))
else:
new_f.append(i)
restore = {v: k for k, v in swap_sym.items()}
return new_f, [swap_sym.get(i, i) for i in orig], restore
def _ispow(e):
"""Return True if e is a Pow or is exp."""
return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp))
def _simple_dens(f, symbols):
# when checking if a denominator is zero, we can just check the
# base of powers with nonzero exponents since if the base is zero
# the power will be zero, too. To keep it simple and fast, we
# limit simplification to exponents that are Numbers
dens = set()
for d in denoms(f, symbols):
if d.is_Pow and d.exp.is_Number:
if d.exp.is_zero:
continue # foo**0 is never 0
d = d.base
dens.add(d)
return dens
def denoms(eq, *symbols):
"""
Return (recursively) set of all denominators that appear in *eq*
that contain any symbol in *symbols*; if *symbols* are not
provided then all denominators will be returned.
Examples
========
>>> from sympy.solvers.solvers import denoms
>>> from sympy.abc import x, y, z
>>> denoms(x/y)
{y}
>>> denoms(x/(y*z))
{y, z}
>>> denoms(3/x + y/z)
{x, z}
>>> denoms(x/2 + y/z)
{2, z}
If *symbols* are provided then only denominators containing
those symbols will be returned:
>>> denoms(1/x + 1/y + 1/z, y, z)
{y, z}
"""
pot = preorder_traversal(eq)
dens = set()
for p in pot:
# Here p might be Tuple or Relational
# Expr subtrees (e.g. lhs and rhs) will be traversed after by pot
if not isinstance(p, Expr):
continue
den = denom(p)
if den is S.One:
continue
for d in Mul.make_args(den):
dens.add(d)
if not symbols:
return dens
elif len(symbols) == 1:
if iterable(symbols[0]):
symbols = symbols[0]
return {d for d in dens if any(s in d.free_symbols for s in symbols)}
def checksol(f, symbol, sol=None, **flags):
"""
Checks whether sol is a solution of equation f == 0.
Explanation
===========
Input can be either a single symbol and corresponding value
or a dictionary of symbols and values. When given as a dictionary
and flag ``simplify=True``, the values in the dictionary will be
simplified. *f* can be a single equation or an iterable of equations.
A solution must satisfy all equations in *f* to be considered valid;
if a solution does not satisfy any equation, False is returned; if one or
more checks are inconclusive (and none are False) then None is returned.
Examples
========
>>> from sympy import checksol, symbols
>>> x, y = symbols('x,y')
>>> checksol(x**4 - 1, x, 1)
True
>>> checksol(x**4 - 1, x, 0)
False
>>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4})
True
To check if an expression is zero using ``checksol()``, pass it
as *f* and send an empty dictionary for *symbol*:
>>> checksol(x**2 + x - x*(x + 1), {})
True
None is returned if ``checksol()`` could not conclude.
flags:
'numerical=True (default)'
do a fast numerical check if ``f`` has only one symbol.
'minimal=True (default is False)'
a very fast, minimal testing.
'warn=True (default is False)'
show a warning if checksol() could not conclude.
'simplify=True (default)'
simplify solution before substituting into function and
simplify the function before trying specific simplifications
'force=True (default is False)'
make positive all symbols without assumptions regarding sign.
"""
from sympy.physics.units import Unit
minimal = flags.get('minimal', False)
if sol is not None:
sol = {symbol: sol}
elif isinstance(symbol, dict):
sol = symbol
else:
msg = 'Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)'
raise ValueError(msg % (symbol, sol))
if iterable(f):
if not f:
raise ValueError('no functions to check')
rv = True
for fi in f:
check = checksol(fi, sol, **flags)
if check:
continue
if check is False:
return False
rv = None # don't return, wait to see if there's a False
return rv
f = _sympify(f)
if f.is_number:
return f.is_zero
if isinstance(f, Poly):
f = f.as_expr()
elif isinstance(f, (Eq, Ne)):
if f.rhs in (S.true, S.false):
f = f.reversed
B, E = f.args
if isinstance(B, BooleanAtom):
f = f.subs(sol)
if not f.is_Boolean:
return
else:
f = f.rewrite(Add, evaluate=False)
if isinstance(f, BooleanAtom):
return bool(f)
elif not f.is_Relational and not f:
return True
illegal = set(_illegal)
if any(sympify(v).atoms() & illegal for k, v in sol.items()):
return False
was = f
attempt = -1
numerical = flags.get('numerical', True)
while 1:
attempt += 1
if attempt == 0:
val = f.subs(sol)
if isinstance(val, Mul):
val = val.as_independent(Unit)[0]
if val.atoms() & illegal:
return False
elif attempt == 1:
if not val.is_number:
if not val.is_constant(*list(sol.keys()), simplify=not minimal):
return False
# there are free symbols -- simple expansion might work
_, val = val.as_content_primitive()
val = _mexpand(val.as_numer_denom()[0], recursive=True)
elif attempt == 2:
if minimal:
return
if flags.get('simplify', True):
for k in sol:
sol[k] = simplify(sol[k])
# start over without the failed expanded form, possibly
# with a simplified solution
val = simplify(f.subs(sol))
if flags.get('force', True):
val, reps = posify(val)
# expansion may work now, so try again and check
exval = _mexpand(val, recursive=True)
if exval.is_number:
# we can decide now
val = exval
else:
# if there are no radicals and no functions then this can't be
# zero anymore -- can it?
pot = preorder_traversal(expand_mul(val))
seen = set()
saw_pow_func = False
for p in pot:
if p in seen:
continue
seen.add(p)
if p.is_Pow and not p.exp.is_Integer:
saw_pow_func = True
elif p.is_Function:
saw_pow_func = True
elif isinstance(p, UndefinedFunction):
saw_pow_func = True
if saw_pow_func:
break
if saw_pow_func is False:
return False
if flags.get('force', True):
# don't do a zero check with the positive assumptions in place
val = val.subs(reps)
nz = fuzzy_not(val.is_zero)
if nz is not None:
# issue 5673: nz may be True even when False
# so these are just hacks to keep a false positive
# from being returned
# HACK 1: LambertW (issue 5673)
if val.is_number and val.has(LambertW):
# don't eval this to verify solution since if we got here,
# numerical must be False
return None
# add other HACKs here if necessary, otherwise we assume
# the nz value is correct
return not nz
break
if numerical and val.is_number:
return (abs(val.n(18).n(12, chop=True)) < 1e-9) is S.true
if val == was:
continue
elif val.is_Rational:
return val == 0
was = val
if flags.get('warn', False):
warnings.warn("\n\tWarning: could not verify solution %s." % sol)
# returns None if it can't conclude
# TODO: improve solution testing
def solve(f, *symbols, **flags):
r"""
Algebraically solves equations and systems of equations.
Explanation
===========
Currently supported:
- polynomial
- transcendental
- piecewise combinations of the above
- systems of linear and polynomial equations
- systems containing relational expressions
- systems implied by undetermined coefficients
Examples
========
The default output varies according to the input and might
be a list (possibly empty), a dictionary, a list of
dictionaries or tuples, or an expression involving relationals.
For specifics regarding different forms of output that may appear, see :ref:`solve_output`.
Let it suffice here to say that to obtain a uniform output from
`solve` use ``dict=True`` or ``set=True`` (see below).
>>> from sympy import solve, Poly, Eq, Matrix, Symbol
>>> from sympy.abc import x, y, z, a, b
The expressions that are passed can be Expr, Equality, or Poly
classes (or lists of the same); a Matrix is considered to be a
list of all the elements of the matrix:
>>> solve(x - 3, x)
[3]
>>> solve(Eq(x, 3), x)
[3]
>>> solve(Poly(x - 3), x)
[3]
>>> solve(Matrix([[x, x + y]]), x, y) == solve([x, x + y], x, y)
True
If no symbols are indicated to be of interest and the equation is
univariate, a list of values is returned; otherwise, the keys in
a dictionary will indicate which (of all the variables used in
the expression(s)) variables and solutions were found:
>>> solve(x**2 - 4)
[-2, 2]
>>> solve((x - a)*(y - b))
[{a: x}, {b: y}]
>>> solve([x - 3, y - 1])
{x: 3, y: 1}
>>> solve([x - 3, y**2 - 1])
[{x: 3, y: -1}, {x: 3, y: 1}]
If you pass symbols for which solutions are sought, the output will vary
depending on the number of symbols you passed, whether you are passing
a list of expressions or not, and whether a linear system was solved.
Uniform output is attained by using ``dict=True`` or ``set=True``.
>>> #### *** feel free to skip to the stars below *** ####
>>> from sympy import TableForm
>>> h = [None, ';|;'.join(['e', 's', 'solve(e, s)', 'solve(e, s, dict=True)',
... 'solve(e, s, set=True)']).split(';')]
>>> t = []
>>> for e, s in [
... (x - y, y),
... (x - y, [x, y]),
... (x**2 - y, [x, y]),
... ([x - 3, y -1], [x, y]),
... ]:
... how = [{}, dict(dict=True), dict(set=True)]
... res = [solve(e, s, **f) for f in how]
... t.append([e, '|', s, '|'] + [res[0], '|', res[1], '|', res[2]])
...
>>> # ******************************************************* #
>>> TableForm(t, headings=h, alignments="<")
e | s | solve(e, s) | solve(e, s, dict=True) | solve(e, s, set=True)
---------------------------------------------------------------------------------------
x - y | y | [x] | [{y: x}] | ([y], {(x,)})
x - y | [x, y] | [(y, y)] | [{x: y}] | ([x, y], {(y, y)})
x**2 - y | [x, y] | [(x, x**2)] | [{y: x**2}] | ([x, y], {(x, x**2)})
[x - 3, y - 1] | [x, y] | {x: 3, y: 1} | [{x: 3, y: 1}] | ([x, y], {(3, 1)})
* If any equation does not depend on the symbol(s) given, it will be
eliminated from the equation set and an answer may be given
implicitly in terms of variables that were not of interest:
>>> solve([x - y, y - 3], x)
{x: y}
When you pass all but one of the free symbols, an attempt
is made to find a single solution based on the method of
undetermined coefficients. If it succeeds, a dictionary of values
is returned. If you want an algebraic solutions for one
or more of the symbols, pass the expression to be solved in a list:
>>> e = a*x + b - 2*x - 3
>>> solve(e, [a, b])
{a: 2, b: 3}
>>> solve([e], [a, b])
{a: -b/x + (2*x + 3)/x}
When there is no solution for any given symbol which will make all
expressions zero, the empty list is returned (or an empty set in
the tuple when ``set=True``):
>>> from sympy import sqrt
>>> solve(3, x)
[]
>>> solve(x - 3, y)
[]
>>> solve(sqrt(x) + 1, x, set=True)
([x], set())
When an object other than a Symbol is given as a symbol, it is
isolated algebraically and an implicit solution may be obtained.
This is mostly provided as a convenience to save you from replacing
the object with a Symbol and solving for that Symbol. It will only
work if the specified object can be replaced with a Symbol using the
subs method:
>>> from sympy import exp, Function
>>> f = Function('f')
>>> solve(f(x) - x, f(x))
[x]
>>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x))
[x + f(x)]
>>> solve(f(x).diff(x) - f(x) - x, f(x))
[-x + Derivative(f(x), x)]
>>> solve(x + exp(x)**2, exp(x), set=True)
([exp(x)], {(-sqrt(-x),), (sqrt(-x),)})
>>> from sympy import Indexed, IndexedBase, Tuple
>>> A = IndexedBase('A')
>>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1)
>>> solve(eqs, eqs.atoms(Indexed))
{A[1]: 1, A[2]: 2}
* To solve for a function within a derivative, use :func:`~.dsolve`.
To solve for a symbol implicitly, use implicit=True:
>>> solve(x + exp(x), x)
[-LambertW(1)]
>>> solve(x + exp(x), x, implicit=True)
[-exp(x)]
It is possible to solve for anything in an expression that can be
replaced with a symbol using :obj:`~sympy.core.basic.Basic.subs`:
>>> solve(x + 2 + sqrt(3), x + 2)
[-sqrt(3)]
>>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2)
{y: -2 + sqrt(3), x + 2: -sqrt(3)}
* Nothing heroic is done in this implicit solving so you may end up
with a symbol still in the solution:
>>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y)
>>> solve(eqs, y, x + 2)
{y: -sqrt(3)/(x + 3), x + 2: -2*x/(x + 3) - 6/(x + 3) + sqrt(3)/(x + 3)}
>>> solve(eqs, y*x, x)
{x: -y - 4, x*y: -3*y - sqrt(3)}
* If you attempt to solve for a number, remember that the number
you have obtained does not necessarily mean that the value is
equivalent to the expression obtained:
>>> solve(sqrt(2) - 1, 1)
[sqrt(2)]
>>> solve(x - y + 1, 1) # /!\ -1 is targeted, too
[x/(y - 1)]
>>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)]
[-x + y]
**Additional Examples**
``solve()`` with check=True (default) will run through the symbol tags to
eliminate unwanted solutions. If no assumptions are included, all possible
solutions will be returned:
>>> x = Symbol("x")
>>> solve(x**2 - 1)
[-1, 1]
By setting the ``positive`` flag, only one solution will be returned:
>>> pos = Symbol("pos", positive=True)
>>> solve(pos**2 - 1)
[1]
When the solutions are checked, those that make any denominator zero
are automatically excluded. If you do not want to exclude such solutions,
then use the check=False option:
>>> from sympy import sin, limit
>>> solve(sin(x)/x) # 0 is excluded
[pi]
If ``check=False``, then a solution to the numerator being zero is found
but the value of $x = 0$ is a spurious solution since $\sin(x)/x$ has the well
known limit (without discontinuity) of 1 at $x = 0$:
>>> solve(sin(x)/x, check=False)
[0, pi]
In the following case, however, the limit exists and is equal to the
value of $x = 0$ that is excluded when check=True:
>>> eq = x**2*(1/x - z**2/x)
>>> solve(eq, x)
[]
>>> solve(eq, x, check=False)
[0]
>>> limit(eq, x, 0, '-')
0
>>> limit(eq, x, 0, '+')
0
**Solving Relationships**
When one or more expressions passed to ``solve`` is a relational,
a relational result is returned (and the ``dict`` and ``set`` flags
are ignored):
>>> solve(x < 3)
(-oo < x) & (x < 3)
>>> solve([x < 3, x**2 > 4], x)
((-oo < x) & (x < -2)) | ((2 < x) & (x < 3))
>>> solve([x + y - 3, x > 3], x)
(3 < x) & (x < oo) & Eq(x, 3 - y)
Although checking of assumptions on symbols in relationals
is not done, setting assumptions will affect how certain
relationals might automatically simplify:
>>> solve(x**2 > 4)
((-oo < x) & (x < -2)) | ((2 < x) & (x < oo))
>>> r = Symbol('r', real=True)
>>> solve(r**2 > 4)
(2 < r) | (r < -2)
There is currently no algorithm in SymPy that allows you to use
relationships to resolve more than one variable. So the following
does not determine that ``q < 0`` (and trying to solve for ``r``
and ``q`` will raise an error):
>>> from sympy import symbols
>>> r, q = symbols('r, q', real=True)
>>> solve([r + q - 3, r > 3], r)
(3 < r) & Eq(r, 3 - q)
You can directly call the routine that ``solve`` calls
when it encounters a relational: :func:`~.reduce_inequalities`.
It treats Expr like Equality.
>>> from sympy import reduce_inequalities
>>> reduce_inequalities([x**2 - 4])
Eq(x, -2) | Eq(x, 2)
If each relationship contains only one symbol of interest,
the expressions can be processed for multiple symbols:
>>> reduce_inequalities([0 <= x - 1, y < 3], [x, y])
(-oo < y) & (1 <= x) & (x < oo) & (y < 3)
But an error is raised if any relationship has more than one
symbol of interest:
>>> reduce_inequalities([0 <= x*y - 1, y < 3], [x, y])
Traceback (most recent call last):
...
NotImplementedError:
inequality has more than one symbol of interest.
**Disabling High-Order Explicit Solutions**
When solving polynomial expressions, you might not want explicit solutions
(which can be quite long). If the expression is univariate, ``CRootOf``
instances will be returned instead:
>>> solve(x**3 - x + 1)
[-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) -
(-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3,
-(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 -
1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)),
-(3*sqrt(69)/2 + 27/2)**(1/3)/3 -
1/(3*sqrt(69)/2 + 27/2)**(1/3)]
>>> solve(x**3 - x + 1, cubics=False)
[CRootOf(x**3 - x + 1, 0),
CRootOf(x**3 - x + 1, 1),
CRootOf(x**3 - x + 1, 2)]
If the expression is multivariate, no solution might be returned:
>>> solve(x**3 - x + a, x, cubics=False)
[]
Sometimes solutions will be obtained even when a flag is False because the
expression could be factored. In the following example, the equation can
be factored as the product of a linear and a quadratic factor so explicit
solutions (which did not require solving a cubic expression) are obtained:
>>> eq = x**3 + 3*x**2 + x - 1
>>> solve(eq, cubics=False)
[-1, -1 + sqrt(2), -sqrt(2) - 1]
**Solving Equations Involving Radicals**
Because of SymPy's use of the principle root, some solutions
to radical equations will be missed unless check=False:
>>> from sympy import root
>>> eq = root(x**3 - 3*x**2, 3) + 1 - x
>>> solve(eq)
[]
>>> solve(eq, check=False)
[1/3]
In the above example, there is only a single solution to the
equation. Other expressions will yield spurious roots which
must be checked manually; roots which give a negative argument
to odd-powered radicals will also need special checking:
>>> from sympy import real_root, S
>>> eq = root(x, 3) - root(x, 5) + S(1)/7
>>> solve(eq) # this gives 2 solutions but misses a 3rd
[CRootOf(7*x**5 - 7*x**3 + 1, 1)**15,
CRootOf(7*x**5 - 7*x**3 + 1, 2)**15]
>>> sol = solve(eq, check=False)
>>> [abs(eq.subs(x,i).n(2)) for i in sol]
[0.48, 0.e-110, 0.e-110, 0.052, 0.052]
The first solution is negative so ``real_root`` must be used to see that it
satisfies the expression:
>>> abs(real_root(eq.subs(x, sol[0])).n(2))
0.e-110
If the roots of the equation are not real then more care will be
necessary to find the roots, especially for higher order equations.
Consider the following expression:
>>> expr = root(x, 3) - root(x, 5)
We will construct a known value for this expression at x = 3 by selecting
the 1-th root for each radical:
>>> expr1 = root(x, 3, 1) - root(x, 5, 1)
>>> v = expr1.subs(x, -3)
The ``solve`` function is unable to find any exact roots to this equation:
>>> eq = Eq(expr, v); eq1 = Eq(expr1, v)
>>> solve(eq, check=False), solve(eq1, check=False)
([], [])
The function ``unrad``, however, can be used to get a form of the equation
for which numerical roots can be found:
>>> from sympy.solvers.solvers import unrad
>>> from sympy import nroots
>>> e, (p, cov) = unrad(eq)
>>> pvals = nroots(e)
>>> inversion = solve(cov, x)[0]
>>> xvals = [inversion.subs(p, i) for i in pvals]
Although ``eq`` or ``eq1`` could have been used to find ``xvals``, the
solution can only be verified with ``expr1``:
>>> z = expr - v
>>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9]
[]
>>> z1 = expr1 - v
>>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9]
[-3.0]
Parameters
==========
f :
- a single Expr or Poly that must be zero
- an Equality
- a Relational expression
- a Boolean
- iterable of one or more of the above
symbols : (object(s) to solve for) specified as
- none given (other non-numeric objects will be used)
- single symbol
- denested list of symbols
(e.g., ``solve(f, x, y)``)
- ordered iterable of symbols
(e.g., ``solve(f, [x, y])``)
flags :
dict=True (default is False)
Return list (perhaps empty) of solution mappings.
set=True (default is False)
Return list of symbols and set of tuple(s) of solution(s).
exclude=[] (default)
Do not try to solve for any of the free symbols in exclude;
if expressions are given, the free symbols in them will
be extracted automatically.
check=True (default)
If False, do not do any testing of solutions. This can be
useful if you want to include solutions that make any
denominator zero.
numerical=True (default)
Do a fast numerical check if *f* has only one symbol.
minimal=True (default is False)
A very fast, minimal testing.
warn=True (default is False)
Show a warning if ``checksol()`` could not conclude.
simplify=True (default)
Simplify all but polynomials of order 3 or greater before
returning them and (if check is not False) use the
general simplify function on the solutions and the
expression obtained when they are substituted into the
function which should be zero.
force=True (default is False)
Make positive all symbols without assumptions regarding sign.
rational=True (default)
Recast Floats as Rational; if this option is not used, the
system containing Floats may fail to solve because of issues
with polys. If rational=None, Floats will be recast as
rationals but the answer will be recast as Floats. If the
flag is False then nothing will be done to the Floats.
manual=True (default is False)
Do not use the polys/matrix method to solve a system of
equations, solve them one at a time as you might "manually."
implicit=True (default is False)
Allows ``solve`` to return a solution for a pattern in terms of
other functions that contain that pattern; this is only
needed if the pattern is inside of some invertible function
like cos, exp, ect.
particular=True (default is False)
Instructs ``solve`` to try to find a particular solution to
a linear system with as many zeros as possible; this is very
expensive.
quick=True (default is False; ``particular`` must be True)
Selects a fast heuristic to find a solution with many zeros
whereas a value of False uses the very slow method guaranteed
to find the largest number of zeros possible.
cubics=True (default)
Return explicit solutions when cubic expressions are encountered.
When False, quartics and quintics are disabled, too.
quartics=True (default)
Return explicit solutions when quartic expressions are encountered.
When False, quintics are disabled, too.
quintics=True (default)
Return explicit solutions (if possible) when quintic expressions
are encountered.
See Also
========
rsolve: For solving recurrence relationships
dsolve: For solving differential equations
"""
from .inequalities import reduce_inequalities
# checking/recording flags
###########################################################################
# set solver types explicitly; as soon as one is False
# all the rest will be False
hints = ('cubics', 'quartics', 'quintics')
default = True
for k in hints:
default = flags.setdefault(k, bool(flags.get(k, default)))
# allow solution to contain symbol if True:
implicit = flags.get('implicit', False)
# record desire to see warnings
warn = flags.get('warn', False)
# this flag will be needed for quick exits below, so record
# now -- but don't record `dict` yet since it might change
as_set = flags.get('set', False)
# keeping track of how f was passed
bare_f = not iterable(f)
# check flag usage for particular/quick which should only be used
# with systems of equations
if flags.get('quick', None) is not None:
if not flags.get('particular', None):
raise ValueError('when using `quick`, `particular` should be True')
if flags.get('particular', False) and bare_f:
raise ValueError(filldedent("""
The 'particular/quick' flag is usually used with systems of
equations. Either pass your equation in a list or
consider using a solver like `diophantine` if you are
looking for a solution in integers."""))
# sympify everything, creating list of expressions and list of symbols
###########################################################################
def _sympified_list(w):
return list(map(sympify, w if iterable(w) else [w]))
f, symbols = (_sympified_list(w) for w in [f, symbols])
# preprocess symbol(s)
###########################################################################
ordered_symbols = None # were the symbols in a well defined order?
if not symbols:
# get symbols from equations
symbols = set().union(*[fi.free_symbols for fi in f])
if len(symbols) < len(f):
for fi in f:
pot = preorder_traversal(fi)
for p in pot:
if isinstance(p, AppliedUndef):
if not as_set:
flags['dict'] = True # better show symbols
symbols.add(p)
pot.skip() # don't go any deeper
ordered_symbols = False
symbols = list(ordered(symbols)) # to make it canonical
else:
if len(symbols) == 1 and iterable(symbols[0]):
symbols = symbols[0]
ordered_symbols = symbols and is_sequence(symbols,
include=GeneratorType)
_symbols = list(uniq(symbols))
if len(_symbols) != len(symbols):
ordered_symbols = False
symbols = list(ordered(symbols))
else:
symbols = _symbols
# check for duplicates
if len(symbols) != len(set(symbols)):
raise ValueError('duplicate symbols given')
# remove those not of interest
exclude = flags.pop('exclude', set())
if exclude:
if isinstance(exclude, Expr):
exclude = [exclude]
exclude = set().union(*[e.free_symbols for e in sympify(exclude)])
symbols = [s for s in symbols if s not in exclude]
# preprocess equation(s)
###########################################################################
# automatically ignore True values
if isinstance(f, list):
f = [s for s in f if s is not S.true]
# handle canonicalization of equation types
for i, fi in enumerate(f):
if isinstance(fi, (Eq, Ne)):
if 'ImmutableDenseMatrix' in [type(a).__name__ for a in fi.args]:
fi = fi.lhs - fi.rhs
else:
L, R = fi.args
if isinstance(R, BooleanAtom):
L, R = R, L
if isinstance(L, BooleanAtom):
if isinstance(fi, Ne):
L = ~L
if R.is_Relational:
fi = ~R if L is S.false else R
elif R.is_Symbol:
return L
elif R.is_Boolean and (~R).is_Symbol:
return ~L
else:
raise NotImplementedError(filldedent('''
Unanticipated argument of Eq when other arg
is True or False.
'''))
else:
fi = fi.rewrite(Add, evaluate=False)
f[i] = fi
# *** dispatch and handle as a system of relationals
# **************************************************
if fi.is_Relational:
if len(symbols) != 1:
raise ValueError("can only solve for one symbol at a time")
if warn and symbols[0].assumptions0:
warnings.warn(filldedent("""
\tWarning: assumptions about variable '%s' are
not handled currently.""" % symbols[0]))
return reduce_inequalities(f, symbols=symbols)
# convert Poly to expression
if isinstance(fi, Poly):
f[i] = fi.as_expr()
# rewrite hyperbolics in terms of exp if they have symbols of
# interest
f[i] = f[i].replace(lambda w: isinstance(w, HyperbolicFunction) and \
w.has_free(*symbols), lambda w: w.rewrite(exp))
# if we have a Matrix, we need to iterate over its elements again
if f[i].is_Matrix:
bare_f = False
f.extend(list(f[i]))
f[i] = S.Zero
# if we can split it into real and imaginary parts then do so
freei = f[i].free_symbols
if freei and all(s.is_extended_real or s.is_imaginary for s in freei):
fr, fi = f[i].as_real_imag()
# accept as long as new re, im, arg or atan2 are not introduced
had = f[i].atoms(re, im, arg, atan2)
if fr and fi and fr != fi and not any(
i.atoms(re, im, arg, atan2) - had for i in (fr, fi)):
if bare_f:
bare_f = False
f[i: i + 1] = [fr, fi]
# real/imag handling -----------------------------
if any(isinstance(fi, (bool, BooleanAtom)) for fi in f):
if as_set:
return [], set()
return []
for i, fi in enumerate(f):
# Abs
while True:
was = fi
fi = fi.replace(Abs, lambda arg:
separatevars(Abs(arg)).rewrite(Piecewise) if arg.has(*symbols)
else Abs(arg))
if was == fi:
break
for e in fi.find(Abs):
if e.has(*symbols):
raise NotImplementedError('solving %s when the argument '
'is not real or imaginary.' % e)
# arg
fi = fi.replace(arg, lambda a: arg(a).rewrite(atan2).rewrite(atan))
# save changes
f[i] = fi
# see if re(s) or im(s) appear
freim = [fi for fi in f if fi.has(re, im)]
if freim:
irf = []
for s in symbols:
if s.is_real or s.is_imaginary:
continue # neither re(x) nor im(x) will appear
# if re(s) or im(s) appear, the auxiliary equation must be present
if any(fi.has(re(s), im(s)) for fi in freim):
irf.append((s, re(s) + S.ImaginaryUnit*im(s)))
if irf:
for s, rhs in irf:
f = [fi.xreplace({s: rhs}) for fi in f] + [s - rhs]
symbols.extend([re(s), im(s)])
if bare_f:
bare_f = False
flags['dict'] = True
# end of real/imag handling -----------------------------
# we can solve for non-symbol entities by replacing them with Dummy symbols
f, symbols, swap_sym = recast_to_symbols(f, symbols)
# this set of symbols (perhaps recast) is needed below
symset = set(symbols)
# get rid of equations that have no symbols of interest; we don't
# try to solve them because the user didn't ask and they might be
# hard to solve; this means that solutions may be given in terms
# of the eliminated equations e.g. solve((x-y, y-3), x) -> {x: y}
newf = []
for fi in f:
# let the solver handle equations that..
# - have no symbols but are expressions
# - have symbols of interest
# - have no symbols of interest but are constant
# but when an expression is not constant and has no symbols of
# interest, it can't change what we obtain for a solution from
# the remaining equations so we don't include it; and if it's
# zero it can be removed and if it's not zero, there is no
# solution for the equation set as a whole
#
# The reason for doing this filtering is to allow an answer
# to be obtained to queries like solve((x - y, y), x); without
# this mod the return value is []
ok = False
if fi.free_symbols & symset:
ok = True
else:
if fi.is_number:
if fi.is_Number:
if fi.is_zero:
continue
return []
ok = True
else:
if fi.is_constant():
ok = True
if ok:
newf.append(fi)
if not newf:
if as_set:
return symbols, set()
return []
f = newf
del newf
# mask off any Object that we aren't going to invert: Derivative,
# Integral, etc... so that solving for anything that they contain will
# give an implicit solution
seen = set()
non_inverts = set()
for fi in f:
pot = preorder_traversal(fi)
for p in pot:
if not isinstance(p, Expr) or isinstance(p, Piecewise):
pass
elif (isinstance(p, bool) or
not p.args or
p in symset or
p.is_Add or p.is_Mul or
p.is_Pow and not implicit or
p.is_Function and not implicit) and p.func not in (re, im):
continue
elif p not in seen:
seen.add(p)
if p.free_symbols & symset:
non_inverts.add(p)
else:
continue
pot.skip()
del seen
non_inverts = dict(list(zip(non_inverts, [Dummy() for _ in non_inverts])))
f = [fi.subs(non_inverts) for fi in f]
# Both xreplace and subs are needed below: xreplace to force substitution
# inside Derivative, subs to handle non-straightforward substitutions
non_inverts = [(v, k.xreplace(swap_sym).subs(swap_sym)) for k, v in non_inverts.items()]
# rationalize Floats
floats = False
if flags.get('rational', True) is not False:
for i, fi in enumerate(f):
if fi.has(Float):
floats = True
f[i] = nsimplify(fi, rational=True)
# capture any denominators before rewriting since
# they may disappear after the rewrite, e.g. issue 14779
flags['_denominators'] = _simple_dens(f[0], symbols)
# Any embedded piecewise functions need to be brought out to the
# top level so that the appropriate strategy gets selected.
# However, this is necessary only if one of the piecewise
# functions depends on one of the symbols we are solving for.
def _has_piecewise(e):
if e.is_Piecewise:
return e.has(*symbols)
return any(_has_piecewise(a) for a in e.args)
for i, fi in enumerate(f):
if _has_piecewise(fi):
f[i] = piecewise_fold(fi)
#
# try to get a solution
###########################################################################
if bare_f:
solution = None
if len(symbols) != 1:
solution = _solve_undetermined(f[0], symbols, flags)
if not solution:
solution = _solve(f[0], *symbols, **flags)
else:
linear, solution = _solve_system(f, symbols, **flags)
assert type(solution) is list
assert not solution or type(solution[0]) is dict, solution
#
# postprocessing
###########################################################################
# capture as_dict flag now (as_set already captured)
as_dict = flags.get('dict', False)
# define how solution will get unpacked
tuple_format = lambda s: [tuple([i.get(x, x) for x in symbols]) for i in s]
if as_dict or as_set:
unpack = None
elif bare_f:
if len(symbols) == 1:
unpack = lambda s: [i[symbols[0]] for i in s]
elif len(solution) == 1 and len(solution[0]) == len(symbols):
# undetermined linear coeffs solution
unpack = lambda s: s[0]
elif ordered_symbols:
unpack = tuple_format
else:
unpack = lambda s: s
else:
if solution:
if linear and len(solution) == 1:
# if you want the tuple solution for the linear
# case, use `set=True`
unpack = lambda s: s[0]
elif ordered_symbols:
unpack = tuple_format
else:
unpack = lambda s: s
else:
unpack = None
# Restore masked-off objects
if non_inverts and type(solution) is list:
solution = [{k: v.subs(non_inverts) for k, v in s.items()}
for s in solution]
# Restore original "symbols" if a dictionary is returned.
# This is not necessary for
# - the single univariate equation case
# since the symbol will have been removed from the solution;
# - the nonlinear poly_system since that only supports zero-dimensional
# systems and those results come back as a list
#
# ** unless there were Derivatives with the symbols, but those were handled
# above.
if swap_sym:
symbols = [swap_sym.get(k, k) for k in symbols]
for i, sol in enumerate(solution):
solution[i] = {swap_sym.get(k, k): v.subs(swap_sym)
for k, v in sol.items()}
# Get assumptions about symbols, to filter solutions.
# Note that if assumptions about a solution can't be verified, it is still
# returned.
check = flags.get('check', True)
# restore floats
if floats and solution and flags.get('rational', None) is None:
solution = nfloat(solution, exponent=False)
if check and solution: # assumption checking
warn = flags.get('warn', False)
got_None = [] # solutions for which one or more symbols gave None
no_False = [] # solutions for which no symbols gave False
for sol in solution:
a_None = False
for symb, val in sol.items():
test = check_assumptions(val, **symb.assumptions0)
if test:
continue
if test is False:
break
a_None = True
else:
no_False.append(sol)
if a_None:
got_None.append(sol)
solution = no_False
if warn and got_None:
warnings.warn(filldedent("""
\tWarning: assumptions concerning following solution(s)
cannot be checked:""" + '\n\t' +
', '.join(str(s) for s in got_None)))
#
# done
###########################################################################
if not solution:
if as_set:
return symbols, set()
return []
# make orderings canonical for list of dictionaries
if not as_set: # for set, no point in ordering
solution = [{k: s[k] for k in ordered(s)} for s in solution]
solution.sort(key=default_sort_key)
if not (as_set or as_dict):
return unpack(solution)
if as_dict:
return solution
# set output: (symbols, {t1, t2, ...}) from list of dictionaries;
# include all symbols for those that like a verbose solution
# and to resolve any differences in dictionary keys.
#
# The set results can easily be used to make a verbose dict as
# k, v = solve(eqs, syms, set=True)
# sol = [dict(zip(k,i)) for i in v]
#
if ordered_symbols:
k = symbols # keep preferred order
else:
# just unify the symbols for which solutions were found
k = list(ordered(set(flatten(tuple(i.keys()) for i in solution))))
return k, {tuple([s.get(ki, ki) for ki in k]) for s in solution}
def _solve_undetermined(g, symbols, flags):
"""solve helper to return a list with one dict (solution) else None
A direct call to solve_undetermined_coeffs is more flexible and
can return both multiple solutions and handle more than one independent
variable. Here, we have to be more cautious to keep from solving
something that does not look like an undetermined coeffs system --
to minimize the surprise factor since singularities that cancel are not
prohibited in solve_undetermined_coeffs.
"""
if g.free_symbols - set(symbols):
sol = solve_undetermined_coeffs(g, symbols, **dict(flags, dict=True, set=None))
if len(sol) == 1:
return sol
def _solve(f, *symbols, **flags):
"""Return a checked solution for *f* in terms of one or more of the
symbols in the form of a list of dictionaries.
If no method is implemented to solve the equation, a NotImplementedError
will be raised. In the case that conversion of an expression to a Poly
gives None a ValueError will be raised.
"""
not_impl_msg = "No algorithms are implemented to solve equation %s"
if len(symbols) != 1:
# look for solutions for desired symbols that are independent
# of symbols already solved for, e.g. if we solve for x = y
# then no symbol having x in its solution will be returned.
# First solve for linear symbols (since that is easier and limits
# solution size) and then proceed with symbols appearing
# in a non-linear fashion. Ideally, if one is solving a single
# expression for several symbols, they would have to be
# appear in factors of an expression, but we do not here
# attempt factorization. XXX perhaps handling a Mul
# should come first in this routine whether there is
# one or several symbols.
nonlin_s = []
got_s = set()
rhs_s = set()
result = []
for s in symbols:
xi, v = solve_linear(f, symbols=[s])
if xi == s:
# no need to check but we should simplify if desired
if flags.get('simplify', True):
v = simplify(v)
vfree = v.free_symbols
if vfree & got_s:
# was linear, but has redundant relationship
# e.g. x - y = 0 has y == x is redundant for x == y
# so ignore
continue
rhs_s |= vfree
got_s.add(xi)
result.append({xi: v})
elif xi: # there might be a non-linear solution if xi is not 0
nonlin_s.append(s)
if not nonlin_s:
return result
for s in nonlin_s:
try:
soln = _solve(f, s, **flags)
for sol in soln:
if sol[s].free_symbols & got_s:
# depends on previously solved symbols: ignore
continue
got_s.add(s)
result.append(sol)
except NotImplementedError:
continue
if got_s:
return result
else:
raise NotImplementedError(not_impl_msg % f)
# solve f for a single variable
symbol = symbols[0]
# expand binomials only if it has the unknown symbol
f = f.replace(lambda e: isinstance(e, binomial) and e.has(symbol),
lambda e: expand_func(e))
# checking will be done unless it is turned off before making a
# recursive call; the variables `checkdens` and `check` are
# captured here (for reference below) in case flag value changes
flags['check'] = checkdens = check = flags.pop('check', True)
# build up solutions if f is a Mul
if f.is_Mul:
result = set()
for m in f.args:
if m in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}:
result = set()
break
soln = _vsolve(m, symbol, **flags)
result.update(set(soln))
result = [{symbol: v} for v in result]
if check:
# all solutions have been checked but now we must
# check that the solutions do not set denominators
# in any factor to zero
dens = flags.get('_denominators', _simple_dens(f, symbols))
result = [s for s in result if
not any(checksol(den, s, **flags) for den in
dens)]
# set flags for quick exit at end; solutions for each
# factor were already checked and simplified
check = False
flags['simplify'] = False
elif f.is_Piecewise:
result = set()
for i, (expr, cond) in enumerate(f.args):
if expr.is_zero:
raise NotImplementedError(
'solve cannot represent interval solutions')
candidates = _vsolve(expr, symbol, **flags)
# the explicit condition for this expr is the current cond
# and none of the previous conditions
args = [~c for _, c in f.args[:i]] + [cond]
cond = And(*args)
for candidate in candidates:
if candidate in result:
# an unconditional value was already there
continue
try:
v = cond.subs(symbol, candidate)
_eval_simplify = getattr(v, '_eval_simplify', None)
if _eval_simplify is not None:
# unconditionally take the simpification of v
v = _eval_simplify(ratio=2, measure=lambda x: 1)
except TypeError:
# incompatible type with condition(s)
continue
if v == False:
continue
if v == True:
result.add(candidate)
else:
result.add(Piecewise(
(candidate, v),
(S.NaN, True)))
# solutions already checked and simplified
# ****************************************
return [{symbol: r} for r in result]
else:
# first see if it really depends on symbol and whether there
# is only a linear solution
f_num, sol = solve_linear(f, symbols=symbols)
if f_num.is_zero or sol is S.NaN:
return []
elif f_num.is_Symbol:
# no need to check but simplify if desired
if flags.get('simplify', True):
sol = simplify(sol)
return [{f_num: sol}]
poly = None
# check for a single Add generator
if not f_num.is_Add:
add_args = [i for i in f_num.atoms(Add)
if symbol in i.free_symbols]
if len(add_args) == 1:
gen = add_args[0]
spart = gen.as_independent(symbol)[1].as_base_exp()[0]
if spart == symbol:
try:
poly = Poly(f_num, spart)
except PolynomialError:
pass
result = False # no solution was obtained
msg = '' # there is no failure message
# Poly is generally robust enough to convert anything to
# a polynomial and tell us the different generators that it
# contains, so we will inspect the generators identified by
# polys to figure out what to do.
# try to identify a single generator that will allow us to solve this
# as a polynomial, followed (perhaps) by a change of variables if the
# generator is not a symbol
try:
if poly is None:
poly = Poly(f_num)
if poly is None:
raise ValueError('could not convert %s to Poly' % f_num)
except GeneratorsNeeded:
simplified_f = simplify(f_num)
if simplified_f != f_num:
return _solve(simplified_f, symbol, **flags)
raise ValueError('expression appears to be a constant')
gens = [g for g in poly.gens if g.has(symbol)]
def _as_base_q(x):
"""Return (b**e, q) for x = b**(p*e/q) where p/q is the leading
Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3)
"""
b, e = x.as_base_exp()
if e.is_Rational:
return b, e.q
if not e.is_Mul:
return x, 1
c, ee = e.as_coeff_Mul()
if c.is_Rational and c is not S.One: # c could be a Float
return b**ee, c.q
return x, 1
if len(gens) > 1:
# If there is more than one generator, it could be that the
# generators have the same base but different powers, e.g.
# >>> Poly(exp(x) + 1/exp(x))
# Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ')
#
# If unrad was not disabled then there should be no rational
# exponents appearing as in
# >>> Poly(sqrt(x) + sqrt(sqrt(x)))
# Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ')
bases, qs = list(zip(*[_as_base_q(g) for g in gens]))
bases = set(bases)
if len(bases) > 1 or not all(q == 1 for q in qs):
funcs = {b for b in bases if b.is_Function}
trig = {_ for _ in funcs if
isinstance(_, TrigonometricFunction)}
other = funcs - trig
if not other and len(funcs.intersection(trig)) > 1:
newf = None
if f_num.is_Add and len(f_num.args) == 2:
# check for sin(x)**p = cos(x)**p
_args = f_num.args
t = a, b = [i.atoms(Function).intersection(
trig) for i in _args]
if all(len(i) == 1 for i in t):
a, b = [i.pop() for i in t]
if isinstance(a, cos):
a, b = b, a
_args = _args[::-1]
if isinstance(a, sin) and isinstance(b, cos
) and a.args[0] == b.args[0]:
# sin(x) + cos(x) = 0 -> tan(x) + 1 = 0
newf, _d = (TR2i(_args[0]/_args[1]) + 1
).as_numer_denom()
if not _d.is_Number:
newf = None
if newf is None:
newf = TR1(f_num).rewrite(tan)
if newf != f_num:
# don't check the rewritten form --check
# solutions in the un-rewritten form below
flags['check'] = False
result = _solve(newf, symbol, **flags)
flags['check'] = check
# just a simple case - see if replacement of single function
# clears all symbol-dependent functions, e.g.
# log(x) - log(log(x) - 1) - 3 can be solved even though it has
# two generators.
if result is False and funcs:
funcs = list(ordered(funcs)) # put shallowest function first
f1 = funcs[0]
t = Dummy('t')
# perform the substitution
ftry = f_num.subs(f1, t)
# if no Functions left, we can proceed with usual solve
if not ftry.has(symbol):
cv_sols = _solve(ftry, t, **flags)
cv_inv = list(ordered(_vsolve(t - f1, symbol, **flags)))[0]
result = [{symbol: cv_inv.subs(sol)} for sol in cv_sols]
if result is False:
msg = 'multiple generators %s' % gens
else:
# e.g. case where gens are exp(x), exp(-x)
u = bases.pop()
t = Dummy('t')
inv = _vsolve(u - t, symbol, **flags)
if isinstance(u, (Pow, exp)):
# this will be resolved by factor in _tsolve but we might
# as well try a simple expansion here to get things in
# order so something like the following will work now without
# having to factor:
#
# >>> eq = (exp(I*(-x-2))+exp(I*(x+2)))
# >>> eq.subs(exp(x),y) # fails
# exp(I*(-x - 2)) + exp(I*(x + 2))
# >>> eq.expand().subs(exp(x),y) # works
# y**I*exp(2*I) + y**(-I)*exp(-2*I)
def _expand(p):
b, e = p.as_base_exp()
e = expand_mul(e)
return expand_power_exp(b**e)
ftry = f_num.replace(
lambda w: w.is_Pow or isinstance(w, exp),
_expand).subs(u, t)
if not ftry.has(symbol):
soln = _solve(ftry, t, **flags)
result = [{symbol: i.subs(s)} for i in inv for s in soln]
elif len(gens) == 1:
# There is only one generator that we are interested in, but
# there may have been more than one generator identified by
# polys (e.g. for symbols other than the one we are interested
# in) so recast the poly in terms of our generator of interest.
# Also use composite=True with f_num since Poly won't update
# poly as documented in issue 8810.
poly = Poly(f_num, gens[0], composite=True)
# if we aren't on the tsolve-pass, use roots
if not flags.pop('tsolve', False):
soln = None
deg = poly.degree()
flags['tsolve'] = True
hints = ('cubics', 'quartics', 'quintics')
solvers = {h: flags.get(h) for h in hints}
soln = roots(poly, **solvers)
if sum(soln.values()) < deg:
# e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 +
# 5000*x**2 + 6250*x + 3189) -> {}
# so all_roots is used and RootOf instances are
# returned *unless* the system is multivariate
# or high-order EX domain.
try:
soln = poly.all_roots()
except NotImplementedError:
if not flags.get('incomplete', True):
raise NotImplementedError(
filldedent('''
Neither high-order multivariate polynomials
nor sorting of EX-domain polynomials is supported.
If you want to see any results, pass keyword incomplete=True to
solve; to see numerical values of roots
for univariate expressions, use nroots.
'''))
else:
pass
else:
soln = list(soln.keys())
if soln is not None:
u = poly.gen
if u != symbol:
try:
t = Dummy('t')
inv = _vsolve(u - t, symbol, **flags)
soln = {i.subs(t, s) for i in inv for s in soln}
except NotImplementedError:
# perhaps _tsolve can handle f_num
soln = None
else:
check = False # only dens need to be checked
if soln is not None:
if len(soln) > 2:
# if the flag wasn't set then unset it since high-order
# results are quite long. Perhaps one could base this
# decision on a certain critical length of the
# roots. In addition, wester test M2 has an expression
# whose roots can be shown to be real with the
# unsimplified form of the solution whereas only one of
# the simplified forms appears to be real.
flags['simplify'] = flags.get('simplify', False)
if soln is not None:
result = [{symbol: v} for v in soln]
# fallback if above fails
# -----------------------
if result is False:
# try unrad
if flags.pop('_unrad', True):
try:
u = unrad(f_num, symbol)
except (ValueError, NotImplementedError):
u = False
if u:
eq, cov = u
if cov:
isym, ieq = cov
inv = _vsolve(ieq, symbol, **flags)[0]
rv = {inv.subs(xi) for xi in _solve(eq, isym, **flags)}
else:
try:
rv = set(_vsolve(eq, symbol, **flags))
except NotImplementedError:
rv = None
if rv is not None:
result = [{symbol: v} for v in rv]
# if the flag wasn't set then unset it since unrad results
# can be quite long or of very high order
flags['simplify'] = flags.get('simplify', False)
else:
pass # for coverage
# try _tsolve
if result is False:
flags.pop('tsolve', None) # allow tsolve to be used on next pass
try:
soln = _tsolve(f_num, symbol, **flags)
if soln is not None:
result = [{symbol: v} for v in soln]
except PolynomialError:
pass
# ----------- end of fallback ----------------------------
if result is False:
raise NotImplementedError('\n'.join([msg, not_impl_msg % f]))
if flags.get('simplify', True):
result = [{k: d[k].simplify() for k in d} for d in result]
# we just simplified the solution so we now set the flag to
# False so the simplification doesn't happen again in checksol()
flags['simplify'] = False
if checkdens:
# reject any result that makes any denom. affirmatively 0;
# if in doubt, keep it
dens = _simple_dens(f, symbols)
result = [r for r in result if
not any(checksol(d, r, **flags)
for d in dens)]
if check:
# keep only results if the check is not False
result = [r for r in result if
checksol(f_num, r, **flags) is not False]
return result
def _solve_system(exprs, symbols, **flags):
"""return ``(linear, solution)`` where ``linear`` is True
if the system was linear, else False; ``solution``
is a list of dictionaries giving solutions for the symbols
"""
if not exprs:
return False, []
if flags.pop('_split', True):
# Split the system into connected components
V = exprs
symsset = set(symbols)
exprsyms = {e: e.free_symbols & symsset for e in exprs}
E = []
sym_indices = {sym: i for i, sym in enumerate(symbols)}
for n, e1 in enumerate(exprs):
for e2 in exprs[:n]:
# Equations are connected if they share a symbol
if exprsyms[e1] & exprsyms[e2]:
E.append((e1, e2))
G = V, E
subexprs = connected_components(G)
if len(subexprs) > 1:
subsols = []
linear = True
for subexpr in subexprs:
subsyms = set()
for e in subexpr:
subsyms |= exprsyms[e]
subsyms = list(sorted(subsyms, key = lambda x: sym_indices[x]))
flags['_split'] = False # skip split step
_linear, subsol = _solve_system(subexpr, subsyms, **flags)
if linear:
linear = linear and _linear
if not isinstance(subsol, list):
subsol = [subsol]
subsols.append(subsol)
# Full solution is cartesion product of subsystems
sols = []
for soldicts in product(*subsols):
sols.append(dict(item for sd in soldicts
for item in sd.items()))
return linear, sols
polys = []
dens = set()
failed = []
result = []
solved_syms = []
linear = True
manual = flags.get('manual', False)
checkdens = check = flags.get('check', True)
for j, g in enumerate(exprs):
dens.update(_simple_dens(g, symbols))
i, d = _invert(g, *symbols)
if d in symbols:
if linear:
linear = solve_linear(g, 0, [d])[0] == d
g = d - i
g = g.as_numer_denom()[0]
if manual:
failed.append(g)
continue
poly = g.as_poly(*symbols, extension=True)
if poly is not None:
polys.append(poly)
else:
failed.append(g)
if polys:
if all(p.is_linear for p in polys):
n, m = len(polys), len(symbols)
matrix = zeros(n, m + 1)
for i, poly in enumerate(polys):
for monom, coeff in poly.terms():
try:
j = monom.index(1)
matrix[i, j] = coeff
except ValueError:
matrix[i, m] = -coeff
# returns a dictionary ({symbols: values}) or None
if flags.pop('particular', False):
result = minsolve_linear_system(matrix, *symbols, **flags)
else:
result = solve_linear_system(matrix, *symbols, **flags)
result = [result] if result else []
if failed:
if result:
solved_syms = list(result[0].keys()) # there is only one result dict
else:
solved_syms = []
# linear doesn't change
else:
linear = False
if len(symbols) > len(polys):
free = set().union(*[p.free_symbols for p in polys])
free = list(ordered(free.intersection(symbols)))
got_s = set()
result = []
for syms in subsets(free, len(polys)):
try:
# returns [], None or list of tuples
res = solve_poly_system(polys, *syms)
if res:
for r in set(res):
skip = False
for r1 in r:
if got_s and any(ss in r1.free_symbols
for ss in got_s):
# sol depends on previously
# solved symbols: discard it
skip = True
if not skip:
got_s.update(syms)
result.append(dict(list(zip(syms, r))))
except NotImplementedError:
pass
if got_s:
solved_syms = list(got_s)
else:
raise NotImplementedError('no valid subset found')
else:
try:
result = solve_poly_system(polys, *symbols)
if result:
solved_syms = symbols
result = [dict(list(zip(solved_syms, r))) for r in set(result)]
except NotImplementedError:
failed.extend([g.as_expr() for g in polys])
solved_syms = []
# convert None or [] to [{}]
result = result or [{}]
if failed:
linear = False
# For each failed equation, see if we can solve for one of the
# remaining symbols from that equation. If so, we update the
# solution set and continue with the next failed equation,
# repeating until we are done or we get an equation that can't
# be solved.
def _ok_syms(e, sort=False):
rv = e.free_symbols & legal
# Solve first for symbols that have lower degree in the equation.
# Ideally we want to solve firstly for symbols that appear linearly
# with rational coefficients e.g. if e = x*y + z then we should
# solve for z first.
def key(sym):
ep = e.as_poly(sym)
if ep is None:
complexity = (S.Infinity, S.Infinity, S.Infinity)
else:
coeff_syms = ep.LC().free_symbols
complexity = (ep.degree(), len(coeff_syms & rv), len(coeff_syms))
return complexity + (default_sort_key(sym),)
if sort:
rv = sorted(rv, key=key)
return rv
legal = set(symbols) # what we are interested in
# sort so equation with the fewest potential symbols is first
u = Dummy() # used in solution checking
for eq in ordered(failed, lambda _: len(_ok_syms(_))):
newresult = []
bad_results = []
hit = False
for r in result:
got_s = set()
# update eq with everything that is known so far
eq2 = eq.subs(r)
# if check is True then we see if it satisfies this
# equation, otherwise we just accept it
if check and r:
b = checksol(u, u, eq2, minimal=True)
if b is not None:
# this solution is sufficient to know whether
# it is valid or not so we either accept or
# reject it, then continue
if b:
newresult.append(r)
else:
bad_results.append(r)
continue
# search for a symbol amongst those available that
# can be solved for
ok_syms = _ok_syms(eq2, sort=True)
if not ok_syms:
if r:
newresult.append(r)
break # skip as it's independent of desired symbols
for s in ok_syms:
try:
soln = _vsolve(eq2, s, **flags)
except NotImplementedError:
continue
# put each solution in r and append the now-expanded
# result in the new result list; use copy since the
# solution for s is being added in-place
for sol in soln:
if got_s and any(ss in sol.free_symbols for ss in got_s):
# sol depends on previously solved symbols: discard it
continue
rnew = r.copy()
for k, v in r.items():
rnew[k] = v.subs(s, sol)
# and add this new solution
rnew[s] = sol
# check that it is independent of previous solutions
iset = set(rnew.items())
for i in newresult:
if len(i) < len(iset) and not set(i.items()) - iset:
# this is a superset of a known solution that
# is smaller
break
else:
# keep it
newresult.append(rnew)
hit = True
got_s.add(s)
if not hit:
raise NotImplementedError('could not solve %s' % eq2)
else:
result = newresult
for b in bad_results:
if b in result:
result.remove(b)
if not result:
return False, []
# rely on linear/polynomial system solvers to simplify
# XXX the following tests show that the expressions
# returned are not the same as they would be if simplify
# were applied to this:
# sympy/solvers/ode/tests/test_systems/test__classify_linear_system
# sympy/solvers/tests/test_solvers/test_issue_4886
# so the docs should be updated to reflect that or else
# the following should be `bool(failed) or not linear`
default_simplify = bool(failed)
if flags.get('simplify', default_simplify):
for r in result:
for k in r:
r[k] = simplify(r[k])
flags['simplify'] = False # don't need to do so in checksol now
if checkdens:
result = [r for r in result
if not any(checksol(d, r, **flags) for d in dens)]
if check and not linear:
result = [r for r in result
if not any(checksol(e, r, **flags) is False for e in exprs)]
result = [r for r in result if r]
return linear, result
def solve_linear(lhs, rhs=0, symbols=[], exclude=[]):
r"""
Return a tuple derived from ``f = lhs - rhs`` that is one of
the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``.
Explanation
===========
``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols*
that are not in *exclude*.
``(0, 0)`` meaning that there is no solution to the equation amongst the
symbols given. If the first element of the tuple is not zero, then the
function is guaranteed to be dependent on a symbol in *symbols*.
``(symbol, solution)`` where symbol appears linearly in the numerator of
``f``, is in *symbols* (if given), and is not in *exclude* (if given). No
simplification is done to ``f`` other than a ``mul=True`` expansion, so the
solution will correspond strictly to a unique solution.
``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f``
when the numerator was not linear in any symbol of interest; ``n`` will
never be a symbol unless a solution for that symbol was found (in which case
the second element is the solution, not the denominator).
Examples
========
>>> from sympy import cancel, Pow
``f`` is independent of the symbols in *symbols* that are not in
*exclude*:
>>> from sympy import cos, sin, solve_linear
>>> from sympy.abc import x, y, z
>>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0
>>> solve_linear(eq)
(0, 1)
>>> eq = cos(x)**2 + sin(x)**2 # = 1
>>> solve_linear(eq)
(0, 1)
>>> solve_linear(x, exclude=[x])
(0, 1)
The variable ``x`` appears as a linear variable in each of the
following:
>>> solve_linear(x + y**2)
(x, -y**2)
>>> solve_linear(1/x - y**2)
(x, y**(-2))
When not linear in ``x`` or ``y`` then the numerator and denominator are
returned:
>>> solve_linear(x**2/y**2 - 3)
(x**2 - 3*y**2, y**2)
If the numerator of the expression is a symbol, then ``(0, 0)`` is
returned if the solution for that symbol would have set any
denominator to 0:
>>> eq = 1/(1/x - 2)
>>> eq.as_numer_denom()
(x, 1 - 2*x)
>>> solve_linear(eq)
(0, 0)
But automatic rewriting may cause a symbol in the denominator to
appear in the numerator so a solution will be returned:
>>> (1/x)**-1
x
>>> solve_linear((1/x)**-1)
(x, 0)
Use an unevaluated expression to avoid this:
>>> solve_linear(Pow(1/x, -1, evaluate=False))
(0, 0)
If ``x`` is allowed to cancel in the following expression, then it
appears to be linear in ``x``, but this sort of cancellation is not
done by ``solve_linear`` so the solution will always satisfy the
original expression without causing a division by zero error.
>>> eq = x**2*(1/x - z**2/x)
>>> solve_linear(cancel(eq))
(x, 0)
>>> solve_linear(eq)
(x**2*(1 - z**2), x)
A list of symbols for which a solution is desired may be given:
>>> solve_linear(x + y + z, symbols=[y])
(y, -x - z)
A list of symbols to ignore may also be given:
>>> solve_linear(x + y + z, exclude=[x])
(y, -x - z)
(A solution for ``y`` is obtained because it is the first variable
from the canonically sorted list of symbols that had a linear
solution.)
"""
if isinstance(lhs, Eq):
if rhs:
raise ValueError(filldedent('''
If lhs is an Equality, rhs must be 0 but was %s''' % rhs))
rhs = lhs.rhs
lhs = lhs.lhs
dens = None
eq = lhs - rhs
n, d = eq.as_numer_denom()
if not n:
return S.Zero, S.One
free = n.free_symbols
if not symbols:
symbols = free
else:
bad = [s for s in symbols if not s.is_Symbol]
if bad:
if len(bad) == 1:
bad = bad[0]
if len(symbols) == 1:
eg = 'solve(%s, %s)' % (eq, symbols[0])
else:
eg = 'solve(%s, *%s)' % (eq, list(symbols))
raise ValueError(filldedent('''
solve_linear only handles symbols, not %s. To isolate
non-symbols use solve, e.g. >>> %s <<<.
''' % (bad, eg)))
symbols = free.intersection(symbols)
symbols = symbols.difference(exclude)
if not symbols:
return S.Zero, S.One
# derivatives are easy to do but tricky to analyze to see if they
# are going to disallow a linear solution, so for simplicity we
# just evaluate the ones that have the symbols of interest
derivs = defaultdict(list)
for der in n.atoms(Derivative):
csym = der.free_symbols & symbols
for c in csym:
derivs[c].append(der)
all_zero = True
for xi in sorted(symbols, key=default_sort_key): # canonical order
# if there are derivatives in this var, calculate them now
if isinstance(derivs[xi], list):
derivs[xi] = {der: der.doit() for der in derivs[xi]}
newn = n.subs(derivs[xi])
dnewn_dxi = newn.diff(xi)
# dnewn_dxi can be nonzero if it survives differentation by any
# of its free symbols
free = dnewn_dxi.free_symbols
if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free) or free == symbols):
all_zero = False
if dnewn_dxi is S.NaN:
break
if xi not in dnewn_dxi.free_symbols:
vi = -1/dnewn_dxi*(newn.subs(xi, 0))
if dens is None:
dens = _simple_dens(eq, symbols)
if not any(checksol(di, {xi: vi}, minimal=True) is True
for di in dens):
# simplify any trivial integral
irep = [(i, i.doit()) for i in vi.atoms(Integral) if
i.function.is_number]
# do a slight bit of simplification
vi = expand_mul(vi.subs(irep))
return xi, vi
if all_zero:
return S.Zero, S.One
if n.is_Symbol: # no solution for this symbol was found
return S.Zero, S.Zero
return n, d
def minsolve_linear_system(system, *symbols, **flags):
r"""
Find a particular solution to a linear system.
Explanation
===========
In particular, try to find a solution with the minimal possible number
of non-zero variables using a naive algorithm with exponential complexity.
If ``quick=True``, a heuristic is used.
"""
quick = flags.get('quick', False)
# Check if there are any non-zero solutions at all
s0 = solve_linear_system(system, *symbols, **flags)
if not s0 or all(v == 0 for v in s0.values()):
return s0
if quick:
# We just solve the system and try to heuristically find a nice
# solution.
s = solve_linear_system(system, *symbols)
def update(determined, solution):
delete = []
for k, v in solution.items():
solution[k] = v.subs(determined)
if not solution[k].free_symbols:
delete.append(k)
determined[k] = solution[k]
for k in delete:
del solution[k]
determined = {}
update(determined, s)
while s:
# NOTE sort by default_sort_key to get deterministic result
k = max((k for k in s.values()),
key=lambda x: (len(x.free_symbols), default_sort_key(x)))
kfree = k.free_symbols
x = next(reversed(list(ordered(kfree))))
if len(kfree) != 1:
determined[x] = S.Zero
else:
val = _vsolve(k, x, check=False)[0]
if not val and not any(v.subs(x, val) for v in s.values()):
determined[x] = S.One
else:
determined[x] = val
update(determined, s)
return determined
else:
# We try to select n variables which we want to be non-zero.
# All others will be assumed zero. We try to solve the modified system.
# If there is a non-trivial solution, just set the free variables to
# one. If we do this for increasing n, trying all combinations of
# variables, we will find an optimal solution.
# We speed up slightly by starting at one less than the number of
# variables the quick method manages.
N = len(symbols)
bestsol = minsolve_linear_system(system, *symbols, quick=True)
n0 = len([x for x in bestsol.values() if x != 0])
for n in range(n0 - 1, 1, -1):
debug('minsolve: %s' % n)
thissol = None
for nonzeros in combinations(list(range(N)), n):
subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T
s = solve_linear_system(subm, *[symbols[i] for i in nonzeros])
if s and not all(v == 0 for v in s.values()):
subs = [(symbols[v], S.One) for v in nonzeros]
for k, v in s.items():
s[k] = v.subs(subs)
for sym in symbols:
if sym not in s:
if symbols.index(sym) in nonzeros:
s[sym] = S.One
else:
s[sym] = S.Zero
thissol = s
break
if thissol is None:
break
bestsol = thissol
return bestsol
def solve_linear_system(system, *symbols, **flags):
r"""
Solve system of $N$ linear equations with $M$ variables, which means
both under- and overdetermined systems are supported.
Explanation
===========
The possible number of solutions is zero, one, or infinite. Respectively,
this procedure will return None or a dictionary with solutions. In the
case of underdetermined systems, all arbitrary parameters are skipped.
This may cause a situation in which an empty dictionary is returned.
In that case, all symbols can be assigned arbitrary values.
Input to this function is a $N\times M + 1$ matrix, which means it has
to be in augmented form. If you prefer to enter $N$ equations and $M$
unknowns then use ``solve(Neqs, *Msymbols)`` instead. Note: a local
copy of the matrix is made by this routine so the matrix that is
passed will not be modified.
The algorithm used here is fraction-free Gaussian elimination,
which results, after elimination, in an upper-triangular matrix.
Then solutions are found using back-substitution. This approach
is more efficient and compact than the Gauss-Jordan method.
Examples
========
>>> from sympy import Matrix, solve_linear_system
>>> from sympy.abc import x, y
Solve the following system::
x + 4 y == 2
-2 x + y == 14
>>> system = Matrix(( (1, 4, 2), (-2, 1, 14)))
>>> solve_linear_system(system, x, y)
{x: -6, y: 2}
A degenerate system returns an empty dictionary:
>>> system = Matrix(( (0,0,0), (0,0,0) ))
>>> solve_linear_system(system, x, y)
{}
"""
assert system.shape[1] == len(symbols) + 1
# This is just a wrapper for solve_lin_sys
eqs = list(system * Matrix(symbols + (-1,)))
eqs, ring = sympy_eqs_to_ring(eqs, symbols)
sol = solve_lin_sys(eqs, ring, _raw=False)
if sol is not None:
sol = {sym:val for sym, val in sol.items() if sym != val}
return sol
def solve_undetermined_coeffs(equ, coeffs, *syms, **flags):
r"""
Solve a system of equations in $k$ parameters that is formed by
matching coefficients in variables ``coeffs`` that are on
factors dependent on the remaining variables (or those given
explicitly by ``syms``.
Explanation
===========
The result of this function is a dictionary with symbolic values of those
parameters with respect to coefficients in $q$ -- empty if there
is no solution or coefficients do not appear in the equation -- else
None (if the system was not recognized). If there is more than one
solution, the solutions are passed as a list. The output can be modified using
the same semantics as for `solve` since the flags that are passed are sent
directly to `solve` so, for example the flag ``dict=True`` will always return a list
of solutions as dictionaries.
This function accepts both Equality and Expr class instances.
The solving process is most efficient when symbols are specified
in addition to parameters to be determined, but an attempt to
determine them (if absent) will be made. If an expected solution is not
obtained (and symbols were not specified) try specifying them.
Examples
========
>>> from sympy import Eq, solve_undetermined_coeffs
>>> from sympy.abc import a, b, c, h, p, k, x, y
>>> solve_undetermined_coeffs(Eq(a*x + a + b, x/2), [a, b], x)
{a: 1/2, b: -1/2}
>>> solve_undetermined_coeffs(a - 2, [a])
{a: 2}
The equation can be nonlinear in the symbols:
>>> X, Y, Z = y, x**y, y*x**y
>>> eq = a*X + b*Y + c*Z - X - 2*Y - 3*Z
>>> coeffs = a, b, c
>>> syms = x, y
>>> solve_undetermined_coeffs(eq, coeffs, syms)
{a: 1, b: 2, c: 3}
And the system can be nonlinear in coefficients, too, but if
there is only a single solution, it will be returned as a
dictionary:
>>> eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p
>>> solve_undetermined_coeffs(eq, (h, p, k), x)
{h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)}
Multiple solutions are always returned in a list:
>>> solve_undetermined_coeffs(a**2*x + b - x, [a, b], x)
[{a: -1, b: 0}, {a: 1, b: 0}]
Using flag ``dict=True`` (in keeping with semantics in :func:`~.solve`)
will force the result to always be a list with any solutions
as elements in that list.
>>> solve_undetermined_coeffs(a*x - 2*x, [a], dict=True)
[{a: 2}]
"""
if not (coeffs and all(i.is_Symbol for i in coeffs)):
raise ValueError('must provide symbols for coeffs')
if isinstance(equ, Eq):
eq = equ.lhs - equ.rhs
else:
eq = equ
ceq = cancel(eq)
xeq = _mexpand(ceq.as_numer_denom()[0], recursive=True)
free = xeq.free_symbols
coeffs = free & set(coeffs)
if not coeffs:
return ([], {}) if flags.get('set', None) else [] # solve(0, x) -> []
if not syms:
# e.g. A*exp(x) + B - (exp(x) + y) separated into parts that
# don't/do depend on coeffs gives
# -(exp(x) + y), A*exp(x) + B
# then see what symbols are common to both
# {x} = {x, A, B} - {x, y}
ind, dep = xeq.as_independent(*coeffs, as_Add=True)
dfree = dep.free_symbols
syms = dfree & ind.free_symbols
if not syms:
# but if the system looks like (a + b)*x + b - c
# then {} = {a, b, x} - c
# so calculate {x} = {a, b, x} - {a, b}
syms = dfree - set(coeffs)
if not syms:
syms = [Dummy()]
else:
if len(syms) == 1 and iterable(syms[0]):
syms = syms[0]
e, s, _ = recast_to_symbols([xeq], syms)
xeq = e[0]
syms = s
# find the functional forms in which symbols appear
gens = set(xeq.as_coefficients_dict(*syms).keys()) - {1}
cset = set(coeffs)
if any(g.has_xfree(cset) for g in gens):
return # a generator contained a coefficient symbol
# make sure we are working with symbols for generators
e, gens, _ = recast_to_symbols([xeq], list(gens))
xeq = e[0]
# collect coefficients in front of generators
system = list(collect(xeq, gens, evaluate=False).values())
# get a solution
soln = solve(system, coeffs, **flags)
# unpack unless told otherwise if length is 1
settings = flags.get('dict', None) or flags.get('set', None)
if type(soln) is dict or settings or len(soln) != 1:
return soln
return soln[0]
def solve_linear_system_LU(matrix, syms):
"""
Solves the augmented matrix system using ``LUsolve`` and returns a
dictionary in which solutions are keyed to the symbols of *syms* as ordered.
Explanation
===========
The matrix must be invertible.
Examples
========
>>> from sympy import Matrix, solve_linear_system_LU
>>> from sympy.abc import x, y, z
>>> solve_linear_system_LU(Matrix([
... [1, 2, 0, 1],
... [3, 2, 2, 1],
... [2, 0, 0, 1]]), [x, y, z])
{x: 1/2, y: 1/4, z: -1/2}
See Also
========
LUsolve
"""
if matrix.rows != matrix.cols - 1:
raise ValueError("Rows should be equal to columns - 1")
A = matrix[:matrix.rows, :matrix.rows]
b = matrix[:, matrix.cols - 1:]
soln = A.LUsolve(b)
solutions = {}
for i in range(soln.rows):
solutions[syms[i]] = soln[i, 0]
return solutions
def det_perm(M):
"""
Return the determinant of *M* by using permutations to select factors.
Explanation
===========
For sizes larger than 8 the number of permutations becomes prohibitively
large, or if there are no symbols in the matrix, it is better to use the
standard determinant routines (e.g., ``M.det()``.)
See Also
========
det_minor
det_quick
"""
args = []
s = True
n = M.rows
list_ = M.flat()
for perm in generate_bell(n):
fac = []
idx = 0
for j in perm:
fac.append(list_[idx + j])
idx += n
term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7
args.append(term if s else -term)
s = not s
return Add(*args)
def det_minor(M):
"""
Return the ``det(M)`` computed from minors without
introducing new nesting in products.
See Also
========
det_perm
det_quick
"""
n = M.rows
if n == 2:
return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1]
else:
return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in
Add.make_args(det_minor(M.minor_submatrix(0, i)))])
if M[0, i] else S.Zero for i in range(n)])
def det_quick(M, method=None):
"""
Return ``det(M)`` assuming that either
there are lots of zeros or the size of the matrix
is small. If this assumption is not met, then the normal
Matrix.det function will be used with method = ``method``.
See Also
========
det_minor
det_perm
"""
if any(i.has(Symbol) for i in M):
if M.rows < 8 and all(i.has(Symbol) for i in M):
return det_perm(M)
return det_minor(M)
else:
return M.det(method=method) if method else M.det()
def inv_quick(M):
"""Return the inverse of ``M``, assuming that either
there are lots of zeros or the size of the matrix
is small.
"""
if not all(i.is_Number for i in M):
if not any(i.is_Number for i in M):
det = lambda _: det_perm(_)
else:
det = lambda _: det_minor(_)
else:
return M.inv()
n = M.rows
d = det(M)
if d == S.Zero:
raise NonInvertibleMatrixError("Matrix det == 0; not invertible")
ret = zeros(n)
s1 = -1
for i in range(n):
s = s1 = -s1
for j in range(n):
di = det(M.minor_submatrix(i, j))
ret[j, i] = s*di/d
s = -s
return ret
# these are functions that have multiple inverse values per period
multi_inverses = {
sin: lambda x: (asin(x), S.Pi - asin(x)),
cos: lambda x: (acos(x), 2*S.Pi - acos(x)),
}
def _vsolve(e, s, **flags):
"""return list of scalar values for the solution of e for symbol s"""
return [i[s] for i in _solve(e, s, **flags)]
def _tsolve(eq, sym, **flags):
"""
Helper for ``_solve`` that solves a transcendental equation with respect
to the given symbol. Various equations containing powers and logarithms,
can be solved.
There is currently no guarantee that all solutions will be returned or
that a real solution will be favored over a complex one.
Either a list of potential solutions will be returned or None will be
returned (in the case that no method was known to get a solution
for the equation). All other errors (like the inability to cast an
expression as a Poly) are unhandled.
Examples
========
>>> from sympy import log, ordered
>>> from sympy.solvers.solvers import _tsolve as tsolve
>>> from sympy.abc import x
>>> list(ordered(tsolve(3**(2*x + 5) - 4, x)))
[-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)]
>>> tsolve(log(x) + 2*x, x)
[LambertW(2)/2]
"""
if 'tsolve_saw' not in flags:
flags['tsolve_saw'] = []
if eq in flags['tsolve_saw']:
return None
else:
flags['tsolve_saw'].append(eq)
rhs, lhs = _invert(eq, sym)
if lhs == sym:
return [rhs]
try:
if lhs.is_Add:
# it's time to try factoring; powdenest is used
# to try get powers in standard form for better factoring
f = factor(powdenest(lhs - rhs))
if f.is_Mul:
return _vsolve(f, sym, **flags)
if rhs:
f = logcombine(lhs, force=flags.get('force', True))
if f.count(log) != lhs.count(log):
if isinstance(f, log):
return _vsolve(f.args[0] - exp(rhs), sym, **flags)
return _tsolve(f - rhs, sym, **flags)
elif lhs.is_Pow:
if lhs.exp.is_Integer:
if lhs - rhs != eq:
return _vsolve(lhs - rhs, sym, **flags)
if sym not in lhs.exp.free_symbols:
return _vsolve(lhs.base - rhs**(1/lhs.exp), sym, **flags)
# _tsolve calls this with Dummy before passing the actual number in.
if any(t.is_Dummy for t in rhs.free_symbols):
raise NotImplementedError # _tsolve will call here again...
# a ** g(x) == 0
if not rhs:
# f(x)**g(x) only has solutions where f(x) == 0 and g(x) != 0 at
# the same place
sol_base = _vsolve(lhs.base, sym, **flags)
return [s for s in sol_base if lhs.exp.subs(sym, s) != 0] # XXX use checksol here?
# a ** g(x) == b
if not lhs.base.has(sym):
if lhs.base == 0:
return _vsolve(lhs.exp, sym, **flags) if rhs != 0 else []
# Gets most solutions...
if lhs.base == rhs.as_base_exp()[0]:
# handles case when bases are equal
sol = _vsolve(lhs.exp - rhs.as_base_exp()[1], sym, **flags)
else:
# handles cases when bases are not equal and exp
# may or may not be equal
f = exp(log(lhs.base)*lhs.exp) - exp(log(rhs))
sol = _vsolve(f, sym, **flags)
# Check for duplicate solutions
def equal(expr1, expr2):
_ = Dummy()
eq = checksol(expr1 - _, _, expr2)
if eq is None:
if nsimplify(expr1) != nsimplify(expr2):
return False
# they might be coincidentally the same
# so check more rigorously
eq = expr1.equals(expr2) # XXX expensive but necessary?
return eq
# Guess a rational exponent
e_rat = nsimplify(log(abs(rhs))/log(abs(lhs.base)))
e_rat = simplify(posify(e_rat)[0])
n, d = fraction(e_rat)
if expand(lhs.base**n - rhs**d) == 0:
sol = [s for s in sol if not equal(lhs.exp.subs(sym, s), e_rat)]
sol.extend(_vsolve(lhs.exp - e_rat, sym, **flags))
return list(set(sol))
# f(x) ** g(x) == c
else:
sol = []
logform = lhs.exp*log(lhs.base) - log(rhs)
if logform != lhs - rhs:
try:
sol.extend(_vsolve(logform, sym, **flags))
except NotImplementedError:
pass
# Collect possible solutions and check with substitution later.
check = []
if rhs == 1:
# f(x) ** g(x) = 1 -- g(x)=0 or f(x)=+-1
check.extend(_vsolve(lhs.exp, sym, **flags))
check.extend(_vsolve(lhs.base - 1, sym, **flags))
check.extend(_vsolve(lhs.base + 1, sym, **flags))
elif rhs.is_Rational:
for d in (i for i in divisors(abs(rhs.p)) if i != 1):
e, t = integer_log(rhs.p, d)
if not t:
continue # rhs.p != d**b
for s in divisors(abs(rhs.q)):
if s**e== rhs.q:
r = Rational(d, s)
check.extend(_vsolve(lhs.base - r, sym, **flags))
check.extend(_vsolve(lhs.base + r, sym, **flags))
check.extend(_vsolve(lhs.exp - e, sym, **flags))
elif rhs.is_irrational:
b_l, e_l = lhs.base.as_base_exp()
n, d = (e_l*lhs.exp).as_numer_denom()
b, e = sqrtdenest(rhs).as_base_exp()
check = [sqrtdenest(i) for i in (_vsolve(lhs.base - b, sym, **flags))]
check.extend([sqrtdenest(i) for i in (_vsolve(lhs.exp - e, sym, **flags))])
if e_l*d != 1:
check.extend(_vsolve(b_l**n - rhs**(e_l*d), sym, **flags))
for s in check:
ok = checksol(eq, sym, s)
if ok is None:
ok = eq.subs(sym, s).equals(0)
if ok:
sol.append(s)
return list(set(sol))
elif lhs.is_Function and len(lhs.args) == 1:
if lhs.func in multi_inverses:
# sin(x) = 1/3 -> x - asin(1/3) & x - (pi - asin(1/3))
soln = []
for i in multi_inverses[type(lhs)](rhs):
soln.extend(_vsolve(lhs.args[0] - i, sym, **flags))
return list(set(soln))
elif lhs.func == LambertW:
return _vsolve(lhs.args[0] - rhs*exp(rhs), sym, **flags)
rewrite = lhs.rewrite(exp)
if rewrite != lhs:
return _vsolve(rewrite - rhs, sym, **flags)
except NotImplementedError:
pass
# maybe it is a lambert pattern
if flags.pop('bivariate', True):
# lambert forms may need some help being recognized, e.g. changing
# 2**(3*x) + x**3*log(2)**3 + 3*x**2*log(2)**2 + 3*x*log(2) + 1
# to 2**(3*x) + (x*log(2) + 1)**3
# make generator in log have exponent of 1
logs = eq.atoms(log)
spow = min(
{i.exp for j in logs for i in j.atoms(Pow)
if i.base == sym} or {1})
if spow != 1:
p = sym**spow
u = Dummy('bivariate-cov')
ueq = eq.subs(p, u)
if not ueq.has_free(sym):
sol = _vsolve(ueq, u, **flags)
inv = _vsolve(p - u, sym)
return [i.subs(u, s) for i in inv for s in sol]
g = _filtered_gens(eq.as_poly(), sym)
up_or_log = set()
for gi in g:
if isinstance(gi, (exp, log)) or (gi.is_Pow and gi.base == S.Exp1):
up_or_log.add(gi)
elif gi.is_Pow:
gisimp = powdenest(expand_power_exp(gi))
if gisimp.is_Pow and sym in gisimp.exp.free_symbols:
up_or_log.add(gi)
eq_down = expand_log(expand_power_exp(eq)).subs(
dict(list(zip(up_or_log, [0]*len(up_or_log)))))
eq = expand_power_exp(factor(eq_down, deep=True) + (eq - eq_down))
rhs, lhs = _invert(eq, sym)
if lhs.has(sym):
try:
poly = lhs.as_poly()
g = _filtered_gens(poly, sym)
_eq = lhs - rhs
sols = _solve_lambert(_eq, sym, g)
# use a simplified form if it satisfies eq
# and has fewer operations
for n, s in enumerate(sols):
ns = nsimplify(s)
if ns != s and ns.count_ops() <= s.count_ops():
ok = checksol(_eq, sym, ns)
if ok is None:
ok = _eq.subs(sym, ns).equals(0)
if ok:
sols[n] = ns
return sols
except NotImplementedError:
# maybe it's a convoluted function
if len(g) == 2:
try:
gpu = bivariate_type(lhs - rhs, *g)
if gpu is None:
raise NotImplementedError
g, p, u = gpu
flags['bivariate'] = False
inversion = _tsolve(g - u, sym, **flags)
if inversion:
sol = _vsolve(p, u, **flags)
return list({i.subs(u, s)
for i in inversion for s in sol})
except NotImplementedError:
pass
else:
pass
if flags.pop('force', True):
flags['force'] = False
pos, reps = posify(lhs - rhs)
if rhs == S.ComplexInfinity:
return []
for u, s in reps.items():
if s == sym:
break
else:
u = sym
if pos.has(u):
try:
soln = _vsolve(pos, u, **flags)
return [s.subs(reps) for s in soln]
except NotImplementedError:
pass
else:
pass # here for coverage
return # here for coverage
# TODO: option for calculating J numerically
@conserve_mpmath_dps
def nsolve(*args, dict=False, **kwargs):
r"""
Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0,
modules=['mpmath'], **kwargs)``.
Explanation
===========
``f`` is a vector function of symbolic expressions representing the system.
*args* are the variables. If there is only one variable, this argument can
be omitted. ``x0`` is a starting vector close to a solution.
Use the modules keyword to specify which modules should be used to
evaluate the function and the Jacobian matrix. Make sure to use a module
that supports matrices. For more information on the syntax, please see the
docstring of ``lambdify``.
If the keyword arguments contain ``dict=True`` (default is False) ``nsolve``
will return a list (perhaps empty) of solution mappings. This might be
especially useful if you want to use ``nsolve`` as a fallback to solve since
using the dict argument for both methods produces return values of
consistent type structure. Please note: to keep this consistent with
``solve``, the solution will be returned in a list even though ``nsolve``
(currently at least) only finds one solution at a time.
Overdetermined systems are supported.
Examples
========
>>> from sympy import Symbol, nsolve
>>> import mpmath
>>> mpmath.mp.dps = 15
>>> x1 = Symbol('x1')
>>> x2 = Symbol('x2')
>>> f1 = 3 * x1**2 - 2 * x2**2 - 1
>>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
>>> print(nsolve((f1, f2), (x1, x2), (-1, 1)))
Matrix([[-1.19287309935246], [1.27844411169911]])
For one-dimensional functions the syntax is simplified:
>>> from sympy import sin, nsolve
>>> from sympy.abc import x
>>> nsolve(sin(x), x, 2)
3.14159265358979
>>> nsolve(sin(x), 2)
3.14159265358979
To solve with higher precision than the default, use the prec argument:
>>> from sympy import cos
>>> nsolve(cos(x) - x, 1)
0.739085133215161
>>> nsolve(cos(x) - x, 1, prec=50)
0.73908513321516064165531208767387340401341175890076
>>> cos(_)
0.73908513321516064165531208767387340401341175890076
To solve for complex roots of real functions, a nonreal initial point
must be specified:
>>> from sympy import I
>>> nsolve(x**2 + 2, I)
1.4142135623731*I
``mpmath.findroot`` is used and you can find their more extensive
documentation, especially concerning keyword parameters and
available solvers. Note, however, that functions which are very
steep near the root, the verification of the solution may fail. In
this case you should use the flag ``verify=False`` and
independently verify the solution.
>>> from sympy import cos, cosh
>>> f = cos(x)*cosh(x) - 1
>>> nsolve(f, 3.14*100)
Traceback (most recent call last):
...
ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19)
>>> ans = nsolve(f, 3.14*100, verify=False); ans
312.588469032184
>>> f.subs(x, ans).n(2)
2.1e+121
>>> (f/f.diff(x)).subs(x, ans).n(2)
7.4e-15
One might safely skip the verification if bounds of the root are known
and a bisection method is used:
>>> bounds = lambda i: (3.14*i, 3.14*(i + 1))
>>> nsolve(f, bounds(100), solver='bisect', verify=False)
315.730061685774
Alternatively, a function may be better behaved when the
denominator is ignored. Since this is not always the case, however,
the decision of what function to use is left to the discretion of
the user.
>>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100
>>> nsolve(eq, 0.46)
Traceback (most recent call last):
...
ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19)
Try another starting point or tweak arguments.
>>> nsolve(eq.as_numer_denom()[0], 0.46)
0.46792545969349058
"""
# there are several other SymPy functions that use method= so
# guard against that here
if 'method' in kwargs:
raise ValueError(filldedent('''
Keyword "method" should not be used in this context. When using
some mpmath solvers directly, the keyword "method" is
used, but when using nsolve (and findroot) the keyword to use is
"solver".'''))
if 'prec' in kwargs:
import mpmath
mpmath.mp.dps = kwargs.pop('prec')
# keyword argument to return result as a dictionary
as_dict = dict
from builtins import dict # to unhide the builtin
# interpret arguments
if len(args) == 3:
f = args[0]
fargs = args[1]
x0 = args[2]
if iterable(fargs) and iterable(x0):
if len(x0) != len(fargs):
raise TypeError('nsolve expected exactly %i guess vectors, got %i'
% (len(fargs), len(x0)))
elif len(args) == 2:
f = args[0]
fargs = None
x0 = args[1]
if iterable(f):
raise TypeError('nsolve expected 3 arguments, got 2')
elif len(args) < 2:
raise TypeError('nsolve expected at least 2 arguments, got %i'
% len(args))
else:
raise TypeError('nsolve expected at most 3 arguments, got %i'
% len(args))
modules = kwargs.get('modules', ['mpmath'])
if iterable(f):
f = list(f)
for i, fi in enumerate(f):
if isinstance(fi, Eq):
f[i] = fi.lhs - fi.rhs
f = Matrix(f).T
if iterable(x0):
x0 = list(x0)
if not isinstance(f, Matrix):
# assume it's a SymPy expression
if isinstance(f, Eq):
f = f.lhs - f.rhs
syms = f.free_symbols
if fargs is None:
fargs = syms.copy().pop()
if not (len(syms) == 1 and (fargs in syms or fargs[0] in syms)):
raise ValueError(filldedent('''
expected a one-dimensional and numerical function'''))
# the function is much better behaved if there is no denominator
# but sending the numerator is left to the user since sometimes
# the function is better behaved when the denominator is present
# e.g., issue 11768
f = lambdify(fargs, f, modules)
x = sympify(findroot(f, x0, **kwargs))
if as_dict:
return [{fargs: x}]
return x
if len(fargs) > f.cols:
raise NotImplementedError(filldedent('''
need at least as many equations as variables'''))
verbose = kwargs.get('verbose', False)
if verbose:
print('f(x):')
print(f)
# derive Jacobian
J = f.jacobian(fargs)
if verbose:
print('J(x):')
print(J)
# create functions
f = lambdify(fargs, f.T, modules)
J = lambdify(fargs, J, modules)
# solve the system numerically
x = findroot(f, x0, J=J, **kwargs)
if as_dict:
return [dict(zip(fargs, [sympify(xi) for xi in x]))]
return Matrix(x)
def _invert(eq, *symbols, **kwargs):
"""
Return tuple (i, d) where ``i`` is independent of *symbols* and ``d``
contains symbols.
Explanation
===========
``i`` and ``d`` are obtained after recursively using algebraic inversion
until an uninvertible ``d`` remains. If there are no free symbols then
``d`` will be zero. Some (but not necessarily all) solutions to the
expression ``i - d`` will be related to the solutions of the original
expression.
Examples
========
>>> from sympy.solvers.solvers import _invert as invert
>>> from sympy import sqrt, cos
>>> from sympy.abc import x, y
>>> invert(x - 3)
(3, x)
>>> invert(3)
(3, 0)
>>> invert(2*cos(x) - 1)
(1/2, cos(x))
>>> invert(sqrt(x) - 3)
(3, sqrt(x))
>>> invert(sqrt(x) + y, x)
(-y, sqrt(x))
>>> invert(sqrt(x) + y, y)
(-sqrt(x), y)
>>> invert(sqrt(x) + y, x, y)
(0, sqrt(x) + y)
If there is more than one symbol in a power's base and the exponent
is not an Integer, then the principal root will be used for the
inversion:
>>> invert(sqrt(x + y) - 2)
(4, x + y)
>>> invert(sqrt(x + y) - 2)
(4, x + y)
If the exponent is an Integer, setting ``integer_power`` to True
will force the principal root to be selected:
>>> invert(x**2 - 4, integer_power=True)
(2, x)
"""
eq = sympify(eq)
if eq.args:
# make sure we are working with flat eq
eq = eq.func(*eq.args)
free = eq.free_symbols
if not symbols:
symbols = free
if not free & set(symbols):
return eq, S.Zero
dointpow = bool(kwargs.get('integer_power', False))
lhs = eq
rhs = S.Zero
while True:
was = lhs
while True:
indep, dep = lhs.as_independent(*symbols)
# dep + indep == rhs
if lhs.is_Add:
# this indicates we have done it all
if indep.is_zero:
break
lhs = dep
rhs -= indep
# dep * indep == rhs
else:
# this indicates we have done it all
if indep is S.One:
break
lhs = dep
rhs /= indep
# collect like-terms in symbols
if lhs.is_Add:
terms = {}
for a in lhs.args:
i, d = a.as_independent(*symbols)
terms.setdefault(d, []).append(i)
if any(len(v) > 1 for v in terms.values()):
args = []
for d, i in terms.items():
if len(i) > 1:
args.append(Add(*i)*d)
else:
args.append(i[0]*d)
lhs = Add(*args)
# if it's a two-term Add with rhs = 0 and two powers we can get the
# dependent terms together, e.g. 3*f(x) + 2*g(x) -> f(x)/g(x) = -2/3
if lhs.is_Add and not rhs and len(lhs.args) == 2 and \
not lhs.is_polynomial(*symbols):
a, b = ordered(lhs.args)
ai, ad = a.as_independent(*symbols)
bi, bd = b.as_independent(*symbols)
if any(_ispow(i) for i in (ad, bd)):
a_base, a_exp = ad.as_base_exp()
b_base, b_exp = bd.as_base_exp()
if a_base == b_base:
# a = -b
lhs = powsimp(powdenest(ad/bd))
rhs = -bi/ai
else:
rat = ad/bd
_lhs = powsimp(ad/bd)
if _lhs != rat:
lhs = _lhs
rhs = -bi/ai
elif ai == -bi:
if isinstance(ad, Function) and ad.func == bd.func:
if len(ad.args) == len(bd.args) == 1:
lhs = ad.args[0] - bd.args[0]
elif len(ad.args) == len(bd.args):
# should be able to solve
# f(x, y) - f(2 - x, 0) == 0 -> x == 1
raise NotImplementedError(
'equal function with more than 1 argument')
else:
raise ValueError(
'function with different numbers of args')
elif lhs.is_Mul and any(_ispow(a) for a in lhs.args):
lhs = powsimp(powdenest(lhs))
if lhs.is_Function:
if hasattr(lhs, 'inverse') and lhs.inverse() is not None and len(lhs.args) == 1:
# -1
# f(x) = g -> x = f (g)
#
# /!\ inverse should not be defined if there are multiple values
# for the function -- these are handled in _tsolve
#
rhs = lhs.inverse()(rhs)
lhs = lhs.args[0]
elif isinstance(lhs, atan2):
y, x = lhs.args
lhs = 2*atan(y/(sqrt(x**2 + y**2) + x))
elif lhs.func == rhs.func:
if len(lhs.args) == len(rhs.args) == 1:
lhs = lhs.args[0]
rhs = rhs.args[0]
elif len(lhs.args) == len(rhs.args):
# should be able to solve
# f(x, y) == f(2, 3) -> x == 2
# f(x, x + y) == f(2, 3) -> x == 2
raise NotImplementedError(
'equal function with more than 1 argument')
else:
raise ValueError(
'function with different numbers of args')
if rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0:
lhs = 1/lhs
rhs = 1/rhs
# base**a = b -> base = b**(1/a) if
# a is an Integer and dointpow=True (this gives real branch of root)
# a is not an Integer and the equation is multivariate and the
# base has more than 1 symbol in it
# The rationale for this is that right now the multi-system solvers
# doesn't try to resolve generators to see, for example, if the whole
# system is written in terms of sqrt(x + y) so it will just fail, so we
# do that step here.
if lhs.is_Pow and (
lhs.exp.is_Integer and dointpow or not lhs.exp.is_Integer and
len(symbols) > 1 and len(lhs.base.free_symbols & set(symbols)) > 1):
rhs = rhs**(1/lhs.exp)
lhs = lhs.base
if lhs == was:
break
return rhs, lhs
def unrad(eq, *syms, **flags):
"""
Remove radicals with symbolic arguments and return (eq, cov),
None, or raise an error.
Explanation
===========
None is returned if there are no radicals to remove.
NotImplementedError is raised if there are radicals and they cannot be
removed or if the relationship between the original symbols and the
change of variable needed to rewrite the system as a polynomial cannot
be solved.
Otherwise the tuple, ``(eq, cov)``, is returned where:
*eq*, ``cov``
*eq* is an equation without radicals (in the symbol(s) of
interest) whose solutions are a superset of the solutions to the
original expression. *eq* might be rewritten in terms of a new
variable; the relationship to the original variables is given by
``cov`` which is a list containing ``v`` and ``v**p - b`` where
``p`` is the power needed to clear the radical and ``b`` is the
radical now expressed as a polynomial in the symbols of interest.
For example, for sqrt(2 - x) the tuple would be
``(c, c**2 - 2 + x)``. The solutions of *eq* will contain
solutions to the original equation (if there are any).
*syms*
An iterable of symbols which, if provided, will limit the focus of
radical removal: only radicals with one or more of the symbols of
interest will be cleared. All free symbols are used if *syms* is not
set.
*flags* are used internally for communication during recursive calls.
Two options are also recognized:
``take``, when defined, is interpreted as a single-argument function
that returns True if a given Pow should be handled.
Radicals can be removed from an expression if:
* All bases of the radicals are the same; a change of variables is
done in this case.
* If all radicals appear in one term of the expression.
* There are only four terms with sqrt() factors or there are less than
four terms having sqrt() factors.
* There are only two terms with radicals.
Examples
========
>>> from sympy.solvers.solvers import unrad
>>> from sympy.abc import x
>>> from sympy import sqrt, Rational, root
>>> unrad(sqrt(x)*x**Rational(1, 3) + 2)
(x**5 - 64, [])
>>> unrad(sqrt(x) + root(x + 1, 3))
(-x**3 + x**2 + 2*x + 1, [])
>>> eq = sqrt(x) + root(x, 3) - 2
>>> unrad(eq)
(_p**3 + _p**2 - 2, [_p, _p**6 - x])
"""
uflags = dict(check=False, simplify=False)
def _cov(p, e):
if cov:
# XXX - uncovered
oldp, olde = cov
if Poly(e, p).degree(p) in (1, 2):
cov[:] = [p, olde.subs(oldp, _vsolve(e, p, **uflags)[0])]
else:
raise NotImplementedError
else:
cov[:] = [p, e]
def _canonical(eq, cov):
if cov:
# change symbol to vanilla so no solutions are eliminated
p, e = cov
rep = {p: Dummy(p.name)}
eq = eq.xreplace(rep)
cov = [p.xreplace(rep), e.xreplace(rep)]
# remove constants and powers of factors since these don't change
# the location of the root; XXX should factor or factor_terms be used?
eq = factor_terms(_mexpand(eq.as_numer_denom()[0], recursive=True), clear=True)
if eq.is_Mul:
args = []
for f in eq.args:
if f.is_number:
continue
if f.is_Pow:
args.append(f.base)
else:
args.append(f)
eq = Mul(*args) # leave as Mul for more efficient solving
# make the sign canonical
margs = list(Mul.make_args(eq))
changed = False
for i, m in enumerate(margs):
if m.could_extract_minus_sign():
margs[i] = -m
changed = True
if changed:
eq = Mul(*margs, evaluate=False)
return eq, cov
def _Q(pow):
# return leading Rational of denominator of Pow's exponent
c = pow.as_base_exp()[1].as_coeff_Mul()[0]
if not c.is_Rational:
return S.One
return c.q
# define the _take method that will determine whether a term is of interest
def _take(d):
# return True if coefficient of any factor's exponent's den is not 1
for pow in Mul.make_args(d):
if not pow.is_Pow:
continue
if _Q(pow) == 1:
continue
if pow.free_symbols & syms:
return True
return False
_take = flags.setdefault('_take', _take)
if isinstance(eq, Eq):
eq = eq.lhs - eq.rhs # XXX legacy Eq as Eqn support
elif not isinstance(eq, Expr):
return
cov, nwas, rpt = [flags.setdefault(k, v) for k, v in
sorted(dict(cov=[], n=None, rpt=0).items())]
# preconditioning
eq = powdenest(factor_terms(eq, radical=True, clear=True))
eq = eq.as_numer_denom()[0]
eq = _mexpand(eq, recursive=True)
if eq.is_number:
return
# see if there are radicals in symbols of interest
syms = set(syms) or eq.free_symbols # _take uses this
poly = eq.as_poly()
gens = [g for g in poly.gens if _take(g)]
if not gens:
return
# recast poly in terms of eigen-gens
poly = eq.as_poly(*gens)
# not a polynomial e.g. 1 + sqrt(x)*exp(sqrt(x)) with gen sqrt(x)
if poly is None:
return
# - an exponent has a symbol of interest (don't handle)
if any(g.exp.has(*syms) for g in gens):
return
def _rads_bases_lcm(poly):
# if all the bases are the same or all the radicals are in one
# term, `lcm` will be the lcm of the denominators of the
# exponents of the radicals
lcm = 1
rads = set()
bases = set()
for g in poly.gens:
q = _Q(g)
if q != 1:
rads.add(g)
lcm = ilcm(lcm, q)
bases.add(g.base)
return rads, bases, lcm
rads, bases, lcm = _rads_bases_lcm(poly)
covsym = Dummy('p', nonnegative=True)
# only keep in syms symbols that actually appear in radicals;
# and update gens
newsyms = set()
for r in rads:
newsyms.update(syms & r.free_symbols)
if newsyms != syms:
syms = newsyms
# get terms together that have common generators
drad = dict(list(zip(rads, list(range(len(rads))))))
rterms = {(): []}
args = Add.make_args(poly.as_expr())
for t in args:
if _take(t):
common = set(t.as_poly().gens).intersection(rads)
key = tuple(sorted([drad[i] for i in common]))
else:
key = ()
rterms.setdefault(key, []).append(t)
others = Add(*rterms.pop(()))
rterms = [Add(*rterms[k]) for k in rterms.keys()]
# the output will depend on the order terms are processed, so
# make it canonical quickly
rterms = list(reversed(list(ordered(rterms))))
ok = False # we don't have a solution yet
depth = sqrt_depth(eq)
if len(rterms) == 1 and not (rterms[0].is_Add and lcm > 2):
eq = rterms[0]**lcm - ((-others)**lcm)
ok = True
else:
if len(rterms) == 1 and rterms[0].is_Add:
rterms = list(rterms[0].args)
if len(bases) == 1:
b = bases.pop()
if len(syms) > 1:
x = b.free_symbols
else:
x = syms
x = list(ordered(x))[0]
try:
inv = _vsolve(covsym**lcm - b, x, **uflags)
if not inv:
raise NotImplementedError
eq = poly.as_expr().subs(b, covsym**lcm).subs(x, inv[0])
_cov(covsym, covsym**lcm - b)
return _canonical(eq, cov)
except NotImplementedError:
pass
if len(rterms) == 2:
if not others:
eq = rterms[0]**lcm - (-rterms[1])**lcm
ok = True
elif not log(lcm, 2).is_Integer:
# the lcm-is-power-of-two case is handled below
r0, r1 = rterms
if flags.get('_reverse', False):
r1, r0 = r0, r1
i0 = _rads0, _bases0, lcm0 = _rads_bases_lcm(r0.as_poly())
i1 = _rads1, _bases1, lcm1 = _rads_bases_lcm(r1.as_poly())
for reverse in range(2):
if reverse:
i0, i1 = i1, i0
r0, r1 = r1, r0
_rads1, _, lcm1 = i1
_rads1 = Mul(*_rads1)
t1 = _rads1**lcm1
c = covsym**lcm1 - t1
for x in syms:
try:
sol = _vsolve(c, x, **uflags)
if not sol:
raise NotImplementedError
neweq = r0.subs(x, sol[0]) + covsym*r1/_rads1 + \
others
tmp = unrad(neweq, covsym)
if tmp:
eq, newcov = tmp
if newcov:
newp, newc = newcov
_cov(newp, c.subs(covsym,
_vsolve(newc, covsym, **uflags)[0]))
else:
_cov(covsym, c)
else:
eq = neweq
_cov(covsym, c)
ok = True
break
except NotImplementedError:
if reverse:
raise NotImplementedError(
'no successful change of variable found')
else:
pass
if ok:
break
elif len(rterms) == 3:
# two cube roots and another with order less than 5
# (so an analytical solution can be found) or a base
# that matches one of the cube root bases
info = [_rads_bases_lcm(i.as_poly()) for i in rterms]
RAD = 0
BASES = 1
LCM = 2
if info[0][LCM] != 3:
info.append(info.pop(0))
rterms.append(rterms.pop(0))
elif info[1][LCM] != 3:
info.append(info.pop(1))
rterms.append(rterms.pop(1))
if info[0][LCM] == info[1][LCM] == 3:
if info[1][BASES] != info[2][BASES]:
info[0], info[1] = info[1], info[0]
rterms[0], rterms[1] = rterms[1], rterms[0]
if info[1][BASES] == info[2][BASES]:
eq = rterms[0]**3 + (rterms[1] + rterms[2] + others)**3
ok = True
elif info[2][LCM] < 5:
# a*root(A, 3) + b*root(B, 3) + others = c
a, b, c, d, A, B = [Dummy(i) for i in 'abcdAB']
# zz represents the unraded expression into which the
# specifics for this case are substituted
zz = (c - d)*(A**3*a**9 + 3*A**2*B*a**6*b**3 -
3*A**2*a**6*c**3 + 9*A**2*a**6*c**2*d - 9*A**2*a**6*c*d**2 +
3*A**2*a**6*d**3 + 3*A*B**2*a**3*b**6 + 21*A*B*a**3*b**3*c**3 -
63*A*B*a**3*b**3*c**2*d + 63*A*B*a**3*b**3*c*d**2 -
21*A*B*a**3*b**3*d**3 + 3*A*a**3*c**6 - 18*A*a**3*c**5*d +
45*A*a**3*c**4*d**2 - 60*A*a**3*c**3*d**3 + 45*A*a**3*c**2*d**4 -
18*A*a**3*c*d**5 + 3*A*a**3*d**6 + B**3*b**9 - 3*B**2*b**6*c**3 +
9*B**2*b**6*c**2*d - 9*B**2*b**6*c*d**2 + 3*B**2*b**6*d**3 +
3*B*b**3*c**6 - 18*B*b**3*c**5*d + 45*B*b**3*c**4*d**2 -
60*B*b**3*c**3*d**3 + 45*B*b**3*c**2*d**4 - 18*B*b**3*c*d**5 +
3*B*b**3*d**6 - c**9 + 9*c**8*d - 36*c**7*d**2 + 84*c**6*d**3 -
126*c**5*d**4 + 126*c**4*d**5 - 84*c**3*d**6 + 36*c**2*d**7 -
9*c*d**8 + d**9)
def _t(i):
b = Mul(*info[i][RAD])
return cancel(rterms[i]/b), Mul(*info[i][BASES])
aa, AA = _t(0)
bb, BB = _t(1)
cc = -rterms[2]
dd = others
eq = zz.xreplace(dict(zip(
(a, A, b, B, c, d),
(aa, AA, bb, BB, cc, dd))))
ok = True
# handle power-of-2 cases
if not ok:
if log(lcm, 2).is_Integer and (not others and
len(rterms) == 4 or len(rterms) < 4):
def _norm2(a, b):
return a**2 + b**2 + 2*a*b
if len(rterms) == 4:
# (r0+r1)**2 - (r2+r3)**2
r0, r1, r2, r3 = rterms
eq = _norm2(r0, r1) - _norm2(r2, r3)
ok = True
elif len(rterms) == 3:
# (r1+r2)**2 - (r0+others)**2
r0, r1, r2 = rterms
eq = _norm2(r1, r2) - _norm2(r0, others)
ok = True
elif len(rterms) == 2:
# r0**2 - (r1+others)**2
r0, r1 = rterms
eq = r0**2 - _norm2(r1, others)
ok = True
new_depth = sqrt_depth(eq) if ok else depth
rpt += 1 # XXX how many repeats with others unchanging is enough?
if not ok or (
nwas is not None and len(rterms) == nwas and
new_depth is not None and new_depth == depth and
rpt > 3):
raise NotImplementedError('Cannot remove all radicals')
flags.update(dict(cov=cov, n=len(rterms), rpt=rpt))
neq = unrad(eq, *syms, **flags)
if neq:
eq, cov = neq
eq, cov = _canonical(eq, cov)
return eq, cov
# delayed imports
from sympy.solvers.bivariate import (
bivariate_type, _solve_lambert, _filtered_gens)
|
25be4efcfda08e1736d47a56f412246dc76c202a29d1855878c9300c098364fa | from sympy.core import Add, Mul, Pow, S
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.numbers import _sympifyit, oo, zoo
from sympy.core.relational import is_le, is_lt, is_ge, is_gt
from sympy.core.sympify import _sympify
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.logic.boolalg import And
from sympy.multipledispatch import dispatch
from sympy.series.order import Order
from sympy.sets.sets import FiniteSet
class AccumulationBounds(Expr):
r"""
# Note AccumulationBounds has an alias: AccumBounds
AccumulationBounds represent an interval `[a, b]`, which is always closed
at the ends. Here `a` and `b` can be any value from extended real numbers.
The intended meaning of AccummulationBounds is to give an approximate
location of the accumulation points of a real function at a limit point.
Let `a` and `b` be reals such that `a \le b`.
`\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}`
`\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}`
`\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}`
`\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}`
``oo`` and ``-oo`` are added to the second and third definition respectively,
since if either ``-oo`` or ``oo`` is an argument, then the other one should
be included (though not as an end point). This is forced, since we have,
for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at
`0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty`
should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need
not appear explicitly.
In many cases it suffices to know that the limit set is bounded.
However, in some other cases more exact information could be useful.
For example, all accumulation values of `\cos(x) + 1` are non-negative.
(``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``)
A AccumulationBounds object is defined to be real AccumulationBounds,
if its end points are finite reals.
Let `X`, `Y` be real AccumulationBounds, then their sum, difference,
product are defined to be the following sets:
`X + Y = \{ x+y \mid x \in X \cap y \in Y\}`
`X - Y = \{ x-y \mid x \in X \cap y \in Y\}`
`X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}`
When an AccumBounds is raised to a negative power, if 0 is contained
between the bounds then an infinite range is returned, otherwise if an
endpoint is 0 then a semi-infinite range with consistent sign will be returned.
AccumBounds in expressions behave a lot like Intervals but the
semantics are not necessarily the same. Division (or exponentiation
to a negative integer power) could be handled with *intervals* by
returning a union of the results obtained after splitting the
bounds between negatives and positives, but that is not done with
AccumBounds. In addition, bounds are assumed to be independent of
each other; if the same bound is used in more than one place in an
expression, the result may not be the supremum or infimum of the
expression (see below). Finally, when a boundary is ``1``,
exponentiation to the power of ``oo`` yields ``oo``, neither
``1`` nor ``nan``.
Examples
========
>>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo
>>> from sympy.abc import x
>>> AccumBounds(0, 1) + AccumBounds(1, 2)
AccumBounds(1, 3)
>>> AccumBounds(0, 1) - AccumBounds(0, 2)
AccumBounds(-2, 1)
>>> AccumBounds(-2, 3)*AccumBounds(-1, 1)
AccumBounds(-3, 3)
>>> AccumBounds(1, 2)*AccumBounds(3, 5)
AccumBounds(3, 10)
The exponentiation of AccumulationBounds is defined
as follows:
If 0 does not belong to `X` or `n > 0` then
`X^n = \{ x^n \mid x \in X\}`
>>> AccumBounds(1, 4)**(S(1)/2)
AccumBounds(1, 2)
otherwise, an infinite or semi-infinite result is obtained:
>>> 1/AccumBounds(-1, 1)
AccumBounds(-oo, oo)
>>> 1/AccumBounds(0, 2)
AccumBounds(1/2, oo)
>>> 1/AccumBounds(-oo, 0)
AccumBounds(-oo, 0)
A boundary of 1 will always generate all nonnegatives:
>>> AccumBounds(1, 2)**oo
AccumBounds(0, oo)
>>> AccumBounds(0, 1)**oo
AccumBounds(0, oo)
If the exponent is itself an AccumulationBounds or is not an
integer then unevaluated results will be returned unless the base
values are positive:
>>> AccumBounds(2, 3)**AccumBounds(-1, 2)
AccumBounds(1/3, 9)
>>> AccumBounds(-2, 3)**AccumBounds(-1, 2)
AccumBounds(-2, 3)**AccumBounds(-1, 2)
>>> AccumBounds(-2, -1)**(S(1)/2)
sqrt(AccumBounds(-2, -1))
Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle`
>>> AccumBounds(-1, 1)**2
AccumBounds(0, 1)
>>> AccumBounds(1, 3) < 4
True
>>> AccumBounds(1, 3) < -1
False
Some elementary functions can also take AccumulationBounds as input.
A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle`
is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}`
>>> sin(AccumBounds(pi/6, pi/3))
AccumBounds(1/2, sqrt(3)/2)
>>> exp(AccumBounds(0, 1))
AccumBounds(1, E)
>>> log(AccumBounds(1, E))
AccumBounds(0, 1)
Some symbol in an expression can be substituted for a AccumulationBounds
object. But it does not necessarily evaluate the AccumulationBounds for
that expression.
The same expression can be evaluated to different values depending upon
the form it is used for substitution since each instance of an
AccumulationBounds is considered independent. For example:
>>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))
AccumBounds(-1, 4)
>>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))
AccumBounds(0, 4)
References
==========
.. [1] https://en.wikipedia.org/wiki/Interval_arithmetic
.. [2] http://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf
Notes
=====
Do not use ``AccumulationBounds`` for floating point interval arithmetic
calculations, use ``mpmath.iv`` instead.
"""
is_extended_real = True
is_number = False
def __new__(cls, min, max):
min = _sympify(min)
max = _sympify(max)
# Only allow real intervals (use symbols with 'is_extended_real=True').
if not min.is_extended_real or not max.is_extended_real:
raise ValueError("Only real AccumulationBounds are supported")
if max == min:
return max
# Make sure that the created AccumBounds object will be valid.
if max.is_number and min.is_number:
bad = max.is_comparable and min.is_comparable and max < min
else:
bad = (max - min).is_extended_negative
if bad:
raise ValueError(
"Lower limit should be smaller than upper limit")
return Basic.__new__(cls, min, max)
# setting the operation priority
_op_priority = 11.0
def _eval_is_real(self):
if self.min.is_real and self.max.is_real:
return True
@property
def min(self):
"""
Returns the minimum possible value attained by AccumulationBounds
object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).min
1
"""
return self.args[0]
@property
def max(self):
"""
Returns the maximum possible value attained by AccumulationBounds
object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).max
3
"""
return self.args[1]
@property
def delta(self):
"""
Returns the difference of maximum possible value attained by
AccumulationBounds object and minimum possible value attained
by AccumulationBounds object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).delta
2
"""
return self.max - self.min
@property
def mid(self):
"""
Returns the mean of maximum possible value attained by
AccumulationBounds object and minimum possible value
attained by AccumulationBounds object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).mid
2
"""
return (self.min + self.max) / 2
@_sympifyit('other', NotImplemented)
def _eval_power(self, other):
return self.__pow__(other)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
return AccumBounds(
Add(self.min, other.min),
Add(self.max, other.max))
if other is S.Infinity and self.min is S.NegativeInfinity or \
other is S.NegativeInfinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif other.is_extended_real:
if self.min is S.NegativeInfinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif self.min is S.NegativeInfinity:
return AccumBounds(-oo, self.max + other)
elif self.max is S.Infinity:
return AccumBounds(self.min + other, oo)
else:
return AccumBounds(Add(self.min, other), Add(self.max, other))
return Add(self, other, evaluate=False)
return NotImplemented
__radd__ = __add__
def __neg__(self):
return AccumBounds(-self.max, -self.min)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
return AccumBounds(
Add(self.min, -other.max),
Add(self.max, -other.min))
if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \
other is S.Infinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif other.is_extended_real:
if self.min is S.NegativeInfinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif self.min is S.NegativeInfinity:
return AccumBounds(-oo, self.max - other)
elif self.max is S.Infinity:
return AccumBounds(self.min - other, oo)
else:
return AccumBounds(
Add(self.min, -other),
Add(self.max, -other))
return Add(self, -other, evaluate=False)
return NotImplemented
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return self.__neg__() + other
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if self.args == (-oo, oo):
return self
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
if other.args == (-oo, oo):
return other
v = set()
for a in self.args:
vi = other*a
for i in vi.args or (vi,):
v.add(i)
return AccumBounds(Min(*v), Max(*v))
if other is S.Infinity:
if self.min.is_zero:
return AccumBounds(0, oo)
if self.max.is_zero:
return AccumBounds(-oo, 0)
if other is S.NegativeInfinity:
if self.min.is_zero:
return AccumBounds(-oo, 0)
if self.max.is_zero:
return AccumBounds(0, oo)
if other.is_extended_real:
if other.is_zero:
if self.max is S.Infinity:
return AccumBounds(0, oo)
if self.min is S.NegativeInfinity:
return AccumBounds(-oo, 0)
return S.Zero
if other.is_extended_positive:
return AccumBounds(
Mul(self.min, other),
Mul(self.max, other))
elif other.is_extended_negative:
return AccumBounds(
Mul(self.max, other),
Mul(self.min, other))
if isinstance(other, Order):
return other
return Mul(self, other, evaluate=False)
return NotImplemented
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
if other.min.is_positive or other.max.is_negative:
return self * AccumBounds(1/other.max, 1/other.min)
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and
other.min.is_extended_nonpositive and other.max.is_extended_nonnegative):
if self.min.is_zero and other.min.is_zero:
return AccumBounds(0, oo)
if self.max.is_zero and other.min.is_zero:
return AccumBounds(-oo, 0)
return AccumBounds(-oo, oo)
if self.max.is_extended_negative:
if other.min.is_extended_negative:
if other.max.is_zero:
return AccumBounds(self.max / other.min, oo)
if other.max.is_extended_positive:
# if we were dealing with intervals we would return
# Union(Interval(-oo, self.max/other.max),
# Interval(self.max/other.min, oo))
return AccumBounds(-oo, oo)
if other.min.is_zero and other.max.is_extended_positive:
return AccumBounds(-oo, self.max / other.max)
if self.min.is_extended_positive:
if other.min.is_extended_negative:
if other.max.is_zero:
return AccumBounds(-oo, self.min / other.min)
if other.max.is_extended_positive:
# if we were dealing with intervals we would return
# Union(Interval(-oo, self.min/other.min),
# Interval(self.min/other.max, oo))
return AccumBounds(-oo, oo)
if other.min.is_zero and other.max.is_extended_positive:
return AccumBounds(self.min / other.max, oo)
elif other.is_extended_real:
if other in (S.Infinity, S.NegativeInfinity):
if self == AccumBounds(-oo, oo):
return AccumBounds(-oo, oo)
if self.max is S.Infinity:
return AccumBounds(Min(0, other), Max(0, other))
if self.min is S.NegativeInfinity:
return AccumBounds(Min(0, -other), Max(0, -other))
if other.is_extended_positive:
return AccumBounds(self.min / other, self.max / other)
elif other.is_extended_negative:
return AccumBounds(self.max / other, self.min / other)
if (1 / other) is S.ComplexInfinity:
return Mul(self, 1 / other, evaluate=False)
else:
return Mul(self, 1 / other)
return NotImplemented
@_sympifyit('other', NotImplemented)
def __rtruediv__(self, other):
if isinstance(other, Expr):
if other.is_extended_real:
if other.is_zero:
return S.Zero
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative):
if self.min.is_zero:
if other.is_extended_positive:
return AccumBounds(Mul(other, 1 / self.max), oo)
if other.is_extended_negative:
return AccumBounds(-oo, Mul(other, 1 / self.max))
if self.max.is_zero:
if other.is_extended_positive:
return AccumBounds(-oo, Mul(other, 1 / self.min))
if other.is_extended_negative:
return AccumBounds(Mul(other, 1 / self.min), oo)
return AccumBounds(-oo, oo)
else:
return AccumBounds(Min(other / self.min, other / self.max),
Max(other / self.min, other / self.max))
return Mul(other, 1 / self, evaluate=False)
else:
return NotImplemented
@_sympifyit('other', NotImplemented)
def __pow__(self, other):
if isinstance(other, Expr):
if other is S.Infinity:
if self.min.is_extended_nonnegative:
if self.max < 1:
return S.Zero
if self.min > 1:
return S.Infinity
return AccumBounds(0, oo)
elif self.max.is_extended_negative:
if self.min > -1:
return S.Zero
if self.max < -1:
return zoo
return S.NaN
else:
if self.min > -1:
if self.max < 1:
return S.Zero
return AccumBounds(0, oo)
return AccumBounds(-oo, oo)
if other is S.NegativeInfinity:
return (1/self)**oo
# generically true
if (self.max - self.min).is_nonnegative:
# well defined
if self.min.is_nonnegative:
# no 0 to worry about
if other.is_nonnegative:
# no infinity to worry about
return self.func(self.min**other, self.max**other)
if other.is_zero:
return S.One # x**0 = 1
if other.is_Integer or other.is_integer:
if self.min.is_extended_positive:
return AccumBounds(
Min(self.min**other, self.max**other),
Max(self.min**other, self.max**other))
elif self.max.is_extended_negative:
return AccumBounds(
Min(self.max**other, self.min**other),
Max(self.max**other, self.min**other))
if other % 2 == 0:
if other.is_extended_negative:
if self.min.is_zero:
return AccumBounds(self.max**other, oo)
if self.max.is_zero:
return AccumBounds(self.min**other, oo)
return (1/self)**(-other)
return AccumBounds(
S.Zero, Max(self.min**other, self.max**other))
elif other % 2 == 1:
if other.is_extended_negative:
if self.min.is_zero:
return AccumBounds(self.max**other, oo)
if self.max.is_zero:
return AccumBounds(-oo, self.min**other)
return (1/self)**(-other)
return AccumBounds(self.min**other, self.max**other)
# non-integer exponent
# 0**neg or neg**frac yields complex
if (other.is_number or other.is_rational) and (
self.min.is_extended_nonnegative or (
other.is_extended_nonnegative and
self.min.is_extended_nonnegative)):
num, den = other.as_numer_denom()
if num is S.One:
return AccumBounds(*[i**(1/den) for i in self.args])
elif den is not S.One: # e.g. if other is not Float
return (self**num)**(1/den) # ok for non-negative base
if isinstance(other, AccumBounds):
if (self.min.is_extended_positive or
self.min.is_extended_nonnegative and
other.min.is_extended_nonnegative):
p = [self**i for i in other.args]
if not any(i.is_Pow for i in p):
a = [j for i in p for j in i.args or (i,)]
try:
return self.func(min(a), max(a))
except TypeError: # can't sort
pass
return Pow(self, other, evaluate=False)
return NotImplemented
@_sympifyit('other', NotImplemented)
def __rpow__(self, other):
if other.is_real and other.is_extended_nonnegative and (
self.max - self.min).is_extended_positive:
if other is S.One:
return S.One
if other.is_extended_positive:
a, b = [other**i for i in self.args]
if min(a, b) != a:
a, b = b, a
return self.func(a, b)
if other.is_zero:
if self.min.is_zero:
return self.func(0, 1)
if self.min.is_extended_positive:
return S.Zero
return Pow(other, self, evaluate=False)
def __abs__(self):
if self.max.is_extended_negative:
return self.__neg__()
elif self.min.is_extended_negative:
return AccumBounds(S.Zero, Max(abs(self.min), self.max))
else:
return self
def __contains__(self, other):
"""
Returns ``True`` if other is contained in self, where other
belongs to extended real numbers, ``False`` if not contained,
otherwise TypeError is raised.
Examples
========
>>> from sympy import AccumBounds, oo
>>> 1 in AccumBounds(-1, 3)
True
-oo and oo go together as limits (in AccumulationBounds).
>>> -oo in AccumBounds(1, oo)
True
>>> oo in AccumBounds(-oo, 0)
True
"""
other = _sympify(other)
if other in (S.Infinity, S.NegativeInfinity):
if self.min is S.NegativeInfinity or self.max is S.Infinity:
return True
return False
rv = And(self.min <= other, self.max >= other)
if rv not in (True, False):
raise TypeError("input failed to evaluate")
return rv
def intersection(self, other):
"""
Returns the intersection of 'self' and 'other'.
Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds.
Parameters
==========
other: AccumulationBounds
Another AccumulationBounds object with which the intersection
has to be computed.
Returns
=======
AccumulationBounds
Intersection of ``self`` and ``other``.
Examples
========
>>> from sympy import AccumBounds, FiniteSet
>>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))
AccumBounds(2, 3)
>>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))
EmptySet
>>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5))
{1, 2}
"""
if not isinstance(other, (AccumBounds, FiniteSet)):
raise TypeError(
"Input must be AccumulationBounds or FiniteSet object")
if isinstance(other, FiniteSet):
fin_set = S.EmptySet
for i in other:
if i in self:
fin_set = fin_set + FiniteSet(i)
return fin_set
if self.max < other.min or self.min > other.max:
return S.EmptySet
if self.min <= other.min:
if self.max <= other.max:
return AccumBounds(other.min, self.max)
if self.max > other.max:
return other
if other.min <= self.min:
if other.max < self.max:
return AccumBounds(self.min, other.max)
if other.max > self.max:
return self
def union(self, other):
# TODO : Devise a better method for Union of AccumBounds
# this method is not actually correct and
# can be made better
if not isinstance(other, AccumBounds):
raise TypeError(
"Input must be AccumulationBounds or FiniteSet object")
if self.min <= other.min and self.max >= other.min:
return AccumBounds(self.min, Max(self.max, other.max))
if other.min <= self.min and other.max >= self.min:
return AccumBounds(other.min, Max(self.max, other.max))
@dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811
def _eval_is_le(lhs, rhs): # noqa:F811
if is_le(lhs.max, rhs.min):
return True
if is_gt(lhs.min, rhs.max):
return False
@dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811
def _eval_is_le(lhs, rhs): # noqa: F811
"""
Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds
object is greater than the range of values attained by ``rhs``,
where ``rhs`` may be any value of type AccumulationBounds object or
extended real number value, ``False`` if ``rhs`` satisfies
the same property, else an unevaluated :py:class:`~.Relational`.
Examples
========
>>> from sympy import AccumBounds, oo
>>> AccumBounds(1, 3) > AccumBounds(4, oo)
False
>>> AccumBounds(1, 4) > AccumBounds(3, 4)
AccumBounds(1, 4) > AccumBounds(3, 4)
>>> AccumBounds(1, oo) > -1
True
"""
if not rhs.is_extended_real:
raise TypeError(
"Invalid comparison of %s %s" %
(type(rhs), rhs))
elif rhs.is_comparable:
if is_le(lhs.max, rhs):
return True
if is_gt(lhs.min, rhs):
return False
@dispatch(AccumulationBounds, AccumulationBounds)
def _eval_is_ge(lhs, rhs): # noqa:F811
if is_ge(lhs.min, rhs.max):
return True
if is_lt(lhs.max, rhs.min):
return False
@dispatch(AccumulationBounds, Expr) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa: F811
"""
Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds
object is less that the range of values attained by ``rhs``, where
other may be any value of type AccumulationBounds object or extended
real number value, ``False`` if ``rhs`` satisfies the same
property, else an unevaluated :py:class:`~.Relational`.
Examples
========
>>> from sympy import AccumBounds, oo
>>> AccumBounds(1, 3) >= AccumBounds(4, oo)
False
>>> AccumBounds(1, 4) >= AccumBounds(3, 4)
AccumBounds(1, 4) >= AccumBounds(3, 4)
>>> AccumBounds(1, oo) >= 1
True
"""
if not rhs.is_extended_real:
raise TypeError(
"Invalid comparison of %s %s" %
(type(rhs), rhs))
elif rhs.is_comparable:
if is_ge(lhs.min, rhs):
return True
if is_lt(lhs.max, rhs):
return False
@dispatch(Expr, AccumulationBounds) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
if not lhs.is_extended_real:
raise TypeError(
"Invalid comparison of %s %s" %
(type(lhs), lhs))
elif lhs.is_comparable:
if is_le(rhs.max, lhs):
return True
if is_gt(rhs.min, lhs):
return False
@dispatch(AccumulationBounds, AccumulationBounds) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
if is_ge(lhs.min, rhs.max):
return True
if is_lt(lhs.max, rhs.min):
return False
# setting an alias for AccumulationBounds
AccumBounds = AccumulationBounds
|
a7cb2456e6392475431a8b8dfa4c59974338bae1fb51a40a0034b1a16fec4e4c | """
This module provides convenient functions to transform SymPy expressions to
lambda functions which can be used to calculate numerical values very fast.
"""
from typing import Any, Dict as tDict
import builtins
import inspect
import keyword
import textwrap
import linecache
# Required despite static analysis claiming it is not used
from sympy.external import import_module # noqa:F401
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import (is_sequence, iterable,
NotIterable, flatten)
from sympy.utilities.misc import filldedent
__doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']}
# Default namespaces, letting us define translations that can't be defined
# by simple variable maps, like I => 1j
MATH_DEFAULT = {} # type: tDict[str, Any]
MPMATH_DEFAULT = {} # type: tDict[str, Any]
NUMPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
SCIPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
CUPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
JAX_DEFAULT = {"I": 1j} # type: tDict[str, Any]
TENSORFLOW_DEFAULT = {} # type: tDict[str, Any]
SYMPY_DEFAULT = {} # type: tDict[str, Any]
NUMEXPR_DEFAULT = {} # type: tDict[str, Any]
# These are the namespaces the lambda functions will use.
# These are separate from the names above because they are modified
# throughout this file, whereas the defaults should remain unmodified.
MATH = MATH_DEFAULT.copy()
MPMATH = MPMATH_DEFAULT.copy()
NUMPY = NUMPY_DEFAULT.copy()
SCIPY = SCIPY_DEFAULT.copy()
CUPY = CUPY_DEFAULT.copy()
JAX = JAX_DEFAULT.copy()
TENSORFLOW = TENSORFLOW_DEFAULT.copy()
SYMPY = SYMPY_DEFAULT.copy()
NUMEXPR = NUMEXPR_DEFAULT.copy()
# Mappings between SymPy and other modules function names.
MATH_TRANSLATIONS = {
"ceiling": "ceil",
"E": "e",
"ln": "log",
}
# NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses
# of Function to automatically evalf.
MPMATH_TRANSLATIONS = {
"Abs": "fabs",
"elliptic_k": "ellipk",
"elliptic_f": "ellipf",
"elliptic_e": "ellipe",
"elliptic_pi": "ellippi",
"ceiling": "ceil",
"chebyshevt": "chebyt",
"chebyshevu": "chebyu",
"E": "e",
"I": "j",
"ln": "log",
#"lowergamma":"lower_gamma",
"oo": "inf",
#"uppergamma":"upper_gamma",
"LambertW": "lambertw",
"MutableDenseMatrix": "matrix",
"ImmutableDenseMatrix": "matrix",
"conjugate": "conj",
"dirichlet_eta": "altzeta",
"Ei": "ei",
"Shi": "shi",
"Chi": "chi",
"Si": "si",
"Ci": "ci",
"RisingFactorial": "rf",
"FallingFactorial": "ff",
"betainc_regularized": "betainc",
}
NUMPY_TRANSLATIONS = {
"Heaviside": "heaviside",
} # type: tDict[str, str]
SCIPY_TRANSLATIONS = {} # type: tDict[str, str]
CUPY_TRANSLATIONS = {} # type: tDict[str, str]
JAX_TRANSLATIONS = {} # type: tDict[str, str]
TENSORFLOW_TRANSLATIONS = {} # type: tDict[str, str]
NUMEXPR_TRANSLATIONS = {} # type: tDict[str, str]
# Available modules:
MODULES = {
"math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)),
"mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)),
"numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)),
"scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import scipy; import numpy; from scipy.special import *",)),
"cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)),
"jax": (JAX, JAX_DEFAULT, JAX_TRANSLATIONS, ("import jax",)),
"tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)),
"sympy": (SYMPY, SYMPY_DEFAULT, {}, (
"from sympy.functions import *",
"from sympy.matrices import *",
"from sympy import Integral, pi, oo, nan, zoo, E, I",)),
"numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS,
("import_module('numexpr')", )),
}
def _import(module, reload=False):
"""
Creates a global translation dictionary for module.
The argument module has to be one of the following strings: "math",
"mpmath", "numpy", "sympy", "tensorflow", "jax".
These dictionaries map names of Python functions to their equivalent in
other modules.
"""
try:
namespace, namespace_default, translations, import_commands = MODULES[
module]
except KeyError:
raise NameError(
"'%s' module cannot be used for lambdification" % module)
# Clear namespace or exit
if namespace != namespace_default:
# The namespace was already generated, don't do it again if not forced.
if reload:
namespace.clear()
namespace.update(namespace_default)
else:
return
for import_command in import_commands:
if import_command.startswith('import_module'):
module = eval(import_command)
if module is not None:
namespace.update(module.__dict__)
continue
else:
try:
exec(import_command, {}, namespace)
continue
except ImportError:
pass
raise ImportError(
"Cannot import '%s' with '%s' command" % (module, import_command))
# Add translated names to namespace
for sympyname, translation in translations.items():
namespace[sympyname] = namespace[translation]
# For computing the modulus of a SymPy expression we use the builtin abs
# function, instead of the previously used fabs function for all
# translation modules. This is because the fabs function in the math
# module does not accept complex valued arguments. (see issue 9474). The
# only exception, where we don't use the builtin abs function is the
# mpmath translation module, because mpmath.fabs returns mpf objects in
# contrast to abs().
if 'Abs' not in namespace:
namespace['Abs'] = abs
# Used for dynamically generated filenames that are inserted into the
# linecache.
_lambdify_generated_counter = 1
@doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,))
def lambdify(args, expr, modules=None, printer=None, use_imps=True,
dummify=False, cse=False):
"""Convert a SymPy expression into a function that allows for fast
numeric evaluation.
.. warning::
This function uses ``exec``, and thus should not be used on
unsanitized input.
.. deprecated:: 1.7
Passing a set for the *args* parameter is deprecated as sets are
unordered. Use an ordered iterable such as a list or tuple.
Explanation
===========
For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an
equivalent NumPy function that numerically evaluates it:
>>> from sympy import sin, cos, symbols, lambdify
>>> import numpy as np
>>> x = symbols('x')
>>> expr = sin(x) + cos(x)
>>> expr
sin(x) + cos(x)
>>> f = lambdify(x, expr, 'numpy')
>>> a = np.array([1, 2])
>>> f(a)
[1.38177329 0.49315059]
The primary purpose of this function is to provide a bridge from SymPy
expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath,
and tensorflow. In general, SymPy functions do not work with objects from
other libraries, such as NumPy arrays, and functions from numeric
libraries like NumPy or mpmath do not work on SymPy expressions.
``lambdify`` bridges the two by converting a SymPy expression to an
equivalent numeric function.
The basic workflow with ``lambdify`` is to first create a SymPy expression
representing whatever mathematical function you wish to evaluate. This
should be done using only SymPy functions and expressions. Then, use
``lambdify`` to convert this to an equivalent function for numerical
evaluation. For instance, above we created ``expr`` using the SymPy symbol
``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an
equivalent NumPy function ``f``, and called it on a NumPy array ``a``.
Parameters
==========
args : List[Symbol]
A variable or a list of variables whose nesting represents the
nesting of the arguments that will be passed to the function.
Variables can be symbols, undefined functions, or matrix symbols.
>>> from sympy import Eq
>>> from sympy.abc import x, y, z
The list of variables should match the structure of how the
arguments will be passed to the function. Simply enclose the
parameters as they will be passed in a list.
To call a function like ``f(x)`` then ``[x]``
should be the first argument to ``lambdify``; for this
case a single ``x`` can also be used:
>>> f = lambdify(x, x + 1)
>>> f(1)
2
>>> f = lambdify([x], x + 1)
>>> f(1)
2
To call a function like ``f(x, y)`` then ``[x, y]`` will
be the first argument of the ``lambdify``:
>>> f = lambdify([x, y], x + y)
>>> f(1, 1)
2
To call a function with a single 3-element tuple like
``f((x, y, z))`` then ``[(x, y, z)]`` will be the first
argument of the ``lambdify``:
>>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2))
>>> f((3, 4, 5))
True
If two args will be passed and the first is a scalar but
the second is a tuple with two arguments then the items
in the list should match that structure:
>>> f = lambdify([x, (y, z)], x + y + z)
>>> f(1, (2, 3))
6
expr : Expr
An expression, list of expressions, or matrix to be evaluated.
Lists may be nested.
If the expression is a list, the output will also be a list.
>>> f = lambdify(x, [x, [x + 1, x + 2]])
>>> f(1)
[1, [2, 3]]
If it is a matrix, an array will be returned (for the NumPy module).
>>> from sympy import Matrix
>>> f = lambdify(x, Matrix([x, x + 1]))
>>> f(1)
[[1]
[2]]
Note that the argument order here (variables then expression) is used
to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works
(roughly) like ``lambda x: expr``
(see :ref:`lambdify-how-it-works` below).
modules : str, optional
Specifies the numeric library to use.
If not specified, *modules* defaults to:
- ``["scipy", "numpy"]`` if SciPy is installed
- ``["numpy"]`` if only NumPy is installed
- ``["math", "mpmath", "sympy"]`` if neither is installed.
That is, SymPy functions are replaced as far as possible by
either ``scipy`` or ``numpy`` functions if available, and Python's
standard library ``math``, or ``mpmath`` functions otherwise.
*modules* can be one of the following types:
- The strings ``"math"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``,
``"scipy"``, ``"sympy"``, or ``"tensorflow"`` or ``"jax"``. This uses the
corresponding printer and namespace mapping for that module.
- A module (e.g., ``math``). This uses the global namespace of the
module. If the module is one of the above known modules, it will
also use the corresponding printer and namespace mapping
(i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``).
- A dictionary that maps names of SymPy functions to arbitrary
functions
(e.g., ``{'sin': custom_sin}``).
- A list that contains a mix of the arguments above, with higher
priority given to entries appearing first
(e.g., to use the NumPy module but override the ``sin`` function
with a custom version, you can use
``[{'sin': custom_sin}, 'numpy']``).
dummify : bool, optional
Whether or not the variables in the provided expression that are not
valid Python identifiers are substituted with dummy symbols.
This allows for undefined functions like ``Function('f')(t)`` to be
supplied as arguments. By default, the variables are only dummified
if they are not valid Python identifiers.
Set ``dummify=True`` to replace all arguments with dummy symbols
(if ``args`` is not a string) - for example, to ensure that the
arguments do not redefine any built-in names.
cse : bool, or callable, optional
Large expressions can be computed more efficiently when
common subexpressions are identified and precomputed before
being used multiple time. Finding the subexpressions will make
creation of the 'lambdify' function slower, however.
When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default)
the user may pass a function matching the ``cse`` signature.
Examples
========
>>> from sympy.utilities.lambdify import implemented_function
>>> from sympy import sqrt, sin, Matrix
>>> from sympy import Function
>>> from sympy.abc import w, x, y, z
>>> f = lambdify(x, x**2)
>>> f(2)
4
>>> f = lambdify((x, y, z), [z, y, x])
>>> f(1,2,3)
[3, 2, 1]
>>> f = lambdify(x, sqrt(x))
>>> f(4)
2.0
>>> f = lambdify((x, y), sin(x*y)**2)
>>> f(0, 5)
0.0
>>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
>>> row(1, 2)
Matrix([[1, 3]])
``lambdify`` can be used to translate SymPy expressions into mpmath
functions. This may be preferable to using ``evalf`` (which uses mpmath on
the backend) in some cases.
>>> f = lambdify(x, sin(x), 'mpmath')
>>> f(1)
0.8414709848078965
Tuple arguments are handled and the lambdified function should
be called with the same type of arguments as were used to create
the function:
>>> f = lambdify((x, (y, z)), x + y)
>>> f(1, (2, 4))
3
The ``flatten`` function can be used to always work with flattened
arguments:
>>> from sympy.utilities.iterables import flatten
>>> args = w, (x, (y, z))
>>> vals = 1, (2, (3, 4))
>>> f = lambdify(flatten(args), w + x + y + z)
>>> f(*flatten(vals))
10
Functions present in ``expr`` can also carry their own numerical
implementations, in a callable attached to the ``_imp_`` attribute. This
can be used with undefined functions using the ``implemented_function``
factory:
>>> f = implemented_function(Function('f'), lambda x: x+1)
>>> func = lambdify(x, f(x))
>>> func(4)
5
``lambdify`` always prefers ``_imp_`` implementations to implementations
in other namespaces, unless the ``use_imps`` input parameter is False.
Usage with Tensorflow:
>>> import tensorflow as tf
>>> from sympy import Max, sin, lambdify
>>> from sympy.abc import x
>>> f = Max(x, sin(x))
>>> func = lambdify(x, f, 'tensorflow')
After tensorflow v2, eager execution is enabled by default.
If you want to get the compatible result across tensorflow v1 and v2
as same as this tutorial, run this line.
>>> tf.compat.v1.enable_eager_execution()
If you have eager execution enabled, you can get the result out
immediately as you can use numpy.
If you pass tensorflow objects, you may get an ``EagerTensor``
object instead of value.
>>> result = func(tf.constant(1.0))
>>> print(result)
tf.Tensor(1.0, shape=(), dtype=float32)
>>> print(result.__class__)
<class 'tensorflow.python.framework.ops.EagerTensor'>
You can use ``.numpy()`` to get the numpy value of the tensor.
>>> result.numpy()
1.0
>>> var = tf.Variable(2.0)
>>> result = func(var) # also works for tf.Variable and tf.Placeholder
>>> result.numpy()
2.0
And it works with any shape array.
>>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
>>> result = func(tensor)
>>> result.numpy()
[[1. 2.]
[3. 4.]]
Notes
=====
- For functions involving large array calculations, numexpr can provide a
significant speedup over numpy. Please note that the available functions
for numexpr are more limited than numpy but can be expanded with
``implemented_function`` and user defined subclasses of Function. If
specified, numexpr may be the only option in modules. The official list
of numexpr functions can be found at:
https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions
- In the above examples, the generated functions can accept scalar
values or numpy arrays as arguments. However, in some cases
the generated function relies on the input being a numpy array:
>>> import numpy
>>> from sympy import Piecewise
>>> from sympy.testing.pytest import ignore_warnings
>>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy")
>>> with ignore_warnings(RuntimeWarning):
... f(numpy.array([-1, 0, 1, 2]))
[-1. 0. 1. 0.5]
>>> f(0)
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
In such cases, the input should be wrapped in a numpy array:
>>> with ignore_warnings(RuntimeWarning):
... float(f(numpy.array([0])))
0.0
Or if numpy functionality is not required another module can be used:
>>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math")
>>> f(0)
0
.. _lambdify-how-it-works:
How it works
============
When using this function, it helps a great deal to have an idea of what it
is doing. At its core, lambdify is nothing more than a namespace
translation, on top of a special printer that makes some corner cases work
properly.
To understand lambdify, first we must properly understand how Python
namespaces work. Say we had two files. One called ``sin_cos_sympy.py``,
with
.. code:: python
# sin_cos_sympy.py
from sympy.functions.elementary.trigonometric import (cos, sin)
def sin_cos(x):
return sin(x) + cos(x)
and one called ``sin_cos_numpy.py`` with
.. code:: python
# sin_cos_numpy.py
from numpy import sin, cos
def sin_cos(x):
return sin(x) + cos(x)
The two files define an identical function ``sin_cos``. However, in the
first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and
``cos``. In the second, they are defined as the NumPy versions.
If we were to import the first file and use the ``sin_cos`` function, we
would get something like
>>> from sin_cos_sympy import sin_cos # doctest: +SKIP
>>> sin_cos(1) # doctest: +SKIP
cos(1) + sin(1)
On the other hand, if we imported ``sin_cos`` from the second file, we
would get
>>> from sin_cos_numpy import sin_cos # doctest: +SKIP
>>> sin_cos(1) # doctest: +SKIP
1.38177329068
In the first case we got a symbolic output, because it used the symbolic
``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric
result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions
from NumPy. But notice that the versions of ``sin`` and ``cos`` that were
used was not inherent to the ``sin_cos`` function definition. Both
``sin_cos`` definitions are exactly the same. Rather, it was based on the
names defined at the module where the ``sin_cos`` function was defined.
The key point here is that when function in Python references a name that
is not defined in the function, that name is looked up in the "global"
namespace of the module where that function is defined.
Now, in Python, we can emulate this behavior without actually writing a
file to disk using the ``exec`` function. ``exec`` takes a string
containing a block of Python code, and a dictionary that should contain
the global variables of the module. It then executes the code "in" that
dictionary, as if it were the module globals. The following is equivalent
to the ``sin_cos`` defined in ``sin_cos_sympy.py``:
>>> import sympy
>>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos}
>>> exec('''
... def sin_cos(x):
... return sin(x) + cos(x)
... ''', module_dictionary)
>>> sin_cos = module_dictionary['sin_cos']
>>> sin_cos(1)
cos(1) + sin(1)
and similarly with ``sin_cos_numpy``:
>>> import numpy
>>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos}
>>> exec('''
... def sin_cos(x):
... return sin(x) + cos(x)
... ''', module_dictionary)
>>> sin_cos = module_dictionary['sin_cos']
>>> sin_cos(1)
1.38177329068
So now we can get an idea of how ``lambdify`` works. The name "lambdify"
comes from the fact that we can think of something like ``lambdify(x,
sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where
``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why
the symbols argument is first in ``lambdify``, as opposed to most SymPy
functions where it comes after the expression: to better mimic the
``lambda`` keyword.
``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and
1. Converts it to a string
2. Creates a module globals dictionary based on the modules that are
passed in (by default, it uses the NumPy module)
3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the
list of variables separated by commas, and ``{expr}`` is the string
created in step 1., then ``exec``s that string with the module globals
namespace and returns ``func``.
In fact, functions returned by ``lambdify`` support inspection. So you can
see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you
are using IPython or the Jupyter notebook.
>>> f = lambdify(x, sin(x) + cos(x))
>>> import inspect
>>> print(inspect.getsource(f))
def _lambdifygenerated(x):
return sin(x) + cos(x)
This shows us the source code of the function, but not the namespace it
was defined in. We can inspect that by looking at the ``__globals__``
attribute of ``f``:
>>> f.__globals__['sin']
<ufunc 'sin'>
>>> f.__globals__['cos']
<ufunc 'cos'>
>>> f.__globals__['sin'] is numpy.sin
True
This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be
``numpy.sin`` and ``numpy.cos``.
Note that there are some convenience layers in each of these steps, but at
the core, this is how ``lambdify`` works. Step 1 is done using the
``LambdaPrinter`` printers defined in the printing module (see
:mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions
to define how they should be converted to a string for different modules.
You can change which printer ``lambdify`` uses by passing a custom printer
in to the ``printer`` argument.
Step 2 is augmented by certain translations. There are default
translations for each module, but you can provide your own by passing a
list to the ``modules`` argument. For instance,
>>> def mysin(x):
... print('taking the sin of', x)
... return numpy.sin(x)
...
>>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy'])
>>> f(1)
taking the sin of 1
0.8414709848078965
The globals dictionary is generated from the list by merging the
dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The
merging is done so that earlier items take precedence, which is why
``mysin`` is used above instead of ``numpy.sin``.
If you want to modify the way ``lambdify`` works for a given function, it
is usually easiest to do so by modifying the globals dictionary as such.
In more complicated cases, it may be necessary to create and pass in a
custom printer.
Finally, step 3 is augmented with certain convenience operations, such as
the addition of a docstring.
Understanding how ``lambdify`` works can make it easier to avoid certain
gotchas when using it. For instance, a common mistake is to create a
lambdified function for one module (say, NumPy), and pass it objects from
another (say, a SymPy expression).
For instance, say we create
>>> from sympy.abc import x
>>> f = lambdify(x, x + 1, 'numpy')
Now if we pass in a NumPy array, we get that array plus 1
>>> import numpy
>>> a = numpy.array([1, 2])
>>> f(a)
[2 3]
But what happens if you make the mistake of passing in a SymPy expression
instead of a NumPy array:
>>> f(x + 1)
x + 2
This worked, but it was only by accident. Now take a different lambdified
function:
>>> from sympy import sin
>>> g = lambdify(x, x + sin(x), 'numpy')
This works as expected on NumPy arrays:
>>> g(a)
[1.84147098 2.90929743]
But if we try to pass in a SymPy expression, it fails
>>> try:
... g(x + 1)
... # NumPy release after 1.17 raises TypeError instead of
... # AttributeError
... except (AttributeError, TypeError):
... raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
AttributeError:
Now, let's look at what happened. The reason this fails is that ``g``
calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not
know how to operate on a SymPy object. **As a general rule, NumPy
functions do not know how to operate on SymPy expressions, and SymPy
functions do not know how to operate on NumPy arrays. This is why lambdify
exists: to provide a bridge between SymPy and NumPy.**
However, why is it that ``f`` did work? That's because ``f`` does not call
any functions, it only adds 1. So the resulting function that is created,
``def _lambdifygenerated(x): return x + 1`` does not depend on the globals
namespace it is defined in. Thus it works, but only by accident. A future
version of ``lambdify`` may remove this behavior.
Be aware that certain implementation details described here may change in
future versions of SymPy. The API of passing in custom modules and
printers will not change, but the details of how a lambda function is
created may change. However, the basic idea will remain the same, and
understanding it will be helpful to understanding the behavior of
lambdify.
**In general: you should create lambdified functions for one module (say,
NumPy), and only pass it input types that are compatible with that module
(say, NumPy arrays).** Remember that by default, if the ``module``
argument is not provided, ``lambdify`` creates functions using the NumPy
and SciPy namespaces.
"""
from sympy.core.symbol import Symbol
from sympy.core.expr import Expr
# If the user hasn't specified any modules, use what is available.
if modules is None:
try:
_import("scipy")
except ImportError:
try:
_import("numpy")
except ImportError:
# Use either numpy (if available) or python.math where possible.
# XXX: This leads to different behaviour on different systems and
# might be the reason for irreproducible errors.
modules = ["math", "mpmath", "sympy"]
else:
modules = ["numpy"]
else:
modules = ["numpy", "scipy"]
# Get the needed namespaces.
namespaces = []
# First find any function implementations
if use_imps:
namespaces.append(_imp_namespace(expr))
# Check for dict before iterating
if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'):
namespaces.append(modules)
else:
# consistency check
if _module_present('numexpr', modules) and len(modules) > 1:
raise TypeError("numexpr must be the only item in 'modules'")
namespaces += list(modules)
# fill namespace with first having highest priority
namespace = {} # type: tDict[str, Any]
for m in namespaces[::-1]:
buf = _get_namespace(m)
namespace.update(buf)
if hasattr(expr, "atoms"):
#Try if you can extract symbols from the expression.
#Move on if expr.atoms in not implemented.
syms = expr.atoms(Symbol)
for term in syms:
namespace.update({str(term): term})
if printer is None:
if _module_present('mpmath', namespaces):
from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore
elif _module_present('scipy', namespaces):
from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore
elif _module_present('numpy', namespaces):
from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore
elif _module_present('cupy', namespaces):
from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore
elif _module_present('jax', namespaces):
from sympy.printing.numpy import JaxPrinter as Printer # type: ignore
elif _module_present('numexpr', namespaces):
from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore
elif _module_present('tensorflow', namespaces):
from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore
elif _module_present('sympy', namespaces):
from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore
else:
from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore
user_functions = {}
for m in namespaces[::-1]:
if isinstance(m, dict):
for k in m:
user_functions[k] = k
printer = Printer({'fully_qualified_modules': False, 'inline': True,
'allow_unknown_functions': True,
'user_functions': user_functions})
if isinstance(args, set):
sympy_deprecation_warning(
"""
Passing the function arguments to lambdify() as a set is deprecated. This
leads to unpredictable results since sets are unordered. Instead, use a list
or tuple for the function arguments.
""",
deprecated_since_version="1.6.3",
active_deprecations_target="deprecated-lambdify-arguments-set",
)
# Get the names of the args, for creating a docstring
iterable_args = (args,) if isinstance(args, Expr) else args
names = []
# Grab the callers frame, for getting the names by inspection (if needed)
callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore
for n, var in enumerate(iterable_args):
if hasattr(var, 'name'):
names.append(var.name)
else:
# It's an iterable. Try to get name by inspection of calling frame.
name_list = [var_name for var_name, var_val in callers_local_vars
if var_val is var]
if len(name_list) == 1:
names.append(name_list[0])
else:
# Cannot infer name with certainty. arg_# will have to do.
names.append('arg_' + str(n))
# Create the function definition code and execute it
funcname = '_lambdifygenerated'
if _module_present('tensorflow', namespaces):
funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter
else:
funcprinter = _EvaluatorPrinter(printer, dummify)
if cse == True:
from sympy.simplify.cse_main import cse as _cse
cses, _expr = _cse(expr, list=False)
elif callable(cse):
cses, _expr = cse(expr)
else:
cses, _expr = (), expr
funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses)
# Collect the module imports from the code printers.
imp_mod_lines = []
for mod, keys in (getattr(printer, 'module_imports', None) or {}).items():
for k in keys:
if k not in namespace:
ln = "from %s import %s" % (mod, k)
try:
exec(ln, {}, namespace)
except ImportError:
# Tensorflow 2.0 has issues with importing a specific
# function from its submodule.
# https://github.com/tensorflow/tensorflow/issues/33022
ln = "%s = %s.%s" % (k, mod, k)
exec(ln, {}, namespace)
imp_mod_lines.append(ln)
# Provide lambda expression with builtins, and compatible implementation of range
namespace.update({'builtins':builtins, 'range':range})
funclocals = {} # type: tDict[str, Any]
global _lambdify_generated_counter
filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter
_lambdify_generated_counter += 1
c = compile(funcstr, filename, 'exec')
exec(c, namespace, funclocals)
# mtime has to be None or else linecache.checkcache will remove it
linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore
func = funclocals[funcname]
# Apply the docstring
sig = "func({})".format(", ".join(str(i) for i in names))
sig = textwrap.fill(sig, subsequent_indent=' '*8)
expr_str = str(expr)
if len(expr_str) > 78:
expr_str = textwrap.wrap(expr_str, 75)[0] + '...'
func.__doc__ = (
"Created with lambdify. Signature:\n\n"
"{sig}\n\n"
"Expression:\n\n"
"{expr}\n\n"
"Source code:\n\n"
"{src}\n\n"
"Imported modules:\n\n"
"{imp_mods}"
).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\n'.join(imp_mod_lines))
return func
def _module_present(modname, modlist):
if modname in modlist:
return True
for m in modlist:
if hasattr(m, '__name__') and m.__name__ == modname:
return True
return False
def _get_namespace(m):
"""
This is used by _lambdify to parse its arguments.
"""
if isinstance(m, str):
_import(m)
return MODULES[m][0]
elif isinstance(m, dict):
return m
elif hasattr(m, "__dict__"):
return m.__dict__
else:
raise TypeError("Argument must be either a string, dict or module but it is: %s" % m)
def _recursive_to_string(doprint, arg):
"""Functions in lambdify accept both SymPy types and non-SymPy types such as python
lists and tuples. This method ensures that we only call the doprint method of the
printer with SymPy types (so that the printer safely can use SymPy-methods)."""
from sympy.matrices.common import MatrixOperations
from sympy.core.basic import Basic
if isinstance(arg, (Basic, MatrixOperations)):
return doprint(arg)
elif iterable(arg):
if isinstance(arg, list):
left, right = "[", "]"
elif isinstance(arg, tuple):
left, right = "(", ",)"
else:
raise NotImplementedError("unhandled type: %s, %s" % (type(arg), arg))
return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right
elif isinstance(arg, str):
return arg
else:
return doprint(arg)
def lambdastr(args, expr, printer=None, dummify=None):
"""
Returns a string that can be evaluated to a lambda function.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
Although tuples may not appear as arguments to lambda in Python 3,
lambdastr will create a lambda function that will unpack the original
arguments so that nested arguments can be handled:
>>> lambdastr((x, (y, z)), x + y)
'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])'
"""
# Transforming everything to strings.
from sympy.matrices import DeferredVector
from sympy.core.basic import Basic
from sympy.core.function import (Derivative, Function)
from sympy.core.symbol import (Dummy, Symbol)
from sympy.core.sympify import sympify
if printer is not None:
if inspect.isfunction(printer):
lambdarepr = printer
else:
if inspect.isclass(printer):
lambdarepr = lambda expr: printer().doprint(expr)
else:
lambdarepr = lambda expr: printer.doprint(expr)
else:
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
def sub_args(args, dummies_dict):
if isinstance(args, str):
return args
elif isinstance(args, DeferredVector):
return str(args)
elif iterable(args):
dummies = flatten([sub_args(a, dummies_dict) for a in args])
return ",".join(str(a) for a in dummies)
else:
# replace these with Dummy symbols
if isinstance(args, (Function, Symbol, Derivative)):
dummies = Dummy()
dummies_dict.update({args : dummies})
return str(dummies)
else:
return str(args)
def sub_expr(expr, dummies_dict):
expr = sympify(expr)
# dict/tuple are sympified to Basic
if isinstance(expr, Basic):
expr = expr.xreplace(dummies_dict)
# list is not sympified to Basic
elif isinstance(expr, list):
expr = [sub_expr(a, dummies_dict) for a in expr]
return expr
# Transform args
def isiter(l):
return iterable(l, exclude=(str, DeferredVector, NotIterable))
def flat_indexes(iterable):
n = 0
for el in iterable:
if isiter(el):
for ndeep in flat_indexes(el):
yield (n,) + ndeep
else:
yield (n,)
n += 1
if dummify is None:
dummify = any(isinstance(a, Basic) and
a.atoms(Function, Derivative) for a in (
args if isiter(args) else [args]))
if isiter(args) and any(isiter(i) for i in args):
dum_args = [str(Dummy(str(i))) for i in range(len(args))]
indexed_args = ','.join([
dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]])
for ind in flat_indexes(args)])
lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)
return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args)
dummies_dict = {}
if dummify:
args = sub_args(args, dummies_dict)
else:
if isinstance(args, str):
pass
elif iterable(args, exclude=DeferredVector):
args = ",".join(str(a) for a in args)
# Transform expr
if dummify:
if isinstance(expr, str):
pass
else:
expr = sub_expr(expr, dummies_dict)
expr = _recursive_to_string(lambdarepr, expr)
return "lambda %s: (%s)" % (args, expr)
class _EvaluatorPrinter:
def __init__(self, printer=None, dummify=False):
self._dummify = dummify
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import LambdaPrinter
if printer is None:
printer = LambdaPrinter()
if inspect.isfunction(printer):
self._exprrepr = printer
else:
if inspect.isclass(printer):
printer = printer()
self._exprrepr = printer.doprint
#if hasattr(printer, '_print_Symbol'):
# symbolrepr = printer._print_Symbol
#if hasattr(printer, '_print_Dummy'):
# dummyrepr = printer._print_Dummy
# Used to print the generated function arguments in a standard way
self._argrepr = LambdaPrinter().doprint
def doprint(self, funcname, args, expr, *, cses=()):
"""
Returns the function definition code as a string.
"""
from sympy.core.symbol import Dummy
funcbody = []
if not iterable(args):
args = [args]
if cses:
subvars, subexprs = zip(*cses)
exprs = [expr] + list(subexprs)
argstrs, exprs = self._preprocess(args, exprs)
expr, subexprs = exprs[0], exprs[1:]
cses = zip(subvars, subexprs)
else:
argstrs, expr = self._preprocess(args, expr)
# Generate argument unpacking and final argument list
funcargs = []
unpackings = []
for argstr in argstrs:
if iterable(argstr):
funcargs.append(self._argrepr(Dummy()))
unpackings.extend(self._print_unpacking(argstr, funcargs[-1]))
else:
funcargs.append(argstr)
funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs))
# Wrap input arguments before unpacking
funcbody.extend(self._print_funcargwrapping(funcargs))
funcbody.extend(unpackings)
for s, e in cses:
if e is None:
funcbody.append('del {}'.format(s))
else:
funcbody.append('{} = {}'.format(s, self._exprrepr(e)))
str_expr = _recursive_to_string(self._exprrepr, expr)
if '\n' in str_expr:
str_expr = '({})'.format(str_expr)
funcbody.append('return {}'.format(str_expr))
funclines = [funcsig]
funclines.extend([' ' + line for line in funcbody])
return '\n'.join(funclines) + '\n'
@classmethod
def _is_safe_ident(cls, ident):
return isinstance(ident, str) and ident.isidentifier() \
and not keyword.iskeyword(ident)
def _preprocess(self, args, expr):
"""Preprocess args, expr to replace arguments that do not map
to valid Python identifiers.
Returns string form of args, and updated expr.
"""
from sympy.core.basic import Basic
from sympy.core.sorting import ordered
from sympy.core.function import (Derivative, Function)
from sympy.core.symbol import Dummy, uniquely_named_symbol
from sympy.matrices import DeferredVector
from sympy.core.expr import Expr
# Args of type Dummy can cause name collisions with args
# of type Symbol. Force dummify of everything in this
# situation.
dummify = self._dummify or any(
isinstance(arg, Dummy) for arg in flatten(args))
argstrs = [None]*len(args)
for arg, i in reversed(list(ordered(zip(args, range(len(args)))))):
if iterable(arg):
s, expr = self._preprocess(arg, expr)
elif isinstance(arg, DeferredVector):
s = str(arg)
elif isinstance(arg, Basic) and arg.is_symbol:
s = self._argrepr(arg)
if dummify or not self._is_safe_ident(s):
dummy = Dummy()
if isinstance(expr, Expr):
dummy = uniquely_named_symbol(
dummy.name, expr, modify=lambda s: '_' + s)
s = self._argrepr(dummy)
expr = self._subexpr(expr, {arg: dummy})
elif dummify or isinstance(arg, (Function, Derivative)):
dummy = Dummy()
s = self._argrepr(dummy)
expr = self._subexpr(expr, {arg: dummy})
else:
s = str(arg)
argstrs[i] = s
return argstrs, expr
def _subexpr(self, expr, dummies_dict):
from sympy.matrices import DeferredVector
from sympy.core.sympify import sympify
expr = sympify(expr)
xreplace = getattr(expr, 'xreplace', None)
if xreplace is not None:
expr = xreplace(dummies_dict)
else:
if isinstance(expr, DeferredVector):
pass
elif isinstance(expr, dict):
k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()]
v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()]
expr = dict(zip(k, v))
elif isinstance(expr, tuple):
expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr)
elif isinstance(expr, list):
expr = [self._subexpr(sympify(a), dummies_dict) for a in expr]
return expr
def _print_funcargwrapping(self, args):
"""Generate argument wrapping code.
args is the argument list of the generated function (strings).
Return value is a list of lines of code that will be inserted at
the beginning of the function definition.
"""
return []
def _print_unpacking(self, unpackto, arg):
"""Generate argument unpacking code.
arg is the function argument to be unpacked (a string), and
unpackto is a list or nested lists of the variable names (strings) to
unpack to.
"""
def unpack_lhs(lvalues):
return '[{}]'.format(', '.join(
unpack_lhs(val) if iterable(val) else val for val in lvalues))
return ['{} = {}'.format(unpack_lhs(unpackto), arg)]
class _TensorflowEvaluatorPrinter(_EvaluatorPrinter):
def _print_unpacking(self, lvalues, rvalue):
"""Generate argument unpacking code.
This method is used when the input value is not interable,
but can be indexed (see issue #14655).
"""
def flat_indexes(elems):
n = 0
for el in elems:
if iterable(el):
for ndeep in flat_indexes(el):
yield (n,) + ndeep
else:
yield (n,)
n += 1
indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind)))
for ind in flat_indexes(lvalues))
return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)]
def _imp_namespace(expr, namespace=None):
""" Return namespace dict with function implementations
We need to search for functions in anything that can be thrown at
us - that is - anything that could be passed as ``expr``. Examples
include SymPy expressions, as well as tuples, lists and dicts that may
contain SymPy expressions.
Parameters
----------
expr : object
Something passed to lambdify, that will generate valid code from
``str(expr)``.
namespace : None or mapping
Namespace to fill. None results in new empty dict
Returns
-------
namespace : dict
dict with keys of implemented function names within ``expr`` and
corresponding values being the numerical implementation of
function
Examples
========
>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import implemented_function, _imp_namespace
>>> from sympy import Function
>>> f = implemented_function(Function('f'), lambda x: x+1)
>>> g = implemented_function(Function('g'), lambda x: x*10)
>>> namespace = _imp_namespace(f(g(x)))
>>> sorted(namespace.keys())
['f', 'g']
"""
# Delayed import to avoid circular imports
from sympy.core.function import FunctionClass
if namespace is None:
namespace = {}
# tuples, lists, dicts are valid expressions
if is_sequence(expr):
for arg in expr:
_imp_namespace(arg, namespace)
return namespace
elif isinstance(expr, dict):
for key, val in expr.items():
# functions can be in dictionary keys
_imp_namespace(key, namespace)
_imp_namespace(val, namespace)
return namespace
# SymPy expressions may be Functions themselves
func = getattr(expr, 'func', None)
if isinstance(func, FunctionClass):
imp = getattr(func, '_imp_', None)
if imp is not None:
name = expr.func.__name__
if name in namespace and namespace[name] != imp:
raise ValueError('We found more than one '
'implementation with name '
'"%s"' % name)
namespace[name] = imp
# and / or they may take Functions as arguments
if hasattr(expr, 'args'):
for arg in expr.args:
_imp_namespace(arg, namespace)
return namespace
def implemented_function(symfunc, implementation):
""" Add numerical ``implementation`` to function ``symfunc``.
``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.
In the latter case we create an ``UndefinedFunction`` instance with that
name.
Be aware that this is a quick workaround, not a general method to create
special symbolic functions. If you want to create a symbolic function to be
used by all the machinery of SymPy you should subclass the ``Function``
class.
Parameters
----------
symfunc : ``str`` or ``UndefinedFunction`` instance
If ``str``, then create new ``UndefinedFunction`` with this as
name. If ``symfunc`` is an Undefined function, create a new function
with the same name and the implemented function attached.
implementation : callable
numerical implementation to be called by ``evalf()`` or ``lambdify``
Returns
-------
afunc : sympy.FunctionClass instance
function with attached implementation
Examples
========
>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import implemented_function
>>> from sympy import lambdify
>>> f = implemented_function('f', lambda x: x+1)
>>> lam_f = lambdify(x, f(x))
>>> lam_f(4)
5
"""
# Delayed import to avoid circular imports
from sympy.core.function import UndefinedFunction
# if name, create function to hold implementation
kwargs = {}
if isinstance(symfunc, UndefinedFunction):
kwargs = symfunc._kwargs
symfunc = symfunc.__name__
if isinstance(symfunc, str):
# Keyword arguments to UndefinedFunction are added as attributes to
# the created class.
symfunc = UndefinedFunction(
symfunc, _imp_=staticmethod(implementation), **kwargs)
elif not isinstance(symfunc, UndefinedFunction):
raise ValueError(filldedent('''
symfunc should be either a string or
an UndefinedFunction instance.'''))
return symfunc
|
72fadbb48c1dcc6b2bd0b183ca1e02586e685c25c184b9d4c3f3c00ccf4eb582 | """Useful utility decorators. """
import sys
import types
import inspect
from functools import wraps, update_wrapper
from sympy.utilities.exceptions import sympy_deprecation_warning
def threaded_factory(func, use_add):
"""A factory for ``threaded`` decorators. """
from sympy.core import sympify
from sympy.matrices import MatrixBase
from sympy.utilities.iterables import iterable
@wraps(func)
def threaded_func(expr, *args, **kwargs):
if isinstance(expr, MatrixBase):
return expr.applyfunc(lambda f: func(f, *args, **kwargs))
elif iterable(expr):
try:
return expr.__class__([func(f, *args, **kwargs) for f in expr])
except TypeError:
return expr
else:
expr = sympify(expr)
if use_add and expr.is_Add:
return expr.__class__(*[ func(f, *args, **kwargs) for f in expr.args ])
elif expr.is_Relational:
return expr.__class__(func(expr.lhs, *args, **kwargs),
func(expr.rhs, *args, **kwargs))
else:
return func(expr, *args, **kwargs)
return threaded_func
def threaded(func):
"""Apply ``func`` to sub--elements of an object, including :class:`~.Add`.
This decorator is intended to make it uniformly possible to apply a
function to all elements of composite objects, e.g. matrices, lists, tuples
and other iterable containers, or just expressions.
This version of :func:`threaded` decorator allows threading over
elements of :class:`~.Add` class. If this behavior is not desirable
use :func:`xthreaded` decorator.
Functions using this decorator must have the following signature::
@threaded
def function(expr, *args, **kwargs):
"""
return threaded_factory(func, True)
def xthreaded(func):
"""Apply ``func`` to sub--elements of an object, excluding :class:`~.Add`.
This decorator is intended to make it uniformly possible to apply a
function to all elements of composite objects, e.g. matrices, lists, tuples
and other iterable containers, or just expressions.
This version of :func:`threaded` decorator disallows threading over
elements of :class:`~.Add` class. If this behavior is not desirable
use :func:`threaded` decorator.
Functions using this decorator must have the following signature::
@xthreaded
def function(expr, *args, **kwargs):
"""
return threaded_factory(func, False)
def conserve_mpmath_dps(func):
"""After the function finishes, resets the value of mpmath.mp.dps to
the value it had before the function was run."""
import mpmath
def func_wrapper(*args, **kwargs):
dps = mpmath.mp.dps
try:
return func(*args, **kwargs)
finally:
mpmath.mp.dps = dps
func_wrapper = update_wrapper(func_wrapper, func)
return func_wrapper
class no_attrs_in_subclass:
"""Don't 'inherit' certain attributes from a base class
>>> from sympy.utilities.decorator import no_attrs_in_subclass
>>> class A(object):
... x = 'test'
>>> A.x = no_attrs_in_subclass(A, A.x)
>>> class B(A):
... pass
>>> hasattr(A, 'x')
True
>>> hasattr(B, 'x')
False
"""
def __init__(self, cls, f):
self.cls = cls
self.f = f
def __get__(self, instance, owner=None):
if owner == self.cls:
if hasattr(self.f, '__get__'):
return self.f.__get__(instance, owner)
return self.f
raise AttributeError
def doctest_depends_on(exe=None, modules=None, disable_viewers=None, python_version=None):
"""
Adds metadata about the dependencies which need to be met for doctesting
the docstrings of the decorated objects.
exe should be a list of executables
modules should be a list of modules
disable_viewers should be a list of viewers for preview() to disable
python_version should be the minimum Python version required, as a tuple
(like (3, 0))
"""
dependencies = {}
if exe is not None:
dependencies['executables'] = exe
if modules is not None:
dependencies['modules'] = modules
if disable_viewers is not None:
dependencies['disable_viewers'] = disable_viewers
if python_version is not None:
dependencies['python_version'] = python_version
def skiptests():
from sympy.testing.runtests import DependencyError, SymPyDocTests, PyTestReporter # lazy import
r = PyTestReporter()
t = SymPyDocTests(r, None)
try:
t._check_dependencies(**dependencies)
except DependencyError:
return True # Skip doctests
else:
return False # Run doctests
def depends_on_deco(fn):
fn._doctest_depends_on = dependencies
fn.__doctest_skip__ = skiptests
if inspect.isclass(fn):
fn._doctest_depdends_on = no_attrs_in_subclass(
fn, fn._doctest_depends_on)
fn.__doctest_skip__ = no_attrs_in_subclass(
fn, fn.__doctest_skip__)
return fn
return depends_on_deco
def public(obj):
"""
Append ``obj``'s name to global ``__all__`` variable (call site).
By using this decorator on functions or classes you achieve the same goal
as by filling ``__all__`` variables manually, you just do not have to repeat
yourself (object's name). You also know if object is public at definition
site, not at some random location (where ``__all__`` was set).
Note that in multiple decorator setup (in almost all cases) ``@public``
decorator must be applied before any other decorators, because it relies
on the pointer to object's global namespace. If you apply other decorators
first, ``@public`` may end up modifying the wrong namespace.
Examples
========
>>> from sympy.utilities.decorator import public
>>> __all__ # noqa: F821
Traceback (most recent call last):
...
NameError: name '__all__' is not defined
>>> @public
... def some_function():
... pass
>>> __all__ # noqa: F821
['some_function']
"""
if isinstance(obj, types.FunctionType):
ns = obj.__globals__
name = obj.__name__
elif isinstance(obj, (type(type), type)):
ns = sys.modules[obj.__module__].__dict__
name = obj.__name__
else:
raise TypeError("expected a function or a class, got %s" % obj)
if "__all__" not in ns:
ns["__all__"] = [name]
else:
ns["__all__"].append(name)
return obj
def memoize_property(propfunc):
"""Property decorator that caches the value of potentially expensive
`propfunc` after the first evaluation. The cached value is stored in
the corresponding property name with an attached underscore."""
attrname = '_' + propfunc.__name__
sentinel = object()
@wraps(propfunc)
def accessor(self):
val = getattr(self, attrname, sentinel)
if val is sentinel:
val = propfunc(self)
setattr(self, attrname, val)
return val
return property(accessor)
def deprecated(message, *, deprecated_since_version,
active_deprecations_target, stacklevel=3):
'''
Mark a function as deprecated.
This decorator should be used if an entire function or class is
deprecated. If only a certain functionality is deprecated, you should use
:func:`~.warns_deprecated_sympy` directly. This decorator is just a
convenience. There is no functional difference between using this
decorator and calling ``warns_deprecated_sympy()`` at the top of the
function.
The decorator takes the same arguments as
:func:`~.warns_deprecated_sympy`. See its
documentation for details on what the keywords to this decorator do.
See the :ref:`deprecation-policy` document for details on when and how
things should be deprecated in SymPy.
Examples
========
>>> from sympy.utilities.decorator import deprecated
>>> from sympy import simplify
>>> @deprecated("""\
... The simplify_this(expr) function is deprecated. Use simplify(expr)
... instead.""", deprecated_since_version="1.1",
... active_deprecations_target='simplify-this-deprecation')
... def simplify_this(expr):
... """
... Simplify ``expr``.
...
... .. deprecated:: 1.1
...
... The ``simplify_this`` function is deprecated. Use :func:`simplify`
... instead. See its documentation for more information. See
... :ref:`simplify-this-deprecation` for details.
...
... """
... return simplify(expr)
>>> from sympy.abc import x
>>> simplify_this(x*(x + 1) - x**2) # doctest: +SKIP
<stdin>:1: SymPyDeprecationWarning:
<BLANKLINE>
The simplify_this(expr) function is deprecated. Use simplify(expr)
instead.
<BLANKLINE>
See https://docs.sympy.org/latest/explanation/active-deprecations.html#simplify-this-deprecation
for details.
<BLANKLINE>
This has been deprecated since SymPy version 1.1. It
will be removed in a future version of SymPy.
<BLANKLINE>
simplify_this(x)
x
See Also
========
sympy.utilities.exceptions.SymPyDeprecationWarning
sympy.utilities.exceptions.sympy_deprecation_warning
sympy.utilities.exceptions.ignore_warnings
sympy.testing.pytest.warns_deprecated_sympy
'''
decorator_kwargs = dict(deprecated_since_version=deprecated_since_version,
active_deprecations_target=active_deprecations_target)
def deprecated_decorator(wrapped):
if hasattr(wrapped, '__mro__'): # wrapped is actually a class
class wrapper(wrapped):
__doc__ = wrapped.__doc__
__module__ = wrapped.__module__
_sympy_deprecated_func = wrapped
if '__new__' in wrapped.__dict__:
def __new__(cls, *args, **kwargs):
sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
return super().__new__(cls, *args, **kwargs)
else:
def __init__(self, *args, **kwargs):
sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
super().__init__(*args, **kwargs)
wrapper.__name__ = wrapped.__name__
else:
@wraps(wrapped)
def wrapper(*args, **kwargs):
sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
return wrapped(*args, **kwargs)
wrapper._sympy_deprecated_func = wrapped
return wrapper
return deprecated_decorator
|
15c99e80efeb9678464e62b923249db479a0bb5f80954f03272a6e525edebf68 | from sympy.core import S
from sympy.core.function import Lambda
from sympy.core.power import Pow
from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits, ArrayPrinter
from .codeprinter import CodePrinter
_not_in_numpy = 'erf erfc factorial gamma loggamma'.split()
_in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy]
_known_functions_numpy = dict(_in_numpy, **{
'acos': 'arccos',
'acosh': 'arccosh',
'asin': 'arcsin',
'asinh': 'arcsinh',
'atan': 'arctan',
'atan2': 'arctan2',
'atanh': 'arctanh',
'exp2': 'exp2',
'sign': 'sign',
'logaddexp': 'logaddexp',
'logaddexp2': 'logaddexp2',
})
_known_constants_numpy = {
'Exp1': 'e',
'Pi': 'pi',
'EulerGamma': 'euler_gamma',
'NaN': 'nan',
'Infinity': 'PINF',
'NegativeInfinity': 'NINF'
}
_numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()}
_numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()}
class NumPyPrinter(ArrayPrinter, PythonCodePrinter):
"""
Numpy printer which handles vectorized piecewise functions,
logical operators, etc.
"""
_module = 'numpy'
_kf = _numpy_known_functions
_kc = _numpy_known_constants
def __init__(self, settings=None):
"""
`settings` is passed to CodePrinter.__init__()
`module` specifies the array module to use, currently 'NumPy', 'CuPy'
or 'JAX'.
"""
self.language = "Python with {}".format(self._module)
self.printmethod = "_{}code".format(self._module)
self._kf = {**PythonCodePrinter._kf, **self._kf}
super().__init__(settings=settings)
def _print_seq(self, seq):
"General sequence printer: converts to tuple"
# Print tuples here instead of lists because numba supports
# tuples in nopython mode.
delimiter=', '
return '({},)'.format(delimiter.join(self._print(item) for item in seq))
def _print_MatMul(self, expr):
"Matrix multiplication printer"
if expr.as_coeff_matrices()[0] is not S.One:
expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])]
return '({})'.format(').dot('.join(self._print(i) for i in expr_list))
return '({})'.format(').dot('.join(self._print(i) for i in expr.args))
def _print_MatPow(self, expr):
"Matrix power printer"
return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'),
self._print(expr.args[0]), self._print(expr.args[1]))
def _print_Inverse(self, expr):
"Matrix inverse printer"
return '{}({})'.format(self._module_format(self._module + '.linalg.inv'),
self._print(expr.args[0]))
def _print_DotProduct(self, expr):
# DotProduct allows any shape order, but numpy.dot does matrix
# multiplication, so we have to make sure it gets 1 x n by n x 1.
arg1, arg2 = expr.args
if arg1.shape[0] != 1:
arg1 = arg1.T
if arg2.shape[1] != 1:
arg2 = arg2.T
return "%s(%s, %s)" % (self._module_format(self._module + '.dot'),
self._print(arg1),
self._print(arg2))
def _print_MatrixSolve(self, expr):
return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'),
self._print(expr.matrix),
self._print(expr.vector))
def _print_ZeroMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.zeros'),
self._print(expr.shape))
def _print_OneMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.ones'),
self._print(expr.shape))
def _print_FunctionMatrix(self, expr):
from sympy.abc import i, j
lamda = expr.lamda
if not isinstance(lamda, Lambda):
lamda = Lambda((i, j), lamda(i, j))
return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'),
', '.join(self._print(arg) for arg in lamda.args[0]),
self._print(lamda.args[1]), self._print(expr.shape))
def _print_HadamardProduct(self, expr):
func = self._module_format(self._module + '.multiply')
return ''.join('{}({}, '.format(func, self._print(arg)) \
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
')' * (len(expr.args) - 1))
def _print_KroneckerProduct(self, expr):
func = self._module_format(self._module + '.kron')
return ''.join('{}({}, '.format(func, self._print(arg)) \
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
')' * (len(expr.args) - 1))
def _print_Adjoint(self, expr):
return '{}({}({}))'.format(
self._module_format(self._module + '.conjugate'),
self._module_format(self._module + '.transpose'),
self._print(expr.args[0]))
def _print_DiagonalOf(self, expr):
vect = '{}({})'.format(
self._module_format(self._module + '.diag'),
self._print(expr.arg))
return '{}({}, (-1, 1))'.format(
self._module_format(self._module + '.reshape'), vect)
def _print_DiagMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.diagflat'),
self._print(expr.args[0]))
def _print_DiagonalMatrix(self, expr):
return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'),
self._print(expr.arg), self._module_format(self._module + '.eye'),
self._print(expr.shape[0]), self._print(expr.shape[1]))
def _print_Piecewise(self, expr):
"Piecewise function printer"
from sympy.logic.boolalg import ITE, simplify_logic
def print_cond(cond):
""" Problem having an ITE in the cond. """
if cond.has(ITE):
return self._print(simplify_logic(cond))
else:
return self._print(cond)
exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args))
conds = '[{}]'.format(','.join(print_cond(arg.cond) for arg in expr.args))
# If [default_value, True] is a (expr, cond) sequence in a Piecewise object
# it will behave the same as passing the 'default' kwarg to select()
# *as long as* it is the last element in expr.args.
# If this is not the case, it may be triggered prematurely.
return '{}({}, {}, default={})'.format(
self._module_format(self._module + '.select'), conds, exprs,
self._print(S.NaN))
def _print_Relational(self, expr):
"Relational printer for Equality and Unequality"
op = {
'==' :'equal',
'!=' :'not_equal',
'<' :'less',
'<=' :'less_equal',
'>' :'greater',
'>=' :'greater_equal',
}
if expr.rel_op in op:
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]),
lhs=lhs, rhs=rhs)
return super()._print_Relational(expr)
def _print_And(self, expr):
"Logical And printer"
# We have to override LambdaPrinter because it uses Python 'and' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_and' to NUMPY_TRANSLATIONS.
return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args))
def _print_Or(self, expr):
"Logical Or printer"
# We have to override LambdaPrinter because it uses Python 'or' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_or' to NUMPY_TRANSLATIONS.
return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args))
def _print_Not(self, expr):
"Logical Not printer"
# We have to override LambdaPrinter because it uses Python 'not' keyword.
# If LambdaPrinter didn't define it, we would still have to define our
# own because StrPrinter doesn't define it.
return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args))
def _print_Pow(self, expr, rational=False):
# XXX Workaround for negative integer power error
if expr.exp.is_integer and expr.exp.is_negative:
expr = Pow(expr.base, expr.exp.evalf(), evaluate=False)
return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt')
def _print_Min(self, expr):
return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args))
def _print_Max(self, expr):
return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args))
def _print_arg(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0]))
def _print_im(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0]))
def _print_Mod(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join(
map(lambda arg: self._print(arg), expr.args)))
def _print_re(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0]))
def _print_sinc(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi))
def _print_MatrixBase(self, expr):
func = self.known_functions.get(expr.__class__.__name__, None)
if func is None:
func = self._module_format(self._module + '.array')
return "%s(%s)" % (func, self._print(expr.tolist()))
def _print_Identity(self, expr):
shape = expr.shape
if all(dim.is_Integer for dim in shape):
return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0]))
else:
raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices")
def _print_BlockMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.block'),
self._print(expr.args[0].tolist()))
def _print_NDimArray(self, expr):
if len(expr.shape) == 1:
return self._module + '.array(' + self._print(expr.args[0]) + ')'
if len(expr.shape) == 2:
return self._print(expr.tomatrix())
# Should be possible to extend to more dimensions
return CodePrinter._print_not_supported(self, expr)
_add = "add"
_einsum = "einsum"
_transpose = "transpose"
_ones = "ones"
_zeros = "zeros"
_print_lowergamma = CodePrinter._print_not_supported
_print_uppergamma = CodePrinter._print_not_supported
_print_fresnelc = CodePrinter._print_not_supported
_print_fresnels = CodePrinter._print_not_supported
for func in _numpy_known_functions:
setattr(NumPyPrinter, f'_print_{func}', _print_known_func)
for const in _numpy_known_constants:
setattr(NumPyPrinter, f'_print_{const}', _print_known_const)
_known_functions_scipy_special = {
'Ei': 'expi',
'erf': 'erf',
'erfc': 'erfc',
'besselj': 'jv',
'bessely': 'yv',
'besseli': 'iv',
'besselk': 'kv',
'cosm1': 'cosm1',
'factorial': 'factorial',
'gamma': 'gamma',
'loggamma': 'gammaln',
'digamma': 'psi',
'RisingFactorial': 'poch',
'jacobi': 'eval_jacobi',
'gegenbauer': 'eval_gegenbauer',
'chebyshevt': 'eval_chebyt',
'chebyshevu': 'eval_chebyu',
'legendre': 'eval_legendre',
'hermite': 'eval_hermite',
'laguerre': 'eval_laguerre',
'assoc_laguerre': 'eval_genlaguerre',
'beta': 'beta',
'LambertW' : 'lambertw',
}
_known_constants_scipy_constants = {
'GoldenRatio': 'golden_ratio',
'Pi': 'pi',
}
_scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()}
_scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()}
class SciPyPrinter(NumPyPrinter):
_kf = {**NumPyPrinter._kf, **_scipy_known_functions}
_kc = {**NumPyPrinter._kc, **_scipy_known_constants}
def __init__(self, settings=None):
super().__init__(settings=settings)
self.language = "Python with SciPy and NumPy"
def _print_SparseRepMatrix(self, expr):
i, j, data = [], [], []
for (r, c), v in expr.todok().items():
i.append(r)
j.append(c)
data.append(v)
return "{name}(({data}, ({i}, {j})), shape={shape})".format(
name=self._module_format('scipy.sparse.coo_matrix'),
data=data, i=i, j=j, shape=expr.shape
)
_print_ImmutableSparseMatrix = _print_SparseRepMatrix
# SciPy's lpmv has a different order of arguments from assoc_legendre
def _print_assoc_legendre(self, expr):
return "{0}({2}, {1}, {3})".format(
self._module_format('scipy.special.lpmv'),
self._print(expr.args[0]),
self._print(expr.args[1]),
self._print(expr.args[2]))
def _print_lowergamma(self, expr):
return "{0}({2})*{1}({2}, {3})".format(
self._module_format('scipy.special.gamma'),
self._module_format('scipy.special.gammainc'),
self._print(expr.args[0]),
self._print(expr.args[1]))
def _print_uppergamma(self, expr):
return "{0}({2})*{1}({2}, {3})".format(
self._module_format('scipy.special.gamma'),
self._module_format('scipy.special.gammaincc'),
self._print(expr.args[0]),
self._print(expr.args[1]))
def _print_betainc(self, expr):
betainc = self._module_format('scipy.special.betainc')
beta = self._module_format('scipy.special.beta')
args = [self._print(arg) for arg in expr.args]
return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \
* {beta}({args[0]}, {args[1]})"
def _print_betainc_regularized(self, expr):
return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format(
self._module_format('scipy.special.betainc'),
self._print(expr.args[0]),
self._print(expr.args[1]),
self._print(expr.args[2]),
self._print(expr.args[3]))
def _print_fresnels(self, expr):
return "{}({})[0]".format(
self._module_format("scipy.special.fresnel"),
self._print(expr.args[0]))
def _print_fresnelc(self, expr):
return "{}({})[1]".format(
self._module_format("scipy.special.fresnel"),
self._print(expr.args[0]))
def _print_airyai(self, expr):
return "{}({})[0]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airyaiprime(self, expr):
return "{}({})[1]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airybi(self, expr):
return "{}({})[2]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airybiprime(self, expr):
return "{}({})[3]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_bernoulli(self, expr):
# scipy's bernoulli is inconsistent with SymPy's so rewrite
return self._print(expr._eval_rewrite_as_zeta(*expr.args))
def _print_harmonic(self, expr):
return self._print(expr._eval_rewrite_as_zeta(*expr.args))
def _print_Integral(self, e):
integration_vars, limits = _unpack_integral_limits(e)
if len(limits) == 1:
# nicer (but not necessary) to prefer quad over nquad for 1D case
module_str = self._module_format("scipy.integrate.quad")
limit_str = "%s, %s" % tuple(map(self._print, limits[0]))
else:
module_str = self._module_format("scipy.integrate.nquad")
limit_str = "({})".format(", ".join(
"(%s, %s)" % tuple(map(self._print, l)) for l in limits))
return "{}(lambda {}: {}, {})[0]".format(
module_str,
", ".join(map(self._print, integration_vars)),
self._print(e.args[0]),
limit_str)
for func in _scipy_known_functions:
setattr(SciPyPrinter, f'_print_{func}', _print_known_func)
for const in _scipy_known_constants:
setattr(SciPyPrinter, f'_print_{const}', _print_known_const)
_cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()}
_cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()}
class CuPyPrinter(NumPyPrinter):
"""
CuPy printer which handles vectorized piecewise functions,
logical operators, etc.
"""
_module = 'cupy'
_kf = _cupy_known_functions
_kc = _cupy_known_constants
def __init__(self, settings=None):
super().__init__(settings=settings)
for func in _cupy_known_functions:
setattr(CuPyPrinter, f'_print_{func}', _print_known_func)
for const in _cupy_known_constants:
setattr(CuPyPrinter, f'_print_{const}', _print_known_const)
_jax_known_functions = {k: 'jax.numpy.' + v for k, v in _known_functions_numpy.items()}
_jax_known_constants = {k: 'jax.numpy.' + v for k, v in _known_constants_numpy.items()}
class JaxPrinter(NumPyPrinter):
"""
JAX printer which handles vectorized piecewise functions,
logical operators, etc.
"""
_module = "jax.numpy"
_kf = _jax_known_functions
_kc = _jax_known_constants
def __init__(self, settings=None):
super().__init__(settings=settings)
# These need specific override to allow for the lack of "jax.numpy.reduce"
def _print_And(self, expr):
"Logical And printer"
return "{}({}.asarray([{}]), axis=0)".format(
self._module_format(self._module + ".all"),
self._module_format(self._module),
",".join(self._print(i) for i in expr.args),
)
def _print_Or(self, expr):
"Logical Or printer"
return "{}({}.asarray([{}]), axis=0)".format(
self._module_format(self._module + ".any"),
self._module_format(self._module),
",".join(self._print(i) for i in expr.args),
)
for func in _jax_known_functions:
setattr(JaxPrinter, f'_print_{func}', _print_known_func)
for const in _jax_known_constants:
setattr(JaxPrinter, f'_print_{const}', _print_known_const)
|
b31f662f07ec143097310ec3ad9b0d29ede3c31d159bf25c5761fa13bdda89c5 | """
Python code printers
This module contains Python code printers for plain Python as well as NumPy & SciPy enabled code.
"""
from collections import defaultdict
from itertools import chain
from sympy.core import S
from sympy.core.mod import Mod
from .precedence import precedence
from .codeprinter import CodePrinter
_kw = {
'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield', 'None', 'False', 'nonlocal', 'True'
}
_known_functions = {
'Abs': 'abs',
'Min': 'min',
'Max': 'max',
}
_known_functions_math = {
'acos': 'acos',
'acosh': 'acosh',
'asin': 'asin',
'asinh': 'asinh',
'atan': 'atan',
'atan2': 'atan2',
'atanh': 'atanh',
'ceiling': 'ceil',
'cos': 'cos',
'cosh': 'cosh',
'erf': 'erf',
'erfc': 'erfc',
'exp': 'exp',
'expm1': 'expm1',
'factorial': 'factorial',
'floor': 'floor',
'gamma': 'gamma',
'hypot': 'hypot',
'loggamma': 'lgamma',
'log': 'log',
'ln': 'log',
'log10': 'log10',
'log1p': 'log1p',
'log2': 'log2',
'sin': 'sin',
'sinh': 'sinh',
'Sqrt': 'sqrt',
'tan': 'tan',
'tanh': 'tanh'
} # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf
# radians trunc fmod fsum gcd degrees fabs]
_known_constants_math = {
'Exp1': 'e',
'Pi': 'pi',
'E': 'e',
'Infinity': 'inf',
'NaN': 'nan',
'ComplexInfinity': 'nan'
}
def _print_known_func(self, expr):
known = self.known_functions[expr.__class__.__name__]
return '{name}({args})'.format(name=self._module_format(known),
args=', '.join(map(lambda arg: self._print(arg), expr.args)))
def _print_known_const(self, expr):
known = self.known_constants[expr.__class__.__name__]
return self._module_format(known)
class AbstractPythonCodePrinter(CodePrinter):
printmethod = "_pythoncode"
language = "Python"
reserved_words = _kw
modules = None # initialized to a set in __init__
tab = ' '
_kf = dict(chain(
_known_functions.items(),
[(k, 'math.' + v) for k, v in _known_functions_math.items()]
))
_kc = {k: 'math.'+v for k, v in _known_constants_math.items()}
_operators = {'and': 'and', 'or': 'or', 'not': 'not'}
_default_settings = dict(
CodePrinter._default_settings,
user_functions={},
precision=17,
inline=True,
fully_qualified_modules=True,
contract=False,
standard='python3',
)
def __init__(self, settings=None):
super().__init__(settings)
# Python standard handler
std = self._settings['standard']
if std is None:
import sys
std = 'python{}'.format(sys.version_info.major)
if std != 'python3':
raise ValueError('Only Python 3 is supported.')
self.standard = std
self.module_imports = defaultdict(set)
# Known functions and constants handler
self.known_functions = dict(self._kf, **(settings or {}).get(
'user_functions', {}))
self.known_constants = dict(self._kc, **(settings or {}).get(
'user_constants', {}))
def _declare_number_const(self, name, value):
return "%s = %s" % (name, value)
def _module_format(self, fqn, register=True):
parts = fqn.split('.')
if register and len(parts) > 1:
self.module_imports['.'.join(parts[:-1])].add(parts[-1])
if self._settings['fully_qualified_modules']:
return fqn
else:
return fqn.split('(')[0].split('[')[0].split('.')[-1]
def _format_code(self, lines):
return lines
def _get_statement(self, codestring):
return "{}".format(codestring)
def _get_comment(self, text):
return " # {}".format(text)
def _expand_fold_binary_op(self, op, args):
"""
This method expands a fold on binary operations.
``functools.reduce`` is an example of a folded operation.
For example, the expression
`A + B + C + D`
is folded into
`((A + B) + C) + D`
"""
if len(args) == 1:
return self._print(args[0])
else:
return "%s(%s, %s)" % (
self._module_format(op),
self._expand_fold_binary_op(op, args[:-1]),
self._print(args[-1]),
)
def _expand_reduce_binary_op(self, op, args):
"""
This method expands a reductin on binary operations.
Notice: this is NOT the same as ``functools.reduce``.
For example, the expression
`A + B + C + D`
is reduced into:
`(A + B) + (C + D)`
"""
if len(args) == 1:
return self._print(args[0])
else:
N = len(args)
Nhalf = N // 2
return "%s(%s, %s)" % (
self._module_format(op),
self._expand_reduce_binary_op(args[:Nhalf]),
self._expand_reduce_binary_op(args[Nhalf:]),
)
def _print_NaN(self, expr):
return "float('nan')"
def _print_Infinity(self, expr):
return "float('inf')"
def _print_NegativeInfinity(self, expr):
return "float('-inf')"
def _print_ComplexInfinity(self, expr):
return self._print_NaN(expr)
def _print_Mod(self, expr):
PREC = precedence(expr)
return ('{} % {}'.format(*map(lambda x: self.parenthesize(x, PREC), expr.args)))
def _print_Piecewise(self, expr):
result = []
i = 0
for arg in expr.args:
e = arg.expr
c = arg.cond
if i == 0:
result.append('(')
result.append('(')
result.append(self._print(e))
result.append(')')
result.append(' if ')
result.append(self._print(c))
result.append(' else ')
i += 1
result = result[:-1]
if result[-1] == 'True':
result = result[:-2]
result.append(')')
else:
result.append(' else None)')
return ''.join(result)
def _print_Relational(self, expr):
"Relational printer for Equality and Unequality"
op = {
'==' :'equal',
'!=' :'not_equal',
'<' :'less',
'<=' :'less_equal',
'>' :'greater',
'>=' :'greater_equal',
}
if expr.rel_op in op:
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs)
return super()._print_Relational(expr)
def _print_ITE(self, expr):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(expr.rewrite(Piecewise))
def _print_Sum(self, expr):
loops = (
'for {i} in range({a}, {b}+1)'.format(
i=self._print(i),
a=self._print(a),
b=self._print(b))
for i, a, b in expr.limits)
return '(builtins.sum({function} {loops}))'.format(
function=self._print(expr.function),
loops=' '.join(loops))
def _print_ImaginaryUnit(self, expr):
return '1j'
def _print_KroneckerDelta(self, expr):
a, b = expr.args
return '(1 if {a} == {b} else 0)'.format(
a = self._print(a),
b = self._print(b)
)
def _print_MatrixBase(self, expr):
name = expr.__class__.__name__
func = self.known_functions.get(name, name)
return "%s(%s)" % (func, self._print(expr.tolist()))
_print_SparseRepMatrix = \
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
lambda self, expr: self._print_MatrixBase(expr)
def _indent_codestring(self, codestring):
return '\n'.join([self.tab + line for line in codestring.split('\n')])
def _print_FunctionDefinition(self, fd):
body = '\n'.join(map(lambda arg: self._print(arg), fd.body))
return "def {name}({parameters}):\n{body}".format(
name=self._print(fd.name),
parameters=', '.join([self._print(var.symbol) for var in fd.parameters]),
body=self._indent_codestring(body)
)
def _print_While(self, whl):
body = '\n'.join(map(lambda arg: self._print(arg), whl.body))
return "while {cond}:\n{body}".format(
cond=self._print(whl.condition),
body=self._indent_codestring(body)
)
def _print_Declaration(self, decl):
return '%s = %s' % (
self._print(decl.variable.symbol),
self._print(decl.variable.value)
)
def _print_Return(self, ret):
arg, = ret.args
return 'return %s' % self._print(arg)
def _print_Print(self, prnt):
print_args = ', '.join(map(lambda arg: self._print(arg), prnt.print_args))
if prnt.format_string != None: # Must be '!= None', cannot be 'is not None'
print_args = '{} % ({})'.format(
self._print(prnt.format_string), print_args)
if prnt.file != None: # Must be '!= None', cannot be 'is not None'
print_args += ', file=%s' % self._print(prnt.file)
return 'print(%s)' % print_args
def _print_Stream(self, strm):
if str(strm.name) == 'stdout':
return self._module_format('sys.stdout')
elif str(strm.name) == 'stderr':
return self._module_format('sys.stderr')
else:
return self._print(strm.name)
def _print_NoneToken(self, arg):
return 'None'
def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'):
"""Printing helper function for ``Pow``
Notes
=====
This preprocesses the ``sqrt`` as math formatter and prints division
Examples
========
>>> from sympy import sqrt
>>> from sympy.printing.pycode import PythonCodePrinter
>>> from sympy.abc import x
Python code printer automatically looks up ``math.sqrt``.
>>> printer = PythonCodePrinter()
>>> printer._hprint_Pow(sqrt(x), rational=True)
'x**(1/2)'
>>> printer._hprint_Pow(sqrt(x), rational=False)
'math.sqrt(x)'
>>> printer._hprint_Pow(1/sqrt(x), rational=True)
'x**(-1/2)'
>>> printer._hprint_Pow(1/sqrt(x), rational=False)
'1/math.sqrt(x)'
>>> printer._hprint_Pow(1/x, rational=False)
'1/x'
>>> printer._hprint_Pow(1/x, rational=True)
'x**(-1)'
Using sqrt from numpy or mpmath
>>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt')
'numpy.sqrt(x)'
>>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt')
'mpmath.sqrt(x)'
See Also
========
sympy.printing.str.StrPrinter._print_Pow
"""
PREC = precedence(expr)
if expr.exp == S.Half and not rational:
func = self._module_format(sqrt)
arg = self._print(expr.base)
return '{func}({arg})'.format(func=func, arg=arg)
if expr.is_commutative and not rational:
if -expr.exp is S.Half:
func = self._module_format(sqrt)
num = self._print(S.One)
arg = self._print(expr.base)
return f"{num}/{func}({arg})"
if expr.exp is S.NegativeOne:
num = self._print(S.One)
arg = self.parenthesize(expr.base, PREC, strict=False)
return f"{num}/{arg}"
base_str = self.parenthesize(expr.base, PREC, strict=False)
exp_str = self.parenthesize(expr.exp, PREC, strict=False)
return "{}**{}".format(base_str, exp_str)
class ArrayPrinter:
def _arrayify(self, indexed):
from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
try:
return convert_indexed_to_array(indexed)
except Exception:
return indexed
def _get_einsum_string(self, subranks, contraction_indices):
letters = self._get_letter_generator_for_einsum()
contraction_string = ""
counter = 0
d = {j: min(i) for i in contraction_indices for j in i}
indices = []
for rank_arg in subranks:
lindices = []
for i in range(rank_arg):
if counter in d:
lindices.append(d[counter])
else:
lindices.append(counter)
counter += 1
indices.append(lindices)
mapping = {}
letters_free = []
letters_dum = []
for i in indices:
for j in i:
if j not in mapping:
l = next(letters)
mapping[j] = l
else:
l = mapping[j]
contraction_string += l
if j in d:
if l not in letters_dum:
letters_dum.append(l)
else:
letters_free.append(l)
contraction_string += ","
contraction_string = contraction_string[:-1]
return contraction_string, letters_free, letters_dum
def _get_letter_generator_for_einsum(self):
for i in range(97, 123):
yield chr(i)
for i in range(65, 91):
yield chr(i)
raise ValueError("out of letters")
def _print_ArrayTensorProduct(self, expr):
letters = self._get_letter_generator_for_einsum()
contraction_string = ",".join(["".join([next(letters) for j in range(i)]) for i in expr.subranks])
return '%s("%s", %s)' % (
self._module_format(self._module + "." + self._einsum),
contraction_string,
", ".join([self._print(arg) for arg in expr.args])
)
def _print_ArrayContraction(self, expr):
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
base = expr.expr
contraction_indices = expr.contraction_indices
if isinstance(base, ArrayTensorProduct):
elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
ranks = base.subranks
else:
elems = self._print(base)
ranks = [len(base.shape)]
contraction_string, letters_free, letters_dum = self._get_einsum_string(ranks, contraction_indices)
if not contraction_indices:
return self._print(base)
if isinstance(base, ArrayTensorProduct):
elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
else:
elems = self._print(base)
return "%s(\"%s\", %s)" % (
self._module_format(self._module + "." + self._einsum),
"{}->{}".format(contraction_string, "".join(sorted(letters_free))),
elems,
)
def _print_ArrayDiagonal(self, expr):
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
diagonal_indices = list(expr.diagonal_indices)
if isinstance(expr.expr, ArrayTensorProduct):
subranks = expr.expr.subranks
elems = expr.expr.args
else:
subranks = expr.subranks
elems = [expr.expr]
diagonal_string, letters_free, letters_dum = self._get_einsum_string(subranks, diagonal_indices)
elems = [self._print(i) for i in elems]
return '%s("%s", %s)' % (
self._module_format(self._module + "." + self._einsum),
"{}->{}".format(diagonal_string, "".join(letters_free+letters_dum)),
", ".join(elems)
)
def _print_PermuteDims(self, expr):
return "%s(%s, %s)" % (
self._module_format(self._module + "." + self._transpose),
self._print(expr.expr),
self._print(expr.permutation.array_form),
)
def _print_ArrayAdd(self, expr):
return self._expand_fold_binary_op(self._module + "." + self._add, expr.args)
def _print_OneArray(self, expr):
return "%s((%s,))" % (
self._module_format(self._module+ "." + self._ones),
','.join(map(self._print,expr.args))
)
def _print_ZeroArray(self, expr):
return "%s((%s,))" % (
self._module_format(self._module+ "." + self._zeros),
','.join(map(self._print,expr.args))
)
def _print_Assignment(self, expr):
#XXX: maybe this needs to happen at a higher level e.g. at _print or
#doprint?
lhs = self._print(self._arrayify(expr.lhs))
rhs = self._print(self._arrayify(expr.rhs))
return "%s = %s" % ( lhs, rhs )
def _print_IndexedBase(self, expr):
return self._print_ArraySymbol(expr)
class PythonCodePrinter(AbstractPythonCodePrinter):
def _print_sign(self, e):
return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(
f=self._module_format('math.copysign'), e=self._print(e.args[0]))
def _print_Not(self, expr):
PREC = precedence(expr)
return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
def _print_Indexed(self, expr):
base = expr.args[0]
index = expr.args[1:]
return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational)
def _print_Rational(self, expr):
return '{}/{}'.format(expr.p, expr.q)
def _print_Half(self, expr):
return self._print_Rational(expr)
def _print_frac(self, expr):
return self._print_Mod(Mod(expr.args[0], 1))
def _print_Symbol(self, expr):
name = super()._print_Symbol(expr)
if name in self.reserved_words:
if self._settings['error_on_reserved']:
msg = ('This expression includes the symbol "{}" which is a '
'reserved keyword in this language.')
raise ValueError(msg.format(name))
return name + self._settings['reserved_word_suffix']
elif '{' in name: # Remove curly braces from subscripted variables
return name.replace('{', '').replace('}', '')
else:
return name
_print_lowergamma = CodePrinter._print_not_supported
_print_uppergamma = CodePrinter._print_not_supported
_print_fresnelc = CodePrinter._print_not_supported
_print_fresnels = CodePrinter._print_not_supported
for k in PythonCodePrinter._kf:
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)
for k in _known_constants_math:
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const)
def pycode(expr, **settings):
""" Converts an expr to a string of Python code
Parameters
==========
expr : Expr
A SymPy expression.
fully_qualified_modules : bool
Whether or not to write out full module names of functions
(``math.sin`` vs. ``sin``). default: ``True``.
standard : str or None, optional
Only 'python3' (default) is supported.
This parameter may be removed in the future.
Examples
========
>>> from sympy import pycode, tan, Symbol
>>> pycode(tan(Symbol('x')) + 1)
'math.tan(x) + 1'
"""
return PythonCodePrinter(settings).doprint(expr)
_not_in_mpmath = 'log1p log2'.split()
_in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath]
_known_functions_mpmath = dict(_in_mpmath, **{
'beta': 'beta',
'frac': 'frac',
'fresnelc': 'fresnelc',
'fresnels': 'fresnels',
'sign': 'sign',
'loggamma': 'loggamma',
'hyper': 'hyper',
'meijerg': 'meijerg',
'besselj': 'besselj',
'bessely': 'bessely',
'besseli': 'besseli',
'besselk': 'besselk',
})
_known_constants_mpmath = {
'Exp1': 'e',
'Pi': 'pi',
'GoldenRatio': 'phi',
'EulerGamma': 'euler',
'Catalan': 'catalan',
'NaN': 'nan',
'Infinity': 'inf',
'NegativeInfinity': 'ninf'
}
def _unpack_integral_limits(integral_expr):
""" helper function for _print_Integral that
- accepts an Integral expression
- returns a tuple of
- a list variables of integration
- a list of tuples of the upper and lower limits of integration
"""
integration_vars = []
limits = []
for integration_range in integral_expr.limits:
if len(integration_range) == 3:
integration_var, lower_limit, upper_limit = integration_range
else:
raise NotImplementedError("Only definite integrals are supported")
integration_vars.append(integration_var)
limits.append((lower_limit, upper_limit))
return integration_vars, limits
class MpmathPrinter(PythonCodePrinter):
"""
Lambda printer for mpmath which maintains precision for floats
"""
printmethod = "_mpmathcode"
language = "Python with mpmath"
_kf = dict(chain(
_known_functions.items(),
[(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()]
))
_kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()}
def _print_Float(self, e):
# XXX: This does not handle setting mpmath.mp.dps. It is assumed that
# the caller of the lambdified function will have set it to sufficient
# precision to match the Floats in the expression.
# Remove 'mpz' if gmpy is installed.
args = str(tuple(map(int, e._mpf_)))
return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args)
def _print_Rational(self, e):
return "{func}({p})/{func}({q})".format(
func=self._module_format('mpmath.mpf'),
q=self._print(e.q),
p=self._print(e.p)
)
def _print_Half(self, e):
return self._print_Rational(e)
def _print_uppergamma(self, e):
return "{}({}, {}, {})".format(
self._module_format('mpmath.gammainc'),
self._print(e.args[0]),
self._print(e.args[1]),
self._module_format('mpmath.inf'))
def _print_lowergamma(self, e):
return "{}({}, 0, {})".format(
self._module_format('mpmath.gammainc'),
self._print(e.args[0]),
self._print(e.args[1]))
def _print_log2(self, e):
return '{0}({1})/{0}(2)'.format(
self._module_format('mpmath.log'), self._print(e.args[0]))
def _print_log1p(self, e):
return '{}({}+1)'.format(
self._module_format('mpmath.log'), self._print(e.args[0]))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt')
def _print_Integral(self, e):
integration_vars, limits = _unpack_integral_limits(e)
return "{}(lambda {}: {}, {})".format(
self._module_format("mpmath.quad"),
", ".join(map(self._print, integration_vars)),
self._print(e.args[0]),
", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits))
for k in MpmathPrinter._kf:
setattr(MpmathPrinter, '_print_%s' % k, _print_known_func)
for k in _known_constants_mpmath:
setattr(MpmathPrinter, '_print_%s' % k, _print_known_const)
class SymPyPrinter(AbstractPythonCodePrinter):
language = "Python with SymPy"
def _print_Function(self, expr):
mod = expr.func.__module__ or ''
return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__),
', '.join(map(lambda arg: self._print(arg), expr.args)))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
|
c2cd8fd8ab215e9c1f9e28f8cda537955cc81503a1ee74a32dbac1e7471515c5 | """Printing subsystem"""
from .pretty import pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode
from .latex import latex, print_latex, multiline_latex
from .mathml import mathml, print_mathml
from .python import python, print_python
from .pycode import pycode
from .codeprinter import print_ccode, print_fcode
from .codeprinter import ccode, fcode, cxxcode # noqa:F811
from .smtlib import smtlib_code
from .glsl import glsl_code, print_glsl
from .rcode import rcode, print_rcode
from .jscode import jscode, print_jscode
from .julia import julia_code
from .mathematica import mathematica_code
from .octave import octave_code
from .rust import rust_code
from .gtk import print_gtk
from .preview import preview
from .repr import srepr
from .tree import print_tree
from .str import StrPrinter, sstr, sstrrepr
from .tableform import TableForm
from .dot import dotprint
from .maple import maple_code, print_maple_code
__all__ = [
# sympy.printing.pretty
'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
'pprint_try_use_unicode',
# sympy.printing.latex
'latex', 'print_latex', 'multiline_latex',
# sympy.printing.mathml
'mathml', 'print_mathml',
# sympy.printing.python
'python', 'print_python',
# sympy.printing.pycode
'pycode',
# sympy.printing.codeprinter
'ccode', 'print_ccode', 'cxxcode', 'fcode', 'print_fcode',
# sympy.printing.smtlib
'smtlib_code',
# sympy.printing.glsl
'glsl_code', 'print_glsl',
# sympy.printing.rcode
'rcode', 'print_rcode',
# sympy.printing.jscode
'jscode', 'print_jscode',
# sympy.printing.julia
'julia_code',
# sympy.printing.mathematica
'mathematica_code',
# sympy.printing.octave
'octave_code',
# sympy.printing.rust
'rust_code',
# sympy.printing.gtk
'print_gtk',
# sympy.printing.preview
'preview',
# sympy.printing.repr
'srepr',
# sympy.printing.tree
'print_tree',
# sympy.printing.str
'StrPrinter', 'sstr', 'sstrrepr',
# sympy.printing.tableform
'TableForm',
# sympy.printing.dot
'dotprint',
# sympy.printing.maple
'maple_code', 'print_maple_code',
]
|
7221a5594645edc7305256b93a12118e768100e6102973cfef82df1f7d6ae03d | """
A Printer which converts an expression into its LaTeX equivalent.
"""
from __future__ import annotations
from typing import Any, Callable, TYPE_CHECKING
import itertools
from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol, Expr
from sympy.core.alphabets import greeks
from sympy.core.containers import Tuple
from sympy.core.function import Function, AppliedUndef, Derivative
from sympy.core.operations import AssocOp
from sympy.core.power import Pow
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import SympifyError
from sympy.logic.boolalg import true, BooleanTrue, BooleanFalse
from sympy.tensor.array import NDimArray
# sympy.printing imports
from sympy.printing.precedence import precedence_traditional
from sympy.printing.printer import Printer, print_function
from sympy.printing.conventions import split_super_sub, requires_partial
from sympy.printing.precedence import precedence, PRECEDENCE
from mpmath.libmp.libmpf import prec_to_dps, to_str as mlib_to_str
from sympy.utilities.iterables import has_variety, sift
import re
if TYPE_CHECKING:
from sympy.vector.basisdependent import BasisDependent
# Hand-picked functions which can be used directly in both LaTeX and MathJax
# Complete list at
# https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands
# This variable only contains those functions which SymPy uses.
accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan',
'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec',
'csc', 'cot', 'coth', 're', 'im', 'frac', 'root',
'arg',
]
tex_greek_dictionary = {
'Alpha': r'\mathrm{A}',
'Beta': r'\mathrm{B}',
'Gamma': r'\Gamma',
'Delta': r'\Delta',
'Epsilon': r'\mathrm{E}',
'Zeta': r'\mathrm{Z}',
'Eta': r'\mathrm{H}',
'Theta': r'\Theta',
'Iota': r'\mathrm{I}',
'Kappa': r'\mathrm{K}',
'Lambda': r'\Lambda',
'Mu': r'\mathrm{M}',
'Nu': r'\mathrm{N}',
'Xi': r'\Xi',
'omicron': 'o',
'Omicron': r'\mathrm{O}',
'Pi': r'\Pi',
'Rho': r'\mathrm{P}',
'Sigma': r'\Sigma',
'Tau': r'\mathrm{T}',
'Upsilon': r'\Upsilon',
'Phi': r'\Phi',
'Chi': r'\mathrm{X}',
'Psi': r'\Psi',
'Omega': r'\Omega',
'lamda': r'\lambda',
'Lamda': r'\Lambda',
'khi': r'\chi',
'Khi': r'\mathrm{X}',
'varepsilon': r'\varepsilon',
'varkappa': r'\varkappa',
'varphi': r'\varphi',
'varpi': r'\varpi',
'varrho': r'\varrho',
'varsigma': r'\varsigma',
'vartheta': r'\vartheta',
}
other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar',
'hslash', 'mho', 'wp'}
# Variable name modifiers
modifier_dict: dict[str, Callable[[str], str]] = {
# Accents
'mathring': lambda s: r'\mathring{'+s+r'}',
'ddddot': lambda s: r'\ddddot{'+s+r'}',
'dddot': lambda s: r'\dddot{'+s+r'}',
'ddot': lambda s: r'\ddot{'+s+r'}',
'dot': lambda s: r'\dot{'+s+r'}',
'check': lambda s: r'\check{'+s+r'}',
'breve': lambda s: r'\breve{'+s+r'}',
'acute': lambda s: r'\acute{'+s+r'}',
'grave': lambda s: r'\grave{'+s+r'}',
'tilde': lambda s: r'\tilde{'+s+r'}',
'hat': lambda s: r'\hat{'+s+r'}',
'bar': lambda s: r'\bar{'+s+r'}',
'vec': lambda s: r'\vec{'+s+r'}',
'prime': lambda s: "{"+s+"}'",
'prm': lambda s: "{"+s+"}'",
# Faces
'bold': lambda s: r'\boldsymbol{'+s+r'}',
'bm': lambda s: r'\boldsymbol{'+s+r'}',
'cal': lambda s: r'\mathcal{'+s+r'}',
'scr': lambda s: r'\mathscr{'+s+r'}',
'frak': lambda s: r'\mathfrak{'+s+r'}',
# Brackets
'norm': lambda s: r'\left\|{'+s+r'}\right\|',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
'abs': lambda s: r'\left|{'+s+r'}\right|',
'mag': lambda s: r'\left|{'+s+r'}\right|',
}
greek_letters_set = frozenset(greeks)
_between_two_numbers_p = (
re.compile(r'[0-9][} ]*$'), # search
re.compile(r'[0-9]'), # match
)
def latex_escape(s: str) -> str:
"""
Escape a string such that latex interprets it as plaintext.
We cannot use verbatim easily with mathjax, so escaping is easier.
Rules from https://tex.stackexchange.com/a/34586/41112.
"""
s = s.replace('\\', r'\textbackslash')
for c in '&%$#_{}':
s = s.replace(c, '\\' + c)
s = s.replace('~', r'\textasciitilde')
s = s.replace('^', r'\textasciicircum')
return s
class LatexPrinter(Printer):
printmethod = "_latex"
_default_settings: dict[str, Any] = {
"full_prec": False,
"fold_frac_powers": False,
"fold_func_brackets": False,
"fold_short_frac": None,
"inv_trig_style": "abbreviated",
"itex": False,
"ln_notation": False,
"long_frac_ratio": None,
"mat_delim": "[",
"mat_str": None,
"mode": "plain",
"mul_symbol": None,
"order": None,
"symbol_names": {},
"root_notation": True,
"mat_symbol_style": "plain",
"imaginary_unit": "i",
"gothic_re_im": False,
"decimal_separator": "period",
"perm_cyclic": True,
"parenthesize_super": True,
"min": None,
"max": None,
"diff_operator": "d",
}
def __init__(self, settings=None):
Printer.__init__(self, settings)
if 'mode' in self._settings:
valid_modes = ['inline', 'plain', 'equation',
'equation*']
if self._settings['mode'] not in valid_modes:
raise ValueError("'mode' must be one of 'inline', 'plain', "
"'equation' or 'equation*'")
if self._settings['fold_short_frac'] is None and \
self._settings['mode'] == 'inline':
self._settings['fold_short_frac'] = True
mul_symbol_table = {
None: r" ",
"ldot": r" \,.\, ",
"dot": r" \cdot ",
"times": r" \times "
}
try:
self._settings['mul_symbol_latex'] = \
mul_symbol_table[self._settings['mul_symbol']]
except KeyError:
self._settings['mul_symbol_latex'] = \
self._settings['mul_symbol']
try:
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table[self._settings['mul_symbol'] or 'dot']
except KeyError:
if (self._settings['mul_symbol'].strip() in
['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']):
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table['dot']
else:
self._settings['mul_symbol_latex_numbers'] = \
self._settings['mul_symbol']
self._delim_dict = {'(': ')', '[': ']'}
imaginary_unit_table = {
None: r"i",
"i": r"i",
"ri": r"\mathrm{i}",
"ti": r"\text{i}",
"j": r"j",
"rj": r"\mathrm{j}",
"tj": r"\text{j}",
}
imag_unit = self._settings['imaginary_unit']
self._settings['imaginary_unit_latex'] = imaginary_unit_table.get(imag_unit, imag_unit)
diff_operator_table = {
None: r"d",
"d": r"d",
"rd": r"\mathrm{d}",
"td": r"\text{d}",
}
diff_operator = self._settings['diff_operator']
self._settings["diff_operator_latex"] = diff_operator_table.get(diff_operator, diff_operator)
def _add_parens(self, s) -> str:
return r"\left({}\right)".format(s)
# TODO: merge this with the above, which requires a lot of test changes
def _add_parens_lspace(self, s) -> str:
return r"\left( {}\right)".format(s)
def parenthesize(self, item, level, is_neg=False, strict=False) -> str:
prec_val = precedence_traditional(item)
if is_neg and strict:
return self._add_parens(self._print(item))
if (prec_val < level) or ((not strict) and prec_val <= level):
return self._add_parens(self._print(item))
else:
return self._print(item)
def parenthesize_super(self, s):
"""
Protect superscripts in s
If the parenthesize_super option is set, protect with parentheses, else
wrap in braces.
"""
if "^" in s:
if self._settings['parenthesize_super']:
return self._add_parens(s)
else:
return "{{{}}}".format(s)
return s
def doprint(self, expr) -> str:
tex = Printer.doprint(self, expr)
if self._settings['mode'] == 'plain':
return tex
elif self._settings['mode'] == 'inline':
return r"$%s$" % tex
elif self._settings['itex']:
return r"$$%s$$" % tex
else:
env_str = self._settings['mode']
return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str)
def _needs_brackets(self, expr) -> bool:
"""
Returns True if the expression needs to be wrapped in brackets when
printed, False otherwise. For example: a + b => True; a => False;
10 => False; -10 => True.
"""
return not ((expr.is_Integer and expr.is_nonnegative)
or (expr.is_Atom and (expr is not S.NegativeOne
and expr.is_Rational is False)))
def _needs_function_brackets(self, expr) -> bool:
"""
Returns True if the expression needs to be wrapped in brackets when
passed as an argument to a function, False otherwise. This is a more
liberal version of _needs_brackets, in that many expressions which need
to be wrapped in brackets when added/subtracted/raised to a power do
not need them when passed to a function. Such an example is a*b.
"""
if not self._needs_brackets(expr):
return False
else:
# Muls of the form a*b*c... can be folded
if expr.is_Mul and not self._mul_is_clean(expr):
return True
# Pows which don't need brackets can be folded
elif expr.is_Pow and not self._pow_is_clean(expr):
return True
# Add and Function always need brackets
elif expr.is_Add or expr.is_Function:
return True
else:
return False
def _needs_mul_brackets(self, expr, first=False, last=False) -> bool:
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of a Mul, False otherwise. This is True for Add,
but also for some container objects that would not need brackets
when appearing last in a Mul, e.g. an Integral. ``last=True``
specifies that this expr is the last to appear in a Mul.
``first=True`` specifies that this expr is the first to appear in
a Mul.
"""
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.integrals.integrals import Integral
if expr.is_Mul:
if not first and expr.could_extract_minus_sign():
return True
elif precedence_traditional(expr) < PRECEDENCE["Mul"]:
return True
elif expr.is_Relational:
return True
if expr.is_Piecewise:
return True
if any(expr.has(x) for x in (Mod,)):
return True
if (not last and
any(expr.has(x) for x in (Integral, Product, Sum))):
return True
return False
def _needs_add_brackets(self, expr) -> bool:
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of an Add, False otherwise. This is False for most
things.
"""
if expr.is_Relational:
return True
if any(expr.has(x) for x in (Mod,)):
return True
if expr.is_Add:
return True
return False
def _mul_is_clean(self, expr) -> bool:
for arg in expr.args:
if arg.is_Function:
return False
return True
def _pow_is_clean(self, expr) -> bool:
return not self._needs_brackets(expr.base)
def _do_exponent(self, expr: str, exp):
if exp is not None:
return r"\left(%s\right)^{%s}" % (expr, exp)
else:
return expr
def _print_Basic(self, expr):
name = self._deal_with_super_sub(expr.__class__.__name__)
if expr.args:
ls = [self._print(o) for o in expr.args]
s = r"\operatorname{{{}}}\left({}\right)"
return s.format(name, ", ".join(ls))
else:
return r"\text{{{}}}".format(name)
def _print_bool(self, e: bool | BooleanTrue | BooleanFalse):
return r"\text{%s}" % e
_print_BooleanTrue = _print_bool
_print_BooleanFalse = _print_bool
def _print_NoneType(self, e):
return r"\text{%s}" % e
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
tex = ""
for i, term in enumerate(terms):
if i == 0:
pass
elif term.could_extract_minus_sign():
tex += " - "
term = -term
else:
tex += " + "
term_tex = self._print(term)
if self._needs_add_brackets(term):
term_tex = r"\left(%s\right)" % term_tex
tex += term_tex
return tex
def _print_Cycle(self, expr):
from sympy.combinatorics.permutations import Permutation
if expr.size == 0:
return r"\left( \right)"
expr = Permutation(expr)
expr_perm = expr.cyclic_form
siz = expr.size
if expr.array_form[-1] == siz - 1:
expr_perm = expr_perm + [[siz - 1]]
term_tex = ''
for i in expr_perm:
term_tex += str(i).replace(',', r"\;")
term_tex = term_tex.replace('[', r"\left( ")
term_tex = term_tex.replace(']', r"\right)")
return term_tex
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation
from sympy.utilities.exceptions import sympy_deprecation_warning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
sympy_deprecation_warning(
f"""
Setting Permutation.print_cyclic is deprecated. Instead use
init_printing(perm_cyclic={perm_cyclic}).
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-permutation-print_cyclic",
stacklevel=8,
)
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
return self._print_Cycle(expr)
if expr.size == 0:
return r"\left( \right)"
lower = [self._print(arg) for arg in expr.array_form]
upper = [self._print(arg) for arg in range(len(lower))]
row1 = " & ".join(upper)
row2 = " & ".join(lower)
mat = r" \\ ".join((row1, row2))
return r"\begin{pmatrix} %s \end{pmatrix}" % mat
def _print_AppliedPermutation(self, expr):
perm, var = expr.args
return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var))
def _print_Float(self, expr):
# Based off of that in StrPrinter
dps = prec_to_dps(expr._prec)
strip = False if self._settings['full_prec'] else True
low = self._settings["min"] if "min" in self._settings else None
high = self._settings["max"] if "max" in self._settings else None
str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
# Must always have a mul symbol (as 2.5 10^{20} just looks odd)
# thus we use the number separator
separator = self._settings['mul_symbol_latex_numbers']
if 'e' in str_real:
(mant, exp) = str_real.split('e')
if exp[0] == '+':
exp = exp[1:]
if self._settings['decimal_separator'] == 'comma':
mant = mant.replace('.','{,}')
return r"%s%s10^{%s}" % (mant, separator, exp)
elif str_real == "+inf":
return r"\infty"
elif str_real == "-inf":
return r"- \infty"
else:
if self._settings['decimal_separator'] == 'comma':
str_real = str_real.replace('.','{,}')
return str_real
def _print_Cross(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Curl(self, expr):
vec = expr._expr
return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Divergence(self, expr):
vec = expr._expr
return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Dot(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Gradient(self, expr):
func = expr._expr
return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Laplacian(self, expr):
func = expr._expr
return r"\Delta %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Mul(self, expr: Expr):
from sympy.physics.units import Quantity
from sympy.physics.units.prefixes import Prefix
from sympy.simplify import fraction
separator: str = self._settings['mul_symbol_latex']
numbersep: str = self._settings['mul_symbol_latex_numbers']
def convert(expr) -> str:
if not expr.is_Mul:
return str(self._print(expr))
else:
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
args = list(expr.args)
# If quantities are present append them at the back
units, nonunits = sift(args, lambda x: isinstance(x, (Quantity, Prefix)) or
(isinstance(x, Pow) and
isinstance(x.base, Quantity)), binary=True)
prefixes, units = sift(units, lambda x: isinstance(x, Prefix), binary=True)
return convert_args(nonunits + prefixes + units)
def convert_args(args) -> str:
_tex = last_term_tex = ""
for i, term in enumerate(args):
term_tex = self._print(term)
if not isinstance(term, (Quantity, Prefix)):
if self._needs_mul_brackets(term, first=(i == 0),
last=(i == len(args) - 1)):
term_tex = r"\left(%s\right)" % term_tex
if _between_two_numbers_p[0].search(last_term_tex) and \
_between_two_numbers_p[1].match(str(term)):
# between two numbers
_tex += numbersep
elif _tex:
_tex += separator
elif _tex:
_tex += separator
_tex += term_tex
last_term_tex = term_tex
return _tex
# 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.
# XXX: _print_Pow calls this routine with instances of Pow...
if isinstance(expr, Mul):
args = expr.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
return convert_args(args)
include_parens = False
if expr.could_extract_minus_sign():
expr = -expr
tex = "- "
if expr.is_Add:
tex += "("
include_parens = True
else:
tex = ""
numer, denom = fraction(expr, exact=True)
if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args:
# use the original expression here, since fraction() may have
# altered it when producing numer and denom
tex += convert(expr)
else:
snumer = convert(numer)
sdenom = convert(denom)
ldenom = len(sdenom.split())
ratio = self._settings['long_frac_ratio']
if self._settings['fold_short_frac'] and ldenom <= 2 and \
"^" not in sdenom:
# handle short fractions
if self._needs_mul_brackets(numer, last=False):
tex += r"\left(%s\right) / %s" % (snumer, sdenom)
else:
tex += r"%s / %s" % (snumer, sdenom)
elif ratio is not None and \
len(snumer.split()) > ratio*ldenom:
# handle long fractions
if self._needs_mul_brackets(numer, last=True):
tex += r"\frac{1}{%s}%s\left(%s\right)" \
% (sdenom, separator, snumer)
elif numer.is_Mul:
# split a long numerator
a = S.One
b = S.One
for x in numer.args:
if self._needs_mul_brackets(x, last=False) or \
len(convert(a*x).split()) > ratio*ldenom or \
(b.is_commutative is x.is_commutative is False):
b *= x
else:
a *= x
if self._needs_mul_brackets(b, last=True):
tex += r"\frac{%s}{%s}%s\left(%s\right)" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{%s}{%s}%s%s" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer)
else:
tex += r"\frac{%s}{%s}" % (snumer, sdenom)
if include_parens:
tex += ")"
return tex
def _print_AlgebraicNumber(self, expr):
if expr.is_aliased:
return self._print(expr.as_poly().as_expr())
else:
return self._print(expr.as_expr())
def _print_PrimeIdeal(self, expr):
p = self._print(expr.p)
if expr.is_inert:
return rf'\left({p}\right)'
alpha = self._print(expr.alpha.as_expr())
return rf'\left({p}, {alpha}\right)'
def _print_Pow(self, expr: Pow):
# Treat x**Rational(1,n) as special case
if expr.exp.is_Rational:
p: int = expr.exp.p # type: ignore
q: int = expr.exp.q # type: ignore
if abs(p) == 1 and q != 1 and self._settings['root_notation']:
base = self._print(expr.base)
if q == 2:
tex = r"\sqrt{%s}" % base
elif self._settings['itex']:
tex = r"\root{%d}{%s}" % (q, base)
else:
tex = r"\sqrt[%d]{%s}" % (q, base)
if expr.exp.is_negative:
return r"\frac{1}{%s}" % tex
else:
return tex
elif self._settings['fold_frac_powers'] and q != 1:
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
# issue #12886: add parentheses for superscripts raised to powers
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
if expr.base.is_Function:
return self._print(expr.base, exp="%s/%s" % (p, q))
return r"%s^{%s/%s}" % (base, p, q)
elif expr.exp.is_negative and expr.base.is_commutative:
# special case for 1^(-x), issue 9216
if expr.base == 1:
return r"%s^{%s}" % (expr.base, expr.exp)
# special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252
if expr.base.is_Rational:
base_p: int = expr.base.p # type: ignore
base_q: int = expr.base.q # type: ignore
if base_p * base_q == abs(base_q):
if expr.exp == -1:
return r"\frac{1}{\frac{%s}{%s}}" % (base_p, base_q)
else:
return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (base_p, base_q, abs(expr.exp))
# things like 1/x
return self._print_Mul(expr)
if expr.base.is_Function:
return self._print(expr.base, exp=self._print(expr.exp))
tex = r"%s^{%s}"
return self._helper_print_standard_power(expr, tex)
def _helper_print_standard_power(self, expr, template: str) -> str:
exp = self._print(expr.exp)
# issue #12886: add parentheses around superscripts raised
# to powers
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
elif (isinstance(expr.base, Derivative)
and base.startswith(r'\left(')
and re.match(r'\\left\(\\d?d?dot', base)
and base.endswith(r'\right)')):
# don't use parentheses around dotted derivative
base = base[6: -7] # remove outermost added parens
return template % (base, exp)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def _print_Sum(self, expr):
if len(expr.limits) == 1:
tex = r"\sum_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\sum_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_Product(self, expr):
if len(expr.limits) == 1:
tex = r"\prod_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\prod_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_BasisDependent(self, expr: 'BasisDependent'):
from sympy.vector import Vector
o1: list[str] = []
if expr == expr.zero:
return expr.zero._latex_form
if isinstance(expr, Vector):
items = expr.separate().items()
else:
items = [(0, expr)]
for system, vect in items:
inneritems = list(vect.components.items())
inneritems.sort(key=lambda x: x[0].__str__())
for k, v in inneritems:
if v == 1:
o1.append(' + ' + k._latex_form)
elif v == -1:
o1.append(' - ' + k._latex_form)
else:
arg_str = r'\left(' + self._print(v) + r'\right)'
o1.append(' + ' + arg_str + k._latex_form)
outstr = (''.join(o1))
if outstr[1] != '-':
outstr = outstr[3:]
else:
outstr = outstr[1:]
return outstr
def _print_Indexed(self, expr):
tex_base = self._print(expr.base)
tex = '{'+tex_base+'}'+'_{%s}' % ','.join(
map(self._print, expr.indices))
return tex
def _print_IndexedBase(self, expr):
return self._print(expr.label)
def _print_Idx(self, expr):
label = self._print(expr.label)
if expr.upper is not None:
upper = self._print(expr.upper)
if expr.lower is not None:
lower = self._print(expr.lower)
else:
lower = self._print(S.Zero)
interval = '{lower}\\mathrel{{..}}\\nobreak {upper}'.format(
lower = lower, upper = upper)
return '{{{label}}}_{{{interval}}}'.format(
label = label, interval = interval)
#if no bounds are defined this just prints the label
return label
def _print_Derivative(self, expr):
if requires_partial(expr.expr):
diff_symbol = r'\partial'
else:
diff_symbol = self._settings["diff_operator_latex"]
tex = ""
dim = 0
for x, num in reversed(expr.variable_count):
dim += num
if num == 1:
tex += r"%s %s" % (diff_symbol, self._print(x))
else:
tex += r"%s %s^{%s}" % (diff_symbol,
self.parenthesize_super(self._print(x)),
self._print(num))
if dim == 1:
tex = r"\frac{%s}{%s}" % (diff_symbol, tex)
else:
tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex)
if any(i.could_extract_minus_sign() for i in expr.args):
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=True,
strict=True))
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=False,
strict=True))
def _print_Subs(self, subs):
expr, old, new = subs.args
latex_expr = self._print(expr)
latex_old = (self._print(e) for e in old)
latex_new = (self._print(e) for e in new)
latex_subs = r'\\ '.join(
e[0] + '=' + e[1] for e in zip(latex_old, latex_new))
return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,
latex_subs)
def _print_Integral(self, expr):
tex, symbols = "", []
diff_symbol = self._settings["diff_operator_latex"]
# Only up to \iiiint exists
if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits):
# Use len(expr.limits)-1 so that syntax highlighters don't think
# \" is an escaped quote
tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt"
symbols = [r"\, %s%s" % (diff_symbol, self._print(symbol[0]))
for symbol in expr.limits]
else:
for lim in reversed(expr.limits):
symbol = lim[0]
tex += r"\int"
if len(lim) > 1:
if self._settings['mode'] != 'inline' \
and not self._settings['itex']:
tex += r"\limits"
if len(lim) == 3:
tex += "_{%s}^{%s}" % (self._print(lim[1]),
self._print(lim[2]))
if len(lim) == 2:
tex += "^{%s}" % (self._print(lim[1]))
symbols.insert(0, r"\, %s%s" % (diff_symbol, self._print(symbol)))
return r"%s %s%s" % (tex, self.parenthesize(expr.function,
PRECEDENCE["Mul"],
is_neg=any(i.could_extract_minus_sign() for i in expr.args),
strict=True),
"".join(symbols))
def _print_Limit(self, expr):
e, z, z0, dir = expr.args
tex = r"\lim_{%s \to " % self._print(z)
if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
tex += r"%s}" % self._print(z0)
else:
tex += r"%s^%s}" % (self._print(z0), self._print(dir))
if isinstance(e, AssocOp):
return r"%s\left(%s\right)" % (tex, self._print(e))
else:
return r"%s %s" % (tex, self._print(e))
def _hprint_Function(self, func: str) -> str:
r'''
Logic to decide how to render a function to latex
- if it is a recognized latex name, use the appropriate latex command
- if it is a single letter, excluding sub- and superscripts, just use that letter
- if it is a longer name, then put \operatorname{} around it and be
mindful of undercores in the name
'''
func = self._deal_with_super_sub(func)
superscriptidx = func.find("^")
subscriptidx = func.find("_")
if func in accepted_latex_functions:
name = r"\%s" % func
elif len(func) == 1 or func.startswith('\\') or subscriptidx == 1 or superscriptidx == 1:
name = func
else:
if superscriptidx > 0 and subscriptidx > 0:
name = r"\operatorname{%s}%s" %(
func[:min(subscriptidx,superscriptidx)],
func[min(subscriptidx,superscriptidx):])
elif superscriptidx > 0:
name = r"\operatorname{%s}%s" %(
func[:superscriptidx],
func[superscriptidx:])
elif subscriptidx > 0:
name = r"\operatorname{%s}%s" %(
func[:subscriptidx],
func[subscriptidx:])
else:
name = r"\operatorname{%s}" % func
return name
def _print_Function(self, expr: Function, exp=None) -> str:
r'''
Render functions to LaTeX, handling functions that LaTeX knows about
e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...).
For single-letter function names, render them as regular LaTeX math
symbols. For multi-letter function names that LaTeX does not know
about, (e.g., Li, sech) use \operatorname{} so that the function name
is rendered in Roman font and LaTeX handles spacing properly.
expr is the expression involving the function
exp is an exponent
'''
func = expr.func.__name__
if hasattr(self, '_print_' + func) and \
not isinstance(expr, AppliedUndef):
return getattr(self, '_print_' + func)(expr, exp)
else:
args = [str(self._print(arg)) for arg in expr.args]
# How inverse trig functions should be displayed, formats are:
# abbreviated: asin, full: arcsin, power: sin^-1
inv_trig_style = self._settings['inv_trig_style']
# If we are dealing with a power-style inverse trig function
inv_trig_power_case = False
# If it is applicable to fold the argument brackets
can_fold_brackets = self._settings['fold_func_brackets'] and \
len(args) == 1 and \
not self._needs_function_brackets(expr.args[0])
inv_trig_table = [
"asin", "acos", "atan",
"acsc", "asec", "acot",
"asinh", "acosh", "atanh",
"acsch", "asech", "acoth",
]
# If the function is an inverse trig function, handle the style
if func in inv_trig_table:
if inv_trig_style == "abbreviated":
pass
elif inv_trig_style == "full":
func = ("ar" if func[-1] == "h" else "arc") + func[1:]
elif inv_trig_style == "power":
func = func[1:]
inv_trig_power_case = True
# Can never fold brackets if we're raised to a power
if exp is not None:
can_fold_brackets = False
if inv_trig_power_case:
if func in accepted_latex_functions:
name = r"\%s^{-1}" % func
else:
name = r"\operatorname{%s}^{-1}" % func
elif exp is not None:
func_tex = self._hprint_Function(func)
func_tex = self.parenthesize_super(func_tex)
name = r'%s^{%s}' % (func_tex, exp)
else:
name = self._hprint_Function(func)
if can_fold_brackets:
if func in accepted_latex_functions:
# Wrap argument safely to avoid parse-time conflicts
# with the function name itself
name += r" {%s}"
else:
name += r"%s"
else:
name += r"{\left(%s \right)}"
if inv_trig_power_case and exp is not None:
name += r"^{%s}" % exp
return name % ",".join(args)
def _print_UndefinedFunction(self, expr):
return self._hprint_Function(str(expr))
def _print_ElementwiseApplyFunction(self, expr):
return r"{%s}_{\circ}\left({%s}\right)" % (
self._print(expr.function),
self._print(expr.expr),
)
@property
def _special_function_classes(self):
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.gamma_functions import gamma, lowergamma
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import Chi
return {KroneckerDelta: r'\delta',
gamma: r'\Gamma',
lowergamma: r'\gamma',
beta: r'\operatorname{B}',
DiracDelta: r'\delta',
Chi: r'\operatorname{Chi}'}
def _print_FunctionClass(self, expr):
for cls in self._special_function_classes:
if issubclass(expr, cls) and expr.__name__ == cls.__name__:
return self._special_function_classes[cls]
return self._hprint_Function(str(expr))
def _print_Lambda(self, expr):
symbols, expr = expr.args
if len(symbols) == 1:
symbols = self._print(symbols[0])
else:
symbols = self._print(tuple(symbols))
tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr))
return tex
def _print_IdentityFunction(self, expr):
return r"\left( x \mapsto x \right)"
def _hprint_variadic_function(self, expr, exp=None) -> str:
args = sorted(expr.args, key=default_sort_key)
texargs = [r"%s" % self._print(symbol) for symbol in args]
tex = r"\%s\left(%s\right)" % (str(expr.func).lower(),
", ".join(texargs))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
_print_Min = _print_Max = _hprint_variadic_function
def _print_floor(self, expr, exp=None):
tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_ceiling(self, expr, exp=None):
tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_log(self, expr, exp=None):
if not self._settings["ln_notation"]:
tex = r"\log{\left(%s \right)}" % self._print(expr.args[0])
else:
tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_Abs(self, expr, exp=None):
tex = r"\left|{%s}\right|" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_re(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_im(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_Not(self, e):
from sympy.logic.boolalg import (Equivalent, Implies)
if isinstance(e.args[0], Equivalent):
return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow")
if isinstance(e.args[0], Implies):
return self._print_Implies(e.args[0], r"\not\Rightarrow")
if (e.args[0].is_Boolean):
return r"\neg \left(%s\right)" % self._print(e.args[0])
else:
return r"\neg %s" % self._print(e.args[0])
def _print_LogOp(self, args, char):
arg = args[0]
if arg.is_Boolean and not arg.is_Not:
tex = r"\left(%s\right)" % self._print(arg)
else:
tex = r"%s" % self._print(arg)
for arg in args[1:]:
if arg.is_Boolean and not arg.is_Not:
tex += r" %s \left(%s\right)" % (char, self._print(arg))
else:
tex += r" %s %s" % (char, self._print(arg))
return tex
def _print_And(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\wedge")
def _print_Or(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\vee")
def _print_Xor(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\veebar")
def _print_Implies(self, e, altchar=None):
return self._print_LogOp(e.args, altchar or r"\Rightarrow")
def _print_Equivalent(self, e, altchar=None):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, altchar or r"\Leftrightarrow")
def _print_conjugate(self, expr, exp=None):
tex = r"\overline{%s}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_polar_lift(self, expr, exp=None):
func = r"\operatorname{polar\_lift}"
arg = r"{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (func, exp, arg)
else:
return r"%s%s" % (func, arg)
def _print_ExpBase(self, expr, exp=None):
# TODO should exp_polar be printed differently?
# what about exp_polar(0), exp_polar(1)?
tex = r"e^{%s}" % self._print(expr.args[0])
return self._do_exponent(tex, exp)
def _print_Exp1(self, expr, exp=None):
return "e"
def _print_elliptic_k(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"K^{%s}%s" % (exp, tex)
else:
return r"K%s" % tex
def _print_elliptic_f(self, expr, exp=None):
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"F^{%s}%s" % (exp, tex)
else:
return r"F%s" % tex
def _print_elliptic_e(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"E^{%s}%s" % (exp, tex)
else:
return r"E%s" % tex
def _print_elliptic_pi(self, expr, exp=None):
if len(expr.args) == 3:
tex = r"\left(%s; %s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]),
self._print(expr.args[2]))
else:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"\Pi^{%s}%s" % (exp, tex)
else:
return r"\Pi%s" % tex
def _print_beta(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\operatorname{B}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{B}%s" % tex
def _print_betainc(self, expr, exp=None, operator='B'):
largs = [self._print(arg) for arg in expr.args]
tex = r"\left(%s, %s\right)" % (largs[0], largs[1])
if exp is not None:
return r"\operatorname{%s}_{(%s, %s)}^{%s}%s" % (operator, largs[2], largs[3], exp, tex)
else:
return r"\operatorname{%s}_{(%s, %s)}%s" % (operator, largs[2], largs[3], tex)
def _print_betainc_regularized(self, expr, exp=None):
return self._print_betainc(expr, exp, operator='I')
def _print_uppergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\Gamma^{%s}%s" % (exp, tex)
else:
return r"\Gamma%s" % tex
def _print_lowergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\gamma^{%s}%s" % (exp, tex)
else:
return r"\gamma%s" % tex
def _hprint_one_arg_func(self, expr, exp=None) -> str:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (self._print(expr.func), exp, tex)
else:
return r"%s%s" % (self._print(expr.func), tex)
_print_gamma = _hprint_one_arg_func
def _print_Chi(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\operatorname{Chi}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{Chi}%s" % tex
def _print_expint(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[1])
nu = self._print(expr.args[0])
if exp is not None:
return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex)
else:
return r"\operatorname{E}_{%s}%s" % (nu, tex)
def _print_fresnels(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"S^{%s}%s" % (exp, tex)
else:
return r"S%s" % tex
def _print_fresnelc(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"C^{%s}%s" % (exp, tex)
else:
return r"C%s" % tex
def _print_subfactorial(self, expr, exp=None):
tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"\left(%s\right)^{%s}" % (tex, exp)
else:
return tex
def _print_factorial(self, expr, exp=None):
tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_factorial2(self, expr, exp=None):
tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_binomial(self, expr, exp=None):
tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_RisingFactorial(self, expr, exp=None):
n, k = expr.args
base = r"%s" % self.parenthesize(n, PRECEDENCE['Func'])
tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k))
return self._do_exponent(tex, exp)
def _print_FallingFactorial(self, expr, exp=None):
n, k = expr.args
sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func'])
tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub)
return self._do_exponent(tex, exp)
def _hprint_BesselBase(self, expr, exp, sym: str) -> str:
tex = r"%s" % (sym)
need_exp = False
if exp is not None:
if tex.find('^') == -1:
tex = r"%s^{%s}" % (tex, exp)
else:
need_exp = True
tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order),
self._print(expr.argument))
if need_exp:
tex = self._do_exponent(tex, exp)
return tex
def _hprint_vec(self, vec) -> str:
if not vec:
return ""
s = ""
for i in vec[:-1]:
s += "%s, " % self._print(i)
s += self._print(vec[-1])
return s
def _print_besselj(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'J')
def _print_besseli(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'I')
def _print_besselk(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'K')
def _print_bessely(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'Y')
def _print_yn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'y')
def _print_jn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'j')
def _print_hankel1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(1)}')
def _print_hankel2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(2)}')
def _print_hn1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(1)}')
def _print_hn2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(2)}')
def _hprint_airy(self, expr, exp=None, notation="") -> str:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (notation, exp, tex)
else:
return r"%s%s" % (notation, tex)
def _hprint_airy_prime(self, expr, exp=None, notation="") -> str:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"{%s^\prime}^{%s}%s" % (notation, exp, tex)
else:
return r"%s^\prime%s" % (notation, tex)
def _print_airyai(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Ai')
def _print_airybi(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Bi')
def _print_airyaiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Ai')
def _print_airybiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Bi')
def _print_hyper(self, expr, exp=None):
tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \
r"\middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._hprint_vec(expr.ap), self._hprint_vec(expr.bq),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_meijerg(self, expr, exp=None):
tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \
r"%s & %s \end{matrix} \middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._print(len(expr.bm)), self._print(len(expr.an)),
self._hprint_vec(expr.an), self._hprint_vec(expr.aother),
self._hprint_vec(expr.bm), self._hprint_vec(expr.bother),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_dirichlet_eta(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\eta^{%s}%s" % (exp, tex)
return r"\eta%s" % tex
def _print_zeta(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\zeta^{%s}%s" % (exp, tex)
return r"\zeta%s" % tex
def _print_stieltjes(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"_{%s}" % self._print(expr.args[0])
if exp is not None:
return r"\gamma%s^{%s}" % (tex, exp)
return r"\gamma%s" % tex
def _print_lerchphi(self, expr, exp=None):
tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args))
if exp is None:
return r"\Phi%s" % tex
return r"\Phi^{%s}%s" % (exp, tex)
def _print_polylog(self, expr, exp=None):
s, z = map(self._print, expr.args)
tex = r"\left(%s\right)" % z
if exp is None:
return r"\operatorname{Li}_{%s}%s" % (s, tex)
return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex)
def _print_jacobi(self, expr, exp=None):
n, a, b, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_gegenbauer(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevt(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"T_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevu(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"U_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_legendre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"P_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_legendre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_hermite(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"H_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_laguerre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"L_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_laguerre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Ynm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Znm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def __print_mathieu_functions(self, character, args, prime=False, exp=None):
a, q, z = map(self._print, args)
sup = r"^{\prime}" if prime else ""
exp = "" if not exp else "^{%s}" % exp
return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp)
def _print_mathieuc(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, exp=exp)
def _print_mathieus(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, exp=exp)
def _print_mathieucprime(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp)
def _print_mathieusprime(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp)
def _print_Rational(self, expr):
if expr.q != 1:
sign = ""
p = expr.p
if expr.p < 0:
sign = "- "
p = -p
if self._settings['fold_short_frac']:
return r"%s%d / %d" % (sign, p, expr.q)
return r"%s\frac{%d}{%d}" % (sign, p, expr.q)
else:
return self._print(expr.p)
def _print_Order(self, expr):
s = self._print(expr.expr)
if expr.point and any(p != S.Zero for p in expr.point) or \
len(expr.variables) > 1:
s += '; '
if len(expr.variables) > 1:
s += self._print(expr.variables)
elif expr.variables:
s += self._print(expr.variables[0])
s += r'\rightarrow '
if len(expr.point) > 1:
s += self._print(expr.point)
else:
s += self._print(expr.point[0])
return r"O\left(%s\right)" % s
def _print_Symbol(self, expr: Symbol, style='plain'):
name: str = self._settings['symbol_names'].get(expr)
if name is not None:
return name
return self._deal_with_super_sub(expr.name, style=style)
_print_RandomSymbol = _print_Symbol
def _deal_with_super_sub(self, string: str, style='plain') -> str:
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
# apply the style only to the name
if style == 'bold':
name = "\\mathbf{{{}}}".format(name)
# glue all items together:
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Relational(self, expr):
if self._settings['itex']:
gt = r"\gt"
lt = r"\lt"
else:
gt = ">"
lt = "<"
charmap = {
"==": "=",
">": gt,
"<": lt,
">=": r"\geq",
"<=": r"\leq",
"!=": r"\neq",
}
return "%s %s %s" % (self._print(expr.lhs),
charmap[expr.rel_op], self._print(expr.rhs))
def _print_Piecewise(self, expr):
ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c))
for e, c in expr.args[:-1]]
if expr.args[-1].cond == true:
ecpairs.append(r"%s & \text{otherwise}" %
self._print(expr.args[-1].expr))
else:
ecpairs.append(r"%s & \text{for}\: %s" %
(self._print(expr.args[-1].expr),
self._print(expr.args[-1].cond)))
tex = r"\begin{cases} %s \end{cases}"
return tex % r" \\".join(ecpairs)
def _print_matrix_contents(self, expr):
lines = []
for line in range(expr.rows): # horrible, should be 'rows'
lines.append(" & ".join([self._print(i) for i in expr[line, :]]))
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.cols <= 10) is True:
mat_str = 'matrix'
else:
mat_str = 'array'
out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
out_str = out_str.replace('%MATSTR%', mat_str)
if mat_str == 'array':
out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s')
return out_str % r"\\".join(lines)
def _print_MatrixBase(self, expr):
out_str = self._print_matrix_contents(expr)
if self._settings['mat_delim']:
left_delim: str = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
out_str = r'\left' + left_delim + out_str + \
r'\right' + right_delim
return out_str
def _print_MatrixElement(self, expr):
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\
+ '_{%s, %s}' % (self._print(expr.i), self._print(expr.j))
def _print_MatrixSlice(self, expr):
def latexslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = None
if x[1] == dim:
x[1] = None
return ':'.join(self._print(xi) if xi is not None else '' for xi in x)
return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' +
latexslice(expr.rowslice, expr.parent.rows) + ', ' +
latexslice(expr.colslice, expr.parent.cols) + r'\right]')
def _print_BlockMatrix(self, expr):
return self._print(expr.blocks)
def _print_Transpose(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol, BlockMatrix
if (not isinstance(mat, MatrixSymbol) and
not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr):
return r"\left(%s\right)^{T}" % self._print(mat)
else:
s = self.parenthesize(mat, precedence_traditional(expr), True)
if '^' in s:
return r"\left(%s\right)^{T}" % s
else:
return "%s^{T}" % s
def _print_Trace(self, expr):
mat = expr.arg
return r"\operatorname{tr}\left(%s \right)" % self._print(mat)
def _print_Adjoint(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol, BlockMatrix
if (not isinstance(mat, MatrixSymbol) and
not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr):
return r"\left(%s\right)^{\dagger}" % self._print(mat)
else:
s = self.parenthesize(mat, precedence_traditional(expr), True)
if '^' in s:
return r"\left(%s\right)^{\dagger}" % s
else:
return r"%s^{\dagger}" % s
def _print_MatMul(self, expr):
from sympy import MatMul
# Parenthesize nested MatMul but not other types of Mul objects:
parens = lambda x: self._print(x) if isinstance(x, Mul) and not isinstance(x, MatMul) else \
self.parenthesize(x, precedence_traditional(expr), False)
args = list(expr.args)
if expr.could_extract_minus_sign():
if args[0] == -1:
args = args[1:]
else:
args[0] = -args[0]
return '- ' + ' '.join(map(parens, args))
else:
return ' '.join(map(parens, args))
def _print_Determinant(self, expr):
mat = expr.arg
if mat.is_MatrixExpr:
from sympy.matrices.expressions.blockmatrix import BlockMatrix
if isinstance(mat, BlockMatrix):
return r"\left|{%s}\right|" % self._print_matrix_contents(mat.blocks)
return r"\left|{%s}\right|" % self._print(mat)
return r"\left|{%s}\right|" % self._print_matrix_contents(mat)
def _print_Mod(self, expr, exp=None):
if exp is not None:
return r'\left(%s \bmod %s\right)^{%s}' % \
(self.parenthesize(expr.args[0], PRECEDENCE['Mul'],
strict=True),
self.parenthesize(expr.args[1], PRECEDENCE['Mul'],
strict=True),
exp)
return r'%s \bmod %s' % (self.parenthesize(expr.args[0],
PRECEDENCE['Mul'],
strict=True),
self.parenthesize(expr.args[1],
PRECEDENCE['Mul'],
strict=True))
def _print_HadamardProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \circ '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_HadamardPower(self, expr):
if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]:
template = r"%s^{\circ \left({%s}\right)}"
else:
template = r"%s^{\circ {%s}}"
return self._helper_print_standard_power(expr, template)
def _print_KroneckerProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \otimes '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_MatPow(self, expr):
base, exp = expr.base, expr.exp
from sympy.matrices import MatrixSymbol
if not isinstance(base, MatrixSymbol) and base.is_MatrixExpr:
return "\\left(%s\\right)^{%s}" % (self._print(base),
self._print(exp))
else:
base_str = self._print(base)
if '^' in base_str:
return r"\left(%s\right)^{%s}" % (base_str, self._print(exp))
else:
return "%s^{%s}" % (base_str, self._print(exp))
def _print_MatrixSymbol(self, expr):
return self._print_Symbol(expr, style=self._settings[
'mat_symbol_style'])
def _print_ZeroMatrix(self, Z):
return "0" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{0}"
def _print_OneMatrix(self, O):
return "1" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{1}"
def _print_Identity(self, I):
return r"\mathbb{I}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{I}"
def _print_PermutationMatrix(self, P):
perm_str = self._print(P.args[0])
return "P_{%s}" % perm_str
def _print_NDimArray(self, expr: NDimArray):
if expr.rank() == 0:
return self._print(expr[()])
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.rank() == 0) or (expr.shape[-1] <= 10):
mat_str = 'matrix'
else:
mat_str = 'array'
block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
block_str = block_str.replace('%MATSTR%', mat_str)
if mat_str == 'array':
block_str= block_str.replace('%s','{}%s')
if self._settings['mat_delim']:
left_delim: str = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
block_str = r'\left' + left_delim + block_str + \
r'\right' + right_delim
if expr.rank() == 0:
return block_str % ""
level_str: list[list[str]] = [[] for i in range(expr.rank() + 1)]
shape_ranges = [list(range(i)) for i in expr.shape]
for outer_i in itertools.product(*shape_ranges):
level_str[-1].append(self._print(expr[outer_i]))
even = True
for back_outer_i in range(expr.rank()-1, -1, -1):
if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]:
break
if even:
level_str[back_outer_i].append(
r" & ".join(level_str[back_outer_i+1]))
else:
level_str[back_outer_i].append(
block_str % (r"\\".join(level_str[back_outer_i+1])))
if len(level_str[back_outer_i+1]) == 1:
level_str[back_outer_i][-1] = r"\left[" + \
level_str[back_outer_i][-1] + r"\right]"
even = not even
level_str[back_outer_i+1] = []
out_str = level_str[0][0]
if expr.rank() % 2 == 1:
out_str = block_str % out_str
return out_str
def _printer_tensor_indices(self, name, indices, index_map: dict):
out_str = self._print(name)
last_valence = None
prev_map = None
for index in indices:
new_valence = index.is_up
if ((index in index_map) or prev_map) and \
last_valence == new_valence:
out_str += ","
if last_valence != new_valence:
if last_valence is not None:
out_str += "}"
if index.is_up:
out_str += "{}^{"
else:
out_str += "{}_{"
out_str += self._print(index.args[0])
if index in index_map:
out_str += "="
out_str += self._print(index_map[index])
prev_map = True
else:
prev_map = False
last_valence = new_valence
if last_valence is not None:
out_str += "}"
return out_str
def _print_Tensor(self, expr):
name = expr.args[0].args[0]
indices = expr.get_indices()
return self._printer_tensor_indices(name, indices, {})
def _print_TensorElement(self, expr):
name = expr.expr.args[0].args[0]
indices = expr.expr.get_indices()
index_map = expr.index_map
return self._printer_tensor_indices(name, indices, index_map)
def _print_TensMul(self, expr):
# prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
sign, args = expr._get_args_for_traditional_printer()
return sign + "".join(
[self.parenthesize(arg, precedence(expr)) for arg in args]
)
def _print_TensAdd(self, expr):
a = []
args = expr.args
for x in args:
a.append(self.parenthesize(x, precedence(expr)))
a.sort()
s = ' + '.join(a)
s = s.replace('+ -', '- ')
return s
def _print_TensorIndex(self, expr):
return "{}%s{%s}" % (
"^" if expr.is_up else "_",
self._print(expr.args[0])
)
def _print_PartialDerivative(self, expr):
if len(expr.variables) == 1:
return r"\frac{\partial}{\partial {%s}}{%s}" % (
self._print(expr.variables[0]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
else:
return r"\frac{\partial^{%s}}{%s}{%s}" % (
len(expr.variables),
" ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
def _print_ArraySymbol(self, expr):
return self._print(expr.name)
def _print_ArrayElement(self, expr):
return "{{%s}_{%s}}" % (
self.parenthesize(expr.name, PRECEDENCE["Func"], True),
", ".join([f"{self._print(i)}" for i in expr.indices]))
def _print_UniversalSet(self, expr):
return r"\mathbb{U}"
def _print_frac(self, expr, exp=None):
if exp is None:
return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])
else:
return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (
self._print(expr.args[0]), exp)
def _print_tuple(self, expr):
if self._settings['decimal_separator'] == 'comma':
sep = ";"
elif self._settings['decimal_separator'] == 'period':
sep = ","
else:
raise ValueError('Unknown Decimal Separator')
if len(expr) == 1:
# 1-tuple needs a trailing separator
return self._add_parens_lspace(self._print(expr[0]) + sep)
else:
return self._add_parens_lspace(
(sep + r" \ ").join([self._print(i) for i in expr]))
def _print_TensorProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \otimes '.join(elements)
def _print_WedgeProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \wedge '.join(elements)
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_list(self, expr):
if self._settings['decimal_separator'] == 'comma':
return r"\left[ %s\right]" % \
r"; \ ".join([self._print(i) for i in expr])
elif self._settings['decimal_separator'] == 'period':
return r"\left[ %s\right]" % \
r", \ ".join([self._print(i) for i in expr])
else:
raise ValueError('Unknown Decimal Separator')
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for key in keys:
val = d[key]
items.append("%s : %s" % (self._print(key), self._print(val)))
return r"\left\{ %s\right\}" % r", \ ".join(items)
def _print_Dict(self, expr):
return self._print_dict(expr)
def _print_DiracDelta(self, expr, exp=None):
if len(expr.args) == 1 or expr.args[1] == 0:
tex = r"\delta\left(%s\right)" % self._print(expr.args[0])
else:
tex = r"\delta^{\left( %s \right)}\left( %s \right)" % (
self._print(expr.args[1]), self._print(expr.args[0]))
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_SingularityFunction(self, expr, exp=None):
shift = self._print(expr.args[0] - expr.args[1])
power = self._print(expr.args[2])
tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power)
if exp is not None:
tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp)
return tex
def _print_Heaviside(self, expr, exp=None):
pargs = ', '.join(self._print(arg) for arg in expr.pargs)
tex = r"\theta\left(%s\right)" % pargs
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_KroneckerDelta(self, expr, exp=None):
i = self._print(expr.args[0])
j = self._print(expr.args[1])
if expr.args[0].is_Atom and expr.args[1].is_Atom:
tex = r'\delta_{%s %s}' % (i, j)
else:
tex = r'\delta_{%s, %s}' % (i, j)
if exp is not None:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_LeviCivita(self, expr, exp=None):
indices = map(self._print, expr.args)
if all(x.is_Atom for x in expr.args):
tex = r'\varepsilon_{%s}' % " ".join(indices)
else:
tex = r'\varepsilon_{%s}' % ", ".join(indices)
if exp:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
return '\\text{Domain: }' + self._print(d.as_boolean())
elif hasattr(d, 'set'):
return ('\\text{Domain: }' + self._print(d.symbols) + ' \\in ' +
self._print(d.set))
elif hasattr(d, 'symbols'):
return '\\text{Domain on }' + self._print(d.symbols)
else:
return self._print(None)
def _print_FiniteSet(self, s):
items = sorted(s.args, key=default_sort_key)
return self._print_set(items)
def _print_set(self, s):
items = sorted(s, key=default_sort_key)
if self._settings['decimal_separator'] == 'comma':
items = "; ".join(map(self._print, items))
elif self._settings['decimal_separator'] == 'period':
items = ", ".join(map(self._print, items))
else:
raise ValueError('Unknown Decimal Separator')
return r"\left\{%s\right\}" % items
_print_frozenset = _print_set
def _print_Range(self, s):
def _print_symbolic_range():
# Symbolic Range that cannot be resolved
if s.args[0] == 0:
if s.args[2] == 1:
cont = self._print(s.args[1])
else:
cont = ", ".join(self._print(arg) for arg in s.args)
else:
if s.args[2] == 1:
cont = ", ".join(self._print(arg) for arg in s.args[:2])
else:
cont = ", ".join(self._print(arg) for arg in s.args)
return(f"\\text{{Range}}\\left({cont}\\right)")
dots = object()
if s.start.is_infinite and s.stop.is_infinite:
if s.step.is_positive:
printset = dots, -1, 0, 1, dots
else:
printset = dots, 1, 0, -1, dots
elif s.start.is_infinite:
printset = dots, s[-1] - s.step, s[-1]
elif s.stop.is_infinite:
it = iter(s)
printset = next(it), next(it), dots
elif s.is_empty is not None:
if (s.size < 4) == True:
printset = tuple(s)
elif s.is_iterable:
it = iter(s)
printset = next(it), next(it), dots, s[-1]
else:
return _print_symbolic_range()
else:
return _print_symbolic_range()
return (r"\left\{" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right\}")
def __print_number_polynomial(self, expr, letter, exp=None):
if len(expr.args) == 2:
if exp is not None:
return r"%s_{%s}^{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), exp,
self._print(expr.args[1]))
return r"%s_{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), self._print(expr.args[1]))
tex = r"%s_{%s}" % (letter, self._print(expr.args[0]))
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_bernoulli(self, expr, exp=None):
return self.__print_number_polynomial(expr, "B", exp)
def _print_genocchi(self, expr, exp=None):
return self.__print_number_polynomial(expr, "G", exp)
def _print_bell(self, expr, exp=None):
if len(expr.args) == 3:
tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for
el in expr.args[2])
if exp is not None:
tex = r"%s^{%s}%s" % (tex1, exp, tex2)
else:
tex = tex1 + tex2
return tex
return self.__print_number_polynomial(expr, "B", exp)
def _print_fibonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "F", exp)
def _print_lucas(self, expr, exp=None):
tex = r"L_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_tribonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "T", exp)
def _print_SeqFormula(self, s):
dots = object()
if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
return r"\left\{%s\right\}_{%s=%s}^{%s}" % (
self._print(s.formula),
self._print(s.variables[0]),
self._print(s.start),
self._print(s.stop)
)
if s.start is S.NegativeInfinity:
stop = s.stop
printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2),
s.coeff(stop - 1), s.coeff(stop))
elif s.stop is S.Infinity or s.length > 4:
printset = s[:4]
printset.append(dots)
else:
printset = tuple(s)
return (r"\left[" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right]")
_print_SeqPer = _print_SeqFormula
_print_SeqAdd = _print_SeqFormula
_print_SeqMul = _print_SeqFormula
def _print_Interval(self, i):
if i.start == i.end:
return r"\left\{%s\right\}" % self._print(i.start)
else:
if i.left_open:
left = '('
else:
left = '['
if i.right_open:
right = ')'
else:
right = ']'
return r"\left%s%s, %s\right%s" % \
(left, self._print(i.start), self._print(i.end), right)
def _print_AccumulationBounds(self, i):
return r"\left\langle %s, %s\right\rangle" % \
(self._print(i.min), self._print(i.max))
def _print_Union(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cup ".join(args_str)
def _print_Complement(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \setminus ".join(args_str)
def _print_Intersection(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cap ".join(args_str)
def _print_SymmetricDifference(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \triangle ".join(args_str)
def _print_ProductSet(self, p):
prec = precedence_traditional(p)
if len(p.sets) >= 1 and not has_variety(p.sets):
return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets)
return r" \times ".join(
self.parenthesize(set, prec) for set in p.sets)
def _print_EmptySet(self, e):
return r"\emptyset"
def _print_Naturals(self, n):
return r"\mathbb{N}"
def _print_Naturals0(self, n):
return r"\mathbb{N}_0"
def _print_Integers(self, i):
return r"\mathbb{Z}"
def _print_Rationals(self, i):
return r"\mathbb{Q}"
def _print_Reals(self, i):
return r"\mathbb{R}"
def _print_Complexes(self, i):
return r"\mathbb{C}"
def _print_ImageSet(self, s):
expr = s.lamda.expr
sig = s.lamda.signature
xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets))
xinys = r", ".join(r"%s \in %s" % xy for xy in xys)
return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys)
def _print_ConditionSet(self, s):
vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)])
if s.base_set is S.UniversalSet:
return r"\left\{%s\; \middle|\; %s \right\}" % \
(vars_print, self._print(s.condition))
return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % (
vars_print,
vars_print,
self._print(s.base_set),
self._print(s.condition))
def _print_PowerSet(self, expr):
arg_print = self._print(expr.args[0])
return r"\mathcal{{P}}\left({}\right)".format(arg_print)
def _print_ComplexRegion(self, s):
vars_print = ', '.join([self._print(var) for var in s.variables])
return r"\left\{%s\; \middle|\; %s \in %s \right\}" % (
self._print(s.expr),
vars_print,
self._print(s.sets))
def _print_Contains(self, e):
return r"%s \in %s" % tuple(self._print(a) for a in e.args)
def _print_FourierSeries(self, s):
if s.an.formula is S.Zero and s.bn.formula is S.Zero:
return self._print(s.a0)
return self._print_Add(s.truncate()) + r' + \ldots'
def _print_FormalPowerSeries(self, s):
return self._print_Add(s.infinite)
def _print_FiniteField(self, expr):
return r"\mathbb{F}_{%s}" % expr.mod
def _print_IntegerRing(self, expr):
return r"\mathbb{Z}"
def _print_RationalField(self, expr):
return r"\mathbb{Q}"
def _print_RealField(self, expr):
return r"\mathbb{R}"
def _print_ComplexField(self, expr):
return r"\mathbb{C}"
def _print_PolynomialRing(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left[%s\right]" % (domain, symbols)
def _print_FractionField(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left(%s\right)" % (domain, symbols)
def _print_PolynomialRingBase(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
inv = ""
if not expr.is_Poly:
inv = r"S_<^{-1}"
return r"%s%s\left[%s\right]" % (inv, domain, symbols)
def _print_Poly(self, poly):
cls = poly.__class__.__name__
terms = []
for monom, coeff in poly.terms():
s_monom = ''
for i, exp in enumerate(monom):
if exp > 0:
if exp == 1:
s_monom += self._print(poly.gens[i])
else:
s_monom += self._print(pow(poly.gens[i], exp))
if coeff.is_Add:
if s_monom:
s_coeff = r"\left(%s\right)" % self._print(coeff)
else:
s_coeff = self._print(coeff)
else:
if s_monom:
if coeff is S.One:
terms.extend(['+', s_monom])
continue
if coeff is S.NegativeOne:
terms.extend(['-', s_monom])
continue
s_coeff = self._print(coeff)
if not s_monom:
s_term = s_coeff
else:
s_term = s_coeff + " " + s_monom
if s_term.startswith('-'):
terms.extend(['-', s_term[1:]])
else:
terms.extend(['+', s_term])
if terms[0] in ('-', '+'):
modifier = terms.pop(0)
if modifier == '-':
terms[0] = '-' + terms[0]
expr = ' '.join(terms)
gens = list(map(self._print, poly.gens))
domain = "domain=%s" % self._print(poly.get_domain())
args = ", ".join([expr] + gens + [domain])
if cls in accepted_latex_functions:
tex = r"\%s {\left(%s \right)}" % (cls, args)
else:
tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args)
return tex
def _print_ComplexRootOf(self, root):
cls = root.__class__.__name__
if cls == "ComplexRootOf":
cls = "CRootOf"
expr = self._print(root.expr)
index = root.index
if cls in accepted_latex_functions:
return r"\%s {\left(%s, %d\right)}" % (cls, expr, index)
else:
return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr,
index)
def _print_RootSum(self, expr):
cls = expr.__class__.__name__
args = [self._print(expr.expr)]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
if cls in accepted_latex_functions:
return r"\%s {\left(%s\right)}" % (cls, ", ".join(args))
else:
return r"\operatorname{%s} {\left(%s\right)}" % (cls,
", ".join(args))
def _print_OrdinalOmega(self, expr):
return r"\omega"
def _print_OmegaPower(self, expr):
exp, mul = expr.args
if mul != 1:
if exp != 1:
return r"{} \omega^{{{}}}".format(mul, exp)
else:
return r"{} \omega".format(mul)
else:
if exp != 1:
return r"\omega^{{{}}}".format(exp)
else:
return r"\omega"
def _print_Ordinal(self, expr):
return " + ".join([self._print(arg) for arg in expr.args])
def _print_PolyElement(self, poly):
mul_symbol = self._settings['mul_symbol_latex']
return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol)
def _print_FracElement(self, frac):
if frac.denom == 1:
return self._print(frac.numer)
else:
numer = self._print(frac.numer)
denom = self._print(frac.denom)
return r"\frac{%s}{%s}" % (numer, denom)
def _print_euler(self, expr, exp=None):
m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args
tex = r"E_{%s}" % self._print(m)
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
if x is not None:
tex = r"%s\left(%s\right)" % (tex, self._print(x))
return tex
def _print_catalan(self, expr, exp=None):
tex = r"C_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_UnifiedTransform(self, expr, s, inverse=False):
return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))
def _print_MellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M')
def _print_InverseMellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M', True)
def _print_LaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L')
def _print_InverseLaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L', True)
def _print_FourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F')
def _print_InverseFourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F', True)
def _print_SineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN')
def _print_InverseSineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN', True)
def _print_CosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS')
def _print_InverseCosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS', True)
def _print_DMP(self, p):
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
return self._print(repr(p))
def _print_DMF(self, p):
return self._print_DMP(p)
def _print_Object(self, object):
return self._print(Symbol(object.name))
def _print_LambertW(self, expr, exp=None):
arg0 = self._print(expr.args[0])
exp = r"^{%s}" % (exp,) if exp is not None else ""
if len(expr.args) == 1:
result = r"W%s\left(%s\right)" % (exp, arg0)
else:
arg1 = self._print(expr.args[1])
result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0)
return result
def _print_Expectation(self, expr):
return r"\operatorname{{E}}\left[{}\right]".format(self._print(expr.args[0]))
def _print_Variance(self, expr):
return r"\operatorname{{Var}}\left({}\right)".format(self._print(expr.args[0]))
def _print_Covariance(self, expr):
return r"\operatorname{{Cov}}\left({}\right)".format(", ".join(self._print(arg) for arg in expr.args))
def _print_Probability(self, expr):
return r"\operatorname{{P}}\left({}\right)".format(self._print(expr.args[0]))
def _print_Morphism(self, morphism):
domain = self._print(morphism.domain)
codomain = self._print(morphism.codomain)
return "%s\\rightarrow %s" % (domain, codomain)
def _print_TransferFunction(self, expr):
num, den = self._print(expr.num), self._print(expr.den)
return r"\frac{%s}{%s}" % (num, den)
def _print_Series(self, expr):
args = list(expr.args)
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
return ' '.join(map(parens, args))
def _print_MIMOSeries(self, expr):
from sympy.physics.control.lti import MIMOParallel
args = list(expr.args)[::-1]
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False) if isinstance(x, MIMOParallel) else self._print(x)
return r"\cdot".join(map(parens, args))
def _print_Parallel(self, expr):
return ' + '.join(map(self._print, expr.args))
def _print_MIMOParallel(self, expr):
return ' + '.join(map(self._print, expr.args))
def _print_Feedback(self, expr):
from sympy.physics.control import TransferFunction, Series
num, tf = expr.sys1, TransferFunction(1, 1, expr.var)
num_arg_list = list(num.args) if isinstance(num, Series) else [num]
den_arg_list = list(expr.sys2.args) if \
isinstance(expr.sys2, Series) else [expr.sys2]
den_term_1 = tf
if isinstance(num, Series) and isinstance(expr.sys2, Series):
den_term_2 = Series(*num_arg_list, *den_arg_list)
elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction):
if expr.sys2 == tf:
den_term_2 = Series(*num_arg_list)
else:
den_term_2 = tf, Series(*num_arg_list, expr.sys2)
elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series):
if num == tf:
den_term_2 = Series(*den_arg_list)
else:
den_term_2 = Series(num, *den_arg_list)
else:
if num == tf:
den_term_2 = Series(*den_arg_list)
elif expr.sys2 == tf:
den_term_2 = Series(*num_arg_list)
else:
den_term_2 = Series(*num_arg_list, *den_arg_list)
numer = self._print(num)
denom_1 = self._print(den_term_1)
denom_2 = self._print(den_term_2)
_sign = "+" if expr.sign == -1 else "-"
return r"\frac{%s}{%s %s %s}" % (numer, denom_1, _sign, denom_2)
def _print_MIMOFeedback(self, expr):
from sympy.physics.control import MIMOSeries
inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1))
sys1 = self._print(expr.sys1)
_sign = "+" if expr.sign == -1 else "-"
return r"\left(I_{\tau} %s %s\right)^{-1} \cdot %s" % (_sign, inv_mat, sys1)
def _print_TransferFunctionMatrix(self, expr):
mat = self._print(expr._expr_mat)
return r"%s_\tau" % mat
def _print_DFT(self, expr):
return r"\text{{{}}}_{{{}}}".format(expr.__class__.__name__, expr.n)
_print_IDFT = _print_DFT
def _print_NamedMorphism(self, morphism):
pretty_name = self._print(Symbol(morphism.name))
pretty_morphism = self._print_Morphism(morphism)
return "%s:%s" % (pretty_name, pretty_morphism)
def _print_IdentityMorphism(self, morphism):
from sympy.categories import NamedMorphism
return self._print_NamedMorphism(NamedMorphism(
morphism.domain, morphism.codomain, "id"))
def _print_CompositeMorphism(self, morphism):
# All components of the morphism have names and it is thus
# possible to build the name of the composite.
component_names_list = [self._print(Symbol(component.name)) for
component in morphism.components]
component_names_list.reverse()
component_names = "\\circ ".join(component_names_list) + ":"
pretty_morphism = self._print_Morphism(morphism)
return component_names + pretty_morphism
def _print_Category(self, morphism):
return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name)))
def _print_Diagram(self, diagram):
if not diagram.premises:
# This is an empty diagram.
return self._print(S.EmptySet)
latex_result = self._print(diagram.premises)
if diagram.conclusions:
latex_result += "\\Longrightarrow %s" % \
self._print(diagram.conclusions)
return latex_result
def _print_DiagramGrid(self, grid):
latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width)
for i in range(grid.height):
for j in range(grid.width):
if grid[i, j]:
latex_result += latex(grid[i, j])
latex_result += " "
if j != grid.width - 1:
latex_result += "& "
if i != grid.height - 1:
latex_result += "\\\\"
latex_result += "\n"
latex_result += "\\end{array}\n"
return latex_result
def _print_FreeModule(self, M):
return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank))
def _print_FreeModuleElement(self, m):
# Print as row vector for convenience, for now.
return r"\left[ {} \right]".format(",".join(
'{' + self._print(x) + '}' for x in m))
def _print_SubModule(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for x in m.gens))
def _print_ModuleImplementedIdeal(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for [x] in m._module.gens))
def _print_Quaternion(self, expr):
# TODO: This expression is potentially confusing,
# shall we print it as `Quaternion( ... )`?
s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True)
for i in expr.args]
a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")]
return " + ".join(a)
def _print_QuotientRing(self, R):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(R.ring),
self._print(R.base_ideal))
def _print_QuotientRingElement(self, x):
return r"{{{}}} + {{{}}}".format(self._print(x.data),
self._print(x.ring.base_ideal))
def _print_QuotientModuleElement(self, m):
return r"{{{}}} + {{{}}}".format(self._print(m.data),
self._print(m.module.killed_module))
def _print_QuotientModule(self, M):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(M.base),
self._print(M.killed_module))
def _print_MatrixHomomorphism(self, h):
return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()),
self._print(h.domain), self._print(h.codomain))
def _print_Manifold(self, manifold):
string = manifold.name.name
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
name = r'\text{%s}' % name
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Patch(self, patch):
return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold))
def _print_CoordSystem(self, coordsys):
return r'\text{%s}^{\text{%s}}_{%s}' % (
self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold)
)
def _print_CovarDerivativeOp(self, cvd):
return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt)
def _print_BaseScalarField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\mathbf{{{}}}'.format(self._print(Symbol(string)))
def _print_BaseVectorField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\partial_{{{}}}'.format(self._print(Symbol(string)))
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
string = field._coord_sys.symbols[field._index].name
return r'\operatorname{{d}}{}'.format(self._print(Symbol(string)))
else:
string = self._print(field)
return r'\operatorname{{d}}\left({}\right)'.format(string)
def _print_Tr(self, p):
# TODO: Handle indices
contents = self._print(p.args[0])
return r'\operatorname{{tr}}\left({}\right)'.format(contents)
def _print_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\phi\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\phi\left(%s\right)' % self._print(expr.args[0])
def _print_reduced_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\lambda\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\lambda\left(%s\right)' % self._print(expr.args[0])
def _print_divisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^{%s}%s" % (exp, tex)
return r"\sigma%s" % tex
def _print_udivisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^*^{%s}%s" % (exp, tex)
return r"\sigma^*%s" % tex
def _print_primenu(self, expr, exp=None):
if exp is not None:
return r'\left(\nu\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\nu\left(%s\right)' % self._print(expr.args[0])
def _print_primeomega(self, expr, exp=None):
if exp is not None:
return r'\left(\Omega\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\Omega\left(%s\right)' % self._print(expr.args[0])
def _print_Str(self, s):
return str(s.name)
def _print_float(self, expr):
return self._print(Float(expr))
def _print_int(self, expr):
return str(expr)
def _print_mpz(self, expr):
return str(expr)
def _print_mpq(self, expr):
return str(expr)
def _print_Predicate(self, expr):
return r"\operatorname{{Q}}_{{\text{{{}}}}}".format(latex_escape(str(expr.name)))
def _print_AppliedPredicate(self, expr):
pred = expr.function
args = expr.arguments
pred_latex = self._print(pred)
args_latex = ', '.join([self._print(a) for a in args])
return '%s(%s)' % (pred_latex, args_latex)
def emptyPrinter(self, expr):
# default to just printing as monospace, like would normally be shown
s = super().emptyPrinter(expr)
return r"\mathtt{\text{%s}}" % latex_escape(s)
def translate(s: str) -> str:
r'''
Check for a modifier ending the string. If present, convert the
modifier to latex and translate the rest recursively.
Given a description of a Greek letter or other special character,
return the appropriate latex.
Let everything else pass as given.
>>> from sympy.printing.latex import translate
>>> translate('alphahatdotprime')
"{\\dot{\\hat{\\alpha}}}'"
'''
# Process the rest
tex = tex_greek_dictionary.get(s)
if tex:
return tex
elif s.lower() in greek_letters_set:
return "\\" + s.lower()
elif s in other_symbols:
return "\\" + s
else:
# Process modifiers, if any, and recurse
for key in sorted(modifier_dict.keys(), key=len, reverse=True):
if s.lower().endswith(key) and len(s) > len(key):
return modifier_dict[key](translate(s[:-len(key)]))
return s
@print_function(LatexPrinter)
def latex(expr, **settings):
r"""Convert the given expression to LaTeX string representation.
Parameters
==========
full_prec: boolean, optional
If set to True, a floating point number is printed with full precision.
fold_frac_powers : boolean, optional
Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers.
fold_func_brackets : boolean, optional
Fold function brackets where applicable.
fold_short_frac : boolean, optional
Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is
simple enough (at most two terms and no powers). The default value is
``True`` for inline mode, ``False`` otherwise.
inv_trig_style : string, optional
How inverse trig functions should be displayed. Can be one of
``'abbreviated'``, ``'full'``, or ``'power'``. Defaults to
``'abbreviated'``.
itex : boolean, optional
Specifies if itex-specific syntax is used, including emitting
``$$...$$``.
ln_notation : boolean, optional
If set to ``True``, ``\ln`` is used instead of default ``\log``.
long_frac_ratio : float or None, optional
The allowed ratio of the width of the numerator to the width of the
denominator before the printer breaks off long fractions. If ``None``
(the default value), long fractions are not broken up.
mat_delim : string, optional
The delimiter to wrap around matrices. Can be one of ``'['``, ``'('``,
or the empty string ``''``. Defaults to ``'['``.
mat_str : string, optional
Which matrix environment string to emit. ``'smallmatrix'``,
``'matrix'``, ``'array'``, etc. Defaults to ``'smallmatrix'`` for
inline mode, ``'matrix'`` for matrices of no more than 10 columns, and
``'array'`` otherwise.
mode: string, optional
Specifies how the generated code will be delimited. ``mode`` can be one
of ``'plain'``, ``'inline'``, ``'equation'`` or ``'equation*'``. If
``mode`` is set to ``'plain'``, then the resulting code will not be
delimited at all (this is the default). If ``mode`` is set to
``'inline'`` then inline LaTeX ``$...$`` will be used. If ``mode`` is
set to ``'equation'`` or ``'equation*'``, the resulting code will be
enclosed in the ``equation`` or ``equation*`` environment (remember to
import ``amsmath`` for ``equation*``), unless the ``itex`` option is
set. In the latter case, the ``$$...$$`` syntax is used.
mul_symbol : string or None, optional
The symbol to use for multiplication. Can be one of ``None``,
``'ldot'``, ``'dot'``, or ``'times'``.
order: string, optional
Any of the supported monomial orderings (currently ``'lex'``,
``'grlex'``, or ``'grevlex'``), ``'old'``, and ``'none'``. This
parameter does nothing for `~.Mul` objects. Setting order to ``'old'``
uses the compatibility ordering for ``~.Add`` defined in Printer. For
very large expressions, set the ``order`` keyword to ``'none'`` if
speed is a concern.
symbol_names : dictionary of strings mapped to symbols, optional
Dictionary of symbols and the custom strings they should be emitted as.
root_notation : boolean, optional
If set to ``False``, exponents of the form 1/n are printed in fractonal
form. Default is ``True``, to print exponent in root form.
mat_symbol_style : string, optional
Can be either ``'plain'`` (default) or ``'bold'``. If set to
``'bold'``, a `~.MatrixSymbol` A will be printed as ``\mathbf{A}``,
otherwise as ``A``.
imaginary_unit : string, optional
String to use for the imaginary unit. Defined options are ``'i'``
(default) and ``'j'``. Adding ``r`` or ``t`` in front gives ``\mathrm``
or ``\text``, so ``'ri'`` leads to ``\mathrm{i}`` which gives
`\mathrm{i}`.
gothic_re_im : boolean, optional
If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively.
The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`.
decimal_separator : string, optional
Specifies what separator to use to separate the whole and fractional parts of a
floating point number as in `2.5` for the default, ``period`` or `2{,}5`
when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon
separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when
``comma`` is chosen and [1,2,3] for when ``period`` is chosen.
parenthesize_super : boolean, optional
If set to ``False``, superscripted expressions will not be parenthesized when
powered. Default is ``True``, which parenthesizes the expression when powered.
min: Integer or None, optional
Sets the lower bound for the exponent to print floating point numbers in
fixed-point format.
max: Integer or None, optional
Sets the upper bound for the exponent to print floating point numbers in
fixed-point format.
diff_operator: string, optional
String to use for differential operator. Default is ``'d'``, to print in italic
form. ``'rd'``, ``'td'`` are shortcuts for ``\mathrm{d}`` and ``\text{d}``.
Notes
=====
Not using a print statement for printing, results in double backslashes for
latex commands since that's the way Python escapes backslashes in strings.
>>> from sympy import latex, Rational
>>> from sympy.abc import tau
>>> latex((2*tau)**Rational(7,2))
'8 \\sqrt{2} \\tau^{\\frac{7}{2}}'
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
Examples
========
>>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log
>>> from sympy.abc import x, y, mu, r, tau
Basic usage:
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
``mode`` and ``itex`` options:
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
Fraction options:
>>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True))
8 \sqrt{2} \tau^{7/2}
>>> print(latex((2*tau)**sin(Rational(7,2))))
\left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
>>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True))
\left(2 \tau\right)^{\sin {\frac{7}{2}}}
>>> print(latex(3*x**2/y))
\frac{3 x^{2}}{y}
>>> print(latex(3*x**2/y, fold_short_frac=True))
3 x^{2} / y
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2))
\frac{\int r\, dr}{2 \pi}
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0))
\frac{1}{2 \pi} \int r\, dr
Multiplication options:
>>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times"))
\left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
Trig options:
>>> print(latex(asin(Rational(7,2))))
\operatorname{asin}{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="full"))
\arcsin{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="power"))
\sin^{-1}{\left(\frac{7}{2} \right)}
Matrix options:
>>> print(latex(Matrix(2, 1, [x, y])))
\left[\begin{matrix}x\\y\end{matrix}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array"))
\left[\begin{array}{c}x\\y\end{array}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_delim="("))
\left(\begin{matrix}x\\y\end{matrix}\right)
Custom printing of symbols:
>>> print(latex(x**2, symbol_names={x: 'x_i'}))
x_i^{2}
Logarithms:
>>> print(latex(log(10)))
\log{\left(10 \right)}
>>> print(latex(log(10), ln_notation=True))
\ln{\left(10 \right)}
``latex()`` also supports the builtin container types :class:`list`,
:class:`tuple`, and :class:`dict`:
>>> print(latex([2/x, y], mode='inline'))
$\left[ 2 / x, \ y\right]$
Unsupported types are rendered as monospaced plaintext:
>>> print(latex(int))
\mathtt{\text{<class 'int'>}}
>>> print(latex("plain % text"))
\mathtt{\text{plain \% text}}
See :ref:`printer_method_example` for an example of how to override
this behavior for your own types by implementing ``_latex``.
.. versionchanged:: 1.7.0
Unsupported types no longer have their ``str`` representation treated as valid latex.
"""
return LatexPrinter(settings).doprint(expr)
def print_latex(expr, **settings):
"""Prints LaTeX representation of the given expression. Takes the same
settings as ``latex()``."""
print(latex(expr, **settings))
def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings):
r"""
This function generates a LaTeX equation with a multiline right-hand side
in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment.
Parameters
==========
lhs : Expr
Left-hand side of equation
rhs : Expr
Right-hand side of equation
terms_per_line : integer, optional
Number of terms per line to print. Default is 1.
environment : "string", optional
Which LaTeX wnvironment to use for the output. Options are "align*"
(default), "eqnarray", and "IEEEeqnarray".
use_dots : boolean, optional
If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``.
Examples
========
>>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I
>>> x, y, alpha = symbols('x y alpha')
>>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y))
>>> print(multiline_latex(x, expr))
\begin{align*}
x = & e^{i \alpha} \\
& + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using at most two terms per line:
>>> print(multiline_latex(x, expr, 2))
\begin{align*}
x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using ``eqnarray`` and dots:
>>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True))
\begin{eqnarray}
x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{eqnarray}
Using ``IEEEeqnarray``:
>>> print(multiline_latex(x, expr, environment="IEEEeqnarray"))
\begin{IEEEeqnarray}{rCl}
x & = & e^{i \alpha} \nonumber\\
& & + \sin{\left(\alpha y \right)} \nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{IEEEeqnarray}
Notes
=====
All optional parameters from ``latex`` can also be used.
"""
# Based on code from https://github.com/sympy/sympy/issues/3001
l = LatexPrinter(**settings)
if environment == "eqnarray":
result = r'\begin{eqnarray}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{eqnarray}'
doubleet = True
elif environment == "IEEEeqnarray":
result = r'\begin{IEEEeqnarray}{rCl}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{IEEEeqnarray}'
doubleet = True
elif environment == "align*":
result = r'\begin{align*}' + '\n'
first_term = '= &'
nonumber = ''
end_term = '\n\\end{align*}'
doubleet = False
else:
raise ValueError("Unknown environment: {}".format(environment))
dots = ''
if use_dots:
dots=r'\dots'
terms = rhs.as_ordered_terms()
n_terms = len(terms)
term_count = 1
for i in range(n_terms):
term = terms[i]
term_start = ''
term_end = ''
sign = '+'
if term_count > terms_per_line:
if doubleet:
term_start = '& & '
else:
term_start = '& '
term_count = 1
if term_count == terms_per_line:
# End of line
if i < n_terms-1:
# There are terms remaining
term_end = dots + nonumber + r'\\' + '\n'
else:
term_end = ''
if term.as_ordered_factors()[0] == -1:
term = -1*term
sign = r'-'
if i == 0: # beginning
if sign == '+':
sign = ''
result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs),
first_term, sign, l.doprint(term), term_end)
else:
result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign,
l.doprint(term), term_end)
term_count += 1
result += end_term
return result
|
22285dd6628f9341ae5052df422b1557fb4508f93e70bbd300ac60a83abc3d03 | """
Fortran code printer
The FCodePrinter converts single SymPy expressions into single Fortran
expressions, using the functions defined in the Fortran 77 standard where
possible. Some useful pointers to Fortran can be found on wikipedia:
https://en.wikipedia.org/wiki/Fortran
Most of the code below is based on the "Professional Programmer\'s Guide to
Fortran77" by Clive G. Page:
http://www.star.le.ac.uk/~cgp/prof77.html
Fortran is a case-insensitive language. This might cause trouble because
SymPy is case sensitive. So, fcode adds underscores to variable names when
it is necessary to make them different for Fortran.
"""
from typing import Dict as tDict, Any
from collections import defaultdict
from itertools import chain
import string
from sympy.codegen.ast import (
Assignment, Declaration, Pointer, value_const,
float32, float64, float80, complex64, complex128, int8, int16, int32,
int64, intc, real, integer, bool_, complex_
)
from sympy.codegen.fnodes import (
allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure,
intent_in, intent_out, intent_inout
)
from sympy.core import S, Add, N, Float, Symbol
from sympy.core.function import Function
from sympy.core.relational import Eq
from sympy.sets import Range
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
from sympy.printing.printer import printer_context
# These are defined in the other file so we can avoid importing sympy.codegen
# from the top-level 'import sympy'. Export them here as well.
from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401
known_functions = {
"sin": "sin",
"cos": "cos",
"tan": "tan",
"asin": "asin",
"acos": "acos",
"atan": "atan",
"atan2": "atan2",
"sinh": "sinh",
"cosh": "cosh",
"tanh": "tanh",
"log": "log",
"exp": "exp",
"erf": "erf",
"Abs": "abs",
"conjugate": "conjg",
"Max": "max",
"Min": "min",
}
class FCodePrinter(CodePrinter):
"""A printer to convert SymPy expressions to strings of Fortran code"""
printmethod = "_fcode"
language = "Fortran"
type_aliases = {
integer: int32,
real: float64,
complex_: complex128,
}
type_mappings = {
intc: 'integer(c_int)',
float32: 'real*4', # real(kind(0.e0))
float64: 'real*8', # real(kind(0.d0))
float80: 'real*10', # real(kind(????))
complex64: 'complex*8',
complex128: 'complex*16',
int8: 'integer*1',
int16: 'integer*2',
int32: 'integer*4',
int64: 'integer*8',
bool_: 'logical'
}
type_modules = {
intc: {'iso_c_binding': 'c_int'}
}
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 17,
'user_functions': {},
'human': True,
'allow_unknown_functions': False,
'source_format': 'fixed',
'contract': True,
'standard': 77,
'name_mangling' : True,
} # type: tDict[str, Any]
_operators = {
'and': '.and.',
'or': '.or.',
'xor': '.neqv.',
'equivalent': '.eqv.',
'not': '.not. ',
}
_relationals = {
'!=': '/=',
}
def __init__(self, settings=None):
if not settings:
settings = {}
self.mangled_symbols = {} # Dict showing mapping of all words
self.used_name = []
self.type_aliases = dict(chain(self.type_aliases.items(),
settings.pop('type_aliases', {}).items()))
self.type_mappings = dict(chain(self.type_mappings.items(),
settings.pop('type_mappings', {}).items()))
super().__init__(settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
# leading columns depend on fixed or free format
standards = {66, 77, 90, 95, 2003, 2008}
if self._settings['standard'] not in standards:
raise ValueError("Unknown Fortran standard: %s" % self._settings[
'standard'])
self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int
@property
def _lead(self):
if self._settings['source_format'] == 'fixed':
return {'code': " ", 'cont': " @ ", 'comment': "C "}
elif self._settings['source_format'] == 'free':
return {'code': "", 'cont': " ", 'comment': "! "}
else:
raise ValueError("Unknown source format: %s" % self._settings['source_format'])
def _print_Symbol(self, expr):
if self._settings['name_mangling'] == True:
if expr not in self.mangled_symbols:
name = expr.name
while name.lower() in self.used_name:
name += '_'
self.used_name.append(name.lower())
if name == expr.name:
self.mangled_symbols[expr] = expr
else:
self.mangled_symbols[expr] = Symbol(name)
expr = expr.xreplace(self.mangled_symbols)
name = super()._print_Symbol(expr)
return name
def _rate_index_position(self, p):
return -p*5
def _get_statement(self, codestring):
return codestring
def _get_comment(self, text):
return "! {}".format(text)
def _declare_number_const(self, name, value):
return "parameter ({} = {})".format(name, self._print(value))
def _print_NumberSymbol(self, expr):
# A Number symbol that is not implemented here or with _printmethod
# is registered and evaluated
self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision']))))
return str(expr)
def _format_code(self, lines):
return self._wrap_fortran(self.indent_code(lines))
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for j in range(cols) for i in range(rows))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
for i in indices:
# fortran arrays start at 1 and end at dimension
var, start, stop = map(self._print,
[i.label, i.lower + 1, i.upper + 1])
open_lines.append("do %s = %s, %s" % (var, start, stop))
close_lines.append("end do")
return open_lines, close_lines
def _print_sign(self, expr):
from sympy.functions.elementary.complexes import Abs
arg, = expr.args
if arg.is_integer:
new_expr = merge(0, isign(1, arg), Eq(arg, 0))
elif (arg.is_complex or arg.is_infinite):
new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0)))
else:
new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0)))
return self._print(new_expr)
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if expr.has(Assignment):
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s) then" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else")
else:
lines.append("else if (%s) then" % self._print(c))
lines.append(self._print(e))
lines.append("end if")
return "\n".join(lines)
elif self._settings["standard"] >= 95:
# Only supported in F95 and newer:
# The piecewise was used in an expression, need to do inline
# operators. This has the downside that inline operators will
# not work for statements that span multiple lines (Matrix or
# Indexed expressions).
pattern = "merge({T}, {F}, {COND})"
code = self._print(expr.args[-1].expr)
terms = list(expr.args[:-1])
while terms:
e, c = terms.pop()
expr = self._print(e)
cond = self._print(c)
code = pattern.format(T=expr, F=code, COND=cond)
return code
else:
# `merge` is not supported prior to F95
raise NotImplementedError("Using Piecewise as an expression using "
"inline operators is not supported in "
"standards earlier than Fortran95.")
def _print_MatrixElement(self, expr):
return "{}({}, {})".format(self.parenthesize(expr.parent,
PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1)
def _print_Add(self, expr):
# purpose: print complex numbers nicely in Fortran.
# collect the purely real and purely imaginary parts:
pure_real = []
pure_imaginary = []
mixed = []
for arg in expr.args:
if arg.is_number and arg.is_real:
pure_real.append(arg)
elif arg.is_number and arg.is_imaginary:
pure_imaginary.append(arg)
else:
mixed.append(arg)
if pure_imaginary:
if mixed:
PREC = precedence(expr)
term = Add(*mixed)
t = self._print(term)
if t.startswith('-'):
sign = "-"
t = t[1:]
else:
sign = "+"
if precedence(term) < PREC:
t = "(%s)" % t
return "cmplx(%s,%s) %s %s" % (
self._print(Add(*pure_real)),
self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
sign, t,
)
else:
return "cmplx(%s,%s)" % (
self._print(Add(*pure_real)),
self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
)
else:
return CodePrinter._print_Add(self, expr)
def _print_Function(self, expr):
# All constant function args are evaluated as floats
prec = self._settings['precision']
args = [N(a, prec) for a in expr.args]
eval_expr = expr.func(*args)
if not isinstance(eval_expr, Function):
return self._print(eval_expr)
else:
return CodePrinter._print_Function(self, expr.func(*args))
def _print_Mod(self, expr):
# NOTE : Fortran has the functions mod() and modulo(). modulo() behaves
# the same wrt to the sign of the arguments as Python and SymPy's
# modulus computations (% and Mod()) but is not available in Fortran 66
# or Fortran 77, thus we raise an error.
if self._settings['standard'] in [66, 77]:
msg = ("Python % operator and SymPy's Mod() function are not "
"supported by Fortran 66 or 77 standards.")
raise NotImplementedError(msg)
else:
x, y = expr.args
return " modulo({}, {})".format(self._print(x), self._print(y))
def _print_ImaginaryUnit(self, expr):
# purpose: print complex numbers nicely in Fortran.
return "cmplx(0,1)"
def _print_int(self, expr):
return str(expr)
def _print_Mul(self, expr):
# purpose: print complex numbers nicely in Fortran.
if expr.is_number and expr.is_imaginary:
return "cmplx(0,%s)" % (
self._print(-S.ImaginaryUnit*expr)
)
else:
return CodePrinter._print_Mul(self, expr)
def _print_Pow(self, expr):
PREC = precedence(expr)
if expr.exp == -1:
return '%s/%s' % (
self._print(literal_dp(1)),
self.parenthesize(expr.base, PREC)
)
elif expr.exp == 0.5:
if expr.base.is_integer:
# Fortran intrinsic sqrt() does not accept integer argument
if expr.base.is_Number:
return 'sqrt(%s.0d0)' % self._print(expr.base)
else:
return 'sqrt(dble(%s))' % self._print(expr.base)
else:
return 'sqrt(%s)' % self._print(expr.base)
else:
return CodePrinter._print_Pow(self, expr)
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return "%d.0d0/%d.0d0" % (p, q)
def _print_Float(self, expr):
printed = CodePrinter._print_Float(self, expr)
e = printed.find('e')
if e > -1:
return "%sd%s" % (printed[:e], printed[e + 1:])
return "%sd0" % printed
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
op = op if op not in self._relationals else self._relationals[op]
return "{} {} {}".format(lhs_code, op, rhs_code)
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_AugmentedAssignment(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
return self._get_statement("{0} = {0} {1} {2}".format(
*map(lambda arg: self._print(arg),
[lhs_code, expr.binop, rhs_code])))
def _print_sum_(self, sm):
params = self._print(sm.array)
if sm.dim != None: # Must use '!= None', cannot use 'is not None'
params += ', ' + self._print(sm.dim)
if sm.mask != None: # Must use '!= None', cannot use 'is not None'
params += ', mask=' + self._print(sm.mask)
return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params)
def _print_product_(self, prod):
return self._print_sum_(prod)
def _print_Do(self, do):
excl = ['concurrent']
if do.step == 1:
excl.append('step')
step = ''
else:
step = ', {step}'
return (
'do {concurrent}{counter} = {first}, {last}'+step+'\n'
'{body}\n'
'end do\n'
).format(
concurrent='concurrent ' if do.concurrent else '',
**do.kwargs(apply=lambda arg: self._print(arg), exclude=excl)
)
def _print_ImpliedDoLoop(self, idl):
step = '' if idl.step == 1 else ', {step}'
return ('({expr}, {counter} = {first}, {last}'+step+')').format(
**idl.kwargs(apply=lambda arg: self._print(arg))
)
def _print_For(self, expr):
target = self._print(expr.target)
if isinstance(expr.iterable, Range):
start, stop, step = expr.iterable.args
else:
raise NotImplementedError("Only iterable currently supported is Range")
body = self._print(expr.body)
return ('do {target} = {start}, {stop}, {step}\n'
'{body}\n'
'end do').format(target=target, start=start, stop=stop - 1,
step=step, body=body)
def _print_Type(self, type_):
type_ = self.type_aliases.get(type_, type_)
type_str = self.type_mappings.get(type_, type_.name)
module_uses = self.type_modules.get(type_)
if module_uses:
for k, v in module_uses:
self.module_uses[k].add(v)
return type_str
def _print_Element(self, elem):
return '{symbol}({idxs})'.format(
symbol=self._print(elem.symbol),
idxs=', '.join(map(lambda arg: self._print(arg), elem.indices))
)
def _print_Extent(self, ext):
return str(ext)
def _print_Declaration(self, expr):
var = expr.variable
val = var.value
dim = var.attr_params('dimension')
intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)]
if intents.count(True) == 0:
intent = ''
elif intents.count(True) == 1:
intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)]
else:
raise ValueError("Multiple intents specified for %s" % self)
if isinstance(var, Pointer):
raise NotImplementedError("Pointers are not available by default in Fortran.")
if self._settings["standard"] >= 90:
result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format(
t=self._print(var.type),
vc=', parameter' if value_const in var.attrs else '',
dim=', dimension(%s)' % ', '.join(map(lambda arg: self._print(arg), dim)) if dim else '',
intent=intent,
alloc=', allocatable' if allocatable in var.attrs else '',
s=self._print(var.symbol)
)
if val != None: # Must be "!= None", cannot be "is not None"
result += ' = %s' % self._print(val)
else:
if value_const in var.attrs or val:
raise NotImplementedError("F77 init./parameter statem. req. multiple lines.")
result = ' '.join(map(lambda arg: self._print(arg), [var.type, var.symbol]))
return result
def _print_Infinity(self, expr):
return '(huge(%s) + 1)' % self._print(literal_dp(0))
def _print_While(self, expr):
return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs(
apply=lambda arg: self._print(arg)))
def _print_BooleanTrue(self, expr):
return '.true.'
def _print_BooleanFalse(self, expr):
return '.false.'
def _pad_leading_columns(self, lines):
result = []
for line in lines:
if line.startswith('!'):
result.append(self._lead['comment'] + line[1:].lstrip())
else:
result.append(self._lead['code'] + line)
return result
def _wrap_fortran(self, lines):
"""Wrap long Fortran lines
Argument:
lines -- a list of lines (without \\n character)
A comment line is split at white space. Code lines are split with a more
complex rule to give nice results.
"""
# routine to find split point in a code line
my_alnum = set("_+-." + string.digits + string.ascii_letters)
my_white = set(" \t()")
def split_pos_code(line, endpos):
if len(line) <= endpos:
return len(line)
pos = endpos
split = lambda pos: \
(line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \
(line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \
(line[pos] in my_white and line[pos - 1] not in my_white) or \
(line[pos] not in my_white and line[pos - 1] in my_white)
while not split(pos):
pos -= 1
if pos == 0:
return endpos
return pos
# split line by line and add the split lines to result
result = []
if self._settings['source_format'] == 'free':
trailing = ' &'
else:
trailing = ''
for line in lines:
if line.startswith(self._lead['comment']):
# comment line
if len(line) > 72:
pos = line.rfind(" ", 6, 72)
if pos == -1:
pos = 72
hunk = line[:pos]
line = line[pos:].lstrip()
result.append(hunk)
while line:
pos = line.rfind(" ", 0, 66)
if pos == -1 or len(line) < 66:
pos = 66
hunk = line[:pos]
line = line[pos:].lstrip()
result.append("%s%s" % (self._lead['comment'], hunk))
else:
result.append(line)
elif line.startswith(self._lead['code']):
# code line
pos = split_pos_code(line, 72)
hunk = line[:pos].rstrip()
line = line[pos:].lstrip()
if line:
hunk += trailing
result.append(hunk)
while line:
pos = split_pos_code(line, 65)
hunk = line[:pos].rstrip()
line = line[pos:].lstrip()
if line:
hunk += trailing
result.append("%s%s" % (self._lead['cont'], hunk))
else:
result.append(line)
return result
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
free = self._settings['source_format'] == 'free'
code = [ line.lstrip(' \t') for line in code ]
inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface')
dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface')
increase = [ int(any(map(line.startswith, inc_keyword)))
for line in code ]
decrease = [ int(any(map(line.startswith, dec_keyword)))
for line in code ]
continuation = [ int(any(map(line.endswith, ['&', '&\n'])))
for line in code ]
level = 0
cont_padding = 0
tabwidth = 3
new_code = []
for i, line in enumerate(code):
if line in ('', '\n'):
new_code.append(line)
continue
level -= decrease[i]
if free:
padding = " "*(level*tabwidth + cont_padding)
else:
padding = " "*level*tabwidth
line = "%s%s" % (padding, line)
if not free:
line = self._pad_leading_columns([line])[0]
new_code.append(line)
if continuation[i]:
cont_padding = 2*tabwidth
else:
cont_padding = 0
level += increase[i]
if not free:
return self._wrap_fortran(new_code)
return new_code
def _print_GoTo(self, goto):
if goto.expr: # computed goto
return "go to ({labels}), {expr}".format(
labels=', '.join(map(lambda arg: self._print(arg), goto.labels)),
expr=self._print(goto.expr)
)
else:
lbl, = goto.labels
return "go to %s" % self._print(lbl)
def _print_Program(self, prog):
return (
"program {name}\n"
"{body}\n"
"end program\n"
).format(**prog.kwargs(apply=lambda arg: self._print(arg)))
def _print_Module(self, mod):
return (
"module {name}\n"
"{declarations}\n"
"\ncontains\n\n"
"{definitions}\n"
"end module\n"
).format(**mod.kwargs(apply=lambda arg: self._print(arg)))
def _print_Stream(self, strm):
if strm.name == 'stdout' and self._settings["standard"] >= 2003:
self.module_uses['iso_c_binding'].add('stdint=>input_unit')
return 'input_unit'
elif strm.name == 'stderr' and self._settings["standard"] >= 2003:
self.module_uses['iso_c_binding'].add('stdint=>error_unit')
return 'error_unit'
else:
if strm.name == 'stdout':
return '*'
else:
return strm.name
def _print_Print(self, ps):
if ps.format_string != None: # Must be '!= None', cannot be 'is not None'
fmt = self._print(ps.format_string)
else:
fmt = "*"
return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join(
map(lambda arg: self._print(arg), ps.print_args)))
def _print_Return(self, rs):
arg, = rs.args
return "{result_name} = {arg}".format(
result_name=self._context.get('result_name', 'sympy_result'),
arg=self._print(arg)
)
def _print_FortranReturn(self, frs):
arg, = frs.args
if arg:
return 'return %s' % self._print(arg)
else:
return 'return'
def _head(self, entity, fp, **kwargs):
bind_C_params = fp.attr_params('bind_C')
if bind_C_params is None:
bind = ''
else:
bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)'
result_name = self._settings.get('result_name', None)
return (
"{entity}{name}({arg_names}){result}{bind}\n"
"{arg_declarations}"
).format(
entity=entity,
name=self._print(fp.name),
arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]),
result=(' result(%s)' % result_name) if result_name else '',
bind=bind,
arg_declarations='\n'.join(map(lambda arg: self._print(Declaration(arg)), fp.parameters))
)
def _print_FunctionPrototype(self, fp):
entity = "{} function ".format(self._print(fp.return_type))
return (
"interface\n"
"{function_head}\n"
"end function\n"
"end interface"
).format(function_head=self._head(entity, fp))
def _print_FunctionDefinition(self, fd):
if elemental in fd.attrs:
prefix = 'elemental '
elif pure in fd.attrs:
prefix = 'pure '
else:
prefix = ''
entity = "{} function ".format(self._print(fd.return_type))
with printer_context(self, result_name=fd.name):
return (
"{prefix}{function_head}\n"
"{body}\n"
"end function\n"
).format(
prefix=prefix,
function_head=self._head(entity, fd),
body=self._print(fd.body)
)
def _print_Subroutine(self, sub):
return (
'{subroutine_head}\n'
'{body}\n'
'end subroutine\n'
).format(
subroutine_head=self._head('subroutine ', sub),
body=self._print(sub.body)
)
def _print_SubroutineCall(self, scall):
return 'call {name}({args})'.format(
name=self._print(scall.name),
args=', '.join(map(lambda arg: self._print(arg), scall.subroutine_args))
)
def _print_use_rename(self, rnm):
return "%s => %s" % tuple(map(lambda arg: self._print(arg), rnm.args))
def _print_use(self, use):
result = 'use %s' % self._print(use.namespace)
if use.rename != None: # Must be '!= None', cannot be 'is not None'
result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename])
if use.only != None: # Must be '!= None', cannot be 'is not None'
result += ', only: ' + ', '.join([self._print(nly) for nly in use.only])
return result
def _print_BreakToken(self, _):
return 'exit'
def _print_ContinueToken(self, _):
return 'cycle'
def _print_ArrayConstructor(self, ac):
fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)'
return fmtstr % ', '.join(map(lambda arg: self._print(arg), ac.elements))
def _print_ArrayElement(self, elem):
return '{symbol}({idxs})'.format(
symbol=self._print(elem.name),
idxs=', '.join(map(lambda arg: self._print(arg), elem.indices))
)
|
6c22760dca62874e073136b7588c8458afd533a7bb1e00db526a1346cd492361 | """
R code printer
The RCodePrinter converts single SymPy expressions into single R expressions,
using the functions defined in math.h where possible.
"""
from typing import Any, Dict as tDict
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
from sympy.sets.fancysets import Range
# dictionary mapping SymPy function to (argument_conditions, C_function).
# Used in RCodePrinter._print_Function(self)
known_functions = {
#"Abs": [(lambda x: not x.is_integer, "fabs")],
"Abs": "abs",
"sin": "sin",
"cos": "cos",
"tan": "tan",
"asin": "asin",
"acos": "acos",
"atan": "atan",
"atan2": "atan2",
"exp": "exp",
"log": "log",
"erf": "erf",
"sinh": "sinh",
"cosh": "cosh",
"tanh": "tanh",
"asinh": "asinh",
"acosh": "acosh",
"atanh": "atanh",
"floor": "floor",
"ceiling": "ceiling",
"sign": "sign",
"Max": "max",
"Min": "min",
"factorial": "factorial",
"gamma": "gamma",
"digamma": "digamma",
"trigamma": "trigamma",
"beta": "beta",
"sqrt": "sqrt", # To enable automatic rewrite
}
# These are the core reserved words in the R language. Taken from:
# https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words
reserved_words = ['if',
'else',
'repeat',
'while',
'function',
'for',
'in',
'next',
'break',
'TRUE',
'FALSE',
'NULL',
'Inf',
'NaN',
'NA',
'NA_integer_',
'NA_real_',
'NA_complex_',
'NA_character_',
'volatile']
class RCodePrinter(CodePrinter):
"""A printer to convert SymPy expressions to strings of R code"""
printmethod = "_rcode"
language = "R"
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 15,
'user_functions': {},
'human': True,
'contract': True,
'dereference': set(),
'error_on_reserved': False,
'reserved_word_suffix': '_',
} # type: tDict[str, Any]
_operators = {
'and': '&',
'or': '|',
'not': '!',
}
_relationals = {
} # type: tDict[str, str]
def __init__(self, settings={}):
CodePrinter.__init__(self, settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
self._dereference = set(settings.get('dereference', []))
self.reserved_words = set(reserved_words)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "// {}".format(text)
def _declare_number_const(self, name, value):
return "{} = {};".format(name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for i in range(rows) for j in range(cols))
def _get_loop_opening_ending(self, indices):
"""Returns a tuple (open_lines, close_lines) containing lists of codelines
"""
open_lines = []
close_lines = []
loopstart = "for (%(var)s in %(start)s:%(end)s){"
for i in indices:
# R arrays start at 1 and end at dimension
open_lines.append(loopstart % {
'var': self._print(i.label),
'start': self._print(i.lower+1),
'end': self._print(i.upper + 1)})
close_lines.append("}")
return open_lines, close_lines
def _print_Pow(self, expr):
if "Pow" in self.known_functions:
return self._print_Function(expr)
PREC = precedence(expr)
if expr.exp == -1:
return '1.0/%s' % (self.parenthesize(expr.base, PREC))
elif expr.exp == 0.5:
return 'sqrt(%s)' % self._print(expr.base)
else:
return '%s^%s' % (self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC))
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return '%d.0/%d.0' % (p, q)
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s[%s]" % (self._print(expr.base.label), ", ".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_Exp1(self, expr):
return "exp(1)"
def _print_Pi(self, expr):
return 'pi'
def _print_Infinity(self, expr):
return 'Inf'
def _print_NegativeInfinity(self, expr):
return '-Inf'
def _print_Assignment(self, expr):
from sympy.codegen.ast import Assignment
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.tensor.indexed import IndexedBase
lhs = expr.lhs
rhs = expr.rhs
# We special case assignments that take multiple lines
#if isinstance(expr.rhs, Piecewise):
# from sympy.functions.elementary.piecewise import Piecewise
# # Here we modify Piecewise so each expression is now
# # an Assignment, and then continue on the print.
# expressions = []
# conditions = []
# for (e, c) in rhs.args:
# expressions.append(Assignment(lhs, e))
# conditions.append(c)
# temp = Piecewise(*zip(expressions, conditions))
# return self._print(temp)
#elif isinstance(lhs, MatrixSymbol):
if isinstance(lhs, MatrixSymbol):
# Here we form an Assignment for each element in the array,
# printing each one.
lines = []
for (i, j) in self._traverse_matrix_indices(lhs):
temp = Assignment(lhs[i, j], rhs[i, j])
code0 = self._print(temp)
lines.append(code0)
return "\n".join(lines)
elif self._settings["contract"] and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
# Here we check if there is looping to be done, and if so
# print the required loops.
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def _print_Piecewise(self, expr):
# This method is called only for inline if constructs
# Top level piecewise is handled in doprint()
if expr.args[-1].cond == True:
last_line = "%s" % self._print(expr.args[-1].expr)
else:
last_line = "ifelse(%s,%s,NA)" % (self._print(expr.args[-1].cond), self._print(expr.args[-1].expr))
code=last_line
for e, c in reversed(expr.args[:-1]):
code= "ifelse(%s,%s," % (self._print(c), self._print(e))+code+")"
return(code)
def _print_ITE(self, expr):
from sympy.functions import Piecewise
return self._print(expr.rewrite(Piecewise))
def _print_MatrixElement(self, expr):
return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
strict=True), expr.j + expr.i*expr.parent.shape[1])
def _print_Symbol(self, expr):
name = super()._print_Symbol(expr)
if expr in self._dereference:
return '(*{})'.format(name)
else:
return name
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{} {} {}".format(lhs_code, op, rhs_code)
def _print_AugmentedAssignment(self, expr):
lhs_code = self._print(expr.lhs)
op = expr.op
rhs_code = self._print(expr.rhs)
return "{} {} {};".format(lhs_code, op, rhs_code)
def _print_For(self, expr):
target = self._print(expr.target)
if isinstance(expr.iterable, Range):
start, stop, step = expr.iterable.args
else:
raise NotImplementedError("Only iterable currently supported is Range")
body = self._print(expr.body)
return 'for({target} in seq(from={start}, to={stop}, by={step}){{\n{body}\n}}'.format(target=target, start=start,
stop=stop-1, step=step, body=body)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_token = ('{', '(', '{\n', '(\n')
dec_token = ('}', ')')
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
decrease = [ int(any(map(line.startswith, dec_token)))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line in ('', '\n'):
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def rcode(expr, assign_to=None, **settings):
"""Converts an expr to a string of r code
Parameters
==========
expr : Expr
A SymPy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
line-wrapping, or for expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=15].
user_functions : dict, optional
A dictionary where the keys are string representations of either
``FunctionClass`` or ``UndefinedFunction`` instances and the values
are their desired R string representations. Alternatively, the
dictionary value can be a list of tuples i.e. [(argument_test,
rfunction_string)] or [(argument_test, rfunction_formater)]. See below
for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
Examples
========
>>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> rcode((2*tau)**Rational(7, 2))
'8*sqrt(2)*tau^(7.0/2.0)'
>>> rcode(sin(x), assign_to="s")
's = sin(x);'
Simple custom printing can be defined for certain types by passing a
dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
Alternatively, the dictionary value can be a list of tuples i.e.
[(argument_test, cfunction_string)].
>>> custom_functions = {
... "ceiling": "CEIL",
... "Abs": [(lambda x: not x.is_integer, "fabs"),
... (lambda x: x.is_integer, "ABS")],
... "func": "f"
... }
>>> func = Function('func')
>>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
'f(fabs(x) + CEIL(x))'
or if the R-function takes a subset of the original arguments:
>>> rcode(2**x + 3**x, user_functions={'Pow': [
... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
... (lambda b, e: b != 2, 'pow')]})
'exp2(x) + pow(3, x)'
``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.
>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(rcode(expr, assign_to=tau))
tau = ifelse(x > 0,x + 1,x);
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> rcode(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
must be provided to ``assign_to``. Note that any expression that can be
generated normally can also exist inside a Matrix:
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(rcode(mat, A))
A[0] = x^2;
A[1] = ifelse(x > 0,x + 1,x);
A[2] = sin(x);
"""
return RCodePrinter(settings).doprint(expr, assign_to)
def print_rcode(expr, **settings):
"""Prints R representation of the given expression."""
print(rcode(expr, **settings))
|
68a8134c643729a8e6fa98f4f4388f30981776d9a3901bdd93e67188c8e2dd85 | from typing import Any, Dict as tDict
from sympy.external import import_module
from sympy.printing.printer import Printer
from sympy.utilities.iterables import is_sequence
import sympy
from functools import partial
aesara = import_module('aesara')
if aesara:
aes = aesara.scalar
aet = aesara.tensor
from aesara.tensor import nlinalg
from aesara.tensor.elemwise import Elemwise
from aesara.tensor.elemwise import DimShuffle
mapping = {
sympy.Add: aet.add,
sympy.Mul: aet.mul,
sympy.Abs: aet.abs,
sympy.sign: aet.sgn,
sympy.ceiling: aet.ceil,
sympy.floor: aet.floor,
sympy.log: aet.log,
sympy.exp: aet.exp,
sympy.sqrt: aet.sqrt,
sympy.cos: aet.cos,
sympy.acos: aet.arccos,
sympy.sin: aet.sin,
sympy.asin: aet.arcsin,
sympy.tan: aet.tan,
sympy.atan: aet.arctan,
sympy.atan2: aet.arctan2,
sympy.cosh: aet.cosh,
sympy.acosh: aet.arccosh,
sympy.sinh: aet.sinh,
sympy.asinh: aet.arcsinh,
sympy.tanh: aet.tanh,
sympy.atanh: aet.arctanh,
sympy.re: aet.real,
sympy.im: aet.imag,
sympy.arg: aet.angle,
sympy.erf: aet.erf,
sympy.gamma: aet.gamma,
sympy.loggamma: aet.gammaln,
sympy.Pow: aet.pow,
sympy.Eq: aet.eq,
sympy.StrictGreaterThan: aet.gt,
sympy.StrictLessThan: aet.lt,
sympy.LessThan: aet.le,
sympy.GreaterThan: aet.ge,
sympy.And: aet.bitwise_and, # bitwise
sympy.Or: aet.bitwise_or, # bitwise
sympy.Not: aet.invert, # bitwise
sympy.Xor: aet.bitwise_xor, # bitwise
sympy.Max: aet.maximum, # Sympy accept >2 inputs, Aesara only 2
sympy.Min: aet.minimum, # Sympy accept >2 inputs, Aesara only 2
sympy.conjugate: aet.conj,
sympy.core.numbers.ImaginaryUnit: lambda:aet.complex(0,1),
# Matrices
sympy.MatAdd: Elemwise(aes.add),
sympy.HadamardProduct: Elemwise(aes.mul),
sympy.Trace: nlinalg.trace,
sympy.Determinant : nlinalg.det,
sympy.Inverse: nlinalg.matrix_inverse,
sympy.Transpose: DimShuffle((False, False), [1, 0]),
}
class AesaraPrinter(Printer):
""" Code printer which creates Aesara symbolic expression graphs.
Parameters
==========
cache : dict
Cache dictionary to use. If None (default) will use
the global cache. To create a printer which does not depend on or alter
global state pass an empty dictionary. Note: the dictionary is not
copied on initialization of the printer and will be updated in-place,
so using the same dict object when creating multiple printers or making
multiple calls to :func:`.aesara_code` or :func:`.aesara_function` means
the cache is shared between all these applications.
Attributes
==========
cache : dict
A cache of Aesara variables which have been created for SymPy
symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or
:class:`sympy.matrices.expressions.MatrixSymbol`). This is used to
ensure that all references to a given symbol in an expression (or
multiple expressions) are printed as the same Aesara variable, which is
created only once. Symbols are differentiated only by name and type. The
format of the cache's contents should be considered opaque to the user.
"""
printmethod = "_aesara"
def __init__(self, *args, **kwargs):
self.cache = kwargs.pop('cache', {})
super().__init__(*args, **kwargs)
def _get_key(self, s, name=None, dtype=None, broadcastable=None):
""" Get the cache key for a SymPy object.
Parameters
==========
s : sympy.core.basic.Basic
SymPy object to get key for.
name : str
Name of object, if it does not have a ``name`` attribute.
"""
if name is None:
name = s.name
return (name, type(s), s.args, dtype, broadcastable)
def _get_or_create(self, s, name=None, dtype=None, broadcastable=None):
"""
Get the Aesara variable for a SymPy symbol from the cache, or create it
if it does not exist.
"""
# Defaults
if name is None:
name = s.name
if dtype is None:
dtype = 'floatX'
if broadcastable is None:
broadcastable = ()
key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable)
if key in self.cache:
return self.cache[key]
value = aet.tensor(name=name, dtype=dtype, broadcastable=broadcastable)
self.cache[key] = value
return value
def _print_Symbol(self, s, **kwargs):
dtype = kwargs.get('dtypes', {}).get(s)
bc = kwargs.get('broadcastables', {}).get(s)
return self._get_or_create(s, dtype=dtype, broadcastable=bc)
def _print_AppliedUndef(self, s, **kwargs):
name = str(type(s)) + '_' + str(s.args[0])
dtype = kwargs.get('dtypes', {}).get(s)
bc = kwargs.get('broadcastables', {}).get(s)
return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc)
def _print_Basic(self, expr, **kwargs):
op = mapping[type(expr)]
children = [self._print(arg, **kwargs) for arg in expr.args]
return op(*children)
def _print_Number(self, n, **kwargs):
# Integers already taken care of below, interpret as float
return float(n.evalf())
def _print_MatrixSymbol(self, X, **kwargs):
dtype = kwargs.get('dtypes', {}).get(X)
return self._get_or_create(X, dtype=dtype, broadcastable=(None, None))
def _print_DenseMatrix(self, X, **kwargs):
if not hasattr(aet, 'stacklists'):
raise NotImplementedError(
"Matrix translation not yet supported in this version of Aesara")
return aet.stacklists([
[self._print(arg, **kwargs) for arg in L]
for L in X.tolist()
])
_print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix
def _print_MatMul(self, expr, **kwargs):
children = [self._print(arg, **kwargs) for arg in expr.args]
result = children[0]
for child in children[1:]:
result = aet.dot(result, child)
return result
def _print_MatPow(self, expr, **kwargs):
children = [self._print(arg, **kwargs) for arg in expr.args]
result = 1
if isinstance(children[1], int) and children[1] > 0:
for i in range(children[1]):
result = aet.dot(result, children[0])
else:
raise NotImplementedError('''Only non-negative integer
powers of matrices can be handled by Aesara at the moment''')
return result
def _print_MatrixSlice(self, expr, **kwargs):
parent = self._print(expr.parent, **kwargs)
rowslice = self._print(slice(*expr.rowslice), **kwargs)
colslice = self._print(slice(*expr.colslice), **kwargs)
return parent[rowslice, colslice]
def _print_BlockMatrix(self, expr, **kwargs):
nrows, ncols = expr.blocks.shape
blocks = [[self._print(expr.blocks[r, c], **kwargs)
for c in range(ncols)]
for r in range(nrows)]
return aet.join(0, *[aet.join(1, *row) for row in blocks])
def _print_slice(self, expr, **kwargs):
return slice(*[self._print(i, **kwargs)
if isinstance(i, sympy.Basic) else i
for i in (expr.start, expr.stop, expr.step)])
def _print_Pi(self, expr, **kwargs):
return 3.141592653589793
def _print_Piecewise(self, expr, **kwargs):
import numpy as np
e, cond = expr.args[0].args # First condition and corresponding value
# Print conditional expression and value for first condition
p_cond = self._print(cond, **kwargs)
p_e = self._print(e, **kwargs)
# One condition only
if len(expr.args) == 1:
# Return value if condition else NaN
return aet.switch(p_cond, p_e, np.nan)
# Return value_1 if condition_1 else evaluate remaining conditions
p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs)
return aet.switch(p_cond, p_e, p_remaining)
def _print_Rational(self, expr, **kwargs):
return aet.true_div(self._print(expr.p, **kwargs),
self._print(expr.q, **kwargs))
def _print_Integer(self, expr, **kwargs):
return expr.p
def _print_factorial(self, expr, **kwargs):
return self._print(sympy.gamma(expr.args[0] + 1), **kwargs)
def _print_Derivative(self, deriv, **kwargs):
from aesara.gradient import Rop
rv = self._print(deriv.expr, **kwargs)
for var in deriv.variables:
var = self._print(var, **kwargs)
rv = Rop(rv, var, aet.ones_like(var))
return rv
def emptyPrinter(self, expr):
return expr
def doprint(self, expr, dtypes=None, broadcastables=None):
""" Convert a SymPy expression to a Aesara graph variable.
The ``dtypes`` and ``broadcastables`` arguments are used to specify the
data type, dimension, and broadcasting behavior of the Aesara variables
corresponding to the free symbols in ``expr``. Each is a mapping from
SymPy symbols to the value of the corresponding argument to
``aesara.tensor.var.TensorVariable``.
See the corresponding `documentation page`__ for more information on
broadcasting in Aesara.
.. __: https://aesara.readthedocs.io/en/latest/tutorial/broadcasting.html
Parameters
==========
expr : sympy.core.expr.Expr
SymPy expression to print.
dtypes : dict
Mapping from SymPy symbols to Aesara datatypes to use when creating
new Aesara variables for those symbols. Corresponds to the ``dtype``
argument to ``aesara.tensor.var.TensorVariable``. Defaults to ``'floatX'``
for symbols not included in the mapping.
broadcastables : dict
Mapping from SymPy symbols to the value of the ``broadcastable``
argument to ``aesara.tensor.var.TensorVariable`` to use when creating Aesara
variables for those symbols. Defaults to the empty tuple for symbols
not included in the mapping (resulting in a scalar).
Returns
=======
aesara.graph.basic.Variable
A variable corresponding to the expression's value in a Aesara
symbolic expression graph.
"""
if dtypes is None:
dtypes = {}
if broadcastables is None:
broadcastables = {}
return self._print(expr, dtypes=dtypes, broadcastables=broadcastables)
global_cache = {} # type: tDict[Any, Any]
def aesara_code(expr, cache=None, **kwargs):
"""
Convert a SymPy expression into a Aesara graph variable.
Parameters
==========
expr : sympy.core.expr.Expr
SymPy expression object to convert.
cache : dict
Cached Aesara variables (see :class:`AesaraPrinter.cache
<AesaraPrinter>`). Defaults to the module-level global cache.
dtypes : dict
Passed to :meth:`.AesaraPrinter.doprint`.
broadcastables : dict
Passed to :meth:`.AesaraPrinter.doprint`.
Returns
=======
aesara.graph.basic.Variable
A variable corresponding to the expression's value in a Aesara symbolic
expression graph.
"""
if not aesara:
raise ImportError("aesara is required for aesara_code")
if cache is None:
cache = global_cache
return AesaraPrinter(cache=cache, settings={}).doprint(expr, **kwargs)
def dim_handling(inputs, dim=None, dims=None, broadcastables=None):
r"""
Get value of ``broadcastables`` argument to :func:`.aesara_code` from
keyword arguments to :func:`.aesara_function`.
Included for backwards compatibility.
Parameters
==========
inputs
Sequence of input symbols.
dim : int
Common number of dimensions for all inputs. Overrides other arguments
if given.
dims : dict
Mapping from input symbols to number of dimensions. Overrides
``broadcastables`` argument if given.
broadcastables : dict
Explicit value of ``broadcastables`` argument to
:meth:`.AesaraPrinter.doprint`. If not None function will return this value unchanged.
Returns
=======
dict
Dictionary mapping elements of ``inputs`` to their "broadcastable"
values (tuple of ``bool``\ s).
"""
if dim is not None:
return {s: (False,) * dim for s in inputs}
if dims is not None:
maxdim = max(dims.values())
return {
s: (False,) * d + (True,) * (maxdim - d)
for s, d in dims.items()
}
if broadcastables is not None:
return broadcastables
return {}
def aesara_function(inputs, outputs, scalar=False, *,
dim=None, dims=None, broadcastables=None, **kwargs):
"""
Create a Aesara function from SymPy expressions.
The inputs and outputs are converted to Aesara variables using
:func:`.aesara_code` and then passed to ``aesara.function``.
Parameters
==========
inputs
Sequence of symbols which constitute the inputs of the function.
outputs
Sequence of expressions which constitute the outputs(s) of the
function. The free symbols of each expression must be a subset of
``inputs``.
scalar : bool
Convert 0-dimensional arrays in output to scalars. This will return a
Python wrapper function around the Aesara function object.
cache : dict
Cached Aesara variables (see :class:`AesaraPrinter.cache
<AesaraPrinter>`). Defaults to the module-level global cache.
dtypes : dict
Passed to :meth:`.AesaraPrinter.doprint`.
broadcastables : dict
Passed to :meth:`.AesaraPrinter.doprint`.
dims : dict
Alternative to ``broadcastables`` argument. Mapping from elements of
``inputs`` to integers indicating the dimension of their associated
arrays/tensors. Overrides ``broadcastables`` argument if given.
dim : int
Another alternative to the ``broadcastables`` argument. Common number of
dimensions to use for all arrays/tensors.
``aesara_function([x, y], [...], dim=2)`` is equivalent to using
``broadcastables={x: (False, False), y: (False, False)}``.
Returns
=======
callable
A callable object which takes values of ``inputs`` as positional
arguments and returns an output array for each of the expressions
in ``outputs``. If ``outputs`` is a single expression the function will
return a Numpy array, if it is a list of multiple expressions the
function will return a list of arrays. See description of the ``squeeze``
argument above for the behavior when a single output is passed in a list.
The returned object will either be an instance of
``aesara.compile.function.types.Function`` or a Python wrapper
function around one. In both cases, the returned value will have a
``aesara_function`` attribute which points to the return value of
``aesara.function``.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.printing.aesaracode import aesara_function
A simple function with one input and one output:
>>> f1 = aesara_function([x], [x**2 - 1], scalar=True)
>>> f1(3)
8.0
A function with multiple inputs and one output:
>>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True)
>>> f2(3, 4, 2)
5.0
A function with multiple inputs and multiple outputs:
>>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
>>> f3(2, 3)
[13.0, -5.0]
See also
========
dim_handling
"""
if not aesara:
raise ImportError("Aesara is required for aesara_function")
# Pop off non-aesara keyword args
cache = kwargs.pop('cache', {})
dtypes = kwargs.pop('dtypes', {})
broadcastables = dim_handling(
inputs, dim=dim, dims=dims, broadcastables=broadcastables,
)
# Print inputs/outputs
code = partial(aesara_code, cache=cache, dtypes=dtypes,
broadcastables=broadcastables)
tinputs = list(map(code, inputs))
toutputs = list(map(code, outputs))
#fix constant expressions as variables
toutputs = [output if isinstance(output, aesara.graph.basic.Variable) else aet.as_tensor_variable(output) for output in toutputs]
if len(toutputs) == 1:
toutputs = toutputs[0]
# Compile aesara func
func = aesara.function(tinputs, toutputs, **kwargs)
is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs]
# No wrapper required
if not scalar or not any(is_0d):
func.aesara_function = func
return func
# Create wrapper to convert 0-dimensional outputs to scalars
def wrapper(*args):
out = func(*args)
# out can be array(1.0) or [array(1.0), array(2.0)]
if is_sequence(out):
return [o[()] if is_0d[i] else o for i, o in enumerate(out)]
else:
return out[()]
wrapper.__wrapped__ = func
wrapper.__doc__ = func.__doc__
wrapper.aesara_function = func
return wrapper
|
808b932832eddefb77bac6dba66a0375330f14e39db1ae1682e29442f91e1c87 | import builtins
import typing
import sympy
from sympy.core import Add, Mul
from sympy.core import Symbol, Expr, Float, Rational, Integer, Basic
from sympy.core.function import UndefinedFunction, Function
from sympy.core.relational import Relational, Unequality, Equality, LessThan, GreaterThan, StrictLessThan, StrictGreaterThan
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp, log, Pow
from sympy.functions.elementary.hyperbolic import sinh, cosh, tanh
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import sin, cos, tan, asin, acos, atan, atan2
from sympy.logic.boolalg import And, Or, Xor, Implies, Boolean
from sympy.logic.boolalg import BooleanTrue, BooleanFalse, BooleanFunction, Not, ITE
from sympy.printing.printer import Printer
from sympy.sets import Interval
class SMTLibPrinter(Printer):
printmethod = "_smtlib"
# based on dReal, an automated reasoning tool for solving problems that can be encoded as first-order logic formulas over the real numbers.
# dReal's special strength is in handling problems that involve a wide range of nonlinear real functions.
_default_settings: dict = {
'precision': None,
'known_types': {
bool: 'Bool',
int: 'Int',
float: 'Real'
},
'known_constants': {
# pi: 'MY_VARIABLE_PI_DECLARED_ELSEWHERE',
},
'known_functions': {
Add: '+',
Mul: '*',
Equality: '=',
LessThan: '<=',
GreaterThan: '>=',
StrictLessThan: '<',
StrictGreaterThan: '>',
exp: 'exp',
log: 'log',
Abs: 'abs',
sin: 'sin',
cos: 'cos',
tan: 'tan',
asin: 'arcsin',
acos: 'arccos',
atan: 'arctan',
atan2: 'arctan2',
sinh: 'sinh',
cosh: 'cosh',
tanh: 'tanh',
Min: 'min',
Max: 'max',
Pow: 'pow',
And: 'and',
Or: 'or',
Xor: 'xor',
Not: 'not',
ITE: 'ite',
Implies: '=>',
}
}
symbol_table: dict
def __init__(self, settings: dict = None, symbol_table=None):
settings = settings or {}
self.symbol_table = symbol_table or {}
Printer.__init__(self, settings)
self._precision = self._settings['precision']
self._known_types = dict(self._settings['known_types'])
self._known_constants = dict(self._settings['known_constants'])
self._known_functions = dict(self._settings['known_functions'])
for _ in self._known_types.values(): assert self._is_legal_name(_)
for _ in self._known_constants.values(): assert self._is_legal_name(_)
# for _ in self._known_functions.values(): assert self._is_legal_name(_) # +, *, <, >, etc.
def _is_legal_name(self, s: str):
if not s: return False
if s[0].isnumeric(): return False
return all(_.isalnum() or _ == '_' for _ in s)
def _s_expr(self, op: str, args: typing.Union[list, tuple]) -> str:
args_str = ' '.join(
a if isinstance(a, str)
else self._print(a)
for a in args
)
return f'({op} {args_str})'
def _print_Function(self, e):
if e in self._known_functions:
op = self._known_functions[e]
elif type(e) in self._known_functions:
op = self._known_functions[type(e)]
elif type(type(e)) == UndefinedFunction:
op = e.name
else:
op = self._known_functions[e] # throw KeyError
return self._s_expr(op, e.args)
def _print_Relational(self, e: Relational):
return self._print_Function(e)
def _print_BooleanFunction(self, e: BooleanFunction):
return self._print_Function(e)
def _print_Expr(self, e: Expr):
return self._print_Function(e)
def _print_Unequality(self, e: Unequality):
if type(e) in self._known_functions:
return self._print_Relational(e) # default
else:
eq_op = self._known_functions[Equality]
not_op = self._known_functions[Not]
return self._s_expr(not_op, [self._s_expr(eq_op, e.args)])
def _print_Piecewise(self, e: Piecewise):
def _print_Piecewise_recursive(args: typing.Union[list, tuple]):
e, c = args[0]
if len(args) == 1:
assert (c is True) or isinstance(c, BooleanTrue)
return self._print(e)
else:
ite = self._known_functions[ITE]
return self._s_expr(ite, [
c, e, _print_Piecewise_recursive(args[1:])
])
return _print_Piecewise_recursive(e.args)
def _print_Interval(self, e: Interval):
if e.start.is_infinite and e.end.is_infinite:
return ''
elif e.start.is_infinite != e.end.is_infinite:
raise ValueError(f'One-sided intervals (`{e}`) are not supported in SMT.')
else:
return f'[{e.start}, {e.end}]'
# todo: Sympy does not support quantifiers yet as of 2022, but quantifiers can be handy in SMT.
# For now, users can extend this class and build in their own quantifier support.
# See `test_quantifier_extensions()` in test_smtlib.py for an example of how this might look.
# def _print_ForAll(self, e: ForAll):
# return self._s('forall', [
# self._s('', [
# self._s(sym.name, [self._type_name(sym), Interval(start, end)])
# for sym, start, end in e.limits
# ]),
# e.function
# ])
def _print_BooleanTrue(self, x: BooleanTrue):
return 'true'
def _print_BooleanFalse(self, x: BooleanFalse):
return 'false'
def _print_Float(self, x: Float):
f = x.evalf(self._precision) if self._precision else x.evalf()
return str(f).rstrip('0')
def _print_float(self, x: float):
return str(x)
def _print_Rational(self, x: Rational):
return self._s_expr('/', [x.p, x.q])
def _print_Integer(self, x: Integer):
assert x.q == 1
return str(x.p)
def _print_int(self, x: int):
return str(x)
def _print_Symbol(self, x: Symbol):
assert self._is_legal_name(x.name)
return x.name
def _print_NumberSymbol(self, x):
name = self._known_constants.get(x)
return name if name else self._print_Float(x)
def _print_UndefinedFunction(self, x):
assert self._is_legal_name(x.name)
return x.name
def _print_Exp1(self, x):
return (
self._print_Function(exp(1, evaluate=False))
if exp in self._known_functions else
self._print_NumberSymbol(x)
)
def emptyPrinter(self, expr):
raise NotImplementedError(f'Cannot convert `{repr(expr)}` of type `{type(expr)}` to SMT.')
def smtlib_code(
expr,
auto_assert=True, auto_declare=True,
precision=None,
symbol_table=None,
known_types=None, known_constants=None, known_functions=None,
prefix_expressions=None, suffix_expressions=None,
log_warn=builtins.print
):
r"""Converts ``expr`` to a string of smtlib code.
Parameters
==========
expr : Expr | List[Expr]
A SymPy expression or system to be converted.
auto_assert : bool, optional
If false, do not modify expr and produce only the S-Expression equivalent of expr.
If true, assume expr is a system and assert each boolean element.
auto_declare : bool, optional
If false, do not produce declarations for the symbols used in expr.
If true, prepend all necessary declarations for variables used in expr based on symbol_table.
precision : integer, optional
The ``evalf(..)`` precision for numbers such as pi.
symbol_table : dict, optional
A dictionary where keys are ``Symbol`` or ``Function`` instances and values are their Python type i.e. ``bool``, ``int``, ``float``, or ``Callable[...]``.
If incomplete, an attempt will be made to infer types from ``expr``.
known_types: dict, optional
A dictionary where keys are ``bool``, ``int``, ``float`` etc. and values are their corresponding SMT type names.
If not given, a partial listing compatible with several solvers will be used.
known_functions : dict, optional
A dictionary where keys are ``Function``, ``Relational``, ``BooleanFunction``, or ``Expr`` instances and values are their SMT string representations.
If not given, a partial listing optimized for dReal solver (but compatible with others) will be used.
known_constants: dict, optional
A dictionary where keys are ``NumberSymbol`` instances and values are their SMT variable names.
When using this feature, extra caution must be taken to avoid naming collisions between user symbols and listed constants.
If not given, constants will be expanded inline i.e. ``3.14159`` instead of ``MY_SMT_VARIABLE_FOR_PI``.
prefix_expressions: list, optional
A list of lists of ``str`` and/or expressions to convert into SMTLib and prefix to the output.
suffix_expressions: list, optional
A list of lists of ``str`` and/or expressions to convert into SMTLib and postfix to the output.
log_warn: lambda function, optional
A function to record all warnings during potentially risky operations.
Soundness is a core value in SMT solving, so it is good to log all assumptions made.
If not given, builtins ``print`` will be used.
Examples
========
>>> noop = (lambda _: None)
>>> from sympy import smtlib_code, symbols, sin, Eq
>>> x = symbols('x')
>>> smtlib_code(sin(x).series(x).removeO(), log_warn=noop)
'(declare-const x Real)\n(+ x (* (/ -1 6) (pow x 3)) (* (/ 1 120) (pow x 5)))'
>>> from sympy import Rational
>>> x, y, tau = symbols("x, y, tau")
>>> smtlib_code((2*tau)**Rational(7, 2), log_warn=noop)
'(declare-const tau Real)\n(* 8 (pow 2 (/ 1 2)) (pow tau (/ 7 2)))'
``Piecewise`` expressions are implemented with ``ite`` expressions by default.
Note that if the ``Piecewise`` lacks a default term, represented by
``(expr, True)`` then an error will be thrown. This is to prevent
generating an expression that may not evaluate to anything.
>>> from sympy import Piecewise
>>> pw = Piecewise((x + 1, x > 0), (x, True))
>>> smtlib_code(Eq(pw, 3))
Could not infer type of `x`. Defaulting to float.
'(declare-const x Real)\n(assert (= (ite (> x 0) (+ 1 x) x) 3))'
Custom printing can be defined for certain types by passing a dictionary of
PythonType : "SMT Name" to the ``known_types``, ``known_constants``, and ``known_functions`` kwargs.
>>> from typing import Callable
>>> from sympy import Function, Add
>>> f = Function('f')
>>> g = Function('g')
>>> smt_builtin_funcs = { # functions our SMT solver will understand
... f: "existing_smtlib_fcn",
... Add: "sum",
... }
>>> user_def_funcs = { # functions defined by the user must have their types specified explicitly
... g: Callable[[int], float],
... }
>>> smtlib_code(f(x) + g(x), symbol_table=user_def_funcs, known_functions=smt_builtin_funcs)
Non-Boolean expression `f(x) + g(x)` will not be asserted. Converting to SMTLib verbatim.
'(declare-const x Int)\n(declare-fun g (Int) Real)\n(sum (existing_smtlib_fcn x) (g x))'
"""
if not log_warn: log_warn = (lambda _: None)
if not isinstance(expr, list): expr = [expr]
expr = [
sympy.sympify(_, strict=True, evaluate=False, convert_xor=False)
for _ in expr
]
if not symbol_table: symbol_table = {}
symbol_table = _auto_infer_smtlib_types(
*expr, symbol_table=symbol_table
)
# See [FALLBACK RULES]
# Need SMTLibPrinter to populate known_functions and known_constants first.
settings = {}
if precision: settings['precision'] = precision
del precision
if known_types: settings['known_types'] = known_types
del known_types
if known_functions: settings['known_functions'] = known_functions
del known_functions
if known_constants: settings['known_constants'] = known_constants
del known_constants
if not prefix_expressions: prefix_expressions = []
if not suffix_expressions: suffix_expressions = []
p = SMTLibPrinter(settings, symbol_table)
del symbol_table
# [FALLBACK RULES]
for e in expr:
for sym in e.atoms(Symbol, Function):
if (
sym.is_Symbol and
sym not in p._known_constants and
sym not in p.symbol_table
):
log_warn(f"Could not infer type of `{sym}`. Defaulting to float.")
p.symbol_table[sym] = float
if (
sym.is_Function and
type(sym) not in p._known_functions and
type(sym) not in p.symbol_table and
not sym.is_Piecewise
): raise TypeError(
f"Unknown type of undefined function `{sym}`. "
f"Must be mapped to ``str`` in known_functions or mapped to ``Callable[..]`` in symbol_table."
)
declarations = []
if auto_declare:
constants = {sym.name: sym for e in expr for sym in e.free_symbols
if sym not in p._known_constants}
functions = {fnc.name: fnc for e in expr for fnc in e.atoms(Function)
if type(fnc) not in p._known_functions and not fnc.is_Piecewise}
declarations = \
[
_auto_declare_smtlib(sym, p, log_warn=log_warn)
for sym in constants.values()
] + [
_auto_declare_smtlib(fnc, p, log_warn=log_warn)
for fnc in functions.values()
]
declarations = [decl for decl in declarations if decl]
if auto_assert:
expr = [_auto_assert_smtlib(e, p, log_warn=log_warn) for e in expr]
# return SMTLibPrinter().doprint(expr)
return '\n'.join([
# ';; PREFIX EXPRESSIONS',
*[
e if isinstance(e, str) else p.doprint(e)
for e in prefix_expressions
],
# ';; DECLARATIONS',
*sorted(e for e in declarations),
# ';; EXPRESSIONS',
*[
e if isinstance(e, str) else p.doprint(e)
for e in expr
],
# ';; SUFFIX EXPRESSIONS',
*[
e if isinstance(e, str) else p.doprint(e)
for e in suffix_expressions
],
])
def _auto_declare_smtlib(sym: typing.Union[Symbol, Function], p: SMTLibPrinter, log_warn=print):
if sym.is_Symbol:
type_signature = p.symbol_table[sym]
assert isinstance(type_signature, type)
type_signature = p._known_types[type_signature]
return p._s_expr('declare-const', [sym, type_signature])
elif sym.is_Function:
type_signature = p.symbol_table[type(sym)]
assert callable(type_signature)
type_signature = [p._known_types[_] for _ in type_signature.__args__]
assert len(type_signature) > 0
params_signature = f"({' '.join(type_signature[:-1])})"
return_signature = type_signature[-1]
return p._s_expr('declare-fun', [type(sym), params_signature, return_signature])
else:
log_warn(f"Non-Symbol/Function `{sym}` will not be declared.")
return None
def _auto_assert_smtlib(e: Expr, p: SMTLibPrinter, log_warn=print):
if isinstance(e, Boolean) or (
e in p.symbol_table and p.symbol_table[e] == bool
) or (
e.is_Function and
type(e) in p.symbol_table and
p.symbol_table[type(e)].__args__[-1] == bool
):
return p._s_expr('assert', [e])
else:
log_warn(f"Non-Boolean expression `{e}` will not be asserted. Converting to SMTLib verbatim.")
return e
def _auto_infer_smtlib_types(
*exprs: Basic,
symbol_table: dict = None
) -> dict:
# [TYPE INFERENCE RULES]
# X is alone in an expr => X is bool
# X in BooleanFunction.args => X is bool
# X matches to a bool param of a symbol_table function => X is bool
# X matches to an int param of a symbol_table function => X is int
# X.is_integer => X is int
# X == Y, where X is T => Y is T
# [FALLBACK RULES]
# see _auto_declare_smtlib(..)
# X is not bool and X is not int and X is Symbol => X is float
# else (e.g. X is Function) => error. must be specified explicitly.
_symbols = dict(symbol_table) if symbol_table else {}
def safe_update(syms: set, inf):
for s in syms:
assert s.is_Symbol
if (old_type := _symbols.setdefault(s, inf)) != inf:
raise TypeError(f"Could not infer type of `{s}`. Apparently both `{old_type}` and `{inf}`?")
# EXPLICIT TYPES
safe_update({
e
for e in exprs
if e.is_Symbol
}, bool)
safe_update({
symbol
for e in exprs
for boolfunc in e.atoms(BooleanFunction)
for symbol in boolfunc.args
if symbol.is_Symbol
}, bool)
safe_update({
symbol
for e in exprs
for boolfunc in e.atoms(Function)
if type(boolfunc) in _symbols
for symbol, param in zip(boolfunc.args, _symbols[type(boolfunc)].__args__)
if symbol.is_Symbol and param == bool
}, bool)
safe_update({
symbol
for e in exprs
for intfunc in e.atoms(Function)
if type(intfunc) in _symbols
for symbol, param in zip(intfunc.args, _symbols[type(intfunc)].__args__)
if symbol.is_Symbol and param == int
}, int)
safe_update({
symbol
for e in exprs
for symbol in e.atoms(Symbol)
if symbol.is_integer
}, int)
safe_update({
symbol
for e in exprs
for symbol in e.atoms(Symbol)
if symbol.is_real and not symbol.is_integer
}, float)
# EQUALITY RELATION RULE
rels = [rel for expr in exprs for rel in expr.atoms(Equality)]
rels = [
(rel.lhs, rel.rhs) for rel in rels if rel.lhs.is_Symbol
] + [
(rel.rhs, rel.lhs) for rel in rels if rel.rhs.is_Symbol
]
for infer, reltd in rels:
inference = (
_symbols[infer] if infer in _symbols else
_symbols[reltd] if reltd in _symbols else
_symbols[type(reltd)].__args__[-1]
if reltd.is_Function and type(reltd) in _symbols else
bool if reltd.is_Boolean else
int if reltd.is_integer or reltd.is_Integer else
float if reltd.is_real else
None
)
if inference: safe_update({infer}, inference)
return _symbols
|
b7942323639725386f82afcd3a3839769849099a5526075a805eddafad6227d3 | """ Integral Transforms """
from functools import reduce, wraps
from itertools import repeat
from sympy.core import S, pi, I
from sympy.core.add import Add
from sympy.core.function import (AppliedUndef, count_ops, Derivative, expand,
expand_complex, expand_mul, Function, Lambda,
WildFunction)
from sympy.core.mul import Mul
from sympy.core.numbers import igcd, ilcm
from sympy.core.relational import _canonical, Ge, Gt, Lt, Unequality, Eq
from sympy.core.sorting import default_sort_key, ordered
from sympy.core.symbol import Dummy, symbols, Wild
from sympy.core.traversal import postorder_traversal
from sympy.functions.combinatorial.factorials import factorial, rf
from sympy.functions.elementary.complexes import (re, arg, Abs, polar_lift,
periodic_argument)
from sympy.functions.elementary.exponential import exp, log, exp_polar
from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh, asinh
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.trigonometric import cos, cot, sin, tan, atan
from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.error_functions import erf, erfc, Ei
from sympy.functions.special.gamma_functions import digamma, gamma, lowergamma
from sympy.functions.special.hyper import meijerg
from sympy.integrals import integrate, Integral
from sympy.integrals.meijerint import _dummy
from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And
from sympy.matrices.matrices import MatrixBase
from sympy.polys.matrices.linsolve import _lin_eq2dict, PolyNonlinearError
from sympy.polys.polyroots import roots
from sympy.polys.polytools import factor, Poly
from sympy.polys.rationaltools import together
from sympy.polys.rootoftools import CRootOf, RootSum
from sympy.utilities.exceptions import (sympy_deprecation_warning,
SymPyDeprecationWarning,
ignore_warnings)
from sympy.utilities.iterables import iterable
from sympy.utilities.misc import debug
##########################################################################
# Helpers / Utilities
##########################################################################
class IntegralTransformError(NotImplementedError):
"""
Exception raised in relation to problems computing transforms.
Explanation
===========
This class is mostly used internally; if integrals cannot be computed
objects representing unevaluated transforms are usually returned.
The hint ``needeval=True`` can be used to disable returning transform
objects, and instead raise this exception if an integral cannot be
computed.
"""
def __init__(self, transform, function, msg):
super().__init__(
"%s Transform could not be computed: %s." % (transform, msg))
self.function = function
class IntegralTransform(Function):
"""
Base class for integral transforms.
Explanation
===========
This class represents unevaluated transforms.
To implement a concrete transform, derive from this class and implement
the ``_compute_transform(f, x, s, **hints)`` and ``_as_integral(f, x, s)``
functions. If the transform cannot be computed, raise :obj:`IntegralTransformError`.
Also set ``cls._name``. For instance,
>>> from sympy import LaplaceTransform
>>> LaplaceTransform._name
'Laplace'
Implement ``self._collapse_extra`` if your function returns more than just a
number and possibly a convergence condition.
"""
@property
def function(self):
""" The function to be transformed. """
return self.args[0]
@property
def function_variable(self):
""" The dependent variable of the function to be transformed. """
return self.args[1]
@property
def transform_variable(self):
""" The independent transform variable. """
return self.args[2]
@property
def free_symbols(self):
"""
This method returns the symbols that will exist when the transform
is evaluated.
"""
return self.function.free_symbols.union({self.transform_variable}) \
- {self.function_variable}
def _compute_transform(self, f, x, s, **hints):
raise NotImplementedError
def _as_integral(self, f, x, s):
raise NotImplementedError
def _collapse_extra(self, extra):
cond = And(*extra)
if cond == False:
raise IntegralTransformError(self.__class__.name, None, '')
return cond
def _try_directly(self, **hints):
T = None
try_directly = not any(func.has(self.function_variable)
for func in self.function.atoms(AppliedUndef))
if try_directly:
try:
T = self._compute_transform(self.function,
self.function_variable, self.transform_variable, **hints)
except IntegralTransformError:
T = None
fn = self.function
if not fn.is_Add:
fn = expand_mul(fn)
return fn, T
def doit(self, **hints):
"""
Try to evaluate the transform in closed form.
Explanation
===========
This general function handles linearity, but apart from that leaves
pretty much everything to _compute_transform.
Standard hints are the following:
- ``simplify``: whether or not to simplify the result
- ``noconds``: if True, do not return convergence conditions
- ``needeval``: if True, raise IntegralTransformError instead of
returning IntegralTransform objects
The default values of these hints depend on the concrete transform,
usually the default is
``(simplify, noconds, needeval) = (True, False, False)``.
"""
needeval = hints.pop('needeval', False)
simplify = hints.pop('simplify', True)
hints['simplify'] = simplify
fn, T = self._try_directly(**hints)
if T is not None:
return T
if fn.is_Add:
hints['needeval'] = needeval
res = [self.__class__(*([x] + list(self.args[1:]))).doit(**hints)
for x in fn.args]
extra = []
ress = []
for x in res:
if not isinstance(x, tuple):
x = [x]
ress.append(x[0])
if len(x) == 2:
# only a condition
extra.append(x[1])
elif len(x) > 2:
# some region parameters and a condition (Mellin, Laplace)
extra += [x[1:]]
if simplify==True:
res = Add(*ress).simplify()
else:
res = Add(*ress)
if not extra:
return res
try:
extra = self._collapse_extra(extra)
if iterable(extra):
return tuple([res]) + tuple(extra)
else:
return (res, extra)
except IntegralTransformError:
pass
if needeval:
raise IntegralTransformError(
self.__class__._name, self.function, 'needeval')
# TODO handle derivatives etc
# pull out constant coefficients
coeff, rest = fn.as_coeff_mul(self.function_variable)
return coeff*self.__class__(*([Mul(*rest)] + list(self.args[1:])))
@property
def as_integral(self):
return self._as_integral(self.function, self.function_variable,
self.transform_variable)
def _eval_rewrite_as_Integral(self, *args, **kwargs):
return self.as_integral
def _simplify(expr, doit):
if doit:
from sympy.simplify import simplify
from sympy.simplify.powsimp import powdenest
return simplify(powdenest(piecewise_fold(expr), polar=True))
return expr
def _noconds_(default):
"""
This is a decorator generator for dropping convergence conditions.
Explanation
===========
Suppose you define a function ``transform(*args)`` which returns a tuple of
the form ``(result, cond1, cond2, ...)``.
Decorating it ``@_noconds_(default)`` will add a new keyword argument
``noconds`` to it. If ``noconds=True``, the return value will be altered to
be only ``result``, whereas if ``noconds=False`` the return value will not
be altered.
The default value of the ``noconds`` keyword will be ``default`` (i.e. the
argument of this function).
"""
def make_wrapper(func):
@wraps(func)
def wrapper(*args, noconds=default, **kwargs):
res = func(*args, **kwargs)
if noconds:
return res[0]
return res
return wrapper
return make_wrapper
_noconds = _noconds_(False)
##########################################################################
# Mellin Transform
##########################################################################
def _default_integrator(f, x):
return integrate(f, (x, S.Zero, S.Infinity))
@_noconds
def _mellin_transform(f, x, s_, integrator=_default_integrator, simplify=True):
""" Backend function to compute Mellin transforms. """
# We use a fresh dummy, because assumptions on s might drop conditions on
# convergence of the integral.
s = _dummy('s', 'mellin-transform', f)
F = integrator(x**(s - 1) * f, x)
if not F.has(Integral):
return _simplify(F.subs(s, s_), simplify), (S.NegativeInfinity, S.Infinity), S.true
if not F.is_Piecewise: # XXX can this work if integration gives continuous result now?
raise IntegralTransformError('Mellin', f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(
'Mellin', f, 'integral in unexpected form')
def process_conds(cond):
"""
Turn ``cond`` into a strip (a, b), and auxiliary conditions.
"""
from sympy.solvers.inequalities import _solve_inequality
a = S.NegativeInfinity
b = S.Infinity
aux = S.true
conds = conjuncts(to_cnf(cond))
t = Dummy('t', real=True)
for c in conds:
a_ = S.Infinity
b_ = S.NegativeInfinity
aux_ = []
for d in disjuncts(c):
d_ = d.replace(
re, lambda x: x.as_real_imag()[0]).subs(re(s), t)
if not d.is_Relational or \
d.rel_op in ('==', '!=') \
or d_.has(s) or not d_.has(t):
aux_ += [d]
continue
soln = _solve_inequality(d_, t)
if not soln.is_Relational or \
soln.rel_op in ('==', '!='):
aux_ += [d]
continue
if soln.lts == t:
b_ = Max(soln.gts, b_)
else:
a_ = Min(soln.lts, a_)
if a_ is not S.Infinity and a_ != b:
a = Max(a_, a)
elif b_ is not S.NegativeInfinity and b_ != a:
b = Min(b_, b)
else:
aux = And(aux, Or(*aux_))
return a, b, aux
conds = [process_conds(c) for c in disjuncts(cond)]
conds = [x for x in conds if x[2] != False]
conds.sort(key=lambda x: (x[0] - x[1], count_ops(x[2])))
if not conds:
raise IntegralTransformError('Mellin', f, 'no convergence found')
a, b, aux = conds[0]
return _simplify(F.subs(s, s_), simplify), (a, b), aux
class MellinTransform(IntegralTransform):
"""
Class representing unevaluated Mellin transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Mellin transforms, see the :func:`mellin_transform`
docstring.
"""
_name = 'Mellin'
def _compute_transform(self, f, x, s, **hints):
return _mellin_transform(f, x, s, **hints)
def _as_integral(self, f, x, s):
return Integral(f*x**(s - 1), (x, S.Zero, S.Infinity))
def _collapse_extra(self, extra):
a = []
b = []
cond = []
for (sa, sb), c in extra:
a += [sa]
b += [sb]
cond += [c]
res = (Max(*a), Min(*b)), And(*cond)
if (res[0][0] >= res[0][1]) == True or res[1] == False:
raise IntegralTransformError(
'Mellin', None, 'no combined convergence.')
return res
def mellin_transform(f, x, s, **hints):
r"""
Compute the Mellin transform `F(s)` of `f(x)`,
.. math :: F(s) = \int_0^\infty x^{s-1} f(x) \mathrm{d}x.
For all "sensible" functions, this converges absolutely in a strip
`a < \operatorname{Re}(s) < b`.
Explanation
===========
The Mellin transform is related via change of variables to the Fourier
transform, and also to the (bilateral) Laplace transform.
This function returns ``(F, (a, b), cond)``
where ``F`` is the Mellin transform of ``f``, ``(a, b)`` is the fundamental strip
(as above), and ``cond`` are auxiliary convergence conditions.
If the integral cannot be computed in closed form, this function returns
an unevaluated :class:`MellinTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=False``,
then only `F` will be returned (i.e. not ``cond``, and also not the strip
``(a, b)``).
Examples
========
>>> from sympy import mellin_transform, exp
>>> from sympy.abc import x, s
>>> mellin_transform(exp(-x), x, s)
(gamma(s), (0, oo), True)
See Also
========
inverse_mellin_transform, laplace_transform, fourier_transform
hankel_transform, inverse_hankel_transform
"""
return MellinTransform(f, x, s).doit(**hints)
def _rewrite_sin(m_n, s, a, b):
"""
Re-write the sine function ``sin(m*s + n)`` as gamma functions, compatible
with the strip (a, b).
Return ``(gamma1, gamma2, fac)`` so that ``f == fac/(gamma1 * gamma2)``.
Examples
========
>>> from sympy.integrals.transforms import _rewrite_sin
>>> from sympy import pi, S
>>> from sympy.abc import s
>>> _rewrite_sin((pi, 0), s, 0, 1)
(gamma(s), gamma(1 - s), pi)
>>> _rewrite_sin((pi, 0), s, 1, 0)
(gamma(s - 1), gamma(2 - s), -pi)
>>> _rewrite_sin((pi, 0), s, -1, 0)
(gamma(s + 1), gamma(-s), -pi)
>>> _rewrite_sin((pi, pi/2), s, S(1)/2, S(3)/2)
(gamma(s - 1/2), gamma(3/2 - s), -pi)
>>> _rewrite_sin((pi, pi), s, 0, 1)
(gamma(s), gamma(1 - s), -pi)
>>> _rewrite_sin((2*pi, 0), s, 0, S(1)/2)
(gamma(2*s), gamma(1 - 2*s), pi)
>>> _rewrite_sin((2*pi, 0), s, S(1)/2, 1)
(gamma(2*s - 1), gamma(2 - 2*s), -pi)
"""
# (This is a separate function because it is moderately complicated,
# and I want to doctest it.)
# We want to use pi/sin(pi*x) = gamma(x)*gamma(1-x).
# But there is one comlication: the gamma functions determine the
# inegration contour in the definition of the G-function. Usually
# it would not matter if this is slightly shifted, unless this way
# we create an undefined function!
# So we try to write this in such a way that the gammas are
# eminently on the right side of the strip.
m, n = m_n
m = expand_mul(m/pi)
n = expand_mul(n/pi)
r = ceiling(-m*a - n.as_real_imag()[0]) # Don't use re(n), does not expand
return gamma(m*s + n + r), gamma(1 - n - r - m*s), (-1)**r*pi
class MellinTransformStripError(ValueError):
"""
Exception raised by _rewrite_gamma. Mainly for internal use.
"""
pass
def _rewrite_gamma(f, s, a, b):
"""
Try to rewrite the product f(s) as a product of gamma functions,
so that the inverse Mellin transform of f can be expressed as a meijer
G function.
Explanation
===========
Return (an, ap), (bm, bq), arg, exp, fac such that
G((an, ap), (bm, bq), arg/z**exp)*fac is the inverse Mellin transform of f(s).
Raises IntegralTransformError or MellinTransformStripError on failure.
It is asserted that f has no poles in the fundamental strip designated by
(a, b). One of a and b is allowed to be None. The fundamental strip is
important, because it determines the inversion contour.
This function can handle exponentials, linear factors, trigonometric
functions.
This is a helper function for inverse_mellin_transform that will not
attempt any transformations on f.
Examples
========
>>> from sympy.integrals.transforms import _rewrite_gamma
>>> from sympy.abc import s
>>> from sympy import oo
>>> _rewrite_gamma(s*(s+3)*(s-1), s, -oo, oo)
(([], [-3, 0, 1]), ([-2, 1, 2], []), 1, 1, -1)
>>> _rewrite_gamma((s-1)**2, s, -oo, oo)
(([], [1, 1]), ([2, 2], []), 1, 1, 1)
Importance of the fundamental strip:
>>> _rewrite_gamma(1/s, s, 0, oo)
(([1], []), ([], [0]), 1, 1, 1)
>>> _rewrite_gamma(1/s, s, None, oo)
(([1], []), ([], [0]), 1, 1, 1)
>>> _rewrite_gamma(1/s, s, 0, None)
(([1], []), ([], [0]), 1, 1, 1)
>>> _rewrite_gamma(1/s, s, -oo, 0)
(([], [1]), ([0], []), 1, 1, -1)
>>> _rewrite_gamma(1/s, s, None, 0)
(([], [1]), ([0], []), 1, 1, -1)
>>> _rewrite_gamma(1/s, s, -oo, None)
(([], [1]), ([0], []), 1, 1, -1)
>>> _rewrite_gamma(2**(-s+3), s, -oo, oo)
(([], []), ([], []), 1/2, 1, 8)
"""
# Our strategy will be as follows:
# 1) Guess a constant c such that the inversion integral should be
# performed wrt s'=c*s (instead of plain s). Write s for s'.
# 2) Process all factors, rewrite them independently as gamma functions in
# argument s, or exponentials of s.
# 3) Try to transform all gamma functions s.t. they have argument
# a+s or a-s.
# 4) Check that the resulting G function parameters are valid.
# 5) Combine all the exponentials.
a_, b_ = S([a, b])
def left(c, is_numer):
"""
Decide whether pole at c lies to the left of the fundamental strip.
"""
# heuristically, this is the best chance for us to solve the inequalities
c = expand(re(c))
if a_ is None and b_ is S.Infinity:
return True
if a_ is None:
return c < b_
if b_ is None:
return c <= a_
if (c >= b_) == True:
return False
if (c <= a_) == True:
return True
if is_numer:
return None
if a_.free_symbols or b_.free_symbols or c.free_symbols:
return None # XXX
#raise IntegralTransformError('Inverse Mellin', f,
# 'Could not determine position of singularity %s'
# ' relative to fundamental strip' % c)
raise MellinTransformStripError('Pole inside critical strip?')
# 1)
s_multipliers = []
for g in f.atoms(gamma):
if not g.has(s):
continue
arg = g.args[0]
if arg.is_Add:
arg = arg.as_independent(s)[1]
coeff, _ = arg.as_coeff_mul(s)
s_multipliers += [coeff]
for g in f.atoms(sin, cos, tan, cot):
if not g.has(s):
continue
arg = g.args[0]
if arg.is_Add:
arg = arg.as_independent(s)[1]
coeff, _ = arg.as_coeff_mul(s)
s_multipliers += [coeff/pi]
s_multipliers = [Abs(x) if x.is_extended_real else x for x in s_multipliers]
common_coefficient = S.One
for x in s_multipliers:
if not x.is_Rational:
common_coefficient = x
break
s_multipliers = [x/common_coefficient for x in s_multipliers]
if not (all(x.is_Rational for x in s_multipliers) and
common_coefficient.is_extended_real):
raise IntegralTransformError("Gamma", None, "Nonrational multiplier")
s_multiplier = common_coefficient/reduce(ilcm, [S(x.q)
for x in s_multipliers], S.One)
if s_multiplier == common_coefficient:
if len(s_multipliers) == 0:
s_multiplier = common_coefficient
else:
s_multiplier = common_coefficient \
*reduce(igcd, [S(x.p) for x in s_multipliers])
f = f.subs(s, s/s_multiplier)
fac = S.One/s_multiplier
exponent = S.One/s_multiplier
if a_ is not None:
a_ *= s_multiplier
if b_ is not None:
b_ *= s_multiplier
# 2)
numer, denom = f.as_numer_denom()
numer = Mul.make_args(numer)
denom = Mul.make_args(denom)
args = list(zip(numer, repeat(True))) + list(zip(denom, repeat(False)))
facs = []
dfacs = []
# *_gammas will contain pairs (a, c) representing Gamma(a*s + c)
numer_gammas = []
denom_gammas = []
# exponentials will contain bases for exponentials of s
exponentials = []
def exception(fact):
return IntegralTransformError("Inverse Mellin", f, "Unrecognised form '%s'." % fact)
while args:
fact, is_numer = args.pop()
if is_numer:
ugammas, lgammas = numer_gammas, denom_gammas
ufacs = facs
else:
ugammas, lgammas = denom_gammas, numer_gammas
ufacs = dfacs
def linear_arg(arg):
""" Test if arg is of form a*s+b, raise exception if not. """
if not arg.is_polynomial(s):
raise exception(fact)
p = Poly(arg, s)
if p.degree() != 1:
raise exception(fact)
return p.all_coeffs()
# constants
if not fact.has(s):
ufacs += [fact]
# exponentials
elif fact.is_Pow or isinstance(fact, exp):
if fact.is_Pow:
base = fact.base
exp_ = fact.exp
else:
base = exp_polar(1)
exp_ = fact.exp
if exp_.is_Integer:
cond = is_numer
if exp_ < 0:
cond = not cond
args += [(base, cond)]*Abs(exp_)
continue
elif not base.has(s):
a, b = linear_arg(exp_)
if not is_numer:
base = 1/base
exponentials += [base**a]
facs += [base**b]
else:
raise exception(fact)
# linear factors
elif fact.is_polynomial(s):
p = Poly(fact, s)
if p.degree() != 1:
# We completely factor the poly. For this we need the roots.
# Now roots() only works in some cases (low degree), and CRootOf
# only works without parameters. So try both...
coeff = p.LT()[1]
rs = roots(p, s)
if len(rs) != p.degree():
rs = CRootOf.all_roots(p)
ufacs += [coeff]
args += [(s - c, is_numer) for c in rs]
continue
a, c = p.all_coeffs()
ufacs += [a]
c /= -a
# Now need to convert s - c
if left(c, is_numer):
ugammas += [(S.One, -c + 1)]
lgammas += [(S.One, -c)]
else:
ufacs += [-1]
ugammas += [(S.NegativeOne, c + 1)]
lgammas += [(S.NegativeOne, c)]
elif isinstance(fact, gamma):
a, b = linear_arg(fact.args[0])
if is_numer:
if (a > 0 and (left(-b/a, is_numer) == False)) or \
(a < 0 and (left(-b/a, is_numer) == True)):
raise NotImplementedError(
'Gammas partially over the strip.')
ugammas += [(a, b)]
elif isinstance(fact, sin):
# We try to re-write all trigs as gammas. This is not in
# general the best strategy, since sometimes this is impossible,
# but rewriting as exponentials would work. However trig functions
# in inverse mellin transforms usually all come from simplifying
# gamma terms, so this should work.
a = fact.args[0]
if is_numer:
# No problem with the poles.
gamma1, gamma2, fac_ = gamma(a/pi), gamma(1 - a/pi), pi
else:
gamma1, gamma2, fac_ = _rewrite_sin(linear_arg(a), s, a_, b_)
args += [(gamma1, not is_numer), (gamma2, not is_numer)]
ufacs += [fac_]
elif isinstance(fact, tan):
a = fact.args[0]
args += [(sin(a, evaluate=False), is_numer),
(sin(pi/2 - a, evaluate=False), not is_numer)]
elif isinstance(fact, cos):
a = fact.args[0]
args += [(sin(pi/2 - a, evaluate=False), is_numer)]
elif isinstance(fact, cot):
a = fact.args[0]
args += [(sin(pi/2 - a, evaluate=False), is_numer),
(sin(a, evaluate=False), not is_numer)]
else:
raise exception(fact)
fac *= Mul(*facs)/Mul(*dfacs)
# 3)
an, ap, bm, bq = [], [], [], []
for gammas, plus, minus, is_numer in [(numer_gammas, an, bm, True),
(denom_gammas, bq, ap, False)]:
while gammas:
a, c = gammas.pop()
if a != -1 and a != +1:
# We use the gamma function multiplication theorem.
p = Abs(S(a))
newa = a/p
newc = c/p
if not a.is_Integer:
raise TypeError("a is not an integer")
for k in range(p):
gammas += [(newa, newc + k/p)]
if is_numer:
fac *= (2*pi)**((1 - p)/2) * p**(c - S.Half)
exponentials += [p**a]
else:
fac /= (2*pi)**((1 - p)/2) * p**(c - S.Half)
exponentials += [p**(-a)]
continue
if a == +1:
plus.append(1 - c)
else:
minus.append(c)
# 4)
# TODO
# 5)
arg = Mul(*exponentials)
# for testability, sort the arguments
an.sort(key=default_sort_key)
ap.sort(key=default_sort_key)
bm.sort(key=default_sort_key)
bq.sort(key=default_sort_key)
return (an, ap), (bm, bq), arg, exponent, fac
@_noconds_(True)
def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False):
""" A helper for the real inverse_mellin_transform function, this one here
assumes x to be real and positive. """
x = _dummy('t', 'inverse-mellin-transform', F, positive=True)
# Actually, we won't try integration at all. Instead we use the definition
# of the Meijer G function as a fairly general inverse mellin transform.
F = F.rewrite(gamma)
for g in [factor(F), expand_mul(F), expand(F)]:
if g.is_Add:
# do all terms separately
ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg,
noconds=False)
for G in g.args]
conds = [p[1] for p in ress]
ress = [p[0] for p in ress]
res = Add(*ress)
if not as_meijerg:
res = factor(res, gens=res.atoms(Heaviside))
return res.subs(x, x_), And(*conds)
try:
a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1])
except IntegralTransformError:
continue
try:
G = meijerg(a, b, C/x**e)
except ValueError:
continue
if as_meijerg:
h = G
else:
try:
from sympy.simplify import hyperexpand
h = hyperexpand(G)
except NotImplementedError:
raise IntegralTransformError(
'Inverse Mellin', F, 'Could not calculate integral')
if h.is_Piecewise and len(h.args) == 3:
# XXX we break modularity here!
h = Heaviside(x - Abs(C))*h.args[0].args[0] \
+ Heaviside(Abs(C) - x)*h.args[1].args[0]
# We must ensure that the integral along the line we want converges,
# and return that value.
# See [L], 5.2
cond = [Abs(arg(G.argument)) < G.delta*pi]
# Note: we allow ">=" here, this corresponds to convergence if we let
# limits go to oo symmetrically. ">" corresponds to absolute convergence.
cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1),
Abs(arg(G.argument)) == G.delta*pi)]
cond = Or(*cond)
if cond == False:
raise IntegralTransformError(
'Inverse Mellin', F, 'does not converge')
return (h*fac).subs(x, x_), cond
raise IntegralTransformError('Inverse Mellin', F, '')
_allowed = None
class InverseMellinTransform(IntegralTransform):
"""
Class representing unevaluated inverse Mellin transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Mellin transforms, see the
:func:`inverse_mellin_transform` docstring.
"""
_name = 'Inverse Mellin'
_none_sentinel = Dummy('None')
_c = Dummy('c')
def __new__(cls, F, s, x, a, b, **opts):
if a is None:
a = InverseMellinTransform._none_sentinel
if b is None:
b = InverseMellinTransform._none_sentinel
return IntegralTransform.__new__(cls, F, s, x, a, b, **opts)
@property
def fundamental_strip(self):
a, b = self.args[3], self.args[4]
if a is InverseMellinTransform._none_sentinel:
a = None
if b is InverseMellinTransform._none_sentinel:
b = None
return a, b
def _compute_transform(self, F, s, x, **hints):
# IntegralTransform's doit will cause this hint to exist, but
# InverseMellinTransform should ignore it
hints.pop('simplify', True)
global _allowed
if _allowed is None:
_allowed = {
exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth,
factorial, rf}
for f in postorder_traversal(F):
if f.is_Function and f.has(s) and f.func not in _allowed:
raise IntegralTransformError('Inverse Mellin', F,
'Component %s not recognised.' % f)
strip = self.fundamental_strip
return _inverse_mellin_transform(F, s, x, strip, **hints)
def _as_integral(self, F, s, x):
c = self.__class__._c
return Integral(F*x**(-s), (s, c - S.ImaginaryUnit*S.Infinity, c +
S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit)
def inverse_mellin_transform(F, s, x, strip, **hints):
r"""
Compute the inverse Mellin transform of `F(s)` over the fundamental
strip given by ``strip=(a, b)``.
Explanation
===========
This can be defined as
.. math:: f(x) = \frac{1}{2\pi i} \int_{c - i\infty}^{c + i\infty} x^{-s} F(s) \mathrm{d}s,
for any `c` in the fundamental strip. Under certain regularity
conditions on `F` and/or `f`,
this recovers `f` from its Mellin transform `F`
(and vice versa), for positive real `x`.
One of `a` or `b` may be passed as ``None``; a suitable `c` will be
inferred.
If the integral cannot be computed in closed form, this function returns
an unevaluated :class:`InverseMellinTransform` object.
Note that this function will assume x to be positive and real, regardless
of the SymPy assumptions!
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Examples
========
>>> from sympy import inverse_mellin_transform, oo, gamma
>>> from sympy.abc import x, s
>>> inverse_mellin_transform(gamma(s), s, x, (0, oo))
exp(-x)
The fundamental strip matters:
>>> f = 1/(s**2 - 1)
>>> inverse_mellin_transform(f, s, x, (-oo, -1))
x*(1 - 1/x**2)*Heaviside(x - 1)/2
>>> inverse_mellin_transform(f, s, x, (-1, 1))
-x*Heaviside(1 - x)/2 - Heaviside(x - 1)/(2*x)
>>> inverse_mellin_transform(f, s, x, (1, oo))
(1/2 - x**2/2)*Heaviside(1 - x)/x
See Also
========
mellin_transform
hankel_transform, inverse_hankel_transform
"""
return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints)
##########################################################################
# Laplace Transform
##########################################################################
def _simplifyconds(expr, s, a):
r"""
Naively simplify some conditions occurring in ``expr``, given that `\operatorname{Re}(s) > a`.
Examples
========
>>> from sympy.integrals.transforms import _simplifyconds as simp
>>> from sympy.abc import x
>>> from sympy import sympify as S
>>> simp(abs(x**2) < 1, x, 1)
False
>>> simp(abs(x**2) < 1, x, 2)
False
>>> simp(abs(x**2) < 1, x, 0)
Abs(x**2) < 1
>>> simp(abs(1/x**2) < 1, x, 1)
True
>>> simp(S(1) < abs(x), x, 1)
True
>>> simp(S(1) < abs(1/x), x, 1)
False
>>> from sympy import Ne
>>> simp(Ne(1, x**3), x, 1)
True
>>> simp(Ne(1, x**3), x, 2)
True
>>> simp(Ne(1, x**3), x, 0)
Ne(1, x**3)
"""
def power(ex):
if ex == s:
return 1
if ex.is_Pow and ex.base == s:
return ex.exp
return None
def bigger(ex1, ex2):
""" Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|.
Else return None. """
if ex1.has(s) and ex2.has(s):
return None
if isinstance(ex1, Abs):
ex1 = ex1.args[0]
if isinstance(ex2, Abs):
ex2 = ex2.args[0]
if ex1.has(s):
return bigger(1/ex2, 1/ex1)
n = power(ex2)
if n is None:
return None
try:
if n > 0 and (Abs(ex1) <= Abs(a)**n) == True:
return False
if n < 0 and (Abs(ex1) >= Abs(a)**n) == True:
return True
except TypeError:
pass
def replie(x, y):
""" simplify x < y """
if not (x.is_positive or isinstance(x, Abs)) \
or not (y.is_positive or isinstance(y, Abs)):
return (x < y)
r = bigger(x, y)
if r is not None:
return not r
return (x < y)
def replue(x, y):
b = bigger(x, y)
if b in (True, False):
return True
return Unequality(x, y)
def repl(ex, *args):
if ex in (True, False):
return bool(ex)
return ex.replace(*args)
from sympy.simplify.radsimp import collect_abs
expr = collect_abs(expr)
expr = repl(expr, Lt, replie)
expr = repl(expr, Gt, lambda x, y: replie(y, x))
expr = repl(expr, Unequality, replue)
return S(expr)
def expand_dirac_delta(expr):
"""
Expand an expression involving DiractDelta to get it as a linear
combination of DiracDelta functions.
"""
return _lin_eq2dict(expr, expr.atoms(DiracDelta))
@_noconds
def _laplace_transform(f, t, s_, simplify=True):
""" The backend function for Laplace transforms.
This backend assumes that the frontend has already split sums
such that `f` is to an addition anymore.
"""
s = Dummy('s')
a = Wild('a', exclude=[t])
deltazero = []
deltanonzero = []
try:
integratable, deltadict = expand_dirac_delta(f)
except PolyNonlinearError:
raise IntegralTransformError(
'Laplace', f, 'could not expand DiracDelta expressions')
for dirac_func, dirac_coeff in deltadict.items():
p = dirac_func.match(DiracDelta(a*t))
if p:
deltazero.append(dirac_coeff.subs(t,0)/p[a])
else:
if dirac_func.args[0].subs(t,0).is_zero:
raise IntegralTransformError('Laplace', f,\
'not implemented yet.')
else:
deltanonzero.append(dirac_func*dirac_coeff)
F = Add(integrate(exp(-s*t) * Add(integratable, *deltanonzero),
(t, S.Zero, S.Infinity)),
Add(*deltazero))
if not F.has(Integral):
return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true
if not F.is_Piecewise:
raise IntegralTransformError(
'Laplace', f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(
'Laplace', f, 'integral in unexpected form')
def process_conds(conds):
""" Turn ``conds`` into a strip and auxiliary conditions. """
from sympy.solvers.inequalities import _solve_inequality
a = S.NegativeInfinity
aux = S.true
conds = conjuncts(to_cnf(conds))
p, q, w1, w2, w3, w4, w5 = symbols(
'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s])
patterns = (
p*Abs(arg((s + w3)*q)) < w2,
p*Abs(arg((s + w3)*q)) <= w2,
Abs(periodic_argument((s + w3)**p*q, w1)) < w2,
Abs(periodic_argument((s + w3)**p*q, w1)) <= w2,
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2,
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2)
for c in conds:
a_ = S.Infinity
aux_ = []
for d in disjuncts(c):
if d.is_Relational and s in d.rhs.free_symbols:
d = d.reversed
if d.is_Relational and isinstance(d, (Ge, Gt)):
d = d.reversedsign
for pat in patterns:
m = d.match(pat)
if m:
break
if m:
if m[q].is_positive and m[w2]/m[p] == pi/2:
d = -re(s + m[w3]) < 0
m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0)
if not m:
m = d.match(
cos(p - Abs(periodic_argument(s**w1*w5, q))*w2)*Abs(s**w3)**w4 < 0)
if not m:
m = d.match(
p - cos(Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2
)*Abs(s**w3)**w4 < 0)
if m and all(m[wild].is_positive for wild in [w1, w2, w3, w4, w5]):
d = re(s) > m[p]
d_ = d.replace(
re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t)
if not d.is_Relational or \
d.rel_op in ('==', '!=') \
or d_.has(s) or not d_.has(t):
aux_ += [d]
continue
soln = _solve_inequality(d_, t)
if not soln.is_Relational or \
soln.rel_op in ('==', '!='):
aux_ += [d]
continue
if soln.lts == t:
raise IntegralTransformError('Laplace', f,
'convergence not in half-plane?')
else:
a_ = Min(soln.lts, a_)
if a_ is not S.Infinity:
a = Max(a_, a)
else:
aux = And(aux, Or(*aux_))
return a, aux.canonical if aux.is_Relational else aux
conds = [process_conds(c) for c in disjuncts(cond)]
conds2 = [x for x in conds if x[1] != False and x[0] is not S.NegativeInfinity]
if not conds2:
conds2 = [x for x in conds if x[1] != False]
conds = list(ordered(conds2))
def cnt(expr):
if expr in (True, False):
return 0
return expr.count_ops()
conds.sort(key=lambda x: (-x[0], cnt(x[1])))
if not conds:
raise IntegralTransformError('Laplace', f, 'no convergence found')
a, aux = conds[0] # XXX is [0] always the right one?
def sbs(expr):
return expr.subs(s, s_)
if simplify:
F = _simplifyconds(F, s, a)
aux = _simplifyconds(aux, s, a)
return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux))
def _laplace_deep_collect(f, t):
"""
This is an internal helper function that traverses through the epression
tree of `f(t)` and collects arguments. The purpose of it is that
anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that
it can match `f(a*t+b)`.
"""
func = f.func
args = list(f.args)
if len(f.args) == 0:
return f
else:
args = [_laplace_deep_collect(arg, t) for arg in args]
if func.is_Add:
return func(*args).collect(t)
else:
return func(*args)
def _laplace_build_rules(t, s):
"""
This is an internal helper function that returns the table of Laplace
transfrom rules in terms of the time variable `t` and the frequency
variable `s`. It is used by `_laplace_apply_rules`.
"""
a = Wild('a', exclude=[t])
b = Wild('b', exclude=[t])
n = Wild('n', exclude=[t])
tau = Wild('tau', exclude=[t])
omega = Wild('omega', exclude=[t])
dco = lambda f: _laplace_deep_collect(f,t)
laplace_transform_rules = [
# ( time domain,
# laplace domain,
# condition, convergence plane, preparation function )
#
# Catch constant (would otherwise be treated by 2.12)
(a, a/s, S.true, S.Zero, dco),
# DiracDelta rules
(DiracDelta(a*t-b),
exp(-s*b/a)/Abs(a),
Or(And(a>0, b>=0), And(a<0, b<=0)), S.Zero, dco),
(DiracDelta(a*t-b),
S(0),
Or(And(a<0, b>=0), And(a>0, b<=0)), S.Zero, dco),
# Rules from http://eqworld.ipmnet.ru/en/auxiliary/inttrans/
# 2.1
(1,
1/s,
S.true, S.Zero, dco),
# 2.2 expressed in terms of Heaviside
(Heaviside(a*t-b),
exp(-s*b/a)/s,
And(a>0, b>0), S.Zero, dco),
(Heaviside(a*t-b),
(1-exp(-s*b/a))/s,
And(a<0, b<0), S.Zero, dco),
(Heaviside(a*t-b),
1/s,
And(a>0, b<=0), S.Zero, dco),
(Heaviside(a*t-b),
0,
And(a<0, b>0), S.Zero, dco),
# 2.3
(t,
1/s**2,
S.true, S.Zero, dco),
# 2.4
(1/(a*t+b),
-exp(-b/a*s)*Ei(-b/a*s)/a,
a>0, S.Zero, dco),
# 2.5 and 2.6 are covered by 2.11
# 2.7
(1/sqrt(a*t+b),
sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a,
a>0, S.Zero, dco),
# 2.8
(sqrt(t)/(t+b),
sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)),
S.true, S.Zero, dco),
# 2.9
((a*t+b)**(-S(3)/2),
2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s)*erfc(sqrt(b/a*s))/a,
a>0, S.Zero, dco),
# 2.10
(t**(S(1)/2)*(t+a)**(-1),
(pi/s)**(S(1)/2)-pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)),
S.true, S.Zero, dco),
# 2.11
(1/(a*sqrt(t) + t**(3/2)),
pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)),
S.true, S.Zero, dco),
# 2.12
(t**n,
gamma(n+1)/s**(n+1),
n>-1, S.Zero, dco),
# 2.13
((a*t+b)**n,
lowergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a,
And(n>-1, a>0), S.Zero, dco),
# 2.14
(t**n/(t+a),
a**n*gamma(n+1)*lowergamma(-n,a*s),
n>-1, S.Zero, dco),
# 3.1
(exp(a*t-tau),
exp(-tau)/(s-a),
S.true, a, dco),
# 3.2
(t*exp(a*t-tau),
exp(-tau)/(s-a)**2,
S.true, a, dco),
# 3.3
(t**n*exp(a*t),
gamma(n+1)/(s-a)**(n+1),
n>-1, a, dco),
# 3.4 and 3.5 cannot be covered here because they are
# sums and only the individual sum terms will get here.
# 3.6
(exp(-a*t**2),
sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)),
a>0, S.Zero, dco),
# 3.7
(t*exp(-a*t**2),
1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)),
S.true, S.Zero, dco),
# 3.8
(exp(-a/t),
2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)),
a>=0, S.Zero, dco),
# 3.9
(sqrt(t)*exp(-a/t),
S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)),
a>=0, S.Zero, dco),
# 3.10
(exp(-a/t)/sqrt(t),
sqrt(pi/s)*exp(-2*sqrt(a*s)),
a>=0, S.Zero, dco),
# 3.11
(exp(-a/t)/(t*sqrt(t)),
sqrt(pi/a)*exp(-2*sqrt(a*s)),
a>0, S.Zero, dco),
# 3.12
(t**n*exp(-a/t),
2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)),
a>0, S.Zero, dco),
# 3.13
(exp(-2*sqrt(a*t)),
s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s)*erfc(sqrt(a/s)),
S.true, S.Zero, dco),
# 3.14
(exp(-2*sqrt(a*t))/sqrt(t),
(pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)),
S.true, S.Zero, dco),
# 4.1
(sinh(a*t),
a/(s**2-a**2),
S.true, Abs(a), dco),
# 4.2
(sinh(a*t)**2,
2*a**2/(s**3-4*a**2*s**2),
S.true, Abs(2*a), dco),
# 4.3
(sinh(a*t)/t,
log((s+a)/(s-a))/2,
S.true, a, dco),
# 4.4
(t**n*sinh(a*t),
gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)),
n>-2, Abs(a), dco),
# 4.5
(sinh(2*sqrt(a*t)),
sqrt(pi*a)/s/sqrt(s)*exp(a/s),
S.true, S.Zero, dco),
# 4.6
(sqrt(t)*sinh(2*sqrt(a*t)),
pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2),
S.true, S.Zero, dco),
# 4.7
(sinh(2*sqrt(a*t))/sqrt(t),
pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s)*erf(sqrt(a/s)),
S.true, S.Zero, dco),
# 4.8
(sinh(sqrt(a*t))**2/sqrt(t),
pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1),
S.true, S.Zero, dco),
# 4.9
(cosh(a*t),
s/(s**2-a**2),
S.true, Abs(a), dco),
# 4.10
(cosh(a*t)**2,
(s**2-2*a**2)/(s**3-4*a**2*s**2),
S.true, Abs(2*a), dco),
# 4.11
(t**n*cosh(a*t),
gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)),
n>-1, Abs(a), dco),
# 4.12
(cosh(2*sqrt(a*t)),
1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)),
S.true, S.Zero, dco),
# 4.13
(sqrt(t)*cosh(2*sqrt(a*t)),
pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s),
S.true, S.Zero, dco),
# 4.14
(cosh(2*sqrt(a*t))/sqrt(t),
pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s),
S.true, S.Zero, dco),
# 4.15
(cosh(sqrt(a*t))**2/sqrt(t),
pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1),
S.true, S.Zero, dco),
# 5.1
(log(a*t),
-log(s/a+S.EulerGamma)/s,
a>0, S.Zero, dco),
# 5.2
(log(1+a*t),
-exp(s/a)/s*Ei(-s/a),
S.true, S.Zero, dco),
# 5.3
(log(a*t+b),
(log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a,
a>0, S.Zero, dco),
# 5.4 is covered by 5.7
# 5.5
(log(t)/sqrt(t),
-sqrt(pi/s)*(log(4*s)+S.EulerGamma),
S.true, S.Zero, dco),
# 5.6 is covered by 5.7
# 5.7
(t**n*log(t),
gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)),
n>-1, S.Zero, dco),
# 5.8
(log(a*t)**2,
((log(s/a)+S.EulerGamma)**2+pi**2/6)/s,
a>0, S.Zero, dco),
# 5.9
(exp(-a*t)*log(t),
-(log(s+a)+S.EulerGamma)/(s+a),
S.true, -a, dco),
# 6.1
(sin(omega*t),
omega/(s**2+omega**2),
S.true, S.Zero, dco),
# 6.2
(Abs(sin(omega*t)),
omega/(s**2+omega**2)*coth(pi*s/2/omega),
omega>0, S.Zero, dco),
# 6.3 and 6.4 are covered by 1.8
# 6.5 is covered by 1.8 together with 2.5
# 6.6
(sin(omega*t)/t,
atan(omega/s),
S.true, S.Zero, dco),
# 6.7
(sin(omega*t)**2/t,
log(1+4*omega**2/s**2)/4,
S.true, S.Zero, dco),
# 6.8
(sin(omega*t)**2/t**2,
omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4,
S.true, S.Zero, dco),
# 6.9
(sin(2*sqrt(a*t)),
sqrt(pi*a)/s/sqrt(s)*exp(-a/s),
a>0, S.Zero, dco),
# 6.10
(sin(2*sqrt(a*t))/t,
pi*erf(sqrt(a/s)),
a>0, S.Zero, dco),
# 6.11
(cos(omega*t),
s/(s**2+omega**2),
S.true, S.Zero, dco),
# 6.12
(cos(omega*t)**2,
(s**2+2*omega**2)/(s**2+4*omega**2)/s,
S.true, S.Zero, dco),
# 6.13 is covered by 1.9 together with 2.5
# 6.14 and 6.15 cannot be done with this method, the respective sum
# parts do not converge. Solve elsewhere if really needed.
# 6.16
(sqrt(t)*cos(2*sqrt(a*t)),
sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s),
a>0, S.Zero, dco),
# 6.17
(cos(2*sqrt(a*t))/sqrt(t),
sqrt(pi/s)*exp(-a/s),
a>0, S.Zero, dco),
# 6.18
(sin(a*t)*sin(b*t),
2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2),
S.true, S.Zero, dco),
# 6.19
(cos(a*t)*sin(b*t),
b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
S.true, S.Zero, dco),
# 6.20
(cos(a*t)*cos(b*t),
s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
S.true, S.Zero, dco),
# 6.21
(exp(b*t)*sin(a*t),
a/((s-b)**2+a**2),
S.true, b, dco),
# 6.22
(exp(b*t)*cos(a*t),
(s-b)/((s-b)**2+a**2),
S.true, b, dco),
# 7.1
(erf(a*t),
exp(s**2/(2*a)**2)*erfc(s/(2*a))/s,
a>0, S.Zero, dco),
# 7.2
(erf(sqrt(a*t)),
sqrt(a)/sqrt(s+a)/s,
a>0, S.Zero, dco),
# 7.3
(exp(a*t)*erf(sqrt(a*t)),
sqrt(a)/sqrt(s)/(s-a),
a>0, a, dco),
# 7.4
(erf(sqrt(a/t)/2),
(1-exp(-sqrt(a*s)))/s,
a>0, S.Zero, dco),
# 7.5
(erfc(sqrt(a*t)),
(sqrt(s+a)-sqrt(a))/sqrt(s+a)/s,
a>0, S.Zero, dco),
# 7.6
(exp(a*t)*erfc(sqrt(a*t)),
1/(s+sqrt(a*s)),
a>0, S.Zero, dco),
# 7.7
(erfc(sqrt(a/t)/2),
exp(-sqrt(a*s))/s,
a>0, S.Zero, dco),
# 8.1, 8.2
(besselj(n, a*t),
a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n),
And(a>0, n>-1), S.Zero, dco),
# 8.3, 8.4
(t**b*besselj(n, a*t),
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half),
And(And(a>0, n>-S.Half), Eq(b, n)), S.Zero, dco),
# 8.5
(t**b*besselj(n, a*t),
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2),
And(And(a>0, n>-1), Eq(b, n+1)), S.Zero, dco),
# 8.6
(besselj(0, 2*sqrt(a*t)),
exp(-a/s)/s,
a>0, S.Zero, dco),
# 8.7, 8.8
(t**(b)*besselj(n, 2*sqrt(a*t)),
a**(n/2)*s**(-n-1)*exp(-a/s),
And(And(a>0, n>-1), Eq(b, n*S.Half)), S.Zero, dco),
# 8.9
(besselj(0, a*sqrt(t**2+b*t)),
exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2),
b>0, S.Zero, dco),
# 8.10, 8.11
(besseli(n, a*t),
a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n),
And(a>0, n>-1), Abs(a), dco),
# 8.12
(t**b*besseli(n, a*t),
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half),
And(And(a>0, n>-S.Half), Eq(b, n)), Abs(a), dco),
# 8.13
(t**b*besseli(n, a*t),
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2),
And(And(a>0, n>-1), Eq(b, n+1)), Abs(a), dco),
# 8.15, 8.16
(t**(b)*besseli(n, 2*sqrt(a*t)),
a**(n/2)*s**(-n-1)*exp(a/s),
And(And(a>0, n>-1), Eq(b, n*S.Half)), S.Zero, dco),
# 8.17
(bessely(0, a*t),
-2/pi*asinh(s/a)/sqrt(s**2+a**2),
a>0, S.Zero, dco),
# 8.18
(besselk(0, a*t),
(log(s+sqrt(s**2-a**2)))/(sqrt(s**2-a**2)),
a>0, Abs(a), dco)
]
return laplace_transform_rules
def _laplace_cr(f, a, c, **hints):
"""
Internal helper function that will return `(f, a, c)` unless `**hints`
contains `noconds=True`, in which case it will only return `f`.
"""
conds = not hints.get('noconds', False)
if conds:
return f, a, c
else:
return f
def _laplace_rule_timescale(f, t, s, doit=True, **hints):
r"""
This internal helper function tries to apply the time-scaling rule of the
Laplace transform and returns `None` if it cannot do it.
Time-scaling means the following: if $F(s)$ is the Laplace transform of,
$f(t)$, then, for any $a>0$, the Laplace transform of $f(at)$ will be
$\frac1a F(\frac{s}{a})$. This scaling will also affect the transform's
convergence plane.
"""
_simplify = hints.pop('simplify', True)
b = Wild('b', exclude=[t])
g = WildFunction('g', nargs=1)
k, func = f.as_independent(t, as_Add=False)
ma1 = func.match(g)
if ma1:
arg = ma1[g].args[0].collect(t)
ma2 = arg.match(b*t)
if ma2 and ma2[b]>0:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s )'%(f, ma1, ma2))
debug(' rule: amplitude and time scaling (1.1, 1.2)')
if ma2[b]==1:
if doit==True and not any(func.has(t) for func
in ma1[g].atoms(AppliedUndef)):
return k*_laplace_transform(ma1[g].func(t), t, s,
simplify=_simplify)
else:
return k*LaplaceTransform(ma1[g].func(t), t, s, **hints)
else:
L = _laplace_apply_rules(ma1[g].func(t), t, s/ma2[b],
doit=doit, **hints)
try:
r, p, c = L
return (k/ma2[b]*r, p, c)
except TypeError:
return k/ma2[b]*L
return None
def _laplace_rule_heaviside(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform a product containing the
`Heaviside` function and returns `None` if it cannot do it.
"""
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
b = Wild('b', exclude=[t])
y = Wild('y')
g = WildFunction('g', nargs=1)
k, func = f.as_independent(t, as_Add=False)
ma1 = func.match(Heaviside(y)*g)
if ma1:
ma2 = ma1[y].match(t-a)
ma3 = ma1[g].args[0].collect(t).match(t-b)
if ma2 and ma2[a]>0 and ma3 and ma2[a]==ma3[b]:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s, %s )'%(f, ma1, ma2, ma3))
debug(' rule: time shift (1.3)')
L = _laplace_apply_rules(ma1[g].func(t), t, s, doit=doit, **hints)
try:
r, p, c = L
return (k*exp(-ma2[a]*s)*r, p, c)
except TypeError:
return k*exp(-ma2[a]*s)*L
return None
def _laplace_rule_exp(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform a product containing the
`exp` function and returns `None` if it cannot do it.
"""
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
z = Wild('z')
k, func = f.as_independent(t, as_Add=False)
ma1 = func.match(exp(y)*z)
if ma1:
ma2 = ma1[y].collect(t).match(a*t)
if ma2:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s )'%(f, ma1, ma2))
debug(' rule: multiply with exp (1.5)')
L = _laplace_apply_rules(ma1[z], t, s-ma2[a], doit=doit, **hints)
try:
r, p, c = L
return (r, p+ma2[a], c)
except TypeError:
return L
return None
def _laplace_rule_trig(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform a product containing a
trigonometric function (`sin`, `cos`, `sinh`, `cosh`, ) and returns
`None` if it cannot do it.
"""
_simplify = hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
z = Wild('z')
k, func = f.as_independent(t, as_Add=False)
# All of the rules have a very similar form: trig(y)*z is matched, and then
# two copies of the Laplace transform of z are shifted in the s Domain
# and added with a weight; see rules 1.6 to 1.9 in
# http://eqworld.ipmnet.ru/en/auxiliary/inttrans/laplace1.pdf
# The parameters in the tuples are (fm, nu, s1, s2, sd):
# fm: Function to match
# nu: Number of the rule, for debug purposes
# s1: weight of the sum, 'I' for sin and '1' for all others
# s2: sign of the second copy of the Laplace transform of z
# sd: shift direction; shift along real or imaginary axis if `1` or `I`
trigrules = [(sinh(y), '1.6', 1, -1, 1), (cosh(y), '1.7', 1, 1, 1),
(sin(y), '1.8', -I, -1, I), (cos(y), '1.9', 1, 1, I)]
for trigrule in trigrules:
fm, nu, s1, s2, sd = trigrule
ma1 = func.match(fm*z)
if ma1:
ma2 = ma1[y].collect(t).match(a*t)
if ma2:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s )'%(f, ma1, ma2))
debug(' rule: multiply with %s (%s)'%(fm.func, nu))
L = _laplace_apply_rules(ma1[z], t, s, doit=doit, **hints)
try:
r, p, c = L
# The convergence plane changes only if the shift has been
# done along the real axis:
if sd==1:
cp_shift = Abs(ma2[a])
else:
cp_shift = 0
return ((s1*(r.subs(s, s-sd*ma2[a])+\
s2*r.subs(s, s+sd*ma2[a]))).simplify()/2,
p+cp_shift, c)
except TypeError:
if doit==True and _simplify==True:
return (s1*(L.subs(s, s-sd*ma2[a])+\
s2*L.subs(s, s+sd*ma2[a]))).simplify()/2
else:
return (s1*(L.subs(s, s-sd*ma2[a])+\
s2*L.subs(s, s+sd*ma2[a])))/2
return None
def _laplace_rule_diff(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform an expression containing
a derivative of an undefined function and returns `None` if it cannot
do it.
"""
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
n = Wild('n', exclude=[t])
g = WildFunction('g', nargs=1)
ma1 = f.match(a*Derivative(g, (t, n)))
if ma1 and ma1[g].args[0] == t and ma1[n].is_integer:
debug('_laplace_apply_rules match:')
debug(' f: %s'%(f,))
debug(' rule: time derivative (1.11, 1.12)')
d = []
for k in range(ma1[n]):
if k==0:
y = ma1[g].func(t).subs(t, 0)
else:
y = Derivative(ma1[g].func(t), (t, k)).subs(t, 0)
d.append(s**(ma1[n]-k-1)*y)
r = s**ma1[n]*_laplace_apply_rules(ma1[g].func(t), t, s, doit=doit,
**hints)
return ma1[a]*(r - Add(*d))
return None
def _laplace_apply_rules(f, t, s, doit=True, **hints):
"""
Helper function for the class LaplaceTransform.
This function does a Laplace transform based on rules and, after
applying the rules, hands the rest over to `_laplace_transform`, which
will attempt to integrate.
If it is called with `doit=False`, then it will instead return
`LaplaceTransform` objects.
"""
k, func = f.as_independent(t, as_Add=False)
simple_rules = _laplace_build_rules(t, s)
for t_dom, s_dom, check, plane, prep in simple_rules:
ma = prep(func).match(t_dom)
if ma:
debug('_laplace_apply_rules match:')
debug(' f: %s'%(func,))
debug(' rule: %s o---o %s'%(t_dom, s_dom))
try:
debug(' try %s'%(check,))
c = check.xreplace(ma)
debug(' check %s -> %s'%(check, c))
if c==True:
return _laplace_cr(k*s_dom.xreplace(ma),
plane.xreplace(ma), S.true, **hints)
except Exception:
debug('_laplace_apply_rules did not match.')
if f.has(DiracDelta):
return None
prog_rules = [_laplace_rule_timescale, _laplace_rule_heaviside,
_laplace_rule_exp, _laplace_rule_trig, _laplace_rule_diff]
for p_rule in prog_rules:
LT = p_rule(f, t, s, doit=doit, **hints)
if LT is not None:
return LT
return None
class LaplaceTransform(IntegralTransform):
"""
Class representing unevaluated Laplace transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Laplace transforms, see the :func:`laplace_transform`
docstring.
"""
_name = 'Laplace'
def _compute_transform(self, f, t, s, **hints):
LT = _laplace_apply_rules(f, t, s, **hints)
if LT is None:
_simplify = hints.pop('simplify', True)
debug('_laplace_apply_rules could not match function %s'%(f,))
debug(' hints: %s'%(hints,))
return _laplace_transform(f, t, s, simplify=_simplify, **hints)
else:
return LT
def _as_integral(self, f, t, s):
return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity))
def _collapse_extra(self, extra):
conds = []
planes = []
for plane, cond in extra:
conds.append(cond)
planes.append(plane)
cond = And(*conds)
plane = Max(*planes)
if cond == False:
raise IntegralTransformError(
'Laplace', None, 'No combined convergence.')
return plane, cond
def _try_directly(self, **hints):
fn = self.function
debug('----> _try_directly: %s'%(fn, ))
t_ = self.function_variable
s_ = self.transform_variable
LT = None
if not fn.is_Add:
fn = expand_mul(fn)
try:
LT = self._compute_transform(fn, t_, s_, **hints)
except IntegralTransformError:
LT = None
return fn, LT
def laplace_transform(f, t, s, legacy_matrix=True, **hints):
r"""
Compute the Laplace Transform `F(s)` of `f(t)`,
.. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t.
Explanation
===========
For all sensible functions, this converges absolutely in a
half-plane
.. math :: a < \operatorname{Re}(s)
This function returns ``(F, a, cond)`` where ``F`` is the Laplace
transform of ``f``, `a` is the half-plane of convergence, and `cond` are
auxiliary convergence conditions.
The implementation is rule-based, and if you are interested in which
rules are applied, and whether integration is attemped, you can switch
debug information on by setting ``sympy.SYMPY_DEBUG=True``.
The lower bound is `0-`, meaning that this bound should be approached
from the lower side. This is only necessary if distributions are involved.
At present, it is only done if `f(t)` contains ``DiracDelta``, in which
case the Laplace transform is computed implicitly as
.. math :: F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} f(t) \mathrm{d}t
by applying rules.
If the integral cannot be fully computed in closed form, this function
returns an unevaluated :class:`LaplaceTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=True``,
only `F` will be returned (i.e. not ``cond``, and also not the plane ``a``).
.. deprecated:: 1.9
Legacy behavior for matrices where ``laplace_transform`` with
``noconds=False`` (the default) returns a Matrix whose elements are
tuples. The behavior of ``laplace_transform`` for matrices will change
in a future release of SymPy to return a tuple of the transformed
Matrix and the convergence conditions for the matrix as a whole. Use
``legacy_matrix=False`` to enable the new behavior.
Examples
========
>>> from sympy import DiracDelta, exp, laplace_transform
>>> from sympy.abc import t, s, a
>>> laplace_transform(t**4, t, s)
(24/s**5, 0, True)
>>> laplace_transform(t**a, t, s)
(s**(-a - 1)*gamma(a + 1), 0, re(a) > -1)
>>> laplace_transform(DiracDelta(t)-a*exp(-a*t),t,s)
(s/(a + s), Max(0, -a), True)
See Also
========
inverse_laplace_transform, mellin_transform, fourier_transform
hankel_transform, inverse_hankel_transform
"""
debug('\n***** laplace_transform(%s, %s, %s)'%(f, t, s))
if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'):
conds = not hints.get('noconds', False)
if conds and legacy_matrix:
sympy_deprecation_warning(
"""
Calling laplace_transform() on a Matrix with noconds=False (the default) is
deprecated. Either noconds=True or use legacy_matrix=False to get the new
behavior.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-laplace-transform-matrix",
)
# Temporarily disable the deprecation warning for non-Expr objects
# in Matrix
with ignore_warnings(SymPyDeprecationWarning):
return f.applyfunc(lambda fij: laplace_transform(fij, t, s, **hints))
else:
elements_trans = [laplace_transform(fij, t, s, **hints) for fij in f]
if conds:
elements, avals, conditions = zip(*elements_trans)
f_laplace = type(f)(*f.shape, elements)
return f_laplace, Max(*avals), And(*conditions)
else:
return type(f)(*f.shape, elements_trans)
return LaplaceTransform(f, t, s).doit(**hints)
@_noconds_(True)
def _inverse_laplace_transform(F, s, t_, plane, simplify=True):
""" The backend function for inverse Laplace transforms. """
from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp
# There are two strategies we can try:
# 1) Use inverse mellin transforms - related by a simple change of variables.
# 2) Use the inversion integral.
t = Dummy('t', real=True)
def pw_simp(*args):
""" Simplify a piecewise expression from hyperexpand. """
# XXX we break modularity here!
if len(args) != 3:
return Piecewise(*args)
arg = args[2].args[0].argument
coeff, exponent = _get_coeff_exp(arg, t)
e1 = args[0].args[0]
e2 = args[1].args[0]
return Heaviside(1/Abs(coeff) - t**exponent)*e1 \
+ Heaviside(t**exponent - 1/Abs(coeff))*e2
if F.is_rational_function(s):
F = F.apart(s)
if F.is_Add:
f = Add(*[_inverse_laplace_transform(X, s, t, plane, simplify)\
for X in F.args])
return _simplify(f.subs(t, t_), simplify), True
try:
f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity),
needeval=True, noconds=False)
except IntegralTransformError:
f = None
if f is None:
f = meijerint_inversion(F, s, t)
if f is None:
raise IntegralTransformError('Inverse Laplace', f, '')
if f.is_Piecewise:
f, cond = f.args[0]
if f.has(Integral):
raise IntegralTransformError('Inverse Laplace', f,
'inversion integral of unrecognised form.')
else:
cond = S.true
f = f.replace(Piecewise, pw_simp)
if f.is_Piecewise:
# many of the functions called below can't work with piecewise
# (b/c it has a bool in args)
return f.subs(t, t_), cond
u = Dummy('u')
def simp_heaviside(arg, H0=S.Half):
a = arg.subs(exp(-t), u)
if a.has(t):
return Heaviside(arg, H0)
from sympy.solvers.inequalities import _solve_inequality
rel = _solve_inequality(a > 0, u)
if rel.lts == u:
k = log(rel.gts)
return Heaviside(t + k, H0)
else:
k = log(rel.lts)
return Heaviside(-(t + k), H0)
f = f.replace(Heaviside, simp_heaviside)
def simp_exp(arg):
return expand_complex(exp(arg))
f = f.replace(exp, simp_exp)
# TODO it would be nice to fix cosh and sinh ... simplify messes these
# exponentials up
return _simplify(f.subs(t, t_), simplify), cond
class InverseLaplaceTransform(IntegralTransform):
"""
Class representing unevaluated inverse Laplace transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Laplace transforms, see the
:func:`inverse_laplace_transform` docstring.
"""
_name = 'Inverse Laplace'
_none_sentinel = Dummy('None')
_c = Dummy('c')
def __new__(cls, F, s, x, plane, **opts):
if plane is None:
plane = InverseLaplaceTransform._none_sentinel
return IntegralTransform.__new__(cls, F, s, x, plane, **opts)
@property
def fundamental_plane(self):
plane = self.args[3]
if plane is InverseLaplaceTransform._none_sentinel:
plane = None
return plane
def _compute_transform(self, F, s, t, **hints):
return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints)
def _as_integral(self, F, s, t):
c = self.__class__._c
return Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity,
c + S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit)
def inverse_laplace_transform(F, s, t, plane=None, **hints):
r"""
Compute the inverse Laplace transform of `F(s)`, defined as
.. math :: f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st} F(s) \mathrm{d}s,
for `c` so large that `F(s)` has no singularites in the
half-plane `\operatorname{Re}(s) > c-\epsilon`.
Explanation
===========
The plane can be specified by
argument ``plane``, but will be inferred if passed as None.
Under certain regularity conditions, this recovers `f(t)` from its
Laplace Transform `F(s)`, for non-negative `t`, and vice
versa.
If the integral cannot be computed in closed form, this function returns
an unevaluated :class:`InverseLaplaceTransform` object.
Note that this function will always assume `t` to be real,
regardless of the SymPy assumption on `t`.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Examples
========
>>> from sympy import inverse_laplace_transform, exp, Symbol
>>> from sympy.abc import s, t
>>> a = Symbol('a', positive=True)
>>> inverse_laplace_transform(exp(-a*s)/s, s, t)
Heaviside(-a + t)
See Also
========
laplace_transform, _fast_inverse_laplace
hankel_transform, inverse_hankel_transform
"""
if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'):
return F.applyfunc(lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints))
return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
def _fast_inverse_laplace(e, s, t):
"""Fast inverse Laplace transform of rational function including RootSum"""
a, b, n = symbols('a, b, n', cls=Wild, exclude=[s])
def _ilt(e):
if not e.has(s):
return e
elif e.is_Add:
return _ilt_add(e)
elif e.is_Mul:
return _ilt_mul(e)
elif e.is_Pow:
return _ilt_pow(e)
elif isinstance(e, RootSum):
return _ilt_rootsum(e)
else:
raise NotImplementedError
def _ilt_add(e):
return e.func(*map(_ilt, e.args))
def _ilt_mul(e):
coeff, expr = e.as_independent(s)
if expr.is_Mul:
raise NotImplementedError
return coeff * _ilt(expr)
def _ilt_pow(e):
match = e.match((a*s + b)**n)
if match is not None:
nm, am, bm = match[n], match[a], match[b]
if nm.is_Integer and nm < 0:
return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm))
if nm == 1:
return exp(-(bm/am)*t) / am
raise NotImplementedError
def _ilt_rootsum(e):
expr = e.fun.expr
[variable] = e.fun.variables
return RootSum(e.poly, Lambda(variable, together(_ilt(expr))))
return _ilt(e)
##########################################################################
# Fourier Transform
##########################################################################
@_noconds_(True)
def _fourier_transform(f, x, k, a, b, name, simplify=True):
r"""
Compute a general Fourier-type transform
.. math::
F(k) = a \int_{-\infty}^{\infty} e^{bixk} f(x)\, dx.
For suitable choice of *a* and *b*, this reduces to the standard Fourier
and inverse Fourier transforms.
"""
F = integrate(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity))
if not F.has(Integral):
return _simplify(F, simplify), S.true
integral_f = integrate(f, (x, S.NegativeInfinity, S.Infinity))
if integral_f in (S.NegativeInfinity, S.Infinity, S.NaN) or integral_f.has(Integral):
raise IntegralTransformError(name, f, 'function not integrable on real axis')
if not F.is_Piecewise:
raise IntegralTransformError(name, f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(name, f, 'integral in unexpected form')
return _simplify(F, simplify), cond
class FourierTypeTransform(IntegralTransform):
""" Base class for Fourier transforms."""
def a(self):
raise NotImplementedError(
"Class %s must implement a(self) but does not" % self.__class__)
def b(self):
raise NotImplementedError(
"Class %s must implement b(self) but does not" % self.__class__)
def _compute_transform(self, f, x, k, **hints):
return _fourier_transform(f, x, k,
self.a(), self.b(),
self.__class__._name, **hints)
def _as_integral(self, f, x, k):
a = self.a()
b = self.b()
return Integral(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity))
class FourierTransform(FourierTypeTransform):
"""
Class representing unevaluated Fourier transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Fourier transforms, see the :func:`fourier_transform`
docstring.
"""
_name = 'Fourier'
def a(self):
return 1
def b(self):
return -2*S.Pi
def fourier_transform(f, x, k, **hints):
r"""
Compute the unitary, ordinary-frequency Fourier transform of ``f``, defined
as
.. math:: F(k) = \int_{-\infty}^\infty f(x) e^{-2\pi i x k} \mathrm{d} x.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`FourierTransform` object.
For other Fourier transform conventions, see the function
:func:`sympy.integrals.transforms._fourier_transform`.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import fourier_transform, exp
>>> from sympy.abc import x, k
>>> fourier_transform(exp(-x**2), x, k)
sqrt(pi)*exp(-pi**2*k**2)
>>> fourier_transform(exp(-x**2), x, k, noconds=False)
(sqrt(pi)*exp(-pi**2*k**2), True)
See Also
========
inverse_fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return FourierTransform(f, x, k).doit(**hints)
class InverseFourierTransform(FourierTypeTransform):
"""
Class representing unevaluated inverse Fourier transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Fourier transforms, see the
:func:`inverse_fourier_transform` docstring.
"""
_name = 'Inverse Fourier'
def a(self):
return 1
def b(self):
return 2*S.Pi
def inverse_fourier_transform(F, k, x, **hints):
r"""
Compute the unitary, ordinary-frequency inverse Fourier transform of `F`,
defined as
.. math:: f(x) = \int_{-\infty}^\infty F(k) e^{2\pi i x k} \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseFourierTransform` object.
For other Fourier transform conventions, see the function
:func:`sympy.integrals.transforms._fourier_transform`.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import inverse_fourier_transform, exp, sqrt, pi
>>> from sympy.abc import x, k
>>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x)
exp(-x**2)
>>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x, noconds=False)
(exp(-x**2), True)
See Also
========
fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return InverseFourierTransform(F, k, x).doit(**hints)
##########################################################################
# Fourier Sine and Cosine Transform
##########################################################################
@_noconds_(True)
def _sine_cosine_transform(f, x, k, a, b, K, name, simplify=True):
"""
Compute a general sine or cosine-type transform
F(k) = a int_0^oo b*sin(x*k) f(x) dx.
F(k) = a int_0^oo b*cos(x*k) f(x) dx.
For suitable choice of a and b, this reduces to the standard sine/cosine
and inverse sine/cosine transforms.
"""
F = integrate(a*f*K(b*x*k), (x, S.Zero, S.Infinity))
if not F.has(Integral):
return _simplify(F, simplify), S.true
if not F.is_Piecewise:
raise IntegralTransformError(name, f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(name, f, 'integral in unexpected form')
return _simplify(F, simplify), cond
class SineCosineTypeTransform(IntegralTransform):
"""
Base class for sine and cosine transforms.
Specify cls._kern.
"""
def a(self):
raise NotImplementedError(
"Class %s must implement a(self) but does not" % self.__class__)
def b(self):
raise NotImplementedError(
"Class %s must implement b(self) but does not" % self.__class__)
def _compute_transform(self, f, x, k, **hints):
return _sine_cosine_transform(f, x, k,
self.a(), self.b(),
self.__class__._kern,
self.__class__._name, **hints)
def _as_integral(self, f, x, k):
a = self.a()
b = self.b()
K = self.__class__._kern
return Integral(a*f*K(b*x*k), (x, S.Zero, S.Infinity))
class SineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated sine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute sine transforms, see the :func:`sine_transform`
docstring.
"""
_name = 'Sine'
_kern = sin
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return S.One
def sine_transform(f, x, k, **hints):
r"""
Compute the unitary, ordinary-frequency sine transform of `f`, defined
as
.. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \sin(2\pi x k) \mathrm{d} x.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`SineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import sine_transform, exp
>>> from sympy.abc import x, k, a
>>> sine_transform(x*exp(-a*x**2), x, k)
sqrt(2)*k*exp(-k**2/(4*a))/(4*a**(3/2))
>>> sine_transform(x**(-a), x, k)
2**(1/2 - a)*k**(a - 1)*gamma(1 - a/2)/gamma(a/2 + 1/2)
See Also
========
fourier_transform, inverse_fourier_transform
inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return SineTransform(f, x, k).doit(**hints)
class InverseSineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated inverse sine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse sine transforms, see the
:func:`inverse_sine_transform` docstring.
"""
_name = 'Inverse Sine'
_kern = sin
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return S.One
def inverse_sine_transform(F, k, x, **hints):
r"""
Compute the unitary, ordinary-frequency inverse sine transform of `F`,
defined as
.. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \sin(2\pi x k) \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseSineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import inverse_sine_transform, exp, sqrt, gamma
>>> from sympy.abc import x, k, a
>>> inverse_sine_transform(2**((1-2*a)/2)*k**(a - 1)*
... gamma(-a/2 + 1)/gamma((a+1)/2), k, x)
x**(-a)
>>> inverse_sine_transform(sqrt(2)*k*exp(-k**2/(4*a))/(4*sqrt(a)**3), k, x)
x*exp(-a*x**2)
See Also
========
fourier_transform, inverse_fourier_transform
sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return InverseSineTransform(F, k, x).doit(**hints)
class CosineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated cosine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute cosine transforms, see the :func:`cosine_transform`
docstring.
"""
_name = 'Cosine'
_kern = cos
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return S.One
def cosine_transform(f, x, k, **hints):
r"""
Compute the unitary, ordinary-frequency cosine transform of `f`, defined
as
.. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \cos(2\pi x k) \mathrm{d} x.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`CosineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import cosine_transform, exp, sqrt, cos
>>> from sympy.abc import x, k, a
>>> cosine_transform(exp(-a*x), x, k)
sqrt(2)*a/(sqrt(pi)*(a**2 + k**2))
>>> cosine_transform(exp(-a*sqrt(x))*cos(a*sqrt(x)), x, k)
a*exp(-a**2/(2*k))/(2*k**(3/2))
See Also
========
fourier_transform, inverse_fourier_transform,
sine_transform, inverse_sine_transform
inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return CosineTransform(f, x, k).doit(**hints)
class InverseCosineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated inverse cosine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse cosine transforms, see the
:func:`inverse_cosine_transform` docstring.
"""
_name = 'Inverse Cosine'
_kern = cos
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return S.One
def inverse_cosine_transform(F, k, x, **hints):
r"""
Compute the unitary, ordinary-frequency inverse cosine transform of `F`,
defined as
.. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \cos(2\pi x k) \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseCosineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import inverse_cosine_transform, sqrt, pi
>>> from sympy.abc import x, k, a
>>> inverse_cosine_transform(sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)), k, x)
exp(-a*x)
>>> inverse_cosine_transform(1/sqrt(k), k, x)
1/sqrt(x)
See Also
========
fourier_transform, inverse_fourier_transform,
sine_transform, inverse_sine_transform
cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return InverseCosineTransform(F, k, x).doit(**hints)
##########################################################################
# Hankel Transform
##########################################################################
@_noconds_(True)
def _hankel_transform(f, r, k, nu, name, simplify=True):
r"""
Compute a general Hankel transform
.. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r.
"""
F = integrate(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity))
if not F.has(Integral):
return _simplify(F, simplify), S.true
if not F.is_Piecewise:
raise IntegralTransformError(name, f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(name, f, 'integral in unexpected form')
return _simplify(F, simplify), cond
class HankelTypeTransform(IntegralTransform):
"""
Base class for Hankel transforms.
"""
def doit(self, **hints):
return self._compute_transform(self.function,
self.function_variable,
self.transform_variable,
self.args[3],
**hints)
def _compute_transform(self, f, r, k, nu, **hints):
return _hankel_transform(f, r, k, nu, self._name, **hints)
def _as_integral(self, f, r, k, nu):
return Integral(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity))
@property
def as_integral(self):
return self._as_integral(self.function,
self.function_variable,
self.transform_variable,
self.args[3])
class HankelTransform(HankelTypeTransform):
"""
Class representing unevaluated Hankel transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Hankel transforms, see the :func:`hankel_transform`
docstring.
"""
_name = 'Hankel'
def hankel_transform(f, r, k, nu, **hints):
r"""
Compute the Hankel transform of `f`, defined as
.. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`HankelTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import hankel_transform, inverse_hankel_transform
>>> from sympy import exp
>>> from sympy.abc import r, k, m, nu, a
>>> ht = hankel_transform(1/r**m, r, k, nu)
>>> ht
2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2))
>>> inverse_hankel_transform(ht, k, r, nu)
r**(-m)
>>> ht = hankel_transform(exp(-a*r), r, k, 0)
>>> ht
a/(k**3*(a**2/k**2 + 1)**(3/2))
>>> inverse_hankel_transform(ht, k, r, 0)
exp(-a*r)
See Also
========
fourier_transform, inverse_fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
inverse_hankel_transform
mellin_transform, laplace_transform
"""
return HankelTransform(f, r, k, nu).doit(**hints)
class InverseHankelTransform(HankelTypeTransform):
"""
Class representing unevaluated inverse Hankel transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Hankel transforms, see the
:func:`inverse_hankel_transform` docstring.
"""
_name = 'Inverse Hankel'
def inverse_hankel_transform(F, k, r, nu, **hints):
r"""
Compute the inverse Hankel transform of `F` defined as
.. math:: f(r) = \int_{0}^\infty F_\nu(k) J_\nu(k r) k \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseHankelTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import hankel_transform, inverse_hankel_transform
>>> from sympy import exp
>>> from sympy.abc import r, k, m, nu, a
>>> ht = hankel_transform(1/r**m, r, k, nu)
>>> ht
2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2))
>>> inverse_hankel_transform(ht, k, r, nu)
r**(-m)
>>> ht = hankel_transform(exp(-a*r), r, k, 0)
>>> ht
a/(k**3*(a**2/k**2 + 1)**(3/2))
>>> inverse_hankel_transform(ht, k, r, 0)
exp(-a*r)
See Also
========
fourier_transform, inverse_fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform
mellin_transform, laplace_transform
"""
return InverseHankelTransform(F, k, r, nu).doit(**hints)
|
54bfc912ee81aa197cc1230bd5463d9e294e8da7e192315e9d5182555d6955b7 | """
Algorithms for solving Parametric Risch Differential Equations.
The methods used for solving Parametric Risch Differential Equations parallel
those for solving Risch Differential Equations. See the outline in the
docstring of rde.py for more information.
The Parametric Risch Differential Equation problem is, given f, g1, ..., gm in
K(t), to determine if there exist y in K(t) and c1, ..., cm in Const(K) such
that Dy + f*y == Sum(ci*gi, (i, 1, m)), and to find such y and ci if they exist.
For the algorithms here G is a list of tuples of factions of the terms on the
right hand side of the equation (i.e., gi in k(t)), and Q is a list of terms on
the right hand side of the equation (i.e., qi in k[t]). See the docstring of
each function for more information.
"""
import itertools
from functools import reduce
from sympy.core import Dummy, ilcm, Add, Mul, Pow, S
from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer,
bound_degree)
from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation,
residue_reduce, splitfactor, residue_reduce_derivation, DecrementLevel,
recognize_log_derivative)
from sympy.polys import Poly, lcm, cancel, sqf_list
from sympy.polys.polymatrix import PolyMatrix as Matrix
from sympy.solvers import solve
zeros = Matrix.zeros
eye = Matrix.eye
def prde_normal_denom(fa, fd, G, DE):
"""
Parametric Risch Differential Equation - Normal part of the denominator.
Explanation
===========
Given a derivation D on k[t] and f, g1, ..., gm in k(t) with f weakly
normalized with respect to t, return the tuple (a, b, G, h) such that
a, h in k[t], b in k<t>, G = [g1, ..., gm] in k(t)^m, and for any solution
c1, ..., cm in Const(k) and y in k(t) of Dy + f*y == Sum(ci*gi, (i, 1, m)),
q == y*h in k<t> satisfies a*Dq + b*q == Sum(ci*Gi, (i, 1, m)).
"""
dn, ds = splitfactor(fd, DE)
Gas, Gds = list(zip(*G))
gd = reduce(lambda i, j: i.lcm(j), Gds, Poly(1, DE.t))
en, es = splitfactor(gd, DE)
p = dn.gcd(en)
h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t)))
a = dn*h
c = a*h
ba = a*fa - dn*derivation(h, DE)*fd
ba, bd = ba.cancel(fd, include=True)
G = [(c*A).cancel(D, include=True) for A, D in G]
return (a, (ba, bd), G, h)
def real_imag(ba, bd, gen):
"""
Helper function, to get the real and imaginary part of a rational function
evaluated at sqrt(-1) without actually evaluating it at sqrt(-1).
Explanation
===========
Separates the even and odd power terms by checking the degree of terms wrt
mod 4. Returns a tuple (ba[0], ba[1], bd) where ba[0] is real part
of the numerator ba[1] is the imaginary part and bd is the denominator
of the rational function.
"""
bd = bd.as_poly(gen).as_dict()
ba = ba.as_poly(gen).as_dict()
denom_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in bd.items()]
denom_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in bd.items()]
bd_real = sum(r for r in denom_real)
bd_imag = sum(r for r in denom_imag)
num_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in ba.items()]
num_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in ba.items()]
ba_real = sum(r for r in num_real)
ba_imag = sum(r for r in num_imag)
ba = ((ba_real*bd_real + ba_imag*bd_imag).as_poly(gen), (ba_imag*bd_real - ba_real*bd_imag).as_poly(gen))
bd = (bd_real*bd_real + bd_imag*bd_imag).as_poly(gen)
return (ba[0], ba[1], bd)
def prde_special_denom(a, ba, bd, G, DE, case='auto'):
"""
Parametric Risch Differential Equation - Special part of the denominator.
Explanation
===========
Case is one of {'exp', 'tan', 'primitive'} for the hyperexponential,
hypertangent, and primitive cases, respectively. For the hyperexponential
(resp. hypertangent) case, given a derivation D on k[t] and a in k[t],
b in k<t>, and g1, ..., gm in k(t) with Dt/t in k (resp. Dt/(t**2 + 1) in
k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp.
gcd(a, t**2 + 1) == 1), return the tuple (A, B, GG, h) such that A, B, h in
k[t], GG = [gg1, ..., ggm] in k(t)^m, and for any solution c1, ..., cm in
Const(k) and q in k<t> of a*Dq + b*q == Sum(ci*gi, (i, 1, m)), r == q*h in
k[t] satisfies A*Dr + B*r == Sum(ci*ggi, (i, 1, m)).
For case == 'primitive', k<t> == k[t], so it returns (a, b, G, 1) in this
case.
"""
# TODO: Merge this with the very similar special_denom() in rde.py
if case == 'auto':
case = DE.case
if case == 'exp':
p = Poly(DE.t, DE.t)
elif case == 'tan':
p = Poly(DE.t**2 + 1, DE.t)
elif case in ('primitive', 'base'):
B = ba.quo(bd)
return (a, B, G, Poly(1, DE.t))
else:
raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
"'base'}, not %s." % case)
nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t)
nc = min([order_at(Ga, p, DE.t) - order_at(Gd, p, DE.t) for Ga, Gd in G])
n = min(0, nc - min(0, nb))
if not nb:
# Possible cancellation.
if case == 'exp':
dcoeff = DE.d.quo(Poly(DE.t, DE.t))
with DecrementLevel(DE): # We are guaranteed to not have problems,
# because case != 'base'.
alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t)
etaa, etad = frac_in(dcoeff, DE.t)
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
if A is not None:
Q, m, z = A
if Q == 1:
n = min(n, m)
elif case == 'tan':
dcoeff = DE.d.quo(Poly(DE.t**2 + 1, DE.t))
with DecrementLevel(DE): # We are guaranteed to not have problems,
# because case != 'base'.
betaa, alphaa, alphad = real_imag(ba, bd*a, DE.t)
betad = alphad
etaa, etad = frac_in(dcoeff, DE.t)
if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE):
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
B = parametric_log_deriv(betaa, betad, etaa, etad, DE)
if A is not None and B is not None:
Q, s, z = A
# TODO: Add test
if Q == 1:
n = min(n, s/2)
N = max(0, -nb)
pN = p**N
pn = p**-n # This is 1/h
A = a*pN
B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN
G = [(Ga*pN*pn).cancel(Gd, include=True) for Ga, Gd in G]
h = pn
# (a*p**N, (b + n*a*Dp/p)*p**N, g1*p**(N - n), ..., gm*p**(N - n), p**-n)
return (A, B, G, h)
def prde_linear_constraints(a, b, G, DE):
"""
Parametric Risch Differential Equation - Generate linear constraints on the constants.
Explanation
===========
Given a derivation D on k[t], a, b, in k[t] with gcd(a, b) == 1, and
G = [g1, ..., gm] in k(t)^m, return Q = [q1, ..., qm] in k[t]^m and a
matrix M with entries in k(t) such that for any solution c1, ..., cm in
Const(k) and p in k[t] of a*Dp + b*p == Sum(ci*gi, (i, 1, m)),
(c1, ..., cm) is a solution of Mx == 0, and p and the ci satisfy
a*Dp + b*p == Sum(ci*qi, (i, 1, m)).
Because M has entries in k(t), and because Matrix does not play well with
Poly, M will be a Matrix of Basic expressions.
"""
m = len(G)
Gns, Gds = list(zip(*G))
d = reduce(lambda i, j: i.lcm(j), Gds)
d = Poly(d, field=True)
Q = [(ga*(d).quo(gd)).div(d) for ga, gd in G]
if not all(ri.is_zero for _, ri in Q):
N = max(ri.degree(DE.t) for _, ri in Q)
M = Matrix(N + 1, m, lambda i, j: Q[j][1].nth(i), DE.t)
else:
M = Matrix(0, m, [], DE.t) # No constraints, return the empty matrix.
qs, _ = list(zip(*Q))
return (qs, M)
def poly_linear_constraints(p, d):
"""
Given p = [p1, ..., pm] in k[t]^m and d in k[t], return
q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such
that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible
by d if and only if (c1, ..., cm) is a solution of Mx = 0, in
which case the quotient is Sum(ci*qi, (i, 1, m)).
"""
m = len(p)
q, r = zip(*[pi.div(d) for pi in p])
if not all(ri.is_zero for ri in r):
n = max(ri.degree() for ri in r)
M = Matrix(n + 1, m, lambda i, j: r[j].nth(i), d.gens)
else:
M = Matrix(0, m, [], d.gens) # No constraints.
return q, M
def constant_system(A, u, DE):
"""
Generate a system for the constant solutions.
Explanation
===========
Given a differential field (K, D) with constant field C = Const(K), a Matrix
A, and a vector (Matrix) u with coefficients in K, returns the tuple
(B, v, s), where B is a Matrix with coefficients in C and v is a vector
(Matrix) such that either v has coefficients in C, in which case s is True
and the solutions in C of Ax == u are exactly all the solutions of Bx == v,
or v has a non-constant coefficient, in which case s is False Ax == u has no
constant solution.
This algorithm is used both in solving parametric problems and in
determining if an element a of K is a derivative of an element of K or the
logarithmic derivative of a K-radical using the structure theorem approach.
Because Poly does not play well with Matrix yet, this algorithm assumes that
all matrix entries are Basic expressions.
"""
if not A:
return A, u
Au = A.row_join(u)
Au, _ = Au.rref()
# Warning: This will NOT return correct results if cancel() cannot reduce
# an identically zero expression to 0. The danger is that we might
# incorrectly prove that an integral is nonelementary (such as
# risch_integrate(exp((sin(x)**2 + cos(x)**2 - 1)*x**2), x).
# But this is a limitation in computer algebra in general, and implicit
# in the correctness of the Risch Algorithm is the computability of the
# constant field (actually, this same correctness problem exists in any
# algorithm that uses rref()).
#
# We therefore limit ourselves to constant fields that are computable
# via the cancel() function, in order to prevent a speed bottleneck from
# calling some more complex simplification function (rational function
# coefficients will fall into this class). Furthermore, (I believe) this
# problem will only crop up if the integral explicitly contains an
# expression in the constant field that is identically zero, but cannot
# be reduced to such by cancel(). Therefore, a careful user can avoid this
# problem entirely by being careful with the sorts of expressions that
# appear in his integrand in the variables other than the integration
# variable (the structure theorems should be able to completely decide these
# problems in the integration variable).
A, u = Au[:, :-1], Au[:, -1]
D = lambda x: derivation(x, DE, basic=True)
for j, i in itertools.product(range(A.cols), range(A.rows)):
if A[i, j].expr.has(*DE.T):
# This assumes that const(F(t0, ..., tn) == const(K) == F
Ri = A[i, :]
# Rm+1; m = A.rows
DAij = D(A[i, j])
Rm1 = Ri.applyfunc(lambda x: D(x) / DAij)
um1 = D(u[i]) / DAij
Aj = A[:, j]
A = A - Aj * Rm1
u = u - Aj * um1
A = A.col_join(Rm1)
u = u.col_join(Matrix([um1], u.gens))
return (A, u)
def prde_spde(a, b, Q, n, DE):
"""
Special Polynomial Differential Equation algorithm: Parametric Version.
Explanation
===========
Given a derivation D on k[t], an integer n, and a, b, q1, ..., qm in k[t]
with deg(a) > 0 and gcd(a, b) == 1, return (A, B, Q, R, n1), with
Qq = [q1, ..., qm] and R = [r1, ..., rm], such that for any solution
c1, ..., cm in Const(k) and q in k[t] of degree at most n of
a*Dq + b*q == Sum(ci*gi, (i, 1, m)), p = (q - Sum(ci*ri, (i, 1, m)))/a has
degree at most n1 and satisfies A*Dp + B*p == Sum(ci*qi, (i, 1, m))
"""
R, Z = list(zip(*[gcdex_diophantine(b, a, qi) for qi in Q]))
A = a
B = b + derivation(a, DE)
Qq = [zi - derivation(ri, DE) for ri, zi in zip(R, Z)]
R = list(R)
n1 = n - a.degree(DE.t)
return (A, B, Qq, R, n1)
def prde_no_cancel_b_large(b, Q, n, DE):
"""
Parametric Poly Risch Differential Equation - No cancellation: deg(b) large enough.
Explanation
===========
Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
b != 0 and either D == d/dt or deg(b) > max(0, deg(D) - 1), returns
h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
Dq + b*q == Sum(ci*qi, (i, 1, m)), then q = Sum(dj*hj, (j, 1, r)), where
d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
"""
db = b.degree(DE.t)
m = len(Q)
H = [Poly(0, DE.t)]*m
for N, i in itertools.product(range(n, -1, -1), range(m)): # [n, ..., 0]
si = Q[i].nth(N + db)/b.LC()
sitn = Poly(si*DE.t**N, DE.t)
H[i] = H[i] + sitn
Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
if all(qi.is_zero for qi in Q):
dc = -1
else:
dc = max([qi.degree(DE.t) for qi in Q])
M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
c = eye(m, DE.t)
A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
return (H, A)
def prde_no_cancel_b_small(b, Q, n, DE):
"""
Parametric Poly Risch Differential Equation - No cancellation: deg(b) small enough.
Explanation
===========
Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
deg(b) < deg(D) - 1 and either D == d/dt or deg(D) >= 2, returns
h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
Dq + b*q == Sum(ci*qi, (i, 1, m)) then q = Sum(dj*hj, (j, 1, r)) where
d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
"""
m = len(Q)
H = [Poly(0, DE.t)]*m
for N, i in itertools.product(range(n, 0, -1), range(m)): # [n, ..., 1]
si = Q[i].nth(N + DE.d.degree(DE.t) - 1)/(N*DE.d.LC())
sitn = Poly(si*DE.t**N, DE.t)
H[i] = H[i] + sitn
Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
if b.degree(DE.t) > 0:
for i in range(m):
si = Poly(Q[i].nth(b.degree(DE.t))/b.LC(), DE.t)
H[i] = H[i] + si
Q[i] = Q[i] - derivation(si, DE) - b*si
if all(qi.is_zero for qi in Q):
dc = -1
else:
dc = max([qi.degree(DE.t) for qi in Q])
M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
c = eye(m, DE.t)
A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
return (H, A)
# else: b is in k, deg(qi) < deg(Dt)
t = DE.t
if DE.case != 'base':
with DecrementLevel(DE):
t0 = DE.t # k = k0(t0)
ba, bd = frac_in(b, t0, field=True)
Q0 = [frac_in(qi.TC(), t0, field=True) for qi in Q]
f, B = param_rischDE(ba, bd, Q0, DE)
# f = [f1, ..., fr] in k^r and B is a matrix with
# m + r columns and entries in Const(k) = Const(k0)
# such that Dy0 + b*y0 = Sum(ci*qi, (i, 1, m)) has
# a solution y0 in k with c1, ..., cm in Const(k)
# if and only y0 = Sum(dj*fj, (j, 1, r)) where
# d1, ..., dr ar in Const(k) and
# B*Matrix([c1, ..., cm, d1, ..., dr]) == 0.
# Transform fractions (fa, fd) in f into constant
# polynomials fa/fd in k[t].
# (Is there a better way?)
f = [Poly(fa.as_expr()/fd.as_expr(), t, field=True)
for fa, fd in f]
B = Matrix.from_Matrix(B.to_Matrix(), t)
else:
# Base case. Dy == 0 for all y in k and b == 0.
# Dy + b*y = Sum(ci*qi) is solvable if and only if
# Sum(ci*qi) == 0 in which case the solutions are
# y = d1*f1 for f1 = 1 and any d1 in Const(k) = k.
f = [Poly(1, t, field=True)] # r = 1
B = Matrix([[qi.TC() for qi in Q] + [S.Zero]], DE.t)
# The condition for solvability is
# B*Matrix([c1, ..., cm, d1]) == 0
# There are no constraints on d1.
# Coefficients of t^j (j > 0) in Sum(ci*qi) must be zero.
d = max([qi.degree(DE.t) for qi in Q])
if d > 0:
M = Matrix(d, m, lambda i, j: Q[j].nth(i + 1), DE.t)
A, _ = constant_system(M, zeros(d, 1, DE.t), DE)
else:
# No constraints on the hj.
A = Matrix(0, m, [], DE.t)
# Solutions of the original equation are
# y = Sum(dj*fj, (j, 1, r) + Sum(ei*hi, (i, 1, m)),
# where ei == ci (i = 1, ..., m), when
# A*Matrix([c1, ..., cm]) == 0 and
# B*Matrix([c1, ..., cm, d1, ..., dr]) == 0
# Build combined constraint matrix with m + r + m columns.
r = len(f)
I = eye(m, DE.t)
A = A.row_join(zeros(A.rows, r + m, DE.t))
B = B.row_join(zeros(B.rows, m, DE.t))
C = I.row_join(zeros(m, r, DE.t)).row_join(-I)
return f + H, A.col_join(B).col_join(C)
def prde_cancel_liouvillian(b, Q, n, DE):
"""
Pg, 237.
"""
H = []
# Why use DecrementLevel? Below line answers that:
# Assuming that we can solve such problems over 'k' (not k[t])
if DE.case == 'primitive':
with DecrementLevel(DE):
ba, bd = frac_in(b, DE.t, field=True)
for i in range(n, -1, -1):
if DE.case == 'exp': # this re-checking can be avoided
with DecrementLevel(DE):
ba, bd = frac_in(b + (i*(derivation(DE.t, DE)/DE.t)).as_poly(b.gens),
DE.t, field=True)
with DecrementLevel(DE):
Qy = [frac_in(q.nth(i), DE.t, field=True) for q in Q]
fi, Ai = param_rischDE(ba, bd, Qy, DE)
fi = [Poly(fa.as_expr()/fd.as_expr(), DE.t, field=True)
for fa, fd in fi]
Ai = Ai.set_gens(DE.t)
ri = len(fi)
if i == n:
M = Ai
else:
M = Ai.col_join(M.row_join(zeros(M.rows, ri, DE.t)))
Fi, hi = [None]*ri, [None]*ri
# from eq. on top of p.238 (unnumbered)
for j in range(ri):
hji = fi[j] * (DE.t**i).as_poly(fi[j].gens)
hi[j] = hji
# building up Sum(djn*(D(fjn*t^n) - b*fjnt^n))
Fi[j] = -(derivation(hji, DE) - b*hji)
H += hi
# in the next loop instead of Q it has
# to be Q + Fi taking its place
Q = Q + Fi
return (H, M)
def param_poly_rischDE(a, b, q, n, DE):
"""Polynomial solutions of a parametric Risch differential equation.
Explanation
===========
Given a derivation D in k[t], a, b in k[t] relatively prime, and q
= [q1, ..., qm] in k[t]^m, return h = [h1, ..., hr] in k[t]^r and
a matrix A with m + r columns and entries in Const(k) such that
a*Dp + b*p = Sum(ci*qi, (i, 1, m)) has a solution p of degree <= n
in k[t] with c1, ..., cm in Const(k) if and only if p = Sum(dj*hj,
(j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
d1, ..., dr) is a solution of Ax == 0.
"""
m = len(q)
if n < 0:
# Only the trivial zero solution is possible.
# Find relations between the qi.
if all(qi.is_zero for qi in q):
return [], zeros(1, m, DE.t) # No constraints.
N = max([qi.degree(DE.t) for qi in q])
M = Matrix(N + 1, m, lambda i, j: q[j].nth(i), DE.t)
A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
return [], A
if a.is_ground:
# Normalization: a = 1.
a = a.LC()
b, q = b.quo_ground(a), [qi.quo_ground(a) for qi in q]
if not b.is_zero and (DE.case == 'base' or
b.degree() > max(0, DE.d.degree() - 1)):
return prde_no_cancel_b_large(b, q, n, DE)
elif ((b.is_zero or b.degree() < DE.d.degree() - 1)
and (DE.case == 'base' or DE.d.degree() >= 2)):
return prde_no_cancel_b_small(b, q, n, DE)
elif (DE.d.degree() >= 2 and
b.degree() == DE.d.degree() - 1 and
n > -b.as_poly().LC()/DE.d.as_poly().LC()):
raise NotImplementedError("prde_no_cancel_b_equal() is "
"not yet implemented.")
else:
# Liouvillian cases
if DE.case in ('primitive', 'exp'):
return prde_cancel_liouvillian(b, q, n, DE)
else:
raise NotImplementedError("non-linear and hypertangent "
"cases have not yet been implemented")
# else: deg(a) > 0
# Iterate SPDE as long as possible cumulating coefficient
# and terms for the recovery of original solutions.
alpha, beta = a.one, [a.zero]*m
while n >= 0: # and a, b relatively prime
a, b, q, r, n = prde_spde(a, b, q, n, DE)
beta = [betai + alpha*ri for betai, ri in zip(beta, r)]
alpha *= a
# Solutions p of a*Dp + b*p = Sum(ci*qi) correspond to
# solutions alpha*p + Sum(ci*betai) of the initial equation.
d = a.gcd(b)
if not d.is_ground:
break
# a*Dp + b*p = Sum(ci*qi) may have a polynomial solution
# only if the sum is divisible by d.
qq, M = poly_linear_constraints(q, d)
# qq = [qq1, ..., qqm] where qqi = qi.quo(d).
# M is a matrix with m columns an entries in k.
# Sum(fi*qi, (i, 1, m)), where f1, ..., fm are elements of k, is
# divisible by d if and only if M*Matrix([f1, ..., fm]) == 0,
# in which case the quotient is Sum(fi*qqi).
A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
# A is a matrix with m columns and entries in Const(k).
# Sum(ci*qqi) is Sum(ci*qi).quo(d), and the remainder is zero
# for c1, ..., cm in Const(k) if and only if
# A*Matrix([c1, ...,cm]) == 0.
V = A.nullspace()
# V = [v1, ..., vu] where each vj is a column matrix with
# entries aj1, ..., ajm in Const(k).
# Sum(aji*qi) is divisible by d with exact quotient Sum(aji*qqi).
# Sum(ci*qi) is divisible by d if and only if ci = Sum(dj*aji)
# (i = 1, ..., m) for some d1, ..., du in Const(k).
# In that case, solutions of
# a*Dp + b*p = Sum(ci*qi) = Sum(dj*Sum(aji*qi))
# are the same as those of
# (a/d)*Dp + (b/d)*p = Sum(dj*rj)
# where rj = Sum(aji*qqi).
if not V: # No non-trivial solution.
return [], eye(m, DE.t) # Could return A, but this has
# the minimum number of rows.
Mqq = Matrix([qq]) # A single row.
r = [(Mqq*vj)[0] for vj in V] # [r1, ..., ru]
# Solutions of (a/d)*Dp + (b/d)*p = Sum(dj*rj) correspond to
# solutions alpha*p + Sum(Sum(dj*aji)*betai) of the initial
# equation. These are equal to alpha*p + Sum(dj*fj) where
# fj = Sum(aji*betai).
Mbeta = Matrix([beta])
f = [(Mbeta*vj)[0] for vj in V] # [f1, ..., fu]
#
# Solve the reduced equation recursively.
#
g, B = param_poly_rischDE(a.quo(d), b.quo(d), r, n, DE)
# g = [g1, ..., gv] in k[t]^v and and B is a matrix with u + v
# columns and entries in Const(k) such that
# (a/d)*Dp + (b/d)*p = Sum(dj*rj) has a solution p of degree <= n
# in k[t] if and only if p = Sum(ek*gk) where e1, ..., ev are in
# Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
# The solutions of the original equation are then
# Sum(dj*fj, (j, 1, u)) + alpha*Sum(ek*gk, (k, 1, v)).
# Collect solution components.
h = f + [alpha*gk for gk in g]
# Build combined relation matrix.
A = -eye(m, DE.t)
for vj in V:
A = A.row_join(vj)
A = A.row_join(zeros(m, len(g), DE.t))
A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
return h, A
def param_rischDE(fa, fd, G, DE):
"""
Solve a Parametric Risch Differential Equation: Dy + f*y == Sum(ci*Gi, (i, 1, m)).
Explanation
===========
Given a derivation D in k(t), f in k(t), and G
= [G1, ..., Gm] in k(t)^m, return h = [h1, ..., hr] in k(t)^r and
a matrix A with m + r columns and entries in Const(k) such that
Dy + f*y = Sum(ci*Gi, (i, 1, m)) has a solution y
in k(t) with c1, ..., cm in Const(k) if and only if y = Sum(dj*hj,
(j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
d1, ..., dr) is a solution of Ax == 0.
Elements of k(t) are tuples (a, d) with a and d in k[t].
"""
m = len(G)
q, (fa, fd) = weak_normalizer(fa, fd, DE)
# Solutions of the weakly normalized equation Dz + f*z = q*Sum(ci*Gi)
# correspond to solutions y = z/q of the original equation.
gamma = q
G = [(q*ga).cancel(gd, include=True) for ga, gd in G]
a, (ba, bd), G, hn = prde_normal_denom(fa, fd, G, DE)
# Solutions q in k<t> of a*Dq + b*q = Sum(ci*Gi) correspond
# to solutions z = q/hn of the weakly normalized equation.
gamma *= hn
A, B, G, hs = prde_special_denom(a, ba, bd, G, DE)
# Solutions p in k[t] of A*Dp + B*p = Sum(ci*Gi) correspond
# to solutions q = p/hs of the previous equation.
gamma *= hs
g = A.gcd(B)
a, b, g = A.quo(g), B.quo(g), [gia.cancel(gid*g, include=True) for
gia, gid in G]
# a*Dp + b*p = Sum(ci*gi) may have a polynomial solution
# only if the sum is in k[t].
q, M = prde_linear_constraints(a, b, g, DE)
# q = [q1, ..., qm] where qi in k[t] is the polynomial component
# of the partial fraction expansion of gi.
# M is a matrix with m columns and entries in k.
# Sum(fi*gi, (i, 1, m)), where f1, ..., fm are elements of k,
# is a polynomial if and only if M*Matrix([f1, ..., fm]) == 0,
# in which case the sum is equal to Sum(fi*qi).
M, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
# M is a matrix with m columns and entries in Const(k).
# Sum(ci*gi) is in k[t] for c1, ..., cm in Const(k)
# if and only if M*Matrix([c1, ..., cm]) == 0,
# in which case the sum is Sum(ci*qi).
## Reduce number of constants at this point
V = M.nullspace()
# V = [v1, ..., vu] where each vj is a column matrix with
# entries aj1, ..., ajm in Const(k).
# Sum(aji*gi) is in k[t] and equal to Sum(aji*qi) (j = 1, ..., u).
# Sum(ci*gi) is in k[t] if and only is ci = Sum(dj*aji)
# (i = 1, ..., m) for some d1, ..., du in Const(k).
# In that case,
# Sum(ci*gi) = Sum(ci*qi) = Sum(dj*Sum(aji*qi)) = Sum(dj*rj)
# where rj = Sum(aji*qi) (j = 1, ..., u) in k[t].
if not V: # No non-trivial solution
return [], eye(m, DE.t)
Mq = Matrix([q]) # A single row.
r = [(Mq*vj)[0] for vj in V] # [r1, ..., ru]
# Solutions of a*Dp + b*p = Sum(dj*rj) correspond to solutions
# y = p/gamma of the initial equation with ci = Sum(dj*aji).
try:
# We try n=5. At least for prde_spde, it will always
# terminate no matter what n is.
n = bound_degree(a, b, r, DE, parametric=True)
except NotImplementedError:
# A temporary bound is set. Eventually, it will be removed.
# the currently added test case takes large time
# even with n=5, and much longer with large n's.
n = 5
h, B = param_poly_rischDE(a, b, r, n, DE)
# h = [h1, ..., hv] in k[t]^v and and B is a matrix with u + v
# columns and entries in Const(k) such that
# a*Dp + b*p = Sum(dj*rj) has a solution p of degree <= n
# in k[t] if and only if p = Sum(ek*hk) where e1, ..., ev are in
# Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
# The solutions of the original equation for ci = Sum(dj*aji)
# (i = 1, ..., m) are then y = Sum(ek*hk, (k, 1, v))/gamma.
## Build combined relation matrix with m + u + v columns.
A = -eye(m, DE.t)
for vj in V:
A = A.row_join(vj)
A = A.row_join(zeros(m, len(h), DE.t))
A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
## Eliminate d1, ..., du.
W = A.nullspace()
# W = [w1, ..., wt] where each wl is a column matrix with
# entries blk (k = 1, ..., m + u + v) in Const(k).
# The vectors (bl1, ..., blm) generate the space of those
# constant families (c1, ..., cm) for which a solution of
# the equation Dy + f*y == Sum(ci*Gi) exists. They generate
# the space and form a basis except possibly when Dy + f*y == 0
# is solvable in k(t}. The corresponding solutions are
# y = Sum(blk'*hk, (k, 1, v))/gamma, where k' = k + m + u.
v = len(h)
shape = (len(W), m+v)
elements = [wl[:m] + wl[-v:] for wl in W] # excise dj's.
items = [e for row in elements for e in row]
# Need to set the shape in case W is empty
M = Matrix(*shape, items, DE.t)
N = M.nullspace()
# N = [n1, ..., ns] where the ni in Const(k)^(m + v) are column
# vectors generating the space of linear relations between
# c1, ..., cm, e1, ..., ev.
C = Matrix([ni[:] for ni in N], DE.t) # rows n1, ..., ns.
return [hk.cancel(gamma, include=True) for hk in h], C
def limited_integrate_reduce(fa, fd, G, DE):
"""
Simpler version of step 1 & 2 for the limited integration problem.
Explanation
===========
Given a derivation D on k(t) and f, g1, ..., gn in k(t), return
(a, b, h, N, g, V) such that a, b, h in k[t], N is a non-negative integer,
g in k(t), V == [v1, ..., vm] in k(t)^m, and for any solution v in k(t),
c1, ..., cm in C of f == Dv + Sum(ci*wi, (i, 1, m)), p = v*h is in k<t>, and
p and the ci satisfy a*Dp + b*p == g + Sum(ci*vi, (i, 1, m)). Furthermore,
if S1irr == Sirr, then p is in k[t], and if t is nonlinear or Liouvillian
over k, then deg(p) <= N.
So that the special part is always computed, this function calls the more
general prde_special_denom() automatically if it cannot determine that
S1irr == Sirr. Furthermore, it will automatically call bound_degree() when
t is linear and non-Liouvillian, which for the transcendental case, implies
that Dt == a*t + b with for some a, b in k*.
"""
dn, ds = splitfactor(fd, DE)
E = [splitfactor(gd, DE) for _, gd in G]
En, Es = list(zip(*E))
c = reduce(lambda i, j: i.lcm(j), (dn,) + En) # lcm(dn, en1, ..., enm)
hn = c.gcd(c.diff(DE.t))
a = hn
b = -derivation(hn, DE)
N = 0
# These are the cases where we know that S1irr = Sirr, but there could be
# others, and this algorithm will need to be extended to handle them.
if DE.case in ('base', 'primitive', 'exp', 'tan'):
hs = reduce(lambda i, j: i.lcm(j), (ds,) + Es) # lcm(ds, es1, ..., esm)
a = hn*hs
b -= (hn*derivation(hs, DE)).quo(hs)
mu = min(order_at_oo(fa, fd, DE.t), min([order_at_oo(ga, gd, DE.t) for
ga, gd in G]))
# So far, all the above are also nonlinear or Liouvillian, but if this
# changes, then this will need to be updated to call bound_degree()
# as per the docstring of this function (DE.case == 'other_linear').
N = hn.degree(DE.t) + hs.degree(DE.t) + max(0, 1 - DE.d.degree(DE.t) - mu)
else:
# TODO: implement this
raise NotImplementedError
V = [(-a*hn*ga).cancel(gd, include=True) for ga, gd in G]
return (a, b, a, N, (a*hn*fa).cancel(fd, include=True), V)
def limited_integrate(fa, fd, G, DE):
"""
Solves the limited integration problem: f = Dv + Sum(ci*wi, (i, 1, n))
"""
fa, fd = fa*Poly(1/fd.LC(), DE.t), fd.monic()
# interpreting limited integration problem as a
# parametric Risch DE problem
Fa = Poly(0, DE.t)
Fd = Poly(1, DE.t)
G = [(fa, fd)] + G
h, A = param_rischDE(Fa, Fd, G, DE)
V = A.nullspace()
V = [v for v in V if v[0] != 0]
if not V:
return None
else:
# we can take any vector from V, we take V[0]
c0 = V[0][0]
# v = [-1, c1, ..., cm, d1, ..., dr]
v = V[0]/(-c0)
r = len(h)
m = len(v) - r - 1
C = list(v[1: m + 1])
y = -sum([v[m + 1 + i]*h[i][0].as_expr()/h[i][1].as_expr() \
for i in range(r)])
y_num, y_den = y.as_numer_denom()
Ya, Yd = Poly(y_num, DE.t), Poly(y_den, DE.t)
Y = Ya*Poly(1/Yd.LC(), DE.t), Yd.monic()
return Y, C
def parametric_log_deriv_heu(fa, fd, wa, wd, DE, c1=None):
"""
Parametric logarithmic derivative heuristic.
Explanation
===========
Given a derivation D on k[t], f in k(t), and a hyperexponential monomial
theta over k(t), raises either NotImplementedError, in which case the
heuristic failed, or returns None, in which case it has proven that no
solution exists, or returns a solution (n, m, v) of the equation
n*f == Dv/v + m*Dtheta/theta, with v in k(t)* and n, m in ZZ with n != 0.
If this heuristic fails, the structure theorem approach will need to be
used.
The argument w == Dtheta/theta
"""
# TODO: finish writing this and write tests
c1 = c1 or Dummy('c1')
p, a = fa.div(fd)
q, b = wa.div(wd)
B = max(0, derivation(DE.t, DE).degree(DE.t) - 1)
C = max(p.degree(DE.t), q.degree(DE.t))
if q.degree(DE.t) > B:
eqs = [p.nth(i) - c1*q.nth(i) for i in range(B + 1, C + 1)]
s = solve(eqs, c1)
if not s or not s[c1].is_Rational:
# deg(q) > B, no solution for c.
return None
M, N = s[c1].as_numer_denom()
M_poly = M.as_poly(q.gens)
N_poly = N.as_poly(q.gens)
nfmwa = N_poly*fa*wd - M_poly*wa*fd
nfmwd = fd*wd
Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE, 'auto')
if Qv is None:
# (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
return None
Q, v = Qv
if Q.is_zero or v.is_zero:
return None
return (Q*N, Q*M, v)
if p.degree(DE.t) > B:
return None
c = lcm(fd.as_poly(DE.t).LC(), wd.as_poly(DE.t).LC())
l = fd.monic().lcm(wd.monic())*Poly(c, DE.t)
ln, ls = splitfactor(l, DE)
z = ls*ln.gcd(ln.diff(DE.t))
if not z.has(DE.t):
# TODO: We treat this as 'no solution', until the structure
# theorem version of parametric_log_deriv is implemented.
return None
u1, r1 = (fa*l.quo(fd)).div(z) # (l*f).div(z)
u2, r2 = (wa*l.quo(wd)).div(z) # (l*w).div(z)
eqs = [r1.nth(i) - c1*r2.nth(i) for i in range(z.degree(DE.t))]
s = solve(eqs, c1)
if not s or not s[c1].is_Rational:
# deg(q) <= B, no solution for c.
return None
M, N = s[c1].as_numer_denom()
nfmwa = N.as_poly(DE.t)*fa*wd - M.as_poly(DE.t)*wa*fd
nfmwd = fd*wd
Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE)
if Qv is None:
# (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
return None
Q, v = Qv
if Q.is_zero or v.is_zero:
return None
return (Q*N, Q*M, v)
def parametric_log_deriv(fa, fd, wa, wd, DE):
# TODO: Write the full algorithm using the structure theorems.
# try:
A = parametric_log_deriv_heu(fa, fd, wa, wd, DE)
# except NotImplementedError:
# Heuristic failed, we have to use the full method.
# TODO: This could be implemented more efficiently.
# It isn't too worrisome, because the heuristic handles most difficult
# cases.
return A
def is_deriv_k(fa, fd, DE):
r"""
Checks if Df/f is the derivative of an element of k(t).
Explanation
===========
a in k(t) is the derivative of an element of k(t) if there exists b in k(t)
such that a = Db. Either returns (ans, u), such that Df/f == Du, or None,
which means that Df/f is not the derivative of an element of k(t). ans is
a list of tuples such that Add(*[i*j for i, j in ans]) == u. This is useful
for seeing exactly which elements of k(t) produce u.
This function uses the structure theorem approach, which says that for any
f in K, Df/f is the derivative of a element of K if and only if there are ri
in QQ such that::
--- --- Dt
\ r * Dt + \ r * i Df
/ i i / i --- = --.
--- --- t f
i in L i in E i
K/C(x) K/C(x)
Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
hyperexponential monomials of K over C(x)). If K is an elementary extension
over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
and L_K/C(x) are disjoint.
The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
recursively using this same function. Therefore, it is required to pass
them as indices to D (or T). E_args are the arguments of the
hyperexponentials indexed by E_K (i.e., if i is in E_K, then T[i] ==
exp(E_args[i])). This is needed to compute the final answer u such that
Df/f == Du.
log(f) will be the same as u up to a additive constant. This is because
they will both behave the same as monomials. For example, both log(x) and
log(2*x) == log(x) + log(2) satisfy Dt == 1/x, because log(2) is constant.
Therefore, the term const is returned. const is such that
log(const) + f == u. This is calculated by dividing the arguments of one
logarithm from the other. Therefore, it is necessary to pass the arguments
of the logarithmic terms in L_args.
To handle the case where we are given Df/f, not f, use is_deriv_k_in_field().
See also
========
is_log_deriv_k_t_radical_in_field, is_log_deriv_k_t_radical
"""
# Compute Df/f
dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)), fd*fa
dfa, dfd = dfa.cancel(dfd, include=True)
# Our assumption here is that each monomial is recursively transcendental
if len(DE.exts) != len(DE.D):
if [i for i in DE.cases if i == 'tan'] or \
({i for i in DE.cases if i == 'primitive'} -
set(DE.indices('log'))):
raise NotImplementedError("Real version of the structure "
"theorems with hypertangent support is not yet implemented.")
# TODO: What should really be done in this case?
raise NotImplementedError("Nonelementary extensions not supported "
"in the structure theorems.")
E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
# The expression dfa/dfd might not be polynomial in any of its symbols so we
# use a Dummy as the generator for PolyMatrix.
dum = Dummy()
lhs = Matrix([E_part + L_part], dum)
rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
A, u = constant_system(lhs, rhs, DE)
u = u.to_Matrix() # Poly to Expr
if not A or not all(derivation(i, DE, basic=True).is_zero for i in u):
# If the elements of u are not all constant
# Note: See comment in constant_system
# Also note: derivation(basic=True) calls cancel()
return None
else:
if not all(i.is_Rational for i in u):
raise NotImplementedError("Cannot work with non-rational "
"coefficients in this case.")
else:
terms = ([DE.extargs[i] for i in DE.indices('exp')] +
[DE.T[i] for i in DE.indices('log')])
ans = list(zip(terms, u))
result = Add(*[Mul(i, j) for i, j in ans])
argterms = ([DE.T[i] for i in DE.indices('exp')] +
[DE.extargs[i] for i in DE.indices('log')])
l = []
ld = []
for i, j in zip(argterms, u):
# We need to get around things like sqrt(x**2) != x
# and also sqrt(x**2 + 2*x + 1) != x + 1
# Issue 10798: i need not be a polynomial
i, d = i.as_numer_denom()
icoeff, iterms = sqf_list(i)
l.append(Mul(*([Pow(icoeff, j)] + [Pow(b, e*j) for b, e in iterms])))
dcoeff, dterms = sqf_list(d)
ld.append(Mul(*([Pow(dcoeff, j)] + [Pow(b, e*j) for b, e in dterms])))
const = cancel(fa.as_expr()/fd.as_expr()/Mul(*l)*Mul(*ld))
return (ans, result, const)
def is_log_deriv_k_t_radical(fa, fd, DE, Df=True):
r"""
Checks if Df is the logarithmic derivative of a k(t)-radical.
Explanation
===========
b in k(t) can be written as the logarithmic derivative of a k(t) radical if
there exist n in ZZ and u in k(t) with n, u != 0 such that n*b == Du/u.
Either returns (ans, u, n, const) or None, which means that Df cannot be
written as the logarithmic derivative of a k(t)-radical. ans is a list of
tuples such that Mul(*[i**j for i, j in ans]) == u. This is useful for
seeing exactly what elements of k(t) produce u.
This function uses the structure theorem approach, which says that for any
f in K, Df is the logarithmic derivative of a K-radical if and only if there
are ri in QQ such that::
--- --- Dt
\ r * Dt + \ r * i
/ i i / i --- = Df.
--- --- t
i in L i in E i
K/C(x) K/C(x)
Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
hyperexponential monomials of K over C(x)). If K is an elementary extension
over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
and L_K/C(x) are disjoint.
The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
recursively using this same function. Therefore, it is required to pass
them as indices to D (or T). L_args are the arguments of the logarithms
indexed by L_K (i.e., if i is in L_K, then T[i] == log(L_args[i])). This is
needed to compute the final answer u such that n*f == Du/u.
exp(f) will be the same as u up to a multiplicative constant. This is
because they will both behave the same as monomials. For example, both
exp(x) and exp(x + 1) == E*exp(x) satisfy Dt == t. Therefore, the term const
is returned. const is such that exp(const)*f == u. This is calculated by
subtracting the arguments of one exponential from the other. Therefore, it
is necessary to pass the arguments of the exponential terms in E_args.
To handle the case where we are given Df, not f, use
is_log_deriv_k_t_radical_in_field().
See also
========
is_log_deriv_k_t_radical_in_field, is_deriv_k
"""
if Df:
dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)).cancel(fd**2,
include=True)
else:
dfa, dfd = fa, fd
# Our assumption here is that each monomial is recursively transcendental
if len(DE.exts) != len(DE.D):
if [i for i in DE.cases if i == 'tan'] or \
({i for i in DE.cases if i == 'primitive'} -
set(DE.indices('log'))):
raise NotImplementedError("Real version of the structure "
"theorems with hypertangent support is not yet implemented.")
# TODO: What should really be done in this case?
raise NotImplementedError("Nonelementary extensions not supported "
"in the structure theorems.")
E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
# The expression dfa/dfd might not be polynomial in any of its symbols so we
# use a Dummy as the generator for PolyMatrix.
dum = Dummy()
lhs = Matrix([E_part + L_part], dum)
rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
A, u = constant_system(lhs, rhs, DE)
u = u.to_Matrix() # Poly to Expr
if not A or not all(derivation(i, DE, basic=True).is_zero for i in u):
# If the elements of u are not all constant
# Note: See comment in constant_system
# Also note: derivation(basic=True) calls cancel()
return None
else:
if not all(i.is_Rational for i in u):
# TODO: But maybe we can tell if they're not rational, like
# log(2)/log(3). Also, there should be an option to continue
# anyway, even if the result might potentially be wrong.
raise NotImplementedError("Cannot work with non-rational "
"coefficients in this case.")
else:
n = reduce(ilcm, [i.as_numer_denom()[1] for i in u])
u *= n
terms = ([DE.T[i] for i in DE.indices('exp')] +
[DE.extargs[i] for i in DE.indices('log')])
ans = list(zip(terms, u))
result = Mul(*[Pow(i, j) for i, j in ans])
# exp(f) will be the same as result up to a multiplicative
# constant. We now find the log of that constant.
argterms = ([DE.extargs[i] for i in DE.indices('exp')] +
[DE.T[i] for i in DE.indices('log')])
const = cancel(fa.as_expr()/fd.as_expr() -
Add(*[Mul(i, j/n) for i, j in zip(argterms, u)]))
return (ans, result, n, const)
def is_log_deriv_k_t_radical_in_field(fa, fd, DE, case='auto', z=None):
"""
Checks if f can be written as the logarithmic derivative of a k(t)-radical.
Explanation
===========
It differs from is_log_deriv_k_t_radical(fa, fd, DE, Df=False)
for any given fa, fd, DE in that it finds the solution in the
given field not in some (possibly unspecified extension) and
"in_field" with the function name is used to indicate that.
f in k(t) can be written as the logarithmic derivative of a k(t) radical if
there exist n in ZZ and u in k(t) with n, u != 0 such that n*f == Du/u.
Either returns (n, u) or None, which means that f cannot be written as the
logarithmic derivative of a k(t)-radical.
case is one of {'primitive', 'exp', 'tan', 'auto'} for the primitive,
hyperexponential, and hypertangent cases, respectively. If case is 'auto',
it will attempt to determine the type of the derivation automatically.
See also
========
is_log_deriv_k_t_radical, is_deriv_k
"""
fa, fd = fa.cancel(fd, include=True)
# f must be simple
n, s = splitfactor(fd, DE)
if not s.is_one:
pass
z = z or Dummy('z')
H, b = residue_reduce(fa, fd, DE, z=z)
if not b:
# I will have to verify, but I believe that the answer should be
# None in this case. This should never happen for the
# functions given when solving the parametric logarithmic
# derivative problem when integration elementary functions (see
# Bronstein's book, page 255), so most likely this indicates a bug.
return None
roots = [(i, i.real_roots()) for i, _ in H]
if not all(len(j) == i.degree() and all(k.is_Rational for k in j) for
i, j in roots):
# If f is the logarithmic derivative of a k(t)-radical, then all the
# roots of the resultant must be rational numbers.
return None
# [(a, i), ...], where i*log(a) is a term in the log-part of the integral
# of f
respolys, residues = list(zip(*roots)) or [[], []]
# Note: this might be empty, but everything below should work find in that
# case (it should be the same as if it were [[1, 1]])
residueterms = [(H[j][1].subs(z, i), i) for j in range(len(H)) for
i in residues[j]]
# TODO: finish writing this and write tests
p = cancel(fa.as_expr()/fd.as_expr() - residue_reduce_derivation(H, DE, z))
p = p.as_poly(DE.t)
if p is None:
# f - Dg will be in k[t] if f is the logarithmic derivative of a k(t)-radical
return None
if p.degree(DE.t) >= max(1, DE.d.degree(DE.t)):
return None
if case == 'auto':
case = DE.case
if case == 'exp':
wa, wd = derivation(DE.t, DE).cancel(Poly(DE.t, DE.t), include=True)
with DecrementLevel(DE):
pa, pd = frac_in(p, DE.t, cancel=True)
wa, wd = frac_in((wa, wd), DE.t)
A = parametric_log_deriv(pa, pd, wa, wd, DE)
if A is None:
return None
n, e, u = A
u *= DE.t**e
elif case == 'primitive':
with DecrementLevel(DE):
pa, pd = frac_in(p, DE.t)
A = is_log_deriv_k_t_radical_in_field(pa, pd, DE, case='auto')
if A is None:
return None
n, u = A
elif case == 'base':
# TODO: we can use more efficient residue reduction from ratint()
if not fd.is_sqf or fa.degree() >= fd.degree():
# f is the logarithmic derivative in the base case if and only if
# f = fa/fd, fd is square-free, deg(fa) < deg(fd), and
# gcd(fa, fd) == 1. The last condition is handled by cancel() above.
return None
# Note: if residueterms = [], returns (1, 1)
# f had better be 0 in that case.
n = reduce(ilcm, [i.as_numer_denom()[1] for _, i in residueterms], S.One)
u = Mul(*[Pow(i, j*n) for i, j in residueterms])
return (n, u)
elif case == 'tan':
raise NotImplementedError("The hypertangent case is "
"not yet implemented for is_log_deriv_k_t_radical_in_field()")
elif case in ('other_linear', 'other_nonlinear'):
# XXX: If these are supported by the structure theorems, change to NotImplementedError.
raise ValueError("The %s case is not supported in this function." % case)
else:
raise ValueError("case must be one of {'primitive', 'exp', 'tan', "
"'base', 'auto'}, not %s" % case)
common_denom = reduce(ilcm, [i.as_numer_denom()[1] for i in [j for _, j in
residueterms]] + [n], S.One)
residueterms = [(i, j*common_denom) for i, j in residueterms]
m = common_denom//n
if common_denom != n*m: # Verify exact division
raise ValueError("Inexact division")
u = cancel(u**m*Mul(*[Pow(i, j) for i, j in residueterms]))
return (common_denom, u)
|
5dd2d8bdcc323f7ff6223e48128faa42b46f9a36ded2761a58539add0eebcc9f | from __future__ import annotations
from typing import Callable
from math import log as _log, sqrt as _sqrt
from itertools import product
from .sympify import _sympify
from .cache import cacheit
from .singleton import S
from .expr import Expr
from .evalf import PrecisionExhausted
from .function import (expand_complex, expand_multinomial,
expand_mul, _mexpand, PoleError)
from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or
from .parameters import global_parameters
from .relational import is_gt, is_lt
from .kind import NumberKind, UndefinedKind
from sympy.external.gmpy import HAS_GMPY, gmpy
from sympy.utilities.iterables import sift
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.misc import as_int
from sympy.multipledispatch import Dispatcher
from mpmath.libmp import sqrtrem as mpmath_sqrtrem
def isqrt(n):
"""Return the largest integer less than or equal to sqrt(n)."""
if n < 0:
raise ValueError("n must be nonnegative")
n = int(n)
# Fast path: with IEEE 754 binary64 floats and a correctly-rounded
# math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <
# 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either
# IEEE 754 format floats *or* correct rounding of math.sqrt, so check the
# answer and fall back to the slow method if necessary.
if n < 4503599761588224:
s = int(_sqrt(n))
if 0 <= n - s*s <= 2*s:
return s
return integer_nthroot(n, 2)[0]
def integer_nthroot(y, n):
"""
Return a tuple containing x = floor(y**(1/n))
and a boolean indicating whether the result is exact (that is,
whether x**n == y).
Examples
========
>>> from sympy import integer_nthroot
>>> integer_nthroot(16, 2)
(4, True)
>>> integer_nthroot(26, 2)
(5, False)
To simply determine if a number is a perfect square, the is_square
function should be used:
>>> from sympy.ntheory.primetest import is_square
>>> is_square(26)
False
See Also
========
sympy.ntheory.primetest.is_square
integer_log
"""
y, n = as_int(y), as_int(n)
if y < 0:
raise ValueError("y must be nonnegative")
if n < 1:
raise ValueError("n must be positive")
if HAS_GMPY and n < 2**63:
# Currently it works only for n < 2**63, else it produces TypeError
# sympy issue: https://github.com/sympy/sympy/issues/18374
# gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257
if HAS_GMPY >= 2:
x, t = gmpy.iroot(y, n)
else:
x, t = gmpy.root(y, n)
return as_int(x), bool(t)
return _integer_nthroot_python(y, n)
def _integer_nthroot_python(y, n):
if y in (0, 1):
return y, True
if n == 1:
return y, True
if n == 2:
x, rem = mpmath_sqrtrem(y)
return int(x), not rem
if n >= y.bit_length():
return 1, False
# Get initial estimate for Newton's method. Care must be taken to
# avoid overflow
try:
guess = int(y**(1./n) + 0.5)
except OverflowError:
exp = _log(y, 2)/n
if exp > 53:
shift = int(exp - 53)
guess = int(2.0**(exp - shift) + 1) << shift
else:
guess = int(2.0**exp)
if guess > 2**50:
# Newton iteration
xprev, x = -1, guess
while 1:
t = x**(n - 1)
xprev, x = x, ((n - 1)*x + y//t)//n
if abs(x - xprev) < 2:
break
else:
x = guess
# Compensate
t = x**n
while t < y:
x += 1
t = x**n
while t > y:
x -= 1
t = x**n
return int(x), t == y # int converts long to int if possible
def integer_log(y, x):
r"""
Returns ``(e, bool)`` where e is the largest nonnegative integer
such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$.
Examples
========
>>> from sympy import integer_log
>>> integer_log(125, 5)
(3, True)
>>> integer_log(17, 9)
(1, False)
>>> integer_log(4, -2)
(2, True)
>>> integer_log(-125,-5)
(3, True)
See Also
========
integer_nthroot
sympy.ntheory.primetest.is_square
sympy.ntheory.factor_.multiplicity
sympy.ntheory.factor_.perfect_power
"""
if x == 1:
raise ValueError('x cannot take value as 1')
if y == 0:
raise ValueError('y cannot take value as 0')
if x in (-2, 2):
x = int(x)
y = as_int(y)
e = y.bit_length() - 1
return e, x**e == y
if x < 0:
n, b = integer_log(y if y > 0 else -y, -x)
return n, b and bool(n % 2 if y < 0 else not n % 2)
x = as_int(x)
y = as_int(y)
r = e = 0
while y >= x:
d = x
m = 1
while y >= d:
y, rem = divmod(y, d)
r = r or rem
e += m
if y > d:
d *= d
m *= 2
return e, r == 0 and y == 1
class Pow(Expr):
"""
Defines the expression x**y as "x raised to a power y"
.. deprecated:: 1.7
Using arguments that aren't subclasses of :class:`~.Expr` in core
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
deprecated. See :ref:`non-expr-args-deprecated` for details.
Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
+--------------+---------+-----------------------------------------------+
| expr | value | reason |
+==============+=========+===============================================+
| z**0 | 1 | Although arguments over 0**0 exist, see [2]. |
+--------------+---------+-----------------------------------------------+
| z**1 | z | |
+--------------+---------+-----------------------------------------------+
| (-oo)**(-1) | 0 | |
+--------------+---------+-----------------------------------------------+
| (-1)**-1 | -1 | |
+--------------+---------+-----------------------------------------------+
| S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be |
| | | undefined, but is convenient in some contexts |
| | | where the base is assumed to be positive. |
+--------------+---------+-----------------------------------------------+
| 1**-1 | 1 | |
+--------------+---------+-----------------------------------------------+
| oo**-1 | 0 | |
+--------------+---------+-----------------------------------------------+
| 0**oo | 0 | Because for all complex numbers z near |
| | | 0, z**oo -> 0. |
+--------------+---------+-----------------------------------------------+
| 0**-oo | zoo | This is not strictly true, as 0**oo may be |
| | | oscillating between positive and negative |
| | | values or rotating in the complex plane. |
| | | It is convenient, however, when the base |
| | | is positive. |
+--------------+---------+-----------------------------------------------+
| 1**oo | nan | Because there are various cases where |
| 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), |
| | | but lim( x(t)**y(t), t) != 1. See [3]. |
+--------------+---------+-----------------------------------------------+
| b**zoo | nan | Because b**z has no limit as z -> zoo |
+--------------+---------+-----------------------------------------------+
| (-1)**oo | nan | Because of oscillations in the limit. |
| (-1)**(-oo) | | |
+--------------+---------+-----------------------------------------------+
| oo**oo | oo | |
+--------------+---------+-----------------------------------------------+
| oo**-oo | 0 | |
+--------------+---------+-----------------------------------------------+
| (-oo)**oo | nan | |
| (-oo)**-oo | | |
+--------------+---------+-----------------------------------------------+
| oo**I | nan | oo**e could probably be best thought of as |
| (-oo)**I | | the limit of x**e for real x as x tends to |
| | | oo. If e is I, then the limit does not exist |
| | | and nan is used to indicate that. |
+--------------+---------+-----------------------------------------------+
| oo**(1+I) | zoo | If the real part of e is positive, then the |
| (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
| | | is zoo. |
+--------------+---------+-----------------------------------------------+
| oo**(-1+I) | 0 | If the real part of e is negative, then the |
| -oo**(-1+I) | | limit is 0. |
+--------------+---------+-----------------------------------------------+
Because symbolic computations are more flexible than floating point
calculations and we prefer to never return an incorrect answer,
we choose not to conform to all IEEE 754 conventions. This helps
us avoid extra test-case code in the calculation of limits.
See Also
========
sympy.core.numbers.Infinity
sympy.core.numbers.NegativeInfinity
sympy.core.numbers.NaN
References
==========
.. [1] https://en.wikipedia.org/wiki/Exponentiation
.. [2] https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_power_of_zero
.. [3] https://en.wikipedia.org/wiki/Indeterminate_forms
"""
is_Pow = True
__slots__ = ('is_commutative',)
args: tuple[Expr, Expr]
_args: tuple[Expr, Expr]
@cacheit
def __new__(cls, b, e, evaluate=None):
if evaluate is None:
evaluate = global_parameters.evaluate
b = _sympify(b)
e = _sympify(e)
# XXX: This can be removed when non-Expr args are disallowed rather
# than deprecated.
from .relational import Relational
if isinstance(b, Relational) or isinstance(e, Relational):
raise TypeError('Relational cannot be used in Pow')
# XXX: This should raise TypeError once deprecation period is over:
for arg in [b, e]:
if not isinstance(arg, Expr):
sympy_deprecation_warning(
f"""
Using non-Expr arguments in Pow is deprecated (in this case, one of the
arguments is of type {type(arg).__name__!r}).
If you really did intend to construct a power with this base, use the **
operator instead.""",
deprecated_since_version="1.7",
active_deprecations_target="non-expr-args-deprecated",
stacklevel=4,
)
if evaluate:
if e is S.ComplexInfinity:
return S.NaN
if e is S.Infinity:
if is_gt(b, S.One):
return S.Infinity
if is_gt(b, S.NegativeOne) and is_lt(b, S.One):
return S.Zero
if is_lt(b, S.NegativeOne):
if b.is_finite:
return S.ComplexInfinity
if b.is_finite is False:
return S.NaN
if e is S.Zero:
return S.One
elif e is S.One:
return b
elif e == -1 and not b:
return S.ComplexInfinity
elif e.__class__.__name__ == "AccumulationBounds":
if b == S.Exp1:
from sympy.calculus.accumulationbounds import AccumBounds
return AccumBounds(Pow(b, e.min), Pow(b, e.max))
# autosimplification if base is a number and exp odd/even
# if base is Number then the base will end up positive; we
# do not do this with arbitrary expressions since symbolic
# cancellation might occur as in (x - 1)/(1 - x) -> -1. If
# we returned Piecewise((-1, Ne(x, 1))) for such cases then
# we could do this...but we don't
elif (e.is_Symbol and e.is_integer or e.is_Integer
) and (b.is_number and b.is_Mul or b.is_Number
) and b.could_extract_minus_sign():
if e.is_even:
b = -b
elif e.is_odd:
return -Pow(-b, e)
if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0
return S.NaN
elif b is S.One:
if abs(e).is_infinite:
return S.NaN
return S.One
else:
# recognize base as E
from sympy.functions.elementary.exponential import exp_polar
if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
from .exprtools import factor_terms
from sympy.functions.elementary.exponential import log
from sympy.simplify.radsimp import fraction
c, ex = factor_terms(e, sign=False).as_coeff_Mul()
num, den = fraction(ex)
if isinstance(den, log) and den.args[0] == b:
return S.Exp1**(c*num)
elif den.is_Add:
from sympy.functions.elementary.complexes import sign, im
s = sign(im(b))
if s.is_Number and s and den == \
log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
return S.Exp1**(c*num)
obj = b._eval_power(e)
if obj is not None:
return obj
obj = Expr.__new__(cls, b, e)
obj = cls._exec_constructor_postprocessors(obj)
if not isinstance(obj, Pow):
return obj
obj.is_commutative = (b.is_commutative and e.is_commutative)
return obj
def inverse(self, argindex=1):
if self.base == S.Exp1:
from sympy.functions.elementary.exponential import log
return log
return None
@property
def base(self) -> Expr:
return self._args[0]
@property
def exp(self) -> Expr:
return self._args[1]
@property
def kind(self):
if self.exp.kind is NumberKind:
return self.base.kind
else:
return UndefinedKind
@classmethod
def class_key(cls):
return 3, 2, cls.__name__
def _eval_refine(self, assumptions):
from sympy.assumptions.ask import ask, Q
b, e = self.as_base_exp()
if ask(Q.integer(e), assumptions) and b.could_extract_minus_sign():
if ask(Q.even(e), assumptions):
return Pow(-b, e)
elif ask(Q.odd(e), assumptions):
return -Pow(-b, e)
def _eval_power(self, other):
b, e = self.as_base_exp()
if b is S.NaN:
return (b**e)**other # let __new__ handle it
s = None
if other.is_integer:
s = 1
elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)...
s = 1
elif e.is_extended_real is not None:
from sympy.functions.elementary.complexes import arg, im, re, sign
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.integers import floor
# helper functions ===========================
def _half(e):
"""Return True if the exponent has a literal 2 as the
denominator, else None."""
if getattr(e, 'q', None) == 2:
return True
n, d = e.as_numer_denom()
if n.is_integer and d == 2:
return True
def _n2(e):
"""Return ``e`` evaluated to a Number with 2 significant
digits, else None."""
try:
rv = e.evalf(2, strict=True)
if rv.is_Number:
return rv
except PrecisionExhausted:
pass
# ===================================================
if e.is_extended_real:
# we need _half(other) with constant floor or
# floor(S.Half - e*arg(b)/2/pi) == 0
# handle -1 as special case
if e == -1:
# floor arg. is 1/2 + arg(b)/2/pi
if _half(other):
if b.is_negative is True:
return S.NegativeOne**other*Pow(-b, e*other)
elif b.is_negative is False: # XXX ok if im(b) != 0?
return Pow(b, -other)
elif e.is_even:
if b.is_extended_real:
b = abs(b)
if b.is_imaginary:
b = abs(im(b))*S.ImaginaryUnit
if (abs(e) < 1) == True or e == 1:
s = 1 # floor = 0
elif b.is_extended_nonnegative:
s = 1 # floor = 0
elif re(b).is_extended_nonnegative and (abs(e) < 2) == True:
s = 1 # floor = 0
elif _half(other):
s = exp(2*S.Pi*S.ImaginaryUnit*other*floor(
S.Half - e*arg(b)/(2*S.Pi)))
if s.is_extended_real and _n2(sign(s) - s) == 0:
s = sign(s)
else:
s = None
else:
# e.is_extended_real is False requires:
# _half(other) with constant floor or
# floor(S.Half - im(e*log(b))/2/pi) == 0
try:
s = exp(2*S.ImaginaryUnit*S.Pi*other*
floor(S.Half - im(e*log(b))/2/S.Pi))
# be careful to test that s is -1 or 1 b/c sign(I) == I:
# so check that s is real
if s.is_extended_real and _n2(sign(s) - s) == 0:
s = sign(s)
else:
s = None
except PrecisionExhausted:
s = None
if s is not None:
return s*Pow(b, e*other)
def _eval_Mod(self, q):
r"""A dispatched function to compute `b^e \bmod q`, dispatched
by ``Mod``.
Notes
=====
Algorithms:
1. For unevaluated integer power, use built-in ``pow`` function
with 3 arguments, if powers are not too large wrt base.
2. For very large powers, use totient reduction if $e \ge \log(m)$.
Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$.
For pollard-rho to be faster than built-in pow $\log(e) > m^{1/4}$
check is added.
3. For any unevaluated power found in `b` or `e`, the step 2
will be recursed down to the base and the exponent
such that the $b \bmod q$ becomes the new base and
$\phi(q) + e \bmod \phi(q)$ becomes the new exponent, and then
the computation for the reduced expression can be done.
"""
base, exp = self.base, self.exp
if exp.is_integer and exp.is_positive:
if q.is_integer and base % q == 0:
return S.Zero
from sympy.ntheory.factor_ import totient
if base.is_Integer and exp.is_Integer and q.is_Integer:
b, e, m = int(base), int(exp), int(q)
mb = m.bit_length()
if mb <= 80 and e >= mb and e.bit_length()**4 >= m:
phi = int(totient(m))
return Integer(pow(b, phi + e%phi, m))
return Integer(pow(b, e, m))
from .mod import Mod
if isinstance(base, Pow) and base.is_integer and base.is_number:
base = Mod(base, q)
return Mod(Pow(base, exp, evaluate=False), q)
if isinstance(exp, Pow) and exp.is_integer and exp.is_number:
bit_length = int(q).bit_length()
# XXX Mod-Pow actually attempts to do a hanging evaluation
# if this dispatched function returns None.
# May need some fixes in the dispatcher itself.
if bit_length <= 80:
phi = totient(q)
exp = phi + Mod(exp, phi)
return Mod(Pow(base, exp, evaluate=False), q)
def _eval_is_even(self):
if self.exp.is_integer and self.exp.is_positive:
return self.base.is_even
def _eval_is_negative(self):
ext_neg = Pow._eval_is_extended_negative(self)
if ext_neg is True:
return self.is_finite
return ext_neg
def _eval_is_extended_positive(self):
if self.base == self.exp:
if self.base.is_extended_nonnegative:
return True
elif self.base.is_positive:
if self.exp.is_real:
return True
elif self.base.is_extended_negative:
if self.exp.is_even:
return True
if self.exp.is_odd:
return False
elif self.base.is_zero:
if self.exp.is_extended_real:
return self.exp.is_zero
elif self.base.is_extended_nonpositive:
if self.exp.is_odd:
return False
elif self.base.is_imaginary:
if self.exp.is_integer:
m = self.exp % 4
if m.is_zero:
return True
if m.is_integer and m.is_zero is False:
return False
if self.exp.is_imaginary:
from sympy.functions.elementary.exponential import log
return log(self.base).is_imaginary
def _eval_is_extended_negative(self):
if self.exp is S.Half:
if self.base.is_complex or self.base.is_extended_real:
return False
if self.base.is_extended_negative:
if self.exp.is_odd and self.base.is_finite:
return True
if self.exp.is_even:
return False
elif self.base.is_extended_positive:
if self.exp.is_extended_real:
return False
elif self.base.is_zero:
if self.exp.is_extended_real:
return False
elif self.base.is_extended_nonnegative:
if self.exp.is_extended_nonnegative:
return False
elif self.base.is_extended_nonpositive:
if self.exp.is_even:
return False
elif self.base.is_extended_real:
if self.exp.is_even:
return False
def _eval_is_zero(self):
if self.base.is_zero:
if self.exp.is_extended_positive:
return True
elif self.exp.is_extended_nonpositive:
return False
elif self.base == S.Exp1:
return self.exp is S.NegativeInfinity
elif self.base.is_zero is False:
if self.base.is_finite and self.exp.is_finite:
return False
elif self.exp.is_negative:
return self.base.is_infinite
elif self.exp.is_nonnegative:
return False
elif self.exp.is_infinite and self.exp.is_extended_real:
if (1 - abs(self.base)).is_extended_positive:
return self.exp.is_extended_positive
elif (1 - abs(self.base)).is_extended_negative:
return self.exp.is_extended_negative
elif self.base.is_finite and self.exp.is_negative:
# when self.base.is_zero is None
return False
def _eval_is_integer(self):
b, e = self.args
if b.is_rational:
if b.is_integer is False and e.is_positive:
return False # rat**nonneg
if b.is_integer and e.is_integer:
if b is S.NegativeOne:
return True
if e.is_nonnegative or e.is_positive:
return True
if b.is_integer and e.is_negative and (e.is_finite or e.is_integer):
if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero):
return False
if b.is_Number and e.is_Number:
check = self.func(*self.args)
return check.is_Integer
if e.is_negative and b.is_positive and (b - 1).is_positive:
return False
if e.is_negative and b.is_negative and (b + 1).is_negative:
return False
def _eval_is_extended_real(self):
if self.base is S.Exp1:
if self.exp.is_extended_real:
return True
elif self.exp.is_imaginary:
return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even
from sympy.functions.elementary.exponential import log, exp
real_b = self.base.is_extended_real
if real_b is None:
if self.base.func == exp and self.base.exp.is_imaginary:
return self.exp.is_imaginary
if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary:
return self.exp.is_imaginary
return
real_e = self.exp.is_extended_real
if real_e is None:
return
if real_b and real_e:
if self.base.is_extended_positive:
return True
elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative:
return True
elif self.exp.is_integer and self.base.is_extended_nonzero:
return True
elif self.exp.is_integer and self.exp.is_nonnegative:
return True
elif self.base.is_extended_negative:
if self.exp.is_Rational:
return False
if real_e and self.exp.is_extended_negative and self.base.is_zero is False:
return Pow(self.base, -self.exp).is_extended_real
im_b = self.base.is_imaginary
im_e = self.exp.is_imaginary
if im_b:
if self.exp.is_integer:
if self.exp.is_even:
return True
elif self.exp.is_odd:
return False
elif im_e and log(self.base).is_imaginary:
return True
elif self.exp.is_Add:
c, a = self.exp.as_coeff_Add()
if c and c.is_Integer:
return Mul(
self.base**c, self.base**a, evaluate=False).is_extended_real
elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit):
if (self.exp/2).is_integer is False:
return False
if real_b and im_e:
if self.base is S.NegativeOne:
return True
c = self.exp.coeff(S.ImaginaryUnit)
if c:
if self.base.is_rational and c.is_rational:
if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero:
return False
ok = (c*log(self.base)/S.Pi).is_integer
if ok is not None:
return ok
if real_b is False and real_e: # we already know it's not imag
from sympy.functions.elementary.complexes import arg
i = arg(self.base)*self.exp/S.Pi
if i.is_complex: # finite
return i.is_integer
def _eval_is_complex(self):
if self.base == S.Exp1:
return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative])
if all(a.is_complex for a in self.args) and self._eval_is_finite():
return True
def _eval_is_imaginary(self):
if self.base.is_commutative is False:
return False
if self.base.is_imaginary:
if self.exp.is_integer:
odd = self.exp.is_odd
if odd is not None:
return odd
return
if self.base == S.Exp1:
f = 2 * self.exp / (S.Pi*S.ImaginaryUnit)
# exp(pi*integer) = 1 or -1, so not imaginary
if f.is_even:
return False
# exp(pi*integer + pi/2) = I or -I, so it is imaginary
if f.is_odd:
return True
return None
if self.exp.is_imaginary:
from sympy.functions.elementary.exponential import log
imlog = log(self.base).is_imaginary
if imlog is not None:
return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
if self.base.is_extended_real and self.exp.is_extended_real:
if self.base.is_positive:
return False
else:
rat = self.exp.is_rational
if not rat:
return rat
if self.exp.is_integer:
return False
else:
half = (2*self.exp).is_integer
if half:
return self.base.is_negative
return half
if self.base.is_extended_real is False: # we already know it's not imag
from sympy.functions.elementary.complexes import arg
i = arg(self.base)*self.exp/S.Pi
isodd = (2*i).is_odd
if isodd is not None:
return isodd
def _eval_is_odd(self):
if self.exp.is_integer:
if self.exp.is_positive:
return self.base.is_odd
elif self.exp.is_nonnegative and self.base.is_odd:
return True
elif self.base is S.NegativeOne:
return True
def _eval_is_finite(self):
if self.exp.is_negative:
if self.base.is_zero:
return False
if self.base.is_infinite or self.base.is_nonzero:
return True
c1 = self.base.is_finite
if c1 is None:
return
c2 = self.exp.is_finite
if c2 is None:
return
if c1 and c2:
if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero):
return True
def _eval_is_prime(self):
'''
An integer raised to the n(>=2)-th power cannot be a prime.
'''
if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive:
return False
def _eval_is_composite(self):
"""
A power is composite if both base and exponent are greater than 1
"""
if (self.base.is_integer and self.exp.is_integer and
((self.base - 1).is_positive and (self.exp - 1).is_positive or
(self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)):
return True
def _eval_is_polar(self):
return self.base.is_polar
def _eval_subs(self, old, new):
from sympy.calculus.accumulationbounds import AccumBounds
if isinstance(self.exp, AccumBounds):
b = self.base.subs(old, new)
e = self.exp.subs(old, new)
if isinstance(e, AccumBounds):
return e.__rpow__(b)
return self.func(b, e)
from sympy.functions.elementary.exponential import exp, log
def _check(ct1, ct2, old):
"""Return (bool, pow, remainder_pow) where, if bool is True, then the
exponent of Pow `old` will combine with `pow` so the substitution
is valid, otherwise bool will be False.
For noncommutative objects, `pow` will be an integer, and a factor
`Pow(old.base, remainder_pow)` needs to be included. If there is
no such factor, None is returned. For commutative objects,
remainder_pow is always None.
cti are the coefficient and terms of an exponent of self or old
In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)
will give y**2 since (b**x)**2 == b**(2*x); if that equality does
not hold then the substitution should not occur so `bool` will be
False.
"""
coeff1, terms1 = ct1
coeff2, terms2 = ct2
if terms1 == terms2:
if old.is_commutative:
# Allow fractional powers for commutative objects
pow = coeff1/coeff2
try:
as_int(pow, strict=False)
combines = True
except ValueError:
b, e = old.as_base_exp()
# These conditions ensure that (b**e)**f == b**(e*f) for any f
combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative
return combines, pow, None
else:
# With noncommutative symbols, substitute only integer powers
if not isinstance(terms1, tuple):
terms1 = (terms1,)
if not all(term.is_integer for term in terms1):
return False, None, None
try:
# Round pow toward zero
pow, remainder = divmod(as_int(coeff1), as_int(coeff2))
if pow < 0 and remainder != 0:
pow += 1
remainder -= as_int(coeff2)
if remainder == 0:
remainder_pow = None
else:
remainder_pow = Mul(remainder, *terms1)
return True, pow, remainder_pow
except ValueError:
# Can't substitute
pass
return False, None, None
if old == self.base or (old == exp and self.base == S.Exp1):
if new.is_Function and isinstance(new, Callable):
return new(self.exp._subs(old, new))
else:
return new**self.exp._subs(old, new)
# issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2
if isinstance(old, self.func) and self.exp == old.exp:
l = log(self.base, old.base)
if l.is_Number:
return Pow(new, l)
if isinstance(old, self.func) and self.base == old.base:
if self.exp.is_Add is False:
ct1 = self.exp.as_independent(Symbol, as_Add=False)
ct2 = old.exp.as_independent(Symbol, as_Add=False)
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
# issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2
result = self.func(new, pow)
if remainder_pow is not None:
result = Mul(result, Pow(old.base, remainder_pow))
return result
else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a
# exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))
oarg = old.exp
new_l = []
o_al = []
ct2 = oarg.as_coeff_mul()
for a in self.exp.args:
newa = a._subs(old, new)
ct1 = newa.as_coeff_mul()
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
new_l.append(new**pow)
if remainder_pow is not None:
o_al.append(remainder_pow)
continue
elif not old.is_commutative and not newa.is_integer:
# If any term in the exponent is non-integer,
# we do not do any substitutions in the noncommutative case
return
o_al.append(newa)
if new_l:
expo = Add(*o_al)
new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base)
return Mul(*new_l)
if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive:
ct1 = old.exp.as_independent(Symbol, as_Add=False)
ct2 = (self.exp*log(self.base)).as_independent(
Symbol, as_Add=False)
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z
if remainder_pow is not None:
result = Mul(result, Pow(old.base, remainder_pow))
return result
def as_base_exp(self):
"""Return base and exp of self.
Explanation
===========
If base a Rational less than 1, then return 1/Rational, -exp.
If this extra processing is not needed, the base and exp
properties will give the raw arguments.
Examples
========
>>> from sympy import Pow, S
>>> p = Pow(S.Half, 2, evaluate=False)
>>> p.as_base_exp()
(2, -2)
>>> p.args
(1/2, 2)
>>> p.base, p.exp
(1/2, 2)
"""
b, e = self.args
if b.is_Rational and b.p < b.q and b.p > 0:
return 1/b, -e
return b, e
def _eval_adjoint(self):
from sympy.functions.elementary.complexes import adjoint
i, p = self.exp.is_integer, self.base.is_positive
if i:
return adjoint(self.base)**self.exp
if p:
return self.base**adjoint(self.exp)
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return adjoint(expanded)
def _eval_conjugate(self):
from sympy.functions.elementary.complexes import conjugate as c
i, p = self.exp.is_integer, self.base.is_positive
if i:
return c(self.base)**self.exp
if p:
return self.base**c(self.exp)
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return c(expanded)
if self.is_extended_real:
return self
def _eval_transpose(self):
from sympy.functions.elementary.complexes import transpose
if self.base == S.Exp1:
return self.func(S.Exp1, self.exp.transpose())
i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite)
if p:
return self.base**self.exp
if i:
return transpose(self.base)**self.exp
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return transpose(expanded)
def _eval_expand_power_exp(self, **hints):
"""a**(n + m) -> a**n*a**m"""
b = self.base
e = self.exp
if b == S.Exp1:
from sympy.concrete.summations import Sum
if isinstance(e, Sum) and e.is_commutative:
from sympy.concrete.products import Product
return Product(self.func(b, e.function), *e.limits)
if e.is_Add and (hints.get('force', False) or
b.is_zero is False or e._all_nonneg_or_nonppos()):
if e.is_commutative:
return Mul(*[self.func(b, x) for x in e.args])
if b.is_commutative:
c, nc = sift(e.args, lambda x: x.is_commutative, binary=True)
if c:
return Mul(*[self.func(b, x) for x in c]
)*b**Add._from_args(nc)
return self
def _eval_expand_power_base(self, **hints):
"""(a*b)**n -> a**n * b**n"""
force = hints.get('force', False)
b = self.base
e = self.exp
if not b.is_Mul:
return self
cargs, nc = b.args_cnc(split_1=False)
# expand each term - this is top-level-only
# expansion but we have to watch out for things
# that don't have an _eval_expand method
if nc:
nc = [i._eval_expand_power_base(**hints)
if hasattr(i, '_eval_expand_power_base') else i
for i in nc]
if e.is_Integer:
if e.is_positive:
rv = Mul(*nc*e)
else:
rv = Mul(*[i**-1 for i in nc[::-1]]*-e)
if cargs:
rv *= Mul(*cargs)**e
return rv
if not cargs:
return self.func(Mul(*nc), e, evaluate=False)
nc = [Mul(*nc)]
# sift the commutative bases
other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False,
binary=True)
def pred(x):
if x is S.ImaginaryUnit:
return S.ImaginaryUnit
polar = x.is_polar
if polar:
return True
if polar is None:
return fuzzy_bool(x.is_extended_nonnegative)
sifted = sift(maybe_real, pred)
nonneg = sifted[True]
other += sifted[None]
neg = sifted[False]
imag = sifted[S.ImaginaryUnit]
if imag:
I = S.ImaginaryUnit
i = len(imag) % 4
if i == 0:
pass
elif i == 1:
other.append(I)
elif i == 2:
if neg:
nonn = -neg.pop()
if nonn is not S.One:
nonneg.append(nonn)
else:
neg.append(S.NegativeOne)
else:
if neg:
nonn = -neg.pop()
if nonn is not S.One:
nonneg.append(nonn)
else:
neg.append(S.NegativeOne)
other.append(I)
del imag
# bring out the bases that can be separated from the base
if force or e.is_integer:
# treat all commutatives the same and put nc in other
cargs = nonneg + neg + other
other = nc
else:
# this is just like what is happening automatically, except
# that now we are doing it for an arbitrary exponent for which
# no automatic expansion is done
assert not e.is_Integer
# handle negatives by making them all positive and putting
# the residual -1 in other
if len(neg) > 1:
o = S.One
if not other and neg[0].is_Number:
o *= neg.pop(0)
if len(neg) % 2:
o = -o
for n in neg:
nonneg.append(-n)
if o is not S.One:
other.append(o)
elif neg and other:
if neg[0].is_Number and neg[0] is not S.NegativeOne:
other.append(S.NegativeOne)
nonneg.append(-neg[0])
else:
other.extend(neg)
else:
other.extend(neg)
del neg
cargs = nonneg
other += nc
rv = S.One
if cargs:
if e.is_Rational:
npow, cargs = sift(cargs, lambda x: x.is_Pow and
x.exp.is_Rational and x.base.is_number,
binary=True)
rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])
rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])
if other:
rv *= self.func(Mul(*other), e, evaluate=False)
return rv
def _eval_expand_multinomial(self, **hints):
"""(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
base, exp = self.args
result = self
if exp.is_Rational and exp.p > 0 and base.is_Add:
if not exp.is_Integer:
n = Integer(exp.p // exp.q)
if not n:
return result
else:
radical, result = self.func(base, exp - n), []
expanded_base_n = self.func(base, n)
if expanded_base_n.is_Pow:
expanded_base_n = \
expanded_base_n._eval_expand_multinomial()
for term in Add.make_args(expanded_base_n):
result.append(term*radical)
return Add(*result)
n = int(exp)
if base.is_commutative:
order_terms, other_terms = [], []
for b in base.args:
if b.is_Order:
order_terms.append(b)
else:
other_terms.append(b)
if order_terms:
# (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
f = Add(*other_terms)
o = Add(*order_terms)
if n == 2:
return expand_multinomial(f**n, deep=False) + n*f*o
else:
g = expand_multinomial(f**(n - 1), deep=False)
return expand_mul(f*g, deep=False) + n*g*o
if base.is_number:
# Efficiently expand expressions of the form (a + b*I)**n
# where 'a' and 'b' are real numbers and 'n' is integer.
a, b = base.as_real_imag()
if a.is_Rational and b.is_Rational:
if not a.is_Integer:
if not b.is_Integer:
k = self.func(a.q * b.q, n)
a, b = a.p*b.q, a.q*b.p
else:
k = self.func(a.q, n)
a, b = a.p, a.q*b
elif not b.is_Integer:
k = self.func(b.q, n)
a, b = a*b.q, b.p
else:
k = 1
a, b, c, d = int(a), int(b), 1, 0
while n:
if n & 1:
c, d = a*c - b*d, b*c + a*d
n -= 1
a, b = a*a - b*b, 2*a*b
n //= 2
I = S.ImaginaryUnit
if k == 1:
return c + I*d
else:
return Integer(c)/k + I*d/k
p = other_terms
# (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
# in this particular example:
# p = [x,y]; n = 3
# so now it's easy to get the correct result -- we get the
# coefficients first:
from sympy.ntheory.multinomial import multinomial_coefficients
from sympy.polys.polyutils import basic_from_dict
expansion_dict = multinomial_coefficients(len(p), n)
# in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
# and now construct the expression.
return basic_from_dict(expansion_dict, *p)
else:
if n == 2:
return Add(*[f*g for f in base.args for g in base.args])
else:
multi = (base**(n - 1))._eval_expand_multinomial()
if multi.is_Add:
return Add(*[f*g for f in base.args
for g in multi.args])
else:
# XXX can this ever happen if base was an Add?
return Add(*[f*multi for f in base.args])
elif (exp.is_Rational and exp.p < 0 and base.is_Add and
abs(exp.p) > exp.q):
return 1 / self.func(base, -exp)._eval_expand_multinomial()
elif exp.is_Add and base.is_Number and (hints.get('force', False) or
base.is_zero is False or exp._all_nonneg_or_nonppos()):
# a + b a b
# n --> n n, where n, a, b are Numbers
# XXX should be in expand_power_exp?
coeff, tail = [], []
for term in exp.args:
if term.is_Number:
coeff.append(self.func(base, term))
else:
tail.append(term)
return Mul(*(coeff + [self.func(base, Add._from_args(tail))]))
else:
return result
def as_real_imag(self, deep=True, **hints):
if self.exp.is_Integer:
from sympy.polys.polytools import poly
exp = self.exp
re_e, im_e = self.base.as_real_imag(deep=deep)
if not im_e:
return self, S.Zero
a, b = symbols('a b', cls=Dummy)
if exp >= 0:
if re_e.is_Number and im_e.is_Number:
# We can be more efficient in this case
expr = expand_multinomial(self.base**exp)
if expr != self:
return expr.as_real_imag()
expr = poly(
(a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
else:
mag = re_e**2 + im_e**2
re_e, im_e = re_e/mag, -im_e/mag
if re_e.is_Number and im_e.is_Number:
# We can be more efficient in this case
expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp)
if expr != self:
return expr.as_real_imag()
expr = poly((a + b)**-exp)
# Terms with even b powers will be real
r = [i for i in expr.terms() if not i[0][1] % 2]
re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
# Terms with odd b powers will be imaginary
r = [i for i in expr.terms() if i[0][1] % 4 == 1]
im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
r = [i for i in expr.terms() if i[0][1] % 4 == 3]
im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}),
im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e}))
from sympy.functions.elementary.trigonometric import atan2, cos, sin
if self.exp.is_Rational:
re_e, im_e = self.base.as_real_imag(deep=deep)
if im_e.is_zero and self.exp is S.Half:
if re_e.is_extended_nonnegative:
return self, S.Zero
if re_e.is_extended_nonpositive:
return S.Zero, (-self.base)**self.exp
# XXX: This is not totally correct since for x**(p/q) with
# x being imaginary there are actually q roots, but
# only a single one is returned from here.
r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half)
t = atan2(im_e, re_e)
rp, tp = self.func(r, self.exp), t*self.exp
return rp*cos(tp), rp*sin(tp)
elif self.base is S.Exp1:
from sympy.functions.elementary.exponential import exp
re_e, im_e = self.exp.as_real_imag()
if deep:
re_e = re_e.expand(deep, **hints)
im_e = im_e.expand(deep, **hints)
c, s = cos(im_e), sin(im_e)
return exp(re_e)*c, exp(re_e)*s
else:
from sympy.functions.elementary.complexes import im, re
if deep:
hints['complex'] = False
expanded = self.expand(deep, **hints)
if hints.get('ignore') == expanded:
return None
else:
return (re(expanded), im(expanded))
else:
return re(self), im(self)
def _eval_derivative(self, s):
from sympy.functions.elementary.exponential import log
dbase = self.base.diff(s)
dexp = self.exp.diff(s)
return self * (dexp * log(self.base) + dbase * self.exp/self.base)
def _eval_evalf(self, prec):
base, exp = self.as_base_exp()
if base == S.Exp1:
# Use mpmath function associated to class "exp":
from sympy.functions.elementary.exponential import exp as exp_function
return exp_function(self.exp, evaluate=False)._eval_evalf(prec)
base = base._evalf(prec)
if not exp.is_Integer:
exp = exp._evalf(prec)
if exp.is_negative and base.is_number and base.is_extended_real is False:
base = base.conjugate() / (base * base.conjugate())._evalf(prec)
exp = -exp
return self.func(base, exp).expand()
return self.func(base, exp)
def _eval_is_polynomial(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return bool(self.base._eval_is_polynomial(syms) and
self.exp.is_Integer and (self.exp >= 0))
else:
return True
def _eval_is_rational(self):
# The evaluation of self.func below can be very expensive in the case
# of integer**integer if the exponent is large. We should try to exit
# before that if possible:
if (self.exp.is_integer and self.base.is_rational
and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))):
return True
p = self.func(*self.as_base_exp()) # in case it's unevaluated
if not p.is_Pow:
return p.is_rational
b, e = p.as_base_exp()
if e.is_Rational and b.is_Rational:
# we didn't check that e is not an Integer
# because Rational**Integer autosimplifies
return False
if e.is_integer:
if b.is_rational:
if fuzzy_not(b.is_zero) or e.is_nonnegative:
return True
if b == e: # always rational, even for 0**0
return True
elif b.is_irrational:
return e.is_zero
if b is S.Exp1:
if e.is_rational and e.is_nonzero:
return False
def _eval_is_algebraic(self):
def _is_one(expr):
try:
return (expr - 1).is_zero
except ValueError:
# when the operation is not allowed
return False
if self.base.is_zero or _is_one(self.base):
return True
elif self.base is S.Exp1:
s = self.func(*self.args)
if s.func == self.func:
if self.exp.is_nonzero:
if self.exp.is_algebraic:
return False
elif (self.exp/S.Pi).is_rational:
return False
elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational:
return True
else:
return s.is_algebraic
elif self.exp.is_rational:
if self.base.is_algebraic is False:
return self.exp.is_zero
if self.base.is_zero is False:
if self.exp.is_nonzero:
return self.base.is_algebraic
elif self.base.is_algebraic:
return True
if self.exp.is_positive:
return self.base.is_algebraic
elif self.base.is_algebraic and self.exp.is_algebraic:
if ((fuzzy_not(self.base.is_zero)
and fuzzy_not(_is_one(self.base)))
or self.base.is_integer is False
or self.base.is_irrational):
return self.exp.is_rational
def _eval_is_rational_function(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return self.base._eval_is_rational_function(syms) and \
self.exp.is_Integer
else:
return True
def _eval_is_meromorphic(self, x, a):
# f**g is meromorphic if g is an integer and f is meromorphic.
# E**(log(f)*g) is meromorphic if log(f)*g is meromorphic
# and finite.
base_merom = self.base._eval_is_meromorphic(x, a)
exp_integer = self.exp.is_Integer
if exp_integer:
return base_merom
exp_merom = self.exp._eval_is_meromorphic(x, a)
if base_merom is False:
# f**g = E**(log(f)*g) may be meromorphic if the
# singularities of log(f) and g cancel each other,
# for example, if g = 1/log(f). Hence,
return False if exp_merom else None
elif base_merom is None:
return None
b = self.base.subs(x, a)
# b is extended complex as base is meromorphic.
# log(base) is finite and meromorphic when b != 0, zoo.
b_zero = b.is_zero
if b_zero:
log_defined = False
else:
log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero)))
if log_defined is False: # zero or pole of base
return exp_integer # False or None
elif log_defined is None:
return None
if not exp_merom:
return exp_merom # False or None
return self.exp.subs(x, a).is_finite
def _eval_is_algebraic_expr(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return self.base._eval_is_algebraic_expr(syms) and \
self.exp.is_Rational
else:
return True
def _eval_rewrite_as_exp(self, base, expo, **kwargs):
from sympy.functions.elementary.exponential import exp, log
if base.is_zero or base.has(exp) or expo.has(exp):
return base**expo
if base.has(Symbol):
# delay evaluation if expo is non symbolic
# (as exp(x*log(5)) automatically reduces to x**5)
if global_parameters.exp_is_pow:
return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol))
else:
return exp(log(base)*expo, evaluate=expo.has(Symbol))
else:
from sympy.functions.elementary.complexes import arg, Abs
return exp((log(Abs(base)) + S.ImaginaryUnit*arg(base))*expo)
def as_numer_denom(self):
if not self.is_commutative:
return self, S.One
base, exp = self.as_base_exp()
n, d = base.as_numer_denom()
# this should be the same as ExpBase.as_numer_denom wrt
# exponent handling
neg_exp = exp.is_negative
if exp.is_Mul and not neg_exp and not exp.is_positive:
neg_exp = exp.could_extract_minus_sign()
int_exp = exp.is_integer
# the denominator cannot be separated from the numerator if
# its sign is unknown unless the exponent is an integer, e.g.
# sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the
# denominator is negative the numerator and denominator can
# be negated and the denominator (now positive) separated.
if not (d.is_extended_real or int_exp):
n = base
d = S.One
dnonpos = d.is_nonpositive
if dnonpos:
n, d = -n, -d
elif dnonpos is None and not int_exp:
n = base
d = S.One
if neg_exp:
n, d = d, n
exp = -exp
if exp.is_infinite:
if n is S.One and d is not S.One:
return n, self.func(d, exp)
if n is not S.One and d is S.One:
return self.func(n, exp), d
return self.func(n, exp), self.func(d, exp)
def matches(self, expr, repl_dict=None, old=False):
expr = _sympify(expr)
if repl_dict is None:
repl_dict = {}
# special case, pattern = 1 and expr.exp can match to 0
if expr is S.One:
d = self.exp.matches(S.Zero, repl_dict)
if d is not None:
return d
# make sure the expression to be matched is an Expr
if not isinstance(expr, Expr):
return None
b, e = expr.as_base_exp()
# special case number
sb, se = self.as_base_exp()
if sb.is_Symbol and se.is_Integer and expr:
if e.is_rational:
return sb.matches(b**(e/se), repl_dict)
return sb.matches(expr**(1/se), repl_dict)
d = repl_dict.copy()
d = self.base.matches(b, d)
if d is None:
return None
d = self.exp.xreplace(d).matches(e, d)
if d is None:
return Expr.matches(self, expr, repl_dict)
return d
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE! This function is an important part of the gruntz algorithm
# for computing limits. It has to return a generalized power
# series with coefficients in C(log, log(x)). In more detail:
# It has to return an expression
# c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
# where e_i are numbers (not necessarily integers) and c_i are
# expressions involving only numbers, the log function, and log(x).
# The series expansion of b**e is computed as follows:
# 1) We express b as f*(1 + g) where f is the leading term of b.
# g has order O(x**d) where d is strictly positive.
# 2) Then b**e = (f**e)*((1 + g)**e).
# (1 + g)**e is computed using binomial series.
from sympy.functions.elementary.exponential import exp, log
from sympy.series.limits import limit
from sympy.series.order import Order
from sympy.core.sympify import sympify
if self.base is S.Exp1:
e_series = self.exp.nseries(x, n=n, logx=logx)
if e_series.is_Order:
return 1 + e_series
e0 = limit(e_series.removeO(), x, 0)
if e0 is S.NegativeInfinity:
return Order(x**n, x)
if e0 is S.Infinity:
return self
t = e_series - e0
exp_series = term = exp(e0)
# series of exp(e0 + t) in t
for i in range(1, n):
term *= t/i
term = term.nseries(x, n=n, logx=logx)
exp_series += term
exp_series += Order(t**n, x)
from sympy.simplify.powsimp import powsimp
return powsimp(exp_series, deep=True, combine='exp')
from sympy.simplify.powsimp import powdenest
from .numbers import _illegal
self = powdenest(self, force=True).trigsimp()
b, e = self.as_base_exp()
if e.has(*_illegal):
raise PoleError()
if e.has(x):
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
if logx is not None and b.has(log):
from .symbol import Wild
c, ex = symbols('c, ex', cls=Wild, exclude=[x])
b = b.replace(log(c*x**ex), log(c) + ex*logx)
self = b**e
b = b.removeO()
try:
from sympy.functions.special.gamma_functions import polygamma
if b.has(polygamma, S.EulerGamma) and logx is not None:
raise ValueError()
_, m = b.leadterm(x)
except (ValueError, NotImplementedError, PoleError):
b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
if b.has(S.NaN, S.ComplexInfinity):
raise NotImplementedError()
_, m = b.leadterm(x)
if e.has(log):
from sympy.simplify.simplify import logcombine
e = logcombine(e).cancel()
if not (m.is_zero or e.is_number and e.is_real):
if self == self._eval_as_leading_term(x, logx=logx, cdir=cdir):
res = exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
if res == exp(e*log(b)):
return self
return res
f = b.as_leading_term(x, logx=logx)
g = (b/f - S.One).cancel(expand=False)
if not m.is_number:
raise NotImplementedError()
maxpow = n - m*e
if maxpow.has(Symbol):
maxpow = sympify(n)
if maxpow.is_negative:
return Order(x**(m*e), x)
if g.is_zero:
r = f**e
if r != self:
r += Order(x**n, x)
return r
def coeff_exp(term, x):
coeff, exp = S.One, S.Zero
for factor in Mul.make_args(term):
if factor.has(x):
base, exp = factor.as_base_exp()
if base != x:
try:
return term.leadterm(x)
except ValueError:
return term, S.Zero
else:
coeff *= factor
return coeff, exp
def mul(d1, d2):
res = {}
for e1, e2 in product(d1, d2):
ex = e1 + e2
if ex < maxpow:
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
return res
try:
c, d = g.leadterm(x, logx=logx)
except (ValueError, NotImplementedError):
if limit(g/x**maxpow, x, 0) == 0:
# g has higher order zero
return f**e + e*f**e*g # first term of binomial series
else:
raise NotImplementedError()
if c.is_Float and d == S.Zero:
# Convert floats like 0.5 to exact SymPy numbers like S.Half, to
# prevent rounding errors which can induce wrong values of d leading
# to a NotImplementedError being returned from the block below.
from sympy.simplify.simplify import nsimplify
_, d = nsimplify(g).leadterm(x, logx=logx)
if not d.is_positive:
g = g.simplify()
if g.is_zero:
return f**e
_, d = g.leadterm(x, logx=logx)
if not d.is_positive:
g = ((b - f)/f).expand()
_, d = g.leadterm(x, logx=logx)
if not d.is_positive:
raise NotImplementedError()
from sympy.functions.elementary.integers import ceiling
gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO()
gterms = {}
for term in Add.make_args(gpoly):
co1, e1 = coeff_exp(term, x)
gterms[e1] = gterms.get(e1, S.Zero) + co1
k = S.One
terms = {S.Zero: S.One}
tk = gterms
from sympy.functions.combinatorial.factorials import factorial, ff
while (k*d - maxpow).is_negative:
coeff = ff(e, k)/factorial(k)
for ex in tk:
terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex]
tk = mul(tk, gterms)
k += S.One
from sympy.functions.elementary.complexes import im
if not e.is_integer and m.is_zero and f.is_negative:
ndir = (b - f).dir(x, cdir)
if im(ndir).is_negative:
inco, inex = coeff_exp(f**e*(-1)**(-2*e), x)
elif im(ndir).is_zero:
inco, inex = coeff_exp(exp(e*log(b)).as_leading_term(x, logx=logx, cdir=cdir), x)
else:
inco, inex = coeff_exp(f**e, x)
else:
inco, inex = coeff_exp(f**e, x)
res = S.Zero
for e1 in terms:
ex = e1 + inex
res += terms[e1]*inco*x**(ex)
if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and
res == _mexpand(self)):
try:
res += Order(x**n, x)
except NotImplementedError:
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
return res
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.functions.elementary.exponential import exp, log
e = self.exp
b = self.base
if self.base is S.Exp1:
arg = e.as_leading_term(x, logx=logx)
arg0 = arg.subs(x, 0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0)
if arg0.is_infinite is False:
return S.Exp1**arg0
raise PoleError("Cannot expand %s around 0" % (self))
elif e.has(x):
lt = exp(e * log(b))
return lt.as_leading_term(x, logx=logx, cdir=cdir)
else:
from sympy.functions.elementary.complexes import im
try:
f = b.as_leading_term(x, logx=logx, cdir=cdir)
except PoleError:
return self
if not e.is_integer and f.is_negative and not f.has(x):
ndir = (b - f).dir(x, cdir)
if im(ndir).is_negative:
# Normally, f**e would evaluate to exp(e*log(f)) but on branch cuts
# an other value is expected through the following computation
# exp(e*(log(f) - 2*pi*I)) == f**e*exp(-2*e*pi*I) == f**e*(-1)**(-2*e).
return self.func(f, e) * (-1)**(-2*e)
elif im(ndir).is_zero:
log_leadterm = log(b)._eval_as_leading_term(x, logx=logx, cdir=cdir)
if log_leadterm.is_infinite is False:
return exp(e*log_leadterm)
return self.func(f, e)
@cacheit
def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
from sympy.functions.combinatorial.factorials import binomial
return binomial(self.exp, n) * self.func(x, n)
def taylor_term(self, n, x, *previous_terms):
if self.base is not S.Exp1:
return super().taylor_term(n, x, *previous_terms)
if n < 0:
return S.Zero
if n == 0:
return S.One
from .sympify import sympify
x = sympify(x)
if previous_terms:
p = previous_terms[-1]
if p is not None:
return p * x / n
from sympy.functions.combinatorial.factorials import factorial
return x**n/factorial(n)
def _eval_rewrite_as_sin(self, base, exp):
if self.base is S.Exp1:
from sympy.functions.elementary.trigonometric import sin
return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
def _eval_rewrite_as_cos(self, base, exp):
if self.base is S.Exp1:
from sympy.functions.elementary.trigonometric import cos
return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
def _eval_rewrite_as_tanh(self, base, exp):
if self.base is S.Exp1:
from sympy.functions.elementary.hyperbolic import tanh
return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2))
def _eval_rewrite_as_sqrt(self, base, exp, **kwargs):
from sympy.functions.elementary.trigonometric import sin, cos
if base is not S.Exp1:
return None
if exp.is_Mul:
coeff = exp.coeff(S.Pi * S.ImaginaryUnit)
if coeff and coeff.is_number:
cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
if not isinstance(cosine, cos) and not isinstance (sine, sin):
return cosine + S.ImaginaryUnit*sine
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import sqrt
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
(2, sqrt(1 + sqrt(2)))
>>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
(1, sqrt(3)*sqrt(1 + sqrt(2)))
>>> from sympy import expand_power_base, powsimp, Mul
>>> from sympy.abc import x, y
>>> ((2*x + 2)**2).as_content_primitive()
(4, (x + 1)**2)
>>> (4**((1 + y)/2)).as_content_primitive()
(2, 4**(y/2))
>>> (3**((1 + y)/2)).as_content_primitive()
(1, 3**((y + 1)/2))
>>> (3**((5 + y)/2)).as_content_primitive()
(9, 3**((y + 1)/2))
>>> eq = 3**(2 + 2*x)
>>> powsimp(eq) == eq
True
>>> eq.as_content_primitive()
(9, 3**(2*x))
>>> powsimp(Mul(*_))
3**(2*x + 2)
>>> eq = (2 + 2*x)**y
>>> s = expand_power_base(eq); s.is_Mul, s
(False, (2*x + 2)**y)
>>> eq.as_content_primitive()
(1, (2*(x + 1))**y)
>>> s = expand_power_base(_[1]); s.is_Mul, s
(True, 2**y*(x + 1)**y)
See docstring of Expr.as_content_primitive for more examples.
"""
b, e = self.as_base_exp()
b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear))
ce, pe = e.as_content_primitive(radical=radical, clear=clear)
if b.is_Rational:
#e
#= ce*pe
#= ce*(h + t)
#= ce*h + ce*t
#=> self
#= b**(ce*h)*b**(ce*t)
#= b**(cehp/cehq)*b**(ce*t)
#= b**(iceh + r/cehq)*b**(ce*t)
#= b**(iceh)*b**(r/cehq)*b**(ce*t)
#= b**(iceh)*b**(ce*t + r/cehq)
h, t = pe.as_coeff_Add()
if h.is_Rational and b != S.Zero:
ceh = ce*h
c = self.func(b, ceh)
r = S.Zero
if not c.is_Rational:
iceh, r = divmod(ceh.p, ceh.q)
c = self.func(b, iceh)
return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q))
e = _keep_coeff(ce, pe)
# b**e = (h*t)**e = h**e*t**e = c*m*t**e
if e.is_Rational and b.is_Mul:
h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive
c, m = self.func(h, e).as_coeff_Mul() # so c is positive
m, me = m.as_base_exp()
if m is S.One or me == e: # probably always true
# return the following, not return c, m*Pow(t, e)
# which would change Pow into Mul; we let SymPy
# decide what to do by using the unevaluated Mul, e.g
# should it stay as sqrt(2 + 2*sqrt(5)) or become
# sqrt(2)*sqrt(1 + sqrt(5))
return c, self.func(_keep_coeff(m, t), e)
return S.One, self.func(b, e)
def is_constant(self, *wrt, **flags):
expr = self
if flags.get('simplify', True):
expr = expr.simplify()
b, e = expr.as_base_exp()
bz = b.equals(0)
if bz: # recalculate with assumptions in case it's unevaluated
new = b**e
if new != expr:
return new.is_constant()
econ = e.is_constant(*wrt)
bcon = b.is_constant(*wrt)
if bcon:
if econ:
return True
bz = b.equals(0)
if bz is False:
return False
elif bcon is None:
return None
return e.equals(0)
def _eval_difference_delta(self, n, step):
b, e = self.args
if e.has(n) and not b.has(n):
new_e = e.subs(n, n + step)
return (b**(new_e - e) - 1) * self
power = Dispatcher('power')
power.add((object, object), Pow)
from .add import Add
from .numbers import Integer
from .mul import Mul, _keep_coeff
from .symbol import Symbol, Dummy, symbols
|
d1324a6081d2205c907151d97481d9d7d6fbb6ab2dfec63b899c232b372f6413 | """
Do NOT manually edit this file.
Instead, run ./bin/ask_update.py.
"""
defined_facts = [
'algebraic',
'antihermitian',
'commutative',
'complex',
'composite',
'even',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'negative',
'noninteger',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'transcendental',
'zero',
] # defined_facts
full_implications = dict( [
# Implications of algebraic = True:
(('algebraic', True), set( (
('commutative', True),
('complex', True),
('finite', True),
('infinite', False),
('transcendental', False),
) ),
),
# Implications of algebraic = False:
(('algebraic', False), set( (
('composite', False),
('even', False),
('integer', False),
('odd', False),
('prime', False),
('rational', False),
('zero', False),
) ),
),
# Implications of antihermitian = True:
(('antihermitian', True), set( (
) ),
),
# Implications of antihermitian = False:
(('antihermitian', False), set( (
('imaginary', False),
) ),
),
# Implications of commutative = True:
(('commutative', True), set( (
) ),
),
# Implications of commutative = False:
(('commutative', False), set( (
('algebraic', False),
('complex', False),
('composite', False),
('even', False),
('extended_negative', False),
('extended_nonnegative', False),
('extended_nonpositive', False),
('extended_nonzero', False),
('extended_positive', False),
('extended_real', False),
('imaginary', False),
('integer', False),
('irrational', False),
('negative', False),
('noninteger', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('real', False),
('transcendental', False),
('zero', False),
) ),
),
# Implications of complex = True:
(('complex', True), set( (
('commutative', True),
('finite', True),
('infinite', False),
) ),
),
# Implications of complex = False:
(('complex', False), set( (
('algebraic', False),
('composite', False),
('even', False),
('imaginary', False),
('integer', False),
('irrational', False),
('negative', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('real', False),
('transcendental', False),
('zero', False),
) ),
),
# Implications of composite = True:
(('composite', True), set( (
('algebraic', True),
('commutative', True),
('complex', True),
('extended_negative', False),
('extended_nonnegative', True),
('extended_nonpositive', False),
('extended_nonzero', True),
('extended_positive', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('integer', True),
('irrational', False),
('negative', False),
('noninteger', False),
('nonnegative', True),
('nonpositive', False),
('nonzero', True),
('positive', True),
('prime', False),
('rational', True),
('real', True),
('transcendental', False),
('zero', False),
) ),
),
# Implications of composite = False:
(('composite', False), set( (
) ),
),
# Implications of even = True:
(('even', True), set( (
('algebraic', True),
('commutative', True),
('complex', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('integer', True),
('irrational', False),
('noninteger', False),
('odd', False),
('rational', True),
('real', True),
('transcendental', False),
) ),
),
# Implications of even = False:
(('even', False), set( (
('zero', False),
) ),
),
# Implications of extended_negative = True:
(('extended_negative', True), set( (
('commutative', True),
('composite', False),
('extended_nonnegative', False),
('extended_nonpositive', True),
('extended_nonzero', True),
('extended_positive', False),
('extended_real', True),
('imaginary', False),
('nonnegative', False),
('positive', False),
('prime', False),
('zero', False),
) ),
),
# Implications of extended_negative = False:
(('extended_negative', False), set( (
('negative', False),
) ),
),
# Implications of extended_nonnegative = True:
(('extended_nonnegative', True), set( (
('commutative', True),
('extended_negative', False),
('extended_real', True),
('imaginary', False),
('negative', False),
) ),
),
# Implications of extended_nonnegative = False:
(('extended_nonnegative', False), set( (
('composite', False),
('extended_positive', False),
('nonnegative', False),
('positive', False),
('prime', False),
('zero', False),
) ),
),
# Implications of extended_nonpositive = True:
(('extended_nonpositive', True), set( (
('commutative', True),
('composite', False),
('extended_positive', False),
('extended_real', True),
('imaginary', False),
('positive', False),
('prime', False),
) ),
),
# Implications of extended_nonpositive = False:
(('extended_nonpositive', False), set( (
('extended_negative', False),
('negative', False),
('nonpositive', False),
('zero', False),
) ),
),
# Implications of extended_nonzero = True:
(('extended_nonzero', True), set( (
('commutative', True),
('extended_real', True),
('imaginary', False),
('zero', False),
) ),
),
# Implications of extended_nonzero = False:
(('extended_nonzero', False), set( (
('composite', False),
('extended_negative', False),
('extended_positive', False),
('negative', False),
('nonzero', False),
('positive', False),
('prime', False),
) ),
),
# Implications of extended_positive = True:
(('extended_positive', True), set( (
('commutative', True),
('extended_negative', False),
('extended_nonnegative', True),
('extended_nonpositive', False),
('extended_nonzero', True),
('extended_real', True),
('imaginary', False),
('negative', False),
('nonpositive', False),
('zero', False),
) ),
),
# Implications of extended_positive = False:
(('extended_positive', False), set( (
('composite', False),
('positive', False),
('prime', False),
) ),
),
# Implications of extended_real = True:
(('extended_real', True), set( (
('commutative', True),
('imaginary', False),
) ),
),
# Implications of extended_real = False:
(('extended_real', False), set( (
('composite', False),
('even', False),
('extended_negative', False),
('extended_nonnegative', False),
('extended_nonpositive', False),
('extended_nonzero', False),
('extended_positive', False),
('integer', False),
('irrational', False),
('negative', False),
('noninteger', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('real', False),
('zero', False),
) ),
),
# Implications of finite = True:
(('finite', True), set( (
('infinite', False),
) ),
),
# Implications of finite = False:
(('finite', False), set( (
('algebraic', False),
('complex', False),
('composite', False),
('even', False),
('imaginary', False),
('infinite', True),
('integer', False),
('irrational', False),
('negative', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('real', False),
('transcendental', False),
('zero', False),
) ),
),
# Implications of hermitian = True:
(('hermitian', True), set( (
) ),
),
# Implications of hermitian = False:
(('hermitian', False), set( (
('composite', False),
('even', False),
('integer', False),
('irrational', False),
('negative', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('real', False),
('zero', False),
) ),
),
# Implications of imaginary = True:
(('imaginary', True), set( (
('antihermitian', True),
('commutative', True),
('complex', True),
('composite', False),
('even', False),
('extended_negative', False),
('extended_nonnegative', False),
('extended_nonpositive', False),
('extended_nonzero', False),
('extended_positive', False),
('extended_real', False),
('finite', True),
('infinite', False),
('integer', False),
('irrational', False),
('negative', False),
('noninteger', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('real', False),
('zero', False),
) ),
),
# Implications of imaginary = False:
(('imaginary', False), set( (
) ),
),
# Implications of infinite = True:
(('infinite', True), set( (
('algebraic', False),
('complex', False),
('composite', False),
('even', False),
('finite', False),
('imaginary', False),
('integer', False),
('irrational', False),
('negative', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('real', False),
('transcendental', False),
('zero', False),
) ),
),
# Implications of infinite = False:
(('infinite', False), set( (
('finite', True),
) ),
),
# Implications of integer = True:
(('integer', True), set( (
('algebraic', True),
('commutative', True),
('complex', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('irrational', False),
('noninteger', False),
('rational', True),
('real', True),
('transcendental', False),
) ),
),
# Implications of integer = False:
(('integer', False), set( (
('composite', False),
('even', False),
('odd', False),
('prime', False),
('zero', False),
) ),
),
# Implications of irrational = True:
(('irrational', True), set( (
('commutative', True),
('complex', True),
('composite', False),
('even', False),
('extended_nonzero', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('integer', False),
('noninteger', True),
('nonzero', True),
('odd', False),
('prime', False),
('rational', False),
('real', True),
('zero', False),
) ),
),
# Implications of irrational = False:
(('irrational', False), set( (
) ),
),
# Implications of negative = True:
(('negative', True), set( (
('commutative', True),
('complex', True),
('composite', False),
('extended_negative', True),
('extended_nonnegative', False),
('extended_nonpositive', True),
('extended_nonzero', True),
('extended_positive', False),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('nonnegative', False),
('nonpositive', True),
('nonzero', True),
('positive', False),
('prime', False),
('real', True),
('zero', False),
) ),
),
# Implications of negative = False:
(('negative', False), set( (
) ),
),
# Implications of noninteger = True:
(('noninteger', True), set( (
('commutative', True),
('composite', False),
('even', False),
('extended_nonzero', True),
('extended_real', True),
('imaginary', False),
('integer', False),
('odd', False),
('prime', False),
('zero', False),
) ),
),
# Implications of noninteger = False:
(('noninteger', False), set( (
) ),
),
# Implications of nonnegative = True:
(('nonnegative', True), set( (
('commutative', True),
('complex', True),
('extended_negative', False),
('extended_nonnegative', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('negative', False),
('real', True),
) ),
),
# Implications of nonnegative = False:
(('nonnegative', False), set( (
('composite', False),
('positive', False),
('prime', False),
('zero', False),
) ),
),
# Implications of nonpositive = True:
(('nonpositive', True), set( (
('commutative', True),
('complex', True),
('composite', False),
('extended_nonpositive', True),
('extended_positive', False),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('positive', False),
('prime', False),
('real', True),
) ),
),
# Implications of nonpositive = False:
(('nonpositive', False), set( (
('negative', False),
('zero', False),
) ),
),
# Implications of nonzero = True:
(('nonzero', True), set( (
('commutative', True),
('complex', True),
('extended_nonzero', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('real', True),
('zero', False),
) ),
),
# Implications of nonzero = False:
(('nonzero', False), set( (
('composite', False),
('negative', False),
('positive', False),
('prime', False),
) ),
),
# Implications of odd = True:
(('odd', True), set( (
('algebraic', True),
('commutative', True),
('complex', True),
('even', False),
('extended_nonzero', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('integer', True),
('irrational', False),
('noninteger', False),
('nonzero', True),
('rational', True),
('real', True),
('transcendental', False),
('zero', False),
) ),
),
# Implications of odd = False:
(('odd', False), set( (
) ),
),
# Implications of positive = True:
(('positive', True), set( (
('commutative', True),
('complex', True),
('extended_negative', False),
('extended_nonnegative', True),
('extended_nonpositive', False),
('extended_nonzero', True),
('extended_positive', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('negative', False),
('nonnegative', True),
('nonpositive', False),
('nonzero', True),
('real', True),
('zero', False),
) ),
),
# Implications of positive = False:
(('positive', False), set( (
('composite', False),
('prime', False),
) ),
),
# Implications of prime = True:
(('prime', True), set( (
('algebraic', True),
('commutative', True),
('complex', True),
('composite', False),
('extended_negative', False),
('extended_nonnegative', True),
('extended_nonpositive', False),
('extended_nonzero', True),
('extended_positive', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('integer', True),
('irrational', False),
('negative', False),
('noninteger', False),
('nonnegative', True),
('nonpositive', False),
('nonzero', True),
('positive', True),
('rational', True),
('real', True),
('transcendental', False),
('zero', False),
) ),
),
# Implications of prime = False:
(('prime', False), set( (
) ),
),
# Implications of rational = True:
(('rational', True), set( (
('algebraic', True),
('commutative', True),
('complex', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('irrational', False),
('real', True),
('transcendental', False),
) ),
),
# Implications of rational = False:
(('rational', False), set( (
('composite', False),
('even', False),
('integer', False),
('odd', False),
('prime', False),
('zero', False),
) ),
),
# Implications of real = True:
(('real', True), set( (
('commutative', True),
('complex', True),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
) ),
),
# Implications of real = False:
(('real', False), set( (
('composite', False),
('even', False),
('integer', False),
('irrational', False),
('negative', False),
('nonnegative', False),
('nonpositive', False),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', False),
('zero', False),
) ),
),
# Implications of transcendental = True:
(('transcendental', True), set( (
('algebraic', False),
('commutative', True),
('complex', True),
('composite', False),
('even', False),
('finite', True),
('infinite', False),
('integer', False),
('odd', False),
('prime', False),
('rational', False),
('zero', False),
) ),
),
# Implications of transcendental = False:
(('transcendental', False), set( (
) ),
),
# Implications of zero = True:
(('zero', True), set( (
('algebraic', True),
('commutative', True),
('complex', True),
('composite', False),
('even', True),
('extended_negative', False),
('extended_nonnegative', True),
('extended_nonpositive', True),
('extended_nonzero', False),
('extended_positive', False),
('extended_real', True),
('finite', True),
('hermitian', True),
('imaginary', False),
('infinite', False),
('integer', True),
('irrational', False),
('negative', False),
('noninteger', False),
('nonnegative', True),
('nonpositive', True),
('nonzero', False),
('odd', False),
('positive', False),
('prime', False),
('rational', True),
('real', True),
('transcendental', False),
) ),
),
# Implications of zero = False:
(('zero', False), set( (
) ),
),
] ) # full_implications
prereq = {
# facts that could determine the value of algebraic
'algebraic': {
'commutative',
'complex',
'composite',
'even',
'finite',
'infinite',
'integer',
'odd',
'prime',
'rational',
'transcendental',
'zero',
},
# facts that could determine the value of antihermitian
'antihermitian': {
'imaginary',
},
# facts that could determine the value of commutative
'commutative': {
'algebraic',
'complex',
'composite',
'even',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'imaginary',
'integer',
'irrational',
'negative',
'noninteger',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of complex
'complex': {
'algebraic',
'commutative',
'composite',
'even',
'finite',
'imaginary',
'infinite',
'integer',
'irrational',
'negative',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of composite
'composite': {
'algebraic',
'commutative',
'complex',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'negative',
'noninteger',
'nonnegative',
'nonpositive',
'nonzero',
'positive',
'prime',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of even
'even': {
'algebraic',
'commutative',
'complex',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'noninteger',
'odd',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of extended_negative
'extended_negative': {
'commutative',
'composite',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'imaginary',
'negative',
'nonnegative',
'positive',
'prime',
'zero',
},
# facts that could determine the value of extended_nonnegative
'extended_nonnegative': {
'commutative',
'composite',
'extended_negative',
'extended_positive',
'extended_real',
'imaginary',
'negative',
'nonnegative',
'positive',
'prime',
'zero',
},
# facts that could determine the value of extended_nonpositive
'extended_nonpositive': {
'commutative',
'composite',
'extended_negative',
'extended_positive',
'extended_real',
'imaginary',
'negative',
'nonpositive',
'positive',
'prime',
'zero',
},
# facts that could determine the value of extended_nonzero
'extended_nonzero': {
'commutative',
'composite',
'extended_negative',
'extended_positive',
'extended_real',
'imaginary',
'irrational',
'negative',
'noninteger',
'nonzero',
'odd',
'positive',
'prime',
'zero',
},
# facts that could determine the value of extended_positive
'extended_positive': {
'commutative',
'composite',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_real',
'imaginary',
'negative',
'nonpositive',
'positive',
'prime',
'zero',
},
# facts that could determine the value of extended_real
'extended_real': {
'commutative',
'composite',
'even',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'imaginary',
'integer',
'irrational',
'negative',
'noninteger',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'zero',
},
# facts that could determine the value of finite
'finite': {
'algebraic',
'complex',
'composite',
'even',
'imaginary',
'infinite',
'integer',
'irrational',
'negative',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of hermitian
'hermitian': {
'composite',
'even',
'integer',
'irrational',
'negative',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'zero',
},
# facts that could determine the value of imaginary
'imaginary': {
'antihermitian',
'commutative',
'complex',
'composite',
'even',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'finite',
'infinite',
'integer',
'irrational',
'negative',
'noninteger',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'zero',
},
# facts that could determine the value of infinite
'infinite': {
'algebraic',
'complex',
'composite',
'even',
'finite',
'imaginary',
'integer',
'irrational',
'negative',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of integer
'integer': {
'algebraic',
'commutative',
'complex',
'composite',
'even',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'irrational',
'noninteger',
'odd',
'prime',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of irrational
'irrational': {
'commutative',
'complex',
'composite',
'even',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'odd',
'prime',
'rational',
'real',
'zero',
},
# facts that could determine the value of negative
'negative': {
'commutative',
'complex',
'composite',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'nonnegative',
'nonpositive',
'nonzero',
'positive',
'prime',
'real',
'zero',
},
# facts that could determine the value of noninteger
'noninteger': {
'commutative',
'composite',
'even',
'extended_real',
'imaginary',
'integer',
'irrational',
'odd',
'prime',
'zero',
},
# facts that could determine the value of nonnegative
'nonnegative': {
'commutative',
'complex',
'composite',
'extended_negative',
'extended_nonnegative',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'negative',
'positive',
'prime',
'real',
'zero',
},
# facts that could determine the value of nonpositive
'nonpositive': {
'commutative',
'complex',
'composite',
'extended_nonpositive',
'extended_positive',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'negative',
'positive',
'prime',
'real',
'zero',
},
# facts that could determine the value of nonzero
'nonzero': {
'commutative',
'complex',
'composite',
'extended_nonzero',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'irrational',
'negative',
'odd',
'positive',
'prime',
'real',
'zero',
},
# facts that could determine the value of odd
'odd': {
'algebraic',
'commutative',
'complex',
'even',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'noninteger',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of positive
'positive': {
'commutative',
'complex',
'composite',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'negative',
'nonnegative',
'nonpositive',
'nonzero',
'prime',
'real',
'zero',
},
# facts that could determine the value of prime
'prime': {
'algebraic',
'commutative',
'complex',
'composite',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'negative',
'noninteger',
'nonnegative',
'nonpositive',
'nonzero',
'positive',
'rational',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of rational
'rational': {
'algebraic',
'commutative',
'complex',
'composite',
'even',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'odd',
'prime',
'real',
'transcendental',
'zero',
},
# facts that could determine the value of real
'real': {
'commutative',
'complex',
'composite',
'even',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'negative',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'zero',
},
# facts that could determine the value of transcendental
'transcendental': {
'algebraic',
'commutative',
'complex',
'composite',
'even',
'finite',
'infinite',
'integer',
'odd',
'prime',
'rational',
'zero',
},
# facts that could determine the value of zero
'zero': {
'algebraic',
'commutative',
'complex',
'composite',
'even',
'extended_negative',
'extended_nonnegative',
'extended_nonpositive',
'extended_nonzero',
'extended_positive',
'extended_real',
'finite',
'hermitian',
'imaginary',
'infinite',
'integer',
'irrational',
'negative',
'noninteger',
'nonnegative',
'nonpositive',
'nonzero',
'odd',
'positive',
'prime',
'rational',
'real',
'transcendental',
},
} # prereq
# Note: the order of the beta rules is used in the beta_triggers
beta_rules = [
# Rules implying composite = True
({('even', True), ('positive', True), ('prime', False)},
('composite', True)),
# Rules implying even = False
({('composite', False), ('positive', True), ('prime', False)},
('even', False)),
# Rules implying even = True
({('integer', True), ('odd', False)},
('even', True)),
# Rules implying extended_negative = True
({('extended_positive', False), ('extended_real', True), ('zero', False)},
('extended_negative', True)),
({('extended_nonpositive', True), ('extended_nonzero', True)},
('extended_negative', True)),
# Rules implying extended_nonnegative = True
({('extended_negative', False), ('extended_real', True)},
('extended_nonnegative', True)),
# Rules implying extended_nonpositive = True
({('extended_positive', False), ('extended_real', True)},
('extended_nonpositive', True)),
# Rules implying extended_nonzero = True
({('extended_real', True), ('zero', False)},
('extended_nonzero', True)),
# Rules implying extended_positive = True
({('extended_negative', False), ('extended_real', True), ('zero', False)},
('extended_positive', True)),
({('extended_nonnegative', True), ('extended_nonzero', True)},
('extended_positive', True)),
# Rules implying extended_real = False
({('infinite', False), ('real', False)},
('extended_real', False)),
({('extended_negative', False), ('extended_positive', False), ('zero', False)},
('extended_real', False)),
# Rules implying infinite = True
({('extended_real', True), ('real', False)},
('infinite', True)),
# Rules implying irrational = True
({('rational', False), ('real', True)},
('irrational', True)),
# Rules implying negative = True
({('positive', False), ('real', True), ('zero', False)},
('negative', True)),
({('nonpositive', True), ('nonzero', True)},
('negative', True)),
({('extended_negative', True), ('finite', True)},
('negative', True)),
# Rules implying noninteger = True
({('extended_real', True), ('integer', False)},
('noninteger', True)),
# Rules implying nonnegative = True
({('negative', False), ('real', True)},
('nonnegative', True)),
({('extended_nonnegative', True), ('finite', True)},
('nonnegative', True)),
# Rules implying nonpositive = True
({('positive', False), ('real', True)},
('nonpositive', True)),
({('extended_nonpositive', True), ('finite', True)},
('nonpositive', True)),
# Rules implying nonzero = True
({('extended_nonzero', True), ('finite', True)},
('nonzero', True)),
# Rules implying odd = True
({('even', False), ('integer', True)},
('odd', True)),
# Rules implying positive = False
({('composite', False), ('even', True), ('prime', False)},
('positive', False)),
# Rules implying positive = True
({('negative', False), ('real', True), ('zero', False)},
('positive', True)),
({('nonnegative', True), ('nonzero', True)},
('positive', True)),
({('extended_positive', True), ('finite', True)},
('positive', True)),
# Rules implying prime = True
({('composite', False), ('even', True), ('positive', True)},
('prime', True)),
# Rules implying real = False
({('negative', False), ('positive', False), ('zero', False)},
('real', False)),
# Rules implying real = True
({('extended_real', True), ('infinite', False)},
('real', True)),
({('extended_real', True), ('finite', True)},
('real', True)),
# Rules implying transcendental = True
({('algebraic', False), ('complex', True)},
('transcendental', True)),
# Rules implying zero = True
({('extended_negative', False), ('extended_positive', False), ('extended_real', True)},
('zero', True)),
({('negative', False), ('positive', False), ('real', True)},
('zero', True)),
({('extended_nonnegative', True), ('extended_nonpositive', True)},
('zero', True)),
({('nonnegative', True), ('nonpositive', True)},
('zero', True)),
] # beta_rules
beta_triggers = {
('algebraic', False): [32, 11, 3, 8, 29, 14, 25, 13, 17, 7],
('algebraic', True): [10, 30, 31, 27, 16, 21, 19, 22],
('antihermitian', False): [],
('commutative', False): [],
('complex', False): [10, 12, 11, 3, 8, 17, 7],
('complex', True): [32, 10, 30, 31, 27, 16, 21, 19, 22],
('composite', False): [1, 28, 24],
('composite', True): [23, 2],
('even', False): [23, 11, 3, 8, 29, 14, 25, 7],
('even', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 0, 28, 24, 7],
('extended_negative', False): [11, 33, 8, 5, 29, 34, 25, 18],
('extended_negative', True): [30, 12, 31, 29, 14, 20, 16, 21, 22, 17],
('extended_nonnegative', False): [11, 3, 6, 29, 14, 20, 7],
('extended_nonnegative', True): [30, 12, 31, 33, 8, 9, 6, 29, 34, 25, 18, 19, 35, 17, 7],
('extended_nonpositive', False): [11, 8, 5, 29, 25, 18, 7],
('extended_nonpositive', True): [30, 12, 31, 3, 33, 4, 5, 29, 14, 34, 20, 21, 35, 17, 7],
('extended_nonzero', False): [11, 33, 6, 5, 29, 34, 20, 18],
('extended_nonzero', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22, 17],
('extended_positive', False): [11, 3, 33, 6, 29, 14, 34, 20],
('extended_positive', True): [30, 12, 31, 29, 25, 18, 27, 19, 22, 17],
('extended_real', False): [],
('extended_real', True): [30, 12, 31, 3, 33, 8, 6, 5, 17, 7],
('finite', False): [11, 3, 8, 17, 7],
('finite', True): [10, 30, 31, 27, 16, 21, 19, 22],
('hermitian', False): [10, 12, 11, 3, 8, 17, 7],
('imaginary', True): [32],
('infinite', False): [10, 30, 31, 27, 16, 21, 19, 22],
('infinite', True): [11, 3, 8, 17, 7],
('integer', False): [11, 3, 8, 29, 14, 25, 17, 7],
('integer', True): [23, 2, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 7],
('irrational', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19],
('negative', False): [29, 34, 25, 18],
('negative', True): [32, 13, 17],
('noninteger', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22],
('nonnegative', False): [11, 3, 8, 29, 14, 20, 7],
('nonnegative', True): [32, 33, 8, 9, 6, 34, 25, 26, 20, 27, 21, 22, 35, 36, 13, 17, 7],
('nonpositive', False): [11, 3, 8, 29, 25, 18, 7],
('nonpositive', True): [32, 3, 33, 4, 5, 14, 34, 15, 18, 16, 19, 22, 35, 36, 13, 17, 7],
('nonzero', False): [29, 34, 20, 18],
('nonzero', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19, 13, 17],
('odd', False): [2],
('odd', True): [3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19],
('positive', False): [29, 14, 34, 20],
('positive', True): [32, 0, 1, 28, 13, 17],
('prime', False): [0, 1, 24],
('prime', True): [23, 2],
('rational', False): [11, 3, 8, 29, 14, 25, 13, 17, 7],
('rational', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 17, 7],
('real', False): [10, 12, 11, 3, 8, 17, 7],
('real', True): [32, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 13, 17, 7],
('transcendental', True): [10, 30, 31, 11, 3, 8, 29, 14, 25, 27, 16, 21, 19, 22, 13, 17, 7],
('zero', False): [11, 3, 8, 29, 14, 25, 7],
('zero', True): [],
} # beta_triggers
generated_assumptions = {'defined_facts': defined_facts, 'full_implications': full_implications,
'prereq': prereq, 'beta_rules': beta_rules, 'beta_triggers': beta_triggers}
|
7942fa5fee2359830706366512ff2a63cfbd62e4630487b219f43b6e5a3e1427 | """Tools for manipulating of large commutative expressions. """
from .add import Add
from .mul import Mul, _keep_coeff
from .power import Pow
from .basic import Basic
from .expr import Expr
from .function import expand_power_exp
from .sympify import sympify
from .numbers import Rational, Integer, Number, I
from .singleton import S
from .sorting import default_sort_key, ordered
from .symbol import Dummy
from .traversal import preorder_traversal
from .coreerrors import NonCommutativeExpression
from .containers import Tuple, Dict
from sympy.external.gmpy import SYMPY_INTS
from sympy.utilities.iterables import (common_prefix, common_suffix,
variations, iterable, is_sequence)
from collections import defaultdict
from typing import Tuple as tTuple
_eps = Dummy(positive=True)
def _isnumber(i):
return isinstance(i, (SYMPY_INTS, float)) or i.is_Number
def _monotonic_sign(self):
"""Return the value closest to 0 that ``self`` may have if all symbols
are signed and the result is uniformly the same sign for all values of symbols.
If a symbol is only signed but not known to be an
integer or the result is 0 then a symbol representative of the sign of self
will be returned. Otherwise, None is returned if a) the sign could be positive
or negative or b) self is not in one of the following forms:
- L(x, y, ...) + A: a function linear in all symbols x, y, ... with an
additive constant; if A is zero then the function can be a monomial whose
sign is monotonic over the range of the variables, e.g. (x + 1)**3 if x is
nonnegative.
- A/L(x, y, ...) + B: the inverse of a function linear in all symbols x, y, ...
that does not have a sign change from positive to negative for any set
of values for the variables.
- M(x, y, ...) + A: a monomial M whose factors are all signed and a constant, A.
- A/M(x, y, ...) + B: the inverse of a monomial and constants A and B.
- P(x): a univariate polynomial
Examples
========
>>> from sympy.core.exprtools import _monotonic_sign as F
>>> from sympy import Dummy
>>> nn = Dummy(integer=True, nonnegative=True)
>>> p = Dummy(integer=True, positive=True)
>>> p2 = Dummy(integer=True, positive=True)
>>> F(nn + 1)
1
>>> F(p - 1)
_nneg
>>> F(nn*p + 1)
1
>>> F(p2*p + 1)
2
>>> F(nn - 1) # could be negative, zero or positive
"""
if not self.is_extended_real:
return
if (-self).is_Symbol:
rv = _monotonic_sign(-self)
return rv if rv is None else -rv
if not self.is_Add and self.as_numer_denom()[1].is_number:
s = self
if s.is_prime:
if s.is_odd:
return Integer(3)
else:
return Integer(2)
elif s.is_composite:
if s.is_odd:
return Integer(9)
else:
return Integer(4)
elif s.is_positive:
if s.is_even:
if s.is_prime is False:
return Integer(4)
else:
return Integer(2)
elif s.is_integer:
return S.One
else:
return _eps
elif s.is_extended_negative:
if s.is_even:
return Integer(-2)
elif s.is_integer:
return S.NegativeOne
else:
return -_eps
if s.is_zero or s.is_extended_nonpositive or s.is_extended_nonnegative:
return S.Zero
return None
# univariate polynomial
free = self.free_symbols
if len(free) == 1:
if self.is_polynomial():
from sympy.polys.polytools import real_roots
from sympy.polys.polyroots import roots
from sympy.polys.polyerrors import PolynomialError
x = free.pop()
x0 = _monotonic_sign(x)
if x0 in (_eps, -_eps):
x0 = S.Zero
if x0 is not None:
d = self.diff(x)
if d.is_number:
currentroots = []
else:
try:
currentroots = real_roots(d)
except (PolynomialError, NotImplementedError):
currentroots = [r for r in roots(d, x) if r.is_extended_real]
y = self.subs(x, x0)
if x.is_nonnegative and all(
(r - x0).is_nonpositive for r in currentroots):
if y.is_nonnegative and d.is_positive:
if y:
return y if y.is_positive else Dummy('pos', positive=True)
else:
return Dummy('nneg', nonnegative=True)
if y.is_nonpositive and d.is_negative:
if y:
return y if y.is_negative else Dummy('neg', negative=True)
else:
return Dummy('npos', nonpositive=True)
elif x.is_nonpositive and all(
(r - x0).is_nonnegative for r in currentroots):
if y.is_nonnegative and d.is_negative:
if y:
return Dummy('pos', positive=True)
else:
return Dummy('nneg', nonnegative=True)
if y.is_nonpositive and d.is_positive:
if y:
return Dummy('neg', negative=True)
else:
return Dummy('npos', nonpositive=True)
else:
n, d = self.as_numer_denom()
den = None
if n.is_number:
den = _monotonic_sign(d)
elif not d.is_number:
if _monotonic_sign(n) is not None:
den = _monotonic_sign(d)
if den is not None and (den.is_positive or den.is_negative):
v = n*den
if v.is_positive:
return Dummy('pos', positive=True)
elif v.is_nonnegative:
return Dummy('nneg', nonnegative=True)
elif v.is_negative:
return Dummy('neg', negative=True)
elif v.is_nonpositive:
return Dummy('npos', nonpositive=True)
return None
# multivariate
c, a = self.as_coeff_Add()
v = None
if not a.is_polynomial():
# F/A or A/F where A is a number and F is a signed, rational monomial
n, d = a.as_numer_denom()
if not (n.is_number or d.is_number):
return
if (
a.is_Mul or a.is_Pow) and \
a.is_rational and \
all(p.exp.is_Integer for p in a.atoms(Pow) if p.is_Pow) and \
(a.is_positive or a.is_negative):
v = S.One
for ai in Mul.make_args(a):
if ai.is_number:
v *= ai
continue
reps = {}
for x in ai.free_symbols:
reps[x] = _monotonic_sign(x)
if reps[x] is None:
return
v *= ai.subs(reps)
elif c:
# signed linear expression
if not any(p for p in a.atoms(Pow) if not p.is_number) and (a.is_nonpositive or a.is_nonnegative):
free = list(a.free_symbols)
p = {}
for i in free:
v = _monotonic_sign(i)
if v is None:
return
p[i] = v or (_eps if i.is_nonnegative else -_eps)
v = a.xreplace(p)
if v is not None:
rv = v + c
if v.is_nonnegative and rv.is_positive:
return rv.subs(_eps, 0)
if v.is_nonpositive and rv.is_negative:
return rv.subs(_eps, 0)
def decompose_power(expr: Expr) -> tTuple[Expr, int]:
"""
Decompose power into symbolic base and integer exponent.
Examples
========
>>> from sympy.core.exprtools import decompose_power
>>> from sympy.abc import x, y
>>> from sympy import exp
>>> decompose_power(x)
(x, 1)
>>> decompose_power(x**2)
(x, 2)
>>> decompose_power(exp(2*y/3))
(exp(y/3), 2)
"""
base, exp = expr.as_base_exp()
if exp.is_Number:
if exp.is_Rational:
if not exp.is_Integer:
base = Pow(base, Rational(1, exp.q)) # type: ignore
e = exp.p # type: ignore
else:
base, e = expr, 1
else:
exp, tail = exp.as_coeff_Mul(rational=True)
if exp is S.NegativeOne:
base, e = Pow(base, tail), -1
elif exp is not S.One:
# todo: after dropping python 3.7 support, use overload and Literal
# in as_coeff_Mul to make exp Rational, and remove these 2 ignores
tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore
base, e = Pow(base, tail), exp.p # type: ignore
else:
base, e = expr, 1
return base, e
def decompose_power_rat(expr: Expr) -> tTuple[Expr, Rational]:
"""
Decompose power into symbolic base and rational exponent;
if the exponent is not a Rational, then separate only the
integer coefficient.
Examples
========
>>> from sympy.core.exprtools import decompose_power_rat
>>> from sympy.abc import x
>>> from sympy import sqrt, exp
>>> decompose_power_rat(sqrt(x))
(x, 1/2)
>>> decompose_power_rat(exp(-3*x/2))
(exp(x/2), -3)
"""
_ = base, exp = expr.as_base_exp()
return _ if exp.is_Rational else decompose_power(expr)
class Factors:
"""Efficient representation of ``f_1*f_2*...*f_n``."""
__slots__ = ('factors', 'gens')
def __init__(self, factors=None): # Factors
"""Initialize Factors from dict or expr.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x
>>> from sympy import I
>>> e = 2*x**3
>>> Factors(e)
Factors({2: 1, x: 3})
>>> Factors(e.as_powers_dict())
Factors({2: 1, x: 3})
>>> f = _
>>> f.factors # underlying dictionary
{2: 1, x: 3}
>>> f.gens # base of each factor
frozenset({2, x})
>>> Factors(0)
Factors({0: 1})
>>> Factors(I)
Factors({I: 1})
Notes
=====
Although a dictionary can be passed, only minimal checking is
performed: powers of -1 and I are made canonical.
"""
if isinstance(factors, (SYMPY_INTS, float)):
factors = S(factors)
if isinstance(factors, Factors):
factors = factors.factors.copy()
elif factors in (None, S.One):
factors = {}
elif factors is S.Zero or factors == 0:
factors = {S.Zero: S.One}
elif isinstance(factors, Number):
n = factors
factors = {}
if n < 0:
factors[S.NegativeOne] = S.One
n = -n
if n is not S.One:
if n.is_Float or n.is_Integer or n is S.Infinity:
factors[n] = S.One
elif n.is_Rational:
# since we're processing Numbers, the denominator is
# stored with a negative exponent; all other factors
# are left .
if n.p != 1:
factors[Integer(n.p)] = S.One
factors[Integer(n.q)] = S.NegativeOne
else:
raise ValueError('Expected Float|Rational|Integer, not %s' % n)
elif isinstance(factors, Basic) and not factors.args:
factors = {factors: S.One}
elif isinstance(factors, Expr):
c, nc = factors.args_cnc()
i = c.count(I)
for _ in range(i):
c.remove(I)
factors = dict(Mul._from_args(c).as_powers_dict())
# Handle all rational Coefficients
for f in list(factors.keys()):
if isinstance(f, Rational) and not isinstance(f, Integer):
p, q = Integer(f.p), Integer(f.q)
factors[p] = (factors[p] if p in factors else S.Zero) + factors[f]
factors[q] = (factors[q] if q in factors else S.Zero) - factors[f]
factors.pop(f)
if i:
factors[I] = factors.get(I, S.Zero) + i
if nc:
factors[Mul(*nc, evaluate=False)] = S.One
else:
factors = factors.copy() # /!\ should be dict-like
# tidy up -/+1 and I exponents if Rational
handle = [k for k in factors if k is I or k in (-1, 1)]
if handle:
i1 = S.One
for k in handle:
if not _isnumber(factors[k]):
continue
i1 *= k**factors.pop(k)
if i1 is not S.One:
for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e
if a is S.NegativeOne:
factors[a] = S.One
elif a is I:
factors[I] = S.One
elif a.is_Pow:
factors[a.base] = factors.get(a.base, S.Zero) + a.exp
elif a == 1:
factors[a] = S.One
elif a == -1:
factors[-a] = S.One
factors[S.NegativeOne] = S.One
else:
raise ValueError('unexpected factor in i1: %s' % a)
self.factors = factors
keys = getattr(factors, 'keys', None)
if keys is None:
raise TypeError('expecting Expr or dictionary')
self.gens = frozenset(keys())
def __hash__(self): # Factors
keys = tuple(ordered(self.factors.keys()))
values = [self.factors[k] for k in keys]
return hash((keys, values))
def __repr__(self): # Factors
return "Factors({%s})" % ', '.join(
['%s: %s' % (k, v) for k, v in ordered(self.factors.items())])
@property
def is_zero(self): # Factors
"""
>>> from sympy.core.exprtools import Factors
>>> Factors(0).is_zero
True
"""
f = self.factors
return len(f) == 1 and S.Zero in f
@property
def is_one(self): # Factors
"""
>>> from sympy.core.exprtools import Factors
>>> Factors(1).is_one
True
"""
return not self.factors
def as_expr(self): # Factors
"""Return the underlying expression.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y
>>> Factors((x*y**2).as_powers_dict()).as_expr()
x*y**2
"""
args = []
for factor, exp in self.factors.items():
if exp != 1:
if isinstance(exp, Integer):
b, e = factor.as_base_exp()
e = _keep_coeff(exp, e)
args.append(b**e)
else:
args.append(factor**exp)
else:
args.append(factor)
return Mul(*args)
def mul(self, other): # Factors
"""Return Factors of ``self * other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.mul(b)
Factors({x: 2, y: 3, z: -1})
>>> a*b
Factors({x: 2, y: 3, z: -1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if any(f.is_zero for f in (self, other)):
return Factors(S.Zero)
factors = dict(self.factors)
for factor, exp in other.factors.items():
if factor in factors:
exp = factors[factor] + exp
if not exp:
del factors[factor]
continue
factors[factor] = exp
return Factors(factors)
def normal(self, other):
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
The only differences between this and method ``div`` is that this
is 1) optimized for the case when there are few factors in common and
2) this does not raise an error if ``other`` is zero.
See Also
========
div
"""
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
return (Factors(), Factors(S.Zero))
if self.is_zero:
return (Factors(S.Zero), Factors())
self_factors = dict(self.factors)
other_factors = dict(other.factors)
for factor, self_exp in self.factors.items():
try:
other_exp = other.factors[factor]
except KeyError:
continue
exp = self_exp - other_exp
if not exp:
del self_factors[factor]
del other_factors[factor]
elif _isnumber(exp):
if exp > 0:
self_factors[factor] = exp
del other_factors[factor]
else:
del self_factors[factor]
other_factors[factor] = -exp
else:
r = self_exp.extract_additively(other_exp)
if r is not None:
if r:
self_factors[factor] = r
del other_factors[factor]
else: # should be handled already
del self_factors[factor]
del other_factors[factor]
else:
sc, sa = self_exp.as_coeff_Add()
if sc:
oc, oa = other_exp.as_coeff_Add()
diff = sc - oc
if diff > 0:
self_factors[factor] -= oc
other_exp = oa
elif diff < 0:
self_factors[factor] -= sc
other_factors[factor] -= sc
other_exp = oa - diff
else:
self_factors[factor] = sa
other_exp = oa
if other_exp:
other_factors[factor] = other_exp
else:
del other_factors[factor]
return Factors(self_factors), Factors(other_factors)
def div(self, other): # Factors
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
This is optimized for the case when there are many factors in common.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> from sympy import S
>>> a = Factors((x*y**2).as_powers_dict())
>>> a.div(a)
(Factors({}), Factors({}))
>>> a.div(x*z)
(Factors({y: 2}), Factors({z: 1}))
The ``/`` operator only gives ``quo``:
>>> a/x
Factors({y: 2})
Factors treats its factors as though they are all in the numerator, so
if you violate this assumption the results will be correct but will
not strictly correspond to the numerator and denominator of the ratio:
>>> a.div(x/z)
(Factors({y: 2}), Factors({z: -1}))
Factors is also naive about bases: it does not attempt any denesting
of Rational-base terms, for example the following does not become
2**(2*x)/2.
>>> Factors(2**(2*x + 2)).div(S(8))
(Factors({2: 2*x + 2}), Factors({8: 1}))
factor_terms can clean up such Rational-bases powers:
>>> from sympy import factor_terms
>>> n, d = Factors(2**(2*x + 2)).div(S(8))
>>> n.as_expr()/d.as_expr()
2**(2*x + 2)/8
>>> factor_terms(_)
2**(2*x)/2
"""
quo, rem = dict(self.factors), {}
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
raise ZeroDivisionError
if self.is_zero:
return (Factors(S.Zero), Factors())
for factor, exp in other.factors.items():
if factor in quo:
d = quo[factor] - exp
if _isnumber(d):
if d <= 0:
del quo[factor]
if d >= 0:
if d:
quo[factor] = d
continue
exp = -d
else:
r = quo[factor].extract_additively(exp)
if r is not None:
if r:
quo[factor] = r
else: # should be handled already
del quo[factor]
else:
other_exp = exp
sc, sa = quo[factor].as_coeff_Add()
if sc:
oc, oa = other_exp.as_coeff_Add()
diff = sc - oc
if diff > 0:
quo[factor] -= oc
other_exp = oa
elif diff < 0:
quo[factor] -= sc
other_exp = oa - diff
else:
quo[factor] = sa
other_exp = oa
if other_exp:
rem[factor] = other_exp
else:
assert factor not in rem
continue
rem[factor] = exp
return Factors(quo), Factors(rem)
def quo(self, other): # Factors
"""Return numerator Factor of ``self / other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.quo(b) # same as a/b
Factors({y: 1})
"""
return self.div(other)[0]
def rem(self, other): # Factors
"""Return denominator Factors of ``self / other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.rem(b)
Factors({z: -1})
>>> a.rem(a)
Factors({})
"""
return self.div(other)[1]
def pow(self, other): # Factors
"""Return self raised to a non-negative integer power.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y
>>> a = Factors((x*y**2).as_powers_dict())
>>> a**2
Factors({x: 2, y: 4})
"""
if isinstance(other, Factors):
other = other.as_expr()
if other.is_Integer:
other = int(other)
if isinstance(other, SYMPY_INTS) and other >= 0:
factors = {}
if other:
for factor, exp in self.factors.items():
factors[factor] = exp*other
return Factors(factors)
else:
raise ValueError("expected non-negative integer, got %s" % other)
def gcd(self, other): # Factors
"""Return Factors of ``gcd(self, other)``. The keys are
the intersection of factors with the minimum exponent for
each factor.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.gcd(b)
Factors({x: 1, y: 1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
return Factors(self.factors)
factors = {}
for factor, exp in self.factors.items():
factor, exp = sympify(factor), sympify(exp)
if factor in other.factors:
lt = (exp - other.factors[factor]).is_negative
if lt == True:
factors[factor] = exp
elif lt == False:
factors[factor] = other.factors[factor]
return Factors(factors)
def lcm(self, other): # Factors
"""Return Factors of ``lcm(self, other)`` which are
the union of factors with the maximum exponent for
each factor.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.lcm(b)
Factors({x: 1, y: 2, z: -1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if any(f.is_zero for f in (self, other)):
return Factors(S.Zero)
factors = dict(self.factors)
for factor, exp in other.factors.items():
if factor in factors:
exp = max(exp, factors[factor])
factors[factor] = exp
return Factors(factors)
def __mul__(self, other): # Factors
return self.mul(other)
def __divmod__(self, other): # Factors
return self.div(other)
def __truediv__(self, other): # Factors
return self.quo(other)
def __mod__(self, other): # Factors
return self.rem(other)
def __pow__(self, other): # Factors
return self.pow(other)
def __eq__(self, other): # Factors
if not isinstance(other, Factors):
other = Factors(other)
return self.factors == other.factors
def __ne__(self, other): # Factors
return not self == other
class Term:
"""Efficient representation of ``coeff*(numer/denom)``. """
__slots__ = ('coeff', 'numer', 'denom')
def __init__(self, term, numer=None, denom=None): # Term
if numer is None and denom is None:
if not term.is_commutative:
raise NonCommutativeExpression(
'commutative expression expected')
coeff, factors = term.as_coeff_mul()
numer, denom = defaultdict(int), defaultdict(int)
for factor in factors:
base, exp = decompose_power(factor)
if base.is_Add:
cont, base = base.primitive()
coeff *= cont**exp
if exp > 0:
numer[base] += exp
else:
denom[base] += -exp
numer = Factors(numer)
denom = Factors(denom)
else:
coeff = term
if numer is None:
numer = Factors()
if denom is None:
denom = Factors()
self.coeff = coeff
self.numer = numer
self.denom = denom
def __hash__(self): # Term
return hash((self.coeff, self.numer, self.denom))
def __repr__(self): # Term
return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom)
def as_expr(self): # Term
return self.coeff*(self.numer.as_expr()/self.denom.as_expr())
def mul(self, other): # Term
coeff = self.coeff*other.coeff
numer = self.numer.mul(other.numer)
denom = self.denom.mul(other.denom)
numer, denom = numer.normal(denom)
return Term(coeff, numer, denom)
def inv(self): # Term
return Term(1/self.coeff, self.denom, self.numer)
def quo(self, other): # Term
return self.mul(other.inv())
def pow(self, other): # Term
if other < 0:
return self.inv().pow(-other)
else:
return Term(self.coeff ** other,
self.numer.pow(other),
self.denom.pow(other))
def gcd(self, other): # Term
return Term(self.coeff.gcd(other.coeff),
self.numer.gcd(other.numer),
self.denom.gcd(other.denom))
def lcm(self, other): # Term
return Term(self.coeff.lcm(other.coeff),
self.numer.lcm(other.numer),
self.denom.lcm(other.denom))
def __mul__(self, other): # Term
if isinstance(other, Term):
return self.mul(other)
else:
return NotImplemented
def __truediv__(self, other): # Term
if isinstance(other, Term):
return self.quo(other)
else:
return NotImplemented
def __pow__(self, other): # Term
if isinstance(other, SYMPY_INTS):
return self.pow(other)
else:
return NotImplemented
def __eq__(self, other): # Term
return (self.coeff == other.coeff and
self.numer == other.numer and
self.denom == other.denom)
def __ne__(self, other): # Term
return not self == other
def _gcd_terms(terms, isprimitive=False, fraction=True):
"""Helper function for :func:`gcd_terms`.
Parameters
==========
isprimitive : boolean, optional
If ``isprimitive`` is True then the call to primitive
for an Add will be skipped. This is useful when the
content has already been extrated.
fraction : boolean, optional
If ``fraction`` is True then the expression will appear over a common
denominator, the lcm of all term denominators.
"""
if isinstance(terms, Basic) and not isinstance(terms, Tuple):
terms = Add.make_args(terms)
terms = list(map(Term, [t for t in terms if t]))
# there is some simplification that may happen if we leave this
# here rather than duplicate it before the mapping of Term onto
# the terms
if len(terms) == 0:
return S.Zero, S.Zero, S.One
if len(terms) == 1:
cont = terms[0].coeff
numer = terms[0].numer.as_expr()
denom = terms[0].denom.as_expr()
else:
cont = terms[0]
for term in terms[1:]:
cont = cont.gcd(term)
for i, term in enumerate(terms):
terms[i] = term.quo(cont)
if fraction:
denom = terms[0].denom
for term in terms[1:]:
denom = denom.lcm(term.denom)
numers = []
for term in terms:
numer = term.numer.mul(denom.quo(term.denom))
numers.append(term.coeff*numer.as_expr())
else:
numers = [t.as_expr() for t in terms]
denom = Term(S.One).numer
cont = cont.as_expr()
numer = Add(*numers)
denom = denom.as_expr()
if not isprimitive and numer.is_Add:
_cont, numer = numer.primitive()
cont *= _cont
return cont, numer, denom
def gcd_terms(terms, isprimitive=False, clear=True, fraction=True):
"""Compute the GCD of ``terms`` and put them together.
Parameters
==========
terms : Expr
Can be an expression or a non-Basic sequence of expressions
which will be handled as though they are terms from a sum.
isprimitive : bool, optional
If ``isprimitive`` is True the _gcd_terms will not run the primitive
method on the terms.
clear : bool, optional
It controls the removal of integers from the denominator of an Add
expression. When True (default), all numerical denominator will be cleared;
when False the denominators will be cleared only if all terms had numerical
denominators other than 1.
fraction : bool, optional
When True (default), will put the expression over a common
denominator.
Examples
========
>>> from sympy import gcd_terms
>>> from sympy.abc import x, y
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
y*(x + 1)*(x + y + 1)
>>> gcd_terms(x/2 + 1)
(x + 2)/2
>>> gcd_terms(x/2 + 1, clear=False)
x/2 + 1
>>> gcd_terms(x/2 + y/2, clear=False)
(x + y)/2
>>> gcd_terms(x/2 + 1/x)
(x**2 + 2)/(2*x)
>>> gcd_terms(x/2 + 1/x, fraction=False)
(x + 2/x)/2
>>> gcd_terms(x/2 + 1/x, fraction=False, clear=False)
x/2 + 1/x
>>> gcd_terms(x/2/y + 1/x/y)
(x**2 + 2)/(2*x*y)
>>> gcd_terms(x/2/y + 1/x/y, clear=False)
(x**2/2 + 1)/(x*y)
>>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False)
(x/2 + 1/x)/y
The ``clear`` flag was ignored in this case because the returned
expression was a rational expression, not a simple sum.
See Also
========
factor_terms, sympy.polys.polytools.terms_gcd
"""
def mask(terms):
"""replace nc portions of each term with a unique Dummy symbols
and return the replacements to restore them"""
args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms]
reps = []
for i, (c, nc) in enumerate(args):
if nc:
nc = Mul(*nc)
d = Dummy()
reps.append((d, nc))
c.append(d)
args[i] = Mul(*c)
else:
args[i] = c
return args, dict(reps)
isadd = isinstance(terms, Add)
addlike = isadd or not isinstance(terms, Basic) and \
is_sequence(terms, include=set) and \
not isinstance(terms, Dict)
if addlike:
if isadd: # i.e. an Add
terms = list(terms.args)
else:
terms = sympify(terms)
terms, reps = mask(terms)
cont, numer, denom = _gcd_terms(terms, isprimitive, fraction)
numer = numer.xreplace(reps)
coeff, factors = cont.as_coeff_Mul()
if not clear:
c, _coeff = coeff.as_coeff_Mul()
if not c.is_Integer and not clear and numer.is_Add:
n, d = c.as_numer_denom()
_numer = numer/d
if any(a.as_coeff_Mul()[0].is_Integer
for a in _numer.args):
numer = _numer
coeff = n*_coeff
return _keep_coeff(coeff, factors*numer/denom, clear=clear)
if not isinstance(terms, Basic):
return terms
if terms.is_Atom:
return terms
if terms.is_Mul:
c, args = terms.as_coeff_mul()
return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction)
for i in args]), clear=clear)
def handle(a):
# don't treat internal args like terms of an Add
if not isinstance(a, Expr):
if isinstance(a, Basic):
if not a.args:
return a
return a.func(*[handle(i) for i in a.args])
return type(a)([handle(i) for i in a])
return gcd_terms(a, isprimitive, clear, fraction)
if isinstance(terms, Dict):
return Dict(*[(k, handle(v)) for k, v in terms.args])
return terms.func(*[handle(i) for i in terms.args])
def _factor_sum_int(expr, **kwargs):
"""Return Sum or Integral object with factors that are not
in the wrt variables removed. In cases where there are additive
terms in the function of the object that are independent, the
object will be separated into two objects.
Examples
========
>>> from sympy import Sum, factor_terms
>>> from sympy.abc import x, y
>>> factor_terms(Sum(x + y, (x, 1, 3)))
y*Sum(1, (x, 1, 3)) + Sum(x, (x, 1, 3))
>>> factor_terms(Sum(x*y, (x, 1, 3)))
y*Sum(x, (x, 1, 3))
Notes
=====
If a function in the summand or integrand is replaced
with a symbol, then this simplification should not be
done or else an incorrect result will be obtained when
the symbol is replaced with an expression that depends
on the variables of summation/integration:
>>> eq = Sum(y, (x, 1, 3))
>>> factor_terms(eq).subs(y, x).doit()
3*x
>>> eq.subs(y, x).doit()
6
"""
result = expr.function
if result == 0:
return S.Zero
limits = expr.limits
# get the wrt variables
wrt = {i.args[0] for i in limits}
# factor out any common terms that are independent of wrt
f = factor_terms(result, **kwargs)
i, d = f.as_independent(*wrt)
if isinstance(f, Add):
return i * expr.func(1, *limits) + expr.func(d, *limits)
else:
return i * expr.func(d, *limits)
def factor_terms(expr, radical=False, clear=False, fraction=False, sign=True):
"""Remove common factors from terms in all arguments without
changing the underlying structure of the expr. No expansion or
simplification (and no processing of non-commutatives) is performed.
Parameters
==========
radical: bool, optional
If radical=True then a radical common to all terms will be factored
out of any Add sub-expressions of the expr.
clear : bool, optional
If clear=False (default) then coefficients will not be separated
from a single Add if they can be distributed to leave one or more
terms with integer coefficients.
fraction : bool, optional
If fraction=True (default is False) then a common denominator will be
constructed for the expression.
sign : bool, optional
If sign=True (default) then even if the only factor in common is a -1,
it will be factored out of the expression.
Examples
========
>>> from sympy import factor_terms, Symbol
>>> from sympy.abc import x, y
>>> factor_terms(x + x*(2 + 4*y)**3)
x*(8*(2*y + 1)**3 + 1)
>>> A = Symbol('A', commutative=False)
>>> factor_terms(x*A + x*A + x*y*A)
x*(y*A + 2*A)
When ``clear`` is False, a rational will only be factored out of an
Add expression if all terms of the Add have coefficients that are
fractions:
>>> factor_terms(x/2 + 1, clear=False)
x/2 + 1
>>> factor_terms(x/2 + 1, clear=True)
(x + 2)/2
If a -1 is all that can be factored out, to *not* factor it out, the
flag ``sign`` must be False:
>>> factor_terms(-x - y)
-(x + y)
>>> factor_terms(-x - y, sign=False)
-x - y
>>> factor_terms(-2*x - 2*y, sign=False)
-2*(x + y)
See Also
========
gcd_terms, sympy.polys.polytools.terms_gcd
"""
def do(expr):
from sympy.concrete.summations import Sum
from sympy.integrals.integrals import Integral
is_iterable = iterable(expr)
if not isinstance(expr, Basic) or expr.is_Atom:
if is_iterable:
return type(expr)([do(i) for i in expr])
return expr
if expr.is_Pow or expr.is_Function or \
is_iterable or not hasattr(expr, 'args_cnc'):
args = expr.args
newargs = tuple([do(i) for i in args])
if newargs == args:
return expr
return expr.func(*newargs)
if isinstance(expr, (Sum, Integral)):
return _factor_sum_int(expr,
radical=radical, clear=clear,
fraction=fraction, sign=sign)
cont, p = expr.as_content_primitive(radical=radical, clear=clear)
if p.is_Add:
list_args = [do(a) for a in Add.make_args(p)]
# get a common negative (if there) which gcd_terms does not remove
if not any(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is None
for a in list_args):
cont = -cont
list_args = [-a for a in list_args]
# watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2)
special = {}
for i, a in enumerate(list_args):
b, e = a.as_base_exp()
if e.is_Mul and e != Mul(*e.args):
list_args[i] = Dummy()
special[list_args[i]] = a
# rebuild p not worrying about the order which gcd_terms will fix
p = Add._from_args(list_args)
p = gcd_terms(p,
isprimitive=True,
clear=clear,
fraction=fraction).xreplace(special)
elif p.args:
p = p.func(
*[do(a) for a in p.args])
rv = _keep_coeff(cont, p, clear=clear, sign=sign)
return rv
expr = sympify(expr)
return do(expr)
def _mask_nc(eq, name=None):
"""
Return ``eq`` with non-commutative objects replaced with Dummy
symbols. A dictionary that can be used to restore the original
values is returned: if it is None, the expression is noncommutative
and cannot be made commutative. The third value returned is a list
of any non-commutative symbols that appear in the returned equation.
Explanation
===========
All non-commutative objects other than Symbols are replaced with
a non-commutative Symbol. Identical objects will be identified
by identical symbols.
If there is only 1 non-commutative object in an expression it will
be replaced with a commutative symbol. Otherwise, the non-commutative
entities are retained and the calling routine should handle
replacements in this case since some care must be taken to keep
track of the ordering of symbols when they occur within Muls.
Parameters
==========
name : str
``name``, if given, is the name that will be used with numbered Dummy
variables that will replace the non-commutative objects and is mainly
used for doctesting purposes.
Examples
========
>>> from sympy.physics.secondquant import Commutator, NO, F, Fd
>>> from sympy import symbols
>>> from sympy.core.exprtools import _mask_nc
>>> from sympy.abc import x, y
>>> A, B, C = symbols('A,B,C', commutative=False)
One nc-symbol:
>>> _mask_nc(A**2 - x**2, 'd')
(_d0**2 - x**2, {_d0: A}, [])
Multiple nc-symbols:
>>> _mask_nc(A**2 - B**2, 'd')
(A**2 - B**2, {}, [A, B])
An nc-object with nc-symbols but no others outside of it:
>>> _mask_nc(1 + x*Commutator(A, B), 'd')
(_d0*x + 1, {_d0: Commutator(A, B)}, [])
>>> _mask_nc(NO(Fd(x)*F(y)), 'd')
(_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, [])
Multiple nc-objects:
>>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B)
>>> _mask_nc(eq, 'd')
(x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1])
Multiple nc-objects and nc-symbols:
>>> eq = A*Commutator(A, B) + B*Commutator(A, C)
>>> _mask_nc(eq, 'd')
(A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B])
"""
name = name or 'mask'
# Make Dummy() append sequential numbers to the name
def numbered_names():
i = 0
while True:
yield name + str(i)
i += 1
names = numbered_names()
def Dummy(*args, **kwargs):
from .symbol import Dummy
return Dummy(next(names), *args, **kwargs)
expr = eq
if expr.is_commutative:
return eq, {}, []
# identify nc-objects; symbols and other
rep = []
nc_obj = set()
nc_syms = set()
pot = preorder_traversal(expr, keys=default_sort_key)
for i, a in enumerate(pot):
if any(a == r[0] for r in rep):
pot.skip()
elif not a.is_commutative:
if a.is_symbol:
nc_syms.add(a)
pot.skip()
elif not (a.is_Add or a.is_Mul or a.is_Pow):
nc_obj.add(a)
pot.skip()
# If there is only one nc symbol or object, it can be factored regularly
# but polys is going to complain, so replace it with a Dummy.
if len(nc_obj) == 1 and not nc_syms:
rep.append((nc_obj.pop(), Dummy()))
elif len(nc_syms) == 1 and not nc_obj:
rep.append((nc_syms.pop(), Dummy()))
# Any remaining nc-objects will be replaced with an nc-Dummy and
# identified as an nc-Symbol to watch out for
nc_obj = sorted(nc_obj, key=default_sort_key)
for n in nc_obj:
nc = Dummy(commutative=False)
rep.append((n, nc))
nc_syms.add(nc)
expr = expr.subs(rep)
nc_syms = list(nc_syms)
nc_syms.sort(key=default_sort_key)
return expr, {v: k for k, v in rep}, nc_syms
def factor_nc(expr):
"""Return the factored form of ``expr`` while handling non-commutative
expressions.
Examples
========
>>> from sympy import factor_nc, Symbol
>>> from sympy.abc import x
>>> A = Symbol('A', commutative=False)
>>> B = Symbol('B', commutative=False)
>>> factor_nc((x**2 + 2*A*x + A**2).expand())
(x + A)**2
>>> factor_nc(((x + A)*(x + B)).expand())
(x + A)*(x + B)
"""
expr = sympify(expr)
if not isinstance(expr, Expr) or not expr.args:
return expr
if not expr.is_Add:
return expr.func(*[factor_nc(a) for a in expr.args])
expr = expr.func(*[expand_power_exp(i) for i in expr.args])
from sympy.polys.polytools import gcd, factor
expr, rep, nc_symbols = _mask_nc(expr)
if rep:
return factor(expr).subs(rep)
else:
args = [a.args_cnc() for a in Add.make_args(expr)]
c = g = l = r = S.One
hit = False
# find any commutative gcd term
for i, a in enumerate(args):
if i == 0:
c = Mul._from_args(a[0])
elif a[0]:
c = gcd(c, Mul._from_args(a[0]))
else:
c = S.One
if c is not S.One:
hit = True
c, g = c.as_coeff_Mul()
if g is not S.One:
for i, (cc, _) in enumerate(args):
cc = list(Mul.make_args(Mul._from_args(list(cc))/g))
args[i][0] = cc
for i, (cc, _) in enumerate(args):
if cc:
cc[0] = cc[0]/c
else:
cc = [1/c]
args[i][0] = cc
# find any noncommutative common prefix
for i, a in enumerate(args):
if i == 0:
n = a[1][:]
else:
n = common_prefix(n, a[1])
if not n:
# is there a power that can be extracted?
if not args[0][1]:
break
b, e = args[0][1][0].as_base_exp()
ok = False
if e.is_Integer:
for t in args:
if not t[1]:
break
bt, et = t[1][0].as_base_exp()
if et.is_Integer and bt == b:
e = min(e, et)
else:
break
else:
ok = hit = True
l = b**e
il = b**-e
for _ in args:
_[1][0] = il*_[1][0]
break
if not ok:
break
else:
hit = True
lenn = len(n)
l = Mul(*n)
for _ in args:
_[1] = _[1][lenn:]
# find any noncommutative common suffix
for i, a in enumerate(args):
if i == 0:
n = a[1][:]
else:
n = common_suffix(n, a[1])
if not n:
# is there a power that can be extracted?
if not args[0][1]:
break
b, e = args[0][1][-1].as_base_exp()
ok = False
if e.is_Integer:
for t in args:
if not t[1]:
break
bt, et = t[1][-1].as_base_exp()
if et.is_Integer and bt == b:
e = min(e, et)
else:
break
else:
ok = hit = True
r = b**e
il = b**-e
for _ in args:
_[1][-1] = _[1][-1]*il
break
if not ok:
break
else:
hit = True
lenn = len(n)
r = Mul(*n)
for _ in args:
_[1] = _[1][:len(_[1]) - lenn]
if hit:
mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args])
else:
mid = expr
from sympy.simplify.powsimp import powsimp
# sort the symbols so the Dummys would appear in the same
# order as the original symbols, otherwise you may introduce
# a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2
# and the former factors into two terms, (A - B)*(A + B) while the
# latter factors into 3 terms, (-1)*(x - y)*(x + y)
rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)]
unrep1 = [(v, k) for k, v in rep1]
unrep1.reverse()
new_mid, r2, _ = _mask_nc(mid.subs(rep1))
new_mid = powsimp(factor(new_mid))
new_mid = new_mid.subs(r2).subs(unrep1)
if new_mid.is_Pow:
return _keep_coeff(c, g*l*new_mid*r)
if new_mid.is_Mul:
def _pemexpand(expr):
"Expand with the minimal set of hints necessary to check the result."
return expr.expand(deep=True, mul=True, power_exp=True,
power_base=False, basic=False, multinomial=True, log=False)
# XXX TODO there should be a way to inspect what order the terms
# must be in and just select the plausible ordering without
# checking permutations
cfac = []
ncfac = []
for f in new_mid.args:
if f.is_commutative:
cfac.append(f)
else:
b, e = f.as_base_exp()
if e.is_Integer:
ncfac.extend([b]*e)
else:
ncfac.append(f)
pre_mid = g*Mul(*cfac)*l
target = _pemexpand(expr/c)
for s in variations(ncfac, len(ncfac)):
ok = pre_mid*Mul(*s)*r
if _pemexpand(ok) == target:
return _keep_coeff(c, ok)
# mid was an Add that didn't factor successfully
return _keep_coeff(c, g*l*mid*r)
|
04d136db10c476e327cc5cfb6dcbb43d3ff12171da331a1dcd0f3952844809dc | """
This module contains the machinery handling assumptions.
Do also consider the guide :ref:`assumptions-guide`.
All symbolic objects have assumption attributes that can be accessed via
``.is_<assumption name>`` attribute.
Assumptions determine certain properties of symbolic objects and can
have 3 possible values: ``True``, ``False``, ``None``. ``True`` is returned if the
object has the property and ``False`` is returned if it does not or cannot
(i.e. does not make sense):
>>> from sympy import I
>>> I.is_algebraic
True
>>> I.is_real
False
>>> I.is_prime
False
When the property cannot be determined (or when a method is not
implemented) ``None`` will be returned. For example, a generic symbol, ``x``,
may or may not be positive so a value of ``None`` is returned for ``x.is_positive``.
By default, all symbolic values are in the largest set in the given context
without specifying the property. For example, a symbol that has a property
being integer, is also real, complex, etc.
Here follows a list of possible assumption names:
.. glossary::
commutative
object commutes with any other object with
respect to multiplication operation. See [12]_.
complex
object can have only values from the set
of complex numbers. See [13]_.
imaginary
object value is a number that can be written as a real
number multiplied by the imaginary unit ``I``. See
[3]_. Please note that ``0`` is not considered to be an
imaginary number, see
`issue #7649 <https://github.com/sympy/sympy/issues/7649>`_.
real
object can have only values from the set
of real numbers.
extended_real
object can have only values from the set
of real numbers, ``oo`` and ``-oo``.
integer
object can have only values from the set
of integers.
odd
even
object can have only values from the set of
odd (even) integers [2]_.
prime
object is a natural number greater than 1 that has
no positive divisors other than 1 and itself. See [6]_.
composite
object is a positive integer that has at least one positive
divisor other than 1 or the number itself. See [4]_.
zero
object has the value of 0.
nonzero
object is a real number that is not zero.
rational
object can have only values from the set
of rationals.
algebraic
object can have only values from the set
of algebraic numbers [11]_.
transcendental
object can have only values from the set
of transcendental numbers [10]_.
irrational
object value cannot be represented exactly by :class:`~.Rational`, see [5]_.
finite
infinite
object absolute value is bounded (arbitrarily large).
See [7]_, [8]_, [9]_.
negative
nonnegative
object can have only negative (nonnegative)
values [1]_.
positive
nonpositive
object can have only positive (nonpositive) values.
extended_negative
extended_nonnegative
extended_positive
extended_nonpositive
extended_nonzero
as without the extended part, but also including infinity with
corresponding sign, e.g., extended_positive includes ``oo``
hermitian
antihermitian
object belongs to the field of Hermitian
(antihermitian) operators.
Examples
========
>>> from sympy import Symbol
>>> x = Symbol('x', real=True); x
x
>>> x.is_real
True
>>> x.is_complex
True
See Also
========
.. seealso::
:py:class:`sympy.core.numbers.ImaginaryUnit`
:py:class:`sympy.core.numbers.Zero`
:py:class:`sympy.core.numbers.One`
:py:class:`sympy.core.numbers.Infinity`
:py:class:`sympy.core.numbers.NegativeInfinity`
:py:class:`sympy.core.numbers.ComplexInfinity`
Notes
=====
The fully-resolved assumptions for any SymPy expression
can be obtained as follows:
>>> from sympy.core.assumptions import assumptions
>>> x = Symbol('x',positive=True)
>>> assumptions(x + I)
{'commutative': True, 'complex': True, 'composite': False, 'even':
False, 'extended_negative': False, 'extended_nonnegative': False,
'extended_nonpositive': False, 'extended_nonzero': False,
'extended_positive': False, 'extended_real': False, 'finite': True,
'imaginary': False, 'infinite': False, 'integer': False, 'irrational':
False, 'negative': False, 'noninteger': False, 'nonnegative': False,
'nonpositive': False, 'nonzero': False, 'odd': False, 'positive':
False, 'prime': False, 'rational': False, 'real': False, 'zero':
False}
Developers Notes
================
The current (and possibly incomplete) values are stored
in the ``obj._assumptions dictionary``; queries to getter methods
(with property decorators) or attributes of objects/classes
will return values and update the dictionary.
>>> eq = x**2 + I
>>> eq._assumptions
{}
>>> eq.is_finite
True
>>> eq._assumptions
{'finite': True, 'infinite': False}
For a :class:`~.Symbol`, there are two locations for assumptions that may
be of interest. The ``assumptions0`` attribute gives the full set of
assumptions derived from a given set of initial assumptions. The
latter assumptions are stored as ``Symbol._assumptions.generator``
>>> Symbol('x', prime=True, even=True)._assumptions.generator
{'even': True, 'prime': True}
The ``generator`` is not necessarily canonical nor is it filtered
in any way: it records the assumptions used to instantiate a Symbol
and (for storage purposes) represents a more compact representation
of the assumptions needed to recreate the full set in
``Symbol.assumptions0``.
References
==========
.. [1] https://en.wikipedia.org/wiki/Negative_number
.. [2] https://en.wikipedia.org/wiki/Parity_%28mathematics%29
.. [3] https://en.wikipedia.org/wiki/Imaginary_number
.. [4] https://en.wikipedia.org/wiki/Composite_number
.. [5] https://en.wikipedia.org/wiki/Irrational_number
.. [6] https://en.wikipedia.org/wiki/Prime_number
.. [7] https://en.wikipedia.org/wiki/Finite
.. [8] https://docs.python.org/3/library/math.html#math.isfinite
.. [9] http://docs.scipy.org/doc/numpy/reference/generated/numpy.isfinite.html
.. [10] https://en.wikipedia.org/wiki/Transcendental_number
.. [11] https://en.wikipedia.org/wiki/Algebraic_number
.. [12] https://en.wikipedia.org/wiki/Commutative_property
.. [13] https://en.wikipedia.org/wiki/Complex_number
"""
from .facts import FactRules, FactKB
from .core import BasicMeta
from .sympify import sympify
from sympy.core.random import shuffle
from sympy.core.assumptions_generated import generated_assumptions as _assumptions
def _load_pre_generated_assumption_rules():
""" Load the assumption rules from pre-generated data
To update the pre-generated data, see :method::`_generate_assumption_rules`
"""
_assume_rules=FactRules._from_python(_assumptions)
return _assume_rules
def _generate_assumption_rules():
""" Generate the default assumption rules
This method should only be called to update the pre-generated
assumption rules.
To update the pre-generated assumptions run: bin/ask_update.py
"""
_assume_rules = FactRules([
'integer -> rational',
'rational -> real',
'rational -> algebraic',
'algebraic -> complex',
'transcendental == complex & !algebraic',
'real -> hermitian',
'imaginary -> complex',
'imaginary -> antihermitian',
'extended_real -> commutative',
'complex -> commutative',
'complex -> finite',
'odd == integer & !even',
'even == integer & !odd',
'real -> complex',
'extended_real -> real | infinite',
'real == extended_real & finite',
'extended_real == extended_negative | zero | extended_positive',
'extended_negative == extended_nonpositive & extended_nonzero',
'extended_positive == extended_nonnegative & extended_nonzero',
'extended_nonpositive == extended_real & !extended_positive',
'extended_nonnegative == extended_real & !extended_negative',
'real == negative | zero | positive',
'negative == nonpositive & nonzero',
'positive == nonnegative & nonzero',
'nonpositive == real & !positive',
'nonnegative == real & !negative',
'positive == extended_positive & finite',
'negative == extended_negative & finite',
'nonpositive == extended_nonpositive & finite',
'nonnegative == extended_nonnegative & finite',
'nonzero == extended_nonzero & finite',
'zero -> even & finite',
'zero == extended_nonnegative & extended_nonpositive',
'zero == nonnegative & nonpositive',
'nonzero -> real',
'prime -> integer & positive',
'composite -> integer & positive & !prime',
'!composite -> !positive | !even | prime',
'irrational == real & !rational',
'imaginary -> !extended_real',
'infinite == !finite',
'noninteger == extended_real & !integer',
'extended_nonzero == extended_real & !zero',
])
return _assume_rules
#_assume_rules = _load_pre_generated_assumption_rules()
_assume_rules =_generate_assumption_rules()
_assume_defined = _assume_rules.defined_facts.copy()
_assume_defined.add('polar')
_assume_defined = frozenset(_assume_defined)
def assumptions(expr, _check=None):
"""return the T/F assumptions of ``expr``"""
n = sympify(expr)
if n.is_Symbol:
rv = n.assumptions0 # are any important ones missing?
if _check is not None:
rv = {k: rv[k] for k in set(rv) & set(_check)}
return rv
rv = {}
for k in _assume_defined if _check is None else _check:
v = getattr(n, 'is_{}'.format(k))
if v is not None:
rv[k] = v
return rv
def common_assumptions(exprs, check=None):
"""return those assumptions which have the same True or False
value for all the given expressions.
Examples
========
>>> from sympy.core import common_assumptions
>>> from sympy import oo, pi, sqrt
>>> common_assumptions([-4, 0, sqrt(2), 2, pi, oo])
{'commutative': True, 'composite': False,
'extended_real': True, 'imaginary': False, 'odd': False}
By default, all assumptions are tested; pass an iterable of the
assumptions to limit those that are reported:
>>> common_assumptions([0, 1, 2], ['positive', 'integer'])
{'integer': True}
"""
check = _assume_defined if check is None else set(check)
if not check or not exprs:
return {}
# get all assumptions for each
assume = [assumptions(i, _check=check) for i in sympify(exprs)]
# focus on those of interest that are True
for i, e in enumerate(assume):
assume[i] = {k: e[k] for k in set(e) & check}
# what assumptions are in common?
common = set.intersection(*[set(i) for i in assume])
# which ones hold the same value
a = assume[0]
return {k: a[k] for k in common if all(a[k] == b[k]
for b in assume)}
def failing_assumptions(expr, **assumptions):
"""
Return a dictionary containing assumptions with values not
matching those of the passed assumptions.
Examples
========
>>> from sympy import failing_assumptions, Symbol
>>> x = Symbol('x', positive=True)
>>> y = Symbol('y')
>>> failing_assumptions(6*x + y, positive=True)
{'positive': None}
>>> failing_assumptions(x**2 - 1, positive=True)
{'positive': None}
If *expr* satisfies all of the assumptions, an empty dictionary is returned.
>>> failing_assumptions(x**2, positive=True)
{}
"""
expr = sympify(expr)
failed = {}
for k in assumptions:
test = getattr(expr, 'is_%s' % k, None)
if test is not assumptions[k]:
failed[k] = test
return failed # {} or {assumption: value != desired}
def check_assumptions(expr, against=None, **assume):
"""
Checks whether assumptions of ``expr`` match the T/F assumptions
given (or possessed by ``against``). True is returned if all
assumptions match; False is returned if there is a mismatch and
the assumption in ``expr`` is not None; else None is returned.
Explanation
===========
*assume* is a dict of assumptions with True or False values
Examples
========
>>> from sympy import Symbol, pi, I, exp, check_assumptions
>>> check_assumptions(-5, integer=True)
True
>>> check_assumptions(pi, real=True, integer=False)
True
>>> check_assumptions(pi, negative=True)
False
>>> check_assumptions(exp(I*pi/7), real=False)
True
>>> x = Symbol('x', positive=True)
>>> check_assumptions(2*x + 1, positive=True)
True
>>> check_assumptions(-2*x - 5, positive=True)
False
To check assumptions of *expr* against another variable or expression,
pass the expression or variable as ``against``.
>>> check_assumptions(2*x + 1, x)
True
To see if a number matches the assumptions of an expression, pass
the number as the first argument, else its specific assumptions
may not have a non-None value in the expression:
>>> check_assumptions(x, 3)
>>> check_assumptions(3, x)
True
``None`` is returned if ``check_assumptions()`` could not conclude.
>>> check_assumptions(2*x - 1, x)
>>> z = Symbol('z')
>>> check_assumptions(z, real=True)
See Also
========
failing_assumptions
"""
expr = sympify(expr)
if against is not None:
if assume:
raise ValueError(
'Expecting `against` or `assume`, not both.')
assume = assumptions(against)
known = True
for k, v in assume.items():
if v is None:
continue
e = getattr(expr, 'is_' + k, None)
if e is None:
known = None
elif v != e:
return False
return known
class StdFactKB(FactKB):
"""A FactKB specialized for the built-in rules
This is the only kind of FactKB that Basic objects should use.
"""
def __init__(self, facts=None):
super().__init__(_assume_rules)
# save a copy of the facts dict
if not facts:
self._generator = {}
elif not isinstance(facts, FactKB):
self._generator = facts.copy()
else:
self._generator = facts.generator
if facts:
self.deduce_all_facts(facts)
def copy(self):
return self.__class__(self)
@property
def generator(self):
return self._generator.copy()
def as_property(fact):
"""Convert a fact name to the name of the corresponding property"""
return 'is_%s' % fact
def make_property(fact):
"""Create the automagic property corresponding to a fact."""
def getit(self):
try:
return self._assumptions[fact]
except KeyError:
if self._assumptions is self.default_assumptions:
self._assumptions = self.default_assumptions.copy()
return _ask(fact, self)
getit.func_name = as_property(fact)
return property(getit)
def _ask(fact, obj):
"""
Find the truth value for a property of an object.
This function is called when a request is made to see what a fact
value is.
For this we use several techniques:
First, the fact-evaluation function is tried, if it exists (for
example _eval_is_integer). Then we try related facts. For example
rational --> integer
another example is joined rule:
integer & !odd --> even
so in the latter case if we are looking at what 'even' value is,
'integer' and 'odd' facts will be asked.
In all cases, when we settle on some fact value, its implications are
deduced, and the result is cached in ._assumptions.
"""
# FactKB which is dict-like and maps facts to their known values:
assumptions = obj._assumptions
# A dict that maps facts to their handlers:
handler_map = obj._prop_handler
# This is our queue of facts to check:
facts_to_check = [fact]
facts_queued = {fact}
# Loop over the queue as it extends
for fact_i in facts_to_check:
# If fact_i has already been determined then we don't need to rerun the
# handler. There is a potential race condition for multithreaded code
# though because it's possible that fact_i was checked in another
# thread. The main logic of the loop below would potentially skip
# checking assumptions[fact] in this case so we check it once after the
# loop to be sure.
if fact_i in assumptions:
continue
# Now we call the associated handler for fact_i if it exists.
fact_i_value = None
handler_i = handler_map.get(fact_i)
if handler_i is not None:
fact_i_value = handler_i(obj)
# If we get a new value for fact_i then we should update our knowledge
# of fact_i as well as any related facts that can be inferred using the
# inference rules connecting the fact_i and any other fact values that
# are already known.
if fact_i_value is not None:
assumptions.deduce_all_facts(((fact_i, fact_i_value),))
# Usually if assumptions[fact] is now not None then that is because of
# the call to deduce_all_facts above. The handler for fact_i returned
# True or False and knowing fact_i (which is equal to fact in the first
# iteration) implies knowing a value for fact. It is also possible
# though that independent code e.g. called indirectly by the handler or
# called in another thread in a multithreaded context might have
# resulted in assumptions[fact] being set. Either way we return it.
fact_value = assumptions.get(fact)
if fact_value is not None:
return fact_value
# Extend the queue with other facts that might determine fact_i. Here
# we randomise the order of the facts that are checked. This should not
# lead to any non-determinism if all handlers are logically consistent
# with the inference rules for the facts. Non-deterministic assumptions
# queries can result from bugs in the handlers that are exposed by this
# call to shuffle. These are pushed to the back of the queue meaning
# that the inference graph is traversed in breadth-first order.
new_facts_to_check = list(_assume_rules.prereq[fact_i] - facts_queued)
shuffle(new_facts_to_check)
facts_to_check.extend(new_facts_to_check)
facts_queued.update(new_facts_to_check)
# The above loop should be able to handle everything fine in a
# single-threaded context but in multithreaded code it is possible that
# this thread skipped computing a particular fact that was computed in
# another thread (due to the continue). In that case it is possible that
# fact was inferred and is now stored in the assumptions dict but it wasn't
# checked for in the body of the loop. This is an obscure case but to make
# sure we catch it we check once here at the end of the loop.
if fact in assumptions:
return assumptions[fact]
# This query can not be answered. It's possible that e.g. another thread
# has already stored None for fact but assumptions._tell does not mind if
# we call _tell twice setting the same value. If this raises
# InconsistentAssumptions then it probably means that another thread
# attempted to compute this and got a value of True or False rather than
# None. In that case there must be a bug in at least one of the handlers.
# If the handlers are all deterministic and are consistent with the
# inference rules then the same value should be computed for fact in all
# threads.
assumptions._tell(fact, None)
return None
class ManagedProperties(BasicMeta):
"""Metaclass for classes with old-style assumptions"""
def __init__(cls, *args, **kws):
BasicMeta.__init__(cls, *args, **kws)
local_defs = {}
for k in _assume_defined:
attrname = as_property(k)
v = cls.__dict__.get(attrname, '')
if isinstance(v, (bool, int, type(None))):
if v is not None:
v = bool(v)
local_defs[k] = v
defs = {}
for base in reversed(cls.__bases__):
assumptions = getattr(base, '_explicit_class_assumptions', None)
if assumptions is not None:
defs.update(assumptions)
defs.update(local_defs)
cls._explicit_class_assumptions = defs
cls.default_assumptions = StdFactKB(defs)
cls._prop_handler = {}
for k in _assume_defined:
eval_is_meth = getattr(cls, '_eval_is_%s' % k, None)
if eval_is_meth is not None:
cls._prop_handler[k] = eval_is_meth
# Put definite results directly into the class dict, for speed
for k, v in cls.default_assumptions.items():
setattr(cls, as_property(k), v)
# protection e.g. for Integer.is_even=F <- (Rational.is_integer=F)
derived_from_bases = set()
for base in cls.__bases__:
default_assumptions = getattr(base, 'default_assumptions', None)
# is an assumption-aware class
if default_assumptions is not None:
derived_from_bases.update(default_assumptions)
for fact in derived_from_bases - set(cls.default_assumptions):
pname = as_property(fact)
if pname not in cls.__dict__:
setattr(cls, pname, make_property(fact))
# Finally, add any missing automagic property (e.g. for Basic)
for fact in _assume_defined:
pname = as_property(fact)
if not hasattr(cls, pname):
setattr(cls, pname, make_property(fact))
|
cf2d1dec2e823d4f2efa2c7d653d811fb50cc33a73edc88aa090e9c7290b6d70 | """
There are three types of functions implemented in SymPy:
1) defined functions (in the sense that they can be evaluated) like
exp or sin; they have a name and a body:
f = exp
2) undefined function which have a name but no body. Undefined
functions can be defined using a Function class as follows:
f = Function('f')
(the result will be a Function instance)
3) anonymous function (or lambda function) which have a body (defined
with dummy variables) but have no name:
f = Lambda(x, exp(x)*x)
f = Lambda((x, y), exp(x)*y)
The fourth type of functions are composites, like (sin + cos)(x); these work in
SymPy core, but are not yet part of SymPy.
Examples
========
>>> import sympy
>>> f = sympy.Function("f")
>>> from sympy.abc import x
>>> f(x)
f(x)
>>> print(sympy.srepr(f(x).func))
Function('f')
>>> f(x).args
(x,)
"""
from typing import Any, Dict as tDict, Optional, Set as tSet, Tuple as tTuple, Union as tUnion
from collections.abc import Iterable
from .add import Add
from .assumptions import ManagedProperties
from .basic import Basic, _atomic
from .cache import cacheit
from .containers import Tuple, Dict
from .decorators import _sympifyit
from .evalf import pure_complex
from .expr import Expr, AtomicExpr
from .logic import fuzzy_and, fuzzy_or, fuzzy_not, FuzzyBool
from .mul import Mul
from .numbers import Rational, Float, Integer
from .operations import LatticeOp
from .parameters import global_parameters
from .rules import Transform
from .singleton import S
from .sympify import sympify, _sympify
from .sorting import default_sort_key, ordered
from sympy.utilities.exceptions import (sympy_deprecation_warning,
SymPyDeprecationWarning, ignore_warnings)
from sympy.utilities.iterables import (has_dups, sift, iterable,
is_sequence, uniq, topological_sort)
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
from sympy.utilities.misc import as_int, filldedent, func_name
import mpmath
from mpmath.libmp.libmpf import prec_to_dps
import inspect
from collections import Counter
def _coeff_isneg(a):
"""Return True if the leading Number is negative.
Examples
========
>>> from sympy.core.function import _coeff_isneg
>>> from sympy import S, Symbol, oo, pi
>>> _coeff_isneg(-3*pi)
True
>>> _coeff_isneg(S(3))
False
>>> _coeff_isneg(-oo)
True
>>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1
False
For matrix expressions:
>>> from sympy import MatrixSymbol, sqrt
>>> A = MatrixSymbol("A", 3, 3)
>>> _coeff_isneg(-sqrt(2)*A)
True
>>> _coeff_isneg(sqrt(2)*A)
False
"""
if a.is_MatMul:
a = a.args[0]
if a.is_Mul:
a = a.args[0]
return a.is_Number and a.is_extended_negative
class PoleError(Exception):
pass
class ArgumentIndexError(ValueError):
def __str__(self):
return ("Invalid operation with argument number %s for Function %s" %
(self.args[1], self.args[0]))
class BadSignatureError(TypeError):
'''Raised when a Lambda is created with an invalid signature'''
pass
class BadArgumentsError(TypeError):
'''Raised when a Lambda is called with an incorrect number of arguments'''
pass
# Python 3 version that does not raise a Deprecation warning
def arity(cls):
"""Return the arity of the function if it is known, else None.
Explanation
===========
When default values are specified for some arguments, they are
optional and the arity is reported as a tuple of possible values.
Examples
========
>>> from sympy import arity, log
>>> arity(lambda x: x)
1
>>> arity(log)
(1, 2)
>>> arity(lambda *x: sum(x)) is None
True
"""
eval_ = getattr(cls, 'eval', cls)
parameters = inspect.signature(eval_).parameters.items()
if [p for _, p in parameters if p.kind == p.VAR_POSITIONAL]:
return
p_or_k = [p for _, p in parameters if p.kind == p.POSITIONAL_OR_KEYWORD]
# how many have no default and how many have a default value
no, yes = map(len, sift(p_or_k,
lambda p:p.default == p.empty, binary=True))
return no if not yes else tuple(range(no, no + yes + 1))
class FunctionClass(ManagedProperties):
"""
Base class for function classes. FunctionClass is a subclass of type.
Use Function('<function name>' [ , signature ]) to create
undefined function classes.
"""
_new = type.__new__
def __init__(cls, *args, **kwargs):
# honor kwarg value or class-defined value before using
# the number of arguments in the eval function (if present)
nargs = kwargs.pop('nargs', cls.__dict__.get('nargs', arity(cls)))
if nargs is None and 'nargs' not in cls.__dict__:
for supcls in cls.__mro__:
if hasattr(supcls, '_nargs'):
nargs = supcls._nargs
break
else:
continue
# Canonicalize nargs here; change to set in nargs.
if is_sequence(nargs):
if not nargs:
raise ValueError(filldedent('''
Incorrectly specified nargs as %s:
if there are no arguments, it should be
`nargs = 0`;
if there are any number of arguments,
it should be
`nargs = None`''' % str(nargs)))
nargs = tuple(ordered(set(nargs)))
elif nargs is not None:
nargs = (as_int(nargs),)
cls._nargs = nargs
# When __init__ is called from UndefinedFunction it is called with
# just one arg but when it is called from subclassing Function it is
# called with the usual (name, bases, namespace) type() signature.
if len(args) == 3:
namespace = args[2]
if 'eval' in namespace and not isinstance(namespace['eval'], classmethod):
raise TypeError("eval on Function subclasses should be a class method (defined with @classmethod)")
super().__init__(*args, **kwargs)
@property
def __signature__(self):
"""
Allow Python 3's inspect.signature to give a useful signature for
Function subclasses.
"""
# Python 3 only, but backports (like the one in IPython) still might
# call this.
try:
from inspect import signature
except ImportError:
return None
# TODO: Look at nargs
return signature(self.eval)
@property
def free_symbols(self):
return set()
@property
def xreplace(self):
# Function needs args so we define a property that returns
# a function that takes args...and then use that function
# to return the right value
return lambda rule, **_: rule.get(self, self)
@property
def nargs(self):
"""Return a set of the allowed number of arguments for the function.
Examples
========
>>> from sympy import Function
>>> f = Function('f')
If the function can take any number of arguments, the set of whole
numbers is returned:
>>> Function('f').nargs
Naturals0
If the function was initialized to accept one or more arguments, a
corresponding set will be returned:
>>> Function('f', nargs=1).nargs
{1}
>>> Function('f', nargs=(2, 1)).nargs
{1, 2}
The undefined function, after application, also has the nargs
attribute; the actual number of arguments is always available by
checking the ``args`` attribute:
>>> f = Function('f')
>>> f(1).nargs
Naturals0
>>> len(f(1).args)
1
"""
from sympy.sets.sets import FiniteSet
# XXX it would be nice to handle this in __init__ but there are import
# problems with trying to import FiniteSet there
return FiniteSet(*self._nargs) if self._nargs else S.Naturals0
def _valid_nargs(self, n : int) -> bool:
""" Return True if the specified interger is a valid number of arguments
The number of arguments n is guaranteed to be an integer and positive
"""
if self._nargs:
return n in self._nargs
nargs = self.nargs
return nargs is S.Naturals0 or n in nargs
def __repr__(cls):
return cls.__name__
class Application(Basic, metaclass=FunctionClass):
"""
Base class for applied functions.
Explanation
===========
Instances of Application represent the result of applying an application of
any type to any object.
"""
is_Function = True
@cacheit
def __new__(cls, *args, **options):
from sympy.sets.fancysets import Naturals0
from sympy.sets.sets import FiniteSet
args = list(map(sympify, args))
evaluate = options.pop('evaluate', global_parameters.evaluate)
# WildFunction (and anything else like it) may have nargs defined
# and we throw that value away here
options.pop('nargs', None)
if options:
raise ValueError("Unknown options: %s" % options)
if evaluate:
evaluated = cls.eval(*args)
if evaluated is not None:
return evaluated
obj = super().__new__(cls, *args, **options)
# make nargs uniform here
sentinel = object()
objnargs = getattr(obj, "nargs", sentinel)
if objnargs is not sentinel:
# things passing through here:
# - functions subclassed from Function (e.g. myfunc(1).nargs)
# - functions like cos(1).nargs
# - AppliedUndef with given nargs like Function('f', nargs=1)(1).nargs
# Canonicalize nargs here
if is_sequence(objnargs):
nargs = tuple(ordered(set(objnargs)))
elif objnargs is not None:
nargs = (as_int(objnargs),)
else:
nargs = None
else:
# things passing through here:
# - WildFunction('f').nargs
# - AppliedUndef with no nargs like Function('f')(1).nargs
nargs = obj._nargs # note the underscore here
# convert to FiniteSet
obj.nargs = FiniteSet(*nargs) if nargs else Naturals0()
return obj
@classmethod
def eval(cls, *args):
"""
Returns a canonical form of cls applied to arguments args.
Explanation
===========
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
Examples of eval() for the function "sign"
---------------------------------------------
.. code-block:: python
@classmethod
def eval(cls, arg):
if arg is S.NaN:
return S.NaN
if arg.is_zero: return S.Zero
if arg.is_positive: return S.One
if arg.is_negative: return S.NegativeOne
if isinstance(arg, Mul):
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff is not S.One:
return cls(coeff) * cls(terms)
"""
return
@property
def func(self):
return self.__class__
def _eval_subs(self, old, new):
if (old.is_Function and new.is_Function and
callable(old) and callable(new) and
old == self.func and len(self.args) in new.nargs):
return new(*[i._subs(old, new) for i in self.args])
class Function(Application, Expr):
r"""
Base class for applied mathematical functions.
It also serves as a constructor for undefined function classes.
See the :ref:`custom-functions` guide for details on how to subclass
``Function`` and what methods can be defined.
Examples
========
**Undefined Functions**
To create an undefined function, pass a string of the function name to
``Function``.
>>> from sympy import Function, Symbol
>>> x = Symbol('x')
>>> f = Function('f')
>>> g = Function('g')(x)
>>> f
f
>>> f(x)
f(x)
>>> g
g(x)
>>> f(x).diff(x)
Derivative(f(x), x)
>>> g.diff(x)
Derivative(g(x), x)
Assumptions can be passed to ``Function`` the same as with a
:class:`~.Symbol`. Alternatively, you can use a ``Symbol`` with
assumptions for the function name and the function will inherit the name
and assumptions associated with the ``Symbol``:
>>> f_real = Function('f', real=True)
>>> f_real(x).is_real
True
>>> f_real_inherit = Function(Symbol('f', real=True))
>>> f_real_inherit(x).is_real
True
Note that assumptions on a function are unrelated to the assumptions on
the variables it is called on. If you want to add a relationship, subclass
``Function`` and define custom assumptions handler methods. See the
:ref:`custom-functions-assumptions` section of the :ref:`custom-functions`
guide for more details.
**Custom Function Subclasses**
The :ref:`custom-functions` guide has several
:ref:`custom-functions-complete-examples` of how to subclass ``Function``
to create a custom function.
"""
@property
def _diff_wrt(self):
return False
@cacheit
def __new__(cls, *args, **options):
# Handle calls like Function('f')
if cls is Function:
return UndefinedFunction(*args, **options)
n = len(args)
if not cls._valid_nargs(n):
# XXX: exception message must be in exactly this format to
# make it work with NumPy's functions like vectorize(). See,
# for example, https://github.com/numpy/numpy/issues/1697.
# The ideal solution would be just to attach metadata to
# the exception and change NumPy to take advantage of this.
temp = ('%(name)s takes %(qual)s %(args)s '
'argument%(plural)s (%(given)s given)')
raise TypeError(temp % {
'name': cls,
'qual': 'exactly' if len(cls.nargs) == 1 else 'at least',
'args': min(cls.nargs),
'plural': 's'*(min(cls.nargs) != 1),
'given': n})
evaluate = options.get('evaluate', global_parameters.evaluate)
result = super().__new__(cls, *args, **options)
if evaluate and isinstance(result, cls) and result.args:
_should_evalf = [cls._should_evalf(a) for a in result.args]
pr2 = min(_should_evalf)
if pr2 > 0:
pr = max(_should_evalf)
result = result.evalf(prec_to_dps(pr))
return _sympify(result)
@classmethod
def _should_evalf(cls, arg):
"""
Decide if the function should automatically evalf().
Explanation
===========
By default (in this implementation), this happens if (and only if) the
ARG is a floating point number (including complex numbers).
This function is used by __new__.
Returns the precision to evalf to, or -1 if it should not evalf.
"""
if arg.is_Float:
return arg._prec
if not arg.is_Add:
return -1
m = pure_complex(arg)
if m is None:
return -1
# the elements of m are of type Number, so have a _prec
return max(m[0]._prec, m[1]._prec)
@classmethod
def class_key(cls):
from sympy.sets.fancysets import Naturals0
funcs = {
'exp': 10,
'log': 11,
'sin': 20,
'cos': 21,
'tan': 22,
'cot': 23,
'sinh': 30,
'cosh': 31,
'tanh': 32,
'coth': 33,
'conjugate': 40,
're': 41,
'im': 42,
'arg': 43,
}
name = cls.__name__
try:
i = funcs[name]
except KeyError:
i = 0 if isinstance(cls.nargs, Naturals0) else 10000
return 4, i, name
def _eval_evalf(self, prec):
def _get_mpmath_func(fname):
"""Lookup mpmath function based on name"""
if isinstance(self, AppliedUndef):
# Shouldn't lookup in mpmath but might have ._imp_
return None
if not hasattr(mpmath, fname):
fname = MPMATH_TRANSLATIONS.get(fname, None)
if fname is None:
return None
return getattr(mpmath, fname)
_eval_mpmath = getattr(self, '_eval_mpmath', None)
if _eval_mpmath is None:
func = _get_mpmath_func(self.func.__name__)
args = self.args
else:
func, args = _eval_mpmath()
# Fall-back evaluation
if func is None:
imp = getattr(self, '_imp_', None)
if imp is None:
return None
try:
return Float(imp(*[i.evalf(prec) for i in self.args]), prec)
except (TypeError, ValueError):
return None
# Convert all args to mpf or mpc
# Convert the arguments to *higher* precision than requested for the
# final result.
# XXX + 5 is a guess, it is similar to what is used in evalf.py. Should
# we be more intelligent about it?
try:
args = [arg._to_mpmath(prec + 5) for arg in args]
def bad(m):
from mpmath import mpf, mpc
# the precision of an mpf value is the last element
# if that is 1 (and m[1] is not 1 which would indicate a
# power of 2), then the eval failed; so check that none of
# the arguments failed to compute to a finite precision.
# Note: An mpc value has two parts, the re and imag tuple;
# check each of those parts, too. Anything else is allowed to
# pass
if isinstance(m, mpf):
m = m._mpf_
return m[1] !=1 and m[-1] == 1
elif isinstance(m, mpc):
m, n = m._mpc_
return m[1] !=1 and m[-1] == 1 and \
n[1] !=1 and n[-1] == 1
else:
return False
if any(bad(a) for a in args):
raise ValueError # one or more args failed to compute with significance
except ValueError:
return
with mpmath.workprec(prec):
v = func(*args)
return Expr._from_mpmath(v, prec)
def _eval_derivative(self, s):
# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
i = 0
l = []
for a in self.args:
i += 1
da = a.diff(s)
if da.is_zero:
continue
try:
df = self.fdiff(i)
except ArgumentIndexError:
df = Function.fdiff(self, i)
l.append(df * da)
return Add(*l)
def _eval_is_commutative(self):
return fuzzy_and(a.is_commutative for a in self.args)
def _eval_is_meromorphic(self, x, a):
if not self.args:
return True
if any(arg.has(x) for arg in self.args[1:]):
return False
arg = self.args[0]
if not arg._eval_is_meromorphic(x, a):
return None
return fuzzy_not(type(self).is_singular(arg.subs(x, a)))
_singularities = None # type: tUnion[FuzzyBool, tTuple[Expr, ...]]
@classmethod
def is_singular(cls, a):
"""
Tests whether the argument is an essential singularity
or a branch point, or the functions is non-holomorphic.
"""
ss = cls._singularities
if ss in (True, None, False):
return ss
return fuzzy_or(a.is_infinite if s is S.ComplexInfinity
else (a - s).is_zero for s in ss)
def as_base_exp(self):
"""
Returns the method as the 2-tuple (base, exponent).
"""
return self, S.One
def _eval_aseries(self, n, args0, x, logx):
"""
Compute an asymptotic expansion around args0, in terms of self.args.
This function is only used internally by _eval_nseries and should not
be called directly; derived classes can overwrite this to implement
asymptotic expansions.
"""
raise PoleError(filldedent('''
Asymptotic expansion of %s around %s is
not implemented.''' % (type(self), args0)))
def _eval_nseries(self, x, n, logx, cdir=0):
"""
This function does compute series for multivariate functions,
but the expansion is always in terms of *one* variable.
Examples
========
>>> from sympy import atan2
>>> from sympy.abc import x, y
>>> atan2(x, y).series(x, n=2)
atan2(0, y) + x/y + O(x**2)
>>> atan2(x, y).series(y, n=2)
-y/x + atan2(x, 0) + O(y**2)
This function also computes asymptotic expansions, if necessary
and possible:
>>> from sympy import loggamma
>>> loggamma(1/x)._eval_nseries(x,0,None)
-1/x - log(x)/x + log(x)/2 + O(1)
"""
from .symbol import uniquely_named_symbol
from sympy.series.order import Order
from sympy.sets.sets import FiniteSet
args = self.args
args0 = [t.limit(x, 0) for t in args]
if any(t.is_finite is False for t in args0):
from .numbers import oo, zoo, nan
a = [t.as_leading_term(x, logx=logx) for t in args]
a0 = [t.limit(x, 0) for t in a]
if any(t.has(oo, -oo, zoo, nan) for t in a0):
return self._eval_aseries(n, args0, x, logx)
# Careful: the argument goes to oo, but only logarithmically so. We
# are supposed to do a power series expansion "around the
# logarithmic term". e.g.
# f(1+x+log(x))
# -> f(1+logx) + x*f'(1+logx) + O(x**2)
# where 'logx' is given in the argument
a = [t._eval_nseries(x, n, logx) for t in args]
z = [r - r0 for (r, r0) in zip(a, a0)]
p = [Dummy() for _ in z]
q = []
v = None
for ai, zi, pi in zip(a0, z, p):
if zi.has(x):
if v is not None:
raise NotImplementedError
q.append(ai + pi)
v = pi
else:
q.append(ai)
e1 = self.func(*q)
if v is None:
return e1
s = e1._eval_nseries(v, n, logx)
o = s.getO()
s = s.removeO()
s = s.subs(v, zi).expand() + Order(o.expr.subs(v, zi), x)
return s
if (self.func.nargs is S.Naturals0
or (self.func.nargs == FiniteSet(1) and args0[0])
or any(c > 1 for c in self.func.nargs)):
e = self
e1 = e.expand()
if e == e1:
#for example when e = sin(x+1) or e = sin(cos(x))
#let's try the general algorithm
if len(e.args) == 1:
# issue 14411
e = e.func(e.args[0].cancel())
term = e.subs(x, S.Zero)
if term.is_finite is False or term is S.NaN:
raise PoleError("Cannot expand %s around 0" % (self))
series = term
fact = S.One
_x = uniquely_named_symbol('xi', self)
e = e.subs(x, _x)
for i in range(1, n):
fact *= Rational(i)
e = e.diff(_x)
subs = e.subs(_x, S.Zero)
if subs is S.NaN:
# try to evaluate a limit if we have to
subs = e.limit(_x, S.Zero)
if subs.is_finite is False:
raise PoleError("Cannot expand %s around 0" % (self))
term = subs*(x**i)/fact
term = term.expand()
series += term
return series + Order(x**n, x)
return e1.nseries(x, n=n, logx=logx)
arg = self.args[0]
l = []
g = None
# try to predict a number of terms needed
nterms = n + 2
cf = Order(arg.as_leading_term(x), x).getn()
if cf != 0:
nterms = (n/cf).ceiling()
for i in range(nterms):
g = self.taylor_term(i, arg, g)
g = g.nseries(x, n=n, logx=logx)
l.append(g)
return Add(*l) + Order(x**n, x)
def fdiff(self, argindex=1):
"""
Returns the first derivative of the function.
"""
if not (1 <= argindex <= len(self.args)):
raise ArgumentIndexError(self, argindex)
ix = argindex - 1
A = self.args[ix]
if A._diff_wrt:
if len(self.args) == 1 or not A.is_Symbol:
return _derivative_dispatch(self, A)
for i, v in enumerate(self.args):
if i != ix and A in v.free_symbols:
# it can't be in any other argument's free symbols
# issue 8510
break
else:
return _derivative_dispatch(self, A)
# See issue 4624 and issue 4719, 5600 and 8510
D = Dummy('xi_%i' % argindex, dummy_index=hash(A))
args = self.args[:ix] + (D,) + self.args[ix + 1:]
return Subs(Derivative(self.func(*args), D), D, A)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
"""Stub that should be overridden by new Functions to return
the first non-zero term in a series if ever an x-dependent
argument whose leading term vanishes as x -> 0 might be encountered.
See, for example, cos._eval_as_leading_term.
"""
from sympy.series.order import Order
args = [a.as_leading_term(x, logx=logx) for a in self.args]
o = Order(1, x)
if any(x in a.free_symbols and o.contains(a) for a in args):
# Whereas x and any finite number are contained in O(1, x),
# expressions like 1/x are not. If any arg simplified to a
# vanishing expression as x -> 0 (like x or x**2, but not
# 3, 1/x, etc...) then the _eval_as_leading_term is needed
# to supply the first non-zero term of the series,
#
# e.g. expression leading term
# ---------- ------------
# cos(1/x) cos(1/x)
# cos(cos(x)) cos(1)
# cos(x) 1 <- _eval_as_leading_term needed
# sin(x) x <- _eval_as_leading_term needed
#
raise NotImplementedError(
'%s has no _eval_as_leading_term routine' % self.func)
else:
return self.func(*args)
class AppliedUndef(Function):
"""
Base class for expressions resulting from the application of an undefined
function.
"""
is_number = False
def __new__(cls, *args, **options):
args = list(map(sympify, args))
u = [a.name for a in args if isinstance(a, UndefinedFunction)]
if u:
raise TypeError('Invalid argument: expecting an expression, not UndefinedFunction%s: %s' % (
's'*(len(u) > 1), ', '.join(u)))
obj = super().__new__(cls, *args, **options)
return obj
def _eval_as_leading_term(self, x, logx=None, cdir=0):
return self
@property
def _diff_wrt(self):
"""
Allow derivatives wrt to undefined functions.
Examples
========
>>> from sympy import Function, Symbol
>>> f = Function('f')
>>> x = Symbol('x')
>>> f(x)._diff_wrt
True
>>> f(x).diff(x)
Derivative(f(x), x)
"""
return True
class UndefSageHelper:
"""
Helper to facilitate Sage conversion.
"""
def __get__(self, ins, typ):
import sage.all as sage
if ins is None:
return lambda: sage.function(typ.__name__)
else:
args = [arg._sage_() for arg in ins.args]
return lambda : sage.function(ins.__class__.__name__)(*args)
_undef_sage_helper = UndefSageHelper()
class UndefinedFunction(FunctionClass):
"""
The (meta)class of undefined functions.
"""
def __new__(mcl, name, bases=(AppliedUndef,), __dict__=None, **kwargs):
from .symbol import _filter_assumptions
# Allow Function('f', real=True)
# and/or Function(Symbol('f', real=True))
assumptions, kwargs = _filter_assumptions(kwargs)
if isinstance(name, Symbol):
assumptions = name._merge(assumptions)
name = name.name
elif not isinstance(name, str):
raise TypeError('expecting string or Symbol for name')
else:
commutative = assumptions.get('commutative', None)
assumptions = Symbol(name, **assumptions).assumptions0
if commutative is None:
assumptions.pop('commutative')
__dict__ = __dict__ or {}
# put the `is_*` for into __dict__
__dict__.update({'is_%s' % k: v for k, v in assumptions.items()})
# You can add other attributes, although they do have to be hashable
# (but seriously, if you want to add anything other than assumptions,
# just subclass Function)
__dict__.update(kwargs)
# add back the sanitized assumptions without the is_ prefix
kwargs.update(assumptions)
# Save these for __eq__
__dict__.update({'_kwargs': kwargs})
# do this for pickling
__dict__['__module__'] = None
obj = super().__new__(mcl, name, bases, __dict__)
obj.name = name
obj._sage_ = _undef_sage_helper
return obj
def __instancecheck__(cls, instance):
return cls in type(instance).__mro__
_kwargs = {} # type: tDict[str, Optional[bool]]
def __hash__(self):
return hash((self.class_key(), frozenset(self._kwargs.items())))
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.class_key() == other.class_key() and
self._kwargs == other._kwargs)
def __ne__(self, other):
return not self == other
@property
def _diff_wrt(self):
return False
# XXX: The type: ignore on WildFunction is because mypy complains:
#
# sympy/core/function.py:939: error: Cannot determine type of 'sort_key' in
# base class 'Expr'
#
# Somehow this is because of the @cacheit decorator but it is not clear how to
# fix it.
class WildFunction(Function, AtomicExpr): # type: ignore
"""
A WildFunction function matches any function (with its arguments).
Examples
========
>>> from sympy import WildFunction, Function, cos
>>> from sympy.abc import x, y
>>> F = WildFunction('F')
>>> f = Function('f')
>>> F.nargs
Naturals0
>>> x.match(F)
>>> F.match(F)
{F_: F_}
>>> f(x).match(F)
{F_: f(x)}
>>> cos(x).match(F)
{F_: cos(x)}
>>> f(x, y).match(F)
{F_: f(x, y)}
To match functions with a given number of arguments, set ``nargs`` to the
desired value at instantiation:
>>> F = WildFunction('F', nargs=2)
>>> F.nargs
{2}
>>> f(x).match(F)
>>> f(x, y).match(F)
{F_: f(x, y)}
To match functions with a range of arguments, set ``nargs`` to a tuple
containing the desired number of arguments, e.g. if ``nargs = (1, 2)``
then functions with 1 or 2 arguments will be matched.
>>> F = WildFunction('F', nargs=(1, 2))
>>> F.nargs
{1, 2}
>>> f(x).match(F)
{F_: f(x)}
>>> f(x, y).match(F)
{F_: f(x, y)}
>>> f(x, y, 1).match(F)
"""
# XXX: What is this class attribute used for?
include = set() # type: tSet[Any]
def __init__(cls, name, **assumptions):
from sympy.sets.sets import Set, FiniteSet
cls.name = name
nargs = assumptions.pop('nargs', S.Naturals0)
if not isinstance(nargs, Set):
# Canonicalize nargs here. See also FunctionClass.
if is_sequence(nargs):
nargs = tuple(ordered(set(nargs)))
elif nargs is not None:
nargs = (as_int(nargs),)
nargs = FiniteSet(*nargs)
cls.nargs = nargs
def matches(self, expr, repl_dict=None, old=False):
if not isinstance(expr, (AppliedUndef, Function)):
return None
if len(expr.args) not in self.nargs:
return None
if repl_dict is None:
repl_dict = {}
else:
repl_dict = repl_dict.copy()
repl_dict[self] = expr
return repl_dict
class Derivative(Expr):
"""
Carries out differentiation of the given expression with respect to symbols.
Examples
========
>>> from sympy import Derivative, Function, symbols, Subs
>>> from sympy.abc import x, y
>>> f, g = symbols('f g', cls=Function)
>>> Derivative(x**2, x, evaluate=True)
2*x
Denesting of derivatives retains the ordering of variables:
>>> Derivative(Derivative(f(x, y), y), x)
Derivative(f(x, y), y, x)
Contiguously identical symbols are merged into a tuple giving
the symbol and the count:
>>> Derivative(f(x), x, x, y, x)
Derivative(f(x), (x, 2), y, x)
If the derivative cannot be performed, and evaluate is True, the
order of the variables of differentiation will be made canonical:
>>> Derivative(f(x, y), y, x, evaluate=True)
Derivative(f(x, y), x, y)
Derivatives with respect to undefined functions can be calculated:
>>> Derivative(f(x)**2, f(x), evaluate=True)
2*f(x)
Such derivatives will show up when the chain rule is used to
evalulate a derivative:
>>> f(g(x)).diff(x)
Derivative(f(g(x)), g(x))*Derivative(g(x), x)
Substitution is used to represent derivatives of functions with
arguments that are not symbols or functions:
>>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3)
True
Notes
=====
Simplification of high-order derivatives:
Because there can be a significant amount of simplification that can be
done when multiple differentiations are performed, results will be
automatically simplified in a fairly conservative fashion unless the
keyword ``simplify`` is set to False.
>>> from sympy import sqrt, diff, Function, symbols
>>> from sympy.abc import x, y, z
>>> f, g = symbols('f,g', cls=Function)
>>> e = sqrt((x + 1)**2 + x)
>>> diff(e, (x, 5), simplify=False).count_ops()
136
>>> diff(e, (x, 5)).count_ops()
30
Ordering of variables:
If evaluate is set to True and the expression cannot be evaluated, the
list of differentiation symbols will be sorted, that is, the expression is
assumed to have continuous derivatives up to the order asked.
Derivative wrt non-Symbols:
For the most part, one may not differentiate wrt non-symbols.
For example, we do not allow differentiation wrt `x*y` because
there are multiple ways of structurally defining where x*y appears
in an expression: a very strict definition would make
(x*y*z).diff(x*y) == 0. Derivatives wrt defined functions (like
cos(x)) are not allowed, either:
>>> (x*y*z).diff(x*y)
Traceback (most recent call last):
...
ValueError: Can't calculate derivative wrt x*y.
To make it easier to work with variational calculus, however,
derivatives wrt AppliedUndef and Derivatives are allowed.
For example, in the Euler-Lagrange method one may write
F(t, u, v) where u = f(t) and v = f'(t). These variables can be
written explicitly as functions of time::
>>> from sympy.abc import t
>>> F = Function('F')
>>> U = f(t)
>>> V = U.diff(t)
The derivative wrt f(t) can be obtained directly:
>>> direct = F(t, U, V).diff(U)
When differentiation wrt a non-Symbol is attempted, the non-Symbol
is temporarily converted to a Symbol while the differentiation
is performed and the same answer is obtained:
>>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U)
>>> assert direct == indirect
The implication of this non-symbol replacement is that all
functions are treated as independent of other functions and the
symbols are independent of the functions that contain them::
>>> x.diff(f(x))
0
>>> g(x).diff(f(x))
0
It also means that derivatives are assumed to depend only
on the variables of differentiation, not on anything contained
within the expression being differentiated::
>>> F = f(x)
>>> Fx = F.diff(x)
>>> Fx.diff(F) # derivative depends on x, not F
0
>>> Fxx = Fx.diff(x)
>>> Fxx.diff(Fx) # derivative depends on x, not Fx
0
The last example can be made explicit by showing the replacement
of Fx in Fxx with y:
>>> Fxx.subs(Fx, y)
Derivative(y, x)
Since that in itself will evaluate to zero, differentiating
wrt Fx will also be zero:
>>> _.doit()
0
Replacing undefined functions with concrete expressions
One must be careful to replace undefined functions with expressions
that contain variables consistent with the function definition and
the variables of differentiation or else insconsistent result will
be obtained. Consider the following example:
>>> eq = f(x)*g(y)
>>> eq.subs(f(x), x*y).diff(x, y).doit()
y*Derivative(g(y), y) + g(y)
>>> eq.diff(x, y).subs(f(x), x*y).doit()
y*Derivative(g(y), y)
The results differ because `f(x)` was replaced with an expression
that involved both variables of differentiation. In the abstract
case, differentiation of `f(x)` by `y` is 0; in the concrete case,
the presence of `y` made that derivative nonvanishing and produced
the extra `g(y)` term.
Defining differentiation for an object
An object must define ._eval_derivative(symbol) method that returns
the differentiation result. This function only needs to consider the
non-trivial case where expr contains symbol and it should call the diff()
method internally (not _eval_derivative); Derivative should be the only
one to call _eval_derivative.
Any class can allow derivatives to be taken with respect to
itself (while indicating its scalar nature). See the
docstring of Expr._diff_wrt.
See Also
========
_sort_variable_count
"""
is_Derivative = True
@property
def _diff_wrt(self):
"""An expression may be differentiated wrt a Derivative if
it is in elementary form.
Examples
========
>>> from sympy import Function, Derivative, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> Derivative(f(x), x)._diff_wrt
True
>>> Derivative(cos(x), x)._diff_wrt
False
>>> Derivative(x + 1, x)._diff_wrt
False
A Derivative might be an unevaluated form of what will not be
a valid variable of differentiation if evaluated. For example,
>>> Derivative(f(f(x)), x).doit()
Derivative(f(x), x)*Derivative(f(f(x)), f(x))
Such an expression will present the same ambiguities as arise
when dealing with any other product, like ``2*x``, so ``_diff_wrt``
is False:
>>> Derivative(f(f(x)), x)._diff_wrt
False
"""
return self.expr._diff_wrt and isinstance(self.doit(), Derivative)
def __new__(cls, expr, *variables, **kwargs):
expr = sympify(expr)
symbols_or_none = getattr(expr, "free_symbols", None)
has_symbol_set = isinstance(symbols_or_none, set)
if not has_symbol_set:
raise ValueError(filldedent('''
Since there are no variables in the expression %s,
it cannot be differentiated.''' % expr))
# determine value for variables if it wasn't given
if not variables:
variables = expr.free_symbols
if len(variables) != 1:
if expr.is_number:
return S.Zero
if len(variables) == 0:
raise ValueError(filldedent('''
Since there are no variables in the expression,
the variable(s) of differentiation must be supplied
to differentiate %s''' % expr))
else:
raise ValueError(filldedent('''
Since there is more than one variable in the
expression, the variable(s) of differentiation
must be supplied to differentiate %s''' % expr))
# Split the list of variables into a list of the variables we are diff
# wrt, where each element of the list has the form (s, count) where
# s is the entity to diff wrt and count is the order of the
# derivative.
variable_count = []
array_likes = (tuple, list, Tuple)
from sympy.tensor.array import Array, NDimArray
for i, v in enumerate(variables):
if isinstance(v, UndefinedFunction):
raise TypeError(
"cannot differentiate wrt "
"UndefinedFunction: %s" % v)
if isinstance(v, array_likes):
if len(v) == 0:
# Ignore empty tuples: Derivative(expr, ... , (), ... )
continue
if isinstance(v[0], array_likes):
# Derive by array: Derivative(expr, ... , [[x, y, z]], ... )
if len(v) == 1:
v = Array(v[0])
count = 1
else:
v, count = v
v = Array(v)
else:
v, count = v
if count == 0:
continue
variable_count.append(Tuple(v, count))
continue
v = sympify(v)
if isinstance(v, Integer):
if i == 0:
raise ValueError("First variable cannot be a number: %i" % v)
count = v
prev, prevcount = variable_count[-1]
if prevcount != 1:
raise TypeError("tuple {} followed by number {}".format((prev, prevcount), v))
if count == 0:
variable_count.pop()
else:
variable_count[-1] = Tuple(prev, count)
else:
count = 1
variable_count.append(Tuple(v, count))
# light evaluation of contiguous, identical
# items: (x, 1), (x, 1) -> (x, 2)
merged = []
for t in variable_count:
v, c = t
if c.is_negative:
raise ValueError(
'order of differentiation must be nonnegative')
if merged and merged[-1][0] == v:
c += merged[-1][1]
if not c:
merged.pop()
else:
merged[-1] = Tuple(v, c)
else:
merged.append(t)
variable_count = merged
# sanity check of variables of differentation; we waited
# until the counts were computed since some variables may
# have been removed because the count was 0
for v, c in variable_count:
# v must have _diff_wrt True
if not v._diff_wrt:
__ = '' # filler to make error message neater
raise ValueError(filldedent('''
Can't calculate derivative wrt %s.%s''' % (v,
__)))
# We make a special case for 0th derivative, because there is no
# good way to unambiguously print this.
if len(variable_count) == 0:
return expr
evaluate = kwargs.get('evaluate', False)
if evaluate:
if isinstance(expr, Derivative):
expr = expr.canonical
variable_count = [
(v.canonical if isinstance(v, Derivative) else v, c)
for v, c in variable_count]
# Look for a quick exit if there are symbols that don't appear in
# expression at all. Note, this cannot check non-symbols like
# Derivatives as those can be created by intermediate
# derivatives.
zero = False
free = expr.free_symbols
from sympy.matrices.expressions.matexpr import MatrixExpr
for v, c in variable_count:
vfree = v.free_symbols
if c.is_positive and vfree:
if isinstance(v, AppliedUndef):
# these match exactly since
# x.diff(f(x)) == g(x).diff(f(x)) == 0
# and are not created by differentiation
D = Dummy()
if not expr.xreplace({v: D}).has(D):
zero = True
break
elif isinstance(v, MatrixExpr):
zero = False
break
elif isinstance(v, Symbol) and v not in free:
zero = True
break
else:
if not free & vfree:
# e.g. v is IndexedBase or Matrix
zero = True
break
if zero:
return cls._get_zero_with_shape_like(expr)
# make the order of symbols canonical
#TODO: check if assumption of discontinuous derivatives exist
variable_count = cls._sort_variable_count(variable_count)
# denest
if isinstance(expr, Derivative):
variable_count = list(expr.variable_count) + variable_count
expr = expr.expr
return _derivative_dispatch(expr, *variable_count, **kwargs)
# we return here if evaluate is False or if there is no
# _eval_derivative method
if not evaluate or not hasattr(expr, '_eval_derivative'):
# return an unevaluated Derivative
if evaluate and variable_count == [(expr, 1)] and expr.is_scalar:
# special hack providing evaluation for classes
# that have defined is_scalar=True but have no
# _eval_derivative defined
return S.One
return Expr.__new__(cls, expr, *variable_count)
# evaluate the derivative by calling _eval_derivative method
# of expr for each variable
# -------------------------------------------------------------
nderivs = 0 # how many derivatives were performed
unhandled = []
from sympy.matrices.common import MatrixCommon
for i, (v, count) in enumerate(variable_count):
old_expr = expr
old_v = None
is_symbol = v.is_symbol or isinstance(v,
(Iterable, Tuple, MatrixCommon, NDimArray))
if not is_symbol:
old_v = v
v = Dummy('xi')
expr = expr.xreplace({old_v: v})
# Derivatives and UndefinedFunctions are independent
# of all others
clashing = not (isinstance(old_v, Derivative) or \
isinstance(old_v, AppliedUndef))
if v not in expr.free_symbols and not clashing:
return expr.diff(v) # expr's version of 0
if not old_v.is_scalar and not hasattr(
old_v, '_eval_derivative'):
# special hack providing evaluation for classes
# that have defined is_scalar=True but have no
# _eval_derivative defined
expr *= old_v.diff(old_v)
obj = cls._dispatch_eval_derivative_n_times(expr, v, count)
if obj is not None and obj.is_zero:
return obj
nderivs += count
if old_v is not None:
if obj is not None:
# remove the dummy that was used
obj = obj.subs(v, old_v)
# restore expr
expr = old_expr
if obj is None:
# we've already checked for quick-exit conditions
# that give 0 so the remaining variables
# are contained in the expression but the expression
# did not compute a derivative so we stop taking
# derivatives
unhandled = variable_count[i:]
break
expr = obj
# what we have so far can be made canonical
expr = expr.replace(
lambda x: isinstance(x, Derivative),
lambda x: x.canonical)
if unhandled:
if isinstance(expr, Derivative):
unhandled = list(expr.variable_count) + unhandled
expr = expr.expr
expr = Expr.__new__(cls, expr, *unhandled)
if (nderivs > 1) == True and kwargs.get('simplify', True):
from .exprtools import factor_terms
from sympy.simplify.simplify import signsimp
expr = factor_terms(signsimp(expr))
return expr
@property
def canonical(cls):
return cls.func(cls.expr,
*Derivative._sort_variable_count(cls.variable_count))
@classmethod
def _sort_variable_count(cls, vc):
"""
Sort (variable, count) pairs into canonical order while
retaining order of variables that do not commute during
differentiation:
* symbols and functions commute with each other
* derivatives commute with each other
* a derivative does not commute with anything it contains
* any other object is not allowed to commute if it has
free symbols in common with another object
Examples
========
>>> from sympy import Derivative, Function, symbols
>>> vsort = Derivative._sort_variable_count
>>> x, y, z = symbols('x y z')
>>> f, g, h = symbols('f g h', cls=Function)
Contiguous items are collapsed into one pair:
>>> vsort([(x, 1), (x, 1)])
[(x, 2)]
>>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)])
[(y, 2), (f(x), 2)]
Ordering is canonical.
>>> def vsort0(*v):
... # docstring helper to
... # change vi -> (vi, 0), sort, and return vi vals
... return [i[0] for i in vsort([(i, 0) for i in v])]
>>> vsort0(y, x)
[x, y]
>>> vsort0(g(y), g(x), f(y))
[f(y), g(x), g(y)]
Symbols are sorted as far to the left as possible but never
move to the left of a derivative having the same symbol in
its variables; the same applies to AppliedUndef which are
always sorted after Symbols:
>>> dfx = f(x).diff(x)
>>> assert vsort0(dfx, y) == [y, dfx]
>>> assert vsort0(dfx, x) == [dfx, x]
"""
if not vc:
return []
vc = list(vc)
if len(vc) == 1:
return [Tuple(*vc[0])]
V = list(range(len(vc)))
E = []
v = lambda i: vc[i][0]
D = Dummy()
def _block(d, v, wrt=False):
# return True if v should not come before d else False
if d == v:
return wrt
if d.is_Symbol:
return False
if isinstance(d, Derivative):
# a derivative blocks if any of it's variables contain
# v; the wrt flag will return True for an exact match
# and will cause an AppliedUndef to block if v is in
# the arguments
if any(_block(k, v, wrt=True)
for k in d._wrt_variables):
return True
return False
if not wrt and isinstance(d, AppliedUndef):
return False
if v.is_Symbol:
return v in d.free_symbols
if isinstance(v, AppliedUndef):
return _block(d.xreplace({v: D}), D)
return d.free_symbols & v.free_symbols
for i in range(len(vc)):
for j in range(i):
if _block(v(j), v(i)):
E.append((j,i))
# this is the default ordering to use in case of ties
O = dict(zip(ordered(uniq([i for i, c in vc])), range(len(vc))))
ix = topological_sort((V, E), key=lambda i: O[v(i)])
# merge counts of contiguously identical items
merged = []
for v, c in [vc[i] for i in ix]:
if merged and merged[-1][0] == v:
merged[-1][1] += c
else:
merged.append([v, c])
return [Tuple(*i) for i in merged]
def _eval_is_commutative(self):
return self.expr.is_commutative
def _eval_derivative(self, v):
# If v (the variable of differentiation) is not in
# self.variables, we might be able to take the derivative.
if v not in self._wrt_variables:
dedv = self.expr.diff(v)
if isinstance(dedv, Derivative):
return dedv.func(dedv.expr, *(self.variable_count + dedv.variable_count))
# dedv (d(self.expr)/dv) could have simplified things such that the
# derivative wrt things in self.variables can now be done. Thus,
# we set evaluate=True to see if there are any other derivatives
# that can be done. The most common case is when dedv is a simple
# number so that the derivative wrt anything else will vanish.
return self.func(dedv, *self.variables, evaluate=True)
# In this case v was in self.variables so the derivative wrt v has
# already been attempted and was not computed, either because it
# couldn't be or evaluate=False originally.
variable_count = list(self.variable_count)
variable_count.append((v, 1))
return self.func(self.expr, *variable_count, evaluate=False)
def doit(self, **hints):
expr = self.expr
if hints.get('deep', True):
expr = expr.doit(**hints)
hints['evaluate'] = True
rv = self.func(expr, *self.variable_count, **hints)
if rv!= self and rv.has(Derivative):
rv = rv.doit(**hints)
return rv
@_sympifyit('z0', NotImplementedError)
def doit_numerically(self, z0):
"""
Evaluate the derivative at z numerically.
When we can represent derivatives at a point, this should be folded
into the normal evalf. For now, we need a special method.
"""
if len(self.free_symbols) != 1 or len(self.variables) != 1:
raise NotImplementedError('partials and higher order derivatives')
z = list(self.free_symbols)[0]
def eval(x):
f0 = self.expr.subs(z, Expr._from_mpmath(x, prec=mpmath.mp.prec))
f0 = f0.evalf(prec_to_dps(mpmath.mp.prec))
return f0._to_mpmath(mpmath.mp.prec)
return Expr._from_mpmath(mpmath.diff(eval,
z0._to_mpmath(mpmath.mp.prec)),
mpmath.mp.prec)
@property
def expr(self):
return self._args[0]
@property
def _wrt_variables(self):
# return the variables of differentiation without
# respect to the type of count (int or symbolic)
return [i[0] for i in self.variable_count]
@property
def variables(self):
# TODO: deprecate? YES, make this 'enumerated_variables' and
# name _wrt_variables as variables
# TODO: support for `d^n`?
rv = []
for v, count in self.variable_count:
if not count.is_Integer:
raise TypeError(filldedent('''
Cannot give expansion for symbolic count. If you just
want a list of all variables of differentiation, use
_wrt_variables.'''))
rv.extend([v]*count)
return tuple(rv)
@property
def variable_count(self):
return self._args[1:]
@property
def derivative_count(self):
return sum([count for _, count in self.variable_count], 0)
@property
def free_symbols(self):
ret = self.expr.free_symbols
# Add symbolic counts to free_symbols
for _, count in self.variable_count:
ret.update(count.free_symbols)
return ret
@property
def kind(self):
return self.args[0].kind
def _eval_subs(self, old, new):
# The substitution (old, new) cannot be done inside
# Derivative(expr, vars) for a variety of reasons
# as handled below.
if old in self._wrt_variables:
# first handle the counts
expr = self.func(self.expr, *[(v, c.subs(old, new))
for v, c in self.variable_count])
if expr != self:
return expr._eval_subs(old, new)
# quick exit case
if not getattr(new, '_diff_wrt', False):
# case (0): new is not a valid variable of
# differentiation
if isinstance(old, Symbol):
# don't introduce a new symbol if the old will do
return Subs(self, old, new)
else:
xi = Dummy('xi')
return Subs(self.xreplace({old: xi}), xi, new)
# If both are Derivatives with the same expr, check if old is
# equivalent to self or if old is a subderivative of self.
if old.is_Derivative and old.expr == self.expr:
if self.canonical == old.canonical:
return new
# collections.Counter doesn't have __le__
def _subset(a, b):
return all((a[i] <= b[i]) == True for i in a)
old_vars = Counter(dict(reversed(old.variable_count)))
self_vars = Counter(dict(reversed(self.variable_count)))
if _subset(old_vars, self_vars):
return _derivative_dispatch(new, *(self_vars - old_vars).items()).canonical
args = list(self.args)
newargs = list(x._subs(old, new) for x in args)
if args[0] == old:
# complete replacement of self.expr
# we already checked that the new is valid so we know
# it won't be a problem should it appear in variables
return _derivative_dispatch(*newargs)
if newargs[0] != args[0]:
# case (1) can't change expr by introducing something that is in
# the _wrt_variables if it was already in the expr
# e.g.
# for Derivative(f(x, g(y)), y), x cannot be replaced with
# anything that has y in it; for f(g(x), g(y)).diff(g(y))
# g(x) cannot be replaced with anything that has g(y)
syms = {vi: Dummy() for vi in self._wrt_variables
if not vi.is_Symbol}
wrt = {syms.get(vi, vi) for vi in self._wrt_variables}
forbidden = args[0].xreplace(syms).free_symbols & wrt
nfree = new.xreplace(syms).free_symbols
ofree = old.xreplace(syms).free_symbols
if (nfree - ofree) & forbidden:
return Subs(self, old, new)
viter = ((i, j) for ((i, _), (j, _)) in zip(newargs[1:], args[1:]))
if any(i != j for i, j in viter): # a wrt-variable change
# case (2) can't change vars by introducing a variable
# that is contained in expr, e.g.
# for Derivative(f(z, g(h(x), y)), y), y cannot be changed to
# x, h(x), or g(h(x), y)
for a in _atomic(self.expr, recursive=True):
for i in range(1, len(newargs)):
vi, _ = newargs[i]
if a == vi and vi != args[i][0]:
return Subs(self, old, new)
# more arg-wise checks
vc = newargs[1:]
oldv = self._wrt_variables
newe = self.expr
subs = []
for i, (vi, ci) in enumerate(vc):
if not vi._diff_wrt:
# case (3) invalid differentiation expression so
# create a replacement dummy
xi = Dummy('xi_%i' % i)
# replace the old valid variable with the dummy
# in the expression
newe = newe.xreplace({oldv[i]: xi})
# and replace the bad variable with the dummy
vc[i] = (xi, ci)
# and record the dummy with the new (invalid)
# differentiation expression
subs.append((xi, vi))
if subs:
# handle any residual substitution in the expression
newe = newe._subs(old, new)
# return the Subs-wrapped derivative
return Subs(Derivative(newe, *vc), *zip(*subs))
# everything was ok
return _derivative_dispatch(*newargs)
def _eval_lseries(self, x, logx, cdir=0):
dx = self.variables
for term in self.expr.lseries(x, logx=logx, cdir=cdir):
yield self.func(term, *dx)
def _eval_nseries(self, x, n, logx, cdir=0):
arg = self.expr.nseries(x, n=n, logx=logx)
o = arg.getO()
dx = self.variables
rv = [self.func(a, *dx) for a in Add.make_args(arg.removeO())]
if o:
rv.append(o/x)
return Add(*rv)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
series_gen = self.expr.lseries(x)
d = S.Zero
for leading_term in series_gen:
d = diff(leading_term, *self.variables)
if d != 0:
break
return d
def as_finite_difference(self, points=1, x0=None, wrt=None):
""" Expresses a Derivative instance as a finite difference.
Parameters
==========
points : sequence or coefficient, optional
If sequence: discrete values (length >= order+1) of the
independent variable used for generating the finite
difference weights.
If it is a coefficient, it will be used as the step-size
for generating an equidistant sequence of length order+1
centered around ``x0``. Default: 1 (step-size 1)
x0 : number or Symbol, optional
the value of the independent variable (``wrt``) at which the
derivative is to be approximated. Default: same as ``wrt``.
wrt : Symbol, optional
"with respect to" the variable for which the (partial)
derivative is to be approximated for. If not provided it
is required that the derivative is ordinary. Default: ``None``.
Examples
========
>>> from sympy import symbols, Function, exp, sqrt, Symbol
>>> x, h = symbols('x h')
>>> f = Function('f')
>>> f(x).diff(x).as_finite_difference()
-f(x - 1/2) + f(x + 1/2)
The default step size and number of points are 1 and
``order + 1`` respectively. We can change the step size by
passing a symbol as a parameter:
>>> f(x).diff(x).as_finite_difference(h)
-f(-h/2 + x)/h + f(h/2 + x)/h
We can also specify the discretized values to be used in a
sequence:
>>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h])
-3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
The algorithm is not restricted to use equidistant spacing, nor
do we need to make the approximation around ``x0``, but we can get
an expression estimating the derivative at an offset:
>>> e, sq2 = exp(1), sqrt(2)
>>> xl = [x-h, x+h, x+e*h]
>>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2) # doctest: +ELLIPSIS
2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/...
To approximate ``Derivative`` around ``x0`` using a non-equidistant
spacing step, the algorithm supports assignment of undefined
functions to ``points``:
>>> dx = Function('dx')
>>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h)
-f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x)
Partial derivatives are also supported:
>>> y = Symbol('y')
>>> d2fdxdy=f(x,y).diff(x,y)
>>> d2fdxdy.as_finite_difference(wrt=x)
-Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
We can apply ``as_finite_difference`` to ``Derivative`` instances in
compound expressions using ``replace``:
>>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative,
... lambda arg: arg.as_finite_difference())
42**(-f(x - 1/2) + f(x + 1/2)) + 1
See also
========
sympy.calculus.finite_diff.apply_finite_diff
sympy.calculus.finite_diff.differentiate_finite
sympy.calculus.finite_diff.finite_diff_weights
"""
from sympy.calculus.finite_diff import _as_finite_diff
return _as_finite_diff(self, points, x0, wrt)
@classmethod
def _get_zero_with_shape_like(cls, expr):
return S.Zero
@classmethod
def _dispatch_eval_derivative_n_times(cls, expr, v, count):
# Evaluate the derivative `n` times. If
# `_eval_derivative_n_times` is not overridden by the current
# object, the default in `Basic` will call a loop over
# `_eval_derivative`:
return expr._eval_derivative_n_times(v, count)
def _derivative_dispatch(expr, *variables, **kwargs):
from sympy.matrices.common import MatrixCommon
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.tensor.array import NDimArray
array_types = (MatrixCommon, MatrixExpr, NDimArray, list, tuple, Tuple)
if isinstance(expr, array_types) or any(isinstance(i[0], array_types) if isinstance(i, (tuple, list, Tuple)) else isinstance(i, array_types) for i in variables):
from sympy.tensor.array.array_derivatives import ArrayDerivative
return ArrayDerivative(expr, *variables, **kwargs)
return Derivative(expr, *variables, **kwargs)
class Lambda(Expr):
"""
Lambda(x, expr) represents a lambda function similar to Python's
'lambda x: expr'. A function of several variables is written as
Lambda((x, y, ...), expr).
Examples
========
A simple example:
>>> from sympy import Lambda
>>> from sympy.abc import x
>>> f = Lambda(x, x**2)
>>> f(4)
16
For multivariate functions, use:
>>> from sympy.abc import y, z, t
>>> f2 = Lambda((x, y, z, t), x + y**z + t**z)
>>> f2(1, 2, 3, 4)
73
It is also possible to unpack tuple arguments:
>>> f = Lambda(((x, y), z), x + y + z)
>>> f((1, 2), 3)
6
A handy shortcut for lots of arguments:
>>> p = x, y, z
>>> f = Lambda(p, x + y*z)
>>> f(*p)
x + y*z
"""
is_Function = True
def __new__(cls, signature, expr):
if iterable(signature) and not isinstance(signature, (tuple, Tuple)):
sympy_deprecation_warning(
"""
Using a non-tuple iterable as the first argument to Lambda
is deprecated. Use Lambda(tuple(args), expr) instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-non-tuple-lambda",
)
signature = tuple(signature)
sig = signature if iterable(signature) else (signature,)
sig = sympify(sig)
cls._check_signature(sig)
if len(sig) == 1 and sig[0] == expr:
return S.IdentityFunction
return Expr.__new__(cls, sig, sympify(expr))
@classmethod
def _check_signature(cls, sig):
syms = set()
def rcheck(args):
for a in args:
if a.is_symbol:
if a in syms:
raise BadSignatureError("Duplicate symbol %s" % a)
syms.add(a)
elif isinstance(a, Tuple):
rcheck(a)
else:
raise BadSignatureError("Lambda signature should be only tuples"
" and symbols, not %s" % a)
if not isinstance(sig, Tuple):
raise BadSignatureError("Lambda signature should be a tuple not %s" % sig)
# Recurse through the signature:
rcheck(sig)
@property
def signature(self):
"""The expected form of the arguments to be unpacked into variables"""
return self._args[0]
@property
def expr(self):
"""The return value of the function"""
return self._args[1]
@property
def variables(self):
"""The variables used in the internal representation of the function"""
def _variables(args):
if isinstance(args, Tuple):
for arg in args:
yield from _variables(arg)
else:
yield args
return tuple(_variables(self.signature))
@property
def nargs(self):
from sympy.sets.sets import FiniteSet
return FiniteSet(len(self.signature))
bound_symbols = variables
@property
def free_symbols(self):
return self.expr.free_symbols - set(self.variables)
def __call__(self, *args):
n = len(args)
if n not in self.nargs: # Lambda only ever has 1 value in nargs
# XXX: exception message must be in exactly this format to
# make it work with NumPy's functions like vectorize(). See,
# for example, https://github.com/numpy/numpy/issues/1697.
# The ideal solution would be just to attach metadata to
# the exception and change NumPy to take advantage of this.
## XXX does this apply to Lambda? If not, remove this comment.
temp = ('%(name)s takes exactly %(args)s '
'argument%(plural)s (%(given)s given)')
raise BadArgumentsError(temp % {
'name': self,
'args': list(self.nargs)[0],
'plural': 's'*(list(self.nargs)[0] != 1),
'given': n})
d = self._match_signature(self.signature, args)
return self.expr.xreplace(d)
def _match_signature(self, sig, args):
symargmap = {}
def rmatch(pars, args):
for par, arg in zip(pars, args):
if par.is_symbol:
symargmap[par] = arg
elif isinstance(par, Tuple):
if not isinstance(arg, (tuple, Tuple)) or len(args) != len(pars):
raise BadArgumentsError("Can't match %s and %s" % (args, pars))
rmatch(par, arg)
rmatch(sig, args)
return symargmap
@property
def is_identity(self):
"""Return ``True`` if this ``Lambda`` is an identity function. """
return self.signature == self.expr
def _eval_evalf(self, prec):
return self.func(self.args[0], self.args[1].evalf(n=prec_to_dps(prec)))
class Subs(Expr):
"""
Represents unevaluated substitutions of an expression.
``Subs(expr, x, x0)`` represents the expression resulting
from substituting x with x0 in expr.
Parameters
==========
expr : Expr
An expression.
x : tuple, variable
A variable or list of distinct variables.
x0 : tuple or list of tuples
A point or list of evaluation points
corresponding to those variables.
Notes
=====
``Subs`` objects are generally useful to represent unevaluated derivatives
calculated at a point.
The variables may be expressions, but they are subjected to the limitations
of subs(), so it is usually a good practice to use only symbols for
variables, since in that case there can be no ambiguity.
There's no automatic expansion - use the method .doit() to effect all
possible substitutions of the object and also of objects inside the
expression.
When evaluating derivatives at a point that is not a symbol, a Subs object
is returned. One is also able to calculate derivatives of Subs objects - in
this case the expression is always expanded (for the unevaluated form, use
Derivative()).
Examples
========
>>> from sympy import Subs, Function, sin, cos
>>> from sympy.abc import x, y, z
>>> f = Function('f')
Subs are created when a particular substitution cannot be made. The
x in the derivative cannot be replaced with 0 because 0 is not a
valid variables of differentiation:
>>> f(x).diff(x).subs(x, 0)
Subs(Derivative(f(x), x), x, 0)
Once f is known, the derivative and evaluation at 0 can be done:
>>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0)
True
Subs can also be created directly with one or more variables:
>>> Subs(f(x)*sin(y) + z, (x, y), (0, 1))
Subs(z + f(x)*sin(y), (x, y), (0, 1))
>>> _.doit()
z + f(0)*sin(1)
Notes
=====
In order to allow expressions to combine before doit is done, a
representation of the Subs expression is used internally to make
expressions that are superficially different compare the same:
>>> a, b = Subs(x, x, 0), Subs(y, y, 0)
>>> a + b
2*Subs(x, x, 0)
This can lead to unexpected consequences when using methods
like `has` that are cached:
>>> s = Subs(x, x, 0)
>>> s.has(x), s.has(y)
(True, False)
>>> ss = s.subs(x, y)
>>> ss.has(x), ss.has(y)
(True, False)
>>> s, ss
(Subs(x, x, 0), Subs(y, y, 0))
"""
def __new__(cls, expr, variables, point, **assumptions):
if not is_sequence(variables, Tuple):
variables = [variables]
variables = Tuple(*variables)
if has_dups(variables):
repeated = [str(v) for v, i in Counter(variables).items() if i > 1]
__ = ', '.join(repeated)
raise ValueError(filldedent('''
The following expressions appear more than once: %s
''' % __))
point = Tuple(*(point if is_sequence(point, Tuple) else [point]))
if len(point) != len(variables):
raise ValueError('Number of point values must be the same as '
'the number of variables.')
if not point:
return sympify(expr)
# denest
if isinstance(expr, Subs):
variables = expr.variables + variables
point = expr.point + point
expr = expr.expr
else:
expr = sympify(expr)
# use symbols with names equal to the point value (with prepended _)
# to give a variable-independent expression
pre = "_"
pts = sorted(set(point), key=default_sort_key)
from sympy.printing.str import StrPrinter
class CustomStrPrinter(StrPrinter):
def _print_Dummy(self, expr):
return str(expr) + str(expr.dummy_index)
def mystr(expr, **settings):
p = CustomStrPrinter(settings)
return p.doprint(expr)
while 1:
s_pts = {p: Symbol(pre + mystr(p)) for p in pts}
reps = [(v, s_pts[p])
for v, p in zip(variables, point)]
# if any underscore-prepended symbol is already a free symbol
# and is a variable with a different point value, then there
# is a clash, e.g. _0 clashes in Subs(_0 + _1, (_0, _1), (1, 0))
# because the new symbol that would be created is _1 but _1
# is already mapped to 0 so __0 and __1 are used for the new
# symbols
if any(r in expr.free_symbols and
r in variables and
Symbol(pre + mystr(point[variables.index(r)])) != r
for _, r in reps):
pre += "_"
continue
break
obj = Expr.__new__(cls, expr, Tuple(*variables), point)
obj._expr = expr.xreplace(dict(reps))
return obj
def _eval_is_commutative(self):
return self.expr.is_commutative
def doit(self, **hints):
e, v, p = self.args
# remove self mappings
for i, (vi, pi) in enumerate(zip(v, p)):
if vi == pi:
v = v[:i] + v[i + 1:]
p = p[:i] + p[i + 1:]
if not v:
return self.expr
if isinstance(e, Derivative):
# apply functions first, e.g. f -> cos
undone = []
for i, vi in enumerate(v):
if isinstance(vi, FunctionClass):
e = e.subs(vi, p[i])
else:
undone.append((vi, p[i]))
if not isinstance(e, Derivative):
e = e.doit()
if isinstance(e, Derivative):
# do Subs that aren't related to differentiation
undone2 = []
D = Dummy()
arg = e.args[0]
for vi, pi in undone:
if D not in e.xreplace({vi: D}).free_symbols:
if arg.has(vi):
e = e.subs(vi, pi)
else:
undone2.append((vi, pi))
undone = undone2
# differentiate wrt variables that are present
wrt = []
D = Dummy()
expr = e.expr
free = expr.free_symbols
for vi, ci in e.variable_count:
if isinstance(vi, Symbol) and vi in free:
expr = expr.diff((vi, ci))
elif D in expr.subs(vi, D).free_symbols:
expr = expr.diff((vi, ci))
else:
wrt.append((vi, ci))
# inject remaining subs
rv = expr.subs(undone)
# do remaining differentiation *in order given*
for vc in wrt:
rv = rv.diff(vc)
else:
# inject remaining subs
rv = e.subs(undone)
else:
rv = e.doit(**hints).subs(list(zip(v, p)))
if hints.get('deep', True) and rv != self:
rv = rv.doit(**hints)
return rv
def evalf(self, prec=None, **options):
return self.doit().evalf(prec, **options)
n = evalf # type:ignore
@property
def variables(self):
"""The variables to be evaluated"""
return self._args[1]
bound_symbols = variables
@property
def expr(self):
"""The expression on which the substitution operates"""
return self._args[0]
@property
def point(self):
"""The values for which the variables are to be substituted"""
return self._args[2]
@property
def free_symbols(self):
return (self.expr.free_symbols - set(self.variables) |
set(self.point.free_symbols))
@property
def expr_free_symbols(self):
sympy_deprecation_warning("""
The expr_free_symbols property is deprecated. Use free_symbols to get
the free symbols of an expression.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-expr-free-symbols")
# Don't show the warning twice from the recursive call
with ignore_warnings(SymPyDeprecationWarning):
return (self.expr.expr_free_symbols - set(self.variables) |
set(self.point.expr_free_symbols))
def __eq__(self, other):
if not isinstance(other, Subs):
return False
return self._hashable_content() == other._hashable_content()
def __ne__(self, other):
return not(self == other)
def __hash__(self):
return super().__hash__()
def _hashable_content(self):
return (self._expr.xreplace(self.canonical_variables),
) + tuple(ordered([(v, p) for v, p in
zip(self.variables, self.point) if not self.expr.has(v)]))
def _eval_subs(self, old, new):
# Subs doit will do the variables in order; the semantics
# of subs for Subs is have the following invariant for
# Subs object foo:
# foo.doit().subs(reps) == foo.subs(reps).doit()
pt = list(self.point)
if old in self.variables:
if _atomic(new) == {new} and not any(
i.has(new) for i in self.args):
# the substitution is neutral
return self.xreplace({old: new})
# any occurrence of old before this point will get
# handled by replacements from here on
i = self.variables.index(old)
for j in range(i, len(self.variables)):
pt[j] = pt[j]._subs(old, new)
return self.func(self.expr, self.variables, pt)
v = [i._subs(old, new) for i in self.variables]
if v != list(self.variables):
return self.func(self.expr, self.variables + (old,), pt + [new])
expr = self.expr._subs(old, new)
pt = [i._subs(old, new) for i in self.point]
return self.func(expr, v, pt)
def _eval_derivative(self, s):
# Apply the chain rule of the derivative on the substitution variables:
f = self.expr
vp = V, P = self.variables, self.point
val = Add.fromiter(p.diff(s)*Subs(f.diff(v), *vp).doit()
for v, p in zip(V, P))
# these are all the free symbols in the expr
efree = f.free_symbols
# some symbols like IndexedBase include themselves and args
# as free symbols
compound = {i for i in efree if len(i.free_symbols) > 1}
# hide them and see what independent free symbols remain
dums = {Dummy() for i in compound}
masked = f.xreplace(dict(zip(compound, dums)))
ifree = masked.free_symbols - dums
# include the compound symbols
free = ifree | compound
# remove the variables already handled
free -= set(V)
# add back any free symbols of remaining compound symbols
free |= {i for j in free & compound for i in j.free_symbols}
# if symbols of s are in free then there is more to do
if free & s.free_symbols:
val += Subs(f.diff(s), self.variables, self.point).doit()
return val
def _eval_nseries(self, x, n, logx, cdir=0):
if x in self.point:
# x is the variable being substituted into
apos = self.point.index(x)
other = self.variables[apos]
else:
other = x
arg = self.expr.nseries(other, n=n, logx=logx)
o = arg.getO()
terms = Add.make_args(arg.removeO())
rv = Add(*[self.func(a, *self.args[1:]) for a in terms])
if o:
rv += o.subs(other, x)
return rv
def _eval_as_leading_term(self, x, logx=None, cdir=0):
if x in self.point:
ipos = self.point.index(x)
xvar = self.variables[ipos]
return self.expr.as_leading_term(xvar)
if x in self.variables:
# if `x` is a dummy variable, it means it won't exist after the
# substitution has been performed:
return self
# The variable is independent of the substitution:
return self.expr.as_leading_term(x)
def diff(f, *symbols, **kwargs):
"""
Differentiate f with respect to symbols.
Explanation
===========
This is just a wrapper to unify .diff() and the Derivative class; its
interface is similar to that of integrate(). You can use the same
shortcuts for multiple variables as with Derivative. For example,
diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative
of f(x).
You can pass evaluate=False to get an unevaluated Derivative class. Note
that if there are 0 symbols (such as diff(f(x), x, 0), then the result will
be the function (the zeroth derivative), even if evaluate=False.
Examples
========
>>> from sympy import sin, cos, Function, diff
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> diff(sin(x), x)
cos(x)
>>> diff(f(x), x, x, x)
Derivative(f(x), (x, 3))
>>> diff(f(x), x, 3)
Derivative(f(x), (x, 3))
>>> diff(sin(x)*cos(y), x, 2, y, 2)
sin(x)*cos(y)
>>> type(diff(sin(x), x))
cos
>>> type(diff(sin(x), x, evaluate=False))
<class 'sympy.core.function.Derivative'>
>>> type(diff(sin(x), x, 0))
sin
>>> type(diff(sin(x), x, 0, evaluate=False))
sin
>>> diff(sin(x))
cos(x)
>>> diff(sin(x*y))
Traceback (most recent call last):
...
ValueError: specify differentiation variables to differentiate sin(x*y)
Note that ``diff(sin(x))`` syntax is meant only for convenience
in interactive sessions and should be avoided in library code.
References
==========
.. [1] http://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html
See Also
========
Derivative
idiff: computes the derivative implicitly
"""
if hasattr(f, 'diff'):
return f.diff(*symbols, **kwargs)
kwargs.setdefault('evaluate', True)
return _derivative_dispatch(f, *symbols, **kwargs)
def expand(e, deep=True, modulus=None, power_base=True, power_exp=True,
mul=True, log=True, multinomial=True, basic=True, **hints):
r"""
Expand an expression using methods given as hints.
Explanation
===========
Hints evaluated unless explicitly set to False are: ``basic``, ``log``,
``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following
hints are supported but not applied unless set to True: ``complex``,
``func``, and ``trig``. In addition, the following meta-hints are
supported by some or all of the other hints: ``frac``, ``numer``,
``denom``, ``modulus``, and ``force``. ``deep`` is supported by all
hints. Additionally, subclasses of Expr may define their own hints or
meta-hints.
The ``basic`` hint is used for any special rewriting of an object that
should be done automatically (along with the other hints like ``mul``)
when expand is called. This is a catch-all hint to handle any sort of
expansion that may not be described by the existing hint names. To use
this hint an object should override the ``_eval_expand_basic`` method.
Objects may also define their own expand methods, which are not run by
default. See the API section below.
If ``deep`` is set to ``True`` (the default), things like arguments of
functions are recursively expanded. Use ``deep=False`` to only expand on
the top level.
If the ``force`` hint is used, assumptions about variables will be ignored
in making the expansion.
Hints
=====
These hints are run by default
mul
---
Distributes multiplication over addition:
>>> from sympy import cos, exp, sin
>>> from sympy.abc import x, y, z
>>> (y*(x + z)).expand(mul=True)
x*y + y*z
multinomial
-----------
Expand (x + y + ...)**n where n is a positive integer.
>>> ((x + y + z)**2).expand(multinomial=True)
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
power_exp
---------
Expand addition in exponents into multiplied bases.
>>> exp(x + y).expand(power_exp=True)
exp(x)*exp(y)
>>> (2**(x + y)).expand(power_exp=True)
2**x*2**y
power_base
----------
Split powers of multiplied bases.
This only happens by default if assumptions allow, or if the
``force`` meta-hint is used:
>>> ((x*y)**z).expand(power_base=True)
(x*y)**z
>>> ((x*y)**z).expand(power_base=True, force=True)
x**z*y**z
>>> ((2*y)**z).expand(power_base=True)
2**z*y**z
Note that in some cases where this expansion always holds, SymPy performs
it automatically:
>>> (x*y)**2
x**2*y**2
log
---
Pull out power of an argument as a coefficient and split logs products
into sums of logs.
Note that these only work if the arguments of the log function have the
proper assumptions--the arguments must be positive and the exponents must
be real--or else the ``force`` hint must be True:
>>> from sympy import log, symbols
>>> log(x**2*y).expand(log=True)
log(x**2*y)
>>> log(x**2*y).expand(log=True, force=True)
2*log(x) + log(y)
>>> x, y = symbols('x,y', positive=True)
>>> log(x**2*y).expand(log=True)
2*log(x) + log(y)
basic
-----
This hint is intended primarily as a way for custom subclasses to enable
expansion by default.
These hints are not run by default:
complex
-------
Split an expression into real and imaginary parts.
>>> x, y = symbols('x,y')
>>> (x + y).expand(complex=True)
re(x) + re(y) + I*im(x) + I*im(y)
>>> cos(x).expand(complex=True)
-I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))
Note that this is just a wrapper around ``as_real_imag()``. Most objects
that wish to redefine ``_eval_expand_complex()`` should consider
redefining ``as_real_imag()`` instead.
func
----
Expand other functions.
>>> from sympy import gamma
>>> gamma(x + 1).expand(func=True)
x*gamma(x)
trig
----
Do trigonometric expansions.
>>> cos(x + y).expand(trig=True)
-sin(x)*sin(y) + cos(x)*cos(y)
>>> sin(2*x).expand(trig=True)
2*sin(x)*cos(x)
Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)``
and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x)
= 1`. The current implementation uses the form obtained from Chebyshev
polynomials, but this may change. See `this MathWorld article
<http://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more
information.
Notes
=====
- You can shut off unwanted methods::
>>> (exp(x + y)*(x + y)).expand()
x*exp(x)*exp(y) + y*exp(x)*exp(y)
>>> (exp(x + y)*(x + y)).expand(power_exp=False)
x*exp(x + y) + y*exp(x + y)
>>> (exp(x + y)*(x + y)).expand(mul=False)
(x + y)*exp(x)*exp(y)
- Use deep=False to only expand on the top level::
>>> exp(x + exp(x + y)).expand()
exp(x)*exp(exp(x)*exp(y))
>>> exp(x + exp(x + y)).expand(deep=False)
exp(x)*exp(exp(x + y))
- Hints are applied in an arbitrary, but consistent order (in the current
implementation, they are applied in alphabetical order, except
multinomial comes before mul, but this may change). Because of this,
some hints may prevent expansion by other hints if they are applied
first. For example, ``mul`` may distribute multiplications and prevent
``log`` and ``power_base`` from expanding them. Also, if ``mul`` is
applied before ``multinomial`, the expression might not be fully
distributed. The solution is to use the various ``expand_hint`` helper
functions or to use ``hint=False`` to this function to finely control
which hints are applied. Here are some examples::
>>> from sympy import expand, expand_mul, expand_power_base
>>> x, y, z = symbols('x,y,z', positive=True)
>>> expand(log(x*(y + z)))
log(x) + log(y + z)
Here, we see that ``log`` was applied before ``mul``. To get the mul
expanded form, either of the following will work::
>>> expand_mul(log(x*(y + z)))
log(x*y + x*z)
>>> expand(log(x*(y + z)), log=False)
log(x*y + x*z)
A similar thing can happen with the ``power_base`` hint::
>>> expand((x*(y + z))**x)
(x*y + x*z)**x
To get the ``power_base`` expanded form, either of the following will
work::
>>> expand((x*(y + z))**x, mul=False)
x**x*(y + z)**x
>>> expand_power_base((x*(y + z))**x)
x**x*(y + z)**x
>>> expand((x + y)*y/x)
y + y**2/x
The parts of a rational expression can be targeted::
>>> expand((x + y)*y/x/(x + 1), frac=True)
(x*y + y**2)/(x**2 + x)
>>> expand((x + y)*y/x/(x + 1), numer=True)
(x*y + y**2)/(x*(x + 1))
>>> expand((x + y)*y/x/(x + 1), denom=True)
y*(x + y)/(x**2 + x)
- The ``modulus`` meta-hint can be used to reduce the coefficients of an
expression post-expansion::
>>> expand((3*x + 1)**2)
9*x**2 + 6*x + 1
>>> expand((3*x + 1)**2, modulus=5)
4*x**2 + x + 1
- Either ``expand()`` the function or ``.expand()`` the method can be
used. Both are equivalent::
>>> expand((x + 1)**2)
x**2 + 2*x + 1
>>> ((x + 1)**2).expand()
x**2 + 2*x + 1
API
===
Objects can define their own expand hints by defining
``_eval_expand_hint()``. The function should take the form::
def _eval_expand_hint(self, **hints):
# Only apply the method to the top-level expression
...
See also the example below. Objects should define ``_eval_expand_hint()``
methods only if ``hint`` applies to that specific object. The generic
``_eval_expand_hint()`` method defined in Expr will handle the no-op case.
Each hint should be responsible for expanding that hint only.
Furthermore, the expansion should be applied to the top-level expression
only. ``expand()`` takes care of the recursion that happens when
``deep=True``.
You should only call ``_eval_expand_hint()`` methods directly if you are
100% sure that the object has the method, as otherwise you are liable to
get unexpected ``AttributeError``s. Note, again, that you do not need to
recursively apply the hint to args of your object: this is handled
automatically by ``expand()``. ``_eval_expand_hint()`` should
generally not be used at all outside of an ``_eval_expand_hint()`` method.
If you want to apply a specific expansion from within another method, use
the public ``expand()`` function, method, or ``expand_hint()`` functions.
In order for expand to work, objects must be rebuildable by their args,
i.e., ``obj.func(*obj.args) == obj`` must hold.
Expand methods are passed ``**hints`` so that expand hints may use
'metahints'--hints that control how different expand methods are applied.
For example, the ``force=True`` hint described above that causes
``expand(log=True)`` to ignore assumptions is such a metahint. The
``deep`` meta-hint is handled exclusively by ``expand()`` and is not
passed to ``_eval_expand_hint()`` methods.
Note that expansion hints should generally be methods that perform some
kind of 'expansion'. For hints that simply rewrite an expression, use the
.rewrite() API.
Examples
========
>>> from sympy import Expr, sympify
>>> class MyClass(Expr):
... def __new__(cls, *args):
... args = sympify(args)
... return Expr.__new__(cls, *args)
...
... def _eval_expand_double(self, *, force=False, **hints):
... '''
... Doubles the args of MyClass.
...
... If there more than four args, doubling is not performed,
... unless force=True is also used (False by default).
... '''
... if not force and len(self.args) > 4:
... return self
... return self.func(*(self.args + self.args))
...
>>> a = MyClass(1, 2, MyClass(3, 4))
>>> a
MyClass(1, 2, MyClass(3, 4))
>>> a.expand(double=True)
MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4))
>>> a.expand(double=True, deep=False)
MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))
>>> b = MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True)
MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True, force=True)
MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
See Also
========
expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig,
expand_power_base, expand_power_exp, expand_func, sympy.simplify.hyperexpand.hyperexpand
"""
# don't modify this; modify the Expr.expand method
hints['power_base'] = power_base
hints['power_exp'] = power_exp
hints['mul'] = mul
hints['log'] = log
hints['multinomial'] = multinomial
hints['basic'] = basic
return sympify(e).expand(deep=deep, modulus=modulus, **hints)
# This is a special application of two hints
def _mexpand(expr, recursive=False):
# expand multinomials and then expand products; this may not always
# be sufficient to give a fully expanded expression (see
# test_issue_8247_8354 in test_arit)
if expr is None:
return
was = None
while was != expr:
was, expr = expr, expand_mul(expand_multinomial(expr))
if not recursive:
break
return expr
# These are simple wrappers around single hints.
def expand_mul(expr, deep=True):
"""
Wrapper around expand that only uses the mul hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import symbols, expand_mul, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_mul(exp(x+y)*(x+y)*log(x*y**2))
x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)
"""
return sympify(expr).expand(deep=deep, mul=True, power_exp=False,
power_base=False, basic=False, multinomial=False, log=False)
def expand_multinomial(expr, deep=True):
"""
Wrapper around expand that only uses the multinomial hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import symbols, expand_multinomial, exp
>>> x, y = symbols('x y', positive=True)
>>> expand_multinomial((x + exp(x + 1))**2)
x**2 + 2*x*exp(x + 1) + exp(2*x + 2)
"""
return sympify(expr).expand(deep=deep, mul=False, power_exp=False,
power_base=False, basic=False, multinomial=True, log=False)
def expand_log(expr, deep=True, force=False, factor=False):
"""
Wrapper around expand that only uses the log hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import symbols, expand_log, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
(x + y)*(log(x) + 2*log(y))*exp(x + y)
"""
from sympy.functions.elementary.exponential import log
if factor is False:
def _handle(x):
x1 = expand_mul(expand_log(x, deep=deep, force=force, factor=True))
if x1.count(log) <= x.count(log):
return x1
return x
expr = expr.replace(
lambda x: x.is_Mul and all(any(isinstance(i, log) and i.args[0].is_Rational
for i in Mul.make_args(j)) for j in x.as_numer_denom()),
_handle)
return sympify(expr).expand(deep=deep, log=True, mul=False,
power_exp=False, power_base=False, multinomial=False,
basic=False, force=force, factor=factor)
def expand_func(expr, deep=True):
"""
Wrapper around expand that only uses the func hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import expand_func, gamma
>>> from sympy.abc import x
>>> expand_func(gamma(x + 2))
x*(x + 1)*gamma(x)
"""
return sympify(expr).expand(deep=deep, func=True, basic=False,
log=False, mul=False, power_exp=False, power_base=False, multinomial=False)
def expand_trig(expr, deep=True):
"""
Wrapper around expand that only uses the trig hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import expand_trig, sin
>>> from sympy.abc import x, y
>>> expand_trig(sin(x+y)*(x+y))
(x + y)*(sin(x)*cos(y) + sin(y)*cos(x))
"""
return sympify(expr).expand(deep=deep, trig=True, basic=False,
log=False, mul=False, power_exp=False, power_base=False, multinomial=False)
def expand_complex(expr, deep=True):
"""
Wrapper around expand that only uses the complex hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import expand_complex, exp, sqrt, I
>>> from sympy.abc import z
>>> expand_complex(exp(z))
I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z))
>>> expand_complex(sqrt(I))
sqrt(2)/2 + sqrt(2)*I/2
See Also
========
sympy.core.expr.Expr.as_real_imag
"""
return sympify(expr).expand(deep=deep, complex=True, basic=False,
log=False, mul=False, power_exp=False, power_base=False, multinomial=False)
def expand_power_base(expr, deep=True, force=False):
"""
Wrapper around expand that only uses the power_base hint.
A wrapper to expand(power_base=True) which separates a power with a base
that is a Mul into a product of powers, without performing any other
expansions, provided that assumptions about the power's base and exponent
allow.
deep=False (default is True) will only apply to the top-level expression.
force=True (default is False) will cause the expansion to ignore
assumptions about the base and exponent. When False, the expansion will
only happen if the base is non-negative or the exponent is an integer.
>>> from sympy.abc import x, y, z
>>> from sympy import expand_power_base, sin, cos, exp, Symbol
>>> (x*y)**2
x**2*y**2
>>> (2*x)**y
(2*x)**y
>>> expand_power_base(_)
2**y*x**y
>>> expand_power_base((x*y)**z)
(x*y)**z
>>> expand_power_base((x*y)**z, force=True)
x**z*y**z
>>> expand_power_base(sin((x*y)**z), deep=False)
sin((x*y)**z)
>>> expand_power_base(sin((x*y)**z), force=True)
sin(x**z*y**z)
>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y)
2**y*sin(x)**y + 2**y*cos(x)**y
>>> expand_power_base((2*exp(y))**x)
2**x*exp(y)**x
>>> expand_power_base((2*cos(x))**y)
2**y*cos(x)**y
Notice that sums are left untouched. If this is not the desired behavior,
apply full ``expand()`` to the expression:
>>> expand_power_base(((x+y)*z)**2)
z**2*(x + y)**2
>>> (((x+y)*z)**2).expand()
x**2*z**2 + 2*x*y*z**2 + y**2*z**2
>>> expand_power_base((2*y)**(1+z))
2**(z + 1)*y**(z + 1)
>>> ((2*y)**(1+z)).expand()
2*2**z*y**(z + 1)
The power that is unexpanded can be expanded safely when
``y != 0``, otherwise different values might be obtained for the expression:
>>> prev = _
If we indicate that ``y`` is positive but then replace it with
a value of 0 after expansion, the expression becomes 0:
>>> p = Symbol('p', positive=True)
>>> prev.subs(y, p).expand().subs(p, 0)
0
But if ``z = -1`` the expression would not be zero:
>>> prev.subs(y, 0).subs(z, -1)
1
See Also
========
expand
"""
return sympify(expr).expand(deep=deep, log=False, mul=False,
power_exp=False, power_base=True, multinomial=False,
basic=False, force=force)
def expand_power_exp(expr, deep=True):
"""
Wrapper around expand that only uses the power_exp hint.
See the expand docstring for more information.
Examples
========
>>> from sympy import expand_power_exp, Symbol
>>> from sympy.abc import x, y
>>> expand_power_exp(3**(y + 2))
9*3**y
>>> expand_power_exp(x**(y + 2))
x**(y + 2)
If ``x = 0`` the value of the expression depends on the
value of ``y``; if the expression were expanded the result
would be 0. So expansion is only done if ``x != 0``:
>>> expand_power_exp(Symbol('x', zero=False)**(y + 2))
x**2*x**y
"""
return sympify(expr).expand(deep=deep, complex=False, basic=False,
log=False, mul=False, power_exp=True, power_base=False, multinomial=False)
def count_ops(expr, visual=False):
"""
Return a representation (integer or expression) of the operations in expr.
Parameters
==========
expr : Expr
If expr is an iterable, the sum of the op counts of the
items will be returned.
visual : bool, optional
If ``False`` (default) then the sum of the coefficients of the
visual expression will be returned.
If ``True`` then the number of each type of operation is shown
with the core class types (or their virtual equivalent) multiplied by the
number of times they occur.
Examples
========
>>> from sympy.abc import a, b, x, y
>>> from sympy import sin, count_ops
Although there is not a SUB object, minus signs are interpreted as
either negations or subtractions:
>>> (x - y).count_ops(visual=True)
SUB
>>> (-x).count_ops(visual=True)
NEG
Here, there are two Adds and a Pow:
>>> (1 + a + b**2).count_ops(visual=True)
2*ADD + POW
In the following, an Add, Mul, Pow and two functions:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=True)
ADD + MUL + POW + 2*SIN
for a total of 5:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=False)
5
Note that "what you type" is not always what you get. The expression
1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather
than two DIVs:
>>> (1/x/y).count_ops(visual=True)
DIV + MUL
The visual option can be used to demonstrate the difference in
operations for expressions in different forms. Here, the Horner
representation is compared with the expanded form of a polynomial:
>>> eq=x*(1 + x*(2 + x*(3 + x)))
>>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True)
-MUL + 3*POW
The count_ops function also handles iterables:
>>> count_ops([x, sin(x), None, True, x + 2], visual=False)
2
>>> count_ops([x, sin(x), None, True, x + 2], visual=True)
ADD + SIN
>>> count_ops({x: sin(x), x + 2: y + 1}, visual=True)
2*ADD + SIN
"""
from .relational import Relational
from sympy.concrete.summations import Sum
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import BooleanFunction
from sympy.simplify.radsimp import fraction
expr = sympify(expr)
if isinstance(expr, Expr) and not expr.is_Relational:
ops = []
args = [expr]
NEG = Symbol('NEG')
DIV = Symbol('DIV')
SUB = Symbol('SUB')
ADD = Symbol('ADD')
EXP = Symbol('EXP')
while args:
a = args.pop()
# if the following fails because the object is
# not Basic type, then the object should be fixed
# since it is the intention that all args of Basic
# should themselves be Basic
if a.is_Rational:
#-1/3 = NEG + DIV
if a is not S.One:
if a.p < 0:
ops.append(NEG)
if a.q != 1:
ops.append(DIV)
continue
elif a.is_Mul or a.is_MatMul:
if _coeff_isneg(a):
ops.append(NEG)
if a.args[0] is S.NegativeOne:
a = a.as_two_terms()[1]
else:
a = -a
n, d = fraction(a)
if n.is_Integer:
ops.append(DIV)
if n < 0:
ops.append(NEG)
args.append(d)
continue # won't be -Mul but could be Add
elif d is not S.One:
if not d.is_Integer:
args.append(d)
ops.append(DIV)
args.append(n)
continue # could be -Mul
elif a.is_Add or a.is_MatAdd:
aargs = list(a.args)
negs = 0
for i, ai in enumerate(aargs):
if _coeff_isneg(ai):
negs += 1
args.append(-ai)
if i > 0:
ops.append(SUB)
else:
args.append(ai)
if i > 0:
ops.append(ADD)
if negs == len(aargs): # -x - y = NEG + SUB
ops.append(NEG)
elif _coeff_isneg(aargs[0]): # -x + y = SUB, but already recorded ADD
ops.append(SUB - ADD)
continue
if a.is_Pow and a.exp is S.NegativeOne:
ops.append(DIV)
args.append(a.base) # won't be -Mul but could be Add
continue
if a == S.Exp1:
ops.append(EXP)
continue
if a.is_Pow and a.base == S.Exp1:
ops.append(EXP)
args.append(a.exp)
continue
if a.is_Mul or isinstance(a, LatticeOp):
o = Symbol(a.func.__name__.upper())
# count the args
ops.append(o*(len(a.args) - 1))
elif a.args and (
a.is_Pow or
a.is_Function or
isinstance(a, Derivative) or
isinstance(a, Integral) or
isinstance(a, Sum)):
# if it's not in the list above we don't
# consider a.func something to count, e.g.
# Tuple, MatrixSymbol, etc...
if isinstance(a.func, UndefinedFunction):
o = Symbol("FUNC_" + a.func.__name__.upper())
else:
o = Symbol(a.func.__name__.upper())
ops.append(o)
if not a.is_Symbol:
args.extend(a.args)
elif isinstance(expr, Dict):
ops = [count_ops(k, visual=visual) +
count_ops(v, visual=visual) for k, v in expr.items()]
elif iterable(expr):
ops = [count_ops(i, visual=visual) for i in expr]
elif isinstance(expr, (Relational, BooleanFunction)):
ops = []
for arg in expr.args:
ops.append(count_ops(arg, visual=True))
o = Symbol(func_name(expr, short=True).upper())
ops.append(o)
elif not isinstance(expr, Basic):
ops = []
else: # it's Basic not isinstance(expr, Expr):
if not isinstance(expr, Basic):
raise TypeError("Invalid type of expr")
else:
ops = []
args = [expr]
while args:
a = args.pop()
if a.args:
o = Symbol(type(a).__name__.upper())
if a.is_Boolean:
ops.append(o*(len(a.args)-1))
else:
ops.append(o)
args.extend(a.args)
if not ops:
if visual:
return S.Zero
return 0
ops = Add(*ops)
if visual:
return ops
if ops.is_Number:
return int(ops)
return sum(int((a.args or [1])[0]) for a in Add.make_args(ops))
def nfloat(expr, n=15, exponent=False, dkeys=False):
"""Make all Rationals in expr Floats except those in exponents
(unless the exponents flag is set to True) and those in undefined
functions. When processing dictionaries, do not modify the keys
unless ``dkeys=True``.
Examples
========
>>> from sympy import nfloat, cos, pi, sqrt
>>> from sympy.abc import x, y
>>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y))
x**4 + 0.5*x + sqrt(y) + 1.5
>>> nfloat(x**4 + sqrt(y), exponent=True)
x**4.0 + y**0.5
Container types are not modified:
>>> type(nfloat((1, 2))) is tuple
True
"""
from sympy.matrices.matrices import MatrixBase
kw = dict(n=n, exponent=exponent, dkeys=dkeys)
if isinstance(expr, MatrixBase):
return expr.applyfunc(lambda e: nfloat(e, **kw))
# handling of iterable containers
if iterable(expr, exclude=str):
if isinstance(expr, (dict, Dict)):
if dkeys:
args = [tuple(map(lambda i: nfloat(i, **kw), a))
for a in expr.items()]
else:
args = [(k, nfloat(v, **kw)) for k, v in expr.items()]
if isinstance(expr, dict):
return type(expr)(args)
else:
return expr.func(*args)
elif isinstance(expr, Basic):
return expr.func(*[nfloat(a, **kw) for a in expr.args])
return type(expr)([nfloat(a, **kw) for a in expr])
rv = sympify(expr)
if rv.is_Number:
return Float(rv, n)
elif rv.is_number:
# evalf doesn't always set the precision
rv = rv.n(n)
if rv.is_Number:
rv = Float(rv.n(n), n)
else:
pass # pure_complex(rv) is likely True
return rv
elif rv.is_Atom:
return rv
elif rv.is_Relational:
args_nfloat = (nfloat(arg, **kw) for arg in rv.args)
return rv.func(*args_nfloat)
# watch out for RootOf instances that don't like to have
# their exponents replaced with Dummies and also sometimes have
# problems with evaluating at low precision (issue 6393)
from sympy.polys.rootoftools import RootOf
rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)})
from .power import Pow
if not exponent:
reps = [(p, Pow(p.base, Dummy())) for p in rv.atoms(Pow)]
rv = rv.xreplace(dict(reps))
rv = rv.n(n)
if not exponent:
rv = rv.xreplace({d.exp: p.exp for p, d in reps})
else:
# Pow._eval_evalf special cases Integer exponents so if
# exponent is suppose to be handled we have to do so here
rv = rv.xreplace(Transform(
lambda x: Pow(x.base, Float(x.exp, n)),
lambda x: x.is_Pow and x.exp.is_Integer))
return rv.xreplace(Transform(
lambda x: x.func(*nfloat(x.args, n, exponent)),
lambda x: isinstance(x, Function) and not isinstance(x, AppliedUndef)))
from .symbol import Dummy, Symbol
|
7f3a5871a02ae58caee232e54b44475c2837be3fbd8b543dedc0e62477f3d7fc | from typing import Tuple as tTuple
from collections import defaultdict
from functools import cmp_to_key, reduce
from operator import attrgetter
from .basic import Basic
from .parameters import global_parameters
from .logic import _fuzzy_group, fuzzy_or, fuzzy_not
from .singleton import S
from .operations import AssocOp, AssocOpDispatcher
from .cache import cacheit
from .numbers import ilcm, igcd
from .expr import Expr
from .kind import UndefinedKind
from sympy.utilities.iterables import is_sequence, sift
# Key for sorting commutative args in canonical order
_args_sortkey = cmp_to_key(Basic.compare)
def _could_extract_minus_sign(expr):
# assume expr is Add-like
# We choose the one with less arguments with minus signs
negative_args = sum(1 for i in expr.args
if i.could_extract_minus_sign())
positive_args = len(expr.args) - negative_args
if positive_args > negative_args:
return False
elif positive_args < negative_args:
return True
# choose based on .sort_key() to prefer
# x - 1 instead of 1 - x and
# 3 - sqrt(2) instead of -3 + sqrt(2)
return bool(expr.sort_key() < (-expr).sort_key())
def _addsort(args):
# in-place sorting of args
args.sort(key=_args_sortkey)
def _unevaluated_Add(*args):
"""Return a well-formed unevaluated Add: Numbers are collected and
put in slot 0 and args are sorted. Use this when args have changed
but you still want to return an unevaluated Add.
Examples
========
>>> from sympy.core.add import _unevaluated_Add as uAdd
>>> from sympy import S, Add
>>> from sympy.abc import x, y
>>> a = uAdd(*[S(1.0), x, S(2)])
>>> a.args[0]
3.00000000000000
>>> a.args[1]
x
Beyond the Number being in slot 0, there is no other assurance of
order for the arguments since they are hash sorted. So, for testing
purposes, output produced by this in some other function can only
be tested against the output of this function or as one of several
options:
>>> opts = (Add(x, y, evaluate=False), Add(y, x, evaluate=False))
>>> a = uAdd(x, y)
>>> assert a in opts and a == uAdd(x, y)
>>> uAdd(x + 1, x + 2)
x + x + 3
"""
args = list(args)
newargs = []
co = S.Zero
while args:
a = args.pop()
if a.is_Add:
# this will keep nesting from building up
# so that x + (x + 1) -> x + x + 1 (3 args)
args.extend(a.args)
elif a.is_Number:
co += a
else:
newargs.append(a)
_addsort(newargs)
if co:
newargs.insert(0, co)
return Add._from_args(newargs)
class Add(Expr, AssocOp):
"""
Expression representing addition operation for algebraic group.
.. deprecated:: 1.7
Using arguments that aren't subclasses of :class:`~.Expr` in core
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
deprecated. See :ref:`non-expr-args-deprecated` for details.
Every argument of ``Add()`` must be ``Expr``. Infix operator ``+``
on most scalar objects in SymPy calls this class.
Another use of ``Add()`` is to represent the structure of abstract
addition so that its arguments can be substituted to return different
class. Refer to examples section for this.
``Add()`` evaluates the argument unless ``evaluate=False`` is passed.
The evaluation logic includes:
1. Flattening
``Add(x, Add(y, z))`` -> ``Add(x, y, z)``
2. Identity removing
``Add(x, 0, y)`` -> ``Add(x, y)``
3. Coefficient collecting by ``.as_coeff_Mul()``
``Add(x, 2*x)`` -> ``Mul(3, x)``
4. Term sorting
``Add(y, x, 2)`` -> ``Add(2, x, y)``
If no argument is passed, identity element 0 is returned. If single
element is passed, that element is returned.
Note that ``Add(*args)`` is more efficient than ``sum(args)`` because
it flattens the arguments. ``sum(a, b, c, ...)`` recursively adds the
arguments as ``a + (b + (c + ...))``, which has quadratic complexity.
On the other hand, ``Add(a, b, c, d)`` does not assume nested
structure, making the complexity linear.
Since addition is group operation, every argument should have the
same :obj:`sympy.core.kind.Kind()`.
Examples
========
>>> from sympy import Add, I
>>> from sympy.abc import x, y
>>> Add(x, 1)
x + 1
>>> Add(x, x)
2*x
>>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1
2*x**2 + 17*x/5 + 3.0*y + I*y + 1
If ``evaluate=False`` is passed, result is not evaluated.
>>> Add(1, 2, evaluate=False)
1 + 2
>>> Add(x, x, evaluate=False)
x + x
``Add()`` also represents the general structure of addition operation.
>>> from sympy import MatrixSymbol
>>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2)
>>> expr = Add(x,y).subs({x:A, y:B})
>>> expr
A + B
>>> type(expr)
<class 'sympy.matrices.expressions.matadd.MatAdd'>
Note that the printers do not display in args order.
>>> Add(x, 1)
x + 1
>>> Add(x, 1).args
(1, x)
See Also
========
MatAdd
"""
__slots__ = ()
args: tTuple[Expr, ...]
is_Add = True
_args_type = Expr
@classmethod
def flatten(cls, seq):
"""
Takes the sequence "seq" of nested Adds and returns a flatten list.
Returns: (commutative_part, noncommutative_part, order_symbols)
Applies associativity, all terms are commutable with respect to
addition.
NB: the removal of 0 is already handled by AssocOp.__new__
See also
========
sympy.core.mul.Mul.flatten
"""
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.matrices.expressions import MatrixExpr
from sympy.tensor.tensor import TensExpr
rv = None
if len(seq) == 2:
a, b = seq
if b.is_Rational:
a, b = b, a
if a.is_Rational:
if b.is_Mul:
rv = [a, b], [], None
if rv:
if all(s.is_commutative for s in rv[0]):
return rv
return [], rv[0], None
terms = {} # term -> coeff
# e.g. x**2 -> 5 for ... + 5*x**2 + ...
coeff = S.Zero # coefficient (Number or zoo) to always be in slot 0
# e.g. 3 + ...
order_factors = []
extra = []
for o in seq:
# O(x)
if o.is_Order:
if o.expr.is_zero:
continue
for o1 in order_factors:
if o1.contains(o):
o = None
break
if o is None:
continue
order_factors = [o] + [
o1 for o1 in order_factors if not o.contains(o1)]
continue
# 3 or NaN
elif o.is_Number:
if (o is S.NaN or coeff is S.ComplexInfinity and
o.is_finite is False) and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
if coeff.is_Number or isinstance(coeff, AccumBounds):
coeff += o
if coeff is S.NaN and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
continue
elif isinstance(o, AccumBounds):
coeff = o.__add__(coeff)
continue
elif isinstance(o, MatrixExpr):
# can't add 0 to Matrix so make sure coeff is not 0
extra.append(o)
continue
elif isinstance(o, TensExpr):
coeff = o.__add__(coeff) if coeff else o
continue
elif o is S.ComplexInfinity:
if coeff.is_finite is False and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
coeff = S.ComplexInfinity
continue
# Add([...])
elif o.is_Add:
# NB: here we assume Add is always commutative
seq.extend(o.args) # TODO zerocopy?
continue
# Mul([...])
elif o.is_Mul:
c, s = o.as_coeff_Mul()
# check for unevaluated Pow, e.g. 2**3 or 2**(-1/2)
elif o.is_Pow:
b, e = o.as_base_exp()
if b.is_Number and (e.is_Integer or
(e.is_Rational and e.is_negative)):
seq.append(b**e)
continue
c, s = S.One, o
else:
# everything else
c = S.One
s = o
# now we have:
# o = c*s, where
#
# c is a Number
# s is an expression with number factor extracted
# let's collect terms with the same s, so e.g.
# 2*x**2 + 3*x**2 -> 5*x**2
if s in terms:
terms[s] += c
if terms[s] is S.NaN and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
else:
terms[s] = c
# now let's construct new args:
# [2*x**2, x**3, 7*x**4, pi, ...]
newseq = []
noncommutative = False
for s, c in terms.items():
# 0*s
if c.is_zero:
continue
# 1*s
elif c is S.One:
newseq.append(s)
# c*s
else:
if s.is_Mul:
# Mul, already keeps its arguments in perfect order.
# so we can simply put c in slot0 and go the fast way.
cs = s._new_rawargs(*((c,) + s.args))
newseq.append(cs)
elif s.is_Add:
# we just re-create the unevaluated Mul
newseq.append(Mul(c, s, evaluate=False))
else:
# alternatively we have to call all Mul's machinery (slow)
newseq.append(Mul(c, s))
noncommutative = noncommutative or not s.is_commutative
# oo, -oo
if coeff is S.Infinity:
newseq = [f for f in newseq if not (f.is_extended_nonnegative or f.is_real)]
elif coeff is S.NegativeInfinity:
newseq = [f for f in newseq if not (f.is_extended_nonpositive or f.is_real)]
if coeff is S.ComplexInfinity:
# zoo might be
# infinite_real + finite_im
# finite_real + infinite_im
# infinite_real + infinite_im
# addition of a finite real or imaginary number won't be able to
# change the zoo nature; adding an infinite qualtity would result
# in a NaN condition if it had sign opposite of the infinite
# portion of zoo, e.g., infinite_real - infinite_real.
newseq = [c for c in newseq if not (c.is_finite and
c.is_extended_real is not None)]
# process O(x)
if order_factors:
newseq2 = []
for t in newseq:
for o in order_factors:
# x + O(x) -> O(x)
if o.contains(t):
t = None
break
# x + O(x**2) -> x + O(x**2)
if t is not None:
newseq2.append(t)
newseq = newseq2 + order_factors
# 1 + O(1) -> O(1)
for o in order_factors:
if o.contains(coeff):
coeff = S.Zero
break
# order args canonically
_addsort(newseq)
# current code expects coeff to be first
if coeff is not S.Zero:
newseq.insert(0, coeff)
if extra:
newseq += extra
noncommutative = True
# we are done
if noncommutative:
return [], newseq, None
else:
return newseq, [], None
@classmethod
def class_key(cls):
"""Nice order of classes"""
return 3, 1, cls.__name__
@property
def kind(self):
k = attrgetter('kind')
kinds = map(k, self.args)
kinds = frozenset(kinds)
if len(kinds) != 1:
# Since addition is group operator, kind must be same.
# We know that this is unexpected signature, so return this.
result = UndefinedKind
else:
result, = kinds
return result
def could_extract_minus_sign(self):
return _could_extract_minus_sign(self)
@cacheit
def as_coeff_add(self, *deps):
"""
Returns a tuple (coeff, args) where self is treated as an Add and coeff
is the Number term and args is a tuple of all other terms.
Examples
========
>>> from sympy.abc import x
>>> (7 + 3*x).as_coeff_add()
(7, (3*x,))
>>> (7*x).as_coeff_add()
(0, (7*x,))
"""
if deps:
l1, l2 = sift(self.args, lambda x: x.has_free(*deps), binary=True)
return self._new_rawargs(*l2), tuple(l1)
coeff, notrat = self.args[0].as_coeff_add()
if coeff is not S.Zero:
return coeff, notrat + self.args[1:]
return S.Zero, self.args
def as_coeff_Add(self, rational=False, deps=None):
"""
Efficiently extract the coefficient of a summation.
"""
coeff, args = self.args[0], self.args[1:]
if coeff.is_Number and not rational or coeff.is_Rational:
return coeff, self._new_rawargs(*args)
return S.Zero, self
# Note, we intentionally do not implement Add.as_coeff_mul(). Rather, we
# let Expr.as_coeff_mul() just always return (S.One, self) for an Add. See
# issue 5524.
def _eval_power(self, e):
from .evalf import pure_complex
from .relational import is_eq
if len(self.args) == 2 and any(_.is_infinite for _ in self.args):
if e.is_zero is False and is_eq(e, S.One) is False:
# looking for literal a + I*b
a, b = self.args
if a.coeff(S.ImaginaryUnit):
a, b = b, a
ico = b.coeff(S.ImaginaryUnit)
if ico and ico.is_extended_real and a.is_extended_real:
if e.is_extended_negative:
return S.Zero
if e.is_extended_positive:
return S.ComplexInfinity
return
if e.is_Rational and self.is_number:
ri = pure_complex(self)
if ri:
r, i = ri
if e.q == 2:
from sympy.functions.elementary.miscellaneous import sqrt
D = sqrt(r**2 + i**2)
if D.is_Rational:
from .exprtools import factor_terms
from sympy.functions.elementary.complexes import sign
from .function import expand_multinomial
# (r, i, D) is a Pythagorean triple
root = sqrt(factor_terms((D - r)/2))**e.p
return root*expand_multinomial((
# principle value
(D + r)/abs(i) + sign(i)*S.ImaginaryUnit)**e.p)
elif e == -1:
return _unevaluated_Mul(
r - i*S.ImaginaryUnit,
1/(r**2 + i**2))
elif e.is_Number and abs(e) != 1:
# handle the Float case: (2.0 + 4*x)**e -> 4**e*(0.5 + x)**e
c, m = zip(*[i.as_coeff_Mul() for i in self.args])
if any(i.is_Float for i in c): # XXX should this always be done?
big = -1
for i in c:
if abs(i) >= big:
big = abs(i)
if big > 0 and big != 1:
from sympy.functions.elementary.complexes import sign
bigs = (big, -big)
c = [sign(i) if i in bigs else i/big for i in c]
addpow = Add(*[c*m for c, m in zip(c, m)])**e
return big**e*addpow
@cacheit
def _eval_derivative(self, s):
return self.func(*[a.diff(s) for a in self.args])
def _eval_nseries(self, x, n, logx, cdir=0):
terms = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args]
return self.func(*terms)
def _matches_simple(self, expr, repl_dict):
# handle (w+3).matches('x+5') -> {w: x+2}
coeff, terms = self.as_coeff_add()
if len(terms) == 1:
return terms[0].matches(expr - coeff, repl_dict)
return
def matches(self, expr, repl_dict=None, old=False):
return self._matches_commutative(expr, repl_dict, old)
@staticmethod
def _combine_inverse(lhs, rhs):
"""
Returns lhs - rhs, but treats oo like a symbol so oo - oo
returns 0, instead of a nan.
"""
from sympy.simplify.simplify import signsimp
inf = (S.Infinity, S.NegativeInfinity)
if lhs.has(*inf) or rhs.has(*inf):
from .symbol import Dummy
oo = Dummy('oo')
reps = {
S.Infinity: oo,
S.NegativeInfinity: -oo}
ireps = {v: k for k, v in reps.items()}
eq = lhs.xreplace(reps) - rhs.xreplace(reps)
if eq.has(oo):
eq = eq.replace(
lambda x: x.is_Pow and x.base is oo,
lambda x: x.base)
rv = eq.xreplace(ireps)
else:
rv = lhs - rhs
srv = signsimp(rv)
return srv if srv.is_Number else rv
@cacheit
def as_two_terms(self):
"""Return head and tail of self.
This is the most efficient way to get the head and tail of an
expression.
- if you want only the head, use self.args[0];
- if you want to process the arguments of the tail then use
self.as_coef_add() which gives the head and a tuple containing
the arguments of the tail when treated as an Add.
- if you want the coefficient when self is treated as a Mul
then use self.as_coeff_mul()[0]
>>> from sympy.abc import x, y
>>> (3*x - 2*y + 5).as_two_terms()
(5, 3*x - 2*y)
"""
return self.args[0], self._new_rawargs(*self.args[1:])
def as_numer_denom(self):
"""
Decomposes an expression to its numerator part and its
denominator part.
Examples
========
>>> from sympy.abc import x, y, z
>>> (x*y/z).as_numer_denom()
(x*y, z)
>>> (x*(y + 1)/y**7).as_numer_denom()
(x*(y + 1), y**7)
See Also
========
sympy.core.expr.Expr.as_numer_denom
"""
# clear rational denominator
content, expr = self.primitive()
if not isinstance(expr, Add):
return Mul(content, expr, evaluate=False).as_numer_denom()
ncon, dcon = content.as_numer_denom()
# collect numerators and denominators of the terms
nd = defaultdict(list)
for f in expr.args:
ni, di = f.as_numer_denom()
nd[di].append(ni)
# check for quick exit
if len(nd) == 1:
d, n = nd.popitem()
return self.func(
*[_keep_coeff(ncon, ni) for ni in n]), _keep_coeff(dcon, d)
# sum up the terms having a common denominator
for d, n in nd.items():
if len(n) == 1:
nd[d] = n[0]
else:
nd[d] = self.func(*n)
# assemble single numerator and denominator
denoms, numers = [list(i) for i in zip(*iter(nd.items()))]
n, d = self.func(*[Mul(*(denoms[:i] + [numers[i]] + denoms[i + 1:]))
for i in range(len(numers))]), Mul(*denoms)
return _keep_coeff(ncon, n), _keep_coeff(dcon, d)
def _eval_is_polynomial(self, syms):
return all(term._eval_is_polynomial(syms) for term in self.args)
def _eval_is_rational_function(self, syms):
return all(term._eval_is_rational_function(syms) for term in self.args)
def _eval_is_meromorphic(self, x, a):
return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
quick_exit=True)
def _eval_is_algebraic_expr(self, syms):
return all(term._eval_is_algebraic_expr(syms) for term in self.args)
# assumption methods
_eval_is_real = lambda self: _fuzzy_group(
(a.is_real for a in self.args), quick_exit=True)
_eval_is_extended_real = lambda self: _fuzzy_group(
(a.is_extended_real for a in self.args), quick_exit=True)
_eval_is_complex = lambda self: _fuzzy_group(
(a.is_complex for a in self.args), quick_exit=True)
_eval_is_antihermitian = lambda self: _fuzzy_group(
(a.is_antihermitian for a in self.args), quick_exit=True)
_eval_is_finite = lambda self: _fuzzy_group(
(a.is_finite for a in self.args), quick_exit=True)
_eval_is_hermitian = lambda self: _fuzzy_group(
(a.is_hermitian for a in self.args), quick_exit=True)
_eval_is_integer = lambda self: _fuzzy_group(
(a.is_integer for a in self.args), quick_exit=True)
_eval_is_rational = lambda self: _fuzzy_group(
(a.is_rational for a in self.args), quick_exit=True)
_eval_is_algebraic = lambda self: _fuzzy_group(
(a.is_algebraic for a in self.args), quick_exit=True)
_eval_is_commutative = lambda self: _fuzzy_group(
a.is_commutative for a in self.args)
def _eval_is_infinite(self):
sawinf = False
for a in self.args:
ainf = a.is_infinite
if ainf is None:
return None
elif ainf is True:
# infinite+infinite might not be infinite
if sawinf is True:
return None
sawinf = True
return sawinf
def _eval_is_imaginary(self):
nz = []
im_I = []
for a in self.args:
if a.is_extended_real:
if a.is_zero:
pass
elif a.is_zero is False:
nz.append(a)
else:
return
elif a.is_imaginary:
im_I.append(a*S.ImaginaryUnit)
elif (S.ImaginaryUnit*a).is_extended_real:
im_I.append(a*S.ImaginaryUnit)
else:
return
b = self.func(*nz)
if b != self:
if b.is_zero:
return fuzzy_not(self.func(*im_I).is_zero)
elif b.is_zero is False:
return False
def _eval_is_zero(self):
if self.is_commutative is False:
# issue 10528: there is no way to know if a nc symbol
# is zero or not
return
nz = []
z = 0
im_or_z = False
im = 0
for a in self.args:
if a.is_extended_real:
if a.is_zero:
z += 1
elif a.is_zero is False:
nz.append(a)
else:
return
elif a.is_imaginary:
im += 1
elif (S.ImaginaryUnit*a).is_extended_real:
im_or_z = True
else:
return
if z == len(self.args):
return True
if len(nz) in [0, len(self.args)]:
return None
b = self.func(*nz)
if b.is_zero:
if not im_or_z:
if im == 0:
return True
elif im == 1:
return False
if b.is_zero is False:
return False
def _eval_is_odd(self):
l = [f for f in self.args if not (f.is_even is True)]
if not l:
return False
if l[0].is_odd:
return self._new_rawargs(*l[1:]).is_even
def _eval_is_irrational(self):
for t in self.args:
a = t.is_irrational
if a:
others = list(self.args)
others.remove(t)
if all(x.is_rational is True for x in others):
return True
return None
if a is None:
return
return False
def _all_nonneg_or_nonppos(self):
nn = np = 0
for a in self.args:
if a.is_nonnegative:
if np:
return False
nn = 1
elif a.is_nonpositive:
if nn:
return False
np = 1
else:
break
else:
return True
def _eval_is_extended_positive(self):
if self.is_number:
return super()._eval_is_extended_positive()
c, a = self.as_coeff_Add()
if not c.is_zero:
from .exprtools import _monotonic_sign
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_positive and a.is_extended_nonnegative:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_positive:
return True
pos = nonneg = nonpos = unknown_sign = False
saw_INF = set()
args = [a for a in self.args if not a.is_zero]
if not args:
return False
for a in args:
ispos = a.is_extended_positive
infinite = a.is_infinite
if infinite:
saw_INF.add(fuzzy_or((ispos, a.is_extended_nonnegative)))
if True in saw_INF and False in saw_INF:
return
if ispos:
pos = True
continue
elif a.is_extended_nonnegative:
nonneg = True
continue
elif a.is_extended_nonpositive:
nonpos = True
continue
if infinite is None:
return
unknown_sign = True
if saw_INF:
if len(saw_INF) > 1:
return
return saw_INF.pop()
elif unknown_sign:
return
elif not nonpos and not nonneg and pos:
return True
elif not nonpos and pos:
return True
elif not pos and not nonneg:
return False
def _eval_is_extended_nonnegative(self):
if not self.is_number:
c, a = self.as_coeff_Add()
if not c.is_zero and a.is_extended_nonnegative:
from .exprtools import _monotonic_sign
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_nonnegative:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_nonnegative:
return True
def _eval_is_extended_nonpositive(self):
if not self.is_number:
c, a = self.as_coeff_Add()
if not c.is_zero and a.is_extended_nonpositive:
from .exprtools import _monotonic_sign
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_nonpositive:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_nonpositive:
return True
def _eval_is_extended_negative(self):
if self.is_number:
return super()._eval_is_extended_negative()
c, a = self.as_coeff_Add()
if not c.is_zero:
from .exprtools import _monotonic_sign
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_negative and a.is_extended_nonpositive:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_negative:
return True
neg = nonpos = nonneg = unknown_sign = False
saw_INF = set()
args = [a for a in self.args if not a.is_zero]
if not args:
return False
for a in args:
isneg = a.is_extended_negative
infinite = a.is_infinite
if infinite:
saw_INF.add(fuzzy_or((isneg, a.is_extended_nonpositive)))
if True in saw_INF and False in saw_INF:
return
if isneg:
neg = True
continue
elif a.is_extended_nonpositive:
nonpos = True
continue
elif a.is_extended_nonnegative:
nonneg = True
continue
if infinite is None:
return
unknown_sign = True
if saw_INF:
if len(saw_INF) > 1:
return
return saw_INF.pop()
elif unknown_sign:
return
elif not nonneg and not nonpos and neg:
return True
elif not nonneg and neg:
return True
elif not neg and not nonpos:
return False
def _eval_subs(self, old, new):
if not old.is_Add:
if old is S.Infinity and -old in self.args:
# foo - oo is foo + (-oo) internally
return self.xreplace({-old: -new})
return None
coeff_self, terms_self = self.as_coeff_Add()
coeff_old, terms_old = old.as_coeff_Add()
if coeff_self.is_Rational and coeff_old.is_Rational:
if terms_self == terms_old: # (2 + a).subs( 3 + a, y) -> -1 + y
return self.func(new, coeff_self, -coeff_old)
if terms_self == -terms_old: # (2 + a).subs(-3 - a, y) -> -1 - y
return self.func(-new, coeff_self, coeff_old)
if coeff_self.is_Rational and coeff_old.is_Rational \
or coeff_self == coeff_old:
args_old, args_self = self.func.make_args(
terms_old), self.func.make_args(terms_self)
if len(args_old) < len(args_self): # (a+b+c).subs(b+c,x) -> a+x
self_set = set(args_self)
old_set = set(args_old)
if old_set < self_set:
ret_set = self_set - old_set
return self.func(new, coeff_self, -coeff_old,
*[s._subs(old, new) for s in ret_set])
args_old = self.func.make_args(
-terms_old) # (a+b+c+d).subs(-b-c,x) -> a-x+d
old_set = set(args_old)
if old_set < self_set:
ret_set = self_set - old_set
return self.func(-new, coeff_self, coeff_old,
*[s._subs(old, new) for s in ret_set])
def removeO(self):
args = [a for a in self.args if not a.is_Order]
return self._new_rawargs(*args)
def getO(self):
args = [a for a in self.args if a.is_Order]
if args:
return self._new_rawargs(*args)
@cacheit
def extract_leading_order(self, symbols, point=None):
"""
Returns the leading term and its order.
Examples
========
>>> from sympy.abc import x
>>> (x + 1 + 1/x**5).extract_leading_order(x)
((x**(-5), O(x**(-5))),)
>>> (1 + x).extract_leading_order(x)
((1, O(1)),)
>>> (x + x**2).extract_leading_order(x)
((x, O(x)),)
"""
from sympy.series.order import Order
lst = []
symbols = list(symbols if is_sequence(symbols) else [symbols])
if not point:
point = [0]*len(symbols)
seq = [(f, Order(f, *zip(symbols, point))) for f in self.args]
for ef, of in seq:
for e, o in lst:
if o.contains(of) and o != of:
of = None
break
if of is None:
continue
new_lst = [(ef, of)]
for e, o in lst:
if of.contains(o) and o != of:
continue
new_lst.append((e, o))
lst = new_lst
return tuple(lst)
def as_real_imag(self, deep=True, **hints):
"""
returns a tuple representing a complex number
Examples
========
>>> from sympy import I
>>> (7 + 9*I).as_real_imag()
(7, 9)
>>> ((1 + I)/(1 - I)).as_real_imag()
(0, 1)
>>> ((1 + 2*I)*(1 + 3*I)).as_real_imag()
(-5, 5)
"""
sargs = self.args
re_part, im_part = [], []
for term in sargs:
re, im = term.as_real_imag(deep=deep)
re_part.append(re)
im_part.append(im)
return (self.func(*re_part), self.func(*im_part))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.core.symbol import Dummy, Symbol
from sympy.series.order import Order
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from .function import expand_mul
o = self.getO()
if o is None:
o = Order(0)
old = self.removeO()
if old.has(Piecewise):
old = piecewise_fold(old)
# This expansion is the last part of expand_log. expand_log also calls
# expand_mul with factor=True, which would be more expensive
if any(isinstance(a, log) for a in self.args):
logflags = dict(deep=True, log=True, mul=False, power_exp=False,
power_base=False, multinomial=False, basic=False, force=False,
factor=False)
old = old.expand(**logflags)
expr = expand_mul(old)
if not expr.is_Add:
return expr.as_leading_term(x, logx=logx, cdir=cdir)
infinite = [t for t in expr.args if t.is_infinite]
_logx = Dummy('logx') if logx is None else logx
leading_terms = [t.as_leading_term(x, logx=_logx, cdir=cdir) for t in expr.args]
min, new_expr = Order(0), 0
try:
for term in leading_terms:
order = Order(term, x)
if not min or order not in min:
min = order
new_expr = term
elif min in order:
new_expr += term
except TypeError:
return expr
if logx is None:
new_expr = new_expr.subs(_logx, log(x))
is_zero = new_expr.is_zero
if is_zero is None:
new_expr = new_expr.trigsimp().cancel()
is_zero = new_expr.is_zero
if is_zero is True:
# simple leading term analysis gave us cancelled terms but we have to send
# back a term, so compute the leading term (via series)
try:
n0 = min.getn()
except NotImplementedError:
n0 = S.One
if n0.has(Symbol):
n0 = S.One
res = Order(1)
incr = S.One
while res.is_Order:
res = old._eval_nseries(x, n=n0+incr, logx=logx, cdir=cdir).cancel().powsimp().trigsimp()
incr *= 2
return res.as_leading_term(x, logx=logx, cdir=cdir)
elif new_expr is S.NaN:
return old.func._from_args(infinite) + o
else:
return new_expr
def _eval_adjoint(self):
return self.func(*[t.adjoint() for t in self.args])
def _eval_conjugate(self):
return self.func(*[t.conjugate() for t in self.args])
def _eval_transpose(self):
return self.func(*[t.transpose() for t in self.args])
def primitive(self):
"""
Return ``(R, self/R)`` where ``R``` is the Rational GCD of ``self```.
``R`` is collected only from the leading coefficient of each term.
Examples
========
>>> from sympy.abc import x, y
>>> (2*x + 4*y).primitive()
(2, x + 2*y)
>>> (2*x/3 + 4*y/9).primitive()
(2/9, 3*x + 2*y)
>>> (2*x/3 + 4.2*y).primitive()
(1/3, 2*x + 12.6*y)
No subprocessing of term factors is performed:
>>> ((2 + 2*x)*x + 2).primitive()
(1, x*(2*x + 2) + 2)
Recursive processing can be done with the ``as_content_primitive()``
method:
>>> ((2 + 2*x)*x + 2).as_content_primitive()
(2, x*(x + 1) + 1)
See also: primitive() function in polytools.py
"""
terms = []
inf = False
for a in self.args:
c, m = a.as_coeff_Mul()
if not c.is_Rational:
c = S.One
m = a
inf = inf or m is S.ComplexInfinity
terms.append((c.p, c.q, m))
if not inf:
ngcd = reduce(igcd, [t[0] for t in terms], 0)
dlcm = reduce(ilcm, [t[1] for t in terms], 1)
else:
ngcd = reduce(igcd, [t[0] for t in terms if t[1]], 0)
dlcm = reduce(ilcm, [t[1] for t in terms if t[1]], 1)
if ngcd == dlcm == 1:
return S.One, self
if not inf:
for i, (p, q, term) in enumerate(terms):
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
else:
for i, (p, q, term) in enumerate(terms):
if q:
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
else:
terms[i] = _keep_coeff(Rational(p, q), term)
# we don't need a complete re-flattening since no new terms will join
# so we just use the same sort as is used in Add.flatten. When the
# coefficient changes, the ordering of terms may change, e.g.
# (3*x, 6*y) -> (2*y, x)
#
# We do need to make sure that term[0] stays in position 0, however.
#
if terms[0].is_Number or terms[0] is S.ComplexInfinity:
c = terms.pop(0)
else:
c = None
_addsort(terms)
if c:
terms.insert(0, c)
return Rational(ngcd, dlcm), self._new_rawargs(*terms)
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self. If radical is True (default is False) then
common radicals will be removed and included as a factor of the
primitive expression.
Examples
========
>>> from sympy import sqrt
>>> (3 + 3*sqrt(2)).as_content_primitive()
(3, 1 + sqrt(2))
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))
See docstring of Expr.as_content_primitive for more examples.
"""
con, prim = self.func(*[_keep_coeff(*a.as_content_primitive(
radical=radical, clear=clear)) for a in self.args]).primitive()
if not clear and not con.is_Integer and prim.is_Add:
con, d = con.as_numer_denom()
_p = prim/d
if any(a.as_coeff_Mul()[0].is_Integer for a in _p.args):
prim = _p
else:
con /= d
if radical and prim.is_Add:
# look for common radicals that can be removed
args = prim.args
rads = []
common_q = None
for m in args:
term_rads = defaultdict(list)
for ai in Mul.make_args(m):
if ai.is_Pow:
b, e = ai.as_base_exp()
if e.is_Rational and b.is_Integer:
term_rads[e.q].append(abs(int(b))**e.p)
if not term_rads:
break
if common_q is None:
common_q = set(term_rads.keys())
else:
common_q = common_q & set(term_rads.keys())
if not common_q:
break
rads.append(term_rads)
else:
# process rads
# keep only those in common_q
for r in rads:
for q in list(r.keys()):
if q not in common_q:
r.pop(q)
for q in r:
r[q] = Mul(*r[q])
# find the gcd of bases for each q
G = []
for q in common_q:
g = reduce(igcd, [r[q] for r in rads], 0)
if g != 1:
G.append(g**Rational(1, q))
if G:
G = Mul(*G)
args = [ai/G for ai in args]
prim = G*prim.func(*args)
return con, prim
@property
def _sorted_args(self):
from .sorting import default_sort_key
return tuple(sorted(self.args, key=default_sort_key))
def _eval_difference_delta(self, n, step):
from sympy.series.limitseq import difference_delta as dd
return self.func(*[dd(a, n, step) for a in self.args])
@property
def _mpc_(self):
"""
Convert self to an mpmath mpc if possible
"""
from .numbers import Float
re_part, rest = self.as_coeff_Add()
im_part, imag_unit = rest.as_coeff_Mul()
if not imag_unit == S.ImaginaryUnit:
# ValueError may seem more reasonable but since it's a @property,
# we need to use AttributeError to keep from confusing things like
# hasattr.
raise AttributeError("Cannot convert Add to mpc. Must be of the form Number + Number*I")
return (Float(re_part)._mpf_, Float(im_part)._mpf_)
def __neg__(self):
if not global_parameters.distribute:
return super().__neg__()
return Add(*[-i for i in self.args])
add = AssocOpDispatcher('add')
from .mul import Mul, _keep_coeff, _unevaluated_Mul
from .numbers import Rational
|
5d9fbb0616f95d58a4614fa4bcc45983d175f7cc0244a0f2d3a6bbf38d438a71 | from __future__ import annotations
from typing import TYPE_CHECKING
from collections.abc import Iterable
from functools import reduce
import re
from .sympify import sympify, _sympify
from .basic import Basic, Atom
from .singleton import S
from .evalf import EvalfMixin, pure_complex, DEFAULT_MAXPREC
from .decorators import call_highest_priority, sympify_method_args, sympify_return
from .cache import cacheit
from .sorting import default_sort_key
from .kind import NumberKind
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.misc import as_int, func_name, filldedent
from sympy.utilities.iterables import has_variety, sift
from mpmath.libmp import mpf_log, prec_to_dps
from mpmath.libmp.libintmath import giant_steps
if TYPE_CHECKING:
from .numbers import Number
from collections import defaultdict
def _corem(eq, c): # helper for extract_additively
# return co, diff from co*c + diff
co = []
non = []
for i in Add.make_args(eq):
ci = i.coeff(c)
if not ci:
non.append(i)
else:
co.append(ci)
return Add(*co), Add(*non)
@sympify_method_args
class Expr(Basic, EvalfMixin):
"""
Base class for algebraic expressions.
Explanation
===========
Everything that requires arithmetic operations to be defined
should subclass this class, instead of Basic (which should be
used only for argument storage and expression manipulation, i.e.
pattern matching, substitutions, etc).
If you want to override the comparisons of expressions:
Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch.
_eval_is_ge return true if x >= y, false if x < y, and None if the two types
are not comparable or the comparison is indeterminate
See Also
========
sympy.core.basic.Basic
"""
__slots__: tuple[str, ...] = ()
is_scalar = True # self derivative is 1
@property
def _diff_wrt(self):
"""Return True if one can differentiate with respect to this
object, else False.
Explanation
===========
Subclasses such as Symbol, Function and Derivative return True
to enable derivatives wrt them. The implementation in Derivative
separates the Symbol and non-Symbol (_diff_wrt=True) variables and
temporarily converts the non-Symbols into Symbols when performing
the differentiation. By default, any object deriving from Expr
will behave like a scalar with self.diff(self) == 1. If this is
not desired then the object must also set `is_scalar = False` or
else define an _eval_derivative routine.
Note, see the docstring of Derivative for how this should work
mathematically. In particular, note that expr.subs(yourclass, Symbol)
should be well-defined on a structural level, or this will lead to
inconsistent results.
Examples
========
>>> from sympy import Expr
>>> e = Expr()
>>> e._diff_wrt
False
>>> class MyScalar(Expr):
... _diff_wrt = True
...
>>> MyScalar().diff(MyScalar())
1
>>> class MySymbol(Expr):
... _diff_wrt = True
... is_scalar = False
...
>>> MySymbol().diff(MySymbol())
Derivative(MySymbol(), MySymbol())
"""
return False
@cacheit
def sort_key(self, order=None):
coeff, expr = self.as_coeff_Mul()
if expr.is_Pow:
if expr.base is S.Exp1:
# If we remove this, many doctests will go crazy:
# (keeps E**x sorted like the exp(x) function,
# part of exp(x) to E**x transition)
expr, exp = Function("exp")(expr.exp), S.One
else:
expr, exp = expr.args
else:
exp = S.One
if expr.is_Dummy:
args = (expr.sort_key(),)
elif expr.is_Atom:
args = (str(expr),)
else:
if expr.is_Add:
args = expr.as_ordered_terms(order=order)
elif expr.is_Mul:
args = expr.as_ordered_factors(order=order)
else:
args = expr.args
args = tuple(
[ default_sort_key(arg, order=order) for arg in args ])
args = (len(args), tuple(args))
exp = exp.sort_key(order=order)
return expr.class_key(), args, exp, coeff
def _hashable_content(self):
"""Return a tuple of information about self that can be used to
compute the hash. If a class defines additional attributes,
like ``name`` in Symbol, then this method should be updated
accordingly to return such relevant attributes.
Defining more than _hashable_content is necessary if __eq__ has
been defined by a class. See note about this in Basic.__eq__."""
return self._args
# ***************
# * Arithmetics *
# ***************
# Expr and its sublcasses use _op_priority to determine which object
# passed to a binary special method (__mul__, etc.) will handle the
# operation. In general, the 'call_highest_priority' decorator will choose
# the object with the highest _op_priority to handle the call.
# Custom subclasses that want to define their own binary special methods
# should set an _op_priority value that is higher than the default.
#
# **NOTE**:
# This is a temporary fix, and will eventually be replaced with
# something better and more powerful. See issue 5510.
_op_priority = 10.0
@property
def _add_handler(self):
return Add
@property
def _mul_handler(self):
return Mul
def __pos__(self):
return self
def __neg__(self):
# Mul has its own __neg__ routine, so we just
# create a 2-args Mul with the -1 in the canonical
# slot 0.
c = self.is_commutative
return Mul._from_args((S.NegativeOne, self), c)
def __abs__(self) -> Expr:
from sympy.functions.elementary.complexes import Abs
return Abs(self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return Add(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return Add(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return Add(self, -other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return Add(other, -self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return Mul(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return Mul(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rpow__')
def _pow(self, other):
return Pow(self, other)
def __pow__(self, other, mod=None) -> Expr:
if mod is None:
return self._pow(other)
try:
_self, other, mod = as_int(self), as_int(other), as_int(mod)
if other >= 0:
return _sympify(pow(_self, other, mod))
else:
from .numbers import mod_inverse
return _sympify(mod_inverse(pow(_self, -other, mod), mod))
except ValueError:
power = self._pow(other)
try:
return power%mod
except TypeError:
return NotImplemented
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
return Pow(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
denom = Pow(other, S.NegativeOne)
if self is S.One:
return denom
else:
return Mul(self, denom)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__truediv__')
def __rtruediv__(self, other):
denom = Pow(self, S.NegativeOne)
if other is S.One:
return denom
else:
return Mul(other, denom)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rmod__')
def __mod__(self, other):
return Mod(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__mod__')
def __rmod__(self, other):
return Mod(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rfloordiv__')
def __floordiv__(self, other):
from sympy.functions.elementary.integers import floor
return floor(self / other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__floordiv__')
def __rfloordiv__(self, other):
from sympy.functions.elementary.integers import floor
return floor(other / self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rdivmod__')
def __divmod__(self, other):
from sympy.functions.elementary.integers import floor
return floor(self / other), Mod(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__divmod__')
def __rdivmod__(self, other):
from sympy.functions.elementary.integers import floor
return floor(other / self), Mod(other, self)
def __int__(self):
# Although we only need to round to the units position, we'll
# get one more digit so the extra testing below can be avoided
# unless the rounded value rounded to an integer, e.g. if an
# expression were equal to 1.9 and we rounded to the unit position
# we would get a 2 and would not know if this rounded up or not
# without doing a test (as done below). But if we keep an extra
# digit we know that 1.9 is not the same as 1 and there is no
# need for further testing: our int value is correct. If the value
# were 1.99, however, this would round to 2.0 and our int value is
# off by one. So...if our round value is the same as the int value
# (regardless of how much extra work we do to calculate extra decimal
# places) we need to test whether we are off by one.
from .symbol import Dummy
if not self.is_number:
raise TypeError("Cannot convert symbols to int")
r = self.round(2)
if not r.is_Number:
raise TypeError("Cannot convert complex to int")
if r in (S.NaN, S.Infinity, S.NegativeInfinity):
raise TypeError("Cannot convert %s to int" % r)
i = int(r)
if not i:
return 0
# off-by-one check
if i == r and not (self - i).equals(0):
isign = 1 if i > 0 else -1
x = Dummy()
# in the following (self - i).evalf(2) will not always work while
# (self - r).evalf(2) and the use of subs does; if the test that
# was added when this comment was added passes, it might be safe
# to simply use sign to compute this rather than doing this by hand:
diff_sign = 1 if (self - x).evalf(2, subs={x: i}) > 0 else -1
if diff_sign != isign:
i -= isign
return i
def __float__(self):
# Don't bother testing if it's a number; if it's not this is going
# to fail, and if it is we still need to check that it evalf'ed to
# a number.
result = self.evalf()
if result.is_Number:
return float(result)
if result.is_number and result.as_real_imag()[1]:
raise TypeError("Cannot convert complex to float")
raise TypeError("Cannot convert expression to float")
def __complex__(self):
result = self.evalf()
re, im = result.as_real_imag()
return complex(float(re), float(im))
@sympify_return([('other', 'Expr')], NotImplemented)
def __ge__(self, other):
from .relational import GreaterThan
return GreaterThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __le__(self, other):
from .relational import LessThan
return LessThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __gt__(self, other):
from .relational import StrictGreaterThan
return StrictGreaterThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __lt__(self, other):
from .relational import StrictLessThan
return StrictLessThan(self, other)
def __trunc__(self):
if not self.is_number:
raise TypeError("Cannot truncate symbols and expressions")
else:
return Integer(self)
def __format__(self, format_spec: str):
if self.is_number:
mt = re.match(r'\+?\d*\.(\d+)f', format_spec)
if mt:
prec = int(mt.group(1))
rounded = self.round(prec)
if rounded.is_Integer:
return format(int(rounded), format_spec)
if rounded.is_Float:
return format(rounded, format_spec)
return super().__format__(format_spec)
@staticmethod
def _from_mpmath(x, prec):
if hasattr(x, "_mpf_"):
return Float._new(x._mpf_, prec)
elif hasattr(x, "_mpc_"):
re, im = x._mpc_
re = Float._new(re, prec)
im = Float._new(im, prec)*S.ImaginaryUnit
return re + im
else:
raise TypeError("expected mpmath number (mpf or mpc)")
@property
def is_number(self):
"""Returns True if ``self`` has no free symbols and no
undefined functions (AppliedUndef, to be precise). It will be
faster than ``if not self.free_symbols``, however, since
``is_number`` will fail as soon as it hits a free symbol
or undefined function.
Examples
========
>>> from sympy import Function, Integral, cos, sin, pi
>>> from sympy.abc import x
>>> f = Function('f')
>>> x.is_number
False
>>> f(1).is_number
False
>>> (2*x).is_number
False
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True
Not all numbers are Numbers in the SymPy sense:
>>> pi.is_number, pi.is_Number
(True, False)
If something is a number it should evaluate to a number with
real and imaginary parts that are Numbers; the result may not
be comparable, however, since the real and/or imaginary part
of the result may not have precision.
>>> cos(1).is_number and cos(1).is_comparable
True
>>> z = cos(1)**2 + sin(1)**2 - 1
>>> z.is_number
True
>>> z.is_comparable
False
See Also
========
sympy.core.basic.Basic.is_comparable
"""
return all(obj.is_number for obj in self.args)
def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1):
"""Return self evaluated, if possible, replacing free symbols with
random complex values, if necessary.
Explanation
===========
The random complex value for each free symbol is generated
by the random_complex_number routine giving real and imaginary
parts in the range given by the re_min, re_max, im_min, and im_max
values. The returned value is evaluated to a precision of n
(if given) else the maximum of 15 and the precision needed
to get more than 1 digit of precision. If the expression
could not be evaluated to a number, or could not be evaluated
to more than 1 digit of precision, then None is returned.
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x, y
>>> x._random() # doctest: +SKIP
0.0392918155679172 + 0.916050214307199*I
>>> x._random(2) # doctest: +SKIP
-0.77 - 0.87*I
>>> (x + y/2)._random(2) # doctest: +SKIP
-0.57 + 0.16*I
>>> sqrt(2)._random(2)
1.4
See Also
========
sympy.core.random.random_complex_number
"""
free = self.free_symbols
prec = 1
if free:
from sympy.core.random import random_complex_number
a, c, b, d = re_min, re_max, im_min, im_max
reps = dict(list(zip(free, [random_complex_number(a, b, c, d, rational=True)
for zi in free])))
try:
nmag = abs(self.evalf(2, subs=reps))
except (ValueError, TypeError):
# if an out of range value resulted in evalf problems
# then return None -- XXX is there a way to know how to
# select a good random number for a given expression?
# e.g. when calculating n! negative values for n should not
# be used
return None
else:
reps = {}
nmag = abs(self.evalf(2))
if not hasattr(nmag, '_prec'):
# e.g. exp_polar(2*I*pi) doesn't evaluate but is_number is True
return None
if nmag._prec == 1:
# increase the precision up to the default maximum
# precision to see if we can get any significance
# evaluate
for prec in giant_steps(2, DEFAULT_MAXPREC):
nmag = abs(self.evalf(prec, subs=reps))
if nmag._prec != 1:
break
if nmag._prec != 1:
if n is None:
n = max(prec, 15)
return self.evalf(n, subs=reps)
# never got any significance
return None
def is_constant(self, *wrt, **flags):
"""Return True if self is constant, False if not, or None if
the constancy could not be determined conclusively.
Explanation
===========
If an expression has no free symbols then it is a constant. If
there are free symbols it is possible that the expression is a
constant, perhaps (but not necessarily) zero. To test such
expressions, a few strategies are tried:
1) numerical evaluation at two random points. If two such evaluations
give two different values and the values have a precision greater than
1 then self is not constant. If the evaluations agree or could not be
obtained with any precision, no decision is made. The numerical testing
is done only if ``wrt`` is different than the free symbols.
2) differentiation with respect to variables in 'wrt' (or all free
symbols if omitted) to see if the expression is constant or not. This
will not always lead to an expression that is zero even though an
expression is constant (see added test in test_expr.py). If
all derivatives are zero then self is constant with respect to the
given symbols.
3) finding out zeros of denominator expression with free_symbols.
It will not be constant if there are zeros. It gives more negative
answers for expression that are not constant.
If neither evaluation nor differentiation can prove the expression is
constant, None is returned unless two numerical values happened to be
the same and the flag ``failing_number`` is True -- in that case the
numerical value will be returned.
If flag simplify=False is passed, self will not be simplified;
the default is True since self should be simplified before testing.
Examples
========
>>> from sympy import cos, sin, Sum, S, pi
>>> from sympy.abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
"""
def check_denominator_zeros(expression):
from sympy.solvers.solvers import denoms
retNone = False
for den in denoms(expression):
z = den.is_zero
if z is True:
return True
if z is None:
retNone = True
if retNone:
return None
return False
simplify = flags.get('simplify', True)
if self.is_number:
return True
free = self.free_symbols
if not free:
return True # assume f(1) is some constant
# if we are only interested in some symbols and they are not in the
# free symbols then this expression is constant wrt those symbols
wrt = set(wrt)
if wrt and not wrt & free:
return True
wrt = wrt or free
# simplify unless this has already been done
expr = self
if simplify:
expr = expr.simplify()
# is_zero should be a quick assumptions check; it can be wrong for
# numbers (see test_is_not_constant test), giving False when it
# shouldn't, but hopefully it will never give True unless it is sure.
if expr.is_zero:
return True
# Don't attempt substitution or differentiation with non-number symbols
wrt_number = {sym for sym in wrt if sym.kind is NumberKind}
# try numerical evaluation to see if we get two different values
failing_number = None
if wrt_number == free:
# try 0 (for a) and 1 (for b)
try:
a = expr.subs(list(zip(free, [0]*len(free))),
simultaneous=True)
if a is S.NaN:
# evaluation may succeed when substitution fails
a = expr._random(None, 0, 0, 0, 0)
except ZeroDivisionError:
a = None
if a is not None and a is not S.NaN:
try:
b = expr.subs(list(zip(free, [1]*len(free))),
simultaneous=True)
if b is S.NaN:
# evaluation may succeed when substitution fails
b = expr._random(None, 1, 0, 1, 0)
except ZeroDivisionError:
b = None
if b is not None and b is not S.NaN and b.equals(a) is False:
return False
# try random real
b = expr._random(None, -1, 0, 1, 0)
if b is not None and b is not S.NaN and b.equals(a) is False:
return False
# try random complex
b = expr._random()
if b is not None and b is not S.NaN:
if b.equals(a) is False:
return False
failing_number = a if a.is_number else b
# now we will test each wrt symbol (or all free symbols) to see if the
# expression depends on them or not using differentiation. This is
# not sufficient for all expressions, however, so we don't return
# False if we get a derivative other than 0 with free symbols.
for w in wrt_number:
deriv = expr.diff(w)
if simplify:
deriv = deriv.simplify()
if deriv != 0:
if not (pure_complex(deriv, or_real=True)):
if flags.get('failing_number', False):
return failing_number
return False
cd = check_denominator_zeros(self)
if cd is True:
return False
elif cd is None:
return None
return True
def equals(self, other, failing_expression=False):
"""Return True if self == other, False if it does not, or None. If
failing_expression is True then the expression which did not simplify
to a 0 will be returned instead of None.
Explanation
===========
If ``self`` is a Number (or complex number) that is not zero, then
the result is False.
If ``self`` is a number and has not evaluated to zero, evalf will be
used to test whether the expression evaluates to zero. If it does so
and the result has significance (i.e. the precision is either -1, for
a Rational result, or is greater than 1) then the evalf value will be
used to return True or False.
"""
from sympy.simplify.simplify import nsimplify, simplify
from sympy.solvers.solvers import solve
from sympy.polys.polyerrors import NotAlgebraic
from sympy.polys.numberfields import minimal_polynomial
other = sympify(other)
if self == other:
return True
# they aren't the same so see if we can make the difference 0;
# don't worry about doing simplification steps one at a time
# because if the expression ever goes to 0 then the subsequent
# simplification steps that are done will be very fast.
diff = factor_terms(simplify(self - other), radical=True)
if not diff:
return True
if not diff.has(Add, Mod):
# if there is no expanding to be done after simplifying
# then this can't be a zero
return False
factors = diff.as_coeff_mul()[1]
if len(factors) > 1: # avoid infinity recursion
fac_zero = [fac.equals(0) for fac in factors]
if None not in fac_zero: # every part can be decided
return any(fac_zero)
constant = diff.is_constant(simplify=False, failing_number=True)
if constant is False:
return False
if not diff.is_number:
if constant is None:
# e.g. unless the right simplification is done, a symbolic
# zero is possible (see expression of issue 6829: without
# simplification constant will be None).
return
if constant is True:
# this gives a number whether there are free symbols or not
ndiff = diff._random()
# is_comparable will work whether the result is real
# or complex; it could be None, however.
if ndiff and ndiff.is_comparable:
return False
# sometimes we can use a simplified result to give a clue as to
# what the expression should be; if the expression is *not* zero
# then we should have been able to compute that and so now
# we can just consider the cases where the approximation appears
# to be zero -- we try to prove it via minimal_polynomial.
#
# removed
# ns = nsimplify(diff)
# if diff.is_number and (not ns or ns == diff):
#
# The thought was that if it nsimplifies to 0 that's a sure sign
# to try the following to prove it; or if it changed but wasn't
# zero that might be a sign that it's not going to be easy to
# prove. But tests seem to be working without that logic.
#
if diff.is_number:
# try to prove via self-consistency
surds = [s for s in diff.atoms(Pow) if s.args[0].is_Integer]
# it seems to work better to try big ones first
surds.sort(key=lambda x: -x.args[0])
for s in surds:
try:
# simplify is False here -- this expression has already
# been identified as being hard to identify as zero;
# we will handle the checking ourselves using nsimplify
# to see if we are in the right ballpark or not and if so
# *then* the simplification will be attempted.
sol = solve(diff, s, simplify=False)
if sol:
if s in sol:
# the self-consistent result is present
return True
if all(si.is_Integer for si in sol):
# perfect powers are removed at instantiation
# so surd s cannot be an integer
return False
if all(i.is_algebraic is False for i in sol):
# a surd is algebraic
return False
if any(si in surds for si in sol):
# it wasn't equal to s but it is in surds
# and different surds are not equal
return False
if any(nsimplify(s - si) == 0 and
simplify(s - si) == 0 for si in sol):
return True
if s.is_real:
if any(nsimplify(si, [s]) == s and simplify(si) == s
for si in sol):
return True
except NotImplementedError:
pass
# try to prove with minimal_polynomial but know when
# *not* to use this or else it can take a long time. e.g. issue 8354
if True: # change True to condition that assures non-hang
try:
mp = minimal_polynomial(diff)
if mp.is_Symbol:
return True
return False
except (NotAlgebraic, NotImplementedError):
pass
# diff has not simplified to zero; constant is either None, True
# or the number with significance (is_comparable) that was randomly
# calculated twice as the same value.
if constant not in (True, None) and constant != 0:
return False
if failing_expression:
return diff
return None
def _eval_is_extended_positive_negative(self, positive):
from sympy.polys.numberfields import minimal_polynomial
from sympy.polys.polyerrors import NotAlgebraic
if self.is_number:
# check to see that we can get a value
try:
n2 = self._eval_evalf(2)
# XXX: This shouldn't be caught here
# Catches ValueError: hypsum() failed to converge to the requested
# 34 bits of accuracy
except ValueError:
return None
if n2 is None:
return None
if getattr(n2, '_prec', 1) == 1: # no significance
return None
if n2 is S.NaN:
return None
f = self.evalf(2)
if f.is_Float:
match = f, S.Zero
else:
match = pure_complex(f)
if match is None:
return False
r, i = match
if not (i.is_Number and r.is_Number):
return False
if r._prec != 1 and i._prec != 1:
return bool(not i and ((r > 0) if positive else (r < 0)))
elif r._prec == 1 and (not i or i._prec == 1) and \
self._eval_is_algebraic() and not self.has(Function):
try:
if minimal_polynomial(self).is_Symbol:
return False
except (NotAlgebraic, NotImplementedError):
pass
def _eval_is_extended_positive(self):
return self._eval_is_extended_positive_negative(positive=True)
def _eval_is_extended_negative(self):
return self._eval_is_extended_positive_negative(positive=False)
def _eval_interval(self, x, a, b):
"""
Returns evaluation over an interval. For most functions this is:
self.subs(x, b) - self.subs(x, a),
possibly using limit() if NaN is returned from subs, or if
singularities are found between a and b.
If b or a is None, it only evaluates -self.subs(x, a) or self.subs(b, x),
respectively.
"""
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.functions.elementary.exponential import log
from sympy.series.limits import limit, Limit
from sympy.sets.sets import Interval
from sympy.solvers.solveset import solveset
if (a is None and b is None):
raise ValueError('Both interval ends cannot be None.')
def _eval_endpoint(left):
c = a if left else b
if c is None:
return S.Zero
else:
C = self.subs(x, c)
if C.has(S.NaN, S.Infinity, S.NegativeInfinity,
S.ComplexInfinity, AccumBounds):
if (a < b) != False:
C = limit(self, x, c, "+" if left else "-")
else:
C = limit(self, x, c, "-" if left else "+")
if isinstance(C, Limit):
raise NotImplementedError("Could not compute limit")
return C
if a == b:
return S.Zero
A = _eval_endpoint(left=True)
if A is S.NaN:
return A
B = _eval_endpoint(left=False)
if (a and b) is None:
return B - A
value = B - A
if a.is_comparable and b.is_comparable:
if a < b:
domain = Interval(a, b)
else:
domain = Interval(b, a)
# check the singularities of self within the interval
# if singularities is a ConditionSet (not iterable), catch the exception and pass
singularities = solveset(self.cancel().as_numer_denom()[1], x,
domain=domain)
for logterm in self.atoms(log):
singularities = singularities | solveset(logterm.args[0], x,
domain=domain)
try:
for s in singularities:
if value is S.NaN:
# no need to keep adding, it will stay NaN
break
if not s.is_comparable:
continue
if (a < s) == (s < b) == True:
value += -limit(self, x, s, "+") + limit(self, x, s, "-")
elif (b < s) == (s < a) == True:
value += limit(self, x, s, "+") - limit(self, x, s, "-")
except TypeError:
pass
return value
def _eval_power(self, other):
# subclass to compute self**other for cases when
# other is not NaN, 0, or 1
return None
def _eval_conjugate(self):
if self.is_extended_real:
return self
elif self.is_imaginary:
return -self
def conjugate(self):
"""Returns the complex conjugate of 'self'."""
from sympy.functions.elementary.complexes import conjugate as c
return c(self)
def dir(self, x, cdir):
if self.is_zero:
return S.Zero
from sympy.functions.elementary.exponential import log
minexp = S.Zero
arg = self
while arg:
minexp += S.One
arg = arg.diff(x)
coeff = arg.subs(x, 0)
if coeff is S.NaN:
coeff = arg.limit(x, 0)
if coeff is S.ComplexInfinity:
try:
coeff, _ = arg.leadterm(x)
if coeff.has(log(x)):
raise ValueError()
except ValueError:
coeff = arg.limit(x, 0)
if coeff != S.Zero:
break
return coeff*cdir**minexp
def _eval_transpose(self):
from sympy.functions.elementary.complexes import conjugate
if (self.is_complex or self.is_infinite):
return self
elif self.is_hermitian:
return conjugate(self)
elif self.is_antihermitian:
return -conjugate(self)
def transpose(self):
from sympy.functions.elementary.complexes import transpose
return transpose(self)
def _eval_adjoint(self):
from sympy.functions.elementary.complexes import conjugate, transpose
if self.is_hermitian:
return self
elif self.is_antihermitian:
return -self
obj = self._eval_conjugate()
if obj is not None:
return transpose(obj)
obj = self._eval_transpose()
if obj is not None:
return conjugate(obj)
def adjoint(self):
from sympy.functions.elementary.complexes import adjoint
return adjoint(self)
@classmethod
def _parse_order(cls, order):
"""Parse and configure the ordering of terms. """
from sympy.polys.orderings import monomial_key
startswith = getattr(order, "startswith", None)
if startswith is None:
reverse = False
else:
reverse = startswith('rev-')
if reverse:
order = order[4:]
monom_key = monomial_key(order)
def neg(monom):
return tuple([neg(m) if isinstance(m, tuple) else -m for m in monom])
def key(term):
_, ((re, im), monom, ncpart) = term
monom = neg(monom_key(monom))
ncpart = tuple([e.sort_key(order=order) for e in ncpart])
coeff = ((bool(im), im), (re, im))
return monom, ncpart, coeff
return key, reverse
def as_ordered_factors(self, order=None):
"""Return list of ordered factors (if Mul) else [self]."""
return [self]
def as_poly(self, *gens, **args):
"""Converts ``self`` to a polynomial or returns ``None``.
Explanation
===========
>>> from sympy import sin
>>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly())
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y))
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y))
None
"""
from sympy.polys.polyerrors import PolynomialError, GeneratorsNeeded
from sympy.polys.polytools import Poly
try:
poly = Poly(self, *gens, **args)
if not poly.is_Poly:
return None
else:
return poly
except (PolynomialError, GeneratorsNeeded):
# PolynomialError is caught for e.g. exp(x).as_poly(x)
# GeneratorsNeeded is caught for e.g. S(2).as_poly()
return None
def as_ordered_terms(self, order=None, data=False):
"""
Transform an expression to an ordered list of terms.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.abc import x
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
"""
from .numbers import Number, NumberSymbol
if order is None and self.is_Add:
# Spot the special case of Add(Number, Mul(Number, expr)) with the
# first number positive and the second number negative
key = lambda x:not isinstance(x, (Number, NumberSymbol))
add_args = sorted(Add.make_args(self), key=key)
if (len(add_args) == 2
and isinstance(add_args[0], (Number, NumberSymbol))
and isinstance(add_args[1], Mul)):
mul_args = sorted(Mul.make_args(add_args[1]), key=key)
if (len(mul_args) == 2
and isinstance(mul_args[0], Number)
and add_args[0].is_positive
and mul_args[0].is_negative):
return add_args
key, reverse = self._parse_order(order)
terms, gens = self.as_terms()
if not any(term.is_Order for term, _ in terms):
ordered = sorted(terms, key=key, reverse=reverse)
else:
_terms, _order = [], []
for term, repr in terms:
if not term.is_Order:
_terms.append((term, repr))
else:
_order.append((term, repr))
ordered = sorted(_terms, key=key, reverse=True) \
+ sorted(_order, key=key, reverse=True)
if data:
return ordered, gens
else:
return [term for term, _ in ordered]
def as_terms(self):
"""Transform an expression to a list of terms. """
from .exprtools import decompose_power
gens, terms = set(), []
for term in Add.make_args(self):
coeff, _term = term.as_coeff_Mul()
coeff = complex(coeff)
cpart, ncpart = {}, []
if _term is not S.One:
for factor in Mul.make_args(_term):
if factor.is_number:
try:
coeff *= complex(factor)
except (TypeError, ValueError):
pass
else:
continue
if factor.is_commutative:
base, exp = decompose_power(factor)
cpart[base] = exp
gens.add(base)
else:
ncpart.append(factor)
coeff = coeff.real, coeff.imag
ncpart = tuple(ncpart)
terms.append((term, (coeff, cpart, ncpart)))
gens = sorted(gens, key=default_sort_key)
k, indices = len(gens), {}
for i, g in enumerate(gens):
indices[g] = i
result = []
for term, (coeff, cpart, ncpart) in terms:
monom = [0]*k
for base, exp in cpart.items():
monom[indices[base]] = exp
result.append((term, (coeff, tuple(monom), ncpart)))
return result, gens
def removeO(self):
"""Removes the additive O(..) symbol if there is one"""
return self
def getO(self):
"""Returns the additive O(..) symbol if there is one, else None."""
return None
def getn(self):
"""
Returns the order of the expression.
Explanation
===========
The order is determined either from the O(...) term. If there
is no O(...) term, it returns None.
Examples
========
>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
"""
o = self.getO()
if o is None:
return None
elif o.is_Order:
o = o.expr
if o is S.One:
return S.Zero
if o.is_Symbol:
return S.One
if o.is_Pow:
return o.args[1]
if o.is_Mul: # x**n*log(x)**n or x**n/log(x)**n
for oi in o.args:
if oi.is_Symbol:
return S.One
if oi.is_Pow:
from .symbol import Dummy, Symbol
syms = oi.atoms(Symbol)
if len(syms) == 1:
x = syms.pop()
oi = oi.subs(x, Dummy('x', positive=True))
if oi.base.is_Symbol and oi.exp.is_Rational:
return abs(oi.exp)
raise NotImplementedError('not sure of order of %s' % o)
def count_ops(self, visual=None):
"""wrapper for count_ops that returns the operation count."""
from .function import count_ops
return count_ops(self, visual)
def args_cnc(self, cset=False, warn=True, split_1=True):
"""Return [commutative factors, non-commutative factors] of self.
Explanation
===========
self is treated as a Mul and the ordering of the factors is maintained.
If ``cset`` is True the commutative factors will be returned in a set.
If there were repeated factors (as may happen with an unevaluated Mul)
then an error will be raised unless it is explicitly suppressed by
setting ``warn`` to False.
Note: -1 is always separated from a Number unless split_1 is False.
Examples
========
>>> from sympy import symbols, oo
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[[-1, 2, x, y], []]
>>> (-2.5*x).args_cnc()
[[-1, 2.5, x], []]
>>> (-2*x*A*B*y).args_cnc()
[[-1, 2, x, y], [A, B]]
>>> (-2*x*A*B*y).args_cnc(split_1=False)
[[-2, x, y], [A, B]]
>>> (-2*x*y).args_cnc(cset=True)
[{-1, 2, x, y}, []]
The arg is always treated as a Mul:
>>> (-2 + x + A).args_cnc()
[[], [x - 2 + A]]
>>> (-oo).args_cnc() # -oo is a singleton
[[-1, oo], []]
"""
if self.is_Mul:
args = list(self.args)
else:
args = [self]
for i, mi in enumerate(args):
if not mi.is_commutative:
c = args[:i]
nc = args[i:]
break
else:
c = args
nc = []
if c and split_1 and (
c[0].is_Number and
c[0].is_extended_negative and
c[0] is not S.NegativeOne):
c[:1] = [S.NegativeOne, -c[0]]
if cset:
clen = len(c)
c = set(c)
if clen and warn and len(c) != clen:
raise ValueError('repeated commutative arguments: %s' %
[ci for ci in c if list(self.args).count(ci) > 1])
return [c, nc]
def coeff(self, x, n=1, right=False, _first=True):
"""
Returns the coefficient from the term(s) containing ``x**n``. If ``n``
is zero then all terms independent of ``x`` will be returned.
Explanation
===========
When ``x`` is noncommutative, the coefficient to the left (default) or
right of ``x`` can be returned. The keyword 'right' is ignored when
``x`` is commutative.
Examples
========
>>> from sympy import symbols
>>> from sympy.abc import x, y, z
You can select terms that have an explicit negative in front of them:
>>> (-x + 2*y).coeff(-1)
x
>>> (x - 2*y).coeff(-1)
2*y
You can select terms with no Rational coefficient:
>>> (x + 2*y).coeff(1)
x
>>> (3 + 2*x + 4*x**2).coeff(1)
0
You can select terms independent of x by making n=0; in this case
expr.as_independent(x)[0] is returned (and 0 will be returned instead
of None):
>>> (3 + 2*x + 4*x**2).coeff(x, 0)
3
>>> eq = ((x + 1)**3).expand() + 1
>>> eq
x**3 + 3*x**2 + 3*x + 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 2]
>>> eq -= 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 0]
You can select terms that have a numerical term in front of them:
>>> (-x - 2*y).coeff(2)
-y
>>> from sympy import sqrt
>>> (x + sqrt(2)*x).coeff(sqrt(2))
x
The matching is exact:
>>> (3 + 2*x + 4*x**2).coeff(x)
2
>>> (3 + 2*x + 4*x**2).coeff(x**2)
4
>>> (3 + 2*x + 4*x**2).coeff(x**3)
0
>>> (z*(x + y)**2).coeff((x + y)**2)
z
>>> (z*(x + y)**2).coeff(x + y)
0
In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
from the following:
>>> (x + z*(x + x*y)).coeff(x)
1
If such factoring is desired, factor_terms can be used first:
>>> from sympy import factor_terms
>>> factor_terms(x + z*(x + x*y)).coeff(x)
z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False)
>>> n.coeff(n)
1
>>> (3*n).coeff(n)
3
>>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
1 + m
>>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
m
If there is more than one possible coefficient 0 is returned:
>>> (n*m + m*n).coeff(n)
0
If there is only one possible coefficient, it is returned:
>>> (n*m + x*m*n).coeff(m*n)
x
>>> (n*m + x*m*n).coeff(m*n, right=1)
1
See Also
========
as_coefficient: separate the expression into a coefficient and factor
as_coeff_Add: separate the additive constant from an expression
as_coeff_Mul: separate the multiplicative constant from an expression
as_independent: separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
"""
x = sympify(x)
if not isinstance(x, Basic):
return S.Zero
n = as_int(n)
if not x:
return S.Zero
if x == self:
if n == 1:
return S.One
return S.Zero
if x is S.One:
co = [a for a in Add.make_args(self)
if a.as_coeff_Mul()[0] is S.One]
if not co:
return S.Zero
return Add(*co)
if n == 0:
if x.is_Add and self.is_Add:
c = self.coeff(x, right=right)
if not c:
return S.Zero
if not right:
return self - Add(*[a*x for a in Add.make_args(c)])
return self - Add(*[x*a for a in Add.make_args(c)])
return self.as_independent(x, as_Add=True)[0]
# continue with the full method, looking for this power of x:
x = x**n
def incommon(l1, l2):
if not l1 or not l2:
return []
n = min(len(l1), len(l2))
for i in range(n):
if l1[i] != l2[i]:
return l1[:i]
return l1[:]
def find(l, sub, first=True):
""" Find where list sub appears in list l. When ``first`` is True
the first occurrence from the left is returned, else the last
occurrence is returned. Return None if sub is not in l.
Examples
========
>> l = range(5)*2
>> find(l, [2, 3])
2
>> find(l, [2, 3], first=0)
7
>> find(l, [2, 4])
None
"""
if not sub or not l or len(sub) > len(l):
return None
n = len(sub)
if not first:
l.reverse()
sub.reverse()
for i in range(len(l) - n + 1):
if all(l[i + j] == sub[j] for j in range(n)):
break
else:
i = None
if not first:
l.reverse()
sub.reverse()
if i is not None and not first:
i = len(l) - (i + n)
return i
co = []
args = Add.make_args(self)
self_c = self.is_commutative
x_c = x.is_commutative
if self_c and not x_c:
return S.Zero
if _first and self.is_Add and not self_c and not x_c:
# get the part that depends on x exactly
xargs = Mul.make_args(x)
d = Add(*[i for i in Add.make_args(self.as_independent(x)[1])
if all(xi in Mul.make_args(i) for xi in xargs)])
rv = d.coeff(x, right=right, _first=False)
if not rv.is_Add or not right:
return rv
c_part, nc_part = zip(*[i.args_cnc() for i in rv.args])
if has_variety(c_part):
return rv
return Add(*[Mul._from_args(i) for i in nc_part])
one_c = self_c or x_c
xargs, nx = x.args_cnc(cset=True, warn=bool(not x_c))
# find the parts that pass the commutative terms
for a in args:
margs, nc = a.args_cnc(cset=True, warn=bool(not self_c))
if nc is None:
nc = []
if len(xargs) > len(margs):
continue
resid = margs.difference(xargs)
if len(resid) + len(xargs) == len(margs):
if one_c:
co.append(Mul(*(list(resid) + nc)))
else:
co.append((resid, nc))
if one_c:
if co == []:
return S.Zero
elif co:
return Add(*co)
else: # both nc
# now check the non-comm parts
if not co:
return S.Zero
if all(n == co[0][1] for r, n in co):
ii = find(co[0][1], nx, right)
if ii is not None:
if not right:
return Mul(Add(*[Mul(*r) for r, c in co]), Mul(*co[0][1][:ii]))
else:
return Mul(*co[0][1][ii + len(nx):])
beg = reduce(incommon, (n[1] for n in co))
if beg:
ii = find(beg, nx, right)
if ii is not None:
if not right:
gcdc = co[0][0]
for i in range(1, len(co)):
gcdc = gcdc.intersection(co[i][0])
if not gcdc:
break
return Mul(*(list(gcdc) + beg[:ii]))
else:
m = ii + len(nx)
return Add(*[Mul(*(list(r) + n[m:])) for r, n in co])
end = list(reversed(
reduce(incommon, (list(reversed(n[1])) for n in co))))
if end:
ii = find(end, nx, right)
if ii is not None:
if not right:
return Add(*[Mul(*(list(r) + n[:-len(end) + ii])) for r, n in co])
else:
return Mul(*end[ii + len(nx):])
# look for single match
hit = None
for i, (r, n) in enumerate(co):
ii = find(n, nx, right)
if ii is not None:
if not hit:
hit = ii, r, n
else:
break
else:
if hit:
ii, r, n = hit
if not right:
return Mul(*(list(r) + n[:ii]))
else:
return Mul(*n[ii + len(nx):])
return S.Zero
def as_expr(self, *gens):
"""
Convert a polynomial to a SymPy expression.
Examples
========
>>> from sympy import sin
>>> from sympy.abc import x, y
>>> f = (x**2 + x*y).as_poly(x, y)
>>> f.as_expr()
x**2 + x*y
>>> sin(x).as_expr()
sin(x)
"""
return self
def as_coefficient(self, expr):
"""
Extracts symbolic coefficient at the given expression. In
other words, this functions separates 'self' into the product
of 'expr' and 'expr'-free coefficient. If such separation
is not possible it will return None.
Examples
========
>>> from sympy import E, pi, sin, I, Poly
>>> from sympy.abc import x
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)
Two terms have E in them so a sum is returned. (If one were
desiring the coefficient of the term exactly matching E then
the constant from the returned expression could be selected.
Or, for greater precision, a method of Poly can be used to
indicate the desired term from which the coefficient is
desired.)
>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> _.args[0] # just want the exact match
2
>>> p = Poly(2*E + x*E); p
Poly(x*E + 2*E, x, E, domain='ZZ')
>>> p.coeff_monomial(E)
2
>>> p.nth(0, 1)
2
Since the following cannot be written as a product containing
E as a factor, None is returned. (If the coefficient ``2*x`` is
desired then the ``coeff`` method should be used.)
>>> (2*E*x + x).as_coefficient(E)
>>> (2*E*x + x).coeff(E)
2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)
See Also
========
coeff: return sum of terms have a given factor
as_coeff_Add: separate the additive constant from an expression
as_coeff_Mul: separate the multiplicative constant from an expression
as_independent: separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
"""
r = self.extract_multiplicatively(expr)
if r and not r.has(expr):
return r
def as_independent(self, *deps, **hint) -> tuple[Expr, Expr]:
"""
A mostly naive separation of a Mul or Add into arguments that are not
are dependent on deps. To obtain as complete a separation of variables
as possible, use a separation method first, e.g.:
* separatevars() to change Mul, Add and Pow (including exp) into Mul
* .expand(mul=True) to change Add or Mul into Add
* .expand(log=True) to change log expr into an Add
The only non-naive thing that is done here is to respect noncommutative
ordering of variables and to always return (0, 0) for `self` of zero
regardless of hints.
For nonzero `self`, the returned tuple (i, d) has the
following interpretation:
* i will has no variable that appears in deps
* d will either have terms that contain variables that are in deps, or
be equal to 0 (when self is an Add) or 1 (when self is a Mul)
* if self is an Add then self = i + d
* if self is a Mul then self = i*d
* otherwise (self, S.One) or (S.One, self) is returned.
To force the expression to be treated as an Add, use the hint as_Add=True
Examples
========
-- self is an Add
>>> from sympy import sin, cos, exp
>>> from sympy.abc import x, y, z
>>> (x + x*y).as_independent(x)
(0, x*y + x)
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> (2*x*sin(x) + y + x + z).as_independent(x)
(y + z, 2*x*sin(x) + x)
>>> (2*x*sin(x) + y + x + z).as_independent(x, y)
(z, 2*x*sin(x) + x + y)
-- self is a Mul
>>> (x*sin(x)*cos(y)).as_independent(x)
(cos(y), x*sin(x))
non-commutative terms cannot always be separated out when self is a Mul
>>> from sympy import symbols
>>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
>>> (n1 + n1*n2).as_independent(n2)
(n1, n1*n2)
>>> (n2*n1 + n1*n2).as_independent(n2)
(0, n1*n2 + n2*n1)
>>> (n1*n2*n3).as_independent(n1)
(1, n1*n2*n3)
>>> (n1*n2*n3).as_independent(n2)
(n1, n2*n3)
>>> ((x-n1)*(x-y)).as_independent(x)
(1, (x - y)*(x - n1))
-- self is anything else:
>>> (sin(x)).as_independent(x)
(1, sin(x))
>>> (sin(x)).as_independent(y)
(sin(x), 1)
>>> exp(x+y).as_independent(x)
(1, exp(x + y))
-- force self to be treated as an Add:
>>> (3*x).as_independent(x, as_Add=True)
(0, 3*x)
-- force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=False)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=False)
(1, x - 3)
Note how the below differs from the above in making the
constant on the dep term positive.
>>> (y*(-3+x)).as_independent(x)
(y, x - 3)
-- use .as_independent() for true independence testing instead
of .has(). The former considers only symbols in the free
symbols while the latter considers all symbols
>>> from sympy import Integral
>>> I = Integral(x, (x, 1, 2))
>>> I.has(x)
True
>>> x in I.free_symbols
False
>>> I.as_independent(x) == (I, 1)
True
>>> (I + x).as_independent(x) == (I, x)
True
Note: when trying to get independent terms, a separation method
might need to be used first. In this case, it is important to keep
track of what you send to this routine so you know how to interpret
the returned values
>>> from sympy import separatevars, log
>>> separatevars(exp(x+y)).as_independent(x)
(exp(y), exp(x))
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> separatevars(x + x*y).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).expand(mul=True).as_independent(y)
(x, x*y)
>>> a, b=symbols('a b', positive=True)
>>> (log(a*b).expand(log=True)).as_independent(b)
(log(a), log(b))
See Also
========
.separatevars(), .expand(log=True), sympy.core.add.Add.as_two_terms(),
sympy.core.mul.Mul.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
"""
from .symbol import Symbol
from .add import _unevaluated_Add
from .mul import _unevaluated_Mul
if self is S.Zero:
return (self, self)
func = self.func
if hint.get('as_Add', isinstance(self, Add) ):
want = Add
else:
want = Mul
# sift out deps into symbolic and other and ignore
# all symbols but those that are in the free symbols
sym = set()
other = []
for d in deps:
if isinstance(d, Symbol): # Symbol.is_Symbol is True
sym.add(d)
else:
other.append(d)
def has(e):
"""return the standard has() if there are no literal symbols, else
check to see that symbol-deps are in the free symbols."""
has_other = e.has(*other)
if not sym:
return has_other
return has_other or e.has(*(e.free_symbols & sym))
if (want is not func or
func is not Add and func is not Mul):
if has(self):
return (want.identity, self)
else:
return (self, want.identity)
else:
if func is Add:
args = list(self.args)
else:
args, nc = self.args_cnc()
d = sift(args, has)
depend = d[True]
indep = d[False]
if func is Add: # all terms were treated as commutative
return (Add(*indep), _unevaluated_Add(*depend))
else: # handle noncommutative by stopping at first dependent term
for i, n in enumerate(nc):
if has(n):
depend.extend(nc[i:])
break
indep.append(n)
return Mul(*indep), (
Mul(*depend, evaluate=False) if nc else
_unevaluated_Mul(*depend))
def as_real_imag(self, deep=True, **hints):
"""Performs complex expansion on 'self' and returns a tuple
containing collected both real and imaginary parts. This
method cannot be confused with re() and im() functions,
which does not perform complex expansion at evaluation.
However it is possible to expand both re() and im()
functions and get exactly the same results as with
a single call to this function.
>>> from sympy import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from sympy.abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
"""
if hints.get('ignore') == self:
return None
else:
from sympy.functions.elementary.complexes import im, re
return (re(self), im(self))
def as_powers_dict(self):
"""Return self as a dictionary of factors with each factor being
treated as a power. The keys are the bases of the factors and the
values, the corresponding exponents. The resulting dictionary should
be used with caution if the expression is a Mul and contains non-
commutative factors since the order that they appeared will be lost in
the dictionary.
See Also
========
as_ordered_factors: An alternative for noncommutative applications,
returning an ordered list of factors.
args_cnc: Similar to as_ordered_factors, but guarantees separation
of commutative and noncommutative factors.
"""
d = defaultdict(int)
d.update(dict([self.as_base_exp()]))
return d
def as_coefficients_dict(self, *syms):
"""Return a dictionary mapping terms to their Rational coefficient.
Since the dictionary is a defaultdict, inquiries about terms which
were not present will return a coefficient of 0.
If symbols ``syms`` are provided, any multiplicative terms
independent of them will be considered a coefficient and a
regular dictionary of syms-dependent generators as keys and
their corresponding coefficients as values will be returned.
Examples
========
>>> from sympy.abc import a, x, y
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
>>> (3*a*x).as_coefficients_dict(x)
{x: 3*a}
>>> (3*a*x).as_coefficients_dict(y)
{1: 3*a*x}
"""
d = defaultdict(list)
if not syms:
for ai in Add.make_args(self):
c, m = ai.as_coeff_Mul()
d[m].append(c)
for k, v in d.items():
if len(v) == 1:
d[k] = v[0]
else:
d[k] = Add(*v)
else:
ind, dep = self.as_independent(*syms, as_Add=True)
for i in Add.make_args(dep):
if i.is_Mul:
c, x = i.as_coeff_mul(*syms)
if c is S.One:
d[i].append(c)
else:
d[i._new_rawargs(*x)].append(c)
elif i:
d[i].append(S.One)
d = {k: Add(*d[k]) for k in d}
if ind is not S.Zero:
d.update({S.One: ind})
di = defaultdict(int)
di.update(d)
return di
def as_base_exp(self) -> tuple[Expr, Expr]:
# a -> b ** e
return self, S.One
def as_coeff_mul(self, *deps, **kwargs) -> tuple[Expr, tuple[Expr, ...]]:
"""Return the tuple (c, args) where self is written as a Mul, ``m``.
c should be a Rational multiplied by any factors of the Mul that are
independent of deps.
args should be a tuple of all other factors of m; args is empty
if self is a Number or if self is independent of deps (when given).
This should be used when you do not know if self is a Mul or not but
you want to treat self as a Mul or if you want to process the
individual arguments of the tail of self as a Mul.
- if you know self is a Mul and want only the head, use self.args[0];
- if you do not want to process the arguments of the tail but need the
tail then use self.as_two_terms() which gives the head and tail;
- if you want to split self into an independent and dependent parts
use ``self.as_independent(*deps)``
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())
"""
if deps:
if not self.has(*deps):
return self, tuple()
return S.One, (self,)
def as_coeff_add(self, *deps) -> tuple[Expr, tuple[Expr, ...]]:
"""Return the tuple (c, args) where self is written as an Add, ``a``.
c should be a Rational added to any terms of the Add that are
independent of deps.
args should be a tuple of all other terms of ``a``; args is empty
if self is a Number or if self is independent of deps (when given).
This should be used when you do not know if self is an Add or not but
you want to treat self as an Add or if you want to process the
individual arguments of the tail of self as an Add.
- if you know self is an Add and want only the head, use self.args[0];
- if you do not want to process the arguments of the tail but need the
tail then use self.as_two_terms() which gives the head and tail.
- if you want to split self into an independent and dependent parts
use ``self.as_independent(*deps)``
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x).as_coeff_add()
(3, (x,))
>>> (3 + x + y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
"""
if deps:
if not self.has_free(*deps):
return self, tuple()
return S.Zero, (self,)
def primitive(self):
"""Return the positive Rational that can be extracted non-recursively
from every term of self (i.e., self is treated like an Add). This is
like the as_coeff_Mul() method but primitive always extracts a positive
Rational (never a negative or a Float).
Examples
========
>>> from sympy.abc import x
>>> (3*(x + 1)**2).primitive()
(3, (x + 1)**2)
>>> a = (6*x + 2); a.primitive()
(2, 3*x + 1)
>>> b = (x/2 + 3); b.primitive()
(1/2, x + 6)
>>> (a*b).primitive() == (1, a*b)
True
"""
if not self:
return S.One, S.Zero
c, r = self.as_coeff_Mul(rational=True)
if c.is_negative:
c, r = -c, -r
return c, r
def as_content_primitive(self, radical=False, clear=True):
"""This method should recursively remove a Rational from all arguments
and return that (content) and the new self (primitive). The content
should always be positive and ``Mul(*foo.as_content_primitive()) == foo``.
The primitive need not be in canonical form and should try to preserve
the underlying structure if possible (i.e. expand_mul should not be
applied to self).
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x, y, z
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)
The as_content_primitive function is recursive and retains structure:
>>> eq.as_content_primitive()
(2, x + 3*y*(y + 1) + 1)
Integer powers will have Rationals extracted from the base:
>>> ((2 + 6*x)**2).as_content_primitive()
(4, (3*x + 1)**2)
>>> ((2 + 6*x)**(2*y)).as_content_primitive()
(1, (2*(3*x + 1))**(2*y))
Terms may end up joining once their as_content_primitives are added:
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(11, x*(y + 1))
>>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(9, x*(y + 1))
>>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
(1, 6.0*x*(y + 1) + 3*z*(y + 1))
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
(121, x**2*(y + 1)**2)
>>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive()
(1, 4.84*x**2*(y + 1)**2)
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))
If clear=False (default is True) then content will not be removed
from an Add if it can be distributed to leave one or more
terms with integer coefficients.
>>> (x/2 + y).as_content_primitive()
(1/2, x + 2*y)
>>> (x/2 + y).as_content_primitive(clear=False)
(1, x/2 + y)
"""
return S.One, self
def as_numer_denom(self):
""" expression -> a/b -> a, b
This is just a stub that should be defined by
an object's class methods to get anything else.
See Also
========
normal: return ``a/b`` instead of ``(a, b)``
"""
return self, S.One
def normal(self):
""" expression -> a/b
See Also
========
as_numer_denom: return ``(a, b)`` instead of ``a/b``
"""
from .mul import _unevaluated_Mul
n, d = self.as_numer_denom()
if d is S.One:
return n
if d.is_Number:
return _unevaluated_Mul(n, 1/d)
else:
return n/d
def extract_multiplicatively(self, c):
"""Return None if it's not possible to make self in the form
c * something in a nice way, i.e. preserving the properties
of arguments of self.
Examples
========
>>> from sympy import symbols, Rational
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_multiplicatively(x**2 * y)
x*y**2
>>> ((x*y)**3).extract_multiplicatively(x**4 * y)
>>> (2*x).extract_multiplicatively(2)
x
>>> (2*x).extract_multiplicatively(3)
>>> (Rational(1, 2)*x).extract_multiplicatively(3)
x/6
"""
from sympy.functions.elementary.exponential import exp
from .add import _unevaluated_Add
c = sympify(c)
if self is S.NaN:
return None
if c is S.One:
return self
elif c == self:
return S.One
if c.is_Add:
cc, pc = c.primitive()
if cc is not S.One:
c = Mul(cc, pc, evaluate=False)
if c.is_Mul:
a, b = c.as_two_terms()
x = self.extract_multiplicatively(a)
if x is not None:
return x.extract_multiplicatively(b)
else:
return x
quotient = self / c
if self.is_Number:
if self is S.Infinity:
if c.is_positive:
return S.Infinity
elif self is S.NegativeInfinity:
if c.is_negative:
return S.Infinity
elif c.is_positive:
return S.NegativeInfinity
elif self is S.ComplexInfinity:
if not c.is_zero:
return S.ComplexInfinity
elif self.is_Integer:
if not quotient.is_Integer:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_Rational:
if not quotient.is_Rational:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_Float:
if not quotient.is_Float:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_NumberSymbol or self.is_Symbol or self is S.ImaginaryUnit:
if quotient.is_Mul and len(quotient.args) == 2:
if quotient.args[0].is_Integer and quotient.args[0].is_positive and quotient.args[1] == self:
return quotient
elif quotient.is_Integer and c.is_Number:
return quotient
elif self.is_Add:
cs, ps = self.primitive()
# assert cs >= 1
if c.is_Number and c is not S.NegativeOne:
# assert c != 1 (handled at top)
if cs is not S.One:
if c.is_negative:
xc = -(cs.extract_multiplicatively(-c))
else:
xc = cs.extract_multiplicatively(c)
if xc is not None:
return xc*ps # rely on 2-arg Mul to restore Add
return # |c| != 1 can only be extracted from cs
if c == ps:
return cs
# check args of ps
newargs = []
for arg in ps.args:
newarg = arg.extract_multiplicatively(c)
if newarg is None:
return # all or nothing
newargs.append(newarg)
if cs is not S.One:
args = [cs*t for t in newargs]
# args may be in different order
return _unevaluated_Add(*args)
else:
return Add._from_args(newargs)
elif self.is_Mul:
args = list(self.args)
for i, arg in enumerate(args):
newarg = arg.extract_multiplicatively(c)
if newarg is not None:
args[i] = newarg
return Mul(*args)
elif self.is_Pow or isinstance(self, exp):
sb, se = self.as_base_exp()
cb, ce = c.as_base_exp()
if cb == sb:
new_exp = se.extract_additively(ce)
if new_exp is not None:
return Pow(sb, new_exp)
elif c == sb:
new_exp = self.exp.extract_additively(1)
if new_exp is not None:
return Pow(sb, new_exp)
def extract_additively(self, c):
"""Return self - c if it's possible to subtract c from self and
make all matching coefficients move towards zero, else return None.
Examples
========
>>> from sympy.abc import x, y
>>> e = 2*x + 3
>>> e.extract_additively(x + 1)
x + 2
>>> e.extract_additively(3*x)
>>> e.extract_additively(4)
>>> (y*(x + 1)).extract_additively(x + 1)
>>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
(x + 1)*(x + 2*y) + 3
See Also
========
extract_multiplicatively
coeff
as_coefficient
"""
c = sympify(c)
if self is S.NaN:
return None
if c.is_zero:
return self
elif c == self:
return S.Zero
elif self == S.Zero:
return None
if self.is_Number:
if not c.is_Number:
return None
co = self
diff = co - c
# XXX should we match types? i.e should 3 - .1 succeed?
if (co > 0 and diff > 0 and diff < co or
co < 0 and diff < 0 and diff > co):
return diff
return None
if c.is_Number:
co, t = self.as_coeff_Add()
xa = co.extract_additively(c)
if xa is None:
return None
return xa + t
# handle the args[0].is_Number case separately
# since we will have trouble looking for the coeff of
# a number.
if c.is_Add and c.args[0].is_Number:
# whole term as a term factor
co = self.coeff(c)
xa0 = (co.extract_additively(1) or 0)*c
if xa0:
diff = self - co*c
return (xa0 + (diff.extract_additively(c) or diff)) or None
# term-wise
h, t = c.as_coeff_Add()
sh, st = self.as_coeff_Add()
xa = sh.extract_additively(h)
if xa is None:
return None
xa2 = st.extract_additively(t)
if xa2 is None:
return None
return xa + xa2
# whole term as a term factor
co, diff = _corem(self, c)
xa0 = (co.extract_additively(1) or 0)*c
if xa0:
return (xa0 + (diff.extract_additively(c) or diff)) or None
# term-wise
coeffs = []
for a in Add.make_args(c):
ac, at = a.as_coeff_Mul()
co = self.coeff(at)
if not co:
return None
coc, cot = co.as_coeff_Add()
xa = coc.extract_additively(ac)
if xa is None:
return None
self -= co*at
coeffs.append((cot + xa)*at)
coeffs.append(self)
return Add(*coeffs)
@property
def expr_free_symbols(self):
"""
Like ``free_symbols``, but returns the free symbols only if
they are contained in an expression node.
Examples
========
>>> from sympy.abc import x, y
>>> (x + y).expr_free_symbols # doctest: +SKIP
{x, y}
If the expression is contained in a non-expression object, do not return
the free symbols. Compare:
>>> from sympy import Tuple
>>> t = Tuple(x + y)
>>> t.expr_free_symbols # doctest: +SKIP
set()
>>> t.free_symbols
{x, y}
"""
sympy_deprecation_warning("""
The expr_free_symbols property is deprecated. Use free_symbols to get
the free symbols of an expression.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-expr-free-symbols")
return {j for i in self.args for j in i.expr_free_symbols}
def could_extract_minus_sign(self):
"""Return True if self has -1 as a leading factor or has
more literal negative signs than positive signs in a sum,
otherwise False.
Examples
========
>>> from sympy.abc import x, y
>>> e = x - y
>>> {i.could_extract_minus_sign() for i in (e, -e)}
{False, True}
Though the ``y - x`` is considered like ``-(x - y)``, since it
is in a product without a leading factor of -1, the result is
false below:
>>> (x*(y - x)).could_extract_minus_sign()
False
To put something in canonical form wrt to sign, use `signsimp`:
>>> from sympy import signsimp
>>> signsimp(x*(y - x))
-x*(x - y)
>>> _.could_extract_minus_sign()
True
"""
return False
def extract_branch_factor(self, allow_half=False):
"""
Try to write self as ``exp_polar(2*pi*I*n)*z`` in a nice way.
Return (z, n).
>>> from sympy import exp_polar, I, pi
>>> from sympy.abc import x, y
>>> exp_polar(I*pi).extract_branch_factor()
(exp_polar(I*pi), 0)
>>> exp_polar(2*I*pi).extract_branch_factor()
(1, 1)
>>> exp_polar(-pi*I).extract_branch_factor()
(exp_polar(I*pi), -1)
>>> exp_polar(3*pi*I + x).extract_branch_factor()
(exp_polar(x + I*pi), 1)
>>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
(y*exp_polar(2*pi*x), -1)
>>> exp_polar(-I*pi/2).extract_branch_factor()
(exp_polar(-I*pi/2), 0)
If allow_half is True, also extract exp_polar(I*pi):
>>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
(1, 1/2)
>>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
(1, 1)
>>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
(1, 3/2)
>>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
(1, -1/2)
"""
from sympy.functions.elementary.exponential import exp_polar
from sympy.functions.elementary.integers import ceiling
n = S.Zero
res = S.One
args = Mul.make_args(self)
exps = []
for arg in args:
if isinstance(arg, exp_polar):
exps += [arg.exp]
else:
res *= arg
piimult = S.Zero
extras = []
ipi = S.Pi*S.ImaginaryUnit
while exps:
exp = exps.pop()
if exp.is_Add:
exps += exp.args
continue
if exp.is_Mul:
coeff = exp.as_coefficient(ipi)
if coeff is not None:
piimult += coeff
continue
extras += [exp]
if piimult.is_number:
coeff = piimult
tail = ()
else:
coeff, tail = piimult.as_coeff_add(*piimult.free_symbols)
# round down to nearest multiple of 2
branchfact = ceiling(coeff/2 - S.Half)*2
n += branchfact/2
c = coeff - branchfact
if allow_half:
nc = c.extract_additively(1)
if nc is not None:
n += S.Half
c = nc
newexp = ipi*Add(*((c, ) + tail)) + Add(*extras)
if newexp != 0:
res *= exp_polar(newexp)
return res, n
def is_polynomial(self, *syms):
r"""
Return True if self is a polynomial in syms and False otherwise.
This checks if self is an exact polynomial in syms. This function
returns False for expressions that are "polynomials" with symbolic
exponents. Thus, you should be able to apply polynomial algorithms to
expressions for which this returns True, and Poly(expr, \*syms) should
work if and only if expr.is_polynomial(\*syms) returns True. The
polynomial does not have to be in expanded form. If no symbols are
given, all free symbols in the expression will be used.
This is not part of the assumptions system. You cannot do
Symbol('z', polynomial=True).
Examples
========
>>> from sympy import Symbol, Function
>>> x = Symbol('x')
>>> ((x**2 + 1)**4).is_polynomial(x)
True
>>> ((x**2 + 1)**4).is_polynomial()
True
>>> (2**x + 1).is_polynomial(x)
False
>>> (2**x + 1).is_polynomial(2**x)
True
>>> f = Function('f')
>>> (f(x) + 1).is_polynomial(x)
False
>>> (f(x) + 1).is_polynomial(f(x))
True
>>> (1/f(x) + 1).is_polynomial(f(x))
False
>>> n = Symbol('n', nonnegative=True, integer=True)
>>> (x**n + 1).is_polynomial(x)
False
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be a polynomial to
become one.
>>> from sympy import sqrt, factor, cancel
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)
>>> a.is_polynomial(y)
False
>>> factor(a)
y + 1
>>> factor(a).is_polynomial(y)
True
>>> b = (y**2 + 2*y + 1)/(y + 1)
>>> b.is_polynomial(y)
False
>>> cancel(b)
y + 1
>>> cancel(b).is_polynomial(y)
True
See also .is_rational_function()
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if not syms:
return True
return self._eval_is_polynomial(syms)
def _eval_is_polynomial(self, syms):
if self in syms:
return True
if not self.has_free(*syms):
# constant polynomial
return True
# subclasses should return True or False
def is_rational_function(self, *syms):
"""
Test whether function is a ratio of two polynomials in the given
symbols, syms. When syms is not given, all free symbols will be used.
The rational function does not have to be in expanded or in any kind of
canonical form.
This function returns False for expressions that are "rational
functions" with symbolic exponents. Thus, you should be able to call
.as_numer_denom() and apply polynomial algorithms to the result for
expressions for which this returns True.
This is not part of the assumptions system. You cannot do
Symbol('z', rational_function=True).
Examples
========
>>> from sympy import Symbol, sin
>>> from sympy.abc import x, y
>>> (x/y).is_rational_function()
True
>>> (x**2).is_rational_function()
True
>>> (x/sin(y)).is_rational_function(y)
False
>>> n = Symbol('n', integer=True)
>>> (x**n + 1).is_rational_function(x)
False
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be a rational function
to become one.
>>> from sympy import sqrt, factor
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)/y
>>> a.is_rational_function(y)
False
>>> factor(a)
(y + 1)/y
>>> factor(a).is_rational_function(y)
True
See also is_algebraic_expr().
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if not syms:
return self not in _illegal
return self._eval_is_rational_function(syms)
def _eval_is_rational_function(self, syms):
if self in syms:
return True
if not self.has_xfree(syms):
return True
# subclasses should return True or False
def is_meromorphic(self, x, a):
"""
This tests whether an expression is meromorphic as
a function of the given symbol ``x`` at the point ``a``.
This method is intended as a quick test that will return
None if no decision can be made without simplification or
more detailed analysis.
Examples
========
>>> from sympy import zoo, log, sin, sqrt
>>> from sympy.abc import x
>>> f = 1/x**2 + 1 - 2*x**3
>>> f.is_meromorphic(x, 0)
True
>>> f.is_meromorphic(x, 1)
True
>>> f.is_meromorphic(x, zoo)
True
>>> g = x**log(3)
>>> g.is_meromorphic(x, 0)
False
>>> g.is_meromorphic(x, 1)
True
>>> g.is_meromorphic(x, zoo)
False
>>> h = sin(1/x)*x**2
>>> h.is_meromorphic(x, 0)
False
>>> h.is_meromorphic(x, 1)
True
>>> h.is_meromorphic(x, zoo)
True
Multivalued functions are considered meromorphic when their
branches are meromorphic. Thus most functions are meromorphic
everywhere except at essential singularities and branch points.
In particular, they will be meromorphic also on branch cuts
except at their endpoints.
>>> log(x).is_meromorphic(x, -1)
True
>>> log(x).is_meromorphic(x, 0)
False
>>> sqrt(x).is_meromorphic(x, -1)
True
>>> sqrt(x).is_meromorphic(x, 0)
False
"""
if not x.is_symbol:
raise TypeError("{} should be of symbol type".format(x))
a = sympify(a)
return self._eval_is_meromorphic(x, a)
def _eval_is_meromorphic(self, x, a):
if self == x:
return True
if not self.has_free(x):
return True
# subclasses should return True or False
def is_algebraic_expr(self, *syms):
"""
This tests whether a given expression is algebraic or not, in the
given symbols, syms. When syms is not given, all free symbols
will be used. The rational function does not have to be in expanded
or in any kind of canonical form.
This function returns False for expressions that are "algebraic
expressions" with symbolic exponents. This is a simple extension to the
is_rational_function, including rational exponentiation.
Examples
========
>>> from sympy import Symbol, sqrt
>>> x = Symbol('x', real=True)
>>> sqrt(1 + x).is_rational_function()
False
>>> sqrt(1 + x).is_algebraic_expr()
True
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be an algebraic
expression to become one.
>>> from sympy import exp, factor
>>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
>>> a.is_algebraic_expr(x)
False
>>> factor(a).is_algebraic_expr()
True
See Also
========
is_rational_function()
References
==========
.. [1] https://en.wikipedia.org/wiki/Algebraic_expression
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if not syms:
return True
return self._eval_is_algebraic_expr(syms)
def _eval_is_algebraic_expr(self, syms):
if self in syms:
return True
if not self.has_free(*syms):
return True
# subclasses should return True or False
###################################################################################
##################### SERIES, LEADING TERM, LIMIT, ORDER METHODS ##################
###################################################################################
def series(self, x=None, x0=0, n=6, dir="+", logx=None, cdir=0):
"""
Series expansion of "self" around ``x = x0`` yielding either terms of
the series one by one (the lazy series given when n=None), else
all the terms at once when n != None.
Returns the series expansion of "self" around the point ``x = x0``
with respect to ``x`` up to ``O((x - x0)**n, x, x0)`` (default n is 6).
If ``x=None`` and ``self`` is univariate, the univariate symbol will
be supplied, otherwise an error will be raised.
Parameters
==========
expr : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
x0 : Value
The value around which ``x`` is calculated. Can be any value
from ``-oo`` to ``oo``.
n : Value
The value used to represent the order in terms of ``x**n``,
up to which the series is to be expanded.
dir : String, optional
The series-expansion can be bi-directional. If ``dir="+"``,
then (x->x0+). If ``dir="-", then (x->x0-). For infinite
``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined
from the direction of the infinity (i.e., ``dir="-"`` for
``oo``).
logx : optional
It is used to replace any log(x) in the returned series with a
symbolic value rather than evaluating the actual value.
cdir : optional
It stands for complex direction, and indicates the direction
from which the expansion needs to be evaluated.
Examples
========
>>> from sympy import cos, exp, tan
>>> from sympy.abc import x, y
>>> cos(x).series()
1 - x**2/2 + x**4/24 + O(x**6)
>>> cos(x).series(n=4)
1 - x**2/2 + O(x**4)
>>> cos(x).series(x, x0=1, n=2)
cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
>>> e = cos(x + exp(y))
>>> e.series(y, n=2)
cos(x + 1) - y*sin(x + 1) + O(y**2)
>>> e.series(x, n=2)
cos(exp(y)) - x*sin(exp(y)) + O(x**2)
If ``n=None`` then a generator of the series terms will be returned.
>>> term=cos(x).series(n=None)
>>> [next(term) for i in range(2)]
[1, -x**2/2]
For ``dir=+`` (default) the series is calculated from the right and
for ``dir=-`` the series from the left. For smooth functions this
flag will not alter the results.
>>> abs(x).series(dir="+")
x
>>> abs(x).series(dir="-")
-x
>>> f = tan(x)
>>> f.series(x, 2, 6, "+")
tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
(x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
>>> f.series(x, 2, 3, "-")
tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
+ O((x - 2)**3, (x, 2))
For rational expressions this method may return original expression without the Order term.
>>> (1/x).series(x, n=8)
1/x
Returns
=======
Expr : Expression
Series expansion of the expression about x0
Raises
======
TypeError
If "n" and "x0" are infinity objects
PoleError
If "x0" is an infinity object
"""
if x is None:
syms = self.free_symbols
if not syms:
return self
elif len(syms) > 1:
raise ValueError('x must be given for multivariate functions.')
x = syms.pop()
from .symbol import Dummy, Symbol
if isinstance(x, Symbol):
dep = x in self.free_symbols
else:
d = Dummy()
dep = d in self.xreplace({x: d}).free_symbols
if not dep:
if n is None:
return (s for s in [self])
else:
return self
if len(dir) != 1 or dir not in '+-':
raise ValueError("Dir must be '+' or '-'")
x0 = sympify(x0)
cdir = sympify(cdir)
from sympy.functions.elementary.complexes import im, sign
if not cdir.is_zero:
if cdir.is_real:
dir = '+' if cdir.is_positive else '-'
else:
dir = '+' if im(cdir).is_positive else '-'
else:
if x0 and x0.is_infinite:
cdir = sign(x0).simplify()
elif str(dir) == "+":
cdir = S.One
elif str(dir) == "-":
cdir = S.NegativeOne
elif cdir == S.Zero:
cdir = S.One
cdir = cdir/abs(cdir)
if x0 and x0.is_infinite:
from .function import PoleError
try:
s = self.subs(x, cdir/x).series(x, n=n, dir='+', cdir=1)
if n is None:
return (si.subs(x, cdir/x) for si in s)
return s.subs(x, cdir/x)
except PoleError:
s = self.subs(x, cdir*x).aseries(x, n=n)
return s.subs(x, cdir*x)
# use rep to shift origin to x0 and change sign (if dir is negative)
# and undo the process with rep2
if x0 or cdir != 1:
s = self.subs({x: x0 + cdir*x}).series(x, x0=0, n=n, dir='+', logx=logx, cdir=1)
if n is None: # lseries...
return (si.subs({x: x/cdir - x0/cdir}) for si in s)
return s.subs({x: x/cdir - x0/cdir})
# from here on it's x0=0 and dir='+' handling
if x.is_positive is x.is_negative is None or x.is_Symbol is not True:
# replace x with an x that has a positive assumption
xpos = Dummy('x', positive=True)
rv = self.subs(x, xpos).series(xpos, x0, n, dir, logx=logx, cdir=cdir)
if n is None:
return (s.subs(xpos, x) for s in rv)
else:
return rv.subs(xpos, x)
from sympy.series.order import Order
if n is not None: # nseries handling
s1 = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
o = s1.getO() or S.Zero
if o:
# make sure the requested order is returned
ngot = o.getn()
if ngot > n:
# leave o in its current form (e.g. with x*log(x)) so
# it eats terms properly, then replace it below
if n != 0:
s1 += o.subs(x, x**Rational(n, ngot))
else:
s1 += Order(1, x)
elif ngot < n:
# increase the requested number of terms to get the desired
# number keep increasing (up to 9) until the received order
# is different than the original order and then predict how
# many additional terms are needed
from sympy.functions.elementary.integers import ceiling
for more in range(1, 9):
s1 = self._eval_nseries(x, n=n + more, logx=logx, cdir=cdir)
newn = s1.getn()
if newn != ngot:
ndo = n + ceiling((n - ngot)*more/(newn - ngot))
s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
while s1.getn() < n:
s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
ndo += 1
break
else:
raise ValueError('Could not calculate %s terms for %s'
% (str(n), self))
s1 += Order(x**n, x)
o = s1.getO()
s1 = s1.removeO()
elif s1.has(Order):
# asymptotic expansion
return s1
else:
o = Order(x**n, x)
s1done = s1.doit()
try:
if (s1done + o).removeO() == s1done:
o = S.Zero
except NotImplementedError:
return s1
try:
from sympy.simplify.radsimp import collect
return collect(s1, x) + o
except NotImplementedError:
return s1 + o
else: # lseries handling
def yield_lseries(s):
"""Return terms of lseries one at a time."""
for si in s:
if not si.is_Add:
yield si
continue
# yield terms 1 at a time if possible
# by increasing order until all the
# terms have been returned
yielded = 0
o = Order(si, x)*x
ndid = 0
ndo = len(si.args)
while 1:
do = (si - yielded + o).removeO()
o *= x
if not do or do.is_Order:
continue
if do.is_Add:
ndid += len(do.args)
else:
ndid += 1
yield do
if ndid == ndo:
break
yielded += do
return yield_lseries(self.removeO()._eval_lseries(x, logx=logx, cdir=cdir))
def aseries(self, x=None, n=6, bound=0, hir=False):
"""Asymptotic Series expansion of self.
This is equivalent to ``self.series(x, oo, n)``.
Parameters
==========
self : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
n : Value
The value used to represent the order in terms of ``x**n``,
up to which the series is to be expanded.
hir : Boolean
Set this parameter to be True to produce hierarchical series.
It stops the recursion at an early level and may provide nicer
and more useful results.
bound : Value, Integer
Use the ``bound`` parameter to give limit on rewriting
coefficients in its normalised form.
Examples
========
>>> from sympy import sin, exp
>>> from sympy.abc import x
>>> e = sin(1/x + exp(-x)) - sin(1/x)
>>> e.aseries(x)
(1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
>>> e.aseries(x, n=3, hir=True)
-exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
>>> e = exp(exp(x)/(1 - 1/x))
>>> e.aseries(x)
exp(exp(x)/(1 - 1/x))
>>> e.aseries(x, bound=3) # doctest: +SKIP
exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))
For rational expressions this method may return original expression without the Order term.
>>> (1/x).aseries(x, n=8)
1/x
Returns
=======
Expr
Asymptotic series expansion of the expression.
Notes
=====
This algorithm is directly induced from the limit computational algorithm provided by Gruntz.
It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first
to look for the most rapidly varying subexpression w of a given expression f and then expands f
in a series in w. Then same thing is recursively done on the leading coefficient
till we get constant coefficients.
If the most rapidly varying subexpression of a given expression f is f itself,
the algorithm tries to find a normalised representation of the mrv set and rewrites f
using this normalised representation.
If the expansion contains an order term, it will be either ``O(x ** (-n))`` or ``O(w ** (-n))``
where ``w`` belongs to the most rapidly varying expression of ``self``.
References
==========
.. [1] Gruntz, Dominik. A new algorithm for computing asymptotic series.
In: Proc. 1993 Int. Symp. Symbolic and Algebraic Computation. 1993.
pp. 239-244.
.. [2] Gruntz thesis - p90
.. [3] http://en.wikipedia.org/wiki/Asymptotic_expansion
See Also
========
Expr.aseries: See the docstring of this function for complete details of this wrapper.
"""
from .symbol import Dummy
if x.is_positive is x.is_negative is None:
xpos = Dummy('x', positive=True)
return self.subs(x, xpos).aseries(xpos, n, bound, hir).subs(xpos, x)
from .function import PoleError
from sympy.series.gruntz import mrv, rewrite
try:
om, exps = mrv(self, x)
except PoleError:
return self
# We move one level up by replacing `x` by `exp(x)`, and then
# computing the asymptotic series for f(exp(x)). Then asymptotic series
# can be obtained by moving one-step back, by replacing x by ln(x).
from sympy.functions.elementary.exponential import exp, log
from sympy.series.order import Order
if x in om:
s = self.subs(x, exp(x)).aseries(x, n, bound, hir).subs(x, log(x))
if s.getO():
return s + Order(1/x**n, (x, S.Infinity))
return s
k = Dummy('k', positive=True)
# f is rewritten in terms of omega
func, logw = rewrite(exps, om, x, k)
if self in om:
if bound <= 0:
return self
s = (self.exp).aseries(x, n, bound=bound)
s = s.func(*[t.removeO() for t in s.args])
try:
res = exp(s.subs(x, 1/x).as_leading_term(x).subs(x, 1/x))
except PoleError:
res = self
func = exp(self.args[0] - res.args[0]) / k
logw = log(1/res)
s = func.series(k, 0, n)
# Hierarchical series
if hir:
return s.subs(k, exp(logw))
o = s.getO()
terms = sorted(Add.make_args(s.removeO()), key=lambda i: int(i.as_coeff_exponent(k)[1]))
s = S.Zero
has_ord = False
# Then we recursively expand these coefficients one by one into
# their asymptotic series in terms of their most rapidly varying subexpressions.
for t in terms:
coeff, expo = t.as_coeff_exponent(k)
if coeff.has(x):
# Recursive step
snew = coeff.aseries(x, n, bound=bound-1)
if has_ord and snew.getO():
break
elif snew.getO():
has_ord = True
s += (snew * k**expo)
else:
s += t
if not o or has_ord:
return s.subs(k, exp(logw))
return (s + o).subs(k, exp(logw))
def taylor_term(self, n, x, *previous_terms):
"""General method for the taylor term.
This method is slow, because it differentiates n-times. Subclasses can
redefine it to make it faster by using the "previous_terms".
"""
from .symbol import Dummy
from sympy.functions.combinatorial.factorials import factorial
x = sympify(x)
_x = Dummy('x')
return self.subs(x, _x).diff(_x, n).subs(_x, x).subs(x, 0) * x**n / factorial(n)
def lseries(self, x=None, x0=0, dir='+', logx=None, cdir=0):
"""
Wrapper for series yielding an iterator of the terms of the series.
Note: an infinite series will yield an infinite iterator. The following,
for exaxmple, will never terminate. It will just keep printing terms
of the sin(x) series::
for term in sin(x).lseries(x):
print term
The advantage of lseries() over nseries() is that many times you are
just interested in the next term in the series (i.e. the first term for
example), but you do not know how many you should ask for in nseries()
using the "n" parameter.
See also nseries().
"""
return self.series(x, x0, n=None, dir=dir, logx=logx, cdir=cdir)
def _eval_lseries(self, x, logx=None, cdir=0):
# default implementation of lseries is using nseries(), and adaptively
# increasing the "n". As you can see, it is not very efficient, because
# we are calculating the series over and over again. Subclasses should
# override this method and implement much more efficient yielding of
# terms.
n = 0
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
while series.is_Order:
n += 1
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
e = series.removeO()
yield e
if e is S.Zero:
return
while 1:
while 1:
n += 1
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir).removeO()
if e != series:
break
if (series - self).cancel() is S.Zero:
return
yield series - e
e = series
def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0):
"""
Wrapper to _eval_nseries if assumptions allow, else to series.
If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is
called. This calculates "n" terms in the innermost expressions and
then builds up the final series just by "cross-multiplying" everything
out.
The optional ``logx`` parameter can be used to replace any log(x) in the
returned series with a symbolic value to avoid evaluating log(x) at 0. A
symbol to use in place of log(x) should be provided.
Advantage -- it's fast, because we do not have to determine how many
terms we need to calculate in advance.
Disadvantage -- you may end up with less terms than you may have
expected, but the O(x**n) term appended will always be correct and
so the result, though perhaps shorter, will also be correct.
If any of those assumptions is not met, this is treated like a
wrapper to series which will try harder to return the correct
number of terms.
See also lseries().
Examples
========
>>> from sympy import sin, log, Symbol
>>> from sympy.abc import x, y
>>> sin(x).nseries(x, 0, 6)
x - x**3/6 + x**5/120 + O(x**6)
>>> log(x+1).nseries(x, 0, 5)
x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
Handling of the ``logx`` parameter --- in the following example the
expansion fails since ``sin`` does not have an asymptotic expansion
at -oo (the limit of log(x) as x approaches 0):
>>> e = sin(log(x))
>>> e.nseries(x, 0, 6)
Traceback (most recent call last):
...
PoleError: ...
...
>>> logx = Symbol('logx')
>>> e.nseries(x, 0, 6, logx=logx)
sin(logx)
In the following example, the expansion works but only returns self
unless the ``logx`` parameter is used:
>>> e = x**y
>>> e.nseries(x, 0, 2)
x**y
>>> e.nseries(x, 0, 2, logx=logx)
exp(logx*y)
"""
if x and x not in self.free_symbols:
return self
if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None):
return self.series(x, x0, n, dir, cdir=cdir)
else:
return self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir):
"""
Return terms of series for self up to O(x**n) at x=0
from the positive direction.
This is a method that should be overridden in subclasses. Users should
never call this method directly (use .nseries() instead), so you do not
have to write docstrings for _eval_nseries().
"""
raise NotImplementedError(filldedent("""
The _eval_nseries method should be added to
%s to give terms up to O(x**n) at x=0
from the positive direction so it is available when
nseries calls it.""" % self.func)
)
def limit(self, x, xlim, dir='+'):
""" Compute limit x->xlim.
"""
from sympy.series.limits import limit
return limit(self, x, xlim, dir)
def compute_leading_term(self, x, logx=None):
"""
as_leading_term is only allowed for results of .series()
This is a wrapper to compute a series first.
"""
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(
feature="compute_leading_term",
useinstead="as_leading_term",
issue=21843,
deprecated_since_version="1.12"
).warn()
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
if self.has(Piecewise):
expr = piecewise_fold(self)
else:
expr = self
if self.removeO() == 0:
return self
from .symbol import Dummy
from sympy.functions.elementary.exponential import log
from sympy.series.order import Order
_logx = logx
logx = Dummy('logx') if logx is None else logx
res = Order(1)
incr = S.One
while res.is_Order:
res = expr._eval_nseries(x, n=1+incr, logx=logx).cancel().powsimp().trigsimp()
incr *= 2
if _logx is None:
res = res.subs(logx, log(x))
return res.as_leading_term(x)
@cacheit
def as_leading_term(self, *symbols, logx=None, cdir=0):
"""
Returns the leading (nonzero) term of the series expansion of self.
The _eval_as_leading_term routines are used to do this, and they must
always return a non-zero value.
Examples
========
>>> from sympy.abc import x
>>> (1 + x + x**2).as_leading_term(x)
1
>>> (1/x**2 + x + x**2).as_leading_term(x)
x**(-2)
"""
if len(symbols) > 1:
c = self
for x in symbols:
c = c.as_leading_term(x, logx=logx, cdir=cdir)
return c
elif not symbols:
return self
x = sympify(symbols[0])
if not x.is_symbol:
raise ValueError('expecting a Symbol but got %s' % x)
if x not in self.free_symbols:
return self
obj = self._eval_as_leading_term(x, logx=logx, cdir=cdir)
if obj is not None:
from sympy.simplify.powsimp import powsimp
return powsimp(obj, deep=True, combine='exp')
raise NotImplementedError('as_leading_term(%s, %s)' % (self, x))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
return self
def as_coeff_exponent(self, x) -> tuple[Expr, Expr]:
""" ``c*x**e -> c,e`` where x can be any symbolic expression.
"""
from sympy.simplify.radsimp import collect
s = collect(self, x)
c, p = s.as_coeff_mul(x)
if len(p) == 1:
b, e = p[0].as_base_exp()
if b == x:
return c, e
return s, S.Zero
def leadterm(self, x, logx=None, cdir=0):
"""
Returns the leading term a*x**b as a tuple (a, b).
Examples
========
>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
"""
from .symbol import Dummy
from sympy.functions.elementary.exponential import log
l = self.as_leading_term(x, logx=logx, cdir=cdir)
d = Dummy('logx')
if l.has(log(x)):
l = l.subs(log(x), d)
c, e = l.as_coeff_exponent(x)
if x in c.free_symbols:
raise ValueError(filldedent("""
cannot compute leadterm(%s, %s). The coefficient
should have been free of %s but got %s""" % (self, x, x, c)))
c = c.subs(d, log(x))
return c, e
def as_coeff_Mul(self, rational: bool = False) -> tuple['Number', Expr]:
"""Efficiently extract the coefficient of a product. """
return S.One, self
def as_coeff_Add(self, rational=False) -> tuple['Number', Expr]:
"""Efficiently extract the coefficient of a summation. """
return S.Zero, self
def fps(self, x=None, x0=0, dir=1, hyper=True, order=4, rational=True,
full=False):
"""
Compute formal power power series of self.
See the docstring of the :func:`fps` function in sympy.series.formal for
more information.
"""
from sympy.series.formal import fps
return fps(self, x, x0, dir, hyper, order, rational, full)
def fourier_series(self, limits=None):
"""Compute fourier sine/cosine series of self.
See the docstring of the :func:`fourier_series` in sympy.series.fourier
for more information.
"""
from sympy.series.fourier import fourier_series
return fourier_series(self, limits)
###################################################################################
##################### DERIVATIVE, INTEGRAL, FUNCTIONAL METHODS ####################
###################################################################################
def diff(self, *symbols, **assumptions):
assumptions.setdefault("evaluate", True)
return _derivative_dispatch(self, *symbols, **assumptions)
###########################################################################
###################### EXPRESSION EXPANSION METHODS #######################
###########################################################################
# Relevant subclasses should override _eval_expand_hint() methods. See
# the docstring of expand() for more info.
def _eval_expand_complex(self, **hints):
real, imag = self.as_real_imag(**hints)
return real + S.ImaginaryUnit*imag
@staticmethod
def _expand_hint(expr, hint, deep=True, **hints):
"""
Helper for ``expand()``. Recursively calls ``expr._eval_expand_hint()``.
Returns ``(expr, hit)``, where expr is the (possibly) expanded
``expr`` and ``hit`` is ``True`` if ``expr`` was truly expanded and
``False`` otherwise.
"""
hit = False
# XXX: Hack to support non-Basic args
# |
# V
if deep and getattr(expr, 'args', ()) and not expr.is_Atom:
sargs = []
for arg in expr.args:
arg, arghit = Expr._expand_hint(arg, hint, **hints)
hit |= arghit
sargs.append(arg)
if hit:
expr = expr.func(*sargs)
if hasattr(expr, hint):
newexpr = getattr(expr, hint)(**hints)
if newexpr != expr:
return (newexpr, True)
return (expr, hit)
@cacheit
def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
mul=True, log=True, multinomial=True, basic=True, **hints):
"""
Expand an expression using hints.
See the docstring of the expand() function in sympy.core.function for
more information.
"""
from sympy.simplify.radsimp import fraction
hints.update(power_base=power_base, power_exp=power_exp, mul=mul,
log=log, multinomial=multinomial, basic=basic)
expr = self
if hints.pop('frac', False):
n, d = [a.expand(deep=deep, modulus=modulus, **hints)
for a in fraction(self)]
return n/d
elif hints.pop('denom', False):
n, d = fraction(self)
return n/d.expand(deep=deep, modulus=modulus, **hints)
elif hints.pop('numer', False):
n, d = fraction(self)
return n.expand(deep=deep, modulus=modulus, **hints)/d
# Although the hints are sorted here, an earlier hint may get applied
# at a given node in the expression tree before another because of how
# the hints are applied. e.g. expand(log(x*(y + z))) -> log(x*y +
# x*z) because while applying log at the top level, log and mul are
# applied at the deeper level in the tree so that when the log at the
# upper level gets applied, the mul has already been applied at the
# lower level.
# Additionally, because hints are only applied once, the expression
# may not be expanded all the way. For example, if mul is applied
# before multinomial, x*(x + 1)**2 won't be expanded all the way. For
# now, we just use a special case to make multinomial run before mul,
# so that at least polynomials will be expanded all the way. In the
# future, smarter heuristics should be applied.
# TODO: Smarter heuristics
def _expand_hint_key(hint):
"""Make multinomial come before mul"""
if hint == 'mul':
return 'mulz'
return hint
for hint in sorted(hints.keys(), key=_expand_hint_key):
use_hint = hints[hint]
if use_hint:
hint = '_eval_expand_' + hint
expr, hit = Expr._expand_hint(expr, hint, deep=deep, **hints)
while True:
was = expr
if hints.get('multinomial', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_multinomial', deep=deep, **hints)
if hints.get('mul', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_mul', deep=deep, **hints)
if hints.get('log', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_log', deep=deep, **hints)
if expr == was:
break
if modulus is not None:
modulus = sympify(modulus)
if not modulus.is_Integer or modulus <= 0:
raise ValueError(
"modulus must be a positive integer, got %s" % modulus)
terms = []
for term in Add.make_args(expr):
coeff, tail = term.as_coeff_Mul(rational=True)
coeff %= modulus
if coeff:
terms.append(coeff*tail)
expr = Add(*terms)
return expr
###########################################################################
################### GLOBAL ACTION VERB WRAPPER METHODS ####################
###########################################################################
def integrate(self, *args, **kwargs):
"""See the integrate function in sympy.integrals"""
from sympy.integrals.integrals import integrate
return integrate(self, *args, **kwargs)
def nsimplify(self, constants=(), tolerance=None, full=False):
"""See the nsimplify function in sympy.simplify"""
from sympy.simplify.simplify import nsimplify
return nsimplify(self, constants, tolerance, full)
def separate(self, deep=False, force=False):
"""See the separate function in sympy.simplify"""
from .function import expand_power_base
return expand_power_base(self, deep=deep, force=force)
def collect(self, syms, func=None, evaluate=True, exact=False, distribute_order_term=True):
"""See the collect function in sympy.simplify"""
from sympy.simplify.radsimp import collect
return collect(self, syms, func, evaluate, exact, distribute_order_term)
def together(self, *args, **kwargs):
"""See the together function in sympy.polys"""
from sympy.polys.rationaltools import together
return together(self, *args, **kwargs)
def apart(self, x=None, **args):
"""See the apart function in sympy.polys"""
from sympy.polys.partfrac import apart
return apart(self, x, **args)
def ratsimp(self):
"""See the ratsimp function in sympy.simplify"""
from sympy.simplify.ratsimp import ratsimp
return ratsimp(self)
def trigsimp(self, **args):
"""See the trigsimp function in sympy.simplify"""
from sympy.simplify.trigsimp import trigsimp
return trigsimp(self, **args)
def radsimp(self, **kwargs):
"""See the radsimp function in sympy.simplify"""
from sympy.simplify.radsimp import radsimp
return radsimp(self, **kwargs)
def powsimp(self, *args, **kwargs):
"""See the powsimp function in sympy.simplify"""
from sympy.simplify.powsimp import powsimp
return powsimp(self, *args, **kwargs)
def combsimp(self):
"""See the combsimp function in sympy.simplify"""
from sympy.simplify.combsimp import combsimp
return combsimp(self)
def gammasimp(self):
"""See the gammasimp function in sympy.simplify"""
from sympy.simplify.gammasimp import gammasimp
return gammasimp(self)
def factor(self, *gens, **args):
"""See the factor() function in sympy.polys.polytools"""
from sympy.polys.polytools import factor
return factor(self, *gens, **args)
def cancel(self, *gens, **args):
"""See the cancel function in sympy.polys"""
from sympy.polys.polytools import cancel
return cancel(self, *gens, **args)
def invert(self, g, *gens, **args):
"""Return the multiplicative inverse of ``self`` mod ``g``
where ``self`` (and ``g``) may be symbolic expressions).
See Also
========
sympy.core.numbers.mod_inverse, sympy.polys.polytools.invert
"""
if self.is_number and getattr(g, 'is_number', True):
from .numbers import mod_inverse
return mod_inverse(self, g)
from sympy.polys.polytools import invert
return invert(self, g, *gens, **args)
def round(self, n=None):
"""Return x rounded to the given decimal place.
If a complex number would results, apply round to the real
and imaginary components of the number.
Examples
========
>>> from sympy import pi, E, I, S, Number
>>> pi.round()
3
>>> pi.round(2)
3.14
>>> (2*pi + E*I).round()
6 + 3*I
The round method has a chopping effect:
>>> (2*pi + I/10).round()
6
>>> (pi/10 + 2*I).round()
2*I
>>> (pi/10 + E*I).round(2)
0.31 + 2.72*I
Notes
=====
The Python ``round`` function uses the SymPy ``round`` method so it
will always return a SymPy number (not a Python float or int):
>>> isinstance(round(S(123), -2), Number)
True
"""
x = self
if not x.is_number:
raise TypeError("Cannot round symbolic expression")
if not x.is_Atom:
if not pure_complex(x.n(2), or_real=True):
raise TypeError(
'Expected a number but got %s:' % func_name(x))
elif x in _illegal:
return x
if x.is_extended_real is False:
r, i = x.as_real_imag()
return r.round(n) + S.ImaginaryUnit*i.round(n)
if not x:
return S.Zero if n is None else x
p = as_int(n or 0)
if x.is_Integer:
return Integer(round(int(x), p))
digits_to_decimal = _mag(x) # _mag(12) = 2, _mag(.012) = -1
allow = digits_to_decimal + p
precs = [f._prec for f in x.atoms(Float)]
dps = prec_to_dps(max(precs)) if precs else None
if dps is None:
# assume everything is exact so use the Python
# float default or whatever was requested
dps = max(15, allow)
else:
allow = min(allow, dps)
# this will shift all digits to right of decimal
# and give us dps to work with as an int
shift = -digits_to_decimal + dps
extra = 1 # how far we look past known digits
# NOTE
# mpmath will calculate the binary representation to
# an arbitrary number of digits but we must base our
# answer on a finite number of those digits, e.g.
# .575 2589569785738035/2**52 in binary.
# mpmath shows us that the first 18 digits are
# >>> Float(.575).n(18)
# 0.574999999999999956
# The default precision is 15 digits and if we ask
# for 15 we get
# >>> Float(.575).n(15)
# 0.575000000000000
# mpmath handles rounding at the 15th digit. But we
# need to be careful since the user might be asking
# for rounding at the last digit and our semantics
# are to round toward the even final digit when there
# is a tie. So the extra digit will be used to make
# that decision. In this case, the value is the same
# to 15 digits:
# >>> Float(.575).n(16)
# 0.5750000000000000
# Now converting this to the 15 known digits gives
# 575000000000000.0
# which rounds to integer
# 5750000000000000
# And now we can round to the desired digt, e.g. at
# the second from the left and we get
# 5800000000000000
# and rescaling that gives
# 0.58
# as the final result.
# If the value is made slightly less than 0.575 we might
# still obtain the same value:
# >>> Float(.575-1e-16).n(16)*10**15
# 574999999999999.8
# What 15 digits best represents the known digits (which are
# to the left of the decimal? 5750000000000000, the same as
# before. The only way we will round down (in this case) is
# if we declared that we had more than 15 digits of precision.
# For example, if we use 16 digits of precision, the integer
# we deal with is
# >>> Float(.575-1e-16).n(17)*10**16
# 5749999999999998.4
# and this now rounds to 5749999999999998 and (if we round to
# the 2nd digit from the left) we get 5700000000000000.
#
xf = x.n(dps + extra)*Pow(10, shift)
xi = Integer(xf)
# use the last digit to select the value of xi
# nearest to x before rounding at the desired digit
sign = 1 if x > 0 else -1
dif2 = sign*(xf - xi).n(extra)
if dif2 < 0:
raise NotImplementedError(
'not expecting int(x) to round away from 0')
if dif2 > .5:
xi += sign # round away from 0
elif dif2 == .5:
xi += sign if xi%2 else -sign # round toward even
# shift p to the new position
ip = p - shift
# let Python handle the int rounding then rescale
xr = round(xi.p, ip)
# restore scale
rv = Rational(xr, Pow(10, shift))
# return Float or Integer
if rv.is_Integer:
if n is None: # the single-arg case
return rv
# use str or else it won't be a float
return Float(str(rv), dps) # keep same precision
else:
if not allow and rv > self:
allow += 1
return Float(rv, allow)
__round__ = round
def _eval_derivative_matrix_lines(self, x):
from sympy.matrices.expressions.matexpr import _LeftRightArgs
return [_LeftRightArgs([S.One, S.One], higher=self._eval_derivative(x))]
class AtomicExpr(Atom, Expr):
"""
A parent class for object which are both atoms and Exprs.
For example: Symbol, Number, Rational, Integer, ...
But not: Add, Mul, Pow, ...
"""
is_number = False
is_Atom = True
__slots__ = ()
def _eval_derivative(self, s):
if self == s:
return S.One
return S.Zero
def _eval_derivative_n_times(self, s, n):
from .containers import Tuple
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.common import MatrixCommon
if isinstance(s, (MatrixCommon, Tuple, Iterable, MatrixExpr)):
return super()._eval_derivative_n_times(s, n)
from .relational import Eq
from sympy.functions.elementary.piecewise import Piecewise
if self == s:
return Piecewise((self, Eq(n, 0)), (1, Eq(n, 1)), (0, True))
else:
return Piecewise((self, Eq(n, 0)), (0, True))
def _eval_is_polynomial(self, syms):
return True
def _eval_is_rational_function(self, syms):
return self not in _illegal
def _eval_is_meromorphic(self, x, a):
from sympy.calculus.accumulationbounds import AccumBounds
return (not self.is_Number or self.is_finite) and not isinstance(self, AccumBounds)
def _eval_is_algebraic_expr(self, syms):
return True
def _eval_nseries(self, x, n, logx, cdir=0):
return self
@property
def expr_free_symbols(self):
sympy_deprecation_warning("""
The expr_free_symbols property is deprecated. Use free_symbols to get
the free symbols of an expression.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-expr-free-symbols")
return {self}
def _mag(x):
r"""Return integer $i$ such that $0.1 \le x/10^i < 1$
Examples
========
>>> from sympy.core.expr import _mag
>>> from sympy import Float
>>> _mag(Float(.1))
0
>>> _mag(Float(.01))
-1
>>> _mag(Float(1234))
4
"""
from math import log10, ceil, log
xpos = abs(x.n())
if not xpos:
return S.Zero
try:
mag_first_dig = int(ceil(log10(xpos)))
except (ValueError, OverflowError):
mag_first_dig = int(ceil(Float(mpf_log(xpos._mpf_, 53))/log(10)))
# check that we aren't off by 1
if (xpos/10**mag_first_dig) >= 1:
assert 1 <= (xpos/10**mag_first_dig) < 10
mag_first_dig += 1
return mag_first_dig
class UnevaluatedExpr(Expr):
"""
Expression that is not evaluated unless released.
Examples
========
>>> from sympy import UnevaluatedExpr
>>> from sympy.abc import x
>>> x*(1/x)
1
>>> x*UnevaluatedExpr(1/x)
x*1/x
"""
def __new__(cls, arg, **kwargs):
arg = _sympify(arg)
obj = Expr.__new__(cls, arg, **kwargs)
return obj
def doit(self, **hints):
if hints.get("deep", True):
return self.args[0].doit(**hints)
else:
return self.args[0]
def unchanged(func, *args):
"""Return True if `func` applied to the `args` is unchanged.
Can be used instead of `assert foo == foo`.
Examples
========
>>> from sympy import Piecewise, cos, pi
>>> from sympy.core.expr import unchanged
>>> from sympy.abc import x
>>> unchanged(cos, 1) # instead of assert cos(1) == cos(1)
True
>>> unchanged(cos, pi)
False
Comparison of args uses the builtin capabilities of the object's
arguments to test for equality so args can be defined loosely. Here,
the ExprCondPair arguments of Piecewise compare as equal to the
tuples that can be used to create the Piecewise:
>>> unchanged(Piecewise, (x, x > 1), (0, True))
True
"""
f = func(*args)
return f.func == func and f.args == args
class ExprBuilder:
def __init__(self, op, args=None, validator=None, check=True):
if not hasattr(op, "__call__"):
raise TypeError("op {} needs to be callable".format(op))
self.op = op
if args is None:
self.args = []
else:
self.args = args
self.validator = validator
if (validator is not None) and check:
self.validate()
@staticmethod
def _build_args(args):
return [i.build() if isinstance(i, ExprBuilder) else i for i in args]
def validate(self):
if self.validator is None:
return
args = self._build_args(self.args)
self.validator(*args)
def build(self, check=True):
args = self._build_args(self.args)
if self.validator and check:
self.validator(*args)
return self.op(*args)
def append_argument(self, arg, check=True):
self.args.append(arg)
if self.validator and check:
self.validate(*self.args)
def __getitem__(self, item):
if item == 0:
return self.op
else:
return self.args[item-1]
def __repr__(self):
return str(self.build())
def search_element(self, elem):
for i, arg in enumerate(self.args):
if isinstance(arg, ExprBuilder):
ret = arg.search_index(elem)
if ret is not None:
return (i,) + ret
elif id(arg) == id(elem):
return (i,)
return None
from .mul import Mul
from .add import Add
from .power import Pow
from .function import Function, _derivative_dispatch
from .mod import Mod
from .exprtools import factor_terms
from .numbers import Float, Integer, Rational, _illegal
|
5078b1b5c018428e05cd12cbd2e2eeeadcfca8afe905273f1f02d11023a5f616 | from __future__ import annotations
import numbers
import decimal
import fractions
import math
import re as regex
import sys
from functools import lru_cache
from .containers import Tuple
from .sympify import (SympifyError, _sympy_converter, sympify, _convert_numpy_types,
_sympify, _is_numpy_instance)
from .singleton import S, Singleton
from .basic import Basic
from .expr import Expr, AtomicExpr
from .evalf import pure_complex
from .cache import cacheit, clear_cache
from .decorators import _sympifyit
from .logic import fuzzy_not
from .kind import NumberKind
from sympy.external.gmpy import SYMPY_INTS, HAS_GMPY, gmpy
from sympy.multipledispatch import dispatch
import mpmath
import mpmath.libmp as mlib
from mpmath.libmp import bitcount, round_nearest as rnd
from mpmath.libmp.backend import MPZ
from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed
from mpmath.ctx_mp import mpnumeric
from mpmath.libmp.libmpf import (
finf as _mpf_inf, fninf as _mpf_ninf,
fnan as _mpf_nan, fzero, _normalize as mpf_normalize,
prec_to_dps, dps_to_prec)
from sympy.utilities.misc import as_int, debug, filldedent
from .parameters import global_parameters
_LOG2 = math.log(2)
def comp(z1, z2, tol=None):
r"""Return a bool indicating whether the error between z1 and z2
is $\le$ ``tol``.
Examples
========
If ``tol`` is ``None`` then ``True`` will be returned if
:math:`|z1 - z2|\times 10^p \le 5` where $p$ is minimum value of the
decimal precision of each value.
>>> from sympy import comp, pi
>>> pi4 = pi.n(4); pi4
3.142
>>> comp(_, 3.142)
True
>>> comp(pi4, 3.141)
False
>>> comp(pi4, 3.143)
False
A comparison of strings will be made
if ``z1`` is a Number and ``z2`` is a string or ``tol`` is ''.
>>> comp(pi4, 3.1415)
True
>>> comp(pi4, 3.1415, '')
False
When ``tol`` is provided and $z2$ is non-zero and
:math:`|z1| > 1` the error is normalized by :math:`|z1|`:
>>> abs(pi4 - 3.14)/pi4
0.000509791731426756
>>> comp(pi4, 3.14, .001) # difference less than 0.1%
True
>>> comp(pi4, 3.14, .0005) # difference less than 0.1%
False
When :math:`|z1| \le 1` the absolute error is used:
>>> 1/pi4
0.3183
>>> abs(1/pi4 - 0.3183)/(1/pi4)
3.07371499106316e-5
>>> abs(1/pi4 - 0.3183)
9.78393554684764e-6
>>> comp(1/pi4, 0.3183, 1e-5)
True
To see if the absolute error between ``z1`` and ``z2`` is less
than or equal to ``tol``, call this as ``comp(z1 - z2, 0, tol)``
or ``comp(z1 - z2, tol=tol)``:
>>> abs(pi4 - 3.14)
0.00160156249999988
>>> comp(pi4 - 3.14, 0, .002)
True
>>> comp(pi4 - 3.14, 0, .001)
False
"""
if isinstance(z2, str):
if not pure_complex(z1, or_real=True):
raise ValueError('when z2 is a str z1 must be a Number')
return str(z1) == z2
if not z1:
z1, z2 = z2, z1
if not z1:
return True
if not tol:
a, b = z1, z2
if tol == '':
return str(a) == str(b)
if tol is None:
a, b = sympify(a), sympify(b)
if not all(i.is_number for i in (a, b)):
raise ValueError('expecting 2 numbers')
fa = a.atoms(Float)
fb = b.atoms(Float)
if not fa and not fb:
# no floats -- compare exactly
return a == b
# get a to be pure_complex
for _ in range(2):
ca = pure_complex(a, or_real=True)
if not ca:
if fa:
a = a.n(prec_to_dps(min([i._prec for i in fa])))
ca = pure_complex(a, or_real=True)
break
else:
fa, fb = fb, fa
a, b = b, a
cb = pure_complex(b)
if not cb and fb:
b = b.n(prec_to_dps(min([i._prec for i in fb])))
cb = pure_complex(b, or_real=True)
if ca and cb and (ca[1] or cb[1]):
return all(comp(i, j) for i, j in zip(ca, cb))
tol = 10**prec_to_dps(min(a._prec, getattr(b, '_prec', a._prec)))
return int(abs(a - b)*tol) <= 5
diff = abs(z1 - z2)
az1 = abs(z1)
if z2 and az1 > 1:
return diff/az1 <= tol
else:
return diff <= tol
def mpf_norm(mpf, prec):
"""Return the mpf tuple normalized appropriately for the indicated
precision after doing a check to see if zero should be returned or
not when the mantissa is 0. ``mpf_normlize`` always assumes that this
is zero, but it may not be since the mantissa for mpf's values "+inf",
"-inf" and "nan" have a mantissa of zero, too.
Note: this is not intended to validate a given mpf tuple, so sending
mpf tuples that were not created by mpmath may produce bad results. This
is only a wrapper to ``mpf_normalize`` which provides the check for non-
zero mpfs that have a 0 for the mantissa.
"""
sign, man, expt, bc = mpf
if not man:
# hack for mpf_normalize which does not do this;
# it assumes that if man is zero the result is 0
# (see issue 6639)
if not bc:
return fzero
else:
# don't change anything; this should already
# be a well formed mpf tuple
return mpf
# Necessary if mpmath is using the gmpy backend
from mpmath.libmp.backend import MPZ
rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)
return rv
# TODO: we should use the warnings module
_errdict = {"divide": False}
def seterr(divide=False):
"""
Should SymPy raise an exception on 0/0 or return a nan?
divide == True .... raise an exception
divide == False ... return nan
"""
if _errdict["divide"] != divide:
clear_cache()
_errdict["divide"] = divide
def _as_integer_ratio(p):
neg_pow, man, expt, _ = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_)
p = [1, -1][neg_pow % 2]*man
if expt < 0:
q = 2**-expt
else:
q = 1
p *= 2**expt
return int(p), int(q)
def _decimal_to_Rational_prec(dec):
"""Convert an ordinary decimal instance to a Rational."""
if not dec.is_finite():
raise TypeError("dec must be finite, got %s." % dec)
s, d, e = dec.as_tuple()
prec = len(d)
if e >= 0: # it's an integer
rv = Integer(int(dec))
else:
s = (-1)**s
d = sum([di*10**i for i, di in enumerate(reversed(d))])
rv = Rational(s*d, 10**-e)
return rv, prec
_floatpat = regex.compile(r"[-+]?((\d*\.\d+)|(\d+\.?))")
def _literal_float(f):
"""Return True if n starts like a floating point number."""
return bool(_floatpat.match(f))
# (a,b) -> gcd(a,b)
# TODO caching with decorator, but not to degrade performance
@lru_cache(1024)
def igcd(*args):
"""Computes nonnegative integer greatest common divisor.
Explanation
===========
The algorithm is based on the well known Euclid's algorithm [1]_. To
improve speed, ``igcd()`` has its own caching mechanism.
Examples
========
>>> from sympy import igcd
>>> igcd(2, 4)
2
>>> igcd(5, 10, 15)
5
References
==========
.. [1] https://en.wikipedia.org/wiki/Euclidean_algorithm
"""
if len(args) < 2:
raise TypeError(
'igcd() takes at least 2 arguments (%s given)' % len(args))
args_temp = [abs(as_int(i)) for i in args]
if 1 in args_temp:
return 1
a = args_temp.pop()
if HAS_GMPY: # Using gmpy if present to speed up.
for b in args_temp:
a = gmpy.gcd(a, b) if b else a
return as_int(a)
for b in args_temp:
a = math.gcd(a, b)
return a
igcd2 = math.gcd
def igcd_lehmer(a, b):
r"""Computes greatest common divisor of two integers.
Explanation
===========
Euclid's algorithm for the computation of the greatest
common divisor ``gcd(a, b)`` of two (positive) integers
$a$ and $b$ is based on the division identity
$$ a = q \times b + r$$,
where the quotient $q$ and the remainder $r$ are integers
and $0 \le r < b$. Then each common divisor of $a$ and $b$
divides $r$, and it follows that ``gcd(a, b) == gcd(b, r)``.
The algorithm works by constructing the sequence
r0, r1, r2, ..., where r0 = a, r1 = b, and each rn
is the remainder from the division of the two preceding
elements.
In Python, ``q = a // b`` and ``r = a % b`` are obtained by the
floor division and the remainder operations, respectively.
These are the most expensive arithmetic operations, especially
for large a and b.
Lehmer's algorithm [1]_ is based on the observation that the quotients
``qn = r(n-1) // rn`` are in general small integers even
when a and b are very large. Hence the quotients can be
usually determined from a relatively small number of most
significant bits.
The efficiency of the algorithm is further enhanced by not
computing each long remainder in Euclid's sequence. The remainders
are linear combinations of a and b with integer coefficients
derived from the quotients. The coefficients can be computed
as far as the quotients can be determined from the chosen
most significant parts of a and b. Only then a new pair of
consecutive remainders is computed and the algorithm starts
anew with this pair.
References
==========
.. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm
"""
a, b = abs(as_int(a)), abs(as_int(b))
if a < b:
a, b = b, a
# The algorithm works by using one or two digit division
# whenever possible. The outer loop will replace the
# pair (a, b) with a pair of shorter consecutive elements
# of the Euclidean gcd sequence until a and b
# fit into two Python (long) int digits.
nbits = 2*sys.int_info.bits_per_digit
while a.bit_length() > nbits and b != 0:
# Quotients are mostly small integers that can
# be determined from most significant bits.
n = a.bit_length() - nbits
x, y = int(a >> n), int(b >> n) # most significant bits
# Elements of the Euclidean gcd sequence are linear
# combinations of a and b with integer coefficients.
# Compute the coefficients of consecutive pairs
# a' = A*a + B*b, b' = C*a + D*b
# using small integer arithmetic as far as possible.
A, B, C, D = 1, 0, 0, 1 # initial values
while True:
# The coefficients alternate in sign while looping.
# The inner loop combines two steps to keep track
# of the signs.
# At this point we have
# A > 0, B <= 0, C <= 0, D > 0,
# x' = x + B <= x < x" = x + A,
# y' = y + C <= y < y" = y + D,
# and
# x'*N <= a' < x"*N, y'*N <= b' < y"*N,
# where N = 2**n.
# Now, if y' > 0, and x"//y' and x'//y" agree,
# then their common value is equal to q = a'//b'.
# In addition,
# x'%y" = x' - q*y" < x" - q*y' = x"%y',
# and
# (x'%y")*N < a'%b' < (x"%y')*N.
# On the other hand, we also have x//y == q,
# and therefore
# x'%y" = x + B - q*(y + D) = x%y + B',
# x"%y' = x + A - q*(y + C) = x%y + A',
# where
# B' = B - q*D < 0, A' = A - q*C > 0.
if y + C <= 0:
break
q = (x + A) // (y + C)
# Now x'//y" <= q, and equality holds if
# x' - q*y" = (x - q*y) + (B - q*D) >= 0.
# This is a minor optimization to avoid division.
x_qy, B_qD = x - q*y, B - q*D
if x_qy + B_qD < 0:
break
# Next step in the Euclidean sequence.
x, y = y, x_qy
A, B, C, D = C, D, A - q*C, B_qD
# At this point the signs of the coefficients
# change and their roles are interchanged.
# A <= 0, B > 0, C > 0, D < 0,
# x' = x + A <= x < x" = x + B,
# y' = y + D < y < y" = y + C.
if y + D <= 0:
break
q = (x + B) // (y + D)
x_qy, A_qC = x - q*y, A - q*C
if x_qy + A_qC < 0:
break
x, y = y, x_qy
A, B, C, D = C, D, A_qC, B - q*D
# Now the conditions on top of the loop
# are again satisfied.
# A > 0, B < 0, C < 0, D > 0.
if B == 0:
# This can only happen when y == 0 in the beginning
# and the inner loop does nothing.
# Long division is forced.
a, b = b, a % b
continue
# Compute new long arguments using the coefficients.
a, b = A*a + B*b, C*a + D*b
# Small divisors. Finish with the standard algorithm.
while b:
a, b = b, a % b
return a
def ilcm(*args):
"""Computes integer least common multiple.
Examples
========
>>> from sympy import ilcm
>>> ilcm(5, 10)
10
>>> ilcm(7, 3)
21
>>> ilcm(5, 10, 15)
30
"""
if len(args) < 2:
raise TypeError(
'ilcm() takes at least 2 arguments (%s given)' % len(args))
if 0 in args:
return 0
a = args[0]
for b in args[1:]:
a = a // igcd(a, b) * b # since gcd(a,b) | a
return a
def igcdex(a, b):
"""Returns x, y, g such that g = x*a + y*b = gcd(a, b).
Examples
========
>>> from sympy.core.numbers import igcdex
>>> igcdex(2, 3)
(-1, 1, 1)
>>> igcdex(10, 12)
(-1, 1, 2)
>>> x, y, g = igcdex(100, 2004)
>>> x, y, g
(-20, 1, 4)
>>> x*100 + y*2004
4
"""
if (not a) and (not b):
return (0, 1, 0)
if not a:
return (0, b//abs(b), abs(b))
if not b:
return (a//abs(a), 0, abs(a))
if a < 0:
a, x_sign = -a, -1
else:
x_sign = 1
if b < 0:
b, y_sign = -b, -1
else:
y_sign = 1
x, y, r, s = 1, 0, 0, 1
while b:
(c, q) = (a % b, a // b)
(a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s)
return (x*x_sign, y*y_sign, a)
def mod_inverse(a, m):
r"""
Return the number $c$ such that, $a \times c = 1 \pmod{m}$
where $c$ has the same sign as $m$. If no such value exists,
a ValueError is raised.
Examples
========
>>> from sympy import mod_inverse, S
Suppose we wish to find multiplicative inverse $x$ of
3 modulo 11. This is the same as finding $x$ such
that $3x = 1 \pmod{11}$. One value of x that satisfies
this congruence is 4. Because $3 \times 4 = 12$ and $12 = 1 \pmod{11}$.
This is the value returned by ``mod_inverse``:
>>> mod_inverse(3, 11)
4
>>> mod_inverse(-3, 11)
7
When there is a common factor between the numerators of
`a` and `m` the inverse does not exist:
>>> mod_inverse(2, 4)
Traceback (most recent call last):
...
ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2)
7/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
.. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
"""
c = None
try:
a, m = as_int(a), as_int(m)
if m != 1 and m != -1:
x, _, g = igcdex(a, m)
if g == 1:
c = x % m
except ValueError:
a, m = sympify(a), sympify(m)
if not (a.is_number and m.is_number):
raise TypeError(filldedent('''
Expected numbers for arguments; symbolic `mod_inverse`
is not implemented
but symbolic expressions can be handled with the
similar function,
sympy.polys.polytools.invert'''))
big = (m > 1)
if big not in (S.true, S.false):
raise ValueError('m > 1 did not evaluate; try to simplify %s' % m)
elif big:
c = 1/a
if c is None:
raise ValueError('inverse of %s (mod %s) does not exist' % (a, m))
return c
class Number(AtomicExpr):
"""Represents atomic numbers in SymPy.
Explanation
===========
Floating point numbers are represented by the Float class.
Rational numbers (of any size) are represented by the Rational class.
Integer numbers (of any size) are represented by the Integer class.
Float and Rational are subclasses of Number; Integer is a subclass
of Rational.
For example, ``2/3`` is represented as ``Rational(2, 3)`` which is
a different object from the floating point number obtained with
Python division ``2/3``. Even for numbers that are exactly
represented in binary, there is a difference between how two forms,
such as ``Rational(1, 2)`` and ``Float(0.5)``, are used in SymPy.
The rational form is to be preferred in symbolic computations.
Other kinds of numbers, such as algebraic numbers ``sqrt(2)`` or
complex numbers ``3 + 4*I``, are not instances of Number class as
they are not atomic.
See Also
========
Float, Integer, Rational
"""
is_commutative = True
is_number = True
is_Number = True
__slots__ = ()
# Used to make max(x._prec, y._prec) return x._prec when only x is a float
_prec = -1
kind = NumberKind
def __new__(cls, *obj):
if len(obj) == 1:
obj = obj[0]
if isinstance(obj, Number):
return obj
if isinstance(obj, SYMPY_INTS):
return Integer(obj)
if isinstance(obj, tuple) and len(obj) == 2:
return Rational(*obj)
if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)):
return Float(obj)
if isinstance(obj, str):
_obj = obj.lower() # float('INF') == float('inf')
if _obj == 'nan':
return S.NaN
elif _obj == 'inf':
return S.Infinity
elif _obj == '+inf':
return S.Infinity
elif _obj == '-inf':
return S.NegativeInfinity
val = sympify(obj)
if isinstance(val, Number):
return val
else:
raise ValueError('String "%s" does not denote a Number' % obj)
msg = "expected str|int|long|float|Decimal|Number object but got %r"
raise TypeError(msg % type(obj).__name__)
def could_extract_minus_sign(self):
return bool(self.is_extended_negative)
def invert(self, other, *gens, **args):
from sympy.polys.polytools import invert
if getattr(other, 'is_number', True):
return mod_inverse(self, other)
return invert(self, other, *gens, **args)
def __divmod__(self, other):
from sympy.functions.elementary.complexes import sign
try:
other = Number(other)
if self.is_infinite or S.NaN in (self, other):
return (S.NaN, S.NaN)
except TypeError:
return NotImplemented
if not other:
raise ZeroDivisionError('modulo by zero')
if self.is_Integer and other.is_Integer:
return Tuple(*divmod(self.p, other.p))
elif isinstance(other, Float):
rat = self/Rational(other)
else:
rat = self/other
if other.is_finite:
w = int(rat) if rat >= 0 else int(rat) - 1
r = self - other*w
else:
w = 0 if not self or (sign(self) == sign(other)) else -1
r = other if w else self
return Tuple(w, r)
def __rdivmod__(self, other):
try:
other = Number(other)
except TypeError:
return NotImplemented
return divmod(other, self)
def _as_mpf_val(self, prec):
"""Evaluation of mpf tuple accurate to at least prec bits."""
raise NotImplementedError('%s needs ._as_mpf_val() method' %
(self.__class__.__name__))
def _eval_evalf(self, prec):
return Float._new(self._as_mpf_val(prec), prec)
def _as_mpf_op(self, prec):
prec = max(prec, self._prec)
return self._as_mpf_val(prec), prec
def __float__(self):
return mlib.to_float(self._as_mpf_val(53))
def floor(self):
raise NotImplementedError('%s needs .floor() method' %
(self.__class__.__name__))
def ceiling(self):
raise NotImplementedError('%s needs .ceiling() method' %
(self.__class__.__name__))
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def _eval_conjugate(self):
return self
def _eval_order(self, *symbols):
from sympy.series.order import Order
# Order(5, x, y) -> Order(1,x,y)
return Order(S.One, *symbols)
def _eval_subs(self, old, new):
if old == -self:
return -new
return self # there is no other possibility
@classmethod
def class_key(cls):
return 1, 0, 'Number'
@cacheit
def sort_key(self, order=None):
return self.class_key(), (0, ()), (), self
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
return S.Infinity
elif other is S.NegativeInfinity:
return S.NegativeInfinity
return AtomicExpr.__add__(self, other)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
return S.NegativeInfinity
elif other is S.NegativeInfinity:
return S.Infinity
return AtomicExpr.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
if self.is_zero:
return S.NaN
elif self.is_positive:
return S.Infinity
else:
return S.NegativeInfinity
elif other is S.NegativeInfinity:
if self.is_zero:
return S.NaN
elif self.is_positive:
return S.NegativeInfinity
else:
return S.Infinity
elif isinstance(other, Tuple):
return NotImplemented
return AtomicExpr.__mul__(self, other)
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other in (S.Infinity, S.NegativeInfinity):
return S.Zero
return AtomicExpr.__truediv__(self, other)
def __eq__(self, other):
raise NotImplementedError('%s needs .__eq__() method' %
(self.__class__.__name__))
def __ne__(self, other):
raise NotImplementedError('%s needs .__ne__() method' %
(self.__class__.__name__))
def __lt__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, other))
raise NotImplementedError('%s needs .__lt__() method' %
(self.__class__.__name__))
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s <= %s" % (self, other))
raise NotImplementedError('%s needs .__le__() method' %
(self.__class__.__name__))
def __gt__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s > %s" % (self, other))
return _sympify(other).__lt__(self)
def __ge__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s >= %s" % (self, other))
return _sympify(other).__le__(self)
def __hash__(self):
return super().__hash__()
def is_constant(self, *wrt, **flags):
return True
def as_coeff_mul(self, *deps, rational=True, **kwargs):
# a -> c*t
if self.is_Rational or not rational:
return self, tuple()
elif self.is_negative:
return S.NegativeOne, (-self,)
return S.One, (self,)
def as_coeff_add(self, *deps):
# a -> c + t
if self.is_Rational:
return self, tuple()
return S.Zero, (self,)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
if rational and not self.is_Rational:
return S.One, self
return (self, S.One) if self else (S.One, self)
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
if not rational:
return self, S.Zero
return S.Zero, self
def gcd(self, other):
"""Compute GCD of `self` and `other`. """
from sympy.polys.polytools import gcd
return gcd(self, other)
def lcm(self, other):
"""Compute LCM of `self` and `other`. """
from sympy.polys.polytools import lcm
return lcm(self, other)
def cofactors(self, other):
"""Compute GCD and cofactors of `self` and `other`. """
from sympy.polys.polytools import cofactors
return cofactors(self, other)
class Float(Number):
"""Represent a floating-point number of arbitrary precision.
Examples
========
>>> from sympy import Float
>>> Float(3.5)
3.50000000000000
>>> Float(3)
3.00000000000000
Creating Floats from strings (and Python ``int`` and ``long``
types) will give a minimum precision of 15 digits, but the
precision will automatically increase to capture all digits
entered.
>>> Float(1)
1.00000000000000
>>> Float(10**20)
100000000000000000000.
>>> Float('1e20')
100000000000000000000.
However, *floating-point* numbers (Python ``float`` types) retain
only 15 digits of precision:
>>> Float(1e20)
1.00000000000000e+20
>>> Float(1.23456789123456789)
1.23456789123457
It may be preferable to enter high-precision decimal numbers
as strings:
>>> Float('1.23456789123456789')
1.23456789123456789
The desired number of digits can also be specified:
>>> Float('1e-3', 3)
0.00100
>>> Float(100, 4)
100.0
Float can automatically count significant figures if a null string
is sent for the precision; spaces or underscores are also allowed. (Auto-
counting is only allowed for strings, ints and longs).
>>> Float('123 456 789.123_456', '')
123456789.123456
>>> Float('12e-3', '')
0.012
>>> Float(3, '')
3.
If a number is written in scientific notation, only the digits before the
exponent are considered significant if a decimal appears, otherwise the
"e" signifies only how to move the decimal:
>>> Float('60.e2', '') # 2 digits significant
6.0e+3
>>> Float('60e2', '') # 4 digits significant
6000.
>>> Float('600e-2', '') # 3 digits significant
6.00
Notes
=====
Floats are inexact by their nature unless their value is a binary-exact
value.
>>> approx, exact = Float(.1, 1), Float(.125, 1)
For calculation purposes, evalf needs to be able to change the precision
but this will not increase the accuracy of the inexact value. The
following is the most accurate 5-digit approximation of a value of 0.1
that had only 1 digit of precision:
>>> approx.evalf(5)
0.099609
By contrast, 0.125 is exact in binary (as it is in base 10) and so it
can be passed to Float or evalf to obtain an arbitrary precision with
matching accuracy:
>>> Float(exact, 5)
0.12500
>>> exact.evalf(20)
0.12500000000000000000
Trying to make a high-precision Float from a float is not disallowed,
but one must keep in mind that the *underlying float* (not the apparent
decimal value) is being obtained with high precision. For example, 0.3
does not have a finite binary representation. The closest rational is
the fraction 5404319552844595/2**54. So if you try to obtain a Float of
0.3 to 20 digits of precision you will not see the same thing as 0.3
followed by 19 zeros:
>>> Float(0.3, 20)
0.29999999999999998890
If you want a 20-digit value of the decimal 0.3 (not the floating point
approximation of 0.3) you should send the 0.3 as a string. The underlying
representation is still binary but a higher precision than Python's float
is used:
>>> Float('0.3', 20)
0.30000000000000000000
Although you can increase the precision of an existing Float using Float
it will not increase the accuracy -- the underlying value is not changed:
>>> def show(f): # binary rep of Float
... from sympy import Mul, Pow
... s, m, e, b = f._mpf_
... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False)
... print('%s at prec=%s' % (v, f._prec))
...
>>> t = Float('0.3', 3)
>>> show(t)
4915/2**14 at prec=13
>>> show(Float(t, 20)) # higher prec, not higher accuracy
4915/2**14 at prec=70
>>> show(Float(t, 2)) # lower prec
307/2**10 at prec=10
The same thing happens when evalf is used on a Float:
>>> show(t.evalf(20))
4915/2**14 at prec=70
>>> show(t.evalf(2))
307/2**10 at prec=10
Finally, Floats can be instantiated with an mpf tuple (n, c, p) to
produce the number (-1)**n*c*2**p:
>>> n, c, p = 1, 5, 0
>>> (-1)**n*c*2**p
-5
>>> Float((1, 5, 0))
-5.00000000000000
An actual mpf tuple also contains the number of bits in c as the last
element of the tuple:
>>> _._mpf_
(1, 5, 0, 3)
This is not needed for instantiation and is not the same thing as the
precision. The mpf tuple and the precision are two separate quantities
that Float tracks.
In SymPy, a Float is a number that can be computed with arbitrary
precision. Although floating point 'inf' and 'nan' are not such
numbers, Float can create these numbers:
>>> Float('-inf')
-oo
>>> _.is_Float
False
"""
__slots__ = ('_mpf_', '_prec')
_mpf_: tuple[int, int, int, int]
# A Float represents many real numbers,
# both rational and irrational.
is_rational = None
is_irrational = None
is_number = True
is_real = True
is_extended_real = True
is_Float = True
def __new__(cls, num, dps=None, precision=None):
if dps is not None and precision is not None:
raise ValueError('Both decimal and binary precision supplied. '
'Supply only one. ')
if isinstance(num, str):
# Float accepts spaces as digit separators
num = num.replace(' ', '').lower()
if num.startswith('.') and len(num) > 1:
num = '0' + num
elif num.startswith('-.') and len(num) > 2:
num = '-0.' + num[2:]
elif num in ('inf', '+inf'):
return S.Infinity
elif num == '-inf':
return S.NegativeInfinity
elif isinstance(num, float) and num == 0:
num = '0'
elif isinstance(num, float) and num == float('inf'):
return S.Infinity
elif isinstance(num, float) and num == float('-inf'):
return S.NegativeInfinity
elif isinstance(num, float) and math.isnan(num):
return S.NaN
elif isinstance(num, (SYMPY_INTS, Integer)):
num = str(num)
elif num is S.Infinity:
return num
elif num is S.NegativeInfinity:
return num
elif num is S.NaN:
return num
elif _is_numpy_instance(num): # support for numpy datatypes
num = _convert_numpy_types(num)
elif isinstance(num, mpmath.mpf):
if precision is None:
if dps is None:
precision = num.context.prec
num = num._mpf_
if dps is None and precision is None:
dps = 15
if isinstance(num, Float):
return num
if isinstance(num, str) and _literal_float(num):
try:
Num = decimal.Decimal(num)
except decimal.InvalidOperation:
pass
else:
isint = '.' not in num
num, dps = _decimal_to_Rational_prec(Num)
if num.is_Integer and isint:
dps = max(dps, len(str(num).lstrip('-')))
dps = max(15, dps)
precision = dps_to_prec(dps)
elif precision == '' and dps is None or precision is None and dps == '':
if not isinstance(num, str):
raise ValueError('The null string can only be used when '
'the number to Float is passed as a string or an integer.')
ok = None
if _literal_float(num):
try:
Num = decimal.Decimal(num)
except decimal.InvalidOperation:
pass
else:
isint = '.' not in num
num, dps = _decimal_to_Rational_prec(Num)
if num.is_Integer and isint:
dps = max(dps, len(str(num).lstrip('-')))
precision = dps_to_prec(dps)
ok = True
if ok is None:
raise ValueError('string-float not recognized: %s' % num)
# decimal precision(dps) is set and maybe binary precision(precision)
# as well.From here on binary precision is used to compute the Float.
# Hence, if supplied use binary precision else translate from decimal
# precision.
if precision is None or precision == '':
precision = dps_to_prec(dps)
precision = int(precision)
if isinstance(num, float):
_mpf_ = mlib.from_float(num, precision, rnd)
elif isinstance(num, str):
_mpf_ = mlib.from_str(num, precision, rnd)
elif isinstance(num, decimal.Decimal):
if num.is_finite():
_mpf_ = mlib.from_str(str(num), precision, rnd)
elif num.is_nan():
return S.NaN
elif num.is_infinite():
if num > 0:
return S.Infinity
return S.NegativeInfinity
else:
raise ValueError("unexpected decimal value %s" % str(num))
elif isinstance(num, tuple) and len(num) in (3, 4):
if isinstance(num[1], str):
# it's a hexadecimal (coming from a pickled object)
num = list(num)
# If we're loading an object pickled in Python 2 into
# Python 3, we may need to strip a tailing 'L' because
# of a shim for int on Python 3, see issue #13470.
if num[1].endswith('L'):
num[1] = num[1][:-1]
# Strip leading '0x' - gmpy2 only documents such inputs
# with base prefix as valid when the 2nd argument (base) is 0.
# When mpmath uses Sage as the backend, however, it
# ends up including '0x' when preparing the picklable tuple.
# See issue #19690.
if num[1].startswith('0x'):
num[1] = num[1][2:]
# Now we can assume that it is in standard form
num[1] = MPZ(num[1], 16)
_mpf_ = tuple(num)
else:
if len(num) == 4:
# handle normalization hack
return Float._new(num, precision)
else:
if not all((
num[0] in (0, 1),
num[1] >= 0,
all(type(i) in (int, int) for i in num)
)):
raise ValueError('malformed mpf: %s' % (num,))
# don't compute number or else it may
# over/underflow
return Float._new(
(num[0], num[1], num[2], bitcount(num[1])),
precision)
else:
try:
_mpf_ = num._as_mpf_val(precision)
except (NotImplementedError, AttributeError):
_mpf_ = mpmath.mpf(num, prec=precision)._mpf_
return cls._new(_mpf_, precision, zero=False)
@classmethod
def _new(cls, _mpf_, _prec, zero=True):
# special cases
if zero and _mpf_ == fzero:
return S.Zero # Float(0) -> 0.0; Float._new((0,0,0,0)) -> 0
elif _mpf_ == _mpf_nan:
return S.NaN
elif _mpf_ == _mpf_inf:
return S.Infinity
elif _mpf_ == _mpf_ninf:
return S.NegativeInfinity
obj = Expr.__new__(cls)
obj._mpf_ = mpf_norm(_mpf_, _prec)
obj._prec = _prec
return obj
# mpz can't be pickled
def __getnewargs_ex__(self):
return ((mlib.to_pickable(self._mpf_),), {'precision': self._prec})
def _hashable_content(self):
return (self._mpf_, self._prec)
def floor(self):
return Integer(int(mlib.to_int(
mlib.mpf_floor(self._mpf_, self._prec))))
def ceiling(self):
return Integer(int(mlib.to_int(
mlib.mpf_ceil(self._mpf_, self._prec))))
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
@property
def num(self):
return mpmath.mpf(self._mpf_)
def _as_mpf_val(self, prec):
rv = mpf_norm(self._mpf_, prec)
if rv != self._mpf_ and self._prec == prec:
debug(self._mpf_, rv)
return rv
def _as_mpf_op(self, prec):
return self._mpf_, max(prec, self._prec)
def _eval_is_finite(self):
if self._mpf_ in (_mpf_inf, _mpf_ninf):
return False
return True
def _eval_is_infinite(self):
if self._mpf_ in (_mpf_inf, _mpf_ninf):
return True
return False
def _eval_is_integer(self):
return self._mpf_ == fzero
def _eval_is_negative(self):
if self._mpf_ in (_mpf_ninf, _mpf_inf):
return False
return self.num < 0
def _eval_is_positive(self):
if self._mpf_ in (_mpf_ninf, _mpf_inf):
return False
return self.num > 0
def _eval_is_extended_negative(self):
if self._mpf_ == _mpf_ninf:
return True
if self._mpf_ == _mpf_inf:
return False
return self.num < 0
def _eval_is_extended_positive(self):
if self._mpf_ == _mpf_inf:
return True
if self._mpf_ == _mpf_ninf:
return False
return self.num > 0
def _eval_is_zero(self):
return self._mpf_ == fzero
def __bool__(self):
return self._mpf_ != fzero
def __neg__(self):
if not self:
return self
return Float._new(mlib.mpf_neg(self._mpf_), self._prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec)
return Number.__add__(self, other)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec)
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec)
return Number.__mul__(self, other)
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and other != 0 and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec)
return Number.__truediv__(self, other)
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if isinstance(other, Rational) and other.q != 1 and global_parameters.evaluate:
# calculate mod with Rationals, *then* round the result
return Float(Rational.__mod__(Rational(self), other),
precision=self._prec)
if isinstance(other, Float) and global_parameters.evaluate:
r = self/other
if r == int(r):
return Float(0, precision=max(self._prec, other._prec))
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec)
return Number.__mod__(self, other)
@_sympifyit('other', NotImplemented)
def __rmod__(self, other):
if isinstance(other, Float) and global_parameters.evaluate:
return other.__mod__(self)
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec)
return Number.__rmod__(self, other)
def _eval_power(self, expt):
"""
expt is symbolic object but not equal to 0, 1
(-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) ->
-> p**r*(sin(Pi*r) + cos(Pi*r)*I)
"""
if self == 0:
if expt.is_extended_positive:
return self
if expt.is_extended_negative:
return S.ComplexInfinity
if isinstance(expt, Number):
if isinstance(expt, Integer):
prec = self._prec
return Float._new(
mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec)
elif isinstance(expt, Rational) and \
expt.p == 1 and expt.q % 2 and self.is_negative:
return Pow(S.NegativeOne, expt, evaluate=False)*(
-self)._eval_power(expt)
expt, prec = expt._as_mpf_op(self._prec)
mpfself = self._mpf_
try:
y = mpf_pow(mpfself, expt, prec, rnd)
return Float._new(y, prec)
except mlib.ComplexResult:
re, im = mlib.mpc_pow(
(mpfself, fzero), (expt, fzero), prec, rnd)
return Float._new(re, prec) + \
Float._new(im, prec)*S.ImaginaryUnit
def __abs__(self):
return Float._new(mlib.mpf_abs(self._mpf_), self._prec)
def __int__(self):
if self._mpf_ == fzero:
return 0
return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down
def __eq__(self, other):
from sympy.logic.boolalg import Boolean
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if isinstance(other, Boolean):
return False
if other.is_NumberSymbol:
if other.is_irrational:
return False
return other.__eq__(self)
if other.is_Float:
# comparison is exact
# so Float(.1, 3) != Float(.1, 33)
return self._mpf_ == other._mpf_
if other.is_Rational:
return other.__eq__(self)
if other.is_Number:
# numbers should compare at the same precision;
# all _as_mpf_val routines should be sure to abide
# by the request to change the prec if necessary; if
# they don't, the equality test will fail since it compares
# the mpf tuples
ompf = other._as_mpf_val(self._prec)
return bool(mlib.mpf_eq(self._mpf_, ompf))
if not self:
return not other
return False # Float != non-Number
def __ne__(self, other):
return not self == other
def _Frel(self, other, op):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Rational:
# test self*other.q <?> other.p without losing precision
'''
>>> f = Float(.1,2)
>>> i = 1234567890
>>> (f*i)._mpf_
(0, 471, 18, 9)
>>> mlib.mpf_mul(f._mpf_, mlib.from_int(i))
(0, 505555550955, -12, 39)
'''
smpf = mlib.mpf_mul(self._mpf_, mlib.from_int(other.q))
ompf = mlib.from_int(other.p)
return _sympify(bool(op(smpf, ompf)))
elif other.is_Float:
return _sympify(bool(
op(self._mpf_, other._mpf_)))
elif other.is_comparable and other not in (
S.Infinity, S.NegativeInfinity):
other = other.evalf(prec_to_dps(self._prec))
if other._prec > 1:
if other.is_Number:
return _sympify(bool(
op(self._mpf_, other._as_mpf_val(self._prec))))
def __gt__(self, other):
if isinstance(other, NumberSymbol):
return other.__lt__(self)
rv = self._Frel(other, mlib.mpf_gt)
if rv is None:
return Expr.__gt__(self, other)
return rv
def __ge__(self, other):
if isinstance(other, NumberSymbol):
return other.__le__(self)
rv = self._Frel(other, mlib.mpf_ge)
if rv is None:
return Expr.__ge__(self, other)
return rv
def __lt__(self, other):
if isinstance(other, NumberSymbol):
return other.__gt__(self)
rv = self._Frel(other, mlib.mpf_lt)
if rv is None:
return Expr.__lt__(self, other)
return rv
def __le__(self, other):
if isinstance(other, NumberSymbol):
return other.__ge__(self)
rv = self._Frel(other, mlib.mpf_le)
if rv is None:
return Expr.__le__(self, other)
return rv
def __hash__(self):
return super().__hash__()
def epsilon_eq(self, other, epsilon="1e-15"):
return abs(self - other) < Float(epsilon)
def __format__(self, format_spec):
return format(decimal.Decimal(str(self)), format_spec)
# Add sympify converters
_sympy_converter[float] = _sympy_converter[decimal.Decimal] = Float
# this is here to work nicely in Sage
RealNumber = Float
class Rational(Number):
"""Represents rational numbers (p/q) of any size.
Examples
========
>>> from sympy import Rational, nsimplify, S, pi
>>> Rational(1, 2)
1/2
Rational is unprejudiced in accepting input. If a float is passed, the
underlying value of the binary representation will be returned:
>>> Rational(.5)
1/2
>>> Rational(.2)
3602879701896397/18014398509481984
If the simpler representation of the float is desired then consider
limiting the denominator to the desired value or convert the float to
a string (which is roughly equivalent to limiting the denominator to
10**12):
>>> Rational(str(.2))
1/5
>>> Rational(.2).limit_denominator(10**12)
1/5
An arbitrarily precise Rational is obtained when a string literal is
passed:
>>> Rational("1.23")
123/100
>>> Rational('1e-2')
1/100
>>> Rational(".1")
1/10
>>> Rational('1e-2/3.2')
1/320
The conversion of other types of strings can be handled by
the sympify() function, and conversion of floats to expressions
or simple fractions can be handled with nsimplify:
>>> S('.[3]') # repeating digits in brackets
1/3
>>> S('3**2/10') # general expressions
9/10
>>> nsimplify(.3) # numbers that have a simple form
3/10
But if the input does not reduce to a literal Rational, an error will
be raised:
>>> Rational(pi)
Traceback (most recent call last):
...
TypeError: invalid input: pi
Low-level
---------
Access numerator and denominator as .p and .q:
>>> r = Rational(3, 4)
>>> r
3/4
>>> r.p
3
>>> r.q
4
Note that p and q return integers (not SymPy Integers) so some care
is needed when using them in expressions:
>>> r.p/r.q
0.75
If an unevaluated Rational is desired, ``gcd=1`` can be passed and
this will keep common divisors of the numerator and denominator
from being eliminated. It is not possible, however, to leave a
negative value in the denominator.
>>> Rational(2, 4, gcd=1)
2/4
>>> Rational(2, -4, gcd=1).q
4
See Also
========
sympy.core.sympify.sympify, sympy.simplify.simplify.nsimplify
"""
is_real = True
is_integer = False
is_rational = True
is_number = True
__slots__ = ('p', 'q')
p: int
q: int
is_Rational = True
@cacheit
def __new__(cls, p, q=None, gcd=None):
if q is None:
if isinstance(p, Rational):
return p
if isinstance(p, SYMPY_INTS):
pass
else:
if isinstance(p, (float, Float)):
return Rational(*_as_integer_ratio(p))
if not isinstance(p, str):
try:
p = sympify(p)
except (SympifyError, SyntaxError):
pass # error will raise below
else:
if p.count('/') > 1:
raise TypeError('invalid input: %s' % p)
p = p.replace(' ', '')
pq = p.rsplit('/', 1)
if len(pq) == 2:
p, q = pq
fp = fractions.Fraction(p)
fq = fractions.Fraction(q)
p = fp/fq
try:
p = fractions.Fraction(p)
except ValueError:
pass # error will raise below
else:
return Rational(p.numerator, p.denominator, 1)
if not isinstance(p, Rational):
raise TypeError('invalid input: %s' % p)
q = 1
gcd = 1
if not isinstance(p, SYMPY_INTS):
p = Rational(p)
q *= p.q
p = p.p
else:
p = int(p)
if not isinstance(q, SYMPY_INTS):
q = Rational(q)
p *= q.q
q = q.p
else:
q = int(q)
# p and q are now ints
if q == 0:
if p == 0:
if _errdict["divide"]:
raise ValueError("Indeterminate 0/0")
else:
return S.NaN
return S.ComplexInfinity
if q < 0:
q = -q
p = -p
if not gcd:
gcd = igcd(abs(p), q)
if gcd > 1:
p //= gcd
q //= gcd
if q == 1:
return Integer(p)
if p == 1 and q == 2:
return S.Half
obj = Expr.__new__(cls)
obj.p = p
obj.q = q
return obj
def limit_denominator(self, max_denominator=1000000):
"""Closest Rational to self with denominator at most max_denominator.
Examples
========
>>> from sympy import Rational
>>> Rational('3.141592653589793').limit_denominator(10)
22/7
>>> Rational('3.141592653589793').limit_denominator(100)
311/99
"""
f = fractions.Fraction(self.p, self.q)
return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator))))
def __getnewargs__(self):
return (self.p, self.q)
def _hashable_content(self):
return (self.p, self.q)
def _eval_is_positive(self):
return self.p > 0
def _eval_is_zero(self):
return self.p == 0
def __neg__(self):
return Rational(-self.p, self.q)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p + self.q*other.p, self.q, 1)
elif isinstance(other, Rational):
#TODO: this can probably be optimized more
return Rational(self.p*other.q + self.q*other.p, self.q*other.q)
elif isinstance(other, Float):
return other + self
else:
return Number.__add__(self, other)
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p - self.q*other.p, self.q, 1)
elif isinstance(other, Rational):
return Rational(self.p*other.q - self.q*other.p, self.q*other.q)
elif isinstance(other, Float):
return -other + self
else:
return Number.__sub__(self, other)
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.q*other.p - self.p, self.q, 1)
elif isinstance(other, Rational):
return Rational(self.q*other.p - self.p*other.q, self.q*other.q)
elif isinstance(other, Float):
return -self + other
else:
return Number.__rsub__(self, other)
return Number.__rsub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p*other.p, self.q, igcd(other.p, self.q))
elif isinstance(other, Rational):
return Rational(self.p*other.p, self.q*other.q, igcd(self.p, other.q)*igcd(self.q, other.p))
elif isinstance(other, Float):
return other*self
else:
return Number.__mul__(self, other)
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
if self.p and other.p == S.Zero:
return S.ComplexInfinity
else:
return Rational(self.p, self.q*other.p, igcd(self.p, other.p))
elif isinstance(other, Rational):
return Rational(self.p*other.q, self.q*other.p, igcd(self.p, other.p)*igcd(self.q, other.q))
elif isinstance(other, Float):
return self*(1/other)
else:
return Number.__truediv__(self, other)
return Number.__truediv__(self, other)
@_sympifyit('other', NotImplemented)
def __rtruediv__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(other.p*self.q, self.p, igcd(self.p, other.p))
elif isinstance(other, Rational):
return Rational(other.p*self.q, other.q*self.p, igcd(self.p, other.p)*igcd(self.q, other.q))
elif isinstance(other, Float):
return other*(1/self)
else:
return Number.__rtruediv__(self, other)
return Number.__rtruediv__(self, other)
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if global_parameters.evaluate:
if isinstance(other, Rational):
n = (self.p*other.q) // (other.p*self.q)
return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q)
if isinstance(other, Float):
# calculate mod with Rationals, *then* round the answer
return Float(self.__mod__(Rational(other)),
precision=other._prec)
return Number.__mod__(self, other)
return Number.__mod__(self, other)
@_sympifyit('other', NotImplemented)
def __rmod__(self, other):
if isinstance(other, Rational):
return Rational.__mod__(other, self)
return Number.__rmod__(self, other)
def _eval_power(self, expt):
if isinstance(expt, Number):
if isinstance(expt, Float):
return self._eval_evalf(expt._prec)**expt
if expt.is_extended_negative:
# (3/4)**-2 -> (4/3)**2
ne = -expt
if (ne is S.One):
return Rational(self.q, self.p)
if self.is_negative:
return S.NegativeOne**expt*Rational(self.q, -self.p)**ne
else:
return Rational(self.q, self.p)**ne
if expt is S.Infinity: # -oo already caught by test for negative
if self.p > self.q:
# (3/2)**oo -> oo
return S.Infinity
if self.p < -self.q:
# (-3/2)**oo -> oo + I*oo
return S.Infinity + S.Infinity*S.ImaginaryUnit
return S.Zero
if isinstance(expt, Integer):
# (4/3)**2 -> 4**2 / 3**2
return Rational(self.p**expt.p, self.q**expt.p, 1)
if isinstance(expt, Rational):
intpart = expt.p // expt.q
if intpart:
intpart += 1
remfracpart = intpart*expt.q - expt.p
ratfracpart = Rational(remfracpart, expt.q)
if self.p != 1:
return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
return Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
else:
remfracpart = expt.q - expt.p
ratfracpart = Rational(remfracpart, expt.q)
if self.p != 1:
return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
return Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
if self.is_extended_negative and expt.is_even:
return (-self)**expt
return
def _as_mpf_val(self, prec):
return mlib.from_rational(self.p, self.q, prec, rnd)
def _mpmath_(self, prec, rnd):
return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd))
def __abs__(self):
return Rational(abs(self.p), self.q)
def __int__(self):
p, q = self.p, self.q
if p < 0:
return -int(-p//q)
return int(p//q)
def floor(self):
return Integer(self.p // self.q)
def ceiling(self):
return -Integer(-self.p // self.q)
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def __eq__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if not isinstance(other, Number):
# S(0) == S.false is False
# S(0) == False is True
return False
if not self:
return not other
if other.is_NumberSymbol:
if other.is_irrational:
return False
return other.__eq__(self)
if other.is_Rational:
# a Rational is always in reduced form so will never be 2/4
# so we can just check equivalence of args
return self.p == other.p and self.q == other.q
if other.is_Float:
# all Floats have a denominator that is a power of 2
# so if self doesn't, it can't be equal to other
if self.q & (self.q - 1):
return False
s, m, t = other._mpf_[:3]
if s:
m = -m
if not t:
# other is an odd integer
if not self.is_Integer or self.is_even:
return False
return m == self.p
from .power import integer_log
if t > 0:
# other is an even integer
if not self.is_Integer:
return False
# does m*2**t == self.p
return self.p and not self.p % m and \
integer_log(self.p//m, 2) == (t, True)
# does non-integer s*m/2**-t = p/q?
if self.is_Integer:
return False
return m == self.p and integer_log(self.q, 2) == (-t, True)
return False
def __ne__(self, other):
return not self == other
def _Rrel(self, other, attr):
# if you want self < other, pass self, other, __gt__
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Number:
op = None
s, o = self, other
if other.is_NumberSymbol:
op = getattr(o, attr)
elif other.is_Float:
op = getattr(o, attr)
elif other.is_Rational:
s, o = Integer(s.p*o.q), Integer(s.q*o.p)
op = getattr(o, attr)
if op:
return op(s)
if o.is_number and o.is_extended_real:
return Integer(s.p), s.q*o
def __gt__(self, other):
rv = self._Rrel(other, '__lt__')
if rv is None:
rv = self, other
elif not isinstance(rv, tuple):
return rv
return Expr.__gt__(*rv)
def __ge__(self, other):
rv = self._Rrel(other, '__le__')
if rv is None:
rv = self, other
elif not isinstance(rv, tuple):
return rv
return Expr.__ge__(*rv)
def __lt__(self, other):
rv = self._Rrel(other, '__gt__')
if rv is None:
rv = self, other
elif not isinstance(rv, tuple):
return rv
return Expr.__lt__(*rv)
def __le__(self, other):
rv = self._Rrel(other, '__ge__')
if rv is None:
rv = self, other
elif not isinstance(rv, tuple):
return rv
return Expr.__le__(*rv)
def __hash__(self):
return super().__hash__()
def factors(self, limit=None, use_trial=True, use_rho=False,
use_pm1=False, verbose=False, visual=False):
"""A wrapper to factorint which return factors of self that are
smaller than limit (or cheap to compute). Special methods of
factoring are disabled by default so that only trial division is used.
"""
from sympy.ntheory.factor_ import factorrat
return factorrat(self, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose).copy()
@property
def numerator(self):
return self.p
@property
def denominator(self):
return self.q
@_sympifyit('other', NotImplemented)
def gcd(self, other):
if isinstance(other, Rational):
if other == S.Zero:
return other
return Rational(
igcd(self.p, other.p),
ilcm(self.q, other.q))
return Number.gcd(self, other)
@_sympifyit('other', NotImplemented)
def lcm(self, other):
if isinstance(other, Rational):
return Rational(
self.p // igcd(self.p, other.p) * other.p,
igcd(self.q, other.q))
return Number.lcm(self, other)
def as_numer_denom(self):
return Integer(self.p), Integer(self.q)
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import S
>>> (S(-3)/2).as_content_primitive()
(3/2, -1)
See docstring of Expr.as_content_primitive for more examples.
"""
if self:
if self.is_positive:
return self, S.One
return -self, S.NegativeOne
return S.One, self
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return self, S.One
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
return self, S.Zero
class Integer(Rational):
"""Represents integer numbers of any size.
Examples
========
>>> from sympy import Integer
>>> Integer(3)
3
If a float or a rational is passed to Integer, the fractional part
will be discarded; the effect is of rounding toward zero.
>>> Integer(3.8)
3
>>> Integer(-3.8)
-3
A string is acceptable input if it can be parsed as an integer:
>>> Integer("9" * 20)
99999999999999999999
It is rarely needed to explicitly instantiate an Integer, because
Python integers are automatically converted to Integer when they
are used in SymPy expressions.
"""
q = 1
is_integer = True
is_number = True
is_Integer = True
__slots__ = ()
def _as_mpf_val(self, prec):
return mlib.from_int(self.p, prec, rnd)
def _mpmath_(self, prec, rnd):
return mpmath.make_mpf(self._as_mpf_val(prec))
@cacheit
def __new__(cls, i):
if isinstance(i, str):
i = i.replace(' ', '')
# whereas we cannot, in general, make a Rational from an
# arbitrary expression, we can make an Integer unambiguously
# (except when a non-integer expression happens to round to
# an integer). So we proceed by taking int() of the input and
# let the int routines determine whether the expression can
# be made into an int or whether an error should be raised.
try:
ival = int(i)
except TypeError:
raise TypeError(
"Argument of Integer should be of numeric type, got %s." % i)
# We only work with well-behaved integer types. This converts, for
# example, numpy.int32 instances.
if ival == 1:
return S.One
if ival == -1:
return S.NegativeOne
if ival == 0:
return S.Zero
obj = Expr.__new__(cls)
obj.p = ival
return obj
def __getnewargs__(self):
return (self.p,)
# Arithmetic operations are here for efficiency
def __int__(self):
return self.p
def floor(self):
return Integer(self.p)
def ceiling(self):
return Integer(self.p)
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def __neg__(self):
return Integer(-self.p)
def __abs__(self):
if self.p >= 0:
return self
else:
return Integer(-self.p)
def __divmod__(self, other):
if isinstance(other, Integer) and global_parameters.evaluate:
return Tuple(*(divmod(self.p, other.p)))
else:
return Number.__divmod__(self, other)
def __rdivmod__(self, other):
if isinstance(other, int) and global_parameters.evaluate:
return Tuple(*(divmod(other, self.p)))
else:
try:
other = Number(other)
except TypeError:
msg = "unsupported operand type(s) for divmod(): '%s' and '%s'"
oname = type(other).__name__
sname = type(self).__name__
raise TypeError(msg % (oname, sname))
return Number.__divmod__(other, self)
# TODO make it decorator + bytecodehacks?
def __add__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p + other)
elif isinstance(other, Integer):
return Integer(self.p + other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.q + other.p, other.q, 1)
return Rational.__add__(self, other)
else:
return Add(self, other)
def __radd__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other + self.p)
elif isinstance(other, Rational):
return Rational(other.p + self.p*other.q, other.q, 1)
return Rational.__radd__(self, other)
return Rational.__radd__(self, other)
def __sub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p - other)
elif isinstance(other, Integer):
return Integer(self.p - other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.q - other.p, other.q, 1)
return Rational.__sub__(self, other)
return Rational.__sub__(self, other)
def __rsub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other - self.p)
elif isinstance(other, Rational):
return Rational(other.p - self.p*other.q, other.q, 1)
return Rational.__rsub__(self, other)
return Rational.__rsub__(self, other)
def __mul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p*other)
elif isinstance(other, Integer):
return Integer(self.p*other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.p, other.q, igcd(self.p, other.q))
return Rational.__mul__(self, other)
return Rational.__mul__(self, other)
def __rmul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other*self.p)
elif isinstance(other, Rational):
return Rational(other.p*self.p, other.q, igcd(self.p, other.q))
return Rational.__rmul__(self, other)
return Rational.__rmul__(self, other)
def __mod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p % other)
elif isinstance(other, Integer):
return Integer(self.p % other.p)
return Rational.__mod__(self, other)
return Rational.__mod__(self, other)
def __rmod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other % self.p)
elif isinstance(other, Integer):
return Integer(other.p % self.p)
return Rational.__rmod__(self, other)
return Rational.__rmod__(self, other)
def __eq__(self, other):
if isinstance(other, int):
return (self.p == other)
elif isinstance(other, Integer):
return (self.p == other.p)
return Rational.__eq__(self, other)
def __ne__(self, other):
return not self == other
def __gt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p > other.p)
return Rational.__gt__(self, other)
def __lt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p < other.p)
return Rational.__lt__(self, other)
def __ge__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p >= other.p)
return Rational.__ge__(self, other)
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p <= other.p)
return Rational.__le__(self, other)
def __hash__(self):
return hash(self.p)
def __index__(self):
return self.p
########################################
def _eval_is_odd(self):
return bool(self.p % 2)
def _eval_power(self, expt):
"""
Tries to do some simplifications on self**expt
Returns None if no further simplifications can be done.
Explanation
===========
When exponent is a fraction (so we have for example a square root),
we try to find a simpler representation by factoring the argument
up to factors of 2**15, e.g.
- sqrt(4) becomes 2
- sqrt(-4) becomes 2*I
- (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7)
Further simplification would require a special call to factorint on
the argument which is not done here for sake of speed.
"""
from sympy.ntheory.factor_ import perfect_power
if expt is S.Infinity:
if self.p > S.One:
return S.Infinity
# cases -1, 0, 1 are done in their respective classes
return S.Infinity + S.ImaginaryUnit*S.Infinity
if expt is S.NegativeInfinity:
return Rational(1, self, 1)**S.Infinity
if not isinstance(expt, Number):
# simplify when expt is even
# (-2)**k --> 2**k
if self.is_negative and expt.is_even:
return (-self)**expt
if isinstance(expt, Float):
# Rational knows how to exponentiate by a Float
return super()._eval_power(expt)
if not isinstance(expt, Rational):
return
if expt is S.Half and self.is_negative:
# we extract I for this special case since everyone is doing so
return S.ImaginaryUnit*Pow(-self, expt)
if expt.is_negative:
# invert base and change sign on exponent
ne = -expt
if self.is_negative:
return S.NegativeOne**expt*Rational(1, -self, 1)**ne
else:
return Rational(1, self.p, 1)**ne
# see if base is a perfect root, sqrt(4) --> 2
x, xexact = integer_nthroot(abs(self.p), expt.q)
if xexact:
# if it's a perfect root we've finished
result = Integer(x**abs(expt.p))
if self.is_negative:
result *= S.NegativeOne**expt
return result
# The following is an algorithm where we collect perfect roots
# from the factors of base.
# if it's not an nth root, it still might be a perfect power
b_pos = int(abs(self.p))
p = perfect_power(b_pos)
if p is not False:
dict = {p[0]: p[1]}
else:
dict = Integer(b_pos).factors(limit=2**15)
# now process the dict of factors
out_int = 1 # integer part
out_rad = 1 # extracted radicals
sqr_int = 1
sqr_gcd = 0
sqr_dict = {}
for prime, exponent in dict.items():
exponent *= expt.p
# remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10)
div_e, div_m = divmod(exponent, expt.q)
if div_e > 0:
out_int *= prime**div_e
if div_m > 0:
# see if the reduced exponent shares a gcd with e.q
# (2**2)**(1/10) -> 2**(1/5)
g = igcd(div_m, expt.q)
if g != 1:
out_rad *= Pow(prime, Rational(div_m//g, expt.q//g, 1))
else:
sqr_dict[prime] = div_m
# identify gcd of remaining powers
for p, ex in sqr_dict.items():
if sqr_gcd == 0:
sqr_gcd = ex
else:
sqr_gcd = igcd(sqr_gcd, ex)
if sqr_gcd == 1:
break
for k, v in sqr_dict.items():
sqr_int *= k**(v//sqr_gcd)
if sqr_int == b_pos and out_int == 1 and out_rad == 1:
result = None
else:
result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))
if self.is_negative:
result *= Pow(S.NegativeOne, expt)
return result
def _eval_is_prime(self):
from sympy.ntheory.primetest import isprime
return isprime(self)
def _eval_is_composite(self):
if self > 1:
return fuzzy_not(self.is_prime)
else:
return False
def as_numer_denom(self):
return self, S.One
@_sympifyit('other', NotImplemented)
def __floordiv__(self, other):
if not isinstance(other, Expr):
return NotImplemented
if isinstance(other, Integer):
return Integer(self.p // other)
return Integer(divmod(self, other)[0])
def __rfloordiv__(self, other):
return Integer(Integer(other).p // self.p)
# These bitwise operations (__lshift__, __rlshift__, ..., __invert__) are defined
# for Integer only and not for general SymPy expressions. This is to achieve
# compatibility with the numbers.Integral ABC which only defines these operations
# among instances of numbers.Integral. Therefore, these methods check explicitly for
# integer types rather than using sympify because they should not accept arbitrary
# symbolic expressions and there is no symbolic analogue of numbers.Integral's
# bitwise operations.
def __lshift__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p << int(other))
else:
return NotImplemented
def __rlshift__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) << self.p)
else:
return NotImplemented
def __rshift__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p >> int(other))
else:
return NotImplemented
def __rrshift__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) >> self.p)
else:
return NotImplemented
def __and__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p & int(other))
else:
return NotImplemented
def __rand__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) & self.p)
else:
return NotImplemented
def __xor__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p ^ int(other))
else:
return NotImplemented
def __rxor__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) ^ self.p)
else:
return NotImplemented
def __or__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p | int(other))
else:
return NotImplemented
def __ror__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) | self.p)
else:
return NotImplemented
def __invert__(self):
return Integer(~self.p)
# Add sympify converters
_sympy_converter[int] = Integer
class AlgebraicNumber(Expr):
r"""
Class for representing algebraic numbers in SymPy.
Symbolically, an instance of this class represents an element
$\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the
algebraic number $\alpha$ is represented as an element of a particular
number field $\mathbb{Q}(\theta)$, with a particular embedding of this
field into the complex numbers.
Formally, the primitive element $\theta$ is given by two data points: (1)
its minimal polynomial (which defines $\mathbb{Q}(\theta)$), and (2) a
particular complex number that is a root of this polynomial (which defines
the embedding $\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$). Finally,
the algebraic number $\alpha$ which we represent is then given by the
coefficients of a polynomial in $\theta$.
"""
__slots__ = ('rep', 'root', 'alias', 'minpoly', '_own_minpoly')
is_AlgebraicNumber = True
is_algebraic = True
is_number = True
kind = NumberKind
# Optional alias symbol is not free.
# Actually, alias should be a Str, but some methods
# expect that it be an instance of Expr.
free_symbols: set[Basic] = set()
def __new__(cls, expr, coeffs=None, alias=None, **args):
r"""
Construct a new algebraic number $\alpha$ belonging to a number field
$k = \mathbb{Q}(\theta)$.
There are four instance attributes to be determined:
=========== ============================================================================
Attribute Type/Meaning
=========== ============================================================================
``root`` :py:class:`~.Expr` for $\theta$ as a complex number
``minpoly`` :py:class:`~.Poly`, the minimal polynomial of $\theta$
``rep`` :py:class:`~sympy.polys.polyclasses.DMP` giving $\alpha$ as poly in $\theta$
``alias`` :py:class:`~.Symbol` for $\theta$, or ``None``
=========== ============================================================================
See Parameters section for how they are determined.
Parameters
==========
expr : :py:class:`~.Expr`, or pair $(m, r)$
There are three distinct modes of construction, depending on what
is passed as *expr*.
**(1)** *expr* is an :py:class:`~.AlgebraicNumber`:
In this case we begin by copying all four instance attributes from
*expr*. If *coeffs* were also given, we compose the two coeff
polynomials (see below). If an *alias* was given, it overrides.
**(2)** *expr* is any other type of :py:class:`~.Expr`:
Then ``root`` will equal *expr*. Therefore it
must express an algebraic quantity, and we will compute its
``minpoly``.
**(3)** *expr* is an ordered pair $(m, r)$ giving the
``minpoly`` $m$, and a ``root`` $r$ thereof, which together
define $\theta$. In this case $m$ may be either a univariate
:py:class:`~.Poly` or any :py:class:`~.Expr` which represents the
same, while $r$ must be some :py:class:`~.Expr` representing a
complex number that is a root of $m$, including both explicit
expressions in radicals, and instances of
:py:class:`~.ComplexRootOf` or :py:class:`~.AlgebraicNumber`.
coeffs : list, :py:class:`~.ANP`, None, optional (default=None)
This defines ``rep``, giving the algebraic number $\alpha$ as a
polynomial in $\theta$.
If a list, the elements should be integers or rational numbers.
If an :py:class:`~.ANP`, we take its coefficients (using its
:py:meth:`~.ANP.to_list()` method). If ``None``, then the list of
coefficients defaults to ``[1, 0]``, meaning that $\alpha = \theta$
is the primitive element of the field.
If *expr* was an :py:class:`~.AlgebraicNumber`, let $g(x)$ be its
``rep`` polynomial, and let $f(x)$ be the polynomial defined by
*coeffs*. Then ``self.rep`` will represent the composition
$(f \circ g)(x)$.
alias : str, :py:class:`~.Symbol`, None, optional (default=None)
This is a way to provide a name for the primitive element. We
described several ways in which the *expr* argument can define the
value of the primitive element, but none of these methods gave it
a name. Here, for example, *alias* could be set as
``Symbol('theta')``, in order to make this symbol appear when
$\alpha$ is printed, or rendered as a polynomial, using the
:py:meth:`~.as_poly()` method.
Examples
========
Recall that we are constructing an algebraic number as a field element
$\alpha \in \mathbb{Q}(\theta)$.
>>> from sympy import AlgebraicNumber, sqrt, CRootOf, S
>>> from sympy.abc import x
Example (1): $\alpha = \theta = \sqrt{2}$
>>> a1 = AlgebraicNumber(sqrt(2))
>>> a1.minpoly_of_element().as_expr(x)
x**2 - 2
>>> a1.evalf(10)
1.414213562
Example (2): $\alpha = 3 \sqrt{2} - 5$, $\theta = \sqrt{2}$. We can
either build on the last example:
>>> a2 = AlgebraicNumber(a1, [3, -5])
>>> a2.as_expr()
-5 + 3*sqrt(2)
or start from scratch:
>>> a2 = AlgebraicNumber(sqrt(2), [3, -5])
>>> a2.as_expr()
-5 + 3*sqrt(2)
Example (3): $\alpha = 6 \sqrt{2} - 11$, $\theta = \sqrt{2}$. Again we
can build on the previous example, and we see that the coeff polys are
composed:
>>> a3 = AlgebraicNumber(a2, [2, -1])
>>> a3.as_expr()
-11 + 6*sqrt(2)
reflecting the fact that $(2x - 1) \circ (3x - 5) = 6x - 11$.
Example (4): $\alpha = \sqrt{2}$, $\theta = \sqrt{2} + \sqrt{3}$. The
easiest way is to use the :py:func:`~.to_number_field()` function:
>>> from sympy import to_number_field
>>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
>>> a4.minpoly_of_element().as_expr(x)
x**2 - 2
>>> a4.to_root()
sqrt(2)
>>> a4.primitive_element()
sqrt(2) + sqrt(3)
>>> a4.coeffs()
[1/2, 0, -9/2, 0]
but if you already knew the right coefficients, you could construct it
directly:
>>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0])
>>> a4.to_root()
sqrt(2)
>>> a4.primitive_element()
sqrt(2) + sqrt(3)
Example (5): Construct the Golden Ratio as an element of the 5th
cyclotomic field, supposing we already know its coefficients. This time
we introduce the alias $\zeta$ for the primitive element of the field:
>>> from sympy import cyclotomic_poly
>>> from sympy.abc import zeta
>>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1),
... [-1, -1, 0, 0], alias=zeta)
>>> a5.as_poly().as_expr()
-zeta**3 - zeta**2
>>> a5.evalf()
1.61803398874989
(The index ``-1`` to ``CRootOf`` selects the complex root with the
largest real and imaginary parts, which in this case is
$\mathrm{e}^{2i\pi/5}$. See :py:class:`~.ComplexRootOf`.)
Example (6): Building on the last example, construct the number
$2 \phi \in \mathbb{Q}(\phi)$, where $\phi$ is the Golden Ratio:
>>> from sympy.abc import phi
>>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi)
>>> a6.as_poly().as_expr()
2*phi
>>> a6.primitive_element().evalf()
1.61803398874989
Note that we needed to use ``a5.to_root()``, since passing ``a5`` as
the first argument would have constructed the number $2 \phi$ as an
element of the field $\mathbb{Q}(\zeta)$:
>>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0])
>>> a6_wrong.as_poly().as_expr()
-2*zeta**3 - 2*zeta**2
>>> a6_wrong.primitive_element().evalf()
0.309016994374947 + 0.951056516295154*I
"""
from sympy.polys.polyclasses import ANP, DMP
from sympy.polys.numberfields import minimal_polynomial
expr = sympify(expr)
rep0 = None
alias0 = None
if isinstance(expr, (tuple, Tuple)):
minpoly, root = expr
if not minpoly.is_Poly:
from sympy.polys.polytools import Poly
minpoly = Poly(minpoly)
elif expr.is_AlgebraicNumber:
minpoly, root, rep0, alias0 = (expr.minpoly, expr.root,
expr.rep, expr.alias)
else:
minpoly, root = minimal_polynomial(
expr, args.get('gen'), polys=True), expr
dom = minpoly.get_domain()
if coeffs is not None:
if not isinstance(coeffs, ANP):
rep = DMP.from_sympy_list(sympify(coeffs), 0, dom)
scoeffs = Tuple(*coeffs)
else:
rep = DMP.from_list(coeffs.to_list(), 0, dom)
scoeffs = Tuple(*coeffs.to_list())
else:
rep = DMP.from_list([1, 0], 0, dom)
scoeffs = Tuple(1, 0)
if rep0 is not None:
from sympy.polys.densetools import dup_compose
c = dup_compose(rep.rep, rep0.rep, dom)
rep = DMP.from_list(c, 0, dom)
scoeffs = Tuple(*c)
if rep.degree() >= minpoly.degree():
rep = rep.rem(minpoly.rep)
sargs = (root, scoeffs)
alias = alias or alias0
if alias is not None:
from .symbol import Symbol
if not isinstance(alias, Symbol):
alias = Symbol(alias)
sargs = sargs + (alias,)
obj = Expr.__new__(cls, *sargs)
obj.rep = rep
obj.root = root
obj.alias = alias
obj.minpoly = minpoly
obj._own_minpoly = None
return obj
def __hash__(self):
return super().__hash__()
def _eval_evalf(self, prec):
return self.as_expr()._evalf(prec)
@property
def is_aliased(self):
"""Returns ``True`` if ``alias`` was set. """
return self.alias is not None
def as_poly(self, x=None):
"""Create a Poly instance from ``self``. """
from sympy.polys.polytools import Poly, PurePoly
if x is not None:
return Poly.new(self.rep, x)
else:
if self.alias is not None:
return Poly.new(self.rep, self.alias)
else:
from .symbol import Dummy
return PurePoly.new(self.rep, Dummy('x'))
def as_expr(self, x=None):
"""Create a Basic expression from ``self``. """
return self.as_poly(x or self.root).as_expr().expand()
def coeffs(self):
"""Returns all SymPy coefficients of an algebraic number. """
return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ]
def native_coeffs(self):
"""Returns all native coefficients of an algebraic number. """
return self.rep.all_coeffs()
def to_algebraic_integer(self):
"""Convert ``self`` to an algebraic integer. """
from sympy.polys.polytools import Poly
f = self.minpoly
if f.LC() == 1:
return self
coeff = f.LC()**(f.degree() - 1)
poly = f.compose(Poly(f.gen/f.LC()))
minpoly = poly*coeff
root = f.LC()*self.root
return AlgebraicNumber((minpoly, root), self.coeffs())
def _eval_simplify(self, **kwargs):
from sympy.polys.rootoftools import CRootOf
from sympy.polys import minpoly
measure, ratio = kwargs['measure'], kwargs['ratio']
for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]:
if minpoly(self.root - r).is_Symbol:
# use the matching root if it's simpler
if measure(r) < ratio*measure(self.root):
return AlgebraicNumber(r)
return self
def field_element(self, coeffs):
r"""
Form another element of the same number field.
Explanation
===========
If we represent $\alpha \in \mathbb{Q}(\theta)$, form another element
$\beta \in \mathbb{Q}(\theta)$ of the same number field.
Parameters
==========
coeffs : list, :py:class:`~.ANP`
Like the *coeffs* arg to the class
:py:meth:`constructor<.AlgebraicNumber.__new__>`, defines the
new element as a polynomial in the primitive element.
If a list, the elements should be integers or rational numbers.
If an :py:class:`~.ANP`, we take its coefficients (using its
:py:meth:`~.ANP.to_list()` method).
Examples
========
>>> from sympy import AlgebraicNumber, sqrt
>>> a = AlgebraicNumber(sqrt(5), [-1, 1])
>>> b = a.field_element([3, 2])
>>> print(a)
1 - sqrt(5)
>>> print(b)
2 + 3*sqrt(5)
>>> print(b.primitive_element() == a.primitive_element())
True
See Also
========
.AlgebraicNumber.__new__()
"""
return AlgebraicNumber(
(self.minpoly, self.root), coeffs=coeffs, alias=self.alias)
@property
def is_primitive_element(self):
r"""
Say whether this algebraic number $\alpha \in \mathbb{Q}(\theta)$ is
equal to the primitive element $\theta$ for its field.
"""
c = self.coeffs()
# Second case occurs if self.minpoly is linear:
return c == [1, 0] or c == [self.root]
def primitive_element(self):
r"""
Get the primitive element $\theta$ for the number field
$\mathbb{Q}(\theta)$ to which this algebraic number $\alpha$ belongs.
Returns
=======
AlgebraicNumber
"""
if self.is_primitive_element:
return self
return self.field_element([1, 0])
def to_primitive_element(self, radicals=True):
r"""
Convert ``self`` to an :py:class:`~.AlgebraicNumber` instance that is
equal to its own primitive element.
Explanation
===========
If we represent $\alpha \in \mathbb{Q}(\theta)$, $\alpha \neq \theta$,
construct a new :py:class:`~.AlgebraicNumber` that represents
$\alpha \in \mathbb{Q}(\alpha)$.
Examples
========
>>> from sympy import sqrt, to_number_field
>>> from sympy.abc import x
>>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
The :py:class:`~.AlgebraicNumber` ``a`` represents the number
$\sqrt{2}$ in the field $\mathbb{Q}(\sqrt{2} + \sqrt{3})$. Rendering
``a`` as a polynomial,
>>> a.as_poly().as_expr(x)
x**3/2 - 9*x/2
reflects the fact that $\sqrt{2} = \theta^3/2 - 9 \theta/2$, where
$\theta = \sqrt{2} + \sqrt{3}$.
``a`` is not equal to its own primitive element. Its minpoly
>>> a.minpoly.as_poly().as_expr(x)
x**4 - 10*x**2 + 1
is that of $\theta$.
Converting to a primitive element,
>>> a_prim = a.to_primitive_element()
>>> a_prim.minpoly.as_poly().as_expr(x)
x**2 - 2
we obtain an :py:class:`~.AlgebraicNumber` whose ``minpoly`` is that of
the number itself.
Parameters
==========
radicals : boolean, optional (default=True)
If ``True``, then we will try to return an
:py:class:`~.AlgebraicNumber` whose ``root`` is an expression
in radicals. If that is not possible (or if *radicals* is
``False``), ``root`` will be a :py:class:`~.ComplexRootOf`.
Returns
=======
AlgebraicNumber
See Also
========
is_primitive_element
"""
if self.is_primitive_element:
return self
m = self.minpoly_of_element()
r = self.to_root(radicals=radicals)
return AlgebraicNumber((m, r))
def minpoly_of_element(self):
r"""
Compute the minimal polynomial for this algebraic number.
Explanation
===========
Recall that we represent an element $\alpha \in \mathbb{Q}(\theta)$.
Our instance attribute ``self.minpoly`` is the minimal polynomial for
our primitive element $\theta$. This method computes the minimal
polynomial for $\alpha$.
"""
if self._own_minpoly is None:
if self.is_primitive_element:
self._own_minpoly = self.minpoly
else:
from sympy.polys.numberfields.minpoly import minpoly
theta = self.primitive_element()
self._own_minpoly = minpoly(self.as_expr(theta), polys=True)
return self._own_minpoly
def to_root(self, radicals=True, minpoly=None):
"""
Convert to an :py:class:`~.Expr` that is not an
:py:class:`~.AlgebraicNumber`, specifically, either a
:py:class:`~.ComplexRootOf`, or, optionally and where possible, an
expression in radicals.
Parameters
==========
radicals : boolean, optional (default=True)
If ``True``, then we will try to return the root as an expression
in radicals. If that is not possible, we will return a
:py:class:`~.ComplexRootOf`.
minpoly : :py:class:`~.Poly`
If the minimal polynomial for `self` has been pre-computed, it can
be passed in order to save time.
"""
if self.is_primitive_element and not isinstance(self.root, AlgebraicNumber):
return self.root
m = minpoly or self.minpoly_of_element()
roots = m.all_roots(radicals=radicals)
if len(roots) == 1:
return roots[0]
ex = self.as_expr()
for b in roots:
if m.same_root(b, ex):
return b
class RationalConstant(Rational):
"""
Abstract base class for rationals with specific behaviors
Derived classes must define class attributes p and q and should probably all
be singletons.
"""
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
class IntegerConstant(Integer):
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
class Zero(IntegerConstant, metaclass=Singleton):
"""The number zero.
Zero is a singleton, and can be accessed by ``S.Zero``
Examples
========
>>> from sympy import S, Integer
>>> Integer(0) is S.Zero
True
>>> 1/S.Zero
zoo
References
==========
.. [1] https://en.wikipedia.org/wiki/Zero
"""
p = 0
q = 1
is_positive = False
is_negative = False
is_zero = True
is_number = True
is_comparable = True
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.Zero
@staticmethod
def __neg__():
return S.Zero
def _eval_power(self, expt):
if expt.is_extended_positive:
return self
if expt.is_extended_negative:
return S.ComplexInfinity
if expt.is_extended_real is False:
return S.NaN
if expt.is_zero:
return S.One
# infinities are already handled with pos and neg
# tests above; now throw away leading numbers on Mul
# exponent since 0**-x = zoo**x even when x == 0
coeff, terms = expt.as_coeff_Mul()
if coeff.is_negative:
return S.ComplexInfinity**terms
if coeff is not S.One: # there is a Number to discard
return self**terms
def _eval_order(self, *symbols):
# Order(0,x) -> 0
return self
def __bool__(self):
return False
class One(IntegerConstant, metaclass=Singleton):
"""The number one.
One is a singleton, and can be accessed by ``S.One``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(1) is S.One
True
References
==========
.. [1] https://en.wikipedia.org/wiki/1_%28number%29
"""
is_number = True
is_positive = True
p = 1
q = 1
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.One
@staticmethod
def __neg__():
return S.NegativeOne
def _eval_power(self, expt):
return self
def _eval_order(self, *symbols):
return
@staticmethod
def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False,
verbose=False, visual=False):
if visual:
return S.One
else:
return {}
class NegativeOne(IntegerConstant, metaclass=Singleton):
"""The number negative one.
NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(-1) is S.NegativeOne
True
See Also
========
One
References
==========
.. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29
"""
is_number = True
p = -1
q = 1
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.One
@staticmethod
def __neg__():
return S.One
def _eval_power(self, expt):
if expt.is_odd:
return S.NegativeOne
if expt.is_even:
return S.One
if isinstance(expt, Number):
if isinstance(expt, Float):
return Float(-1.0)**expt
if expt is S.NaN:
return S.NaN
if expt in (S.Infinity, S.NegativeInfinity):
return S.NaN
if expt is S.Half:
return S.ImaginaryUnit
if isinstance(expt, Rational):
if expt.q == 2:
return S.ImaginaryUnit**Integer(expt.p)
i, r = divmod(expt.p, expt.q)
if i:
return self**i*self**Rational(r, expt.q)
return
class Half(RationalConstant, metaclass=Singleton):
"""The rational number 1/2.
Half is a singleton, and can be accessed by ``S.Half``.
Examples
========
>>> from sympy import S, Rational
>>> Rational(1, 2) is S.Half
True
References
==========
.. [1] https://en.wikipedia.org/wiki/One_half
"""
is_number = True
p = 1
q = 2
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.Half
class Infinity(Number, metaclass=Singleton):
r"""Positive infinite quantity.
Explanation
===========
In real analysis the symbol `\infty` denotes an unbounded
limit: `x\to\infty` means that `x` grows without bound.
Infinity is often used not only to define a limit but as a value
in the affinely extended real number system. Points labeled `+\infty`
and `-\infty` can be added to the topological space of the real numbers,
producing the two-point compactification of the real numbers. Adding
algebraic properties to this gives us the extended real numbers.
Infinity is a singleton, and can be accessed by ``S.Infinity``,
or can be imported as ``oo``.
Examples
========
>>> from sympy import oo, exp, limit, Symbol
>>> 1 + oo
oo
>>> 42/oo
0
>>> x = Symbol('x')
>>> limit(exp(x), x, oo)
oo
See Also
========
NegativeInfinity, NaN
References
==========
.. [1] https://en.wikipedia.org/wiki/Infinity
"""
is_commutative = True
is_number = True
is_complex = False
is_extended_real = True
is_infinite = True
is_comparable = True
is_extended_positive = True
is_prime = False
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\infty"
def _eval_subs(self, old, new):
if self == old:
return new
def _eval_evalf(self, prec=None):
return Float('inf')
def evalf(self, prec=None, **options):
return self._eval_evalf(prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other in (S.NegativeInfinity, S.NaN):
return S.NaN
return self
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other in (S.Infinity, S.NaN):
return S.NaN
return self
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return (-self).__add__(other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other.is_zero or other is S.NaN:
return S.NaN
if other.is_extended_positive:
return self
return S.NegativeInfinity
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or \
other is S.NegativeInfinity or \
other is S.NaN:
return S.NaN
if other.is_extended_nonnegative:
return self
return S.NegativeInfinity
return Number.__truediv__(self, other)
def __abs__(self):
return S.Infinity
def __neg__(self):
return S.NegativeInfinity
def _eval_power(self, expt):
"""
``expt`` is symbolic object but not equal to 0 or 1.
================ ======= ==============================
Expression Result Notes
================ ======= ==============================
``oo ** nan`` ``nan``
``oo ** -p`` ``0`` ``p`` is number, ``oo``
================ ======= ==============================
See Also
========
Pow
NaN
NegativeInfinity
"""
if expt.is_extended_positive:
return S.Infinity
if expt.is_extended_negative:
return S.Zero
if expt is S.NaN:
return S.NaN
if expt is S.ComplexInfinity:
return S.NaN
if expt.is_extended_real is False and expt.is_number:
from sympy.functions.elementary.complexes import re
expt_real = re(expt)
if expt_real.is_positive:
return S.ComplexInfinity
if expt_real.is_negative:
return S.Zero
if expt_real.is_zero:
return S.NaN
return self**expt.evalf()
def _as_mpf_val(self, prec):
return mlib.finf
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
return other is S.Infinity or other == float('inf')
def __ne__(self, other):
return other is not S.Infinity and other != float('inf')
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if not isinstance(other, Expr):
return NotImplemented
return S.NaN
__rmod__ = __mod__
def floor(self):
return self
def ceiling(self):
return self
oo = S.Infinity
class NegativeInfinity(Number, metaclass=Singleton):
"""Negative infinite quantity.
NegativeInfinity is a singleton, and can be accessed
by ``S.NegativeInfinity``.
See Also
========
Infinity
"""
is_extended_real = True
is_complex = False
is_commutative = True
is_infinite = True
is_comparable = True
is_extended_negative = True
is_number = True
is_prime = False
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"-\infty"
def _eval_subs(self, old, new):
if self == old:
return new
def _eval_evalf(self, prec=None):
return Float('-inf')
def evalf(self, prec=None, **options):
return self._eval_evalf(prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other in (S.Infinity, S.NaN):
return S.NaN
return self
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other in (S.NegativeInfinity, S.NaN):
return S.NaN
return self
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return (-self).__add__(other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other.is_zero or other is S.NaN:
return S.NaN
if other.is_extended_positive:
return self
return S.Infinity
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or \
other is S.NegativeInfinity or \
other is S.NaN:
return S.NaN
if other.is_extended_nonnegative:
return self
return S.Infinity
return Number.__truediv__(self, other)
def __abs__(self):
return S.Infinity
def __neg__(self):
return S.Infinity
def _eval_power(self, expt):
"""
``expt`` is symbolic object but not equal to 0 or 1.
================ ======= ==============================
Expression Result Notes
================ ======= ==============================
``(-oo) ** nan`` ``nan``
``(-oo) ** oo`` ``nan``
``(-oo) ** -oo`` ``nan``
``(-oo) ** e`` ``oo`` ``e`` is positive even integer
``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer
================ ======= ==============================
See Also
========
Infinity
Pow
NaN
"""
if expt.is_number:
if expt is S.NaN or \
expt is S.Infinity or \
expt is S.NegativeInfinity:
return S.NaN
if isinstance(expt, Integer) and expt.is_extended_positive:
if expt.is_odd:
return S.NegativeInfinity
else:
return S.Infinity
inf_part = S.Infinity**expt
s_part = S.NegativeOne**expt
if inf_part == 0 and s_part.is_finite:
return inf_part
if (inf_part is S.ComplexInfinity and
s_part.is_finite and not s_part.is_zero):
return S.ComplexInfinity
return s_part*inf_part
def _as_mpf_val(self, prec):
return mlib.fninf
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
return other is S.NegativeInfinity or other == float('-inf')
def __ne__(self, other):
return other is not S.NegativeInfinity and other != float('-inf')
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if not isinstance(other, Expr):
return NotImplemented
return S.NaN
__rmod__ = __mod__
def floor(self):
return self
def ceiling(self):
return self
def as_powers_dict(self):
return {S.NegativeOne: 1, S.Infinity: 1}
class NaN(Number, metaclass=Singleton):
"""
Not a Number.
Explanation
===========
This serves as a place holder for numeric values that are indeterminate.
Most operations on NaN, produce another NaN. Most indeterminate forms,
such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0``
and ``oo**0``, which all produce ``1`` (this is consistent with Python's
float).
NaN is loosely related to floating point nan, which is defined in the
IEEE 754 floating point standard, and corresponds to the Python
``float('nan')``. Differences are noted below.
NaN is mathematically not equal to anything else, even NaN itself. This
explains the initially counter-intuitive results with ``Eq`` and ``==`` in
the examples below.
NaN is not comparable so inequalities raise a TypeError. This is in
contrast with floating point nan where all inequalities are false.
NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported
as ``nan``.
Examples
========
>>> from sympy import nan, S, oo, Eq
>>> nan is S.NaN
True
>>> oo - oo
nan
>>> nan + 1
nan
>>> Eq(nan, nan) # mathematical equality
False
>>> nan == nan # structural equality
True
References
==========
.. [1] https://en.wikipedia.org/wiki/NaN
"""
is_commutative = True
is_extended_real = None
is_real = None
is_rational = None
is_algebraic = None
is_transcendental = None
is_integer = None
is_comparable = False
is_finite = None
is_zero = None
is_prime = None
is_positive = None
is_negative = None
is_number = True
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\text{NaN}"
def __neg__(self):
return self
@_sympifyit('other', NotImplemented)
def __add__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
return self
def floor(self):
return self
def ceiling(self):
return self
def _as_mpf_val(self, prec):
return _mpf_nan
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
# NaN is structurally equal to another NaN
return other is S.NaN
def __ne__(self, other):
return other is not S.NaN
# Expr will _sympify and raise TypeError
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
nan = S.NaN
@dispatch(NaN, Expr) # type:ignore
def _eval_is_eq(a, b): # noqa:F811
return False
class ComplexInfinity(AtomicExpr, metaclass=Singleton):
r"""Complex infinity.
Explanation
===========
In complex analysis the symbol `\tilde\infty`, called "complex
infinity", represents a quantity with infinite magnitude, but
undetermined complex phase.
ComplexInfinity is a singleton, and can be accessed by
``S.ComplexInfinity``, or can be imported as ``zoo``.
Examples
========
>>> from sympy import zoo
>>> zoo + 42
zoo
>>> 42/zoo
0
>>> zoo + zoo
nan
>>> zoo*zoo
zoo
See Also
========
Infinity
"""
is_commutative = True
is_infinite = True
is_number = True
is_prime = False
is_complex = False
is_extended_real = False
kind = NumberKind
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\tilde{\infty}"
@staticmethod
def __abs__():
return S.Infinity
def floor(self):
return self
def ceiling(self):
return self
@staticmethod
def __neg__():
return S.ComplexInfinity
def _eval_power(self, expt):
if expt is S.ComplexInfinity:
return S.NaN
if isinstance(expt, Number):
if expt.is_zero:
return S.NaN
else:
if expt.is_positive:
return S.ComplexInfinity
else:
return S.Zero
zoo = S.ComplexInfinity
class NumberSymbol(AtomicExpr):
is_commutative = True
is_finite = True
is_number = True
__slots__ = ()
is_NumberSymbol = True
kind = NumberKind
def __new__(cls):
return AtomicExpr.__new__(cls)
def approximation(self, number_cls):
""" Return an interval with number_cls endpoints
that contains the value of NumberSymbol.
If not implemented, then return None.
"""
def _eval_evalf(self, prec):
return Float._new(self._as_mpf_val(prec), prec)
def __eq__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if self is other:
return True
if other.is_Number and self.is_irrational:
return False
return False # NumberSymbol != non-(Number|self)
def __ne__(self, other):
return not self == other
def __le__(self, other):
if self is other:
return S.true
return Expr.__le__(self, other)
def __ge__(self, other):
if self is other:
return S.true
return Expr.__ge__(self, other)
def __int__(self):
# subclass with appropriate return value
raise NotImplementedError
def __hash__(self):
return super().__hash__()
class Exp1(NumberSymbol, metaclass=Singleton):
r"""The `e` constant.
Explanation
===========
The transcendental number `e = 2.718281828\ldots` is the base of the
natural logarithm and of the exponential function, `e = \exp(1)`.
Sometimes called Euler's number or Napier's constant.
Exp1 is a singleton, and can be accessed by ``S.Exp1``,
or can be imported as ``E``.
Examples
========
>>> from sympy import exp, log, E
>>> E is exp(1)
True
>>> log(E)
1
References
==========
.. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29
"""
is_real = True
is_positive = True
is_negative = False # XXX Forces is_negative/is_nonnegative
is_irrational = True
is_number = True
is_algebraic = False
is_transcendental = True
__slots__ = ()
def _latex(self, printer):
return r"e"
@staticmethod
def __abs__():
return S.Exp1
def __int__(self):
return 2
def _as_mpf_val(self, prec):
return mpf_e(prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (Integer(2), Integer(3))
elif issubclass(number_cls, Rational):
pass
def _eval_power(self, expt):
if global_parameters.exp_is_pow:
return self._eval_power_exp_is_pow(expt)
else:
from sympy.functions.elementary.exponential import exp
return exp(expt)
def _eval_power_exp_is_pow(self, arg):
if arg.is_Number:
if arg is oo:
return oo
elif arg == -oo:
return S.Zero
from sympy.functions.elementary.exponential import log
if isinstance(arg, log):
return arg.args[0]
# don't autoexpand Pow or Mul (see the issue 3351):
elif not arg.is_Add:
Ioo = I*oo
if arg in [Ioo, -Ioo]:
return nan
coeff = arg.coeff(pi*I)
if coeff:
if (2*coeff).is_integer:
if coeff.is_even:
return S.One
elif coeff.is_odd:
return S.NegativeOne
elif (coeff + S.Half).is_even:
return -I
elif (coeff + S.Half).is_odd:
return I
elif coeff.is_Rational:
ncoeff = coeff % 2 # restrict to [0, 2pi)
if ncoeff > 1: # restrict to (-pi, pi]
ncoeff -= 2
if ncoeff != coeff:
return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit)
# Warning: code in risch.py will be very sensitive to changes
# in this (see DifferentialExtension).
# look for a single log factor
coeff, terms = arg.as_coeff_Mul()
# but it can't be multiplied by oo
if coeff in (oo, -oo):
return
coeffs, log_term = [coeff], None
for term in Mul.make_args(terms):
if isinstance(term, log):
if log_term is None:
log_term = term.args[0]
else:
return
elif term.is_comparable:
coeffs.append(term)
else:
return
return log_term**Mul(*coeffs) if log_term else None
elif arg.is_Add:
out = []
add = []
argchanged = False
for a in arg.args:
if a is S.One:
add.append(a)
continue
newa = self**a
if isinstance(newa, Pow) and newa.base is self:
if newa.exp != a:
add.append(newa.exp)
argchanged = True
else:
add.append(a)
else:
out.append(newa)
if out or argchanged:
return Mul(*out)*Pow(self, Add(*add), evaluate=False)
elif arg.is_Matrix:
return arg.exp()
def _eval_rewrite_as_sin(self, **kwargs):
from sympy.functions.elementary.trigonometric import sin
return sin(I + S.Pi/2) - I*sin(I)
def _eval_rewrite_as_cos(self, **kwargs):
from sympy.functions.elementary.trigonometric import cos
return cos(I) + I*cos(I + S.Pi/2)
E = S.Exp1
class Pi(NumberSymbol, metaclass=Singleton):
r"""The `\pi` constant.
Explanation
===========
The transcendental number `\pi = 3.141592654\ldots` represents the ratio
of a circle's circumference to its diameter, the area of the unit circle,
the half-period of trigonometric functions, and many other things
in mathematics.
Pi is a singleton, and can be accessed by ``S.Pi``, or can
be imported as ``pi``.
Examples
========
>>> from sympy import S, pi, oo, sin, exp, integrate, Symbol
>>> S.Pi
pi
>>> pi > 3
True
>>> pi.is_irrational
True
>>> x = Symbol('x')
>>> sin(x + 2*pi)
sin(x)
>>> integrate(exp(-x**2), (x, -oo, oo))
sqrt(pi)
References
==========
.. [1] https://en.wikipedia.org/wiki/Pi
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = False
is_transcendental = True
__slots__ = ()
def _latex(self, printer):
return r"\pi"
@staticmethod
def __abs__():
return S.Pi
def __int__(self):
return 3
def _as_mpf_val(self, prec):
return mpf_pi(prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (Integer(3), Integer(4))
elif issubclass(number_cls, Rational):
return (Rational(223, 71, 1), Rational(22, 7, 1))
pi = S.Pi
class GoldenRatio(NumberSymbol, metaclass=Singleton):
r"""The golden ratio, `\phi`.
Explanation
===========
`\phi = \frac{1 + \sqrt{5}}{2}` is an algebraic number. Two quantities
are in the golden ratio if their ratio is the same as the ratio of
their sum to the larger of the two quantities, i.e. their maximum.
GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``.
Examples
========
>>> from sympy import S
>>> S.GoldenRatio > 1
True
>>> S.GoldenRatio.expand(func=True)
1/2 + sqrt(5)/2
>>> S.GoldenRatio.is_irrational
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Golden_ratio
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = True
is_transcendental = False
__slots__ = ()
def _latex(self, printer):
return r"\phi"
def __int__(self):
return 1
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10)
return mpf_norm(rv, prec)
def _eval_expand_func(self, **hints):
from sympy.functions.elementary.miscellaneous import sqrt
return S.Half + S.Half*sqrt(5)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.One, Rational(2))
elif issubclass(number_cls, Rational):
pass
_eval_rewrite_as_sqrt = _eval_expand_func
class TribonacciConstant(NumberSymbol, metaclass=Singleton):
r"""The tribonacci constant.
Explanation
===========
The tribonacci numbers are like the Fibonacci numbers, but instead
of starting with two predetermined terms, the sequence starts with
three predetermined terms and each term afterwards is the sum of the
preceding three terms.
The tribonacci constant is the ratio toward which adjacent tribonacci
numbers tend. It is a root of the polynomial `x^3 - x^2 - x - 1 = 0`,
and also satisfies the equation `x + x^{-3} = 2`.
TribonacciConstant is a singleton, and can be accessed
by ``S.TribonacciConstant``.
Examples
========
>>> from sympy import S
>>> S.TribonacciConstant > 1
True
>>> S.TribonacciConstant.expand(func=True)
1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3
>>> S.TribonacciConstant.is_irrational
True
>>> S.TribonacciConstant.n(20)
1.8392867552141611326
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = True
is_transcendental = False
__slots__ = ()
def _latex(self, printer):
return r"\text{TribonacciConstant}"
def __int__(self):
return 1
def _eval_evalf(self, prec):
rv = self._eval_expand_func(function=True)._eval_evalf(prec + 4)
return Float(rv, precision=prec)
def _eval_expand_func(self, **hints):
from sympy.functions.elementary.miscellaneous import cbrt, sqrt
return (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.One, Rational(2))
elif issubclass(number_cls, Rational):
pass
_eval_rewrite_as_sqrt = _eval_expand_func
class EulerGamma(NumberSymbol, metaclass=Singleton):
r"""The Euler-Mascheroni constant.
Explanation
===========
`\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical
constant recurring in analysis and number theory. It is defined as the
limiting difference between the harmonic series and the
natural logarithm:
.. math:: \gamma = \lim\limits_{n\to\infty}
\left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)
EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``.
Examples
========
>>> from sympy import S
>>> S.EulerGamma.is_irrational
>>> S.EulerGamma > 0
True
>>> S.EulerGamma > 1
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = None
is_number = True
__slots__ = ()
def _latex(self, printer):
return r"\gamma"
def __int__(self):
return 0
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
v = mlib.libhyper.euler_fixed(prec + 10)
rv = mlib.from_man_exp(v, -prec - 10)
return mpf_norm(rv, prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.Zero, S.One)
elif issubclass(number_cls, Rational):
return (S.Half, Rational(3, 5, 1))
class Catalan(NumberSymbol, metaclass=Singleton):
r"""Catalan's constant.
Explanation
===========
$G = 0.91596559\ldots$ is given by the infinite series
.. math:: G = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}
Catalan is a singleton, and can be accessed by ``S.Catalan``.
Examples
========
>>> from sympy import S
>>> S.Catalan.is_irrational
>>> S.Catalan > 0
True
>>> S.Catalan > 1
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Catalan%27s_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = None
is_number = True
__slots__ = ()
def __int__(self):
return 0
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
v = mlib.catalan_fixed(prec + 10)
rv = mlib.from_man_exp(v, -prec - 10)
return mpf_norm(rv, prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.Zero, S.One)
elif issubclass(number_cls, Rational):
return (Rational(9, 10, 1), S.One)
def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):
if (k_sym is not None) or (symbols is not None):
return self
from .symbol import Dummy
from sympy.concrete.summations import Sum
k = Dummy('k', integer=True, nonnegative=True)
return Sum(S.NegativeOne**k / (2*k+1)**2, (k, 0, S.Infinity))
def _latex(self, printer):
return "G"
class ImaginaryUnit(AtomicExpr, metaclass=Singleton):
r"""The imaginary unit, `i = \sqrt{-1}`.
I is a singleton, and can be accessed by ``S.I``, or can be
imported as ``I``.
Examples
========
>>> from sympy import I, sqrt
>>> sqrt(-1)
I
>>> I*I
-1
>>> 1/I
-I
References
==========
.. [1] https://en.wikipedia.org/wiki/Imaginary_unit
"""
is_commutative = True
is_imaginary = True
is_finite = True
is_number = True
is_algebraic = True
is_transcendental = False
kind = NumberKind
__slots__ = ()
def _latex(self, printer):
return printer._settings['imaginary_unit_latex']
@staticmethod
def __abs__():
return S.One
def _eval_evalf(self, prec):
return self
def _eval_conjugate(self):
return -S.ImaginaryUnit
def _eval_power(self, expt):
"""
b is I = sqrt(-1)
e is symbolic object but not equal to 0, 1
I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal
I**0 mod 4 -> 1
I**1 mod 4 -> I
I**2 mod 4 -> -1
I**3 mod 4 -> -I
"""
if isinstance(expt, Integer):
expt = expt % 4
if expt == 0:
return S.One
elif expt == 1:
return S.ImaginaryUnit
elif expt == 2:
return S.NegativeOne
elif expt == 3:
return -S.ImaginaryUnit
if isinstance(expt, Rational):
i, r = divmod(expt, 2)
rv = Pow(S.ImaginaryUnit, r, evaluate=False)
if i % 2:
return Mul(S.NegativeOne, rv, evaluate=False)
return rv
def as_base_exp(self):
return S.NegativeOne, S.Half
@property
def _mpc_(self):
return (Float(0)._mpf_, Float(1)._mpf_)
I = S.ImaginaryUnit
@dispatch(Tuple, Number) # type:ignore
def _eval_is_eq(self, other): # noqa: F811
return False
def sympify_fractions(f):
return Rational(f.numerator, f.denominator, 1)
_sympy_converter[fractions.Fraction] = sympify_fractions
if HAS_GMPY:
def sympify_mpz(x):
return Integer(int(x))
# XXX: The sympify_mpq function here was never used because it is
# overridden by the other sympify_mpq function below. Maybe it should just
# be removed or maybe it should be used for something...
def sympify_mpq(x):
return Rational(int(x.numerator), int(x.denominator))
_sympy_converter[type(gmpy.mpz(1))] = sympify_mpz
_sympy_converter[type(gmpy.mpq(1, 2))] = sympify_mpq
def sympify_mpmath_mpq(x):
p, q = x._mpq_
return Rational(p, q, 1)
_sympy_converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq
def sympify_mpmath(x):
return Expr._from_mpmath(x, x.context.prec)
_sympy_converter[mpnumeric] = sympify_mpmath
def sympify_complex(a):
real, imag = list(map(sympify, (a.real, a.imag)))
return real + S.ImaginaryUnit*imag
_sympy_converter[complex] = sympify_complex
from .power import Pow, integer_nthroot
from .mul import Mul
Mul.identity = One()
from .add import Add
Add.identity = Zero()
def _register_classes():
numbers.Number.register(Number)
numbers.Real.register(Float)
numbers.Rational.register(Rational)
numbers.Integral.register(Integer)
_register_classes()
_illegal = (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity)
|
b8d7b123a0aa05dcbcb69ae0e207d4d29077d8cdfda9746319ae3965befe3790 | """
Adaptive numerical evaluation of SymPy expressions, using mpmath
for mathematical functions.
"""
from __future__ import annotations
from typing import Tuple as tTuple, Optional, Union as tUnion, Callable, List, Dict as tDict, Type, TYPE_CHECKING, \
Any, overload
import math
import mpmath.libmp as libmp
from mpmath import (
make_mpc, make_mpf, mp, mpc, mpf, nsum, quadts, quadosc, workprec)
from mpmath import inf as mpmath_inf
from mpmath.libmp import (from_int, from_man_exp, from_rational, fhalf,
fnan, finf, fninf, fnone, fone, fzero, mpf_abs, mpf_add,
mpf_atan, mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log, mpf_lt,
mpf_mul, mpf_neg, mpf_pi, mpf_pow, mpf_pow_int, mpf_shift, mpf_sin,
mpf_sqrt, normalize, round_nearest, to_int, to_str)
from mpmath.libmp import bitcount as mpmath_bitcount
from mpmath.libmp.backend import MPZ
from mpmath.libmp.libmpc import _infs_nan
from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps
from .sympify import sympify
from .singleton import S
from sympy.external.gmpy import SYMPY_INTS
from sympy.utilities.iterables import is_sequence
from sympy.utilities.lambdify import lambdify
from sympy.utilities.misc import as_int
if TYPE_CHECKING:
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.integrals.integrals import Integral
from sympy.concrete.summations import Sum
from sympy.concrete.products import Product
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.complexes import Abs, re, im
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.trigonometric import atan
from .numbers import Float, Rational, Integer, AlgebraicNumber, Number
LG10 = math.log(10, 2)
rnd = round_nearest
def bitcount(n):
"""Return smallest integer, b, such that |n|/2**b < 1.
"""
return mpmath_bitcount(abs(int(n)))
# Used in a few places as placeholder values to denote exponents and
# precision levels, e.g. of exact numbers. Must be careful to avoid
# passing these to mpmath functions or returning them in final results.
INF = float(mpmath_inf)
MINUS_INF = float(-mpmath_inf)
# ~= 100 digits. Real men set this to INF.
DEFAULT_MAXPREC = 333
class PrecisionExhausted(ArithmeticError):
pass
#----------------------------------------------------------------------------#
# #
# Helper functions for arithmetic and complex parts #
# #
#----------------------------------------------------------------------------#
"""
An mpf value tuple is a tuple of integers (sign, man, exp, bc)
representing a floating-point number: [1, -1][sign]*man*2**exp where
sign is 0 or 1 and bc should correspond to the number of bits used to
represent the mantissa (man) in binary notation, e.g.
"""
MPF_TUP = tTuple[int, int, int, int] # mpf value tuple
"""
Explanation
===========
>>> from sympy.core.evalf import bitcount
>>> sign, man, exp, bc = 0, 5, 1, 3
>>> n = [1, -1][sign]*man*2**exp
>>> n, bitcount(man)
(10, 3)
A temporary result is a tuple (re, im, re_acc, im_acc) where
re and im are nonzero mpf value tuples representing approximate
numbers, or None to denote exact zeros.
re_acc, im_acc are integers denoting log2(e) where e is the estimated
relative accuracy of the respective complex part, but may be anything
if the corresponding complex part is None.
"""
TMP_RES = Any # temporary result, should be some variant of
# tUnion[tTuple[Optional[MPF_TUP], Optional[MPF_TUP],
# Optional[int], Optional[int]],
# 'ComplexInfinity']
# but mypy reports error because it doesn't know as we know
# 1. re and re_acc are either both None or both MPF_TUP
# 2. sometimes the result can't be zoo
# type of the "options" parameter in internal evalf functions
OPT_DICT = tDict[str, Any]
def fastlog(x: Optional[MPF_TUP]) -> tUnion[int, Any]:
"""Fast approximation of log2(x) for an mpf value tuple x.
Explanation
===========
Calculated as exponent + width of mantissa. This is an
approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
value and 2) it is too high by 1 in the case that x is an exact
power of 2. Although this is easy to remedy by testing to see if
the odd mpf mantissa is 1 (indicating that one was dealing with
an exact power of 2) that would decrease the speed and is not
necessary as this is only being used as an approximation for the
number of bits in x. The correct return value could be written as
"x[2] + (x[3] if x[1] != 1 else 0)".
Since mpf tuples always have an odd mantissa, no check is done
to see if the mantissa is a multiple of 2 (in which case the
result would be too large by 1).
Examples
========
>>> from sympy import log
>>> from sympy.core.evalf import fastlog, bitcount
>>> s, m, e = 0, 5, 1
>>> bc = bitcount(m)
>>> n = [1, -1][s]*m*2**e
>>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
(10, 3.3, 4)
"""
if not x or x == fzero:
return MINUS_INF
return x[2] + x[3]
def pure_complex(v: 'Expr', or_real=False) -> tuple['Number', 'Number'] | None:
"""Return a and b if v matches a + I*b where b is not zero and
a and b are Numbers, else None. If `or_real` is True then 0 will
be returned for `b` if `v` is a real number.
Examples
========
>>> from sympy.core.evalf import pure_complex
>>> from sympy import sqrt, I, S
>>> a, b, surd = S(2), S(3), sqrt(2)
>>> pure_complex(a)
>>> pure_complex(a, or_real=True)
(2, 0)
>>> pure_complex(surd)
>>> pure_complex(a + b*I)
(2, 3)
>>> pure_complex(I)
(0, 1)
"""
h, t = v.as_coeff_Add()
if t:
c, i = t.as_coeff_Mul()
if i is S.ImaginaryUnit:
return h, c
elif or_real:
return h, S.Zero
return None
# I don't know what this is, see function scaled_zero below
SCALED_ZERO_TUP = tTuple[List[int], int, int, int]
@overload
def scaled_zero(mag: SCALED_ZERO_TUP, sign=1) -> MPF_TUP:
...
@overload
def scaled_zero(mag: int, sign=1) -> tTuple[SCALED_ZERO_TUP, int]:
...
def scaled_zero(mag: tUnion[SCALED_ZERO_TUP, int], sign=1) -> \
tUnion[MPF_TUP, tTuple[SCALED_ZERO_TUP, int]]:
"""Return an mpf representing a power of two with magnitude ``mag``
and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
remove the sign from within the list that it was initially wrapped
in.
Examples
========
>>> from sympy.core.evalf import scaled_zero
>>> from sympy import Float
>>> z, p = scaled_zero(100)
>>> z, p
(([0], 1, 100, 1), -1)
>>> ok = scaled_zero(z)
>>> ok
(0, 1, 100, 1)
>>> Float(ok)
1.26765060022823e+30
>>> Float(ok, p)
0.e+30
>>> ok, p = scaled_zero(100, -1)
>>> Float(scaled_zero(ok), p)
-0.e+30
"""
if isinstance(mag, tuple) and len(mag) == 4 and iszero(mag, scaled=True):
return (mag[0][0],) + mag[1:]
elif isinstance(mag, SYMPY_INTS):
if sign not in [-1, 1]:
raise ValueError('sign must be +/-1')
rv, p = mpf_shift(fone, mag), -1
s = 0 if sign == 1 else 1
rv = ([s],) + rv[1:]
return rv, p
else:
raise ValueError('scaled zero expects int or scaled_zero tuple.')
def iszero(mpf: tUnion[MPF_TUP, SCALED_ZERO_TUP, None], scaled=False) -> Optional[bool]:
if not scaled:
return not mpf or not mpf[1] and not mpf[-1]
return mpf and isinstance(mpf[0], list) and mpf[1] == mpf[-1] == 1
def complex_accuracy(result: TMP_RES) -> tUnion[int, Any]:
"""
Returns relative accuracy of a complex number with given accuracies
for the real and imaginary parts. The relative accuracy is defined
in the complex norm sense as ||z|+|error|| / |z| where error
is equal to (real absolute error) + (imag absolute error)*i.
The full expression for the (logarithmic) error can be approximated
easily by using the max norm to approximate the complex norm.
In the worst case (re and im equal), this is wrong by a factor
sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
"""
if result is S.ComplexInfinity:
return INF
re, im, re_acc, im_acc = result
if not im:
if not re:
return INF
return re_acc
if not re:
return im_acc
re_size = fastlog(re)
im_size = fastlog(im)
absolute_error = max(re_size - re_acc, im_size - im_acc)
relative_error = absolute_error - max(re_size, im_size)
return -relative_error
def get_abs(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
result = evalf(expr, prec + 2, options)
if result is S.ComplexInfinity:
return finf, None, prec, None
re, im, re_acc, im_acc = result
if not re:
re, re_acc, im, im_acc = im, im_acc, re, re_acc
if im:
if expr.is_number:
abs_expr, _, acc, _ = evalf(abs(N(expr, prec + 2)),
prec + 2, options)
return abs_expr, None, acc, None
else:
if 'subs' in options:
return libmp.mpc_abs((re, im), prec), None, re_acc, None
return abs(expr), None, prec, None
elif re:
return mpf_abs(re), None, re_acc, None
else:
return None, None, None, None
def get_complex_part(expr: 'Expr', no: int, prec: int, options: OPT_DICT) -> TMP_RES:
"""no = 0 for real part, no = 1 for imaginary part"""
workprec = prec
i = 0
while 1:
res = evalf(expr, workprec, options)
if res is S.ComplexInfinity:
return fnan, None, prec, None
value, accuracy = res[no::2]
# XXX is the last one correct? Consider re((1+I)**2).n()
if (not value) or accuracy >= prec or -value[2] > prec:
return value, None, accuracy, None
workprec += max(30, 2**i)
i += 1
def evalf_abs(expr: 'Abs', prec: int, options: OPT_DICT) -> TMP_RES:
return get_abs(expr.args[0], prec, options)
def evalf_re(expr: 're', prec: int, options: OPT_DICT) -> TMP_RES:
return get_complex_part(expr.args[0], 0, prec, options)
def evalf_im(expr: 'im', prec: int, options: OPT_DICT) -> TMP_RES:
return get_complex_part(expr.args[0], 1, prec, options)
def finalize_complex(re: MPF_TUP, im: MPF_TUP, prec: int) -> TMP_RES:
if re == fzero and im == fzero:
raise ValueError("got complex zero with unknown accuracy")
elif re == fzero:
return None, im, None, prec
elif im == fzero:
return re, None, prec, None
size_re = fastlog(re)
size_im = fastlog(im)
if size_re > size_im:
re_acc = prec
im_acc = prec + min(-(size_re - size_im), 0)
else:
im_acc = prec
re_acc = prec + min(-(size_im - size_re), 0)
return re, im, re_acc, im_acc
def chop_parts(value: TMP_RES, prec: int) -> TMP_RES:
"""
Chop off tiny real or complex parts.
"""
if value is S.ComplexInfinity:
return value
re, im, re_acc, im_acc = value
# Method 1: chop based on absolute value
if re and re not in _infs_nan and (fastlog(re) < -prec + 4):
re, re_acc = None, None
if im and im not in _infs_nan and (fastlog(im) < -prec + 4):
im, im_acc = None, None
# Method 2: chop if inaccurate and relatively small
if re and im:
delta = fastlog(re) - fastlog(im)
if re_acc < 2 and (delta - re_acc <= -prec + 4):
re, re_acc = None, None
if im_acc < 2 and (delta - im_acc >= prec - 4):
im, im_acc = None, None
return re, im, re_acc, im_acc
def check_target(expr: 'Expr', result: TMP_RES, prec: int):
a = complex_accuracy(result)
if a < prec:
raise PrecisionExhausted("Failed to distinguish the expression: \n\n%s\n\n"
"from zero. Try simplifying the input, using chop=True, or providing "
"a higher maxn for evalf" % (expr))
def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \
tUnion[TMP_RES, tTuple[int, int]]:
"""
With no = 1, computes ceiling(expr)
With no = -1, computes floor(expr)
Note: this function either gives the exact result or signals failure.
"""
from sympy.functions.elementary.complexes import re, im
# The expression is likely less than 2^30 or so
assumed_size = 30
result = evalf(expr, assumed_size, options)
if result is S.ComplexInfinity:
raise ValueError("Cannot get integer part of Complex Infinity")
ire, iim, ire_acc, iim_acc = result
# We now know the size, so we can calculate how much extra precision
# (if any) is needed to get within the nearest integer
if ire and iim:
gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc)
elif ire:
gap = fastlog(ire) - ire_acc
elif iim:
gap = fastlog(iim) - iim_acc
else:
# ... or maybe the expression was exactly zero
if return_ints:
return 0, 0
else:
return None, None, None, None
margin = 10
if gap >= -margin:
prec = margin + assumed_size + gap
ire, iim, ire_acc, iim_acc = evalf(
expr, prec, options)
else:
prec = assumed_size
# We can now easily find the nearest integer, but to find floor/ceil, we
# must also calculate whether the difference to the nearest integer is
# positive or negative (which may fail if very close).
def calc_part(re_im: 'Expr', nexpr: MPF_TUP):
from .add import Add
_, _, exponent, _ = nexpr
is_int = exponent == 0
nint = int(to_int(nexpr, rnd))
if is_int:
# make sure that we had enough precision to distinguish
# between nint and the re or im part (re_im) of expr that
# was passed to calc_part
ire, iim, ire_acc, iim_acc = evalf(
re_im - nint, 10, options) # don't need much precision
assert not iim
size = -fastlog(ire) + 2 # -ve b/c ire is less than 1
if size > prec:
ire, iim, ire_acc, iim_acc = evalf(
re_im, size, options)
assert not iim
nexpr = ire
nint = int(to_int(nexpr, rnd))
_, _, new_exp, _ = ire
is_int = new_exp == 0
if not is_int:
# if there are subs and they all contain integer re/im parts
# then we can (hopefully) safely substitute them into the
# expression
s = options.get('subs', False)
if s:
doit = True
# use strict=False with as_int because we take
# 2.0 == 2
for v in s.values():
try:
as_int(v, strict=False)
except ValueError:
try:
[as_int(i, strict=False) for i in v.as_real_imag()]
continue
except (ValueError, AttributeError):
doit = False
break
if doit:
re_im = re_im.subs(s)
re_im = Add(re_im, -nint, evaluate=False)
x, _, x_acc, _ = evalf(re_im, 10, options)
try:
check_target(re_im, (x, None, x_acc, None), 3)
except PrecisionExhausted:
if not re_im.equals(0):
raise PrecisionExhausted
x = fzero
nint += int(no*(mpf_cmp(x or fzero, fzero) == no))
nint = from_int(nint)
return nint, INF
re_, im_, re_acc, im_acc = None, None, None, None
if ire:
re_, re_acc = calc_part(re(expr, evaluate=False), ire)
if iim:
im_, im_acc = calc_part(im(expr, evaluate=False), iim)
if return_ints:
return int(to_int(re_ or fzero)), int(to_int(im_ or fzero))
return re_, im_, re_acc, im_acc
def evalf_ceiling(expr: 'ceiling', prec: int, options: OPT_DICT) -> TMP_RES:
return get_integer_part(expr.args[0], 1, options)
def evalf_floor(expr: 'floor', prec: int, options: OPT_DICT) -> TMP_RES:
return get_integer_part(expr.args[0], -1, options)
def evalf_float(expr: 'Float', prec: int, options: OPT_DICT) -> TMP_RES:
return expr._mpf_, None, prec, None
def evalf_rational(expr: 'Rational', prec: int, options: OPT_DICT) -> TMP_RES:
return from_rational(expr.p, expr.q, prec), None, prec, None
def evalf_integer(expr: 'Integer', prec: int, options: OPT_DICT) -> TMP_RES:
return from_int(expr.p, prec), None, prec, None
#----------------------------------------------------------------------------#
# #
# Arithmetic operations #
# #
#----------------------------------------------------------------------------#
def add_terms(terms: list, prec: int, target_prec: int) -> \
tTuple[tUnion[MPF_TUP, SCALED_ZERO_TUP, None], Optional[int]]:
"""
Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
Returns
=======
- None, None if there are no non-zero terms;
- terms[0] if there is only 1 term;
- scaled_zero if the sum of the terms produces a zero by cancellation
e.g. mpfs representing 1 and -1 would produce a scaled zero which need
special handling since they are not actually zero and they are purposely
malformed to ensure that they cannot be used in anything but accuracy
calculations;
- a tuple that is scaled to target_prec that corresponds to the
sum of the terms.
The returned mpf tuple will be normalized to target_prec; the input
prec is used to define the working precision.
XXX explain why this is needed and why one cannot just loop using mpf_add
"""
terms = [t for t in terms if not iszero(t[0])]
if not terms:
return None, None
elif len(terms) == 1:
return terms[0]
# see if any argument is NaN or oo and thus warrants a special return
special = []
from .numbers import Float
for t in terms:
arg = Float._new(t[0], 1)
if arg is S.NaN or arg.is_infinite:
special.append(arg)
if special:
from .add import Add
rv = evalf(Add(*special), prec + 4, {})
return rv[0], rv[2]
working_prec = 2*prec
sum_man, sum_exp = 0, 0
absolute_err: List[int] = []
for x, accuracy in terms:
sign, man, exp, bc = x
if sign:
man = -man
absolute_err.append(bc + exp - accuracy)
delta = exp - sum_exp
if exp >= sum_exp:
# x much larger than existing sum?
# first: quick test
if ((delta > working_prec) and
((not sum_man) or
delta - bitcount(abs(sum_man)) > working_prec)):
sum_man = man
sum_exp = exp
else:
sum_man += (man << delta)
else:
delta = -delta
# x much smaller than existing sum?
if delta - bc > working_prec:
if not sum_man:
sum_man, sum_exp = man, exp
else:
sum_man = (sum_man << delta) + man
sum_exp = exp
absolute_error = max(absolute_err)
if not sum_man:
return scaled_zero(absolute_error)
if sum_man < 0:
sum_sign = 1
sum_man = -sum_man
else:
sum_sign = 0
sum_bc = bitcount(sum_man)
sum_accuracy = sum_exp + sum_bc - absolute_error
r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec,
rnd), sum_accuracy
return r
def evalf_add(v: 'Add', prec: int, options: OPT_DICT) -> TMP_RES:
res = pure_complex(v)
if res:
h, c = res
re, _, re_acc, _ = evalf(h, prec, options)
im, _, im_acc, _ = evalf(c, prec, options)
return re, im, re_acc, im_acc
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
i = 0
target_prec = prec
while 1:
options['maxprec'] = min(oldmaxprec, 2*prec)
terms = [evalf(arg, prec + 10, options) for arg in v.args]
n = terms.count(S.ComplexInfinity)
if n >= 2:
return fnan, None, prec, None
re, re_acc = add_terms(
[a[0::2] for a in terms if isinstance(a, tuple) and a[0]], prec, target_prec)
im, im_acc = add_terms(
[a[1::2] for a in terms if isinstance(a, tuple) and a[1]], prec, target_prec)
if n == 1:
if re in (finf, fninf, fnan) or im in (finf, fninf, fnan):
return fnan, None, prec, None
return S.ComplexInfinity
acc = complex_accuracy((re, im, re_acc, im_acc))
if acc >= target_prec:
if options.get('verbose'):
print("ADD: wanted", target_prec, "accurate bits, got", re_acc, im_acc)
break
else:
if (prec - target_prec) > options['maxprec']:
break
prec = prec + max(10 + 2**i, target_prec - acc)
i += 1
if options.get('verbose'):
print("ADD: restarting with prec", prec)
options['maxprec'] = oldmaxprec
if iszero(re, scaled=True):
re = scaled_zero(re)
if iszero(im, scaled=True):
im = scaled_zero(im)
return re, im, re_acc, im_acc
def evalf_mul(v: 'Mul', prec: int, options: OPT_DICT) -> TMP_RES:
res = pure_complex(v)
if res:
# the only pure complex that is a mul is h*I
_, h = res
im, _, im_acc, _ = evalf(h, prec, options)
return None, im, None, im_acc
args = list(v.args)
# see if any argument is NaN or oo and thus warrants a special return
has_zero = False
special = []
from .numbers import Float
for arg in args:
result = evalf(arg, prec, options)
if result is S.ComplexInfinity:
special.append(result)
continue
if result[0] is None:
if result[1] is None:
has_zero = True
continue
num = Float._new(result[0], 1)
if num is S.NaN:
return fnan, None, prec, None
if num.is_infinite:
special.append(num)
if special:
if has_zero:
return fnan, None, prec, None
from .mul import Mul
return evalf(Mul(*special), prec + 4, {})
if has_zero:
return None, None, None, None
# With guard digits, multiplication in the real case does not destroy
# accuracy. This is also true in the complex case when considering the
# total accuracy; however accuracy for the real or imaginary parts
# separately may be lower.
acc = prec
# XXX: big overestimate
working_prec = prec + len(args) + 5
# Empty product is 1
start = man, exp, bc = MPZ(1), 0, 1
# First, we multiply all pure real or pure imaginary numbers.
# direction tells us that the result should be multiplied by
# I**direction; all other numbers get put into complex_factors
# to be multiplied out after the first phase.
last = len(args)
direction = 0
args.append(S.One)
complex_factors = []
for i, arg in enumerate(args):
if i != last and pure_complex(arg):
args[-1] = (args[-1]*arg).expand()
continue
elif i == last and arg is S.One:
continue
re, im, re_acc, im_acc = evalf(arg, working_prec, options)
if re and im:
complex_factors.append((re, im, re_acc, im_acc))
continue
elif re:
(s, m, e, b), w_acc = re, re_acc
elif im:
(s, m, e, b), w_acc = im, im_acc
direction += 1
else:
return None, None, None, None
direction += 2*s
man *= m
exp += e
bc += b
while bc > 3*working_prec:
man >>= working_prec
exp += working_prec
bc -= working_prec
acc = min(acc, w_acc)
sign = (direction & 2) >> 1
if not complex_factors:
v = normalize(sign, man, exp, bitcount(man), prec, rnd)
# multiply by i
if direction & 1:
return None, v, None, acc
else:
return v, None, acc, None
else:
# initialize with the first term
if (man, exp, bc) != start:
# there was a real part; give it an imaginary part
re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0)
i0 = 0
else:
# there is no real part to start (other than the starting 1)
wre, wim, wre_acc, wim_acc = complex_factors[0]
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
re = wre
im = wim
i0 = 1
for wre, wim, wre_acc, wim_acc in complex_factors[i0:]:
# acc is the overall accuracy of the product; we aren't
# computing exact accuracies of the product.
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
use_prec = working_prec
A = mpf_mul(re, wre, use_prec)
B = mpf_mul(mpf_neg(im), wim, use_prec)
C = mpf_mul(re, wim, use_prec)
D = mpf_mul(im, wre, use_prec)
re = mpf_add(A, B, use_prec)
im = mpf_add(C, D, use_prec)
if options.get('verbose'):
print("MUL: wanted", prec, "accurate bits, got", acc)
# multiply by I
if direction & 1:
re, im = mpf_neg(im), re
return re, im, acc, acc
def evalf_pow(v: 'Pow', prec: int, options) -> TMP_RES:
target_prec = prec
base, exp = v.args
# We handle x**n separately. This has two purposes: 1) it is much
# faster, because we avoid calling evalf on the exponent, and 2) it
# allows better handling of real/imaginary parts that are exactly zero
if exp.is_Integer:
p: int = exp.p # type: ignore
# Exact
if not p:
return fone, None, prec, None
# Exponentiation by p magnifies relative error by |p|, so the
# base must be evaluated with increased precision if p is large
prec += int(math.log(abs(p), 2))
result = evalf(base, prec + 5, options)
if result is S.ComplexInfinity:
if p < 0:
return None, None, None, None
return result
re, im, re_acc, im_acc = result
# Real to integer power
if re and not im:
return mpf_pow_int(re, p, target_prec), None, target_prec, None
# (x*I)**n = I**n * x**n
if im and not re:
z = mpf_pow_int(im, p, target_prec)
case = p % 4
if case == 0:
return z, None, target_prec, None
if case == 1:
return None, z, None, target_prec
if case == 2:
return mpf_neg(z), None, target_prec, None
if case == 3:
return None, mpf_neg(z), None, target_prec
# Zero raised to an integer power
if not re:
if p < 0:
return S.ComplexInfinity
return None, None, None, None
# General complex number to arbitrary integer power
re, im = libmp.mpc_pow_int((re, im), p, prec)
# Assumes full accuracy in input
return finalize_complex(re, im, target_prec)
result = evalf(base, prec + 5, options)
if result is S.ComplexInfinity:
if exp.is_Rational:
if exp < 0:
return None, None, None, None
return result
raise NotImplementedError
# Pure square root
if exp is S.Half:
xre, xim, _, _ = result
# General complex square root
if xim:
re, im = libmp.mpc_sqrt((xre or fzero, xim), prec)
return finalize_complex(re, im, prec)
if not xre:
return None, None, None, None
# Square root of a negative real number
if mpf_lt(xre, fzero):
return None, mpf_sqrt(mpf_neg(xre), prec), None, prec
# Positive square root
return mpf_sqrt(xre, prec), None, prec, None
# We first evaluate the exponent to find its magnitude
# This determines the working precision that must be used
prec += 10
result = evalf(exp, prec, options)
if result is S.ComplexInfinity:
return fnan, None, prec, None
yre, yim, _, _ = result
# Special cases: x**0
if not (yre or yim):
return fone, None, prec, None
ysize = fastlog(yre)
# Restart if too big
# XXX: prec + ysize might exceed maxprec
if ysize > 5:
prec += ysize
yre, yim, _, _ = evalf(exp, prec, options)
# Pure exponential function; no need to evalf the base
if base is S.Exp1:
if yim:
re, im = libmp.mpc_exp((yre or fzero, yim), prec)
return finalize_complex(re, im, target_prec)
return mpf_exp(yre, target_prec), None, target_prec, None
xre, xim, _, _ = evalf(base, prec + 5, options)
# 0**y
if not (xre or xim):
if yim:
return fnan, None, prec, None
if yre[0] == 1: # y < 0
return S.ComplexInfinity
return None, None, None, None
# (real ** complex) or (complex ** complex)
if yim:
re, im = libmp.mpc_pow(
(xre or fzero, xim or fzero), (yre or fzero, yim),
target_prec)
return finalize_complex(re, im, target_prec)
# complex ** real
if xim:
re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec)
return finalize_complex(re, im, target_prec)
# negative ** real
elif mpf_lt(xre, fzero):
re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec)
return finalize_complex(re, im, target_prec)
# positive ** real
else:
return mpf_pow(xre, yre, target_prec), None, target_prec, None
#----------------------------------------------------------------------------#
# #
# Special functions #
# #
#----------------------------------------------------------------------------#
def evalf_exp(expr: 'exp', prec: int, options: OPT_DICT) -> TMP_RES:
from .power import Pow
return evalf_pow(Pow(S.Exp1, expr.exp, evaluate=False), prec, options)
def evalf_trig(v: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
"""
This function handles sin and cos of complex arguments.
TODO: should also handle tan of complex arguments.
"""
from sympy.functions.elementary.trigonometric import cos, sin
if isinstance(v, cos):
func = mpf_cos
elif isinstance(v, sin):
func = mpf_sin
else:
raise NotImplementedError
arg = v.args[0]
# 20 extra bits is possibly overkill. It does make the need
# to restart very unlikely
xprec = prec + 20
re, im, re_acc, im_acc = evalf(arg, xprec, options)
if im:
if 'subs' in options:
v = v.subs(options['subs'])
return evalf(v._eval_evalf(prec), prec, options)
if not re:
if isinstance(v, cos):
return fone, None, prec, None
elif isinstance(v, sin):
return None, None, None, None
else:
raise NotImplementedError
# For trigonometric functions, we are interested in the
# fixed-point (absolute) accuracy of the argument.
xsize = fastlog(re)
# Magnitude <= 1.0. OK to compute directly, because there is no
# danger of hitting the first root of cos (with sin, magnitude
# <= 2.0 would actually be ok)
if xsize < 1:
return func(re, prec, rnd), None, prec, None
# Very large
if xsize >= 10:
xprec = prec + xsize
re, im, re_acc, im_acc = evalf(arg, xprec, options)
# Need to repeat in case the argument is very close to a
# multiple of pi (or pi/2), hitting close to a root
while 1:
y = func(re, prec, rnd)
ysize = fastlog(y)
gap = -ysize
accuracy = (xprec - xsize) - gap
if accuracy < prec:
if options.get('verbose'):
print("SIN/COS", accuracy, "wanted", prec, "gap", gap)
print(to_str(y, 10))
if xprec > options.get('maxprec', DEFAULT_MAXPREC):
return y, None, accuracy, None
xprec += gap
re, im, re_acc, im_acc = evalf(arg, xprec, options)
continue
else:
return y, None, prec, None
def evalf_log(expr: 'log', prec: int, options: OPT_DICT) -> TMP_RES:
if len(expr.args)>1:
expr = expr.doit()
return evalf(expr, prec, options)
arg = expr.args[0]
workprec = prec + 10
result = evalf(arg, workprec, options)
if result is S.ComplexInfinity:
return result
xre, xim, xacc, _ = result
# evalf can return NoneTypes if chop=True
# issue 18516, 19623
if xre is xim is None:
# Dear reviewer, I do not know what -inf is;
# it looks to be (1, 0, -789, -3)
# but I'm not sure in general,
# so we just let mpmath figure
# it out by taking log of 0 directly.
# It would be better to return -inf instead.
xre = fzero
if xim:
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import log
# XXX: use get_abs etc instead
re = evalf_log(
log(Abs(arg, evaluate=False), evaluate=False), prec, options)
im = mpf_atan2(xim, xre or fzero, prec)
return re[0], im, re[2], prec
imaginary_term = (mpf_cmp(xre, fzero) < 0)
re = mpf_log(mpf_abs(xre), prec, rnd)
size = fastlog(re)
if prec - size > workprec and re != fzero:
from .add import Add
# We actually need to compute 1+x accurately, not x
add = Add(S.NegativeOne, arg, evaluate=False)
xre, xim, _, _ = evalf_add(add, prec, options)
prec2 = workprec - fastlog(xre)
# xre is now x - 1 so we add 1 back here to calculate x
re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd)
re_acc = prec
if imaginary_term:
return re, mpf_pi(prec), re_acc, prec
else:
return re, None, re_acc, None
def evalf_atan(v: 'atan', prec: int, options: OPT_DICT) -> TMP_RES:
arg = v.args[0]
xre, xim, reacc, imacc = evalf(arg, prec + 5, options)
if xre is xim is None:
return (None,)*4
if xim:
raise NotImplementedError
return mpf_atan(xre, prec, rnd), None, prec, None
def evalf_subs(prec: int, subs: dict) -> dict:
""" Change all Float entries in `subs` to have precision prec. """
newsubs = {}
for a, b in subs.items():
b = S(b)
if b.is_Float:
b = b._eval_evalf(prec)
newsubs[a] = b
return newsubs
def evalf_piecewise(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
from .numbers import Float, Integer
if 'subs' in options:
expr = expr.subs(evalf_subs(prec, options['subs']))
newopts = options.copy()
del newopts['subs']
if hasattr(expr, 'func'):
return evalf(expr, prec, newopts)
if isinstance(expr, float):
return evalf(Float(expr), prec, newopts)
if isinstance(expr, int):
return evalf(Integer(expr), prec, newopts)
# We still have undefined symbols
raise NotImplementedError
def evalf_alg_num(a: 'AlgebraicNumber', prec: int, options: OPT_DICT) -> TMP_RES:
return evalf(a.to_root(), prec, options)
#----------------------------------------------------------------------------#
# #
# High-level operations #
# #
#----------------------------------------------------------------------------#
def as_mpmath(x: Any, prec: int, options: OPT_DICT) -> tUnion[mpc, mpf]:
from .numbers import Infinity, NegativeInfinity, Zero
x = sympify(x)
if isinstance(x, Zero) or x == 0:
return mpf(0)
if isinstance(x, Infinity):
return mpf('inf')
if isinstance(x, NegativeInfinity):
return mpf('-inf')
# XXX
result = evalf(x, prec, options)
return quad_to_mpmath(result)
def do_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
func = expr.args[0]
x, xlow, xhigh = expr.args[1]
if xlow == xhigh:
xlow = xhigh = 0
elif x not in func.free_symbols:
# only the difference in limits matters in this case
# so if there is a symbol in common that will cancel
# out when taking the difference, then use that
# difference
if xhigh.free_symbols & xlow.free_symbols:
diff = xhigh - xlow
if diff.is_number:
xlow, xhigh = 0, diff
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
options['maxprec'] = min(oldmaxprec, 2*prec)
with workprec(prec + 5):
xlow = as_mpmath(xlow, prec + 15, options)
xhigh = as_mpmath(xhigh, prec + 15, options)
# Integration is like summation, and we can phone home from
# the integrand function to update accuracy summation style
# Note that this accuracy is inaccurate, since it fails
# to account for the variable quadrature weights,
# but it is better than nothing
from sympy.functions.elementary.trigonometric import cos, sin
from .symbol import Wild
have_part = [False, False]
max_real_term: tUnion[float, int] = MINUS_INF
max_imag_term: tUnion[float, int] = MINUS_INF
def f(t: 'Expr') -> tUnion[mpc, mpf]:
nonlocal max_real_term, max_imag_term
re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}})
have_part[0] = re or have_part[0]
have_part[1] = im or have_part[1]
max_real_term = max(max_real_term, fastlog(re))
max_imag_term = max(max_imag_term, fastlog(im))
if im:
return mpc(re or fzero, im)
return mpf(re or fzero)
if options.get('quad') == 'osc':
A = Wild('A', exclude=[x])
B = Wild('B', exclude=[x])
D = Wild('D')
m = func.match(cos(A*x + B)*D)
if not m:
m = func.match(sin(A*x + B)*D)
if not m:
raise ValueError("An integrand of the form sin(A*x+B)*f(x) "
"or cos(A*x+B)*f(x) is required for oscillatory quadrature")
period = as_mpmath(2*S.Pi/m[A], prec + 15, options)
result = quadosc(f, [xlow, xhigh], period=period)
# XXX: quadosc does not do error detection yet
quadrature_error = MINUS_INF
else:
result, quadrature_err = quadts(f, [xlow, xhigh], error=1)
quadrature_error = fastlog(quadrature_err._mpf_)
options['maxprec'] = oldmaxprec
if have_part[0]:
re: Optional[MPF_TUP] = result.real._mpf_
re_acc: Optional[int]
if re == fzero:
re_s, re_acc = scaled_zero(int(-max(prec, max_real_term, quadrature_error)))
re = scaled_zero(re_s) # handled ok in evalf_integral
else:
re_acc = int(-max(max_real_term - fastlog(re) - prec, quadrature_error))
else:
re, re_acc = None, None
if have_part[1]:
im: Optional[MPF_TUP] = result.imag._mpf_
im_acc: Optional[int]
if im == fzero:
im_s, im_acc = scaled_zero(int(-max(prec, max_imag_term, quadrature_error)))
im = scaled_zero(im_s) # handled ok in evalf_integral
else:
im_acc = int(-max(max_imag_term - fastlog(im) - prec, quadrature_error))
else:
im, im_acc = None, None
result = re, im, re_acc, im_acc
return result
def evalf_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
workprec = prec
i = 0
maxprec = options.get('maxprec', INF)
while 1:
result = do_integral(expr, workprec, options)
accuracy = complex_accuracy(result)
if accuracy >= prec: # achieved desired precision
break
if workprec >= maxprec: # can't increase accuracy any more
break
if accuracy == -1:
# maybe the answer really is zero and maybe we just haven't increased
# the precision enough. So increase by doubling to not take too long
# to get to maxprec.
workprec *= 2
else:
workprec += max(prec, 2**i)
workprec = min(workprec, maxprec)
i += 1
return result
def check_convergence(numer: 'Expr', denom: 'Expr', n: 'Symbol') -> tTuple[int, Any, Any]:
"""
Returns
=======
(h, g, p) where
-- h is:
> 0 for convergence of rate 1/factorial(n)**h
< 0 for divergence of rate factorial(n)**(-h)
= 0 for geometric or polynomial convergence or divergence
-- abs(g) is:
> 1 for geometric convergence of rate 1/h**n
< 1 for geometric divergence of rate h**n
= 1 for polynomial convergence or divergence
(g < 0 indicates an alternating series)
-- p is:
> 1 for polynomial convergence of rate 1/n**h
<= 1 for polynomial divergence of rate n**(-h)
"""
from sympy.polys.polytools import Poly
npol = Poly(numer, n)
dpol = Poly(denom, n)
p = npol.degree()
q = dpol.degree()
rate = q - p
if rate:
return rate, None, None
constant = dpol.LC() / npol.LC()
if abs(constant) != 1:
return rate, constant, None
if npol.degree() == dpol.degree() == 0:
return rate, constant, 0
pc = npol.all_coeffs()[1]
qc = dpol.all_coeffs()[1]
return rate, constant, (qc - pc)/dpol.LC()
def hypsum(expr: 'Expr', n: 'Symbol', start: int, prec: int) -> mpf:
"""
Sum a rapidly convergent infinite hypergeometric series with
given general term, e.g. e = hypsum(1/factorial(n), n). The
quotient between successive terms must be a quotient of integer
polynomials.
"""
from .numbers import Float
from sympy.simplify.simplify import hypersimp
if prec == float('inf'):
raise NotImplementedError('does not support inf prec')
if start:
expr = expr.subs(n, n + start)
hs = hypersimp(expr, n)
if hs is None:
raise NotImplementedError("a hypergeometric series is required")
num, den = hs.as_numer_denom()
func1 = lambdify(n, num)
func2 = lambdify(n, den)
h, g, p = check_convergence(num, den, n)
if h < 0:
raise ValueError("Sum diverges like (n!)^%i" % (-h))
term = expr.subs(n, 0)
if not term.is_Rational:
raise NotImplementedError("Non rational term functionality is not implemented.")
# Direct summation if geometric or faster
if h > 0 or (h == 0 and abs(g) > 1):
term = (MPZ(term.p) << prec) // term.q
s = term
k = 1
while abs(term) > 5:
term *= MPZ(func1(k - 1))
term //= MPZ(func2(k - 1))
s += term
k += 1
return from_man_exp(s, -prec)
else:
alt = g < 0
if abs(g) < 1:
raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
if p < 1 or (p == 1 and not alt):
raise ValueError("Sum diverges like n^%i" % (-p))
# We have polynomial convergence: use Richardson extrapolation
vold = None
ndig = prec_to_dps(prec)
while True:
# Need to use at least quad precision because a lot of cancellation
# might occur in the extrapolation process; we check the answer to
# make sure that the desired precision has been reached, too.
prec2 = 4*prec
term0 = (MPZ(term.p) << prec2) // term.q
def summand(k, _term=[term0]):
if k:
k = int(k)
_term[0] *= MPZ(func1(k - 1))
_term[0] //= MPZ(func2(k - 1))
return make_mpf(from_man_exp(_term[0], -prec2))
with workprec(prec):
v = nsum(summand, [0, mpmath_inf], method='richardson')
vf = Float(v, ndig)
if vold is not None and vold == vf:
break
prec += prec # double precision each time
vold = vf
return v._mpf_
def evalf_prod(expr: 'Product', prec: int, options: OPT_DICT) -> TMP_RES:
if all((l[1] - l[2]).is_Integer for l in expr.limits):
result = evalf(expr.doit(), prec=prec, options=options)
else:
from sympy.concrete.summations import Sum
result = evalf(expr.rewrite(Sum), prec=prec, options=options)
return result
def evalf_sum(expr: 'Sum', prec: int, options: OPT_DICT) -> TMP_RES:
from .numbers import Float
if 'subs' in options:
expr = expr.subs(options['subs'])
func = expr.function
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
if func.is_zero:
return None, None, prec, None
prec2 = prec + 10
try:
n, a, b = limits[0]
if b is not S.Infinity or a is S.NegativeInfinity or a != int(a):
raise NotImplementedError
# Use fast hypergeometric summation if possible
v = hypsum(func, n, int(a), prec2)
delta = prec - fastlog(v)
if fastlog(v) < -10:
v = hypsum(func, n, int(a), delta)
return v, None, min(prec, delta), None
except NotImplementedError:
# Euler-Maclaurin summation for general series
eps = Float(2.0)**(-prec)
for i in range(1, 5):
m = n = 2**i * prec
s, err = expr.euler_maclaurin(m=m, n=n, eps=eps,
eval_integral=False)
err = err.evalf()
if err is S.NaN:
raise NotImplementedError
if err <= eps:
break
err = fastlog(evalf(abs(err), 20, options)[0])
re, im, re_acc, im_acc = evalf(s, prec2, options)
if re_acc is None:
re_acc = -err
if im_acc is None:
im_acc = -err
return re, im, re_acc, im_acc
#----------------------------------------------------------------------------#
# #
# Symbolic interface #
# #
#----------------------------------------------------------------------------#
def evalf_symbol(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
val = options['subs'][x]
if isinstance(val, mpf):
if not val:
return None, None, None, None
return val._mpf_, None, prec, None
else:
if '_cache' not in options:
options['_cache'] = {}
cache = options['_cache']
cached, cached_prec = cache.get(x, (None, MINUS_INF))
if cached_prec >= prec:
return cached
v = evalf(sympify(val), prec, options)
cache[x] = (v, prec)
return v
evalf_table: tDict[Type['Expr'], Callable[['Expr', int, OPT_DICT], TMP_RES]] = {}
def _create_evalf_table():
global evalf_table
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from .add import Add
from .mul import Mul
from .numbers import Exp1, Float, Half, ImaginaryUnit, Integer, NaN, NegativeOne, One, Pi, Rational, \
Zero, ComplexInfinity, AlgebraicNumber
from .power import Pow
from .symbol import Dummy, Symbol
from sympy.functions.elementary.complexes import Abs, im, re
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import atan, cos, sin
from sympy.integrals.integrals import Integral
evalf_table = {
Symbol: evalf_symbol,
Dummy: evalf_symbol,
Float: evalf_float,
Rational: evalf_rational,
Integer: evalf_integer,
Zero: lambda x, prec, options: (None, None, prec, None),
One: lambda x, prec, options: (fone, None, prec, None),
Half: lambda x, prec, options: (fhalf, None, prec, None),
Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None),
Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None),
ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec),
NegativeOne: lambda x, prec, options: (fnone, None, prec, None),
ComplexInfinity: lambda x, prec, options: S.ComplexInfinity,
NaN: lambda x, prec, options: (fnan, None, prec, None),
exp: evalf_exp,
cos: evalf_trig,
sin: evalf_trig,
Add: evalf_add,
Mul: evalf_mul,
Pow: evalf_pow,
log: evalf_log,
atan: evalf_atan,
Abs: evalf_abs,
re: evalf_re,
im: evalf_im,
floor: evalf_floor,
ceiling: evalf_ceiling,
Integral: evalf_integral,
Sum: evalf_sum,
Product: evalf_prod,
Piecewise: evalf_piecewise,
AlgebraicNumber: evalf_alg_num,
}
def evalf(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
"""
Evaluate the ``Expr`` instance, ``x``
to a binary precision of ``prec``. This
function is supposed to be used internally.
Parameters
==========
x : Expr
The formula to evaluate to a float.
prec : int
The binary precision that the output should have.
options : dict
A dictionary with the same entries as
``EvalfMixin.evalf`` and in addition,
``maxprec`` which is the maximum working precision.
Returns
=======
An optional tuple, ``(re, im, re_acc, im_acc)``
which are the real, imaginary, real accuracy
and imaginary accuracy respectively. ``re`` is
an mpf value tuple and so is ``im``. ``re_acc``
and ``im_acc`` are ints.
NB: all these return values can be ``None``.
If all values are ``None``, then that represents 0.
Note that 0 is also represented as ``fzero = (0, 0, 0, 0)``.
"""
from sympy.functions.elementary.complexes import re as re_, im as im_
try:
rf = evalf_table[type(x)]
r = rf(x, prec, options)
except KeyError:
# Fall back to ordinary evalf if possible
if 'subs' in options:
x = x.subs(evalf_subs(prec, options['subs']))
xe = x._eval_evalf(prec)
if xe is None:
raise NotImplementedError
as_real_imag = getattr(xe, "as_real_imag", None)
if as_real_imag is None:
raise NotImplementedError # e.g. FiniteSet(-1.0, 1.0).evalf()
re, im = as_real_imag()
if re.has(re_) or im.has(im_):
raise NotImplementedError
if re == 0:
re = None
reprec = None
elif re.is_number:
re = re._to_mpmath(prec, allow_ints=False)._mpf_
reprec = prec
else:
raise NotImplementedError
if im == 0:
im = None
imprec = None
elif im.is_number:
im = im._to_mpmath(prec, allow_ints=False)._mpf_
imprec = prec
else:
raise NotImplementedError
r = re, im, reprec, imprec
if options.get("verbose"):
print("### input", x)
print("### output", to_str(r[0] or fzero, 50) if isinstance(r, tuple) else r)
print("### raw", r) # r[0], r[2]
print()
chop = options.get('chop', False)
if chop:
if chop is True:
chop_prec = prec
else:
# convert (approximately) from given tolerance;
# the formula here will will make 1e-i rounds to 0 for
# i in the range +/-27 while 2e-i will not be chopped
chop_prec = int(round(-3.321*math.log10(chop) + 2.5))
if chop_prec == 3:
chop_prec -= 1
r = chop_parts(r, chop_prec)
if options.get("strict"):
check_target(x, r, prec)
return r
def quad_to_mpmath(q):
"""Turn the quad returned by ``evalf`` into an ``mpf`` or ``mpc``. """
if q is S.ComplexInfinity:
raise NotImplementedError
re, im, _, _ = q
if im:
if not re:
re = fzero
return make_mpc((re, im))
elif re:
return make_mpf(re)
else:
return make_mpf(fzero)
class EvalfMixin:
"""Mixin class adding evalf capability."""
__slots__ = () # type: tTuple[str, ...]
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
"""
Evaluate the given formula to an accuracy of *n* digits.
Parameters
==========
subs : dict, optional
Substitute numerical values for symbols, e.g.
``subs={x:3, y:1+pi}``. The substitutions must be given as a
dictionary.
maxn : int, optional
Allow a maximum temporary working precision of maxn digits.
chop : bool or number, optional
Specifies how to replace tiny real or imaginary parts in
subresults by exact zeros.
When ``True`` the chop value defaults to standard precision.
Otherwise the chop value is used to determine the
magnitude of "small" for purposes of chopping.
>>> from sympy import N
>>> x = 1e-4
>>> N(x, chop=True)
0.000100000000000000
>>> N(x, chop=1e-5)
0.000100000000000000
>>> N(x, chop=1e-4)
0
strict : bool, optional
Raise ``PrecisionExhausted`` if any subresult fails to
evaluate to full accuracy, given the available maxprec.
quad : str, optional
Choose algorithm for numerical quadrature. By default,
tanh-sinh quadrature is used. For oscillatory
integrals on an infinite interval, try ``quad='osc'``.
verbose : bool, optional
Print debug information.
Notes
=====
When Floats are naively substituted into an expression,
precision errors may adversely affect the result. For example,
adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is
then subtracted, the result will be 0.
That is exactly what happens in the following:
>>> from sympy.abc import x, y, z
>>> values = {x: 1e16, y: 1, z: 1e16}
>>> (x + y - z).subs(values)
0
Using the subs argument for evalf is the accurate way to
evaluate such an expression:
>>> (x + y - z).evalf(subs=values)
1.00000000000000
"""
from .numbers import Float, Number
n = n if n is not None else 15
if subs and is_sequence(subs):
raise TypeError('subs must be given as a dictionary')
# for sake of sage that doesn't like evalf(1)
if n == 1 and isinstance(self, Number):
from .expr import _mag
rv = self.evalf(2, subs, maxn, chop, strict, quad, verbose)
m = _mag(rv)
rv = rv.round(1 - m)
return rv
if not evalf_table:
_create_evalf_table()
prec = dps_to_prec(n)
options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop,
'strict': strict, 'verbose': verbose}
if subs is not None:
options['subs'] = subs
if quad is not None:
options['quad'] = quad
try:
result = evalf(self, prec + 4, options)
except NotImplementedError:
# Fall back to the ordinary evalf
if hasattr(self, 'subs') and subs is not None: # issue 20291
v = self.subs(subs)._eval_evalf(prec)
else:
v = self._eval_evalf(prec)
if v is None:
return self
elif not v.is_number:
return v
try:
# If the result is numerical, normalize it
result = evalf(v, prec, options)
except NotImplementedError:
# Probably contains symbols or unknown functions
return v
if result is S.ComplexInfinity:
return result
re, im, re_acc, im_acc = result
if re is S.NaN or im is S.NaN:
return S.NaN
if re:
p = max(min(prec, re_acc), 1)
re = Float._new(re, p)
else:
re = S.Zero
if im:
p = max(min(prec, im_acc), 1)
im = Float._new(im, p)
return re + im*S.ImaginaryUnit
else:
return re
n = evalf
def _evalf(self, prec):
"""Helper for evalf. Does the same thing but takes binary precision"""
r = self._eval_evalf(prec)
if r is None:
r = self
return r
def _eval_evalf(self, prec):
return
def _to_mpmath(self, prec, allow_ints=True):
# mpmath functions accept ints as input
errmsg = "cannot convert to mpmath number"
if allow_ints and self.is_Integer:
return self.p
if hasattr(self, '_as_mpf_val'):
return make_mpf(self._as_mpf_val(prec))
try:
result = evalf(self, prec, {})
return quad_to_mpmath(result)
except NotImplementedError:
v = self._eval_evalf(prec)
if v is None:
raise ValueError(errmsg)
if v.is_Float:
return make_mpf(v._mpf_)
# Number + Number*I is also fine
re, im = v.as_real_imag()
if allow_ints and re.is_Integer:
re = from_int(re.p)
elif re.is_Float:
re = re._mpf_
else:
raise ValueError(errmsg)
if allow_ints and im.is_Integer:
im = from_int(im.p)
elif im.is_Float:
im = im._mpf_
else:
raise ValueError(errmsg)
return make_mpc((re, im))
def N(x, n=15, **options):
r"""
Calls x.evalf(n, \*\*options).
Explanations
============
Both .n() and N() are equivalent to .evalf(); use the one that you like better.
See also the docstring of .evalf() for information on the options.
Examples
========
>>> from sympy import Sum, oo, N
>>> from sympy.abc import k
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(_, 4)
1.291
"""
# by using rational=True, any evaluation of a string
# will be done using exact values for the Floats
return sympify(x, rational=True).evalf(n, **options)
def _evalf_with_bounded_error(x: 'Expr', eps: 'Expr' = None, m: int = 0,
options: OPT_DICT = None) -> TMP_RES:
"""
Evaluate *x* to within a bounded absolute error.
Parameters
==========
x : Expr
The quantity to be evaluated.
eps : Expr, None, optional (default=None)
Positive real upper bound on the acceptable error.
m : int, optional (default=0)
If *eps* is None, then use 2**(-m) as the upper bound on the error.
options: OPT_DICT
As in the ``evalf`` function.
Returns
=======
A tuple ``(re, im, re_acc, im_acc)``, as returned by ``evalf``.
See Also
========
evalf
"""
if eps is not None:
if not (eps.is_Rational or eps.is_Float) or not eps > 0:
raise ValueError("eps must be positive")
r, _, _, _ = evalf(1/eps, 1, {})
m = fastlog(r)
c, d, _, _ = evalf(x, 1, {})
# Note: If x = a + b*I, then |a| <= 2|c| and |b| <= 2|d|, with equality
# only in the zero case.
# If a is non-zero, then |c| = 2**nc for some integer nc, and c has
# bitcount 1. Therefore 2**fastlog(c) = 2**(nc+1) = 2|c| is an upper bound
# on |a|. Likewise for b and d.
nr, ni = fastlog(c), fastlog(d)
n = max(nr, ni) + 1
# If x is 0, then n is MINUS_INF, and p will be 1. Otherwise,
# n - 1 bits get us past the integer parts of a and b, and +1 accounts for
# the factor of <= sqrt(2) that is |x|/max(|a|, |b|).
p = max(1, m + n + 1)
options = options or {}
return evalf(x, p, options)
|
e78a452a127013353c2e43bbacbdb94f01a321be72e42bd995e1c4cbf4e90faf | r"""This is rule-based deduction system for SymPy
The whole thing is split into two parts
- rules compilation and preparation of tables
- runtime inference
For rule-based inference engines, the classical work is RETE algorithm [1],
[2] Although we are not implementing it in full (or even significantly)
it's still worth a read to understand the underlying ideas.
In short, every rule in a system of rules is one of two forms:
- atom -> ... (alpha rule)
- And(atom1, atom2, ...) -> ... (beta rule)
The major complexity is in efficient beta-rules processing and usually for an
expert system a lot of effort goes into code that operates on beta-rules.
Here we take minimalistic approach to get something usable first.
- (preparation) of alpha- and beta- networks, everything except
- (runtime) FactRules.deduce_all_facts
_____________________________________
( Kirr: I've never thought that doing )
( logic stuff is that difficult... )
-------------------------------------
o ^__^
o (oo)\_______
(__)\ )\/\
||----w |
|| ||
Some references on the topic
----------------------------
[1] https://en.wikipedia.org/wiki/Rete_algorithm
[2] http://reports-archive.adm.cs.cmu.edu/anon/1995/CMU-CS-95-113.pdf
https://en.wikipedia.org/wiki/Propositional_formula
https://en.wikipedia.org/wiki/Inference_rule
https://en.wikipedia.org/wiki/List_of_rules_of_inference
"""
from collections import defaultdict
from typing import Iterator
from .logic import Logic, And, Or, Not
def _base_fact(atom):
"""Return the literal fact of an atom.
Effectively, this merely strips the Not around a fact.
"""
if isinstance(atom, Not):
return atom.arg
else:
return atom
def _as_pair(atom):
if isinstance(atom, Not):
return (atom.arg, False)
else:
return (atom, True)
# XXX this prepares forward-chaining rules for alpha-network
def transitive_closure(implications):
"""
Computes the transitive closure of a list of implications
Uses Warshall's algorithm, as described at
http://www.cs.hope.edu/~cusack/Notes/Notes/DiscreteMath/Warshall.pdf.
"""
full_implications = set(implications)
literals = set().union(*map(set, full_implications))
for k in literals:
for i in literals:
if (i, k) in full_implications:
for j in literals:
if (k, j) in full_implications:
full_implications.add((i, j))
return full_implications
def deduce_alpha_implications(implications):
"""deduce all implications
Description by example
----------------------
given set of logic rules:
a -> b
b -> c
we deduce all possible rules:
a -> b, c
b -> c
implications: [] of (a,b)
return: {} of a -> set([b, c, ...])
"""
implications = implications + [(Not(j), Not(i)) for (i, j) in implications]
res = defaultdict(set)
full_implications = transitive_closure(implications)
for a, b in full_implications:
if a == b:
continue # skip a->a cyclic input
res[a].add(b)
# Clean up tautologies and check consistency
for a, impl in res.items():
impl.discard(a)
na = Not(a)
if na in impl:
raise ValueError(
'implications are inconsistent: %s -> %s %s' % (a, na, impl))
return res
def apply_beta_to_alpha_route(alpha_implications, beta_rules):
"""apply additional beta-rules (And conditions) to already-built
alpha implication tables
TODO: write about
- static extension of alpha-chains
- attaching refs to beta-nodes to alpha chains
e.g.
alpha_implications:
a -> [b, !c, d]
b -> [d]
...
beta_rules:
&(b,d) -> e
then we'll extend a's rule to the following
a -> [b, !c, d, e]
"""
x_impl = {}
for x in alpha_implications.keys():
x_impl[x] = (set(alpha_implications[x]), [])
for bcond, bimpl in beta_rules:
for bk in bcond.args:
if bk in x_impl:
continue
x_impl[bk] = (set(), [])
# static extensions to alpha rules:
# A: x -> a,b B: &(a,b) -> c ==> A: x -> a,b,c
seen_static_extension = True
while seen_static_extension:
seen_static_extension = False
for bcond, bimpl in beta_rules:
if not isinstance(bcond, And):
raise TypeError("Cond is not And")
bargs = set(bcond.args)
for x, (ximpls, bb) in x_impl.items():
x_all = ximpls | {x}
# A: ... -> a B: &(...) -> a is non-informative
if bimpl not in x_all and bargs.issubset(x_all):
ximpls.add(bimpl)
# we introduced new implication - now we have to restore
# completeness of the whole set.
bimpl_impl = x_impl.get(bimpl)
if bimpl_impl is not None:
ximpls |= bimpl_impl[0]
seen_static_extension = True
# attach beta-nodes which can be possibly triggered by an alpha-chain
for bidx, (bcond, bimpl) in enumerate(beta_rules):
bargs = set(bcond.args)
for x, (ximpls, bb) in x_impl.items():
x_all = ximpls | {x}
# A: ... -> a B: &(...) -> a (non-informative)
if bimpl in x_all:
continue
# A: x -> a... B: &(!a,...) -> ... (will never trigger)
# A: x -> a... B: &(...) -> !a (will never trigger)
if any(Not(xi) in bargs or Not(xi) == bimpl for xi in x_all):
continue
if bargs & x_all:
bb.append(bidx)
return x_impl
def rules_2prereq(rules):
"""build prerequisites table from rules
Description by example
----------------------
given set of logic rules:
a -> b, c
b -> c
we build prerequisites (from what points something can be deduced):
b <- a
c <- a, b
rules: {} of a -> [b, c, ...]
return: {} of c <- [a, b, ...]
Note however, that this prerequisites may be *not* enough to prove a
fact. An example is 'a -> b' rule, where prereq(a) is b, and prereq(b)
is a. That's because a=T -> b=T, and b=F -> a=F, but a=F -> b=?
"""
prereq = defaultdict(set)
for (a, _), impl in rules.items():
if isinstance(a, Not):
a = a.args[0]
for (i, _) in impl:
if isinstance(i, Not):
i = i.args[0]
prereq[i].add(a)
return prereq
################
# RULES PROVER #
################
class TautologyDetected(Exception):
"""(internal) Prover uses it for reporting detected tautology"""
pass
class Prover:
"""ai - prover of logic rules
given a set of initial rules, Prover tries to prove all possible rules
which follow from given premises.
As a result proved_rules are always either in one of two forms: alpha or
beta:
Alpha rules
-----------
This are rules of the form::
a -> b & c & d & ...
Beta rules
----------
This are rules of the form::
&(a,b,...) -> c & d & ...
i.e. beta rules are join conditions that say that something follows when
*several* facts are true at the same time.
"""
def __init__(self):
self.proved_rules = []
self._rules_seen = set()
def split_alpha_beta(self):
"""split proved rules into alpha and beta chains"""
rules_alpha = [] # a -> b
rules_beta = [] # &(...) -> b
for a, b in self.proved_rules:
if isinstance(a, And):
rules_beta.append((a, b))
else:
rules_alpha.append((a, b))
return rules_alpha, rules_beta
@property
def rules_alpha(self):
return self.split_alpha_beta()[0]
@property
def rules_beta(self):
return self.split_alpha_beta()[1]
def process_rule(self, a, b):
"""process a -> b rule""" # TODO write more?
if (not a) or isinstance(b, bool):
return
if isinstance(a, bool):
return
if (a, b) in self._rules_seen:
return
else:
self._rules_seen.add((a, b))
# this is the core of processing
try:
self._process_rule(a, b)
except TautologyDetected:
pass
def _process_rule(self, a, b):
# right part first
# a -> b & c --> a -> b ; a -> c
# (?) FIXME this is only correct when b & c != null !
if isinstance(b, And):
sorted_bargs = sorted(b.args, key=str)
for barg in sorted_bargs:
self.process_rule(a, barg)
# a -> b | c --> !b & !c -> !a
# --> a & !b -> c
# --> a & !c -> b
elif isinstance(b, Or):
sorted_bargs = sorted(b.args, key=str)
# detect tautology first
if not isinstance(a, Logic): # Atom
# tautology: a -> a|c|...
if a in sorted_bargs:
raise TautologyDetected(a, b, 'a -> a|c|...')
self.process_rule(And(*[Not(barg) for barg in b.args]), Not(a))
for bidx in range(len(sorted_bargs)):
barg = sorted_bargs[bidx]
brest = sorted_bargs[:bidx] + sorted_bargs[bidx + 1:]
self.process_rule(And(a, Not(barg)), Or(*brest))
# left part
# a & b -> c --> IRREDUCIBLE CASE -- WE STORE IT AS IS
# (this will be the basis of beta-network)
elif isinstance(a, And):
sorted_aargs = sorted(a.args, key=str)
if b in sorted_aargs:
raise TautologyDetected(a, b, 'a & b -> a')
self.proved_rules.append((a, b))
# XXX NOTE at present we ignore !c -> !a | !b
elif isinstance(a, Or):
sorted_aargs = sorted(a.args, key=str)
if b in sorted_aargs:
raise TautologyDetected(a, b, 'a | b -> a')
for aarg in sorted_aargs:
self.process_rule(aarg, b)
else:
# both `a` and `b` are atoms
self.proved_rules.append((a, b)) # a -> b
self.proved_rules.append((Not(b), Not(a))) # !b -> !a
########################################
class FactRules:
"""Rules that describe how to deduce facts in logic space
When defined, these rules allow implications to quickly be determined
for a set of facts. For this precomputed deduction tables are used.
see `deduce_all_facts` (forward-chaining)
Also it is possible to gather prerequisites for a fact, which is tried
to be proven. (backward-chaining)
Definition Syntax
-----------------
a -> b -- a=T -> b=T (and automatically b=F -> a=F)
a -> !b -- a=T -> b=F
a == b -- a -> b & b -> a
a -> b & c -- a=T -> b=T & c=T
# TODO b | c
Internals
---------
.full_implications[k, v]: all the implications of fact k=v
.beta_triggers[k, v]: beta rules that might be triggered when k=v
.prereq -- {} k <- [] of k's prerequisites
.defined_facts -- set of defined fact names
"""
def __init__(self, rules):
"""Compile rules into internal lookup tables"""
if isinstance(rules, str):
rules = rules.splitlines()
# --- parse and process rules ---
P = Prover()
for rule in rules:
# XXX `a` is hardcoded to be always atom
a, op, b = rule.split(None, 2)
a = Logic.fromstring(a)
b = Logic.fromstring(b)
if op == '->':
P.process_rule(a, b)
elif op == '==':
P.process_rule(a, b)
P.process_rule(b, a)
else:
raise ValueError('unknown op %r' % op)
# --- build deduction networks ---
self.beta_rules = []
for bcond, bimpl in P.rules_beta:
self.beta_rules.append(
({_as_pair(a) for a in bcond.args}, _as_pair(bimpl)))
# deduce alpha implications
impl_a = deduce_alpha_implications(P.rules_alpha)
# now:
# - apply beta rules to alpha chains (static extension), and
# - further associate beta rules to alpha chain (for inference
# at runtime)
impl_ab = apply_beta_to_alpha_route(impl_a, P.rules_beta)
# extract defined fact names
self.defined_facts = {_base_fact(k) for k in impl_ab.keys()}
# build rels (forward chains)
full_implications = defaultdict(set)
beta_triggers = defaultdict(set)
for k, (impl, betaidxs) in impl_ab.items():
full_implications[_as_pair(k)] = {_as_pair(i) for i in impl}
beta_triggers[_as_pair(k)] = betaidxs
self.full_implications = full_implications
self.beta_triggers = beta_triggers
# build prereq (backward chains)
prereq = defaultdict(set)
rel_prereq = rules_2prereq(full_implications)
for k, pitems in rel_prereq.items():
prereq[k] |= pitems
self.prereq = prereq
def _to_python(self) -> str:
""" Generate a string with plain python representation of the instance """
return '\n'.join(self.print_rules())
@classmethod
def _from_python(cls, data : dict):
""" Generate an instance from the plain python representation """
self = cls('')
for key in ['full_implications', 'beta_triggers', 'prereq']:
d=defaultdict(set)
d.update(data[key])
setattr(self, key, d)
self.beta_rules = data['beta_rules']
self.defined_facts = set(data['defined_facts'])
return self
def _defined_facts_lines(self):
yield 'defined_facts = ['
for fact in sorted(self.defined_facts):
yield f' {fact!r},'
yield '] # defined_facts'
def _full_implications_lines(self):
yield 'full_implications = dict( ['
for fact in sorted(self.defined_facts):
for value in (True, False):
yield f' # Implications of {fact} = {value}:'
yield f' (({fact!r}, {value!r}), set( ('
implications = self.full_implications[(fact, value)]
for implied in sorted(implications):
yield f' {implied!r},'
yield ' ) ),'
yield ' ),'
yield ' ] ) # full_implications'
def _prereq_lines(self):
yield 'prereq = {'
yield ''
for fact in sorted(self.prereq):
yield f' # facts that could determine the value of {fact}'
yield f' {fact!r}: {{'
for pfact in sorted(self.prereq[fact]):
yield f' {pfact!r},'
yield ' },'
yield ''
yield '} # prereq'
def _beta_rules_lines(self):
reverse_implications = defaultdict(list)
for n, (pre, implied) in enumerate(self.beta_rules):
reverse_implications[implied].append((pre, n))
yield '# Note: the order of the beta rules is used in the beta_triggers'
yield 'beta_rules = ['
yield ''
m = 0
indices = {}
for implied in sorted(reverse_implications):
fact, value = implied
yield f' # Rules implying {fact} = {value}'
for pre, n in reverse_implications[implied]:
indices[n] = m
m += 1
setstr = ", ".join(map(str, sorted(pre)))
yield f' ({{{setstr}}},'
yield f' {implied!r}),'
yield ''
yield '] # beta_rules'
yield 'beta_triggers = {'
for query in sorted(self.beta_triggers):
fact, value = query
triggers = [indices[n] for n in self.beta_triggers[query]]
yield f' {query!r}: {triggers!r},'
yield '} # beta_triggers'
def print_rules(self) -> Iterator[str]:
""" Returns a generator with lines to represent the facts and rules """
yield from self._defined_facts_lines()
yield ''
yield ''
yield from self._full_implications_lines()
yield ''
yield ''
yield from self._prereq_lines()
yield ''
yield ''
yield from self._beta_rules_lines()
yield ''
yield ''
yield "generated_assumptions = {'defined_facts': defined_facts, 'full_implications': full_implications,"
yield " 'prereq': prereq, 'beta_rules': beta_rules, 'beta_triggers': beta_triggers}"
class InconsistentAssumptions(ValueError):
def __str__(self):
kb, fact, value = self.args
return "%s, %s=%s" % (kb, fact, value)
class FactKB(dict):
"""
A simple propositional knowledge base relying on compiled inference rules.
"""
def __str__(self):
return '{\n%s}' % ',\n'.join(
["\t%s: %s" % i for i in sorted(self.items())])
def __init__(self, rules):
self.rules = rules
def _tell(self, k, v):
"""Add fact k=v to the knowledge base.
Returns True if the KB has actually been updated, False otherwise.
"""
if k in self and self[k] is not None:
if self[k] == v:
return False
else:
raise InconsistentAssumptions(self, k, v)
else:
self[k] = v
return True
# *********************************************
# * This is the workhorse, so keep it *fast*. *
# *********************************************
def deduce_all_facts(self, facts):
"""
Update the KB with all the implications of a list of facts.
Facts can be specified as a dictionary or as a list of (key, value)
pairs.
"""
# keep frequently used attributes locally, so we'll avoid extra
# attribute access overhead
full_implications = self.rules.full_implications
beta_triggers = self.rules.beta_triggers
beta_rules = self.rules.beta_rules
if isinstance(facts, dict):
facts = facts.items()
while facts:
beta_maytrigger = set()
# --- alpha chains ---
for k, v in facts:
if not self._tell(k, v) or v is None:
continue
# lookup routing tables
for key, value in full_implications[k, v]:
self._tell(key, value)
beta_maytrigger.update(beta_triggers[k, v])
# --- beta chains ---
facts = []
for bidx in beta_maytrigger:
bcond, bimpl = beta_rules[bidx]
if all(self.get(k) is v for k, v in bcond):
facts.append(bimpl)
|
ee0c939cca30a5185052d6bfa3c0d991be6b0fadd809aef76f01c8ec09e5e73a | """ Caching facility for SymPy """
from importlib import import_module
from typing import Callable
class _cache(list):
""" List of cached functions """
def print_cache(self):
"""print cache info"""
for item in self:
name = item.__name__
myfunc = item
while hasattr(myfunc, '__wrapped__'):
if hasattr(myfunc, 'cache_info'):
info = myfunc.cache_info()
break
else:
myfunc = myfunc.__wrapped__
else:
info = None
print(name, info)
def clear_cache(self):
"""clear cache content"""
for item in self:
myfunc = item
while hasattr(myfunc, '__wrapped__'):
if hasattr(myfunc, 'cache_clear'):
myfunc.cache_clear()
break
else:
myfunc = myfunc.__wrapped__
# global cache registry:
CACHE = _cache()
# make clear and print methods available
print_cache = CACHE.print_cache
clear_cache = CACHE.clear_cache
from functools import lru_cache, wraps
def __cacheit(maxsize):
"""caching decorator.
important: the result of cached function must be *immutable*
Examples
========
>>> from sympy import cacheit
>>> @cacheit
... def f(a, b):
... return a+b
>>> @cacheit
... def f(a, b): # noqa: F811
... return [a, b] # <-- WRONG, returns mutable object
to force cacheit to check returned results mutability and consistency,
set environment variable SYMPY_USE_CACHE to 'debug'
"""
def func_wrapper(func):
cfunc = lru_cache(maxsize, typed=True)(func)
@wraps(func)
def wrapper(*args, **kwargs):
try:
retval = cfunc(*args, **kwargs)
except TypeError as e:
if not e.args or not e.args[0].startswith('unhashable type:'):
raise
retval = func(*args, **kwargs)
return retval
wrapper.cache_info = cfunc.cache_info
wrapper.cache_clear = cfunc.cache_clear
CACHE.append(wrapper)
return wrapper
return func_wrapper
########################################
def __cacheit_nocache(func):
return func
def __cacheit_debug(maxsize):
"""cacheit + code to check cache consistency"""
def func_wrapper(func):
cfunc = __cacheit(maxsize)(func)
@wraps(func)
def wrapper(*args, **kw_args):
# always call function itself and compare it with cached version
r1 = func(*args, **kw_args)
r2 = cfunc(*args, **kw_args)
# try to see if the result is immutable
#
# this works because:
#
# hash([1,2,3]) -> raise TypeError
# hash({'a':1, 'b':2}) -> raise TypeError
# hash((1,[2,3])) -> raise TypeError
#
# hash((1,2,3)) -> just computes the hash
hash(r1), hash(r2)
# also see if returned values are the same
if r1 != r2:
raise RuntimeError("Returned values are not the same")
return r1
return wrapper
return func_wrapper
def _getenv(key, default=None):
from os import getenv
return getenv(key, default)
# SYMPY_USE_CACHE=yes/no/debug
USE_CACHE = _getenv('SYMPY_USE_CACHE', 'yes').lower()
# SYMPY_CACHE_SIZE=some_integer/None
# special cases :
# SYMPY_CACHE_SIZE=0 -> No caching
# SYMPY_CACHE_SIZE=None -> Unbounded caching
scs = _getenv('SYMPY_CACHE_SIZE', '1000')
if scs.lower() == 'none':
SYMPY_CACHE_SIZE = None
else:
try:
SYMPY_CACHE_SIZE = int(scs)
except ValueError:
raise RuntimeError(
'SYMPY_CACHE_SIZE must be a valid integer or None. ' + \
'Got: %s' % SYMPY_CACHE_SIZE)
if USE_CACHE == 'no':
cacheit = __cacheit_nocache
elif USE_CACHE == 'yes':
cacheit = __cacheit(SYMPY_CACHE_SIZE)
elif USE_CACHE == 'debug':
cacheit = __cacheit_debug(SYMPY_CACHE_SIZE) # a lot slower
else:
raise RuntimeError(
'unrecognized value for SYMPY_USE_CACHE: %s' % USE_CACHE)
def cached_property(func):
'''Decorator to cache property method'''
attrname = '__' + func.__name__
_cached_property_sentinel = object()
def propfunc(self):
val = getattr(self, attrname, _cached_property_sentinel)
if val is _cached_property_sentinel:
val = func(self)
setattr(self, attrname, val)
return val
return property(propfunc)
def lazy_function(module : str, name : str) -> Callable:
""" Create a lazy proxy for a function in a module
The module containing the function is not imported until the function is used.
"""
func = None
def _get_function():
nonlocal func
if func is None:
func = getattr(import_module(module), name)
return func
# The metaclass is needed so that help() shows the docstring
class LazyFunctionMeta(type):
@property
def __doc__(self):
docstring = _get_function().__doc__
docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
return docstring
class LazyFunction(metaclass=LazyFunctionMeta):
def __call__(self, *args, **kwargs):
# inline get of function for performance gh-23832
nonlocal func
if func is None:
func = getattr(import_module(module), name)
return func(*args, **kwargs)
@property
def __doc__(self):
docstring = _get_function().__doc__
docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
return docstring
def __str__(self):
return _get_function().__str__()
def __repr__(self):
return f"<{__class__.__name__} object at 0x{id(self):x}>: wrapping '{module}.{name}'"
return LazyFunction()
|
8567832ac2a726e02e3cdff9214ea6d6892eac0abdc4cb772d080c7a172f04a4 | r"""
Efficient functions for generating Appell sequences.
An Appell sequence is a zero-indexed sequence of polynomials `p_i(x)`
satisfying `p_{i+1}'(x)=(i+1)p_i(x)` for all `i`. This definition leads
to the following iterative algorithm:
.. math :: p_0(x) = c_0,\ p_i(x) = i \int_0^x p_{i-1}(t)\,dt + c_i
The constant coefficients `c_i` are usually determined from the
just-evaluated integral and `i`.
Appell sequences satisfy the following identity from umbral calculus:
.. math :: p_n(x+y) = \sum_{k=0}^n \binom{n}{k} p_k(x) y^{n-k}
References
==========
.. [1] https://en.wikipedia.org/wiki/Appell_sequence
.. [2] Peter Luschny, "An introduction to the Bernoulli function",
https://arxiv.org/abs/2009.06743
"""
from sympy.polys.densearith import dup_mul_ground, dup_sub_ground, dup_quo_ground
from sympy.polys.densetools import dup_eval, dup_integrate
from sympy.polys.domains import ZZ, QQ
from sympy.polys.polytools import named_poly
from sympy.utilities import public
def dup_bernoulli(n, K):
"""Low-level implementation of Bernoulli polynomials."""
if n < 1:
return [K.one]
p = [K.one, K(-1,2)]
for i in range(2, n+1):
p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
if i % 2 == 0:
p = dup_sub_ground(p, dup_eval(p, K(1,2), K) * K(1<<(i-1), (1<<i)-1), K)
return p
@public
def bernoulli_poly(n, x=None, polys=False):
r"""Generates the Bernoulli polynomial `\operatorname{B}_n(x)`.
`\operatorname{B}_n(x)` is the unique polynomial satisfying
.. math :: \int_{x}^{x+1} \operatorname{B}_n(t) \,dt = x^n.
Based on this, we have for nonnegative integer `s` and integer
`a` and `b`
.. math :: \sum_{k=a}^{b} k^s = \frac{\operatorname{B}_{s+1}(b+1) -
\operatorname{B}_{s+1}(a)}{s+1}
which is related to Jakob Bernoulli's original motivation for introducing
the Bernoulli numbers, the values of these polynomials at `x = 1`.
Examples
========
>>> from sympy import summation
>>> from sympy.abc import x
>>> from sympy.polys import bernoulli_poly
>>> bernoulli_poly(5, x)
x**5 - 5*x**4/2 + 5*x**3/3 - x/6
>>> def psum(p, a, b):
... return (bernoulli_poly(p+1,b+1) - bernoulli_poly(p+1,a)) / (p+1)
>>> psum(4, -6, 27)
3144337
>>> summation(x**4, (x, -6, 27))
3144337
>>> psum(1, 1, x).factor()
x*(x + 1)/2
>>> psum(2, 1, x).factor()
x*(x + 1)*(2*x + 1)/6
>>> psum(3, 1, x).factor()
x**2*(x + 1)**2/4
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
See Also
========
sympy.functions.combinatorial.numbers.bernoulli
References
==========
.. [1] https://en.wikipedia.org/wiki/Bernoulli_polynomials
"""
return named_poly(n, dup_bernoulli, QQ, "Bernoulli polynomial", (x,), polys)
def dup_bernoulli_c(n, K):
"""Low-level implementation of central Bernoulli polynomials."""
p = [K.one]
for i in range(1, n+1):
p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
if i % 2 == 0:
p = dup_sub_ground(p, dup_eval(p, K.one, K) * K((1<<(i-1))-1, (1<<i)-1), K)
return p
@public
def bernoulli_c_poly(n, x=None, polys=False):
r"""Generates the central Bernoulli polynomial `\operatorname{B}_n^c(x)`.
These are scaled and shifted versions of the plain Bernoulli polynomials,
done in such a way that `\operatorname{B}_n^c(x)` is an even or odd function
for even or odd `n` respectively:
.. math :: \operatorname{B}_n^c(x) = 2^n \operatorname{B}_n
\left(\frac{x+1}{2}\right)
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_bernoulli_c, QQ, "central Bernoulli polynomial", (x,), polys)
def dup_genocchi(n, K):
"""Low-level implementation of Genocchi polynomials."""
if n < 1:
return [K.zero]
p = [-K.one]
for i in range(2, n+1):
p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
if i % 2 == 0:
p = dup_sub_ground(p, dup_eval(p, K.one, K) // K(2), K)
return p
@public
def genocchi_poly(n, x=None, polys=False):
r"""Generates the Genocchi polynomial `\operatorname{G}_n(x)`.
`\operatorname{G}_n(x)` is twice the difference between the plain and
central Bernoulli polynomials, so has degree `n-1`:
.. math :: \operatorname{G}_n(x) = 2 (\operatorname{B}_n(x) -
\operatorname{B}_n^c(x))
The factor of 2 in the definition endows `\operatorname{G}_n(x)` with
integer coefficients.
Parameters
==========
n : int
Degree of the polynomial plus one.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
See Also
========
sympy.functions.combinatorial.numbers.genocchi
"""
return named_poly(n, dup_genocchi, ZZ, "Genocchi polynomial", (x,), polys)
def dup_euler(n, K):
"""Low-level implementation of Euler polynomials."""
return dup_quo_ground(dup_genocchi(n+1, ZZ), K(-n-1), K)
@public
def euler_poly(n, x=None, polys=False):
r"""Generates the Euler polynomial `\operatorname{E}_n(x)`.
These are scaled and reindexed versions of the Genocchi polynomials:
.. math :: \operatorname{E}_n(x) = -\frac{\operatorname{G}_{n+1}(x)}{n+1}
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
See Also
========
sympy.functions.combinatorial.numbers.euler
"""
return named_poly(n, dup_euler, QQ, "Euler polynomial", (x,), polys)
def dup_andre(n, K):
"""Low-level implementation of Andre polynomials."""
p = [K.one]
for i in range(1, n+1):
p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
if i % 2 == 0:
p = dup_sub_ground(p, dup_eval(p, K.one, K), K)
return p
@public
def andre_poly(n, x=None, polys=False):
r"""Generates the Andre polynomial `\mathcal{A}_n(x)`.
This is the Appell sequence where the constant coefficients form the sequence
of Euler numbers ``euler(n)``. As such they have integer coefficients
and parities matching the parity of `n`.
Luschny calls these the *Swiss-knife polynomials* because their values
at 0 and 1 can be simply transformed into both the Bernoulli and Euler
numbers. Here they are called the Andre polynomials because
`|\mathcal{A}_n(n\bmod 2)|` for `n \ge 0` generates what Luschny calls
the *Andre numbers*, A000111 in the OEIS.
Examples
========
>>> from sympy import bernoulli, euler, genocchi
>>> from sympy.abc import x
>>> from sympy.polys import andre_poly
>>> andre_poly(9, x)
x**9 - 36*x**7 + 630*x**5 - 5124*x**3 + 12465*x
>>> [andre_poly(n, 0) for n in range(11)]
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]
>>> [euler(n) for n in range(11)]
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]
>>> [andre_poly(n-1, 1) * n / (4**n - 2**n) for n in range(1, 11)]
[1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
>>> [bernoulli(n) for n in range(1, 11)]
[1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
>>> [-andre_poly(n-1, -1) * n / (-2)**(n-1) for n in range(1, 11)]
[-1, -1, 0, 1, 0, -3, 0, 17, 0, -155]
>>> [genocchi(n) for n in range(1, 11)]
[-1, -1, 0, 1, 0, -3, 0, 17, 0, -155]
>>> [abs(andre_poly(n, n%2)) for n in range(11)]
[1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
See Also
========
sympy.functions.combinatorial.numbers.andre
References
==========
.. [1] Peter Luschny, "An introduction to the Bernoulli function",
https://arxiv.org/abs/2009.06743
"""
return named_poly(n, dup_andre, ZZ, "Andre polynomial", (x,), polys)
|
a0453dcf8220b50b15b7ed6b8290e9ee9abec76dbbdaeeed28dabf3f1232a53c | """User-friendly public interface to polynomial functions. """
from functools import wraps, reduce
from operator import mul
from typing import Optional
from sympy.core import (
S, Expr, Add, Tuple
)
from sympy.core.basic import Basic
from sympy.core.decorators import _sympifyit
from sympy.core.exprtools import Factors, factor_nc, factor_terms
from sympy.core.evalf import (
pure_complex, evalf, fastlog, _evalf_with_bounded_error, quad_to_mpmath)
from sympy.core.function import Derivative
from sympy.core.mul import Mul, _keep_coeff
from sympy.core.numbers import ilcm, I, Integer
from sympy.core.relational import Relational, Equality
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy, Symbol
from sympy.core.sympify import sympify, _sympify
from sympy.core.traversal import preorder_traversal, bottom_up
from sympy.logic.boolalg import BooleanAtom
from sympy.polys import polyoptions as options
from sympy.polys.constructor import construct_domain
from sympy.polys.domains import FF, QQ, ZZ
from sympy.polys.domains.domainelement import DomainElement
from sympy.polys.fglmtools import matrix_fglm
from sympy.polys.groebnertools import groebner as _groebner
from sympy.polys.monomials import Monomial
from sympy.polys.orderings import monomial_key
from sympy.polys.polyclasses import DMP, DMF, ANP
from sympy.polys.polyerrors import (
OperationNotSupported, DomainError,
CoercionFailed, UnificationFailed,
GeneratorsNeeded, PolynomialError,
MultivariatePolynomialError,
ExactQuotientFailed,
PolificationFailed,
ComputationFailed,
GeneratorsError,
)
from sympy.polys.polyutils import (
basic_from_dict,
_sort_gens,
_unify_gens,
_dict_reorder,
_dict_from_expr,
_parallel_dict_from_expr,
)
from sympy.polys.rationaltools import together
from sympy.polys.rootisolation import dup_isolate_real_roots_list
from sympy.utilities import group, public, filldedent
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import iterable, sift
# Required to avoid errors
import sympy.polys
import mpmath
from mpmath.libmp.libhyper import NoConvergence
def _polifyit(func):
@wraps(func)
def wrapper(f, g):
g = _sympify(g)
if isinstance(g, Poly):
return func(f, g)
elif isinstance(g, Expr):
try:
g = f.from_expr(g, *f.gens)
except PolynomialError:
if g.is_Matrix:
return NotImplemented
expr_method = getattr(f.as_expr(), func.__name__)
result = expr_method(g)
if result is not NotImplemented:
sympy_deprecation_warning(
"""
Mixing Poly with non-polynomial expressions in binary
operations is deprecated. Either explicitly convert
the non-Poly operand to a Poly with as_poly() or
convert the Poly to an Expr with as_expr().
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-poly-nonpoly-binary-operations",
)
return result
else:
return func(f, g)
else:
return NotImplemented
return wrapper
@public
class Poly(Basic):
"""
Generic class for representing and operating on polynomial expressions.
See :ref:`polys-docs` for general documentation.
Poly is a subclass of Basic rather than Expr but instances can be
converted to Expr with the :py:meth:`~.Poly.as_expr` method.
.. deprecated:: 1.6
Combining Poly with non-Poly objects in binary operations is
deprecated. Explicitly convert both objects to either Poly or Expr
first. See :ref:`deprecated-poly-nonpoly-binary-operations`.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
Create a univariate polynomial:
>>> Poly(x*(x**2 + x - 1)**2)
Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')
Create a univariate polynomial with specific domain:
>>> from sympy import sqrt
>>> Poly(x**2 + 2*x + sqrt(3), domain='R')
Poly(1.0*x**2 + 2.0*x + 1.73205080756888, x, domain='RR')
Create a multivariate polynomial:
>>> Poly(y*x**2 + x*y + 1)
Poly(x**2*y + x*y + 1, x, y, domain='ZZ')
Create a univariate polynomial, where y is a constant:
>>> Poly(y*x**2 + x*y + 1,x)
Poly(y*x**2 + y*x + 1, x, domain='ZZ[y]')
You can evaluate the above polynomial as a function of y:
>>> Poly(y*x**2 + x*y + 1,x).eval(2)
6*y + 1
See Also
========
sympy.core.expr.Expr
"""
__slots__ = ('rep', 'gens')
is_commutative = True
is_Poly = True
_op_priority = 10.001
def __new__(cls, rep, *gens, **args):
"""Create a new polynomial instance out of something useful. """
opt = options.build_options(gens, args)
if 'order' in opt:
raise NotImplementedError("'order' keyword is not implemented yet")
if isinstance(rep, (DMP, DMF, ANP, DomainElement)):
return cls._from_domain_element(rep, opt)
elif iterable(rep, exclude=str):
if isinstance(rep, dict):
return cls._from_dict(rep, opt)
else:
return cls._from_list(list(rep), opt)
else:
rep = sympify(rep)
if rep.is_Poly:
return cls._from_poly(rep, opt)
else:
return cls._from_expr(rep, opt)
# Poly does not pass its args to Basic.__new__ to be stored in _args so we
# have to emulate them here with an args property that derives from rep
# and gens which are instance attributes. This also means we need to
# define _hashable_content. The _hashable_content is rep and gens but args
# uses expr instead of rep (expr is the Basic version of rep). Passing
# expr in args means that Basic methods like subs should work. Using rep
# otherwise means that Poly can remain more efficient than Basic by
# avoiding creating a Basic instance just to be hashable.
@classmethod
def new(cls, rep, *gens):
"""Construct :class:`Poly` instance from raw representation. """
if not isinstance(rep, DMP):
raise PolynomialError(
"invalid polynomial representation: %s" % rep)
elif rep.lev != len(gens) - 1:
raise PolynomialError("invalid arguments: %s, %s" % (rep, gens))
obj = Basic.__new__(cls)
obj.rep = rep
obj.gens = gens
return obj
@property
def expr(self):
return basic_from_dict(self.rep.to_sympy_dict(), *self.gens)
@property
def args(self):
return (self.expr,) + self.gens
def _hashable_content(self):
return (self.rep,) + self.gens
@classmethod
def from_dict(cls, rep, *gens, **args):
"""Construct a polynomial from a ``dict``. """
opt = options.build_options(gens, args)
return cls._from_dict(rep, opt)
@classmethod
def from_list(cls, rep, *gens, **args):
"""Construct a polynomial from a ``list``. """
opt = options.build_options(gens, args)
return cls._from_list(rep, opt)
@classmethod
def from_poly(cls, rep, *gens, **args):
"""Construct a polynomial from a polynomial. """
opt = options.build_options(gens, args)
return cls._from_poly(rep, opt)
@classmethod
def from_expr(cls, rep, *gens, **args):
"""Construct a polynomial from an expression. """
opt = options.build_options(gens, args)
return cls._from_expr(rep, opt)
@classmethod
def _from_dict(cls, rep, opt):
"""Construct a polynomial from a ``dict``. """
gens = opt.gens
if not gens:
raise GeneratorsNeeded(
"Cannot initialize from 'dict' without generators")
level = len(gens) - 1
domain = opt.domain
if domain is None:
domain, rep = construct_domain(rep, opt=opt)
else:
for monom, coeff in rep.items():
rep[monom] = domain.convert(coeff)
return cls.new(DMP.from_dict(rep, level, domain), *gens)
@classmethod
def _from_list(cls, rep, opt):
"""Construct a polynomial from a ``list``. """
gens = opt.gens
if not gens:
raise GeneratorsNeeded(
"Cannot initialize from 'list' without generators")
elif len(gens) != 1:
raise MultivariatePolynomialError(
"'list' representation not supported")
level = len(gens) - 1
domain = opt.domain
if domain is None:
domain, rep = construct_domain(rep, opt=opt)
else:
rep = list(map(domain.convert, rep))
return cls.new(DMP.from_list(rep, level, domain), *gens)
@classmethod
def _from_poly(cls, rep, opt):
"""Construct a polynomial from a polynomial. """
if cls != rep.__class__:
rep = cls.new(rep.rep, *rep.gens)
gens = opt.gens
field = opt.field
domain = opt.domain
if gens and rep.gens != gens:
if set(rep.gens) != set(gens):
return cls._from_expr(rep.as_expr(), opt)
else:
rep = rep.reorder(*gens)
if 'domain' in opt and domain:
rep = rep.set_domain(domain)
elif field is True:
rep = rep.to_field()
return rep
@classmethod
def _from_expr(cls, rep, opt):
"""Construct a polynomial from an expression. """
rep, opt = _dict_from_expr(rep, opt)
return cls._from_dict(rep, opt)
@classmethod
def _from_domain_element(cls, rep, opt):
gens = opt.gens
domain = opt.domain
level = len(gens) - 1
rep = [domain.convert(rep)]
return cls.new(DMP.from_list(rep, level, domain), *gens)
def __hash__(self):
return super().__hash__()
@property
def free_symbols(self):
"""
Free symbols of a polynomial expression.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x**2 + 1).free_symbols
{x}
>>> Poly(x**2 + y).free_symbols
{x, y}
>>> Poly(x**2 + y, x).free_symbols
{x, y}
>>> Poly(x**2 + y, x, z).free_symbols
{x, y}
"""
symbols = set()
gens = self.gens
for i in range(len(gens)):
for monom in self.monoms():
if monom[i]:
symbols |= gens[i].free_symbols
break
return symbols | self.free_symbols_in_domain
@property
def free_symbols_in_domain(self):
"""
Free symbols of the domain of ``self``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 1).free_symbols_in_domain
set()
>>> Poly(x**2 + y).free_symbols_in_domain
set()
>>> Poly(x**2 + y, x).free_symbols_in_domain
{y}
"""
domain, symbols = self.rep.dom, set()
if domain.is_Composite:
for gen in domain.symbols:
symbols |= gen.free_symbols
elif domain.is_EX:
for coeff in self.coeffs():
symbols |= coeff.free_symbols
return symbols
@property
def gen(self):
"""
Return the principal generator.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).gen
x
"""
return self.gens[0]
@property
def domain(self):
"""Get the ground domain of a :py:class:`~.Poly`
Returns
=======
:py:class:`~.Domain`:
Ground domain of the :py:class:`~.Poly`.
Examples
========
>>> from sympy import Poly, Symbol
>>> x = Symbol('x')
>>> p = Poly(x**2 + x)
>>> p
Poly(x**2 + x, x, domain='ZZ')
>>> p.domain
ZZ
"""
return self.get_domain()
@property
def zero(self):
"""Return zero polynomial with ``self``'s properties. """
return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens)
@property
def one(self):
"""Return one polynomial with ``self``'s properties. """
return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens)
@property
def unit(self):
"""Return unit polynomial with ``self``'s properties. """
return self.new(self.rep.unit(self.rep.lev, self.rep.dom), *self.gens)
def unify(f, g):
"""
Make ``f`` and ``g`` belong to the same domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f, g = Poly(x/2 + 1), Poly(2*x + 1)
>>> f
Poly(1/2*x + 1, x, domain='QQ')
>>> g
Poly(2*x + 1, x, domain='ZZ')
>>> F, G = f.unify(g)
>>> F
Poly(1/2*x + 1, x, domain='QQ')
>>> G
Poly(2*x + 1, x, domain='QQ')
"""
_, per, F, G = f._unify(g)
return per(F), per(G)
def _unify(f, g):
g = sympify(g)
if not g.is_Poly:
try:
return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g))
except CoercionFailed:
raise UnificationFailed("Cannot unify %s with %s" % (f, g))
if isinstance(f.rep, DMP) and isinstance(g.rep, DMP):
gens = _unify_gens(f.gens, g.gens)
dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens) - 1
if f.gens != gens:
f_monoms, f_coeffs = _dict_reorder(
f.rep.to_dict(), f.gens, gens)
if f.rep.dom != dom:
f_coeffs = [dom.convert(c, f.rep.dom) for c in f_coeffs]
F = DMP(dict(list(zip(f_monoms, f_coeffs))), dom, lev)
else:
F = f.rep.convert(dom)
if g.gens != gens:
g_monoms, g_coeffs = _dict_reorder(
g.rep.to_dict(), g.gens, gens)
if g.rep.dom != dom:
g_coeffs = [dom.convert(c, g.rep.dom) for c in g_coeffs]
G = DMP(dict(list(zip(g_monoms, g_coeffs))), dom, lev)
else:
G = g.rep.convert(dom)
else:
raise UnificationFailed("Cannot unify %s with %s" % (f, g))
cls = f.__class__
def per(rep, dom=dom, gens=gens, remove=None):
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return dom.to_sympy(rep)
return cls.new(rep, *gens)
return dom, per, F, G
def per(f, rep, gens=None, remove=None):
"""
Create a Poly out of the given representation.
Examples
========
>>> from sympy import Poly, ZZ
>>> from sympy.abc import x, y
>>> from sympy.polys.polyclasses import DMP
>>> a = Poly(x**2 + 1)
>>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y])
Poly(y + 1, y, domain='ZZ')
"""
if gens is None:
gens = f.gens
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return f.rep.dom.to_sympy(rep)
return f.__class__.new(rep, *gens)
def set_domain(f, domain):
"""Set the ground domain of ``f``. """
opt = options.build_options(f.gens, {'domain': domain})
return f.per(f.rep.convert(opt.domain))
def get_domain(f):
"""Get the ground domain of ``f``. """
return f.rep.dom
def set_modulus(f, modulus):
"""
Set the modulus of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2)
Poly(x**2 + 1, x, modulus=2)
"""
modulus = options.Modulus.preprocess(modulus)
return f.set_domain(FF(modulus))
def get_modulus(f):
"""
Get the modulus of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, modulus=2).get_modulus()
2
"""
domain = f.get_domain()
if domain.is_FiniteField:
return Integer(domain.characteristic())
else:
raise PolynomialError("not a polynomial over a Galois field")
def _eval_subs(f, old, new):
"""Internal implementation of :func:`subs`. """
if old in f.gens:
if new.is_number:
return f.eval(old, new)
else:
try:
return f.replace(old, new)
except PolynomialError:
pass
return f.as_expr().subs(old, new)
def exclude(f):
"""
Remove unnecessary generators from ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import a, b, c, d, x
>>> Poly(a + x, a, b, c, d, x).exclude()
Poly(a + x, a, x, domain='ZZ')
"""
J, new = f.rep.exclude()
gens = [gen for j, gen in enumerate(f.gens) if j not in J]
return f.per(new, gens=gens)
def replace(f, x, y=None, **_ignore):
# XXX this does not match Basic's signature
"""
Replace ``x`` with ``y`` in generators list.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 1, x).replace(x, y)
Poly(y**2 + 1, y, domain='ZZ')
"""
if y is None:
if f.is_univariate:
x, y = f.gen, x
else:
raise PolynomialError(
"syntax supported only in univariate case")
if x == y or x not in f.gens:
return f
if x in f.gens and y not in f.gens:
dom = f.get_domain()
if not dom.is_Composite or y not in dom.symbols:
gens = list(f.gens)
gens[gens.index(x)] = y
return f.per(f.rep, gens=gens)
raise PolynomialError("Cannot replace %s with %s in %s" % (x, y, f))
def match(f, *args, **kwargs):
"""Match expression from Poly. See Basic.match()"""
return f.as_expr().match(*args, **kwargs)
def reorder(f, *gens, **args):
"""
Efficiently apply new order of generators.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x*y**2, x, y).reorder(y, x)
Poly(y**2*x + x**2, y, x, domain='ZZ')
"""
opt = options.Options((), args)
if not gens:
gens = _sort_gens(f.gens, opt=opt)
elif set(f.gens) != set(gens):
raise PolynomialError(
"generators list can differ only up to order of elements")
rep = dict(list(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens))))
return f.per(DMP(rep, f.rep.dom, len(gens) - 1), gens=gens)
def ltrim(f, gen):
"""
Remove dummy generators from ``f`` that are to the left of
specified ``gen`` in the generators as ordered. When ``gen``
is an integer, it refers to the generator located at that
position within the tuple of generators of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(y**2 + y*z**2, x, y, z).ltrim(y)
Poly(y**2 + y*z**2, y, z, domain='ZZ')
>>> Poly(z, x, y, z).ltrim(-1)
Poly(z, z, domain='ZZ')
"""
rep = f.as_dict(native=True)
j = f._gen_to_level(gen)
terms = {}
for monom, coeff in rep.items():
if any(monom[:j]):
# some generator is used in the portion to be trimmed
raise PolynomialError("Cannot left trim %s" % f)
terms[monom[j:]] = coeff
gens = f.gens[j:]
return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens)
def has_only_gens(f, *gens):
"""
Return ``True`` if ``Poly(f, *gens)`` retains ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x*y + 1, x, y, z).has_only_gens(x, y)
True
>>> Poly(x*y + z, x, y, z).has_only_gens(x, y)
False
"""
indices = set()
for gen in gens:
try:
index = f.gens.index(gen)
except ValueError:
raise GeneratorsError(
"%s doesn't have %s as generator" % (f, gen))
else:
indices.add(index)
for monom in f.monoms():
for i, elt in enumerate(monom):
if i not in indices and elt:
return False
return True
def to_ring(f):
"""
Make the ground domain a ring.
Examples
========
>>> from sympy import Poly, QQ
>>> from sympy.abc import x
>>> Poly(x**2 + 1, domain=QQ).to_ring()
Poly(x**2 + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'to_ring'):
result = f.rep.to_ring()
else: # pragma: no cover
raise OperationNotSupported(f, 'to_ring')
return f.per(result)
def to_field(f):
"""
Make the ground domain a field.
Examples
========
>>> from sympy import Poly, ZZ
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x, domain=ZZ).to_field()
Poly(x**2 + 1, x, domain='QQ')
"""
if hasattr(f.rep, 'to_field'):
result = f.rep.to_field()
else: # pragma: no cover
raise OperationNotSupported(f, 'to_field')
return f.per(result)
def to_exact(f):
"""
Make the ground domain exact.
Examples
========
>>> from sympy import Poly, RR
>>> from sympy.abc import x
>>> Poly(x**2 + 1.0, x, domain=RR).to_exact()
Poly(x**2 + 1, x, domain='QQ')
"""
if hasattr(f.rep, 'to_exact'):
result = f.rep.to_exact()
else: # pragma: no cover
raise OperationNotSupported(f, 'to_exact')
return f.per(result)
def retract(f, field=None):
"""
Recalculate the ground domain of a polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**2 + 1, x, domain='QQ[y]')
>>> f
Poly(x**2 + 1, x, domain='QQ[y]')
>>> f.retract()
Poly(x**2 + 1, x, domain='ZZ')
>>> f.retract(field=True)
Poly(x**2 + 1, x, domain='QQ')
"""
dom, rep = construct_domain(f.as_dict(zero=True),
field=field, composite=f.domain.is_Composite or None)
return f.from_dict(rep, f.gens, domain=dom)
def slice(f, x, m, n=None):
"""Take a continuous subsequence of terms of ``f``. """
if n is None:
j, m, n = 0, x, m
else:
j = f._gen_to_level(x)
m, n = int(m), int(n)
if hasattr(f.rep, 'slice'):
result = f.rep.slice(m, n, j)
else: # pragma: no cover
raise OperationNotSupported(f, 'slice')
return f.per(result)
def coeffs(f, order=None):
"""
Returns all non-zero coefficients from ``f`` in lex order.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x + 3, x).coeffs()
[1, 2, 3]
See Also
========
all_coeffs
coeff_monomial
nth
"""
return [f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order)]
def monoms(f, order=None):
"""
Returns all non-zero monomials from ``f`` in lex order.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms()
[(2, 0), (1, 2), (1, 1), (0, 1)]
See Also
========
all_monoms
"""
return f.rep.monoms(order=order)
def terms(f, order=None):
"""
Returns all non-zero terms from ``f`` in lex order.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms()
[((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)]
See Also
========
all_terms
"""
return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order)]
def all_coeffs(f):
"""
Returns all coefficients from a univariate polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_coeffs()
[1, 0, 2, -1]
"""
return [f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs()]
def all_monoms(f):
"""
Returns all monomials from a univariate polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_monoms()
[(3,), (2,), (1,), (0,)]
See Also
========
all_terms
"""
return f.rep.all_monoms()
def all_terms(f):
"""
Returns all terms from a univariate polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_terms()
[((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)]
"""
return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms()]
def termwise(f, func, *gens, **args):
"""
Apply a function to all terms of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> def func(k, coeff):
... k = k[0]
... return coeff//10**(2-k)
>>> Poly(x**2 + 20*x + 400).termwise(func)
Poly(x**2 + 2*x + 4, x, domain='ZZ')
"""
terms = {}
for monom, coeff in f.terms():
result = func(monom, coeff)
if isinstance(result, tuple):
monom, coeff = result
else:
coeff = result
if coeff:
if monom not in terms:
terms[monom] = coeff
else:
raise PolynomialError(
"%s monomial was generated twice" % monom)
return f.from_dict(terms, *(gens or f.gens), **args)
def length(f):
"""
Returns the number of non-zero terms in ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 2*x - 1).length()
3
"""
return len(f.as_dict())
def as_dict(f, native=False, zero=False):
"""
Switch to a ``dict`` representation.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict()
{(0, 1): -1, (1, 2): 2, (2, 0): 1}
"""
if native:
return f.rep.to_dict(zero=zero)
else:
return f.rep.to_sympy_dict(zero=zero)
def as_list(f, native=False):
"""Switch to a ``list`` representation. """
if native:
return f.rep.to_list()
else:
return f.rep.to_sympy_list()
def as_expr(f, *gens):
"""
Convert a Poly instance to an Expr instance.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2 + 2*x*y**2 - y, x, y)
>>> f.as_expr()
x**2 + 2*x*y**2 - y
>>> f.as_expr({x: 5})
10*y**2 - y + 25
>>> f.as_expr(5, 6)
379
"""
if not gens:
return f.expr
if len(gens) == 1 and isinstance(gens[0], dict):
mapping = gens[0]
gens = list(f.gens)
for gen, value in mapping.items():
try:
index = gens.index(gen)
except ValueError:
raise GeneratorsError(
"%s doesn't have %s as generator" % (f, gen))
else:
gens[index] = value
return basic_from_dict(f.rep.to_sympy_dict(), *gens)
def as_poly(self, *gens, **args):
"""Converts ``self`` to a polynomial or returns ``None``.
>>> from sympy import sin
>>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly())
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y))
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y))
None
"""
try:
poly = Poly(self, *gens, **args)
if not poly.is_Poly:
return None
else:
return poly
except PolynomialError:
return None
def lift(f):
"""
Convert algebraic coefficients to rationals.
Examples
========
>>> from sympy import Poly, I
>>> from sympy.abc import x
>>> Poly(x**2 + I*x + 1, x, extension=I).lift()
Poly(x**4 + 3*x**2 + 1, x, domain='QQ')
"""
if hasattr(f.rep, 'lift'):
result = f.rep.lift()
else: # pragma: no cover
raise OperationNotSupported(f, 'lift')
return f.per(result)
def deflate(f):
"""
Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate()
((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ'))
"""
if hasattr(f.rep, 'deflate'):
J, result = f.rep.deflate()
else: # pragma: no cover
raise OperationNotSupported(f, 'deflate')
return J, f.per(result)
def inject(f, front=False):
"""
Inject ground domain generators into ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2*y + x*y**3 + x*y + 1, x)
>>> f.inject()
Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ')
>>> f.inject(front=True)
Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ')
"""
dom = f.rep.dom
if dom.is_Numerical:
return f
elif not dom.is_Poly:
raise DomainError("Cannot inject generators over %s" % dom)
if hasattr(f.rep, 'inject'):
result = f.rep.inject(front=front)
else: # pragma: no cover
raise OperationNotSupported(f, 'inject')
if front:
gens = dom.symbols + f.gens
else:
gens = f.gens + dom.symbols
return f.new(result, *gens)
def eject(f, *gens):
"""
Eject selected generators into the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)
>>> f.eject(x)
Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
>>> f.eject(y)
Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
"""
dom = f.rep.dom
if not dom.is_Numerical:
raise DomainError("Cannot eject generators over %s" % dom)
k = len(gens)
if f.gens[:k] == gens:
_gens, front = f.gens[k:], True
elif f.gens[-k:] == gens:
_gens, front = f.gens[:-k], False
else:
raise NotImplementedError(
"can only eject front or back generators")
dom = dom.inject(*gens)
if hasattr(f.rep, 'eject'):
result = f.rep.eject(dom, front=front)
else: # pragma: no cover
raise OperationNotSupported(f, 'eject')
return f.new(result, *_gens)
def terms_gcd(f):
"""
Remove GCD of terms from the polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd()
((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ'))
"""
if hasattr(f.rep, 'terms_gcd'):
J, result = f.rep.terms_gcd()
else: # pragma: no cover
raise OperationNotSupported(f, 'terms_gcd')
return J, f.per(result)
def add_ground(f, coeff):
"""
Add an element of the ground domain to ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).add_ground(2)
Poly(x + 3, x, domain='ZZ')
"""
if hasattr(f.rep, 'add_ground'):
result = f.rep.add_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'add_ground')
return f.per(result)
def sub_ground(f, coeff):
"""
Subtract an element of the ground domain from ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).sub_ground(2)
Poly(x - 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'sub_ground'):
result = f.rep.sub_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'sub_ground')
return f.per(result)
def mul_ground(f, coeff):
"""
Multiply ``f`` by a an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).mul_ground(2)
Poly(2*x + 2, x, domain='ZZ')
"""
if hasattr(f.rep, 'mul_ground'):
result = f.rep.mul_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'mul_ground')
return f.per(result)
def quo_ground(f, coeff):
"""
Quotient of ``f`` by a an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x + 4).quo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> Poly(2*x + 3).quo_ground(2)
Poly(x + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'quo_ground'):
result = f.rep.quo_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'quo_ground')
return f.per(result)
def exquo_ground(f, coeff):
"""
Exact quotient of ``f`` by a an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x + 4).exquo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> Poly(2*x + 3).exquo_ground(2)
Traceback (most recent call last):
...
ExactQuotientFailed: 2 does not divide 3 in ZZ
"""
if hasattr(f.rep, 'exquo_ground'):
result = f.rep.exquo_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'exquo_ground')
return f.per(result)
def abs(f):
"""
Make all coefficients in ``f`` positive.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).abs()
Poly(x**2 + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'abs'):
result = f.rep.abs()
else: # pragma: no cover
raise OperationNotSupported(f, 'abs')
return f.per(result)
def neg(f):
"""
Negate all coefficients in ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).neg()
Poly(-x**2 + 1, x, domain='ZZ')
>>> -Poly(x**2 - 1, x)
Poly(-x**2 + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'neg'):
result = f.rep.neg()
else: # pragma: no cover
raise OperationNotSupported(f, 'neg')
return f.per(result)
def add(f, g):
"""
Add two polynomials ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).add(Poly(x - 2, x))
Poly(x**2 + x - 1, x, domain='ZZ')
>>> Poly(x**2 + 1, x) + Poly(x - 2, x)
Poly(x**2 + x - 1, x, domain='ZZ')
"""
g = sympify(g)
if not g.is_Poly:
return f.add_ground(g)
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'add'):
result = F.add(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'add')
return per(result)
def sub(f, g):
"""
Subtract two polynomials ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).sub(Poly(x - 2, x))
Poly(x**2 - x + 3, x, domain='ZZ')
>>> Poly(x**2 + 1, x) - Poly(x - 2, x)
Poly(x**2 - x + 3, x, domain='ZZ')
"""
g = sympify(g)
if not g.is_Poly:
return f.sub_ground(g)
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'sub'):
result = F.sub(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'sub')
return per(result)
def mul(f, g):
"""
Multiply two polynomials ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).mul(Poly(x - 2, x))
Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')
>>> Poly(x**2 + 1, x)*Poly(x - 2, x)
Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')
"""
g = sympify(g)
if not g.is_Poly:
return f.mul_ground(g)
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'mul'):
result = F.mul(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'mul')
return per(result)
def sqr(f):
"""
Square a polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x - 2, x).sqr()
Poly(x**2 - 4*x + 4, x, domain='ZZ')
>>> Poly(x - 2, x)**2
Poly(x**2 - 4*x + 4, x, domain='ZZ')
"""
if hasattr(f.rep, 'sqr'):
result = f.rep.sqr()
else: # pragma: no cover
raise OperationNotSupported(f, 'sqr')
return f.per(result)
def pow(f, n):
"""
Raise ``f`` to a non-negative power ``n``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x - 2, x).pow(3)
Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')
>>> Poly(x - 2, x)**3
Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')
"""
n = int(n)
if hasattr(f.rep, 'pow'):
result = f.rep.pow(n)
else: # pragma: no cover
raise OperationNotSupported(f, 'pow')
return f.per(result)
def pdiv(f, g):
"""
Polynomial pseudo-division of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x))
(Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ'))
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'pdiv'):
q, r = F.pdiv(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'pdiv')
return per(q), per(r)
def prem(f, g):
"""
Polynomial pseudo-remainder of ``f`` by ``g``.
Caveat: The function prem(f, g, x) can be safely used to compute
in Z[x] _only_ subresultant polynomial remainder sequences (prs's).
To safely compute Euclidean and Sturmian prs's in Z[x]
employ anyone of the corresponding functions found in
the module sympy.polys.subresultants_qq_zz. The functions
in the module with suffix _pg compute prs's in Z[x] employing
rem(f, g, x), whereas the functions with suffix _amv
compute prs's in Z[x] employing rem_z(f, g, x).
The function rem_z(f, g, x) differs from prem(f, g, x) in that
to compute the remainder polynomials in Z[x] it premultiplies
the divident times the absolute value of the leading coefficient
of the divisor raised to the power degree(f, x) - degree(g, x) + 1.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x))
Poly(20, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'prem'):
result = F.prem(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'prem')
return per(result)
def pquo(f, g):
"""
Polynomial pseudo-quotient of ``f`` by ``g``.
See the Caveat note in the function prem(f, g).
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x))
Poly(2*x + 4, x, domain='ZZ')
>>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x))
Poly(2*x + 2, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'pquo'):
result = F.pquo(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'pquo')
return per(result)
def pexquo(f, g):
"""
Polynomial exact pseudo-quotient of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x))
Poly(2*x + 2, x, domain='ZZ')
>>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x))
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'pexquo'):
try:
result = F.pexquo(G)
except ExactQuotientFailed as exc:
raise exc.new(f.as_expr(), g.as_expr())
else: # pragma: no cover
raise OperationNotSupported(f, 'pexquo')
return per(result)
def div(f, g, auto=True):
"""
Polynomial division with remainder of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x))
(Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ'))
>>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False)
(Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ'))
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.is_Ring and not dom.is_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'div'):
q, r = F.div(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'div')
if retract:
try:
Q, R = q.to_ring(), r.to_ring()
except CoercionFailed:
pass
else:
q, r = Q, R
return per(q), per(r)
def rem(f, g, auto=True):
"""
Computes the polynomial remainder of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x))
Poly(5, x, domain='ZZ')
>>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False)
Poly(x**2 + 1, x, domain='ZZ')
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.is_Ring and not dom.is_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'rem'):
r = F.rem(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'rem')
if retract:
try:
r = r.to_ring()
except CoercionFailed:
pass
return per(r)
def quo(f, g, auto=True):
"""
Computes polynomial quotient of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x))
Poly(1/2*x + 1, x, domain='QQ')
>>> Poly(x**2 - 1, x).quo(Poly(x - 1, x))
Poly(x + 1, x, domain='ZZ')
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.is_Ring and not dom.is_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'quo'):
q = F.quo(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'quo')
if retract:
try:
q = q.to_ring()
except CoercionFailed:
pass
return per(q)
def exquo(f, g, auto=True):
"""
Computes polynomial exact quotient of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x))
Poly(x + 1, x, domain='ZZ')
>>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x))
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.is_Ring and not dom.is_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'exquo'):
try:
q = F.exquo(G)
except ExactQuotientFailed as exc:
raise exc.new(f.as_expr(), g.as_expr())
else: # pragma: no cover
raise OperationNotSupported(f, 'exquo')
if retract:
try:
q = q.to_ring()
except CoercionFailed:
pass
return per(q)
def _gen_to_level(f, gen):
"""Returns level associated with the given generator. """
if isinstance(gen, int):
length = len(f.gens)
if -length <= gen < length:
if gen < 0:
return length + gen
else:
return gen
else:
raise PolynomialError("-%s <= gen < %s expected, got %s" %
(length, length, gen))
else:
try:
return f.gens.index(sympify(gen))
except ValueError:
raise PolynomialError(
"a valid generator expected, got %s" % gen)
def degree(f, gen=0):
"""
Returns degree of ``f`` in ``x_j``.
The degree of 0 is negative infinity.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).degree()
2
>>> Poly(x**2 + y*x + y, x, y).degree(y)
1
>>> Poly(0, x).degree()
-oo
"""
j = f._gen_to_level(gen)
if hasattr(f.rep, 'degree'):
return f.rep.degree(j)
else: # pragma: no cover
raise OperationNotSupported(f, 'degree')
def degree_list(f):
"""
Returns a list of degrees of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).degree_list()
(2, 1)
"""
if hasattr(f.rep, 'degree_list'):
return f.rep.degree_list()
else: # pragma: no cover
raise OperationNotSupported(f, 'degree_list')
def total_degree(f):
"""
Returns the total degree of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).total_degree()
2
>>> Poly(x + y**5, x, y).total_degree()
5
"""
if hasattr(f.rep, 'total_degree'):
return f.rep.total_degree()
else: # pragma: no cover
raise OperationNotSupported(f, 'total_degree')
def homogenize(f, s):
"""
Returns the homogeneous polynomial of ``f``.
A homogeneous polynomial is a polynomial whose all monomials with
non-zero coefficients have the same total degree. If you only
want to check if a polynomial is homogeneous, then use
:func:`Poly.is_homogeneous`. If you want not only to check if a
polynomial is homogeneous but also compute its homogeneous order,
then use :func:`Poly.homogeneous_order`.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> f = Poly(x**5 + 2*x**2*y**2 + 9*x*y**3)
>>> f.homogenize(z)
Poly(x**5 + 2*x**2*y**2*z + 9*x*y**3*z, x, y, z, domain='ZZ')
"""
if not isinstance(s, Symbol):
raise TypeError("``Symbol`` expected, got %s" % type(s))
if s in f.gens:
i = f.gens.index(s)
gens = f.gens
else:
i = len(f.gens)
gens = f.gens + (s,)
if hasattr(f.rep, 'homogenize'):
return f.per(f.rep.homogenize(i), gens=gens)
raise OperationNotSupported(f, 'homogeneous_order')
def homogeneous_order(f):
"""
Returns the homogeneous order of ``f``.
A homogeneous polynomial is a polynomial whose all monomials with
non-zero coefficients have the same total degree. This degree is
the homogeneous order of ``f``. If you only want to check if a
polynomial is homogeneous, then use :func:`Poly.is_homogeneous`.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4)
>>> f.homogeneous_order()
5
"""
if hasattr(f.rep, 'homogeneous_order'):
return f.rep.homogeneous_order()
else: # pragma: no cover
raise OperationNotSupported(f, 'homogeneous_order')
def LC(f, order=None):
"""
Returns the leading coefficient of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC()
4
"""
if order is not None:
return f.coeffs(order)[0]
if hasattr(f.rep, 'LC'):
result = f.rep.LC()
else: # pragma: no cover
raise OperationNotSupported(f, 'LC')
return f.rep.dom.to_sympy(result)
def TC(f):
"""
Returns the trailing coefficient of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x**2 + 3*x, x).TC()
0
"""
if hasattr(f.rep, 'TC'):
result = f.rep.TC()
else: # pragma: no cover
raise OperationNotSupported(f, 'TC')
return f.rep.dom.to_sympy(result)
def EC(f, order=None):
"""
Returns the last non-zero coefficient of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x**2 + 3*x, x).EC()
3
"""
if hasattr(f.rep, 'coeffs'):
return f.coeffs(order)[-1]
else: # pragma: no cover
raise OperationNotSupported(f, 'EC')
def coeff_monomial(f, monom):
"""
Returns the coefficient of ``monom`` in ``f`` if there, else None.
Examples
========
>>> from sympy import Poly, exp
>>> from sympy.abc import x, y
>>> p = Poly(24*x*y*exp(8) + 23*x, x, y)
>>> p.coeff_monomial(x)
23
>>> p.coeff_monomial(y)
0
>>> p.coeff_monomial(x*y)
24*exp(8)
Note that ``Expr.coeff()`` behaves differently, collecting terms
if possible; the Poly must be converted to an Expr to use that
method, however:
>>> p.as_expr().coeff(x)
24*y*exp(8) + 23
>>> p.as_expr().coeff(y)
24*x*exp(8)
>>> p.as_expr().coeff(x*y)
24*exp(8)
See Also
========
nth: more efficient query using exponents of the monomial's generators
"""
return f.nth(*Monomial(monom, f.gens).exponents)
def nth(f, *N):
"""
Returns the ``n``-th coefficient of ``f`` where ``N`` are the
exponents of the generators in the term of interest.
Examples
========
>>> from sympy import Poly, sqrt
>>> from sympy.abc import x, y
>>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2)
2
>>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2)
2
>>> Poly(4*sqrt(x)*y)
Poly(4*y*(sqrt(x)), y, sqrt(x), domain='ZZ')
>>> _.nth(1, 1)
4
See Also
========
coeff_monomial
"""
if hasattr(f.rep, 'nth'):
if len(N) != len(f.gens):
raise ValueError('exponent of each generator must be specified')
result = f.rep.nth(*list(map(int, N)))
else: # pragma: no cover
raise OperationNotSupported(f, 'nth')
return f.rep.dom.to_sympy(result)
def coeff(f, x, n=1, right=False):
# the semantics of coeff_monomial and Expr.coeff are different;
# if someone is working with a Poly, they should be aware of the
# differences and chose the method best suited for the query.
# Alternatively, a pure-polys method could be written here but
# at this time the ``right`` keyword would be ignored because Poly
# doesn't work with non-commutatives.
raise NotImplementedError(
'Either convert to Expr with `as_expr` method '
'to use Expr\'s coeff method or else use the '
'`coeff_monomial` method of Polys.')
def LM(f, order=None):
"""
Returns the leading monomial of ``f``.
The Leading monomial signifies the monomial having
the highest power of the principal generator in the
expression f.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM()
x**2*y**0
"""
return Monomial(f.monoms(order)[0], f.gens)
def EM(f, order=None):
"""
Returns the last non-zero monomial of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM()
x**0*y**1
"""
return Monomial(f.monoms(order)[-1], f.gens)
def LT(f, order=None):
"""
Returns the leading term of ``f``.
The Leading term signifies the term having
the highest power of the principal generator in the
expression f along with its coefficient.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT()
(x**2*y**0, 4)
"""
monom, coeff = f.terms(order)[0]
return Monomial(monom, f.gens), coeff
def ET(f, order=None):
"""
Returns the last non-zero term of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET()
(x**0*y**1, 3)
"""
monom, coeff = f.terms(order)[-1]
return Monomial(monom, f.gens), coeff
def max_norm(f):
"""
Returns maximum norm of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(-x**2 + 2*x - 3, x).max_norm()
3
"""
if hasattr(f.rep, 'max_norm'):
result = f.rep.max_norm()
else: # pragma: no cover
raise OperationNotSupported(f, 'max_norm')
return f.rep.dom.to_sympy(result)
def l1_norm(f):
"""
Returns l1 norm of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(-x**2 + 2*x - 3, x).l1_norm()
6
"""
if hasattr(f.rep, 'l1_norm'):
result = f.rep.l1_norm()
else: # pragma: no cover
raise OperationNotSupported(f, 'l1_norm')
return f.rep.dom.to_sympy(result)
def clear_denoms(self, convert=False):
"""
Clear denominators, but keep the ground domain.
Examples
========
>>> from sympy import Poly, S, QQ
>>> from sympy.abc import x
>>> f = Poly(x/2 + S(1)/3, x, domain=QQ)
>>> f.clear_denoms()
(6, Poly(3*x + 2, x, domain='QQ'))
>>> f.clear_denoms(convert=True)
(6, Poly(3*x + 2, x, domain='ZZ'))
"""
f = self
if not f.rep.dom.is_Field:
return S.One, f
dom = f.get_domain()
if dom.has_assoc_Ring:
dom = f.rep.dom.get_ring()
if hasattr(f.rep, 'clear_denoms'):
coeff, result = f.rep.clear_denoms()
else: # pragma: no cover
raise OperationNotSupported(f, 'clear_denoms')
coeff, f = dom.to_sympy(coeff), f.per(result)
if not convert or not dom.has_assoc_Ring:
return coeff, f
else:
return coeff, f.to_ring()
def rat_clear_denoms(self, g):
"""
Clear denominators in a rational function ``f/g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2/y + 1, x)
>>> g = Poly(x**3 + y, x)
>>> p, q = f.rat_clear_denoms(g)
>>> p
Poly(x**2 + y, x, domain='ZZ[y]')
>>> q
Poly(y*x**3 + y**2, x, domain='ZZ[y]')
"""
f = self
dom, per, f, g = f._unify(g)
f = per(f)
g = per(g)
if not (dom.is_Field and dom.has_assoc_Ring):
return f, g
a, f = f.clear_denoms(convert=True)
b, g = g.clear_denoms(convert=True)
f = f.mul_ground(b)
g = g.mul_ground(a)
return f, g
def integrate(self, *specs, **args):
"""
Computes indefinite integral of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x + 1, x).integrate()
Poly(1/3*x**3 + x**2 + x, x, domain='QQ')
>>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0))
Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ')
"""
f = self
if args.get('auto', True) and f.rep.dom.is_Ring:
f = f.to_field()
if hasattr(f.rep, 'integrate'):
if not specs:
return f.per(f.rep.integrate(m=1))
rep = f.rep
for spec in specs:
if isinstance(spec, tuple):
gen, m = spec
else:
gen, m = spec, 1
rep = rep.integrate(int(m), f._gen_to_level(gen))
return f.per(rep)
else: # pragma: no cover
raise OperationNotSupported(f, 'integrate')
def diff(f, *specs, **kwargs):
"""
Computes partial derivative of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x + 1, x).diff()
Poly(2*x + 2, x, domain='ZZ')
>>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1))
Poly(2*x*y, x, y, domain='ZZ')
"""
if not kwargs.get('evaluate', True):
return Derivative(f, *specs, **kwargs)
if hasattr(f.rep, 'diff'):
if not specs:
return f.per(f.rep.diff(m=1))
rep = f.rep
for spec in specs:
if isinstance(spec, tuple):
gen, m = spec
else:
gen, m = spec, 1
rep = rep.diff(int(m), f._gen_to_level(gen))
return f.per(rep)
else: # pragma: no cover
raise OperationNotSupported(f, 'diff')
_eval_derivative = diff
def eval(self, x, a=None, auto=True):
"""
Evaluate ``f`` at ``a`` in the given variable.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x**2 + 2*x + 3, x).eval(2)
11
>>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2)
Poly(5*y + 8, y, domain='ZZ')
>>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z)
>>> f.eval({x: 2})
Poly(5*y + 2*z + 6, y, z, domain='ZZ')
>>> f.eval({x: 2, y: 5})
Poly(2*z + 31, z, domain='ZZ')
>>> f.eval({x: 2, y: 5, z: 7})
45
>>> f.eval((2, 5))
Poly(2*z + 31, z, domain='ZZ')
>>> f(2, 5)
Poly(2*z + 31, z, domain='ZZ')
"""
f = self
if a is None:
if isinstance(x, dict):
mapping = x
for gen, value in mapping.items():
f = f.eval(gen, value)
return f
elif isinstance(x, (tuple, list)):
values = x
if len(values) > len(f.gens):
raise ValueError("too many values provided")
for gen, value in zip(f.gens, values):
f = f.eval(gen, value)
return f
else:
j, a = 0, x
else:
j = f._gen_to_level(x)
if not hasattr(f.rep, 'eval'): # pragma: no cover
raise OperationNotSupported(f, 'eval')
try:
result = f.rep.eval(a, j)
except CoercionFailed:
if not auto:
raise DomainError("Cannot evaluate at %s in %s" % (a, f.rep.dom))
else:
a_domain, [a] = construct_domain([a])
new_domain = f.get_domain().unify_with_symbols(a_domain, f.gens)
f = f.set_domain(new_domain)
a = new_domain.convert(a, a_domain)
result = f.rep.eval(a, j)
return f.per(result, remove=j)
def __call__(f, *values):
"""
Evaluate ``f`` at the give values.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z)
>>> f(2)
Poly(5*y + 2*z + 6, y, z, domain='ZZ')
>>> f(2, 5)
Poly(2*z + 31, z, domain='ZZ')
>>> f(2, 5, 7)
45
"""
return f.eval(values)
def half_gcdex(f, g, auto=True):
"""
Half extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
>>> g = x**3 + x**2 - 4*x - 4
>>> Poly(f).half_gcdex(Poly(g))
(Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ'))
"""
dom, per, F, G = f._unify(g)
if auto and dom.is_Ring:
F, G = F.to_field(), G.to_field()
if hasattr(f.rep, 'half_gcdex'):
s, h = F.half_gcdex(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'half_gcdex')
return per(s), per(h)
def gcdex(f, g, auto=True):
"""
Extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
>>> g = x**3 + x**2 - 4*x - 4
>>> Poly(f).gcdex(Poly(g))
(Poly(-1/5*x + 3/5, x, domain='QQ'),
Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'),
Poly(x + 1, x, domain='QQ'))
"""
dom, per, F, G = f._unify(g)
if auto and dom.is_Ring:
F, G = F.to_field(), G.to_field()
if hasattr(f.rep, 'gcdex'):
s, t, h = F.gcdex(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'gcdex')
return per(s), per(t), per(h)
def invert(f, g, auto=True):
"""
Invert ``f`` modulo ``g`` when possible.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x))
Poly(-4/3, x, domain='QQ')
>>> Poly(x**2 - 1, x).invert(Poly(x - 1, x))
Traceback (most recent call last):
...
NotInvertible: zero divisor
"""
dom, per, F, G = f._unify(g)
if auto and dom.is_Ring:
F, G = F.to_field(), G.to_field()
if hasattr(f.rep, 'invert'):
result = F.invert(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'invert')
return per(result)
def revert(f, n):
"""
Compute ``f**(-1)`` mod ``x**n``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(1, x).revert(2)
Poly(1, x, domain='ZZ')
>>> Poly(1 + x, x).revert(1)
Poly(1, x, domain='ZZ')
>>> Poly(x**2 - 2, x).revert(2)
Traceback (most recent call last):
...
NotReversible: only units are reversible in a ring
>>> Poly(1/x, x).revert(1)
Traceback (most recent call last):
...
PolynomialError: 1/x contains an element of the generators set
"""
if hasattr(f.rep, 'revert'):
result = f.rep.revert(int(n))
else: # pragma: no cover
raise OperationNotSupported(f, 'revert')
return f.per(result)
def subresultants(f, g):
"""
Computes the subresultant PRS of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x))
[Poly(x**2 + 1, x, domain='ZZ'),
Poly(x**2 - 1, x, domain='ZZ'),
Poly(-2, x, domain='ZZ')]
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'subresultants'):
result = F.subresultants(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'subresultants')
return list(map(per, result))
def resultant(f, g, includePRS=False):
"""
Computes the resultant of ``f`` and ``g`` via PRS.
If includePRS=True, it includes the subresultant PRS in the result.
Because the PRS is used to calculate the resultant, this is more
efficient than calling :func:`subresultants` separately.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**2 + 1, x)
>>> f.resultant(Poly(x**2 - 1, x))
4
>>> f.resultant(Poly(x**2 - 1, x), includePRS=True)
(4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'),
Poly(-2, x, domain='ZZ')])
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'resultant'):
if includePRS:
result, R = F.resultant(G, includePRS=includePRS)
else:
result = F.resultant(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'resultant')
if includePRS:
return (per(result, remove=0), list(map(per, R)))
return per(result, remove=0)
def discriminant(f):
"""
Computes the discriminant of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 2*x + 3, x).discriminant()
-8
"""
if hasattr(f.rep, 'discriminant'):
result = f.rep.discriminant()
else: # pragma: no cover
raise OperationNotSupported(f, 'discriminant')
return f.per(result, remove=0)
def dispersionset(f, g=None):
r"""Compute the *dispersion set* of two polynomials.
For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as:
.. math::
\operatorname{J}(f, g)
& := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\
& = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\}
For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`.
Examples
========
>>> from sympy import poly
>>> from sympy.polys.dispersion import dispersion, dispersionset
>>> from sympy.abc import x
Dispersion set and dispersion of a simple polynomial:
>>> fp = poly((x - 3)*(x + 3), x)
>>> sorted(dispersionset(fp))
[0, 6]
>>> dispersion(fp)
6
Note that the definition of the dispersion is not symmetric:
>>> fp = poly(x**4 - 3*x**2 + 1, x)
>>> gp = fp.shift(-3)
>>> sorted(dispersionset(fp, gp))
[2, 3, 4]
>>> dispersion(fp, gp)
4
>>> sorted(dispersionset(gp, fp))
[]
>>> dispersion(gp, fp)
-oo
Computing the dispersion also works over field extensions:
>>> from sympy import sqrt
>>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
>>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
>>> sorted(dispersionset(fp, gp))
[2]
>>> sorted(dispersionset(gp, fp))
[1, 4]
We can even perform the computations for polynomials
having symbolic coefficients:
>>> from sympy.abc import a
>>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
>>> sorted(dispersionset(fp))
[0, 1]
See Also
========
dispersion
References
==========
1. [ManWright94]_
2. [Koepf98]_
3. [Abramov71]_
4. [Man93]_
"""
from sympy.polys.dispersion import dispersionset
return dispersionset(f, g)
def dispersion(f, g=None):
r"""Compute the *dispersion* of polynomials.
For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as:
.. math::
\operatorname{dis}(f, g)
& := \max\{ J(f,g) \cup \{0\} \} \\
& = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \}
and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`.
Examples
========
>>> from sympy import poly
>>> from sympy.polys.dispersion import dispersion, dispersionset
>>> from sympy.abc import x
Dispersion set and dispersion of a simple polynomial:
>>> fp = poly((x - 3)*(x + 3), x)
>>> sorted(dispersionset(fp))
[0, 6]
>>> dispersion(fp)
6
Note that the definition of the dispersion is not symmetric:
>>> fp = poly(x**4 - 3*x**2 + 1, x)
>>> gp = fp.shift(-3)
>>> sorted(dispersionset(fp, gp))
[2, 3, 4]
>>> dispersion(fp, gp)
4
>>> sorted(dispersionset(gp, fp))
[]
>>> dispersion(gp, fp)
-oo
Computing the dispersion also works over field extensions:
>>> from sympy import sqrt
>>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
>>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
>>> sorted(dispersionset(fp, gp))
[2]
>>> sorted(dispersionset(gp, fp))
[1, 4]
We can even perform the computations for polynomials
having symbolic coefficients:
>>> from sympy.abc import a
>>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
>>> sorted(dispersionset(fp))
[0, 1]
See Also
========
dispersionset
References
==========
1. [ManWright94]_
2. [Koepf98]_
3. [Abramov71]_
4. [Man93]_
"""
from sympy.polys.dispersion import dispersion
return dispersion(f, g)
def cofactors(f, g):
"""
Returns the GCD of ``f`` and ``g`` and their cofactors.
Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and
``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors
of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x))
(Poly(x - 1, x, domain='ZZ'),
Poly(x + 1, x, domain='ZZ'),
Poly(x - 2, x, domain='ZZ'))
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'cofactors'):
h, cff, cfg = F.cofactors(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'cofactors')
return per(h), per(cff), per(cfg)
def gcd(f, g):
"""
Returns the polynomial GCD of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x))
Poly(x - 1, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'gcd'):
result = F.gcd(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'gcd')
return per(result)
def lcm(f, g):
"""
Returns polynomial LCM of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x))
Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'lcm'):
result = F.lcm(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'lcm')
return per(result)
def trunc(f, p):
"""
Reduce ``f`` modulo a constant ``p``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3)
Poly(-x**3 - x + 1, x, domain='ZZ')
"""
p = f.rep.dom.convert(p)
if hasattr(f.rep, 'trunc'):
result = f.rep.trunc(p)
else: # pragma: no cover
raise OperationNotSupported(f, 'trunc')
return f.per(result)
def monic(self, auto=True):
"""
Divides all coefficients by ``LC(f)``.
Examples
========
>>> from sympy import Poly, ZZ
>>> from sympy.abc import x
>>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic()
Poly(x**2 + 2*x + 3, x, domain='QQ')
>>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic()
Poly(x**2 + 4/3*x + 2/3, x, domain='QQ')
"""
f = self
if auto and f.rep.dom.is_Ring:
f = f.to_field()
if hasattr(f.rep, 'monic'):
result = f.rep.monic()
else: # pragma: no cover
raise OperationNotSupported(f, 'monic')
return f.per(result)
def content(f):
"""
Returns the GCD of polynomial coefficients.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(6*x**2 + 8*x + 12, x).content()
2
"""
if hasattr(f.rep, 'content'):
result = f.rep.content()
else: # pragma: no cover
raise OperationNotSupported(f, 'content')
return f.rep.dom.to_sympy(result)
def primitive(f):
"""
Returns the content and a primitive form of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 + 8*x + 12, x).primitive()
(2, Poly(x**2 + 4*x + 6, x, domain='ZZ'))
"""
if hasattr(f.rep, 'primitive'):
cont, result = f.rep.primitive()
else: # pragma: no cover
raise OperationNotSupported(f, 'primitive')
return f.rep.dom.to_sympy(cont), f.per(result)
def compose(f, g):
"""
Computes the functional composition of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + x, x).compose(Poly(x - 1, x))
Poly(x**2 - x, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'compose'):
result = F.compose(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'compose')
return per(result)
def decompose(f):
"""
Computes a functional decomposition of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose()
[Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')]
"""
if hasattr(f.rep, 'decompose'):
result = f.rep.decompose()
else: # pragma: no cover
raise OperationNotSupported(f, 'decompose')
return list(map(f.per, result))
def shift(f, a):
"""
Efficiently compute Taylor shift ``f(x + a)``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).shift(2)
Poly(x**2 + 2*x + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'shift'):
result = f.rep.shift(a)
else: # pragma: no cover
raise OperationNotSupported(f, 'shift')
return f.per(result)
def transform(f, p, q):
"""
Efficiently evaluate the functional transformation ``q**n * f(p/q)``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1, x), Poly(x - 1, x))
Poly(4, x, domain='ZZ')
"""
P, Q = p.unify(q)
F, P = f.unify(P)
F, Q = F.unify(Q)
if hasattr(F.rep, 'transform'):
result = F.rep.transform(P.rep, Q.rep)
else: # pragma: no cover
raise OperationNotSupported(F, 'transform')
return F.per(result)
def sturm(self, auto=True):
"""
Computes the Sturm sequence of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 - 2*x**2 + x - 3, x).sturm()
[Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'),
Poly(3*x**2 - 4*x + 1, x, domain='QQ'),
Poly(2/9*x + 25/9, x, domain='QQ'),
Poly(-2079/4, x, domain='QQ')]
"""
f = self
if auto and f.rep.dom.is_Ring:
f = f.to_field()
if hasattr(f.rep, 'sturm'):
result = f.rep.sturm()
else: # pragma: no cover
raise OperationNotSupported(f, 'sturm')
return list(map(f.per, result))
def gff_list(f):
"""
Computes greatest factorial factorization of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**5 + 2*x**4 - x**3 - 2*x**2
>>> Poly(f).gff_list()
[(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)]
"""
if hasattr(f.rep, 'gff_list'):
result = f.rep.gff_list()
else: # pragma: no cover
raise OperationNotSupported(f, 'gff_list')
return [(f.per(g), k) for g, k in result]
def norm(f):
"""
Computes the product, ``Norm(f)``, of the conjugates of
a polynomial ``f`` defined over a number field ``K``.
Examples
========
>>> from sympy import Poly, sqrt
>>> from sympy.abc import x
>>> a, b = sqrt(2), sqrt(3)
A polynomial over a quadratic extension.
Two conjugates x - a and x + a.
>>> f = Poly(x - a, x, extension=a)
>>> f.norm()
Poly(x**2 - 2, x, domain='QQ')
A polynomial over a quartic extension.
Four conjugates x - a, x - a, x + a and x + a.
>>> f = Poly(x - a, x, extension=(a, b))
>>> f.norm()
Poly(x**4 - 4*x**2 + 4, x, domain='QQ')
"""
if hasattr(f.rep, 'norm'):
r = f.rep.norm()
else: # pragma: no cover
raise OperationNotSupported(f, 'norm')
return f.per(r)
def sqf_norm(f):
"""
Computes square-free norm of ``f``.
Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and
``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``,
where ``a`` is the algebraic extension of the ground domain.
Examples
========
>>> from sympy import Poly, sqrt
>>> from sympy.abc import x
>>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm()
>>> s
1
>>> f
Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>')
>>> r
Poly(x**4 - 4*x**2 + 16, x, domain='QQ')
"""
if hasattr(f.rep, 'sqf_norm'):
s, g, r = f.rep.sqf_norm()
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_norm')
return s, f.per(g), f.per(r)
def sqf_part(f):
"""
Computes square-free part of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 - 3*x - 2, x).sqf_part()
Poly(x**2 - x - 2, x, domain='ZZ')
"""
if hasattr(f.rep, 'sqf_part'):
result = f.rep.sqf_part()
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_part')
return f.per(result)
def sqf_list(f, all=False):
"""
Returns a list of square-free factors of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16
>>> Poly(f).sqf_list()
(2, [(Poly(x + 1, x, domain='ZZ'), 2),
(Poly(x + 2, x, domain='ZZ'), 3)])
>>> Poly(f).sqf_list(all=True)
(2, [(Poly(1, x, domain='ZZ'), 1),
(Poly(x + 1, x, domain='ZZ'), 2),
(Poly(x + 2, x, domain='ZZ'), 3)])
"""
if hasattr(f.rep, 'sqf_list'):
coeff, factors = f.rep.sqf_list(all)
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_list')
return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors]
def sqf_list_include(f, all=False):
"""
Returns a list of square-free factors of ``f``.
Examples
========
>>> from sympy import Poly, expand
>>> from sympy.abc import x
>>> f = expand(2*(x + 1)**3*x**4)
>>> f
2*x**7 + 6*x**6 + 6*x**5 + 2*x**4
>>> Poly(f).sqf_list_include()
[(Poly(2, x, domain='ZZ'), 1),
(Poly(x + 1, x, domain='ZZ'), 3),
(Poly(x, x, domain='ZZ'), 4)]
>>> Poly(f).sqf_list_include(all=True)
[(Poly(2, x, domain='ZZ'), 1),
(Poly(1, x, domain='ZZ'), 2),
(Poly(x + 1, x, domain='ZZ'), 3),
(Poly(x, x, domain='ZZ'), 4)]
"""
if hasattr(f.rep, 'sqf_list_include'):
factors = f.rep.sqf_list_include(all)
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_list_include')
return [(f.per(g), k) for g, k in factors]
def factor_list(f):
"""
Returns a list of irreducible factors of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y
>>> Poly(f).factor_list()
(2, [(Poly(x + y, x, y, domain='ZZ'), 1),
(Poly(x**2 + 1, x, y, domain='ZZ'), 2)])
"""
if hasattr(f.rep, 'factor_list'):
try:
coeff, factors = f.rep.factor_list()
except DomainError:
return S.One, [(f, 1)]
else: # pragma: no cover
raise OperationNotSupported(f, 'factor_list')
return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors]
def factor_list_include(f):
"""
Returns a list of irreducible factors of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y
>>> Poly(f).factor_list_include()
[(Poly(2*x + 2*y, x, y, domain='ZZ'), 1),
(Poly(x**2 + 1, x, y, domain='ZZ'), 2)]
"""
if hasattr(f.rep, 'factor_list_include'):
try:
factors = f.rep.factor_list_include()
except DomainError:
return [(f, 1)]
else: # pragma: no cover
raise OperationNotSupported(f, 'factor_list_include')
return [(f.per(g), k) for g, k in factors]
def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False):
"""
Compute isolating intervals for roots of ``f``.
For real roots the Vincent-Akritas-Strzebonski (VAS) continued fractions method is used.
References
==========
.. [#] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root
Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005.
.. [#] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the
Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear
Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3, x).intervals()
[((-2, -1), 1), ((1, 2), 1)]
>>> Poly(x**2 - 3, x).intervals(eps=1e-2)
[((-26/15, -19/11), 1), ((19/11, 26/15), 1)]
"""
if eps is not None:
eps = QQ.convert(eps)
if eps <= 0:
raise ValueError("'eps' must be a positive rational")
if inf is not None:
inf = QQ.convert(inf)
if sup is not None:
sup = QQ.convert(sup)
if hasattr(f.rep, 'intervals'):
result = f.rep.intervals(
all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf)
else: # pragma: no cover
raise OperationNotSupported(f, 'intervals')
if sqf:
def _real(interval):
s, t = interval
return (QQ.to_sympy(s), QQ.to_sympy(t))
if not all:
return list(map(_real, result))
def _complex(rectangle):
(u, v), (s, t) = rectangle
return (QQ.to_sympy(u) + I*QQ.to_sympy(v),
QQ.to_sympy(s) + I*QQ.to_sympy(t))
real_part, complex_part = result
return list(map(_real, real_part)), list(map(_complex, complex_part))
else:
def _real(interval):
(s, t), k = interval
return ((QQ.to_sympy(s), QQ.to_sympy(t)), k)
if not all:
return list(map(_real, result))
def _complex(rectangle):
((u, v), (s, t)), k = rectangle
return ((QQ.to_sympy(u) + I*QQ.to_sympy(v),
QQ.to_sympy(s) + I*QQ.to_sympy(t)), k)
real_part, complex_part = result
return list(map(_real, real_part)), list(map(_complex, complex_part))
def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False):
"""
Refine an isolating interval of a root to the given precision.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2)
(19/11, 26/15)
"""
if check_sqf and not f.is_sqf:
raise PolynomialError("only square-free polynomials supported")
s, t = QQ.convert(s), QQ.convert(t)
if eps is not None:
eps = QQ.convert(eps)
if eps <= 0:
raise ValueError("'eps' must be a positive rational")
if steps is not None:
steps = int(steps)
elif eps is None:
steps = 1
if hasattr(f.rep, 'refine_root'):
S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast)
else: # pragma: no cover
raise OperationNotSupported(f, 'refine_root')
return QQ.to_sympy(S), QQ.to_sympy(T)
def count_roots(f, inf=None, sup=None):
"""
Return the number of roots of ``f`` in ``[inf, sup]`` interval.
Examples
========
>>> from sympy import Poly, I
>>> from sympy.abc import x
>>> Poly(x**4 - 4, x).count_roots(-3, 3)
2
>>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I)
1
"""
inf_real, sup_real = True, True
if inf is not None:
inf = sympify(inf)
if inf is S.NegativeInfinity:
inf = None
else:
re, im = inf.as_real_imag()
if not im:
inf = QQ.convert(inf)
else:
inf, inf_real = list(map(QQ.convert, (re, im))), False
if sup is not None:
sup = sympify(sup)
if sup is S.Infinity:
sup = None
else:
re, im = sup.as_real_imag()
if not im:
sup = QQ.convert(sup)
else:
sup, sup_real = list(map(QQ.convert, (re, im))), False
if inf_real and sup_real:
if hasattr(f.rep, 'count_real_roots'):
count = f.rep.count_real_roots(inf=inf, sup=sup)
else: # pragma: no cover
raise OperationNotSupported(f, 'count_real_roots')
else:
if inf_real and inf is not None:
inf = (inf, QQ.zero)
if sup_real and sup is not None:
sup = (sup, QQ.zero)
if hasattr(f.rep, 'count_complex_roots'):
count = f.rep.count_complex_roots(inf=inf, sup=sup)
else: # pragma: no cover
raise OperationNotSupported(f, 'count_complex_roots')
return Integer(count)
def root(f, index, radicals=True):
"""
Get an indexed root of a polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4)
>>> f.root(0)
-1/2
>>> f.root(1)
2
>>> f.root(2)
2
>>> f.root(3)
Traceback (most recent call last):
...
IndexError: root index out of [-3, 2] range, got 3
>>> Poly(x**5 + x + 1).root(0)
CRootOf(x**3 - x**2 + 1, 0)
"""
return sympy.polys.rootoftools.rootof(f, index, radicals=radicals)
def real_roots(f, multiple=True, radicals=True):
"""
Return a list of real roots with multiplicities.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots()
[-1/2, 2, 2]
>>> Poly(x**3 + x + 1).real_roots()
[CRootOf(x**3 + x + 1, 0)]
"""
reals = sympy.polys.rootoftools.CRootOf.real_roots(f, radicals=radicals)
if multiple:
return reals
else:
return group(reals, multiple=False)
def all_roots(f, multiple=True, radicals=True):
"""
Return a list of real and complex roots with multiplicities.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots()
[-1/2, 2, 2]
>>> Poly(x**3 + x + 1).all_roots()
[CRootOf(x**3 + x + 1, 0),
CRootOf(x**3 + x + 1, 1),
CRootOf(x**3 + x + 1, 2)]
"""
roots = sympy.polys.rootoftools.CRootOf.all_roots(f, radicals=radicals)
if multiple:
return roots
else:
return group(roots, multiple=False)
def nroots(f, n=15, maxsteps=50, cleanup=True):
"""
Compute numerical approximations of roots of ``f``.
Parameters
==========
n ... the number of digits to calculate
maxsteps ... the maximum number of iterations to do
If the accuracy `n` cannot be reached in `maxsteps`, it will raise an
exception. You need to rerun with higher maxsteps.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3).nroots(n=15)
[-1.73205080756888, 1.73205080756888]
>>> Poly(x**2 - 3).nroots(n=30)
[-1.73205080756887729352744634151, 1.73205080756887729352744634151]
"""
if f.is_multivariate:
raise MultivariatePolynomialError(
"Cannot compute numerical roots of %s" % f)
if f.degree() <= 0:
return []
# For integer and rational coefficients, convert them to integers only
# (for accuracy). Otherwise just try to convert the coefficients to
# mpmath.mpc and raise an exception if the conversion fails.
if f.rep.dom is ZZ:
coeffs = [int(coeff) for coeff in f.all_coeffs()]
elif f.rep.dom is QQ:
denoms = [coeff.q for coeff in f.all_coeffs()]
fac = ilcm(*denoms)
coeffs = [int(coeff*fac) for coeff in f.all_coeffs()]
else:
coeffs = [coeff.evalf(n=n).as_real_imag()
for coeff in f.all_coeffs()]
try:
coeffs = [mpmath.mpc(*coeff) for coeff in coeffs]
except TypeError:
raise DomainError("Numerical domain expected, got %s" % \
f.rep.dom)
dps = mpmath.mp.dps
mpmath.mp.dps = n
from sympy.functions.elementary.complexes import sign
try:
# We need to add extra precision to guard against losing accuracy.
# 10 times the degree of the polynomial seems to work well.
roots = mpmath.polyroots(coeffs, maxsteps=maxsteps,
cleanup=cleanup, error=False, extraprec=f.degree()*10)
# Mpmath puts real roots first, then complex ones (as does all_roots)
# so we make sure this convention holds here, too.
roots = list(map(sympify,
sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag)))))
except NoConvergence:
try:
# If roots did not converge try again with more extra precision.
roots = mpmath.polyroots(coeffs, maxsteps=maxsteps,
cleanup=cleanup, error=False, extraprec=f.degree()*15)
roots = list(map(sympify,
sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag)))))
except NoConvergence:
raise NoConvergence(
'convergence to root failed; try n < %s or maxsteps > %s' % (
n, maxsteps))
finally:
mpmath.mp.dps = dps
return roots
def ground_roots(f):
"""
Compute roots of ``f`` by factorization in the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots()
{0: 2, 1: 2}
"""
if f.is_multivariate:
raise MultivariatePolynomialError(
"Cannot compute ground roots of %s" % f)
roots = {}
for factor, k in f.factor_list()[1]:
if factor.is_linear:
a, b = factor.all_coeffs()
roots[-b/a] = k
return roots
def nth_power_roots_poly(f, n):
"""
Construct a polynomial with n-th powers of roots of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**4 - x**2 + 1)
>>> f.nth_power_roots_poly(2)
Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(3)
Poly(x**4 + 2*x**2 + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(4)
Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(12)
Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ')
"""
if f.is_multivariate:
raise MultivariatePolynomialError(
"must be a univariate polynomial")
N = sympify(n)
if N.is_Integer and N >= 1:
n = int(N)
else:
raise ValueError("'n' must an integer and n >= 1, got %s" % n)
x = f.gen
t = Dummy('t')
r = f.resultant(f.__class__.from_expr(x**n - t, x, t))
return r.replace(t, x)
def same_root(f, a, b):
"""
Decide whether two roots of this polynomial are equal.
Examples
========
>>> from sympy import Poly, cyclotomic_poly, exp, I, pi
>>> f = Poly(cyclotomic_poly(5))
>>> r0 = exp(2*I*pi/5)
>>> indices = [i for i, r in enumerate(f.all_roots()) if f.same_root(r, r0)]
>>> print(indices)
[3]
Raises
======
DomainError
If the domain of the polynomial is not :ref:`ZZ`, :ref:`QQ`,
:ref:`RR`, or :ref:`CC`.
MultivariatePolynomialError
If the polynomial is not univariate.
PolynomialError
If the polynomial is of degree < 2.
"""
if f.is_multivariate:
raise MultivariatePolynomialError(
"Must be a univariate polynomial")
dom_delta_sq = f.rep.mignotte_sep_bound_squared()
delta_sq = f.domain.get_field().to_sympy(dom_delta_sq)
# We have delta_sq = delta**2, where delta is a lower bound on the
# minimum separation between any two roots of this polynomial.
# Let eps = delta/3, and define eps_sq = eps**2 = delta**2/9.
eps_sq = delta_sq / 9
r, _, _, _ = evalf(1/eps_sq, 1, {})
n = fastlog(r)
# Then 2^n > 1/eps**2.
m = (n // 2) + (n % 2)
# Then 2^(-m) < eps.
ev = lambda x: quad_to_mpmath(_evalf_with_bounded_error(x, m=m))
# Then for any complex numbers a, b we will have
# |a - ev(a)| < eps and |b - ev(b)| < eps.
# So if |ev(a) - ev(b)|**2 < eps**2, then
# |ev(a) - ev(b)| < eps, hence |a - b| < 3*eps = delta.
A, B = ev(a), ev(b)
return (A.real - B.real)**2 + (A.imag - B.imag)**2 < eps_sq
def cancel(f, g, include=False):
"""
Cancel common factors in a rational function ``f/g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x))
(1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))
>>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True)
(Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))
"""
dom, per, F, G = f._unify(g)
if hasattr(F, 'cancel'):
result = F.cancel(G, include=include)
else: # pragma: no cover
raise OperationNotSupported(f, 'cancel')
if not include:
if dom.has_assoc_Ring:
dom = dom.get_ring()
cp, cq, p, q = result
cp = dom.to_sympy(cp)
cq = dom.to_sympy(cq)
return cp/cq, per(p), per(q)
else:
return tuple(map(per, result))
@property
def is_zero(f):
"""
Returns ``True`` if ``f`` is a zero polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(0, x).is_zero
True
>>> Poly(1, x).is_zero
False
"""
return f.rep.is_zero
@property
def is_one(f):
"""
Returns ``True`` if ``f`` is a unit polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(0, x).is_one
False
>>> Poly(1, x).is_one
True
"""
return f.rep.is_one
@property
def is_sqf(f):
"""
Returns ``True`` if ``f`` is a square-free polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).is_sqf
False
>>> Poly(x**2 - 1, x).is_sqf
True
"""
return f.rep.is_sqf
@property
def is_monic(f):
"""
Returns ``True`` if the leading coefficient of ``f`` is one.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 2, x).is_monic
True
>>> Poly(2*x + 2, x).is_monic
False
"""
return f.rep.is_monic
@property
def is_primitive(f):
"""
Returns ``True`` if GCD of the coefficients of ``f`` is one.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 + 6*x + 12, x).is_primitive
False
>>> Poly(x**2 + 3*x + 6, x).is_primitive
True
"""
return f.rep.is_primitive
@property
def is_ground(f):
"""
Returns ``True`` if ``f`` is an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x, x).is_ground
False
>>> Poly(2, x).is_ground
True
>>> Poly(y, x).is_ground
True
"""
return f.rep.is_ground
@property
def is_linear(f):
"""
Returns ``True`` if ``f`` is linear in all its variables.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x + y + 2, x, y).is_linear
True
>>> Poly(x*y + 2, x, y).is_linear
False
"""
return f.rep.is_linear
@property
def is_quadratic(f):
"""
Returns ``True`` if ``f`` is quadratic in all its variables.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x*y + 2, x, y).is_quadratic
True
>>> Poly(x*y**2 + 2, x, y).is_quadratic
False
"""
return f.rep.is_quadratic
@property
def is_monomial(f):
"""
Returns ``True`` if ``f`` is zero or has only one term.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(3*x**2, x).is_monomial
True
>>> Poly(3*x**2 + 1, x).is_monomial
False
"""
return f.rep.is_monomial
@property
def is_homogeneous(f):
"""
Returns ``True`` if ``f`` is a homogeneous polynomial.
A homogeneous polynomial is a polynomial whose all monomials with
non-zero coefficients have the same total degree. If you want not
only to check if a polynomial is homogeneous but also compute its
homogeneous order, then use :func:`Poly.homogeneous_order`.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x*y, x, y).is_homogeneous
True
>>> Poly(x**3 + x*y, x, y).is_homogeneous
False
"""
return f.rep.is_homogeneous
@property
def is_irreducible(f):
"""
Returns ``True`` if ``f`` has no factors over its domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible
True
>>> Poly(x**2 + 1, x, modulus=2).is_irreducible
False
"""
return f.rep.is_irreducible
@property
def is_univariate(f):
"""
Returns ``True`` if ``f`` is a univariate polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x + 1, x).is_univariate
True
>>> Poly(x*y**2 + x*y + 1, x, y).is_univariate
False
>>> Poly(x*y**2 + x*y + 1, x).is_univariate
True
>>> Poly(x**2 + x + 1, x, y).is_univariate
False
"""
return len(f.gens) == 1
@property
def is_multivariate(f):
"""
Returns ``True`` if ``f`` is a multivariate polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x + 1, x).is_multivariate
False
>>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate
True
>>> Poly(x*y**2 + x*y + 1, x).is_multivariate
False
>>> Poly(x**2 + x + 1, x, y).is_multivariate
True
"""
return len(f.gens) != 1
@property
def is_cyclotomic(f):
"""
Returns ``True`` if ``f`` is a cyclotomic polnomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1
>>> Poly(f).is_cyclotomic
False
>>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1
>>> Poly(g).is_cyclotomic
True
"""
return f.rep.is_cyclotomic
def __abs__(f):
return f.abs()
def __neg__(f):
return f.neg()
@_polifyit
def __add__(f, g):
return f.add(g)
@_polifyit
def __radd__(f, g):
return g.add(f)
@_polifyit
def __sub__(f, g):
return f.sub(g)
@_polifyit
def __rsub__(f, g):
return g.sub(f)
@_polifyit
def __mul__(f, g):
return f.mul(g)
@_polifyit
def __rmul__(f, g):
return g.mul(f)
@_sympifyit('n', NotImplemented)
def __pow__(f, n):
if n.is_Integer and n >= 0:
return f.pow(n)
else:
return NotImplemented
@_polifyit
def __divmod__(f, g):
return f.div(g)
@_polifyit
def __rdivmod__(f, g):
return g.div(f)
@_polifyit
def __mod__(f, g):
return f.rem(g)
@_polifyit
def __rmod__(f, g):
return g.rem(f)
@_polifyit
def __floordiv__(f, g):
return f.quo(g)
@_polifyit
def __rfloordiv__(f, g):
return g.quo(f)
@_sympifyit('g', NotImplemented)
def __truediv__(f, g):
return f.as_expr()/g.as_expr()
@_sympifyit('g', NotImplemented)
def __rtruediv__(f, g):
return g.as_expr()/f.as_expr()
@_sympifyit('other', NotImplemented)
def __eq__(self, other):
f, g = self, other
if not g.is_Poly:
try:
g = f.__class__(g, f.gens, domain=f.get_domain())
except (PolynomialError, DomainError, CoercionFailed):
return False
if f.gens != g.gens:
return False
if f.rep.dom != g.rep.dom:
return False
return f.rep == g.rep
@_sympifyit('g', NotImplemented)
def __ne__(f, g):
return not f == g
def __bool__(f):
return not f.is_zero
def eq(f, g, strict=False):
if not strict:
return f == g
else:
return f._strict_eq(sympify(g))
def ne(f, g, strict=False):
return not f.eq(g, strict=strict)
def _strict_eq(f, g):
return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True)
@public
class PurePoly(Poly):
"""Class for representing pure polynomials. """
def _hashable_content(self):
"""Allow SymPy to hash Poly instances. """
return (self.rep,)
def __hash__(self):
return super().__hash__()
@property
def free_symbols(self):
"""
Free symbols of a polynomial.
Examples
========
>>> from sympy import PurePoly
>>> from sympy.abc import x, y
>>> PurePoly(x**2 + 1).free_symbols
set()
>>> PurePoly(x**2 + y).free_symbols
set()
>>> PurePoly(x**2 + y, x).free_symbols
{y}
"""
return self.free_symbols_in_domain
@_sympifyit('other', NotImplemented)
def __eq__(self, other):
f, g = self, other
if not g.is_Poly:
try:
g = f.__class__(g, f.gens, domain=f.get_domain())
except (PolynomialError, DomainError, CoercionFailed):
return False
if len(f.gens) != len(g.gens):
return False
if f.rep.dom != g.rep.dom:
try:
dom = f.rep.dom.unify(g.rep.dom, f.gens)
except UnificationFailed:
return False
f = f.set_domain(dom)
g = g.set_domain(dom)
return f.rep == g.rep
def _strict_eq(f, g):
return isinstance(g, f.__class__) and f.rep.eq(g.rep, strict=True)
def _unify(f, g):
g = sympify(g)
if not g.is_Poly:
try:
return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g))
except CoercionFailed:
raise UnificationFailed("Cannot unify %s with %s" % (f, g))
if len(f.gens) != len(g.gens):
raise UnificationFailed("Cannot unify %s with %s" % (f, g))
if not (isinstance(f.rep, DMP) and isinstance(g.rep, DMP)):
raise UnificationFailed("Cannot unify %s with %s" % (f, g))
cls = f.__class__
gens = f.gens
dom = f.rep.dom.unify(g.rep.dom, gens)
F = f.rep.convert(dom)
G = g.rep.convert(dom)
def per(rep, dom=dom, gens=gens, remove=None):
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return dom.to_sympy(rep)
return cls.new(rep, *gens)
return dom, per, F, G
@public
def poly_from_expr(expr, *gens, **args):
"""Construct a polynomial from an expression. """
opt = options.build_options(gens, args)
return _poly_from_expr(expr, opt)
def _poly_from_expr(expr, opt):
"""Construct a polynomial from an expression. """
orig, expr = expr, sympify(expr)
if not isinstance(expr, Basic):
raise PolificationFailed(opt, orig, expr)
elif expr.is_Poly:
poly = expr.__class__._from_poly(expr, opt)
opt.gens = poly.gens
opt.domain = poly.domain
if opt.polys is None:
opt.polys = True
return poly, opt
elif opt.expand:
expr = expr.expand()
rep, opt = _dict_from_expr(expr, opt)
if not opt.gens:
raise PolificationFailed(opt, orig, expr)
monoms, coeffs = list(zip(*list(rep.items())))
domain = opt.domain
if domain is None:
opt.domain, coeffs = construct_domain(coeffs, opt=opt)
else:
coeffs = list(map(domain.from_sympy, coeffs))
rep = dict(list(zip(monoms, coeffs)))
poly = Poly._from_dict(rep, opt)
if opt.polys is None:
opt.polys = False
return poly, opt
@public
def parallel_poly_from_expr(exprs, *gens, **args):
"""Construct polynomials from expressions. """
opt = options.build_options(gens, args)
return _parallel_poly_from_expr(exprs, opt)
def _parallel_poly_from_expr(exprs, opt):
"""Construct polynomials from expressions. """
if len(exprs) == 2:
f, g = exprs
if isinstance(f, Poly) and isinstance(g, Poly):
f = f.__class__._from_poly(f, opt)
g = g.__class__._from_poly(g, opt)
f, g = f.unify(g)
opt.gens = f.gens
opt.domain = f.domain
if opt.polys is None:
opt.polys = True
return [f, g], opt
origs, exprs = list(exprs), []
_exprs, _polys = [], []
failed = False
for i, expr in enumerate(origs):
expr = sympify(expr)
if isinstance(expr, Basic):
if expr.is_Poly:
_polys.append(i)
else:
_exprs.append(i)
if opt.expand:
expr = expr.expand()
else:
failed = True
exprs.append(expr)
if failed:
raise PolificationFailed(opt, origs, exprs, True)
if _polys:
# XXX: this is a temporary solution
for i in _polys:
exprs[i] = exprs[i].as_expr()
reps, opt = _parallel_dict_from_expr(exprs, opt)
if not opt.gens:
raise PolificationFailed(opt, origs, exprs, True)
from sympy.functions.elementary.piecewise import Piecewise
for k in opt.gens:
if isinstance(k, Piecewise):
raise PolynomialError("Piecewise generators do not make sense")
coeffs_list, lengths = [], []
all_monoms = []
all_coeffs = []
for rep in reps:
monoms, coeffs = list(zip(*list(rep.items())))
coeffs_list.extend(coeffs)
all_monoms.append(monoms)
lengths.append(len(coeffs))
domain = opt.domain
if domain is None:
opt.domain, coeffs_list = construct_domain(coeffs_list, opt=opt)
else:
coeffs_list = list(map(domain.from_sympy, coeffs_list))
for k in lengths:
all_coeffs.append(coeffs_list[:k])
coeffs_list = coeffs_list[k:]
polys = []
for monoms, coeffs in zip(all_monoms, all_coeffs):
rep = dict(list(zip(monoms, coeffs)))
poly = Poly._from_dict(rep, opt)
polys.append(poly)
if opt.polys is None:
opt.polys = bool(_polys)
return polys, opt
def _update_args(args, key, value):
"""Add a new ``(key, value)`` pair to arguments ``dict``. """
args = dict(args)
if key not in args:
args[key] = value
return args
@public
def degree(f, gen=0):
"""
Return the degree of ``f`` in the given variable.
The degree of 0 is negative infinity.
Examples
========
>>> from sympy import degree
>>> from sympy.abc import x, y
>>> degree(x**2 + y*x + 1, gen=x)
2
>>> degree(x**2 + y*x + 1, gen=y)
1
>>> degree(0, x)
-oo
See also
========
sympy.polys.polytools.Poly.total_degree
degree_list
"""
f = sympify(f, strict=True)
gen_is_Num = sympify(gen, strict=True).is_Number
if f.is_Poly:
p = f
isNum = p.as_expr().is_Number
else:
isNum = f.is_Number
if not isNum:
if gen_is_Num:
p, _ = poly_from_expr(f)
else:
p, _ = poly_from_expr(f, gen)
if isNum:
return S.Zero if f else S.NegativeInfinity
if not gen_is_Num:
if f.is_Poly and gen not in p.gens:
# try recast without explicit gens
p, _ = poly_from_expr(f.as_expr())
if gen not in p.gens:
return S.Zero
elif not f.is_Poly and len(f.free_symbols) > 1:
raise TypeError(filldedent('''
A symbolic generator of interest is required for a multivariate
expression like func = %s, e.g. degree(func, gen = %s) instead of
degree(func, gen = %s).
''' % (f, next(ordered(f.free_symbols)), gen)))
result = p.degree(gen)
return Integer(result) if isinstance(result, int) else S.NegativeInfinity
@public
def total_degree(f, *gens):
"""
Return the total_degree of ``f`` in the given variables.
Examples
========
>>> from sympy import total_degree, Poly
>>> from sympy.abc import x, y
>>> total_degree(1)
0
>>> total_degree(x + x*y)
2
>>> total_degree(x + x*y, x)
1
If the expression is a Poly and no variables are given
then the generators of the Poly will be used:
>>> p = Poly(x + x*y, y)
>>> total_degree(p)
1
To deal with the underlying expression of the Poly, convert
it to an Expr:
>>> total_degree(p.as_expr())
2
This is done automatically if any variables are given:
>>> total_degree(p, x)
1
See also
========
degree
"""
p = sympify(f)
if p.is_Poly:
p = p.as_expr()
if p.is_Number:
rv = 0
else:
if f.is_Poly:
gens = gens or f.gens
rv = Poly(p, gens).total_degree()
return Integer(rv)
@public
def degree_list(f, *gens, **args):
"""
Return a list of degrees of ``f`` in all variables.
Examples
========
>>> from sympy import degree_list
>>> from sympy.abc import x, y
>>> degree_list(x**2 + y*x + 1)
(2, 1)
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('degree_list', 1, exc)
degrees = F.degree_list()
return tuple(map(Integer, degrees))
@public
def LC(f, *gens, **args):
"""
Return the leading coefficient of ``f``.
Examples
========
>>> from sympy import LC
>>> from sympy.abc import x, y
>>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y)
4
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('LC', 1, exc)
return F.LC(order=opt.order)
@public
def LM(f, *gens, **args):
"""
Return the leading monomial of ``f``.
Examples
========
>>> from sympy import LM
>>> from sympy.abc import x, y
>>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y)
x**2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('LM', 1, exc)
monom = F.LM(order=opt.order)
return monom.as_expr()
@public
def LT(f, *gens, **args):
"""
Return the leading term of ``f``.
Examples
========
>>> from sympy import LT
>>> from sympy.abc import x, y
>>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y)
4*x**2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('LT', 1, exc)
monom, coeff = F.LT(order=opt.order)
return coeff*monom.as_expr()
@public
def pdiv(f, g, *gens, **args):
"""
Compute polynomial pseudo-division of ``f`` and ``g``.
Examples
========
>>> from sympy import pdiv
>>> from sympy.abc import x
>>> pdiv(x**2 + 1, 2*x - 4)
(2*x + 4, 20)
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('pdiv', 2, exc)
q, r = F.pdiv(G)
if not opt.polys:
return q.as_expr(), r.as_expr()
else:
return q, r
@public
def prem(f, g, *gens, **args):
"""
Compute polynomial pseudo-remainder of ``f`` and ``g``.
Examples
========
>>> from sympy import prem
>>> from sympy.abc import x
>>> prem(x**2 + 1, 2*x - 4)
20
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('prem', 2, exc)
r = F.prem(G)
if not opt.polys:
return r.as_expr()
else:
return r
@public
def pquo(f, g, *gens, **args):
"""
Compute polynomial pseudo-quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import pquo
>>> from sympy.abc import x
>>> pquo(x**2 + 1, 2*x - 4)
2*x + 4
>>> pquo(x**2 - 1, 2*x - 1)
2*x + 1
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('pquo', 2, exc)
try:
q = F.pquo(G)
except ExactQuotientFailed:
raise ExactQuotientFailed(f, g)
if not opt.polys:
return q.as_expr()
else:
return q
@public
def pexquo(f, g, *gens, **args):
"""
Compute polynomial exact pseudo-quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import pexquo
>>> from sympy.abc import x
>>> pexquo(x**2 - 1, 2*x - 2)
2*x + 2
>>> pexquo(x**2 + 1, 2*x - 4)
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('pexquo', 2, exc)
q = F.pexquo(G)
if not opt.polys:
return q.as_expr()
else:
return q
@public
def div(f, g, *gens, **args):
"""
Compute polynomial division of ``f`` and ``g``.
Examples
========
>>> from sympy import div, ZZ, QQ
>>> from sympy.abc import x
>>> div(x**2 + 1, 2*x - 4, domain=ZZ)
(0, x**2 + 1)
>>> div(x**2 + 1, 2*x - 4, domain=QQ)
(x/2 + 1, 5)
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('div', 2, exc)
q, r = F.div(G, auto=opt.auto)
if not opt.polys:
return q.as_expr(), r.as_expr()
else:
return q, r
@public
def rem(f, g, *gens, **args):
"""
Compute polynomial remainder of ``f`` and ``g``.
Examples
========
>>> from sympy import rem, ZZ, QQ
>>> from sympy.abc import x
>>> rem(x**2 + 1, 2*x - 4, domain=ZZ)
x**2 + 1
>>> rem(x**2 + 1, 2*x - 4, domain=QQ)
5
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('rem', 2, exc)
r = F.rem(G, auto=opt.auto)
if not opt.polys:
return r.as_expr()
else:
return r
@public
def quo(f, g, *gens, **args):
"""
Compute polynomial quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import quo
>>> from sympy.abc import x
>>> quo(x**2 + 1, 2*x - 4)
x/2 + 1
>>> quo(x**2 - 1, x - 1)
x + 1
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('quo', 2, exc)
q = F.quo(G, auto=opt.auto)
if not opt.polys:
return q.as_expr()
else:
return q
@public
def exquo(f, g, *gens, **args):
"""
Compute polynomial exact quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import exquo
>>> from sympy.abc import x
>>> exquo(x**2 - 1, x - 1)
x + 1
>>> exquo(x**2 + 1, 2*x - 4)
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('exquo', 2, exc)
q = F.exquo(G, auto=opt.auto)
if not opt.polys:
return q.as_expr()
else:
return q
@public
def half_gcdex(f, g, *gens, **args):
"""
Half extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``.
Examples
========
>>> from sympy import half_gcdex
>>> from sympy.abc import x
>>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
(3/5 - x/5, x + 1)
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
s, h = domain.half_gcdex(a, b)
except NotImplementedError:
raise ComputationFailed('half_gcdex', 2, exc)
else:
return domain.to_sympy(s), domain.to_sympy(h)
s, h = F.half_gcdex(G, auto=opt.auto)
if not opt.polys:
return s.as_expr(), h.as_expr()
else:
return s, h
@public
def gcdex(f, g, *gens, **args):
"""
Extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.
Examples
========
>>> from sympy import gcdex
>>> from sympy.abc import x
>>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
(3/5 - x/5, x**2/5 - 6*x/5 + 2, x + 1)
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
s, t, h = domain.gcdex(a, b)
except NotImplementedError:
raise ComputationFailed('gcdex', 2, exc)
else:
return domain.to_sympy(s), domain.to_sympy(t), domain.to_sympy(h)
s, t, h = F.gcdex(G, auto=opt.auto)
if not opt.polys:
return s.as_expr(), t.as_expr(), h.as_expr()
else:
return s, t, h
@public
def invert(f, g, *gens, **args):
"""
Invert ``f`` modulo ``g`` when possible.
Examples
========
>>> from sympy import invert, S, mod_inverse
>>> from sympy.abc import x
>>> invert(x**2 - 1, 2*x - 1)
-4/3
>>> invert(x**2 - 1, x - 1)
Traceback (most recent call last):
...
NotInvertible: zero divisor
For more efficient inversion of Rationals,
use the :obj:`~.mod_inverse` function:
>>> mod_inverse(3, 5)
2
>>> (S(2)/5).invert(S(7)/3)
5/2
See Also
========
sympy.core.numbers.mod_inverse
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
return domain.to_sympy(domain.invert(a, b))
except NotImplementedError:
raise ComputationFailed('invert', 2, exc)
h = F.invert(G, auto=opt.auto)
if not opt.polys:
return h.as_expr()
else:
return h
@public
def subresultants(f, g, *gens, **args):
"""
Compute subresultant PRS of ``f`` and ``g``.
Examples
========
>>> from sympy import subresultants
>>> from sympy.abc import x
>>> subresultants(x**2 + 1, x**2 - 1)
[x**2 + 1, x**2 - 1, -2]
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('subresultants', 2, exc)
result = F.subresultants(G)
if not opt.polys:
return [r.as_expr() for r in result]
else:
return result
@public
def resultant(f, g, *gens, includePRS=False, **args):
"""
Compute resultant of ``f`` and ``g``.
Examples
========
>>> from sympy import resultant
>>> from sympy.abc import x
>>> resultant(x**2 + 1, x**2 - 1)
4
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('resultant', 2, exc)
if includePRS:
result, R = F.resultant(G, includePRS=includePRS)
else:
result = F.resultant(G)
if not opt.polys:
if includePRS:
return result.as_expr(), [r.as_expr() for r in R]
return result.as_expr()
else:
if includePRS:
return result, R
return result
@public
def discriminant(f, *gens, **args):
"""
Compute discriminant of ``f``.
Examples
========
>>> from sympy import discriminant
>>> from sympy.abc import x
>>> discriminant(x**2 + 2*x + 3)
-8
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('discriminant', 1, exc)
result = F.discriminant()
if not opt.polys:
return result.as_expr()
else:
return result
@public
def cofactors(f, g, *gens, **args):
"""
Compute GCD and cofactors of ``f`` and ``g``.
Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and
``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors
of ``f`` and ``g``.
Examples
========
>>> from sympy import cofactors
>>> from sympy.abc import x
>>> cofactors(x**2 - 1, x**2 - 3*x + 2)
(x - 1, x + 1, x - 2)
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
h, cff, cfg = domain.cofactors(a, b)
except NotImplementedError:
raise ComputationFailed('cofactors', 2, exc)
else:
return domain.to_sympy(h), domain.to_sympy(cff), domain.to_sympy(cfg)
h, cff, cfg = F.cofactors(G)
if not opt.polys:
return h.as_expr(), cff.as_expr(), cfg.as_expr()
else:
return h, cff, cfg
@public
def gcd_list(seq, *gens, **args):
"""
Compute GCD of a list of polynomials.
Examples
========
>>> from sympy import gcd_list
>>> from sympy.abc import x
>>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
x - 1
"""
seq = sympify(seq)
def try_non_polynomial_gcd(seq):
if not gens and not args:
domain, numbers = construct_domain(seq)
if not numbers:
return domain.zero
elif domain.is_Numerical:
result, numbers = numbers[0], numbers[1:]
for number in numbers:
result = domain.gcd(result, number)
if domain.is_one(result):
break
return domain.to_sympy(result)
return None
result = try_non_polynomial_gcd(seq)
if result is not None:
return result
options.allowed_flags(args, ['polys'])
try:
polys, opt = parallel_poly_from_expr(seq, *gens, **args)
# gcd for domain Q[irrational] (purely algebraic irrational)
if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq):
a = seq[-1]
lst = [ (a/elt).ratsimp() for elt in seq[:-1] ]
if all(frc.is_rational for frc in lst):
lc = 1
for frc in lst:
lc = lcm(lc, frc.as_numer_denom()[0])
# abs ensures that the gcd is always non-negative
return abs(a/lc)
except PolificationFailed as exc:
result = try_non_polynomial_gcd(exc.exprs)
if result is not None:
return result
else:
raise ComputationFailed('gcd_list', len(seq), exc)
if not polys:
if not opt.polys:
return S.Zero
else:
return Poly(0, opt=opt)
result, polys = polys[0], polys[1:]
for poly in polys:
result = result.gcd(poly)
if result.is_one:
break
if not opt.polys:
return result.as_expr()
else:
return result
@public
def gcd(f, g=None, *gens, **args):
"""
Compute GCD of ``f`` and ``g``.
Examples
========
>>> from sympy import gcd
>>> from sympy.abc import x
>>> gcd(x**2 - 1, x**2 - 3*x + 2)
x - 1
"""
if hasattr(f, '__iter__'):
if g is not None:
gens = (g,) + gens
return gcd_list(f, *gens, **args)
elif g is None:
raise TypeError("gcd() takes 2 arguments or a sequence of arguments")
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
# gcd for domain Q[irrational] (purely algebraic irrational)
a, b = map(sympify, (f, g))
if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational:
frc = (a/b).ratsimp()
if frc.is_rational:
# abs ensures that the returned gcd is always non-negative
return abs(a/frc.as_numer_denom()[0])
except PolificationFailed as exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
return domain.to_sympy(domain.gcd(a, b))
except NotImplementedError:
raise ComputationFailed('gcd', 2, exc)
result = F.gcd(G)
if not opt.polys:
return result.as_expr()
else:
return result
@public
def lcm_list(seq, *gens, **args):
"""
Compute LCM of a list of polynomials.
Examples
========
>>> from sympy import lcm_list
>>> from sympy.abc import x
>>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
x**5 - x**4 - 2*x**3 - x**2 + x + 2
"""
seq = sympify(seq)
def try_non_polynomial_lcm(seq) -> Optional[Expr]:
if not gens and not args:
domain, numbers = construct_domain(seq)
if not numbers:
return domain.to_sympy(domain.one)
elif domain.is_Numerical:
result, numbers = numbers[0], numbers[1:]
for number in numbers:
result = domain.lcm(result, number)
return domain.to_sympy(result)
return None
result = try_non_polynomial_lcm(seq)
if result is not None:
return result
options.allowed_flags(args, ['polys'])
try:
polys, opt = parallel_poly_from_expr(seq, *gens, **args)
# lcm for domain Q[irrational] (purely algebraic irrational)
if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq):
a = seq[-1]
lst = [ (a/elt).ratsimp() for elt in seq[:-1] ]
if all(frc.is_rational for frc in lst):
lc = 1
for frc in lst:
lc = lcm(lc, frc.as_numer_denom()[1])
return a*lc
except PolificationFailed as exc:
result = try_non_polynomial_lcm(exc.exprs)
if result is not None:
return result
else:
raise ComputationFailed('lcm_list', len(seq), exc)
if not polys:
if not opt.polys:
return S.One
else:
return Poly(1, opt=opt)
result, polys = polys[0], polys[1:]
for poly in polys:
result = result.lcm(poly)
if not opt.polys:
return result.as_expr()
else:
return result
@public
def lcm(f, g=None, *gens, **args):
"""
Compute LCM of ``f`` and ``g``.
Examples
========
>>> from sympy import lcm
>>> from sympy.abc import x
>>> lcm(x**2 - 1, x**2 - 3*x + 2)
x**3 - 2*x**2 - x + 2
"""
if hasattr(f, '__iter__'):
if g is not None:
gens = (g,) + gens
return lcm_list(f, *gens, **args)
elif g is None:
raise TypeError("lcm() takes 2 arguments or a sequence of arguments")
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
# lcm for domain Q[irrational] (purely algebraic irrational)
a, b = map(sympify, (f, g))
if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational:
frc = (a/b).ratsimp()
if frc.is_rational:
return a*frc.as_numer_denom()[1]
except PolificationFailed as exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
return domain.to_sympy(domain.lcm(a, b))
except NotImplementedError:
raise ComputationFailed('lcm', 2, exc)
result = F.lcm(G)
if not opt.polys:
return result.as_expr()
else:
return result
@public
def terms_gcd(f, *gens, **args):
"""
Remove GCD of terms from ``f``.
If the ``deep`` flag is True, then the arguments of ``f`` will have
terms_gcd applied to them.
If a fraction is factored out of ``f`` and ``f`` is an Add, then
an unevaluated Mul will be returned so that automatic simplification
does not redistribute it. The hint ``clear``, when set to False, can be
used to prevent such factoring when all coefficients are not fractions.
Examples
========
>>> from sympy import terms_gcd, cos
>>> from sympy.abc import x, y
>>> terms_gcd(x**6*y**2 + x**3*y, x, y)
x**3*y*(x**3*y + 1)
The default action of polys routines is to expand the expression
given to them. terms_gcd follows this behavior:
>>> terms_gcd((3+3*x)*(x+x*y))
3*x*(x*y + x + y + 1)
If this is not desired then the hint ``expand`` can be set to False.
In this case the expression will be treated as though it were comprised
of one or more terms:
>>> terms_gcd((3+3*x)*(x+x*y), expand=False)
(3*x + 3)*(x*y + x)
In order to traverse factors of a Mul or the arguments of other
functions, the ``deep`` hint can be used:
>>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True)
3*x*(x + 1)*(y + 1)
>>> terms_gcd(cos(x + x*y), deep=True)
cos(x*(y + 1))
Rationals are factored out by default:
>>> terms_gcd(x + y/2)
(2*x + y)/2
Only the y-term had a coefficient that was a fraction; if one
does not want to factor out the 1/2 in cases like this, the
flag ``clear`` can be set to False:
>>> terms_gcd(x + y/2, clear=False)
x + y/2
>>> terms_gcd(x*y/2 + y**2, clear=False)
y*(x/2 + y)
The ``clear`` flag is ignored if all coefficients are fractions:
>>> terms_gcd(x/3 + y/2, clear=False)
(2*x + 3*y)/6
See Also
========
sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms
"""
orig = sympify(f)
if isinstance(f, Equality):
return Equality(*(terms_gcd(s, *gens, **args) for s in [f.lhs, f.rhs]))
elif isinstance(f, Relational):
raise TypeError("Inequalities cannot be used with terms_gcd. Found: %s" %(f,))
if not isinstance(f, Expr) or f.is_Atom:
return orig
if args.get('deep', False):
new = f.func(*[terms_gcd(a, *gens, **args) for a in f.args])
args.pop('deep')
args['expand'] = False
return terms_gcd(new, *gens, **args)
clear = args.pop('clear', True)
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
return exc.expr
J, f = F.terms_gcd()
if opt.domain.is_Ring:
if opt.domain.is_Field:
denom, f = f.clear_denoms(convert=True)
coeff, f = f.primitive()
if opt.domain.is_Field:
coeff /= denom
else:
coeff = S.One
term = Mul(*[x**j for x, j in zip(f.gens, J)])
if coeff == 1:
coeff = S.One
if term == 1:
return orig
if clear:
return _keep_coeff(coeff, term*f.as_expr())
# base the clearing on the form of the original expression, not
# the (perhaps) Mul that we have now
coeff, f = _keep_coeff(coeff, f.as_expr(), clear=False).as_coeff_Mul()
return _keep_coeff(coeff, term*f, clear=False)
@public
def trunc(f, p, *gens, **args):
"""
Reduce ``f`` modulo a constant ``p``.
Examples
========
>>> from sympy import trunc
>>> from sympy.abc import x
>>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3)
-x**3 - x + 1
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('trunc', 1, exc)
result = F.trunc(sympify(p))
if not opt.polys:
return result.as_expr()
else:
return result
@public
def monic(f, *gens, **args):
"""
Divide all coefficients of ``f`` by ``LC(f)``.
Examples
========
>>> from sympy import monic
>>> from sympy.abc import x
>>> monic(3*x**2 + 4*x + 2)
x**2 + 4*x/3 + 2/3
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('monic', 1, exc)
result = F.monic(auto=opt.auto)
if not opt.polys:
return result.as_expr()
else:
return result
@public
def content(f, *gens, **args):
"""
Compute GCD of coefficients of ``f``.
Examples
========
>>> from sympy import content
>>> from sympy.abc import x
>>> content(6*x**2 + 8*x + 12)
2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('content', 1, exc)
return F.content()
@public
def primitive(f, *gens, **args):
"""
Compute content and the primitive form of ``f``.
Examples
========
>>> from sympy.polys.polytools import primitive
>>> from sympy.abc import x
>>> primitive(6*x**2 + 8*x + 12)
(2, 3*x**2 + 4*x + 6)
>>> eq = (2 + 2*x)*x + 2
Expansion is performed by default:
>>> primitive(eq)
(2, x**2 + x + 1)
Set ``expand`` to False to shut this off. Note that the
extraction will not be recursive; use the as_content_primitive method
for recursive, non-destructive Rational extraction.
>>> primitive(eq, expand=False)
(1, x*(2*x + 2) + 2)
>>> eq.as_content_primitive()
(2, x*(x + 1) + 1)
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('primitive', 1, exc)
cont, result = F.primitive()
if not opt.polys:
return cont, result.as_expr()
else:
return cont, result
@public
def compose(f, g, *gens, **args):
"""
Compute functional composition ``f(g)``.
Examples
========
>>> from sympy import compose
>>> from sympy.abc import x
>>> compose(x**2 + x, x - 1)
x**2 - x
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('compose', 2, exc)
result = F.compose(G)
if not opt.polys:
return result.as_expr()
else:
return result
@public
def decompose(f, *gens, **args):
"""
Compute functional decomposition of ``f``.
Examples
========
>>> from sympy import decompose
>>> from sympy.abc import x
>>> decompose(x**4 + 2*x**3 - x - 1)
[x**2 - x - 1, x**2 + x]
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('decompose', 1, exc)
result = F.decompose()
if not opt.polys:
return [r.as_expr() for r in result]
else:
return result
@public
def sturm(f, *gens, **args):
"""
Compute Sturm sequence of ``f``.
Examples
========
>>> from sympy import sturm
>>> from sympy.abc import x
>>> sturm(x**3 - 2*x**2 + x - 3)
[x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4]
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('sturm', 1, exc)
result = F.sturm(auto=opt.auto)
if not opt.polys:
return [r.as_expr() for r in result]
else:
return result
@public
def gff_list(f, *gens, **args):
"""
Compute a list of greatest factorial factors of ``f``.
Note that the input to ff() and rf() should be Poly instances to use the
definitions here.
Examples
========
>>> from sympy import gff_list, ff, Poly
>>> from sympy.abc import x
>>> f = Poly(x**5 + 2*x**4 - x**3 - 2*x**2, x)
>>> gff_list(f)
[(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)]
>>> (ff(Poly(x), 1)*ff(Poly(x + 2), 4)) == f
True
>>> f = Poly(x**12 + 6*x**11 - 11*x**10 - 56*x**9 + 220*x**8 + 208*x**7 - \
1401*x**6 + 1090*x**5 + 2715*x**4 - 6720*x**3 - 1092*x**2 + 5040*x, x)
>>> gff_list(f)
[(Poly(x**3 + 7, x, domain='ZZ'), 2), (Poly(x**2 + 5*x, x, domain='ZZ'), 3)]
>>> ff(Poly(x**3 + 7, x), 2)*ff(Poly(x**2 + 5*x, x), 3) == f
True
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('gff_list', 1, exc)
factors = F.gff_list()
if not opt.polys:
return [(g.as_expr(), k) for g, k in factors]
else:
return factors
@public
def gff(f, *gens, **args):
"""Compute greatest factorial factorization of ``f``. """
raise NotImplementedError('symbolic falling factorial')
@public
def sqf_norm(f, *gens, **args):
"""
Compute square-free norm of ``f``.
Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and
``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``,
where ``a`` is the algebraic extension of the ground domain.
Examples
========
>>> from sympy import sqf_norm, sqrt
>>> from sympy.abc import x
>>> sqf_norm(x**2 + 1, extension=[sqrt(3)])
(1, x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16)
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('sqf_norm', 1, exc)
s, g, r = F.sqf_norm()
if not opt.polys:
return Integer(s), g.as_expr(), r.as_expr()
else:
return Integer(s), g, r
@public
def sqf_part(f, *gens, **args):
"""
Compute square-free part of ``f``.
Examples
========
>>> from sympy import sqf_part
>>> from sympy.abc import x
>>> sqf_part(x**3 - 3*x - 2)
x**2 - x - 2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('sqf_part', 1, exc)
result = F.sqf_part()
if not opt.polys:
return result.as_expr()
else:
return result
def _sorted_factors(factors, method):
"""Sort a list of ``(expr, exp)`` pairs. """
if method == 'sqf':
def key(obj):
poly, exp = obj
rep = poly.rep.rep
return (exp, len(rep), len(poly.gens), str(poly.domain), rep)
else:
def key(obj):
poly, exp = obj
rep = poly.rep.rep
return (len(rep), len(poly.gens), exp, str(poly.domain), rep)
return sorted(factors, key=key)
def _factors_product(factors):
"""Multiply a list of ``(expr, exp)`` pairs. """
return Mul(*[f.as_expr()**k for f, k in factors])
def _symbolic_factor_list(expr, opt, method):
"""Helper function for :func:`_symbolic_factor`. """
coeff, factors = S.One, []
args = [i._eval_factor() if hasattr(i, '_eval_factor') else i
for i in Mul.make_args(expr)]
for arg in args:
if arg.is_Number or (isinstance(arg, Expr) and pure_complex(arg)):
coeff *= arg
continue
elif arg.is_Pow and arg.base != S.Exp1:
base, exp = arg.args
if base.is_Number and exp.is_Number:
coeff *= arg
continue
if base.is_Number:
factors.append((base, exp))
continue
else:
base, exp = arg, S.One
try:
poly, _ = _poly_from_expr(base, opt)
except PolificationFailed as exc:
factors.append((exc.expr, exp))
else:
func = getattr(poly, method + '_list')
_coeff, _factors = func()
if _coeff is not S.One:
if exp.is_Integer:
coeff *= _coeff**exp
elif _coeff.is_positive:
factors.append((_coeff, exp))
else:
_factors.append((_coeff, S.One))
if exp is S.One:
factors.extend(_factors)
elif exp.is_integer:
factors.extend([(f, k*exp) for f, k in _factors])
else:
other = []
for f, k in _factors:
if f.as_expr().is_positive:
factors.append((f, k*exp))
else:
other.append((f, k))
factors.append((_factors_product(other), exp))
if method == 'sqf':
factors = [(reduce(mul, (f for f, _ in factors if _ == k)), k)
for k in {i for _, i in factors}]
return coeff, factors
def _symbolic_factor(expr, opt, method):
"""Helper function for :func:`_factor`. """
if isinstance(expr, Expr):
if hasattr(expr,'_eval_factor'):
return expr._eval_factor()
coeff, factors = _symbolic_factor_list(together(expr, fraction=opt['fraction']), opt, method)
return _keep_coeff(coeff, _factors_product(factors))
elif hasattr(expr, 'args'):
return expr.func(*[_symbolic_factor(arg, opt, method) for arg in expr.args])
elif hasattr(expr, '__iter__'):
return expr.__class__([_symbolic_factor(arg, opt, method) for arg in expr])
else:
return expr
def _generic_factor_list(expr, gens, args, method):
"""Helper function for :func:`sqf_list` and :func:`factor_list`. """
options.allowed_flags(args, ['frac', 'polys'])
opt = options.build_options(gens, args)
expr = sympify(expr)
if isinstance(expr, (Expr, Poly)):
if isinstance(expr, Poly):
numer, denom = expr, 1
else:
numer, denom = together(expr).as_numer_denom()
cp, fp = _symbolic_factor_list(numer, opt, method)
cq, fq = _symbolic_factor_list(denom, opt, method)
if fq and not opt.frac:
raise PolynomialError("a polynomial expected, got %s" % expr)
_opt = opt.clone(dict(expand=True))
for factors in (fp, fq):
for i, (f, k) in enumerate(factors):
if not f.is_Poly:
f, _ = _poly_from_expr(f, _opt)
factors[i] = (f, k)
fp = _sorted_factors(fp, method)
fq = _sorted_factors(fq, method)
if not opt.polys:
fp = [(f.as_expr(), k) for f, k in fp]
fq = [(f.as_expr(), k) for f, k in fq]
coeff = cp/cq
if not opt.frac:
return coeff, fp
else:
return coeff, fp, fq
else:
raise PolynomialError("a polynomial expected, got %s" % expr)
def _generic_factor(expr, gens, args, method):
"""Helper function for :func:`sqf` and :func:`factor`. """
fraction = args.pop('fraction', True)
options.allowed_flags(args, [])
opt = options.build_options(gens, args)
opt['fraction'] = fraction
return _symbolic_factor(sympify(expr), opt, method)
def to_rational_coeffs(f):
"""
try to transform a polynomial to have rational coefficients
try to find a transformation ``x = alpha*y``
``f(x) = lc*alpha**n * g(y)`` where ``g`` is a polynomial with
rational coefficients, ``lc`` the leading coefficient.
If this fails, try ``x = y + beta``
``f(x) = g(y)``
Returns ``None`` if ``g`` not found;
``(lc, alpha, None, g)`` in case of rescaling
``(None, None, beta, g)`` in case of translation
Notes
=====
Currently it transforms only polynomials without roots larger than 2.
Examples
========
>>> from sympy import sqrt, Poly, simplify
>>> from sympy.polys.polytools import to_rational_coeffs
>>> from sympy.abc import x
>>> p = Poly(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}), x, domain='EX')
>>> lc, r, _, g = to_rational_coeffs(p)
>>> lc, r
(7 + 5*sqrt(2), 2 - 2*sqrt(2))
>>> g
Poly(x**3 + x**2 - 1/4*x - 1/4, x, domain='QQ')
>>> r1 = simplify(1/r)
>>> Poly(lc*r**3*(g.as_expr()).subs({x:x*r1}), x, domain='EX') == p
True
"""
from sympy.simplify.simplify import simplify
def _try_rescale(f, f1=None):
"""
try rescaling ``x -> alpha*x`` to convert f to a polynomial
with rational coefficients.
Returns ``alpha, f``; if the rescaling is successful,
``alpha`` is the rescaling factor, and ``f`` is the rescaled
polynomial; else ``alpha`` is ``None``.
"""
if not len(f.gens) == 1 or not (f.gens[0]).is_Atom:
return None, f
n = f.degree()
lc = f.LC()
f1 = f1 or f1.monic()
coeffs = f1.all_coeffs()[1:]
coeffs = [simplify(coeffx) for coeffx in coeffs]
if len(coeffs) > 1 and coeffs[-2]:
rescale1_x = simplify(coeffs[-2]/coeffs[-1])
coeffs1 = []
for i in range(len(coeffs)):
coeffx = simplify(coeffs[i]*rescale1_x**(i + 1))
if not coeffx.is_rational:
break
coeffs1.append(coeffx)
else:
rescale_x = simplify(1/rescale1_x)
x = f.gens[0]
v = [x**n]
for i in range(1, n + 1):
v.append(coeffs1[i - 1]*x**(n - i))
f = Add(*v)
f = Poly(f)
return lc, rescale_x, f
return None
def _try_translate(f, f1=None):
"""
try translating ``x -> x + alpha`` to convert f to a polynomial
with rational coefficients.
Returns ``alpha, f``; if the translating is successful,
``alpha`` is the translating factor, and ``f`` is the shifted
polynomial; else ``alpha`` is ``None``.
"""
if not len(f.gens) == 1 or not (f.gens[0]).is_Atom:
return None, f
n = f.degree()
f1 = f1 or f1.monic()
coeffs = f1.all_coeffs()[1:]
c = simplify(coeffs[0])
if c.is_Add and not c.is_rational:
rat, nonrat = sift(c.args,
lambda z: z.is_rational is True, binary=True)
alpha = -c.func(*nonrat)/n
f2 = f1.shift(alpha)
return alpha, f2
return None
def _has_square_roots(p):
"""
Return True if ``f`` is a sum with square roots but no other root
"""
coeffs = p.coeffs()
has_sq = False
for y in coeffs:
for x in Add.make_args(y):
f = Factors(x).factors
r = [wx.q for b, wx in f.items() if
b.is_number and wx.is_Rational and wx.q >= 2]
if not r:
continue
if min(r) == 2:
has_sq = True
if max(r) > 2:
return False
return has_sq
if f.get_domain().is_EX and _has_square_roots(f):
f1 = f.monic()
r = _try_rescale(f, f1)
if r:
return r[0], r[1], None, r[2]
else:
r = _try_translate(f, f1)
if r:
return None, None, r[0], r[1]
return None
def _torational_factor_list(p, x):
"""
helper function to factor polynomial using to_rational_coeffs
Examples
========
>>> from sympy.polys.polytools import _torational_factor_list
>>> from sympy.abc import x
>>> from sympy import sqrt, expand, Mul
>>> p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}))
>>> factors = _torational_factor_list(p, x); factors
(-2, [(-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)])
>>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p
True
>>> p = expand(((x**2-1)*(x-2)).subs({x:x + sqrt(2)}))
>>> factors = _torational_factor_list(p, x); factors
(1, [(x - 2 + sqrt(2), 1), (x - 1 + sqrt(2), 1), (x + 1 + sqrt(2), 1)])
>>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p
True
"""
from sympy.simplify.simplify import simplify
p1 = Poly(p, x, domain='EX')
n = p1.degree()
res = to_rational_coeffs(p1)
if not res:
return None
lc, r, t, g = res
factors = factor_list(g.as_expr())
if lc:
c = simplify(factors[0]*lc*r**n)
r1 = simplify(1/r)
a = []
for z in factors[1:][0]:
a.append((simplify(z[0].subs({x: x*r1})), z[1]))
else:
c = factors[0]
a = []
for z in factors[1:][0]:
a.append((z[0].subs({x: x - t}), z[1]))
return (c, a)
@public
def sqf_list(f, *gens, **args):
"""
Compute a list of square-free factors of ``f``.
Examples
========
>>> from sympy import sqf_list
>>> from sympy.abc import x
>>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
(2, [(x + 1, 2), (x + 2, 3)])
"""
return _generic_factor_list(f, gens, args, method='sqf')
@public
def sqf(f, *gens, **args):
"""
Compute square-free factorization of ``f``.
Examples
========
>>> from sympy import sqf
>>> from sympy.abc import x
>>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
2*(x + 1)**2*(x + 2)**3
"""
return _generic_factor(f, gens, args, method='sqf')
@public
def factor_list(f, *gens, **args):
"""
Compute a list of irreducible factors of ``f``.
Examples
========
>>> from sympy import factor_list
>>> from sympy.abc import x, y
>>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
(2, [(x + y, 1), (x**2 + 1, 2)])
"""
return _generic_factor_list(f, gens, args, method='factor')
@public
def factor(f, *gens, deep=False, **args):
"""
Compute the factorization of expression, ``f``, into irreducibles. (To
factor an integer into primes, use ``factorint``.)
There two modes implemented: symbolic and formal. If ``f`` is not an
instance of :class:`Poly` and generators are not specified, then the
former mode is used. Otherwise, the formal mode is used.
In symbolic mode, :func:`factor` will traverse the expression tree and
factor its components without any prior expansion, unless an instance
of :class:`~.Add` is encountered (in this case formal factorization is
used). This way :func:`factor` can handle large or symbolic exponents.
By default, the factorization is computed over the rationals. To factor
over other domain, e.g. an algebraic or finite field, use appropriate
options: ``extension``, ``modulus`` or ``domain``.
Examples
========
>>> from sympy import factor, sqrt, exp
>>> from sympy.abc import x, y
>>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
2*(x + y)*(x**2 + 1)**2
>>> factor(x**2 + 1)
x**2 + 1
>>> factor(x**2 + 1, modulus=2)
(x + 1)**2
>>> factor(x**2 + 1, gaussian=True)
(x - I)*(x + I)
>>> factor(x**2 - 2, extension=sqrt(2))
(x - sqrt(2))*(x + sqrt(2))
>>> factor((x**2 - 1)/(x**2 + 4*x + 4))
(x - 1)*(x + 1)/(x + 2)**2
>>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1))
(x + 2)**20000000*(x**2 + 1)
By default, factor deals with an expression as a whole:
>>> eq = 2**(x**2 + 2*x + 1)
>>> factor(eq)
2**(x**2 + 2*x + 1)
If the ``deep`` flag is True then subexpressions will
be factored:
>>> factor(eq, deep=True)
2**((x + 1)**2)
If the ``fraction`` flag is False then rational expressions
will not be combined. By default it is True.
>>> factor(5*x + 3*exp(2 - 7*x), deep=True)
(5*x*exp(7*x) + 3*exp(2))*exp(-7*x)
>>> factor(5*x + 3*exp(2 - 7*x), deep=True, fraction=False)
5*x + 3*exp(2)*exp(-7*x)
See Also
========
sympy.ntheory.factor_.factorint
"""
f = sympify(f)
if deep:
def _try_factor(expr):
"""
Factor, but avoid changing the expression when unable to.
"""
fac = factor(expr, *gens, **args)
if fac.is_Mul or fac.is_Pow:
return fac
return expr
f = bottom_up(f, _try_factor)
# clean up any subexpressions that may have been expanded
# while factoring out a larger expression
partials = {}
muladd = f.atoms(Mul, Add)
for p in muladd:
fac = factor(p, *gens, **args)
if (fac.is_Mul or fac.is_Pow) and fac != p:
partials[p] = fac
return f.xreplace(partials)
try:
return _generic_factor(f, gens, args, method='factor')
except PolynomialError as msg:
if not f.is_commutative:
return factor_nc(f)
else:
raise PolynomialError(msg)
@public
def intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False):
"""
Compute isolating intervals for roots of ``f``.
Examples
========
>>> from sympy import intervals
>>> from sympy.abc import x
>>> intervals(x**2 - 3)
[((-2, -1), 1), ((1, 2), 1)]
>>> intervals(x**2 - 3, eps=1e-2)
[((-26/15, -19/11), 1), ((19/11, 26/15), 1)]
"""
if not hasattr(F, '__iter__'):
try:
F = Poly(F)
except GeneratorsNeeded:
return []
return F.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf)
else:
polys, opt = parallel_poly_from_expr(F, domain='QQ')
if len(opt.gens) > 1:
raise MultivariatePolynomialError
for i, poly in enumerate(polys):
polys[i] = poly.rep.rep
if eps is not None:
eps = opt.domain.convert(eps)
if eps <= 0:
raise ValueError("'eps' must be a positive rational")
if inf is not None:
inf = opt.domain.convert(inf)
if sup is not None:
sup = opt.domain.convert(sup)
intervals = dup_isolate_real_roots_list(polys, opt.domain,
eps=eps, inf=inf, sup=sup, strict=strict, fast=fast)
result = []
for (s, t), indices in intervals:
s, t = opt.domain.to_sympy(s), opt.domain.to_sympy(t)
result.append(((s, t), indices))
return result
@public
def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False):
"""
Refine an isolating interval of a root to the given precision.
Examples
========
>>> from sympy import refine_root
>>> from sympy.abc import x
>>> refine_root(x**2 - 3, 1, 2, eps=1e-2)
(19/11, 26/15)
"""
try:
F = Poly(f)
if not isinstance(f, Poly) and not F.gen.is_Symbol:
# root of sin(x) + 1 is -1 but when someone
# passes an Expr instead of Poly they may not expect
# that the generator will be sin(x), not x
raise PolynomialError("generator must be a Symbol")
except GeneratorsNeeded:
raise PolynomialError(
"Cannot refine a root of %s, not a polynomial" % f)
return F.refine_root(s, t, eps=eps, steps=steps, fast=fast, check_sqf=check_sqf)
@public
def count_roots(f, inf=None, sup=None):
"""
Return the number of roots of ``f`` in ``[inf, sup]`` interval.
If one of ``inf`` or ``sup`` is complex, it will return the number of roots
in the complex rectangle with corners at ``inf`` and ``sup``.
Examples
========
>>> from sympy import count_roots, I
>>> from sympy.abc import x
>>> count_roots(x**4 - 4, -3, 3)
2
>>> count_roots(x**4 - 4, 0, 1 + 3*I)
1
"""
try:
F = Poly(f, greedy=False)
if not isinstance(f, Poly) and not F.gen.is_Symbol:
# root of sin(x) + 1 is -1 but when someone
# passes an Expr instead of Poly they may not expect
# that the generator will be sin(x), not x
raise PolynomialError("generator must be a Symbol")
except GeneratorsNeeded:
raise PolynomialError("Cannot count roots of %s, not a polynomial" % f)
return F.count_roots(inf=inf, sup=sup)
@public
def real_roots(f, multiple=True):
"""
Return a list of real roots with multiplicities of ``f``.
Examples
========
>>> from sympy import real_roots
>>> from sympy.abc import x
>>> real_roots(2*x**3 - 7*x**2 + 4*x + 4)
[-1/2, 2, 2]
"""
try:
F = Poly(f, greedy=False)
if not isinstance(f, Poly) and not F.gen.is_Symbol:
# root of sin(x) + 1 is -1 but when someone
# passes an Expr instead of Poly they may not expect
# that the generator will be sin(x), not x
raise PolynomialError("generator must be a Symbol")
except GeneratorsNeeded:
raise PolynomialError(
"Cannot compute real roots of %s, not a polynomial" % f)
return F.real_roots(multiple=multiple)
@public
def nroots(f, n=15, maxsteps=50, cleanup=True):
"""
Compute numerical approximations of roots of ``f``.
Examples
========
>>> from sympy import nroots
>>> from sympy.abc import x
>>> nroots(x**2 - 3, n=15)
[-1.73205080756888, 1.73205080756888]
>>> nroots(x**2 - 3, n=30)
[-1.73205080756887729352744634151, 1.73205080756887729352744634151]
"""
try:
F = Poly(f, greedy=False)
if not isinstance(f, Poly) and not F.gen.is_Symbol:
# root of sin(x) + 1 is -1 but when someone
# passes an Expr instead of Poly they may not expect
# that the generator will be sin(x), not x
raise PolynomialError("generator must be a Symbol")
except GeneratorsNeeded:
raise PolynomialError(
"Cannot compute numerical roots of %s, not a polynomial" % f)
return F.nroots(n=n, maxsteps=maxsteps, cleanup=cleanup)
@public
def ground_roots(f, *gens, **args):
"""
Compute roots of ``f`` by factorization in the ground domain.
Examples
========
>>> from sympy import ground_roots
>>> from sympy.abc import x
>>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2)
{0: 2, 1: 2}
"""
options.allowed_flags(args, [])
try:
F, opt = poly_from_expr(f, *gens, **args)
if not isinstance(f, Poly) and not F.gen.is_Symbol:
# root of sin(x) + 1 is -1 but when someone
# passes an Expr instead of Poly they may not expect
# that the generator will be sin(x), not x
raise PolynomialError("generator must be a Symbol")
except PolificationFailed as exc:
raise ComputationFailed('ground_roots', 1, exc)
return F.ground_roots()
@public
def nth_power_roots_poly(f, n, *gens, **args):
"""
Construct a polynomial with n-th powers of roots of ``f``.
Examples
========
>>> from sympy import nth_power_roots_poly, factor, roots
>>> from sympy.abc import x
>>> f = x**4 - x**2 + 1
>>> g = factor(nth_power_roots_poly(f, 2))
>>> g
(x**2 - x + 1)**2
>>> R_f = [ (r**2).expand() for r in roots(f) ]
>>> R_g = roots(g).keys()
>>> set(R_f) == set(R_g)
True
"""
options.allowed_flags(args, [])
try:
F, opt = poly_from_expr(f, *gens, **args)
if not isinstance(f, Poly) and not F.gen.is_Symbol:
# root of sin(x) + 1 is -1 but when someone
# passes an Expr instead of Poly they may not expect
# that the generator will be sin(x), not x
raise PolynomialError("generator must be a Symbol")
except PolificationFailed as exc:
raise ComputationFailed('nth_power_roots_poly', 1, exc)
result = F.nth_power_roots_poly(n)
if not opt.polys:
return result.as_expr()
else:
return result
@public
def cancel(f, *gens, _signsimp=True, **args):
"""
Cancel common factors in a rational function ``f``.
Examples
========
>>> from sympy import cancel, sqrt, Symbol, together
>>> from sympy.abc import x
>>> A = Symbol('A', commutative=False)
>>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1))
(2*x + 2)/(x - 1)
>>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A))
sqrt(6)/2
Note: due to automatic distribution of Rationals, a sum divided by an integer
will appear as a sum. To recover a rational form use `together` on the result:
>>> cancel(x/2 + 1)
x/2 + 1
>>> together(_)
(x + 2)/2
"""
from sympy.simplify.simplify import signsimp
from sympy.polys.rings import sring
options.allowed_flags(args, ['polys'])
f = sympify(f)
if _signsimp:
f = signsimp(f)
opt = {}
if 'polys' in args:
opt['polys'] = args['polys']
if not isinstance(f, (tuple, Tuple)):
if f.is_Number or isinstance(f, Relational) or not isinstance(f, Expr):
return f
f = factor_terms(f, radical=True)
p, q = f.as_numer_denom()
elif len(f) == 2:
p, q = f
if isinstance(p, Poly) and isinstance(q, Poly):
opt['gens'] = p.gens
opt['domain'] = p.domain
opt['polys'] = opt.get('polys', True)
p, q = p.as_expr(), q.as_expr()
elif isinstance(f, Tuple):
return factor_terms(f)
else:
raise ValueError('unexpected argument: %s' % f)
from sympy.functions.elementary.piecewise import Piecewise
try:
if f.has(Piecewise):
raise PolynomialError()
R, (F, G) = sring((p, q), *gens, **args)
if not R.ngens:
if not isinstance(f, (tuple, Tuple)):
return f.expand()
else:
return S.One, p, q
except PolynomialError as msg:
if f.is_commutative and not f.has(Piecewise):
raise PolynomialError(msg)
# Handling of noncommutative and/or piecewise expressions
if f.is_Add or f.is_Mul:
c, nc = sift(f.args, lambda x:
x.is_commutative is True and not x.has(Piecewise),
binary=True)
nc = [cancel(i) for i in nc]
return f.func(cancel(f.func(*c)), *nc)
else:
reps = []
pot = preorder_traversal(f)
next(pot)
for e in pot:
# XXX: This should really skip anything that's not Expr.
if isinstance(e, (tuple, Tuple, BooleanAtom)):
continue
try:
reps.append((e, cancel(e)))
pot.skip() # this was handled successfully
except NotImplementedError:
pass
return f.xreplace(dict(reps))
c, (P, Q) = 1, F.cancel(G)
if opt.get('polys', False) and 'gens' not in opt:
opt['gens'] = R.symbols
if not isinstance(f, (tuple, Tuple)):
return c*(P.as_expr()/Q.as_expr())
else:
P, Q = P.as_expr(), Q.as_expr()
if not opt.get('polys', False):
return c, P, Q
else:
return c, Poly(P, *gens, **opt), Poly(Q, *gens, **opt)
@public
def reduced(f, G, *gens, **args):
"""
Reduces a polynomial ``f`` modulo a set of polynomials ``G``.
Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``,
computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r``
such that ``f = q_1*g_1 + ... + q_n*g_n + r``, where ``r`` vanishes or ``r``
is a completely reduced polynomial with respect to ``G``.
Examples
========
>>> from sympy import reduced
>>> from sympy.abc import x, y
>>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y])
([2*x, 1], x**2 + y**2 + y)
"""
options.allowed_flags(args, ['polys', 'auto'])
try:
polys, opt = parallel_poly_from_expr([f] + list(G), *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('reduced', 0, exc)
domain = opt.domain
retract = False
if opt.auto and domain.is_Ring and not domain.is_Field:
opt = opt.clone(dict(domain=domain.get_field()))
retract = True
from sympy.polys.rings import xring
_ring, _ = xring(opt.gens, opt.domain, opt.order)
for i, poly in enumerate(polys):
poly = poly.set_domain(opt.domain).rep.to_dict()
polys[i] = _ring.from_dict(poly)
Q, r = polys[0].div(polys[1:])
Q = [Poly._from_dict(dict(q), opt) for q in Q]
r = Poly._from_dict(dict(r), opt)
if retract:
try:
_Q, _r = [q.to_ring() for q in Q], r.to_ring()
except CoercionFailed:
pass
else:
Q, r = _Q, _r
if not opt.polys:
return [q.as_expr() for q in Q], r.as_expr()
else:
return Q, r
@public
def groebner(F, *gens, **args):
"""
Computes the reduced Groebner basis for a set of polynomials.
Use the ``order`` argument to set the monomial ordering that will be
used to compute the basis. Allowed orders are ``lex``, ``grlex`` and
``grevlex``. If no order is specified, it defaults to ``lex``.
For more information on Groebner bases, see the references and the docstring
of :func:`~.solve_poly_system`.
Examples
========
Example taken from [1].
>>> from sympy import groebner
>>> from sympy.abc import x, y
>>> F = [x*y - 2*y, 2*y**2 - x**2]
>>> groebner(F, x, y, order='lex')
GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y,
domain='ZZ', order='lex')
>>> groebner(F, x, y, order='grlex')
GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
domain='ZZ', order='grlex')
>>> groebner(F, x, y, order='grevlex')
GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
domain='ZZ', order='grevlex')
By default, an improved implementation of the Buchberger algorithm is
used. Optionally, an implementation of the F5B algorithm can be used. The
algorithm can be set using the ``method`` flag or with the
:func:`sympy.polys.polyconfig.setup` function.
>>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)]
>>> groebner(F, x, y, method='buchberger')
GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')
>>> groebner(F, x, y, method='f5b')
GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')
References
==========
1. [Buchberger01]_
2. [Cox97]_
"""
return GroebnerBasis(F, *gens, **args)
@public
def is_zero_dimensional(F, *gens, **args):
"""
Checks if the ideal generated by a Groebner basis is zero-dimensional.
The algorithm checks if the set of monomials not divisible by the
leading monomial of any element of ``F`` is bounded.
References
==========
David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and
Algorithms, 3rd edition, p. 230
"""
return GroebnerBasis(F, *gens, **args).is_zero_dimensional
@public
class GroebnerBasis(Basic):
"""Represents a reduced Groebner basis. """
def __new__(cls, F, *gens, **args):
"""Compute a reduced Groebner basis for a system of polynomials. """
options.allowed_flags(args, ['polys', 'method'])
try:
polys, opt = parallel_poly_from_expr(F, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('groebner', len(F), exc)
from sympy.polys.rings import PolyRing
ring = PolyRing(opt.gens, opt.domain, opt.order)
polys = [ring.from_dict(poly.rep.to_dict()) for poly in polys if poly]
G = _groebner(polys, ring, method=opt.method)
G = [Poly._from_dict(g, opt) for g in G]
return cls._new(G, opt)
@classmethod
def _new(cls, basis, options):
obj = Basic.__new__(cls)
obj._basis = tuple(basis)
obj._options = options
return obj
@property
def args(self):
basis = (p.as_expr() for p in self._basis)
return (Tuple(*basis), Tuple(*self._options.gens))
@property
def exprs(self):
return [poly.as_expr() for poly in self._basis]
@property
def polys(self):
return list(self._basis)
@property
def gens(self):
return self._options.gens
@property
def domain(self):
return self._options.domain
@property
def order(self):
return self._options.order
def __len__(self):
return len(self._basis)
def __iter__(self):
if self._options.polys:
return iter(self.polys)
else:
return iter(self.exprs)
def __getitem__(self, item):
if self._options.polys:
basis = self.polys
else:
basis = self.exprs
return basis[item]
def __hash__(self):
return hash((self._basis, tuple(self._options.items())))
def __eq__(self, other):
if isinstance(other, self.__class__):
return self._basis == other._basis and self._options == other._options
elif iterable(other):
return self.polys == list(other) or self.exprs == list(other)
else:
return False
def __ne__(self, other):
return not self == other
@property
def is_zero_dimensional(self):
"""
Checks if the ideal generated by a Groebner basis is zero-dimensional.
The algorithm checks if the set of monomials not divisible by the
leading monomial of any element of ``F`` is bounded.
References
==========
David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and
Algorithms, 3rd edition, p. 230
"""
def single_var(monomial):
return sum(map(bool, monomial)) == 1
exponents = Monomial([0]*len(self.gens))
order = self._options.order
for poly in self.polys:
monomial = poly.LM(order=order)
if single_var(monomial):
exponents *= monomial
# If any element of the exponents vector is zero, then there's
# a variable for which there's no degree bound and the ideal
# generated by this Groebner basis isn't zero-dimensional.
return all(exponents)
def fglm(self, order):
"""
Convert a Groebner basis from one ordering to another.
The FGLM algorithm converts reduced Groebner bases of zero-dimensional
ideals from one ordering to another. This method is often used when it
is infeasible to compute a Groebner basis with respect to a particular
ordering directly.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import groebner
>>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
>>> G = groebner(F, x, y, order='grlex')
>>> list(G.fglm('lex'))
[2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]
>>> list(groebner(F, x, y, order='lex'))
[2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]
References
==========
.. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient
Computation of Zero-dimensional Groebner Bases by Change of
Ordering
"""
opt = self._options
src_order = opt.order
dst_order = monomial_key(order)
if src_order == dst_order:
return self
if not self.is_zero_dimensional:
raise NotImplementedError("Cannot convert Groebner bases of ideals with positive dimension")
polys = list(self._basis)
domain = opt.domain
opt = opt.clone(dict(
domain=domain.get_field(),
order=dst_order,
))
from sympy.polys.rings import xring
_ring, _ = xring(opt.gens, opt.domain, src_order)
for i, poly in enumerate(polys):
poly = poly.set_domain(opt.domain).rep.to_dict()
polys[i] = _ring.from_dict(poly)
G = matrix_fglm(polys, _ring, dst_order)
G = [Poly._from_dict(dict(g), opt) for g in G]
if not domain.is_Field:
G = [g.clear_denoms(convert=True)[1] for g in G]
opt.domain = domain
return self._new(G, opt)
def reduce(self, expr, auto=True):
"""
Reduces a polynomial modulo a Groebner basis.
Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``,
computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r``
such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r``
is a completely reduced polynomial with respect to ``G``.
Examples
========
>>> from sympy import groebner, expand
>>> from sympy.abc import x, y
>>> f = 2*x**4 - x**2 + y**3 + y**2
>>> G = groebner([x**3 - x, y**3 - y])
>>> G.reduce(f)
([2*x, 1], x**2 + y**2 + y)
>>> Q, r = _
>>> expand(sum(q*g for q, g in zip(Q, G)) + r)
2*x**4 - x**2 + y**3 + y**2
>>> _ == f
True
"""
poly = Poly._from_expr(expr, self._options)
polys = [poly] + list(self._basis)
opt = self._options
domain = opt.domain
retract = False
if auto and domain.is_Ring and not domain.is_Field:
opt = opt.clone(dict(domain=domain.get_field()))
retract = True
from sympy.polys.rings import xring
_ring, _ = xring(opt.gens, opt.domain, opt.order)
for i, poly in enumerate(polys):
poly = poly.set_domain(opt.domain).rep.to_dict()
polys[i] = _ring.from_dict(poly)
Q, r = polys[0].div(polys[1:])
Q = [Poly._from_dict(dict(q), opt) for q in Q]
r = Poly._from_dict(dict(r), opt)
if retract:
try:
_Q, _r = [q.to_ring() for q in Q], r.to_ring()
except CoercionFailed:
pass
else:
Q, r = _Q, _r
if not opt.polys:
return [q.as_expr() for q in Q], r.as_expr()
else:
return Q, r
def contains(self, poly):
"""
Check if ``poly`` belongs the ideal generated by ``self``.
Examples
========
>>> from sympy import groebner
>>> from sympy.abc import x, y
>>> f = 2*x**3 + y**3 + 3*y
>>> G = groebner([x**2 + y**2 - 1, x*y - 2])
>>> G.contains(f)
True
>>> G.contains(f + 1)
False
"""
return self.reduce(poly)[1] == 0
@public
def poly(expr, *gens, **args):
"""
Efficiently transform an expression into a polynomial.
Examples
========
>>> from sympy import poly
>>> from sympy.abc import x
>>> poly(x*(x**2 + x - 1)**2)
Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')
"""
options.allowed_flags(args, [])
def _poly(expr, opt):
terms, poly_terms = [], []
for term in Add.make_args(expr):
factors, poly_factors = [], []
for factor in Mul.make_args(term):
if factor.is_Add:
poly_factors.append(_poly(factor, opt))
elif factor.is_Pow and factor.base.is_Add and \
factor.exp.is_Integer and factor.exp >= 0:
poly_factors.append(
_poly(factor.base, opt).pow(factor.exp))
else:
factors.append(factor)
if not poly_factors:
terms.append(term)
else:
product = poly_factors[0]
for factor in poly_factors[1:]:
product = product.mul(factor)
if factors:
factor = Mul(*factors)
if factor.is_Number:
product = product.mul(factor)
else:
product = product.mul(Poly._from_expr(factor, opt))
poly_terms.append(product)
if not poly_terms:
result = Poly._from_expr(expr, opt)
else:
result = poly_terms[0]
for term in poly_terms[1:]:
result = result.add(term)
if terms:
term = Add(*terms)
if term.is_Number:
result = result.add(term)
else:
result = result.add(Poly._from_expr(term, opt))
return result.reorder(*opt.get('gens', ()), **args)
expr = sympify(expr)
if expr.is_Poly:
return Poly(expr, *gens, **args)
if 'expand' not in args:
args['expand'] = False
opt = options.build_options(gens, args)
return _poly(expr, opt)
def named_poly(n, f, K, name, x, polys):
r"""Common interface to the low-level polynomial generating functions
in orthopolys and appellseqs.
Parameters
==========
n : int
Index of the polynomial, which may or may not equal its degree.
f : callable
Low-level generating function to use.
K : Domain or None
Domain in which to perform the computations. If None, use the smallest
field containing the rationals and the extra parameters of x (see below).
name : str
Name of an arbitrary individual polynomial in the sequence generated
by f, only used in the error message for invalid n.
x : seq
The first element of this argument is the main variable of all
polynomials in this sequence. Any further elements are extra
parameters required by f.
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
if n < 0:
raise ValueError("Cannot generate %s of index %s" % (name, n))
head, tail = x[0], x[1:]
if K is None:
K, tail = construct_domain(tail, field=True)
poly = DMP(f(int(n), *tail, K), K)
if head is None:
poly = PurePoly.new(poly, Dummy('x'))
else:
poly = Poly.new(poly, head)
return poly if polys else poly.as_expr()
|
10cd9093b081a647dacdae42c5cde65c2461fedc37a206cfd56622f6615fbbcb | """Polynomial manipulation algorithms and algebraic objects. """
__all__ = [
'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree',
'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo',
'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert',
'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list',
'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content',
'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff',
'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor',
'intervals', 'refine_root', 'count_roots', 'real_roots', 'nroots',
'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', 'groebner',
'is_zero_dimensional', 'GroebnerBasis', 'poly',
'symmetrize', 'horner', 'interpolate', 'rational_interpolate', 'viete',
'together',
'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed',
'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed',
'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed',
'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible',
'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed',
'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed',
'UnivariatePolynomialError', 'MultivariatePolynomialError',
'PolificationFailed', 'OptionError', 'FlagError',
'minpoly', 'minimal_polynomial', 'primitive_element', 'field_isomorphism',
'to_number_field', 'isolate', 'round_two', 'prime_decomp',
'prime_valuation',
'itermonomials', 'Monomial',
'lex', 'grlex', 'grevlex', 'ilex', 'igrlex', 'igrevlex',
'CRootOf', 'rootof', 'RootOf', 'ComplexRootOf', 'RootSum',
'roots',
'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField',
'ComplexField', 'PythonFiniteField', 'GMPYFiniteField',
'PythonIntegerRing', 'GMPYIntegerRing', 'PythonRational',
'GMPYRationalField', 'AlgebraicField', 'PolynomialRing', 'FractionField',
'ExpressionDomain', 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy',
'QQ_python', 'QQ_gmpy', 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR',
'CC', 'EX', 'EXRAW',
'construct_domain',
'swinnerton_dyer_poly', 'cyclotomic_poly', 'symmetric_poly',
'random_poly', 'interpolating_poly',
'jacobi_poly', 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly',
'hermite_prob_poly', 'legendre_poly', 'laguerre_poly',
'bernoulli_poly', 'bernoulli_c_poly', 'genocchi_poly', 'euler_poly',
'andre_poly',
'apart', 'apart_list', 'assemble_partfrac_list',
'Options',
'ring', 'xring', 'vring', 'sring',
'field', 'xfield', 'vfield', 'sfield'
]
from .polytools import (Poly, PurePoly, poly_from_expr,
parallel_poly_from_expr, degree, total_degree, degree_list, LC, LM,
LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex,
invert, subresultants, resultant, discriminant, cofactors, gcd_list,
gcd, lcm_list, lcm, terms_gcd, trunc, monic, content, primitive,
compose, decompose, sturm, gff_list, gff, sqf_norm, sqf_part,
sqf_list, sqf, factor_list, factor, intervals, refine_root,
count_roots, real_roots, nroots, ground_roots, nth_power_roots_poly,
cancel, reduced, groebner, is_zero_dimensional, GroebnerBasis, poly)
from .polyfuncs import (symmetrize, horner, interpolate,
rational_interpolate, viete)
from .rationaltools import together
from .polyerrors import (BasePolynomialError, ExactQuotientFailed,
PolynomialDivisionFailed, OperationNotSupported, HeuristicGCDFailed,
HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
NotReversible, NotAlgebraic, DomainError, PolynomialError,
UnificationFailed, GeneratorsError, GeneratorsNeeded,
ComputationFailed, UnivariatePolynomialError,
MultivariatePolynomialError, PolificationFailed, OptionError,
FlagError)
from .numberfields import (minpoly, minimal_polynomial, primitive_element,
field_isomorphism, to_number_field, isolate, round_two, prime_decomp,
prime_valuation)
from .monomials import itermonomials, Monomial
from .orderings import lex, grlex, grevlex, ilex, igrlex, igrevlex
from .rootoftools import CRootOf, rootof, RootOf, ComplexRootOf, RootSum
from .polyroots import roots
from .domains import (Domain, FiniteField, IntegerRing, RationalField,
RealField, ComplexField, PythonFiniteField, GMPYFiniteField,
PythonIntegerRing, GMPYIntegerRing, PythonRational, GMPYRationalField,
AlgebraicField, PolynomialRing, FractionField, ExpressionDomain,
FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, QQ_gmpy, GF, FF,
ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW)
from .constructor import construct_domain
from .specialpolys import (swinnerton_dyer_poly, cyclotomic_poly,
symmetric_poly, random_poly, interpolating_poly)
from .orthopolys import (jacobi_poly, chebyshevt_poly, chebyshevu_poly,
hermite_poly, hermite_prob_poly, legendre_poly, laguerre_poly)
from .appellseqs import (bernoulli_poly, bernoulli_c_poly, genocchi_poly,
euler_poly, andre_poly)
from .partfrac import apart, apart_list, assemble_partfrac_list
from .polyoptions import Options
from .rings import ring, xring, vring, sring
from .fields import field, xfield, vfield, sfield
|
2a3c777d2a0b0e95fe6d75258243d074e2bf4eeb4889d234307989fba72f88a3 | """Efficient functions for generating orthogonal polynomials."""
from sympy.core.symbol import Dummy
from sympy.polys.densearith import (dup_mul, dup_mul_ground,
dup_lshift, dup_sub, dup_add)
from sympy.polys.domains import ZZ, QQ
from sympy.polys.polytools import named_poly
from sympy.utilities import public
def dup_jacobi(n, a, b, K):
"""Low-level implementation of Jacobi polynomials."""
if n < 1:
return [K.one]
m2, m1 = [K.one], [(a+b)/K(2) + K.one, (a-b)/K(2)]
for i in range(2, n+1):
den = K(i)*(a + b + i)*(a + b + K(2)*i - K(2))
f0 = (a + b + K(2)*i - K.one) * (a*a - b*b) / (K(2)*den)
f1 = (a + b + K(2)*i - K.one) * (a + b + K(2)*i - K(2)) * (a + b + K(2)*i) / (K(2)*den)
f2 = (a + i - K.one)*(b + i - K.one)*(a + b + K(2)*i) / den
p0 = dup_mul_ground(m1, f0, K)
p1 = dup_mul_ground(dup_lshift(m1, 1, K), f1, K)
p2 = dup_mul_ground(m2, f2, K)
m2, m1 = m1, dup_sub(dup_add(p0, p1, K), p2, K)
return m1
@public
def jacobi_poly(n, a, b, x=None, polys=False):
r"""Generates the Jacobi polynomial `P_n^{(a,b)}(x)`.
Parameters
==========
n : int
Degree of the polynomial.
a
Lower limit of minimal domain for the list of coefficients.
b
Upper limit of minimal domain for the list of coefficients.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_jacobi, None, "Jacobi polynomial", (x, a, b), polys)
def dup_gegenbauer(n, a, K):
"""Low-level implementation of Gegenbauer polynomials."""
if n < 1:
return [K.one]
m2, m1 = [K.one], [K(2)*a, K.zero]
for i in range(2, n+1):
p1 = dup_mul_ground(dup_lshift(m1, 1, K), K(2)*(a-K.one)/K(i) + K(2), K)
p2 = dup_mul_ground(m2, K(2)*(a-K.one)/K(i) + K.one, K)
m2, m1 = m1, dup_sub(p1, p2, K)
return m1
def gegenbauer_poly(n, a, x=None, polys=False):
r"""Generates the Gegenbauer polynomial `C_n^{(a)}(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
a
Decides minimal domain for the list of coefficients.
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_gegenbauer, None, "Gegenbauer polynomial", (x, a), polys)
def dup_chebyshevt(n, K):
"""Low-level implementation of Chebyshev polynomials of the first kind."""
if n < 1:
return [K.one]
m2, m1 = [K.one], [K.one, K.zero]
for i in range(2, n+1):
m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2), K), m2, K)
return m1
def dup_chebyshevu(n, K):
"""Low-level implementation of Chebyshev polynomials of the second kind."""
if n < 1:
return [K.one]
m2, m1 = [K.one], [K(2), K.zero]
for i in range(2, n+1):
m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2), K), m2, K)
return m1
@public
def chebyshevt_poly(n, x=None, polys=False):
r"""Generates the Chebyshev polynomial of the first kind `T_n(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_chebyshevt, ZZ,
"Chebyshev polynomial of the first kind", (x,), polys)
@public
def chebyshevu_poly(n, x=None, polys=False):
r"""Generates the Chebyshev polynomial of the second kind `U_n(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_chebyshevu, ZZ,
"Chebyshev polynomial of the second kind", (x,), polys)
def dup_hermite(n, K):
"""Low-level implementation of Hermite polynomials."""
if n < 1:
return [K.one]
m2, m1 = [K.one], [K(2), K.zero]
for i in range(2, n+1):
a = dup_lshift(m1, 1, K)
b = dup_mul_ground(m2, K(i-1), K)
m2, m1 = m1, dup_mul_ground(dup_sub(a, b, K), K(2), K)
return m1
def dup_hermite_prob(n, K):
"""Low-level implementation of probabilist's Hermite polynomials."""
if n < 1:
return [K.one]
m2, m1 = [K.one], [K.one, K.zero]
for i in range(2, n+1):
a = dup_lshift(m1, 1, K)
b = dup_mul_ground(m2, K(i-1), K)
m2, m1 = m1, dup_sub(a, b, K)
return m1
@public
def hermite_poly(n, x=None, polys=False):
r"""Generates the Hermite polynomial `H_n(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_hermite, ZZ, "Hermite polynomial", (x,), polys)
@public
def hermite_prob_poly(n, x=None, polys=False):
r"""Generates the probabilist's Hermite polynomial `He_n(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_hermite_prob, ZZ,
"probabilist's Hermite polynomial", (x,), polys)
def dup_legendre(n, K):
"""Low-level implementation of Legendre polynomials."""
if n < 1:
return [K.one]
m2, m1 = [K.one], [K.one, K.zero]
for i in range(2, n+1):
a = dup_mul_ground(dup_lshift(m1, 1, K), K(2*i-1, i), K)
b = dup_mul_ground(m2, K(i-1, i), K)
m2, m1 = m1, dup_sub(a, b, K)
return m1
@public
def legendre_poly(n, x=None, polys=False):
r"""Generates the Legendre polynomial `P_n(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_legendre, QQ, "Legendre polynomial", (x,), polys)
def dup_laguerre(n, alpha, K):
"""Low-level implementation of Laguerre polynomials."""
m2, m1 = [K.zero], [K.one]
for i in range(1, n+1):
a = dup_mul(m1, [-K.one/K(i), (alpha-K.one)/K(i) + K(2)], K)
b = dup_mul_ground(m2, (alpha-K.one)/K(i) + K.one, K)
m2, m1 = m1, dup_sub(a, b, K)
return m1
@public
def laguerre_poly(n, x=None, alpha=0, polys=False):
r"""Generates the Laguerre polynomial `L_n^{(\alpha)}(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
alpha : optional
Decides minimal domain for the list of coefficients.
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
"""
return named_poly(n, dup_laguerre, None, "Laguerre polynomial", (x, alpha), polys)
def dup_spherical_bessel_fn(n, K):
"""Low-level implementation of fn(n, x)."""
if n < 1:
return [K.one, K.zero]
m2, m1 = [K.one], [K.one, K.zero]
for i in range(2, n+1):
m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2*i-1), K), m2, K)
return dup_lshift(m1, 1, K)
def dup_spherical_bessel_fn_minus(n, K):
"""Low-level implementation of fn(-n, x)."""
m2, m1 = [K.one, K.zero], [K.zero]
for i in range(2, n+1):
m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(3-2*i), K), m2, K)
return m1
def spherical_bessel_fn(n, x=None, polys=False):
"""
Coefficients for the spherical Bessel functions.
These are only needed in the jn() function.
The coefficients are calculated from:
fn(0, z) = 1/z
fn(1, z) = 1/z**2
fn(n-1, z) + fn(n+1, z) == (2*n+1)/z * fn(n, z)
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
Examples
========
>>> from sympy.polys.orthopolys import spherical_bessel_fn as fn
>>> from sympy import Symbol
>>> z = Symbol("z")
>>> fn(1, z)
z**(-2)
>>> fn(2, z)
-1/z + 3/z**3
>>> fn(3, z)
-6/z**2 + 15/z**4
>>> fn(4, z)
1/z - 45/z**3 + 105/z**5
"""
if x is None:
x = Dummy("x")
f = dup_spherical_bessel_fn_minus if n < 0 else dup_spherical_bessel_fn
return named_poly(abs(n), f, ZZ, "", (QQ(1)/x,), polys)
|
d317fd086c4aa7e048e27baf2a3454b52c4e672e793b4c1dbf85a5c585cae17a | """
This is our testing framework.
Goals:
* it should be compatible with py.test and operate very similarly
(or identically)
* does not require any external dependencies
* preferably all the functionality should be in this file only
* no magic, just import the test file and execute the test functions, that's it
* portable
"""
import os
import sys
import platform
import inspect
import traceback
import pdb
import re
import linecache
import time
from fnmatch import fnmatch
from timeit import default_timer as clock
import doctest as pdoctest # avoid clashing with our doctest() function
from doctest import DocTestFinder, DocTestRunner
import random
import subprocess
import shutil
import signal
import stat
import tempfile
import warnings
from contextlib import contextmanager
from inspect import unwrap
from sympy.core.cache import clear_cache
from sympy.external import import_module
from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY
IS_WINDOWS = (os.name == 'nt')
ON_TRAVIS = os.getenv('TRAVIS_BUILD_NUMBER', None)
# emperically generated list of the proportion of time spent running
# an even split of tests. This should periodically be regenerated.
# A list of [.6, .1, .3] would mean that if the tests are evenly split
# into '1/3', '2/3', '3/3', the first split would take 60% of the time,
# the second 10% and the third 30%. These lists are normalized to sum
# to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3].
#
# This list can be generated with the code:
# from time import time
# import sympy
# import os
# os.environ["TRAVIS_BUILD_NUMBER"] = '2' # Mock travis to get more correct densities
# delays, num_splits = [], 30
# for i in range(1, num_splits + 1):
# tic = time()
# sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests
# delays.append(time() - tic)
# tot = sum(delays)
# print([round(x / tot, 4) for x in delays])
SPLIT_DENSITY = [
0.0059, 0.0027, 0.0068, 0.0011, 0.0006,
0.0058, 0.0047, 0.0046, 0.004, 0.0257,
0.0017, 0.0026, 0.004, 0.0032, 0.0016,
0.0015, 0.0004, 0.0011, 0.0016, 0.0014,
0.0077, 0.0137, 0.0217, 0.0074, 0.0043,
0.0067, 0.0236, 0.0004, 0.1189, 0.0142,
0.0234, 0.0003, 0.0003, 0.0047, 0.0006,
0.0013, 0.0004, 0.0008, 0.0007, 0.0006,
0.0139, 0.0013, 0.0007, 0.0051, 0.002,
0.0004, 0.0005, 0.0213, 0.0048, 0.0016,
0.0012, 0.0014, 0.0024, 0.0015, 0.0004,
0.0005, 0.0007, 0.011, 0.0062, 0.0015,
0.0021, 0.0049, 0.0006, 0.0006, 0.0011,
0.0006, 0.0019, 0.003, 0.0044, 0.0054,
0.0057, 0.0049, 0.0016, 0.0006, 0.0009,
0.0006, 0.0012, 0.0006, 0.0149, 0.0532,
0.0076, 0.0041, 0.0024, 0.0135, 0.0081,
0.2209, 0.0459, 0.0438, 0.0488, 0.0137,
0.002, 0.0003, 0.0008, 0.0039, 0.0024,
0.0005, 0.0004, 0.003, 0.056, 0.0026]
SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483]
class Skipped(Exception):
pass
class TimeOutError(Exception):
pass
class DependencyError(Exception):
pass
def _indent(s, indent=4):
"""
Add the given number of space characters to the beginning of
every non-blank line in ``s``, and return the result.
If the string ``s`` is Unicode, it is encoded using the stdout
encoding and the ``backslashreplace`` error handler.
"""
# This regexp matches the start of non-blank lines:
return re.sub('(?m)^(?!$)', indent*' ', s)
pdoctest._indent = _indent # type: ignore
# override reporter to maintain windows and python3
def _report_failure(self, out, test, example, got):
"""
Report that the given example failed.
"""
s = self._checker.output_difference(example, got, self.optionflags)
s = s.encode('raw_unicode_escape').decode('utf8', 'ignore')
out(self._failure_header(test, example) + s)
if IS_WINDOWS:
DocTestRunner.report_failure = _report_failure # type: ignore
def convert_to_native_paths(lst):
"""
Converts a list of '/' separated paths into a list of
native (os.sep separated) paths and converts to lowercase
if the system is case insensitive.
"""
newlst = []
for i, rv in enumerate(lst):
rv = os.path.join(*rv.split("/"))
# on windows the slash after the colon is dropped
if sys.platform == "win32":
pos = rv.find(':')
if pos != -1:
if rv[pos + 1] != '\\':
rv = rv[:pos + 1] + '\\' + rv[pos + 1:]
newlst.append(os.path.normcase(rv))
return newlst
def get_sympy_dir():
"""
Returns the root SymPy directory and set the global value
indicating whether the system is case sensitive or not.
"""
this_file = os.path.abspath(__file__)
sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..")
sympy_dir = os.path.normpath(sympy_dir)
return os.path.normcase(sympy_dir)
def setup_pprint():
from sympy.interactive.printing import init_printing
from sympy.printing.pretty.pretty import pprint_use_unicode
import sympy.interactive.printing as interactive_printing
# force pprint to be in ascii mode in doctests
use_unicode_prev = pprint_use_unicode(False)
# hook our nice, hash-stable strprinter
init_printing(pretty_print=False)
# Prevent init_printing() in doctests from affecting other doctests
interactive_printing.NO_GLOBAL = True
return use_unicode_prev
@contextmanager
def raise_on_deprecated():
"""Context manager to make DeprecationWarning raise an error
This is to catch SymPyDeprecationWarning from library code while running
tests and doctests. It is important to use this context manager around
each individual test/doctest in case some tests modify the warning
filters.
"""
with warnings.catch_warnings():
warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*')
yield
def run_in_subprocess_with_hash_randomization(
function, function_args=(),
function_kwargs=None, command=sys.executable,
module='sympy.testing.runtests', force=False):
"""
Run a function in a Python subprocess with hash randomization enabled.
If hash randomization is not supported by the version of Python given, it
returns False. Otherwise, it returns the exit value of the command. The
function is passed to sys.exit(), so the return value of the function will
be the return value.
The environment variable PYTHONHASHSEED is used to seed Python's hash
randomization. If it is set, this function will return False, because
starting a new subprocess is unnecessary in that case. If it is not set,
one is set at random, and the tests are run. Note that if this
environment variable is set when Python starts, hash randomization is
automatically enabled. To force a subprocess to be created even if
PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a
subprocess in Python versions that do not support hash randomization (see
below), because those versions of Python do not support the ``-R`` flag.
``function`` should be a string name of a function that is importable from
the module ``module``, like "_test". The default for ``module`` is
"sympy.testing.runtests". ``function_args`` and ``function_kwargs``
should be a repr-able tuple and dict, respectively. The default Python
command is sys.executable, which is the currently running Python command.
This function is necessary because the seed for hash randomization must be
set by the environment variable before Python starts. Hence, in order to
use a predetermined seed for tests, we must start Python in a separate
subprocess.
Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
3.1.5, and 3.2.3, and is enabled by default in all Python versions after
and including 3.3.0.
Examples
========
>>> from sympy.testing.runtests import (
... run_in_subprocess_with_hash_randomization)
>>> # run the core tests in verbose mode
>>> run_in_subprocess_with_hash_randomization("_test",
... function_args=("core",),
... function_kwargs={'verbose': True}) # doctest: +SKIP
# Will return 0 if sys.executable supports hash randomization and tests
# pass, 1 if they fail, and False if it does not support hash
# randomization.
"""
cwd = get_sympy_dir()
# Note, we must return False everywhere, not None, as subprocess.call will
# sometimes return None.
# First check if the Python version supports hash randomization
# If it does not have this support, it won't recognize the -R flag
p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, cwd=cwd)
p.communicate()
if p.returncode != 0:
return False
hash_seed = os.getenv("PYTHONHASHSEED")
if not hash_seed:
os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32))
else:
if not force:
return False
function_kwargs = function_kwargs or {}
# Now run the command
commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" %
(module, function, function, repr(function_args),
repr(function_kwargs)))
try:
p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd)
p.communicate()
except KeyboardInterrupt:
p.wait()
finally:
# Put the environment variable back, so that it reads correctly for
# the current Python process.
if hash_seed is None:
del os.environ["PYTHONHASHSEED"]
else:
os.environ["PYTHONHASHSEED"] = hash_seed
return p.returncode
def run_all_tests(test_args=(), test_kwargs=None,
doctest_args=(), doctest_kwargs=None,
examples_args=(), examples_kwargs=None):
"""
Run all tests.
Right now, this runs the regular tests (bin/test), the doctests
(bin/doctest), and the examples (examples/all.py).
This is what ``setup.py test`` uses.
You can pass arguments and keyword arguments to the test functions that
support them (for now, test, doctest, and the examples). See the
docstrings of those functions for a description of the available options.
For example, to run the solvers tests with colors turned off:
>>> from sympy.testing.runtests import run_all_tests
>>> run_all_tests(test_args=("solvers",),
... test_kwargs={"colors:False"}) # doctest: +SKIP
"""
tests_successful = True
test_kwargs = test_kwargs or {}
doctest_kwargs = doctest_kwargs or {}
examples_kwargs = examples_kwargs or {'quiet': True}
try:
# Regular tests
if not test(*test_args, **test_kwargs):
# some regular test fails, so set the tests_successful
# flag to false and continue running the doctests
tests_successful = False
# Doctests
print()
if not doctest(*doctest_args, **doctest_kwargs):
tests_successful = False
# Examples
print()
sys.path.append("examples") # examples/all.py
from all import run_examples # type: ignore
if not run_examples(*examples_args, **examples_kwargs):
tests_successful = False
if tests_successful:
return
else:
# Return nonzero exit code
sys.exit(1)
except KeyboardInterrupt:
print()
print("DO *NOT* COMMIT!")
sys.exit(1)
def test(*paths, subprocess=True, rerun=0, **kwargs):
"""
Run tests in the specified test_*.py files.
Tests in a particular test_*.py file are run if any of the given strings
in ``paths`` matches a part of the test file's path. If ``paths=[]``,
tests in all test_*.py files are run.
Notes:
- If sort=False, tests are run in random order (not default).
- Paths can be entered in native system format or in unix,
forward-slash format.
- Files that are on the blacklist can be tested by providing
their path; they are only excluded if no paths are given.
**Explanation of test results**
====== ===============================================================
Output Meaning
====== ===============================================================
. passed
F failed
X XPassed (expected to fail but passed)
f XFAILed (expected to fail and indeed failed)
s skipped
w slow
T timeout (e.g., when ``--timeout`` is used)
K KeyboardInterrupt (when running the slow tests with ``--slow``,
you can interrupt one of them without killing the test runner)
====== ===============================================================
Colors have no additional meaning and are used just to facilitate
interpreting the output.
Examples
========
>>> import sympy
Run all tests:
>>> sympy.test() # doctest: +SKIP
Run one file:
>>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP
>>> sympy.test("_basic") # doctest: +SKIP
Run all tests in sympy/functions/ and some particular file:
>>> sympy.test("sympy/core/tests/test_basic.py",
... "sympy/functions") # doctest: +SKIP
Run all tests in sympy/core and sympy/utilities:
>>> sympy.test("/core", "/util") # doctest: +SKIP
Run specific test from a file:
>>> sympy.test("sympy/core/tests/test_basic.py",
... kw="test_equality") # doctest: +SKIP
Run specific test from any file:
>>> sympy.test(kw="subs") # doctest: +SKIP
Run the tests with verbose mode on:
>>> sympy.test(verbose=True) # doctest: +SKIP
Do not sort the test output:
>>> sympy.test(sort=False) # doctest: +SKIP
Turn on post-mortem pdb:
>>> sympy.test(pdb=True) # doctest: +SKIP
Turn off colors:
>>> sympy.test(colors=False) # doctest: +SKIP
Force colors, even when the output is not to a terminal (this is useful,
e.g., if you are piping to ``less -r`` and you still want colors)
>>> sympy.test(force_colors=False) # doctest: +SKIP
The traceback verboseness can be set to "short" or "no" (default is
"short")
>>> sympy.test(tb='no') # doctest: +SKIP
The ``split`` option can be passed to split the test run into parts. The
split currently only splits the test files, though this may change in the
future. ``split`` should be a string of the form 'a/b', which will run
part ``a`` of ``b``. For instance, to run the first half of the test suite:
>>> sympy.test(split='1/2') # doctest: +SKIP
The ``time_balance`` option can be passed in conjunction with ``split``.
If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt
to split the tests such that each split takes equal time. This heuristic
for balancing is based on pre-recorded test data.
>>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP
You can disable running the tests in a separate subprocess using
``subprocess=False``. This is done to support seeding hash randomization,
which is enabled by default in the Python versions where it is supported.
If subprocess=False, hash randomization is enabled/disabled according to
whether it has been enabled or not in the calling Python process.
However, even if it is enabled, the seed cannot be printed unless it is
called from a new Python process.
Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
3.1.5, and 3.2.3, and is enabled by default in all Python versions after
and including 3.3.0.
If hash randomization is not supported ``subprocess=False`` is used
automatically.
>>> sympy.test(subprocess=False) # doctest: +SKIP
To set the hash randomization seed, set the environment variable
``PYTHONHASHSEED`` before running the tests. This can be done from within
Python using
>>> import os
>>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP
Or from the command line using
$ PYTHONHASHSEED=42 ./bin/test
If the seed is not set, a random seed will be chosen.
Note that to reproduce the same hash values, you must use both the same seed
as well as the same architecture (32-bit vs. 64-bit).
"""
# count up from 0, do not print 0
print_counter = lambda i : (print("rerun %d" % (rerun-i))
if rerun-i else None)
if subprocess:
# loop backwards so last i is 0
for i in range(rerun, -1, -1):
print_counter(i)
ret = run_in_subprocess_with_hash_randomization("_test",
function_args=paths, function_kwargs=kwargs)
if ret is False:
break
val = not bool(ret)
# exit on the first failure or if done
if not val or i == 0:
return val
# rerun even if hash randomization is not supported
for i in range(rerun, -1, -1):
print_counter(i)
val = not bool(_test(*paths, **kwargs))
if not val or i == 0:
return val
def _test(*paths,
verbose=False, tb="short", kw=None, pdb=False, colors=True,
force_colors=False, sort=True, seed=None, timeout=False,
fail_on_timeout=False, slow=False, enhance_asserts=False, split=None,
time_balance=True, blacklist=('sympy/integrals/rubi/rubi_tests/tests',),
fast_threshold=None, slow_threshold=None):
"""
Internal function that actually runs the tests.
All keyword arguments from ``test()`` are passed to this function except for
``subprocess``.
Returns 0 if tests passed and 1 if they failed. See the docstring of
``test()`` for more information.
"""
kw = kw or ()
# ensure that kw is a tuple
if isinstance(kw, str):
kw = (kw,)
post_mortem = pdb
if seed is None:
seed = random.randrange(100000000)
if ON_TRAVIS and timeout is False:
# Travis times out if no activity is seen for 10 minutes.
timeout = 595
fail_on_timeout = True
if ON_TRAVIS:
# pyglet does not work on Travis
blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests']
blacklist = convert_to_native_paths(blacklist)
r = PyTestReporter(verbose=verbose, tb=tb, colors=colors,
force_colors=force_colors, split=split)
t = SymPyTests(r, kw, post_mortem, seed,
fast_threshold=fast_threshold,
slow_threshold=slow_threshold)
test_files = t.get_test_files('sympy')
not_blacklisted = [f for f in test_files
if not any(b in f for b in blacklist)]
if len(paths) == 0:
matched = not_blacklisted
else:
paths = convert_to_native_paths(paths)
matched = []
for f in not_blacklisted:
basename = os.path.basename(f)
for p in paths:
if p in f or fnmatch(basename, p):
matched.append(f)
break
density = None
if time_balance:
if slow:
density = SPLIT_DENSITY_SLOW
else:
density = SPLIT_DENSITY
if split:
matched = split_list(matched, split, density=density)
t._testfiles.extend(matched)
return int(not t.test(sort=sort, timeout=timeout, slow=slow,
enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout))
def doctest(*paths, subprocess=True, rerun=0, **kwargs):
r"""
Runs doctests in all \*.py files in the SymPy directory which match
any of the given strings in ``paths`` or all tests if paths=[].
Notes:
- Paths can be entered in native system format or in unix,
forward-slash format.
- Files that are on the blacklist can be tested by providing
their path; they are only excluded if no paths are given.
Examples
========
>>> import sympy
Run all tests:
>>> sympy.doctest() # doctest: +SKIP
Run one file:
>>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP
>>> sympy.doctest("polynomial.rst") # doctest: +SKIP
Run all tests in sympy/functions/ and some particular file:
>>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP
Run any file having polynomial in its name, doc/src/modules/polynomial.rst,
sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py:
>>> sympy.doctest("polynomial") # doctest: +SKIP
The ``split`` option can be passed to split the test run into parts. The
split currently only splits the test files, though this may change in the
future. ``split`` should be a string of the form 'a/b', which will run
part ``a`` of ``b``. Note that the regular doctests and the Sphinx
doctests are split independently. For instance, to run the first half of
the test suite:
>>> sympy.doctest(split='1/2') # doctest: +SKIP
The ``subprocess`` and ``verbose`` options are the same as with the function
``test()``. See the docstring of that function for more information.
"""
# count up from 0, do not print 0
print_counter = lambda i : (print("rerun %d" % (rerun-i))
if rerun-i else None)
if subprocess:
# loop backwards so last i is 0
for i in range(rerun, -1, -1):
print_counter(i)
ret = run_in_subprocess_with_hash_randomization("_doctest",
function_args=paths, function_kwargs=kwargs)
if ret is False:
break
val = not bool(ret)
# exit on the first failure or if done
if not val or i == 0:
return val
# rerun even if hash randomization is not supported
for i in range(rerun, -1, -1):
print_counter(i)
val = not bool(_doctest(*paths, **kwargs))
if not val or i == 0:
return val
def _get_doctest_blacklist():
'''Get the default blacklist for the doctests'''
blacklist = []
blacklist.extend([
"doc/src/modules/plotting.rst", # generates live plots
"doc/src/modules/physics/mechanics/autolev_parser.rst",
"sympy/codegen/array_utils.py", # raises deprecation warning
"sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning
"sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning
"sympy/galgebra.py", # no longer part of SymPy
"sympy/integrals/rubi/rubi.py",
"sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code
"sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code
"sympy/parsing/autolev/_antlr/autolevparser.py", # generated code
"sympy/parsing/latex/_antlr/latexlexer.py", # generated code
"sympy/parsing/latex/_antlr/latexparser.py", # generated code
"sympy/plotting/pygletplot/__init__.py", # crashes on some systems
"sympy/plotting/pygletplot/plot.py", # crashes on some systems
"sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests
"sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
"sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
"sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning
"sympy/this.py", # prints text
])
# autolev parser tests
num = 12
for i in range (1, num+1):
blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py")
blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py",
"sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py",
"sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py",
"sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"])
if import_module('numpy') is None:
blacklist.extend([
"sympy/plotting/experimental_lambdify.py",
"sympy/plotting/plot_implicit.py",
"examples/advanced/autowrap_integrators.py",
"examples/advanced/autowrap_ufuncify.py",
"examples/intermediate/sample.py",
"examples/intermediate/mplot2d.py",
"examples/intermediate/mplot3d.py",
"doc/src/modules/numeric-computation.rst"
])
else:
if import_module('matplotlib') is None:
blacklist.extend([
"examples/intermediate/mplot2d.py",
"examples/intermediate/mplot3d.py"
])
else:
# Use a non-windowed backend, so that the tests work on Travis
import matplotlib
matplotlib.use('Agg')
if ON_TRAVIS or import_module('pyglet') is None:
blacklist.extend(["sympy/plotting/pygletplot"])
if import_module('aesara') is None:
blacklist.extend([
"sympy/printing/aesaracode.py",
"doc/src/modules/numeric-computation.rst",
])
if import_module('cupy') is None:
blacklist.extend([
"doc/src/modules/numeric-computation.rst",
])
if import_module('jax') is None:
blacklist.extend([
"doc/src/modules/numeric-computation.rst",
])
if import_module('antlr4') is None:
blacklist.extend([
"sympy/parsing/autolev/__init__.py",
"sympy/parsing/latex/_parse_latex_antlr.py",
])
if import_module('lfortran') is None:
#throws ImportError when lfortran not installed
blacklist.extend([
"sympy/parsing/sym_expr.py",
])
if import_module("scipy") is None:
# throws ModuleNotFoundError when scipy not installed
blacklist.extend(
["doc/src/guides/solving/solve-numerically.md",]
)
# disabled because of doctest failures in asmeurer's bot
blacklist.extend([
"sympy/utilities/autowrap.py",
"examples/advanced/autowrap_integrators.py",
"examples/advanced/autowrap_ufuncify.py"
])
# blacklist these modules until issue 4840 is resolved
blacklist.extend([
"sympy/conftest.py", # Depends on pytest
"sympy/testing/benchmarking.py",
])
# These are deprecated stubs to be removed:
blacklist.extend([
"sympy/utilities/benchmarking.py",
"sympy/utilities/tmpfiles.py",
"sympy/utilities/pytest.py",
"sympy/utilities/runtests.py",
"sympy/utilities/quality_unicode.py",
"sympy/utilities/randtest.py",
])
blacklist = convert_to_native_paths(blacklist)
return blacklist
def _doctest(*paths, **kwargs):
"""
Internal function that actually runs the doctests.
All keyword arguments from ``doctest()`` are passed to this function
except for ``subprocess``.
Returns 0 if tests passed and 1 if they failed. See the docstrings of
``doctest()`` and ``test()`` for more information.
"""
from sympy.printing.pretty.pretty import pprint_use_unicode
normal = kwargs.get("normal", False)
verbose = kwargs.get("verbose", False)
colors = kwargs.get("colors", True)
force_colors = kwargs.get("force_colors", False)
blacklist = kwargs.get("blacklist", [])
split = kwargs.get('split', None)
blacklist.extend(_get_doctest_blacklist())
# Use a non-windowed backend, so that the tests work on Travis
if import_module('matplotlib') is not None:
import matplotlib
matplotlib.use('Agg')
# Disable warnings for external modules
import sympy.external
sympy.external.importtools.WARN_OLD_VERSION = False
sympy.external.importtools.WARN_NOT_INSTALLED = False
# Disable showing up of plots
from sympy.plotting.plot import unset_show
unset_show()
r = PyTestReporter(verbose, split=split, colors=colors,\
force_colors=force_colors)
t = SymPyDocTests(r, normal)
test_files = t.get_test_files('sympy')
test_files.extend(t.get_test_files('examples', init_only=False))
not_blacklisted = [f for f in test_files
if not any(b in f for b in blacklist)]
if len(paths) == 0:
matched = not_blacklisted
else:
# take only what was requested...but not blacklisted items
# and allow for partial match anywhere or fnmatch of name
paths = convert_to_native_paths(paths)
matched = []
for f in not_blacklisted:
basename = os.path.basename(f)
for p in paths:
if p in f or fnmatch(basename, p):
matched.append(f)
break
matched.sort()
if split:
matched = split_list(matched, split)
t._testfiles.extend(matched)
# run the tests and record the result for this *py portion of the tests
if t._testfiles:
failed = not t.test()
else:
failed = False
# N.B.
# --------------------------------------------------------------------
# Here we test *.rst and *.md files at or below doc/src. Code from these
# must be self supporting in terms of imports since there is no importing
# of necessary modules by doctest.testfile. If you try to pass *.py files
# through this they might fail because they will lack the needed imports
# and smarter parsing that can be done with source code.
#
test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False)
test_files_md = t.get_test_files('doc/src', '*.md', init_only=False)
test_files = test_files_rst + test_files_md
test_files.sort()
not_blacklisted = [f for f in test_files
if not any(b in f for b in blacklist)]
if len(paths) == 0:
matched = not_blacklisted
else:
# Take only what was requested as long as it's not on the blacklist.
# Paths were already made native in *py tests so don't repeat here.
# There's no chance of having a *py file slip through since we
# only have *rst files in test_files.
matched = []
for f in not_blacklisted:
basename = os.path.basename(f)
for p in paths:
if p in f or fnmatch(basename, p):
matched.append(f)
break
if split:
matched = split_list(matched, split)
first_report = True
for rst_file in matched:
if not os.path.isfile(rst_file):
continue
old_displayhook = sys.displayhook
try:
use_unicode_prev = setup_pprint()
out = sympytestfile(
rst_file, module_relative=False, encoding='utf-8',
optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE |
pdoctest.IGNORE_EXCEPTION_DETAIL)
finally:
# make sure we return to the original displayhook in case some
# doctest has changed that
sys.displayhook = old_displayhook
# The NO_GLOBAL flag overrides the no_global flag to init_printing
# if True
import sympy.interactive.printing as interactive_printing
interactive_printing.NO_GLOBAL = False
pprint_use_unicode(use_unicode_prev)
rstfailed, tested = out
if tested:
failed = rstfailed or failed
if first_report:
first_report = False
msg = 'rst/md doctests start'
if not t._testfiles:
r.start(msg=msg)
else:
r.write_center(msg)
print()
# use as the id, everything past the first 'sympy'
file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:]
print(file_id, end=" ")
# get at least the name out so it is know who is being tested
wid = r.terminal_width - len(file_id) - 1 # update width
test_file = '[%s]' % (tested)
report = '[%s]' % (rstfailed or 'OK')
print(''.join(
[test_file, ' '*(wid - len(test_file) - len(report)), report])
)
# the doctests for *py will have printed this message already if there was
# a failure, so now only print it if there was intervening reporting by
# testing the *rst as evidenced by first_report no longer being True.
if not first_report and failed:
print()
print("DO *NOT* COMMIT!")
return int(failed)
sp = re.compile(r'([0-9]+)/([1-9][0-9]*)')
def split_list(l, split, density=None):
"""
Splits a list into part a of b
split should be a string of the form 'a/b'. For instance, '1/3' would give
the split one of three.
If the length of the list is not divisible by the number of splits, the
last split will have more items.
`density` may be specified as a list. If specified,
tests will be balanced so that each split has as equal-as-possible
amount of mass according to `density`.
>>> from sympy.testing.runtests import split_list
>>> a = list(range(10))
>>> split_list(a, '1/3')
[0, 1, 2]
>>> split_list(a, '2/3')
[3, 4, 5]
>>> split_list(a, '3/3')
[6, 7, 8, 9]
"""
m = sp.match(split)
if not m:
raise ValueError("split must be a string of the form a/b where a and b are ints")
i, t = map(int, m.groups())
if not density:
return l[(i - 1)*len(l)//t : i*len(l)//t]
# normalize density
tot = sum(density)
density = [x / tot for x in density]
def density_inv(x):
"""Interpolate the inverse to the cumulative
distribution function given by density"""
if x <= 0:
return 0
if x >= sum(density):
return 1
# find the first time the cumulative sum surpasses x
# and linearly interpolate
cumm = 0
for i, d in enumerate(density):
cumm += d
if cumm >= x:
break
frac = (d - (cumm - x)) / d
return (i + frac) / len(density)
lower_frac = density_inv((i - 1) / t)
higher_frac = density_inv(i / t)
return l[int(lower_frac*len(l)) : int(higher_frac*len(l))]
from collections import namedtuple
SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted')
def sympytestfile(filename, module_relative=True, name=None, package=None,
globs=None, verbose=None, report=True, optionflags=0,
extraglobs=None, raise_on_error=False,
parser=pdoctest.DocTestParser(), encoding=None):
"""
Test examples in the given file. Return (#failures, #tests).
Optional keyword arg ``module_relative`` specifies how filenames
should be interpreted:
- If ``module_relative`` is True (the default), then ``filename``
specifies a module-relative path. By default, this path is
relative to the calling module's directory; but if the
``package`` argument is specified, then it is relative to that
package. To ensure os-independence, ``filename`` should use
"/" characters to separate path segments, and should not
be an absolute path (i.e., it may not begin with "/").
- If ``module_relative`` is False, then ``filename`` specifies an
os-specific path. The path may be absolute or relative (to
the current working directory).
Optional keyword arg ``name`` gives the name of the test; by default
use the file's basename.
Optional keyword argument ``package`` is a Python package or the
name of a Python package whose directory should be used as the
base directory for a module relative filename. If no package is
specified, then the calling module's directory is used as the base
directory for module relative filenames. It is an error to
specify ``package`` if ``module_relative`` is False.
Optional keyword arg ``globs`` gives a dict to be used as the globals
when executing examples; by default, use {}. A copy of this dict
is actually used for each docstring, so that each docstring's
examples start with a clean slate.
Optional keyword arg ``extraglobs`` gives a dictionary that should be
merged into the globals that are used to execute examples. By
default, no extra globals are used.
Optional keyword arg ``verbose`` prints lots of stuff if true, prints
only failures if false; by default, it's true iff "-v" is in sys.argv.
Optional keyword arg ``report`` prints a summary at the end when true,
else prints nothing at the end. In verbose mode, the summary is
detailed, else very brief (in fact, empty if all tests passed).
Optional keyword arg ``optionflags`` or's together module constants,
and defaults to 0. Possible values (see the docs for details):
- DONT_ACCEPT_TRUE_FOR_1
- DONT_ACCEPT_BLANKLINE
- NORMALIZE_WHITESPACE
- ELLIPSIS
- SKIP
- IGNORE_EXCEPTION_DETAIL
- REPORT_UDIFF
- REPORT_CDIFF
- REPORT_NDIFF
- REPORT_ONLY_FIRST_FAILURE
Optional keyword arg ``raise_on_error`` raises an exception on the
first unexpected exception or failure. This allows failures to be
post-mortem debugged.
Optional keyword arg ``parser`` specifies a DocTestParser (or
subclass) that should be used to extract tests from the files.
Optional keyword arg ``encoding`` specifies an encoding that should
be used to convert the file to unicode.
Advanced tomfoolery: testmod runs methods of a local instance of
class doctest.Tester, then merges the results into (or creates)
global Tester instance doctest.master. Methods of doctest.master
can be called directly too, if you want to do something unusual.
Passing report=0 to testmod is especially useful then, to delay
displaying a summary. Invoke doctest.master.summarize(verbose)
when you're done fiddling.
"""
if package and not module_relative:
raise ValueError("Package may only be specified for module-"
"relative paths.")
# Relativize the path
text, filename = pdoctest._load_testfile(
filename, package, module_relative, encoding)
# If no name was given, then use the file's name.
if name is None:
name = os.path.basename(filename)
# Assemble the globals.
if globs is None:
globs = {}
else:
globs = globs.copy()
if extraglobs is not None:
globs.update(extraglobs)
if '__name__' not in globs:
globs['__name__'] = '__main__'
if raise_on_error:
runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags)
else:
runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags)
runner._checker = SymPyOutputChecker()
# Read the file, convert it to a test, and run it.
test = parser.get_doctest(text, globs, name, filename, 0)
runner.run(test)
if report:
runner.summarize()
if pdoctest.master is None:
pdoctest.master = runner
else:
pdoctest.master.merge(runner)
return SymPyTestResults(runner.failures, runner.tries)
class SymPyTests:
def __init__(self, reporter, kw="", post_mortem=False,
seed=None, fast_threshold=None, slow_threshold=None):
self._post_mortem = post_mortem
self._kw = kw
self._count = 0
self._root_dir = get_sympy_dir()
self._reporter = reporter
self._reporter.root_dir(self._root_dir)
self._testfiles = []
self._seed = seed if seed is not None else random.random()
# Defaults in seconds, from human / UX design limits
# http://www.nngroup.com/articles/response-times-3-important-limits/
#
# These defaults are *NOT* set in stone as we are measuring different
# things, so others feel free to come up with a better yardstick :)
if fast_threshold:
self._fast_threshold = float(fast_threshold)
else:
self._fast_threshold = 8
if slow_threshold:
self._slow_threshold = float(slow_threshold)
else:
self._slow_threshold = 10
def test(self, sort=False, timeout=False, slow=False,
enhance_asserts=False, fail_on_timeout=False):
"""
Runs the tests returning True if all tests pass, otherwise False.
If sort=False run tests in random order.
"""
if sort:
self._testfiles.sort()
elif slow:
pass
else:
random.seed(self._seed)
random.shuffle(self._testfiles)
self._reporter.start(self._seed)
for f in self._testfiles:
try:
self.test_file(f, sort, timeout, slow,
enhance_asserts, fail_on_timeout)
except KeyboardInterrupt:
print(" interrupted by user")
self._reporter.finish()
raise
return self._reporter.finish()
def _enhance_asserts(self, source):
from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple,
Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations)
ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=',
"Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not',
"In": 'in', "NotIn": 'not in'}
class Transform(NodeTransformer):
def visit_Assert(self, stmt):
if isinstance(stmt.test, Compare):
compare = stmt.test
values = [compare.left] + compare.comparators
names = [ "_%s" % i for i, _ in enumerate(values) ]
names_store = [ Name(n, Store()) for n in names ]
names_load = [ Name(n, Load()) for n in names ]
target = Tuple(names_store, Store())
value = Tuple(values, Load())
assign = Assign([target], value)
new_compare = Compare(names_load[0], compare.ops, names_load[1:])
msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s"
msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load()))
test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset)
return [assign, test]
else:
return stmt
tree = parse(source)
new_tree = Transform().visit(tree)
return fix_missing_locations(new_tree)
def test_file(self, filename, sort=True, timeout=False, slow=False,
enhance_asserts=False, fail_on_timeout=False):
reporter = self._reporter
funcs = []
try:
gl = {'__file__': filename}
try:
open_file = lambda: open(filename, encoding="utf8")
with open_file() as f:
source = f.read()
if self._kw:
for l in source.splitlines():
if l.lstrip().startswith('def '):
if any(l.lower().find(k.lower()) != -1 for k in self._kw):
break
else:
return
if enhance_asserts:
try:
source = self._enhance_asserts(source)
except ImportError:
pass
code = compile(source, filename, "exec", flags=0, dont_inherit=True)
exec(code, gl)
except (SystemExit, KeyboardInterrupt):
raise
except ImportError:
reporter.import_error(filename, sys.exc_info())
return
except Exception:
reporter.test_exception(sys.exc_info())
clear_cache()
self._count += 1
random.seed(self._seed)
disabled = gl.get("disabled", False)
if not disabled:
# we need to filter only those functions that begin with 'test_'
# We have to be careful about decorated functions. As long as
# the decorator uses functools.wraps, we can detect it.
funcs = []
for f in gl:
if (f.startswith("test_") and (inspect.isfunction(gl[f])
or inspect.ismethod(gl[f]))):
func = gl[f]
# Handle multiple decorators
while hasattr(func, '__wrapped__'):
func = func.__wrapped__
if inspect.getsourcefile(func) == filename:
funcs.append(gl[f])
if slow:
funcs = [f for f in funcs if getattr(f, '_slow', False)]
# Sorting of XFAILed functions isn't fixed yet :-(
funcs.sort(key=lambda x: inspect.getsourcelines(x)[1])
i = 0
while i < len(funcs):
if inspect.isgeneratorfunction(funcs[i]):
# some tests can be generators, that return the actual
# test functions. We unpack it below:
f = funcs.pop(i)
for fg in f():
func = fg[0]
args = fg[1:]
fgw = lambda: func(*args)
funcs.insert(i, fgw)
i += 1
else:
i += 1
# drop functions that are not selected with the keyword expression:
funcs = [x for x in funcs if self.matches(x)]
if not funcs:
return
except Exception:
reporter.entering_filename(filename, len(funcs))
raise
reporter.entering_filename(filename, len(funcs))
if not sort:
random.shuffle(funcs)
for f in funcs:
start = time.time()
reporter.entering_test(f)
try:
if getattr(f, '_slow', False) and not slow:
raise Skipped("Slow")
with raise_on_deprecated():
if timeout:
self._timeout(f, timeout, fail_on_timeout)
else:
random.seed(self._seed)
f()
except KeyboardInterrupt:
if getattr(f, '_slow', False):
reporter.test_skip("KeyboardInterrupt")
else:
raise
except Exception:
if timeout:
signal.alarm(0) # Disable the alarm. It could not be handled before.
t, v, tr = sys.exc_info()
if t is AssertionError:
reporter.test_fail((t, v, tr))
if self._post_mortem:
pdb.post_mortem(tr)
elif t.__name__ == "Skipped":
reporter.test_skip(v)
elif t.__name__ == "XFail":
reporter.test_xfail()
elif t.__name__ == "XPass":
reporter.test_xpass(v)
else:
reporter.test_exception((t, v, tr))
if self._post_mortem:
pdb.post_mortem(tr)
else:
reporter.test_pass()
taken = time.time() - start
if taken > self._slow_threshold:
filename = os.path.relpath(filename, reporter._root_dir)
reporter.slow_test_functions.append(
(filename + "::" + f.__name__, taken))
if getattr(f, '_slow', False) and slow:
if taken < self._fast_threshold:
filename = os.path.relpath(filename, reporter._root_dir)
reporter.fast_test_functions.append(
(filename + "::" + f.__name__, taken))
reporter.leaving_filename()
def _timeout(self, function, timeout, fail_on_timeout):
def callback(x, y):
signal.alarm(0)
if fail_on_timeout:
raise TimeOutError("Timed out after %d seconds" % timeout)
else:
raise Skipped("Timeout")
signal.signal(signal.SIGALRM, callback)
signal.alarm(timeout) # Set an alarm with a given timeout
function()
signal.alarm(0) # Disable the alarm
def matches(self, x):
"""
Does the keyword expression self._kw match "x"? Returns True/False.
Always returns True if self._kw is "".
"""
if not self._kw:
return True
for kw in self._kw:
if x.__name__.lower().find(kw.lower()) != -1:
return True
return False
def get_test_files(self, dir, pat='test_*.py'):
"""
Returns the list of test_*.py (default) files at or below directory
``dir`` relative to the SymPy home directory.
"""
dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
g = []
for path, folders, files in os.walk(dir):
g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)])
return sorted([os.path.normcase(gi) for gi in g])
class SymPyDocTests:
def __init__(self, reporter, normal):
self._count = 0
self._root_dir = get_sympy_dir()
self._reporter = reporter
self._reporter.root_dir(self._root_dir)
self._normal = normal
self._testfiles = []
def test(self):
"""
Runs the tests and returns True if all tests pass, otherwise False.
"""
self._reporter.start()
for f in self._testfiles:
try:
self.test_file(f)
except KeyboardInterrupt:
print(" interrupted by user")
self._reporter.finish()
raise
return self._reporter.finish()
def test_file(self, filename):
clear_cache()
from io import StringIO
import sympy.interactive.printing as interactive_printing
from sympy.printing.pretty.pretty import pprint_use_unicode
rel_name = filename[len(self._root_dir) + 1:]
dirname, file = os.path.split(filename)
module = rel_name.replace(os.sep, '.')[:-3]
if rel_name.startswith("examples"):
# Examples files do not have __init__.py files,
# So we have to temporarily extend sys.path to import them
sys.path.insert(0, dirname)
module = file[:-3] # remove ".py"
try:
module = pdoctest._normalize_module(module)
tests = SymPyDocTestFinder().find(module)
except (SystemExit, KeyboardInterrupt):
raise
except ImportError:
self._reporter.import_error(filename, sys.exc_info())
return
finally:
if rel_name.startswith("examples"):
del sys.path[0]
tests = [test for test in tests if len(test.examples) > 0]
# By default tests are sorted by alphabetical order by function name.
# We sort by line number so one can edit the file sequentially from
# bottom to top. However, if there are decorated functions, their line
# numbers will be too large and for now one must just search for these
# by text and function name.
tests.sort(key=lambda x: -x.lineno)
if not tests:
return
self._reporter.entering_filename(filename, len(tests))
for test in tests:
assert len(test.examples) != 0
if self._reporter._verbose:
self._reporter.write("\n{} ".format(test.name))
# check if there are external dependencies which need to be met
if '_doctest_depends_on' in test.globs:
try:
self._check_dependencies(**test.globs['_doctest_depends_on'])
except DependencyError as e:
self._reporter.test_skip(v=str(e))
continue
runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS |
pdoctest.NORMALIZE_WHITESPACE |
pdoctest.IGNORE_EXCEPTION_DETAIL)
runner._checker = SymPyOutputChecker()
old = sys.stdout
new = StringIO()
sys.stdout = new
# If the testing is normal, the doctests get importing magic to
# provide the global namespace. If not normal (the default) then
# then must run on their own; all imports must be explicit within
# a function's docstring. Once imported that import will be
# available to the rest of the tests in a given function's
# docstring (unless clear_globs=True below).
if not self._normal:
test.globs = {}
# if this is uncommented then all the test would get is what
# comes by default with a "from sympy import *"
#exec('from sympy import *') in test.globs
old_displayhook = sys.displayhook
use_unicode_prev = setup_pprint()
try:
f, t = runner.run(test,
out=new.write, clear_globs=False)
except KeyboardInterrupt:
raise
finally:
sys.stdout = old
if f > 0:
self._reporter.doctest_fail(test.name, new.getvalue())
else:
self._reporter.test_pass()
sys.displayhook = old_displayhook
interactive_printing.NO_GLOBAL = False
pprint_use_unicode(use_unicode_prev)
self._reporter.leaving_filename()
def get_test_files(self, dir, pat='*.py', init_only=True):
r"""
Returns the list of \*.py files (default) from which docstrings
will be tested which are at or below directory ``dir``. By default,
only those that have an __init__.py in their parent directory
and do not start with ``test_`` will be included.
"""
def importable(x):
"""
Checks if given pathname x is an importable module by checking for
__init__.py file.
Returns True/False.
Currently we only test if the __init__.py file exists in the
directory with the file "x" (in theory we should also test all the
parent dirs).
"""
init_py = os.path.join(os.path.dirname(x), "__init__.py")
return os.path.exists(init_py)
dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
g = []
for path, folders, files in os.walk(dir):
g.extend([os.path.join(path, f) for f in files
if not f.startswith('test_') and fnmatch(f, pat)])
if init_only:
# skip files that are not importable (i.e. missing __init__.py)
g = [x for x in g if importable(x)]
return [os.path.normcase(gi) for gi in g]
def _check_dependencies(self,
executables=(),
modules=(),
disable_viewers=(),
python_version=(3, 5)):
"""
Checks if the dependencies for the test are installed.
Raises ``DependencyError`` it at least one dependency is not installed.
"""
for executable in executables:
if not shutil.which(executable):
raise DependencyError("Could not find %s" % executable)
for module in modules:
if module == 'matplotlib':
matplotlib = import_module(
'matplotlib',
import_kwargs={'fromlist':
['pyplot', 'cm', 'collections']},
min_module_version='1.0.0', catch=(RuntimeError,))
if matplotlib is None:
raise DependencyError("Could not import matplotlib")
else:
if not import_module(module):
raise DependencyError("Could not import %s" % module)
if disable_viewers:
tempdir = tempfile.mkdtemp()
os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH'])
vw = ('#!/usr/bin/env python3\n'
'import sys\n'
'if len(sys.argv) <= 1:\n'
' exit("wrong number of args")\n')
for viewer in disable_viewers:
with open(os.path.join(tempdir, viewer), 'w') as fh:
fh.write(vw)
# make the file executable
os.chmod(os.path.join(tempdir, viewer),
stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR)
if python_version:
if sys.version_info < python_version:
raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version)))
if 'pyglet' in modules:
# monkey-patch pyglet s.t. it does not open a window during
# doctesting
import pyglet
class DummyWindow:
def __init__(self, *args, **kwargs):
self.has_exit = True
self.width = 600
self.height = 400
def set_vsync(self, x):
pass
def switch_to(self):
pass
def push_handlers(self, x):
pass
def close(self):
pass
pyglet.window.Window = DummyWindow
class SymPyDocTestFinder(DocTestFinder):
"""
A class used to extract the DocTests that are relevant to a given
object, from its docstring and the docstrings of its contained
objects. Doctests can currently be extracted from the following
object types: modules, functions, classes, methods, staticmethods,
classmethods, and properties.
Modified from doctest's version to look harder for code that
appears comes from a different module. For example, the @vectorize
decorator makes it look like functions come from multidimensional.py
even though their code exists elsewhere.
"""
def _find(self, tests, obj, name, module, source_lines, globs, seen):
"""
Find tests for the given object and any contained objects, and
add them to ``tests``.
"""
if self._verbose:
print('Finding tests in %s' % name)
# If we've already processed this object, then ignore it.
if id(obj) in seen:
return
seen[id(obj)] = 1
# Make sure we don't run doctests for classes outside of sympy, such
# as in numpy or scipy.
if inspect.isclass(obj):
if obj.__module__.split('.')[0] != 'sympy':
return
# Find a test for this object, and add it to the list of tests.
test = self._get_test(obj, name, module, globs, source_lines)
if test is not None:
tests.append(test)
if not self._recurse:
return
# Look for tests in a module's contained objects.
if inspect.ismodule(obj):
for rawname, val in obj.__dict__.items():
# Recurse to functions & classes.
if inspect.isfunction(val) or inspect.isclass(val):
# Make sure we don't run doctests functions or classes
# from different modules
if val.__module__ != module.__name__:
continue
assert self._from_module(module, val), \
"%s is not in module %s (rawname %s)" % (val, module, rawname)
try:
valname = '%s.%s' % (name, rawname)
self._find(tests, val, valname, module,
source_lines, globs, seen)
except KeyboardInterrupt:
raise
# Look for tests in a module's __test__ dictionary.
for valname, val in getattr(obj, '__test__', {}).items():
if not isinstance(valname, str):
raise ValueError("SymPyDocTestFinder.find: __test__ keys "
"must be strings: %r" %
(type(valname),))
if not (inspect.isfunction(val) or inspect.isclass(val) or
inspect.ismethod(val) or inspect.ismodule(val) or
isinstance(val, str)):
raise ValueError("SymPyDocTestFinder.find: __test__ values "
"must be strings, functions, methods, "
"classes, or modules: %r" %
(type(val),))
valname = '%s.__test__.%s' % (name, valname)
self._find(tests, val, valname, module, source_lines,
globs, seen)
# Look for tests in a class's contained objects.
if inspect.isclass(obj):
for valname, val in obj.__dict__.items():
# Special handling for staticmethod/classmethod.
if isinstance(val, staticmethod):
val = getattr(obj, valname)
if isinstance(val, classmethod):
val = getattr(obj, valname).__func__
# Recurse to methods, properties, and nested classes.
if ((inspect.isfunction(unwrap(val)) or
inspect.isclass(val) or
isinstance(val, property)) and
self._from_module(module, val)):
# Make sure we don't run doctests functions or classes
# from different modules
if isinstance(val, property):
if hasattr(val.fget, '__module__'):
if val.fget.__module__ != module.__name__:
continue
else:
if val.__module__ != module.__name__:
continue
assert self._from_module(module, val), \
"%s is not in module %s (valname %s)" % (
val, module, valname)
valname = '%s.%s' % (name, valname)
self._find(tests, val, valname, module, source_lines,
globs, seen)
def _get_test(self, obj, name, module, globs, source_lines):
"""
Return a DocTest for the given object, if it defines a docstring;
otherwise, return None.
"""
lineno = None
# Extract the object's docstring. If it does not have one,
# then return None (no test for this object).
if isinstance(obj, str):
# obj is a string in the case for objects in the polys package.
# Note that source_lines is a binary string (compiled polys
# modules), which can't be handled by _find_lineno so determine
# the line number here.
docstring = obj
matches = re.findall(r"line \d+", name)
assert len(matches) == 1, \
"string '%s' does not contain lineno " % name
# NOTE: this is not the exact linenumber but its better than no
# lineno ;)
lineno = int(matches[0][5:])
else:
try:
if obj.__doc__ is None:
docstring = ''
else:
docstring = obj.__doc__
if not isinstance(docstring, str):
docstring = str(docstring)
except (TypeError, AttributeError):
docstring = ''
# Don't bother if the docstring is empty.
if self._exclude_empty and not docstring:
return None
# check that properties have a docstring because _find_lineno
# assumes it
if isinstance(obj, property):
if obj.fget.__doc__ is None:
return None
# Find the docstring's location in the file.
if lineno is None:
obj = unwrap(obj)
# handling of properties is not implemented in _find_lineno so do
# it here
if hasattr(obj, 'func_closure') and obj.func_closure is not None:
tobj = obj.func_closure[0].cell_contents
elif isinstance(obj, property):
tobj = obj.fget
else:
tobj = obj
lineno = self._find_lineno(tobj, source_lines)
if lineno is None:
return None
# Return a DocTest for this object.
if module is None:
filename = None
else:
filename = getattr(module, '__file__', module.__name__)
if filename[-4:] in (".pyc", ".pyo"):
filename = filename[:-1]
globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {})
return self._parser.get_doctest(docstring, globs, name,
filename, lineno)
class SymPyDocTestRunner(DocTestRunner):
"""
A class used to run DocTest test cases, and accumulate statistics.
The ``run`` method is used to process a single DocTest case. It
returns a tuple ``(f, t)``, where ``t`` is the number of test cases
tried, and ``f`` is the number of test cases that failed.
Modified from the doctest version to not reset the sys.displayhook (see
issue 5140).
See the docstring of the original DocTestRunner for more information.
"""
def run(self, test, compileflags=None, out=None, clear_globs=True):
"""
Run the examples in ``test``, and display the results using the
writer function ``out``.
The examples are run in the namespace ``test.globs``. If
``clear_globs`` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collection. If you would like to examine the namespace after
the test completes, then use ``clear_globs=False``.
``compileflags`` gives the set of flags that should be used by
the Python compiler when running the examples. If not
specified, then it will default to the set of future-import
flags that apply to ``globs``.
The output of each example is checked using
``SymPyDocTestRunner.check_output``, and the results are
formatted by the ``SymPyDocTestRunner.report_*`` methods.
"""
self.test = test
# Remove ``` from the end of example, which may appear in Markdown
# files
for example in test.examples:
example.want = example.want.replace('```\n', '')
example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '')
if compileflags is None:
compileflags = pdoctest._extract_future_flags(test.globs)
save_stdout = sys.stdout
if out is None:
out = save_stdout.write
sys.stdout = self._fakeout
# Patch pdb.set_trace to restore sys.stdout during interactive
# debugging (so it's not still redirected to self._fakeout).
# Note that the interactive output will go to *our*
# save_stdout, even if that's not the real sys.stdout; this
# allows us to write test cases for the set_trace behavior.
save_set_trace = pdb.set_trace
self.debugger = pdoctest._OutputRedirectingPdb(save_stdout)
self.debugger.reset()
pdb.set_trace = self.debugger.set_trace
# Patch linecache.getlines, so we can see the example's source
# when we're inside the debugger.
self.save_linecache_getlines = pdoctest.linecache.getlines
linecache.getlines = self.__patched_linecache_getlines
# Fail for deprecation warnings
with raise_on_deprecated():
try:
return self.__run(test, compileflags, out)
finally:
sys.stdout = save_stdout
pdb.set_trace = save_set_trace
linecache.getlines = self.save_linecache_getlines
if clear_globs:
test.globs.clear()
# We have to override the name mangled methods.
monkeypatched_methods = [
'patched_linecache_getlines',
'run',
'record_outcome'
]
for method in monkeypatched_methods:
oldname = '_DocTestRunner__' + method
newname = '_SymPyDocTestRunner__' + method
setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname))
class SymPyOutputChecker(pdoctest.OutputChecker):
"""
Compared to the OutputChecker from the stdlib our OutputChecker class
supports numerical comparison of floats occurring in the output of the
doctest examples
"""
def __init__(self):
# NOTE OutputChecker is an old-style class with no __init__ method,
# so we can't call the base class version of __init__ here
got_floats = r'(\d+\.\d*|\.\d+)'
# floats in the 'want' string may contain ellipses
want_floats = got_floats + r'(\.{3})?'
front_sep = r'\s|\+|\-|\*|,'
back_sep = front_sep + r'|j|e'
fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep)
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep)
self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep)
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep)
self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
def check_output(self, want, got, optionflags):
"""
Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See the
documentation for `TestRunner` for more information about
option flags.
"""
# Handle the common case first, for efficiency:
# if they're string-identical, always return true.
if got == want:
return True
# TODO parse integers as well ?
# Parse floats and compare them. If some of the parsed floats contain
# ellipses, skip the comparison.
matches = self.num_got_rgx.finditer(got)
numbers_got = [match.group(1) for match in matches] # list of strs
matches = self.num_want_rgx.finditer(want)
numbers_want = [match.group(1) for match in matches] # list of strs
if len(numbers_got) != len(numbers_want):
return False
if len(numbers_got) > 0:
nw_ = []
for ng, nw in zip(numbers_got, numbers_want):
if '...' in nw:
nw_.append(ng)
continue
else:
nw_.append(nw)
if abs(float(ng)-float(nw)) > 1e-5:
return False
got = self.num_got_rgx.sub(r'%s', got)
got = got % tuple(nw_)
# <BLANKLINE> can be used as a special sequence to signify a
# blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE):
# Replace <BLANKLINE> in want with a blank line.
want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER),
'', want)
# If a line in got contains only spaces, then remove the
# spaces.
got = re.sub(r'(?m)^\s*?$', '', got)
if got == want:
return True
# This flag causes doctest to ignore any differences in the
# contents of whitespace strings. Note that this can be used
# in conjunction with the ELLIPSIS flag.
if optionflags & pdoctest.NORMALIZE_WHITESPACE:
got = ' '.join(got.split())
want = ' '.join(want.split())
if got == want:
return True
# The ELLIPSIS flag says to let the sequence "..." in `want`
# match any substring in `got`.
if optionflags & pdoctest.ELLIPSIS:
if pdoctest._ellipsis_match(want, got):
return True
# We didn't find any match; return false.
return False
class Reporter:
"""
Parent class for all reporters.
"""
pass
class PyTestReporter(Reporter):
"""
Py.test like reporter. Should produce output identical to py.test.
"""
def __init__(self, verbose=False, tb="short", colors=True,
force_colors=False, split=None):
self._verbose = verbose
self._tb_style = tb
self._colors = colors
self._force_colors = force_colors
self._xfailed = 0
self._xpassed = []
self._failed = []
self._failed_doctest = []
self._passed = 0
self._skipped = 0
self._exceptions = []
self._terminal_width = None
self._default_width = 80
self._split = split
self._active_file = ''
self._active_f = None
# TODO: Should these be protected?
self.slow_test_functions = []
self.fast_test_functions = []
# this tracks the x-position of the cursor (useful for positioning
# things on the screen), without the need for any readline library:
self._write_pos = 0
self._line_wrap = False
def root_dir(self, dir):
self._root_dir = dir
@property
def terminal_width(self):
if self._terminal_width is not None:
return self._terminal_width
def findout_terminal_width():
if sys.platform == "win32":
# Windows support is based on:
#
# http://code.activestate.com/recipes/
# 440694-determine-size-of-console-window-on-windows/
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
import struct
(_, _, _, _, _, left, _, right, _, _, _) = \
struct.unpack("hhhhHhhhhhh", csbi.raw)
return right - left
else:
return self._default_width
if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
return self._default_width # leave PIPEs alone
try:
process = subprocess.Popen(['stty', '-a'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout = stdout.decode("utf-8")
except OSError:
pass
else:
# We support the following output formats from stty:
#
# 1) Linux -> columns 80
# 2) OS X -> 80 columns
# 3) Solaris -> columns = 80
re_linux = r"columns\s+(?P<columns>\d+);"
re_osx = r"(?P<columns>\d+)\s*columns;"
re_solaris = r"columns\s+=\s+(?P<columns>\d+);"
for regex in (re_linux, re_osx, re_solaris):
match = re.search(regex, stdout)
if match is not None:
columns = match.group('columns')
try:
width = int(columns)
except ValueError:
pass
if width != 0:
return width
return self._default_width
width = findout_terminal_width()
self._terminal_width = width
return width
def write(self, text, color="", align="left", width=None,
force_colors=False):
"""
Prints a text on the screen.
It uses sys.stdout.write(), so no readline library is necessary.
Parameters
==========
color : choose from the colors below, "" means default color
align : "left"/"right", "left" is a normal print, "right" is aligned on
the right-hand side of the screen, filled with spaces if
necessary
width : the screen width
"""
color_templates = (
("Black", "0;30"),
("Red", "0;31"),
("Green", "0;32"),
("Brown", "0;33"),
("Blue", "0;34"),
("Purple", "0;35"),
("Cyan", "0;36"),
("LightGray", "0;37"),
("DarkGray", "1;30"),
("LightRed", "1;31"),
("LightGreen", "1;32"),
("Yellow", "1;33"),
("LightBlue", "1;34"),
("LightPurple", "1;35"),
("LightCyan", "1;36"),
("White", "1;37"),
)
colors = {}
for name, value in color_templates:
colors[name] = value
c_normal = '\033[0m'
c_color = '\033[%sm'
if width is None:
width = self.terminal_width
if align == "right":
if self._write_pos + len(text) > width:
# we don't fit on the current line, create a new line
self.write("\n")
self.write(" "*(width - self._write_pos - len(text)))
if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \
sys.stdout.isatty():
# the stdout is not a terminal, this for example happens if the
# output is piped to less, e.g. "bin/test | less". In this case,
# the terminal control sequences would be printed verbatim, so
# don't use any colors.
color = ""
elif sys.platform == "win32":
# Windows consoles don't support ANSI escape sequences
color = ""
elif not self._colors:
color = ""
if self._line_wrap:
if text[0] != "\n":
sys.stdout.write("\n")
# Avoid UnicodeEncodeError when printing out test failures
if IS_WINDOWS:
text = text.encode('raw_unicode_escape').decode('utf8', 'ignore')
elif not sys.stdout.encoding.lower().startswith('utf'):
text = text.encode(sys.stdout.encoding, 'backslashreplace'
).decode(sys.stdout.encoding)
if color == "":
sys.stdout.write(text)
else:
sys.stdout.write("%s%s%s" %
(c_color % colors[color], text, c_normal))
sys.stdout.flush()
l = text.rfind("\n")
if l == -1:
self._write_pos += len(text)
else:
self._write_pos = len(text) - l - 1
self._line_wrap = self._write_pos >= width
self._write_pos %= width
def write_center(self, text, delim="="):
width = self.terminal_width
if text != "":
text = " %s " % text
idx = (width - len(text)) // 2
t = delim*idx + text + delim*(width - idx - len(text))
self.write(t + "\n")
def write_exception(self, e, val, tb):
# remove the first item, as that is always runtests.py
tb = tb.tb_next
t = traceback.format_exception(e, val, tb)
self.write("".join(t))
def start(self, seed=None, msg="test process starts"):
self.write_center(msg)
executable = sys.executable
v = tuple(sys.version_info)
python_version = "%s.%s.%s-%s-%s" % v
implementation = platform.python_implementation()
if implementation == 'PyPy':
implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info
self.write("executable: %s (%s) [%s]\n" %
(executable, python_version, implementation))
from sympy.utilities.misc import ARCH
self.write("architecture: %s\n" % ARCH)
from sympy.core.cache import USE_CACHE
self.write("cache: %s\n" % USE_CACHE)
version = ''
if GROUND_TYPES =='gmpy':
if HAS_GMPY == 1:
import gmpy
elif HAS_GMPY == 2:
import gmpy2 as gmpy
version = gmpy.version()
self.write("ground types: %s %s\n" % (GROUND_TYPES, version))
numpy = import_module('numpy')
self.write("numpy: %s\n" % (None if not numpy else numpy.__version__))
if seed is not None:
self.write("random seed: %d\n" % seed)
from sympy.utilities.misc import HASH_RANDOMIZATION
self.write("hash randomization: ")
hash_seed = os.getenv("PYTHONHASHSEED") or '0'
if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)):
self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed)
else:
self.write("off\n")
if self._split:
self.write("split: %s\n" % self._split)
self.write('\n')
self._t_start = clock()
def finish(self):
self._t_end = clock()
self.write("\n")
global text, linelen
text = "tests finished: %d passed, " % self._passed
linelen = len(text)
def add_text(mytext):
global text, linelen
"""Break new text if too long."""
if linelen + len(mytext) > self.terminal_width:
text += '\n'
linelen = 0
text += mytext
linelen += len(mytext)
if len(self._failed) > 0:
add_text("%d failed, " % len(self._failed))
if len(self._failed_doctest) > 0:
add_text("%d failed, " % len(self._failed_doctest))
if self._skipped > 0:
add_text("%d skipped, " % self._skipped)
if self._xfailed > 0:
add_text("%d expected to fail, " % self._xfailed)
if len(self._xpassed) > 0:
add_text("%d expected to fail but passed, " % len(self._xpassed))
if len(self._exceptions) > 0:
add_text("%d exceptions, " % len(self._exceptions))
add_text("in %.2f seconds" % (self._t_end - self._t_start))
if self.slow_test_functions:
self.write_center('slowest tests', '_')
sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1])
for slow_func_name, taken in sorted_slow:
print('%s - Took %.3f seconds' % (slow_func_name, taken))
if self.fast_test_functions:
self.write_center('unexpectedly fast tests', '_')
sorted_fast = sorted(self.fast_test_functions,
key=lambda r: r[1])
for fast_func_name, taken in sorted_fast:
print('%s - Took %.3f seconds' % (fast_func_name, taken))
if len(self._xpassed) > 0:
self.write_center("xpassed tests", "_")
for e in self._xpassed:
self.write("%s: %s\n" % (e[0], e[1]))
self.write("\n")
if self._tb_style != "no" and len(self._exceptions) > 0:
for e in self._exceptions:
filename, f, (t, val, tb) = e
self.write_center("", "_")
if f is None:
s = "%s" % filename
else:
s = "%s:%s" % (filename, f.__name__)
self.write_center(s, "_")
self.write_exception(t, val, tb)
self.write("\n")
if self._tb_style != "no" and len(self._failed) > 0:
for e in self._failed:
filename, f, (t, val, tb) = e
self.write_center("", "_")
self.write_center("%s:%s" % (filename, f.__name__), "_")
self.write_exception(t, val, tb)
self.write("\n")
if self._tb_style != "no" and len(self._failed_doctest) > 0:
for e in self._failed_doctest:
filename, msg = e
self.write_center("", "_")
self.write_center("%s" % filename, "_")
self.write(msg)
self.write("\n")
self.write_center(text)
ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \
len(self._failed_doctest) == 0
if not ok:
self.write("DO *NOT* COMMIT!\n")
return ok
def entering_filename(self, filename, n):
rel_name = filename[len(self._root_dir) + 1:]
self._active_file = rel_name
self._active_file_error = False
self.write(rel_name)
self.write("[%d] " % n)
def leaving_filename(self):
self.write(" ")
if self._active_file_error:
self.write("[FAIL]", "Red", align="right")
else:
self.write("[OK]", "Green", align="right")
self.write("\n")
if self._verbose:
self.write("\n")
def entering_test(self, f):
self._active_f = f
if self._verbose:
self.write("\n" + f.__name__ + " ")
def test_xfail(self):
self._xfailed += 1
self.write("f", "Green")
def test_xpass(self, v):
message = str(v)
self._xpassed.append((self._active_file, message))
self.write("X", "Green")
def test_fail(self, exc_info):
self._failed.append((self._active_file, self._active_f, exc_info))
self.write("F", "Red")
self._active_file_error = True
def doctest_fail(self, name, error_msg):
# the first line contains "******", remove it:
error_msg = "\n".join(error_msg.split("\n")[1:])
self._failed_doctest.append((name, error_msg))
self.write("F", "Red")
self._active_file_error = True
def test_pass(self, char="."):
self._passed += 1
if self._verbose:
self.write("ok", "Green")
else:
self.write(char, "Green")
def test_skip(self, v=None):
char = "s"
self._skipped += 1
if v is not None:
message = str(v)
if message == "KeyboardInterrupt":
char = "K"
elif message == "Timeout":
char = "T"
elif message == "Slow":
char = "w"
if self._verbose:
if v is not None:
self.write(message + ' ', "Blue")
else:
self.write(" - ", "Blue")
self.write(char, "Blue")
def test_exception(self, exc_info):
self._exceptions.append((self._active_file, self._active_f, exc_info))
if exc_info[0] is TimeOutError:
self.write("T", "Red")
else:
self.write("E", "Red")
self._active_file_error = True
def import_error(self, filename, exc_info):
self._exceptions.append((filename, None, exc_info))
rel_name = filename[len(self._root_dir) + 1:]
self.write(rel_name)
self.write("[?] Failed to import", "Red")
self.write(" ")
self.write("[FAIL]", "Red", align="right")
self.write("\n")
|
e2361cbfada07c72469497d871b9f4e81166348b3924288404d9f151b8363b2a | # -*- coding: utf-8 -*-
r"""
Wigner, Clebsch-Gordan, Racah, and Gaunt coefficients
Collection of functions for calculating Wigner 3j, 6j, 9j,
Clebsch-Gordan, Racah as well as Gaunt coefficients exactly, all
evaluating to a rational number times the square root of a rational
number [Rasch03]_.
Please see the description of the individual functions for further
details and examples.
References
==========
.. [Regge58] 'Symmetry Properties of Clebsch-Gordan Coefficients',
T. Regge, Nuovo Cimento, Volume 10, pp. 544 (1958)
.. [Regge59] 'Symmetry Properties of Racah Coefficients',
T. Regge, Nuovo Cimento, Volume 11, pp. 116 (1959)
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
Investigations in physics, 4.; Investigations in physics, no. 4.
Princeton, N.J., Princeton University Press, 1957.
.. [Rasch03] J. Rasch and A. C. H. Yu, 'Efficient Storage Scheme for
Pre-calculated Wigner 3j, 6j and Gaunt Coefficients', SIAM
J. Sci. Comput. Volume 25, Issue 4, pp. 1416-1428 (2003)
.. [Liberatodebrito82] 'FORTRAN program for the integral of three
spherical harmonics', A. Liberato de Brito,
Comput. Phys. Commun., Volume 25, pp. 81-85 (1982)
.. [Homeier96] 'Some Properties of the Coupling Coefficients of Real
Spherical Harmonics and Their Relation to Gaunt Coefficients',
H. H. H. Homeier and E. O. Steinborn J. Mol. Struct., Volume 368,
pp. 31-37 (1996)
Credits and Copyright
=====================
This code was taken from Sage with the permission of all authors:
https://groups.google.com/forum/#!topic/sage-devel/M4NZdu-7O38
Authors
=======
- Jens Rasch (2009-03-24): initial version for Sage
- Jens Rasch (2009-05-31): updated to sage-4.0
- Oscar Gerardo Lazo Arjona (2017-06-18): added Wigner D matrices
- Phil Adam LeMaitre (2022-09-19): added real Gaunt coefficient
Copyright (C) 2008 Jens Rasch <[email protected]>
"""
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.function import Function
from sympy.core.numbers import (I, Integer, pi)
from sympy.core.singleton import S
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import (binomial, factorial)
from sympy.functions.elementary.complexes import re
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.spherical_harmonics import Ynm
from sympy.matrices.dense import zeros
from sympy.matrices.immutable import ImmutableMatrix
from sympy.utilities.misc import as_int
# This list of precomputed factorials is needed to massively
# accelerate future calculations of the various coefficients
_Factlist = [1]
def _calc_factlist(nn):
r"""
Function calculates a list of precomputed factorials in order to
massively accelerate future calculations of the various
coefficients.
Parameters
==========
nn : integer
Highest factorial to be computed.
Returns
=======
list of integers :
The list of precomputed factorials.
Examples
========
Calculate list of factorials::
sage: from sage.functions.wigner import _calc_factlist
sage: _calc_factlist(10)
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
"""
if nn >= len(_Factlist):
for ii in range(len(_Factlist), int(nn + 1)):
_Factlist.append(_Factlist[ii - 1] * ii)
return _Factlist[:int(nn) + 1]
def wigner_3j(j_1, j_2, j_3, m_1, m_2, m_3):
r"""
Calculate the Wigner 3j symbol `\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)`.
Parameters
==========
j_1, j_2, j_3, m_1, m_2, m_3 :
Integer or half integer.
Returns
=======
Rational number times the square root of a rational number.
Examples
========
>>> from sympy.physics.wigner import wigner_3j
>>> wigner_3j(2, 6, 4, 0, 0, 0)
sqrt(715)/143
>>> wigner_3j(2, 6, 4, 0, 0, 1)
0
It is an error to have arguments that are not integer or half
integer values::
sage: wigner_3j(2.1, 6, 4, 0, 0, 0)
Traceback (most recent call last):
...
ValueError: j values must be integer or half integer
sage: wigner_3j(2, 6, 4, 1, 0, -1.1)
Traceback (most recent call last):
...
ValueError: m values must be integer or half integer
Notes
=====
The Wigner 3j symbol obeys the following symmetry rules:
- invariant under any permutation of the columns (with the
exception of a sign change where `J:=j_1+j_2+j_3`):
.. math::
\begin{aligned}
\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)
&=\operatorname{Wigner3j}(j_3,j_1,j_2,m_3,m_1,m_2) \\
&=\operatorname{Wigner3j}(j_2,j_3,j_1,m_2,m_3,m_1) \\
&=(-1)^J \operatorname{Wigner3j}(j_3,j_2,j_1,m_3,m_2,m_1) \\
&=(-1)^J \operatorname{Wigner3j}(j_1,j_3,j_2,m_1,m_3,m_2) \\
&=(-1)^J \operatorname{Wigner3j}(j_2,j_1,j_3,m_2,m_1,m_3)
\end{aligned}
- invariant under space inflection, i.e.
.. math::
\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)
=(-1)^J \operatorname{Wigner3j}(j_1,j_2,j_3,-m_1,-m_2,-m_3)
- symmetric with respect to the 72 additional symmetries based on
the work by [Regge58]_
- zero for `j_1`, `j_2`, `j_3` not fulfilling triangle relation
- zero for `m_1 + m_2 + m_3 \neq 0`
- zero for violating any one of the conditions
`j_1 \ge |m_1|`, `j_2 \ge |m_2|`, `j_3 \ge |m_3|`
Algorithm
=========
This function uses the algorithm of [Edmonds74]_ to calculate the
value of the 3j symbol exactly. Note that the formula contains
alternating sums over large factorials and is therefore unsuitable
for finite precision arithmetic and only useful for a computer
algebra system [Rasch03]_.
Authors
=======
- Jens Rasch (2009-03-24): initial version
"""
if int(j_1 * 2) != j_1 * 2 or int(j_2 * 2) != j_2 * 2 or \
int(j_3 * 2) != j_3 * 2:
raise ValueError("j values must be integer or half integer")
if int(m_1 * 2) != m_1 * 2 or int(m_2 * 2) != m_2 * 2 or \
int(m_3 * 2) != m_3 * 2:
raise ValueError("m values must be integer or half integer")
if m_1 + m_2 + m_3 != 0:
return S.Zero
prefid = Integer((-1) ** int(j_1 - j_2 - m_3))
m_3 = -m_3
a1 = j_1 + j_2 - j_3
if a1 < 0:
return S.Zero
a2 = j_1 - j_2 + j_3
if a2 < 0:
return S.Zero
a3 = -j_1 + j_2 + j_3
if a3 < 0:
return S.Zero
if (abs(m_1) > j_1) or (abs(m_2) > j_2) or (abs(m_3) > j_3):
return S.Zero
maxfact = max(j_1 + j_2 + j_3 + 1, j_1 + abs(m_1), j_2 + abs(m_2),
j_3 + abs(m_3))
_calc_factlist(int(maxfact))
argsqrt = Integer(_Factlist[int(j_1 + j_2 - j_3)] *
_Factlist[int(j_1 - j_2 + j_3)] *
_Factlist[int(-j_1 + j_2 + j_3)] *
_Factlist[int(j_1 - m_1)] *
_Factlist[int(j_1 + m_1)] *
_Factlist[int(j_2 - m_2)] *
_Factlist[int(j_2 + m_2)] *
_Factlist[int(j_3 - m_3)] *
_Factlist[int(j_3 + m_3)]) / \
_Factlist[int(j_1 + j_2 + j_3 + 1)]
ressqrt = sqrt(argsqrt)
if ressqrt.is_complex or ressqrt.is_infinite:
ressqrt = ressqrt.as_real_imag()[0]
imin = max(-j_3 + j_1 + m_2, -j_3 + j_2 - m_1, 0)
imax = min(j_2 + m_2, j_1 - m_1, j_1 + j_2 - j_3)
sumres = 0
for ii in range(int(imin), int(imax) + 1):
den = _Factlist[ii] * \
_Factlist[int(ii + j_3 - j_1 - m_2)] * \
_Factlist[int(j_2 + m_2 - ii)] * \
_Factlist[int(j_1 - ii - m_1)] * \
_Factlist[int(ii + j_3 - j_2 + m_1)] * \
_Factlist[int(j_1 + j_2 - j_3 - ii)]
sumres = sumres + Integer((-1) ** ii) / den
res = ressqrt * sumres * prefid
return res
def clebsch_gordan(j_1, j_2, j_3, m_1, m_2, m_3):
r"""
Calculates the Clebsch-Gordan coefficient.
`\left\langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \right\rangle`.
The reference for this function is [Edmonds74]_.
Parameters
==========
j_1, j_2, j_3, m_1, m_2, m_3 :
Integer or half integer.
Returns
=======
Rational number times the square root of a rational number.
Examples
========
>>> from sympy import S
>>> from sympy.physics.wigner import clebsch_gordan
>>> clebsch_gordan(S(3)/2, S(1)/2, 2, S(3)/2, S(1)/2, 2)
1
>>> clebsch_gordan(S(3)/2, S(1)/2, 1, S(3)/2, -S(1)/2, 1)
sqrt(3)/2
>>> clebsch_gordan(S(3)/2, S(1)/2, 1, -S(1)/2, S(1)/2, 0)
-sqrt(2)/2
Notes
=====
The Clebsch-Gordan coefficient will be evaluated via its relation
to Wigner 3j symbols:
.. math::
\left\langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \right\rangle
=(-1)^{j_1-j_2+m_3} \sqrt{2j_3+1}
\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,-m_3)
See also the documentation on Wigner 3j symbols which exhibit much
higher symmetry relations than the Clebsch-Gordan coefficient.
Authors
=======
- Jens Rasch (2009-03-24): initial version
"""
res = (-1) ** sympify(j_1 - j_2 + m_3) * sqrt(2 * j_3 + 1) * \
wigner_3j(j_1, j_2, j_3, m_1, m_2, -m_3)
return res
def _big_delta_coeff(aa, bb, cc, prec=None):
r"""
Calculates the Delta coefficient of the 3 angular momenta for
Racah symbols. Also checks that the differences are of integer
value.
Parameters
==========
aa :
First angular momentum, integer or half integer.
bb :
Second angular momentum, integer or half integer.
cc :
Third angular momentum, integer or half integer.
prec :
Precision of the ``sqrt()`` calculation.
Returns
=======
double : Value of the Delta coefficient.
Examples
========
sage: from sage.functions.wigner import _big_delta_coeff
sage: _big_delta_coeff(1,1,1)
1/2*sqrt(1/6)
"""
if int(aa + bb - cc) != (aa + bb - cc):
raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
if int(aa + cc - bb) != (aa + cc - bb):
raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
if int(bb + cc - aa) != (bb + cc - aa):
raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
if (aa + bb - cc) < 0:
return S.Zero
if (aa + cc - bb) < 0:
return S.Zero
if (bb + cc - aa) < 0:
return S.Zero
maxfact = max(aa + bb - cc, aa + cc - bb, bb + cc - aa, aa + bb + cc + 1)
_calc_factlist(maxfact)
argsqrt = Integer(_Factlist[int(aa + bb - cc)] *
_Factlist[int(aa + cc - bb)] *
_Factlist[int(bb + cc - aa)]) / \
Integer(_Factlist[int(aa + bb + cc + 1)])
ressqrt = sqrt(argsqrt)
if prec:
ressqrt = ressqrt.evalf(prec).as_real_imag()[0]
return ressqrt
def racah(aa, bb, cc, dd, ee, ff, prec=None):
r"""
Calculate the Racah symbol `W(a,b,c,d;e,f)`.
Parameters
==========
a, ..., f :
Integer or half integer.
prec :
Precision, default: ``None``. Providing a precision can
drastically speed up the calculation.
Returns
=======
Rational number times the square root of a rational number
(if ``prec=None``), or real number if a precision is given.
Examples
========
>>> from sympy.physics.wigner import racah
>>> racah(3,3,3,3,3,3)
-1/14
Notes
=====
The Racah symbol is related to the Wigner 6j symbol:
.. math::
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
=(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6)
Please see the 6j symbol for its much richer symmetries and for
additional properties.
Algorithm
=========
This function uses the algorithm of [Edmonds74]_ to calculate the
value of the 6j symbol exactly. Note that the formula contains
alternating sums over large factorials and is therefore unsuitable
for finite precision arithmetic and only useful for a computer
algebra system [Rasch03]_.
Authors
=======
- Jens Rasch (2009-03-24): initial version
"""
prefac = _big_delta_coeff(aa, bb, ee, prec) * \
_big_delta_coeff(cc, dd, ee, prec) * \
_big_delta_coeff(aa, cc, ff, prec) * \
_big_delta_coeff(bb, dd, ff, prec)
if prefac == 0:
return S.Zero
imin = max(aa + bb + ee, cc + dd + ee, aa + cc + ff, bb + dd + ff)
imax = min(aa + bb + cc + dd, aa + dd + ee + ff, bb + cc + ee + ff)
maxfact = max(imax + 1, aa + bb + cc + dd, aa + dd + ee + ff,
bb + cc + ee + ff)
_calc_factlist(maxfact)
sumres = 0
for kk in range(int(imin), int(imax) + 1):
den = _Factlist[int(kk - aa - bb - ee)] * \
_Factlist[int(kk - cc - dd - ee)] * \
_Factlist[int(kk - aa - cc - ff)] * \
_Factlist[int(kk - bb - dd - ff)] * \
_Factlist[int(aa + bb + cc + dd - kk)] * \
_Factlist[int(aa + dd + ee + ff - kk)] * \
_Factlist[int(bb + cc + ee + ff - kk)]
sumres = sumres + Integer((-1) ** kk * _Factlist[kk + 1]) / den
res = prefac * sumres * (-1) ** int(aa + bb + cc + dd)
return res
def wigner_6j(j_1, j_2, j_3, j_4, j_5, j_6, prec=None):
r"""
Calculate the Wigner 6j symbol `\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)`.
Parameters
==========
j_1, ..., j_6 :
Integer or half integer.
prec :
Precision, default: ``None``. Providing a precision can
drastically speed up the calculation.
Returns
=======
Rational number times the square root of a rational number
(if ``prec=None``), or real number if a precision is given.
Examples
========
>>> from sympy.physics.wigner import wigner_6j
>>> wigner_6j(3,3,3,3,3,3)
-1/14
>>> wigner_6j(5,5,5,5,5,5)
1/52
It is an error to have arguments that are not integer or half
integer values or do not fulfill the triangle relation::
sage: wigner_6j(2.5,2.5,2.5,2.5,2.5,2.5)
Traceback (most recent call last):
...
ValueError: j values must be integer or half integer and fulfill the triangle relation
sage: wigner_6j(0.5,0.5,1.1,0.5,0.5,1.1)
Traceback (most recent call last):
...
ValueError: j values must be integer or half integer and fulfill the triangle relation
Notes
=====
The Wigner 6j symbol is related to the Racah symbol but exhibits
more symmetries as detailed below.
.. math::
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
=(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6)
The Wigner 6j symbol obeys the following symmetry rules:
- Wigner 6j symbols are left invariant under any permutation of
the columns:
.. math::
\begin{aligned}
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
&=\operatorname{Wigner6j}(j_3,j_1,j_2,j_6,j_4,j_5) \\
&=\operatorname{Wigner6j}(j_2,j_3,j_1,j_5,j_6,j_4) \\
&=\operatorname{Wigner6j}(j_3,j_2,j_1,j_6,j_5,j_4) \\
&=\operatorname{Wigner6j}(j_1,j_3,j_2,j_4,j_6,j_5) \\
&=\operatorname{Wigner6j}(j_2,j_1,j_3,j_5,j_4,j_6)
\end{aligned}
- They are invariant under the exchange of the upper and lower
arguments in each of any two columns, i.e.
.. math::
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
=\operatorname{Wigner6j}(j_1,j_5,j_6,j_4,j_2,j_3)
=\operatorname{Wigner6j}(j_4,j_2,j_6,j_1,j_5,j_3)
=\operatorname{Wigner6j}(j_4,j_5,j_3,j_1,j_2,j_6)
- additional 6 symmetries [Regge59]_ giving rise to 144 symmetries
in total
- only non-zero if any triple of `j`'s fulfill a triangle relation
Algorithm
=========
This function uses the algorithm of [Edmonds74]_ to calculate the
value of the 6j symbol exactly. Note that the formula contains
alternating sums over large factorials and is therefore unsuitable
for finite precision arithmetic and only useful for a computer
algebra system [Rasch03]_.
"""
res = (-1) ** int(j_1 + j_2 + j_4 + j_5) * \
racah(j_1, j_2, j_5, j_4, j_3, j_6, prec)
return res
def wigner_9j(j_1, j_2, j_3, j_4, j_5, j_6, j_7, j_8, j_9, prec=None):
r"""
Calculate the Wigner 9j symbol
`\operatorname{Wigner9j}(j_1,j_2,j_3,j_4,j_5,j_6,j_7,j_8,j_9)`.
Parameters
==========
j_1, ..., j_9 :
Integer or half integer.
prec : precision, default
``None``. Providing a precision can
drastically speed up the calculation.
Returns
=======
Rational number times the square root of a rational number
(if ``prec=None``), or real number if a precision is given.
Examples
========
>>> from sympy.physics.wigner import wigner_9j
>>> wigner_9j(1,1,1, 1,1,1, 1,1,0, prec=64) # ==1/18
0.05555555...
>>> wigner_9j(1/2,1/2,0, 1/2,3/2,1, 0,1,1, prec=64) # ==1/6
0.1666666...
It is an error to have arguments that are not integer or half
integer values or do not fulfill the triangle relation::
sage: wigner_9j(0.5,0.5,0.5, 0.5,0.5,0.5, 0.5,0.5,0.5,prec=64)
Traceback (most recent call last):
...
ValueError: j values must be integer or half integer and fulfill the triangle relation
sage: wigner_9j(1,1,1, 0.5,1,1.5, 0.5,1,2.5,prec=64)
Traceback (most recent call last):
...
ValueError: j values must be integer or half integer and fulfill the triangle relation
Algorithm
=========
This function uses the algorithm of [Edmonds74]_ to calculate the
value of the 3j symbol exactly. Note that the formula contains
alternating sums over large factorials and is therefore unsuitable
for finite precision arithmetic and only useful for a computer
algebra system [Rasch03]_.
"""
imax = int(min(j_1 + j_9, j_2 + j_6, j_4 + j_8) * 2)
imin = imax % 2
sumres = 0
for kk in range(imin, int(imax) + 1, 2):
sumres = sumres + (kk + 1) * \
racah(j_1, j_2, j_9, j_6, j_3, kk / 2, prec) * \
racah(j_4, j_6, j_8, j_2, j_5, kk / 2, prec) * \
racah(j_1, j_4, j_9, j_8, j_7, kk / 2, prec)
return sumres
def gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):
r"""
Calculate the Gaunt coefficient.
Explanation
===========
The Gaunt coefficient is defined as the integral over three
spherical harmonics:
.. math::
\begin{aligned}
\operatorname{Gaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
&=\int Y_{l_1,m_1}(\Omega)
Y_{l_2,m_2}(\Omega) Y_{l_3,m_3}(\Omega) \,d\Omega \\
&=\sqrt{\frac{(2l_1+1)(2l_2+1)(2l_3+1)}{4\pi}}
\operatorname{Wigner3j}(l_1,l_2,l_3,0,0,0)
\operatorname{Wigner3j}(l_1,l_2,l_3,m_1,m_2,m_3)
\end{aligned}
Parameters
==========
l_1, l_2, l_3, m_1, m_2, m_3 :
Integer.
prec - precision, default: ``None``.
Providing a precision can
drastically speed up the calculation.
Returns
=======
Rational number times the square root of a rational number
(if ``prec=None``), or real number if a precision is given.
Examples
========
>>> from sympy.physics.wigner import gaunt
>>> gaunt(1,0,1,1,0,-1)
-1/(2*sqrt(pi))
>>> gaunt(1000,1000,1200,9,3,-12).n(64)
0.00689500421922113448...
It is an error to use non-integer values for `l` and `m`::
sage: gaunt(1.2,0,1.2,0,0,0)
Traceback (most recent call last):
...
ValueError: l values must be integer
sage: gaunt(1,0,1,1.1,0,-1.1)
Traceback (most recent call last):
...
ValueError: m values must be integer
Notes
=====
The Gaunt coefficient obeys the following symmetry rules:
- invariant under any permutation of the columns
.. math::
\begin{aligned}
Y(l_1,l_2,l_3,m_1,m_2,m_3)
&=Y(l_3,l_1,l_2,m_3,m_1,m_2) \\
&=Y(l_2,l_3,l_1,m_2,m_3,m_1) \\
&=Y(l_3,l_2,l_1,m_3,m_2,m_1) \\
&=Y(l_1,l_3,l_2,m_1,m_3,m_2) \\
&=Y(l_2,l_1,l_3,m_2,m_1,m_3)
\end{aligned}
- invariant under space inflection, i.e.
.. math::
Y(l_1,l_2,l_3,m_1,m_2,m_3)
=Y(l_1,l_2,l_3,-m_1,-m_2,-m_3)
- symmetric with respect to the 72 Regge symmetries as inherited
for the `3j` symbols [Regge58]_
- zero for `l_1`, `l_2`, `l_3` not fulfilling triangle relation
- zero for violating any one of the conditions: `l_1 \ge |m_1|`,
`l_2 \ge |m_2|`, `l_3 \ge |m_3|`
- non-zero only for an even sum of the `l_i`, i.e.
`L = l_1 + l_2 + l_3 = 2n` for `n` in `\mathbb{N}`
Algorithms
==========
This function uses the algorithm of [Liberatodebrito82]_ to
calculate the value of the Gaunt coefficient exactly. Note that
the formula contains alternating sums over large factorials and is
therefore unsuitable for finite precision arithmetic and only
useful for a computer algebra system [Rasch03]_.
Authors
=======
Jens Rasch (2009-03-24): initial version for Sage.
"""
l_1, l_2, l_3, m_1, m_2, m_3 = [
as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)]
if l_1 + l_2 - l_3 < 0:
return S.Zero
if l_1 - l_2 + l_3 < 0:
return S.Zero
if -l_1 + l_2 + l_3 < 0:
return S.Zero
if (m_1 + m_2 + m_3) != 0:
return S.Zero
if (abs(m_1) > l_1) or (abs(m_2) > l_2) or (abs(m_3) > l_3):
return S.Zero
bigL, remL = divmod(l_1 + l_2 + l_3, 2)
if remL % 2:
return S.Zero
imin = max(-l_3 + l_1 + m_2, -l_3 + l_2 - m_1, 0)
imax = min(l_2 + m_2, l_1 - m_1, l_1 + l_2 - l_3)
_calc_factlist(max(l_1 + l_2 + l_3 + 1, imax + 1))
ressqrt = sqrt((2 * l_1 + 1) * (2 * l_2 + 1) * (2 * l_3 + 1) * \
_Factlist[l_1 - m_1] * _Factlist[l_1 + m_1] * _Factlist[l_2 - m_2] * \
_Factlist[l_2 + m_2] * _Factlist[l_3 - m_3] * _Factlist[l_3 + m_3] / \
(4*pi))
prefac = Integer(_Factlist[bigL] * _Factlist[l_2 - l_1 + l_3] *
_Factlist[l_1 - l_2 + l_3] * _Factlist[l_1 + l_2 - l_3])/ \
_Factlist[2 * bigL + 1]/ \
(_Factlist[bigL - l_1] *
_Factlist[bigL - l_2] * _Factlist[bigL - l_3])
sumres = 0
for ii in range(int(imin), int(imax) + 1):
den = _Factlist[ii] * _Factlist[ii + l_3 - l_1 - m_2] * \
_Factlist[l_2 + m_2 - ii] * _Factlist[l_1 - ii - m_1] * \
_Factlist[ii + l_3 - l_2 + m_1] * _Factlist[l_1 + l_2 - l_3 - ii]
sumres = sumres + Integer((-1) ** ii) / den
res = ressqrt * prefac * sumres * Integer((-1) ** (bigL + l_3 + m_1 - m_2))
if prec is not None:
res = res.n(prec)
return res
def real_gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):
r"""
Calculate the real Gaunt coefficient.
Explanation
===========
The real Gaunt coefficient is defined as the integral over three
real spherical harmonics:
.. math::
\begin{aligned}
\operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
&=\int Z^{m_1}_{l_1}(\Omega)
Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\
\end{aligned}
Alternatively, it can be defined in terms of the standard Gaunt
coefficient by relating the real spherical harmonics to the standard
spherical harmonics via a unitary transformation `U`, i.e.
`Z^{m}_{l}(\Omega)=\sum_{m'}U^{m}_{m'}Y^{m'}_{l}(\Omega)` [Homeier96]_.
The real Gaunt coefficient is then defined as
.. math::
\begin{aligned}
\operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
&=\int Z^{m_1}_{l_1}(\Omega)
Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\
&=\sum_{m'_1 m'_2 m'_3} U^{m_1}_{m'_1}U^{m_2}_{m'_2}U^{m_3}_{m'_3}
\operatorname{Gaunt}(l_1,l_2,l_3,m'_1,m'_2,m'_3)
\end{aligned}
The unitary matrix `U` has components
.. math::
\begin{aligned}
U^m_{m'} = \delta_{|m||m'|}*(\delta_{m'0}\delta_{m0} + \frac{1}{\sqrt{2}}\big[\Theta(m)
\big(\delta_{m'm}+(-1)^{m'}\delta_{m'-m}\big)+i\Theta(-m)\big((-1)^{-m}
\delta_{m'-m}-\delta_{m'm}*(-1)^{m'-m}\big)\big])
\end{aligned}
where `\delta_{ij}` is the Kronecker delta symbol and `\Theta` is a step
function defined as
.. math::
\begin{aligned}
\Theta(x) = \begin{cases} 1 \,\text{for}\, x > 0 \\ 0 \,\text{for}\, x \leq 0 \end{cases}
\end{aligned}
Parameters
==========
l_1, l_2, l_3, m_1, m_2, m_3 :
Integer.
prec - precision, default: ``None``.
Providing a precision can
drastically speed up the calculation.
Returns
=======
Rational number times the square root of a rational number.
Examples
========
>>> from sympy.physics.wigner import real_gaunt
>>> real_gaunt(2,2,4,-1,-1,0)
-2/(7*sqrt(pi))
>>> real_gaunt(10,10,20,-9,-9,0).n(64)
-0.00002480019791932209313156167...
It is an error to use non-integer values for `l` and `m`::
real_gaunt(2.8,0.5,1.3,0,0,0)
Traceback (most recent call last):
...
ValueError: l values must be integer
real_gaunt(2,2,4,0.7,1,-3.4)
Traceback (most recent call last):
...
ValueError: m values must be integer
Notes
=====
The real Gaunt coefficient inherits from the standard Gaunt coefficient,
the invariance under any permutation of the pairs `(l_i, m_i)` and the
requirement that the sum of the `l_i` be even to yield a non-zero value.
It also obeys the following symmetry rules:
- zero for `l_1`, `l_2`, `l_3` not fulfiling the condition
`l_1 \in \{l_{\text{max}}, l_{\text{max}}-2, \ldots, l_{\text{min}}\}`,
where `l_{\text{max}} = l_2+l_3`,
.. math::
\begin{aligned}
l_{\text{min}} = \begin{cases} \kappa(l_2, l_3, m_2, m_3) & \text{if}\,
\kappa(l_2, l_3, m_2, m_3) + l_{\text{max}}\, \text{is even} \\
\kappa(l_2, l_3, m_2, m_3)+1 & \text{if}\, \kappa(l_2, l_3, m_2, m_3) +
l_{\text{max}}\, \text{is odd}\end{cases}
\end{aligned}
and `\kappa(l_2, l_3, m_2, m_3) = \max{\big(|l_2-l_3|, \min{\big(|m_2+m_3|,
|m_2-m_3|\big)}\big)}`
- zero for an odd number of negative `m_i`
Algorithms
==========
This function uses the algorithms of [Homeier96]_ and [Rasch03]_ to
calculate the value of the real Gaunt coefficient exactly. Note that
the formula used in [Rasch03]_ contains alternating sums over large
factorials and is therefore unsuitable for finite precision arithmetic
and only useful for a computer algebra system [Rasch03]_. However, this
function can in principle use any algorithm that computes the Gaunt
coefficient, so it is suitable for finite precision arithmetic in so far
as the algorithm which computes the Gaunt coefficient is.
"""
l_1, l_2, l_3, m_1, m_2, m_3 = [
as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)]
# check for quick exits
if sum(1 for i in (m_1, m_2, m_3) if i < 0) % 2:
return S.Zero # odd number of negative m
if (l_1 + l_2 + l_3) % 2:
return S.Zero # sum of l is odd
lmax = l_2 + l_3
lmin = max(abs(l_2 - l_3), min(abs(m_2 + m_3), abs(m_2 - m_3)))
if (lmin + lmax) % 2:
lmin += 1
if lmin not in range(lmax, lmin - 2, -2):
return S.Zero
kron_del = lambda i, j: 1 if i == j else 0
s = lambda e: -1 if e % 2 else 1 # (-1)**e to give +/-1, avoiding float when e<0
A = lambda a, b: (-kron_del(a, b)*s(a-b) + kron_del(a, -b)*
s(b)) if b < 0 else 0
B = lambda a, b: (kron_del(a, b) + kron_del(a, -b)*s(a)) if b > 0 else 0
C = lambda a, b: kron_del(abs(a), abs(b))*(kron_del(a, 0)*kron_del(b, 0) +
(B(a, b) + I*A(a, b))/sqrt(2))
ugnt = 0
for i in range(-l_1, l_1+1):
U1 = C(i, m_1)
for j in range(-l_2, l_2+1):
U2 = C(j, m_2)
U3 = C(-i-j, m_3)
ugnt = ugnt + re(U1*U2*U3)*gaunt(l_1, l_2, l_3, i, j, -i-j)
if prec is not None:
ugnt = ugnt.n(prec)
return ugnt
class Wigner3j(Function):
def doit(self, **hints):
if all(obj.is_number for obj in self.args):
return wigner_3j(*self.args)
else:
return self
def dot_rot_grad_Ynm(j, p, l, m, theta, phi):
r"""
Returns dot product of rotational gradients of spherical harmonics.
Explanation
===========
This function returns the right hand side of the following expression:
.. math ::
\vec{R}Y{_j^{p}} \cdot \vec{R}Y{_l^{m}} = (-1)^{m+p}
\sum\limits_{k=|l-j|}^{l+j}Y{_k^{m+p}} * \alpha_{l,m,j,p,k} *
\frac{1}{2} (k^2-j^2-l^2+k-j-l)
Arguments
=========
j, p, l, m .... indices in spherical harmonics (expressions or integers)
theta, phi .... angle arguments in spherical harmonics
Example
=======
>>> from sympy import symbols
>>> from sympy.physics.wigner import dot_rot_grad_Ynm
>>> theta, phi = symbols("theta phi")
>>> dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit()
3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi))
"""
j = sympify(j)
p = sympify(p)
l = sympify(l)
m = sympify(m)
theta = sympify(theta)
phi = sympify(phi)
k = Dummy("k")
def alpha(l,m,j,p,k):
return sqrt((2*l+1)*(2*j+1)*(2*k+1)/(4*pi)) * \
Wigner3j(j, l, k, S.Zero, S.Zero, S.Zero) * \
Wigner3j(j, l, k, p, m, -m-p)
return (S.NegativeOne)**(m+p) * Sum(Ynm(k, m+p, theta, phi) * alpha(l,m,j,p,k) / 2 \
*(k**2-j**2-l**2+k-j-l), (k, abs(l-j), l+j))
def wigner_d_small(J, beta):
"""Return the small Wigner d matrix for angular momentum J.
Explanation
===========
J : An integer, half-integer, or SymPy symbol for the total angular
momentum of the angular momentum space being rotated.
beta : A real number representing the Euler angle of rotation about
the so-called line of nodes. See [Edmonds74]_.
Returns
=======
A matrix representing the corresponding Euler angle rotation( in the basis
of eigenvectors of `J_z`).
.. math ::
\\mathcal{d}_{\\beta} = \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)
The components are calculated using the general form [Edmonds74]_,
equation 4.1.15.
Examples
========
>>> from sympy import Integer, symbols, pi, pprint
>>> from sympy.physics.wigner import wigner_d_small
>>> half = 1/Integer(2)
>>> beta = symbols("beta", real=True)
>>> pprint(wigner_d_small(half, beta), use_unicode=True)
⎡ ⎛β⎞ ⎛β⎞⎤
⎢cos⎜─⎟ sin⎜─⎟⎥
⎢ ⎝2⎠ ⎝2⎠⎥
⎢ ⎥
⎢ ⎛β⎞ ⎛β⎞⎥
⎢-sin⎜─⎟ cos⎜─⎟⎥
⎣ ⎝2⎠ ⎝2⎠⎦
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
⎡ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎤
⎢ cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟ sin ⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ ⎛β⎞ ⎛β⎞ 2⎛β⎞ 2⎛β⎞ ⎛β⎞ ⎛β⎞⎥
⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟ - sin ⎜─⎟ + cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠⎥
⎢ ⎥
⎢ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎥
⎢ sin ⎜─⎟ -√2⋅sin⎜─⎟⋅cos⎜─⎟ cos ⎜─⎟ ⎥
⎣ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎦
From table 4 in [Edmonds74]_
>>> pprint(wigner_d_small(half, beta).subs({beta:pi/2}), use_unicode=True)
⎡ √2 √2⎤
⎢ ── ──⎥
⎢ 2 2 ⎥
⎢ ⎥
⎢-√2 √2⎥
⎢──── ──⎥
⎣ 2 2 ⎦
>>> pprint(wigner_d_small(2*half, beta).subs({beta:pi/2}),
... use_unicode=True)
⎡ √2 ⎤
⎢1/2 ── 1/2⎥
⎢ 2 ⎥
⎢ ⎥
⎢-√2 √2 ⎥
⎢──── 0 ── ⎥
⎢ 2 2 ⎥
⎢ ⎥
⎢ -√2 ⎥
⎢1/2 ──── 1/2⎥
⎣ 2 ⎦
>>> pprint(wigner_d_small(3*half, beta).subs({beta:pi/2}),
... use_unicode=True)
⎡ √2 √6 √6 √2⎤
⎢ ── ── ── ──⎥
⎢ 4 4 4 4 ⎥
⎢ ⎥
⎢-√6 -√2 √2 √6⎥
⎢──── ──── ── ──⎥
⎢ 4 4 4 4 ⎥
⎢ ⎥
⎢ √6 -√2 -√2 √6⎥
⎢ ── ──── ──── ──⎥
⎢ 4 4 4 4 ⎥
⎢ ⎥
⎢-√2 √6 -√6 √2⎥
⎢──── ── ──── ──⎥
⎣ 4 4 4 4 ⎦
>>> pprint(wigner_d_small(4*half, beta).subs({beta:pi/2}),
... use_unicode=True)
⎡ √6 ⎤
⎢1/4 1/2 ── 1/2 1/4⎥
⎢ 4 ⎥
⎢ ⎥
⎢-1/2 -1/2 0 1/2 1/2⎥
⎢ ⎥
⎢ √6 √6 ⎥
⎢ ── 0 -1/2 0 ── ⎥
⎢ 4 4 ⎥
⎢ ⎥
⎢-1/2 1/2 0 -1/2 1/2⎥
⎢ ⎥
⎢ √6 ⎥
⎢1/4 -1/2 ── -1/2 1/4⎥
⎣ 4 ⎦
"""
M = [J-i for i in range(2*J+1)]
d = zeros(2*J+1)
for i, Mi in enumerate(M):
for j, Mj in enumerate(M):
# We get the maximum and minimum value of sigma.
sigmamax = max([-Mi-Mj, J-Mj])
sigmamin = min([0, J-Mi])
dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
factorial(J+Mj)/factorial(J-Mj))
terms = [(-1)**(J-Mi-s) *
binomial(J+Mj, J-Mi-s) *
binomial(J-Mj, s) *
cos(beta/2)**(2*s+Mi+Mj) *
sin(beta/2)**(2*J-2*s-Mj-Mi)
for s in range(sigmamin, sigmamax+1)]
d[i, j] = dij*Add(*terms)
return ImmutableMatrix(d)
def wigner_d(J, alpha, beta, gamma):
"""Return the Wigner D matrix for angular momentum J.
Explanation
===========
J :
An integer, half-integer, or SymPy symbol for the total angular
momentum of the angular momentum space being rotated.
alpha, beta, gamma - Real numbers representing the Euler.
Angles of rotation about the so-called vertical, line of nodes, and
figure axes. See [Edmonds74]_.
Returns
=======
A matrix representing the corresponding Euler angle rotation( in the basis
of eigenvectors of `J_z`).
.. math ::
\\mathcal{D}_{\\alpha \\beta \\gamma} =
\\exp\\big( \\frac{i\\alpha}{\\hbar} J_z\\big)
\\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)
\\exp\\big( \\frac{i\\gamma}{\\hbar} J_z\\big)
The components are calculated using the general form [Edmonds74]_,
equation 4.1.12.
Examples
========
The simplest possible example:
>>> from sympy.physics.wigner import wigner_d
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
⎡ ⅈ⋅α ⅈ⋅γ ⅈ⋅α -ⅈ⋅γ ⎤
⎢ ─── ─── ─── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞ ⎥
⎢ ℯ ⋅ℯ ⋅cos⎜─⎟ ℯ ⋅ℯ ⋅sin⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ -ⅈ⋅α ⅈ⋅γ -ⅈ⋅α -ⅈ⋅γ ⎥
⎢ ───── ─── ───── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞⎥
⎢-ℯ ⋅ℯ ⋅sin⎜─⎟ ℯ ⋅ℯ ⋅cos⎜─⎟⎥
⎣ ⎝2⎠ ⎝2⎠⎦
"""
d = wigner_d_small(J, beta)
M = [J-i for i in range(2*J+1)]
D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
return ImmutableMatrix(D)
|
182a89082c70509c1941cdbbb6667afab53dc8201461eb289297c3a7a954faeb | """
Boolean algebra module for SymPy
"""
from collections import defaultdict
from itertools import chain, combinations, product, permutations
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.decorators import sympify_method_args, sympify_return
from sympy.core.function import Application, Derivative
from sympy.core.kind import BooleanKind, NumberKind
from sympy.core.numbers import Number
from sympy.core.operations import LatticeOp
from sympy.core.singleton import Singleton, S
from sympy.core.sorting import ordered
from sympy.core.sympify import _sympy_converter, _sympify, sympify
from sympy.utilities.iterables import sift, ibin
from sympy.utilities.misc import filldedent
def as_Boolean(e):
"""Like ``bool``, return the Boolean value of an expression, e,
which can be any instance of :py:class:`~.Boolean` or ``bool``.
Examples
========
>>> from sympy import true, false, nan
>>> from sympy.logic.boolalg import as_Boolean
>>> from sympy.abc import x
>>> as_Boolean(0) is false
True
>>> as_Boolean(1) is true
True
>>> as_Boolean(x)
x
>>> as_Boolean(2)
Traceback (most recent call last):
...
TypeError: expecting bool or Boolean, not `2`.
>>> as_Boolean(nan)
Traceback (most recent call last):
...
TypeError: expecting bool or Boolean, not `nan`.
"""
from sympy.core.symbol import Symbol
if e == True:
return true
if e == False:
return false
if isinstance(e, Symbol):
z = e.is_zero
if z is None:
return e
return false if z else true
if isinstance(e, Boolean):
return e
raise TypeError('expecting bool or Boolean, not `%s`.' % e)
@sympify_method_args
class Boolean(Basic):
"""A Boolean object is an object for which logic operations make sense."""
__slots__ = ()
kind = BooleanKind
@sympify_return([('other', 'Boolean')], NotImplemented)
def __and__(self, other):
return And(self, other)
__rand__ = __and__
@sympify_return([('other', 'Boolean')], NotImplemented)
def __or__(self, other):
return Or(self, other)
__ror__ = __or__
def __invert__(self):
"""Overloading for ~"""
return Not(self)
@sympify_return([('other', 'Boolean')], NotImplemented)
def __rshift__(self, other):
return Implies(self, other)
@sympify_return([('other', 'Boolean')], NotImplemented)
def __lshift__(self, other):
return Implies(other, self)
__rrshift__ = __lshift__
__rlshift__ = __rshift__
@sympify_return([('other', 'Boolean')], NotImplemented)
def __xor__(self, other):
return Xor(self, other)
__rxor__ = __xor__
def equals(self, other):
"""
Returns ``True`` if the given formulas have the same truth table.
For two formulas to be equal they must have the same literals.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy import And, Or, Not
>>> (A >> B).equals(~B >> ~A)
True
>>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C)))
False
>>> Not(And(A, Not(A))).equals(Or(B, Not(B)))
False
"""
from sympy.logic.inference import satisfiable
from sympy.core.relational import Relational
if self.has(Relational) or other.has(Relational):
raise NotImplementedError('handling of relationals')
return self.atoms() == other.atoms() and \
not satisfiable(Not(Equivalent(self, other)))
def to_nnf(self, simplify=True):
# override where necessary
return self
def as_set(self):
"""
Rewrites Boolean expression in terms of real sets.
Examples
========
>>> from sympy import Symbol, Eq, Or, And
>>> x = Symbol('x', real=True)
>>> Eq(x, 0).as_set()
{0}
>>> (x > 0).as_set()
Interval.open(0, oo)
>>> And(-2 < x, x < 2).as_set()
Interval.open(-2, 2)
>>> Or(x < -2, 2 < x).as_set()
Union(Interval.open(-oo, -2), Interval.open(2, oo))
"""
from sympy.calculus.util import periodicity
from sympy.core.relational import Relational
free = self.free_symbols
if len(free) == 1:
x = free.pop()
if x.kind is NumberKind:
reps = {}
for r in self.atoms(Relational):
if periodicity(r, x) not in (0, None):
s = r._eval_as_set()
if s in (S.EmptySet, S.UniversalSet, S.Reals):
reps[r] = s.as_relational(x)
continue
raise NotImplementedError(filldedent('''
as_set is not implemented for relationals
with periodic solutions
'''))
new = self.subs(reps)
if new.func != self.func:
return new.as_set() # restart with new obj
else:
return new._eval_as_set()
return self._eval_as_set()
else:
raise NotImplementedError("Sorry, as_set has not yet been"
" implemented for multivariate"
" expressions")
@property
def binary_symbols(self):
from sympy.core.relational import Eq, Ne
return set().union(*[i.binary_symbols for i in self.args
if i.is_Boolean or i.is_Symbol
or isinstance(i, (Eq, Ne))])
def _eval_refine(self, assumptions):
from sympy.assumptions import ask
ret = ask(self, assumptions)
if ret is True:
return true
elif ret is False:
return false
return None
class BooleanAtom(Boolean):
"""
Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`.
"""
is_Boolean = True
is_Atom = True
_op_priority = 11 # higher than Expr
def simplify(self, *a, **kw):
return self
def expand(self, *a, **kw):
return self
@property
def canonical(self):
return self
def _noop(self, other=None):
raise TypeError('BooleanAtom not allowed in this context.')
__add__ = _noop
__radd__ = _noop
__sub__ = _noop
__rsub__ = _noop
__mul__ = _noop
__rmul__ = _noop
__pow__ = _noop
__rpow__ = _noop
__truediv__ = _noop
__rtruediv__ = _noop
__mod__ = _noop
__rmod__ = _noop
_eval_power = _noop
# /// drop when Py2 is no longer supported
def __lt__(self, other):
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
__le__ = __lt__
__gt__ = __lt__
__ge__ = __lt__
# \\\
def _eval_simplify(self, **kwargs):
return self
class BooleanTrue(BooleanAtom, metaclass=Singleton):
"""
SymPy version of ``True``, a singleton that can be accessed via ``S.true``.
This is the SymPy version of ``True``, for use in the logic module. The
primary advantage of using ``true`` instead of ``True`` is that shorthand Boolean
operations like ``~`` and ``>>`` will work as expected on this class, whereas with
True they act bitwise on 1. Functions in the logic module will return this
class when they evaluate to true.
Notes
=====
There is liable to be some confusion as to when ``True`` should
be used and when ``S.true`` should be used in various contexts
throughout SymPy. An important thing to remember is that
``sympify(True)`` returns ``S.true``. This means that for the most
part, you can just use ``True`` and it will automatically be converted
to ``S.true`` when necessary, similar to how you can generally use 1
instead of ``S.One``.
The rule of thumb is:
"If the boolean in question can be replaced by an arbitrary symbolic
``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``.
Otherwise, use ``True``"
In other words, use ``S.true`` only on those contexts where the
boolean is being used as a symbolic representation of truth.
For example, if the object ends up in the ``.args`` of any expression,
then it must necessarily be ``S.true`` instead of ``True``, as
elements of ``.args`` must be ``Basic``. On the other hand,
``==`` is not a symbolic operation in SymPy, since it always returns
``True`` or ``False``, and does so in terms of structural equality
rather than mathematical, so it should return ``True``. The assumptions
system should use ``True`` and ``False``. Aside from not satisfying
the above rule of thumb, the assumptions system uses a three-valued logic
(``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false``
represent a two-valued logic. When in doubt, use ``True``.
"``S.true == True is True``."
While "``S.true is True``" is ``False``, "``S.true == True``"
is ``True``, so if there is any doubt over whether a function or
expression will return ``S.true`` or ``True``, just use ``==``
instead of ``is`` to do the comparison, and it will work in either
case. Finally, for boolean flags, it's better to just use ``if x``
instead of ``if x is True``. To quote PEP 8:
Do not compare boolean values to ``True`` or ``False``
using ``==``.
* Yes: ``if greeting:``
* No: ``if greeting == True:``
* Worse: ``if greeting is True:``
Examples
========
>>> from sympy import sympify, true, false, Or
>>> sympify(True)
True
>>> _ is True, _ is true
(False, True)
>>> Or(true, false)
True
>>> _ is true
True
Python operators give a boolean result for true but a
bitwise result for True
>>> ~true, ~True
(False, -2)
>>> true >> true, True >> True
(True, 0)
Python operators give a boolean result for true but a
bitwise result for True
>>> ~true, ~True
(False, -2)
>>> true >> true, True >> True
(True, 0)
See Also
========
sympy.logic.boolalg.BooleanFalse
"""
def __bool__(self):
return True
def __hash__(self):
return hash(True)
def __eq__(self, other):
if other is True:
return True
if other is False:
return False
return super().__eq__(other)
@property
def negated(self):
return false
def as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import true
>>> true.as_set()
UniversalSet
"""
return S.UniversalSet
class BooleanFalse(BooleanAtom, metaclass=Singleton):
"""
SymPy version of ``False``, a singleton that can be accessed via ``S.false``.
This is the SymPy version of ``False``, for use in the logic module. The
primary advantage of using ``false`` instead of ``False`` is that shorthand
Boolean operations like ``~`` and ``>>`` will work as expected on this class,
whereas with ``False`` they act bitwise on 0. Functions in the logic module
will return this class when they evaluate to false.
Notes
======
See the notes section in :py:class:`sympy.logic.boolalg.BooleanTrue`
Examples
========
>>> from sympy import sympify, true, false, Or
>>> sympify(False)
False
>>> _ is False, _ is false
(False, True)
>>> Or(true, false)
True
>>> _ is true
True
Python operators give a boolean result for false but a
bitwise result for False
>>> ~false, ~False
(True, -1)
>>> false >> false, False >> False
(True, 0)
See Also
========
sympy.logic.boolalg.BooleanTrue
"""
def __bool__(self):
return False
def __hash__(self):
return hash(False)
def __eq__(self, other):
if other is True:
return False
if other is False:
return True
return super().__eq__(other)
@property
def negated(self):
return true
def as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import false
>>> false.as_set()
EmptySet
"""
return S.EmptySet
true = BooleanTrue()
false = BooleanFalse()
# We want S.true and S.false to work, rather than S.BooleanTrue and
# S.BooleanFalse, but making the class and instance names the same causes some
# major issues (like the inability to import the class directly from this
# file).
S.true = true
S.false = false
_sympy_converter[bool] = lambda x: true if x else false
class BooleanFunction(Application, Boolean):
"""Boolean function is a function that lives in a boolean space
It is used as base class for :py:class:`~.And`, :py:class:`~.Or`,
:py:class:`~.Not`, etc.
"""
is_Boolean = True
def _eval_simplify(self, **kwargs):
rv = simplify_univariate(self)
if not isinstance(rv, BooleanFunction):
return rv.simplify(**kwargs)
rv = rv.func(*[a.simplify(**kwargs) for a in rv.args])
return simplify_logic(rv)
def simplify(self, **kwargs):
from sympy.simplify.simplify import simplify
return simplify(self, **kwargs)
def __lt__(self, other):
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
__le__ = __lt__
__ge__ = __lt__
__gt__ = __lt__
@classmethod
def binary_check_and_simplify(self, *args):
from sympy.core.relational import Relational, Eq, Ne
args = [as_Boolean(i) for i in args]
bin_syms = set().union(*[i.binary_symbols for i in args])
rel = set().union(*[i.atoms(Relational) for i in args])
reps = {}
for x in bin_syms:
for r in rel:
if x in bin_syms and x in r.free_symbols:
if isinstance(r, (Eq, Ne)):
if not (
true in r.args or
false in r.args):
reps[r] = false
else:
raise TypeError(filldedent('''
Incompatible use of binary symbol `%s` as a
real variable in `%s`
''' % (x, r)))
return [i.subs(reps) for i in args]
def to_nnf(self, simplify=True):
return self._to_nnf(*self.args, simplify=simplify)
def to_anf(self, deep=True):
return self._to_anf(*self.args, deep=deep)
@classmethod
def _to_nnf(cls, *args, **kwargs):
simplify = kwargs.get('simplify', True)
argset = set()
for arg in args:
if not is_literal(arg):
arg = arg.to_nnf(simplify)
if simplify:
if isinstance(arg, cls):
arg = arg.args
else:
arg = (arg,)
for a in arg:
if Not(a) in argset:
return cls.zero
argset.add(a)
else:
argset.add(arg)
return cls(*argset)
@classmethod
def _to_anf(cls, *args, **kwargs):
deep = kwargs.get('deep', True)
argset = set()
for arg in args:
if deep:
if not is_literal(arg) or isinstance(arg, Not):
arg = arg.to_anf(deep=deep)
argset.add(arg)
else:
argset.add(arg)
return cls(*argset, remove_true=False)
# the diff method below is copied from Expr class
def diff(self, *symbols, **assumptions):
assumptions.setdefault("evaluate", True)
return Derivative(self, *symbols, **assumptions)
def _eval_derivative(self, x):
if x in self.binary_symbols:
from sympy.core.relational import Eq
from sympy.functions.elementary.piecewise import Piecewise
return Piecewise(
(0, Eq(self.subs(x, 0), self.subs(x, 1))),
(1, True))
elif x in self.free_symbols:
# not implemented, see https://www.encyclopediaofmath.org/
# index.php/Boolean_differential_calculus
pass
else:
return S.Zero
class And(LatticeOp, BooleanFunction):
"""
Logical AND function.
It evaluates its arguments in order, returning false immediately
when an argument is false and true if they are all true.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import And
>>> x & y
x & y
Notes
=====
The ``&`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
and. Hence, ``And(a, b)`` and ``a & b`` will produce different results if
``a`` and ``b`` are integers.
>>> And(x, y).subs(x, 1)
y
"""
zero = false
identity = true
nargs = None
@classmethod
def _new_args_filter(cls, args):
args = BooleanFunction.binary_check_and_simplify(*args)
args = LatticeOp._new_args_filter(args, And)
newargs = []
rel = set()
for x in ordered(args):
if x.is_Relational:
c = x.canonical
if c in rel:
continue
elif c.negated.canonical in rel:
return [false]
else:
rel.add(c)
newargs.append(x)
return newargs
def _eval_subs(self, old, new):
args = []
bad = None
for i in self.args:
try:
i = i.subs(old, new)
except TypeError:
# store TypeError
if bad is None:
bad = i
continue
if i == False:
return false
elif i != True:
args.append(i)
if bad is not None:
# let it raise
bad.subs(old, new)
# If old is And, replace the parts of the arguments with new if all
# are there
if isinstance(old, And):
old_set = set(old.args)
if old_set.issubset(args):
args = set(args) - old_set
args.add(new)
return self.func(*args)
def _eval_simplify(self, **kwargs):
from sympy.core.relational import Equality, Relational
from sympy.solvers.solveset import linear_coeffs
# standard simplify
rv = super()._eval_simplify(**kwargs)
if not isinstance(rv, And):
return rv
# simplify args that are equalities involving
# symbols so x == 0 & x == y -> x==0 & y == 0
Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
binary=True)
if not Rel:
return rv
eqs, other = sift(Rel, lambda i: isinstance(i, Equality), binary=True)
measure = kwargs['measure']
if eqs:
ratio = kwargs['ratio']
reps = {}
sifted = {}
# group by length of free symbols
sifted = sift(ordered([
(i.free_symbols, i) for i in eqs]),
lambda x: len(x[0]))
eqs = []
nonlineqs = []
while 1 in sifted:
for free, e in sifted.pop(1):
x = free.pop()
if (e.lhs != x or x in e.rhs.free_symbols) and x not in reps:
try:
m, b = linear_coeffs(
e.rewrite(Add, evaluate=False), x)
enew = e.func(x, -b/m)
if measure(enew) <= ratio*measure(e):
e = enew
else:
eqs.append(e)
continue
except ValueError:
pass
if x in reps:
eqs.append(e.subs(x, reps[x]))
elif e.lhs == x and x not in e.rhs.free_symbols:
reps[x] = e.rhs
eqs.append(e)
else:
# x is not yet identified, but may be later
nonlineqs.append(e)
resifted = defaultdict(list)
for k in sifted:
for f, e in sifted[k]:
e = e.xreplace(reps)
f = e.free_symbols
resifted[len(f)].append((f, e))
sifted = resifted
for k in sifted:
eqs.extend([e for f, e in sifted[k]])
nonlineqs = [ei.subs(reps) for ei in nonlineqs]
other = [ei.subs(reps) for ei in other]
rv = rv.func(*([i.canonical for i in (eqs + nonlineqs + other)] + nonRel))
patterns = _simplify_patterns_and()
threeterm_patterns = _simplify_patterns_and3()
return _apply_patternbased_simplification(rv, patterns,
measure, false,
threeterm_patterns=threeterm_patterns)
def _eval_as_set(self):
from sympy.sets.sets import Intersection
return Intersection(*[arg.as_set() for arg in self.args])
def _eval_rewrite_as_Nor(self, *args, **kwargs):
return Nor(*[Not(arg) for arg in self.args])
def to_anf(self, deep=True):
if deep:
result = And._to_anf(*self.args, deep=deep)
return distribute_xor_over_and(result)
return self
class Or(LatticeOp, BooleanFunction):
"""
Logical OR function
It evaluates its arguments in order, returning true immediately
when an argument is true, and false if they are all false.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import Or
>>> x | y
x | y
Notes
=====
The ``|`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if
``a`` and ``b`` are integers.
>>> Or(x, y).subs(x, 0)
y
"""
zero = true
identity = false
@classmethod
def _new_args_filter(cls, args):
newargs = []
rel = []
args = BooleanFunction.binary_check_and_simplify(*args)
for x in args:
if x.is_Relational:
c = x.canonical
if c in rel:
continue
nc = c.negated.canonical
if any(r == nc for r in rel):
return [true]
rel.append(c)
newargs.append(x)
return LatticeOp._new_args_filter(newargs, Or)
def _eval_subs(self, old, new):
args = []
bad = None
for i in self.args:
try:
i = i.subs(old, new)
except TypeError:
# store TypeError
if bad is None:
bad = i
continue
if i == True:
return true
elif i != False:
args.append(i)
if bad is not None:
# let it raise
bad.subs(old, new)
# If old is Or, replace the parts of the arguments with new if all
# are there
if isinstance(old, Or):
old_set = set(old.args)
if old_set.issubset(args):
args = set(args) - old_set
args.add(new)
return self.func(*args)
def _eval_as_set(self):
from sympy.sets.sets import Union
return Union(*[arg.as_set() for arg in self.args])
def _eval_rewrite_as_Nand(self, *args, **kwargs):
return Nand(*[Not(arg) for arg in self.args])
def _eval_simplify(self, **kwargs):
from sympy.core.relational import Le, Ge, Eq
lege = self.atoms(Le, Ge)
if lege:
reps = {i: self.func(
Eq(i.lhs, i.rhs), i.strict) for i in lege}
return self.xreplace(reps)._eval_simplify(**kwargs)
# standard simplify
rv = super()._eval_simplify(**kwargs)
if not isinstance(rv, Or):
return rv
patterns = _simplify_patterns_or()
return _apply_patternbased_simplification(rv, patterns,
kwargs['measure'], true)
def to_anf(self, deep=True):
args = range(1, len(self.args) + 1)
args = (combinations(self.args, j) for j in args)
args = chain.from_iterable(args) # powerset
args = (And(*arg) for arg in args)
args = map(lambda x: to_anf(x, deep=deep) if deep else x, args)
return Xor(*list(args), remove_true=False)
class Not(BooleanFunction):
"""
Logical Not function (negation)
Returns ``true`` if the statement is ``false`` or ``False``.
Returns ``false`` if the statement is ``true`` or ``True``.
Examples
========
>>> from sympy import Not, And, Or
>>> from sympy.abc import x, A, B
>>> Not(True)
False
>>> Not(False)
True
>>> Not(And(True, False))
True
>>> Not(Or(True, False))
False
>>> Not(And(And(True, x), Or(x, False)))
~x
>>> ~x
~x
>>> Not(And(Or(A, B), Or(~A, ~B)))
~((A | B) & (~A | ~B))
Notes
=====
- The ``~`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is
an integer. Furthermore, since bools in Python subclass from ``int``,
``~True`` is the same as ``~1`` which is ``-2``, which has a boolean
value of True. To avoid this issue, use the SymPy boolean types
``true`` and ``false``.
>>> from sympy import true
>>> ~True
-2
>>> ~true
False
"""
is_Not = True
@classmethod
def eval(cls, arg):
if isinstance(arg, Number) or arg in (True, False):
return false if arg else true
if arg.is_Not:
return arg.args[0]
# Simplify Relational objects.
if arg.is_Relational:
return arg.negated
def _eval_as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import Not, Symbol
>>> x = Symbol('x')
>>> Not(x > 0).as_set()
Interval(-oo, 0)
"""
return self.args[0].as_set().complement(S.Reals)
def to_nnf(self, simplify=True):
if is_literal(self):
return self
expr = self.args[0]
func, args = expr.func, expr.args
if func == And:
return Or._to_nnf(*[Not(arg) for arg in args], simplify=simplify)
if func == Or:
return And._to_nnf(*[Not(arg) for arg in args], simplify=simplify)
if func == Implies:
a, b = args
return And._to_nnf(a, Not(b), simplify=simplify)
if func == Equivalent:
return And._to_nnf(Or(*args), Or(*[Not(arg) for arg in args]),
simplify=simplify)
if func == Xor:
result = []
for i in range(1, len(args)+1, 2):
for neg in combinations(args, i):
clause = [Not(s) if s in neg else s for s in args]
result.append(Or(*clause))
return And._to_nnf(*result, simplify=simplify)
if func == ITE:
a, b, c = args
return And._to_nnf(Or(a, Not(c)), Or(Not(a), Not(b)), simplify=simplify)
raise ValueError("Illegal operator %s in expression" % func)
def to_anf(self, deep=True):
return Xor._to_anf(true, self.args[0], deep=deep)
class Xor(BooleanFunction):
"""
Logical XOR (exclusive OR) function.
Returns True if an odd number of the arguments are True and the rest are
False.
Returns False if an even number of the arguments are True and the rest are
False.
Examples
========
>>> from sympy.logic.boolalg import Xor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Xor(True, False)
True
>>> Xor(True, True)
False
>>> Xor(True, False, True, True, False)
True
>>> Xor(True, False, True, False)
False
>>> x ^ y
x ^ y
Notes
=====
The ``^`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise xor. In
particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and
``b`` are integers.
>>> Xor(x, y).subs(y, 0)
x
"""
def __new__(cls, *args, remove_true=True, **kwargs):
argset = set()
obj = super().__new__(cls, *args, **kwargs)
for arg in obj._args:
if isinstance(arg, Number) or arg in (True, False):
if arg:
arg = true
else:
continue
if isinstance(arg, Xor):
for a in arg.args:
argset.remove(a) if a in argset else argset.add(a)
elif arg in argset:
argset.remove(arg)
else:
argset.add(arg)
rel = [(r, r.canonical, r.negated.canonical)
for r in argset if r.is_Relational]
odd = False # is number of complimentary pairs odd? start 0 -> False
remove = []
for i, (r, c, nc) in enumerate(rel):
for j in range(i + 1, len(rel)):
rj, cj = rel[j][:2]
if cj == nc:
odd = ~odd
break
elif cj == c:
break
else:
continue
remove.append((r, rj))
if odd:
argset.remove(true) if true in argset else argset.add(true)
for a, b in remove:
argset.remove(a)
argset.remove(b)
if len(argset) == 0:
return false
elif len(argset) == 1:
return argset.pop()
elif True in argset and remove_true:
argset.remove(True)
return Not(Xor(*argset))
else:
obj._args = tuple(ordered(argset))
obj._argset = frozenset(argset)
return obj
# XXX: This should be cached on the object rather than using cacheit
# Maybe it can be computed in __new__?
@property # type: ignore
@cacheit
def args(self):
return tuple(ordered(self._argset))
def to_nnf(self, simplify=True):
args = []
for i in range(0, len(self.args)+1, 2):
for neg in combinations(self.args, i):
clause = [Not(s) if s in neg else s for s in self.args]
args.append(Or(*clause))
return And._to_nnf(*args, simplify=simplify)
def _eval_rewrite_as_Or(self, *args, **kwargs):
a = self.args
return Or(*[_convert_to_varsSOP(x, self.args)
for x in _get_odd_parity_terms(len(a))])
def _eval_rewrite_as_And(self, *args, **kwargs):
a = self.args
return And(*[_convert_to_varsPOS(x, self.args)
for x in _get_even_parity_terms(len(a))])
def _eval_simplify(self, **kwargs):
# as standard simplify uses simplify_logic which writes things as
# And and Or, we only simplify the partial expressions before using
# patterns
rv = self.func(*[a.simplify(**kwargs) for a in self.args])
if not isinstance(rv, Xor): # This shouldn't really happen here
return rv
patterns = _simplify_patterns_xor()
return _apply_patternbased_simplification(rv, patterns,
kwargs['measure'], None)
def _eval_subs(self, old, new):
# If old is Xor, replace the parts of the arguments with new if all
# are there
if isinstance(old, Xor):
old_set = set(old.args)
if old_set.issubset(self.args):
args = set(self.args) - old_set
args.add(new)
return self.func(*args)
class Nand(BooleanFunction):
"""
Logical NAND function.
It evaluates its arguments in order, giving True immediately if any
of them are False, and False if they are all True.
Returns True if any of the arguments are False
Returns False if all arguments are True
Examples
========
>>> from sympy.logic.boolalg import Nand
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Nand(False, True)
True
>>> Nand(True, True)
False
>>> Nand(x, y)
~(x & y)
"""
@classmethod
def eval(cls, *args):
return Not(And(*args))
class Nor(BooleanFunction):
"""
Logical NOR function.
It evaluates its arguments in order, giving False immediately if any
of them are True, and True if they are all False.
Returns False if any argument is True
Returns True if all arguments are False
Examples
========
>>> from sympy.logic.boolalg import Nor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Nor(True, False)
False
>>> Nor(True, True)
False
>>> Nor(False, True)
False
>>> Nor(False, False)
True
>>> Nor(x, y)
~(x | y)
"""
@classmethod
def eval(cls, *args):
return Not(Or(*args))
class Xnor(BooleanFunction):
"""
Logical XNOR function.
Returns False if an odd number of the arguments are True and the rest are
False.
Returns True if an even number of the arguments are True and the rest are
False.
Examples
========
>>> from sympy.logic.boolalg import Xnor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Xnor(True, False)
False
>>> Xnor(True, True)
True
>>> Xnor(True, False, True, True, False)
False
>>> Xnor(True, False, True, False)
True
"""
@classmethod
def eval(cls, *args):
return Not(Xor(*args))
class Implies(BooleanFunction):
r"""
Logical implication.
A implies B is equivalent to if A then B. Mathematically, it is written
as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``.
Accepts two Boolean arguments; A and B.
Returns False if A is True and B is False
Returns True otherwise.
Examples
========
>>> from sympy.logic.boolalg import Implies
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Implies(True, False)
False
>>> Implies(False, False)
True
>>> Implies(True, True)
True
>>> Implies(False, True)
True
>>> x >> y
Implies(x, y)
>>> y << x
Implies(x, y)
Notes
=====
The ``>>`` and ``<<`` operators are provided as a convenience, but note
that their use here is different from their normal use in Python, which is
bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different
things if ``a`` and ``b`` are integers. In particular, since Python
considers ``True`` and ``False`` to be integers, ``True >> True`` will be
the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To
avoid this issue, use the SymPy objects ``true`` and ``false``.
>>> from sympy import true, false
>>> True >> False
1
>>> true >> false
False
"""
@classmethod
def eval(cls, *args):
try:
newargs = []
for x in args:
if isinstance(x, Number) or x in (0, 1):
newargs.append(bool(x))
else:
newargs.append(x)
A, B = newargs
except ValueError:
raise ValueError(
"%d operand(s) used for an Implies "
"(pairs are required): %s" % (len(args), str(args)))
if A in (True, False) or B in (True, False):
return Or(Not(A), B)
elif A == B:
return true
elif A.is_Relational and B.is_Relational:
if A.canonical == B.canonical:
return true
if A.negated.canonical == B.canonical:
return B
else:
return Basic.__new__(cls, *args)
def to_nnf(self, simplify=True):
a, b = self.args
return Or._to_nnf(Not(a), b, simplify=simplify)
def to_anf(self, deep=True):
a, b = self.args
return Xor._to_anf(true, a, And(a, b), deep=deep)
class Equivalent(BooleanFunction):
"""
Equivalence relation.
``Equivalent(A, B)`` is True iff A and B are both True or both False.
Returns True if all of the arguments are logically equivalent.
Returns False otherwise.
For two arguments, this is equivalent to :py:class:`~.Xnor`.
Examples
========
>>> from sympy.logic.boolalg import Equivalent, And
>>> from sympy.abc import x
>>> Equivalent(False, False, False)
True
>>> Equivalent(True, False, False)
False
>>> Equivalent(x, And(x, True))
True
"""
def __new__(cls, *args, **options):
from sympy.core.relational import Relational
args = [_sympify(arg) for arg in args]
argset = set(args)
for x in args:
if isinstance(x, Number) or x in [True, False]: # Includes 0, 1
argset.discard(x)
argset.add(bool(x))
rel = []
for r in argset:
if isinstance(r, Relational):
rel.append((r, r.canonical, r.negated.canonical))
remove = []
for i, (r, c, nc) in enumerate(rel):
for j in range(i + 1, len(rel)):
rj, cj = rel[j][:2]
if cj == nc:
return false
elif cj == c:
remove.append((r, rj))
break
for a, b in remove:
argset.remove(a)
argset.remove(b)
argset.add(True)
if len(argset) <= 1:
return true
if True in argset:
argset.discard(True)
return And(*argset)
if False in argset:
argset.discard(False)
return And(*[Not(arg) for arg in argset])
_args = frozenset(argset)
obj = super().__new__(cls, _args)
obj._argset = _args
return obj
# XXX: This should be cached on the object rather than using cacheit
# Maybe it can be computed in __new__?
@property # type: ignore
@cacheit
def args(self):
return tuple(ordered(self._argset))
def to_nnf(self, simplify=True):
args = []
for a, b in zip(self.args, self.args[1:]):
args.append(Or(Not(a), b))
args.append(Or(Not(self.args[-1]), self.args[0]))
return And._to_nnf(*args, simplify=simplify)
def to_anf(self, deep=True):
a = And(*self.args)
b = And(*[to_anf(Not(arg), deep=False) for arg in self.args])
b = distribute_xor_over_and(b)
return Xor._to_anf(a, b, deep=deep)
class ITE(BooleanFunction):
"""
If-then-else clause.
``ITE(A, B, C)`` evaluates and returns the result of B if A is true
else it returns the result of C. All args must be Booleans.
From a logic gate perspective, ITE corresponds to a 2-to-1 multiplexer,
where A is the select signal.
Examples
========
>>> from sympy.logic.boolalg import ITE, And, Xor, Or
>>> from sympy.abc import x, y, z
>>> ITE(True, False, True)
False
>>> ITE(Or(True, False), And(True, True), Xor(True, True))
True
>>> ITE(x, y, z)
ITE(x, y, z)
>>> ITE(True, x, y)
x
>>> ITE(False, x, y)
y
>>> ITE(x, y, y)
y
Trying to use non-Boolean args will generate a TypeError:
>>> ITE(True, [], ())
Traceback (most recent call last):
...
TypeError: expecting bool, Boolean or ITE, not `[]`
"""
def __new__(cls, *args, **kwargs):
from sympy.core.relational import Eq, Ne
if len(args) != 3:
raise ValueError('expecting exactly 3 args')
a, b, c = args
# check use of binary symbols
if isinstance(a, (Eq, Ne)):
# in this context, we can evaluate the Eq/Ne
# if one arg is a binary symbol and the other
# is true/false
b, c = map(as_Boolean, (b, c))
bin_syms = set().union(*[i.binary_symbols for i in (b, c)])
if len(set(a.args) - bin_syms) == 1:
# one arg is a binary_symbols
_a = a
if a.lhs is true:
a = a.rhs
elif a.rhs is true:
a = a.lhs
elif a.lhs is false:
a = Not(a.rhs)
elif a.rhs is false:
a = Not(a.lhs)
else:
# binary can only equal True or False
a = false
if isinstance(_a, Ne):
a = Not(a)
else:
a, b, c = BooleanFunction.binary_check_and_simplify(
a, b, c)
rv = None
if kwargs.get('evaluate', True):
rv = cls.eval(a, b, c)
if rv is None:
rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False)
return rv
@classmethod
def eval(cls, *args):
from sympy.core.relational import Eq, Ne
# do the args give a singular result?
a, b, c = args
if isinstance(a, (Ne, Eq)):
_a = a
if true in a.args:
a = a.lhs if a.rhs is true else a.rhs
elif false in a.args:
a = Not(a.lhs) if a.rhs is false else Not(a.rhs)
else:
_a = None
if _a is not None and isinstance(_a, Ne):
a = Not(a)
if a is true:
return b
if a is false:
return c
if b == c:
return b
else:
# or maybe the results allow the answer to be expressed
# in terms of the condition
if b is true and c is false:
return a
if b is false and c is true:
return Not(a)
if [a, b, c] != args:
return cls(a, b, c, evaluate=False)
def to_nnf(self, simplify=True):
a, b, c = self.args
return And._to_nnf(Or(Not(a), b), Or(a, c), simplify=simplify)
def _eval_as_set(self):
return self.to_nnf().as_set()
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
from sympy.functions.elementary.piecewise import Piecewise
return Piecewise((args[1], args[0]), (args[2], True))
class Exclusive(BooleanFunction):
"""
True if only one or no argument is true.
``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``.
For two arguments, this is equivalent to :py:class:`~.Xor`.
Examples
========
>>> from sympy.logic.boolalg import Exclusive
>>> Exclusive(False, False, False)
True
>>> Exclusive(False, True, False)
True
>>> Exclusive(False, True, True)
False
"""
@classmethod
def eval(cls, *args):
and_args = []
for a, b in combinations(args, 2):
and_args.append(Not(And(a, b)))
return And(*and_args)
# end class definitions. Some useful methods
def conjuncts(expr):
"""Return a list of the conjuncts in ``expr``.
Examples
========
>>> from sympy.logic.boolalg import conjuncts
>>> from sympy.abc import A, B
>>> conjuncts(A & B)
frozenset({A, B})
>>> conjuncts(A | B)
frozenset({A | B})
"""
return And.make_args(expr)
def disjuncts(expr):
"""Return a list of the disjuncts in ``expr``.
Examples
========
>>> from sympy.logic.boolalg import disjuncts
>>> from sympy.abc import A, B
>>> disjuncts(A | B)
frozenset({A, B})
>>> disjuncts(A & B)
frozenset({A & B})
"""
return Or.make_args(expr)
def distribute_and_over_or(expr):
"""
Given a sentence ``expr`` consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in CNF.
Examples
========
>>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not
>>> from sympy.abc import A, B, C
>>> distribute_and_over_or(Or(A, And(Not(B), Not(C))))
(A | ~B) & (A | ~C)
"""
return _distribute((expr, And, Or))
def distribute_or_over_and(expr):
"""
Given a sentence ``expr`` consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in DNF.
Note that the output is NOT simplified.
Examples
========
>>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not
>>> from sympy.abc import A, B, C
>>> distribute_or_over_and(And(Or(Not(A), B), C))
(B & C) | (C & ~A)
"""
return _distribute((expr, Or, And))
def distribute_xor_over_and(expr):
"""
Given a sentence ``expr`` consisting of conjunction and
exclusive disjunctions of literals, return an
equivalent exclusive disjunction.
Note that the output is NOT simplified.
Examples
========
>>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not
>>> from sympy.abc import A, B, C
>>> distribute_xor_over_and(And(Xor(Not(A), B), C))
(B & C) ^ (C & ~A)
"""
return _distribute((expr, Xor, And))
def _distribute(info):
"""
Distributes ``info[1]`` over ``info[2]`` with respect to ``info[0]``.
"""
if isinstance(info[0], info[2]):
for arg in info[0].args:
if isinstance(arg, info[1]):
conj = arg
break
else:
return info[0]
rest = info[2](*[a for a in info[0].args if a is not conj])
return info[1](*list(map(_distribute,
[(info[2](c, rest), info[1], info[2])
for c in conj.args])), remove_true=False)
elif isinstance(info[0], info[1]):
return info[1](*list(map(_distribute,
[(x, info[1], info[2])
for x in info[0].args])),
remove_true=False)
else:
return info[0]
def to_anf(expr, deep=True):
r"""
Converts expr to Algebraic Normal Form (ANF).
ANF is a canonical normal form, which means that two
equivalent formulas will convert to the same ANF.
A logical expression is in ANF if it has the form
.. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
i.e. it can be:
- purely true,
- purely false,
- conjunction of variables,
- exclusive disjunction.
The exclusive disjunction can only contain true, variables
or conjunction of variables. No negations are permitted.
If ``deep`` is ``False``, arguments of the boolean
expression are considered variables, i.e. only the
top-level expression is converted to ANF.
Examples
========
>>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent
>>> from sympy.logic.boolalg import to_anf
>>> from sympy.abc import A, B, C
>>> to_anf(Not(A))
A ^ True
>>> to_anf(And(Or(A, B), Not(C)))
A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C)
>>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False)
True ^ ~A ^ (~A & (Equivalent(B, C)))
"""
expr = sympify(expr)
if is_anf(expr):
return expr
return expr.to_anf(deep=deep)
def to_nnf(expr, simplify=True):
"""
Converts ``expr`` to Negation Normal Form (NNF).
A logical expression is in NNF if it
contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`,
and :py:class:`~.Not` is applied only to literals.
If ``simplify`` is ``True``, the result contains no redundant clauses.
Examples
========
>>> from sympy.abc import A, B, C, D
>>> from sympy.logic.boolalg import Not, Equivalent, to_nnf
>>> to_nnf(Not((~A & ~B) | (C & D)))
(A | B) & (~C | ~D)
>>> to_nnf(Equivalent(A >> B, B >> A))
(A | ~B | (A & ~B)) & (B | ~A | (B & ~A))
"""
if is_nnf(expr, simplify):
return expr
return expr.to_nnf(simplify)
def to_cnf(expr, simplify=False, force=False):
"""
Convert a propositional logical sentence ``expr`` to conjunctive normal
form: ``((A | ~B | ...) & (B | C | ...) & ...)``.
If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest CNF
form using the Quine-McCluskey algorithm; this may take a long
time. If there are more than 8 variables the ``force`` flag must be set
to ``True`` to simplify (default is ``False``).
Examples
========
>>> from sympy.logic.boolalg import to_cnf
>>> from sympy.abc import A, B, D
>>> to_cnf(~(A | B) | D)
(D | ~A) & (D | ~B)
>>> to_cnf((A | B) & (A | ~A), True)
A | B
"""
expr = sympify(expr)
if not isinstance(expr, BooleanFunction):
return expr
if simplify:
if not force and len(_find_predicates(expr)) > 8:
raise ValueError(filldedent('''
To simplify a logical expression with more
than 8 variables may take a long time and requires
the use of `force=True`.'''))
return simplify_logic(expr, 'cnf', True, force=force)
# Don't convert unless we have to
if is_cnf(expr):
return expr
expr = eliminate_implications(expr)
res = distribute_and_over_or(expr)
return res
def to_dnf(expr, simplify=False, force=False):
"""
Convert a propositional logical sentence ``expr`` to disjunctive normal
form: ``((A & ~B & ...) | (B & C & ...) | ...)``.
If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest DNF form using
the Quine-McCluskey algorithm; this may take a long
time. If there are more than 8 variables, the ``force`` flag must be set to
``True`` to simplify (default is ``False``).
Examples
========
>>> from sympy.logic.boolalg import to_dnf
>>> from sympy.abc import A, B, C
>>> to_dnf(B & (A | C))
(A & B) | (B & C)
>>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True)
A | C
"""
expr = sympify(expr)
if not isinstance(expr, BooleanFunction):
return expr
if simplify:
if not force and len(_find_predicates(expr)) > 8:
raise ValueError(filldedent('''
To simplify a logical expression with more
than 8 variables may take a long time and requires
the use of `force=True`.'''))
return simplify_logic(expr, 'dnf', True, force=force)
# Don't convert unless we have to
if is_dnf(expr):
return expr
expr = eliminate_implications(expr)
return distribute_or_over_and(expr)
def is_anf(expr):
r"""
Checks if ``expr`` is in Algebraic Normal Form (ANF).
A logical expression is in ANF if it has the form
.. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
i.e. it is purely true, purely false, conjunction of
variables or exclusive disjunction. The exclusive
disjunction can only contain true, variables or
conjunction of variables. No negations are permitted.
Examples
========
>>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf
>>> from sympy.abc import A, B, C
>>> is_anf(true)
True
>>> is_anf(A)
True
>>> is_anf(And(A, B, C))
True
>>> is_anf(Xor(A, Not(B)))
False
"""
expr = sympify(expr)
if is_literal(expr) and not isinstance(expr, Not):
return True
if isinstance(expr, And):
for arg in expr.args:
if not arg.is_Symbol:
return False
return True
elif isinstance(expr, Xor):
for arg in expr.args:
if isinstance(arg, And):
for a in arg.args:
if not a.is_Symbol:
return False
elif is_literal(arg):
if isinstance(arg, Not):
return False
else:
return False
return True
else:
return False
def is_nnf(expr, simplified=True):
"""
Checks if ``expr`` is in Negation Normal Form (NNF).
A logical expression is in NNF if it
contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`,
and :py:class:`~.Not` is applied only to literals.
If ``simplified`` is ``True``, checks if result contains no redundant clauses.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy.logic.boolalg import Not, is_nnf
>>> is_nnf(A & B | ~C)
True
>>> is_nnf((A | ~A) & (B | C))
False
>>> is_nnf((A | ~A) & (B | C), False)
True
>>> is_nnf(Not(A & B) | C)
False
>>> is_nnf((A >> B) & (B >> A))
False
"""
expr = sympify(expr)
if is_literal(expr):
return True
stack = [expr]
while stack:
expr = stack.pop()
if expr.func in (And, Or):
if simplified:
args = expr.args
for arg in args:
if Not(arg) in args:
return False
stack.extend(expr.args)
elif not is_literal(expr):
return False
return True
def is_cnf(expr):
"""
Test whether or not an expression is in conjunctive normal form.
Examples
========
>>> from sympy.logic.boolalg import is_cnf
>>> from sympy.abc import A, B, C
>>> is_cnf(A | B | C)
True
>>> is_cnf(A & B & C)
True
>>> is_cnf((A & B) | C)
False
"""
return _is_form(expr, And, Or)
def is_dnf(expr):
"""
Test whether or not an expression is in disjunctive normal form.
Examples
========
>>> from sympy.logic.boolalg import is_dnf
>>> from sympy.abc import A, B, C
>>> is_dnf(A | B | C)
True
>>> is_dnf(A & B & C)
True
>>> is_dnf((A & B) | C)
True
>>> is_dnf(A & (B | C))
False
"""
return _is_form(expr, Or, And)
def _is_form(expr, function1, function2):
"""
Test whether or not an expression is of the required form.
"""
expr = sympify(expr)
vals = function1.make_args(expr) if isinstance(expr, function1) else [expr]
for lit in vals:
if isinstance(lit, function2):
vals2 = function2.make_args(lit) if isinstance(lit, function2) else [lit]
for l in vals2:
if is_literal(l) is False:
return False
elif is_literal(lit) is False:
return False
return True
def eliminate_implications(expr):
"""
Change :py:class:`~.Implies` and :py:class:`~.Equivalent` into
:py:class:`~.And`, :py:class:`~.Or`, and :py:class:`~.Not`.
That is, return an expression that is equivalent to ``expr``, but has only
``&``, ``|``, and ``~`` as logical
operators.
Examples
========
>>> from sympy.logic.boolalg import Implies, Equivalent, \
eliminate_implications
>>> from sympy.abc import A, B, C
>>> eliminate_implications(Implies(A, B))
B | ~A
>>> eliminate_implications(Equivalent(A, B))
(A | ~B) & (B | ~A)
>>> eliminate_implications(Equivalent(A, B, C))
(A | ~C) & (B | ~A) & (C | ~B)
"""
return to_nnf(expr, simplify=False)
def is_literal(expr):
"""
Returns True if expr is a literal, else False.
Examples
========
>>> from sympy import Or, Q
>>> from sympy.abc import A, B
>>> from sympy.logic.boolalg import is_literal
>>> is_literal(A)
True
>>> is_literal(~A)
True
>>> is_literal(Q.zero(A))
True
>>> is_literal(A + B)
True
>>> is_literal(Or(A, B))
False
"""
from sympy.assumptions import AppliedPredicate
if isinstance(expr, Not):
return is_literal(expr.args[0])
elif expr in (True, False) or isinstance(expr, AppliedPredicate) or expr.is_Atom:
return True
elif not isinstance(expr, BooleanFunction) and all(
(isinstance(expr, AppliedPredicate) or a.is_Atom) for a in expr.args):
return True
return False
def to_int_repr(clauses, symbols):
"""
Takes clauses in CNF format and puts them into an integer representation.
Examples
========
>>> from sympy.logic.boolalg import to_int_repr
>>> from sympy.abc import x, y
>>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}]
True
"""
# Convert the symbol list into a dict
symbols = dict(list(zip(symbols, list(range(1, len(symbols) + 1)))))
def append_symbol(arg, symbols):
if isinstance(arg, Not):
return -symbols[arg.args[0]]
else:
return symbols[arg]
return [{append_symbol(arg, symbols) for arg in Or.make_args(c)}
for c in clauses]
def term_to_integer(term):
"""
Return an integer corresponding to the base-2 digits given by *term*.
Parameters
==========
term : a string or list of ones and zeros
Examples
========
>>> from sympy.logic.boolalg import term_to_integer
>>> term_to_integer([1, 0, 0])
4
>>> term_to_integer('100')
4
"""
return int(''.join(list(map(str, list(term)))), 2)
integer_to_term = ibin # XXX could delete?
def truth_table(expr, variables, input=True):
"""
Return a generator of all possible configurations of the input variables,
and the result of the boolean expression for those values.
Parameters
==========
expr : Boolean expression
variables : list of variables
input : bool (default ``True``)
Indicates whether to return the input combinations.
Examples
========
>>> from sympy.logic.boolalg import truth_table
>>> from sympy.abc import x,y
>>> table = truth_table(x >> y, [x, y])
>>> for t in table:
... print('{0} -> {1}'.format(*t))
[0, 0] -> True
[0, 1] -> True
[1, 0] -> False
[1, 1] -> True
>>> table = truth_table(x | y, [x, y])
>>> list(table)
[([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)]
If ``input`` is ``False``, ``truth_table`` returns only a list of truth values.
In this case, the corresponding input values of variables can be
deduced from the index of a given output.
>>> from sympy.utilities.iterables import ibin
>>> vars = [y, x]
>>> values = truth_table(x >> y, vars, input=False)
>>> values = list(values)
>>> values
[True, False, True, True]
>>> for i, value in enumerate(values):
... print('{0} -> {1}'.format(list(zip(
... vars, ibin(i, len(vars)))), value))
[(y, 0), (x, 0)] -> True
[(y, 0), (x, 1)] -> False
[(y, 1), (x, 0)] -> True
[(y, 1), (x, 1)] -> True
"""
variables = [sympify(v) for v in variables]
expr = sympify(expr)
if not isinstance(expr, BooleanFunction) and not is_literal(expr):
return
table = product((0, 1), repeat=len(variables))
for term in table:
value = expr.xreplace(dict(zip(variables, term)))
if input:
yield list(term), value
else:
yield value
def _check_pair(minterm1, minterm2):
"""
Checks if a pair of minterms differs by only one bit. If yes, returns
index, else returns `-1`.
"""
# Early termination seems to be faster than list comprehension,
# at least for large examples.
index = -1
for x, i in enumerate(minterm1): # zip(minterm1, minterm2) is slower
if i != minterm2[x]:
if index == -1:
index = x
else:
return -1
return index
def _convert_to_varsSOP(minterm, variables):
"""
Converts a term in the expansion of a function from binary to its
variable form (for SOP).
"""
temp = [variables[n] if val == 1 else Not(variables[n])
for n, val in enumerate(minterm) if val != 3]
return And(*temp)
def _convert_to_varsPOS(maxterm, variables):
"""
Converts a term in the expansion of a function from binary to its
variable form (for POS).
"""
temp = [variables[n] if val == 0 else Not(variables[n])
for n, val in enumerate(maxterm) if val != 3]
return Or(*temp)
def _convert_to_varsANF(term, variables):
"""
Converts a term in the expansion of a function from binary to its
variable form (for ANF).
Parameters
==========
term : list of 1's and 0's (complementation patter)
variables : list of variables
"""
temp = [variables[n] for n, t in enumerate(term) if t == 1]
if not temp:
return true
return And(*temp)
def _get_odd_parity_terms(n):
"""
Returns a list of lists, with all possible combinations of n zeros and ones
with an odd number of ones.
"""
return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 1]
def _get_even_parity_terms(n):
"""
Returns a list of lists, with all possible combinations of n zeros and ones
with an even number of ones.
"""
return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 0]
def _simplified_pairs(terms):
"""
Reduces a set of minterms, if possible, to a simplified set of minterms
with one less variable in the terms using QM method.
"""
if not terms:
return []
simplified_terms = []
todo = list(range(len(terms)))
# Count number of ones as _check_pair can only potentially match if there
# is at most a difference of a single one
termdict = defaultdict(list)
for n, term in enumerate(terms):
ones = sum([1 for t in term if t == 1])
termdict[ones].append(n)
variables = len(terms[0])
for k in range(variables):
for i in termdict[k]:
for j in termdict[k+1]:
index = _check_pair(terms[i], terms[j])
if index != -1:
# Mark terms handled
todo[i] = todo[j] = None
# Copy old term
newterm = terms[i][:]
# Set differing position to don't care
newterm[index] = 3
# Add if not already there
if newterm not in simplified_terms:
simplified_terms.append(newterm)
if simplified_terms:
# Further simplifications only among the new terms
simplified_terms = _simplified_pairs(simplified_terms)
# Add remaining, non-simplified, terms
simplified_terms.extend([terms[i] for i in todo if i is not None])
return simplified_terms
def _rem_redundancy(l1, terms):
"""
After the truth table has been sufficiently simplified, use the prime
implicant table method to recognize and eliminate redundant pairs,
and return the essential arguments.
"""
if not terms:
return []
nterms = len(terms)
nl1 = len(l1)
# Create dominating matrix
dommatrix = [[0]*nl1 for n in range(nterms)]
colcount = [0]*nl1
rowcount = [0]*nterms
for primei, prime in enumerate(l1):
for termi, term in enumerate(terms):
# Check prime implicant covering term
if all(t == 3 or t == mt for t, mt in zip(prime, term)):
dommatrix[termi][primei] = 1
colcount[primei] += 1
rowcount[termi] += 1
# Keep track if anything changed
anythingchanged = True
# Then, go again
while anythingchanged:
anythingchanged = False
for rowi in range(nterms):
# Still non-dominated?
if rowcount[rowi]:
row = dommatrix[rowi]
for row2i in range(nterms):
# Still non-dominated?
if rowi != row2i and rowcount[rowi] and (rowcount[rowi] <= rowcount[row2i]):
row2 = dommatrix[row2i]
if all(row2[n] >= row[n] for n in range(nl1)):
# row2 dominating row, remove row2
rowcount[row2i] = 0
anythingchanged = True
for primei, prime in enumerate(row2):
if prime:
# Make corresponding entry 0
dommatrix[row2i][primei] = 0
colcount[primei] -= 1
colcache = {}
for coli in range(nl1):
# Still non-dominated?
if colcount[coli]:
if coli in colcache:
col = colcache[coli]
else:
col = [dommatrix[i][coli] for i in range(nterms)]
colcache[coli] = col
for col2i in range(nl1):
# Still non-dominated?
if coli != col2i and colcount[col2i] and (colcount[coli] >= colcount[col2i]):
if col2i in colcache:
col2 = colcache[col2i]
else:
col2 = [dommatrix[i][col2i] for i in range(nterms)]
colcache[col2i] = col2
if all(col[n] >= col2[n] for n in range(nterms)):
# col dominating col2, remove col2
colcount[col2i] = 0
anythingchanged = True
for termi, term in enumerate(col2):
if term and dommatrix[termi][col2i]:
# Make corresponding entry 0
dommatrix[termi][col2i] = 0
rowcount[termi] -= 1
if not anythingchanged:
# Heuristically select the prime implicant covering most terms
maxterms = 0
bestcolidx = -1
for coli in range(nl1):
s = colcount[coli]
if s > maxterms:
bestcolidx = coli
maxterms = s
# In case we found a prime implicant covering at least two terms
if bestcolidx != -1 and maxterms > 1:
for primei, prime in enumerate(l1):
if primei != bestcolidx:
for termi, term in enumerate(colcache[bestcolidx]):
if term and dommatrix[termi][primei]:
# Make corresponding entry 0
dommatrix[termi][primei] = 0
anythingchanged = True
rowcount[termi] -= 1
colcount[primei] -= 1
return [l1[i] for i in range(nl1) if colcount[i]]
def _input_to_binlist(inputlist, variables):
binlist = []
bits = len(variables)
for val in inputlist:
if isinstance(val, int):
binlist.append(ibin(val, bits))
elif isinstance(val, dict):
nonspecvars = list(variables)
for key in val.keys():
nonspecvars.remove(key)
for t in product((0, 1), repeat=len(nonspecvars)):
d = dict(zip(nonspecvars, t))
d.update(val)
binlist.append([d[v] for v in variables])
elif isinstance(val, (list, tuple)):
if len(val) != bits:
raise ValueError("Each term must contain {bits} bits as there are"
"\n{bits} variables (or be an integer)."
"".format(bits=bits))
binlist.append(list(val))
else:
raise TypeError("A term list can only contain lists,"
" ints or dicts.")
return binlist
def SOPform(variables, minterms, dontcares=None):
"""
The SOPform function uses simplified_pairs and a redundant group-
eliminating algorithm to convert the list of all input combos that
generate '1' (the minterms) into the smallest sum-of-products form.
The variables must be given as the first argument.
Return a logical :py:class:`~.Or` function (i.e., the "sum of products" or
"SOP" form) that gives the desired outcome. If there are inputs that can
be ignored, pass them as a list, too.
The result will be one of the (perhaps many) functions that satisfy
the conditions.
Examples
========
>>> from sympy.logic import SOPform
>>> from sympy import symbols
>>> w, x, y, z = symbols('w x y z')
>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1],
... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]]
>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
>>> SOPform([w, x, y, z], minterms, dontcares)
(y & z) | (~w & ~x)
The terms can also be represented as integers:
>>> minterms = [1, 3, 7, 11, 15]
>>> dontcares = [0, 2, 5]
>>> SOPform([w, x, y, z], minterms, dontcares)
(y & z) | (~w & ~x)
They can also be specified using dicts, which does not have to be fully
specified:
>>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
>>> SOPform([w, x, y, z], minterms)
(x & ~w) | (y & z & ~x)
Or a combination:
>>> minterms = [4, 7, 11, [1, 1, 1, 1]]
>>> dontcares = [{w : 0, x : 0, y: 0}, 5]
>>> SOPform([w, x, y, z], minterms, dontcares)
(w & y & z) | (~w & ~y) | (x & z & ~w)
See also
========
POSform
References
==========
.. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
.. [2] https://en.wikipedia.org/wiki/Don%27t-care_term
"""
if not minterms:
return false
variables = tuple(map(sympify, variables))
minterms = _input_to_binlist(minterms, variables)
dontcares = _input_to_binlist((dontcares or []), variables)
for d in dontcares:
if d in minterms:
raise ValueError('%s in minterms is also in dontcares' % d)
return _sop_form(variables, minterms, dontcares)
def _sop_form(variables, minterms, dontcares):
new = _simplified_pairs(minterms + dontcares)
essential = _rem_redundancy(new, minterms)
return Or(*[_convert_to_varsSOP(x, variables) for x in essential])
def POSform(variables, minterms, dontcares=None):
"""
The POSform function uses simplified_pairs and a redundant-group
eliminating algorithm to convert the list of all input combinations
that generate '1' (the minterms) into the smallest product-of-sums form.
The variables must be given as the first argument.
Return a logical :py:class:`~.And` function (i.e., the "product of sums"
or "POS" form) that gives the desired outcome. If there are inputs that can
be ignored, pass them as a list, too.
The result will be one of the (perhaps many) functions that satisfy
the conditions.
Examples
========
>>> from sympy.logic import POSform
>>> from sympy import symbols
>>> w, x, y, z = symbols('w x y z')
>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1],
... [1, 0, 1, 1], [1, 1, 1, 1]]
>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
>>> POSform([w, x, y, z], minterms, dontcares)
z & (y | ~w)
The terms can also be represented as integers:
>>> minterms = [1, 3, 7, 11, 15]
>>> dontcares = [0, 2, 5]
>>> POSform([w, x, y, z], minterms, dontcares)
z & (y | ~w)
They can also be specified using dicts, which does not have to be fully
specified:
>>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
>>> POSform([w, x, y, z], minterms)
(x | y) & (x | z) & (~w | ~x)
Or a combination:
>>> minterms = [4, 7, 11, [1, 1, 1, 1]]
>>> dontcares = [{w : 0, x : 0, y: 0}, 5]
>>> POSform([w, x, y, z], minterms, dontcares)
(w | x) & (y | ~w) & (z | ~y)
See also
========
SOPform
References
==========
.. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
.. [2] https://en.wikipedia.org/wiki/Don%27t-care_term
"""
if not minterms:
return false
variables = tuple(map(sympify, variables))
minterms = _input_to_binlist(minterms, variables)
dontcares = _input_to_binlist((dontcares or []), variables)
for d in dontcares:
if d in minterms:
raise ValueError('%s in minterms is also in dontcares' % d)
maxterms = []
for t in product((0, 1), repeat=len(variables)):
t = list(t)
if (t not in minterms) and (t not in dontcares):
maxterms.append(t)
new = _simplified_pairs(maxterms + dontcares)
essential = _rem_redundancy(new, maxterms)
return And(*[_convert_to_varsPOS(x, variables) for x in essential])
def ANFform(variables, truthvalues):
"""
The ANFform function converts the list of truth values to
Algebraic Normal Form (ANF).
The variables must be given as the first argument.
Return True, False, logical :py:class:`~.And` funciton (i.e., the
"Zhegalkin monomial") or logical :py:class:`~.Xor` function (i.e.,
the "Zhegalkin polynomial"). When True and False
are represented by 1 and 0, respectively, then
:py:class:`~.And` is multiplication and :py:class:`~.Xor` is addition.
Formally a "Zhegalkin monomial" is the product (logical
And) of a finite set of distinct variables, including
the empty set whose product is denoted 1 (True).
A "Zhegalkin polynomial" is the sum (logical Xor) of a
set of Zhegalkin monomials, with the empty set denoted
by 0 (False).
Parameters
==========
variables : list of variables
truthvalues : list of 1's and 0's (result column of truth table)
Examples
========
>>> from sympy.logic.boolalg import ANFform
>>> from sympy.abc import x, y
>>> ANFform([x], [1, 0])
x ^ True
>>> ANFform([x, y], [0, 1, 1, 1])
x ^ y ^ (x & y)
References
==========
.. [1] https://en.wikipedia.org/wiki/Zhegalkin_polynomial
"""
n_vars = len(variables)
n_values = len(truthvalues)
if n_values != 2 ** n_vars:
raise ValueError("The number of truth values must be equal to 2^%d, "
"got %d" % (n_vars, n_values))
variables = tuple(map(sympify, variables))
coeffs = anf_coeffs(truthvalues)
terms = []
for i, t in enumerate(product((0, 1), repeat=n_vars)):
if coeffs[i] == 1:
terms.append(t)
return Xor(*[_convert_to_varsANF(x, variables) for x in terms],
remove_true=False)
def anf_coeffs(truthvalues):
"""
Convert a list of truth values of some boolean expression
to the list of coefficients of the polynomial mod 2 (exclusive
disjunction) representing the boolean expression in ANF
(i.e., the "Zhegalkin polynomial").
There are `2^n` possible Zhegalkin monomials in `n` variables, since
each monomial is fully specified by the presence or absence of
each variable.
We can enumerate all the monomials. For example, boolean
function with four variables ``(a, b, c, d)`` can contain
up to `2^4 = 16` monomials. The 13-th monomial is the
product ``a & b & d``, because 13 in binary is 1, 1, 0, 1.
A given monomial's presence or absence in a polynomial corresponds
to that monomial's coefficient being 1 or 0 respectively.
Examples
========
>>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor
>>> from sympy.abc import a, b, c
>>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1]
>>> coeffs = anf_coeffs(truthvalues)
>>> coeffs
[0, 1, 1, 0, 0, 0, 1, 0]
>>> polynomial = Xor(*[
... bool_monomial(k, [a, b, c])
... for k, coeff in enumerate(coeffs) if coeff == 1
... ])
>>> polynomial
b ^ c ^ (a & b)
"""
s = '{:b}'.format(len(truthvalues))
n = len(s) - 1
if len(truthvalues) != 2**n:
raise ValueError("The number of truth values must be a power of two, "
"got %d" % len(truthvalues))
coeffs = [[v] for v in truthvalues]
for i in range(n):
tmp = []
for j in range(2 ** (n-i-1)):
tmp.append(coeffs[2*j] +
list(map(lambda x, y: x^y, coeffs[2*j], coeffs[2*j+1])))
coeffs = tmp
return coeffs[0]
def bool_minterm(k, variables):
"""
Return the k-th minterm.
Minterms are numbered by a binary encoding of the complementation
pattern of the variables. This convention assigns the value 1 to
the direct form and 0 to the complemented form.
Parameters
==========
k : int or list of 1's and 0's (complementation patter)
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_minterm
>>> from sympy.abc import x, y, z
>>> bool_minterm([1, 0, 1], [x, y, z])
x & z & ~y
>>> bool_minterm(6, [x, y, z])
x & y & ~z
References
==========
.. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms
"""
if isinstance(k, int):
k = ibin(k, len(variables))
variables = tuple(map(sympify, variables))
return _convert_to_varsSOP(k, variables)
def bool_maxterm(k, variables):
"""
Return the k-th maxterm.
Each maxterm is assigned an index based on the opposite
conventional binary encoding used for minterms. The maxterm
convention assigns the value 0 to the direct form and 1 to
the complemented form.
Parameters
==========
k : int or list of 1's and 0's (complementation pattern)
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_maxterm
>>> from sympy.abc import x, y, z
>>> bool_maxterm([1, 0, 1], [x, y, z])
y | ~x | ~z
>>> bool_maxterm(6, [x, y, z])
z | ~x | ~y
References
==========
.. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms
"""
if isinstance(k, int):
k = ibin(k, len(variables))
variables = tuple(map(sympify, variables))
return _convert_to_varsPOS(k, variables)
def bool_monomial(k, variables):
"""
Return the k-th monomial.
Monomials are numbered by a binary encoding of the presence and
absences of the variables. This convention assigns the value
1 to the presence of variable and 0 to the absence of variable.
Each boolean function can be uniquely represented by a
Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin
Polynomial of the boolean function with `n` variables can contain
up to `2^n` monomials. We can enumarate all the monomials.
Each monomial is fully specified by the presence or absence
of each variable.
For example, boolean function with four variables ``(a, b, c, d)``
can contain up to `2^4 = 16` monomials. The 13-th monomial is the
product ``a & b & d``, because 13 in binary is 1, 1, 0, 1.
Parameters
==========
k : int or list of 1's and 0's
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_monomial
>>> from sympy.abc import x, y, z
>>> bool_monomial([1, 0, 1], [x, y, z])
x & z
>>> bool_monomial(6, [x, y, z])
x & y
"""
if isinstance(k, int):
k = ibin(k, len(variables))
variables = tuple(map(sympify, variables))
return _convert_to_varsANF(k, variables)
def _find_predicates(expr):
"""Helper to find logical predicates in BooleanFunctions.
A logical predicate is defined here as anything within a BooleanFunction
that is not a BooleanFunction itself.
"""
if not isinstance(expr, BooleanFunction):
return {expr}
return set().union(*(map(_find_predicates, expr.args)))
def simplify_logic(expr, form=None, deep=True, force=False, dontcare=None):
"""
This function simplifies a boolean function to its simplified version
in SOP or POS form. The return type is an :py:class:`~.Or` or
:py:class:`~.And` object in SymPy.
Parameters
==========
expr : Boolean expression
form : string (``'cnf'`` or ``'dnf'``) or ``None`` (default).
If ``'cnf'`` or ``'dnf'``, the simplest expression in the corresponding
normal form is returned; if ``None``, the answer is returned
according to the form with fewest args (in CNF by default).
deep : bool (default ``True``)
Indicates whether to recursively simplify any
non-boolean functions contained within the input.
force : bool (default ``False``)
As the simplifications require exponential time in the number
of variables, there is by default a limit on expressions with
8 variables. When the expression has more than 8 variables
only symbolical simplification (controlled by ``deep``) is
made. By setting ``force`` to ``True``, this limit is removed. Be
aware that this can lead to very long simplification times.
dontcare : Boolean expression
Optimize expression under the assumption that inputs where this
expression is true are don't care. This is useful in e.g. Piecewise
conditions, where later conditions do not need to consider inputs that
are convered by previous conditions. For example, if a previous
condition is ``And(A, B)``, the simplification of expr can be made
with don't cares for ``And(A, B)``.
Examples
========
>>> from sympy.logic import simplify_logic
>>> from sympy.abc import x, y, z
>>> b = (~x & ~y & ~z) | ( ~x & ~y & z)
>>> simplify_logic(b)
~x & ~y
>>> simplify_logic(x | y, dontcare=y)
x
References
==========
.. [1] https://en.wikipedia.org/wiki/Don%27t-care_term
"""
if form not in (None, 'cnf', 'dnf'):
raise ValueError("form can be cnf or dnf only")
expr = sympify(expr)
# check for quick exit if form is given: right form and all args are
# literal and do not involve Not
if form:
form_ok = False
if form == 'cnf':
form_ok = is_cnf(expr)
elif form == 'dnf':
form_ok = is_dnf(expr)
if form_ok and all(is_literal(a)
for a in expr.args):
return expr
from sympy.core.relational import Relational
if deep:
variables = expr.atoms(Relational)
from sympy.simplify.simplify import simplify
s = tuple(map(simplify, variables))
expr = expr.xreplace(dict(zip(variables, s)))
if not isinstance(expr, BooleanFunction):
return expr
# Replace Relationals with Dummys to possibly
# reduce the number of variables
repl = {}
undo = {}
from sympy.core.symbol import Dummy
variables = expr.atoms(Relational)
if dontcare is not None:
dontcare = sympify(dontcare)
variables.update(dontcare.atoms(Relational))
while variables:
var = variables.pop()
if var.is_Relational:
d = Dummy()
undo[d] = var
repl[var] = d
nvar = var.negated
if nvar in variables:
repl[nvar] = Not(d)
variables.remove(nvar)
expr = expr.xreplace(repl)
if dontcare is not None:
dontcare = dontcare.xreplace(repl)
# Get new variables after replacing
variables = _find_predicates(expr)
if not force and len(variables) > 8:
return expr.xreplace(undo)
if dontcare is not None:
# Add variables from dontcare
dcvariables = _find_predicates(dontcare)
variables.update(dcvariables)
# if too many restore to variables only
if not force and len(variables) > 8:
variables = _find_predicates(expr)
dontcare = None
# group into constants and variable values
c, v = sift(ordered(variables), lambda x: x in (True, False), binary=True)
variables = c + v
# standardize constants to be 1 or 0 in keeping with truthtable
c = [1 if i == True else 0 for i in c]
truthtable = _get_truthtable(v, expr, c)
if dontcare is not None:
dctruthtable = _get_truthtable(v, dontcare, c)
truthtable = [t for t in truthtable if t not in dctruthtable]
else:
dctruthtable = []
big = len(truthtable) >= (2 ** (len(variables) - 1))
if form == 'dnf' or form is None and big:
return _sop_form(variables, truthtable, dctruthtable).xreplace(undo)
return POSform(variables, truthtable, dctruthtable).xreplace(undo)
def _get_truthtable(variables, expr, const):
""" Return a list of all combinations leading to a True result for ``expr``.
"""
_variables = variables.copy()
def _get_tt(inputs):
if _variables:
v = _variables.pop()
tab = [[i[0].xreplace({v: false}), [0] + i[1]] for i in inputs if i[0] is not false]
tab.extend([[i[0].xreplace({v: true}), [1] + i[1]] for i in inputs if i[0] is not false])
return _get_tt(tab)
return inputs
res = [const + k[1] for k in _get_tt([[expr, []]]) if k[0]]
if res == [[]]:
return []
else:
return res
def _finger(eq):
"""
Assign a 5-item fingerprint to each symbol in the equation:
[
# of times it appeared as a Symbol;
# of times it appeared as a Not(symbol);
# of times it appeared as a Symbol in an And or Or;
# of times it appeared as a Not(Symbol) in an And or Or;
a sorted tuple of tuples, (i, j, k), where i is the number of arguments
in an And or Or with which it appeared as a Symbol, and j is
the number of arguments that were Not(Symbol); k is the number
of times that (i, j) was seen.
]
Examples
========
>>> from sympy.logic.boolalg import _finger as finger
>>> from sympy import And, Or, Not, Xor, to_cnf, symbols
>>> from sympy.abc import a, b, x, y
>>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y))
>>> dict(finger(eq))
{(0, 0, 1, 0, ((2, 0, 1),)): [x],
(0, 0, 1, 0, ((2, 1, 1),)): [a, b],
(0, 0, 1, 2, ((2, 0, 1),)): [y]}
>>> dict(finger(x & ~y))
{(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]}
In the following, the (5, 2, 6) means that there were 6 Or
functions in which a symbol appeared as itself amongst 5 arguments in
which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)``
is counted once for a0, a1 and a2.
>>> dict(finger(to_cnf(Xor(*symbols('a:5')))))
{(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]}
The equation must not have more than one level of nesting:
>>> dict(finger(And(Or(x, y), y)))
{(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]}
>>> dict(finger(And(Or(x, And(a, x)), y)))
Traceback (most recent call last):
...
NotImplementedError: unexpected level of nesting
So y and x have unique fingerprints, but a and b do not.
"""
f = eq.free_symbols
d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f])))
for a in eq.args:
if a.is_Symbol:
d[a][0] += 1
elif a.is_Not:
d[a.args[0]][1] += 1
else:
o = len(a.args), sum(isinstance(ai, Not) for ai in a.args)
for ai in a.args:
if ai.is_Symbol:
d[ai][2] += 1
d[ai][-1][o] += 1
elif ai.is_Not:
d[ai.args[0]][3] += 1
else:
raise NotImplementedError('unexpected level of nesting')
inv = defaultdict(list)
for k, v in ordered(iter(d.items())):
v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()]))
inv[tuple(v)].append(k)
return inv
def bool_map(bool1, bool2):
"""
Return the simplified version of *bool1*, and the mapping of variables
that makes the two expressions *bool1* and *bool2* represent the same
logical behaviour for some correspondence between the variables
of each.
If more than one mappings of this sort exist, one of them
is returned.
For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for
the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``.
If no such mapping exists, return ``False``.
Examples
========
>>> from sympy import SOPform, bool_map, Or, And, Not, Xor
>>> from sympy.abc import w, x, y, z, a, b, c, d
>>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]])
>>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]])
>>> bool_map(function1, function2)
(y & ~z, {y: a, z: b})
The results are not necessarily unique, but they are canonical. Here,
``(w, z)`` could be ``(a, d)`` or ``(d, a)``:
>>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y))
>>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c))
>>> bool_map(eq, eq2)
((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d})
>>> eq = And(Xor(a, b), c, And(c,d))
>>> bool_map(eq, eq.subs(c, x))
(c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x})
"""
def match(function1, function2):
"""Return the mapping that equates variables between two
simplified boolean expressions if possible.
By "simplified" we mean that a function has been denested
and is either an And (or an Or) whose arguments are either
symbols (x), negated symbols (Not(x)), or Or (or an And) whose
arguments are only symbols or negated symbols. For example,
``And(x, Not(y), Or(w, Not(z)))``.
Basic.match is not robust enough (see issue 4835) so this is
a workaround that is valid for simplified boolean expressions
"""
# do some quick checks
if function1.__class__ != function2.__class__:
return None # maybe simplification makes them the same?
if len(function1.args) != len(function2.args):
return None # maybe simplification makes them the same?
if function1.is_Symbol:
return {function1: function2}
# get the fingerprint dictionaries
f1 = _finger(function1)
f2 = _finger(function2)
# more quick checks
if len(f1) != len(f2):
return False
# assemble the match dictionary if possible
matchdict = {}
for k in f1.keys():
if k not in f2:
return False
if len(f1[k]) != len(f2[k]):
return False
for i, x in enumerate(f1[k]):
matchdict[x] = f2[k][i]
return matchdict
a = simplify_logic(bool1)
b = simplify_logic(bool2)
m = match(a, b)
if m:
return a, m
return m
def _apply_patternbased_simplification(rv, patterns, measure,
dominatingvalue,
replacementvalue=None,
threeterm_patterns=None):
"""
Replace patterns of Relational
Parameters
==========
rv : Expr
Boolean expression
patterns : tuple
Tuple of tuples, with (pattern to simplify, simplified pattern) with
two terms.
measure : function
Simplification measure.
dominatingvalue : Boolean or ``None``
The dominating value for the function of consideration.
For example, for :py:class:`~.And` ``S.false`` is dominating.
As soon as one expression is ``S.false`` in :py:class:`~.And`,
the whole expression is ``S.false``.
replacementvalue : Boolean or ``None``, optional
The resulting value for the whole expression if one argument
evaluates to ``dominatingvalue``.
For example, for :py:class:`~.Nand` ``S.false`` is dominating, but
in this case the resulting value is ``S.true``. Default is ``None``.
If ``replacementvalue`` is ``None`` and ``dominatingvalue`` is not
``None``, ``replacementvalue = dominatingvalue``.
threeterm_patterns : tuple, optional
Tuple of tuples, with (pattern to simplify, simplified pattern) with
three terms.
"""
from sympy.core.relational import Relational, _canonical
if replacementvalue is None and dominatingvalue is not None:
replacementvalue = dominatingvalue
# Use replacement patterns for Relationals
Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
binary=True)
if len(Rel) <= 1:
return rv
Rel, nonRealRel = sift(Rel, lambda i: not any(s.is_real is False
for s in i.free_symbols),
binary=True)
Rel = [i.canonical for i in Rel]
if threeterm_patterns and len(Rel) >= 3:
Rel = _apply_patternbased_threeterm_simplification(Rel,
threeterm_patterns, rv.func, dominatingvalue,
replacementvalue, measure)
Rel = _apply_patternbased_twoterm_simplification(Rel, patterns,
rv.func, dominatingvalue, replacementvalue, measure)
rv = rv.func(*([_canonical(i) for i in ordered(Rel)]
+ nonRel + nonRealRel))
return rv
def _apply_patternbased_twoterm_simplification(Rel, patterns, func,
dominatingvalue,
replacementvalue,
measure):
""" Apply pattern-based two-term simplification."""
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core.relational import Ge, Gt, _Inequality
changed = True
while changed and len(Rel) >= 2:
changed = False
# Use only < or <=
Rel = [r.reversed if isinstance(r, (Ge, Gt)) else r for r in Rel]
# Sort based on ordered
Rel = list(ordered(Rel))
# Eq and Ne must be tested reversed as well
rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel]
# Create a list of possible replacements
results = []
# Try all combinations of possibly reversed relational
for ((i, pi), (j, pj)) in combinations(enumerate(rtmp), 2):
for pattern, simp in patterns:
res = []
for p1, p2 in product(pi, pj):
# use SymPy matching
oldexpr = Tuple(p1, p2)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
if res:
for tmpres, oldexpr in res:
# we have a matching, compute replacement
np = simp.xreplace(tmpres)
if np == dominatingvalue:
# if dominatingvalue, the whole expression
# will be replacementvalue
return [replacementvalue]
# add replacement
if not isinstance(np, ITE) and not np.has(Min, Max):
# We only want to use ITE and Min/Max replacements if
# they simplify to a relational
costsaving = measure(func(*oldexpr.args)) - measure(np)
if costsaving > 0:
results.append((costsaving, ([i, j], np)))
if results:
# Sort results based on complexity
results = list(reversed(sorted(results,
key=lambda pair: pair[0])))
# Replace the one providing most simplification
replacement = results[0][1]
idx, newrel = replacement
idx.sort()
# Remove the old relationals
for index in reversed(idx):
del Rel[index]
if dominatingvalue is None or newrel != Not(dominatingvalue):
# Insert the new one (no need to insert a value that will
# not affect the result)
if newrel.func == func:
for a in newrel.args:
Rel.append(a)
else:
Rel.append(newrel)
# We did change something so try again
changed = True
return Rel
def _apply_patternbased_threeterm_simplification(Rel, patterns, func,
dominatingvalue,
replacementvalue,
measure):
""" Apply pattern-based three-term simplification."""
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core.relational import Le, Lt, _Inequality
changed = True
while changed and len(Rel) >= 3:
changed = False
# Use only > or >=
Rel = [r.reversed if isinstance(r, (Le, Lt)) else r for r in Rel]
# Sort based on ordered
Rel = list(ordered(Rel))
# Create a list of possible replacements
results = []
# Eq and Ne must be tested reversed as well
rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel]
# Try all combinations of possibly reversed relational
for ((i, pi), (j, pj), (k, pk)) in permutations(enumerate(rtmp), 3):
for pattern, simp in patterns:
res = []
for p1, p2, p3 in product(pi, pj, pk):
# use SymPy matching
oldexpr = Tuple(p1, p2, p3)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
if res:
for tmpres, oldexpr in res:
# we have a matching, compute replacement
np = simp.xreplace(tmpres)
if np == dominatingvalue:
# if dominatingvalue, the whole expression
# will be replacementvalue
return [replacementvalue]
# add replacement
if not isinstance(np, ITE) and not np.has(Min, Max):
# We only want to use ITE and Min/Max replacements if
# they simplify to a relational
costsaving = measure(func(*oldexpr.args)) - measure(np)
if costsaving > 0:
results.append((costsaving, ([i, j, k], np)))
if results:
# Sort results based on complexity
results = list(reversed(sorted(results,
key=lambda pair: pair[0])))
# Replace the one providing most simplification
replacement = results[0][1]
idx, newrel = replacement
idx.sort()
# Remove the old relationals
for index in reversed(idx):
del Rel[index]
if dominatingvalue is None or newrel != Not(dominatingvalue):
# Insert the new one (no need to insert a value that will
# not affect the result)
if newrel.func == func:
for a in newrel.args:
Rel.append(a)
else:
Rel.append(newrel)
# We did change something so try again
changed = True
return Rel
@cacheit
def _simplify_patterns_and():
""" Two-term patterns for And."""
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.miscellaneous import Min, Max
a = Wild('a')
b = Wild('b')
c = Wild('c')
# Relationals patterns should be in alphabetical order
# (pattern1, pattern2, simplified)
# Do not use Ge, Gt
_matchers_and = ((Tuple(Eq(a, b), Lt(a, b)), false),
#(Tuple(Eq(a, b), Lt(b, a)), S.false),
#(Tuple(Le(b, a), Lt(a, b)), S.false),
#(Tuple(Lt(b, a), Le(a, b)), S.false),
(Tuple(Lt(b, a), Lt(a, b)), false),
(Tuple(Eq(a, b), Le(b, a)), Eq(a, b)),
#(Tuple(Eq(a, b), Le(a, b)), Eq(a, b)),
#(Tuple(Le(b, a), Lt(b, a)), Gt(a, b)),
(Tuple(Le(b, a), Le(a, b)), Eq(a, b)),
#(Tuple(Le(b, a), Ne(a, b)), Gt(a, b)),
#(Tuple(Lt(b, a), Ne(a, b)), Gt(a, b)),
(Tuple(Le(a, b), Lt(a, b)), Lt(a, b)),
(Tuple(Le(a, b), Ne(a, b)), Lt(a, b)),
(Tuple(Lt(a, b), Ne(a, b)), Lt(a, b)),
# Sign
(Tuple(Eq(a, b), Eq(a, -b)), And(Eq(a, S.Zero), Eq(b, S.Zero))),
# Min/Max/ITE
(Tuple(Le(b, a), Le(c, a)), Ge(a, Max(b, c))),
(Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Ge(a, b), Gt(a, c))),
(Tuple(Lt(b, a), Lt(c, a)), Gt(a, Max(b, c))),
(Tuple(Le(a, b), Le(a, c)), Le(a, Min(b, c))),
(Tuple(Le(a, b), Lt(a, c)), ITE(b < c, Le(a, b), Lt(a, c))),
(Tuple(Lt(a, b), Lt(a, c)), Lt(a, Min(b, c))),
(Tuple(Le(a, b), Le(c, a)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))),
(Tuple(Le(c, a), Le(a, b)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))),
(Tuple(Lt(a, b), Lt(c, a)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))),
(Tuple(Lt(c, a), Lt(a, b)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))),
(Tuple(Le(a, b), Lt(c, a)), ITE(b <= c, false, And(Le(a, b), Gt(a, c)))),
(Tuple(Le(c, a), Lt(a, b)), ITE(b <= c, false, And(Lt(a, b), Ge(a, c)))),
(Tuple(Eq(a, b), Eq(a, c)), ITE(Eq(b, c), Eq(a, b), false)),
(Tuple(Lt(a, b), Lt(-b, a)), ITE(b > 0, Lt(Abs(a), b), false)),
(Tuple(Le(a, b), Le(-b, a)), ITE(b >= 0, Le(Abs(a), b), false)),
)
return _matchers_and
@cacheit
def _simplify_patterns_and3():
""" Three-term patterns for And."""
from sympy.core import Wild
from sympy.core.relational import Eq, Ge, Gt
a = Wild('a')
b = Wild('b')
c = Wild('c')
# Relationals patterns should be in alphabetical order
# (pattern1, pattern2, pattern3, simplified)
# Do not use Le, Lt
_matchers_and = ((Tuple(Ge(a, b), Ge(b, c), Gt(c, a)), false),
(Tuple(Ge(a, b), Gt(b, c), Gt(c, a)), false),
(Tuple(Gt(a, b), Gt(b, c), Gt(c, a)), false),
# (Tuple(Ge(c, a), Gt(a, b), Gt(b, c)), S.false),
# Lower bound relations
# Commented out combinations that does not simplify
(Tuple(Ge(a, b), Ge(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))),
(Tuple(Ge(a, b), Ge(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))),
# (Tuple(Ge(a, b), Gt(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))),
(Tuple(Ge(a, b), Gt(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))),
# (Tuple(Gt(a, b), Ge(a, c), Ge(b, c)), And(Gt(a, b), Ge(b, c))),
(Tuple(Ge(a, c), Gt(a, b), Gt(b, c)), And(Gt(a, b), Gt(b, c))),
(Tuple(Ge(b, c), Gt(a, b), Gt(a, c)), And(Gt(a, b), Ge(b, c))),
(Tuple(Gt(a, b), Gt(a, c), Gt(b, c)), And(Gt(a, b), Gt(b, c))),
# Upper bound relations
# Commented out combinations that does not simplify
(Tuple(Ge(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))),
(Tuple(Ge(b, a), Ge(c, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))),
# (Tuple(Ge(b, a), Gt(c, a), Ge(b, c)), And(Gt(c, a), Ge(b, c))),
(Tuple(Ge(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))),
# (Tuple(Gt(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))),
(Tuple(Ge(c, a), Gt(b, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))),
(Tuple(Ge(b, c), Gt(b, a), Gt(c, a)), And(Gt(c, a), Ge(b, c))),
(Tuple(Gt(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))),
# Circular relation
(Tuple(Ge(a, b), Ge(b, c), Ge(c, a)), And(Eq(a, b), Eq(b, c))),
)
return _matchers_and
@cacheit
def _simplify_patterns_or():
""" Two-term patterns for Or."""
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.miscellaneous import Min, Max
a = Wild('a')
b = Wild('b')
c = Wild('c')
# Relationals patterns should be in alphabetical order
# (pattern1, pattern2, simplified)
# Do not use Ge, Gt
_matchers_or = ((Tuple(Le(b, a), Le(a, b)), true),
#(Tuple(Le(b, a), Lt(a, b)), true),
(Tuple(Le(b, a), Ne(a, b)), true),
#(Tuple(Le(a, b), Lt(b, a)), true),
#(Tuple(Le(a, b), Ne(a, b)), true),
#(Tuple(Eq(a, b), Le(b, a)), Ge(a, b)),
#(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)),
(Tuple(Eq(a, b), Le(a, b)), Le(a, b)),
(Tuple(Eq(a, b), Lt(a, b)), Le(a, b)),
#(Tuple(Le(b, a), Lt(b, a)), Ge(a, b)),
(Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)),
(Tuple(Lt(b, a), Ne(a, b)), Ne(a, b)),
(Tuple(Le(a, b), Lt(a, b)), Le(a, b)),
#(Tuple(Lt(a, b), Ne(a, b)), Ne(a, b)),
(Tuple(Eq(a, b), Ne(a, c)), ITE(Eq(b, c), true, Ne(a, c))),
(Tuple(Ne(a, b), Ne(a, c)), ITE(Eq(b, c), Ne(a, b), true)),
# Min/Max/ITE
(Tuple(Le(b, a), Le(c, a)), Ge(a, Min(b, c))),
#(Tuple(Ge(b, a), Ge(c, a)), Ge(Min(b, c), a)),
(Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Lt(c, a), Le(b, a))),
(Tuple(Lt(b, a), Lt(c, a)), Gt(a, Min(b, c))),
#(Tuple(Gt(b, a), Gt(c, a)), Gt(Min(b, c), a)),
(Tuple(Le(a, b), Le(a, c)), Le(a, Max(b, c))),
#(Tuple(Le(b, a), Le(c, a)), Le(Max(b, c), a)),
(Tuple(Le(a, b), Lt(a, c)), ITE(b >= c, Le(a, b), Lt(a, c))),
(Tuple(Lt(a, b), Lt(a, c)), Lt(a, Max(b, c))),
#(Tuple(Lt(b, a), Lt(c, a)), Lt(Max(b, c), a)),
(Tuple(Le(a, b), Le(c, a)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))),
(Tuple(Le(c, a), Le(a, b)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))),
(Tuple(Lt(a, b), Lt(c, a)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))),
(Tuple(Lt(c, a), Lt(a, b)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))),
(Tuple(Le(a, b), Lt(c, a)), ITE(b >= c, true, Or(Le(a, b), Gt(a, c)))),
(Tuple(Le(c, a), Lt(a, b)), ITE(b >= c, true, Or(Lt(a, b), Ge(a, c)))),
(Tuple(Lt(b, a), Lt(a, -b)), ITE(b >= 0, Gt(Abs(a), b), true)),
(Tuple(Le(b, a), Le(a, -b)), ITE(b > 0, Ge(Abs(a), b), true)),
)
return _matchers_or
@cacheit
def _simplify_patterns_xor():
""" Two-term patterns for Xor."""
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
a = Wild('a')
b = Wild('b')
c = Wild('c')
# Relationals patterns should be in alphabetical order
# (pattern1, pattern2, simplified)
# Do not use Ge, Gt
_matchers_xor = (#(Tuple(Le(b, a), Lt(a, b)), true),
#(Tuple(Lt(b, a), Le(a, b)), true),
#(Tuple(Eq(a, b), Le(b, a)), Gt(a, b)),
#(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)),
(Tuple(Eq(a, b), Le(a, b)), Lt(a, b)),
(Tuple(Eq(a, b), Lt(a, b)), Le(a, b)),
(Tuple(Le(a, b), Lt(a, b)), Eq(a, b)),
(Tuple(Le(a, b), Le(b, a)), Ne(a, b)),
(Tuple(Le(b, a), Ne(a, b)), Le(a, b)),
# (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)),
(Tuple(Lt(b, a), Ne(a, b)), Lt(a, b)),
# (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)),
# (Tuple(Le(a, b), Ne(a, b)), Ge(a, b)),
# (Tuple(Lt(a, b), Ne(a, b)), Gt(a, b)),
# Min/Max/ITE
(Tuple(Le(b, a), Le(c, a)),
And(Ge(a, Min(b, c)), Lt(a, Max(b, c)))),
(Tuple(Le(b, a), Lt(c, a)),
ITE(b > c, And(Gt(a, c), Lt(a, b)),
And(Ge(a, b), Le(a, c)))),
(Tuple(Lt(b, a), Lt(c, a)),
And(Gt(a, Min(b, c)), Le(a, Max(b, c)))),
(Tuple(Le(a, b), Le(a, c)),
And(Le(a, Max(b, c)), Gt(a, Min(b, c)))),
(Tuple(Le(a, b), Lt(a, c)),
ITE(b < c, And(Lt(a, c), Gt(a, b)),
And(Le(a, b), Ge(a, c)))),
(Tuple(Lt(a, b), Lt(a, c)),
And(Lt(a, Max(b, c)), Ge(a, Min(b, c)))),
)
return _matchers_xor
def simplify_univariate(expr):
"""return a simplified version of univariate boolean expression, else ``expr``"""
from sympy.functions.elementary.piecewise import Piecewise
from sympy.core.relational import Eq, Ne
if not isinstance(expr, BooleanFunction):
return expr
if expr.atoms(Eq, Ne):
return expr
c = expr
free = c.free_symbols
if len(free) != 1:
return c
x = free.pop()
ok, i = Piecewise((0, c), evaluate=False
)._intervals(x, err_on_Eq=True)
if not ok:
return c
if not i:
return false
args = []
for a, b, _, _ in i:
if a is S.NegativeInfinity:
if b is S.Infinity:
c = true
else:
if c.subs(x, b) == True:
c = (x <= b)
else:
c = (x < b)
else:
incl_a = (c.subs(x, a) == True)
incl_b = (c.subs(x, b) == True)
if incl_a and incl_b:
if b.is_infinite:
c = (x >= a)
else:
c = And(a <= x, x <= b)
elif incl_a:
c = And(a <= x, x < b)
elif incl_b:
if b.is_infinite:
c = (x > a)
else:
c = And(a < x, x <= b)
else:
c = And(a < x, x < b)
args.append(c)
return Or(*args)
# Classes corresponding to logic gates
# Used in gateinputcount method
BooleanGates = (And, Or, Xor, Nand, Nor, Not, Xnor, ITE)
def gateinputcount(expr):
"""
Return the total number of inputs for the logic gates realizing the
Boolean expression.
Returns
=======
int
Number of gate inputs
Note
====
Not all Boolean functions count as gate here, only those that are
considered to be standard gates. These are: :py:class:`~.And`,
:py:class:`~.Or`, :py:class:`~.Xor`, :py:class:`~.Not`, and
:py:class:`~.ITE` (multiplexer). :py:class:`~.Nand`, :py:class:`~.Nor`,
and :py:class:`~.Xnor` will be evaluated to ``Not(And())`` etc.
Examples
========
>>> from sympy.logic import And, Or, Nand, Not, gateinputcount
>>> from sympy.abc import x, y, z
>>> expr = And(x, y)
>>> gateinputcount(expr)
2
>>> gateinputcount(Or(expr, z))
4
Note that ``Nand`` is automatically evaluated to ``Not(And())`` so
>>> gateinputcount(Nand(x, y, z))
4
>>> gateinputcount(Not(And(x, y, z)))
4
Although this can be avoided by using ``evaluate=False``
>>> gateinputcount(Nand(x, y, z, evaluate=False))
3
Also note that a comparison will count as a Boolean variable:
>>> gateinputcount(And(x > z, y >= 2))
2
As will a symbol:
>>> gateinputcount(x)
0
"""
if not isinstance(expr, Boolean):
raise TypeError("Expression must be Boolean")
if isinstance(expr, BooleanGates):
return len(expr.args) + sum(gateinputcount(x) for x in expr.args)
return 0
|
71a61cfb194422b5fd23f03e28f41dc29e680e9ad52526df70e68a83fa949ec3 | from sympy.concrete.products import (Product, product)
from sympy.concrete.summations import Sum
from sympy.core.function import (Derivative, Function, diff)
from sympy.core.numbers import (Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.combinatorial.factorials import (rf, factorial)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.simplify.combsimp import combsimp
from sympy.simplify.simplify import simplify
from sympy.testing.pytest import raises
a, k, n, m, x = symbols('a,k,n,m,x', integer=True)
f = Function('f')
def test_karr_convention():
# Test the Karr product convention that we want to hold.
# See his paper "Summation in Finite Terms" for a detailed
# reasoning why we really want exactly this definition.
# The convention is described for sums on page 309 and
# essentially in section 1.4, definition 3. For products
# we can find in analogy:
#
# \prod_{m <= i < n} f(i) 'has the obvious meaning' for m < n
# \prod_{m <= i < n} f(i) = 0 for m = n
# \prod_{m <= i < n} f(i) = 1 / \prod_{n <= i < m} f(i) for m > n
#
# It is important to note that he defines all products with
# the upper limit being *exclusive*.
# In contrast, SymPy and the usual mathematical notation has:
#
# prod_{i = a}^b f(i) = f(a) * f(a+1) * ... * f(b-1) * f(b)
#
# with the upper limit *inclusive*. So translating between
# the two we find that:
#
# \prod_{m <= i < n} f(i) = \prod_{i = m}^{n-1} f(i)
#
# where we intentionally used two different ways to typeset the
# products and its limits.
i = Symbol("i", integer=True)
k = Symbol("k", integer=True)
j = Symbol("j", integer=True, positive=True)
# A simple example with a concrete factors and symbolic limits.
# The normal product: m = k and n = k + j and therefore m < n:
m = k
n = k + j
a = m
b = n - 1
S1 = Product(i**2, (i, a, b)).doit()
# The reversed product: m = k + j and n = k and therefore m > n:
m = k + j
n = k
a = m
b = n - 1
S2 = Product(i**2, (i, a, b)).doit()
assert S1 * S2 == 1
# Test the empty product: m = k and n = k and therefore m = n:
m = k
n = k
a = m
b = n - 1
Sz = Product(i**2, (i, a, b)).doit()
assert Sz == 1
# Another example this time with an unspecified factor and
# numeric limits. (We can not do both tests in the same example.)
f = Function("f")
# The normal product with m < n:
m = 2
n = 11
a = m
b = n - 1
S1 = Product(f(i), (i, a, b)).doit()
# The reversed product with m > n:
m = 11
n = 2
a = m
b = n - 1
S2 = Product(f(i), (i, a, b)).doit()
assert simplify(S1 * S2) == 1
# Test the empty product with m = n:
m = 5
n = 5
a = m
b = n - 1
Sz = Product(f(i), (i, a, b)).doit()
assert Sz == 1
def test_karr_proposition_2a():
# Test Karr, page 309, proposition 2, part a
i, u, v = symbols('i u v', integer=True)
def test_the_product(m, n):
# g
g = i**3 + 2*i**2 - 3*i
# f = Delta g
f = simplify(g.subs(i, i+1) / g)
# The product
a = m
b = n - 1
P = Product(f, (i, a, b)).doit()
# Test if Product_{m <= i < n} f(i) = g(n) / g(m)
assert combsimp(P / (g.subs(i, n) / g.subs(i, m))) == 1
# m < n
test_the_product(u, u + v)
# m = n
test_the_product(u, u)
# m > n
test_the_product(u + v, u)
def test_karr_proposition_2b():
# Test Karr, page 309, proposition 2, part b
i, u, v, w = symbols('i u v w', integer=True)
def test_the_product(l, n, m):
# Productmand
s = i**3
# First product
a = l
b = n - 1
S1 = Product(s, (i, a, b)).doit()
# Second product
a = l
b = m - 1
S2 = Product(s, (i, a, b)).doit()
# Third product
a = m
b = n - 1
S3 = Product(s, (i, a, b)).doit()
# Test if S1 = S2 * S3 as required
assert combsimp(S1 / (S2 * S3)) == 1
# l < m < n
test_the_product(u, u + v, u + v + w)
# l < m = n
test_the_product(u, u + v, u + v)
# l < m > n
test_the_product(u, u + v + w, v)
# l = m < n
test_the_product(u, u, u + v)
# l = m = n
test_the_product(u, u, u)
# l = m > n
test_the_product(u + v, u + v, u)
# l > m < n
test_the_product(u + v, u, u + w)
# l > m = n
test_the_product(u + v, u, u)
# l > m > n
test_the_product(u + v + w, u + v, u)
def test_simple_products():
assert product(2, (k, a, n)) == 2**(n - a + 1)
assert product(k, (k, 1, n)) == factorial(n)
assert product(k**3, (k, 1, n)) == factorial(n)**3
assert product(k + 1, (k, 0, n - 1)) == factorial(n)
assert product(k + 1, (k, a, n - 1)) == rf(1 + a, n - a)
assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5)
assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5)
assert product(cos(k), (k, 1, Rational(5, 2))) != cos(1)*cos(2)
assert isinstance(product(k**k, (k, 1, n)), Product)
assert Product(x**k, (k, 1, n)).variables == [k]
raises(ValueError, lambda: Product(n))
raises(ValueError, lambda: Product(n, k))
raises(ValueError, lambda: Product(n, k, 1))
raises(ValueError, lambda: Product(n, k, 1, 10))
raises(ValueError, lambda: Product(n, (k, 1)))
assert product(1, (n, 1, oo)) == 1 # issue 8301
assert product(2, (n, 1, oo)) is oo
assert product(-1, (n, 1, oo)).func is Product
def test_multiple_products():
assert product(x, (n, 1, k), (k, 1, m)) == x**(m**2/2 + m/2)
assert product(f(n), (
n, 1, m), (m, 1, k)) == Product(f(n), (n, 1, m), (m, 1, k)).doit()
assert Product(f(n), (m, 1, k), (n, 1, k)).doit() == \
Product(Product(f(n), (m, 1, k)), (n, 1, k)).doit() == \
product(f(n), (m, 1, k), (n, 1, k)) == \
product(product(f(n), (m, 1, k)), (n, 1, k)) == \
Product(f(n)**k, (n, 1, k))
assert Product(
x, (x, 1, k), (k, 1, n)).doit() == Product(factorial(k), (k, 1, n))
assert Product(x**k, (n, 1, k), (k, 1, m)).variables == [n, k]
def test_rational_products():
assert product(1 + 1/k, (k, 1, n)) == rf(2, n)/factorial(n)
def test_special_products():
# Wallis product
assert product((4*k)**2 / (4*k**2 - 1), (k, 1, n)) == \
4**n*factorial(n)**2/rf(S.Half, n)/rf(Rational(3, 2), n)
# Euler's product formula for sin
assert product(1 + a/k**2, (k, 1, n)) == \
rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2
def test__eval_product():
from sympy.abc import i, n
# issue 4809
a = Function('a')
assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n))
# issue 4810
assert product(2**i, (i, 1, n)) == 2**(n*(n + 1)/2)
k, m = symbols('k m', integer=True)
assert product(2**i, (i, k, m)) == 2**(-k**2/2 + k/2 + m**2/2 + m/2)
n = Symbol('n', negative=True, integer=True)
p = Symbol('p', positive=True, integer=True)
assert product(2**i, (i, n, p)) == 2**(-n**2/2 + n/2 + p**2/2 + p/2)
assert product(2**i, (i, p, n)) == 2**(n**2/2 + n/2 - p**2/2 + p/2)
def test_product_pow():
# issue 4817
assert product(2**f(k), (k, 1, n)) == 2**Sum(f(k), (k, 1, n))
assert product(2**(2*f(k)), (k, 1, n)) == 2**Sum(2*f(k), (k, 1, n))
def test_infinite_product():
# issue 5737
assert isinstance(Product(2**(1/factorial(n)), (n, 0, oo)), Product)
def test_conjugate_transpose():
p = Product(x**k, (k, 1, 3))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
A, B = symbols("A B", commutative=False)
p = Product(A*B**k, (k, 1, 3))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
p = Product(B**k*A, (k, 1, 3))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
def test_simplify_prod():
y, t, b, c, v, d = symbols('y, t, b, c, v, d', integer = True)
_simplify = lambda e: simplify(e, doit=False)
assert _simplify(Product(x*y, (x, n, m), (y, a, k)) * \
Product(y, (x, n, m), (y, a, k))) == \
Product(x*y**2, (x, n, m), (y, a, k))
assert _simplify(3 * y* Product(x, (x, n, m)) * Product(x, (x, m + 1, a))) \
== 3 * y * Product(x, (x, n, a))
assert _simplify(Product(x, (x, k + 1, a)) * Product(x, (x, n, k))) == \
Product(x, (x, n, a))
assert _simplify(Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))) == \
Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))
assert _simplify(Product(x, (t, a, b)) * Product(y, (t, a, b)) * \
Product(x, (t, b+1, c))) == Product(x*y, (t, a, b)) * \
Product(x, (t, b+1, c))
assert _simplify(Product(x, (t, a, b)) * Product(x, (t, b+1, c)) * \
Product(y, (t, a, b))) == Product(x*y, (t, a, b)) * \
Product(x, (t, b+1, c))
assert _simplify(Product(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \
Product(2, (t, a, b))
assert _simplify(Product(sin(t)**2 + cos(t)**2 - 1, (t, a, b))) == \
Product(0, (t, a, b))
assert _simplify(Product(v*Product(sin(t)**2 + cos(t)**2, (t, a, b)),
(v, c, d))) == Product(v*Product(1, (t, a, b)), (v, c, d))
def test_change_index():
b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
assert Product(x, (x, a, b)).change_index(x, x + 1, y) == \
Product(y - 1, (y, a + 1, b + 1))
assert Product(x**2, (x, a, b)).change_index(x, x - 1) == \
Product((x + 1)**2, (x, a - 1, b - 1))
assert Product(x**2, (x, a, b)).change_index(x, -x, y) == \
Product((-y)**2, (y, -b, -a))
assert Product(x, (x, a, b)).change_index(x, -x - 1) == \
Product(-x - 1, (x, - b - 1, -a - 1))
assert Product(x*y, (x, a, b), (y, c, d)).change_index(x, x - 1, z) == \
Product((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
def test_reorder():
b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
assert Product(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
Product(x*y, (y, c, d), (x, a, b))
assert Product(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
Product(x, (x, c, d), (x, a, b))
assert Product(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
(2, 0), (0, 1)) == Product(x*y + z, (z, m, n), (y, c, d), (x, a, b))
assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
(0, 1), (1, 2), (0, 2)) == \
Product(x*y*z, (x, a, b), (z, m, n), (y, c, d))
assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
(x, y), (y, z), (x, z)) == \
Product(x*y*z, (x, a, b), (z, m, n), (y, c, d))
assert Product(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
Product(x*y, (y, c, d), (x, a, b))
assert Product(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
Product(x*y, (y, c, d), (x, a, b))
def test_Product_is_convergent():
assert Product(1/n**2, (n, 1, oo)).is_convergent() is S.false
assert Product(exp(1/n**2), (n, 1, oo)).is_convergent() is S.true
assert Product(1/n, (n, 1, oo)).is_convergent() is S.false
assert Product(1 + 1/n, (n, 1, oo)).is_convergent() is S.false
assert Product(1 + 1/n**2, (n, 1, oo)).is_convergent() is S.true
def test_reverse_order():
x, y, a, b, c, d= symbols('x, y, a, b, c, d', integer = True)
assert Product(x, (x, 0, 3)).reverse_order(0) == Product(1/x, (x, 4, -1))
assert Product(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
Product(x*y, (x, 6, 0), (y, 7, -1))
assert Product(x, (x, 1, 2)).reverse_order(0) == Product(1/x, (x, 3, 0))
assert Product(x, (x, 1, 3)).reverse_order(0) == Product(1/x, (x, 4, 0))
assert Product(x, (x, 1, a)).reverse_order(0) == Product(1/x, (x, a + 1, 0))
assert Product(x, (x, a, 5)).reverse_order(0) == Product(1/x, (x, 6, a - 1))
assert Product(x, (x, a + 1, a + 5)).reverse_order(0) == \
Product(1/x, (x, a + 6, a))
assert Product(x, (x, a + 1, a + 2)).reverse_order(0) == \
Product(1/x, (x, a + 3, a))
assert Product(x, (x, a + 1, a + 1)).reverse_order(0) == \
Product(1/x, (x, a + 2, a))
assert Product(x, (x, a, b)).reverse_order(0) == Product(1/x, (x, b + 1, a - 1))
assert Product(x, (x, a, b)).reverse_order(x) == Product(1/x, (x, b + 1, a - 1))
assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
Product(x*y, (x, b + 1, a - 1), (y, 6, 1))
assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
Product(x*y, (x, b + 1, a - 1), (y, 6, 1))
def test_issue_9983():
n = Symbol('n', integer=True, positive=True)
p = Product(1 + 1/n**Rational(2, 3), (n, 1, oo))
assert p.is_convergent() is S.false
assert product(1 + 1/n**Rational(2, 3), (n, 1, oo)) == p.doit()
def test_issue_13546():
n = Symbol('n')
k = Symbol('k')
p = Product(n + 1 / 2**k, (k, 0, n-1)).doit()
assert p.subs(n, 2).doit() == Rational(15, 2)
def test_issue_14036():
a, n = symbols('a n')
assert product(1 - a**2 / (n*pi)**2, [n, 1, oo]) != 0
def test_rewrite_Sum():
assert Product(1 - S.Half**2/k**2, (k, 1, oo)).rewrite(Sum) == \
exp(Sum(log(1 - 1/(4*k**2)), (k, 1, oo)))
def test_KroneckerDelta_Product():
y = Symbol('y')
assert Product(x*KroneckerDelta(x, y), (x, 0, 1)).doit() == 0
def test_issue_20848():
_i = Dummy('i')
t, y, z = symbols('t y z')
assert diff(Product(x, (y, 1, z)), x).as_dummy() == Sum(Product(x, (y, 1, _i - 1))*Product(x, (y, _i + 1, z)), (_i, 1, z)).as_dummy()
assert diff(Product(x, (y, 1, z)), x).doit() == x**(z - 1)*z
assert diff(Product(x, (y, x, z)), x) == Derivative(Product(x, (y, x, z)), x)
assert diff(Product(t, (x, 1, z)), x) == S(0)
assert Product(sin(n*x), (n, -1, 1)).diff(x).doit() == S(0)
|
b88ef18ccc7b26e55bde490dedc2d1ebfa46b0a4b8525ab6da9f99f68b62e497 | from sympy.concrete import Sum
from sympy.concrete.delta import deltaproduct as dp, deltasummation as ds, _extract_delta
from sympy.core import Eq, S, symbols, oo
from sympy.functions import KroneckerDelta as KD, Piecewise, piecewise_fold
from sympy.logic import And
from sympy.testing.pytest import raises
i, j, k, l, m = symbols("i j k l m", integer=True, finite=True)
x, y = symbols("x y", commutative=False)
def test_deltaproduct_trivial():
assert dp(x, (j, 1, 0)) == 1
assert dp(x, (j, 1, 3)) == x**3
assert dp(x + y, (j, 1, 3)) == (x + y)**3
assert dp(x*y, (j, 1, 3)) == (x*y)**3
assert dp(KD(i, j), (k, 1, 3)) == KD(i, j)
assert dp(x*KD(i, j), (k, 1, 3)) == x**3*KD(i, j)
assert dp(x*y*KD(i, j), (k, 1, 3)) == (x*y)**3*KD(i, j)
def test_deltaproduct_basic():
assert dp(KD(i, j), (j, 1, 3)) == 0
assert dp(KD(i, j), (j, 1, 1)) == KD(i, 1)
assert dp(KD(i, j), (j, 2, 2)) == KD(i, 2)
assert dp(KD(i, j), (j, 3, 3)) == KD(i, 3)
assert dp(KD(i, j), (j, 1, k)) == KD(i, 1)*KD(k, 1) + KD(k, 0)
assert dp(KD(i, j), (j, k, 3)) == KD(i, 3)*KD(k, 3) + KD(k, 4)
assert dp(KD(i, j), (j, k, l)) == KD(i, l)*KD(k, l) + KD(k, l + 1)
def test_deltaproduct_mul_x_kd():
assert dp(x*KD(i, j), (j, 1, 3)) == 0
assert dp(x*KD(i, j), (j, 1, 1)) == x*KD(i, 1)
assert dp(x*KD(i, j), (j, 2, 2)) == x*KD(i, 2)
assert dp(x*KD(i, j), (j, 3, 3)) == x*KD(i, 3)
assert dp(x*KD(i, j), (j, 1, k)) == x*KD(i, 1)*KD(k, 1) + KD(k, 0)
assert dp(x*KD(i, j), (j, k, 3)) == x*KD(i, 3)*KD(k, 3) + KD(k, 4)
assert dp(x*KD(i, j), (j, k, l)) == x*KD(i, l)*KD(k, l) + KD(k, l + 1)
def test_deltaproduct_mul_add_x_y_kd():
assert dp((x + y)*KD(i, j), (j, 1, 3)) == 0
assert dp((x + y)*KD(i, j), (j, 1, 1)) == (x + y)*KD(i, 1)
assert dp((x + y)*KD(i, j), (j, 2, 2)) == (x + y)*KD(i, 2)
assert dp((x + y)*KD(i, j), (j, 3, 3)) == (x + y)*KD(i, 3)
assert dp((x + y)*KD(i, j), (j, 1, k)) == \
(x + y)*KD(i, 1)*KD(k, 1) + KD(k, 0)
assert dp((x + y)*KD(i, j), (j, k, 3)) == \
(x + y)*KD(i, 3)*KD(k, 3) + KD(k, 4)
assert dp((x + y)*KD(i, j), (j, k, l)) == \
(x + y)*KD(i, l)*KD(k, l) + KD(k, l + 1)
def test_deltaproduct_add_kd_kd():
assert dp(KD(i, k) + KD(j, k), (k, 1, 3)) == 0
assert dp(KD(i, k) + KD(j, k), (k, 1, 1)) == KD(i, 1) + KD(j, 1)
assert dp(KD(i, k) + KD(j, k), (k, 2, 2)) == KD(i, 2) + KD(j, 2)
assert dp(KD(i, k) + KD(j, k), (k, 3, 3)) == KD(i, 3) + KD(j, 3)
assert dp(KD(i, k) + KD(j, k), (k, 1, l)) == KD(l, 0) + \
KD(i, 1)*KD(l, 1) + KD(j, 1)*KD(l, 1) + \
KD(i, 1)*KD(j, 2)*KD(l, 2) + KD(j, 1)*KD(i, 2)*KD(l, 2)
assert dp(KD(i, k) + KD(j, k), (k, l, 3)) == KD(l, 4) + \
KD(i, 3)*KD(l, 3) + KD(j, 3)*KD(l, 3) + \
KD(i, 2)*KD(j, 3)*KD(l, 2) + KD(i, 3)*KD(j, 2)*KD(l, 2)
assert dp(KD(i, k) + KD(j, k), (k, l, m)) == KD(l, m + 1) + \
KD(i, m)*KD(l, m) + KD(j, m)*KD(l, m) + \
KD(i, m)*KD(j, m - 1)*KD(l, m - 1) + KD(i, m - 1)*KD(j, m)*KD(l, m - 1)
def test_deltaproduct_mul_x_add_kd_kd():
assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, 3)) == 0
assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, 1)) == x*(KD(i, 1) + KD(j, 1))
assert dp(x*(KD(i, k) + KD(j, k)), (k, 2, 2)) == x*(KD(i, 2) + KD(j, 2))
assert dp(x*(KD(i, k) + KD(j, k)), (k, 3, 3)) == x*(KD(i, 3) + KD(j, 3))
assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, l)) == KD(l, 0) + \
x*KD(i, 1)*KD(l, 1) + x*KD(j, 1)*KD(l, 1) + \
x**2*KD(i, 1)*KD(j, 2)*KD(l, 2) + x**2*KD(j, 1)*KD(i, 2)*KD(l, 2)
assert dp(x*(KD(i, k) + KD(j, k)), (k, l, 3)) == KD(l, 4) + \
x*KD(i, 3)*KD(l, 3) + x*KD(j, 3)*KD(l, 3) + \
x**2*KD(i, 2)*KD(j, 3)*KD(l, 2) + x**2*KD(i, 3)*KD(j, 2)*KD(l, 2)
assert dp(x*(KD(i, k) + KD(j, k)), (k, l, m)) == KD(l, m + 1) + \
x*KD(i, m)*KD(l, m) + x*KD(j, m)*KD(l, m) + \
x**2*KD(i, m - 1)*KD(j, m)*KD(l, m - 1) + \
x**2*KD(i, m)*KD(j, m - 1)*KD(l, m - 1)
def test_deltaproduct_mul_add_x_y_add_kd_kd():
assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 3)) == 0
assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 1)) == \
(x + y)*(KD(i, 1) + KD(j, 1))
assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 2, 2)) == \
(x + y)*(KD(i, 2) + KD(j, 2))
assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 3, 3)) == \
(x + y)*(KD(i, 3) + KD(j, 3))
assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, l)) == KD(l, 0) + \
(x + y)*KD(i, 1)*KD(l, 1) + (x + y)*KD(j, 1)*KD(l, 1) + \
(x + y)**2*KD(i, 1)*KD(j, 2)*KD(l, 2) + \
(x + y)**2*KD(j, 1)*KD(i, 2)*KD(l, 2)
assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, l, 3)) == KD(l, 4) + \
(x + y)*KD(i, 3)*KD(l, 3) + (x + y)*KD(j, 3)*KD(l, 3) + \
(x + y)**2*KD(i, 2)*KD(j, 3)*KD(l, 2) + \
(x + y)**2*KD(i, 3)*KD(j, 2)*KD(l, 2)
assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, l, m)) == KD(l, m + 1) + \
(x + y)*KD(i, m)*KD(l, m) + (x + y)*KD(j, m)*KD(l, m) + \
(x + y)**2*KD(i, m - 1)*KD(j, m)*KD(l, m - 1) + \
(x + y)**2*KD(i, m)*KD(j, m - 1)*KD(l, m - 1)
def test_deltaproduct_add_mul_x_y_mul_x_kd():
assert dp(x*y + x*KD(i, j), (j, 1, 3)) == (x*y)**3 + \
x*(x*y)**2*KD(i, 1) + (x*y)*x*(x*y)*KD(i, 2) + (x*y)**2*x*KD(i, 3)
assert dp(x*y + x*KD(i, j), (j, 1, 1)) == x*y + x*KD(i, 1)
assert dp(x*y + x*KD(i, j), (j, 2, 2)) == x*y + x*KD(i, 2)
assert dp(x*y + x*KD(i, j), (j, 3, 3)) == x*y + x*KD(i, 3)
assert dp(x*y + x*KD(i, j), (j, 1, k)) == \
(x*y)**k + Piecewise(
((x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
(0, True)
)
assert dp(x*y + x*KD(i, j), (j, k, 3)) == \
(x*y)**(-k + 4) + Piecewise(
((x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
(0, True)
)
assert dp(x*y + x*KD(i, j), (j, k, l)) == \
(x*y)**(-k + l + 1) + Piecewise(
((x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
(0, True)
)
def test_deltaproduct_mul_x_add_y_kd():
assert dp(x*(y + KD(i, j)), (j, 1, 3)) == (x*y)**3 + \
x*(x*y)**2*KD(i, 1) + (x*y)*x*(x*y)*KD(i, 2) + (x*y)**2*x*KD(i, 3)
assert dp(x*(y + KD(i, j)), (j, 1, 1)) == x*(y + KD(i, 1))
assert dp(x*(y + KD(i, j)), (j, 2, 2)) == x*(y + KD(i, 2))
assert dp(x*(y + KD(i, j)), (j, 3, 3)) == x*(y + KD(i, 3))
assert dp(x*(y + KD(i, j)), (j, 1, k)) == \
(x*y)**k + Piecewise(
((x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
(0, True)
).expand()
assert dp(x*(y + KD(i, j)), (j, k, 3)) == \
((x*y)**(-k + 4) + Piecewise(
((x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
(0, True)
)).expand()
assert dp(x*(y + KD(i, j)), (j, k, l)) == \
((x*y)**(-k + l + 1) + Piecewise(
((x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
(0, True)
)).expand()
def test_deltaproduct_mul_x_add_y_twokd():
assert dp(x*(y + 2*KD(i, j)), (j, 1, 3)) == (x*y)**3 + \
2*x*(x*y)**2*KD(i, 1) + 2*x*y*x*x*y*KD(i, 2) + 2*(x*y)**2*x*KD(i, 3)
assert dp(x*(y + 2*KD(i, j)), (j, 1, 1)) == x*(y + 2*KD(i, 1))
assert dp(x*(y + 2*KD(i, j)), (j, 2, 2)) == x*(y + 2*KD(i, 2))
assert dp(x*(y + 2*KD(i, j)), (j, 3, 3)) == x*(y + 2*KD(i, 3))
assert dp(x*(y + 2*KD(i, j)), (j, 1, k)) == \
(x*y)**k + Piecewise(
(2*(x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
(0, True)
).expand()
assert dp(x*(y + 2*KD(i, j)), (j, k, 3)) == \
((x*y)**(-k + 4) + Piecewise(
(2*(x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
(0, True)
)).expand()
assert dp(x*(y + 2*KD(i, j)), (j, k, l)) == \
((x*y)**(-k + l + 1) + Piecewise(
(2*(x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
(0, True)
)).expand()
def test_deltaproduct_mul_add_x_y_add_y_kd():
assert dp((x + y)*(y + KD(i, j)), (j, 1, 3)) == ((x + y)*y)**3 + \
(x + y)*((x + y)*y)**2*KD(i, 1) + \
(x + y)*y*(x + y)**2*y*KD(i, 2) + \
((x + y)*y)**2*(x + y)*KD(i, 3)
assert dp((x + y)*(y + KD(i, j)), (j, 1, 1)) == (x + y)*(y + KD(i, 1))
assert dp((x + y)*(y + KD(i, j)), (j, 2, 2)) == (x + y)*(y + KD(i, 2))
assert dp((x + y)*(y + KD(i, j)), (j, 3, 3)) == (x + y)*(y + KD(i, 3))
assert dp((x + y)*(y + KD(i, j)), (j, 1, k)) == \
((x + y)*y)**k + Piecewise(
(((x + y)*y)**(-1)*((x + y)*y)**i*(x + y)*((x + y)*y
)**k*((x + y)*y)**(-i), (i >= 1) & (i <= k)), (0, True))
assert dp((x + y)*(y + KD(i, j)), (j, k, 3)) == (
(x + y)*y)**4*((x + y)*y)**(-k) + Piecewise((((x + y)*y)**i*(
(x + y)*y)**(-k)*(x + y)*((x + y)*y)**3*((x + y)*y)**(-i),
(i >= k) & (i <= 3)), (0, True))
assert dp((x + y)*(y + KD(i, j)), (j, k, l)) == \
(x + y)*y*((x + y)*y)**l*((x + y)*y)**(-k) + Piecewise(
(((x + y)*y)**i*((x + y)*y)**(-k)*(x + y)*((x + y)*y
)**l*((x + y)*y)**(-i), (i >= k) & (i <= l)), (0, True))
def test_deltaproduct_mul_add_x_kd_add_y_kd():
assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 3)) == \
KD(i, 1)*(KD(i, k) + x)*((KD(i, k) + x)*y)**2 + \
KD(i, 2)*(KD(i, k) + x)*y*(KD(i, k) + x)**2*y + \
KD(i, 3)*((KD(i, k) + x)*y)**2*(KD(i, k) + x) + \
((KD(i, k) + x)*y)**3
assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 1)) == \
(x + KD(i, k))*(y + KD(i, 1))
assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 2, 2)) == \
(x + KD(i, k))*(y + KD(i, 2))
assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 3, 3)) == \
(x + KD(i, k))*(y + KD(i, 3))
assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, k)) == \
((KD(i, k) + x)*y)**k + Piecewise(
(((KD(i, k) + x)*y)**(-1)*((KD(i, k) + x)*y)**i*(KD(i, k) + x
)*((KD(i, k) + x)*y)**k*((KD(i, k) + x)*y)**(-i), (i >= 1
) & (i <= k)), (0, True))
assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, 3)) == (
(KD(i, k) + x)*y)**4*((KD(i, k) + x)*y)**(-k) + Piecewise(
(((KD(i, k) + x)*y)**i*((KD(i, k) + x)*y)**(-k)*(KD(i, k)
+ x)*((KD(i, k) + x)*y)**3*((KD(i, k) + x)*y)**(-i),
(i >= k) & (i <= 3)), (0, True))
assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, l)) == (
KD(i, k) + x)*y*((KD(i, k) + x)*y)**l*((KD(i, k) + x)*y
)**(-k) + Piecewise((((KD(i, k) + x)*y)**i*((KD(i, k) + x
)*y)**(-k)*(KD(i, k) + x)*((KD(i, k) + x)*y)**l*((KD(i, k) + x
)*y)**(-i), (i >= k) & (i <= l)), (0, True))
def test_deltasummation_trivial():
assert ds(x, (j, 1, 0)) == 0
assert ds(x, (j, 1, 3)) == 3*x
assert ds(x + y, (j, 1, 3)) == 3*(x + y)
assert ds(x*y, (j, 1, 3)) == 3*x*y
assert ds(KD(i, j), (k, 1, 3)) == 3*KD(i, j)
assert ds(x*KD(i, j), (k, 1, 3)) == 3*x*KD(i, j)
assert ds(x*y*KD(i, j), (k, 1, 3)) == 3*x*y*KD(i, j)
def test_deltasummation_basic_numerical():
n = symbols('n', integer=True, nonzero=True)
assert ds(KD(n, 0), (n, 1, 3)) == 0
# return unevaluated, until it gets implemented
assert ds(KD(i**2, j**2), (j, -oo, oo)) == \
Sum(KD(i**2, j**2), (j, -oo, oo))
assert Piecewise((KD(i, k), And(1 <= i, i <= 3)), (0, True)) == \
ds(KD(i, j)*KD(j, k), (j, 1, 3)) == \
ds(KD(j, k)*KD(i, j), (j, 1, 3))
assert ds(KD(i, k), (k, -oo, oo)) == 1
assert ds(KD(i, k), (k, 0, oo)) == Piecewise((1, S.Zero <= i), (0, True))
assert ds(KD(i, k), (k, 1, 3)) == \
Piecewise((1, And(1 <= i, i <= 3)), (0, True))
assert ds(k*KD(i, j)*KD(j, k), (k, -oo, oo)) == j*KD(i, j)
assert ds(j*KD(i, j), (j, -oo, oo)) == i
assert ds(i*KD(i, j), (i, -oo, oo)) == j
assert ds(x, (i, 1, 3)) == 3*x
assert ds((i + j)*KD(i, j), (j, -oo, oo)) == 2*i
def test_deltasummation_basic_symbolic():
assert ds(KD(i, j), (j, 1, 3)) == \
Piecewise((1, And(1 <= i, i <= 3)), (0, True))
assert ds(KD(i, j), (j, 1, 1)) == Piecewise((1, Eq(i, 1)), (0, True))
assert ds(KD(i, j), (j, 2, 2)) == Piecewise((1, Eq(i, 2)), (0, True))
assert ds(KD(i, j), (j, 3, 3)) == Piecewise((1, Eq(i, 3)), (0, True))
assert ds(KD(i, j), (j, 1, k)) == \
Piecewise((1, And(1 <= i, i <= k)), (0, True))
assert ds(KD(i, j), (j, k, 3)) == \
Piecewise((1, And(k <= i, i <= 3)), (0, True))
assert ds(KD(i, j), (j, k, l)) == \
Piecewise((1, And(k <= i, i <= l)), (0, True))
def test_deltasummation_mul_x_kd():
assert ds(x*KD(i, j), (j, 1, 3)) == \
Piecewise((x, And(1 <= i, i <= 3)), (0, True))
assert ds(x*KD(i, j), (j, 1, 1)) == Piecewise((x, Eq(i, 1)), (0, True))
assert ds(x*KD(i, j), (j, 2, 2)) == Piecewise((x, Eq(i, 2)), (0, True))
assert ds(x*KD(i, j), (j, 3, 3)) == Piecewise((x, Eq(i, 3)), (0, True))
assert ds(x*KD(i, j), (j, 1, k)) == \
Piecewise((x, And(1 <= i, i <= k)), (0, True))
assert ds(x*KD(i, j), (j, k, 3)) == \
Piecewise((x, And(k <= i, i <= 3)), (0, True))
assert ds(x*KD(i, j), (j, k, l)) == \
Piecewise((x, And(k <= i, i <= l)), (0, True))
def test_deltasummation_mul_add_x_y_kd():
assert ds((x + y)*KD(i, j), (j, 1, 3)) == \
Piecewise((x + y, And(1 <= i, i <= 3)), (0, True))
assert ds((x + y)*KD(i, j), (j, 1, 1)) == \
Piecewise((x + y, Eq(i, 1)), (0, True))
assert ds((x + y)*KD(i, j), (j, 2, 2)) == \
Piecewise((x + y, Eq(i, 2)), (0, True))
assert ds((x + y)*KD(i, j), (j, 3, 3)) == \
Piecewise((x + y, Eq(i, 3)), (0, True))
assert ds((x + y)*KD(i, j), (j, 1, k)) == \
Piecewise((x + y, And(1 <= i, i <= k)), (0, True))
assert ds((x + y)*KD(i, j), (j, k, 3)) == \
Piecewise((x + y, And(k <= i, i <= 3)), (0, True))
assert ds((x + y)*KD(i, j), (j, k, l)) == \
Piecewise((x + y, And(k <= i, i <= l)), (0, True))
def test_deltasummation_add_kd_kd():
assert ds(KD(i, k) + KD(j, k), (k, 1, 3)) == piecewise_fold(
Piecewise((1, And(1 <= i, i <= 3)), (0, True)) +
Piecewise((1, And(1 <= j, j <= 3)), (0, True)))
assert ds(KD(i, k) + KD(j, k), (k, 1, 1)) == piecewise_fold(
Piecewise((1, Eq(i, 1)), (0, True)) +
Piecewise((1, Eq(j, 1)), (0, True)))
assert ds(KD(i, k) + KD(j, k), (k, 2, 2)) == piecewise_fold(
Piecewise((1, Eq(i, 2)), (0, True)) +
Piecewise((1, Eq(j, 2)), (0, True)))
assert ds(KD(i, k) + KD(j, k), (k, 3, 3)) == piecewise_fold(
Piecewise((1, Eq(i, 3)), (0, True)) +
Piecewise((1, Eq(j, 3)), (0, True)))
assert ds(KD(i, k) + KD(j, k), (k, 1, l)) == piecewise_fold(
Piecewise((1, And(1 <= i, i <= l)), (0, True)) +
Piecewise((1, And(1 <= j, j <= l)), (0, True)))
assert ds(KD(i, k) + KD(j, k), (k, l, 3)) == piecewise_fold(
Piecewise((1, And(l <= i, i <= 3)), (0, True)) +
Piecewise((1, And(l <= j, j <= 3)), (0, True)))
assert ds(KD(i, k) + KD(j, k), (k, l, m)) == piecewise_fold(
Piecewise((1, And(l <= i, i <= m)), (0, True)) +
Piecewise((1, And(l <= j, j <= m)), (0, True)))
def test_deltasummation_add_mul_x_kd_kd():
assert ds(x*KD(i, k) + KD(j, k), (k, 1, 3)) == piecewise_fold(
Piecewise((x, And(1 <= i, i <= 3)), (0, True)) +
Piecewise((1, And(1 <= j, j <= 3)), (0, True)))
assert ds(x*KD(i, k) + KD(j, k), (k, 1, 1)) == piecewise_fold(
Piecewise((x, Eq(i, 1)), (0, True)) +
Piecewise((1, Eq(j, 1)), (0, True)))
assert ds(x*KD(i, k) + KD(j, k), (k, 2, 2)) == piecewise_fold(
Piecewise((x, Eq(i, 2)), (0, True)) +
Piecewise((1, Eq(j, 2)), (0, True)))
assert ds(x*KD(i, k) + KD(j, k), (k, 3, 3)) == piecewise_fold(
Piecewise((x, Eq(i, 3)), (0, True)) +
Piecewise((1, Eq(j, 3)), (0, True)))
assert ds(x*KD(i, k) + KD(j, k), (k, 1, l)) == piecewise_fold(
Piecewise((x, And(1 <= i, i <= l)), (0, True)) +
Piecewise((1, And(1 <= j, j <= l)), (0, True)))
assert ds(x*KD(i, k) + KD(j, k), (k, l, 3)) == piecewise_fold(
Piecewise((x, And(l <= i, i <= 3)), (0, True)) +
Piecewise((1, And(l <= j, j <= 3)), (0, True)))
assert ds(x*KD(i, k) + KD(j, k), (k, l, m)) == piecewise_fold(
Piecewise((x, And(l <= i, i <= m)), (0, True)) +
Piecewise((1, And(l <= j, j <= m)), (0, True)))
def test_deltasummation_mul_x_add_kd_kd():
assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, 3)) == piecewise_fold(
Piecewise((x, And(1 <= i, i <= 3)), (0, True)) +
Piecewise((x, And(1 <= j, j <= 3)), (0, True)))
assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, 1)) == piecewise_fold(
Piecewise((x, Eq(i, 1)), (0, True)) +
Piecewise((x, Eq(j, 1)), (0, True)))
assert ds(x*(KD(i, k) + KD(j, k)), (k, 2, 2)) == piecewise_fold(
Piecewise((x, Eq(i, 2)), (0, True)) +
Piecewise((x, Eq(j, 2)), (0, True)))
assert ds(x*(KD(i, k) + KD(j, k)), (k, 3, 3)) == piecewise_fold(
Piecewise((x, Eq(i, 3)), (0, True)) +
Piecewise((x, Eq(j, 3)), (0, True)))
assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, l)) == piecewise_fold(
Piecewise((x, And(1 <= i, i <= l)), (0, True)) +
Piecewise((x, And(1 <= j, j <= l)), (0, True)))
assert ds(x*(KD(i, k) + KD(j, k)), (k, l, 3)) == piecewise_fold(
Piecewise((x, And(l <= i, i <= 3)), (0, True)) +
Piecewise((x, And(l <= j, j <= 3)), (0, True)))
assert ds(x*(KD(i, k) + KD(j, k)), (k, l, m)) == piecewise_fold(
Piecewise((x, And(l <= i, i <= m)), (0, True)) +
Piecewise((x, And(l <= j, j <= m)), (0, True)))
def test_deltasummation_mul_add_x_y_add_kd_kd():
assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 3)) == piecewise_fold(
Piecewise((x + y, And(1 <= i, i <= 3)), (0, True)) +
Piecewise((x + y, And(1 <= j, j <= 3)), (0, True)))
assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 1)) == piecewise_fold(
Piecewise((x + y, Eq(i, 1)), (0, True)) +
Piecewise((x + y, Eq(j, 1)), (0, True)))
assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 2, 2)) == piecewise_fold(
Piecewise((x + y, Eq(i, 2)), (0, True)) +
Piecewise((x + y, Eq(j, 2)), (0, True)))
assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 3, 3)) == piecewise_fold(
Piecewise((x + y, Eq(i, 3)), (0, True)) +
Piecewise((x + y, Eq(j, 3)), (0, True)))
assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, l)) == piecewise_fold(
Piecewise((x + y, And(1 <= i, i <= l)), (0, True)) +
Piecewise((x + y, And(1 <= j, j <= l)), (0, True)))
assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, l, 3)) == piecewise_fold(
Piecewise((x + y, And(l <= i, i <= 3)), (0, True)) +
Piecewise((x + y, And(l <= j, j <= 3)), (0, True)))
assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, l, m)) == piecewise_fold(
Piecewise((x + y, And(l <= i, i <= m)), (0, True)) +
Piecewise((x + y, And(l <= j, j <= m)), (0, True)))
def test_deltasummation_add_mul_x_y_mul_x_kd():
assert ds(x*y + x*KD(i, j), (j, 1, 3)) == \
Piecewise((3*x*y + x, And(1 <= i, i <= 3)), (3*x*y, True))
assert ds(x*y + x*KD(i, j), (j, 1, 1)) == \
Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
assert ds(x*y + x*KD(i, j), (j, 2, 2)) == \
Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
assert ds(x*y + x*KD(i, j), (j, 3, 3)) == \
Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
assert ds(x*y + x*KD(i, j), (j, 1, k)) == \
Piecewise((k*x*y + x, And(1 <= i, i <= k)), (k*x*y, True))
assert ds(x*y + x*KD(i, j), (j, k, 3)) == \
Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
assert ds(x*y + x*KD(i, j), (j, k, l)) == Piecewise(
((l - k + 1)*x*y + x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
def test_deltasummation_mul_x_add_y_kd():
assert ds(x*(y + KD(i, j)), (j, 1, 3)) == \
Piecewise((3*x*y + x, And(1 <= i, i <= 3)), (3*x*y, True))
assert ds(x*(y + KD(i, j)), (j, 1, 1)) == \
Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
assert ds(x*(y + KD(i, j)), (j, 2, 2)) == \
Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
assert ds(x*(y + KD(i, j)), (j, 3, 3)) == \
Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
assert ds(x*(y + KD(i, j)), (j, 1, k)) == \
Piecewise((k*x*y + x, And(1 <= i, i <= k)), (k*x*y, True))
assert ds(x*(y + KD(i, j)), (j, k, 3)) == \
Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
assert ds(x*(y + KD(i, j)), (j, k, l)) == Piecewise(
((l - k + 1)*x*y + x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
def test_deltasummation_mul_x_add_y_twokd():
assert ds(x*(y + 2*KD(i, j)), (j, 1, 3)) == \
Piecewise((3*x*y + 2*x, And(1 <= i, i <= 3)), (3*x*y, True))
assert ds(x*(y + 2*KD(i, j)), (j, 1, 1)) == \
Piecewise((x*y + 2*x, Eq(i, 1)), (x*y, True))
assert ds(x*(y + 2*KD(i, j)), (j, 2, 2)) == \
Piecewise((x*y + 2*x, Eq(i, 2)), (x*y, True))
assert ds(x*(y + 2*KD(i, j)), (j, 3, 3)) == \
Piecewise((x*y + 2*x, Eq(i, 3)), (x*y, True))
assert ds(x*(y + 2*KD(i, j)), (j, 1, k)) == \
Piecewise((k*x*y + 2*x, And(1 <= i, i <= k)), (k*x*y, True))
assert ds(x*(y + 2*KD(i, j)), (j, k, 3)) == Piecewise(
((4 - k)*x*y + 2*x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
assert ds(x*(y + 2*KD(i, j)), (j, k, l)) == Piecewise(
((l - k + 1)*x*y + 2*x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
def test_deltasummation_mul_add_x_y_add_y_kd():
assert ds((x + y)*(y + KD(i, j)), (j, 1, 3)) == Piecewise(
(3*(x + y)*y + x + y, And(1 <= i, i <= 3)), (3*(x + y)*y, True))
assert ds((x + y)*(y + KD(i, j)), (j, 1, 1)) == \
Piecewise(((x + y)*y + x + y, Eq(i, 1)), ((x + y)*y, True))
assert ds((x + y)*(y + KD(i, j)), (j, 2, 2)) == \
Piecewise(((x + y)*y + x + y, Eq(i, 2)), ((x + y)*y, True))
assert ds((x + y)*(y + KD(i, j)), (j, 3, 3)) == \
Piecewise(((x + y)*y + x + y, Eq(i, 3)), ((x + y)*y, True))
assert ds((x + y)*(y + KD(i, j)), (j, 1, k)) == Piecewise(
(k*(x + y)*y + x + y, And(1 <= i, i <= k)), (k*(x + y)*y, True))
assert ds((x + y)*(y + KD(i, j)), (j, k, 3)) == Piecewise(
((4 - k)*(x + y)*y + x + y, And(k <= i, i <= 3)),
((4 - k)*(x + y)*y, True))
assert ds((x + y)*(y + KD(i, j)), (j, k, l)) == Piecewise(
((l - k + 1)*(x + y)*y + x + y, And(k <= i, i <= l)),
((l - k + 1)*(x + y)*y, True))
def test_deltasummation_mul_add_x_kd_add_y_kd():
assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, 3)) == piecewise_fold(
Piecewise((KD(i, k) + x, And(1 <= i, i <= 3)), (0, True)) +
3*(KD(i, k) + x)*y)
assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, 1)) == piecewise_fold(
Piecewise((KD(i, k) + x, Eq(i, 1)), (0, True)) +
(KD(i, k) + x)*y)
assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 2, 2)) == piecewise_fold(
Piecewise((KD(i, k) + x, Eq(i, 2)), (0, True)) +
(KD(i, k) + x)*y)
assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 3, 3)) == piecewise_fold(
Piecewise((KD(i, k) + x, Eq(i, 3)), (0, True)) +
(KD(i, k) + x)*y)
assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, k)) == piecewise_fold(
Piecewise((KD(i, k) + x, And(1 <= i, i <= k)), (0, True)) +
k*(KD(i, k) + x)*y)
assert ds((x + KD(i, k))*(y + KD(i, j)), (j, k, 3)) == piecewise_fold(
Piecewise((KD(i, k) + x, And(k <= i, i <= 3)), (0, True)) +
(4 - k)*(KD(i, k) + x)*y)
assert ds((x + KD(i, k))*(y + KD(i, j)), (j, k, l)) == piecewise_fold(
Piecewise((KD(i, k) + x, And(k <= i, i <= l)), (0, True)) +
(l - k + 1)*(KD(i, k) + x)*y)
def test_extract_delta():
raises(ValueError, lambda: _extract_delta(KD(i, j) + KD(k, l), i))
|
6478997d81827824bd23ed28a8deac15b8986bedbce06785a06b0d6e1216ab82 | """Tests for Gosper's algorithm for hypergeometric summation. """
from sympy.core.numbers import (Rational, pi)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import (binomial, factorial)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.special.gamma_functions import gamma
from sympy.polys.polytools import Poly
from sympy.simplify.simplify import simplify
from sympy.concrete.gosper import gosper_normal, gosper_sum, gosper_term
from sympy.abc import a, b, j, k, m, n, r, x
def test_gosper_normal():
eq = 4*n + 5, 2*(4*n + 1)*(2*n + 3), n
assert gosper_normal(*eq) == \
(Poly(Rational(1, 4), n), Poly(n + Rational(3, 2)), Poly(n + Rational(1, 4)))
assert gosper_normal(*eq, polys=False) == \
(Rational(1, 4), n + Rational(3, 2), n + Rational(1, 4))
def test_gosper_term():
assert gosper_term((4*k + 1)*factorial(
k)/factorial(2*k + 1), k) == (-k - S.Half)/(k + Rational(1, 4))
def test_gosper_sum():
assert gosper_sum(1, (k, 0, n)) == 1 + n
assert gosper_sum(k, (k, 0, n)) == n*(1 + n)/2
assert gosper_sum(k**2, (k, 0, n)) == n*(1 + n)*(1 + 2*n)/6
assert gosper_sum(k**3, (k, 0, n)) == n**2*(1 + n)**2/4
assert gosper_sum(2**k, (k, 0, n)) == 2*2**n - 1
assert gosper_sum(factorial(k), (k, 0, n)) is None
assert gosper_sum(binomial(n, k), (k, 0, n)) is None
assert gosper_sum(factorial(k)/k**2, (k, 0, n)) is None
assert gosper_sum((k - 3)*factorial(k), (k, 0, n)) is None
assert gosper_sum(k*factorial(k), k) == factorial(k)
assert gosper_sum(
k*factorial(k), (k, 0, n)) == n*factorial(n) + factorial(n) - 1
assert gosper_sum((-1)**k*binomial(n, k), (k, 0, n)) == 0
assert gosper_sum((
-1)**k*binomial(n, k), (k, 0, m)) == -(-1)**m*(m - n)*binomial(n, m)/n
assert gosper_sum((4*k + 1)*factorial(k)/factorial(2*k + 1), (k, 0, n)) == \
(2*factorial(2*n + 1) - factorial(n))/factorial(2*n + 1)
# issue 6033:
assert gosper_sum(
n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)), \
(n, 0, m)).simplify() == -exp(m*log(a) + m*log(b))*gamma(a + 1) \
*gamma(b + 1)/(gamma(a)*gamma(b)*gamma(a + m + 1)*gamma(b + m + 1)) \
+ 1/(gamma(a)*gamma(b))
def test_gosper_sum_indefinite():
assert gosper_sum(k, k) == k*(k - 1)/2
assert gosper_sum(k**2, k) == k*(k - 1)*(2*k - 1)/6
assert gosper_sum(1/(k*(k + 1)), k) == -1/k
assert gosper_sum(-(27*k**4 + 158*k**3 + 430*k**2 + 678*k + 445)*gamma(2*k
+ 4)/(3*(3*k + 7)*gamma(3*k + 6)), k) == \
(3*k + 5)*(k**2 + 2*k + 5)*gamma(2*k + 4)/gamma(3*k + 6)
def test_gosper_sum_parametric():
assert gosper_sum(binomial(S.Half, m - j + 1)*binomial(S.Half, m + j), (j, 1, n)) == \
n*(1 + m - n)*(-1 + 2*m + 2*n)*binomial(S.Half, 1 + m - n)* \
binomial(S.Half, m + n)/(m*(1 + 2*m))
def test_gosper_sum_algebraic():
assert gosper_sum(
n**2 + sqrt(2), (n, 0, m)) == (m + 1)*(2*m**2 + m + 6*sqrt(2))/6
def test_gosper_sum_iterated():
f1 = binomial(2*k, k)/4**k
f2 = (1 + 2*n)*binomial(2*n, n)/4**n
f3 = (1 + 2*n)*(3 + 2*n)*binomial(2*n, n)/(3*4**n)
f4 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*binomial(2*n, n)/(15*4**n)
f5 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*binomial(2*n, n)/(105*4**n)
assert gosper_sum(f1, (k, 0, n)) == f2
assert gosper_sum(f2, (n, 0, n)) == f3
assert gosper_sum(f3, (n, 0, n)) == f4
assert gosper_sum(f4, (n, 0, n)) == f5
# the AeqB tests test expressions given in
# www.math.upenn.edu/~wilf/AeqB.pdf
def test_gosper_sum_AeqB_part1():
f1a = n**4
f1b = n**3*2**n
f1c = 1/(n**2 + sqrt(5)*n - 1)
f1d = n**4*4**n/binomial(2*n, n)
f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n)
f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n))
f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n))
f1h = n*factorial(n - S.Half)**2/factorial(n + 1)**2
g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30
g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13)
g1c = (m + 1)*(m*(m**2 - 7*m + 3)*sqrt(5) - (
3*m**3 - 7*m**2 + 19*m - 6))/(2*m**3*sqrt(5) + m**4 + 5*m**2 - 1)/6
g1d = Rational(-2, 231) + 2*4**m*(m + 1)*(63*m**4 + 112*m**3 + 18*m**2 -
22*m + 3)/(693*binomial(2*m, m))
g1e = Rational(-9, 2) + (81*m**2 + 261*m + 200)*factorial(
3*m + 2)/(40*27**m*factorial(m)*factorial(m + 1)*factorial(m + 2))
g1f = (2*m + 1)**2*binomial(2*m, m)**2/(4**(2*m)*(m + 1))
g1g = -binomial(2*m, m)**2/4**(2*m)
g1h = 4*pi -(2*m + 1)**2*(3*m + 4)*factorial(m - S.Half)**2/factorial(m + 1)**2
g = gosper_sum(f1a, (n, 0, m))
assert g is not None and simplify(g - g1a) == 0
g = gosper_sum(f1b, (n, 0, m))
assert g is not None and simplify(g - g1b) == 0
g = gosper_sum(f1c, (n, 0, m))
assert g is not None and simplify(g - g1c) == 0
g = gosper_sum(f1d, (n, 0, m))
assert g is not None and simplify(g - g1d) == 0
g = gosper_sum(f1e, (n, 0, m))
assert g is not None and simplify(g - g1e) == 0
g = gosper_sum(f1f, (n, 0, m))
assert g is not None and simplify(g - g1f) == 0
g = gosper_sum(f1g, (n, 0, m))
assert g is not None and simplify(g - g1g) == 0
g = gosper_sum(f1h, (n, 0, m))
# need to call rewrite(gamma) here because we have terms involving
# factorial(1/2)
assert g is not None and simplify(g - g1h).rewrite(gamma) == 0
def test_gosper_sum_AeqB_part2():
f2a = n**2*a**n
f2b = (n - r/2)*binomial(r, n)
f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x))
g2a = -a*(a + 1)/(a - 1)**3 + a**(
m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3
g2b = (m - r)*binomial(r, m)/2
ff = factorial(1 - x)*factorial(1 + x)
g2c = 1/ff*(
1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x))
g = gosper_sum(f2a, (n, 0, m))
assert g is not None and simplify(g - g2a) == 0
g = gosper_sum(f2b, (n, 0, m))
assert g is not None and simplify(g - g2b) == 0
g = gosper_sum(f2c, (n, 1, m))
assert g is not None and simplify(g - g2c) == 0
def test_gosper_nan():
a = Symbol('a', positive=True)
b = Symbol('b', positive=True)
n = Symbol('n', integer=True)
m = Symbol('m', integer=True)
f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b))
g2d = 1/(factorial(a - 1)*factorial(
b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m))
g = gosper_sum(f2d, (n, 0, m))
assert simplify(g - g2d) == 0
def test_gosper_sum_AeqB_part3():
f3a = 1/n**4
f3b = (6*n + 3)/(4*n**4 + 8*n**3 + 8*n**2 + 4*n + 3)
f3c = 2**n*(n**2 - 2*n - 1)/(n**2*(n + 1)**2)
f3d = n**2*4**n/((n + 1)*(n + 2))
f3e = 2**n/(n + 1)
f3f = 4*(n - 1)*(n**2 - 2*n - 1)/(n**2*(n + 1)**2*(n - 2)**2*(n - 3)**2)
f3g = (n**4 - 14*n**2 - 24*n - 9)*2**n/(n**2*(n + 1)**2*(n + 2)**2*
(n + 3)**2)
# g3a -> no closed form
g3b = m*(m + 2)/(2*m**2 + 4*m + 3)
g3c = 2**m/m**2 - 2
g3d = Rational(2, 3) + 4**(m + 1)*(m - 1)/(m + 2)/3
# g3e -> no closed form
g3f = -(Rational(-1, 16) + 1/((m - 2)**2*(m + 1)**2)) # the AeqB key is wrong
g3g = Rational(-2, 9) + 2**(m + 1)/((m + 1)**2*(m + 3)**2)
g = gosper_sum(f3a, (n, 1, m))
assert g is None
g = gosper_sum(f3b, (n, 1, m))
assert g is not None and simplify(g - g3b) == 0
g = gosper_sum(f3c, (n, 1, m - 1))
assert g is not None and simplify(g - g3c) == 0
g = gosper_sum(f3d, (n, 1, m))
assert g is not None and simplify(g - g3d) == 0
g = gosper_sum(f3e, (n, 0, m - 1))
assert g is None
g = gosper_sum(f3f, (n, 4, m))
assert g is not None and simplify(g - g3f) == 0
g = gosper_sum(f3g, (n, 1, m))
assert g is not None and simplify(g - g3g) == 0
|
aa3c70f0a1be6ac2394ad14436dd807f062800b69ba61f9e0214cfed219582e2 | from math import prod
from sympy.concrete.expr_with_intlimits import ReorderError
from sympy.concrete.products import (Product, product)
from sympy.concrete.summations import (Sum, summation, telescopic,
eval_sum_residue, _dummy_with_inherited_properties_concrete)
from sympy.core.function import (Derivative, Function)
from sympy.core import (Catalan, EulerGamma)
from sympy.core.facts import InconsistentAssumptions
from sympy.core.mod import Mod
from sympy.core.numbers import (E, I, Rational, nan, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import (rf, binomial, factorial)
from sympy.functions.combinatorial.numbers import harmonic
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.hyperbolic import (sinh, tanh)
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.gamma_functions import (gamma, lowergamma)
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.zeta_functions import zeta
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import And, Or
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.matrices import (Matrix, SparseMatrix,
ImmutableDenseMatrix, ImmutableSparseMatrix, diag)
from sympy.sets.fancysets import Range
from sympy.sets.sets import Interval
from sympy.simplify.combsimp import combsimp
from sympy.simplify.simplify import simplify
from sympy.tensor.indexed import (Idx, Indexed, IndexedBase)
from sympy.testing.pytest import XFAIL, raises, slow
from sympy.abc import a, b, c, d, k, m, x, y, z
n = Symbol('n', integer=True)
f, g = symbols('f g', cls=Function)
def test_karr_convention():
# Test the Karr summation convention that we want to hold.
# See his paper "Summation in Finite Terms" for a detailed
# reasoning why we really want exactly this definition.
# The convention is described on page 309 and essentially
# in section 1.4, definition 3:
#
# \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n
# \sum_{m <= i < n} f(i) = 0 for m = n
# \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n
#
# It is important to note that he defines all sums with
# the upper limit being *exclusive*.
# In contrast, SymPy and the usual mathematical notation has:
#
# sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b)
#
# with the upper limit *inclusive*. So translating between
# the two we find that:
#
# \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i)
#
# where we intentionally used two different ways to typeset the
# sum and its limits.
i = Symbol("i", integer=True)
k = Symbol("k", integer=True)
j = Symbol("j", integer=True)
# A simple example with a concrete summand and symbolic limits.
# The normal sum: m = k and n = k + j and therefore m < n:
m = k
n = k + j
a = m
b = n - 1
S1 = Sum(i**2, (i, a, b)).doit()
# The reversed sum: m = k + j and n = k and therefore m > n:
m = k + j
n = k
a = m
b = n - 1
S2 = Sum(i**2, (i, a, b)).doit()
assert simplify(S1 + S2) == 0
# Test the empty sum: m = k and n = k and therefore m = n:
m = k
n = k
a = m
b = n - 1
Sz = Sum(i**2, (i, a, b)).doit()
assert Sz == 0
# Another example this time with an unspecified summand and
# numeric limits. (We can not do both tests in the same example.)
# The normal sum with m < n:
m = 2
n = 11
a = m
b = n - 1
S1 = Sum(f(i), (i, a, b)).doit()
# The reversed sum with m > n:
m = 11
n = 2
a = m
b = n - 1
S2 = Sum(f(i), (i, a, b)).doit()
assert simplify(S1 + S2) == 0
# Test the empty sum with m = n:
m = 5
n = 5
a = m
b = n - 1
Sz = Sum(f(i), (i, a, b)).doit()
assert Sz == 0
e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True))
s = Sum(e, (i, 0, 11))
assert s.n(3) == s.doit().n(3)
def test_karr_proposition_2a():
# Test Karr, page 309, proposition 2, part a
i = Symbol("i", integer=True)
u = Symbol("u", integer=True)
v = Symbol("v", integer=True)
def test_the_sum(m, n):
# g
g = i**3 + 2*i**2 - 3*i
# f = Delta g
f = simplify(g.subs(i, i+1) - g)
# The sum
a = m
b = n - 1
S = Sum(f, (i, a, b)).doit()
# Test if Sum_{m <= i < n} f(i) = g(n) - g(m)
assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0
# m < n
test_the_sum(u, u+v)
# m = n
test_the_sum(u, u )
# m > n
test_the_sum(u+v, u )
def test_karr_proposition_2b():
# Test Karr, page 309, proposition 2, part b
i = Symbol("i", integer=True)
u = Symbol("u", integer=True)
v = Symbol("v", integer=True)
w = Symbol("w", integer=True)
def test_the_sum(l, n, m):
# Summand
s = i**3
# First sum
a = l
b = n - 1
S1 = Sum(s, (i, a, b)).doit()
# Second sum
a = l
b = m - 1
S2 = Sum(s, (i, a, b)).doit()
# Third sum
a = m
b = n - 1
S3 = Sum(s, (i, a, b)).doit()
# Test if S1 = S2 + S3 as required
assert S1 - (S2 + S3) == 0
# l < m < n
test_the_sum(u, u+v, u+v+w)
# l < m = n
test_the_sum(u, u+v, u+v )
# l < m > n
test_the_sum(u, u+v+w, v )
# l = m < n
test_the_sum(u, u, u+v )
# l = m = n
test_the_sum(u, u, u )
# l = m > n
test_the_sum(u+v, u+v, u )
# l > m < n
test_the_sum(u+v, u, u+w )
# l > m = n
test_the_sum(u+v, u, u )
# l > m > n
test_the_sum(u+v+w, u+v, u )
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)) is oo
assert summation(k, (k, Range(1, 11))) == 55
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_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(S.Half**n, (n, 1, oo)) == 1
assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1
assert summation(2**n, (n, 1, oo)) is 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)) is -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) - Rational(4, 3)
assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half
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)) is 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 == 1/3.
assert result.is_Float
result = Sum(0.99999**n, (n, 1, oo)).doit()
assert result == 99999
assert result.is_Float
result = Sum(S.Half**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 == Rational(3, 2)
assert not result.is_Float
assert Sum(1.0**n, (n, 1, oo)).doit() is oo
assert Sum(2.43**n, (n, 1, oo)).doit() is oo
# Issue 13979
i, k, q = symbols('i k q', integer=True)
result = summation(
exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1)
)
assert result.simplify() == Piecewise(
(1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True)
)
#Issue 23491
assert Sum(1/(n**2 + 1), (n, 1, oo)).doit() == S(-1)/2 + pi/(2*tanh(pi))
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 test_composite_sums():
f = S.Half*(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 test_hypergeometric_sums():
assert summation(
binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n
assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5)
def test_other_sums():
f = m**2 + m*exp(m)
g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5
assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g
assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10)
fac = factorial
def NS(e, n=15, **options):
return str(sympify(e).evalf(n, **options))
def test_evalf_fast_series():
# Euler transformed series for sqrt(1+x)
assert NS(Sum(
fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100)
# Some series for exp(1)
estr = NS(E, 100)
assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr
assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr
assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr
assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr
pistr = NS(pi, 100)
# Ramanujan series for pi
assert NS(9801/sqrt(8)/Sum(fac(
4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr
assert NS(1/Sum(
binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr
# Machin's formula for pi
assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) -
4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr
# Apery's constant
astr = NS(zeta(3), 100)
P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \
n + 12463
assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac(
n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr
assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 /
fac(2*n + 1)**5, (n, 0, oo)), 100) == astr
def test_evalf_fast_series_issue_4021():
# Catalan's constant
assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3*
fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \
NS(Catalan, 100)
astr = NS(zeta(3), 100)
assert NS(5*Sum(
(-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr
assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1)
**3 / fac(3*n), (n, 1, oo))/4, 100) == astr
def test_evalf_slow_series():
assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15)
assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50)
assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15)
assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100)
assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500)
assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15)
assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50)
def test_evalf_oo_to_oo():
# There used to be an error in certain cases
# Does not evaluate, but at least do not throw an error
# Evaluates symbolically to 0, which is not correct
assert Sum(1/(n**2+1), (n, -oo, oo)).evalf() == Sum(1/(n**2+1), (n, -oo, oo))
# This evaluates if from 1 to oo and symbolically
assert Sum(1/(factorial(abs(n))), (n, -oo, -1)).evalf() == Sum(1/(factorial(abs(n))), (n, -oo, -1))
def test_euler_maclaurin():
# Exact polynomial sums with E-M
def check_exact(f, a, b, m, n):
A = Sum(f, (k, a, b))
s, e = A.euler_maclaurin(m, n)
assert (e == 0) and (s.expand() == A.doit())
check_exact(k**4, a, b, 0, 2)
check_exact(k**4 + 2*k, a, b, 1, 2)
check_exact(k**4 + k**2, a, b, 1, 5)
check_exact(k**5, 2, 6, 1, 2)
check_exact(k**5, 2, 6, 1, 3)
assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0)
# Not exact
assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0
# Numerical test
for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]:
A = Sum(1/k**3, (k, 1, oo))
s, e = A.euler_maclaurin(mi, ni)
assert abs((s - zeta(3)).evalf()) < e.evalf()
raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin())
@slow
def test_evalf_euler_maclaurin():
assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266'
assert NS(Sum(1/k**k, (k, 1, oo)),
50) == '1.2912859970626635404072825905956005414986193682745'
assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15)
assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50)
assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844'
assert NS(Sum(log(k)/k**2, (k, 1, oo)),
50) == '0.93754825431584375370257409456786497789786028861483'
assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008'
assert NS(Sum(1/k, (k, 1000000, 2000000)),
50) == '0.69314793056000780941723211364567656807940638436025'
def test_evalf_symbolic():
# issue 6328
expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3))
assert expr.evalf() == expr
def test_evalf_issue_3273():
assert Sum(0, (k, 1, oo)).evalf() == 0
def test_simple_products():
assert Product(S.NaN, (x, 1, 3)) is S.NaN
assert product(S.NaN, (x, 1, 3)) is S.NaN
assert Product(x, (n, a, a)).doit() == x
assert Product(x, (x, a, a)).doit() == a
assert Product(x, (y, 1, a)).doit() == x**a
lo, hi = 1, 2
s1 = Product(n, (n, lo, hi))
s2 = Product(n, (n, hi, lo))
assert s1 != s2
# This IS correct according to Karr product convention
assert s1.doit() == 2
assert s2.doit() == 1
lo, hi = x, x + 1
s1 = Product(n, (n, lo, hi))
s2 = Product(n, (n, hi, lo))
s3 = 1 / Product(n, (n, hi + 1, lo - 1))
assert s1 != s2
# This IS correct according to Karr product convention
assert s1.doit() == x*(x + 1)
assert s2.doit() == 1
assert s3.doit() == x*(x + 1)
assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \
(y**2 + 1)*(y**2 + 3)
assert product(2, (n, a, b)) == 2**(b - a + 1)
assert product(n, (n, 1, b)) == factorial(b)
assert product(n**3, (n, 1, b)) == factorial(b)**3
assert product(3**(2 + n), (n, a, b)) \
== 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2)
assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5)
assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2)
assert isinstance(product(cos(n), (n, x, x + S.Half)), Product)
# If Product managed to evaluate this one, it most likely got it wrong!
assert isinstance(Product(n**n, (n, 1, b)), Product)
def test_rational_products():
assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a
assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a)
assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1))
assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \
a*gamma(a + 2)/(b + 1)/gamma(b + 3)
assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \
b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2))
def test_wallis_product():
# Wallis product, given in two different forms to ensure that Product
# can factor simple rational expressions
A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b))
B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b))
R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2)))
assert simplify(A.doit()) == R
assert simplify(B.doit()) == R
# This one should eventually also be doable (Euler's product formula for sin)
# assert Product(1+x/n**2, (n, 1, b)) == ...
def test_telescopic_sums():
#checks also input 2 of comment 1 issue 4127
assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n)
assert Sum(
f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m)
assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \
cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3)
# dummy variable shouldn't matter
assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \
telescopic(1/k, -k/(1 + k), (k, n - 1, n))
assert Sum(1/x/(x - 1), (x, a, b)).doit() == 1/(a - 1) - 1/b
eq = 1/((5*n + 2)*(5*(n + 1) + 2))
assert Sum(eq, (n, 0, oo)).doit() == S(1)/10
nz = symbols('nz', nonzero=True)
v = Sum(eq.subs(5, nz), (n, 0, oo)).doit()
assert v.subs(nz, 5).simplify() == S(1)/10
# check that apart is being used in non-symbolic case
s = Sum(eq, (n, 0, k)).doit()
v = Sum(eq, (n, 0, 10**100)).doit()
assert v == s.subs(k, 10**100)
def test_sum_reconstruct():
s = Sum(n**2, (n, -1, 1))
assert s == Sum(*s.args)
raises(ValueError, lambda: Sum(x, x))
raises(ValueError, lambda: Sum(x, (x, 1)))
def test_limit_subs():
for F in (Sum, Product, Integral):
assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2)
assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \
F(a, (a, c, 4))
assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1))
def test_function_subs():
S = Sum(x*f(y),(x,0,oo),(y,0,oo))
assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
assert S.subs(f(x),x) == S
raises(ValueError, lambda: S.subs(f(y),x+y) )
S = Sum(x*log(y),(x,0,oo),(y,0,oo))
assert S.subs(log(y),y) == S
S = Sum(x*f(y),(x,0,oo),(y,0,oo))
assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
def test_equality():
# if this fails remove special handling below
raises(ValueError, lambda: Sum(x, x))
r = symbols('x', real=True)
for F in (Sum, Product, Integral):
try:
assert F(x, x) != F(y, y)
assert F(x, (x, 1, 2)) != F(x, x)
assert F(x, (x, x)) != F(x, x) # or else they print the same
assert F(1, x) != F(1, y)
except ValueError:
pass
assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) # diff limit
assert F(a, (x, 1, x)) != F(a, (y, 1, y))
assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) # diff expression
assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) # diff assumptions
assert F(1, (x, 1, x)) != F(1, (y, 1, x)) # only dummy is diff
assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x)))
# issue 5265
assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a))
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()
# Integer assumes finite
assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo < y, y < oo)), (0, True))
assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1
assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo < y, y < oo)), (0, True))
assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x
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(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(f(n), (n, 1, oo))
# issue 2597
nmax = symbols('N', integer=True, positive=True)
pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True))
assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n),
(0, True)), (n, 1, nmax))
q, s = symbols('q, s')
assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1),
(Sum(n**(-2*s), (n, 1, oo)), True))
assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1),
(Sum((n + 1)**(-s), (n, 0, oo)), True))
assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise(
(zeta(s, q), And(q > 0, s > 1)),
(Sum((n + q)**(-s), (n, 0, oo)), True))
assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise(
(zeta(s, 2*q), And(2*q > 0, s > 1)),
(Sum((n + q)**(-s), (n, q, oo)), True))
assert summation(1/n**2, (n, 1, oo)) == zeta(2)
assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo))
def test_Product_doit():
assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9
assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \
6*Integral(a**2)**3
assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3
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_diff():
assert Sum(x, (x, 1, 2)).diff(x) == 0
assert Sum(x*y, (x, 1, 2)).diff(x) == 0
assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2))
e = Sum(x*y, (x, 1, a))
assert e.diff(a) == Derivative(e, a)
assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \
Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24
assert Sum(x, (x, 1, 2)).diff(y) == 0
def test_hypersum():
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)) == Rational(-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 test_issue_4170():
assert summation(1/factorial(k), (k, 0, oo)) == E
def test_is_commutative():
from sympy.physics.secondquant import NO, F, Fd
m = Symbol('m', commutative=False)
for f in (Sum, Product, Integral):
assert f(z, (z, 1, 1)).is_commutative is True
assert f(z*y, (z, 1, 6)).is_commutative is True
assert f(m*x, (x, 1, 2)).is_commutative is False
assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False
def test_is_zero():
for func in [Sum, Product]:
assert func(0, (x, 1, 1)).is_zero is True
assert func(x, (x, 1, 1)).is_zero is None
assert Sum(0, (x, 1, 0)).is_zero is True
assert Product(0, (x, 1, 0)).is_zero is False
def test_is_number():
# is number should not rely on evaluation or assumptions,
# it should be equivalent to `not foo.free_symbols`
assert Sum(1, (x, 1, 1)).is_number is True
assert Sum(1, (x, 1, x)).is_number is False
assert Sum(0, (x, y, z)).is_number is False
assert Sum(x, (y, 1, 2)).is_number is False
assert Sum(x, (y, 1, 1)).is_number is False
assert Sum(x, (x, 1, 2)).is_number is True
assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
assert Product(2, (x, 1, 1)).is_number is True
assert Product(2, (x, 1, y)).is_number is False
assert Product(0, (x, y, z)).is_number is False
assert Product(1, (x, y, z)).is_number is False
assert Product(x, (y, 1, x)).is_number is False
assert Product(x, (y, 1, 2)).is_number is False
assert Product(x, (y, 1, 1)).is_number is False
assert Product(x, (x, 1, 2)).is_number is True
def test_free_symbols():
for func in [Sum, Product]:
assert func(1, (x, 1, 2)).free_symbols == set()
assert func(0, (x, 1, y)).free_symbols == {y}
assert func(2, (x, 1, y)).free_symbols == {y}
assert func(x, (x, 1, 2)).free_symbols == set()
assert func(x, (x, 1, y)).free_symbols == {y}
assert func(x, (y, 1, y)).free_symbols == {x, y}
assert func(x, (y, 1, 2)).free_symbols == {x}
assert func(x, (y, 1, 1)).free_symbols == {x}
assert func(x, (y, 1, z)).free_symbols == {x, z}
assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set()
assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z}
assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y}
assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z}
assert Sum(1, (x, 1, y)).free_symbols == {y}
# free_symbols answers whether the object *as written* has free symbols,
# not whether the evaluated expression has free symbols
assert Product(1, (x, 1, y)).free_symbols == {y}
# don't count free symbols that are not independent of integration
# variable(s)
assert func(f(x), (f(x), 1, 2)).free_symbols == set()
assert func(f(x), (f(x), 1, x)).free_symbols == {x}
assert func(f(x), (f(x), 1, y)).free_symbols == {y}
assert func(f(x), (z, 1, y)).free_symbols == {x, y}
def test_conjugate_transpose():
A, B = symbols("A B", commutative=False)
p = Sum(A*B**n, (n, 1, 3))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
p = Sum(B**n*A, (n, 1, 3))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
def test_noncommutativity_honoured():
A, B = symbols("A B", commutative=False)
M = symbols('M', integer=True, positive=True)
p = Sum(A*B**n, (n, 1, M))
assert p.doit() == A*Piecewise((M, Eq(B, 1)),
((B - B**(M + 1))*(1 - B)**(-1), True))
p = Sum(B**n*A, (n, 1, M))
assert p.doit() == Piecewise((M, Eq(B, 1)),
((B - B**(M + 1))*(1 - B)**(-1), True))*A
p = Sum(B**n*A*B**n, (n, 1, M))
assert p.doit() == p
def test_issue_4171():
assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo
assert summation(2*k + 1, (k, 0, oo)) is oo
def test_issue_6273():
assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == 1
def test_issue_6274():
assert Sum(x, (x, 1, 0)).doit() == 0
assert NS(Sum(x, (x, 1, 0))) == '0'
assert Sum(n, (n, 10, 5)).doit() == -30
assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000'
def test_simplify_sum():
y, t, v = symbols('y, t, v')
_simplify = lambda e: simplify(e, doit=False)
assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \
Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k))
assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \
Sum(x, (x, n, a))
assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \
Sum(x, (x, n, a))
assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \
Sum(x, (x, n, a)) + Sum(1, (x, n, k))
assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \
4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6))
assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \
Sum(x*(3*x + 1), (x, a, b))
assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \
4 * y * Sum(z, (z, n, k))) + 1 == \
4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1
assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \
1 + Sum(x, (x, a, c))
assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \
Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \
Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \
_simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c)))
assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \
Sum(x, (x, a, b)) * Sum(x**2, (x, a, b))
assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \
== (x + y + z) * Sum(1, (t, a, b)) # issue 8596
assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \
Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596
assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \
(Sum(x, (x, a, b)) / 3)
assert _simplify(Sum(f(x) * y * z, (x, a, b)) / (y * z)) \
== Sum(f(x), (x, a, b))
assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0
assert _simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b)))
assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \
c * (y + 1) * Sum(x, (x, a, b))
assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \
c * Sum(x, (x, a, b), (y, a, b))
assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \
c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b))
assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \
c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b))
assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \
Sum(d * t, (x, b, c)), (t, a, b))) == \
d * Sum(1, (x, a, c)) * Sum(t, (t, a, b))
assert _simplify(Sum(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \
2 * Sum(1, (t, a, b))
def test_change_index():
b, v, w = symbols('b, v, w', integer = True)
assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \
Sum(y - 1, (y, a + 1, b + 1))
assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \
Sum((x+1)**2, (x, a - 1, b - 1))
assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \
Sum((-y)**2, (y, -b, -a))
assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \
Sum(-x - 1, (x, -b - 1, -a - 1))
assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \
Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
assert Sum(x, (x, a, b)).change_index( x, x + v) == \
Sum(-v + x, (x, a + v, b + v))
assert Sum(x, (x, a, b)).change_index( x, -x - v) == \
Sum(-v - x, (x, -b - v, -a - v))
assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \
Sum(v/w, (v, b*w, a*w))
raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x))
def test_reorder():
b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
Sum(x*y, (y, c, d), (x, a, b))
assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
Sum(x, (x, c, d), (x, a, b))
assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
(2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b))
assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
(0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
(x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
Sum(x*y, (y, c, d), (x, a, b))
assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
Sum(x*y, (y, c, d), (x, a, b))
def test_reverse_order():
assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1))
assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
Sum(x*y, (x, 6, 0), (y, 7, -1))
assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0))
assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0))
assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0))
assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1))
assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \
Sum(-x, (x, a + 6, a))
assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \
Sum(-x, (x, a + 3, a))
assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \
Sum(-x, (x, a + 2, a))
assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1))
assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1))
assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
def test_issue_7097():
assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400))
def test_factor_expand_subs():
# test factoring
assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y))
assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y))
assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y))
assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y))
# test expand
_x = Symbol('x', zero=False)
assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y))
assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y))
assert Sum(_x**(n + 1)*(n + 1), (n, -1, oo)).expand() \
== Sum(n*_x*_x**n + _x*_x**n, (n, -1, oo))
assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \
== Sum(n*x**(n + 1) + x**(n + 1), (n, -1, oo))
assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(force=True) \
== Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo))
assert Sum(a*n+a*n**2,(n,0,4)).expand() \
== Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4))
assert Sum(_x**a*_x**n,(x,0,3)) \
== Sum(_x**(a+n),(x,0,3)).expand(power_exp=True)
_a, _n = symbols('a n', positive=True)
assert Sum(x**(_a+_n),(x,0,3)).expand(power_exp=True) \
== Sum(x**_a*x**_n, (x, 0, 3))
assert Sum(x**(_a-_n),(x,0,3)).expand(power_exp=True) \
== Sum(x**(_a-_n),(x,0,3)).expand(power_exp=False)
# test subs
assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3))
assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3))
assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10))
assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10))
assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10))
def test_distribution_over_equality():
assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3))
assert Sum(Eq(f(x), x**2), (x, 0, y)) == \
Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
def test_issue_2787():
n, k = symbols('n k', positive=True, integer=True)
p = symbols('p', positive=True)
binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k)
s = Sum(binomial_dist*k, (k, 0, n))
res = s.doit().simplify()
ans = Piecewise(
(n*p, x),
(Sum(k*p**k*binomial(n, k)*(1 - p)**(n - k), (k, 0, n)),
True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
ans2 = Piecewise(
(n*p, x),
(factorial(n)*Sum(p**k*(1 - p)**(-k + n)/
(factorial(-k + n)*factorial(k - 1)), (k, 0, n)),
True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
assert res in [ans, ans2] # XXX system dependent
# Issue #17165: make sure that another simplify does not complicate
# the result by much. Why didn't first simplify replace
# Eq(n, 1) | (n > 1) with True?
assert res.simplify().count_ops() <= res.count_ops() + 2
def test_issue_4668():
assert summation(1/n, (n, 2, oo)) is oo
def test_matrix_sum():
A = Matrix([[0, 1], [n, 0]])
result = Sum(A, (n, 0, 3)).doit()
assert result == Matrix([[0, 4], [6, 0]])
assert result.__class__ == ImmutableDenseMatrix
A = SparseMatrix([[0, 1], [n, 0]])
result = Sum(A, (n, 0, 3)).doit()
assert result.__class__ == ImmutableSparseMatrix
def test_failing_matrix_sum():
n = Symbol('n')
# TODO Implement matrix geometric series summation.
A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]])
assert Sum(A ** n, (n, 1, 4)).doit() == \
Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
# issue sympy/sympy#16989
assert summation(A**n, (n, 1, 1)) == A
def test_indexed_idx_sum():
i = symbols('i', cls=Idx)
r = Indexed('r', i)
assert Sum(r, (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)])
assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)])
j = symbols('j', integer=True)
assert Sum(r, (i, j, j+2)).doit() == sum([r.xreplace({i: j+k}) for k in range(3)])
assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)])
k = Idx('k', range=(1, 3))
A = IndexedBase('A')
assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)])
assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)])
raises(ValueError, lambda: Sum(A[k], (k, 1, 4)))
raises(ValueError, lambda: Sum(A[k], (k, 0, 3)))
raises(ValueError, lambda: Sum(A[k], (k, 2, oo)))
raises(ValueError, lambda: Product(A[k], (k, 1, 4)))
raises(ValueError, lambda: Product(A[k], (k, 0, 3)))
raises(ValueError, lambda: Product(A[k], (k, 2, oo)))
@slow
def test_is_convergent():
# divergence tests --
assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false
assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false
assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false
assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false
assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false
assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false
# Raabe's test --
assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true
# root test --
assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false
# integral test --
# p-series test --
assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true
assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true
assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false
assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true
assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true
assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false
# comparison test --
assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false
assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false
assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true
assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true
assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false
assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false
assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false
assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true
assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true
# alternating series tests --
assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true
# with -negativeInfinite Limits
assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true
assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false
assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true
assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true
assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true
# piecewise functions
f = Piecewise((n**(-2), n <= 1), (n**2, n > 1))
assert Sum(f, (n, 1, oo)).is_convergent() is S.false
assert Sum(f, (n, -oo, oo)).is_convergent() is S.false
assert Sum(f, (n, 1, 100)).is_convergent() is S.true
#assert Sum(f, (n, -oo, 1)).is_convergent() is S.true
# integral test
assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
# the following function has maxima located at (x, y) =
# (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050)
eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x)
assert Sum(eq, (x, 1, oo)).is_convergent() is S.true
assert Sum(eq, (x, 1, 2)).is_convergent() is S.true
assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true
assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false
# issue 19545
assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true
# issue 19836
assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true
def test_is_absolutely_convergent():
assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false
assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true
@XFAIL
def test_convergent_failing():
# dirichlet tests
assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true
assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true
def test_issue_6966():
i, k, m = symbols('i k m', integer=True)
z_i, q_i = symbols('z_i q_i')
a_k = Sum(-q_i*z_i/k,(i,1,m))
b_k = a_k.diff(z_i)
assert isinstance(b_k, Sum)
assert b_k == Sum(-q_i/k,(i,1,m))
def test_issue_10156():
cx = Sum(2*y**2*x, (x, 1,3))
e = 2*y*Sum(2*cx*x**2, (x, 1, 9))
assert e.factor() == \
8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9))
def test_issue_10973():
assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true
def test_issue_14129():
x = Symbol('x', zero=False)
assert Sum( k*x**k, (k, 0, n-1)).doit() == \
Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n -
n*x**n - x*x**n + x)/(x - 1)**2, True))
assert Sum( x**k, (k, 0, n-1)).doit() == \
Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True))
assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \
Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))),
(x*(y + 1)*(n*x*y*(x + x/y)**(n - 1) +
n*x*(x + x/y)**(n - 1) - n*y*(x + x/y)**(n - 1) -
x*y*(x + x/y)**(n - 1) - x*(x + x/y)**(n - 1) + y)/
(x*y + x - y)**2, True))
def test_issue_14112():
assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false
assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false
assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false
def test_issue_14219():
A = diag(0, 2, -3)
res = diag(1, 15, -20)
assert Sum(A**n, (n, 0, 3)).doit() == res
def test_sin_times_absolutely_convergent():
assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true
assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true
def test_issue_14111():
assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false
def test_issue_14484():
assert Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent() is S.false
def test_issue_14640():
i, n = symbols("i n", integer=True)
a, b, c = symbols("a b c", zero=False)
assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum(
1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise(
(n + 1, Eq(1/a, 1)),
((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b)
assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise(
(n + 1, Eq(a**(-2), 1)),
((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2
s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit()
assert not s.has(Sum)
assert s.subs({a: 2, b: 3, n: 5}) == 122
def test_issue_15943():
s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma)
assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2
) + E*gamma(n + 1)
assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1))
def test_Sum_dummy_eq():
assert not Sum(x, (x, a, b)).dummy_eq(1)
assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2)))
assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c)))
assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b)))
d = Dummy()
assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c)
assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)))
assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c)))
assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c)
assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)))
def test_issue_15852():
assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo))
def test_exceptions():
S = Sum(x, (x, a, b))
raises(ValueError, lambda: S.change_index(x, x**2, y))
S = Sum(x, (x, a, b), (x, 1, 4))
raises(ValueError, lambda: S.index(x))
S = Sum(x, (x, a, b), (y, 1, 4))
raises(ValueError, lambda: S.reorder([x]))
S = Sum(x, (x, y, b), (y, 1, 4))
raises(ReorderError, lambda: S.reorder_limit(0, 1))
S = Sum(x*y, (x, a, b), (y, 1, 4))
raises(NotImplementedError, lambda: S.is_convergent())
def test_sumproducts_assumptions():
M = Symbol('M', integer=True, positive=True)
m = Symbol('m', integer=True)
for func in [Sum, Product]:
assert func(m, (m, -M, M)).is_positive is None
assert func(m, (m, -M, M)).is_nonpositive is None
assert func(m, (m, -M, M)).is_negative is None
assert func(m, (m, -M, M)).is_nonnegative is None
assert func(m, (m, -M, M)).is_finite is True
m = Symbol('m', integer=True, nonnegative=True)
for func in [Sum, Product]:
assert func(m, (m, 0, M)).is_positive is None
assert func(m, (m, 0, M)).is_nonpositive is None
assert func(m, (m, 0, M)).is_negative is False
assert func(m, (m, 0, M)).is_nonnegative is True
assert func(m, (m, 0, M)).is_finite is True
m = Symbol('m', integer=True, positive=True)
for func in [Sum, Product]:
assert func(m, (m, 1, M)).is_positive is True
assert func(m, (m, 1, M)).is_nonpositive is False
assert func(m, (m, 1, M)).is_negative is False
assert func(m, (m, 1, M)).is_nonnegative is True
assert func(m, (m, 1, M)).is_finite is True
m = Symbol('m', integer=True, negative=True)
assert Sum(m, (m, -M, -1)).is_positive is False
assert Sum(m, (m, -M, -1)).is_nonpositive is True
assert Sum(m, (m, -M, -1)).is_negative is True
assert Sum(m, (m, -M, -1)).is_nonnegative is False
assert Sum(m, (m, -M, -1)).is_finite is True
assert Product(m, (m, -M, -1)).is_positive is None
assert Product(m, (m, -M, -1)).is_nonpositive is None
assert Product(m, (m, -M, -1)).is_negative is None
assert Product(m, (m, -M, -1)).is_nonnegative is None
assert Product(m, (m, -M, -1)).is_finite is True
m = Symbol('m', integer=True, nonpositive=True)
assert Sum(m, (m, -M, 0)).is_positive is False
assert Sum(m, (m, -M, 0)).is_nonpositive is True
assert Sum(m, (m, -M, 0)).is_negative is None
assert Sum(m, (m, -M, 0)).is_nonnegative is None
assert Sum(m, (m, -M, 0)).is_finite is True
assert Product(m, (m, -M, 0)).is_positive is None
assert Product(m, (m, -M, 0)).is_nonpositive is None
assert Product(m, (m, -M, 0)).is_negative is None
assert Product(m, (m, -M, 0)).is_nonnegative is None
assert Product(m, (m, -M, 0)).is_finite is True
m = Symbol('m', integer=True)
assert Sum(2, (m, 0, oo)).is_positive is None
assert Sum(2, (m, 0, oo)).is_nonpositive is None
assert Sum(2, (m, 0, oo)).is_negative is None
assert Sum(2, (m, 0, oo)).is_nonnegative is None
assert Sum(2, (m, 0, oo)).is_finite is None
assert Product(2, (m, 0, oo)).is_positive is None
assert Product(2, (m, 0, oo)).is_nonpositive is None
assert Product(2, (m, 0, oo)).is_negative is False
assert Product(2, (m, 0, oo)).is_nonnegative is None
assert Product(2, (m, 0, oo)).is_finite is None
assert Product(0, (x, M, M-1)).is_positive is True
assert Product(0, (x, M, M-1)).is_finite is True
def test_expand_with_assumptions():
M = Symbol('M', integer=True, positive=True)
x = Symbol('x', positive=True)
m = Symbol('m', nonnegative=True)
assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M))
assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M))
assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M))
assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M))
n = Symbol('n', nonnegative=True)
i, j = symbols('i,j', positive=True, integer=True)
x, y = symbols('x,y', positive=True)
assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \
== Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
m = Symbol('m', nonnegative=True, integer=True)
s = Sum(x**m, (m, 0, M))
s_as_product = s.rewrite(Product)
assert s_as_product.has(Product)
assert s_as_product == log(Product(exp(x**m), (m, 0, M)))
assert s_as_product.expand() == s
s5 = s.subs(M, 5)
s5_as_product = s5.rewrite(Product)
assert s5_as_product.has(Product)
assert s5_as_product.doit().expand() == s5.doit()
def test_has_finite_limits():
x = Symbol('x')
assert Sum(1, (x, 1, 9)).has_finite_limits is True
assert Sum(1, (x, 1, oo)).has_finite_limits is False
M = Symbol('M')
assert Sum(1, (x, 1, M)).has_finite_limits is None
M = Symbol('M', positive=True)
assert Sum(1, (x, 1, M)).has_finite_limits is True
x = Symbol('x', positive=True)
M = Symbol('M')
assert Sum(1, (x, 1, M)).has_finite_limits is True
assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False
def test_has_reversed_limits():
assert Sum(1, (x, 1, 1)).has_reversed_limits is False
assert Sum(1, (x, 1, 9)).has_reversed_limits is False
assert Sum(1, (x, 1, -9)).has_reversed_limits is True
assert Sum(1, (x, 1, 0)).has_reversed_limits is True
assert Sum(1, (x, 1, oo)).has_reversed_limits is False
M = Symbol('M')
assert Sum(1, (x, 1, M)).has_reversed_limits is None
M = Symbol('M', positive=True, integer=True)
assert Sum(1, (x, 1, M)).has_reversed_limits is False
assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False
M = Symbol('M', negative=True)
assert Sum(1, (x, 1, M)).has_reversed_limits is True
assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True
assert Sum(1, (x, oo, oo)).has_reversed_limits is None
def test_has_empty_sequence():
assert Sum(1, (x, 1, 1)).has_empty_sequence is False
assert Sum(1, (x, 1, 9)).has_empty_sequence is False
assert Sum(1, (x, 1, -9)).has_empty_sequence is False
assert Sum(1, (x, 1, 0)).has_empty_sequence is True
assert Sum(1, (x, y, y - 1)).has_empty_sequence is True
assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True
assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True
assert Sum(1, (x, oo, oo)).has_empty_sequence is False
def test_empty_sequence():
assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1
assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1
assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0
assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0
def test_issue_8016():
k = Symbol('k', integer=True)
n, m = symbols('n, m', integer=True, positive=True)
s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n))
assert s.doit().simplify() == \
cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1)
def test_issue_14313():
assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent()
def test_issue_14563():
# The assertion was failing due to no assumptions methods in Sums and Product
assert 1 % Sum(1, (x, 0, 1)) == 1
def test_issue_16735():
assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true
def test_issue_14871():
assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1
def test_issue_17165():
n = symbols("n", integer=True)
x = symbols('x')
s = (x*Sum(x**n, (n, -1, oo)))
ssimp = s.doit().simplify()
assert ssimp == Piecewise((-1/(x - 1), (x > -1) & (x < 1)),
(x*Sum(x**n, (n, -1, oo)), True)), ssimp
assert ssimp.simplify() == ssimp
def test_issue_19379():
assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true
def test_issue_20777():
assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m))
def test__dummy_with_inherited_properties_concrete():
x = Symbol('x')
from sympy.core.containers import Tuple
d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5))
assert d.is_real
assert d.is_integer
assert d.is_nonnegative
assert d.is_extended_nonnegative
d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9))
assert d.is_real
assert d.is_integer
assert d.is_positive
assert d.is_odd is None
d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5))
assert d.is_real
assert d.is_integer
assert d.is_positive is None
assert d.is_extended_nonnegative is None
assert d.is_odd is None
d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5))
assert d.is_real
assert d.is_integer is None
assert d.is_positive is None
assert d.is_extended_nonnegative is None
N = Symbol('N', integer=True, positive=True)
d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N))
assert d.is_real
assert d.is_positive
assert d.is_integer
# Return None if no assumptions are added
N = Symbol('N', integer=True, positive=True)
d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4))
assert d is None
x = Symbol('x', negative=True)
raises(InconsistentAssumptions,
lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5)))
def test_matrixsymbol_summation_numerical_limits():
A = MatrixSymbol('A', 3, 3)
n = Symbol('n', integer=True)
assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2
assert Sum(A, (n, 0, 2)).doit() == 3*A
assert Sum(n*A, (n, 0, 2)).doit() == 3*A
B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]])
ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A
assert Sum(A+B, (n, 0, 3)).doit() == ans
ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]])
assert Sum(A*B, (n, 0, 3)).doit() == ans
ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) +
A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) +
A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]]))
assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans
def test_issue_21651():
i = Symbol('i')
a = Sum(floor(2*2**(-i)), (i, S.One, 2))
assert a.doit() == S.One
@XFAIL
def test_matrixsymbol_summation_symbolic_limits():
N = Symbol('N', integer=True, positive=True)
A = MatrixSymbol('A', 3, 3)
n = Symbol('n', integer=True)
assert Sum(A, (n, 0, N)).doit() == (N+1)*A
assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A
def test_summation_by_residues():
x = Symbol('x')
# Examples from Nakhle H. Asmar, Loukas Grafakos,
# Complex Analysis with Applications
assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi)
assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945
assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi))
assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
(-pi**2*tanh(pi)**2 + pi*tanh(pi) + pi**2)/(2*tanh(pi)**2)
assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
(-pi**2 + pi*tanh(pi) + pi**2*tanh(pi)**2)/(2*tanh(pi)**2)
assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0
assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2
assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8
assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi)
assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6
assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90
assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \
-pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2
# Some examples made from 1 / (x**2 + 1)
assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \
S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \
-S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \
1 + pi/(2*tanh(pi))
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \
pi/sinh(pi)
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \
pi/(2*sinh(pi)) + S(1)/2
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \
-S(1)/2 + pi/(2*sinh(pi))
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \
pi/(2*sinh(pi))
# Some examples made from shifting of 1 / (x**2 + 1)
assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*sinh(pi))
assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi))
# Some examples made from 1 / x**2
assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6
assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6
assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12
assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12
@slow
def test_summation_by_residues_failing():
x = Symbol('x')
# Failing because of the bug in residue computation
assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo))
assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0
def test_process_limits():
from sympy.concrete.expr_with_limits import _process_limits
# these should be (x, Range(3)) not Range(3)
raises(ValueError, lambda: _process_limits(
Range(3), discrete=True))
raises(ValueError, lambda: _process_limits(
Range(3), discrete=False))
# these should be (x, union) not union
# (but then we would get a TypeError because we don't
# handle non-contiguous sets: see below use of `union`)
union = Or(x < 1, x > 3).as_set()
raises(ValueError, lambda: _process_limits(
union, discrete=True))
raises(ValueError, lambda: _process_limits(
union, discrete=False))
# error not triggered if not needed
assert _process_limits((x, 1, 2)) == ([(x, 1, 2)], 1)
# this equivalence is used to detect Reals in _process_limits
assert isinstance(S.Reals, Interval)
C = Integral # continuous limits
assert C(x, x >= 5) == C(x, (x, 5, oo))
assert C(x, x < 3) == C(x, (x, -oo, 3))
ans = C(x, (x, 0, 3))
assert C(x, And(x >= 0, x < 3)) == ans
assert C(x, (x, Interval.Ropen(0, 3))) == ans
raises(TypeError, lambda: C(x, (x, Range(3))))
# discrete limits
for D in (Sum, Product):
r, ans = Range(3, 10, 2), D(2*x + 3, (x, 0, 3))
assert D(x, (x, r)) == ans
assert D(x, (x, r.reversed)) == ans
r, ans = Range(3, oo, 2), D(2*x + 3, (x, 0, oo))
assert D(x, (x, r)) == ans
assert D(x, (x, r.reversed)) == ans
r, ans = Range(-oo, 5, 2), D(3 - 2*x, (x, 0, oo))
assert D(x, (x, r)) == ans
assert D(x, (x, r.reversed)) == ans
raises(TypeError, lambda: D(x, x > 0))
raises(ValueError, lambda: D(x, Interval(1, 3)))
raises(NotImplementedError, lambda: D(x, (x, union)))
def test_pr_22677():
b = Symbol('b', integer=True, positive=True)
assert Sum(1/x**2,(x, 0, b)).doit() == Sum(x**(-2), (x, 0, b))
assert Sum(1/(x - b)**2,(x, 0, b-1)).doit() == Sum(
(-b + x)**(-2), (x, 0, b - 1))
def test_issue_23952():
p, q = symbols("p q", real=True, nonnegative=True)
k1, k2 = symbols("k1 k2", integer=True, nonnegative=True)
n = Symbol("n", integer=True, positive=True)
expr = Sum(abs(k1 - k2)*p**k1 *(1 - q)**(n - k2),
(k1, 0, n), (k2, 0, n))
assert expr.subs(p,0).subs(q,1).subs(n, 3).doit() == 3
|
423105f7db18103a9f63b50bcf5aa3413a3a7b494845409f9443818220d84550 | from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial)
from sympy.functions.combinatorial.numbers import (fibonacci, harmonic)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.gamma_functions import gamma
from sympy.series.limitseq import limit_seq
from sympy.series.limitseq import difference_delta as dd
from sympy.testing.pytest import raises, XFAIL
from sympy.calculus.accumulationbounds import AccumulationBounds
n, m, k = symbols('n m k', integer=True)
def test_difference_delta():
e = n*(n + 1)
e2 = e * k
assert dd(e) == 2*n + 2
assert dd(e2, n, 2) == k*(4*n + 6)
raises(ValueError, lambda: dd(e2))
raises(ValueError, lambda: dd(e2, n, oo))
def test_difference_delta__Sum():
e = Sum(1/k, (k, 1, n))
assert dd(e, n) == 1/(n + 1)
assert dd(e, n, 5) == Add(*[1/(i + n + 1) for i in range(5)])
e = Sum(1/k, (k, 1, 3*n))
assert dd(e, n) == Add(*[1/(i + 3*n + 1) for i in range(3)])
e = n * Sum(1/k, (k, 1, n))
assert dd(e, n) == 1 + Sum(1/k, (k, 1, n))
e = Sum(1/k, (k, 1, n), (m, 1, n))
assert dd(e, n) == harmonic(n)
def test_difference_delta__Add():
e = n + n*(n + 1)
assert dd(e, n) == 2*n + 3
assert dd(e, n, 2) == 4*n + 8
e = n + Sum(1/k, (k, 1, n))
assert dd(e, n) == 1 + 1/(n + 1)
assert dd(e, n, 5) == 5 + Add(*[1/(i + n + 1) for i in range(5)])
def test_difference_delta__Pow():
e = 4**n
assert dd(e, n) == 3*4**n
assert dd(e, n, 2) == 15*4**n
e = 4**(2*n)
assert dd(e, n) == 15*4**(2*n)
assert dd(e, n, 2) == 255*4**(2*n)
e = n**4
assert dd(e, n) == (n + 1)**4 - n**4
e = n**n
assert dd(e, n) == (n + 1)**(n + 1) - n**n
def test_limit_seq():
e = binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n))
assert limit_seq(e) == S(3) / 4
assert limit_seq(e, m) == e
e = (5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5)
assert limit_seq(e, n) == S(5) / 3
e = (harmonic(n) * Sum(harmonic(k), (k, 1, n))) / (n * harmonic(2*n)**2)
assert limit_seq(e, n) == 1
e = Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n)
assert limit_seq(e, n) == 4
e = (Sum(binomial(3*k, k) * binomial(5*k, k), (k, 1, n)) /
(binomial(3*n, n) * binomial(5*n, n)))
assert limit_seq(e, n) == S(84375) / 83351
e = Sum(harmonic(k)**2/k, (k, 1, 2*n)) / harmonic(n)**3
assert limit_seq(e, n) == S.One / 3
raises(ValueError, lambda: limit_seq(e * m))
def test_alternating_sign():
assert limit_seq((-1)**n/n**2, n) == 0
assert limit_seq((-2)**(n+1)/(n + 3**n), n) == 0
assert limit_seq((2*n + (-1)**n)/(n + 1), n) == 2
assert limit_seq(sin(pi*n), n) == 0
assert limit_seq(cos(2*pi*n), n) == 1
assert limit_seq((S.NegativeOne/5)**n, n) == 0
assert limit_seq((Rational(-1, 5))**n, n) == 0
assert limit_seq((I/3)**n, n) == 0
assert limit_seq(sqrt(n)*(I/2)**n, n) == 0
assert limit_seq(n**7*(I/3)**n, n) == 0
assert limit_seq(n/(n + 1) + (I/2)**n, n) == 1
def test_accum_bounds():
assert limit_seq((-1)**n, n) == AccumulationBounds(-1, 1)
assert limit_seq(cos(pi*n), n) == AccumulationBounds(-1, 1)
assert limit_seq(sin(pi*n/2)**2, n) == AccumulationBounds(0, 1)
assert limit_seq(2*(-3)**n/(n + 3**n), n) == AccumulationBounds(-2, 2)
assert limit_seq(3*n/(n + 1) + 2*(-1)**n, n) == AccumulationBounds(1, 5)
def test_limitseq_sum():
from sympy.abc import x, y, z
assert limit_seq(Sum(1/x, (x, 1, y)) - log(y), y) == S.EulerGamma
assert limit_seq(Sum(1/x, (x, 1, y)) - 1/y, y) is S.Infinity
assert (limit_seq(binomial(2*x, x) / Sum(binomial(2*y, y), (y, 1, x)), x) ==
S(3) / 4)
assert (limit_seq(Sum(y**2 * Sum(2**z/z, (z, 1, y)), (y, 1, x)) /
(2**x*x), x) == 4)
def test_issue_9308():
assert limit_seq(subfactorial(n)/factorial(n), n) == exp(-1)
def test_issue_10382():
n = Symbol('n', integer=True)
assert limit_seq(fibonacci(n+1)/fibonacci(n), n).together() == S.GoldenRatio
def test_issue_11672():
assert limit_seq(Rational(-1, 2)**n, n) == 0
def test_issue_14196():
k, n = symbols('k, n', positive=True)
m = Symbol('m')
assert limit_seq(Sum(m**k, (m, 1, n)).doit()/(n**(k + 1)), n) == 1/(k + 1)
def test_issue_16735():
assert limit_seq(5**n/factorial(n), n) == 0
def test_issue_19868():
assert limit_seq(1/gamma(n + S.One/2), n) == 0
@XFAIL
def test_limit_seq_fail():
# improve Summation algorithm or add ad-hoc criteria
e = (harmonic(n)**3 * Sum(1/harmonic(k), (k, 1, n)) /
(n * Sum(harmonic(k)/k, (k, 1, n))))
assert limit_seq(e, n) == 2
# No unique dominant term
e = (Sum(2**k * binomial(2*k, k) / k**2, (k, 1, n)) /
(Sum(2**k/k*2, (k, 1, n)) * Sum(binomial(2*k, k), (k, 1, n))))
assert limit_seq(e, n) == S(3) / 7
# Simplifications of summations needs to be improved.
e = n**3*Sum(2**k/k**2, (k, 1, n))**2 / (2**n * Sum(2**k/k, (k, 1, n)))
assert limit_seq(e, n) == 2
e = (harmonic(n) * Sum(2**k/k, (k, 1, n)) /
(n * Sum(2**k*harmonic(k)/k**2, (k, 1, n))))
assert limit_seq(e, n) == 1
e = (Sum(2**k*factorial(k) / k**2, (k, 1, 2*n)) /
(Sum(4**k/k**2, (k, 1, n)) * Sum(factorial(k), (k, 1, 2*n))))
assert limit_seq(e, n) == S(3) / 16
|
091440954d092f28032fba479f17c82d20c043a51b25f68a66b0a501d181d621 | from sympy.core import EulerGamma
from sympy.core.numbers import (E, I, Integer, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (acot, atan, cos, sin)
from sympy.functions.elementary.complexes import sign as _sign
from sympy.functions.special.error_functions import (Ei, erf)
from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma)
from sympy.functions.special.zeta_functions import zeta
from sympy.polys.polytools import cancel
from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh
from sympy.series.gruntz import compare, mrv, rewrite, mrv_leadterm, gruntz, \
sign
from sympy.testing.pytest import XFAIL, skip, slow
"""
This test suite is testing the limit algorithm using the bottom up approach.
See the documentation in limits2.py. The algorithm itself is highly recursive
by nature, so "compare" is logically the lowest part of the algorithm, yet in
some sense it's the most complex part, because it needs to calculate a limit
to return the result.
Nevertheless, the rest of the algorithm depends on compare working correctly.
"""
x = Symbol('x', real=True)
m = Symbol('m', real=True)
runslow = False
def _sskip():
if not runslow:
skip("slow")
@slow
def test_gruntz_evaluation():
# Gruntz' thesis pp. 122 to 123
# 8.1
assert gruntz(exp(x)*(exp(1/x - exp(-x)) - exp(1/x)), x, oo) == -1
# 8.2
assert gruntz(exp(x)*(exp(1/x + exp(-x) + exp(-x**2))
- exp(1/x - exp(-exp(x)))), x, oo) == 1
# 8.3
assert gruntz(exp(exp(x - exp(-x))/(1 - 1/x)) - exp(exp(x)), x, oo) is oo
# 8.5
assert gruntz(exp(exp(exp(x + exp(-x)))) / exp(exp(exp(x))), x, oo) is oo
# 8.6
assert gruntz(exp(exp(exp(x))) / exp(exp(exp(x - exp(-exp(x))))),
x, oo) is oo
# 8.7
assert gruntz(exp(exp(exp(x))) / exp(exp(exp(x - exp(-exp(exp(x)))))),
x, oo) == 1
# 8.8
assert gruntz(exp(exp(x)) / exp(exp(x - exp(-exp(exp(x))))), x, oo) == 1
# 8.9
assert gruntz(log(x)**2 * exp(sqrt(log(x))*(log(log(x)))**2
* exp(sqrt(log(log(x))) * (log(log(log(x))))**3)) / sqrt(x),
x, oo) == 0
# 8.10
assert gruntz((x*log(x)*(log(x*exp(x) - x**2))**2)
/ (log(log(x**2 + 2*exp(exp(3*x**3*log(x)))))), x, oo) == Rational(1, 3)
# 8.11
assert gruntz((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x,
x, oo) == -exp(2)
# 8.12
assert gruntz((3**x + 5**x)**(1/x), x, oo) == 5
# 8.13
assert gruntz(x/log(x**(log(x**(log(2)/log(x))))), x, oo) is oo
# 8.14
assert gruntz(exp(exp(2*log(x**5 + x)*log(log(x))))
/ exp(exp(10*log(x)*log(log(x)))), x, oo) is oo
# 8.15
assert gruntz(exp(exp(Rational(5, 2)*x**Rational(-5, 7) + Rational(21, 8)*x**Rational(6, 11)
+ 2*x**(-8) + Rational(54, 17)*x**Rational(49, 45)))**8
/ log(log(-log(Rational(4, 3)*x**Rational(-5, 14))))**Rational(7, 6), x, oo) is oo
# 8.16
assert gruntz((exp(4*x*exp(-x)/(1/exp(x) + 1/exp(2*x**2/(x + 1)))) - exp(x))
/ exp(x)**4, x, oo) == 1
# 8.17
assert gruntz(exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1))))/exp(x), x, oo) \
== 1
# 8.19
assert gruntz(log(x)*(log(log(x) + log(log(x))) - log(log(x)))
/ (log(log(x) + log(log(log(x))))), x, oo) == 1
# 8.20
assert gruntz(exp((log(log(x + exp(log(x)*log(log(x))))))
/ (log(log(log(exp(x) + x + log(x)))))), x, oo) == E
# Another
assert gruntz(exp(exp(exp(x + exp(-x)))) / exp(exp(x)), x, oo) is oo
def test_gruntz_evaluation_slow():
_sskip()
# 8.4
assert gruntz(exp(exp(exp(x)/(1 - 1/x)))
- exp(exp(exp(x)/(1 - 1/x - log(x)**(-log(x))))), x, oo) is -oo
# 8.18
assert gruntz((exp(exp(-x/(1 + exp(-x))))*exp(-x/(1 + exp(-x/(1 + exp(-x)))))
*exp(exp(-x + exp(-x/(1 + exp(-x))))))
/ (exp(-x/(1 + exp(-x))))**2 - exp(x) + x, x, oo) == 2
@slow
def test_gruntz_eval_special():
# Gruntz, p. 126
assert gruntz(exp(x)*(sin(1/x + exp(-x)) - sin(1/x + exp(-x**2))), x, oo) == 1
assert gruntz((erf(x - exp(-exp(x))) - erf(x)) * exp(exp(x)) * exp(x**2),
x, oo) == -2/sqrt(pi)
assert gruntz(exp(exp(x)) * (exp(sin(1/x + exp(-exp(x)))) - exp(sin(1/x))),
x, oo) == 1
assert gruntz(exp(x)*(gamma(x + exp(-x)) - gamma(x)), x, oo) is oo
assert gruntz(exp(exp(digamma(digamma(x))))/x, x, oo) == exp(Rational(-1, 2))
assert gruntz(exp(exp(digamma(log(x))))/x, x, oo) == exp(Rational(-1, 2))
assert gruntz(digamma(digamma(digamma(x))), x, oo) is oo
assert gruntz(loggamma(loggamma(x)), x, oo) is oo
assert gruntz(((gamma(x + 1/gamma(x)) - gamma(x))/log(x) - cos(1/x))
* x*log(x), x, oo) == Rational(-1, 2)
assert gruntz(x * (gamma(x - 1/gamma(x)) - gamma(x) + log(x)), x, oo) \
== S.Half
assert gruntz((gamma(x + 1/gamma(x)) - gamma(x)) / log(x), x, oo) == 1
def test_gruntz_eval_special_slow():
_sskip()
assert gruntz(gamma(x + 1)/sqrt(2*pi)
- exp(-x)*(x**(x + S.Half) + x**(x - S.Half)/12), x, oo) is oo
assert gruntz(exp(exp(exp(digamma(digamma(digamma(x))))))/x, x, oo) == 0
@XFAIL
def test_grunts_eval_special_slow_sometimes_fail():
_sskip()
# XXX This sometimes fails!!!
assert gruntz(exp(gamma(x - exp(-x))*exp(1/x)) - exp(gamma(x)), x, oo) is oo
def test_gruntz_Ei():
assert gruntz((Ei(x - exp(-exp(x))) - Ei(x)) *exp(-x)*exp(exp(x))*x, x, oo) == -1
@XFAIL
def test_gruntz_eval_special_fail():
# TODO zeta function series
assert gruntz(
exp((log(2) + 1)*x) * (zeta(x + exp(-x)) - zeta(x)), x, oo) == -log(2)
# TODO 8.35 - 8.37 (bessel, max-min)
def test_gruntz_hyperbolic():
assert gruntz(cosh(x), x, oo) is oo
assert gruntz(cosh(x), x, -oo) is oo
assert gruntz(sinh(x), x, oo) is oo
assert gruntz(sinh(x), x, -oo) is -oo
assert gruntz(2*cosh(x)*exp(x), x, oo) is oo
assert gruntz(2*cosh(x)*exp(x), x, -oo) == 1
assert gruntz(2*sinh(x)*exp(x), x, oo) is oo
assert gruntz(2*sinh(x)*exp(x), x, -oo) == -1
assert gruntz(tanh(x), x, oo) == 1
assert gruntz(tanh(x), x, -oo) == -1
assert gruntz(coth(x), x, oo) == 1
assert gruntz(coth(x), x, -oo) == -1
def test_compare1():
assert compare(2, x, x) == "<"
assert compare(x, exp(x), x) == "<"
assert compare(exp(x), exp(x**2), x) == "<"
assert compare(exp(x**2), exp(exp(x)), x) == "<"
assert compare(1, exp(exp(x)), x) == "<"
assert compare(x, 2, x) == ">"
assert compare(exp(x), x, x) == ">"
assert compare(exp(x**2), exp(x), x) == ">"
assert compare(exp(exp(x)), exp(x**2), x) == ">"
assert compare(exp(exp(x)), 1, x) == ">"
assert compare(2, 3, x) == "="
assert compare(3, -5, x) == "="
assert compare(2, -5, x) == "="
assert compare(x, x**2, x) == "="
assert compare(x**2, x**3, x) == "="
assert compare(x**3, 1/x, x) == "="
assert compare(1/x, x**m, x) == "="
assert compare(x**m, -x, x) == "="
assert compare(exp(x), exp(-x), x) == "="
assert compare(exp(-x), exp(2*x), x) == "="
assert compare(exp(2*x), exp(x)**2, x) == "="
assert compare(exp(x)**2, exp(x + exp(-x)), x) == "="
assert compare(exp(x), exp(x + exp(-x)), x) == "="
assert compare(exp(x**2), 1/exp(x**2), x) == "="
def test_compare2():
assert compare(exp(x), x**5, x) == ">"
assert compare(exp(x**2), exp(x)**2, x) == ">"
assert compare(exp(x), exp(x + exp(-x)), x) == "="
assert compare(exp(x + exp(-x)), exp(x), x) == "="
assert compare(exp(x + exp(-x)), exp(-x), x) == "="
assert compare(exp(-x), x, x) == ">"
assert compare(x, exp(-x), x) == "<"
assert compare(exp(x + 1/x), x, x) == ">"
assert compare(exp(-exp(x)), exp(x), x) == ">"
assert compare(exp(exp(-exp(x)) + x), exp(-exp(x)), x) == "<"
def test_compare3():
assert compare(exp(exp(x)), exp(x + exp(-exp(x))), x) == ">"
def test_sign1():
assert sign(Rational(0), x) == 0
assert sign(Rational(3), x) == 1
assert sign(Rational(-5), x) == -1
assert sign(log(x), x) == 1
assert sign(exp(-x), x) == 1
assert sign(exp(x), x) == 1
assert sign(-exp(x), x) == -1
assert sign(3 - 1/x, x) == 1
assert sign(-3 - 1/x, x) == -1
assert sign(sin(1/x), x) == 1
assert sign((x**Integer(2)), x) == 1
assert sign(x**2, x) == 1
assert sign(x**5, x) == 1
def test_sign2():
assert sign(x, x) == 1
assert sign(-x, x) == -1
y = Symbol("y", positive=True)
assert sign(y, x) == 1
assert sign(-y, x) == -1
assert sign(y*x, x) == 1
assert sign(-y*x, x) == -1
def mmrv(a, b):
return set(mrv(a, b)[0].keys())
def test_mrv1():
assert mmrv(x, x) == {x}
assert mmrv(x + 1/x, x) == {x}
assert mmrv(x**2, x) == {x}
assert mmrv(log(x), x) == {x}
assert mmrv(exp(x), x) == {exp(x)}
assert mmrv(exp(-x), x) == {exp(-x)}
assert mmrv(exp(x**2), x) == {exp(x**2)}
assert mmrv(-exp(1/x), x) == {x}
assert mmrv(exp(x + 1/x), x) == {exp(x + 1/x)}
def test_mrv2a():
assert mmrv(exp(x + exp(-exp(x))), x) == {exp(-exp(x))}
assert mmrv(exp(x + exp(-x)), x) == {exp(x + exp(-x)), exp(-x)}
assert mmrv(exp(1/x + exp(-x)), x) == {exp(-x)}
#sometimes infinite recursion due to log(exp(x**2)) not simplifying
def test_mrv2b():
assert mmrv(exp(x + exp(-x**2)), x) == {exp(-x**2)}
#sometimes infinite recursion due to log(exp(x**2)) not simplifying
def test_mrv2c():
assert mmrv(
exp(-x + 1/x**2) - exp(x + 1/x), x) == {exp(x + 1/x), exp(1/x**2 - x)}
#sometimes infinite recursion due to log(exp(x**2)) not simplifying
def test_mrv3():
assert mmrv(exp(x**2) + x*exp(x) + log(x)**x/x, x) == {exp(x**2)}
assert mmrv(
exp(x)*(exp(1/x + exp(-x)) - exp(1/x)), x) == {exp(x), exp(-x)}
assert mmrv(log(
x**2 + 2*exp(exp(3*x**3*log(x)))), x) == {exp(exp(3*x**3*log(x)))}
assert mmrv(log(x - log(x))/log(x), x) == {x}
assert mmrv(
(exp(1/x - exp(-x)) - exp(1/x))*exp(x), x) == {exp(x), exp(-x)}
assert mmrv(
1/exp(-x + exp(-x)) - exp(x), x) == {exp(x), exp(-x), exp(x - exp(-x))}
assert mmrv(log(log(x*exp(x*exp(x)) + 1)), x) == {exp(x*exp(x))}
assert mmrv(exp(exp(log(log(x) + 1/x))), x) == {x}
def test_mrv4():
ln = log
assert mmrv((ln(ln(x) + ln(ln(x))) - ln(ln(x)))/ln(ln(x) + ln(ln(ln(x))))*ln(x),
x) == {x}
assert mmrv(log(log(x*exp(x*exp(x)) + 1)) - exp(exp(log(log(x) + 1/x))), x) == \
{exp(x*exp(x))}
def mrewrite(a, b, c):
return rewrite(a[1], a[0], b, c)
def test_rewrite1():
e = exp(x)
assert mrewrite(mrv(e, x), x, m) == (1/m, -x)
e = exp(x**2)
assert mrewrite(mrv(e, x), x, m) == (1/m, -x**2)
e = exp(x + 1/x)
assert mrewrite(mrv(e, x), x, m) == (1/m, -x - 1/x)
e = 1/exp(-x + exp(-x)) - exp(x)
assert mrewrite(mrv(e, x), x, m) == (1/(m*exp(m)) - 1/m, -x)
def test_rewrite2():
e = exp(x)*log(log(exp(x)))
assert mmrv(e, x) == {exp(x)}
assert mrewrite(mrv(e, x), x, m) == (1/m*log(x), -x)
#sometimes infinite recursion due to log(exp(x**2)) not simplifying
def test_rewrite3():
e = exp(-x + 1/x**2) - exp(x + 1/x)
#both of these are correct and should be equivalent:
assert mrewrite(mrv(e, x), x, m) in [(-1/m + m*exp(
1/x + 1/x**2), -x - 1/x), (m - 1/m*exp(1/x + x**(-2)), x**(-2) - x)]
def test_mrv_leadterm1():
assert mrv_leadterm(-exp(1/x), x) == (-1, 0)
assert mrv_leadterm(1/exp(-x + exp(-x)) - exp(x), x) == (-1, 0)
assert mrv_leadterm(
(exp(1/x - exp(-x)) - exp(1/x))*exp(x), x) == (-exp(1/x), 0)
def test_mrv_leadterm2():
#Gruntz: p51, 3.25
assert mrv_leadterm((log(exp(x) + x) - x)/log(exp(x) + log(x))*exp(x), x) == \
(1, 0)
def test_mrv_leadterm3():
#Gruntz: p56, 3.27
assert mmrv(exp(-x + exp(-x)*exp(-x*log(x))), x) == {exp(-x - x*log(x))}
assert mrv_leadterm(exp(-x + exp(-x)*exp(-x*log(x))), x) == (exp(-x), 0)
def test_limit1():
assert gruntz(x, x, oo) is oo
assert gruntz(x, x, -oo) is -oo
assert gruntz(-x, x, oo) is -oo
assert gruntz(x**2, x, -oo) is oo
assert gruntz(-x**2, x, oo) is -oo
assert gruntz(x*log(x), x, 0, dir="+") == 0
assert gruntz(1/x, x, oo) == 0
assert gruntz(exp(x), x, oo) is oo
assert gruntz(-exp(x), x, oo) is -oo
assert gruntz(exp(x)/x, x, oo) is oo
assert gruntz(1/x - exp(-x), x, oo) == 0
assert gruntz(x + 1/x, x, oo) is oo
def test_limit2():
assert gruntz(x**x, x, 0, dir="+") == 1
assert gruntz((exp(x) - 1)/x, x, 0) == 1
assert gruntz(1 + 1/x, x, oo) == 1
assert gruntz(-exp(1/x), x, oo) == -1
assert gruntz(x + exp(-x), x, oo) is oo
assert gruntz(x + exp(-x**2), x, oo) is oo
assert gruntz(x + exp(-exp(x)), x, oo) is oo
assert gruntz(13 + 1/x - exp(-x), x, oo) == 13
def test_limit3():
a = Symbol('a')
assert gruntz(x - log(1 + exp(x)), x, oo) == 0
assert gruntz(x - log(a + exp(x)), x, oo) == 0
assert gruntz(exp(x)/(1 + exp(x)), x, oo) == 1
assert gruntz(exp(x)/(a + exp(x)), x, oo) == 1
def test_limit4():
#issue 3463
assert gruntz((3**x + 5**x)**(1/x), x, oo) == 5
#issue 3463
assert gruntz((3**(1/x) + 5**(1/x))**x, x, 0) == 5
@XFAIL
def test_MrvTestCase_page47_ex3_21():
h = exp(-x/(1 + exp(-x)))
expr = exp(h)*exp(-x/(1 + h))*exp(exp(-x + h))/h**2 - exp(x) + x
assert mmrv(expr, x) == {1/h, exp(-x), exp(x), exp(x - h), exp(x/(1 + h))}
def test_gruntz_I():
y = Symbol("y")
assert gruntz(I*x, x, oo) == I*oo
assert gruntz(y*I*x, x, oo) == y*I*oo
assert gruntz(y*3*I*x, x, oo) == y*I*oo
assert gruntz(y*3*sin(I)*x, x, oo).simplify().rewrite(_sign) == _sign(y)*I*oo
def test_issue_4814():
assert gruntz((x + 1)**(1/log(x + 1)), x, oo) == E
def test_intractable():
assert gruntz(1/gamma(x), x, oo) == 0
assert gruntz(1/loggamma(x), x, oo) == 0
assert gruntz(gamma(x)/loggamma(x), x, oo) is oo
assert gruntz(exp(gamma(x))/gamma(x), x, oo) is oo
assert gruntz(gamma(x), x, 3) == 2
assert gruntz(gamma(Rational(1, 7) + 1/x), x, oo) == gamma(Rational(1, 7))
assert gruntz(log(x**x)/log(gamma(x)), x, oo) == 1
assert gruntz(log(gamma(gamma(x)))/exp(x), x, oo) is oo
def test_aseries_trig():
assert cancel(gruntz(1/log(atan(x)), x, oo)
- 1/(log(pi) + log(S.Half))) == 0
assert gruntz(1/acot(x), x, -oo) is -oo
def test_exp_log_series():
assert gruntz(x/log(log(x*exp(x))), x, oo) is oo
def test_issue_3644():
assert gruntz(((x**7 + x + 1)/(2**x + x**2))**(-1/x), x, oo) == 2
def test_issue_6843():
n = Symbol('n', integer=True, positive=True)
r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1)
assert gruntz(r, x, 1).simplify() == n/2
def test_issue_4190():
assert gruntz(x - gamma(1/x), x, oo) == S.EulerGamma
@XFAIL
def test_issue_5172():
n = Symbol('n')
r = Symbol('r', positive=True)
c = Symbol('c')
p = Symbol('p', positive=True)
m = Symbol('m', negative=True)
expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c + \
(r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n)
expr = expr.subs(c, c + 1)
assert gruntz(expr.subs(c, m), n, oo) == 1
# fail:
assert gruntz(expr.subs(c, p), n, oo).simplify() == \
(2**(p + 1) + r - 1)/(r + 1)**(p + 1)
def test_issue_4109():
assert gruntz(1/gamma(x), x, 0) == 0
assert gruntz(x*gamma(x), x, 0) == 1
def test_issue_6682():
assert gruntz(exp(2*Ei(-x))/x**2, x, 0) == exp(2*EulerGamma)
def test_issue_7096():
from sympy.functions import sign
assert gruntz(x**-pi, x, 0, dir='-') == oo*sign((-1)**(-pi))
|
936aeac92260e969cf4b0703c90046ef4e356c9c57762619b7e292b3f200b28d | from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.function import (Derivative, Function)
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.hyperbolic import (acosh, asech)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin)
from sympy.functions.special.bessel import airyai
from sympy.functions.special.error_functions import erf
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import integrate
from sympy.series.formal import fps
from sympy.series.order import O
from sympy.series.formal import (rational_algorithm, FormalPowerSeries,
FormalPowerSeriesProduct, FormalPowerSeriesCompose,
FormalPowerSeriesInverse, simpleDE,
rational_independent, exp_re, hyper_re)
from sympy.testing.pytest import raises, XFAIL, slow
x, y, z = symbols('x y z')
n, m, k = symbols('n m k', integer=True)
f, r = Function('f'), Function('r')
def test_rational_algorithm():
f = 1 / ((x - 1)**2 * (x - 2))
assert rational_algorithm(f, x, k) == \
(-2**(-k - 1) + 1 - (factorial(k + 1) / factorial(k)), 0, 0)
f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2))
assert rational_algorithm(f, x, k) == \
(-15*2**(-k - 1) + 4, x + 4, 0)
f = z / (y*m - m*x - y*x + x**2)
assert rational_algorithm(f, x, k) == \
(((-y**(-k - 1)*z) / (y - m)) + ((m**(-k - 1)*z) / (y - m)), 0, 0)
f = x / (1 - x - x**2)
assert rational_algorithm(f, x, k) is None
assert rational_algorithm(f, x, k, full=True) == \
(((Rational(-1, 2) + sqrt(5)/2)**(-k - 1) *
(-sqrt(5)/10 + S.Half)) +
((-sqrt(5)/2 - S.Half)**(-k - 1) *
(sqrt(5)/10 + S.Half)), 0, 0)
f = 1 / (x**2 + 2*x + 2)
assert rational_algorithm(f, x, k) is None
assert rational_algorithm(f, x, k, full=True) == \
((I*(-1 + I)**(-k - 1)) / 2 - (I*(-1 - I)**(-k - 1)) / 2, 0, 0)
f = log(1 + x)
assert rational_algorithm(f, x, k) == \
(-(-1)**(-k) / k, 0, 1)
f = atan(x)
assert rational_algorithm(f, x, k) is None
assert rational_algorithm(f, x, k, full=True) == \
(((I*I**(-k)) / 2 - (I*(-I)**(-k)) / 2) / k, 0, 1)
f = x*atan(x) - log(1 + x**2) / 2
assert rational_algorithm(f, x, k) is None
assert rational_algorithm(f, x, k, full=True) == \
(((I*I**(-k + 1)) / 2 - (I*(-I)**(-k + 1)) / 2) /
(k*(k - 1)), 0, 2)
f = log((1 + x) / (1 - x)) / 2 - atan(x)
assert rational_algorithm(f, x, k) is None
assert rational_algorithm(f, x, k, full=True) == \
((-(-1)**(-k) / 2 - (I*I**(-k)) / 2 + (I*(-I)**(-k)) / 2 +
S.Half) / k, 0, 1)
assert rational_algorithm(cos(x), x, k) is None
def test_rational_independent():
ri = rational_independent
assert ri([], x) == []
assert ri([cos(x), sin(x)], x) == [cos(x), sin(x)]
assert ri([x**2, sin(x), x*sin(x), x**3], x) == \
[x**3 + x**2, x*sin(x) + sin(x)]
assert ri([S.One, x*log(x), log(x), sin(x)/x, cos(x), sin(x), x], x) == \
[x + 1, x*log(x) + log(x), sin(x)/x + sin(x), cos(x)]
def test_simpleDE():
# Tests just the first valid DE
for DE in simpleDE(exp(x), x, f):
assert DE == (-f(x) + Derivative(f(x), x), 1)
break
for DE in simpleDE(sin(x), x, f):
assert DE == (f(x) + Derivative(f(x), x, x), 2)
break
for DE in simpleDE(log(1 + x), x, f):
assert DE == ((x + 1)*Derivative(f(x), x, 2) + Derivative(f(x), x), 2)
break
for DE in simpleDE(asin(x), x, f):
assert DE == (x*Derivative(f(x), x) + (x**2 - 1)*Derivative(f(x), x, x),
2)
break
for DE in simpleDE(exp(x)*sin(x), x, f):
assert DE == (2*f(x) - 2*Derivative(f(x)) + Derivative(f(x), x, x), 2)
break
for DE in simpleDE(((1 + x)/(1 - x))**n, x, f):
assert DE == (2*n*f(x) + (x**2 - 1)*Derivative(f(x), x), 1)
break
for DE in simpleDE(airyai(x), x, f):
assert DE == (-x*f(x) + Derivative(f(x), x, x), 2)
break
def test_exp_re():
d = -f(x) + Derivative(f(x), x)
assert exp_re(d, r, k) == -r(k) + r(k + 1)
d = f(x) + Derivative(f(x), x, x)
assert exp_re(d, r, k) == r(k) + r(k + 2)
d = f(x) + Derivative(f(x), x) + Derivative(f(x), x, x)
assert exp_re(d, r, k) == r(k) + r(k + 1) + r(k + 2)
d = Derivative(f(x), x) + Derivative(f(x), x, x)
assert exp_re(d, r, k) == r(k) + r(k + 1)
d = Derivative(f(x), x, 3) + Derivative(f(x), x, 4) + Derivative(f(x))
assert exp_re(d, r, k) == r(k) + r(k + 2) + r(k + 3)
def test_hyper_re():
d = f(x) + Derivative(f(x), x, x)
assert hyper_re(d, r, k) == r(k) + (k+1)*(k+2)*r(k + 2)
d = -x*f(x) + Derivative(f(x), x, x)
assert hyper_re(d, r, k) == (k + 2)*(k + 3)*r(k + 3) - r(k)
d = 2*f(x) - 2*Derivative(f(x), x) + Derivative(f(x), x, x)
assert hyper_re(d, r, k) == \
(-2*k - 2)*r(k + 1) + (k + 1)*(k + 2)*r(k + 2) + 2*r(k)
d = 2*n*f(x) + (x**2 - 1)*Derivative(f(x), x)
assert hyper_re(d, r, k) == \
k*r(k) + 2*n*r(k + 1) + (-k - 2)*r(k + 2)
d = (x**10 + 4)*Derivative(f(x), x) + x*(x**10 - 1)*Derivative(f(x), x, x)
assert hyper_re(d, r, k) == \
(k*(k - 1) + k)*r(k) + (4*k - (k + 9)*(k + 10) + 40)*r(k + 10)
d = ((x**2 - 1)*Derivative(f(x), x, 3) + 3*x*Derivative(f(x), x, x) +
Derivative(f(x), x))
assert hyper_re(d, r, k) == \
((k*(k - 2)*(k - 1) + 3*k*(k - 1) + k)*r(k) +
(-k*(k + 1)*(k + 2))*r(k + 2))
def test_fps():
assert fps(1) == 1
assert fps(2, x) == 2
assert fps(2, x, dir='+') == 2
assert fps(2, x, dir='-') == 2
assert fps(1/x + 1/x**2) == 1/x + 1/x**2
assert fps(log(1 + x), hyper=False, rational=False) == log(1 + x)
f = fps(x**2 + x + 1)
assert isinstance(f, FormalPowerSeries)
assert f.function == x**2 + x + 1
assert f[0] == 1
assert f[2] == x**2
assert f.truncate(4) == x**2 + x + 1 + O(x**4)
assert f.polynomial() == x**2 + x + 1
f = fps(log(1 + x))
assert isinstance(f, FormalPowerSeries)
assert f.function == log(1 + x)
assert f.subs(x, y) == f
assert f[:5] == [0, x, -x**2/2, x**3/3, -x**4/4]
assert f.as_leading_term(x) == x
assert f.polynomial(6) == x - x**2/2 + x**3/3 - x**4/4 + x**5/5
k = f.ak.variables[0]
assert f.infinite == Sum((-(-1)**(-k)*x**k)/k, (k, 1, oo))
ft, s = f.truncate(n=None), f[:5]
for i, t in enumerate(ft):
if i == 5:
break
assert s[i] == t
f = sin(x).fps(x)
assert isinstance(f, FormalPowerSeries)
assert f.truncate() == x - x**3/6 + x**5/120 + O(x**6)
raises(NotImplementedError, lambda: fps(y*x))
raises(ValueError, lambda: fps(x, dir=0))
@slow
def test_fps__rational():
assert fps(1/x) == (1/x)
assert fps((x**2 + x + 1) / x**3, dir=-1) == (x**2 + x + 1) / x**3
f = 1 / ((x - 1)**2 * (x - 2))
assert fps(f, x).truncate() == \
(Rational(-1, 2) - x*Rational(5, 4) - 17*x**2/8 - 49*x**3/16 - 129*x**4/32 -
321*x**5/64 + O(x**6))
f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2))
assert fps(f, x).truncate() == \
(S.Half + x*Rational(5, 4) + 17*x**2/8 + 49*x**3/16 + 113*x**4/32 +
241*x**5/64 + O(x**6))
f = x / (1 - x - x**2)
assert fps(f, x, full=True).truncate() == \
x + x**2 + 2*x**3 + 3*x**4 + 5*x**5 + O(x**6)
f = 1 / (x**2 + 2*x + 2)
assert fps(f, x, full=True).truncate() == \
S.Half - x/2 + x**2/4 - x**4/8 + x**5/8 + O(x**6)
f = log(1 + x)
assert fps(f, x).truncate() == \
x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
assert fps(f, x, dir=1).truncate() == fps(f, x, dir=-1).truncate()
assert fps(f, x, 2).truncate() == \
(log(3) - Rational(2, 3) - (x - 2)**2/18 + (x - 2)**3/81 -
(x - 2)**4/324 + (x - 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2)))
assert fps(f, x, 2, dir=-1).truncate() == \
(log(3) - Rational(2, 3) - (-x + 2)**2/18 - (-x + 2)**3/81 -
(-x + 2)**4/324 - (-x + 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2)))
f = atan(x)
assert fps(f, x, full=True).truncate() == x - x**3/3 + x**5/5 + O(x**6)
assert fps(f, x, full=True, dir=1).truncate() == \
fps(f, x, full=True, dir=-1).truncate()
assert fps(f, x, 2, full=True).truncate() == \
(atan(2) - Rational(2, 5) - 2*(x - 2)**2/25 + 11*(x - 2)**3/375 -
6*(x - 2)**4/625 + 41*(x - 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2)))
assert fps(f, x, 2, full=True, dir=-1).truncate() == \
(atan(2) - Rational(2, 5) - 2*(-x + 2)**2/25 - 11*(-x + 2)**3/375 -
6*(-x + 2)**4/625 - 41*(-x + 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2)))
f = x*atan(x) - log(1 + x**2) / 2
assert fps(f, x, full=True).truncate() == x**2/2 - x**4/12 + O(x**6)
f = log((1 + x) / (1 - x)) / 2 - atan(x)
assert fps(f, x, full=True).truncate(n=10) == 2*x**3/3 + 2*x**7/7 + O(x**10)
@slow
def test_fps__hyper():
f = sin(x)
assert fps(f, x).truncate() == x - x**3/6 + x**5/120 + O(x**6)
f = cos(x)
assert fps(f, x).truncate() == 1 - x**2/2 + x**4/24 + O(x**6)
f = exp(x)
assert fps(f, x).truncate() == \
1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
f = atan(x)
assert fps(f, x).truncate() == x - x**3/3 + x**5/5 + O(x**6)
f = exp(acos(x))
assert fps(f, x).truncate() == \
(exp(pi/2) - x*exp(pi/2) + x**2*exp(pi/2)/2 - x**3*exp(pi/2)/3 +
5*x**4*exp(pi/2)/24 - x**5*exp(pi/2)/6 + O(x**6))
f = exp(acosh(x))
assert fps(f, x).truncate() == I + x - I*x**2/2 - I*x**4/8 + O(x**6)
f = atan(1/x)
assert fps(f, x).truncate() == pi/2 - x + x**3/3 - x**5/5 + O(x**6)
f = x*atan(x) - log(1 + x**2) / 2
assert fps(f, x, rational=False).truncate() == x**2/2 - x**4/12 + O(x**6)
f = log(1 + x)
assert fps(f, x, rational=False).truncate() == \
x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
f = airyai(x**2)
assert fps(f, x).truncate() == \
(3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) -
3**Rational(2, 3)*x**2/(3*gamma(Rational(1, 3))) + O(x**6))
f = exp(x)*sin(x)
assert fps(f, x).truncate() == x + x**2 + x**3/3 - x**5/30 + O(x**6)
f = exp(x)*sin(x)/x
assert fps(f, x).truncate() == 1 + x + x**2/3 - x**4/30 - x**5/90 + O(x**6)
f = sin(x) * cos(x)
assert fps(f, x).truncate() == x - 2*x**3/3 + 2*x**5/15 + O(x**6)
def test_fps_shift():
f = x**-5*sin(x)
assert fps(f, x).truncate() == \
1/x**4 - 1/(6*x**2) + Rational(1, 120) - x**2/5040 + x**4/362880 + O(x**6)
f = x**2*atan(x)
assert fps(f, x, rational=False).truncate() == \
x**3 - x**5/3 + O(x**6)
f = cos(sqrt(x))*x
assert fps(f, x).truncate() == \
x - x**2/2 + x**3/24 - x**4/720 + x**5/40320 + O(x**6)
f = x**2*cos(sqrt(x))
assert fps(f, x).truncate() == \
x**2 - x**3/2 + x**4/24 - x**5/720 + O(x**6)
def test_fps__Add_expr():
f = x*atan(x) - log(1 + x**2) / 2
assert fps(f, x).truncate() == x**2/2 - x**4/12 + O(x**6)
f = sin(x) + cos(x) - exp(x) + log(1 + x)
assert fps(f, x).truncate() == x - 3*x**2/2 - x**4/4 + x**5/5 + O(x**6)
f = 1/x + sin(x)
assert fps(f, x).truncate() == 1/x + x - x**3/6 + x**5/120 + O(x**6)
f = sin(x) - cos(x) + 1/(x - 1)
assert fps(f, x).truncate() == \
-2 - x**2/2 - 7*x**3/6 - 25*x**4/24 - 119*x**5/120 + O(x**6)
def test_fps__asymptotic():
f = exp(x)
assert fps(f, x, oo) == f
assert fps(f, x, -oo).truncate() == O(1/x**6, (x, oo))
f = erf(x)
assert fps(f, x, oo).truncate() == 1 + O(1/x**6, (x, oo))
assert fps(f, x, -oo).truncate() == -1 + O(1/x**6, (x, oo))
f = atan(x)
assert fps(f, x, oo, full=True).truncate() == \
-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2 + O(1/x**6, (x, oo))
assert fps(f, x, -oo, full=True).truncate() == \
-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2 + O(1/x**6, (x, oo))
f = log(1 + x)
assert fps(f, x, oo) != \
(-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x - log(1/x) +
O(1/x**6, (x, oo)))
assert fps(f, x, -oo) != \
(-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x + I*pi -
log(-1/x) + O(1/x**6, (x, oo)))
def test_fps__fractional():
f = sin(sqrt(x)) / x
assert fps(f, x).truncate() == \
(1/sqrt(x) - sqrt(x)/6 + x**Rational(3, 2)/120 -
x**Rational(5, 2)/5040 + x**Rational(7, 2)/362880 -
x**Rational(9, 2)/39916800 + x**Rational(11, 2)/6227020800 + O(x**6))
f = sin(sqrt(x)) * x
assert fps(f, x).truncate() == \
(x**Rational(3, 2) - x**Rational(5, 2)/6 + x**Rational(7, 2)/120 -
x**Rational(9, 2)/5040 + x**Rational(11, 2)/362880 + O(x**6))
f = atan(sqrt(x)) / x**2
assert fps(f, x).truncate() == \
(x**Rational(-3, 2) - x**Rational(-1, 2)/3 + x**S.Half/5 -
x**Rational(3, 2)/7 + x**Rational(5, 2)/9 - x**Rational(7, 2)/11 +
x**Rational(9, 2)/13 - x**Rational(11, 2)/15 + O(x**6))
f = exp(sqrt(x))
assert fps(f, x).truncate().expand() == \
(1 + x/2 + x**2/24 + x**3/720 + x**4/40320 + x**5/3628800 + sqrt(x) +
x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + x**Rational(7, 2)/5040 +
x**Rational(9, 2)/362880 + x**Rational(11, 2)/39916800 + O(x**6))
f = exp(sqrt(x))*x
assert fps(f, x).truncate().expand() == \
(x + x**2/2 + x**3/24 + x**4/720 + x**5/40320 + x**Rational(3, 2) +
x**Rational(5, 2)/6 + x**Rational(7, 2)/120 + x**Rational(9, 2)/5040 +
x**Rational(11, 2)/362880 + O(x**6))
def test_fps__logarithmic_singularity():
f = log(1 + 1/x)
assert fps(f, x) != \
-log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
assert fps(f, x, rational=False) != \
-log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
@XFAIL
def test_fps__logarithmic_singularity_fail():
f = asech(x) # Algorithms for computing limits probably needs improvemnts
assert fps(f, x) == log(2) - log(x) - x**2/4 - 3*x**4/64 + O(x**6)
def test_fps_symbolic():
f = x**n*sin(x**2)
assert fps(f, x).truncate(8) == x**(n + 2) - x**(n + 6)/6 + O(x**(n + 8), x)
f = x**n*log(1 + x)
fp = fps(f, x)
k = fp.ak.variables[0]
assert fp.infinite == \
Sum((-(-1)**(-k)*x**(k + n))/k, (k, 1, oo))
f = (x - 2)**n*log(1 + x)
assert fps(f, x, 2).truncate() == \
((x - 2)**n*log(3) + (x - 2)**(n + 1)/3 - (x - 2)**(n + 2)/18 + (x - 2)**(n + 3)/81 -
(x - 2)**(n + 4)/324 + (x - 2)**(n + 5)/1215 + O((x - 2)**(n + 6), (x, 2)))
f = x**(n - 2)*cos(x)
assert fps(f, x).truncate() == \
(x**(n - 2) - x**n/2 + x**(n + 2)/24 + O(x**(n + 4), x))
f = x**(n - 2)*sin(x) + x**n*exp(x)
assert fps(f, x).truncate() == \
(x**(n - 1) + x**(n + 1) + x**(n + 2)/2 + x**n +
x**(n + 4)/24 + x**(n + 5)/60 + O(x**(n + 6), x))
f = x**n*atan(x)
assert fps(f, x, oo).truncate() == \
(-x**(n - 5)/5 + x**(n - 3)/3 + x**n*(pi/2 - 1/x) +
O((1/x)**(-n)/x**6, (x, oo)))
f = x**(n/2)*cos(x)
assert fps(f, x).truncate() == \
x**(n/2) - x**(n/2 + 2)/2 + x**(n/2 + 4)/24 + O(x**(n/2 + 6), x)
f = x**(n + m)*sin(x)
assert fps(f, x).truncate() == \
x**(m + n + 1) - x**(m + n + 3)/6 + x**(m + n + 5)/120 + O(x**(m + n + 6), x)
def test_fps__slow():
f = x*exp(x)*sin(2*x) # TODO: rsolve needs improvement
assert fps(f, x).truncate() == 2*x**2 + 2*x**3 - x**4/3 - x**5 + O(x**6)
def test_fps__operations():
f1, f2 = fps(sin(x)), fps(cos(x))
fsum = f1 + f2
assert fsum.function == sin(x) + cos(x)
assert fsum.truncate() == \
1 + x - x**2/2 - x**3/6 + x**4/24 + x**5/120 + O(x**6)
fsum = f1 + 1
assert fsum.function == sin(x) + 1
assert fsum.truncate() == 1 + x - x**3/6 + x**5/120 + O(x**6)
fsum = 1 + f2
assert fsum.function == cos(x) + 1
assert fsum.truncate() == 2 - x**2/2 + x**4/24 + O(x**6)
assert (f1 + x) == Add(f1, x)
assert -f2.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
assert (f1 - f1) is S.Zero
fsub = f1 - f2
assert fsub.function == sin(x) - cos(x)
assert fsub.truncate() == \
-1 + x + x**2/2 - x**3/6 - x**4/24 + x**5/120 + O(x**6)
fsub = f1 - 1
assert fsub.function == sin(x) - 1
assert fsub.truncate() == -1 + x - x**3/6 + x**5/120 + O(x**6)
fsub = 1 - f2
assert fsub.function == -cos(x) + 1
assert fsub.truncate() == x**2/2 - x**4/24 + O(x**6)
raises(ValueError, lambda: f1 + fps(exp(x), dir=-1))
raises(ValueError, lambda: f1 + fps(exp(x), x0=1))
fm = f1 * 3
assert fm.function == 3*sin(x)
assert fm.truncate() == 3*x - x**3/2 + x**5/40 + O(x**6)
fm = 3 * f2
assert fm.function == 3*cos(x)
assert fm.truncate() == 3 - 3*x**2/2 + x**4/8 + O(x**6)
assert (f1 * f2) == Mul(f1, f2)
assert (f1 * x) == Mul(f1, x)
fd = f1.diff()
assert fd.function == cos(x)
assert fd.truncate() == 1 - x**2/2 + x**4/24 + O(x**6)
fd = f2.diff()
assert fd.function == -sin(x)
assert fd.truncate() == -x + x**3/6 - x**5/120 + O(x**6)
fd = f2.diff().diff()
assert fd.function == -cos(x)
assert fd.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
f3 = fps(exp(sqrt(x)))
fd = f3.diff()
assert fd.truncate().expand() == \
(1/(2*sqrt(x)) + S.Half + x/12 + x**2/240 + x**3/10080 + x**4/725760 +
x**5/79833600 + sqrt(x)/4 + x**Rational(3, 2)/48 + x**Rational(5, 2)/1440 +
x**Rational(7, 2)/80640 + x**Rational(9, 2)/7257600 + x**Rational(11, 2)/958003200 +
O(x**6))
assert f1.integrate((x, 0, 1)) == -cos(1) + 1
assert integrate(f1, (x, 0, 1)) == -cos(1) + 1
fi = integrate(f1, x)
assert fi.function == -cos(x)
assert fi.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
fi = f2.integrate(x)
assert fi.function == sin(x)
assert fi.truncate() == x - x**3/6 + x**5/120 + O(x**6)
def test_fps__product():
f1, f2, f3 = fps(sin(x)), fps(exp(x)), fps(cos(x))
raises(ValueError, lambda: f1.product(exp(x), x))
raises(ValueError, lambda: f1.product(fps(exp(x), dir=-1), x, 4))
raises(ValueError, lambda: f1.product(fps(exp(x), x0=1), x, 4))
raises(ValueError, lambda: f1.product(fps(exp(y)), x, 4))
fprod = f1.product(f2, x)
assert isinstance(fprod, FormalPowerSeriesProduct)
assert isinstance(fprod.ffps, FormalPowerSeries)
assert isinstance(fprod.gfps, FormalPowerSeries)
assert fprod.f == sin(x)
assert fprod.g == exp(x)
assert fprod.function == sin(x) * exp(x)
assert fprod._eval_terms(4) == x + x**2 + x**3/3
assert fprod.truncate(4) == x + x**2 + x**3/3 + O(x**4)
assert fprod.polynomial(4) == x + x**2 + x**3/3
raises(NotImplementedError, lambda: fprod._eval_term(5))
raises(NotImplementedError, lambda: fprod.infinite)
raises(NotImplementedError, lambda: fprod._eval_derivative(x))
raises(NotImplementedError, lambda: fprod.integrate(x))
assert f1.product(f3, x)._eval_terms(4) == x - 2*x**3/3
assert f1.product(f3, x).truncate(4) == x - 2*x**3/3 + O(x**4)
def test_fps__compose():
f1, f2, f3 = fps(exp(x)), fps(sin(x)), fps(cos(x))
raises(ValueError, lambda: f1.compose(sin(x), x))
raises(ValueError, lambda: f1.compose(fps(sin(x), dir=-1), x, 4))
raises(ValueError, lambda: f1.compose(fps(sin(x), x0=1), x, 4))
raises(ValueError, lambda: f1.compose(fps(sin(y)), x, 4))
raises(ValueError, lambda: f1.compose(f3, x))
raises(ValueError, lambda: f2.compose(f3, x))
fcomp = f1.compose(f2, x)
assert isinstance(fcomp, FormalPowerSeriesCompose)
assert isinstance(fcomp.ffps, FormalPowerSeries)
assert isinstance(fcomp.gfps, FormalPowerSeries)
assert fcomp.f == exp(x)
assert fcomp.g == sin(x)
assert fcomp.function == exp(sin(x))
assert fcomp._eval_terms(6) == 1 + x + x**2/2 - x**4/8 - x**5/15
assert fcomp.truncate() == 1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
assert fcomp.truncate(5) == 1 + x + x**2/2 - x**4/8 + O(x**5)
raises(NotImplementedError, lambda: fcomp._eval_term(5))
raises(NotImplementedError, lambda: fcomp.infinite)
raises(NotImplementedError, lambda: fcomp._eval_derivative(x))
raises(NotImplementedError, lambda: fcomp.integrate(x))
assert f1.compose(f2, x).truncate(4) == 1 + x + x**2/2 + O(x**4)
assert f1.compose(f2, x).truncate(8) == \
1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8)
assert f1.compose(f2, x).truncate(6) == \
1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
assert f2.compose(f2, x).truncate(4) == x - x**3/3 + O(x**4)
assert f2.compose(f2, x).truncate(8) == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8)
assert f2.compose(f2, x).truncate(6) == x - x**3/3 + x**5/10 + O(x**6)
def test_fps__inverse():
f1, f2, f3 = fps(sin(x)), fps(exp(x)), fps(cos(x))
raises(ValueError, lambda: f1.inverse(x))
finv = f2.inverse(x)
assert isinstance(finv, FormalPowerSeriesInverse)
assert isinstance(finv.ffps, FormalPowerSeries)
raises(ValueError, lambda: finv.gfps)
assert finv.f == exp(x)
assert finv.function == exp(-x)
assert finv._eval_terms(5) == 1 - x + x**2/2 - x**3/6 + x**4/24
assert finv.truncate() == 1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6)
assert finv.truncate(5) == 1 - x + x**2/2 - x**3/6 + x**4/24 + O(x**5)
raises(NotImplementedError, lambda: finv._eval_term(5))
raises(ValueError, lambda: finv.g)
raises(NotImplementedError, lambda: finv.infinite)
raises(NotImplementedError, lambda: finv._eval_derivative(x))
raises(NotImplementedError, lambda: finv.integrate(x))
assert f2.inverse(x).truncate(8) == \
1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + x**6/720 - x**7/5040 + O(x**8)
assert f3.inverse(x).truncate() == 1 + x**2/2 + 5*x**4/24 + O(x**6)
assert f3.inverse(x).truncate(8) == 1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8)
|
67dfb89a7dafe14b3594de37c682279e19b1330c733f094907176bc384f3301f | from sympy.core.evalf import N
from sympy.core.function import (Derivative, Function, PoleError, Subs)
from sympy.core.numbers import (E, Rational, oo, pi, I)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (atan, cos, sin)
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import Integral, integrate
from sympy.series.order import O
from sympy.series.series import series
from sympy.abc import x, y, n, k
from sympy.testing.pytest import raises
def test_sin():
e1 = sin(x).series(x, 0)
e2 = series(sin(x), x, 0)
assert e1 == e2
def test_cos():
e1 = cos(x).series(x, 0)
e2 = series(cos(x), x, 0)
assert e1 == e2
def test_exp():
e1 = exp(x).series(x, 0)
e2 = series(exp(x), x, 0)
assert e1 == e2
def test_exp2():
e1 = exp(cos(x)).series(x, 0)
e2 = series(exp(cos(x)), x, 0)
assert e1 == e2
def test_issue_5223():
assert series(1, x) == 1
assert next(S.Zero.lseries(x)) == 0
assert cos(x).series() == cos(x).series(x)
raises(ValueError, lambda: cos(x + y).series())
raises(ValueError, lambda: x.series(dir=""))
assert (cos(x).series(x, 1) -
cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0
e = cos(x).series(x, 1, n=None)
assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))]
e = cos(x).series(x, 1, n=None, dir='-')
assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)]
# the following test is exact so no need for x -> x - 1 replacement
assert abs(x).series(x, 1, dir='-') == x
assert exp(x).series(x, 1, dir='-', n=3).removeO() == \
E - E*(-x + 1) + E*(-x + 1)**2/2
D = Derivative
assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y
assert next(D(cos(x), x).lseries()) == D(1, x)
assert D(
exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + D(x**3/6, x) + O(x**3)
assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x
assert (1 + x + O(x**2)).getn() == 2
assert (1 + x).getn() is None
raises(PoleError, lambda: ((1/sin(x))**oo).series())
logx = Symbol('logx')
assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \
exp(y*logx) + O(x*exp(y*logx), x)
assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo))
assert abs(x).series(x, oo, n=5, dir='+') == x
assert abs(x).series(x, -oo, n=5, dir='-') == -x
assert abs(-x).series(x, oo, n=5, dir='+') == x
assert abs(-x).series(x, -oo, n=5, dir='-') == -x
assert exp(x*log(x)).series(n=3) == \
1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3)
# XXX is this right? If not, fix "ngot > n" handling in expr.
p = Symbol('p', positive=True)
assert exp(sqrt(p)**3*log(p)).series(n=3) == \
1 + p**S('3/2')*log(p) + O(p**3*log(p)**3)
assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2)
def test_issue_6350():
expr = integrate(exp(k*(y**3 - 3*y)), (y, 0, oo), conds='none')
assert expr.series(k, 0, 3) == -(-1)**(S(2)/3)*sqrt(3)*gamma(S(1)/3)**2*gamma(S(2)/3)/(6*pi*k**(S(1)/3)) - \
sqrt(3)*k*gamma(-S(2)/3)*gamma(-S(1)/3)/(6*pi) - \
(-1)**(S(1)/3)*sqrt(3)*k**(S(1)/3)*gamma(-S(1)/3)*gamma(S(1)/3)*gamma(S(2)/3)/(6*pi) - \
(-1)**(S(2)/3)*sqrt(3)*k**(S(5)/3)*gamma(S(1)/3)**2*gamma(S(2)/3)/(4*pi) - \
(-1)**(S(1)/3)*sqrt(3)*k**(S(7)/3)*gamma(-S(1)/3)*gamma(S(1)/3)*gamma(S(2)/3)/(8*pi) + O(k**3)
def test_issue_11313():
assert Integral(cos(x), x).series(x) == sin(x).series(x)
assert Derivative(sin(x), x).series(x, n=3).doit() == cos(x).series(x, n=3)
assert Derivative(x**3, x).as_leading_term(x) == 3*x**2
assert Derivative(x**3, y).as_leading_term(x) == 0
assert Derivative(sin(x), x).as_leading_term(x) == 1
assert Derivative(cos(x), x).as_leading_term(x) == -x
# This result is equivalent to zero, zero is not return because
# `Expr.series` doesn't currently detect an `x` in its `free_symbol`s.
assert Derivative(1, x).as_leading_term(x) == Derivative(1, x)
assert Derivative(exp(x), x).series(x).doit() == exp(x).series(x)
assert 1 + Integral(exp(x), x).series(x) == exp(x).series(x)
assert Derivative(log(x), x).series(x).doit() == (1/x).series(x)
assert Integral(log(x), x).series(x) == Integral(log(x), x).doit().series(x).removeO()
def test_series_of_Subs():
from sympy.abc import z
subs1 = Subs(sin(x), x, y)
subs2 = Subs(sin(x) * cos(z), x, y)
subs3 = Subs(sin(x * z), (x, z), (y, x))
assert subs1.series(x) == subs1
subs1_series = (Subs(x, x, y) + Subs(-x**3/6, x, y) +
Subs(x**5/120, x, y) + O(y**6))
assert subs1.series() == subs1_series
assert subs1.series(y) == subs1_series
assert subs1.series(z) == subs1
assert subs2.series(z) == (Subs(z**4*sin(x)/24, x, y) +
Subs(-z**2*sin(x)/2, x, y) + Subs(sin(x), x, y) + O(z**6))
assert subs3.series(x).doit() == subs3.doit().series(x)
assert subs3.series(z).doit() == sin(x*y)
raises(ValueError, lambda: Subs(x + 2*y, y, z).series())
assert Subs(x + y, y, z).series(x).doit() == x + z
def test_issue_3978():
f = Function('f')
assert f(x).series(x, 0, 3, dir='-') == \
f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
assert f(x).series(x, 0, 3) == \
f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
assert f(x**2).series(x, 0, 3) == \
f(0) + x**2*Subs(Derivative(f(x), x), x, 0) + O(x**3)
assert f(x**2+1).series(x, 0, 3) == \
f(1) + x**2*Subs(Derivative(f(x), x), x, 1) + O(x**3)
class TestF(Function):
pass
assert TestF(x).series(x, 0, 3) == TestF(0) + \
x*Subs(Derivative(TestF(x), x), x, 0) + \
x**2*Subs(Derivative(TestF(x), x, x), x, 0)/2 + O(x**3)
from sympy.series.acceleration import richardson, shanks
from sympy.concrete.summations import Sum
from sympy.core.numbers import Integer
def test_acceleration():
e = (1 + 1/n)**n
assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10)
A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n))
assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4)
assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10)
def test_issue_5852():
assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \
5*x**4/(24*log(x)**4) + O(x**6)
def test_issue_4583():
assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \
x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \
x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5)
def test_issue_6318():
eq = (1/x)**Rational(2, 3)
assert (eq + 1).as_leading_term(x) == eq
def test_x_is_base_detection():
eq = (x**2)**Rational(2, 3)
assert eq.series() == x**Rational(4, 3)
def test_issue_7203():
assert series(cos(x), x, pi, 3) == \
-1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi))
def test_exp_product_positive_factors():
a, b = symbols('a, b', positive=True)
x = a * b
assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \
a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \
a**7*b**7/5040 + O(a**8*b**8, a, b)
def test_issue_8805():
assert series(1, n=8) == 1
def test_issue_9549():
y = (x**2 + x + 1) / (x**3 + x**2)
assert series(y, x, oo) == x**(-5) - 1/x**4 + x**(-3) + 1/x + O(x**(-6), (x, oo))
def test_issue_10761():
assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6)
def test_issue_12578():
y = (1 - 1/(x/2 - 1/(2*x))**4)**(S(1)/8)
assert y.series(x, 0, n=17) == 1 - 2*x**4 - 8*x**6 - 34*x**8 - 152*x**10 - 714*x**12 - \
3472*x**14 - 17318*x**16 + O(x**17)
def test_issue_12791():
beta = symbols('beta', positive=True)
theta, varphi = symbols('theta varphi', real=True)
expr = (-beta**2*varphi*sin(theta) + beta**2*cos(theta) + \
beta*varphi*sin(theta) - beta*cos(theta) - beta + 1)/(beta*cos(theta) - 1)**2
sol = 0.5/(0.5*cos(theta) - 1.0)**2 - 0.25*cos(theta)/(0.5*cos(theta)\
- 1.0)**2 + (beta - 0.5)*(-0.25*varphi*sin(2*theta) - 1.5*cos(theta)\
+ 0.25*cos(2*theta) + 1.25)/(0.5*cos(theta) - 1.0)**3\
+ 0.25*varphi*sin(theta)/(0.5*cos(theta) - 1.0)**2 + O((beta - S.Half)**2, (beta, S.Half))
assert expr.series(beta, 0.5, 2).trigsimp() == sol
def test_issue_14384():
x, a = symbols('x a')
assert series(x**a, x) == x**a
assert series(x**(-2*a), x) == x**(-2*a)
assert series(exp(a*log(x)), x) == exp(a*log(x))
assert series(x**I, x) == x**I
assert series(x**(I + 1), x) == x**(1 + I)
assert series(exp(I*log(x)), x) == exp(I*log(x))
def test_issue_14885():
assert series(x**Rational(-3, 2)*exp(x), x, 0) == (x**Rational(-3, 2) + 1/sqrt(x) +
sqrt(x)/2 + x**Rational(3, 2)/6 + x**Rational(5, 2)/24 + x**Rational(7, 2)/120 +
x**Rational(9, 2)/720 + x**Rational(11, 2)/5040 + O(x**6))
def test_issue_15539():
assert series(atan(x), x, -oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2
+ O(x**(-6), (x, -oo)))
assert series(atan(x), x, oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2
+ O(x**(-6), (x, oo)))
def test_issue_7259():
assert series(LambertW(x), x) == x - x**2 + 3*x**3/2 - 8*x**4/3 + 125*x**5/24 + O(x**6)
assert series(LambertW(x**2), x, n=8) == x**2 - x**4 + 3*x**6/2 + O(x**8)
assert series(LambertW(sin(x)), x, n=4) == x - x**2 + 4*x**3/3 + O(x**4)
def test_issue_11884():
assert cos(x).series(x, 1, n=1) == cos(1) + O(x - 1, (x, 1))
def test_issue_18008():
y = x*(1 + x*(1 - x))/((1 + x*(1 - x)) - (1 - x)*(1 - x))
assert y.series(x, oo, n=4) == -9/(32*x**3) - 3/(16*x**2) - 1/(8*x) + S(1)/4 + x/2 + \
O(x**(-4), (x, oo))
def test_issue_18842():
f = log(x/(1 - x))
assert f.series(x, 0.491, n=1).removeO().nsimplify() == \
-S(180019443780011)/5000000000000000
def test_issue_19534():
dt = symbols('dt', real=True)
expr = 16*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0)/45 + \
49*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.051640768506639183825*dt + \
dt*(1/2 - sqrt(21)/14) + 1.0)/180 + 49*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + \
2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
1.1854881643947648988*dt + dt*(sqrt(21)/14 + 1/2) + 1.0)/180 + \
dt*(0.66666666666666666667*dt*(2.0*dt + 1.0) + \
6.0173399699313066769*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
4.1117044797036320069*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) - \
7.0189140975801991157*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) + \
0.94010945196161777522*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + \
2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
0.35816132904077632692*dt + 1.0) + 5.5065024887242400038*dt + 1.0)/20 + dt/20 + 1
assert N(expr.series(dt, 0, 8), 20) == -0.00092592592592592596126*dt**7 + 0.0027777777777777783175*dt**6 + \
0.016666666666666656027*dt**5 + 0.083333333333333300952*dt**4 + 0.33333333333333337034*dt**3 + \
1.0*dt**2 + 1.0*dt + 1.0
def test_issue_11407():
a, b, c, x = symbols('a b c x')
assert series(sqrt(a + b + c*x), x, 0, 1) == sqrt(a + b) + O(x)
assert series(sqrt(a + b + c + c*x), x, 0, 1) == sqrt(a + b + c) + O(x)
def test_issue_14037():
assert (sin(x**50)/x**51).series(x, n=0) == 1/x + O(1, x)
def test_issue_20551():
expr = (exp(x)/x).series(x, n=None)
terms = [ next(expr) for i in range(3) ]
assert terms == [1/x, 1, x/2]
def test_issue_20697():
p_0, p_1, p_2, p_3, b_0, b_1, b_2 = symbols('p_0 p_1 p_2 p_3 b_0 b_1 b_2')
Q = (p_0 + (p_1 + (p_2 + p_3/y)/y)/y)/(1 + ((p_3/(b_0*y) + (b_0*p_2\
- b_1*p_3)/b_0**2)/y + (b_0**2*p_1 - b_0*b_1*p_2 - p_3*(b_0*b_2\
- b_1**2))/b_0**3)/y)
assert Q.series(y, n=3).ratsimp() == b_2*y**2 + b_1*y + b_0 + O(y**3)
def test_issue_21245():
fi = (1 + sqrt(5))/2
assert (1/(1 - x - x**2)).series(x, 1/fi, 1).factor() == \
(-4812 - 2152*sqrt(5) + 1686*x + 754*sqrt(5)*x\
+ O((x - 2/(1 + sqrt(5)))**2, (x, 2/(1 + sqrt(5)))))/((1 + sqrt(5))\
*(20 + 9*sqrt(5))**2*(x + sqrt(5)*x - 2))
def test_issue_21938():
expr = sin(1/x + exp(-x)) - sin(1/x)
assert expr.series(x, oo) == (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
def test_issue_23432():
expr = 1/sqrt(1 - x**2)
result = expr.series(x, 0.5)
assert result.is_Add and len(result.args) == 7
def test_issue_23727():
res = series(sqrt(1 - x**2), x, 0.1)
assert res.is_Add == True
|
467e60bc3635f918d79f4d58239be51b1070ea7263de1c3e5bfe91db994fcf89 | from itertools import product
from sympy.concrete.summations import Sum
from sympy.core.function import (Function, diff)
from sympy.core import EulerGamma
from sympy.core.numbers import (E, I, Rational, oo, pi, zoo)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial)
from sympy.functions.elementary.complexes import (Abs, re, sign)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (acosh, acoth, acsch, asech, atanh, sinh)
from sympy.functions.elementary.integers import (ceiling, floor, frac)
from sympy.functions.elementary.miscellaneous import (cbrt, real_root, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin,
atan, cos, cot, csc, sec, sin, tan)
from sympy.functions.special.bessel import (besseli, bessely, besselj, besselk)
from sympy.functions.special.error_functions import (Ei, erf, erfc, erfi, fresnelc, fresnels)
from sympy.functions.special.gamma_functions import (digamma, gamma, uppergamma)
from sympy.functions.special.hyper import meijerg
from sympy.integrals.integrals import (Integral, integrate)
from sympy.series.limits import (Limit, limit)
from sympy.simplify.simplify import (logcombine, simplify)
from sympy.simplify.hyperexpand import hyperexpand
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.core.mul import Mul
from sympy.series.limits import heuristics
from sympy.series.order import Order
from sympy.testing.pytest import XFAIL, raises
from sympy.abc import x, y, z, k
n = Symbol('n', integer=True, positive=True)
def test_basic1():
assert limit(x, x, oo) is oo
assert limit(x, x, -oo) is -oo
assert limit(-x, x, oo) is -oo
assert limit(x**2, x, -oo) is oo
assert limit(-x**2, x, oo) is -oo
assert limit(x*log(x), x, 0, dir="+") == 0
assert limit(1/x, x, oo) == 0
assert limit(exp(x), x, oo) is oo
assert limit(-exp(x), x, oo) is -oo
assert limit(exp(x)/x, x, oo) is oo
assert limit(1/x - exp(-x), x, oo) == 0
assert limit(x + 1/x, x, oo) is oo
assert limit(x - x**2, x, oo) is -oo
assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1
assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0)
assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-')
assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((1 + x + y)**oo, x, 0, dir='-')
assert limit(y/x/log(x), x, 0) == -oo*sign(y)
assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo
assert limit(gamma(1/x + 3), x, oo) == 2
assert limit(S.NaN, x, -oo) is S.NaN
assert limit(Order(2)*x, x, S.NaN) is S.NaN
assert limit(1/(x - 1), x, 1, dir="+") is oo
assert limit(1/(x - 1), x, 1, dir="-") is -oo
assert limit(1/(5 - x)**3, x, 5, dir="+") is -oo
assert limit(1/(5 - x)**3, x, 5, dir="-") is oo
assert limit(1/sin(x), x, pi, dir="+") is -oo
assert limit(1/sin(x), x, pi, dir="-") is oo
assert limit(1/cos(x), x, pi/2, dir="+") is -oo
assert limit(1/cos(x), x, pi/2, dir="-") is oo
assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="+") is oo
assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="-") is -oo
assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="+") is -oo
assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="-") is oo
assert limit(tan(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert limit(cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert limit(sec(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert limit(csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
# test bi-directional limits
assert limit(sin(x)/x, x, 0, dir="+-") == 1
assert limit(x**2, x, 0, dir="+-") == 0
assert limit(1/x**2, x, 0, dir="+-") is oo
# test failing bi-directional limits
assert limit(1/x, x, 0, dir="+-") is zoo
# approaching 0
# from dir="+"
assert limit(1 + 1/x, x, 0) is oo
# from dir='-'
# Add
assert limit(1 + 1/x, x, 0, dir='-') is -oo
# Pow
assert limit(x**(-2), x, 0, dir='-') is oo
assert limit(x**(-3), x, 0, dir='-') is -oo
assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I
assert limit(x**2, x, 0, dir='-') == 0
assert limit(sqrt(x), x, 0, dir='-') == 0
assert limit(x**-pi, x, 0, dir='-') == oo/(-1)**pi
assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0)
# test pull request 22491
assert limit(1/asin(x), x, 0, dir = '+') == oo
assert limit(1/asin(x), x, 0, dir = '-') == -oo
assert limit(1/sinh(x), x, 0, dir = '+') == oo
assert limit(1/sinh(x), x, 0, dir = '-') == -oo
assert limit(log(1/x) + 1/sin(x), x, 0, dir = '+') == oo
assert limit(log(1/x) + 1/x, x, 0, dir = '+') == oo
def test_basic2():
assert limit(x**x, x, 0, dir="+") == 1
assert limit((exp(x) - 1)/x, x, 0) == 1
assert limit(1 + 1/x, x, oo) == 1
assert limit(-exp(1/x), x, oo) == -1
assert limit(x + exp(-x), x, oo) is oo
assert limit(x + exp(-x**2), x, oo) is oo
assert limit(x + exp(-exp(x)), x, oo) is oo
assert limit(13 + 1/x - exp(-x), x, oo) == 13
def test_basic3():
assert limit(1/x, x, 0, dir="+") is oo
assert limit(1/x, x, 0, dir="-") is -oo
def test_basic4():
assert limit(2*x + y*x, x, 0) == 0
assert limit(2*x + y*x, x, 1) == 2 + y
assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8
assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0
assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9
def test_log():
# https://github.com/sympy/sympy/issues/21598
a, b, c = symbols('a b c', positive=True)
A = log(a/b) - (log(a) - log(b))
assert A.limit(a, oo) == 0
assert (A * c).limit(a, oo) == 0
tau, x = symbols('tau x', positive=True)
# The value of manualintegrate in the issue
expr = tau**2*((tau - 1)*(tau + 1)*log(x + 1)/(tau**2 + 1)**2 + 1/((tau**2\
+ 1)*(x + 1)) - (-2*tau*atan(x/tau) + (tau**2/2 - 1/2)*log(tau**2\
+ x**2))/(tau**2 + 1)**2)
assert limit(expr, x, oo) == pi*tau**3/(tau**2 + 1)**2
def test_piecewise():
# https://github.com/sympy/sympy/issues/18363
assert limit((real_root(x - 6, 3) + 2)/(x + 2), x, -2, '+') == Rational(1, 12)
def test_piecewise2():
func1 = 2*sqrt(x)*Piecewise(((4*x - 2)/Abs(sqrt(4 - 4*(2*x - 1)**2)), 4*x - 2\
>= 0), ((2 - 4*x)/Abs(sqrt(4 - 4*(2*x - 1)**2)), True))
func2 = Piecewise((x**2/2, x <= 0.5), (x/2 - 0.125, True))
func3 = Piecewise(((x - 9) / 5, x < -1), ((x - 9) / 5, x > 4), (sqrt(Abs(x - 3)), True))
assert limit(func1, x, 0) == 1
assert limit(func2, x, 0) == 0
assert limit(func3, x, -1) == 2
def test_basic5():
class my(Function):
@classmethod
def eval(cls, arg):
if arg is S.Infinity:
return S.NaN
assert limit(my(x), x, oo) == Limit(my(x), x, oo)
def test_issue_3885():
assert limit(x*y + x*z, z, 2) == x*y + 2*x
def test_Limit():
assert Limit(sin(x)/x, x, 0) != 1
assert Limit(sin(x)/x, x, 0).doit() == 1
assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-'))
def test_floor():
assert limit(floor(x), x, -2, "+") == -2
assert limit(floor(x), x, -2, "-") == -3
assert limit(floor(x), x, -1, "+") == -1
assert limit(floor(x), x, -1, "-") == -2
assert limit(floor(x), x, 0, "+") == 0
assert limit(floor(x), x, 0, "-") == -1
assert limit(floor(x), x, 1, "+") == 1
assert limit(floor(x), x, 1, "-") == 0
assert limit(floor(x), x, 2, "+") == 2
assert limit(floor(x), x, 2, "-") == 1
assert limit(floor(x), x, 248, "+") == 248
assert limit(floor(x), x, 248, "-") == 247
# https://github.com/sympy/sympy/issues/14478
assert limit(x*floor(3/x)/2, x, 0, '+') == Rational(3, 2)
assert limit(floor(x + 1/2) - floor(x), x, oo) == AccumBounds(-S.Half, S(3)/2)
# test issue 9158
assert limit(floor(atan(x)), x, oo) == 1
assert limit(floor(atan(x)), x, -oo) == -2
assert limit(ceiling(atan(x)), x, oo) == 2
assert limit(ceiling(atan(x)), x, -oo) == -1
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 test_ceiling():
assert limit(ceiling(x), x, -2, "+") == -1
assert limit(ceiling(x), x, -2, "-") == -2
assert limit(ceiling(x), x, -1, "+") == 0
assert limit(ceiling(x), x, -1, "-") == -1
assert limit(ceiling(x), x, 0, "+") == 1
assert limit(ceiling(x), x, 0, "-") == 0
assert limit(ceiling(x), x, 1, "+") == 2
assert limit(ceiling(x), x, 1, "-") == 1
assert limit(ceiling(x), x, 2, "+") == 3
assert limit(ceiling(x), x, 2, "-") == 2
assert limit(ceiling(x), x, 248, "+") == 249
assert limit(ceiling(x), x, 248, "-") == 248
# https://github.com/sympy/sympy/issues/14478
assert limit(x*ceiling(3/x)/2, x, 0, '+') == Rational(3, 2)
assert limit(ceiling(x + 1/2) - ceiling(x), x, oo) == AccumBounds(-S.Half, S(3)/2)
def test_ceiling_requires_robust_assumptions():
assert limit(ceiling(sin(x)), x, 0, "+") == 1
assert limit(ceiling(sin(x)), x, 0, "-") == 0
assert limit(ceiling(cos(x)), x, 0, "+") == 1
assert limit(ceiling(cos(x)), x, 0, "-") == 1
assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6
assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5
assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6
assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6
def test_frac():
assert limit(frac(x), x, oo) == AccumBounds(0, 1)
assert limit(frac(x)**(1/x), x, oo) == AccumBounds(0, 1)
assert limit(frac(x)**(1/x), x, -oo) == AccumBounds(1, oo)
assert limit(frac(x)**x, x, oo) == AccumBounds(0, oo) # wolfram gives (0, 1)
assert limit(frac(sin(x)), x, 0, "+") == 0
assert limit(frac(sin(x)), x, 0, "-") == 1
assert limit(frac(cos(x)), x, 0, "+-") == 1
assert limit(frac(x**2), x, 0, "+-") == 0
raises(ValueError, lambda: limit(frac(x), x, 0, '+-'))
assert limit(frac(-2*x + 1), x, 0, "+") == 1
assert limit(frac(-2*x + 1), x, 0, "-") == 0
assert limit(frac(x + S.Half), x, 0, "+-") == 1/2
assert limit(frac(1/x), x, 0) == AccumBounds(0, 1)
def test_issue_14355():
assert limit(floor(sin(x)/x), x, 0, '+') == 0
assert limit(floor(sin(x)/x), x, 0, '-') == 0
# test comment https://github.com/sympy/sympy/issues/14355#issuecomment-372121314
assert limit(floor(-tan(x)/x), x, 0, '+') == -2
assert limit(floor(-tan(x)/x), x, 0, '-') == -2
def test_atan():
x = Symbol("x", real=True)
assert limit(atan(x)*sin(1/x), x, 0) == 0
assert limit(atan(x) + sqrt(x + 1) - sqrt(x), x, oo) == pi/2
def test_set_signs():
assert limit(abs(x), x, 0) == 0
assert limit(abs(sin(x)), x, 0) == 0
assert limit(abs(cos(x)), x, 0) == 1
assert limit(abs(sin(x + 1)), x, 0) == sin(1)
# https://github.com/sympy/sympy/issues/9449
assert limit((Abs(x + y) - Abs(x - y))/(2*x), x, 0) == sign(y)
# https://github.com/sympy/sympy/issues/12398
assert limit(Abs(log(x)/x**3), x, oo) == 0
assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3
# https://github.com/sympy/sympy/issues/18501
assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo
# https://github.com/sympy/sympy/issues/18997
assert limit(Abs(log(x)), x, 0) == oo
assert limit(Abs(log(Abs(x))), x, 0) == oo
# https://github.com/sympy/sympy/issues/19026
z = Symbol('z', positive=True)
assert limit(Abs(log(z) + 1)/log(z), z, oo) == 1
# https://github.com/sympy/sympy/issues/20704
assert limit(z*(Abs(1/z + y) - Abs(y - 1/z))/2, z, 0) == 0
# https://github.com/sympy/sympy/issues/21606
assert limit(cos(z)/sign(z), z, pi, '-') == -1
def test_heuristic():
x = Symbol("x", real=True)
assert heuristics(sin(1/x) + atan(x), x, 0, '+') == AccumBounds(-1, 1)
assert limit(log(2 + sqrt(atan(x))*sqrt(sin(1/x))), x, 0) == log(2)
def test_issue_3871():
z = Symbol("z", positive=True)
f = -1/z*exp(-z*x)
assert limit(f, x, oo) == 0
assert f.limit(x, oo) == 0
def test_exponential():
n = Symbol('n')
x = Symbol('x', real=True)
assert limit((1 + x/n)**n, n, oo) == exp(x)
assert limit((1 + x/(2*n))**n, n, oo) == exp(x/2)
assert limit((1 + x/(2*n + 1))**n, n, oo) == exp(x/2)
assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2)
assert limit(1 + (1 + 1/x)**x, x, oo) == 1 + S.Exp1
assert limit((2 + 6*x)**x/(6*x)**x, x, oo) == exp(S('1/3'))
def test_exponential2():
n = Symbol('n')
assert limit((1 + x/(n + sin(n)))**n, n, oo) == exp(x)
def test_doit():
f = Integral(2 * x, x)
l = Limit(f, x, oo)
assert l.doit() is oo
def test_series_AccumBounds():
assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2)
assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3)
# not the exact bound
assert limit(sin(k) - sin(k)*cos(k), k, oo) == AccumBounds(-2, 2)
# test for issue #9934
lo = (-3 + cos(1))/2
hi = (1 + cos(1))/2
t1 = Mul(AccumBounds(lo, hi), 1/(-1 + cos(1)), evaluate=False)
assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1
t2 = Mul(AccumBounds(-1 + sin(1)/2, sin(1)/2 + 1), 1/(1 - cos(1)))
assert limit(simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t2
assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo) # wolfram says 0
# https://github.com/sympy/sympy/issues/12312
e = 2**(-x)*(sin(x) + 1)**x
assert limit(e, x, oo) == AccumBounds(0, oo)
def test_bessel_functions_at_infinity():
# Pull Request 23844 implements limits for all bessel and modified bessel
# functions approaching infinity along any direction i.e. abs(z0) tends to oo
assert limit(besselj(1, x), x, oo) == 0
assert limit(besselj(1, x), x, -oo) == 0
assert limit(besselj(1, x), x, I*oo) == oo*I
assert limit(besselj(1, x), x, -I*oo) == -oo*I
assert limit(bessely(1, x), x, oo) == 0
assert limit(bessely(1, x), x, -oo) == 0
assert limit(bessely(1, x), x, I*oo) == -oo
assert limit(bessely(1, x), x, -I*oo) == -oo
assert limit(besseli(1, x), x, oo) == oo
assert limit(besseli(1, x), x, -oo) == -oo
assert limit(besseli(1, x), x, I*oo) == 0
assert limit(besseli(1, x), x, -I*oo) == 0
assert limit(besselk(1, x), x, oo) == 0
assert limit(besselk(1, x), x, -oo) == -oo*I
assert limit(besselk(1, x), x, I*oo) == 0
assert limit(besselk(1, x), x, -I*oo) == 0
# test issue 14874
assert limit(besselk(0, x), x, oo) == 0
@XFAIL
def test_doit2():
f = Integral(2 * x, x)
l = Limit(f, x, oo)
# limit() breaks on the contained Integral.
assert l.doit(deep=False) == l
def test_issue_2929():
assert limit((x * exp(x))/(exp(x) - 1), x, -oo) == 0
def test_issue_3792():
assert limit((1 - cos(x))/x**2, x, S.Half) == 4 - 4*cos(S.Half)
assert limit(sin(sin(x + 1) + 1), x, 0) == sin(1 + sin(1))
assert limit(abs(sin(x + 1) + 1), x, 0) == 1 + sin(1)
def test_issue_4090():
assert limit(1/(x + 3), x, 2) == Rational(1, 5)
assert limit(1/(x + pi), x, 2) == S.One/(2 + pi)
assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7
assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi)
def test_issue_4547():
assert limit(cot(x), x, 0, dir='+') is oo
assert limit(cot(x), x, pi/2, dir='+') == 0
def test_issue_5164():
assert limit(x**0.5, x, oo) == oo**0.5 is oo
assert limit(x**0.5, x, 16) == S(16)**0.5
assert limit(x**0.5, x, 0) == 0
assert limit(x**(-0.5), x, oo) == 0
assert limit(x**(-0.5), x, 4) == S(4)**(-0.5)
def test_issue_5383():
func = (1.0 * 1 + 1.0 * x)**(1.0 * 1 / x)
assert limit(func, x, 0) == E
def test_issue_14793():
expr = ((x + S(1)/2) * log(x) - x + log(2*pi)/2 - \
log(factorial(x)) + S(1)/(12*x))*x**3
assert limit(expr, x, oo) == S(1)/360
def test_issue_5183():
# using list(...) so py.test can recalculate values
tests = list(product([x, -x],
[-1, 1],
[2, 3, S.Half, Rational(2, 3)],
['-', '+']))
results = (oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), oo,
0, 0, 0, 0, 0, 0, 0, 0,
oo, oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3),
0, 0, 0, 0, 0, 0, 0, 0)
assert len(tests) == len(results)
for i, (args, res) in enumerate(zip(tests, results)):
y, s, e, d = args
eq = y**(s*e)
try:
assert limit(eq, x, 0, dir=d) == res
except AssertionError:
if 0: # change to 1 if you want to see the failing tests
print()
print(i, res, eq, d, limit(eq, x, 0, dir=d))
else:
assert None
def test_issue_5184():
assert limit(sin(x)/x, x, oo) == 0
assert limit(atan(x), x, oo) == pi/2
assert limit(gamma(x), x, oo) is oo
assert limit(cos(x)/x, x, oo) == 0
assert limit(gamma(x), x, S.Half) == sqrt(pi)
r = Symbol('r', real=True)
assert limit(r*sin(1/r), r, 0) == 0
def test_issue_5229():
assert limit((1 + y)**(1/y) - S.Exp1, y, 0) == 0
def test_issue_4546():
# using list(...) so py.test can recalculate values
tests = list(product([cot, tan],
[-pi/2, 0, pi/2, pi, pi*Rational(3, 2)],
['-', '+']))
results = (0, 0, -oo, oo, 0, 0, -oo, oo, 0, 0,
oo, -oo, 0, 0, oo, -oo, 0, 0, oo, -oo)
assert len(tests) == len(results)
for i, (args, res) in enumerate(zip(tests, results)):
f, l, d = args
eq = f(x)
try:
assert limit(eq, x, l, dir=d) == res
except AssertionError:
if 0: # change to 1 if you want to see the failing tests
print()
print(i, res, eq, l, d, limit(eq, x, l, dir=d))
else:
assert None
def test_issue_3934():
assert limit((1 + x**log(3))**(1/x), x, 0) == 1
assert limit((5**(1/x) + 3**(1/x))**x, x, 0) == 5
def test_calculate_series():
# NOTE
# The calculate_series method is being deprecated and is no longer responsible
# for result being returned. The mrv_leadterm function now uses simple leadterm
# calls rather than calculate_series.
# needs gruntz calculate_series to go to n = 32
assert limit(x**Rational(77, 3)/(1 + x**Rational(77, 3)), x, oo) == 1
# needs gruntz calculate_series to go to n = 128
assert limit(x**101.1/(1 + x**101.1), x, oo) == 1
def test_issue_5955():
assert limit((x**16)/(1 + x**16), x, oo) == 1
assert limit((x**100)/(1 + x**100), x, oo) == 1
assert limit((x**1885)/(1 + x**1885), x, oo) == 1
assert limit((x**1000/((x + 1)**1000 + exp(-x))), x, oo) == 1
def test_newissue():
assert limit(exp(1/sin(x))/exp(cot(x)), x, 0) == 1
def test_extended_real_line():
assert limit(x - oo, x, oo) == Limit(x - oo, x, oo)
assert limit(1/(x + sin(x)) - oo, x, 0) == Limit(1/(x + sin(x)) - oo, x, 0)
assert limit(oo/x, x, oo) == Limit(oo/x, x, oo)
assert limit(x - oo + 1/x, x, oo) == Limit(x - oo + 1/x, x, oo)
@XFAIL
def test_order_oo():
x = Symbol('x', positive=True)
assert Order(x)*oo != Order(1, x)
assert limit(oo/(x**2 - 4), x, oo) is oo
def test_issue_5436():
raises(NotImplementedError, lambda: limit(exp(x*y), x, oo))
raises(NotImplementedError, lambda: limit(exp(-x*y), x, oo))
def test_Limit_dir():
raises(TypeError, lambda: Limit(x, x, 0, dir=0))
raises(ValueError, lambda: Limit(x, x, 0, dir='0'))
def test_polynomial():
assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, oo) == 1
assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, -oo) == 1
def test_rational():
assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, oo) == (z - 1)/(y*z)
assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, -oo) == (z - 1)/(y*z)
def test_issue_5740():
assert limit(log(x)*z - log(2*x)*y, x, 0) == oo*sign(y - z)
def test_issue_6366():
n = Symbol('n', integer=True, positive=True)
r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1)
assert limit(r, x, 1).cancel() == n/2
def test_factorial():
f = factorial(x)
assert limit(f, x, oo) is oo
assert limit(x/f, x, oo) == 0
# see Stirling's approximation:
# https://en.wikipedia.org/wiki/Stirling's_approximation
assert limit(f/(sqrt(2*pi*x)*(x/E)**x), x, oo) == 1
assert limit(f, x, -oo) == gamma(-oo)
def test_issue_6560():
e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) +
35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1)))
assert limit(e, y, oo) == 5*x**3/4 + 3*x**2/4 - 3*x/4 - Rational(1, 4)
@XFAIL
def test_issue_5172():
n = Symbol('n')
r = Symbol('r', positive=True)
c = Symbol('c')
p = Symbol('p', positive=True)
m = Symbol('m', negative=True)
expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c +
(r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n)
expr = expr.subs(c, c + 1)
raises(NotImplementedError, lambda: limit(expr, n, oo))
assert limit(expr.subs(c, m), n, oo) == 1
assert limit(expr.subs(c, p), n, oo).simplify() == \
(2**(p + 1) + r - 1)/(r + 1)**(p + 1)
def test_issue_7088():
a = Symbol('a')
assert limit(sqrt(x/(x + a)), x, oo) == 1
def test_branch_cuts():
assert limit(asin(I*x + 2), x, 0) == pi - asin(2)
assert limit(asin(I*x + 2), x, 0, '-') == asin(2)
assert limit(asin(I*x - 2), x, 0) == -asin(2)
assert limit(asin(I*x - 2), x, 0, '-') == -pi + asin(2)
assert limit(acos(I*x + 2), x, 0) == -acos(2)
assert limit(acos(I*x + 2), x, 0, '-') == acos(2)
assert limit(acos(I*x - 2), x, 0) == acos(-2)
assert limit(acos(I*x - 2), x, 0, '-') == 2*pi - acos(-2)
assert limit(atan(x + 2*I), x, 0) == I*atanh(2)
assert limit(atan(x + 2*I), x, 0, '-') == -pi + I*atanh(2)
assert limit(atan(x - 2*I), x, 0) == pi - I*atanh(2)
assert limit(atan(x - 2*I), x, 0, '-') == -I*atanh(2)
assert limit(atan(1/x), x, 0) == pi/2
assert limit(atan(1/x), x, 0, '-') == -pi/2
assert limit(atan(x), x, oo) == pi/2
assert limit(atan(x), x, -oo) == -pi/2
assert limit(acot(x + S(1)/2*I), x, 0) == pi - I*acoth(S(1)/2)
assert limit(acot(x + S(1)/2*I), x, 0, '-') == -I*acoth(S(1)/2)
assert limit(acot(x - S(1)/2*I), x, 0) == I*acoth(S(1)/2)
assert limit(acot(x - S(1)/2*I), x, 0, '-') == -pi + I*acoth(S(1)/2)
assert limit(acot(x), x, 0) == pi/2
assert limit(acot(x), x, 0, '-') == -pi/2
assert limit(asec(I*x + S(1)/2), x, 0) == asec(S(1)/2)
assert limit(asec(I*x + S(1)/2), x, 0, '-') == -asec(S(1)/2)
assert limit(asec(I*x - S(1)/2), x, 0) == 2*pi - asec(-S(1)/2)
assert limit(asec(I*x - S(1)/2), x, 0, '-') == asec(-S(1)/2)
assert limit(acsc(I*x + S(1)/2), x, 0) == acsc(S(1)/2)
assert limit(acsc(I*x + S(1)/2), x, 0, '-') == pi - acsc(S(1)/2)
assert limit(acsc(I*x - S(1)/2), x, 0) == -pi + acsc(S(1)/2)
assert limit(acsc(I*x - S(1)/2), x, 0, '-') == -acsc(S(1)/2)
assert limit(log(I*x - 1), x, 0) == I*pi
assert limit(log(I*x - 1), x, 0, '-') == -I*pi
assert limit(log(-I*x - 1), x, 0) == -I*pi
assert limit(log(-I*x - 1), x, 0, '-') == I*pi
assert limit(sqrt(I*x - 1), x, 0) == I
assert limit(sqrt(I*x - 1), x, 0, '-') == -I
assert limit(sqrt(-I*x - 1), x, 0) == -I
assert limit(sqrt(-I*x - 1), x, 0, '-') == I
assert limit(cbrt(I*x - 1), x, 0) == (-1)**(S(1)/3)
assert limit(cbrt(I*x - 1), x, 0, '-') == -(-1)**(S(2)/3)
assert limit(cbrt(-I*x - 1), x, 0) == -(-1)**(S(2)/3)
assert limit(cbrt(-I*x - 1), x, 0, '-') == (-1)**(S(1)/3)
def test_issue_6364():
a = Symbol('a')
e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2)
assert limit(e, z, 0) == 1/(cos(a)**2 - S.Half)
def test_issue_6682():
assert limit(exp(2*Ei(-x))/x**2, x, 0) == exp(2*EulerGamma)
def test_issue_4099():
a = Symbol('a')
assert limit(a/x, x, 0) == oo*sign(a)
assert limit(-a/x, x, 0) == -oo*sign(a)
assert limit(-a*x, x, oo) == -oo*sign(a)
assert limit(a*x, x, oo) == oo*sign(a)
def test_issue_4503():
dx = Symbol('dx')
assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \
exp(x)/(2*sqrt(exp(x) + 1))
def test_issue_6052():
G = meijerg((), (), (1,), (0,), -x)
g = hyperexpand(G)
assert limit(g, x, 0, '+-') == 0
assert limit(g, x, oo) == -oo
def test_issue_7224():
expr = sqrt(x)*besseli(1,sqrt(8*x))
assert limit(x*diff(expr, x, x)/expr, x, 0) == 2
assert limit(x*diff(expr, x, x)/expr, x, 1).evalf(n=2) == 2.0
def test_issue_8208():
assert limit(n**(Rational(1, 1e9) - 1), n, oo) == 0
def test_issue_8229():
assert limit((x**Rational(1, 4) - 2)/(sqrt(x) - 4)**Rational(2, 3), x, 16) == 0
def test_issue_8433():
d, t = symbols('d t', positive=True)
assert limit(erf(1 - t/d), t, oo) == -1
def test_issue_8481():
k = Symbol('k', integer=True, nonnegative=True)
lamda = Symbol('lamda', positive=True)
assert limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0
def test_issue_8462():
assert limit(binomial(n, n/2), n, oo) == oo
assert limit(binomial(n, n/2) * 3 ** (-n), n, oo) == 0
def test_issue_8635_18176():
x = Symbol('x', real=True)
k = Symbol('k', positive=True)
assert limit(x**n - x**(n - 0), x, oo) == 0
assert limit(x**n - x**(n - 5), x, oo) == oo
assert limit(x**n - x**(n - 2.5), x, oo) == oo
assert limit(x**n - x**(n - k - 1), x, oo) == oo
x = Symbol('x', positive=True)
assert limit(x**n - x**(n - 1), x, oo) == oo
assert limit(x**n - x**(n + 2), x, oo) == -oo
def test_issue_8730():
assert limit(subfactorial(x), x, oo) is oo
def test_issue_9252():
n = Symbol('n', integer=True)
c = Symbol('c', positive=True)
assert limit((log(n))**(n/log(n)) / (1 + c)**n, n, oo) == 0
# limit should depend on the value of c
raises(NotImplementedError, lambda: limit((log(n))**(n/log(n)) / c**n, n, oo))
def test_issue_9558():
assert limit(sin(x)**15, x, 0, '-') == 0
def test_issue_10801():
# make sure limits work with binomial
assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi
def test_issue_10976():
s, x = symbols('s x', real=True)
assert limit(erf(s*x)/erf(s), s, 0) == x
def test_issue_9041():
assert limit(factorial(n) / ((n/exp(1))**n * sqrt(2*pi*n)), n, oo) == 1
def test_issue_9205():
x, y, a = symbols('x, y, a')
assert Limit(x, x, a).free_symbols == {a}
assert Limit(x, x, a, '-').free_symbols == {a}
assert Limit(x + y, x + y, a).free_symbols == {a}
assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a}
def test_issue_9471():
assert limit(((27**(log(n,3)))/n**3),n,oo) == 1
assert limit(((27**(log(n,3)+1))/n**3),n,oo) == 27
def test_issue_11496():
assert limit(erfc(log(1/x)), x, oo) == 2
def test_issue_11879():
assert simplify(limit(((x+y)**n-x**n)/y, y, 0)) == n*x**(n-1)
def test_limit_with_Float():
k = symbols("k")
assert limit(1.0 ** k, k, oo) == 1
assert limit(0.3*1.0**k, k, oo) == Rational(3, 10)
def test_issue_10610():
assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3)
def test_issue_10868():
assert limit(log(x) + asech(x), x, 0, '+') == log(2)
assert limit(log(x) + asech(x), x, 0, '-') == log(2) + 2*I*pi
raises(ValueError, lambda: limit(log(x) + asech(x), x, 0, '+-'))
assert limit(log(x) + asech(x), x, oo) == oo
assert limit(log(x) + acsch(x), x, 0, '+') == log(2)
assert limit(log(x) + acsch(x), x, 0, '-') == -oo
raises(ValueError, lambda: limit(log(x) + acsch(x), x, 0, '+-'))
assert limit(log(x) + acsch(x), x, oo) == oo
def test_issue_6599():
assert limit((n + cos(n))/n, n, oo) == 1
def test_issue_12555():
assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, -oo) == 2
assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, oo) is oo
def test_issue_12769():
r, z, x = symbols('r z x', real=True)
a, b, s0, K, F0, s, T = symbols('a b s0 K F0 s T', positive=True, real=True)
fx = (F0**b*K**b*r*s0 - sqrt((F0**2*K**(2*b)*a**2*(b - 1) + \
F0**(2*b)*K**2*a**2*(b - 1) + F0**(2*b)*K**(2*b)*s0**2*(b - 1)*(b**2 - 2*b + 1) - \
2*F0**(2*b)*K**(b + 1)*a*r*s0*(b**2 - 2*b + 1) + \
2*F0**(b + 1)*K**(2*b)*a*r*s0*(b**2 - 2*b + 1) - \
2*F0**(b + 1)*K**(b + 1)*a**2*(b - 1))/((b - 1)*(b**2 - 2*b + 1))))*(b*r - b - r + 1)
assert fx.subs(K, F0).factor(deep=True) == limit(fx, K, F0).factor(deep=True)
def test_issue_13332():
assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) *
(6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36)
def test_issue_12564():
assert limit(x**2 + x*sin(x) + cos(x), x, -oo) is oo
assert limit(x**2 + x*sin(x) + cos(x), x, oo) is oo
assert limit(((x + cos(x))**2).expand(), x, oo) is oo
assert limit(((x + sin(x))**2).expand(), x, oo) is oo
assert limit(((x + cos(x))**2).expand(), x, -oo) is oo
assert limit(((x + sin(x))**2).expand(), x, -oo) is oo
def test_issue_14456():
raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit())
raises(NotImplementedError, lambda: Limit(x**2/(x+1), x, zoo).doit())
def test_issue_14411():
assert limit(3*sec(4*pi*x - x/3), x, 3*pi/(24*pi - 2)) is -oo
def test_issue_13382():
assert limit(x*(((x + 1)**2 + 1)/(x**2 + 1) - 1), x, oo) == 2
def test_issue_13403():
assert limit(x*(-1 + (x + log(x + 1) + 1)/(x + log(x))), x, oo) == 1
def test_issue_13416():
assert limit((-x**3*log(x)**3 + (x - 1)*(x + 1)**2*log(x + 1)**3)/(x**2*log(x)**3), x, oo) == 1
def test_issue_13462():
assert limit(n**2*(2*n*(-(1 - 1/(2*n))**x + 1) - x - (-x**2/4 + x/4)/n), n, oo) == x**3/24 - x**2/8 + x/12
def test_issue_13750():
a = Symbol('a')
assert limit(erf(a - x), x, oo) == -1
assert limit(erf(sqrt(x) - x), x, oo) == -1
def test_issue_14276():
assert isinstance(limit(sin(x)**log(x), x, oo), Limit)
assert isinstance(limit(sin(x)**cos(x), x, oo), Limit)
assert isinstance(limit(sin(log(cos(x))), x, oo), Limit)
assert limit((1 + 1/(x**2 + cos(x)))**(x**2 + x), x, oo) == E
def test_issue_14514():
assert limit((1/(log(x)**log(x)))**(1/x), x, oo) == 1
def test_issues_14525():
assert limit(sin(x)**2 - cos(x) + tan(x)*csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert limit(sin(x)**2 - cos(x) + sin(x)*cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert limit(cot(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert limit(cos(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One)
assert limit(sin(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One)
assert limit(cos(x)**2 - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One)
assert limit(tan(x)**2 + sin(x)**2 - cos(x), x, oo) == AccumBounds(-S.One, S.Infinity)
def test_issue_14574():
assert limit(sqrt(x)*cos(x - x**2) / (x + 1), x, oo) == 0
def test_issue_10102():
assert limit(fresnels(x), x, oo) == S.Half
assert limit(3 + fresnels(x), x, oo) == 3 + S.Half
assert limit(5*fresnels(x), x, oo) == Rational(5, 2)
assert limit(fresnelc(x), x, oo) == S.Half
assert limit(fresnels(x), x, -oo) == Rational(-1, 2)
assert limit(4*fresnelc(x), x, -oo) == -2
def test_issue_14377():
raises(NotImplementedError, lambda: limit(exp(I*x)*sin(pi*x), x, oo))
def test_issue_15146():
e = (x/2) * (-2*x**3 - 2*(x**3 - 1) * x**2 * digamma(x**3 + 1) + \
2*(x**3 - 1) * x**2 * digamma(x**3 + x + 1) + x + 3)
assert limit(e, x, oo) == S(1)/3
def test_issue_15202():
e = (2**x*(2 + 2**(-x)*(-2*2**x + x + 2))/(x + 1))**(x + 1)
assert limit(e, x, oo) == exp(1)
e = (log(x, 2)**7 + 10*x*factorial(x) + 5**x) / (factorial(x + 1) + 3*factorial(x) + 10**x)
assert limit(e, x, oo) == 10
def test_issue_15282():
assert limit((x**2000 - (x + 1)**2000) / x**1999, x, oo) == -2000
def test_issue_15984():
assert limit((-x + log(exp(x) + 1))/x, x, oo, dir='-') == 0
def test_issue_13571():
assert limit(uppergamma(x, 1) / gamma(x), x, oo) == 1
def test_issue_13575():
assert limit(acos(erfi(x)), x, 1) == acos(erfi(S.One))
def test_issue_17325():
assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1
assert Limit(x**2, x, 0, dir="+-").doit() == 0
assert Limit(1/x**2, x, 0, dir="+-").doit() is oo
assert Limit(1/x, x, 0, dir="+-").doit() is zoo
def test_issue_10978():
assert LambertW(x).limit(x, 0) == 0
def test_issue_14313_comment():
assert limit(floor(n/2), n, oo) is oo
@XFAIL
def test_issue_15323():
d = ((1 - 1/x)**x).diff(x)
assert limit(d, x, 1, dir='+') == 1
def test_issue_12571():
assert limit(-LambertW(-log(x))/log(x), x, 1) == 1
def test_issue_14590():
assert limit((x**3*((x + 1)/x)**x)/((x + 1)*(x + 2)*(x + 3)), x, oo) == exp(1)
def test_issue_14393():
a, b = symbols('a b')
assert limit((x**b - y**b)/(x**a - y**a), x, y) == b*y**(-a + b)/a
def test_issue_14556():
assert limit(factorial(n + 1)**(1/(n + 1)) - factorial(n)**(1/n), n, oo) == exp(-1)
def test_issue_14811():
assert limit(((1 + ((S(2)/3)**(x + 1)))**(2**x))/(2**((S(4)/3)**(x - 1))), x, oo) == oo
def test_issue_16222():
assert limit(exp(x), x, 1000000000) == exp(1000000000)
def test_issue_16714():
assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1))
def test_issue_16722():
z = symbols('z', positive=True)
assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
z = symbols('z', positive=True, integer=True)
assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
def test_issue_17431():
assert limit(((n + 1) + 1) / (((n + 1) + 2) * factorial(n + 1)) *
(n + 2) * factorial(n) / (n + 1), n, oo) == 0
assert limit((n + 2)**2*factorial(n)/((n + 1)*(n + 3)*factorial(n + 1))
, n, oo) == 0
assert limit((n + 1) * factorial(n) / (n * factorial(n + 1)), n, oo) == 0
def test_issue_17671():
assert limit(Ei(-log(x)) - log(log(x))/x, x, 1) == EulerGamma
def test_issue_17751():
a, b, c, x = symbols('a b c x', positive=True)
assert limit((a + 1)*x - sqrt((a + 1)**2*x**2 + b*x + c), x, oo) == -b/(2*a + 2)
def test_issue_17792():
assert limit(factorial(n)/sqrt(n)*(exp(1)/n)**n, n, oo) == sqrt(2)*sqrt(pi)
def test_issue_18118():
assert limit(sign(sin(x)), x, 0, "-") == -1
assert limit(sign(sin(x)), x, 0, "+") == 1
def test_issue_18306():
assert limit(sin(sqrt(x))/sqrt(sin(x)), x, 0, '+') == 1
def test_issue_18378():
assert limit(log(exp(3*x) + x)/log(exp(x) + x**100), x, oo) == 3
def test_issue_18399():
assert limit((1 - S(1)/2*x)**(3*x), x, oo) is zoo
assert limit((-x)**x, x, oo) is zoo
def test_issue_18442():
assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-')
def test_issue_18452():
assert limit(abs(log(x))**x, x, 0) == 1
assert limit(abs(log(x))**x, x, 0, "-") == 1
def test_issue_18473():
assert limit(sin(x)**(1/x), x, oo) == Limit(sin(x)**(1/x), x, oo, dir='-')
assert limit(cos(x)**(1/x), x, oo) == Limit(cos(x)**(1/x), x, oo, dir='-')
assert limit(tan(x)**(1/x), x, oo) == Limit(tan(x)**(1/x), x, oo, dir='-')
assert limit((cos(x) + 2)**(1/x), x, oo) == 1
assert limit((sin(x) + 10)**(1/x), x, oo) == 1
assert limit((cos(x) - 2)**(1/x), x, oo) == Limit((cos(x) - 2)**(1/x), x, oo, dir='-')
assert limit((cos(x) + 1)**(1/x), x, oo) == AccumBounds(0, 1)
assert limit((tan(x)**2)**(2/x) , x, oo) == AccumBounds(0, oo)
assert limit((sin(x)**2)**(1/x), x, oo) == AccumBounds(0, 1)
# Tests for issue #23751
assert limit((cos(x) + 1)**(1/x), x, -oo) == AccumBounds(1, oo)
assert limit((sin(x)**2)**(1/x), x, -oo) == AccumBounds(1, oo)
assert limit((tan(x)**2)**(2/x) , x, -oo) == AccumBounds(0, oo)
def test_issue_18482():
assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1)
def test_issue_18508():
assert limit(sin(x)/sqrt(1-cos(x)), x, 0) == sqrt(2)
assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='+') == sqrt(2)
assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='-') == -sqrt(2)
def test_issue_18521():
raises(NotImplementedError, lambda: limit(exp((2 - n) * x), x, oo))
def test_issue_18969():
a, b = symbols('a b', positive=True)
assert limit(LambertW(a), a, b) == LambertW(b)
assert limit(exp(LambertW(a)), a, b) == exp(LambertW(b))
def test_issue_18992():
assert limit(n/(factorial(n)**(1/n)), n, oo) == exp(1)
def test_issue_19067():
x = Symbol('x')
assert limit(gamma(x)/(gamma(x - 1)*gamma(x + 2)), x, 0) == -1
def test_issue_19586():
assert limit(x**(2**x*3**(-x)), x, oo) == 1
def test_issue_13715():
n = Symbol('n')
p = Symbol('p', zero=True)
assert limit(n + p, n, 0) == 0
def test_issue_15055():
assert limit(n**3*((-n - 1)*sin(1/n) + (n + 2)*sin(1/(n + 1)))/(-n + 1), n, oo) == 1
def test_issue_16708():
m, vi = symbols('m vi', positive=True)
B, ti, d = symbols('B ti d')
assert limit((B*ti*vi - sqrt(m)*sqrt(-2*B*d*vi + m*(vi)**2) + m*vi)/(B*vi), B, 0) == (d + ti*vi)/vi
def test_issue_19154():
assert limit(besseli(1, 3 *x)/(x *besseli(1, x)**3), x , oo) == 2*sqrt(3)*pi/3
assert limit(besseli(1, 3 *x)/(x *besseli(1, x)**3), x , -oo) == -2*sqrt(3)*pi/3
def test_issue_19453():
beta = Symbol("beta", positive=True)
h = Symbol("h", positive=True)
m = Symbol("m", positive=True)
w = Symbol("omega", positive=True)
g = Symbol("g", positive=True)
e = exp(1)
q = 3*h**2*beta*g*e**(0.5*h*beta*w)
p = m**2*w**2
s = e**(h*beta*w) - 1
Z = -q/(4*p*s) - q/(2*p*s**2) - q*(e**(h*beta*w) + 1)/(2*p*s**3)\
+ e**(0.5*h*beta*w)/s
E = -diff(log(Z), beta)
assert limit(E - 0.5*h*w, beta, oo) == 0
assert limit(E.simplify() - 0.5*h*w, beta, oo) == 0
def test_issue_19739():
assert limit((-S(1)/4)**x, x, oo) == 0
def test_issue_19766():
assert limit(2**(-x)*sqrt(4**(x + 1) + 1), x, oo) == 2
def test_issue_19770():
m = Symbol('m')
# the result is not 0 for non-real m
assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
m = Symbol('m', real=True)
# can be improved to give the correct result 0
assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
m = Symbol('m', nonzero=True)
assert limit(cos(m*x), x, oo) == AccumBounds(-1, 1)
assert limit(cos(m*x)/x, x, oo) == 0
def test_issue_7535():
assert limit(tan(x)/sin(tan(x)), x, pi/2) == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+')
assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='-')
assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-')
assert limit(sin(tan(x)),x,pi/2) == AccumBounds(-1, 1)
assert -oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
assert oo*(1/sin(oo)) == AccumBounds(-oo, oo)
assert oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
assert -oo*(1/sin(oo)) == AccumBounds(-oo, oo)
def test_issue_20365():
assert limit(((x + 1)**(1/x) - E)/x, x, 0) == -E/2
def test_issue_21031():
assert limit(((1 + x)**(1/x) - (1 + 2*x)**(1/(2*x)))/asin(x), x, 0) == E/2
def test_issue_21038():
assert limit(sin(pi*x)/(3*x - 12), x, 4) == pi/3
def test_issue_20578():
expr = abs(x) * sin(1/x)
assert limit(expr,x,0,'+') == 0
assert limit(expr,x,0,'-') == 0
assert limit(expr,x,0,'+-') == 0
def test_issue_21227():
f = log(x)
assert f.nseries(x, logx=y) == y
assert f.nseries(x, logx=-x) == -x
f = log(-log(x))
assert f.nseries(x, logx=y) == log(-y)
assert f.nseries(x, logx=-x) == log(x)
f = log(log(x))
assert f.nseries(x, logx=y) == log(y)
assert f.nseries(x, logx=-x) == log(-x)
assert f.nseries(x, logx=x) == log(x)
f = log(log(log(1/x)))
assert f.nseries(x, logx=y) == log(log(-y))
assert f.nseries(x, logx=-y) == log(log(y))
assert f.nseries(x, logx=x) == log(log(-x))
assert f.nseries(x, logx=-x) == log(log(x))
def test_issue_21415():
exp = (x-1)*cos(1/(x-1))
assert exp.limit(x,1) == 0
assert exp.expand().limit(x,1) == 0
def test_issue_21530():
assert limit(sinh(n + 1)/sinh(n), n, oo) == E
def test_issue_21550():
r = (sqrt(5) - 1)/2
assert limit((x - r)/(x**2 + x - 1), x, r) == sqrt(5)/5
def test_issue_21661():
out = limit((x**(x + 1) * (log(x) + 1) + 1) / x, x, 11)
assert out == S(3138428376722)/11 + 285311670611*log(11)
def test_issue_21701():
assert limit((besselj(z, x)/x**z).subs(z, 7), x, 0) == S(1)/645120
def test_issue_21721():
a = Symbol('a', real=True)
I = integrate(1/(pi*(1 + (x - a)**2)), x)
assert I.limit(x, oo) == S.Half
def test_issue_21756():
term = (1 - exp(-2*I*pi*z))/(1 - exp(-2*I*pi*z/5))
assert term.limit(z, 0) == 5
assert re(term).limit(z, 0) == 5
def test_issue_21785():
a = Symbol('a')
assert sqrt((-a**2 + x**2)/(1 - x**2)).limit(a, 1, '-') == I
def test_issue_22181():
assert limit((-1)**x * 2**(-x), x, oo) == 0
def test_issue_22220():
e1 = sqrt(30)*atan(sqrt(30)*tan(x/2)/6)/30
e2 = sqrt(30)*I*(-log(sqrt(2)*tan(x/2) - 2*sqrt(15)*I/5) +
+log(sqrt(2)*tan(x/2) + 2*sqrt(15)*I/5))/60
assert limit(e1, x, -pi) == -sqrt(30)*pi/60
assert limit(e2, x, -pi) == -sqrt(30)*pi/30
assert limit(e1, x, -pi, '-') == sqrt(30)*pi/60
assert limit(e2, x, -pi, '-') == 0
# test https://github.com/sympy/sympy/issues/22220#issuecomment-972727694
expr = log(x - I) - log(-x - I)
expr2 = logcombine(expr, force=True)
assert limit(expr, x, oo) == limit(expr2, x, oo) == I*pi
# test https://github.com/sympy/sympy/issues/22220#issuecomment-1077618340
expr = expr = (-log(tan(x/2) - I) +log(tan(x/2) + I))
assert limit(expr, x, pi, '+') == 2*I*pi
assert limit(expr, x, pi, '-') == 0
def test_issue_22334():
k, n = symbols('k, n', positive=True)
assert limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)), n, oo) == 1/(k + 1)
assert limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)).expand(), n, oo) == 1/(k + 1)
assert limit((n+1)**k/(n*(-n**k + (n + 1)**k) + (n + 1)**k), n, oo) == 1/(k + 1)
def test_sympyissue_22986():
assert limit(acosh(1 + 1/x)*sqrt(x), x, oo) == sqrt(2)
def test_issue_23231():
f = (2**x - 2**(-x))/(2**x + 2**(-x))
assert limit(f, x, -oo) == -1
def test_issue_23596():
assert integrate(((1 + x)/x**2)*exp(-1/x), (x, 0, oo)) == oo
def test_issue_23752():
expr1 = sqrt(-I*x**2 + x - 3)
expr2 = sqrt(-I*x**2 + I*x - 3)
assert limit(expr1, x, 0, '+') == -sqrt(3)*I
assert limit(expr1, x, 0, '-') == -sqrt(3)*I
assert limit(expr2, x, 0, '+') == sqrt(3)*I
assert limit(expr2, x, 0, '-') == -sqrt(3)*I
|
bb387362cc1239ef4687f9d629e3baf6dbc63cc2ddfbdb6a9381c1617f09226e | from sympy.calculus.util import AccumBounds
from sympy.core.function import (Derivative, PoleError)
from sympy.core.numbers import (E, I, Integer, Rational, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.hyperbolic import (acosh, acoth, asinh, atanh, cosh, coth, sinh, tanh)
from sympy.functions.elementary.integers import (ceiling, floor, frac)
from sympy.functions.elementary.miscellaneous import (cbrt, sqrt)
from sympy.functions.elementary.trigonometric import (asin, cos, cot, sin, tan)
from sympy.series.limits import limit
from sympy.series.order import O
from sympy.abc import x, y, z
from sympy.testing.pytest import raises, XFAIL
def test_simple_1():
assert x.nseries(x, n=5) == x
assert y.nseries(x, n=5) == y
assert (1/(x*y)).nseries(y, n=5) == 1/(x*y)
assert Rational(3, 4).nseries(x, n=5) == Rational(3, 4)
assert x.nseries() == x
def test_mul_0():
assert (x*log(x)).nseries(x, n=5) == x*log(x)
def test_mul_1():
assert (x*log(2 + x)).nseries(x, n=5) == x*log(2) + x**2/2 - x**3/8 + \
x**4/24 + O(x**5)
assert (x*log(1 + x)).nseries(
x, n=5) == x**2 - x**3/2 + x**4/3 + O(x**5)
def test_pow_0():
assert (x**2).nseries(x, n=5) == x**2
assert (1/x).nseries(x, n=5) == 1/x
assert (1/x**2).nseries(x, n=5) == 1/x**2
assert (x**Rational(2, 3)).nseries(x, n=5) == (x**Rational(2, 3))
assert (sqrt(x)**3).nseries(x, n=5) == (sqrt(x)**3)
def test_pow_1():
assert ((1 + x)**2).nseries(x, n=5) == x**2 + 2*x + 1
# https://github.com/sympy/sympy/issues/21075
assert ((sqrt(x) + 1)**2).nseries(x) == 2*sqrt(x) + x + 1
assert ((sqrt(x) + cbrt(x))**2).nseries(x) == 2*x**Rational(5, 6)\
+ x**Rational(2, 3) + x
def test_geometric_1():
assert (1/(1 - x)).nseries(x, n=5) == 1 + x + x**2 + x**3 + x**4 + O(x**5)
assert (x/(1 - x)).nseries(x, n=6) == x + x**2 + x**3 + x**4 + x**5 + O(x**6)
assert (x**3/(1 - x)).nseries(x, n=8) == x**3 + x**4 + x**5 + x**6 + \
x**7 + O(x**8)
def test_sqrt_1():
assert sqrt(1 + x).nseries(x, n=5) == 1 + x/2 - x**2/8 + x**3/16 - 5*x**4/128 + O(x**5)
def test_exp_1():
assert exp(x).nseries(x, n=5) == 1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5)
assert exp(x).nseries(x, n=12) == 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + \
x**6/720 + x**7/5040 + x**8/40320 + x**9/362880 + x**10/3628800 + \
x**11/39916800 + O(x**12)
assert exp(1/x).nseries(x, n=5) == exp(1/x)
assert exp(1/(1 + x)).nseries(x, n=4) == \
(E*(1 - x - 13*x**3/6 + 3*x**2/2)).expand() + O(x**4)
assert exp(2 + x).nseries(x, n=5) == \
(exp(2)*(1 + x + x**2/2 + x**3/6 + x**4/24)).expand() + O(x**5)
def test_exp_sqrt_1():
assert exp(1 + sqrt(x)).nseries(x, n=3) == \
(exp(1)*(1 + sqrt(x) + x/2 + sqrt(x)*x/6)).expand() + O(sqrt(x)**3)
def test_power_x_x1():
assert (exp(x*log(x))).nseries(x, n=4) == \
1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)
def test_power_x_x2():
assert (x**x).nseries(x, n=4) == \
1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)
def test_log_singular1():
assert log(1 + 1/x).nseries(x, n=5) == x - log(x) - x**2/2 + x**3/3 - \
x**4/4 + O(x**5)
def test_log_power1():
e = 1 / (1/x + x ** (log(3)/log(2)))
assert e.nseries(x, n=5) == -x**(log(3)/log(2) + 2) + x + O(x**5)
def test_log_series():
l = Symbol('l')
e = 1/(1 - log(x))
assert e.nseries(x, n=5, logx=l) == 1/(1 - l)
def test_log2():
e = log(-1/x)
assert e.nseries(x, n=5) == -log(x) + log(-1)
def test_log3():
l = Symbol('l')
e = 1/log(-1/x)
assert e.nseries(x, n=4, logx=l) == 1/(-l + log(-1))
def test_series1():
e = sin(x)
assert e.nseries(x, 0, 0) != 0
assert e.nseries(x, 0, 0) == O(1, x)
assert e.nseries(x, 0, 1) == O(x, x)
assert e.nseries(x, 0, 2) == x + O(x**2, x)
assert e.nseries(x, 0, 3) == x + O(x**3, x)
assert e.nseries(x, 0, 4) == x - x**3/6 + O(x**4, x)
e = (exp(x) - 1)/x
assert e.nseries(x, 0, 3) == 1 + x/2 + x**2/6 + O(x**3)
assert x.nseries(x, 0, 2) == x
@XFAIL
def test_series1_failing():
assert x.nseries(x, 0, 0) == O(1, x)
assert x.nseries(x, 0, 1) == O(x, x)
def test_seriesbug1():
assert (1/x).nseries(x, 0, 3) == 1/x
assert (x + 1/x).nseries(x, 0, 3) == x + 1/x
def test_series2x():
assert ((x + 1)**(-2)).nseries(x, 0, 4) == 1 - 2*x + 3*x**2 - 4*x**3 + O(x**4, x)
assert ((x + 1)**(-1)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x)
assert ((x + 1)**0).nseries(x, 0, 3) == 1
assert ((x + 1)**1).nseries(x, 0, 3) == 1 + x
assert ((x + 1)**2).nseries(x, 0, 3) == x**2 + 2*x + 1
assert ((x + 1)**3).nseries(x, 0, 3) == 1 + 3*x + 3*x**2 + O(x**3)
assert (1/(1 + x)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x)
assert (x + 3/(1 + 2*x)).nseries(x, 0, 4) == 3 - 5*x + 12*x**2 - 24*x**3 + O(x**4, x)
assert ((1/x + 1)**3).nseries(x, 0, 3) == 1 + 3/x + 3/x**2 + x**(-3)
assert (1/(1 + 1/x)).nseries(x, 0, 4) == x - x**2 + x**3 - O(x**4, x)
assert (1/(1 + 1/x**2)).nseries(x, 0, 6) == x**2 - x**4 + O(x**6, x)
def test_bug2(): # 1/log(0)*log(0) problem
w = Symbol("w")
e = (w**(-1) + w**(
-log(3)*log(2)**(-1)))**(-1)*(3*w**(-log(3)*log(2)**(-1)) + 2*w**(-1))
e = e.expand()
assert e.nseries(w, 0, 4).subs(w, 0) == 3
def test_exp():
e = (1 + x)**(1/x)
assert e.nseries(x, n=3) == exp(1) - x*exp(1)/2 + 11*exp(1)*x**2/24 + O(x**3)
def test_exp2():
w = Symbol("w")
e = w**(1 - log(x)/(log(2) + log(x)))
logw = Symbol("logw")
assert e.nseries(
w, 0, 1, logx=logw) == exp(logw*log(2)/(log(x) + log(2)))
def test_bug3():
e = (2/x + 3/x**2)/(1/x + 1/x**2)
assert e.nseries(x, n=3) == 3 - x + x**2 + O(x**3)
def test_generalexponent():
p = 2
e = (2/x + 3/x**p)/(1/x + 1/x**p)
assert e.nseries(x, 0, 3) == 3 - x + x**2 + O(x**3)
p = S.Half
e = (2/x + 3/x**p)/(1/x + 1/x**p)
assert e.nseries(x, 0, 2) == 2 - x + sqrt(x) + x**(S(3)/2) + O(x**2)
e = 1 + sqrt(x)
assert e.nseries(x, 0, 4) == 1 + sqrt(x)
# more complicated example
def test_genexp_x():
e = 1/(1 + sqrt(x))
assert e.nseries(x, 0, 2) == \
1 + x - sqrt(x) - sqrt(x)**3 + O(x**2, x)
# more complicated example
def test_genexp_x2():
p = Rational(3, 2)
e = (2/x + 3/x**p)/(1/x + 1/x**p)
assert e.nseries(x, 0, 3) == 3 + x + x**2 - sqrt(x) - x**(S(3)/2) - x**(S(5)/2) + O(x**3)
def test_seriesbug2():
w = Symbol("w")
#simple case (1):
e = ((2*w)/w)**(1 + w)
assert e.nseries(w, 0, 1) == 2 + O(w, w)
assert e.nseries(w, 0, 1).subs(w, 0) == 2
def test_seriesbug2b():
w = Symbol("w")
#test sin
e = sin(2*w)/w
assert e.nseries(w, 0, 3) == 2 - 4*w**2/3 + O(w**3)
def test_seriesbug2d():
w = Symbol("w", real=True)
e = log(sin(2*w)/w)
assert e.series(w, n=5) == log(2) - 2*w**2/3 - 4*w**4/45 + O(w**5)
def test_seriesbug2c():
w = Symbol("w", real=True)
#more complicated case, but sin(x)~x, so the result is the same as in (1)
e = (sin(2*w)/w)**(1 + w)
assert e.series(w, 0, 1) == 2 + O(w)
assert e.series(w, 0, 3) == 2 + 2*w*log(2) + \
w**2*(Rational(-4, 3) + log(2)**2) + O(w**3)
assert e.series(w, 0, 2).subs(w, 0) == 2
def test_expbug4():
x = Symbol("x", real=True)
assert (log(
sin(2*x)/x)*(1 + x)).series(x, 0, 2) == log(2) + x*log(2) + O(x**2, x)
assert exp(
log(sin(2*x)/x)*(1 + x)).series(x, 0, 2) == 2 + 2*x*log(2) + O(x**2)
assert exp(log(2) + O(x)).nseries(x, 0, 2) == 2 + O(x)
assert ((2 + O(x))**(1 + x)).nseries(x, 0, 2) == 2 + O(x)
def test_logbug4():
assert log(2 + O(x)).nseries(x, 0, 2) == log(2) + O(x, x)
def test_expbug5():
assert exp(log(1 + x)/x).nseries(x, n=3) == exp(1) + -exp(1)*x/2 + 11*exp(1)*x**2/24 + O(x**3)
assert exp(O(x)).nseries(x, 0, 2) == 1 + O(x)
def test_sinsinbug():
assert sin(sin(x)).nseries(x, 0, 8) == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8)
def test_issue_3258():
a = x/(exp(x) - 1)
assert a.nseries(x, 0, 5) == 1 - x/2 - x**4/720 + x**2/12 + O(x**5)
def test_issue_3204():
x = Symbol("x", nonnegative=True)
f = sin(x**3)**Rational(1, 3)
assert f.nseries(x, 0, 17) == x - x**7/18 - x**13/3240 + O(x**17)
def test_issue_3224():
f = sqrt(1 - sqrt(y))
assert f.nseries(y, 0, 2) == 1 - sqrt(y)/2 - y/8 - sqrt(y)**3/16 + O(y**2)
def test_issue_3463():
w, i = symbols('w,i')
r = log(5)/log(3)
p = w**(-1 + r)
e = 1/x*(-log(w**(1 + r)) + log(w + w**r))
e_ser = -r*log(w)/x + p/x - p**2/(2*x) + O(w)
assert e.nseries(w, n=1) == e_ser
def test_sin():
assert sin(8*x).nseries(x, n=4) == 8*x - 256*x**3/3 + O(x**4)
assert sin(x + y).nseries(x, n=1) == sin(y) + O(x)
assert sin(x + y).nseries(x, n=2) == sin(y) + cos(y)*x + O(x**2)
assert sin(x + y).nseries(x, n=5) == sin(y) + cos(y)*x - sin(y)*x**2/2 - \
cos(y)*x**3/6 + sin(y)*x**4/24 + O(x**5)
def test_issue_3515():
e = sin(8*x)/x
assert e.nseries(x, n=6) == 8 - 256*x**2/3 + 4096*x**4/15 + O(x**6)
def test_issue_3505():
e = sin(x)**(-4)*(sqrt(cos(x))*sin(x)**2 -
cos(x)**Rational(1, 3)*sin(x)**2)
assert e.nseries(x, n=9) == Rational(-1, 12) - 7*x**2/288 - \
43*x**4/10368 - 1123*x**6/2488320 + 377*x**8/29859840 + O(x**9)
def test_issue_3501():
a = Symbol("a")
e = x**(-2)*(x*sin(a + x) - x*sin(a))
assert e.nseries(x, n=6) == cos(a) - sin(a)*x/2 - cos(a)*x**2/6 + \
x**3*sin(a)/24 + x**4*cos(a)/120 - x**5*sin(a)/720 + O(x**6)
e = x**(-2)*(x*cos(a + x) - x*cos(a))
assert e.nseries(x, n=6) == -sin(a) - cos(a)*x/2 + sin(a)*x**2/6 + \
cos(a)*x**3/24 - x**4*sin(a)/120 - x**5*cos(a)/720 + O(x**6)
def test_issue_3502():
e = sin(5*x)/sin(2*x)
assert e.nseries(x, n=2) == Rational(5, 2) + O(x**2)
assert e.nseries(x, n=6) == \
Rational(5, 2) - 35*x**2/4 + 329*x**4/48 + O(x**6)
def test_issue_3503():
e = sin(2 + x)/(2 + x)
assert e.nseries(x, n=2) == sin(2)/2 + x*cos(2)/2 - x*sin(2)/4 + O(x**2)
def test_issue_3506():
e = (x + sin(3*x))**(-2)*(x*(x + sin(3*x)) - (x + sin(3*x))*sin(2*x))
assert e.nseries(x, n=7) == \
Rational(-1, 4) + 5*x**2/96 + 91*x**4/768 + 11117*x**6/129024 + O(x**7)
def test_issue_3508():
x = Symbol("x", real=True)
assert log(sin(x)).series(x, n=5) == log(x) - x**2/6 - x**4/180 + O(x**5)
e = -log(x) + x*(-log(x) + log(sin(2*x))) + log(sin(2*x))
assert e.series(x, n=5) == \
log(2) + log(2)*x - 2*x**2/3 - 2*x**3/3 - 4*x**4/45 + O(x**5)
def test_issue_3507():
e = x**(-4)*(x**2 - x**2*sqrt(cos(x)))
assert e.nseries(x, n=9) == \
Rational(1, 4) + x**2/96 + 19*x**4/5760 + 559*x**6/645120 + 29161*x**8/116121600 + O(x**9)
def test_issue_3639():
assert sin(cos(x)).nseries(x, n=5) == \
sin(1) - x**2*cos(1)/2 - x**4*sin(1)/8 + x**4*cos(1)/24 + O(x**5)
def test_hyperbolic():
assert sinh(x).nseries(x, n=6) == x + x**3/6 + x**5/120 + O(x**6)
assert cosh(x).nseries(x, n=5) == 1 + x**2/2 + x**4/24 + O(x**5)
assert tanh(x).nseries(x, n=6) == x - x**3/3 + 2*x**5/15 + O(x**6)
assert coth(x).nseries(x, n=6) == \
1/x - x**3/45 + x/3 + 2*x**5/945 + O(x**6)
assert asinh(x).nseries(x, n=6) == x - x**3/6 + 3*x**5/40 + O(x**6)
assert acosh(x).nseries(x, n=6) == \
pi*I/2 - I*x - 3*I*x**5/40 - I*x**3/6 + O(x**6)
assert atanh(x).nseries(x, n=6) == x + x**3/3 + x**5/5 + O(x**6)
assert acoth(x).nseries(x, n=6) == -I*pi/2 + x + x**3/3 + x**5/5 + O(x**6)
def test_series2():
w = Symbol("w", real=True)
x = Symbol("x", real=True)
e = w**(-2)*(w*exp(1/x - w) - w*exp(1/x))
assert e.nseries(w, n=4) == -exp(1/x) + w*exp(1/x)/2 - w**2*exp(1/x)/6 + w**3*exp(1/x)/24 + O(w**4)
def test_series3():
w = Symbol("w", real=True)
e = w**(-6)*(w**3*tan(w) - w**3*sin(w))
assert e.nseries(w, n=8) == Integer(1)/2 + w**2/8 + 13*w**4/240 + 529*w**6/24192 + O(w**8)
def test_bug4():
w = Symbol("w")
e = x/(w**4 + x**2*w**4 + 2*x*w**4)*w**4
assert e.nseries(w, n=2).removeO().expand() in [x/(1 + 2*x + x**2),
1/(1 + x/2 + 1/x/2)/2, 1/x/(1 + 2/x + x**(-2))]
def test_bug5():
w = Symbol("w")
l = Symbol('l')
e = (-log(w) + log(1 + w*log(x)))**(-2)*w**(-2)*((-log(w) +
log(1 + x*w))*(-log(w) + log(1 + w*log(x)))*w - x*(-log(w) +
log(1 + w*log(x)))*w)
assert e.nseries(w, n=0, logx=l) == x/w/l + 1/w + O(1, w)
assert e.nseries(w, n=1, logx=l) == x/w/l + 1/w - x/l + 1/l*log(x) \
+ x*log(x)/l**2 + O(w)
def test_issue_4115():
assert (sin(x)/(1 - cos(x))).nseries(x, n=1) == 2/x + O(x)
assert (sin(x)**2/(1 - cos(x))).nseries(x, n=1) == 2 + O(x)
def test_pole():
raises(PoleError, lambda: sin(1/x).series(x, 0, 5))
raises(PoleError, lambda: sin(1 + 1/x).series(x, 0, 5))
raises(PoleError, lambda: (x*sin(1/x)).series(x, 0, 5))
def test_expsinbug():
assert exp(sin(x)).series(x, 0, 0) == O(1, x)
assert exp(sin(x)).series(x, 0, 1) == 1 + O(x)
assert exp(sin(x)).series(x, 0, 2) == 1 + x + O(x**2)
assert exp(sin(x)).series(x, 0, 3) == 1 + x + x**2/2 + O(x**3)
assert exp(sin(x)).series(x, 0, 4) == 1 + x + x**2/2 + O(x**4)
assert exp(sin(x)).series(x, 0, 5) == 1 + x + x**2/2 - x**4/8 + O(x**5)
def test_floor():
x = Symbol('x')
assert floor(x).series(x) == 0
assert floor(-x).series(x) == -1
assert floor(sin(x)).series(x) == 0
assert floor(sin(-x)).series(x) == -1
assert floor(x**3).series(x) == 0
assert floor(-x**3).series(x) == -1
assert floor(cos(x)).series(x) == 0
assert floor(cos(-x)).series(x) == 0
assert floor(5 + sin(x)).series(x) == 5
assert floor(5 + sin(-x)).series(x) == 4
assert floor(x).series(x, 2) == 2
assert floor(-x).series(x, 2) == -3
x = Symbol('x', negative=True)
assert floor(x + 1.5).series(x) == 1
def test_frac():
assert frac(x).series(x, cdir=1) == x
assert frac(x).series(x, cdir=-1) == 1 + x
assert frac(2*x + 1).series(x, cdir=1) == 2*x
assert frac(2*x + 1).series(x, cdir=-1) == 1 + 2*x
assert frac(x**2).series(x, cdir=1) == x**2
assert frac(x**2).series(x, cdir=-1) == x**2
assert frac(sin(x) + 5).series(x, cdir=1) == x - x**3/6 + x**5/120 + O(x**6)
assert frac(sin(x) + 5).series(x, cdir=-1) == 1 + x - x**3/6 + x**5/120 + O(x**6)
assert frac(sin(x) + S.Half).series(x) == S.Half + x - x**3/6 + x**5/120 + O(x**6)
assert frac(x**8).series(x, cdir=1) == O(x**6)
assert frac(1/x).series(x) == AccumBounds(0, 1) + O(x**6)
def test_ceiling():
assert ceiling(x).series(x) == 1
assert ceiling(-x).series(x) == 0
assert ceiling(sin(x)).series(x) == 1
assert ceiling(sin(-x)).series(x) == 0
assert ceiling(1 - cos(x)).series(x) == 1
assert ceiling(1 - cos(-x)).series(x) == 1
assert ceiling(x).series(x, 2) == 3
assert ceiling(-x).series(x, 2) == -2
def test_abs():
a = Symbol('a')
assert abs(x).nseries(x, n=4) == x
assert abs(-x).nseries(x, n=4) == x
assert abs(x + 1).nseries(x, n=4) == x + 1
assert abs(sin(x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4)
assert abs(sin(-x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4)
assert abs(x - a).nseries(x, 1) == -a*sign(1 - a) + (x - 1)*sign(1 - a) + sign(1 - a)
def test_dir():
assert abs(x).series(x, 0, dir="+") == x
assert abs(x).series(x, 0, dir="-") == -x
assert floor(x + 2).series(x, 0, dir='+') == 2
assert floor(x + 2).series(x, 0, dir='-') == 1
assert floor(x + 2.2).series(x, 0, dir='-') == 2
assert ceiling(x + 2.2).series(x, 0, dir='-') == 3
assert sin(x + y).series(x, 0, dir='-') == sin(x + y).series(x, 0, dir='+')
def test_cdir():
assert abs(x).series(x, 0, cdir=1) == x
assert abs(x).series(x, 0, cdir=-1) == -x
assert floor(x + 2).series(x, 0, cdir=1) == 2
assert floor(x + 2).series(x, 0, cdir=-1) == 1
assert floor(x + 2.2).series(x, 0, cdir=1) == 2
assert ceiling(x + 2.2).series(x, 0, cdir=-1) == 3
assert sin(x + y).series(x, 0, cdir=-1) == sin(x + y).series(x, 0, cdir=1)
def test_issue_3504():
a = Symbol("a")
e = asin(a*x)/x
assert e.series(x, 4, n=2).removeO() == \
(x - 4)*(a/(4*sqrt(-16*a**2 + 1)) - asin(4*a)/16) + asin(4*a)/4
def test_issue_4441():
a, b = symbols('a,b')
f = 1/(1 + a*x)
assert f.series(x, 0, 5) == 1 - a*x + a**2*x**2 - a**3*x**3 + \
a**4*x**4 + O(x**5)
f = 1/(1 + (a + b)*x)
assert f.series(x, 0, 3) == 1 + x*(-a - b)\
+ x**2*(a + b)**2 + O(x**3)
def test_issue_4329():
assert tan(x).series(x, pi/2, n=3).removeO() == \
-pi/6 + x/3 - 1/(x - pi/2)
assert cot(x).series(x, pi, n=3).removeO() == \
-x/3 + pi/3 + 1/(x - pi)
assert limit(tan(x)**tan(2*x), x, pi/4) == exp(-1)
def test_issue_5183():
assert abs(x + x**2).series(n=1) == O(x)
assert abs(x + x**2).series(n=2) == x + O(x**2)
assert ((1 + x)**2).series(x, n=6) == x**2 + 2*x + 1
assert (1 + 1/x).series() == 1 + 1/x
assert Derivative(exp(x).series(), x).doit() == \
1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5)
def test_issue_5654():
a = Symbol('a')
assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=0) == \
-I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(1, (x, I*a))
assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=1) == 3/(16*a**4) \
-I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(-I*a + x, (x, I*a))
def test_issue_5925():
sx = sqrt(x + z).series(z, 0, 1)
sxy = sqrt(x + y + z).series(z, 0, 1)
s1, s2 = sx.subs(x, x + y), sxy
assert (s1 - s2).expand().removeO().simplify() == 0
sx = sqrt(x + z).series(z, 0, 1)
sxy = sqrt(x + y + z).series(z, 0, 1)
assert sxy.subs({x:1, y:2}) == sx.subs(x, 3)
def test_exp_2():
assert exp(x**3).nseries(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 + x**12/24 + O(x**14)
|
696c5e214590c470d8b3e7c396d54b37b11070cd57e70102a279d7bb72137aec | """
This module implements some special functions that commonly appear in
combinatorial contexts (e.g. in power series); in particular,
sequences of rational numbers such as Bernoulli and Fibonacci numbers.
Factorials, binomial coefficients and related functions are located in
the separate 'factorials' module.
"""
from math import prod
from collections import defaultdict
from typing import Tuple as tTuple
from sympy.core import S, Symbol, Add, Dummy
from sympy.core.cache import cacheit
from sympy.core.expr import Expr
from sympy.core.function import ArgumentIndexError, Function, expand_mul
from sympy.core.logic import fuzzy_not
from sympy.core.mul import Mul
from sympy.core.numbers import E, I, pi, oo, Rational, Integer
from sympy.core.relational import Eq, is_le, is_gt
from sympy.external.gmpy import SYMPY_INTS
from sympy.functions.combinatorial.factorials import (binomial,
factorial, subfactorial)
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.piecewise import Piecewise
from sympy.ntheory.primetest import isprime, is_square
from sympy.polys.appellseqs import bernoulli_poly, euler_poly, genocchi_poly
from sympy.utilities.enumerative import MultisetPartitionTraverser
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import multiset, multiset_derangements, iterable
from sympy.utilities.memoization import recurrence_memo
from sympy.utilities.misc import as_int
from mpmath import mp, workprec
from mpmath.libmp import ifib as _ifib
def _product(a, b):
return prod(range(a, b + 1))
# Dummy symbol used for computing polynomial sequences
_sym = Symbol('x')
#----------------------------------------------------------------------------#
# #
# Carmichael numbers #
# #
#----------------------------------------------------------------------------#
def _divides(p, n):
return n % p == 0
class carmichael(Function):
r"""
Carmichael Numbers:
Certain cryptographic algorithms make use of big prime numbers.
However, checking whether a big number is prime is not so easy.
Randomized prime number checking tests exist that offer a high degree of
confidence of accurate determination at low cost, such as the Fermat test.
Let 'a' be a random number between $2$ and $n - 1$, where $n$ is the
number whose primality we are testing. Then, $n$ is probably prime if it
satisfies the modular arithmetic congruence relation:
.. math :: a^{n-1} = 1 \pmod{n}
(where mod refers to the modulo operation)
If a number passes the Fermat test several times, then it is prime with a
high probability.
Unfortunately, certain composite numbers (non-primes) still pass the Fermat
test with every number smaller than themselves.
These numbers are called Carmichael numbers.
A Carmichael number will pass a Fermat primality test to every base $b$
relatively prime to the number, even though it is not actually prime.
This makes tests based on Fermat's Little Theorem less effective than
strong probable prime tests such as the Baillie-PSW primality test and
the Miller-Rabin primality test.
Examples
========
>>> from sympy import carmichael
>>> carmichael.find_first_n_carmichaels(5)
[561, 1105, 1729, 2465, 2821]
>>> carmichael.find_carmichael_numbers_in_range(0, 562)
[561]
>>> carmichael.find_carmichael_numbers_in_range(0,1000)
[561]
>>> carmichael.find_carmichael_numbers_in_range(0,2000)
[561, 1105, 1729]
References
==========
.. [1] https://en.wikipedia.org/wiki/Carmichael_number
.. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
.. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
"""
@staticmethod
def is_perfect_square(n):
sympy_deprecation_warning(
"""
is_perfect_square is just a wrapper around sympy.ntheory.primetest.is_square
so use that directly instead.
""",
deprecated_since_version="1.11",
active_deprecations_target='deprecated-carmichael-static-methods',
)
return is_square(n)
@staticmethod
def divides(p, n):
sympy_deprecation_warning(
"""
divides can be replaced by directly testing n % p == 0.
""",
deprecated_since_version="1.11",
active_deprecations_target='deprecated-carmichael-static-methods',
)
return n % p == 0
@staticmethod
def is_prime(n):
sympy_deprecation_warning(
"""
is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that
directly instead.
""",
deprecated_since_version="1.11",
active_deprecations_target='deprecated-carmichael-static-methods',
)
return isprime(n)
@staticmethod
def is_carmichael(n):
if n >= 0:
if (n == 1) or isprime(n) or (n % 2 == 0):
return False
divisors = [1, n]
# get divisors
divisors.extend([i for i in range(3, n // 2 + 1, 2) if n % i == 0])
for i in divisors:
if is_square(i) and i != 1:
return False
if isprime(i):
if not _divides(i - 1, n - 1):
return False
return True
else:
raise ValueError('The provided number must be greater than or equal to 0')
@staticmethod
def find_carmichael_numbers_in_range(x, y):
if 0 <= x <= y:
if x % 2 == 0:
return [i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)]
else:
return [i for i in range(x, y, 2) if carmichael.is_carmichael(i)]
else:
raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
@staticmethod
def find_first_n_carmichaels(n):
i = 1
carmichaels = list()
while len(carmichaels) < n:
if carmichael.is_carmichael(i):
carmichaels.append(i)
i += 2
return carmichaels
#----------------------------------------------------------------------------#
# #
# 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
relation `F_n = F_{n-1} + F_{n-2}`. This definition
extended to arbitrary real and complex arguments using
the formula
.. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}
The Fibonacci polynomials are defined by `F_1(x) = 1`,
`F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
For all positive integers `n`, `F_n(1) = F_n`.
* ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
* ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`
Examples
========
>>> from sympy import fibonacci, Symbol
>>> [fibonacci(x) for x in range(11)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fibonacci(5, Symbol('t'))
t**4 + 3*t**2 + 1
See Also
========
bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Fibonacci_number
.. [2] http://mathworld.wolfram.com/FibonacciNumber.html
"""
@staticmethod
def _fib(n):
return _ifib(n)
@staticmethod
@recurrence_memo([None, S.One, _sym])
def _fibpoly(n, prev):
return (prev[-2] + _sym*prev[-1]).expand()
@classmethod
def eval(cls, n, sym=None):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
if sym is None:
n = int(n)
if n < 0:
return S.NegativeOne**(n + 1) * fibonacci(-n)
else:
return Integer(cls._fib(n))
else:
if n < 1:
raise ValueError("Fibonacci polynomials are defined "
"only for positive integer indices.")
return cls._fibpoly(n).subs(_sym, sym)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
from sympy.functions.elementary.miscellaneous import sqrt
return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
def _eval_rewrite_as_GoldenRatio(self,n, **kwargs):
return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1)
#----------------------------------------------------------------------------#
# #
# Lucas numbers #
# #
#----------------------------------------------------------------------------#
class lucas(Function):
"""
Lucas numbers
Lucas numbers satisfy a recurrence relation similar to that of
the Fibonacci sequence, in which each term is the sum of the
preceding two. They are generated by choosing the initial
values `L_0 = 2` and `L_1 = 1`.
* ``lucas(n)`` gives the `n^{th}` Lucas number
Examples
========
>>> from sympy import lucas
>>> [lucas(x) for x in range(11)]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Lucas_number
.. [2] http://mathworld.wolfram.com/LucasNumber.html
"""
@classmethod
def eval(cls, n):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
return fibonacci(n + 1) + fibonacci(n - 1)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
from sympy.functions.elementary.miscellaneous import sqrt
return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n)
#----------------------------------------------------------------------------#
# #
# Tribonacci numbers #
# #
#----------------------------------------------------------------------------#
class tribonacci(Function):
r"""
Tribonacci numbers / Tribonacci polynomials
The Tribonacci numbers are the integer sequence defined by the
initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.
The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
`T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`.
* ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
* ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`
Examples
========
>>> from sympy import tribonacci, Symbol
>>> [tribonacci(x) for x in range(11)]
[0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
>>> tribonacci(5, Symbol('t'))
t**8 + 3*t**5 + 3*t**2
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
.. [2] http://mathworld.wolfram.com/TribonacciNumber.html
.. [3] https://oeis.org/A000073
"""
@staticmethod
@recurrence_memo([S.Zero, S.One, S.One])
def _trib(n, prev):
return (prev[-3] + prev[-2] + prev[-1])
@staticmethod
@recurrence_memo([S.Zero, S.One, _sym**2])
def _tribpoly(n, prev):
return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand()
@classmethod
def eval(cls, n, sym=None):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
n = int(n)
if n < 0:
raise ValueError("Tribonacci polynomials are defined "
"only for non-negative integer indices.")
if sym is None:
return Integer(cls._trib(n))
else:
return cls._tribpoly(n).subs(_sym, sym)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
from sympy.functions.elementary.miscellaneous import cbrt, sqrt
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
Tn = (a**(n + 1)/((a - b)*(a - c))
+ b**(n + 1)/((b - a)*(b - c))
+ c**(n + 1)/((c - a)*(c - b)))
return Tn
def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs):
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import cbrt, sqrt
b = cbrt(586 + 102*sqrt(33))
Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4)
return floor(Tn + S.Half)
#----------------------------------------------------------------------------#
# #
# Bernoulli numbers #
# #
#----------------------------------------------------------------------------#
class bernoulli(Function):
r"""
Bernoulli numbers / Bernoulli polynomials / Bernoulli function
The Bernoulli numbers are a sequence of rational numbers
defined by `B_0 = 1` and the recursive relation (`n > 0`):
.. math :: n+1 = \sum_{k=0}^n \binom{n+1}{k} B_k
They are also commonly defined by their exponential generating
function, which is `\frac{x}{1 - e^{-x}}`. For odd indices > 1,
the Bernoulli numbers are zero.
The Bernoulli polynomials satisfy the analogous formula:
.. math :: B_n(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} B_k x^{n-k}
Bernoulli numbers and Bernoulli polynomials are related as
`B_n(1) = B_n`.
The generalized Bernoulli function `\operatorname{B}(s, a)`
is defined for any complex `s` and `a`, except where `a` is a
nonpositive integer and `s` is not a nonnegative integer. It is
an entire function of `s` for fixed `a`, related to the Hurwitz
zeta function by
.. math:: \operatorname{B}(s, a) = \begin{cases}
-s \zeta(1-s, a) & s \ne 0 \\ 1 & s = 0 \end{cases}
When `s` is a nonnegative integer this function reduces to the
Bernoulli polynomials: `\operatorname{B}(n, x) = B_n(x)`. When
`a` is omitted it is assumed to be 1, yielding the (ordinary)
Bernoulli function which interpolates the Bernoulli numbers and is
related to the Riemann zeta function.
We compute Bernoulli numbers using Ramanujan's formula:
.. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}
where:
.. math :: A(n) = \begin{cases} \frac{n+3}{3} &
n \equiv 0\ \text{or}\ 2 \pmod{6} \\
-\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}
and:
.. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}
This formula is similar to the sum given in the definition, but
cuts `\frac{2}{3}` of the terms. For Bernoulli polynomials, we use
Appell sequences.
For `n` a nonnegative integer and `s`, `a`, `x` arbitrary complex numbers,
* ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
* ``bernoulli(s)`` gives the Bernoulli function `\operatorname{B}(s)`
* ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
* ``bernoulli(s, a)`` gives the generalized Bernoulli function
`\operatorname{B}(s, a)`
.. versionchanged:: 1.12
``bernoulli(1)`` gives `+\frac{1}{2}` instead of `-\frac{1}{2}`.
This choice of value confers several theoretical advantages [5]_,
including the extension to complex parameters described above
which this function now implements. The previous behavior, defined
only for nonnegative integers `n`, can be obtained with
``(-1)**n*bernoulli(n)``.
Examples
========
>>> from sympy import bernoulli
>>> from sympy.abc import x
>>> [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
>>> bernoulli(3, x)
x**3 - 3*x**2/2 + x/2
See Also
========
andre, bell, catalan, euler, fibonacci, harmonic, lucas, genocchi,
partition, tribonacci, sympy.polys.appellseqs.bernoulli_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Bernoulli_number
.. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
.. [3] http://mathworld.wolfram.com/BernoulliNumber.html
.. [4] http://mathworld.wolfram.com/BernoulliPolynomial.html
.. [5] Peter Luschny, "The Bernoulli Manifesto",
http://luschny.de/math/zeta/The-Bernoulli-Manifesto.html
.. [6] Peter Luschny, "An introduction to the Bernoulli function",
https://arxiv.org/abs/2009.06743
"""
args: tTuple[Integer]
# 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, x=None):
if x is S.One:
return cls(n)
elif n.is_zero:
return S.One
elif n.is_integer is False or n.is_nonnegative is False:
if x is not None and x.is_Integer and x.is_nonpositive:
return S.NaN
return
# Bernoulli numbers
elif x is None:
if n is S.One:
return S.Half
elif n.is_odd and (n-1).is_positive:
return S.Zero
elif n.is_Number:
n = int(n)
# Use mpmath for enormous Bernoulli numbers
if n > 500:
p, q = mp.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
elif n.is_Number:
return bernoulli_poly(n, x)
def _eval_rewrite_as_zeta(self, n, x=1, **kwargs):
from sympy.functions.special.zeta_functions import zeta
return Piecewise((1, Eq(n, 0)), (-n * zeta(1-n, x), True))
def _eval_evalf(self, prec):
if not all(x.is_number for x in self.args):
return
n = self.args[0]._to_mpmath(prec)
x = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
with workprec(prec):
if n == 0:
res = mp.mpf(1)
elif n == 1:
res = x - mp.mpf(0.5)
elif mp.isint(n) and n >= 0:
res = mp.bernoulli(n) if x == 1 else mp.bernpoly(n, x)
else:
res = -n * mp.zeta(1-n, x)
return Expr._from_mpmath(res, prec)
#----------------------------------------------------------------------------#
# #
# Bell numbers #
# #
#----------------------------------------------------------------------------#
class bell(Function):
r"""
Bell numbers / Bell polynomials
The Bell numbers satisfy `B_0 = 1` and
.. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.
They are also given by:
.. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
The Bell polynomials are given by `B_0(x) = 1` and
.. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).
The second kind of Bell polynomials (are sometimes called "partial" Bell
polynomials or incomplete Bell polynomials) are defined as
.. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
\sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
\frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
\left(\frac{x_1}{1!} \right)^{j_1}
\left(\frac{x_2}{2!} \right)^{j_2} \dotsb
\left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
* ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
* ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
* ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
`B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
Notes
=====
Not to be confused with Bernoulli numbers and Bernoulli polynomials,
which use the same notation.
Examples
========
>>> from sympy import bell, Symbol, symbols
>>> [bell(n) for n in range(11)]
[1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
>>> bell(30)
846749014511809332450147
>>> bell(4, Symbol('t'))
t**4 + 6*t**3 + 7*t**2 + t
>>> bell(6, 2, symbols('x:6')[1:])
6*x1*x5 + 15*x2*x4 + 10*x3**2
See Also
========
bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Bell_number
.. [2] http://mathworld.wolfram.com/BellNumber.html
.. [3] http://mathworld.wolfram.com/BellPolynomial.html
"""
@staticmethod
@recurrence_memo([1, 1])
def _bell(n, prev):
s = 1
a = 1
for k in range(1, n):
a = a * (n - k) // k
s += a * prev[k]
return s
@staticmethod
@recurrence_memo([S.One, _sym])
def _bell_poly(n, prev):
s = 1
a = 1
for k in range(2, n + 1):
a = a * (n - k + 1) // (k - 1)
s += a * prev[k - 1]
return expand_mul(_sym * s)
@staticmethod
def _bell_incomplete_poly(n, k, symbols):
r"""
The second kind of Bell polynomials (incomplete Bell polynomials).
Calculated by recurrence formula:
.. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
\sum_{m=1}^{n-k+1}
\x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})
where
`B_{0,0} = 1;`
`B_{n,0} = 0; for n \ge 1`
`B_{0,k} = 0; for k \ge 1`
"""
if (n == 0) and (k == 0):
return S.One
elif (n == 0) or (k == 0):
return S.Zero
s = S.Zero
a = S.One
for m in range(1, n - k + 2):
s += a * bell._bell_incomplete_poly(
n - m, k - 1, symbols) * symbols[m - 1]
a = a * (n - m) / m
return expand_mul(s)
@classmethod
def eval(cls, n, k_sym=None, symbols=None):
if n is S.Infinity:
if k_sym is None:
return S.Infinity
else:
raise ValueError("Bell polynomial is not defined")
if n.is_negative or n.is_integer is False:
raise ValueError("a non-negative integer expected")
if n.is_Integer and n.is_nonnegative:
if k_sym is None:
return Integer(cls._bell(int(n)))
elif symbols is None:
return cls._bell_poly(int(n)).subs(_sym, k_sym)
else:
r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
return r
def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs):
from sympy.concrete.summations import Sum
if (k_sym is not None) or (symbols is not None):
return self
# Dobinski's formula
if not n.is_nonnegative:
return self
k = Dummy('k', integer=True, nonnegative=True)
return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity))
#----------------------------------------------------------------------------#
# #
# Harmonic numbers #
# #
#----------------------------------------------------------------------------#
class harmonic(Function):
r"""
Harmonic numbers
The nth harmonic number is given by `\operatorname{H}_{n} =
1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
More generally:
.. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
the Riemann zeta function.
* ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`
* ``harmonic(n, m)`` gives the nth generalized harmonic number
of order `m`, `\operatorname{H}_{n,m}`, where
``harmonic(n) == harmonic(n, 1)``
This function can be extended to complex `n` and `m` where `n` is not a
negative integer or `m` is a nonpositive integer as
.. math:: \operatorname{H}_{n,m} = \begin{cases} \zeta(m) - \zeta(m, n+1)
& m \ne 1 \\ \psi(n+1) + \gamma & m = 1 \end{cases}
Examples
========
>>> from sympy import harmonic, oo
>>> [harmonic(n) for n in range(6)]
[0, 1, 3/2, 11/6, 25/12, 137/60]
>>> [harmonic(n, 2) for n in range(6)]
[0, 1, 5/4, 49/36, 205/144, 5269/3600]
>>> harmonic(oo, 2)
pi**2/6
>>> from sympy import Symbol, Sum
>>> n = Symbol("n")
>>> harmonic(n).rewrite(Sum)
Sum(1/_k, (_k, 1, n))
We can evaluate harmonic numbers for all integral and positive
rational arguments:
>>> from sympy import S, expand_func, simplify
>>> harmonic(8)
761/280
>>> harmonic(11)
83711/27720
>>> H = harmonic(1/S(3))
>>> H
harmonic(1/3)
>>> He = expand_func(H)
>>> He
-log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
+ 3*Sum(1/(3*_k + 1), (_k, 0, 0))
>>> He.doit()
-log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
>>> H = harmonic(25/S(7))
>>> He = simplify(expand_func(H).doit())
>>> He
log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900
>>> He.n(40)
1.983697455232980674869851942390639915940
>>> harmonic(25/S(7)).n(40)
1.983697455232980674869851942390639915940
We can rewrite harmonic numbers in terms of polygamma functions:
>>> from sympy import digamma, polygamma
>>> m = Symbol("m", integer=True, positive=True)
>>> harmonic(n).rewrite(digamma)
polygamma(0, n + 1) + EulerGamma
>>> harmonic(n).rewrite(polygamma)
polygamma(0, n + 1) + EulerGamma
>>> harmonic(n,3).rewrite(polygamma)
polygamma(2, n + 1)/2 + zeta(3)
>>> simplify(harmonic(n,m).rewrite(polygamma))
Piecewise((polygamma(0, n + 1) + EulerGamma, Eq(m, 1)),
(-(-1)**m*polygamma(m - 1, n + 1)/factorial(m - 1) + zeta(m), True))
Integer offsets in the argument can be pulled out:
>>> from sympy import expand_func
>>> expand_func(harmonic(n+4))
harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
>>> expand_func(harmonic(n-4))
harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
Some limits can be computed as well:
>>> from sympy import limit, oo
>>> limit(harmonic(n), n, oo)
oo
>>> limit(harmonic(n, 2), n, oo)
pi**2/6
>>> limit(harmonic(n, 3), n, oo)
zeta(3)
For `m > 1`, `H_{n,m}` tends to `\zeta(m)` in the limit of infinite `n`:
>>> m = Symbol("m", positive=True)
>>> limit(harmonic(n, m+1), n, oo)
zeta(m + 1)
See Also
========
bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Harmonic_number
.. [2] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
.. [3] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/
"""
@classmethod
def eval(cls, n, m=None):
from sympy.functions.special.zeta_functions import zeta
if m is S.One:
return cls(n)
if m is None:
m = S.One
if n.is_zero:
return S.Zero
elif m.is_zero:
return n
elif n is S.Infinity:
if m.is_negative:
return S.NaN
elif is_le(m, S.One):
return S.Infinity
elif is_gt(m, S.One):
return zeta(m)
elif m.is_Integer and m.is_nonpositive:
return (bernoulli(1-m, n+1) - bernoulli(1-m)) / (1-m)
elif n.is_Integer:
if n.is_negative and (m.is_integer is False or m.is_nonpositive is False):
return S.ComplexInfinity if m is S.One else S.NaN
if n.is_nonnegative:
return Add(*(k**(-m) for k in range(1, int(n)+1)))
def _eval_rewrite_as_polygamma(self, n, m=S.One, **kwargs):
from sympy.functions.special.gamma_functions import gamma, polygamma
if m.is_integer and m.is_positive:
return Piecewise((polygamma(0, n+1) + S.EulerGamma, Eq(m, 1)),
(S.NegativeOne**m * (polygamma(m-1, 1) - polygamma(m-1, n+1)) /
gamma(m), True))
def _eval_rewrite_as_digamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return self.rewrite(polygamma)
def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return self.rewrite(polygamma)
def _eval_rewrite_as_Sum(self, n, m=None, **kwargs):
from sympy.concrete.summations import Sum
k = Dummy("k", integer=True)
if m is None:
m = S.One
return Sum(k**(-m), (k, 1, n))
def _eval_rewrite_as_zeta(self, n, m=S.One, **kwargs):
from sympy.functions.special.zeta_functions import zeta
from sympy.functions.special.gamma_functions import digamma
return Piecewise((digamma(n + 1) + S.EulerGamma, Eq(m, 1)),
(zeta(m) - zeta(m, n+1), True))
def _eval_expand_func(self, **hints):
from sympy.concrete.summations 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:
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.trigonometric import sin, cos, cot
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_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs):
from sympy.functions.special.zeta_functions import zeta
from sympy.functions.special.gamma_functions import polygamma
pg = self.rewrite(polygamma)
if not isinstance(pg, harmonic):
return pg.rewrite("tractable", deep=True)
arg = m - S.One
if arg.is_nonzero:
return (zeta(m) - zeta(m, n+1)).rewrite("tractable", deep=True)
def _eval_evalf(self, prec):
if not all(x.is_number for x in self.args):
return
n = self.args[0]._to_mpmath(prec)
m = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
if mp.isint(n) and n < 0:
return S.NaN
with workprec(prec):
if m == 1:
res = mp.harmonic(n)
else:
res = mp.zeta(m) - mp.zeta(m, n+1)
return Expr._from_mpmath(res, prec)
def fdiff(self, argindex=1):
from sympy.functions.special.zeta_functions import zeta
if len(self.args) == 2:
n, m = self.args
else:
n, m = self.args + (1,)
if argindex == 1:
return m * zeta(m+1, n+1)
else:
raise ArgumentIndexError
#----------------------------------------------------------------------------#
# #
# Euler numbers #
# #
#----------------------------------------------------------------------------#
class euler(Function):
r"""
Euler numbers / Euler polynomials / Euler function
The Euler numbers are given by:
.. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
\frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}
.. math:: E_{2n+1} = 0
Euler numbers and Euler polynomials are related by
.. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).
We compute symbolic Euler polynomials using Appell sequences,
but numerical evaluation of the Euler polynomial is computed
more efficiently (and more accurately) using the mpmath library.
The Euler polynomials are special cases of the generalized Euler function,
related to the Genocchi function as
.. math:: \operatorname{E}(s, a) = -\frac{\operatorname{G}(s+1, a)}{s+1}
with the limit of `\psi\left(\frac{a+1}{2}\right) - \psi\left(\frac{a}{2}\right)`
being taken when `s = -1`. The (ordinary) Euler function interpolating
the Euler numbers is then obtained as
`\operatorname{E}(s) = 2^s \operatorname{E}\left(s, \frac{1}{2}\right)`.
* ``euler(n)`` gives the nth Euler number `E_n`.
* ``euler(s)`` gives the Euler function `\operatorname{E}(s)`.
* ``euler(n, x)`` gives the nth Euler polynomial `E_n(x)`.
* ``euler(s, a)`` gives the generalized Euler function `\operatorname{E}(s, a)`.
Examples
========
>>> from sympy import euler, Symbol, S
>>> [euler(n) for n in range(10)]
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
>>> [2**n*euler(n,1) for n in range(10)]
[1, 1, 0, -2, 0, 16, 0, -272, 0, 7936]
>>> n = Symbol("n")
>>> euler(n + 2*n)
euler(3*n)
>>> x = Symbol("x")
>>> euler(n, x)
euler(n, x)
>>> euler(0, x)
1
>>> euler(1, x)
x - 1/2
>>> euler(2, x)
x**2 - x
>>> euler(3, x)
x**3 - 3*x**2/2 + 1/4
>>> euler(4, x)
x**4 - 2*x**3 + x
>>> euler(12, S.Half)
2702765/4096
>>> euler(12)
2702765
See Also
========
andre, bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi,
partition, tribonacci, sympy.polys.appellseqs.euler_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler_numbers
.. [2] http://mathworld.wolfram.com/EulerNumber.html
.. [3] https://en.wikipedia.org/wiki/Alternating_permutation
.. [4] http://mathworld.wolfram.com/AlternatingPermutation.html
"""
@classmethod
def eval(cls, n, x=None):
if n.is_zero:
return S.One
elif n is S.NegativeOne:
if x is None:
return S.Pi/2
from sympy.functions.special.gamma_functions import digamma
return digamma((x+1)/2) - digamma(x/2)
elif n.is_integer is False or n.is_nonnegative is False:
return
# Euler numbers
elif x is None:
if n.is_odd and n.is_positive:
return S.Zero
elif n.is_Number:
from mpmath import mp
n = n._to_mpmath(mp.prec)
res = mp.eulernum(n, exact=True)
return Integer(res)
# Euler polynomials
elif n.is_Number:
return euler_poly(n, x)
def _eval_rewrite_as_Sum(self, n, x=None, **kwargs):
from sympy.concrete.summations import Sum
if x is None and n.is_even:
k = Dummy("k", integer=True)
j = Dummy("j", integer=True)
n = n / 2
Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j *
(k - 2*j)**(2*n + 1)) /
(2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1)))
return Em
if x:
k = Dummy("k", integer=True)
return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n))
def _eval_rewrite_as_genocchi(self, n, x=None, **kwargs):
if x is None:
return Piecewise((S.Pi/2, Eq(n, -1)),
(-2**n * genocchi(n+1, S.Half) / (n+1), True))
from sympy.functions.special.gamma_functions import digamma
return Piecewise((digamma((x+1)/2) - digamma(x/2), Eq(n, -1)),
(-genocchi(n+1, x) / (n+1), True))
def _eval_evalf(self, prec):
if not all(i.is_number for i in self.args):
return
from mpmath import mp
m, x = (self.args[0], None) if len(self.args) == 1 else self.args
m = m._to_mpmath(prec)
if x is not None:
x = x._to_mpmath(prec)
with workprec(prec):
if mp.isint(m) and m >= 0:
res = mp.eulernum(m) if x is None else mp.eulerpoly(m, x)
else:
if m == -1:
res = mp.pi if x is None else mp.digamma((x+1)/2) - mp.digamma(x/2)
else:
y = 0.5 if x is None else x
res = 2 * (mp.zeta(-m, y) - 2**(m+1) * mp.zeta(-m, (y+1)/2))
if x is None:
res *= 2**m
return Expr._from_mpmath(res, prec)
#----------------------------------------------------------------------------#
# #
# Catalan numbers #
# #
#----------------------------------------------------------------------------#
class catalan(Function):
r"""
Catalan numbers
The `n^{th}` catalan number is given by:
.. math :: C_n = \frac{1}{n+1} \binom{2n}{n}
* ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`
Examples
========
>>> from sympy import (Symbol, binomial, gamma, hyper,
... catalan, diff, combsimp, Rational, I)
>>> [catalan(i) for i in range(1,10)]
[1, 2, 5, 14, 42, 132, 429, 1430, 4862]
>>> n = Symbol("n", integer=True)
>>> catalan(n)
catalan(n)
Catalan numbers can be transformed into several other, identical
expressions involving other mathematical functions
>>> catalan(n).rewrite(binomial)
binomial(2*n, n)/(n + 1)
>>> catalan(n).rewrite(gamma)
4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))
>>> catalan(n).rewrite(hyper)
hyper((1 - n, -n), (2,), 1)
For some non-integer values of n we can get closed form
expressions by rewriting in terms of gamma functions:
>>> catalan(Rational(1, 2)).rewrite(gamma)
8/(3*pi)
We can differentiate the Catalan numbers C(n) interpreted as a
continuous real function in n:
>>> diff(catalan(n), n)
(polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)
As a more advanced example consider the following ratio
between consecutive numbers:
>>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
2*(2*n + 1)/(n + 2)
The Catalan numbers can be generalized to complex numbers:
>>> catalan(I).rewrite(gamma)
4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))
and evaluated with arbitrary precision:
>>> catalan(I).evalf(20)
0.39764993382373624267 - 0.020884341620842555705*I
See Also
========
andre, bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi,
partition, tribonacci, sympy.functions.combinatorial.factorials.binomial
References
==========
.. [1] https://en.wikipedia.org/wiki/Catalan_number
.. [2] http://mathworld.wolfram.com/CatalanNumber.html
.. [3] http://functions.wolfram.com/GammaBetaErf/CatalanNumber/
.. [4] http://geometer.org/mathcircles/catalan.pdf
"""
@classmethod
def eval(cls, n):
from sympy.functions.special.gamma_functions import gamma
if (n.is_Integer and n.is_nonnegative) or \
(n.is_noninteger and n.is_negative):
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
if (n.is_integer and n.is_negative):
if (n + 1).is_negative:
return S.Zero
if (n + 1).is_zero:
return Rational(-1, 2)
def fdiff(self, argindex=1):
from sympy.functions.elementary.exponential import log
from sympy.functions.special.gamma_functions import polygamma
n = self.args[0]
return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4))
def _eval_rewrite_as_binomial(self, n, **kwargs):
return binomial(2*n, n)/(n + 1)
def _eval_rewrite_as_factorial(self, n, **kwargs):
return factorial(2*n) / (factorial(n+1) * factorial(n))
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
from sympy.functions.special.gamma_functions import gamma
# The gamma function allows to generalize Catalan numbers to complex n
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
def _eval_rewrite_as_hyper(self, n, **kwargs):
from sympy.functions.special.hyper import hyper
return hyper([1 - n, -n], [2], 1)
def _eval_rewrite_as_Product(self, n, **kwargs):
from sympy.concrete.products import Product
if not (n.is_integer and n.is_nonnegative):
return self
k = Dummy('k', integer=True, positive=True)
return Product((n + k) / k, (k, 2, n))
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
def _eval_is_positive(self):
if self.args[0].is_nonnegative:
return True
def _eval_is_composite(self):
if self.args[0].is_integer and (self.args[0] - 3).is_positive:
return True
def _eval_evalf(self, prec):
from sympy.functions.special.gamma_functions import gamma
if self.args[0].is_number:
return self.rewrite(gamma)._eval_evalf(prec)
#----------------------------------------------------------------------------#
# #
# Genocchi numbers #
# #
#----------------------------------------------------------------------------#
class genocchi(Function):
r"""
Genocchi numbers / Genocchi polynomials / Genocchi function
The Genocchi numbers are a sequence of integers `G_n` that satisfy the
relation:
.. math:: \frac{-2t}{1 + e^{-t}} = \sum_{n=0}^\infty \frac{G_n t^n}{n!}
They are related to the Bernoulli numbers by
.. math:: G_n = 2 (1 - 2^n) B_n
and generalize like the Bernoulli numbers to the Genocchi polynomials and
function as
.. math:: \operatorname{G}(s, a) = 2 \left(\operatorname{B}(s, a) -
2^s \operatorname{B}\left(s, \frac{a+1}{2}\right)\right)
.. versionchanged:: 1.12
``genocchi(1)`` gives `-1` instead of `1`.
Examples
========
>>> from sympy import genocchi, Symbol
>>> [genocchi(n) for n in range(9)]
[0, -1, -1, 0, 1, 0, -3, 0, 17]
>>> n = Symbol('n', integer=True, positive=True)
>>> genocchi(2*n + 1)
0
>>> x = Symbol('x')
>>> genocchi(4, x)
-4*x**3 + 6*x**2 - 1
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
sympy.polys.appellseqs.genocchi_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Genocchi_number
.. [2] http://mathworld.wolfram.com/GenocchiNumber.html
.. [3] Peter Luschny, "An introduction to the Bernoulli function",
https://arxiv.org/abs/2009.06743
"""
@classmethod
def eval(cls, n, x=None):
if x is S.One:
return cls(n)
elif n.is_integer is False or n.is_nonnegative is False:
return
# Genocchi numbers
elif x is None:
if n.is_odd and (n-1).is_positive:
return S.Zero
elif n.is_Number:
return 2 * (1-S(2)**n) * bernoulli(n)
# Genocchi polynomials
elif n.is_Number:
return genocchi_poly(n, x)
def _eval_rewrite_as_bernoulli(self, n, x=1, **kwargs):
if x == 1 and n.is_integer and n.is_nonnegative:
return 2 * (1-S(2)**n) * bernoulli(n)
return 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
def _eval_rewrite_as_dirichlet_eta(self, n, x=1, **kwargs):
from sympy.functions.special.zeta_functions import dirichlet_eta
return -2*n * dirichlet_eta(1-n, x)
def _eval_is_integer(self):
if len(self.args) > 1 and self.args[1] != 1:
return
n = self.args[0]
if n.is_integer and n.is_nonnegative:
return True
def _eval_is_negative(self):
if len(self.args) > 1 and self.args[1] != 1:
return
n = self.args[0]
if n.is_integer and n.is_nonnegative:
if n.is_odd:
return fuzzy_not((n-1).is_positive)
return (n/2).is_odd
def _eval_is_positive(self):
if len(self.args) > 1 and self.args[1] != 1:
return
n = self.args[0]
if n.is_integer and n.is_nonnegative:
if n.is_zero or n.is_odd:
return False
return (n/2).is_even
def _eval_is_even(self):
if len(self.args) > 1 and self.args[1] != 1:
return
n = self.args[0]
if n.is_integer and n.is_nonnegative:
if n.is_even:
return n.is_zero
return (n-1).is_positive
def _eval_is_odd(self):
if len(self.args) > 1 and self.args[1] != 1:
return
n = self.args[0]
if n.is_integer and n.is_nonnegative:
if n.is_even:
return fuzzy_not(n.is_zero)
return fuzzy_not((n-1).is_positive)
def _eval_is_prime(self):
if len(self.args) > 1 and self.args[1] != 1:
return
n = self.args[0]
# only G_6 = -3 and G_8 = 17 are prime,
# but SymPy does not consider negatives as prime
# so only n=8 is tested
return (n-8).is_zero
def _eval_evalf(self, prec):
if all(i.is_number for i in self.args):
return self.rewrite(bernoulli)._eval_evalf(prec)
#----------------------------------------------------------------------------#
# #
# Andre numbers #
# #
#----------------------------------------------------------------------------#
class andre(Function):
r"""
Andre numbers / Andre function
The Andre number `\mathcal{A}_n` is Luschny's name for half the number of
*alternating permutations* on `n` elements, where a permutation is alternating
if adjacent elements alternately compare "greater" and "smaller" going from
left to right. For example, `2 < 3 > 1 < 4` is an alternating permutation.
This sequence is A000111 in the OEIS, which assigns the names *up/down numbers*
and *Euler zigzag numbers*. It satisfies a recurrence relation similar to that
for the Catalan numbers, with `\mathcal{A}_0 = 1` and
.. math:: 2 \mathcal{A}_{n+1} = \sum_{k=0}^n \binom{n}{k} \mathcal{A}_k \mathcal{A}_{n-k}
The Bernoulli and Euler numbers are signed transformations of the odd- and
even-indexed elements of this sequence respectively:
.. math :: \operatorname{B}_{2k} = \frac{2k \mathcal{A}_{2k-1}}{(-4)^k - (-16)^k}
.. math :: \operatorname{E}_{2k} = (-1)^k \mathcal{A}_{2k}
Like the Bernoulli and Euler numbers, the Andre numbers are interpolated by the
entire Andre function:
.. math :: \mathcal{A}(s) = (-i)^{s+1} \operatorname{Li}_{-s}(i) +
i^{s+1} \operatorname{Li}_{-s}(-i) = \\ \frac{2 \Gamma(s+1)}{(2\pi)^{s+1}}
(\zeta(s+1, 1/4) - \zeta(s+1, 3/4) \cos{\pi s})
Examples
========
>>> from sympy import andre, euler, bernoulli
>>> [andre(n) for n in range(11)]
[1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
>>> [(-1)**k * andre(2*k) for k in range(7)]
[1, -1, 5, -61, 1385, -50521, 2702765]
>>> [euler(2*k) for k in range(7)]
[1, -1, 5, -61, 1385, -50521, 2702765]
>>> [andre(2*k-1) * (2*k) / ((-4)**k - (-16)**k) for k in range(1, 8)]
[1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
>>> [bernoulli(2*k) for k in range(1, 8)]
[1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
See Also
========
bernoulli, catalan, euler, sympy.polys.appellseqs.andre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Alternating_permutation
.. [2] https://mathworld.wolfram.com/EulerZigzagNumber.html
.. [3] Peter Luschny, "An introduction to the Bernoulli function",
https://arxiv.org/abs/2009.06743
"""
@classmethod
def eval(cls, n):
if n is S.NaN:
return S.NaN
elif n is S.Infinity:
return S.Infinity
if n.is_zero:
return S.One
elif n == -1:
return -log(2)
elif n == -2:
return -2*S.Catalan
elif n.is_Integer:
if n.is_nonnegative and n.is_even:
return abs(euler(n))
elif n.is_odd:
from sympy.functions.special.zeta_functions import zeta
m = -n-1
return I**m * Rational(1-2**m, 4**m) * zeta(-n)
def _eval_rewrite_as_zeta(self, s, **kwargs):
from sympy.functions.elementary.trigonometric import cos
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.zeta_functions import zeta
return 2 * gamma(s+1) / (2*pi)**(s+1) * \
(zeta(s+1, S.One/4) - cos(pi*s) * zeta(s+1, S(3)/4))
def _eval_rewrite_as_polylog(self, s, **kwargs):
from sympy.functions.special.zeta_functions import polylog
return (-I)**(s+1) * polylog(-s, I) + I**(s+1) * polylog(-s, -I)
def _eval_is_integer(self):
n = self.args[0]
if n.is_integer and n.is_nonnegative:
return True
def _eval_is_positive(self):
if self.args[0].is_nonnegative:
return True
def _eval_evalf(self, prec):
if not self.args[0].is_number:
return
s = self.args[0]._to_mpmath(prec+12)
with workprec(prec+12):
sp, cp = mp.sinpi(s/2), mp.cospi(s/2)
res = 2*mp.dirichlet(-s, (-sp, cp, sp, -cp))
return Expr._from_mpmath(res, prec)
#----------------------------------------------------------------------------#
# #
# Partition numbers #
# #
#----------------------------------------------------------------------------#
_npartition = [1, 1]
class partition(Function):
r"""
Partition numbers
The Partition numbers are a sequence of integers `p_n` that represent the
number of distinct ways of representing `n` as a sum of natural numbers
(with order irrelevant). The generating function for `p_n` is given by:
.. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}
Examples
========
>>> from sympy import partition, Symbol
>>> [partition(n) for n in range(9)]
[1, 1, 2, 3, 5, 7, 11, 15, 22]
>>> n = Symbol('n', integer=True, negative=True)
>>> partition(n)
0
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
.. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem
"""
@staticmethod
def _partition(n):
L = len(_npartition)
if n < L:
return _npartition[n]
# lengthen cache
for _n in range(L, n + 1):
v, p, i = 0, 0, 0
while 1:
s = 0
p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ...
if _n >= p:
s += _npartition[_n - p]
i += 1
gp = p + i # gp = generalized pentagonal: 2, 7, 15, ...
if _n >= gp:
s += _npartition[_n - gp]
if s == 0:
break
else:
v += s if i%2 == 1 else -s
_npartition.append(v)
return v
@classmethod
def eval(cls, n):
is_int = n.is_integer
if is_int == False:
raise ValueError("Partition numbers are defined only for "
"integers")
elif is_int:
if n.is_negative:
return S.Zero
if n.is_zero or (n - 1).is_zero:
return S.One
if n.is_Integer:
return Integer(cls._partition(n))
def _eval_is_integer(self):
if self.args[0].is_integer:
return True
def _eval_is_negative(self):
if self.args[0].is_integer:
return False
def _eval_is_positive(self):
n = self.args[0]
if n.is_nonnegative and n.is_integer:
return True
#######################################################################
###
### Functions for enumerating partitions, permutations and combinations
###
#######################################################################
class _MultisetHistogram(tuple):
pass
_N = -1
_ITEMS = -2
_M = slice(None, _ITEMS)
def _multiset_histogram(n):
"""Return tuple used in permutation and combination counting. Input
is a dictionary giving items with counts as values or a sequence of
items (which need not be sorted).
The data is stored in a class deriving from tuple so it is easily
recognized and so it can be converted easily to a list.
"""
if isinstance(n, dict): # item: count
if not all(isinstance(v, int) and v >= 0 for v in n.values()):
raise ValueError
tot = sum(n.values())
items = sum(1 for k in n if n[k] > 0)
return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot])
else:
n = list(n)
s = set(n)
lens = len(s)
lenn = len(n)
if lens == lenn:
n = [1]*lenn + [lenn, lenn]
return _MultisetHistogram(n)
m = dict(zip(s, range(lens)))
d = dict(zip(range(lens), (0,)*lens))
for i in n:
d[m[i]] += 1
return _multiset_histogram(d)
def nP(n, k=None, replacement=False):
"""Return the number of permutations of ``n`` items taken ``k`` at a time.
Possible values for ``n``:
integer - set of length ``n``
sequence - converted to a multiset internally
multiset - {element: multiplicity}
If ``k`` is None then the total of all permutations of length 0
through the number of items represented by ``n`` will be returned.
If ``replacement`` is True then a given item can appear more than once
in the ``k`` items. (For example, for 'ab' permutations of 2 would
include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
``n`` is ignored when ``replacement`` is True but the total number
of elements is considered since no element can appear more times than
the number of elements in ``n``.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nP
>>> from sympy.utilities.iterables import multiset_permutations, multiset
>>> nP(3, 2)
6
>>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
True
>>> nP('aab', 2)
3
>>> nP([1, 2, 2], 2)
3
>>> [nP(3, i) for i in range(4)]
[1, 3, 6, 6]
>>> nP(3) == sum(_)
True
When ``replacement`` is True, each item can have multiplicity
equal to the length represented by ``n``:
>>> nP('aabc', replacement=True)
121
>>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
[1, 3, 9, 27, 81]
>>> sum(_)
121
See Also
========
sympy.utilities.iterables.multiset_permutations
References
==========
.. [1] https://en.wikipedia.org/wiki/Permutation
"""
try:
n = as_int(n)
except ValueError:
return Integer(_nP(_multiset_histogram(n), k, replacement))
return Integer(_nP(n, k, replacement))
@cacheit
def _nP(n, k=None, replacement=False):
if k == 0:
return 1
if isinstance(n, SYMPY_INTS): # n different items
# assert n >= 0
if k is None:
return sum(_nP(n, i, replacement) for i in range(n + 1))
elif replacement:
return n**k
elif k > n:
return 0
elif k == n:
return factorial(k)
elif k == 1:
return n
else:
# assert k >= 0
return _product(n - k + 1, n)
elif isinstance(n, _MultisetHistogram):
if k is None:
return sum(_nP(n, i, replacement) for i in range(n[_N] + 1))
elif replacement:
return n[_ITEMS]**k
elif k == n[_N]:
return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1])
elif k > n[_N]:
return 0
elif k == 1:
return n[_ITEMS]
else:
# assert k >= 0
tot = 0
n = list(n)
for i in range(len(n[_M])):
if not n[i]:
continue
n[_N] -= 1
if n[i] == 1:
n[i] = 0
n[_ITEMS] -= 1
tot += _nP(_MultisetHistogram(n), k - 1)
n[_ITEMS] += 1
n[i] = 1
else:
n[i] -= 1
tot += _nP(_MultisetHistogram(n), k - 1)
n[i] += 1
n[_N] += 1
return tot
@cacheit
def _AOP_product(n):
"""for n = (m1, m2, .., mk) return the coefficients of the polynomial,
prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
of the product of AOPs (all-one polynomials) or order given in n. The
resulting coefficient corresponding to x**r is the number of r-length
combinations of sum(n) elements with multiplicities given in n.
The coefficients are given as a default dictionary (so if a query is made
for a key that is not present, 0 will be returned).
Examples
========
>>> from sympy.functions.combinatorial.numbers import _AOP_product
>>> from sympy.abc import x
>>> n = (2, 2, 3) # e.g. aabbccc
>>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
>>> c = _AOP_product(n); dict(c)
{0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
>>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
True
The generating poly used here is the same as that listed in
http://tinyurl.com/cep849r, but in a refactored form.
"""
n = list(n)
ord = sum(n)
need = (ord + 2)//2
rv = [1]*(n.pop() + 1)
rv.extend((0,) * (need - len(rv)))
rv = rv[:need]
while n:
ni = n.pop()
N = ni + 1
was = rv[:]
for i in range(1, min(N, len(rv))):
rv[i] += rv[i - 1]
for i in range(N, need):
rv[i] += rv[i - 1] - was[i - N]
rev = list(reversed(rv))
if ord % 2:
rv = rv + rev
else:
rv[-1:] = rev
d = defaultdict(int)
for i, r in enumerate(rv):
d[i] = r
return d
def nC(n, k=None, replacement=False):
"""Return the number of combinations of ``n`` items taken ``k`` at a time.
Possible values for ``n``:
integer - set of length ``n``
sequence - converted to a multiset internally
multiset - {element: multiplicity}
If ``k`` is None then the total of all combinations of length 0
through the number of items represented in ``n`` will be returned.
If ``replacement`` is True then a given item can appear more than once
in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
``replacement`` is True but the total number of elements is considered
since no element can appear more times than the number of elements in
``n``.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nC
>>> from sympy.utilities.iterables import multiset_combinations
>>> nC(3, 2)
3
>>> nC('abc', 2)
3
>>> nC('aab', 2)
2
When ``replacement`` is True, each item can have multiplicity
equal to the length represented by ``n``:
>>> nC('aabc', replacement=True)
35
>>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
[1, 3, 6, 10, 15]
>>> sum(_)
35
If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
then the total of all combinations of length 0 through ``k`` is the
product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
of each item is 1 (i.e., k unique items) then there are 2**k
combinations. For example, if there are 4 unique items, the total number
of combinations is 16:
>>> sum(nC(4, i) for i in range(5))
16
See Also
========
sympy.utilities.iterables.multiset_combinations
References
==========
.. [1] https://en.wikipedia.org/wiki/Combination
.. [2] http://tinyurl.com/cep849r
"""
if isinstance(n, SYMPY_INTS):
if k is None:
if not replacement:
return 2**n
return sum(nC(n, i, replacement) for i in range(n + 1))
if k < 0:
raise ValueError("k cannot be negative")
if replacement:
return binomial(n + k - 1, k)
return binomial(n, k)
if isinstance(n, _MultisetHistogram):
N = n[_N]
if k is None:
if not replacement:
return prod(m + 1 for m in n[_M])
return sum(nC(n, i, replacement) for i in range(N + 1))
elif replacement:
return nC(n[_ITEMS], k, replacement)
# assert k >= 0
elif k in (1, N - 1):
return n[_ITEMS]
elif k in (0, N):
return 1
return _AOP_product(tuple(n[_M]))[k]
else:
return nC(_multiset_histogram(n), k, replacement)
def _eval_stirling1(n, k):
if n == k == 0:
return S.One
if 0 in (n, k):
return S.Zero
# some special values
if n == k:
return S.One
elif k == n - 1:
return binomial(n, 2)
elif k == n - 2:
return (3*n - 1)*binomial(n, 3)/4
elif k == n - 3:
return binomial(n, 2)*binomial(n, 4)
return _stirling1(n, k)
@cacheit
def _stirling1(n, k):
row = [0, 1]+[0]*(k-1) # for n = 1
for i in range(2, n+1):
for j in range(min(k,i), 0, -1):
row[j] = (i-1) * row[j] + row[j-1]
return Integer(row[k])
def _eval_stirling2(n, k):
if n == k == 0:
return S.One
if 0 in (n, k):
return S.Zero
# some special values
if n == k:
return S.One
elif k == n - 1:
return binomial(n, 2)
elif k == 1:
return S.One
elif k == 2:
return Integer(2**(n - 1) - 1)
return _stirling2(n, k)
@cacheit
def _stirling2(n, k):
row = [0, 1]+[0]*(k-1) # for n = 1
for i in range(2, n+1):
for j in range(min(k,i), 0, -1):
row[j] = j * row[j] + row[j-1]
return Integer(row[k])
def stirling(n, k, d=None, kind=2, signed=False):
r"""Return Stirling number $S(n, k)$ of the first or second (default) kind.
The sum of all Stirling numbers of the second kind for $k = 1$
through $n$ is ``bell(n)``. The recurrence relationship for these numbers
is:
.. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;
.. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}
where $j$ is:
$n$ for Stirling numbers of the first kind,
$-n$ for signed Stirling numbers of the first kind,
$k$ for Stirling numbers of the second kind.
The first kind of Stirling number counts the number of permutations of
``n`` distinct items that have ``k`` cycles; the second kind counts the
ways in which ``n`` distinct items can be partitioned into ``k`` parts.
If ``d`` is given, the "reduced Stirling number of the second kind" is
returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
(This counts the ways to partition $n$ consecutive integers into $k$
groups with no pairwise difference less than $d$. See example below.)
To obtain the signed Stirling numbers of the first kind, use keyword
``signed=True``. Using this keyword automatically sets ``kind`` to 1.
Examples
========
>>> from sympy.functions.combinatorial.numbers import stirling, bell
>>> from sympy.combinatorics import Permutation
>>> from sympy.utilities.iterables import multiset_partitions, permutations
First kind (unsigned by default):
>>> [stirling(6, i, kind=1) for i in range(7)]
[0, 120, 274, 225, 85, 15, 1]
>>> perms = list(permutations(range(4)))
>>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
[0, 6, 11, 6, 1]
>>> [stirling(4, i, kind=1) for i in range(5)]
[0, 6, 11, 6, 1]
First kind (signed):
>>> [stirling(4, i, signed=True) for i in range(5)]
[0, -6, 11, -6, 1]
Second kind:
>>> [stirling(10, i) for i in range(12)]
[0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
>>> sum(_) == bell(10)
True
>>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
True
Reduced second kind:
>>> from sympy import subsets, oo
>>> def delta(p):
... if len(p) == 1:
... return oo
... return min(abs(i[0] - i[1]) for i in subsets(p, 2))
>>> parts = multiset_partitions(range(5), 3)
>>> d = 2
>>> sum(1 for p in parts if all(delta(i) >= d for i in p))
7
>>> stirling(5, 3, 2)
7
See Also
========
sympy.utilities.iterables.multiset_partitions
References
==========
.. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
.. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
"""
# TODO: make this a class like bell()
n = as_int(n)
k = as_int(k)
if n < 0:
raise ValueError('n must be nonnegative')
if k > n:
return S.Zero
if d:
# assert k >= d
# kind is ignored -- only kind=2 is supported
return _eval_stirling2(n - d + 1, k - d + 1)
elif signed:
# kind is ignored -- only kind=1 is supported
return S.NegativeOne**(n - k)*_eval_stirling1(n, k)
if kind == 1:
return _eval_stirling1(n, k)
elif kind == 2:
return _eval_stirling2(n, k)
else:
raise ValueError('kind must be 1 or 2, not %s' % k)
@cacheit
def _nT(n, k):
"""Return the partitions of ``n`` items into ``k`` parts. This
is used by ``nT`` for the case when ``n`` is an integer."""
# really quick exits
if k > n or k < 0:
return 0
if k in (1, n):
return 1
if k == 0:
return 0
# exits that could be done below but this is quicker
if k == 2:
return n//2
d = n - k
if d <= 3:
return d
# quick exit
if 3*k >= n: # or, equivalently, 2*k >= d
# all the information needed in this case
# will be in the cache needed to calculate
# partition(d), so...
# update cache
tot = partition._partition(d)
# and correct for values not needed
if d - k > 0:
tot -= sum(_npartition[:d - k])
return tot
# regular exit
# nT(n, k) = Sum(nT(n - k, m), (m, 1, k));
# calculate needed nT(i, j) values
p = [1]*d
for i in range(2, k + 1):
for m in range(i + 1, d):
p[m] += p[m - i]
d -= 1
# if p[0] were appended to the end of p then the last
# k values of p are the nT(n, j) values for 0 < j < k in reverse
# order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of
# putting the 1 from p[0] there, however, it is simply added to
# the sum below which is valid for 1 < k <= n//2
return (1 + sum(p[1 - k:]))
def nT(n, k=None):
"""Return the number of ``k``-sized partitions of ``n`` items.
Possible values for ``n``:
integer - ``n`` identical items
sequence - converted to a multiset internally
multiset - {element: multiplicity}
Note: the convention for ``nT`` is different than that of ``nC`` and
``nP`` in that
here an integer indicates ``n`` *identical* items instead of a set of
length ``n``; this is in keeping with the ``partitions`` function which
treats its integer-``n`` input like a list of ``n`` 1s. One can use
``range(n)`` for ``n`` to indicate ``n`` distinct items.
If ``k`` is None then the total number of ways to partition the elements
represented in ``n`` will be returned.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nT
Partitions of the given multiset:
>>> [nT('aabbc', i) for i in range(1, 7)]
[1, 8, 11, 5, 1, 0]
>>> nT('aabbc') == sum(_)
True
>>> [nT("mississippi", i) for i in range(1, 12)]
[1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]
Partitions when all items are identical:
>>> [nT(5, i) for i in range(1, 6)]
[1, 2, 2, 1, 1]
>>> nT('1'*5) == sum(_)
True
When all items are different:
>>> [nT(range(5), i) for i in range(1, 6)]
[1, 15, 25, 10, 1]
>>> nT(range(5)) == sum(_)
True
Partitions of an integer expressed as a sum of positive integers:
>>> from sympy import partition
>>> partition(4)
5
>>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
5
>>> nT('1'*4)
5
See Also
========
sympy.utilities.iterables.partitions
sympy.utilities.iterables.multiset_partitions
sympy.functions.combinatorial.numbers.partition
References
==========
.. [1] http://undergraduate.csse.uwa.edu.au/units/CITS7209/partition.pdf
"""
if isinstance(n, SYMPY_INTS):
# n identical items
if k is None:
return partition(n)
if isinstance(k, SYMPY_INTS):
n = as_int(n)
k = as_int(k)
return Integer(_nT(n, k))
if not isinstance(n, _MultisetHistogram):
try:
# if n contains hashable items there is some
# quick handling that can be done
u = len(set(n))
if u <= 1:
return nT(len(n), k)
elif u == len(n):
n = range(u)
raise TypeError
except TypeError:
n = _multiset_histogram(n)
N = n[_N]
if k is None and N == 1:
return 1
if k in (1, N):
return 1
if k == 2 or N == 2 and k is None:
m, r = divmod(N, 2)
rv = sum(nC(n, i) for i in range(1, m + 1))
if not r:
rv -= nC(n, m)//2
if k is None:
rv += 1 # for k == 1
return rv
if N == n[_ITEMS]:
# all distinct
if k is None:
return bell(N)
return stirling(N, k)
m = MultisetPartitionTraverser()
if k is None:
return m.count_partitions(n[_M])
# MultisetPartitionTraverser does not have a range-limited count
# method, so need to enumerate and count
tot = 0
for discard in m.enum_range(n[_M], k-1, k):
tot += 1
return tot
#-----------------------------------------------------------------------------#
# #
# Motzkin numbers #
# #
#-----------------------------------------------------------------------------#
class motzkin(Function):
"""
The nth Motzkin number is the number
of ways of drawing non-intersecting chords
between n points on a circle (not necessarily touching
every point by a chord). The Motzkin numbers are named
after Theodore Motzkin and have diverse applications
in geometry, combinatorics and number theory.
Motzkin numbers are the integer sequence defined by the
initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
`M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`.
Examples
========
>>> from sympy import motzkin
>>> motzkin.is_motzkin(5)
False
>>> motzkin.find_motzkin_numbers_in_range(2,300)
[2, 4, 9, 21, 51, 127]
>>> motzkin.find_motzkin_numbers_in_range(2,900)
[2, 4, 9, 21, 51, 127, 323, 835]
>>> motzkin.find_first_n_motzkins(10)
[1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
References
==========
.. [1] https://en.wikipedia.org/wiki/Motzkin_number
.. [2] https://mathworld.wolfram.com/MotzkinNumber.html
"""
@staticmethod
def is_motzkin(n):
try:
n = as_int(n)
except ValueError:
return False
if n > 0:
if n in (1, 2):
return True
tn1 = 1
tn = 2
i = 3
while tn < n:
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = a
if tn == n:
return True
else:
return False
else:
return False
@staticmethod
def find_motzkin_numbers_in_range(x, y):
if 0 <= x <= y:
motzkins = list()
if x <= 1 <= y:
motzkins.append(1)
tn1 = 1
tn = 2
i = 3
while tn <= y:
if tn >= x:
motzkins.append(tn)
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = int(a)
return motzkins
else:
raise ValueError('The provided range is not valid. This condition should satisfy x <= y')
@staticmethod
def find_first_n_motzkins(n):
try:
n = as_int(n)
except ValueError:
raise ValueError('The provided number must be a positive integer')
if n < 0:
raise ValueError('The provided number must be a positive integer')
motzkins = [1]
if n >= 1:
motzkins.append(1)
tn1 = 1
tn = 2
i = 3
while i <= n:
motzkins.append(tn)
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = int(a)
return motzkins
@staticmethod
@recurrence_memo([S.One, S.One])
def _motzkin(n, prev):
return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2)
@classmethod
def eval(cls, n):
try:
n = as_int(n)
except ValueError:
raise ValueError('The provided number must be a positive integer')
if n < 0:
raise ValueError('The provided number must be a positive integer')
return Integer(cls._motzkin(n - 1))
def nD(i=None, brute=None, *, n=None, m=None):
"""return the number of derangements for: ``n`` unique items, ``i``
items (as a sequence or multiset), or multiplicities, ``m`` given
as a sequence or multiset.
Examples
========
>>> from sympy.utilities.iterables import generate_derangements as enum
>>> from sympy.functions.combinatorial.numbers import nD
A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``:
>>> set([''.join(i) for i in enum('abc')])
{'bca', 'cab'}
>>> nD('abc')
2
Input as iterable or dictionary (multiset form) is accepted:
>>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3})
By default, a brute-force enumeration and count of multiset permutations
is only done if there are fewer than 9 elements. There may be cases when
there is high multiplicty with few unique elements that will benefit
from a brute-force enumeration, too. For this reason, the `brute`
keyword (default None) is provided. When False, the brute-force
enumeration will never be used. When True, it will always be used.
>>> nD('1111222233', brute=True)
44
For convenience, one may specify ``n`` distinct items using the
``n`` keyword:
>>> assert nD(n=3) == nD('abc') == 2
Since the number of derangments depends on the multiplicity of the
elements and not the elements themselves, it may be more convenient
to give a list or multiset of multiplicities using keyword ``m``:
>>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2
"""
from sympy.integrals.integrals import integrate
from sympy.functions.special.polynomials import laguerre
from sympy.abc import x
def ok(x):
if not isinstance(x, SYMPY_INTS):
raise TypeError('expecting integer values')
if x < 0:
raise ValueError('value must not be negative')
return True
if (i, n, m).count(None) != 2:
raise ValueError('enter only 1 of i, n, or m')
if i is not None:
if isinstance(i, SYMPY_INTS):
raise TypeError('items must be a list or dictionary')
if not i:
return S.Zero
if type(i) is not dict:
s = list(i)
ms = multiset(s)
elif type(i) is dict:
all(ok(_) for _ in i.values())
ms = {k: v for k, v in i.items() if v}
s = None
if not ms:
return S.Zero
N = sum(ms.values())
counts = multiset(ms.values())
nkey = len(ms)
elif n is not None:
ok(n)
if not n:
return S.Zero
return subfactorial(n)
elif m is not None:
if isinstance(m, dict):
all(ok(i) and ok(j) for i, j in m.items())
counts = {k: v for k, v in m.items() if k*v}
elif iterable(m) or isinstance(m, str):
m = list(m)
all(ok(i) for i in m)
counts = multiset([i for i in m if i])
else:
raise TypeError('expecting iterable')
if not counts:
return S.Zero
N = sum(k*v for k, v in counts.items())
nkey = sum(counts.values())
s = None
big = int(max(counts))
if big == 1: # no repetition
return subfactorial(nkey)
nval = len(counts)
if big*2 > N:
return S.Zero
if big*2 == N:
if nkey == 2 and nval == 1:
return S.One # aaabbb
if nkey - 1 == big: # one element repeated
return factorial(big) # e.g. abc part of abcddd
if N < 9 and brute is None or brute:
# for all possibilities, this was found to be faster
if s is None:
s = []
i = 0
for m, v in counts.items():
for j in range(v):
s.extend([i]*m)
i += 1
return Integer(sum(1 for i in multiset_derangements(s)))
from sympy.functions.elementary.exponential import exp
return Integer(abs(integrate(exp(-x)*Mul(*[
laguerre(i, x)**m for i, m in counts.items()]), (x, 0, oo))))
|
e2fbb6b2e8d90b5518a397684ce63847038687d715c3a6a313e0f6119d817c98 | from sympy.core import S, Function, diff, Tuple, Dummy, Mul
from sympy.core.basic import Basic, as_Basic
from sympy.core.numbers import Rational, NumberSymbol, _illegal
from sympy.core.parameters import global_parameters
from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational,
_canonical, _canonical_coeff)
from sympy.core.sorting import ordered
from sympy.functions.elementary.miscellaneous import Max, Min
from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not,
true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and)
from sympy.utilities.iterables import uniq, sift, common_prefix
from sympy.utilities.misc import filldedent, func_name
from itertools import product
Undefined = S.NaN # Piecewise()
class ExprCondPair(Tuple):
"""Represents an expression, condition pair."""
def __new__(cls, expr, cond):
expr = as_Basic(expr)
if cond == True:
return Tuple.__new__(cls, expr, true)
elif cond == False:
return Tuple.__new__(cls, expr, false)
elif isinstance(cond, Basic) and cond.has(Piecewise):
cond = piecewise_fold(cond)
if isinstance(cond, Piecewise):
cond = cond.rewrite(ITE)
if not isinstance(cond, Boolean):
raise TypeError(filldedent('''
Second argument must be a Boolean,
not `%s`''' % func_name(cond)))
return Tuple.__new__(cls, expr, cond)
@property
def expr(self):
"""
Returns the expression of this pair.
"""
return self.args[0]
@property
def cond(self):
"""
Returns the condition of this pair.
"""
return self.args[1]
@property
def is_commutative(self):
return self.expr.is_commutative
def __iter__(self):
yield self.expr
yield self.cond
def _eval_simplify(self, **kwargs):
return self.func(*[a.simplify(**kwargs) for a in self.args])
class Piecewise(Function):
"""
Represents a piecewise function.
Usage:
Piecewise( (expr,cond), (expr,cond), ... )
- Each argument is a 2-tuple defining an expression and condition
- The conds are evaluated in turn returning the first that is True.
If any of the evaluated conds are not explicitly False,
e.g. ``x < 1``, the function is returned in symbolic form.
- If the function is evaluated at a place where all conditions are False,
nan will be returned.
- Pairs where the cond is explicitly False, will be removed and no pair
appearing after a True condition will ever be retained. If a single
pair with a True condition remains, it will be returned, even when
evaluation is False.
Examples
========
>>> from sympy import Piecewise, log, piecewise_fold
>>> from sympy.abc import x, y
>>> f = x**2
>>> g = log(x)
>>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
>>> p.subs(x,1)
1
>>> p.subs(x,5)
log(5)
Booleans can contain Piecewise elements:
>>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond
Piecewise((2, x < 0), (3, True)) < y
The folded version of this results in a Piecewise whose
expressions are Booleans:
>>> folded_cond = piecewise_fold(cond); folded_cond
Piecewise((2 < y, x < 0), (3 < y, True))
When a Boolean containing Piecewise (like cond) or a Piecewise
with Boolean expressions (like folded_cond) is used as a condition,
it is converted to an equivalent :class:`~.ITE` object:
>>> Piecewise((1, folded_cond))
Piecewise((1, ITE(x < 0, y > 2, y > 3)))
When a condition is an ``ITE``, it will be converted to a simplified
Boolean expression:
>>> piecewise_fold(_)
Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0))))
See Also
========
piecewise_fold
piecewise_exclusive
ITE
"""
nargs = None
is_Piecewise = True
def __new__(cls, *args, **options):
if len(args) == 0:
raise TypeError("At least one (expr, cond) pair expected.")
# (Try to) sympify args first
newargs = []
for ec in args:
# ec could be a ExprCondPair or a tuple
pair = ExprCondPair(*getattr(ec, 'args', ec))
cond = pair.cond
if cond is false:
continue
newargs.append(pair)
if cond is true:
break
eval = options.pop('evaluate', global_parameters.evaluate)
if eval:
r = cls.eval(*newargs)
if r is not None:
return r
elif len(newargs) == 1 and newargs[0].cond == True:
return newargs[0].expr
return Basic.__new__(cls, *newargs, **options)
@classmethod
def eval(cls, *_args):
"""Either return a modified version of the args or, if no
modifications were made, return None.
Modifications that are made here:
1. relationals are made canonical
2. any False conditions are dropped
3. any repeat of a previous condition is ignored
4. any args past one with a true condition are dropped
If there are no args left, nan will be returned.
If there is a single arg with a True condition, its
corresponding expression will be returned.
EXAMPLES
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> cond = -x < -1
>>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)]
>>> Piecewise(*args, evaluate=False)
Piecewise((1, -x < -1), (4, -x < -1), (2, True))
>>> Piecewise(*args)
Piecewise((1, x > 1), (2, True))
"""
if not _args:
return Undefined
if len(_args) == 1 and _args[0][-1] == True:
return _args[0][0]
newargs = _piecewise_collapse_arguments(_args)
# some conditions may have been redundant
missing = len(newargs) != len(_args)
# some conditions may have changed
same = all(a == b for a, b in zip(newargs, _args))
# if either change happened we return the expr with the
# updated args
if not newargs:
raise ValueError(filldedent('''
There are no conditions (or none that
are not trivially false) to define an
expression.'''))
if missing or not same:
return cls(*newargs)
def doit(self, **hints):
"""
Evaluate this piecewise function.
"""
newargs = []
for e, c in self.args:
if hints.get('deep', True):
if isinstance(e, Basic):
newe = e.doit(**hints)
if newe != self:
e = newe
if isinstance(c, Basic):
c = c.doit(**hints)
newargs.append((e, c))
return self.func(*newargs)
def _eval_simplify(self, **kwargs):
return piecewise_simplify(self, **kwargs)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
for e, c in self.args:
if c == True or c.subs(x, 0) == True:
return e.as_leading_term(x)
def _eval_adjoint(self):
return self.func(*[(e.adjoint(), c) for e, c in self.args])
def _eval_conjugate(self):
return self.func(*[(e.conjugate(), c) for e, c in self.args])
def _eval_derivative(self, x):
return self.func(*[(diff(e, x), c) for e, c in self.args])
def _eval_evalf(self, prec):
return self.func(*[(e._evalf(prec), c) for e, c in self.args])
def piecewise_integrate(self, x, **kwargs):
"""Return the Piecewise with each expression being
replaced with its antiderivative. To obtain a continuous
antiderivative, use the :func:`~.integrate` function or method.
Examples
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
>>> p.piecewise_integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
Note that this does not give a continuous function, e.g.
at x = 1 the 3rd condition applies and the antiderivative
there is 2*x so the value of the antiderivative is 2:
>>> anti = _
>>> anti.subs(x, 1)
2
The continuous derivative accounts for the integral *up to*
the point of interest, however:
>>> p.integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
>>> _.subs(x, 1)
1
See Also
========
Piecewise._eval_integral
"""
from sympy.integrals import integrate
return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
def _handle_irel(self, x, handler):
"""Return either None (if the conditions of self depend only on x) else
a Piecewise expression whose expressions (handled by the handler that
was passed) are paired with the governing x-independent relationals,
e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) ->
Piecewise(
(handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)),
(handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)),
(handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)),
(handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True))
"""
# identify governing relationals
rel = self.atoms(Relational)
irel = list(ordered([r for r in rel if x not in r.free_symbols
and r not in (S.true, S.false)]))
if irel:
args = {}
exprinorder = []
for truth in product((1, 0), repeat=len(irel)):
reps = dict(zip(irel, truth))
# only store the true conditions since the false are implied
# when they appear lower in the Piecewise args
if 1 not in truth:
cond = None # flag this one so it doesn't get combined
else:
andargs = Tuple(*[i for i in reps if reps[i]])
free = list(andargs.free_symbols)
if len(free) == 1:
from sympy.solvers.inequalities import (
reduce_inequalities, _solve_inequality)
try:
t = reduce_inequalities(andargs, free[0])
# ValueError when there are potentially
# nonvanishing imaginary parts
except (ValueError, NotImplementedError):
# at least isolate free symbol on left
t = And(*[_solve_inequality(
a, free[0], linear=True)
for a in andargs])
else:
t = And(*andargs)
if t is S.false:
continue # an impossible combination
cond = t
expr = handler(self.xreplace(reps))
if isinstance(expr, self.func) and len(expr.args) == 1:
expr, econd = expr.args[0]
cond = And(econd, True if cond is None else cond)
# the ec pairs are being collected since all possibilities
# are being enumerated, but don't put the last one in since
# its expr might match a previous expression and it
# must appear last in the args
if cond is not None:
args.setdefault(expr, []).append(cond)
# but since we only store the true conditions we must maintain
# the order so that the expression with the most true values
# comes first
exprinorder.append(expr)
# convert collected conditions as args of Or
for k in args:
args[k] = Or(*args[k])
# take them in the order obtained
args = [(e, args[e]) for e in uniq(exprinorder)]
# add in the last arg
args.append((expr, True))
return Piecewise(*args)
def _eval_integral(self, x, _first=True, **kwargs):
"""Return the indefinite integral of the
Piecewise such that subsequent substitution of x with a
value will give the value of the integral (not including
the constant of integration) up to that point. To only
integrate the individual parts of Piecewise, use the
``piecewise_integrate`` method.
Examples
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
>>> p.integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
>>> p.piecewise_integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
See Also
========
Piecewise.piecewise_integrate
"""
from sympy.integrals.integrals import integrate
if _first:
def handler(ipw):
if isinstance(ipw, self.func):
return ipw._eval_integral(x, _first=False, **kwargs)
else:
return ipw.integrate(x, **kwargs)
irv = self._handle_irel(x, handler)
if irv is not None:
return irv
# handle a Piecewise from -oo to oo with and no x-independent relationals
# -----------------------------------------------------------------------
ok, abei = self._intervals(x)
if not ok:
from sympy.integrals.integrals import Integral
return Integral(self, x) # unevaluated
pieces = [(a, b) for a, b, _, _ in abei]
oo = S.Infinity
done = [(-oo, oo, -1)]
for k, p in enumerate(pieces):
if p == (-oo, oo):
# all undone intervals will get this key
for j, (a, b, i) in enumerate(done):
if i == -1:
done[j] = a, b, k
break # nothing else to consider
N = len(done) - 1
for j, (a, b, i) in enumerate(reversed(done)):
if i == -1:
j = N - j
done[j: j + 1] = _clip(p, (a, b), k)
done = [(a, b, i) for a, b, i in done if a != b]
# append an arg if there is a hole so a reference to
# argument -1 will give Undefined
if any(i == -1 for (a, b, i) in done):
abei.append((-oo, oo, Undefined, -1))
# return the sum of the intervals
args = []
sum = None
for a, b, i in done:
anti = integrate(abei[i][-2], x, **kwargs)
if sum is None:
sum = anti
else:
sum = sum.subs(x, a)
e = anti._eval_interval(x, a, x)
if sum.has(*_illegal) or e.has(*_illegal):
sum = anti
else:
sum += e
# see if we know whether b is contained in original
# condition
if b is S.Infinity:
cond = True
elif self.args[abei[i][-1]].cond.subs(x, b) == False:
cond = (x < b)
else:
cond = (x <= b)
args.append((sum, cond))
return Piecewise(*args)
def _eval_interval(self, sym, a, b, _first=True):
"""Evaluates the function along the sym in a given interval [a, b]"""
# FIXME: Currently complex intervals are not supported. A possible
# replacement algorithm, discussed in issue 5227, can be found in the
# following papers;
# http://portal.acm.org/citation.cfm?id=281649
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
if a is None or b is None:
# In this case, it is just simple substitution
return super()._eval_interval(sym, a, b)
else:
x, lo, hi = map(as_Basic, (sym, a, b))
if _first: # get only x-dependent relationals
def handler(ipw):
if isinstance(ipw, self.func):
return ipw._eval_interval(x, lo, hi, _first=None)
else:
return ipw._eval_interval(x, lo, hi)
irv = self._handle_irel(x, handler)
if irv is not None:
return irv
if (lo < hi) is S.false or (
lo is S.Infinity or hi is S.NegativeInfinity):
rv = self._eval_interval(x, hi, lo, _first=False)
if isinstance(rv, Piecewise):
rv = Piecewise(*[(-e, c) for e, c in rv.args])
else:
rv = -rv
return rv
if (lo < hi) is S.true or (
hi is S.Infinity or lo is S.NegativeInfinity):
pass
else:
_a = Dummy('lo')
_b = Dummy('hi')
a = lo if lo.is_comparable else _a
b = hi if hi.is_comparable else _b
pos = self._eval_interval(x, a, b, _first=False)
if a == _a and b == _b:
# it's purely symbolic so just swap lo and hi and
# change the sign to get the value for when lo > hi
neg, pos = (-pos.xreplace({_a: hi, _b: lo}),
pos.xreplace({_a: lo, _b: hi}))
else:
# at least one of the bounds was comparable, so allow
# _eval_interval to use that information when computing
# the interval with lo and hi reversed
neg, pos = (-self._eval_interval(x, hi, lo, _first=False),
pos.xreplace({_a: lo, _b: hi}))
# allow simplification based on ordering of lo and hi
p = Dummy('', positive=True)
if lo.is_Symbol:
pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo})
neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi})
elif hi.is_Symbol:
pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo})
neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi})
# evaluate limits that may have unevaluate Min/Max
touch = lambda _: _.replace(
lambda x: isinstance(x, (Min, Max)),
lambda x: x.func(*x.args))
neg = touch(neg)
pos = touch(pos)
# assemble return expression; make the first condition be Lt
# b/c then the first expression will look the same whether
# the lo or hi limit is symbolic
if a == _a: # the lower limit was symbolic
rv = Piecewise(
(pos,
lo < hi),
(neg,
True))
else:
rv = Piecewise(
(neg,
hi < lo),
(pos,
True))
if rv == Undefined:
raise ValueError("Can't integrate across undefined region.")
if any(isinstance(i, Piecewise) for i in (pos, neg)):
rv = piecewise_fold(rv)
return rv
# handle a Piecewise with lo <= hi and no x-independent relationals
# -----------------------------------------------------------------
ok, abei = self._intervals(x)
if not ok:
from sympy.integrals.integrals import Integral
# not being able to do the interval of f(x) can
# be stated as not being able to do the integral
# of f'(x) over the same range
return Integral(self.diff(x), (x, lo, hi)) # unevaluated
pieces = [(a, b) for a, b, _, _ in abei]
done = [(lo, hi, -1)]
oo = S.Infinity
for k, p in enumerate(pieces):
if p[:2] == (-oo, oo):
# all undone intervals will get this key
for j, (a, b, i) in enumerate(done):
if i == -1:
done[j] = a, b, k
break # nothing else to consider
N = len(done) - 1
for j, (a, b, i) in enumerate(reversed(done)):
if i == -1:
j = N - j
done[j: j + 1] = _clip(p, (a, b), k)
done = [(a, b, i) for a, b, i in done if a != b]
# return the sum of the intervals
sum = S.Zero
upto = None
for a, b, i in done:
if i == -1:
if upto is None:
return Undefined
# TODO simplify hi <= upto
return Piecewise((sum, hi <= upto), (Undefined, True))
sum += abei[i][-2]._eval_interval(x, a, b)
upto = b
return sum
def _intervals(self, sym, err_on_Eq=False):
r"""Return a bool and a message (when bool is False), else a
list of unique tuples, (a, b, e, i), where a and b
are the lower and upper bounds in which the expression e of
argument i in self is defined and $a < b$ (when involving
numbers) or $a \le b$ when involving symbols.
If there are any relationals not involving sym, or any
relational cannot be solved for sym, the bool will be False
a message be given as the second return value. The calling
routine should have removed such relationals before calling
this routine.
The evaluated conditions will be returned as ranges.
Discontinuous ranges will be returned separately with
identical expressions. The first condition that evaluates to
True will be returned as the last tuple with a, b = -oo, oo.
"""
from sympy.solvers.inequalities import _solve_inequality
assert isinstance(self, Piecewise)
def nonsymfail(cond):
return False, filldedent('''
A condition not involving
%s appeared: %s''' % (sym, cond))
def _solve_relational(r):
if sym not in r.free_symbols:
return nonsymfail(r)
try:
rv = _solve_inequality(r, sym)
except NotImplementedError:
return False, 'Unable to solve relational %s for %s.' % (r, sym)
if isinstance(rv, Relational):
free = rv.args[1].free_symbols
if rv.args[0] != sym or sym in free:
return False, 'Unable to solve relational %s for %s.' % (r, sym)
if rv.rel_op == '==':
# this equality has been affirmed to have the form
# Eq(sym, rhs) where rhs is sym-free; it represents
# a zero-width interval which will be ignored
# whether it is an isolated condition or contained
# within an And or an Or
rv = S.false
elif rv.rel_op == '!=':
try:
rv = Or(sym < rv.rhs, sym > rv.rhs)
except TypeError:
# e.g. x != I ==> all real x satisfy
rv = S.true
elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity):
rv = S.true
return True, rv
args = list(self.args)
# make self canonical wrt Relationals
keys = self.atoms(Relational)
reps = {}
for r in keys:
ok, s = _solve_relational(r)
if ok != True:
return False, ok
reps[r] = s
# process args individually so if any evaluate, their position
# in the original Piecewise will be known
args = [i.xreplace(reps) for i in self.args]
# precondition args
expr_cond = []
default = idefault = None
for i, (expr, cond) in enumerate(args):
if cond is S.false:
continue
if cond is S.true:
default = expr
idefault = i
break
if isinstance(cond, Eq):
# unanticipated condition, but it is here in case a
# replacement caused an Eq to appear
if err_on_Eq:
return False, 'encountered Eq condition: %s' % cond
continue # zero width interval
cond = to_cnf(cond)
if isinstance(cond, And):
cond = distribute_or_over_and(cond)
if isinstance(cond, Or):
expr_cond.extend(
[(i, expr, o) for o in cond.args
if not isinstance(o, Eq)])
elif cond is not S.false:
expr_cond.append((i, expr, cond))
elif cond is S.true:
default = expr
idefault = i
break
# determine intervals represented by conditions
int_expr = []
for iarg, expr, cond in expr_cond:
if isinstance(cond, And):
lower = S.NegativeInfinity
upper = S.Infinity
exclude = []
for cond2 in cond.args:
if not isinstance(cond2, Relational):
return False, 'expecting only Relationals'
if isinstance(cond2, Eq):
lower = upper # ignore
if err_on_Eq:
return False, 'encountered secondary Eq condition'
break
elif isinstance(cond2, Ne):
l, r = cond2.args
if l == sym:
exclude.append(r)
elif r == sym:
exclude.append(l)
else:
return nonsymfail(cond2)
continue
elif cond2.lts == sym:
upper = Min(cond2.gts, upper)
elif cond2.gts == sym:
lower = Max(cond2.lts, lower)
else:
return nonsymfail(cond2) # should never get here
if exclude:
exclude = list(ordered(exclude))
newcond = []
for i, e in enumerate(exclude):
if e < lower == True or e > upper == True:
continue
if not newcond:
newcond.append((None, lower)) # add a primer
newcond.append((newcond[-1][1], e))
newcond.append((newcond[-1][1], upper))
newcond.pop(0) # remove the primer
expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond])
continue
elif isinstance(cond, Relational) and cond.rel_op != '!=':
lower, upper = cond.lts, cond.gts # part 1: initialize with givens
if cond.lts == sym: # part 1a: expand the side ...
lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0
elif cond.gts == sym: # part 1a: ... that can be expanded
upper = S.Infinity # e.g. x >= 0 ---> oo >= 0
else:
return nonsymfail(cond)
else:
return False, 'unrecognized condition: %s' % cond
lower, upper = lower, Max(lower, upper)
if err_on_Eq and lower == upper:
return False, 'encountered Eq condition'
if (lower >= upper) is not S.true:
int_expr.append((lower, upper, expr, iarg))
if default is not None:
int_expr.append(
(S.NegativeInfinity, S.Infinity, default, idefault))
return True, list(uniq(int_expr))
def _eval_nseries(self, x, n, logx, cdir=0):
args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args]
return self.func(*args)
def _eval_power(self, s):
return self.func(*[(e**s, c) for e, c in self.args])
def _eval_subs(self, old, new):
# this is strictly not necessary, but we can keep track
# of whether True or False conditions arise and be
# somewhat more efficient by avoiding other substitutions
# and avoiding invalid conditions that appear after a
# True condition
args = list(self.args)
args_exist = False
for i, (e, c) in enumerate(args):
c = c._subs(old, new)
if c != False:
args_exist = True
e = e._subs(old, new)
args[i] = (e, c)
if c == True:
break
if not args_exist:
args = ((Undefined, True),)
return self.func(*args)
def _eval_transpose(self):
return self.func(*[(e.transpose(), c) for e, c in self.args])
def _eval_template_is_attr(self, is_attr):
b = None
for expr, _ in self.args:
a = getattr(expr, is_attr)
if a is None:
return
if b is None:
b = a
elif b is not a:
return
return b
_eval_is_finite = lambda self: self._eval_template_is_attr(
'is_finite')
_eval_is_complex = lambda self: self._eval_template_is_attr('is_complex')
_eval_is_even = lambda self: self._eval_template_is_attr('is_even')
_eval_is_imaginary = lambda self: self._eval_template_is_attr(
'is_imaginary')
_eval_is_integer = lambda self: self._eval_template_is_attr('is_integer')
_eval_is_irrational = lambda self: self._eval_template_is_attr(
'is_irrational')
_eval_is_negative = lambda self: self._eval_template_is_attr('is_negative')
_eval_is_nonnegative = lambda self: self._eval_template_is_attr(
'is_nonnegative')
_eval_is_nonpositive = lambda self: self._eval_template_is_attr(
'is_nonpositive')
_eval_is_nonzero = lambda self: self._eval_template_is_attr(
'is_nonzero')
_eval_is_odd = lambda self: self._eval_template_is_attr('is_odd')
_eval_is_polar = lambda self: self._eval_template_is_attr('is_polar')
_eval_is_positive = lambda self: self._eval_template_is_attr('is_positive')
_eval_is_extended_real = lambda self: self._eval_template_is_attr(
'is_extended_real')
_eval_is_extended_positive = lambda self: self._eval_template_is_attr(
'is_extended_positive')
_eval_is_extended_negative = lambda self: self._eval_template_is_attr(
'is_extended_negative')
_eval_is_extended_nonzero = lambda self: self._eval_template_is_attr(
'is_extended_nonzero')
_eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr(
'is_extended_nonpositive')
_eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr(
'is_extended_nonnegative')
_eval_is_real = lambda self: self._eval_template_is_attr('is_real')
_eval_is_zero = lambda self: self._eval_template_is_attr(
'is_zero')
@classmethod
def __eval_cond(cls, cond):
"""Return the truth value of the condition."""
if cond == True:
return True
if isinstance(cond, Eq):
try:
diff = cond.lhs - cond.rhs
if diff.is_commutative:
return diff.is_zero
except TypeError:
pass
def as_expr_set_pairs(self, domain=None):
"""Return tuples for each argument of self that give
the expression and the interval in which it is valid
which is contained within the given domain.
If a condition cannot be converted to a set, an error
will be raised. The variable of the conditions is
assumed to be real; sets of real values are returned.
Examples
========
>>> from sympy import Piecewise, Interval
>>> from sympy.abc import x
>>> p = Piecewise(
... (1, x < 2),
... (2,(x > 0) & (x < 4)),
... (3, True))
>>> p.as_expr_set_pairs()
[(1, Interval.open(-oo, 2)),
(2, Interval.Ropen(2, 4)),
(3, Interval(4, oo))]
>>> p.as_expr_set_pairs(Interval(0, 3))
[(1, Interval.Ropen(0, 2)),
(2, Interval(2, 3))]
"""
if domain is None:
domain = S.Reals
exp_sets = []
U = domain
complex = not domain.is_subset(S.Reals)
cond_free = set()
for expr, cond in self.args:
cond_free |= cond.free_symbols
if len(cond_free) > 1:
raise NotImplementedError(filldedent('''
multivariate conditions are not handled.'''))
if complex:
for i in cond.atoms(Relational):
if not isinstance(i, (Eq, Ne)):
raise ValueError(filldedent('''
Inequalities in the complex domain are
not supported. Try the real domain by
setting domain=S.Reals'''))
cond_int = U.intersect(cond.as_set())
U = U - cond_int
if cond_int != S.EmptySet:
exp_sets.append((expr, cond_int))
return exp_sets
def _eval_rewrite_as_ITE(self, *args, **kwargs):
byfree = {}
args = list(args)
default = any(c == True for b, c in args)
for i, (b, c) in enumerate(args):
if not isinstance(b, Boolean) and b != True:
raise TypeError(filldedent('''
Expecting Boolean or bool but got `%s`
''' % func_name(b)))
if c == True:
break
# loop over independent conditions for this b
for c in c.args if isinstance(c, Or) else [c]:
free = c.free_symbols
x = free.pop()
try:
byfree[x] = byfree.setdefault(
x, S.EmptySet).union(c.as_set())
except NotImplementedError:
if not default:
raise NotImplementedError(filldedent('''
A method to determine whether a multivariate
conditional is consistent with a complete coverage
of all variables has not been implemented so the
rewrite is being stopped after encountering `%s`.
This error would not occur if a default expression
like `(foo, True)` were given.
''' % c))
if byfree[x] in (S.UniversalSet, S.Reals):
# collapse the ith condition to True and break
args[i] = list(args[i])
c = args[i][1] = True
break
if c == True:
break
if c != True:
raise ValueError(filldedent('''
Conditions must cover all reals or a final default
condition `(foo, True)` must be given.
'''))
last, _ = args[i] # ignore all past ith arg
for a, c in reversed(args[:i]):
last = ITE(c, a, last)
return _canonical(last)
def _eval_rewrite_as_KroneckerDelta(self, *args):
from sympy.functions.special.tensor_functions import KroneckerDelta
rules = {
And: [False, False],
Or: [True, True],
Not: [True, False],
Eq: [None, None],
Ne: [None, None]
}
class UnrecognizedCondition(Exception):
pass
def rewrite(cond):
if isinstance(cond, Eq):
return KroneckerDelta(*cond.args)
if isinstance(cond, Ne):
return 1 - KroneckerDelta(*cond.args)
cls, args = type(cond), cond.args
if cls not in rules:
raise UnrecognizedCondition(cls)
b1, b2 = rules[cls]
k = Mul(*[1 - rewrite(c) for c in args]) if b1 else Mul(*[rewrite(c) for c in args])
if b2:
return 1 - k
return k
conditions = []
true_value = None
for value, cond in args:
if type(cond) in rules:
conditions.append((value, cond))
elif cond is S.true:
if true_value is None:
true_value = value
else:
return
if true_value is not None:
result = true_value
for value, cond in conditions[::-1]:
try:
k = rewrite(cond)
result = k * value + (1 - k) * result
except UnrecognizedCondition:
return
return result
def piecewise_fold(expr, evaluate=True):
"""
Takes an expression containing a piecewise function and returns the
expression in piecewise form. In addition, any ITE conditions are
rewritten in negation normal form and simplified.
The final Piecewise is evaluated (default) but if the raw form
is desired, send ``evaluate=False``; if trivial evaluation is
desired, send ``evaluate=None`` and duplicate conditions and
processing of True and False will be handled.
Examples
========
>>> from sympy import Piecewise, piecewise_fold, S
>>> from sympy.abc import x
>>> p = Piecewise((x, x < 1), (1, S(1) <= x))
>>> piecewise_fold(x*p)
Piecewise((x**2, x < 1), (x, True))
See Also
========
Piecewise
piecewise_exclusive
"""
if not isinstance(expr, Basic) or not expr.has(Piecewise):
return expr
new_args = []
if isinstance(expr, (ExprCondPair, Piecewise)):
for e, c in expr.args:
if not isinstance(e, Piecewise):
e = piecewise_fold(e)
# we don't keep Piecewise in condition because
# it has to be checked to see that it's complete
# and we convert it to ITE at that time
assert not c.has(Piecewise) # pragma: no cover
if isinstance(c, ITE):
c = c.to_nnf()
c = simplify_logic(c, form='cnf')
if isinstance(e, Piecewise):
new_args.extend([(piecewise_fold(ei), And(ci, c))
for ei, ci in e.args])
else:
new_args.append((e, c))
else:
# Given
# P1 = Piecewise((e11, c1), (e12, c2), A)
# P2 = Piecewise((e21, c1), (e22, c2), B)
# ...
# the folding of f(P1, P2) is trivially
# Piecewise(
# (f(e11, e21), c1),
# (f(e12, e22), c2),
# (f(Piecewise(A), Piecewise(B)), True))
# Certain objects end up rewriting themselves as thus, so
# we do that grouping before the more generic folding.
# The following applies this idea when f = Add or f = Mul
# (and the expression is commutative).
if expr.is_Add or expr.is_Mul and expr.is_commutative:
p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
pc = sift(p, lambda x: tuple([c for e,c in x.args]))
for c in list(ordered(pc)):
if len(pc[c]) > 1:
pargs = [list(i.args) for i in pc[c]]
# the first one is the same; there may be more
com = common_prefix(*[
[i.cond for i in j] for j in pargs])
n = len(com)
collected = []
for i in range(n):
collected.append((
expr.func(*[ai[i].expr for ai in pargs]),
com[i]))
remains = []
for a in pargs:
if n == len(a): # no more args
continue
if a[n].cond == True: # no longer Piecewise
remains.append(a[n].expr)
else: # restore the remaining Piecewise
remains.append(
Piecewise(*a[n:], evaluate=False))
if remains:
collected.append((expr.func(*remains), True))
args.append(Piecewise(*collected, evaluate=False))
continue
args.extend(pc[c])
else:
args = expr.args
# fold
folded = list(map(piecewise_fold, args))
for ec in product(*[
(i.args if isinstance(i, Piecewise) else
[(i, true)]) for i in folded]):
e, c = zip(*ec)
new_args.append((expr.func(*e), And(*c)))
if evaluate is None:
# don't return duplicate conditions, otherwise don't evaluate
new_args = list(reversed([(e, c) for c, e in {
c: e for e, c in reversed(new_args)}.items()]))
rv = Piecewise(*new_args, evaluate=evaluate)
if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True:
return rv.args[0].expr
if any(s.expr.has(Piecewise) for p in rv.atoms(Piecewise) for s in p.args):
return piecewise_fold(rv)
return rv
def _clip(A, B, k):
"""Return interval B as intervals that are covered by A (keyed
to k) and all other intervals of B not covered by A keyed to -1.
The reference point of each interval is the rhs; if the lhs is
greater than the rhs then an interval of zero width interval will
result, e.g. (4, 1) is treated like (1, 1).
Examples
========
>>> from sympy.functions.elementary.piecewise import _clip
>>> from sympy import Tuple
>>> A = Tuple(1, 3)
>>> B = Tuple(2, 4)
>>> _clip(A, B, 0)
[(2, 3, 0), (3, 4, -1)]
Interpretation: interval portion (2, 3) of interval (2, 4) is
covered by interval (1, 3) and is keyed to 0 as requested;
interval (3, 4) was not covered by (1, 3) and is keyed to -1.
"""
a, b = B
c, d = A
c, d = Min(Max(c, a), b), Min(Max(d, a), b)
a, b = Min(a, b), b
p = []
if a != c:
p.append((a, c, -1))
else:
pass
if c != d:
p.append((c, d, k))
else:
pass
if b != d:
if d == c and p and p[-1][-1] == -1:
p[-1] = p[-1][0], b, -1
else:
p.append((d, b, -1))
else:
pass
return p
def piecewise_simplify_arguments(expr, **kwargs):
from sympy.simplify.simplify import simplify
# simplify conditions
f1 = expr.args[0].cond.free_symbols
args = None
if len(f1) == 1 and not expr.atoms(Eq):
x = f1.pop()
# this won't return intervals involving Eq
# and it won't handle symbols treated as
# booleans
ok, abe_ = expr._intervals(x, err_on_Eq=True)
def include(c, x, a):
"return True if c.subs(x, a) is True, else False"
try:
return c.subs(x, a) == True
except TypeError:
return False
if ok:
args = []
covered = S.EmptySet
from sympy.sets.sets import Interval
for a, b, e, i in abe_:
c = expr.args[i].cond
incl_a = include(c, x, a)
incl_b = include(c, x, b)
iv = Interval(a, b, not incl_a, not incl_b)
cset = iv - covered
if not cset:
continue
if incl_a and incl_b:
if a.is_infinite and b.is_infinite:
c = S.true
elif b.is_infinite:
c = (x >= a)
elif a in covered or a.is_infinite:
c = (x <= b)
else:
c = And(a <= x, x <= b)
elif incl_a:
if a in covered or a.is_infinite:
c = (x < b)
else:
c = And(a <= x, x < b)
elif incl_b:
if b.is_infinite:
c = (x > a)
else:
c = (x <= b)
else:
if a in covered:
c = (x < b)
else:
c = And(a < x, x < b)
covered |= iv
if a is S.NegativeInfinity and incl_a:
covered |= {S.NegativeInfinity}
if b is S.Infinity and incl_b:
covered |= {S.Infinity}
args.append((e, c))
if not S.Reals.is_subset(covered):
args.append((Undefined, True))
if args is None:
args = list(expr.args)
for i in range(len(args)):
e, c = args[i]
if isinstance(c, Basic):
c = simplify(c, **kwargs)
args[i] = (e, c)
# simplify expressions
doit = kwargs.pop('doit', None)
for i in range(len(args)):
e, c = args[i]
if isinstance(e, Basic):
# Skip doit to avoid growth at every call for some integrals
# and sums, see sympy/sympy#17165
newe = simplify(e, doit=False, **kwargs)
if newe != e:
e = newe
args[i] = (e, c)
# restore kwargs flag
if doit is not None:
kwargs['doit'] = doit
return Piecewise(*args)
def _piecewise_collapse_arguments(_args):
newargs = [] # the unevaluated conditions
current_cond = set() # the conditions up to a given e, c pair
for expr, cond in _args:
cond = cond.replace(
lambda _: _.is_Relational, _canonical_coeff)
# Check here if expr is a Piecewise and collapse if one of
# the conds in expr matches cond. This allows the collapsing
# of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
# This is important when using piecewise_fold to simplify
# multiple Piecewise instances having the same conds.
# Eventually, this code should be able to collapse Piecewise's
# having different intervals, but this will probably require
# using the new assumptions.
if isinstance(expr, Piecewise):
unmatching = []
for i, (e, c) in enumerate(expr.args):
if c in current_cond:
# this would already have triggered
continue
if c == cond:
if c != True:
# nothing past this condition will ever
# trigger and only those args before this
# that didn't match a previous condition
# could possibly trigger
if unmatching:
expr = Piecewise(*(
unmatching + [(e, c)]))
else:
expr = e
break
else:
unmatching.append((e, c))
# check for condition repeats
got = False
# -- if an And contains a condition that was
# already encountered, then the And will be
# False: if the previous condition was False
# then the And will be False and if the previous
# condition is True then then we wouldn't get to
# this point. In either case, we can skip this condition.
for i in ([cond] +
(list(cond.args) if isinstance(cond, And) else
[])):
if i in current_cond:
got = True
break
if got:
continue
# -- if not(c) is already in current_cond then c is
# a redundant condition in an And. This does not
# apply to Or, however: (e1, c), (e2, Or(~c, d))
# is not (e1, c), (e2, d) because if c and d are
# both False this would give no results when the
# true answer should be (e2, True)
if isinstance(cond, And):
nonredundant = []
for c in cond.args:
if isinstance(c, Relational):
if c.negated.canonical in current_cond:
continue
# if a strict inequality appears after
# a non-strict one, then the condition is
# redundant
if isinstance(c, (Lt, Gt)) and (
c.weak in current_cond):
cond = False
break
nonredundant.append(c)
else:
cond = cond.func(*nonredundant)
elif isinstance(cond, Relational):
if cond.negated.canonical in current_cond:
cond = S.true
current_cond.add(cond)
# collect successive e,c pairs when exprs or cond match
if newargs:
if newargs[-1].expr == expr:
orcond = Or(cond, newargs[-1].cond)
if isinstance(orcond, (And, Or)):
orcond = distribute_and_over_or(orcond)
newargs[-1] = ExprCondPair(expr, orcond)
continue
elif newargs[-1].cond == cond:
continue
newargs.append(ExprCondPair(expr, cond))
return newargs
_blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
getattr(e.rhs, '_diff_wrt', None) or
isinstance(e.rhs, (Rational, NumberSymbol)))
def piecewise_simplify(expr, **kwargs):
expr = piecewise_simplify_arguments(expr, **kwargs)
if not isinstance(expr, Piecewise):
return expr
args = list(expr.args)
args = _piecewise_simplify_eq_and(args)
args = _piecewise_simplify_equal_to_next_segment(args)
return Piecewise(*args)
def _piecewise_simplify_equal_to_next_segment(args):
"""
See if expressions valid for an Equal expression happens to evaluate
to the same function as in the next piecewise segment, see:
https://github.com/sympy/sympy/issues/8458
"""
prevexpr = None
for i, (expr, cond) in reversed(list(enumerate(args))):
if prevexpr is not None:
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Eq), binary=True)
elif isinstance(cond, Eq):
eqs, other = [cond], []
else:
eqs = other = []
_prevexpr = prevexpr
_expr = expr
if eqs and not other:
eqs = list(ordered(eqs))
for e in eqs:
# allow 2 args to collapse into 1 for any e
# otherwise limit simplification to only simple-arg
# Eq instances
if len(args) == 2 or _blessed(e):
_prevexpr = _prevexpr.subs(*e.args)
_expr = _expr.subs(*e.args)
# Did it evaluate to the same?
if _prevexpr == _expr:
# Set the expression for the Not equal section to the same
# as the next. These will be merged when creating the new
# Piecewise
args[i] = args[i].func(args[i + 1][0], cond)
else:
# Update the expression that we compare against
prevexpr = expr
else:
prevexpr = expr
return args
def _piecewise_simplify_eq_and(args):
"""
Try to simplify conditions and the expression for
equalities that are part of the condition, e.g.
Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
-> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
"""
for i, (expr, cond) in enumerate(args):
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Eq), binary=True)
elif isinstance(cond, Eq):
eqs, other = [cond], []
else:
eqs = other = []
if eqs:
eqs = list(ordered(eqs))
for j, e in enumerate(eqs):
# these blessed lhs objects behave like Symbols
# and the rhs are simple replacements for the "symbols"
if _blessed(e):
expr = expr.subs(*e.args)
eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
other = [ei.subs(*e.args) for ei in other]
cond = And(*(eqs + other))
args[i] = args[i].func(expr, cond)
return args
def piecewise_exclusive(expr, *, skip_nan=False, deep=True):
"""
Rewrite :class:`Piecewise` with mutually exclusive conditions.
Explanation
===========
SymPy represents the conditions of a :class:`Piecewise` in an
"if-elif"-fashion, allowing more than one condition to be simultaneously
True. The interpretation is that the first condition that is True is the
case that holds. While this is a useful representation computationally it
is not how a piecewise formula is typically shown in a mathematical text.
The :func:`piecewise_exclusive` function can be used to rewrite any
:class:`Piecewise` with more typical mutually exclusive conditions.
Note that further manipulation of the resulting :class:`Piecewise`, e.g.
simplifying it, will most likely make it non-exclusive. Hence, this is
primarily a function to be used in conjunction with printing the Piecewise
or if one would like to reorder the expression-condition pairs.
If it is not possible to determine that all possibilities are covered by
the different cases of the :class:`Piecewise` then a final
:class:`~sympy.core.numbers.NaN` case will be included explicitly. This
can be prevented by passing ``skip_nan=True``.
Examples
========
>>> from sympy import piecewise_exclusive, Symbol, Piecewise, S
>>> x = Symbol('x', real=True)
>>> p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
>>> piecewise_exclusive(p)
Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
>>> piecewise_exclusive(Piecewise((2, x > 1)))
Piecewise((2, x > 1), (nan, x <= 1))
>>> piecewise_exclusive(Piecewise((2, x > 1)), skip_nan=True)
Piecewise((2, x > 1))
Parameters
==========
expr: a SymPy expression.
Any :class:`Piecewise` in the expression will be rewritten.
skip_nan: ``bool`` (default ``False``)
If ``skip_nan`` is set to ``True`` then a final
:class:`~sympy.core.numbers.NaN` case will not be included.
deep: ``bool`` (default ``True``)
If ``deep`` is ``True`` then :func:`piecewise_exclusive` will rewrite
any :class:`Piecewise` subexpressions in ``expr`` rather than just
rewriting ``expr`` itself.
Returns
=======
An expression equivalent to ``expr`` but where all :class:`Piecewise` have
been rewritten with mutually exclusive conditions.
See Also
========
Piecewise
piecewise_fold
"""
def make_exclusive(*pwargs):
cumcond = false
newargs = []
# Handle the first n-1 cases
for expr_i, cond_i in pwargs[:-1]:
cancond = And(cond_i, Not(cumcond)).simplify()
cumcond = Or(cond_i, cumcond).simplify()
newargs.append((expr_i, cancond))
# For the nth case defer simplification of cumcond
expr_n, cond_n = pwargs[-1]
cancond_n = And(cond_n, Not(cumcond)).simplify()
newargs.append((expr_n, cancond_n))
if not skip_nan:
cumcond = Or(cond_n, cumcond).simplify()
if cumcond is not true:
newargs.append((Undefined, Not(cumcond).simplify()))
return Piecewise(*newargs, evaluate=False)
if deep:
return expr.replace(Piecewise, make_exclusive)
elif isinstance(expr, Piecewise):
return make_exclusive(*expr.args)
else:
return expr
|
7729c15eb22a9763c38ae6fd181421ccde6d255178924b497575b0889ef7caca | from typing import Tuple as tTuple
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core import Add, S
from sympy.core.evalf import get_integer_part, PrecisionExhausted
from sympy.core.function import Function
from sympy.core.logic import fuzzy_or
from sympy.core.numbers import Integer
from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq
from sympy.core.symbol import Symbol
from sympy.core.sympify import _sympify
from sympy.functions.elementary.complexes import im, re
from sympy.multipledispatch import dispatch
###############################################################################
######################### FLOOR and CEILING FUNCTIONS #########################
###############################################################################
class RoundFunction(Function):
"""Abstract base class for rounding functions."""
args: tTuple[Expr]
@classmethod
def eval(cls, arg):
v = cls._eval_number(arg)
if v is not None:
return v
if arg.is_integer or arg.is_finite is False:
return arg
if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real:
i = im(arg)
if not i.has(S.ImaginaryUnit):
return cls(i)*S.ImaginaryUnit
return cls(arg, evaluate=False)
# Integral, numerical, symbolic part
ipart = npart = spart = S.Zero
# Extract integral (or complex integral) terms
terms = Add.make_args(arg)
for t in terms:
if t.is_integer or (t.is_imaginary and im(t).is_integer):
ipart += t
elif t.has(Symbol):
spart += t
else:
npart += t
if not (npart or spart):
return ipart
# Evaluate npart numerically if independent of spart
if npart and (
not spart or
npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or
npart.is_imaginary and spart.is_real):
try:
r, i = get_integer_part(
npart, cls._dir, {}, return_ints=True)
ipart += Integer(r) + Integer(i)*S.ImaginaryUnit
npart = S.Zero
except (PrecisionExhausted, NotImplementedError):
pass
spart += npart
if not spart:
return ipart
elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real:
return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit
elif isinstance(spart, (floor, ceiling)):
return ipart + spart
else:
return ipart + cls(spart, evaluate=False)
@classmethod
def _eval_number(cls, arg):
raise NotImplementedError()
def _eval_is_finite(self):
return self.args[0].is_finite
def _eval_is_real(self):
return self.args[0].is_real
def _eval_is_integer(self):
return self.args[0].is_real
class floor(RoundFunction):
"""
Floor is a univariate function which returns the largest integer
value not greater than its argument. This implementation
generalizes floor to complex numbers by taking the floor of the
real and imaginary parts separately.
Examples
========
>>> from sympy import floor, E, I, S, Float, Rational
>>> floor(17)
17
>>> floor(Rational(23, 10))
2
>>> floor(2*E)
5
>>> floor(-Float(0.567))
-1
>>> floor(-I/2)
-I
>>> floor(S(5)/2 + 5*I/2)
2 + 2*I
See Also
========
sympy.functions.elementary.integers.ceiling
References
==========
.. [1] "Concrete mathematics" by Graham, pp. 87
.. [2] http://mathworld.wolfram.com/FloorFunction.html
"""
_dir = -1
@classmethod
def _eval_number(cls, arg):
if arg.is_Number:
return arg.floor()
elif any(isinstance(i, j)
for i in (arg, -arg) for j in (floor, ceiling)):
return arg
if arg.is_NumberSymbol:
return arg.approximation_interval(Integer)[0]
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
arg = self.args[0]
arg0 = arg.subs(x, 0)
r = self.subs(x, 0)
if arg0 is S.NaN or isinstance(arg0, AccumBounds):
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
r = floor(arg0)
if arg0.is_finite:
if arg0 == r:
ndir = arg.dir(x, cdir=cdir)
return r - 1 if ndir.is_negative else r
else:
return r
return arg.as_leading_term(x, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir=0):
arg = self.args[0]
arg0 = arg.subs(x, 0)
r = self.subs(x, 0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
r = floor(arg0)
if arg0.is_infinite:
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.series.order import Order
s = arg._eval_nseries(x, n, logx, cdir)
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(-1, 0)
return s + o
if arg0 == r:
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
return r - 1 if ndir.is_negative else r
else:
return r
def _eval_is_negative(self):
return self.args[0].is_negative
def _eval_is_nonnegative(self):
return self.args[0].is_nonnegative
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
return -ceiling(-arg)
def _eval_rewrite_as_frac(self, arg, **kwargs):
return arg - frac(arg)
def __le__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] < other + 1
if other.is_number and other.is_real:
return self.args[0] < ceiling(other)
if self.args[0] == other and other.is_real:
return S.true
if other is S.Infinity and self.is_finite:
return S.true
return Le(self, other, evaluate=False)
def __ge__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] >= other
if other.is_number and other.is_real:
return self.args[0] >= ceiling(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Ge(self, other, evaluate=False)
def __gt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] >= other + 1
if other.is_number and other.is_real:
return self.args[0] >= ceiling(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Gt(self, other, evaluate=False)
def __lt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] < other
if other.is_number and other.is_real:
return self.args[0] < ceiling(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.Infinity and self.is_finite:
return S.true
return Lt(self, other, evaluate=False)
@dispatch(floor, Expr)
def _eval_is_eq(lhs, rhs): # noqa:F811
return is_eq(lhs.rewrite(ceiling), rhs) or \
is_eq(lhs.rewrite(frac),rhs)
class ceiling(RoundFunction):
"""
Ceiling is a univariate function which returns the smallest integer
value not less than its argument. This implementation
generalizes ceiling to complex numbers by taking the ceiling of the
real and imaginary parts separately.
Examples
========
>>> from sympy import ceiling, E, I, S, Float, Rational
>>> ceiling(17)
17
>>> ceiling(Rational(23, 10))
3
>>> ceiling(2*E)
6
>>> ceiling(-Float(0.567))
0
>>> ceiling(I/2)
I
>>> ceiling(S(5)/2 + 5*I/2)
3 + 3*I
See Also
========
sympy.functions.elementary.integers.floor
References
==========
.. [1] "Concrete mathematics" by Graham, pp. 87
.. [2] http://mathworld.wolfram.com/CeilingFunction.html
"""
_dir = 1
@classmethod
def _eval_number(cls, arg):
if arg.is_Number:
return arg.ceiling()
elif any(isinstance(i, j)
for i in (arg, -arg) for j in (floor, ceiling)):
return arg
if arg.is_NumberSymbol:
return arg.approximation_interval(Integer)[1]
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
arg = self.args[0]
arg0 = arg.subs(x, 0)
r = self.subs(x, 0)
if arg0 is S.NaN or isinstance(arg0, AccumBounds):
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
r = ceiling(arg0)
if arg0.is_finite:
if arg0 == r:
ndir = arg.dir(x, cdir=cdir)
return r if ndir.is_negative else r + 1
else:
return r
return arg.as_leading_term(x, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir=0):
arg = self.args[0]
arg0 = arg.subs(x, 0)
r = self.subs(x, 0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
r = ceiling(arg0)
if arg0.is_infinite:
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.series.order import Order
s = arg._eval_nseries(x, n, logx, cdir)
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1)
return s + o
if arg0 == r:
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
return r if ndir.is_negative else r + 1
else:
return r
def _eval_rewrite_as_floor(self, arg, **kwargs):
return -floor(-arg)
def _eval_rewrite_as_frac(self, arg, **kwargs):
return arg + frac(-arg)
def _eval_is_positive(self):
return self.args[0].is_positive
def _eval_is_nonpositive(self):
return self.args[0].is_nonpositive
def __lt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] <= other - 1
if other.is_number and other.is_real:
return self.args[0] <= floor(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.Infinity and self.is_finite:
return S.true
return Lt(self, other, evaluate=False)
def __gt__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] > other
if other.is_number and other.is_real:
return self.args[0] > floor(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Gt(self, other, evaluate=False)
def __ge__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] > other - 1
if other.is_number and other.is_real:
return self.args[0] > floor(other)
if self.args[0] == other and other.is_real:
return S.true
if other is S.NegativeInfinity and self.is_finite:
return S.true
return Ge(self, other, evaluate=False)
def __le__(self, other):
other = S(other)
if self.args[0].is_real:
if other.is_integer:
return self.args[0] <= other
if other.is_number and other.is_real:
return self.args[0] <= floor(other)
if self.args[0] == other and other.is_real:
return S.false
if other is S.Infinity and self.is_finite:
return S.true
return Le(self, other, evaluate=False)
@dispatch(ceiling, Basic) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs)
class frac(Function):
r"""Represents the fractional part of x
For real numbers it is defined [1]_ as
.. math::
x - \left\lfloor{x}\right\rfloor
Examples
========
>>> from sympy import Symbol, frac, Rational, floor, I
>>> frac(Rational(4, 3))
1/3
>>> frac(-Rational(4, 3))
2/3
returns zero for integer arguments
>>> n = Symbol('n', integer=True)
>>> frac(n)
0
rewrite as floor
>>> x = Symbol('x')
>>> frac(x).rewrite(floor)
x - floor(x)
for complex arguments
>>> r = Symbol('r', real=True)
>>> t = Symbol('t', real=True)
>>> frac(t + I*r)
I*frac(r) + frac(t)
See Also
========
sympy.functions.elementary.integers.floor
sympy.functions.elementary.integers.ceiling
References
===========
.. [1] https://en.wikipedia.org/wiki/Fractional_part
.. [2] http://mathworld.wolfram.com/FractionalPart.html
"""
@classmethod
def eval(cls, arg):
from sympy.calculus.accumulationbounds import AccumBounds
def _eval(arg):
if arg in (S.Infinity, S.NegativeInfinity):
return AccumBounds(0, 1)
if arg.is_integer:
return S.Zero
if arg.is_number:
if arg is S.NaN:
return S.NaN
elif arg is S.ComplexInfinity:
return S.NaN
else:
return arg - floor(arg)
return cls(arg, evaluate=False)
terms = Add.make_args(arg)
real, imag = S.Zero, S.Zero
for t in terms:
# Two checks are needed for complex arguments
# see issue-7649 for details
if t.is_imaginary or (S.ImaginaryUnit*t).is_real:
i = im(t)
if not i.has(S.ImaginaryUnit):
imag += i
else:
real += t
else:
real += t
real = _eval(real)
imag = _eval(imag)
return real + S.ImaginaryUnit*imag
def _eval_rewrite_as_floor(self, arg, **kwargs):
return arg - floor(arg)
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
return arg + ceiling(-arg)
def _eval_is_finite(self):
return True
def _eval_is_real(self):
return self.args[0].is_extended_real
def _eval_is_imaginary(self):
return self.args[0].is_imaginary
def _eval_is_integer(self):
return self.args[0].is_integer
def _eval_is_zero(self):
return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])
def _eval_is_negative(self):
return False
def __ge__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other <= 0
if other.is_extended_nonpositive:
return S.true
# Check if other >= 1
res = self._value_one_or_more(other)
if res is not None:
return not(res)
return Ge(self, other, evaluate=False)
def __gt__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other < 0
res = self._value_one_or_more(other)
if res is not None:
return not(res)
# Check if other >= 1
if other.is_extended_negative:
return S.true
return Gt(self, other, evaluate=False)
def __le__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other < 0
if other.is_extended_negative:
return S.false
# Check if other >= 1
res = self._value_one_or_more(other)
if res is not None:
return res
return Le(self, other, evaluate=False)
def __lt__(self, other):
if self.is_extended_real:
other = _sympify(other)
# Check if other <= 0
if other.is_extended_nonpositive:
return S.false
# Check if other >= 1
res = self._value_one_or_more(other)
if res is not None:
return res
return Lt(self, other, evaluate=False)
def _value_one_or_more(self, other):
if other.is_extended_real:
if other.is_number:
res = other >= 1
if res and not isinstance(res, Relational):
return S.true
if other.is_integer and other.is_positive:
return S.true
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
arg = self.args[0]
arg0 = arg.subs(x, 0)
r = self.subs(x, 0)
if arg0.is_finite:
if r.is_zero:
ndir = arg.dir(x, cdir=cdir)
if ndir.is_negative:
return S.One
return (arg - arg0).as_leading_term(x, logx=logx, cdir=cdir)
else:
return r
elif arg0 in (S.ComplexInfinity, S.Infinity, S.NegativeInfinity):
return AccumBounds(0, 1)
return arg.as_leading_term(x, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy.series.order import Order
arg = self.args[0]
arg0 = arg.subs(x, 0)
r = self.subs(x, 0)
if arg0.is_infinite:
from sympy.calculus.accumulationbounds import AccumBounds
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) + Order(x**n, (x, 0))
return o
else:
res = (arg - arg0)._eval_nseries(x, n, logx=logx, cdir=cdir)
if r.is_zero:
ndir = arg.dir(x, cdir=cdir)
res += S.One if ndir.is_negative else S.Zero
else:
res += r
return res
@dispatch(frac, Basic) # type:ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
if (lhs.rewrite(floor) == rhs) or \
(lhs.rewrite(ceiling) == rhs):
return True
# Check if other < 0
if rhs.is_extended_negative:
return False
# Check if other >= 1
res = lhs._value_one_or_more(rhs)
if res is not None:
return False
|
54701e4d0107ff1c4cf5b27dc08ff93fb3bcad77643f8ceeb93e2079f3f545cc | from itertools import product
from typing import Tuple as tTuple
from sympy.core.expr import Expr
from sympy.core import sympify
from sympy.core.add import Add
from sympy.core.cache import cacheit
from sympy.core.function import (Function, ArgumentIndexError, expand_log,
expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex)
from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or
from sympy.core.mul import Mul
from sympy.core.numbers import Integer, Rational, pi, I, ImaginaryUnit
from sympy.core.parameters import global_parameters
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Wild, Dummy
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import arg, unpolarify, im, re, Abs
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.ntheory import multiplicity, perfect_power
from sympy.ntheory.factor_ import factorint
# NOTE IMPORTANT
# The series expansion code in this file is an important part of the gruntz
# algorithm for determining limits. _eval_nseries has to return a generalized
# power series with coefficients in C(log(x), log).
# In more detail, the result of _eval_nseries(self, x, n) must be
# c_0*x**e_0 + ... (finitely many terms)
# where e_i are numbers (not necessarily integers) and c_i involve only
# numbers, the function log, and log(x). [This also means it must not contain
# log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and
# p.is_positive.]
class ExpBase(Function):
unbranched = True
_singularities = (S.ComplexInfinity,)
@property
def kind(self):
return self.exp.kind
def inverse(self, argindex=1):
"""
Returns the inverse function of ``exp(x)``.
"""
return log
def as_numer_denom(self):
"""
Returns this with a positive exponent as a 2-tuple (a fraction).
Examples
========
>>> from sympy import exp
>>> from sympy.abc import x
>>> exp(-x).as_numer_denom()
(1, exp(x))
>>> exp(x).as_numer_denom()
(exp(x), 1)
"""
# this should be the same as Pow.as_numer_denom wrt
# exponent handling
exp = self.exp
neg_exp = exp.is_negative
if not neg_exp and not (-exp).is_negative:
neg_exp = exp.could_extract_minus_sign()
if neg_exp:
return S.One, self.func(-exp)
return self, S.One
@property
def exp(self):
"""
Returns the exponent of the function.
"""
return self.args[0]
def as_base_exp(self):
"""
Returns the 2-tuple (base, exponent).
"""
return self.func(1), Mul(*self.args)
def _eval_adjoint(self):
return self.func(self.exp.adjoint())
def _eval_conjugate(self):
return self.func(self.exp.conjugate())
def _eval_transpose(self):
return self.func(self.exp.transpose())
def _eval_is_finite(self):
arg = self.exp
if arg.is_infinite:
if arg.is_extended_negative:
return True
if arg.is_extended_positive:
return False
if arg.is_finite:
return True
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
z = s.exp.is_zero
if z:
return True
elif s.exp.is_rational and fuzzy_not(z):
return False
else:
return s.is_rational
def _eval_is_zero(self):
return self.exp is S.NegativeInfinity
def _eval_power(self, other):
"""exp(arg)**e -> exp(arg*e) if assumptions allow it.
"""
b, e = self.as_base_exp()
return Pow._eval_power(Pow(b, e, evaluate=False), other)
def _eval_expand_power_exp(self, **hints):
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
arg = self.args[0]
if arg.is_Add and arg.is_commutative:
return Mul.fromiter(self.func(x) for x in arg.args)
elif isinstance(arg, Sum) and arg.is_commutative:
return Product(self.func(arg.function), *arg.limits)
return self.func(arg)
class exp_polar(ExpBase):
r"""
Represent a *polar number* (see g-function Sphinx documentation).
Explanation
===========
``exp_polar`` represents the function
`Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
`z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
the main functions to construct polar numbers.
Examples
========
>>> from sympy import exp_polar, pi, I, exp
The main difference is that polar numbers do not "wrap around" at `2 \pi`:
>>> exp(2*pi*I)
1
>>> exp_polar(2*pi*I)
exp_polar(2*I*pi)
apart from that they behave mostly like classical complex numbers:
>>> exp_polar(2)*exp_polar(3)
exp_polar(5)
See Also
========
sympy.simplify.powsimp.powsimp
polar_lift
periodic_argument
principal_branch
"""
is_polar = True
is_comparable = False # cannot be evalf'd
def _eval_Abs(self): # Abs is never a polar number
return exp(re(self.args[0]))
def _eval_evalf(self, prec):
""" Careful! any evalf of polar numbers is flaky """
i = im(self.args[0])
try:
bad = (i <= -pi or i > pi)
except TypeError:
bad = True
if bad:
return self # cannot evalf for this argument
res = exp(self.args[0])._eval_evalf(prec)
if i > 0 and im(res) < 0:
# i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
return re(res)
return res
def _eval_power(self, other):
return self.func(self.args[0]*other)
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
def as_base_exp(self):
# XXX exp_polar(0) is special!
if self.args[0] == 0:
return self, S.One
return ExpBase.as_base_exp(self)
class ExpMeta(FunctionClass):
def __instancecheck__(cls, instance):
if exp in instance.__class__.__mro__:
return True
return isinstance(instance, Pow) and instance.base is S.Exp1
class exp(ExpBase, metaclass=ExpMeta):
"""
The exponential function, :math:`e^x`.
Examples
========
>>> from sympy import exp, I, pi
>>> from sympy.abc import x
>>> exp(x)
exp(x)
>>> exp(x).diff(x)
exp(x)
>>> exp(I*pi)
-1
Parameters
==========
arg : Expr
See Also
========
log
"""
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return self
else:
raise ArgumentIndexError(self, argindex)
def _eval_refine(self, assumptions):
from sympy.assumptions import ask, Q
arg = self.args[0]
if arg.is_Mul:
Ioo = S.ImaginaryUnit*S.Infinity
if arg in [Ioo, -Ioo]:
return S.NaN
coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)
if coeff:
if ask(Q.integer(2*coeff)):
if ask(Q.even(coeff)):
return S.One
elif ask(Q.odd(coeff)):
return S.NegativeOne
elif ask(Q.even(coeff + S.Half)):
return -S.ImaginaryUnit
elif ask(Q.odd(coeff + S.Half)):
return S.ImaginaryUnit
@classmethod
def eval(cls, arg):
from sympy.calculus import AccumBounds
from sympy.matrices.matrices import MatrixBase
from sympy.sets.setexpr import SetExpr
from sympy.simplify.simplify import logcombine
if isinstance(arg, MatrixBase):
return arg.exp()
elif global_parameters.exp_is_pow:
return Pow(S.Exp1, arg)
elif arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.One
elif arg is S.One:
return S.Exp1
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Zero
elif arg is S.ComplexInfinity:
return S.NaN
elif isinstance(arg, log):
return arg.args[0]
elif isinstance(arg, AccumBounds):
return AccumBounds(exp(arg.min), exp(arg.max))
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
elif arg.is_Mul:
coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)
if coeff:
if (2*coeff).is_integer:
if coeff.is_even:
return S.One
elif coeff.is_odd:
return S.NegativeOne
elif (coeff + S.Half).is_even:
return -S.ImaginaryUnit
elif (coeff + S.Half).is_odd:
return S.ImaginaryUnit
elif coeff.is_Rational:
ncoeff = coeff % 2 # restrict to [0, 2pi)
if ncoeff > 1: # restrict to (-pi, pi]
ncoeff -= 2
if ncoeff != coeff:
return cls(ncoeff*S.Pi*S.ImaginaryUnit)
# Warning: code in risch.py will be very sensitive to changes
# in this (see DifferentialExtension).
# look for a single log factor
coeff, terms = arg.as_coeff_Mul()
# but it can't be multiplied by oo
if coeff in [S.NegativeInfinity, S.Infinity]:
if terms.is_number:
if coeff is S.NegativeInfinity:
terms = -terms
if re(terms).is_zero and terms is not S.Zero:
return S.NaN
if re(terms).is_positive and im(terms) is not S.Zero:
return S.ComplexInfinity
if re(terms).is_negative:
return S.Zero
return None
coeffs, log_term = [coeff], None
for term in Mul.make_args(terms):
term_ = logcombine(term)
if isinstance(term_, log):
if log_term is None:
log_term = term_.args[0]
else:
return None
elif term.is_comparable:
coeffs.append(term)
else:
return None
return log_term**Mul(*coeffs) if log_term else None
elif arg.is_Add:
out = []
add = []
argchanged = False
for a in arg.args:
if a is S.One:
add.append(a)
continue
newa = cls(a)
if isinstance(newa, cls):
if newa.args[0] != a:
add.append(newa.args[0])
argchanged = True
else:
add.append(a)
else:
out.append(newa)
if out or argchanged:
return Mul(*out)*cls(Add(*add), evaluate=False)
if arg.is_zero:
return S.One
@property
def base(self):
"""
Returns the base of the exponential function.
"""
return S.Exp1
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
"""
Calculates the next term in the Taylor series expansion.
"""
if n < 0:
return S.Zero
if n == 0:
return S.One
x = sympify(x)
if previous_terms:
p = previous_terms[-1]
if p is not None:
return p * x / n
return x**n/factorial(n)
def as_real_imag(self, deep=True, **hints):
"""
Returns this function as a 2-tuple representing a complex number.
Examples
========
>>> from sympy import exp, I
>>> from sympy.abc import x
>>> exp(x).as_real_imag()
(exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x)))
>>> exp(1).as_real_imag()
(E, 0)
>>> exp(I).as_real_imag()
(cos(1), sin(1))
>>> exp(1+I).as_real_imag()
(E*cos(1), E*sin(1))
See Also
========
sympy.functions.elementary.complexes.re
sympy.functions.elementary.complexes.im
"""
from sympy.functions.elementary.trigonometric import cos, sin
re, im = self.args[0].as_real_imag()
if deep:
re = re.expand(deep, **hints)
im = im.expand(deep, **hints)
cos, sin = cos(im), sin(im)
return (exp(re)*cos, exp(re)*sin)
def _eval_subs(self, old, new):
# keep processing of power-like args centralized in Pow
if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2)
old = exp(old.exp*log(old.base))
elif old is S.Exp1 and new.is_Function:
old = exp
if isinstance(old, exp) or old is S.Exp1:
f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if (
a.is_Pow or isinstance(a, exp)) else a
return Pow._eval_subs(f(self), f(old), new)
if old is exp and not new.is_Function:
return new**self.exp._subs(old, new)
return Function._eval_subs(self, old, new)
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
elif self.args[0].is_imaginary:
arg2 = -S(2) * S.ImaginaryUnit * self.args[0] / S.Pi
return arg2.is_even
def _eval_is_complex(self):
def complex_extended_negative(arg):
yield arg.is_complex
yield arg.is_extended_negative
return fuzzy_or(complex_extended_negative(self.args[0]))
def _eval_is_algebraic(self):
if (self.exp / S.Pi / S.ImaginaryUnit).is_rational:
return True
if fuzzy_not(self.exp.is_zero):
if self.exp.is_algebraic:
return False
elif (self.exp / S.Pi).is_rational:
return False
def _eval_is_extended_positive(self):
if self.exp.is_extended_real:
return self.args[0] is not S.NegativeInfinity
elif self.exp.is_imaginary:
arg2 = -S.ImaginaryUnit * self.args[0] / S.Pi
return arg2.is_even
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE Please see the comment at the beginning of this file, labelled
# IMPORTANT.
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.integers import ceiling
from sympy.series.limits import limit
from sympy.series.order import Order
from sympy.simplify.powsimp import powsimp
arg = self.exp
arg_series = arg._eval_nseries(x, n=n, logx=logx)
if arg_series.is_Order:
return 1 + arg_series
arg0 = limit(arg_series.removeO(), x, 0)
if arg0 is S.NegativeInfinity:
return Order(x**n, x)
if arg0 is S.Infinity:
return self
# checking for indecisiveness/ sign terms in arg0
if any(isinstance(arg, (sign, ImaginaryUnit)) for arg in arg0.args):
return self
t = Dummy("t")
nterms = n
try:
cf = Order(arg.as_leading_term(x, logx=logx), x).getn()
except (NotImplementedError, PoleError):
cf = 0
if cf and cf > 0:
nterms = ceiling(n/cf)
exp_series = exp(t)._taylor(t, nterms)
r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
rep = {logx: log(x)} if logx is not None else {}
if r.subs(rep) == self:
return r
if cf and cf > 1:
r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
else:
r += Order((arg_series - arg0)**n, x)
r = r.expand()
r = powsimp(r, deep=True, combine='exp')
# powsimp may introduce unexpanded (-1)**Rational; see PR #17201
simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
w = Wild('w', properties=[simplerat])
r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w))
return r
def _taylor(self, x, n):
l = []
g = None
for i in range(n):
g = self.taylor_term(i, self.args[0], g)
g = g.nseries(x, n=n)
l.append(g.removeO())
return Add(*l)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.util import AccumBounds
arg = self.args[0].cancel().as_leading_term(x, logx=logx)
arg0 = arg.subs(x, 0)
if arg is S.NaN:
return S.NaN
if isinstance(arg0, AccumBounds):
# This check addresses a corner case involving AccumBounds.
# if isinstance(arg, AccumBounds) is True, then arg0 can either be 0,
# AccumBounds(-oo, 0) or AccumBounds(-oo, oo).
# Check out function: test_issue_18473() in test_exponential.py and
# test_limits.py for more information.
if re(cdir) < S.Zero:
return exp(-arg0)
return exp(arg0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0)
if arg0.is_infinite is False:
return exp(arg0)
raise PoleError("Cannot expand %s around 0" % (self))
def _eval_rewrite_as_sin(self, arg, **kwargs):
from sympy.functions.elementary.trigonometric import sin
I = S.ImaginaryUnit
return sin(I*arg + S.Pi/2) - I*sin(I*arg)
def _eval_rewrite_as_cos(self, arg, **kwargs):
from sympy.functions.elementary.trigonometric import cos
I = S.ImaginaryUnit
return cos(I*arg) + I*cos(I*arg + S.Pi/2)
def _eval_rewrite_as_tanh(self, arg, **kwargs):
from sympy.functions.elementary.hyperbolic import tanh
return (1 + tanh(arg/2))/(1 - tanh(arg/2))
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
from sympy.functions.elementary.trigonometric import sin, cos
if arg.is_Mul:
coeff = arg.coeff(S.Pi*S.ImaginaryUnit)
if coeff and coeff.is_number:
cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
if not isinstance(cosine, cos) and not isinstance (sine, sin):
return cosine + S.ImaginaryUnit*sine
def _eval_rewrite_as_Pow(self, arg, **kwargs):
if arg.is_Mul:
logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
if logs:
return Pow(logs[0].args[0], arg.coeff(logs[0]))
def match_real_imag(expr):
r"""
Try to match expr with $a + Ib$ for real $a$ and $b$.
``match_real_imag`` returns a tuple containing the real and imaginary
parts of expr or ``(None, None)`` if direct matching is not possible. Contrary
to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things
by returning expressions themselves containing ``re()`` or ``im()`` and it
does not expand its argument either.
"""
r_, i_ = expr.as_independent(S.ImaginaryUnit, as_Add=True)
if i_ == 0 and r_.is_real:
return (r_, i_)
i_ = i_.as_coefficient(S.ImaginaryUnit)
if i_ and i_.is_real and r_.is_real:
return (r_, i_)
else:
return (None, None) # simpler to check for than None
class log(Function):
r"""
The natural logarithm function `\ln(x)` or `\log(x)`.
Explanation
===========
Logarithms are taken with the natural base, `e`. To get
a logarithm of a different base ``b``, use ``log(x, b)``,
which is essentially short-hand for ``log(x)/log(b)``.
``log`` represents the principal branch of the natural
logarithm. As such it has a branch cut along the negative
real axis and returns values having a complex argument in
`(-\pi, \pi]`.
Examples
========
>>> from sympy import log, sqrt, S, I
>>> log(8, 2)
3
>>> log(S(8)/3, 2)
-log(3)/log(2) + 3
>>> log(-1 + I*sqrt(3))
log(2) + 2*I*pi/3
See Also
========
exp
"""
args: tTuple[Expr]
_singularities = (S.Zero, S.ComplexInfinity)
def fdiff(self, argindex=1):
"""
Returns the first derivative of the function.
"""
if argindex == 1:
return 1/self.args[0]
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
r"""
Returns `e^x`, the inverse function of `\log(x)`.
"""
return exp
@classmethod
def eval(cls, arg, base=None):
from sympy.calculus import AccumBounds
from sympy.sets.setexpr import SetExpr
arg = sympify(arg)
if base is not None:
base = sympify(base)
if base == 1:
if arg == 1:
return S.NaN
else:
return S.ComplexInfinity
try:
# handle extraction of powers of the base now
# or else expand_log in Mul would have to handle this
n = multiplicity(base, arg)
if n:
return n + log(arg / base**n) / log(base)
else:
return log(arg)/log(base)
except ValueError:
pass
if base is not S.Exp1:
return cls(arg)/cls(base)
else:
return cls(arg)
if arg.is_Number:
if arg.is_zero:
return S.ComplexInfinity
elif arg is S.One:
return S.Zero
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Infinity
elif arg is S.NaN:
return S.NaN
elif arg.is_Rational and arg.p == 1:
return -cls(arg.q)
if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
return arg.exp
I = S.ImaginaryUnit
if isinstance(arg, exp) and arg.exp.is_extended_real:
return arg.exp
elif isinstance(arg, exp) and arg.exp.is_number:
r_, i_ = match_real_imag(arg.exp)
if i_ and i_.is_comparable:
i_ %= 2*S.Pi
if i_ > S.Pi:
i_ -= 2*S.Pi
return r_ + expand_mul(i_ * I, deep=False)
elif isinstance(arg, exp_polar):
return unpolarify(arg.exp)
elif isinstance(arg, AccumBounds):
if arg.min.is_positive:
return AccumBounds(log(arg.min), log(arg.max))
elif arg.min.is_zero:
return AccumBounds(S.NegativeInfinity, log(arg.max))
else:
return S.NaN
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
if arg.is_number:
if arg.is_negative:
return S.Pi * I + cls(-arg)
elif arg is S.ComplexInfinity:
return S.ComplexInfinity
elif arg is S.Exp1:
return S.One
if arg.is_zero:
return S.ComplexInfinity
# don't autoexpand Pow or Mul (see the issue 3351):
if not arg.is_Add:
coeff = arg.as_coefficient(I)
if coeff is not None:
if coeff is S.Infinity:
return S.Infinity
elif coeff is S.NegativeInfinity:
return S.Infinity
elif coeff.is_Rational:
if coeff.is_nonnegative:
return S.Pi * I * S.Half + cls(coeff)
else:
return -S.Pi * I * S.Half + cls(-coeff)
if arg.is_number and arg.is_algebraic:
# Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
coeff, arg_ = arg.as_independent(I, as_Add=False)
if coeff.is_negative:
coeff *= -1
arg_ *= -1
arg_ = expand_mul(arg_, deep=False)
r_, i_ = arg_.as_independent(I, as_Add=True)
i_ = i_.as_coefficient(I)
if coeff.is_real and i_ and i_.is_real and r_.is_real:
if r_.is_zero:
if i_.is_positive:
return S.Pi * I * S.Half + cls(coeff * i_)
elif i_.is_negative:
return -S.Pi * I * S.Half + cls(coeff * -i_)
else:
from sympy.simplify import ratsimp
# Check for arguments involving rational multiples of pi
t = (i_/r_).cancel()
t1 = (-t).cancel()
atan_table = {
# first quadrant only
sqrt(3): S.Pi/3,
1: S.Pi/4,
sqrt(5 - 2*sqrt(5)): S.Pi/5,
sqrt(2)*sqrt(5 - sqrt(5))/(1 + sqrt(5)): S.Pi/5,
sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5),
sqrt(2)*sqrt(sqrt(5) + 5)/(-1 + sqrt(5)): S.Pi*Rational(2, 5),
sqrt(3)/3: S.Pi/6,
sqrt(2) - 1: S.Pi/8,
sqrt(2 - sqrt(2))/sqrt(sqrt(2) + 2): S.Pi/8,
sqrt(2) + 1: S.Pi*Rational(3, 8),
sqrt(sqrt(2) + 2)/sqrt(2 - sqrt(2)): S.Pi*Rational(3, 8),
sqrt(1 - 2*sqrt(5)/5): S.Pi/10,
(-sqrt(2) + sqrt(10))/(2*sqrt(sqrt(5) + 5)): S.Pi/10,
sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10),
(sqrt(2) + sqrt(10))/(2*sqrt(5 - sqrt(5))): S.Pi*Rational(3, 10),
2 - sqrt(3): S.Pi/12,
(-1 + sqrt(3))/(1 + sqrt(3)): S.Pi/12,
2 + sqrt(3): S.Pi*Rational(5, 12),
(1 + sqrt(3))/(-1 + sqrt(3)): S.Pi*Rational(5, 12)
}
if t in atan_table:
modulus = ratsimp(coeff * Abs(arg_))
if r_.is_positive:
return cls(modulus) + I * atan_table[t]
else:
return cls(modulus) + I * (atan_table[t] - S.Pi)
elif t1 in atan_table:
modulus = ratsimp(coeff * Abs(arg_))
if r_.is_positive:
return cls(modulus) + I * (-atan_table[t1])
else:
return cls(modulus) + I * (S.Pi - atan_table[t1])
def as_base_exp(self):
"""
Returns this function in the form (base, exponent).
"""
return self, S.One
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms): # of log(1+x)
r"""
Returns the next term in the Taylor series expansion of `\log(1+x)`.
"""
from sympy.simplify.powsimp import powsimp
if n < 0:
return S.Zero
x = sympify(x)
if n == 0:
return x
if previous_terms:
p = previous_terms[-1]
if p is not None:
return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
def _eval_expand_log(self, deep=True, **hints):
from sympy.concrete import Sum, Product
force = hints.get('force', False)
factor = hints.get('factor', False)
if (len(self.args) == 2):
return expand_log(self.func(*self.args), deep=deep, force=force)
arg = self.args[0]
if arg.is_Integer:
# remove perfect powers
p = perfect_power(arg)
logarg = None
coeff = 1
if p is not False:
arg, coeff = p
logarg = self.func(arg)
# expand as product of its prime factors if factor=True
if factor:
p = factorint(arg)
if arg not in p.keys():
logarg = sum(n*log(val) for val, n in p.items())
if logarg is not None:
return coeff*logarg
elif arg.is_Rational:
return log(arg.p) - log(arg.q)
elif arg.is_Mul:
expr = []
nonpos = []
for x in arg.args:
if force or x.is_positive or x.is_polar:
a = self.func(x)
if isinstance(a, log):
expr.append(self.func(x)._eval_expand_log(**hints))
else:
expr.append(a)
elif x.is_negative:
a = self.func(-x)
expr.append(a)
nonpos.append(S.NegativeOne)
else:
nonpos.append(x)
return Add(*expr) + log(Mul(*nonpos))
elif arg.is_Pow or isinstance(arg, exp):
if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
.is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
b = arg.base
e = arg.exp
a = self.func(b)
if isinstance(a, log):
return unpolarify(e) * a._eval_expand_log(**hints)
else:
return unpolarify(e) * a
elif isinstance(arg, Product):
if force or arg.function.is_positive:
return Sum(log(arg.function), *arg.limits)
return self.func(arg)
def _eval_simplify(self, **kwargs):
from sympy.simplify.simplify import expand_log, simplify, inversecombine
if len(self.args) == 2: # it's unevaluated
return simplify(self.func(*self.args), **kwargs)
expr = self.func(simplify(self.args[0], **kwargs))
if kwargs['inverse']:
expr = inversecombine(expr)
expr = expand_log(expr, deep=True)
return min([expr, self], key=kwargs['measure'])
def as_real_imag(self, deep=True, **hints):
"""
Returns this function as a complex coordinate.
Examples
========
>>> from sympy import I, log
>>> from sympy.abc import x
>>> log(x).as_real_imag()
(log(Abs(x)), arg(x))
>>> log(I).as_real_imag()
(0, pi/2)
>>> log(1 + I).as_real_imag()
(log(sqrt(2)), pi/4)
>>> log(I*x).as_real_imag()
(log(Abs(x)), arg(I*x))
"""
sarg = self.args[0]
if deep:
sarg = self.args[0].expand(deep, **hints)
sarg_abs = Abs(sarg)
if sarg_abs == sarg:
return self, S.Zero
sarg_arg = arg(sarg)
if hints.get('log', False): # Expand the log
hints['complex'] = False
return (log(sarg_abs).expand(deep, **hints), sarg_arg)
else:
return log(sarg_abs), sarg_arg
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if (self.args[0] - 1).is_zero:
return True
if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
return False
else:
return s.is_rational
def _eval_is_algebraic(self):
s = self.func(*self.args)
if s.func == self.func:
if (self.args[0] - 1).is_zero:
return True
elif fuzzy_not((self.args[0] - 1).is_zero):
if self.args[0].is_algebraic:
return False
else:
return s.is_algebraic
def _eval_is_extended_real(self):
return self.args[0].is_extended_positive
def _eval_is_complex(self):
z = self.args[0]
return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_zero:
return False
return arg.is_finite
def _eval_is_extended_positive(self):
return (self.args[0] - 1).is_extended_positive
def _eval_is_zero(self):
return (self.args[0] - 1).is_zero
def _eval_is_extended_nonnegative(self):
return (self.args[0] - 1).is_extended_nonnegative
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE Please see the comment at the beginning of this file, labelled
# IMPORTANT.
from sympy.series.order import Order
from sympy.simplify.simplify import logcombine
from sympy.core.symbol import Dummy
if self.args[0] == x:
return log(x) if logx is None else logx
arg = self.args[0]
t = Dummy('t', positive=True)
if cdir == 0:
cdir = 1
z = arg.subs(x, cdir*t)
k, l = Wild("k"), Wild("l")
r = z.match(k*t**l)
if r is not None:
k, l = r[k], r[l]
if l != 0 and not l.has(t) and not k.has(t):
r = l*log(x) if logx is None else l*logx
r += log(k) - l*log(cdir) # XXX true regardless of assumptions?
return r
def coeff_exp(term, x):
coeff, exp = S.One, S.Zero
for factor in Mul.make_args(term):
if factor.has(x):
base, exp = factor.as_base_exp()
if base != x:
try:
return term.leadterm(x)
except ValueError:
return term, S.Zero
else:
coeff *= factor
return coeff, exp
# TODO new and probably slow
try:
a, b = z.leadterm(t, logx=logx, cdir=1)
except (ValueError, NotImplementedError, PoleError):
s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
while s.is_Order:
n += 1
s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
try:
a, b = s.removeO().leadterm(t, cdir=1)
except ValueError:
a, b = s.removeO().as_leading_term(t, cdir=1), S.Zero
p = (z/(a*t**b) - 1)._eval_nseries(t, n=n, logx=logx, cdir=1)
if p.has(exp):
p = logcombine(p)
if isinstance(p, Order):
n = p.getn()
_, d = coeff_exp(p, t)
logx = log(x) if logx is None else logx
if not d.is_positive:
res = log(a) - b*log(cdir) + b*logx
_res = res
logflags = dict(deep=True, log=True, mul=False, power_exp=False,
power_base=False, multinomial=False, basic=False, force=True,
factor=False)
expr = self.expand(**logflags)
if (not a.could_extract_minus_sign() and
logx.could_extract_minus_sign()):
_res = _res.subs(-logx, -log(x)).expand(**logflags)
else:
_res = _res.subs(logx, log(x)).expand(**logflags)
if _res == expr:
return res
return res + Order(x**n, x)
def mul(d1, d2):
res = {}
for e1, e2 in product(d1, d2):
ex = e1 + e2
if ex < n:
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
return res
pterms = {}
for term in Add.make_args(p.removeO()):
co1, e1 = coeff_exp(term, t)
pterms[e1] = pterms.get(e1, S.Zero) + co1
k = S.One
terms = {}
pk = pterms
while k*d < n:
coeff = -S.NegativeOne**k/k
for ex in pk:
_ = terms.get(ex, S.Zero) + coeff*pk[ex]
terms[ex] = _.nsimplify()
pk = mul(pk, pterms)
k += S.One
res = log(a) - b*log(cdir) + b*logx
for ex in terms:
res += terms[ex]*t**(ex)
if a.is_negative and im(z) != 0:
from sympy.functions.special.delta_functions import Heaviside
for i, term in enumerate(z.lseries(t)):
if not term.is_real or i == 5:
break
if i < 5:
coeff, _ = term.as_coeff_exponent(t)
res += -2*I*S.Pi*Heaviside(-im(coeff), 0)
res = res.subs(t, x/cdir)
return res + Order(x**n, x)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
# NOTE
# Refer https://github.com/sympy/sympy/pull/23592 for more information
# on each of the following steps involved in this method.
arg0 = self.args[0].together()
# STEP 1
t = Dummy('t', positive=True)
if cdir == 0:
cdir = 1
z = arg0.subs(x, cdir*t)
# STEP 2
try:
c, e = z.leadterm(t, logx=logx, cdir=1)
except ValueError:
arg = arg0.as_leading_term(x, logx=logx, cdir=cdir)
return log(arg)
if c.has(t):
c = c.subs(t, x/cdir)
if e != 0:
raise PoleError("Cannot expand %s around 0" % (self))
return log(c)
# STEP 3
if c == S.One and e == S.Zero:
return (arg0 - S.One).as_leading_term(x, logx=logx)
# STEP 4
res = log(c) - e*log(cdir)
logx = log(x) if logx is None else logx
res += e*logx
# STEP 5
if c.is_negative and im(z) != 0:
from sympy.functions.special.delta_functions import Heaviside
for i, term in enumerate(z.lseries(t)):
if not term.is_real or i == 5:
break
if i < 5:
coeff, _ = term.as_coeff_exponent(t)
res += -2*I*S.Pi*Heaviside(-im(coeff), 0)
return res
class LambertW(Function):
r"""
The Lambert W function $W(z)$ is defined as the inverse
function of $w \exp(w)$ [1]_.
Explanation
===========
In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$
for any complex number $z$. The Lambert W function is a multivalued
function with infinitely many branches $W_k(z)$, indexed by
$k \in \mathbb{Z}$. Each branch gives a different solution $w$
of the equation $z = w \exp(w)$.
The Lambert W function has two partially real branches: the
principal branch ($k = 0$) is real for real $z > -1/e$, and the
$k = -1$ branch is real for $-1/e < z < 0$. All branches except
$k = 0$ have a logarithmic singularity at $z = 0$.
Examples
========
>>> from sympy import LambertW
>>> LambertW(1.2)
0.635564016364870
>>> LambertW(1.2, -1).n()
-1.34747534407696 - 4.41624341514535*I
>>> LambertW(-1).is_real
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Lambert_W_function
"""
_singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
@classmethod
def eval(cls, x, k=None):
if k == S.Zero:
return cls(x)
elif k is None:
k = S.Zero
if k.is_zero:
if x.is_zero:
return S.Zero
if x is S.Exp1:
return S.One
if x == -1/S.Exp1:
return S.NegativeOne
if x == -log(2)/2:
return -log(2)
if x == 2*log(2):
return log(2)
if x == -S.Pi/2:
return S.ImaginaryUnit*S.Pi/2
if x == exp(1 + S.Exp1):
return S.Exp1
if x is S.Infinity:
return S.Infinity
if x.is_zero:
return S.Zero
if fuzzy_not(k.is_zero):
if x.is_zero:
return S.NegativeInfinity
if k is S.NegativeOne:
if x == -S.Pi/2:
return -S.ImaginaryUnit*S.Pi/2
elif x == -1/S.Exp1:
return S.NegativeOne
elif x == -2*exp(-2):
return -Integer(2)
def fdiff(self, argindex=1):
"""
Return the first derivative of this function.
"""
x = self.args[0]
if len(self.args) == 1:
if argindex == 1:
return LambertW(x)/(x*(1 + LambertW(x)))
else:
k = self.args[1]
if argindex == 1:
return LambertW(x, k)/(x*(1 + LambertW(x, k)))
raise ArgumentIndexError(self, argindex)
def _eval_is_extended_real(self):
x = self.args[0]
if len(self.args) == 1:
k = S.Zero
else:
k = self.args[1]
if k.is_zero:
if (x + 1/S.Exp1).is_positive:
return True
elif (x + 1/S.Exp1).is_nonpositive:
return False
elif (k + 1).is_zero:
if x.is_negative and (x + 1/S.Exp1).is_positive:
return True
elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
return False
elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
if x.is_extended_real:
return False
def _eval_is_finite(self):
return self.args[0].is_finite
def _eval_is_algebraic(self):
s = self.func(*self.args)
if s.func == self.func:
if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
return False
else:
return s.is_algebraic
def _eval_as_leading_term(self, x, logx=None, cdir=0):
if len(self.args) == 1:
arg = self.args[0]
arg0 = arg.subs(x, 0).cancel()
if not arg0.is_zero:
return self.func(arg0)
return arg.as_leading_term(x)
def _eval_nseries(self, x, n, logx, cdir=0):
if len(self.args) == 1:
from sympy.functions.elementary.integers import ceiling
from sympy.series.order import Order
arg = self.args[0].nseries(x, n=n, logx=logx)
lt = arg.as_leading_term(x, logx=logx)
lte = 1
if lt.is_Pow:
lte = lt.exp
if ceiling(n/lte) >= 1:
s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
s = expand_multinomial(s)
else:
s = S.Zero
return s + Order(x**n, x)
return super()._eval_nseries(x, n, logx)
def _eval_is_zero(self):
x = self.args[0]
if len(self.args) == 1:
return x.is_zero
else:
return fuzzy_and([x.is_zero, self.args[1].is_zero])
|
be46919c2451e43d063a38fbf555d5aacf6e76c686c440db5b928a2c93229aa1 | from math import prod
from sympy.core import Add, S, Dummy, expand_func
from sympy.core.expr import Expr
from sympy.core.function import Function, ArgumentIndexError, PoleError
from sympy.core.logic import fuzzy_and, fuzzy_not
from sympy.core.numbers import Rational, pi, oo, I
from sympy.core.power import Pow
from sympy.functions.special.zeta_functions import zeta
from sympy.functions.special.error_functions import erf, erfc, Ei
from sympy.functions.elementary.complexes import re, unpolarify
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin, cos, cot
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
from sympy.functions.combinatorial.factorials import factorial, rf, RisingFactorial
from sympy.utilities.misc import as_int
from mpmath import mp, workprec
from mpmath.libmp.libmpf import prec_to_dps
def intlike(n):
try:
as_int(n, strict=False)
return True
except ValueError:
return False
###############################################################################
############################ COMPLETE GAMMA FUNCTION ##########################
###############################################################################
class gamma(Function):
r"""
The gamma function
.. math::
\Gamma(x) := \int^{\infty}_{0} t^{x-1} e^{-t} \mathrm{d}t.
Explanation
===========
The ``gamma`` function implements the function which passes through the
values of the factorial function (i.e., $\Gamma(n) = (n - 1)!$ when n is
an integer). More generally, $\Gamma(z)$ is defined in the whole complex
plane except at the negative integers where there are simple poles.
Examples
========
>>> from sympy import S, I, pi, gamma
>>> from sympy.abc import x
Several special values are known:
>>> gamma(1)
1
>>> gamma(4)
6
>>> gamma(S(3)/2)
sqrt(pi)/2
The ``gamma`` function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(gamma(x))
gamma(conjugate(x))
Differentiation with respect to $x$ is supported:
>>> from sympy import diff
>>> diff(gamma(x), x)
gamma(x)*polygamma(0, x)
Series expansion is also supported:
>>> from sympy import series
>>> series(gamma(x), x, 0, 3)
1/x - EulerGamma + x*(EulerGamma**2/2 + pi**2/12) + x**2*(-EulerGamma*pi**2/12 - zeta(3)/3 - EulerGamma**3/6) + O(x**3)
We can numerically evaluate the ``gamma`` function to arbitrary precision
on the whole complex plane:
>>> gamma(pi).evalf(40)
2.288037795340032417959588909060233922890
>>> gamma(1+I).evalf(20)
0.49801566811835604271 - 0.15494982830181068512*I
See Also
========
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Gamma_function
.. [2] http://dlmf.nist.gov/5
.. [3] http://mathworld.wolfram.com/GammaFunction.html
.. [4] http://functions.wolfram.com/GammaBetaErf/Gamma/
"""
unbranched = True
_singularities = (S.ComplexInfinity,)
def fdiff(self, argindex=1):
if argindex == 1:
return self.func(self.args[0])*polygamma(0, self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif intlike(arg):
if arg.is_positive:
return factorial(arg - 1)
else:
return S.ComplexInfinity
elif arg.is_Rational:
if arg.q == 2:
n = abs(arg.p) // arg.q
if arg.is_positive:
k, coeff = n, S.One
else:
n = k = n + 1
if n & 1 == 0:
coeff = S.One
else:
coeff = S.NegativeOne
coeff *= prod(range(3, 2*k, 2))
if arg.is_positive:
return coeff*sqrt(S.Pi) / 2**n
else:
return 2**n*sqrt(S.Pi) / coeff
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 self.func(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 self.func(tail)*RisingFactorial(tail, coeff)
return self.func(*self.args)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_is_real(self):
x = self.args[0]
if x.is_nonpositive and x.is_integer:
return False
if intlike(x) and x <= 0:
return False
if x.is_positive or x.is_noninteger:
return True
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_tractable(self, z, limitvar=None, **kwargs):
return exp(loggamma(z))
def _eval_rewrite_as_factorial(self, z, **kwargs):
return factorial(z - 1)
def _eval_nseries(self, x, n, logx, cdir=0):
x0 = self.args[0].limit(x, 0)
if not (x0.is_Integer and x0 <= 0):
return super()._eval_nseries(x, n, logx)
t = self.args[0] - x0
return (self.func(t + 1)/rf(self.args[0], -x0 + 1))._eval_nseries(x, n, logx)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0)
if x0.is_integer and x0.is_nonpositive:
n = -x0
res = S.NegativeOne**n/self.func(n + 1)
return res/(arg + n).as_leading_term(x)
elif not x0.is_infinite:
return self.func(x0)
raise PoleError()
###############################################################################
################## LOWER and UPPER INCOMPLETE GAMMA FUNCTIONS #################
###############################################################################
class lowergamma(Function):
r"""
The lower incomplete gamma function.
Explanation
===========
It can be defined as the meromorphic continuation of
.. math::
\gamma(s, x) := \int_0^x t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \Gamma(s, x).
This can be shown to be the same as
.. math::
\gamma(s, x) = \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right),
where ${}_1F_1$ is the (confluent) hypergeometric function.
Examples
========
>>> from sympy import lowergamma, S
>>> from sympy.abc import s, x
>>> lowergamma(s, x)
lowergamma(s, x)
>>> lowergamma(3, x)
-2*(x**2/2 + x + 1)*exp(-x) + 2
>>> lowergamma(-S(1)/2, x)
-2*sqrt(pi)*erf(sqrt(x)) - 2*exp(-x)/sqrt(x)
See Also
========
gamma: Gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Lower_incomplete_Gamma_function
.. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6,
Section 5, Handbook of Mathematical Functions with Formulas, Graphs,
and Mathematical Tables
.. [3] http://dlmf.nist.gov/8
.. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/
.. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/
"""
def fdiff(self, argindex=2):
from sympy.functions.special.hyper import meijerg
if argindex == 2:
a, z = self.args
return exp(-unpolarify(z))*z**(a - 1)
elif argindex == 1:
a, z = self.args
return gamma(a)*digamma(a) - log(z)*uppergamma(a, z) \
- meijerg([], [1, 1], [0, 0, a], [], z)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, a, x):
# For lack of a better place, we use this one to extract branching
# information. The following can be
# found in the literature (c/f references given above), albeit scattered:
# 1) For fixed x != 0, lowergamma(s, x) is an entire function of s
# 2) For fixed positive integers s, lowergamma(s, x) is an entire
# function of x.
# 3) For fixed non-positive integers s,
# lowergamma(s, exp(I*2*pi*n)*x) =
# 2*pi*I*n*(-1)**(-s)/factorial(-s) + lowergamma(s, x)
# (this follows from lowergamma(s, x).diff(x) = x**(s-1)*exp(-x)).
# 4) For fixed non-integral s,
# lowergamma(s, x) = x**s*gamma(s)*lowergamma_unbranched(s, x),
# where lowergamma_unbranched(s, x) is an entire function (in fact
# of both s and x), i.e.
# lowergamma(s, exp(2*I*pi*n)*x) = exp(2*pi*I*n*a)*lowergamma(a, x)
if x is S.Zero:
return S.Zero
nx, n = x.extract_branch_factor()
if a.is_integer and a.is_positive:
nx = unpolarify(x)
if nx != x:
return lowergamma(a, nx)
elif a.is_integer and a.is_nonpositive:
if n != 0:
return 2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + lowergamma(a, nx)
elif n != 0:
return exp(2*pi*I*n*a)*lowergamma(a, nx)
# Special values.
if a.is_Number:
if a is S.One:
return S.One - exp(-x)
elif a is S.Half:
return sqrt(pi)*erf(sqrt(x))
elif a.is_Integer or (2*a).is_Integer:
b = a - 1
if b.is_positive:
if a.is_integer:
return factorial(b) - exp(-x) * factorial(b) * Add(*[x ** k / factorial(k) for k in range(a)])
else:
return gamma(a)*(lowergamma(S.Half, x)/sqrt(pi) - exp(-x)*Add(*[x**(k - S.Half)/gamma(S.Half + k) for k in range(1, a + S.Half)]))
if not a.is_Integer:
return S.NegativeOne**(S.Half - a)*pi*erf(sqrt(x))/gamma(1 - a) + exp(-x)*Add(*[x**(k + a - 1)*gamma(a)/gamma(a + k) for k in range(1, Rational(3, 2) - a)])
if x.is_zero:
return S.Zero
def _eval_evalf(self, prec):
if all(x.is_number for x in self.args):
a = self.args[0]._to_mpmath(prec)
z = self.args[1]._to_mpmath(prec)
with workprec(prec):
res = mp.gammainc(a, 0, z)
return Expr._from_mpmath(res, prec)
else:
return self
def _eval_conjugate(self):
x = self.args[1]
if x not in (S.Zero, S.NegativeInfinity):
return self.func(self.args[0].conjugate(), x.conjugate())
def _eval_is_meromorphic(self, x, a):
# By https://en.wikipedia.org/wiki/Incomplete_gamma_function#Holomorphic_extension,
# lowergamma(s, z) = z**s*gamma(s)*gammastar(s, z),
# where gammastar(s, z) is holomorphic for all s and z.
# Hence the singularities of lowergamma are z = 0 (branch
# point) and nonpositive integer values of s (poles of gamma(s)).
s, z = self.args
args_merom = fuzzy_and([z._eval_is_meromorphic(x, a),
s._eval_is_meromorphic(x, a)])
if not args_merom:
return args_merom
z0 = z.subs(x, a)
if s.is_integer:
return fuzzy_and([s.is_positive, z0.is_finite])
s0 = s.subs(x, a)
return fuzzy_and([s0.is_finite, z0.is_finite, fuzzy_not(z0.is_zero)])
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import O
s, z = self.args
if args0[0] is S.Infinity and not z.has(x):
coeff = z**s*exp(-z)
sum_expr = sum(z**k/rf(s, k + 1) for k in range(n - 1))
o = O(z**s*s**(-n))
return coeff*sum_expr + o
return super()._eval_aseries(n, args0, x, logx)
def _eval_rewrite_as_uppergamma(self, s, x, **kwargs):
return gamma(s) - uppergamma(s, x)
def _eval_rewrite_as_expint(self, s, x, **kwargs):
from sympy.functions.special.error_functions import expint
if s.is_integer and s.is_nonpositive:
return self
return self.rewrite(uppergamma).rewrite(expint)
def _eval_is_zero(self):
x = self.args[1]
if x.is_zero:
return True
class uppergamma(Function):
r"""
The upper incomplete gamma function.
Explanation
===========
It can be defined as the meromorphic continuation of
.. math::
\Gamma(s, x) := \int_x^\infty t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \gamma(s, x).
where $\gamma(s, x)$ is the lower incomplete gamma function,
:class:`lowergamma`. This can be shown to be the same as
.. math::
\Gamma(s, x) = \Gamma(s) - \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right),
where ${}_1F_1$ is the (confluent) hypergeometric function.
The upper incomplete gamma function is also essentially equivalent to the
generalized exponential integral:
.. math::
\operatorname{E}_{n}(x) = \int_{1}^{\infty}{\frac{e^{-xt}}{t^n} \, dt} = x^{n-1}\Gamma(1-n,x).
Examples
========
>>> from sympy import uppergamma, S
>>> from sympy.abc import s, x
>>> uppergamma(s, x)
uppergamma(s, x)
>>> uppergamma(3, x)
2*(x**2/2 + x + 1)*exp(-x)
>>> uppergamma(-S(1)/2, x)
-2*sqrt(pi)*erfc(sqrt(x)) + 2*exp(-x)/sqrt(x)
>>> uppergamma(-2, x)
expint(3, x)/x**2
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Upper_incomplete_Gamma_function
.. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6,
Section 5, Handbook of Mathematical Functions with Formulas, Graphs,
and Mathematical Tables
.. [3] http://dlmf.nist.gov/8
.. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/
.. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/
.. [6] https://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions
"""
def fdiff(self, argindex=2):
from sympy.functions.special.hyper import meijerg
if argindex == 2:
a, z = self.args
return -exp(-unpolarify(z))*z**(a - 1)
elif argindex == 1:
a, z = self.args
return uppergamma(a, z)*log(z) + meijerg([], [1, 1], [0, 0, a], [], z)
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
if all(x.is_number for x in self.args):
a = self.args[0]._to_mpmath(prec)
z = self.args[1]._to_mpmath(prec)
with workprec(prec):
res = mp.gammainc(a, z, mp.inf)
return Expr._from_mpmath(res, prec)
return self
@classmethod
def eval(cls, a, z):
from sympy.functions.special.error_functions import expint
if z.is_Number:
if z is S.NaN:
return S.NaN
elif z is S.Infinity:
return S.Zero
elif z.is_zero:
if re(a).is_positive:
return gamma(a)
# We extract branching information here. C/f lowergamma.
nx, n = z.extract_branch_factor()
if a.is_integer and a.is_positive:
nx = unpolarify(z)
if z != nx:
return uppergamma(a, nx)
elif a.is_integer and a.is_nonpositive:
if n != 0:
return -2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + uppergamma(a, nx)
elif n != 0:
return gamma(a)*(1 - exp(2*pi*I*n*a)) + exp(2*pi*I*n*a)*uppergamma(a, nx)
# Special values.
if a.is_Number:
if a is S.Zero and z.is_positive:
return -Ei(-z)
elif a is S.One:
return exp(-z)
elif a is S.Half:
return sqrt(pi)*erfc(sqrt(z))
elif a.is_Integer or (2*a).is_Integer:
b = a - 1
if b.is_positive:
if a.is_integer:
return exp(-z) * factorial(b) * Add(*[z**k / factorial(k)
for k in range(a)])
else:
return (gamma(a) * erfc(sqrt(z)) +
S.NegativeOne**(a - S(3)/2) * exp(-z) * sqrt(z)
* Add(*[gamma(-S.Half - k) * (-z)**k / gamma(1-a)
for k in range(a - S.Half)]))
elif b.is_Integer:
return expint(-b, z)*unpolarify(z)**(b + 1)
if not a.is_Integer:
return (S.NegativeOne**(S.Half - a) * pi*erfc(sqrt(z))/gamma(1-a)
- z**a * exp(-z) * Add(*[z**k * gamma(a) / gamma(a+k+1)
for k in range(S.Half - a)]))
if a.is_zero and z.is_positive:
return -Ei(-z)
if z.is_zero and re(a).is_positive:
return gamma(a)
def _eval_conjugate(self):
z = self.args[1]
if z not in (S.Zero, S.NegativeInfinity):
return self.func(self.args[0].conjugate(), z.conjugate())
def _eval_is_meromorphic(self, x, a):
return lowergamma._eval_is_meromorphic(self, x, a)
def _eval_rewrite_as_lowergamma(self, s, x, **kwargs):
return gamma(s) - lowergamma(s, x)
def _eval_rewrite_as_tractable(self, s, x, **kwargs):
return exp(loggamma(s)) - lowergamma(s, x)
def _eval_rewrite_as_expint(self, s, x, **kwargs):
from sympy.functions.special.error_functions import expint
return expint(1 - s, x)*x**s
###############################################################################
###################### POLYGAMMA and LOGGAMMA FUNCTIONS #######################
###############################################################################
class polygamma(Function):
r"""
The function ``polygamma(n, z)`` returns ``log(gamma(z)).diff(n + 1)``.
Explanation
===========
It is a meromorphic function on $\mathbb{C}$ and defined as the $(n+1)$-th
derivative of the logarithm of the gamma function:
.. math::
\psi^{(n)} (z) := \frac{\mathrm{d}^{n+1}}{\mathrm{d} z^{n+1}} \log\Gamma(z).
For `n` not a nonnegative integer the generalization by Espinosa and Moll [5]_
is used:
.. math:: \psi(s,z) = \frac{\zeta'(s+1, z) + (\gamma + \psi(-s)) \zeta(s+1, z)}
{\Gamma(-s)}
Examples
========
Several special values are known:
>>> from sympy import S, polygamma
>>> polygamma(0, 1)
-EulerGamma
>>> polygamma(0, 1/S(2))
-2*log(2) - EulerGamma
>>> polygamma(0, 1/S(3))
-log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3))
>>> polygamma(0, 1/S(4))
-pi/2 - log(4) - log(2) - EulerGamma
>>> polygamma(0, 2)
1 - EulerGamma
>>> polygamma(0, 23)
19093197/5173168 - EulerGamma
>>> from sympy import oo, I
>>> polygamma(0, oo)
oo
>>> polygamma(0, -oo)
oo
>>> polygamma(0, I*oo)
oo
>>> polygamma(0, -I*oo)
oo
Differentiation with respect to $x$ is supported:
>>> from sympy import Symbol, diff
>>> x = Symbol("x")
>>> diff(polygamma(0, x), x)
polygamma(1, x)
>>> diff(polygamma(0, x), x, 2)
polygamma(2, x)
>>> diff(polygamma(0, x), x, 3)
polygamma(3, x)
>>> diff(polygamma(1, x), x)
polygamma(2, x)
>>> diff(polygamma(1, x), x, 2)
polygamma(3, x)
>>> diff(polygamma(2, x), x)
polygamma(3, x)
>>> diff(polygamma(2, x), x, 2)
polygamma(4, x)
>>> n = Symbol("n")
>>> diff(polygamma(n, x), x)
polygamma(n + 1, x)
>>> diff(polygamma(n, x), x, 2)
polygamma(n + 2, x)
We can rewrite ``polygamma`` functions in terms of harmonic numbers:
>>> from sympy import harmonic
>>> polygamma(0, x).rewrite(harmonic)
harmonic(x - 1) - EulerGamma
>>> polygamma(2, x).rewrite(harmonic)
2*harmonic(x - 1, 3) - 2*zeta(3)
>>> ni = Symbol("n", integer=True)
>>> polygamma(ni, x).rewrite(harmonic)
(-1)**(n + 1)*(-harmonic(x - 1, n + 1) + zeta(n + 1))*factorial(n)
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Polygamma_function
.. [2] http://mathworld.wolfram.com/PolygammaFunction.html
.. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma/
.. [4] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/
.. [5] O. Espinosa and V. Moll, "A generalized polygamma function",
*Integral Transforms and Special Functions* (2004), 101-115.
"""
@classmethod
def eval(cls, n, z):
if n is S.NaN or z is S.NaN:
return S.NaN
elif z is S.Infinity:
return S.Infinity if n.is_zero else S.Zero
elif z.is_Integer and z.is_nonpositive:
return S.ComplexInfinity
elif n is S.NegativeOne:
return loggamma(z) - log(2*pi) / 2
elif n.is_zero:
if z is -oo or z.extract_multiplicatively(I) in (oo, -oo):
return S.Infinity
elif z.is_Integer:
return harmonic(z-1) - S.EulerGamma
elif z.is_Rational:
# TODO n == 1 also can do some rational z
p, q = z.as_numer_denom()
# only expand for small denominators to avoid creating long expressions
if q <= 6:
return expand_func(polygamma(S.Zero, z, evaluate=False))
elif n.is_integer and n.is_nonnegative:
nz = unpolarify(z)
if z != nz:
return polygamma(n, nz)
if z.is_Integer:
return S.NegativeOne**(n+1) * factorial(n) * zeta(n+1, z)
elif z is S.Half:
return S.NegativeOne**(n+1) * factorial(n) * (2**(n+1)-1) * zeta(n+1)
def _eval_is_real(self):
if self.args[0].is_positive and self.args[1].is_positive:
return True
def _eval_is_complex(self):
z = self.args[1]
is_negative_integer = fuzzy_and([z.is_negative, z.is_integer])
return fuzzy_and([z.is_complex, fuzzy_not(is_negative_integer)])
def _eval_is_positive(self):
n, z = self.args
if n.is_positive:
if n.is_odd and z.is_real:
return True
if n.is_even and z.is_positive:
return False
def _eval_is_negative(self):
n, z = self.args
if n.is_positive:
if n.is_even and z.is_positive:
return True
if n.is_odd and z.is_real:
return False
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(int(-coeff))])
return polygamma(n, z - coeff) + S.NegativeOne**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(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)])
if n == -1:
return loggamma(z) - log(2*pi) / 2
if n.is_integer is False or n.is_nonnegative is False:
s = Dummy("s")
dzt = zeta(s, z).diff(s).subs(s, n+1)
return (dzt + (S.EulerGamma + digamma(-n)) * zeta(n+1, z)) / gamma(-n)
return polygamma(n, z)
def _eval_rewrite_as_zeta(self, n, z, **kwargs):
if n.is_integer and n.is_positive:
return S.NegativeOne**(n + 1)*factorial(n)*zeta(n + 1, z)
def _eval_rewrite_as_harmonic(self, n, z, **kwargs):
if n.is_integer:
if n.is_zero:
return harmonic(z - 1) - S.EulerGamma
else:
return S.NegativeOne**(n+1) * factorial(n) * (zeta(n+1) - harmonic(z-1, n+1))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.series.order import Order
n, z = [a.as_leading_term(x) for a in self.args]
o = Order(z, x)
if n == 0 and o.contains(1/x):
logx = log(x) if logx is None else logx
return o.getn() * logx
else:
return self.func(n, z)
def fdiff(self, argindex=2):
if argindex == 2:
n, z = self.args[:2]
return polygamma(n + 1, z)
else:
raise ArgumentIndexError(self, argindex)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
if args0[1] != oo or not \
(self.args[0].is_Integer and self.args[0].is_nonnegative):
return super()._eval_aseries(n, args0, x, logx)
z = self.args[1]
N = self.args[0]
if N == 0:
# digamma function series
# Abramowitz & Stegun, p. 259, 6.3.18
r = log(z) - 1/(2*z)
o = None
if n < 2:
o = Order(1/z, x)
else:
m = ceiling((n + 1)//2)
l = [bernoulli(2*k) / (2*k*z**(2*k)) for k in range(1, m)]
r -= Add(*l)
o = Order(1/z**n, x)
return r._eval_nseries(x, n, logx) + o
else:
# proper polygamma function
# Abramowitz & Stegun, p. 260, 6.4.10
# We return terms to order higher than O(x**n) on purpose
# -- otherwise we would not be able to return any terms for
# quite a long time!
fac = gamma(N)
e0 = fac + N*fac/(2*z)
m = ceiling((n + 1)//2)
for k in range(1, m):
fac = fac*(2*k + N - 1)*(2*k + N - 2) / ((2*k)*(2*k - 1))
e0 += bernoulli(2*k)*fac/z**(2*k)
o = Order(1/z**(2*m), x)
if n == 0:
o = Order(1/z, x)
elif n == 1:
o = Order(1/z**2, x)
r = e0._eval_nseries(z, n, logx) + o
return (-1 * (-1/z)**N * r)._eval_nseries(x, n, logx)
def _eval_evalf(self, prec):
if not all(i.is_number for i in self.args):
return
s = self.args[0]._to_mpmath(prec+12)
z = self.args[1]._to_mpmath(prec+12)
if mp.isint(z) and z <= 0:
return S.ComplexInfinity
with workprec(prec+12):
if mp.isint(s) and s >= 0:
res = mp.polygamma(s, z)
else:
zt = mp.zeta(s+1, z)
dzt = mp.zeta(s+1, z, 1)
res = (dzt + (mp.euler + mp.digamma(-s)) * zt) * mp.rgamma(-s)
return Expr._from_mpmath(res, prec)
class loggamma(Function):
r"""
The ``loggamma`` function implements the logarithm of the
gamma function (i.e., $\log\Gamma(x)$).
Examples
========
Several special values are known. For numerical integral
arguments we have:
>>> from sympy import loggamma
>>> loggamma(-2)
oo
>>> loggamma(0)
oo
>>> loggamma(1)
0
>>> loggamma(2)
0
>>> loggamma(3)
log(2)
And for symbolic values:
>>> from sympy import Symbol
>>> n = Symbol("n", integer=True, positive=True)
>>> loggamma(n)
log(gamma(n))
>>> loggamma(-n)
oo
For half-integral values:
>>> from sympy import S
>>> loggamma(S(5)/2)
log(3*sqrt(pi)/4)
>>> loggamma(n/2)
log(2**(1 - n)*sqrt(pi)*gamma(n)/gamma(n/2 + 1/2))
And general rational arguments:
>>> from sympy import expand_func
>>> L = loggamma(S(16)/3)
>>> expand_func(L).doit()
-5*log(3) + loggamma(1/3) + log(4) + log(7) + log(10) + log(13)
>>> L = loggamma(S(19)/4)
>>> expand_func(L).doit()
-4*log(4) + loggamma(3/4) + log(3) + log(7) + log(11) + log(15)
>>> L = loggamma(S(23)/7)
>>> expand_func(L).doit()
-3*log(7) + log(2) + loggamma(2/7) + log(9) + log(16)
The ``loggamma`` function has the following limits towards infinity:
>>> from sympy import oo
>>> loggamma(oo)
oo
>>> loggamma(-oo)
zoo
The ``loggamma`` function obeys the mirror symmetry
if $x \in \mathbb{C} \setminus \{-\infty, 0\}$:
>>> from sympy.abc import x
>>> from sympy import conjugate
>>> conjugate(loggamma(x))
loggamma(conjugate(x))
Differentiation with respect to $x$ is supported:
>>> from sympy import diff
>>> diff(loggamma(x), x)
polygamma(0, x)
Series expansion is also supported:
>>> from sympy import series
>>> series(loggamma(x), x, 0, 4).cancel()
-log(x) - EulerGamma*x + pi**2*x**2/12 - x**3*zeta(3)/3 + O(x**4)
We can numerically evaluate the ``loggamma`` function
to arbitrary precision on the whole complex plane:
>>> from sympy import I
>>> loggamma(5).evalf(30)
3.17805383034794561964694160130
>>> loggamma(I).evalf(20)
-0.65092319930185633889 - 1.8724366472624298171*I
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Gamma_function
.. [2] http://dlmf.nist.gov/5
.. [3] http://mathworld.wolfram.com/LogGammaFunction.html
.. [4] http://functions.wolfram.com/GammaBetaErf/LogGamma/
"""
@classmethod
def eval(cls, z):
if z.is_integer:
if z.is_nonpositive:
return S.Infinity
elif z.is_positive:
return log(gamma(z))
elif z.is_rational:
p, q = z.as_numer_denom()
# Half-integral values:
if p.is_positive and q == 2:
return log(sqrt(S.Pi) * 2**(1 - p) * gamma(p) / gamma((p + 1)*S.Half))
if z is S.Infinity:
return S.Infinity
elif abs(z) is S.Infinity:
return S.ComplexInfinity
if z is S.NaN:
return S.NaN
def _eval_expand_func(self, **hints):
from sympy.concrete.summations import Sum
z = self.args[0]
if z.is_Rational:
p, q = z.as_numer_denom()
# General rational arguments (u + p/q)
# Split z as n + p/q with p < q
n = p // q
p = p - n*q
if p.is_positive and q.is_positive and p < q:
k = Dummy("k")
if n.is_positive:
return loggamma(p / q) - n*log(q) + Sum(log((k - 1)*q + p), (k, 1, n))
elif n.is_negative:
return loggamma(p / q) - n*log(q) + S.Pi*S.ImaginaryUnit*n - Sum(log(k*q - p), (k, 1, -n))
elif n.is_zero:
return loggamma(p / q)
return self
def _eval_nseries(self, x, n, logx=None, cdir=0):
x0 = self.args[0].limit(x, 0)
if x0.is_zero:
f = self._eval_rewrite_as_intractable(*self.args)
return f._eval_nseries(x, n, logx)
return super()._eval_nseries(x, n, logx)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
if args0[0] != oo:
return super()._eval_aseries(n, args0, x, logx)
z = self.args[0]
r = log(z)*(z - S.Half) - z + log(2*pi)/2
l = [bernoulli(2*k) / (2*k*(2*k - 1)*z**(2*k - 1)) for k in range(1, n)]
o = None
if n == 0:
o = Order(1, x)
else:
o = Order(1/z**n, x)
# It is very inefficient to first add the order and then do the nseries
return (r + Add(*l))._eval_nseries(x, n, logx) + o
def _eval_rewrite_as_intractable(self, z, **kwargs):
return log(gamma(z))
def _eval_is_real(self):
z = self.args[0]
if z.is_positive:
return True
elif z.is_nonpositive:
return False
def _eval_conjugate(self):
z = self.args[0]
if z not in (S.Zero, S.NegativeInfinity):
return self.func(z.conjugate())
def fdiff(self, argindex=1):
if argindex == 1:
return polygamma(0, self.args[0])
else:
raise ArgumentIndexError(self, argindex)
class digamma(Function):
r"""
The ``digamma`` function is the first derivative of the ``loggamma``
function
.. math::
\psi(x) := \frac{\mathrm{d}}{\mathrm{d} z} \log\Gamma(z)
= \frac{\Gamma'(z)}{\Gamma(z) }.
In this case, ``digamma(z) = polygamma(0, z)``.
Examples
========
>>> from sympy import digamma
>>> digamma(0)
zoo
>>> from sympy import Symbol
>>> z = Symbol('z')
>>> digamma(z)
polygamma(0, z)
To retain ``digamma`` as it is:
>>> digamma(0, evaluate=False)
digamma(0)
>>> digamma(z, evaluate=False)
digamma(z)
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Digamma_function
.. [2] http://mathworld.wolfram.com/DigammaFunction.html
.. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/
"""
def _eval_evalf(self, prec):
z = self.args[0]
nprec = prec_to_dps(prec)
return polygamma(0, z).evalf(n=nprec)
def fdiff(self, argindex=1):
z = self.args[0]
return polygamma(0, z).fdiff()
def _eval_is_real(self):
z = self.args[0]
return polygamma(0, z).is_real
def _eval_is_positive(self):
z = self.args[0]
return polygamma(0, z).is_positive
def _eval_is_negative(self):
z = self.args[0]
return polygamma(0, z).is_negative
def _eval_aseries(self, n, args0, x, logx):
as_polygamma = self.rewrite(polygamma)
args0 = [S.Zero,] + args0
return as_polygamma._eval_aseries(n, args0, x, logx)
@classmethod
def eval(cls, z):
return polygamma(0, z)
def _eval_expand_func(self, **hints):
z = self.args[0]
return polygamma(0, z).expand(func=True)
def _eval_rewrite_as_harmonic(self, z, **kwargs):
return harmonic(z - 1) - S.EulerGamma
def _eval_rewrite_as_polygamma(self, z, **kwargs):
return polygamma(0, z)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
z = self.args[0]
return polygamma(0, z).as_leading_term(x)
class trigamma(Function):
r"""
The ``trigamma`` function is the second derivative of the ``loggamma``
function
.. math::
\psi^{(1)}(z) := \frac{\mathrm{d}^{2}}{\mathrm{d} z^{2}} \log\Gamma(z).
In this case, ``trigamma(z) = polygamma(1, z)``.
Examples
========
>>> from sympy import trigamma
>>> trigamma(0)
zoo
>>> from sympy import Symbol
>>> z = Symbol('z')
>>> trigamma(z)
polygamma(1, z)
To retain ``trigamma`` as it is:
>>> trigamma(0, evaluate=False)
trigamma(0)
>>> trigamma(z, evaluate=False)
trigamma(z)
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigamma_function
.. [2] http://mathworld.wolfram.com/TrigammaFunction.html
.. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/
"""
def _eval_evalf(self, prec):
z = self.args[0]
nprec = prec_to_dps(prec)
return polygamma(1, z).evalf(n=nprec)
def fdiff(self, argindex=1):
z = self.args[0]
return polygamma(1, z).fdiff()
def _eval_is_real(self):
z = self.args[0]
return polygamma(1, z).is_real
def _eval_is_positive(self):
z = self.args[0]
return polygamma(1, z).is_positive
def _eval_is_negative(self):
z = self.args[0]
return polygamma(1, z).is_negative
def _eval_aseries(self, n, args0, x, logx):
as_polygamma = self.rewrite(polygamma)
args0 = [S.One,] + args0
return as_polygamma._eval_aseries(n, args0, x, logx)
@classmethod
def eval(cls, z):
return polygamma(1, z)
def _eval_expand_func(self, **hints):
z = self.args[0]
return polygamma(1, z).expand(func=True)
def _eval_rewrite_as_zeta(self, z, **kwargs):
return zeta(2, z)
def _eval_rewrite_as_polygamma(self, z, **kwargs):
return polygamma(1, z)
def _eval_rewrite_as_harmonic(self, z, **kwargs):
return -harmonic(z - 1, 2) + S.Pi**2 / 6
def _eval_as_leading_term(self, x, logx=None, cdir=0):
z = self.args[0]
return polygamma(1, z).as_leading_term(x)
###############################################################################
##################### COMPLETE MULTIVARIATE GAMMA FUNCTION ####################
###############################################################################
class multigamma(Function):
r"""
The multivariate gamma function is a generalization of the gamma function
.. math::
\Gamma_p(z) = \pi^{p(p-1)/4}\prod_{k=1}^p \Gamma[z + (1 - k)/2].
In a special case, ``multigamma(x, 1) = gamma(x)``.
Examples
========
>>> from sympy import S, multigamma
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> p = Symbol('p', positive=True, integer=True)
>>> multigamma(x, p)
pi**(p*(p - 1)/4)*Product(gamma(-_k/2 + x + 1/2), (_k, 1, p))
Several special values are known:
>>> multigamma(1, 1)
1
>>> multigamma(4, 1)
6
>>> multigamma(S(3)/2, 1)
sqrt(pi)/2
Writing ``multigamma`` in terms of the ``gamma`` function:
>>> multigamma(x, 1)
gamma(x)
>>> multigamma(x, 2)
sqrt(pi)*gamma(x)*gamma(x - 1/2)
>>> multigamma(x, 3)
pi**(3/2)*gamma(x)*gamma(x - 1)*gamma(x - 1/2)
Parameters
==========
p : order or dimension of the multivariate gamma function
See Also
========
gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma,
beta
References
==========
.. [1] https://en.wikipedia.org/wiki/Multivariate_gamma_function
"""
unbranched = True
def fdiff(self, argindex=2):
from sympy.concrete.summations import Sum
if argindex == 2:
x, p = self.args
k = Dummy("k")
return self.func(x, p)*Sum(polygamma(0, x + (1 - k)/2), (k, 1, p))
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, x, p):
from sympy.concrete.products import Product
if p.is_positive is False or p.is_integer is False:
raise ValueError('Order parameter p must be positive integer.')
k = Dummy("k")
return (pi**(p*(p - 1)/4)*Product(gamma(x + (1 - k)/2),
(k, 1, p))).doit()
def _eval_conjugate(self):
x, p = self.args
return self.func(x.conjugate(), p)
def _eval_is_real(self):
x, p = self.args
y = 2*x
if y.is_integer and (y <= (p - 1)) is True:
return False
if intlike(y) and (y <= (p - 1)):
return False
if y > (p - 1) or y.is_noninteger:
return True
|
a644f1f1348f714035c0ed7e4125c4ec1994ac629139bd3889fcba72232ae401 | """ Riemann zeta and related function. """
from sympy.core.add import Add
from sympy.core import Function, S, sympify, pi, I
from sympy.core.function import ArgumentIndexError, expand_mul
from sympy.core.relational import Eq
from sympy.core.symbol import Dummy
from sympy.functions.combinatorial.numbers import bernoulli, factorial, genocchi, harmonic
from sympy.functions.elementary.complexes import re, unpolarify, Abs, polar_lift
from sympy.functions.elementary.exponential import log, exp_polar, exp
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.polys.polytools import Poly
###############################################################################
###################### LERCH TRANSCENDENT #####################################
###############################################################################
class lerchphi(Function):
r"""
Lerch transcendent (Lerch phi function).
Explanation
===========
For $\operatorname{Re}(a) > 0$, $|z| < 1$ and $s \in \mathbb{C}$, the
Lerch transcendent is defined as
.. math :: \Phi(z, s, a) = \sum_{n=0}^\infty \frac{z^n}{(n + a)^s},
where the standard branch of the argument is used for $n + a$,
and by analytic continuation for other values of the parameters.
A commonly used related function is the Lerch zeta function, defined by
.. math:: L(q, s, a) = \Phi(e^{2\pi i q}, s, a).
**Analytic Continuation and Branching Behavior**
It can be shown that
.. math:: \Phi(z, s, a) = z\Phi(z, s, a+1) + a^{-s}.
This provides the analytic continuation to $\operatorname{Re}(a) \le 0$.
Assume now $\operatorname{Re}(a) > 0$. The integral representation
.. math:: \Phi_0(z, s, a) = \int_0^\infty \frac{t^{s-1} e^{-at}}{1 - ze^{-t}}
\frac{\mathrm{d}t}{\Gamma(s)}
provides an analytic continuation to $\mathbb{C} - [1, \infty)$.
Finally, for $x \in (1, \infty)$ we find
.. math:: \lim_{\epsilon \to 0^+} \Phi_0(x + i\epsilon, s, a)
-\lim_{\epsilon \to 0^+} \Phi_0(x - i\epsilon, s, a)
= \frac{2\pi i \log^{s-1}{x}}{x^a \Gamma(s)},
using the standard branch for both $\log{x}$ and
$\log{\log{x}}$ (a branch of $\log{\log{x}}$ is needed to
evaluate $\log{x}^{s-1}$).
This concludes the analytic continuation. The Lerch transcendent is thus
branched at $z \in \{0, 1, \infty\}$ and
$a \in \mathbb{Z}_{\le 0}$. For fixed $z, a$ outside these
branch points, it is an entire function of $s$.
Examples
========
The Lerch transcendent is a fairly general function, for this reason it does
not automatically evaluate to simpler functions. Use ``expand_func()`` to
achieve this.
If $z=1$, the Lerch transcendent reduces to the Hurwitz zeta function:
>>> from sympy import lerchphi, expand_func
>>> from sympy.abc import z, s, a
>>> expand_func(lerchphi(1, s, a))
zeta(s, a)
More generally, if $z$ is a root of unity, the Lerch transcendent
reduces to a sum of Hurwitz zeta functions:
>>> expand_func(lerchphi(-1, s, a))
zeta(s, a/2)/2**s - zeta(s, a/2 + 1/2)/2**s
If $a=1$, the Lerch transcendent reduces to the polylogarithm:
>>> expand_func(lerchphi(z, s, 1))
polylog(s, z)/z
More generally, if $a$ is rational, the Lerch transcendent reduces
to a sum of polylogarithms:
>>> from sympy import S
>>> expand_func(lerchphi(z, s, S(1)/2))
2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) -
polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z))
>>> expand_func(lerchphi(z, s, S(3)/2))
-2**s/z + 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) -
polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z))/z
The derivatives with respect to $z$ and $a$ can be computed in
closed form:
>>> lerchphi(z, s, a).diff(z)
(-a*lerchphi(z, s, a) + lerchphi(z, s - 1, a))/z
>>> lerchphi(z, s, a).diff(a)
-s*lerchphi(z, s + 1, a)
See Also
========
polylog, zeta
References
==========
.. [1] Bateman, H.; Erdelyi, A. (1953), Higher Transcendental Functions,
Vol. I, New York: McGraw-Hill. Section 1.11.
.. [2] http://dlmf.nist.gov/25.14
.. [3] https://en.wikipedia.org/wiki/Lerch_transcendent
"""
def _eval_expand_func(self, **hints):
z, s, a = self.args
if z == 1:
return zeta(s, a)
if s.is_Integer and s <= 0:
t = Dummy('t')
p = Poly((t + a)**(-s), t)
start = 1/(1 - t)
res = S.Zero
for c in reversed(p.all_coeffs()):
res += c*start
start = t*start.diff(t)
return res.subs(t, z)
if a.is_Rational:
# See section 18 of
# Kelly B. Roach. Hypergeometric Function Representations.
# In: Proceedings of the 1997 International Symposium on Symbolic and
# Algebraic Computation, pages 205-211, New York, 1997. ACM.
# TODO should something be polarified here?
add = S.Zero
mul = S.One
# First reduce a to the interaval (0, 1]
if a > 1:
n = floor(a)
if n == a:
n -= 1
a -= n
mul = z**(-n)
add = Add(*[-z**(k - n)/(a + k)**s for k in range(n)])
elif a <= 0:
n = floor(-a) + 1
a += n
mul = z**n
add = Add(*[z**(n - 1 - k)/(a - k - 1)**s for k in range(n)])
m, n = S([a.p, a.q])
zet = exp_polar(2*pi*I/n)
root = z**(1/n)
return add + mul*n**(s - 1)*Add(
*[polylog(s, zet**k*root)._eval_expand_func(**hints)
/ (unpolarify(zet)**k*root)**m for k in range(n)])
# TODO use minpoly instead of ad-hoc methods when issue 5888 is fixed
if isinstance(z, exp) and (z.args[0]/(pi*I)).is_Rational or z in [-1, I, -I]:
# TODO reference?
if z == -1:
p, q = S([1, 2])
elif z == I:
p, q = S([1, 4])
elif z == -I:
p, q = S([-1, 4])
else:
arg = z.args[0]/(2*pi*I)
p, q = S([arg.p, arg.q])
return Add(*[exp(2*pi*I*k*p/q)/q**s*zeta(s, (k + a)/q)
for k in range(q)])
return lerchphi(z, s, a)
def fdiff(self, argindex=1):
z, s, a = self.args
if argindex == 3:
return -s*lerchphi(z, s + 1, a)
elif argindex == 1:
return (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z
else:
raise ArgumentIndexError
def _eval_rewrite_helper(self, z, s, a, target):
res = self._eval_expand_func()
if res.has(target):
return res
else:
return self
def _eval_rewrite_as_zeta(self, z, s, a, **kwargs):
return self._eval_rewrite_helper(z, s, a, zeta)
def _eval_rewrite_as_polylog(self, z, s, a, **kwargs):
return self._eval_rewrite_helper(z, s, a, polylog)
###############################################################################
###################### POLYLOGARITHM ##########################################
###############################################################################
class polylog(Function):
r"""
Polylogarithm function.
Explanation
===========
For $|z| < 1$ and $s \in \mathbb{C}$, the polylogarithm is
defined by
.. math:: \operatorname{Li}_s(z) = \sum_{n=1}^\infty \frac{z^n}{n^s},
where the standard branch of the argument is used for $n$. It admits
an analytic continuation which is branched at $z=1$ (notably not on the
sheet of initial definition), $z=0$ and $z=\infty$.
The name polylogarithm comes from the fact that for $s=1$, the
polylogarithm is related to the ordinary logarithm (see examples), and that
.. math:: \operatorname{Li}_{s+1}(z) =
\int_0^z \frac{\operatorname{Li}_s(t)}{t} \mathrm{d}t.
The polylogarithm is a special case of the Lerch transcendent:
.. math:: \operatorname{Li}_{s}(z) = z \Phi(z, s, 1).
Examples
========
For $z \in \{0, 1, -1\}$, the polylogarithm is automatically expressed
using other functions:
>>> from sympy import polylog
>>> from sympy.abc import s
>>> polylog(s, 0)
0
>>> polylog(s, 1)
zeta(s)
>>> polylog(s, -1)
-dirichlet_eta(s)
If $s$ is a negative integer, $0$ or $1$, the polylogarithm can be
expressed using elementary functions. This can be done using
``expand_func()``:
>>> from sympy import expand_func
>>> from sympy.abc import z
>>> expand_func(polylog(1, z))
-log(1 - z)
>>> expand_func(polylog(0, z))
z/(1 - z)
The derivative with respect to $z$ can be computed in closed form:
>>> polylog(s, z).diff(z)
polylog(s - 1, z)/z
The polylogarithm can be expressed in terms of the lerch transcendent:
>>> from sympy import lerchphi
>>> polylog(s, z).rewrite(lerchphi)
z*lerchphi(z, s, 1)
See Also
========
zeta, lerchphi
"""
@classmethod
def eval(cls, s, z):
if z is S.One:
return zeta(s)
elif z is S.NegativeOne:
return -dirichlet_eta(s)
elif z is S.Zero:
return S.Zero
elif s == 2:
if z == S.Half:
return pi**2/12 - log(2)**2/2
elif z == 2:
return pi**2/4 - I*pi*log(2)
elif z == -(sqrt(5) - 1)/2:
return -pi**2/15 + log((sqrt(5)-1)/2)**2/2
elif z == -(sqrt(5) + 1)/2:
return -pi**2/10 - log((sqrt(5)+1)/2)**2
elif z == (3 - sqrt(5))/2:
return pi**2/15 - log((sqrt(5)-1)/2)**2
elif z == (sqrt(5) - 1)/2:
return pi**2/10 - log((sqrt(5)-1)/2)**2
if z.is_zero:
return S.Zero
# Make an effort to determine if z is 1 to avoid replacing into
# expression with singularity
zone = z.equals(S.One)
if zone:
return zeta(s)
elif zone is False:
# For s = 0 or -1 use explicit formulas to evaluate, but
# automatically expanding polylog(1, z) to -log(1-z) seems
# undesirable for summation methods based on hypergeometric
# functions
if s is S.Zero:
return z/(1 - z)
elif s is S.NegativeOne:
return z/(1 - z)**2
if s.is_zero:
return z/(1 - z)
# polylog is branched, but not over the unit disk
if z.has(exp_polar, polar_lift) and (zone or (Abs(z) <= S.One) == True):
return cls(s, unpolarify(z))
def fdiff(self, argindex=1):
s, z = self.args
if argindex == 2:
return polylog(s - 1, z)/z
raise ArgumentIndexError
def _eval_rewrite_as_lerchphi(self, s, z, **kwargs):
return z*lerchphi(z, s, 1)
def _eval_expand_func(self, **hints):
s, z = self.args
if s == 1:
return -log(1 - z)
if s.is_Integer and s <= 0:
u = Dummy('u')
start = u/(1 - u)
for _ in range(-s):
start = u*start.diff(u)
return expand_mul(start).subs(u, z)
return polylog(s, z)
def _eval_is_zero(self):
z = self.args[1]
if z.is_zero:
return True
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy.series.order import Order
nu, z = self.args
z0 = z.subs(x, 0)
if z0 is S.NaN:
z0 = z.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if z0.is_zero:
# In case of powers less than 1, number of terms need to be computed
# separately to avoid repeated callings of _eval_nseries with wrong n
try:
_, exp = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
if exp.is_positive:
newn = ceiling(n/exp)
o = Order(x**n, x)
r = z._eval_nseries(x, n, logx, cdir).removeO()
if r is S.Zero:
return o
term = r
s = [term]
for k in range(2, newn):
term *= r
s.append(term/k**nu)
return Add(*s) + o
return super(polylog, self)._eval_nseries(x, n, logx, cdir)
###############################################################################
###################### HURWITZ GENERALIZED ZETA FUNCTION ######################
###############################################################################
class zeta(Function):
r"""
Hurwitz zeta function (or Riemann zeta function).
Explanation
===========
For $\operatorname{Re}(a) > 0$ and $\operatorname{Re}(s) > 1$, this
function is defined as
.. math:: \zeta(s, a) = \sum_{n=0}^\infty \frac{1}{(n + a)^s},
where the standard choice of argument for $n + a$ is used. For fixed
$a$ not a nonpositive integer the Hurwitz zeta function admits a
meromorphic continuation to all of $\mathbb{C}$; it is an unbranched
function with a simple pole at $s = 1$.
The Hurwitz zeta function is a special case of the Lerch transcendent:
.. math:: \zeta(s, a) = \Phi(1, s, a).
This formula defines an analytic continuation for all possible values of
$s$ and $a$ (also $\operatorname{Re}(a) < 0$), see the documentation of
:class:`lerchphi` for a description of the branching behavior.
If no value is passed for $a$ a default value of $a = 1$ is assumed,
yielding the Riemann zeta function.
Examples
========
For $a = 1$ the Hurwitz zeta function reduces to the famous Riemann
zeta function:
.. math:: \zeta(s, 1) = \zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}.
>>> from sympy import zeta
>>> from sympy.abc import s
>>> zeta(s, 1)
zeta(s)
>>> zeta(s)
zeta(s)
The Riemann zeta function can also be expressed using the Dirichlet eta
function:
>>> from sympy import dirichlet_eta
>>> zeta(s).rewrite(dirichlet_eta)
dirichlet_eta(s)/(1 - 2**(1 - s))
The Riemann zeta function at nonnegative even and negative integer
values is related to the Bernoulli numbers and polynomials:
>>> zeta(2)
pi**2/6
>>> zeta(4)
pi**4/90
>>> zeta(0)
-1/2
>>> zeta(-1)
-1/12
>>> zeta(-4)
0
The specific formulae are:
.. math:: \zeta(2n) = -\frac{(2\pi i)^{2n} B_{2n}}{2(2n)!}
.. math:: \zeta(-n,a) = -\frac{B_{n+1}(a)}{n+1}
No closed-form expressions are known at positive odd integers, but
numerical evaluation is possible:
>>> zeta(3).n()
1.20205690315959
The derivative of $\zeta(s, a)$ with respect to $a$ can be computed:
>>> from sympy.abc import a
>>> zeta(s, a).diff(a)
-s*zeta(s + 1, a)
However the derivative with respect to $s$ has no useful closed form
expression:
>>> zeta(s, a).diff(s)
Derivative(zeta(s, a), s)
The Hurwitz zeta function can be expressed in terms of the Lerch
transcendent, :class:`~.lerchphi`:
>>> from sympy import lerchphi
>>> zeta(s, a).rewrite(lerchphi)
lerchphi(1, s, a)
See Also
========
dirichlet_eta, lerchphi, polylog
References
==========
.. [1] http://dlmf.nist.gov/25.11
.. [2] https://en.wikipedia.org/wiki/Hurwitz_zeta_function
"""
@classmethod
def eval(cls, s, a=None):
if a is S.One:
return cls(s)
elif s is S.NaN or a is S.NaN:
return S.NaN
elif s is S.One:
return S.ComplexInfinity
elif s is S.Infinity:
return S.One
elif a is S.Infinity:
return S.Zero
sint = s.is_Integer
if a is None:
a = S.One
if sint and s.is_nonpositive:
return bernoulli(1-s, a) / (s-1)
elif a is S.One:
if sint and s.is_even:
return -(2*pi*I)**s * bernoulli(s) / (2*factorial(s))
elif sint and a.is_Integer and a.is_positive:
return cls(s) - harmonic(a-1, s)
elif a.is_Integer and a.is_nonpositive and \
(s.is_integer is False or s.is_nonpositive is False):
return S.NaN
def _eval_rewrite_as_bernoulli(self, s, a=1, **kwargs):
if a == 1 and s.is_integer and s.is_nonnegative and s.is_even:
return -(2*pi*I)**s * bernoulli(s) / (2*factorial(s))
return bernoulli(1-s, a) / (s-1)
def _eval_rewrite_as_dirichlet_eta(self, s, a=1, **kwargs):
if a != 1:
return self
s = self.args[0]
return dirichlet_eta(s)/(1 - 2**(1 - s))
def _eval_rewrite_as_lerchphi(self, s, a=1, **kwargs):
return lerchphi(1, s, a)
def _eval_is_finite(self):
arg_is_one = (self.args[0] - 1).is_zero
if arg_is_one is not None:
return not arg_is_one
def _eval_expand_func(self, **hints):
s = self.args[0]
a = self.args[1] if len(self.args) > 1 else S.One
if a.is_integer:
if a.is_positive:
return zeta(s) - harmonic(a-1, s)
if a.is_nonpositive and (s.is_integer is False or
s.is_nonpositive is False):
return S.NaN
return self
def fdiff(self, argindex=1):
if len(self.args) == 2:
s, a = self.args
else:
s, a = self.args + (1,)
if argindex == 2:
return -s*zeta(s + 1, a)
else:
raise ArgumentIndexError
def _eval_as_leading_term(self, x, logx=None, cdir=0):
if len(self.args) == 2:
s, a = self.args
else:
s, a = self.args + (S.One,)
try:
c, e = a.leadterm(x)
except NotImplementedError:
return self
if e.is_negative and not s.is_positive:
raise NotImplementedError
return super(zeta, self)._eval_as_leading_term(x, logx, cdir)
class dirichlet_eta(Function):
r"""
Dirichlet eta function.
Explanation
===========
For $\operatorname{Re}(s) > 0$ and $0 < x \le 1$, this function is defined as
.. math:: \eta(s, a) = \sum_{n=0}^\infty \frac{(-1)^n}{(n+a)^s}.
It admits a unique analytic continuation to all of $\mathbb{C}$ for any
fixed $a$ not a nonpositive integer. It is an entire, unbranched function.
It can be expressed using the Hurwitz zeta function as
.. math:: \eta(s, a) = \zeta(s,a) - 2^{1-s} \zeta\left(s, \frac{a+1}{2}\right)
and using the generalized Genocchi function as
.. math:: \eta(s, a) = \frac{G(1-s, a)}{2(s-1)}.
In both cases the limiting value of $\log2 - \psi(a) + \psi\left(\frac{a+1}{2}\right)$
is used when $s = 1$.
Examples
========
>>> from sympy import dirichlet_eta, zeta
>>> from sympy.abc import s
>>> dirichlet_eta(s).rewrite(zeta)
Piecewise((log(2), Eq(s, 1)), ((1 - 2**(1 - s))*zeta(s), True))
See Also
========
zeta
References
==========
.. [1] https://en.wikipedia.org/wiki/Dirichlet_eta_function
.. [2] Peter Luschny, "An introduction to the Bernoulli function",
https://arxiv.org/abs/2009.06743
"""
@classmethod
def eval(cls, s, a=None):
if a is S.One:
return cls(s)
if a is None:
if s == 1:
return log(2)
z = zeta(s)
if not z.has(zeta):
return (1 - 2**(1-s)) * z
return
elif s == 1:
from sympy.functions.special.gamma_functions import digamma
return log(2) - digamma(a) + digamma((a+1)/2)
z1 = zeta(s, a)
z2 = zeta(s, (a+1)/2)
if not z1.has(zeta) and not z2.has(zeta):
return z1 - 2**(1-s) * z2
def _eval_rewrite_as_zeta(self, s, a=1, **kwargs):
from sympy.functions.special.gamma_functions import digamma
if a == 1:
return Piecewise((log(2), Eq(s, 1)), ((1 - 2**(1-s)) * zeta(s), True))
return Piecewise((log(2) - digamma(a) + digamma((a+1)/2), Eq(s, 1)),
(zeta(s, a) - 2**(1-s) * zeta(s, (a+1)/2), True))
def _eval_rewrite_as_genocchi(self, s, a=S.One, **kwargs):
from sympy.functions.special.gamma_functions import digamma
return Piecewise((log(2) - digamma(a) + digamma((a+1)/2), Eq(s, 1)),
(genocchi(1-s, a) / (2 * (s-1)), True))
def _eval_evalf(self, prec):
if all(i.is_number for i in self.args):
return self.rewrite(zeta)._eval_evalf(prec)
class riemann_xi(Function):
r"""
Riemann Xi function.
Examples
========
The Riemann Xi function is closely related to the Riemann zeta function.
The zeros of Riemann Xi function are precisely the non-trivial zeros
of the zeta function.
>>> from sympy import riemann_xi, zeta
>>> from sympy.abc import s
>>> riemann_xi(s).rewrite(zeta)
s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Riemann_Xi_function
"""
@classmethod
def eval(cls, s):
from sympy.functions.special.gamma_functions import gamma
z = zeta(s)
if s in (S.Zero, S.One):
return S.Half
if not isinstance(z, zeta):
return s*(s - 1)*gamma(s/2)*z/(2*pi**(s/2))
def _eval_rewrite_as_zeta(self, s, **kwargs):
from sympy.functions.special.gamma_functions import gamma
return s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2))
class stieltjes(Function):
r"""
Represents Stieltjes constants, $\gamma_{k}$ that occur in
Laurent Series expansion of the Riemann zeta function.
Examples
========
>>> from sympy import stieltjes
>>> from sympy.abc import n, m
>>> stieltjes(n)
stieltjes(n)
The zero'th stieltjes constant:
>>> stieltjes(0)
EulerGamma
>>> stieltjes(0, 1)
EulerGamma
For generalized stieltjes constants:
>>> stieltjes(n, m)
stieltjes(n, m)
Constants are only defined for integers >= 0:
>>> stieltjes(-1)
zoo
References
==========
.. [1] https://en.wikipedia.org/wiki/Stieltjes_constants
"""
@classmethod
def eval(cls, n, a=None):
if a is not None:
a = sympify(a)
if a is S.NaN:
return S.NaN
if a.is_Integer and a.is_nonpositive:
return S.ComplexInfinity
if n.is_Number:
if n is S.NaN:
return S.NaN
elif n < 0:
return S.ComplexInfinity
elif not n.is_Integer:
return S.ComplexInfinity
elif n is S.Zero and a in [None, 1]:
return S.EulerGamma
if n.is_extended_negative:
return S.ComplexInfinity
if n.is_zero and a in [None, 1]:
return S.EulerGamma
if n.is_integer == False:
return S.ComplexInfinity
|
8318c375c769df2199ac86dbf27035676d41e570190efa4c391ca6ab8e14d722 | from functools import wraps
from sympy.core import S
from sympy.core.add import Add
from sympy.core.cache import cacheit
from sympy.core.expr import Expr
from sympy.core.function import Function, ArgumentIndexError, _mexpand
from sympy.core.logic import fuzzy_or, fuzzy_not
from sympy.core.numbers import Rational, pi, I
from sympy.core.power import Pow
from sympy.core.symbol import Dummy, Wild
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.trigonometric import sin, cos, csc, cot
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.miscellaneous import cbrt, sqrt, root
from sympy.functions.elementary.complexes import (Abs, re, im, polar_lift, unpolarify)
from sympy.functions.special.gamma_functions import gamma, digamma, uppergamma
from sympy.functions.special.hyper import hyper
from sympy.polys.orthopolys import spherical_bessel_fn
from mpmath import mp, workprec
# TODO
# o Scorer functions G1 and G2
# o Asymptotic expansions
# These are possible, e.g. for fixed order, but since the bessel type
# functions are oscillatory they are not actually tractable at
# infinity, so this is not particularly useful right now.
# o Nicer series expansions.
# o More rewriting.
# o Add solvers to ode.py (or rather add solvers for the hypergeometric equation).
class BesselBase(Function):
"""
Abstract base class for Bessel-type functions.
This class is meant to reduce code duplication.
All Bessel-type functions can 1) be differentiated, with the derivatives
expressed in terms of similar functions, and 2) be rewritten in terms
of other Bessel-type functions.
Here, Bessel-type functions are assumed to have one complex parameter.
To use this base class, define class attributes ``_a`` and ``_b`` such that
``2*F_n' = -_a*F_{n+1} + b*F_{n-1}``.
"""
@property
def order(self):
""" The order of the Bessel-type function. """
return self.args[0]
@property
def argument(self):
""" The argument of the Bessel-type function. """
return self.args[1]
@classmethod
def eval(cls, nu, z):
return
def fdiff(self, argindex=2):
if argindex != 2:
raise ArgumentIndexError(self, argindex)
return (self._b/2 * self.__class__(self.order - 1, self.argument) -
self._a/2 * self.__class__(self.order + 1, self.argument))
def _eval_conjugate(self):
z = self.argument
if z.is_extended_negative is False:
return self.__class__(self.order.conjugate(), z.conjugate())
def _eval_is_meromorphic(self, x, a):
nu, z = self.order, self.argument
if nu.has(x):
return False
if not z._eval_is_meromorphic(x, a):
return None
z0 = z.subs(x, a)
if nu.is_integer:
if isinstance(self, (besselj, besseli, hn1, hn2, jn, yn)) or not nu.is_zero:
return fuzzy_not(z0.is_infinite)
return fuzzy_not(fuzzy_or([z0.is_zero, z0.is_infinite]))
def _eval_expand_func(self, **hints):
nu, z, f = self.order, self.argument, self.__class__
if nu.is_real:
if (nu - 1).is_positive:
return (-self._a*self._b*f(nu - 2, z)._eval_expand_func() +
2*self._a*(nu - 1)*f(nu - 1, z)._eval_expand_func()/z)
elif (nu + 1).is_negative:
return (2*self._b*(nu + 1)*f(nu + 1, z)._eval_expand_func()/z -
self._a*self._b*f(nu + 2, z)._eval_expand_func())
return self
def _eval_simplify(self, **kwargs):
from sympy.simplify.simplify import besselsimp
return besselsimp(self)
class besselj(BesselBase):
r"""
Bessel function of the first kind.
Explanation
===========
The Bessel $J$ function of order $\nu$ is defined to be the function
satisfying Bessel's differential equation
.. math ::
z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
+ z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu^2) w = 0,
with Laurent expansion
.. math ::
J_\nu(z) = z^\nu \left(\frac{1}{\Gamma(\nu + 1) 2^\nu} + O(z^2) \right),
if $\nu$ is not a negative integer. If $\nu=-n \in \mathbb{Z}_{<0}$
*is* a negative integer, then the definition is
.. math ::
J_{-n}(z) = (-1)^n J_n(z).
Examples
========
Create a Bessel function object:
>>> from sympy import besselj, jn
>>> from sympy.abc import z, n
>>> b = besselj(n, z)
Differentiate it:
>>> b.diff(z)
besselj(n - 1, z)/2 - besselj(n + 1, z)/2
Rewrite in terms of spherical Bessel functions:
>>> b.rewrite(jn)
sqrt(2)*sqrt(z)*jn(n - 1/2, z)/sqrt(pi)
Access the parameter and argument:
>>> b.order
n
>>> b.argument
z
See Also
========
bessely, besseli, besselk
References
==========
.. [1] Abramowitz, Milton; Stegun, Irene A., eds. (1965), "Chapter 9",
Handbook of Mathematical Functions with Formulas, Graphs, and
Mathematical Tables
.. [2] Luke, Y. L. (1969), The Special Functions and Their
Approximations, Volume 1
.. [3] https://en.wikipedia.org/wiki/Bessel_function
.. [4] http://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/
"""
_a = S.One
_b = S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.One
elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive:
return S.Zero
elif re(nu).is_negative and not (nu.is_integer is True):
return S.ComplexInfinity
elif nu.is_imaginary:
return S.NaN
if z in (S.Infinity, S.NegativeInfinity):
return S.Zero
if z.could_extract_minus_sign():
return (z)**nu*(-z)**(-nu)*besselj(nu, -z)
if nu.is_integer:
if nu.could_extract_minus_sign():
return S.NegativeOne**(-nu)*besselj(-nu, z)
newz = z.extract_multiplicatively(I)
if newz: # NOTE we don't want to change the function if z==0
return I**(nu)*besseli(nu, newz)
# branch handling:
if nu.is_integer:
newz = unpolarify(z)
if newz != z:
return besselj(nu, newz)
else:
newz, n = z.extract_branch_factor()
if n != 0:
return exp(2*n*pi*nu*I)*besselj(nu, newz)
nnu = unpolarify(nu)
if nu != nnu:
return besselj(nnu, z)
def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
return exp(I*pi*nu/2)*besseli(nu, polar_lift(-I)*z)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
if nu.is_integer is False:
return csc(pi*nu)*bessely(-nu, z) - cot(pi*nu)*bessely(nu, z)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
return sqrt(2*z/pi)*jn(nu - S.Half, self.argument)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
nu, z = self.args
try:
arg = z.as_leading_term(x)
except NotImplementedError:
return self
c, e = arg.as_coeff_exponent(x)
if e.is_positive:
return arg**nu/(2**nu*gamma(nu + 1))
elif e.is_negative:
cdir = 1 if cdir == 0 else cdir
sign = c*cdir**e
if not sign.is_negative:
# Refer Abramowitz and Stegun 1965, p. 364 for more information on
# asymptotic approximation of besselj function.
return sqrt(2)*cos(z - pi*(2*nu + 1)/4)/sqrt(pi*z)
return self
return super(besselj, self)._eval_as_leading_term(x, logx, cdir)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_extended_real:
return True
def _eval_nseries(self, x, n, logx, cdir=0):
# Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/06/01/04/01/01/0003/
# for more information on nseries expansion of besselj function.
from sympy.series.order import Order
nu, z = self.args
# In case of powers less than 1, number of terms need to be computed
# separately to avoid repeated callings of _eval_nseries with wrong n
try:
_, exp = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
if exp.is_positive:
newn = ceiling(n/exp)
o = Order(x**n, x)
r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
if r is S.Zero:
return o
t = (_mexpand(r**2) + o).removeO()
term = r**nu/gamma(nu + 1)
s = [term]
for k in range(1, (newn + 1)//2):
term *= -t/(k*(nu + k))
term = (_mexpand(term) + o).removeO()
s.append(term)
return Add(*s) + o
return super(besselj, self)._eval_nseries(x, n, logx, cdir)
class bessely(BesselBase):
r"""
Bessel function of the second kind.
Explanation
===========
The Bessel $Y$ function of order $\nu$ is defined as
.. math ::
Y_\nu(z) = \lim_{\mu \to \nu} \frac{J_\mu(z) \cos(\pi \mu)
- J_{-\mu}(z)}{\sin(\pi \mu)},
where $J_\mu(z)$ is the Bessel function of the first kind.
It is a solution to Bessel's equation, and linearly independent from
$J_\nu$.
Examples
========
>>> from sympy import bessely, yn
>>> from sympy.abc import z, n
>>> b = bessely(n, z)
>>> b.diff(z)
bessely(n - 1, z)/2 - bessely(n + 1, z)/2
>>> b.rewrite(yn)
sqrt(2)*sqrt(z)*yn(n - 1/2, z)/sqrt(pi)
See Also
========
besselj, besseli, besselk
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselY/
"""
_a = S.One
_b = S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.NegativeInfinity
elif re(nu).is_zero is False:
return S.ComplexInfinity
elif re(nu).is_zero:
return S.NaN
if z in (S.Infinity, S.NegativeInfinity):
return S.Zero
if z == S.ImaginaryUnit*S.Infinity:
return exp(I*pi*(nu + 1)/2) * S.Infinity
if z == S.ImaginaryUnit*S.NegativeInfinity:
return exp(-I*pi*(nu + 1)/2) * S.Infinity
if nu.is_integer:
if nu.could_extract_minus_sign():
return S.NegativeOne**(-nu)*bessely(-nu, z)
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
if nu.is_integer is False:
return csc(pi*nu)*(cos(pi*nu)*besselj(nu, z) - besselj(-nu, z))
def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
aj = self._eval_rewrite_as_besselj(*self.args)
if aj:
return aj.rewrite(besseli)
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
return sqrt(2*z/pi) * yn(nu - S.Half, self.argument)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
nu, z = self.args
try:
arg = z.as_leading_term(x)
except NotImplementedError:
return self
c, e = arg.as_coeff_exponent(x)
if e.is_positive:
term_one = ((2/pi)*log(z/2)*besselj(nu, z))
term_two = -(z/2)**(-nu)*factorial(nu - 1)/pi if (nu).is_positive else S.Zero
term_three = -(z/2)**nu/(pi*factorial(nu))*(digamma(nu + 1) - S.EulerGamma)
arg = Add(*[term_one, term_two, term_three]).as_leading_term(x, logx=logx)
return arg
elif e.is_negative:
cdir = 1 if cdir == 0 else cdir
sign = c*cdir**e
if not sign.is_negative:
# Refer Abramowitz and Stegun 1965, p. 364 for more information on
# asymptotic approximation of bessely function.
return sqrt(2)*(-sin(pi*nu/2 - z + pi/4) + 3*cos(pi*nu/2 - z + pi/4)/(8*z))*sqrt(1/z)/sqrt(pi)
return self
return super(bessely, self)._eval_as_leading_term(x, logx, cdir)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_positive:
return True
def _eval_nseries(self, x, n, logx, cdir=0):
# Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselY/06/01/04/01/02/0008/
# for more information on nseries expansion of bessely function.
from sympy.series.order import Order
nu, z = self.args
# In case of powers less than 1, number of terms need to be computed
# separately to avoid repeated callings of _eval_nseries with wrong n
try:
_, exp = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
if exp.is_positive and nu.is_integer:
newn = ceiling(n/exp)
bn = besselj(nu, z)
a = ((2/pi)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir)
b, c = [], []
o = Order(x**n, x)
r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
if r is S.Zero:
return o
t = (_mexpand(r**2) + o).removeO()
if nu > S.Zero:
term = r**(-nu)*factorial(nu - 1)/pi
b.append(term)
for k in range(1, nu):
denom = (nu - k)*k
if denom == S.Zero:
term *= t/k
else:
term *= t/denom
term = (_mexpand(term) + o).removeO()
b.append(term)
p = r**nu/(pi*factorial(nu))
term = p*(digamma(nu + 1) - S.EulerGamma)
c.append(term)
for k in range(1, (newn + 1)//2):
p *= -t/(k*(k + nu))
p = (_mexpand(p) + o).removeO()
term = p*(digamma(k + nu + 1) + digamma(k + 1))
c.append(term)
return a - Add(*b) - Add(*c) # Order term comes from a
return super(bessely, self)._eval_nseries(x, n, logx, cdir)
class besseli(BesselBase):
r"""
Modified Bessel function of the first kind.
Explanation
===========
The Bessel $I$ function is a solution to the modified Bessel equation
.. math ::
z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
+ z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 + \nu^2)^2 w = 0.
It can be defined as
.. math ::
I_\nu(z) = i^{-\nu} J_\nu(iz),
where $J_\nu(z)$ is the Bessel function of the first kind.
Examples
========
>>> from sympy import besseli
>>> from sympy.abc import z, n
>>> besseli(n, z).diff(z)
besseli(n - 1, z)/2 + besseli(n + 1, z)/2
See Also
========
besselj, bessely, besselk
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselI/
"""
_a = -S.One
_b = S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.One
elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive:
return S.Zero
elif re(nu).is_negative and not (nu.is_integer is True):
return S.ComplexInfinity
elif nu.is_imaginary:
return S.NaN
if im(z) in (S.Infinity, S.NegativeInfinity):
return S.Zero
if z is S.Infinity:
return S.Infinity
if z is S.NegativeInfinity:
return (-1)**nu*S.Infinity
if z.could_extract_minus_sign():
return (z)**nu*(-z)**(-nu)*besseli(nu, -z)
if nu.is_integer:
if nu.could_extract_minus_sign():
return besseli(-nu, z)
newz = z.extract_multiplicatively(I)
if newz: # NOTE we don't want to change the function if z==0
return I**(-nu)*besselj(nu, -newz)
# branch handling:
if nu.is_integer:
newz = unpolarify(z)
if newz != z:
return besseli(nu, newz)
else:
newz, n = z.extract_branch_factor()
if n != 0:
return exp(2*n*pi*nu*I)*besseli(nu, newz)
nnu = unpolarify(nu)
if nu != nnu:
return besseli(nnu, z)
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
return exp(-I*pi*nu/2)*besselj(nu, polar_lift(I)*z)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
aj = self._eval_rewrite_as_besselj(*self.args)
if aj:
return aj.rewrite(bessely)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
return self._eval_rewrite_as_besselj(*self.args).rewrite(jn)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_extended_real:
return True
def _eval_as_leading_term(self, x, logx=None, cdir=0):
nu, z = self.args
try:
arg = z.as_leading_term(x)
except NotImplementedError:
return self
c, e = arg.as_coeff_exponent(x)
if e.is_positive:
return arg**nu/(2**nu*gamma(nu + 1))
elif e.is_negative:
cdir = 1 if cdir == 0 else cdir
sign = c*cdir**e
if not sign.is_negative:
# Refer Abramowitz and Stegun 1965, p. 377 for more information on
# asymptotic approximation of besseli function.
return exp(z)/sqrt(2*pi*z)
return self
return super(besseli, self)._eval_as_leading_term(x, logx, cdir)
def _eval_nseries(self, x, n, logx, cdir=0):
# Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselI/06/01/04/01/01/0003/
# for more information on nseries expansion of besseli function.
from sympy.series.order import Order
nu, z = self.args
# In case of powers less than 1, number of terms need to be computed
# separately to avoid repeated callings of _eval_nseries with wrong n
try:
_, exp = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
if exp.is_positive:
newn = ceiling(n/exp)
o = Order(x**n, x)
r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
if r is S.Zero:
return o
t = (_mexpand(r**2) + o).removeO()
term = r**nu/gamma(nu + 1)
s = [term]
for k in range(1, (newn + 1)//2):
term *= t/(k*(nu + k))
term = (_mexpand(term) + o).removeO()
s.append(term)
return Add(*s) + o
return super(besseli, self)._eval_nseries(x, n, logx, cdir)
class besselk(BesselBase):
r"""
Modified Bessel function of the second kind.
Explanation
===========
The Bessel $K$ function of order $\nu$ is defined as
.. math ::
K_\nu(z) = \lim_{\mu \to \nu} \frac{\pi}{2}
\frac{I_{-\mu}(z) -I_\mu(z)}{\sin(\pi \mu)},
where $I_\mu(z)$ is the modified Bessel function of the first kind.
It is a solution of the modified Bessel equation, and linearly independent
from $Y_\nu$.
Examples
========
>>> from sympy import besselk
>>> from sympy.abc import z, n
>>> besselk(n, z).diff(z)
-besselk(n - 1, z)/2 - besselk(n + 1, z)/2
See Also
========
besselj, besseli, bessely
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselK/
"""
_a = S.One
_b = -S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.Infinity
elif re(nu).is_zero is False:
return S.ComplexInfinity
elif re(nu).is_zero:
return S.NaN
if z in (S.Infinity, I*S.Infinity, I*S.NegativeInfinity):
return S.Zero
if nu.is_integer:
if nu.could_extract_minus_sign():
return besselk(-nu, z)
def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
if nu.is_integer is False:
return pi*csc(pi*nu)*(besseli(-nu, z) - besseli(nu, z))/2
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
ai = self._eval_rewrite_as_besseli(*self.args)
if ai:
return ai.rewrite(besselj)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
aj = self._eval_rewrite_as_besselj(*self.args)
if aj:
return aj.rewrite(bessely)
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
ay = self._eval_rewrite_as_bessely(*self.args)
if ay:
return ay.rewrite(yn)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_positive:
return True
def _eval_as_leading_term(self, x, logx=None, cdir=0):
nu, z = self.args
try:
arg = z.as_leading_term(x)
except NotImplementedError:
return self
_, e = arg.as_coeff_exponent(x)
if e.is_positive:
term_one = ((-1)**(nu -1)*log(z/2)*besseli(nu, z))
term_two = (z/2)**(-nu)*factorial(nu - 1)/2 if (nu).is_positive else S.Zero
term_three = (-1)**nu*(z/2)**nu/(2*factorial(nu))*(digamma(nu + 1) - S.EulerGamma)
arg = Add(*[term_one, term_two, term_three]).as_leading_term(x, logx=logx)
return arg
elif e.is_negative:
# Refer Abramowitz and Stegun 1965, p. 378 for more information on
# asymptotic approximation of besselk function.
return sqrt(pi)*exp(-z)/sqrt(2*z)
return super(besselk, self)._eval_as_leading_term(x, logx, cdir)
def _eval_nseries(self, x, n, logx, cdir=0):
# Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselK/06/01/04/01/02/0008/
# for more information on nseries expansion of besselk function.
from sympy.series.order import Order
nu, z = self.args
# In case of powers less than 1, number of terms need to be computed
# separately to avoid repeated callings of _eval_nseries with wrong n
try:
_, exp = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
if exp.is_positive and nu.is_integer:
newn = ceiling(n/exp)
bn = besseli(nu, z)
a = ((-1)**(nu - 1)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir)
b, c = [], []
o = Order(x**n, x)
r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
if r is S.Zero:
return o
t = (_mexpand(r**2) + o).removeO()
if nu > S.Zero:
term = r**(-nu)*factorial(nu - 1)/2
b.append(term)
for k in range(1, nu):
denom = (k - nu)*k
if denom == S.Zero:
term *= t/k
else:
term *= t/denom
term = (_mexpand(term) + o).removeO()
b.append(term)
p = r**nu*(-1)**nu/(2*factorial(nu))
term = p*(digamma(nu + 1) - S.EulerGamma)
c.append(term)
for k in range(1, (newn + 1)//2):
p *= t/(k*(k + nu))
p = (_mexpand(p) + o).removeO()
term = p*(digamma(k + nu + 1) + digamma(k + 1))
c.append(term)
return a + Add(*b) + Add(*c) # Order term comes from a
return super(besselk, self)._eval_nseries(x, n, logx, cdir)
class hankel1(BesselBase):
r"""
Hankel function of the first kind.
Explanation
===========
This function is defined as
.. math ::
H_\nu^{(1)} = J_\nu(z) + iY_\nu(z),
where $J_\nu(z)$ is the Bessel function of the first kind, and
$Y_\nu(z)$ is the Bessel function of the second kind.
It is a solution to Bessel's equation.
Examples
========
>>> from sympy import hankel1
>>> from sympy.abc import z, n
>>> hankel1(n, z).diff(z)
hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2
See Also
========
hankel2, besselj, bessely
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH1/
"""
_a = S.One
_b = S.One
def _eval_conjugate(self):
z = self.argument
if z.is_extended_negative is False:
return hankel2(self.order.conjugate(), z.conjugate())
class hankel2(BesselBase):
r"""
Hankel function of the second kind.
Explanation
===========
This function is defined as
.. math ::
H_\nu^{(2)} = J_\nu(z) - iY_\nu(z),
where $J_\nu(z)$ is the Bessel function of the first kind, and
$Y_\nu(z)$ is the Bessel function of the second kind.
It is a solution to Bessel's equation, and linearly independent from
$H_\nu^{(1)}$.
Examples
========
>>> from sympy import hankel2
>>> from sympy.abc import z, n
>>> hankel2(n, z).diff(z)
hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2
See Also
========
hankel1, besselj, bessely
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH2/
"""
_a = S.One
_b = S.One
def _eval_conjugate(self):
z = self.argument
if z.is_extended_negative is False:
return hankel1(self.order.conjugate(), z.conjugate())
def assume_integer_order(fn):
@wraps(fn)
def g(self, nu, z):
if nu.is_integer:
return fn(self, nu, z)
return g
class SphericalBesselBase(BesselBase):
"""
Base class for spherical Bessel functions.
These are thin wrappers around ordinary Bessel functions,
since spherical Bessel functions differ from the ordinary
ones just by a slight change in order.
To use this class, define the ``_eval_evalf()`` and ``_expand()`` methods.
"""
def _expand(self, **hints):
""" Expand self into a polynomial. Nu is guaranteed to be Integer. """
raise NotImplementedError('expansion')
def _eval_expand_func(self, **hints):
if self.order.is_Integer:
return self._expand(**hints)
return self
def fdiff(self, argindex=2):
if argindex != 2:
raise ArgumentIndexError(self, argindex)
return self.__class__(self.order - 1, self.argument) - \
self * (self.order + 1)/self.argument
def _jn(n, z):
return (spherical_bessel_fn(n, z)*sin(z) +
S.NegativeOne**(n + 1)*spherical_bessel_fn(-n - 1, z)*cos(z))
def _yn(n, z):
# (-1)**(n + 1) * _jn(-n - 1, z)
return (S.NegativeOne**(n + 1) * spherical_bessel_fn(-n - 1, z)*sin(z) -
spherical_bessel_fn(n, z)*cos(z))
class jn(SphericalBesselBase):
r"""
Spherical Bessel function of the first kind.
Explanation
===========
This function is a solution to the spherical Bessel equation
.. math ::
z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
+ 2z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu(\nu + 1)) w = 0.
It can be defined as
.. math ::
j_\nu(z) = \sqrt{\frac{\pi}{2z}} J_{\nu + \frac{1}{2}}(z),
where $J_\nu(z)$ is the Bessel function of the first kind.
The spherical Bessel functions of integral order are
calculated using the formula:
.. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z},
where the coefficients $f_n(z)$ are available as
:func:`sympy.polys.orthopolys.spherical_bessel_fn`.
Examples
========
>>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(jn(0, z)))
sin(z)/z
>>> expand_func(jn(1, z)) == sin(z)/z**2 - cos(z)/z
True
>>> expand_func(jn(3, z))
(-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z)
>>> jn(nu, z).rewrite(besselj)
sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(nu + 1/2, z)/2
>>> jn(nu, z).rewrite(bessely)
(-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-nu - 1/2, z)/2
>>> jn(2, 5.2+0.3j).evalf(20)
0.099419756723640344491 - 0.054525080242173562897*I
See Also
========
besselj, bessely, besselk, yn
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.One
elif nu.is_integer:
if nu.is_positive:
return S.Zero
else:
return S.ComplexInfinity
if z in (S.NegativeInfinity, S.Infinity):
return S.Zero
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
return sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
return S.NegativeOne**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
return S.NegativeOne**(nu) * yn(-nu - 1, z)
def _expand(self, **hints):
return _jn(self.order, self.argument)
def _eval_evalf(self, prec):
if self.order.is_Integer:
return self.rewrite(besselj)._eval_evalf(prec)
class yn(SphericalBesselBase):
r"""
Spherical Bessel function of the second kind.
Explanation
===========
This function is another solution to the spherical Bessel equation, and
linearly independent from $j_n$. It can be defined as
.. math ::
y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z),
where $Y_\nu(z)$ is the Bessel function of the second kind.
For integral orders $n$, $y_n$ is calculated using the formula:
.. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z)
Examples
========
>>> from sympy import Symbol, yn, sin, cos, expand_func, besselj, bessely
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(yn(0, z)))
-cos(z)/z
>>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z
True
>>> yn(nu, z).rewrite(besselj)
(-1)**(nu + 1)*sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(-nu - 1/2, z)/2
>>> yn(nu, z).rewrite(bessely)
sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(nu + 1/2, z)/2
>>> yn(2, 5.2+0.3j).evalf(20)
0.18525034196069722536 + 0.014895573969924817587*I
See Also
========
besselj, bessely, besselk, jn
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
@assume_integer_order
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
return S.NegativeOne**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
@assume_integer_order
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
return sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
return S.NegativeOne**(nu + 1) * jn(-nu - 1, z)
def _expand(self, **hints):
return _yn(self.order, self.argument)
def _eval_evalf(self, prec):
if self.order.is_Integer:
return self.rewrite(bessely)._eval_evalf(prec)
class SphericalHankelBase(SphericalBesselBase):
@assume_integer_order
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
# jn +- I*yn
# jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
# yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
hks = self._hankel_kind_sign
return sqrt(pi/(2*z))*(besselj(nu + S.Half, z) +
hks*I*S.NegativeOne**(nu+1)*besselj(-nu - S.Half, z))
@assume_integer_order
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
# jn +- I*yn
# jn as bessely: (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
# yn as bessely: sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
hks = self._hankel_kind_sign
return sqrt(pi/(2*z))*(S.NegativeOne**nu*bessely(-nu - S.Half, z) +
hks*I*bessely(nu + S.Half, z))
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
hks = self._hankel_kind_sign
return jn(nu, z).rewrite(yn) + hks*I*yn(nu, z)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
hks = self._hankel_kind_sign
return jn(nu, z) + hks*I*yn(nu, z).rewrite(jn)
def _eval_expand_func(self, **hints):
if self.order.is_Integer:
return self._expand(**hints)
else:
nu = self.order
z = self.argument
hks = self._hankel_kind_sign
return jn(nu, z) + hks*I*yn(nu, z)
def _expand(self, **hints):
n = self.order
z = self.argument
hks = self._hankel_kind_sign
# fully expanded version
# return ((fn(n, z) * sin(z) +
# (-1)**(n + 1) * fn(-n - 1, z) * cos(z)) + # jn
# (hks * I * (-1)**(n + 1) *
# (fn(-n - 1, z) * hk * I * sin(z) +
# (-1)**(-n) * fn(n, z) * I * cos(z))) # +-I*yn
# )
return (_jn(n, z) + hks*I*_yn(n, z)).expand()
def _eval_evalf(self, prec):
if self.order.is_Integer:
return self.rewrite(besselj)._eval_evalf(prec)
class hn1(SphericalHankelBase):
r"""
Spherical Hankel function of the first kind.
Explanation
===========
This function is defined as
.. math:: h_\nu^(1)(z) = j_\nu(z) + i y_\nu(z),
where $j_\nu(z)$ and $y_\nu(z)$ are the spherical
Bessel function of the first and second kinds.
For integral orders $n$, $h_n^(1)$ is calculated using the formula:
.. math:: h_n^(1)(z) = j_{n}(z) + i (-1)^{n+1} j_{-n-1}(z)
Examples
========
>>> from sympy import Symbol, hn1, hankel1, expand_func, yn, jn
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(hn1(nu, z)))
jn(nu, z) + I*yn(nu, z)
>>> print(expand_func(hn1(0, z)))
sin(z)/z - I*cos(z)/z
>>> print(expand_func(hn1(1, z)))
-I*sin(z)/z - cos(z)/z + sin(z)/z**2 - I*cos(z)/z**2
>>> hn1(nu, z).rewrite(jn)
(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
>>> hn1(nu, z).rewrite(yn)
(-1)**nu*yn(-nu - 1, z) + I*yn(nu, z)
>>> hn1(nu, z).rewrite(hankel1)
sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel1(nu, z)/2
See Also
========
hn2, jn, yn, hankel1, hankel2
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
_hankel_kind_sign = S.One
@assume_integer_order
def _eval_rewrite_as_hankel1(self, nu, z, **kwargs):
return sqrt(pi/(2*z))*hankel1(nu, z)
class hn2(SphericalHankelBase):
r"""
Spherical Hankel function of the second kind.
Explanation
===========
This function is defined as
.. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z),
where $j_\nu(z)$ and $y_\nu(z)$ are the spherical
Bessel function of the first and second kinds.
For integral orders $n$, $h_n^(2)$ is calculated using the formula:
.. math:: h_n^(2)(z) = j_{n} - i (-1)^{n+1} j_{-n-1}(z)
Examples
========
>>> from sympy import Symbol, hn2, hankel2, expand_func, jn, yn
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(hn2(nu, z)))
jn(nu, z) - I*yn(nu, z)
>>> print(expand_func(hn2(0, z)))
sin(z)/z + I*cos(z)/z
>>> print(expand_func(hn2(1, z)))
I*sin(z)/z - cos(z)/z + sin(z)/z**2 + I*cos(z)/z**2
>>> hn2(nu, z).rewrite(hankel2)
sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel2(nu, z)/2
>>> hn2(nu, z).rewrite(jn)
-(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
>>> hn2(nu, z).rewrite(yn)
(-1)**nu*yn(-nu - 1, z) - I*yn(nu, z)
See Also
========
hn1, jn, yn, hankel1, hankel2
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
_hankel_kind_sign = -S.One
@assume_integer_order
def _eval_rewrite_as_hankel2(self, nu, z, **kwargs):
return sqrt(pi/(2*z))*hankel2(nu, z)
def jn_zeros(n, k, method="sympy", dps=15):
"""
Zeros of the spherical Bessel function of the first kind.
Explanation
===========
This returns an array of zeros of $jn$ up to the $k$-th zero.
* method = "sympy": uses `mpmath.besseljzero
<http://mpmath.org/doc/current/functions/bessel.html#mpmath.besseljzero>`_
* method = "scipy": uses the
`SciPy's sph_jn <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_
and
`newton <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_
to find all
roots, which is faster than computing the zeros using a general
numerical solver, but it requires SciPy and only works with low
precision floating point numbers. (The function used with
method="sympy" is a recent addition to mpmath; before that a general
solver was used.)
Examples
========
>>> from sympy import jn_zeros
>>> jn_zeros(2, 4, dps=5)
[5.7635, 9.095, 12.323, 15.515]
See Also
========
jn, yn, besselj, besselk, bessely
Parameters
==========
n : integer
order of Bessel function
k : integer
number of zeros to return
"""
from math import pi as math_pi
if method == "sympy":
from mpmath import besseljzero
from mpmath.libmp.libmpf import dps_to_prec
prec = dps_to_prec(dps)
return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec),
int(l)), prec)
for l in range(1, k + 1)]
elif method == "scipy":
from scipy.optimize import newton
try:
from scipy.special import spherical_jn
f = lambda x: spherical_jn(n, x)
except ImportError:
from scipy.special import sph_jn
f = lambda x: sph_jn(n, x)[0][-1]
else:
raise NotImplementedError("Unknown method.")
def solver(f, x):
if method == "scipy":
root = newton(f, x)
else:
raise NotImplementedError("Unknown method.")
return root
# we need to approximate the position of the first root:
root = n + math_pi
# determine the first root exactly:
root = solver(f, root)
roots = [root]
for i in range(k - 1):
# estimate the position of the next root using the last root + pi:
root = solver(f, root + math_pi)
roots.append(root)
return roots
class AiryBase(Function):
"""
Abstract base class for Airy functions.
This class is meant to reduce code duplication.
"""
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_is_extended_real(self):
return self.args[0].is_extended_real
def as_real_imag(self, deep=True, **hints):
z = self.args[0]
zc = z.conjugate()
f = self.func
u = (f(z)+f(zc))/2
v = I*(f(zc)-f(z))/2
return u, v
def _eval_expand_complex(self, deep=True, **hints):
re_part, im_part = self.as_real_imag(deep=deep, **hints)
return re_part + im_part*S.ImaginaryUnit
class airyai(AiryBase):
r"""
The Airy function $\operatorname{Ai}$ of the first kind.
Explanation
===========
The Airy function $\operatorname{Ai}(z)$ is defined to be the function
satisfying Airy's differential equation
.. math::
\frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0.
Equivalently, for real $z$
.. math::
\operatorname{Ai}(z) := \frac{1}{\pi}
\int_0^\infty \cos\left(\frac{t^3}{3} + z t\right) \mathrm{d}t.
Examples
========
Create an Airy function object:
>>> from sympy import airyai
>>> from sympy.abc import z
>>> airyai(z)
airyai(z)
Several special values are known:
>>> airyai(0)
3**(1/3)/(3*gamma(2/3))
>>> from sympy import oo
>>> airyai(oo)
0
>>> airyai(-oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airyai(z))
airyai(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airyai(z), z)
airyaiprime(z)
>>> diff(airyai(z), z, 2)
z*airyai(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airyai(z), z, 0, 3)
3**(5/6)*gamma(1/3)/(6*pi) - 3**(1/6)*z*gamma(2/3)/(2*pi) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airyai(-2).evalf(50)
0.22740742820168557599192443603787379946077222541710
Rewrite $\operatorname{Ai}(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airyai(z).rewrite(hyper)
-3**(2/3)*z*hyper((), (4/3,), z**3/9)/(3*gamma(1/3)) + 3**(1/3)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3))
See Also
========
airybi: Airy function of the second kind.
airyaiprime: Derivative of the Airy function of the first kind.
airybiprime: Derivative of the Airy function of the second kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Zero
elif arg is S.NegativeInfinity:
return S.Zero
elif arg.is_zero:
return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3)))
if arg.is_zero:
return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3)))
def fdiff(self, argindex=1):
if argindex == 1:
return airyaiprime(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 1:
p = previous_terms[-1]
return ((cbrt(3)*x)**(-n)*(cbrt(3)*x)**(n + 1)*sin(pi*(n*Rational(2, 3) + Rational(4, 3)))*factorial(n) *
gamma(n/3 + Rational(2, 3))/(sin(pi*(n*Rational(2, 3) + Rational(2, 3)))*factorial(n + 1)*gamma(n/3 + Rational(1, 3))) * p)
else:
return (S.One/(3**Rational(2, 3)*pi) * gamma((n+S.One)/S(3)) * sin(Rational(2, 3)*pi*(n+S.One)) /
factorial(n) * (cbrt(3)*x)**n)
def _eval_rewrite_as_besselj(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(-z, Rational(3, 2))
if re(z).is_negative:
return ot*sqrt(-z) * (besselj(-ot, tt*a) + besselj(ot, tt*a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(z, Rational(3, 2))
if re(z).is_positive:
return ot*sqrt(z) * (besseli(-ot, tt*a) - besseli(ot, tt*a))
else:
return ot*(Pow(a, ot)*besseli(-ot, tt*a) - z*Pow(a, -ot)*besseli(ot, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = S.One / (3**Rational(2, 3)*gamma(Rational(2, 3)))
pf2 = z / (root(3, 3)*gamma(Rational(1, 3)))
return pf1 * hyper([], [Rational(2, 3)], z**3/9) - pf2 * hyper([], [Rational(4, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is given by 03.05.16.0001.01
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryAi/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d * z**n)**m / (d**m * z**(m*n))
newarg = c * d**m * z**(m*n)
return S.Half * ((pf + S.One)*airyai(newarg) - (pf - S.One)/sqrt(3)*airybi(newarg))
class airybi(AiryBase):
r"""
The Airy function $\operatorname{Bi}$ of the second kind.
Explanation
===========
The Airy function $\operatorname{Bi}(z)$ is defined to be the function
satisfying Airy's differential equation
.. math::
\frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0.
Equivalently, for real $z$
.. math::
\operatorname{Bi}(z) := \frac{1}{\pi}
\int_0^\infty
\exp\left(-\frac{t^3}{3} + z t\right)
+ \sin\left(\frac{t^3}{3} + z t\right) \mathrm{d}t.
Examples
========
Create an Airy function object:
>>> from sympy import airybi
>>> from sympy.abc import z
>>> airybi(z)
airybi(z)
Several special values are known:
>>> airybi(0)
3**(5/6)/(3*gamma(2/3))
>>> from sympy import oo
>>> airybi(oo)
oo
>>> airybi(-oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airybi(z))
airybi(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airybi(z), z)
airybiprime(z)
>>> diff(airybi(z), z, 2)
z*airybi(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airybi(z), z, 0, 3)
3**(1/3)*gamma(1/3)/(2*pi) + 3**(2/3)*z*gamma(2/3)/(2*pi) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airybi(-2).evalf(50)
-0.41230258795639848808323405461146104203453483447240
Rewrite $\operatorname{Bi}(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airybi(z).rewrite(hyper)
3**(1/6)*z*hyper((), (4/3,), z**3/9)/gamma(1/3) + 3**(5/6)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3))
See Also
========
airyai: Airy function of the first kind.
airyaiprime: Derivative of the Airy function of the first kind.
airybiprime: Derivative of the Airy function of the second kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@classmethod
def eval(cls, 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.Zero
elif arg.is_zero:
return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3)))
if arg.is_zero:
return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3)))
def fdiff(self, argindex=1):
if argindex == 1:
return airybiprime(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 1:
p = previous_terms[-1]
return (cbrt(3)*x * Abs(sin(Rational(2, 3)*pi*(n + S.One))) * factorial((n - S.One)/S(3)) /
((n + S.One) * Abs(cos(Rational(2, 3)*pi*(n + S.Half))) * factorial((n - 2)/S(3))) * p)
else:
return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(Rational(2, 3)*pi*(n + S.One))) /
factorial(n) * (cbrt(3)*x)**n)
def _eval_rewrite_as_besselj(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(-z, Rational(3, 2))
if re(z).is_negative:
return sqrt(-z/3) * (besselj(-ot, tt*a) - besselj(ot, tt*a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(z, Rational(3, 2))
if re(z).is_positive:
return sqrt(z)/sqrt(3) * (besseli(-ot, tt*a) + besseli(ot, tt*a))
else:
b = Pow(a, ot)
c = Pow(a, -ot)
return sqrt(ot)*(b*besseli(-ot, tt*a) + z*c*besseli(ot, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = S.One / (root(3, 6)*gamma(Rational(2, 3)))
pf2 = z*root(3, 6) / gamma(Rational(1, 3))
return pf1 * hyper([], [Rational(2, 3)], z**3/9) + pf2 * hyper([], [Rational(4, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is given by 03.06.16.0001.01
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryBi/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d * z**n)**m / (d**m * z**(m*n))
newarg = c * d**m * z**(m*n)
return S.Half * (sqrt(3)*(S.One - pf)*airyai(newarg) + (S.One + pf)*airybi(newarg))
class airyaiprime(AiryBase):
r"""
The derivative $\operatorname{Ai}^\prime$ of the Airy function of the first
kind.
Explanation
===========
The Airy function $\operatorname{Ai}^\prime(z)$ is defined to be the
function
.. math::
\operatorname{Ai}^\prime(z) := \frac{\mathrm{d} \operatorname{Ai}(z)}{\mathrm{d} z}.
Examples
========
Create an Airy function object:
>>> from sympy import airyaiprime
>>> from sympy.abc import z
>>> airyaiprime(z)
airyaiprime(z)
Several special values are known:
>>> airyaiprime(0)
-3**(2/3)/(3*gamma(1/3))
>>> from sympy import oo
>>> airyaiprime(oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airyaiprime(z))
airyaiprime(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airyaiprime(z), z)
z*airyai(z)
>>> diff(airyaiprime(z), z, 2)
z*airyaiprime(z) + airyai(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airyaiprime(z), z, 0, 3)
-3**(2/3)/(3*gamma(1/3)) + 3**(1/3)*z**2/(6*gamma(2/3)) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airyaiprime(-2).evalf(50)
0.61825902074169104140626429133247528291577794512415
Rewrite $\operatorname{Ai}^\prime(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airyaiprime(z).rewrite(hyper)
3**(1/3)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) - 3**(2/3)*hyper((), (1/3,), z**3/9)/(3*gamma(1/3))
See Also
========
airyai: Airy function of the first kind.
airybi: Airy function of the second kind.
airybiprime: Derivative of the Airy function of the second kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Zero
if arg.is_zero:
return S.NegativeOne / (3**Rational(1, 3) * gamma(Rational(1, 3)))
def fdiff(self, argindex=1):
if argindex == 1:
return self.args[0]*airyai(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
z = self.args[0]._to_mpmath(prec)
with workprec(prec):
res = mp.airyai(z, derivative=1)
return Expr._from_mpmath(res, prec)
def _eval_rewrite_as_besselj(self, z, **kwargs):
tt = Rational(2, 3)
a = Pow(-z, Rational(3, 2))
if re(z).is_negative:
return z/3 * (besselj(-tt, tt*a) - besselj(tt, tt*a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = tt * Pow(z, Rational(3, 2))
if re(z).is_positive:
return z/3 * (besseli(tt, a) - besseli(-tt, a))
else:
a = Pow(z, Rational(3, 2))
b = Pow(a, tt)
c = Pow(a, -tt)
return ot * (z**2*c*besseli(tt, tt*a) - b*besseli(-ot, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = z**2 / (2*3**Rational(2, 3)*gamma(Rational(2, 3)))
pf2 = 1 / (root(3, 3)*gamma(Rational(1, 3)))
return pf1 * hyper([], [Rational(5, 3)], z**3/9) - pf2 * hyper([], [Rational(1, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is in principle
# given by 03.07.16.0001.01 but note
# that there is an error in this formula.
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryAiPrime/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d**m * z**(n*m)) / (d * z**n)**m
newarg = c * d**m * z**(n*m)
return S.Half * ((pf + S.One)*airyaiprime(newarg) + (pf - S.One)/sqrt(3)*airybiprime(newarg))
class airybiprime(AiryBase):
r"""
The derivative $\operatorname{Bi}^\prime$ of the Airy function of the first
kind.
Explanation
===========
The Airy function $\operatorname{Bi}^\prime(z)$ is defined to be the
function
.. math::
\operatorname{Bi}^\prime(z) := \frac{\mathrm{d} \operatorname{Bi}(z)}{\mathrm{d} z}.
Examples
========
Create an Airy function object:
>>> from sympy import airybiprime
>>> from sympy.abc import z
>>> airybiprime(z)
airybiprime(z)
Several special values are known:
>>> airybiprime(0)
3**(1/6)/gamma(1/3)
>>> from sympy import oo
>>> airybiprime(oo)
oo
>>> airybiprime(-oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airybiprime(z))
airybiprime(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airybiprime(z), z)
z*airybi(z)
>>> diff(airybiprime(z), z, 2)
z*airybiprime(z) + airybi(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airybiprime(z), z, 0, 3)
3**(1/6)/gamma(1/3) + 3**(5/6)*z**2/(6*gamma(2/3)) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airybiprime(-2).evalf(50)
0.27879516692116952268509756941098324140300059345163
Rewrite $\operatorname{Bi}^\prime(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airybiprime(z).rewrite(hyper)
3**(5/6)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) + 3**(1/6)*hyper((), (1/3,), z**3/9)/gamma(1/3)
See Also
========
airyai: Airy function of the first kind.
airybi: Airy function of the second kind.
airyaiprime: Derivative of the Airy function of the first kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@classmethod
def eval(cls, 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.Zero
elif arg.is_zero:
return 3**Rational(1, 6) / gamma(Rational(1, 3))
if arg.is_zero:
return 3**Rational(1, 6) / gamma(Rational(1, 3))
def fdiff(self, argindex=1):
if argindex == 1:
return self.args[0]*airybi(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
z = self.args[0]._to_mpmath(prec)
with workprec(prec):
res = mp.airybi(z, derivative=1)
return Expr._from_mpmath(res, prec)
def _eval_rewrite_as_besselj(self, z, **kwargs):
tt = Rational(2, 3)
a = tt * Pow(-z, Rational(3, 2))
if re(z).is_negative:
return -z/sqrt(3) * (besselj(-tt, a) + besselj(tt, a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = tt * Pow(z, Rational(3, 2))
if re(z).is_positive:
return z/sqrt(3) * (besseli(-tt, a) + besseli(tt, a))
else:
a = Pow(z, Rational(3, 2))
b = Pow(a, tt)
c = Pow(a, -tt)
return sqrt(ot) * (b*besseli(-tt, tt*a) + z**2*c*besseli(tt, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = z**2 / (2*root(3, 6)*gamma(Rational(2, 3)))
pf2 = root(3, 6) / gamma(Rational(1, 3))
return pf1 * hyper([], [Rational(5, 3)], z**3/9) + pf2 * hyper([], [Rational(1, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is in principle
# given by 03.08.16.0001.01 but note
# that there is an error in this formula.
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryBiPrime/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d**m * z**(n*m)) / (d * z**n)**m
newarg = c * d**m * z**(n*m)
return S.Half * (sqrt(3)*(pf - S.One)*airyaiprime(newarg) + (pf + S.One)*airybiprime(newarg))
class marcumq(Function):
r"""
The Marcum Q-function.
Explanation
===========
The Marcum Q-function is defined by the meromorphic continuation of
.. math::
Q_m(a, b) = a^{- m + 1} \int_{b}^{\infty} x^{m} e^{- \frac{a^{2}}{2} - \frac{x^{2}}{2}} I_{m - 1}\left(a x\right)\, dx
Examples
========
>>> from sympy import marcumq
>>> from sympy.abc import m, a, b
>>> marcumq(m, a, b)
marcumq(m, a, b)
Special values:
>>> marcumq(m, 0, b)
uppergamma(m, b**2/2)/gamma(m)
>>> marcumq(0, 0, 0)
0
>>> marcumq(0, a, 0)
1 - exp(-a**2/2)
>>> marcumq(1, a, a)
1/2 + exp(-a**2)*besseli(0, a**2)/2
>>> marcumq(2, a, a)
1/2 + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2)
Differentiation with respect to $a$ and $b$ is supported:
>>> from sympy import diff
>>> diff(marcumq(m, a, b), a)
a*(-marcumq(m, a, b) + marcumq(m + 1, a, b))
>>> diff(marcumq(m, a, b), b)
-a**(1 - m)*b**m*exp(-a**2/2 - b**2/2)*besseli(m - 1, a*b)
References
==========
.. [1] https://en.wikipedia.org/wiki/Marcum_Q-function
.. [2] http://mathworld.wolfram.com/MarcumQ-Function.html
"""
@classmethod
def eval(cls, m, a, b):
if a is S.Zero:
if m is S.Zero and b is S.Zero:
return S.Zero
return uppergamma(m, b**2 * S.Half) / gamma(m)
if m is S.Zero and b is S.Zero:
return 1 - 1 / exp(a**2 * S.Half)
if a == b:
if m is S.One:
return (1 + exp(-a**2) * besseli(0, a**2))*S.Half
if m == 2:
return S.Half + S.Half * exp(-a**2) * besseli(0, a**2) + exp(-a**2) * besseli(1, a**2)
if a.is_zero:
if m.is_zero and b.is_zero:
return S.Zero
return uppergamma(m, b**2*S.Half) / gamma(m)
if m.is_zero and b.is_zero:
return 1 - 1 / exp(a**2*S.Half)
def fdiff(self, argindex=2):
m, a, b = self.args
if argindex == 2:
return a * (-marcumq(m, a, b) + marcumq(1+m, a, b))
elif argindex == 3:
return (-b**m / a**(m-1)) * exp(-(a**2 + b**2)/2) * besseli(m-1, a*b)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Integral(self, m, a, b, **kwargs):
from sympy.integrals.integrals import Integral
x = kwargs.get('x', Dummy('x'))
return a ** (1 - m) * \
Integral(x**m * exp(-(x**2 + a**2)/2) * besseli(m-1, a*x), [x, b, S.Infinity])
def _eval_rewrite_as_Sum(self, m, a, b, **kwargs):
from sympy.concrete.summations import Sum
k = kwargs.get('k', Dummy('k'))
return exp(-(a**2 + b**2) / 2) * Sum((a/b)**k * besseli(k, a*b), [k, 1-m, S.Infinity])
def _eval_rewrite_as_besseli(self, m, a, b, **kwargs):
if a == b:
if m == 1:
return (1 + exp(-a**2) * besseli(0, a**2)) / 2
if m.is_Integer and m >= 2:
s = sum([besseli(i, a**2) for i in range(1, m)])
return S.Half + exp(-a**2) * besseli(0, a**2) / 2 + exp(-a**2) * s
def _eval_is_zero(self):
if all(arg.is_zero for arg in self.args):
return True
|
3a5dd5c1c1a07ca2f51603520dc5aba1a795e07b7910fa37b1dced7b9b32e8c6 | """ This module contains various functions that are special cases
of incomplete gamma functions. It should probably be renamed. """
from sympy.core import Add, S, sympify, cacheit, pi, I, Rational, EulerGamma
from sympy.core.function import Function, ArgumentIndexError, expand_mul
from sympy.core.relational import is_eq
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import factorial, factorial2, RisingFactorial
from sympy.functions.elementary.complexes import polar_lift, re, unpolarify
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.miscellaneous import sqrt, root
from sympy.functions.elementary.exponential import exp, log, exp_polar
from sympy.functions.elementary.hyperbolic import cosh, sinh
from sympy.functions.elementary.trigonometric import cos, sin, sinc
from sympy.functions.special.hyper import hyper, meijerg
# TODO series expansions
# TODO see the "Note:" in Ei
# Helper function
def real_to_real_as_real_imag(self, deep=True, **hints):
if self.args[0].is_extended_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
x, y = self.args[0].expand(deep, **hints).as_real_imag()
else:
x, y = self.args[0].as_real_imag()
re = (self.func(x + I*y) + self.func(x - I*y))/2
im = (self.func(x + I*y) - self.func(x - I*y))/(2*I)
return (re, im)
###############################################################################
################################ ERROR FUNCTION ###############################
###############################################################################
class erf(Function):
r"""
The Gauss error function.
Explanation
===========
This function is defined as:
.. math ::
\mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} \mathrm{d}t.
Examples
========
>>> from sympy import I, oo, erf
>>> from sympy.abc import z
Several special values are known:
>>> erf(0)
0
>>> erf(oo)
1
>>> erf(-oo)
-1
>>> erf(I*oo)
oo*I
>>> erf(-I*oo)
-oo*I
In general one can pull out factors of -1 and $I$ from the argument:
>>> erf(-z)
-erf(z)
The error function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(erf(z))
erf(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(erf(z), z)
2*exp(-z**2)/sqrt(pi)
We can numerically evaluate the error function to arbitrary precision
on the whole complex plane:
>>> erf(4).evalf(30)
0.999999984582742099719981147840
>>> erf(-4*I).evalf(30)
-1296959.73071763923152794095062*I
See Also
========
erfc: Complementary error function.
erfi: Imaginary error function.
erf2: Two-argument error function.
erfinv: Inverse error function.
erfcinv: Inverse Complementary error function.
erf2inv: Inverse two-argument error function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Error_function
.. [2] http://dlmf.nist.gov/7
.. [3] http://mathworld.wolfram.com/Erf.html
.. [4] http://functions.wolfram.com/GammaBetaErf/Erf
"""
unbranched = True
def fdiff(self, argindex=1):
if argindex == 1:
return 2*exp(-self.args[0]**2)/sqrt(S.Pi)
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return erfinv
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.One
elif arg is S.NegativeInfinity:
return S.NegativeOne
elif arg.is_zero:
return S.Zero
if isinstance(arg, erfinv):
return arg.args[0]
if isinstance(arg, erfcinv):
return S.One - arg.args[0]
if arg.is_zero:
return S.Zero
# Only happens with unevaluated erf2inv
if isinstance(arg, erf2inv) and arg.args[0].is_zero:
return arg.args[1]
# Try to pull out factors of I
t = arg.extract_multiplicatively(S.ImaginaryUnit)
if t in (S.Infinity, S.NegativeInfinity):
return arg
# Try to pull out factors of -1
if arg.could_extract_minus_sign():
return -cls(-arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
k = floor((n - 1)/S(2))
if len(previous_terms) > 2:
return -previous_terms[-2] * x**2 * (n - 2)/(n*k)
else:
return 2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(S.Pi))
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_is_real(self):
return self.args[0].is_extended_real
def _eval_is_finite(self):
if self.args[0].is_finite:
return True
else:
return self.args[0].is_extended_real
def _eval_is_zero(self):
return self.args[0].is_zero
def _eval_rewrite_as_uppergamma(self, z, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
return sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(S.Pi))
def _eval_rewrite_as_fresnels(self, z, **kwargs):
arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi)
return (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg))
def _eval_rewrite_as_fresnelc(self, z, **kwargs):
arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi)
return (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg))
def _eval_rewrite_as_meijerg(self, z, **kwargs):
return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)
def _eval_rewrite_as_hyper(self, z, **kwargs):
return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2)
def _eval_rewrite_as_expint(self, z, **kwargs):
return sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi)
def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
from sympy.series.limits import limit
if limitvar:
lim = limit(z, limitvar, S.Infinity)
if lim is S.NegativeInfinity:
return S.NegativeOne + _erfs(-z)*exp(-z**2)
return S.One - _erfs(z)*exp(-z**2)
def _eval_rewrite_as_erfc(self, z, **kwargs):
return S.One - erfc(z)
def _eval_rewrite_as_erfi(self, z, **kwargs):
return -I*erfi(I*z)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
arg0 = arg.subs(x, 0)
if arg0 is S.ComplexInfinity:
arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+')
if x in arg.free_symbols and arg0.is_zero:
return 2*arg/sqrt(pi)
else:
return self.func(arg0)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
if point in [S.Infinity, S.NegativeInfinity]:
z = self.args[0]
try:
_, ex = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
ex = -ex # as x->1/x for aseries
if ex.is_positive:
newn = ceiling(n/ex)
s = [S.NegativeOne**k * factorial2(2*k - 1) / (z**(2*k + 1) * 2**k)
for k in range(newn)] + [Order(1/z**newn, x)]
return S.One - (exp(-z**2)/sqrt(pi)) * Add(*s)
return super(erf, self)._eval_aseries(n, args0, x, logx)
as_real_imag = real_to_real_as_real_imag
class erfc(Function):
r"""
Complementary Error Function.
Explanation
===========
The function is defined as:
.. math ::
\mathrm{erfc}(x) = \frac{2}{\sqrt{\pi}} \int_x^\infty e^{-t^2} \mathrm{d}t
Examples
========
>>> from sympy import I, oo, erfc
>>> from sympy.abc import z
Several special values are known:
>>> erfc(0)
1
>>> erfc(oo)
0
>>> erfc(-oo)
2
>>> erfc(I*oo)
-oo*I
>>> erfc(-I*oo)
oo*I
The error function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(erfc(z))
erfc(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(erfc(z), z)
-2*exp(-z**2)/sqrt(pi)
It also follows
>>> erfc(-z)
2 - erfc(z)
We can numerically evaluate the complementary error function to arbitrary
precision on the whole complex plane:
>>> erfc(4).evalf(30)
0.0000000154172579002800188521596734869
>>> erfc(4*I).evalf(30)
1.0 - 1296959.73071763923152794095062*I
See Also
========
erf: Gaussian error function.
erfi: Imaginary error function.
erf2: Two-argument error function.
erfinv: Inverse error function.
erfcinv: Inverse Complementary error function.
erf2inv: Inverse two-argument error function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Error_function
.. [2] http://dlmf.nist.gov/7
.. [3] http://mathworld.wolfram.com/Erfc.html
.. [4] http://functions.wolfram.com/GammaBetaErf/Erfc
"""
unbranched = True
def fdiff(self, argindex=1):
if argindex == 1:
return -2*exp(-self.args[0]**2)/sqrt(S.Pi)
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return erfcinv
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Zero
elif arg.is_zero:
return S.One
if isinstance(arg, erfinv):
return S.One - arg.args[0]
if isinstance(arg, erfcinv):
return arg.args[0]
if arg.is_zero:
return S.One
# Try to pull out factors of I
t = arg.extract_multiplicatively(S.ImaginaryUnit)
if t in (S.Infinity, S.NegativeInfinity):
return -arg
# Try to pull out factors of -1
if arg.could_extract_minus_sign():
return 2 - cls(-arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return S.One
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
k = floor((n - 1)/S(2))
if len(previous_terms) > 2:
return -previous_terms[-2] * x**2 * (n - 2)/(n*k)
else:
return -2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(S.Pi))
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_is_real(self):
return self.args[0].is_extended_real
def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar)
def _eval_rewrite_as_erf(self, z, **kwargs):
return S.One - erf(z)
def _eval_rewrite_as_erfi(self, z, **kwargs):
return S.One + I*erfi(I*z)
def _eval_rewrite_as_fresnels(self, z, **kwargs):
arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi)
return S.One - (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg))
def _eval_rewrite_as_fresnelc(self, z, **kwargs):
arg = (S.One-S.ImaginaryUnit)*z/sqrt(pi)
return S.One - (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg))
def _eval_rewrite_as_meijerg(self, z, **kwargs):
return S.One - z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)
def _eval_rewrite_as_hyper(self, z, **kwargs):
return S.One - 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2)
def _eval_rewrite_as_uppergamma(self, z, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
return S.One - sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(S.Pi))
def _eval_rewrite_as_expint(self, z, **kwargs):
return S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi)
def _eval_expand_func(self, **hints):
return self.rewrite(erf)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
arg0 = arg.subs(x, 0)
if arg0 is S.ComplexInfinity:
arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+')
if arg0.is_zero:
return S.One
else:
return self.func(arg0)
as_real_imag = real_to_real_as_real_imag
def _eval_aseries(self, n, args0, x, logx):
return S.One - erf(*self.args)._eval_aseries(n, args0, x, logx)
class erfi(Function):
r"""
Imaginary error function.
Explanation
===========
The function erfi is defined as:
.. math ::
\mathrm{erfi}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{t^2} \mathrm{d}t
Examples
========
>>> from sympy import I, oo, erfi
>>> from sympy.abc import z
Several special values are known:
>>> erfi(0)
0
>>> erfi(oo)
oo
>>> erfi(-oo)
-oo
>>> erfi(I*oo)
I
>>> erfi(-I*oo)
-I
In general one can pull out factors of -1 and $I$ from the argument:
>>> erfi(-z)
-erfi(z)
>>> from sympy import conjugate
>>> conjugate(erfi(z))
erfi(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(erfi(z), z)
2*exp(z**2)/sqrt(pi)
We can numerically evaluate the imaginary error function to arbitrary
precision on the whole complex plane:
>>> erfi(2).evalf(30)
18.5648024145755525987042919132
>>> erfi(-2*I).evalf(30)
-0.995322265018952734162069256367*I
See Also
========
erf: Gaussian error function.
erfc: Complementary error function.
erf2: Two-argument error function.
erfinv: Inverse error function.
erfcinv: Inverse Complementary error function.
erf2inv: Inverse two-argument error function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Error_function
.. [2] http://mathworld.wolfram.com/Erfi.html
.. [3] http://functions.wolfram.com/GammaBetaErf/Erfi
"""
unbranched = True
def fdiff(self, argindex=1):
if argindex == 1:
return 2*exp(self.args[0]**2)/sqrt(S.Pi)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, z):
if z.is_Number:
if z is S.NaN:
return S.NaN
elif z.is_zero:
return S.Zero
elif z is S.Infinity:
return S.Infinity
if z.is_zero:
return S.Zero
# Try to pull out factors of -1
if z.could_extract_minus_sign():
return -cls(-z)
# Try to pull out factors of I
nz = z.extract_multiplicatively(I)
if nz is not None:
if nz is S.Infinity:
return I
if isinstance(nz, erfinv):
return I*nz.args[0]
if isinstance(nz, erfcinv):
return I*(S.One - nz.args[0])
# Only happens with unevaluated erf2inv
if isinstance(nz, erf2inv) and nz.args[0].is_zero:
return I*nz.args[1]
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
k = floor((n - 1)/S(2))
if len(previous_terms) > 2:
return previous_terms[-2] * x**2 * (n - 2)/(n*k)
else:
return 2 * x**n/(n*factorial(k)*sqrt(S.Pi))
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_is_extended_real(self):
return self.args[0].is_extended_real
def _eval_is_zero(self):
return self.args[0].is_zero
def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar)
def _eval_rewrite_as_erf(self, z, **kwargs):
return -I*erf(I*z)
def _eval_rewrite_as_erfc(self, z, **kwargs):
return I*erfc(I*z) - I
def _eval_rewrite_as_fresnels(self, z, **kwargs):
arg = (S.One + S.ImaginaryUnit)*z/sqrt(pi)
return (S.One - S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg))
def _eval_rewrite_as_fresnelc(self, z, **kwargs):
arg = (S.One + S.ImaginaryUnit)*z/sqrt(pi)
return (S.One - S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg))
def _eval_rewrite_as_meijerg(self, z, **kwargs):
return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2)
def _eval_rewrite_as_hyper(self, z, **kwargs):
return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], z**2)
def _eval_rewrite_as_uppergamma(self, z, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
return sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(S.Pi) - S.One)
def _eval_rewrite_as_expint(self, z, **kwargs):
return sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi)
def _eval_expand_func(self, **hints):
return self.rewrite(erf)
as_real_imag = real_to_real_as_real_imag
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
arg0 = arg.subs(x, 0)
if x in arg.free_symbols and arg0.is_zero:
return 2*arg/sqrt(pi)
elif arg0.is_finite:
return self.func(arg0)
return self.func(arg)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
if point is S.Infinity:
z = self.args[0]
s = [factorial2(2*k - 1) / (2**k * z**(2*k + 1))
for k in range(n)] + [Order(1/z**n, x)]
return -S.ImaginaryUnit + (exp(z**2)/sqrt(pi)) * Add(*s)
return super(erfi, self)._eval_aseries(n, args0, x, logx)
class erf2(Function):
r"""
Two-argument error function.
Explanation
===========
This function is defined as:
.. math ::
\mathrm{erf2}(x, y) = \frac{2}{\sqrt{\pi}} \int_x^y e^{-t^2} \mathrm{d}t
Examples
========
>>> from sympy import oo, erf2
>>> from sympy.abc import x, y
Several special values are known:
>>> erf2(0, 0)
0
>>> erf2(x, x)
0
>>> erf2(x, oo)
1 - erf(x)
>>> erf2(x, -oo)
-erf(x) - 1
>>> erf2(oo, y)
erf(y) - 1
>>> erf2(-oo, y)
erf(y) + 1
In general one can pull out factors of -1:
>>> erf2(-x, -y)
-erf2(x, y)
The error function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(erf2(x, y))
erf2(conjugate(x), conjugate(y))
Differentiation with respect to $x$, $y$ is supported:
>>> from sympy import diff
>>> diff(erf2(x, y), x)
-2*exp(-x**2)/sqrt(pi)
>>> diff(erf2(x, y), y)
2*exp(-y**2)/sqrt(pi)
See Also
========
erf: Gaussian error function.
erfc: Complementary error function.
erfi: Imaginary error function.
erfinv: Inverse error function.
erfcinv: Inverse Complementary error function.
erf2inv: Inverse two-argument error function.
References
==========
.. [1] http://functions.wolfram.com/GammaBetaErf/Erf2/
"""
def fdiff(self, argindex):
x, y = self.args
if argindex == 1:
return -2*exp(-x**2)/sqrt(S.Pi)
elif argindex == 2:
return 2*exp(-y**2)/sqrt(S.Pi)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, x, y):
chk = (S.Infinity, S.NegativeInfinity, S.Zero)
if x is S.NaN or y is S.NaN:
return S.NaN
elif x == y:
return S.Zero
elif x in chk or y in chk:
return erf(y) - erf(x)
if isinstance(y, erf2inv) and y.args[0] == x:
return y.args[1]
if x.is_zero or y.is_zero or x.is_extended_real and x.is_infinite or \
y.is_extended_real and y.is_infinite:
return erf(y) - erf(x)
#Try to pull out -1 factor
sign_x = x.could_extract_minus_sign()
sign_y = y.could_extract_minus_sign()
if (sign_x and sign_y):
return -cls(-x, -y)
elif (sign_x or sign_y):
return erf(y)-erf(x)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate(), self.args[1].conjugate())
def _eval_is_extended_real(self):
return self.args[0].is_extended_real and self.args[1].is_extended_real
def _eval_rewrite_as_erf(self, x, y, **kwargs):
return erf(y) - erf(x)
def _eval_rewrite_as_erfc(self, x, y, **kwargs):
return erfc(x) - erfc(y)
def _eval_rewrite_as_erfi(self, x, y, **kwargs):
return I*(erfi(I*x)-erfi(I*y))
def _eval_rewrite_as_fresnels(self, x, y, **kwargs):
return erf(y).rewrite(fresnels) - erf(x).rewrite(fresnels)
def _eval_rewrite_as_fresnelc(self, x, y, **kwargs):
return erf(y).rewrite(fresnelc) - erf(x).rewrite(fresnelc)
def _eval_rewrite_as_meijerg(self, x, y, **kwargs):
return erf(y).rewrite(meijerg) - erf(x).rewrite(meijerg)
def _eval_rewrite_as_hyper(self, x, y, **kwargs):
return erf(y).rewrite(hyper) - erf(x).rewrite(hyper)
def _eval_rewrite_as_uppergamma(self, x, y, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
return (sqrt(y**2)/y*(S.One - uppergamma(S.Half, y**2)/sqrt(S.Pi)) -
sqrt(x**2)/x*(S.One - uppergamma(S.Half, x**2)/sqrt(S.Pi)))
def _eval_rewrite_as_expint(self, x, y, **kwargs):
return erf(y).rewrite(expint) - erf(x).rewrite(expint)
def _eval_expand_func(self, **hints):
return self.rewrite(erf)
def _eval_is_zero(self):
return is_eq(*self.args)
class erfinv(Function):
r"""
Inverse Error Function. The erfinv function is defined as:
.. math ::
\mathrm{erf}(x) = y \quad \Rightarrow \quad \mathrm{erfinv}(y) = x
Examples
========
>>> from sympy import erfinv
>>> from sympy.abc import x
Several special values are known:
>>> erfinv(0)
0
>>> erfinv(1)
oo
Differentiation with respect to $x$ is supported:
>>> from sympy import diff
>>> diff(erfinv(x), x)
sqrt(pi)*exp(erfinv(x)**2)/2
We can numerically evaluate the inverse error function to arbitrary
precision on [-1, 1]:
>>> erfinv(0.2).evalf(30)
0.179143454621291692285822705344
See Also
========
erf: Gaussian error function.
erfc: Complementary error function.
erfi: Imaginary error function.
erf2: Two-argument error function.
erfcinv: Inverse Complementary error function.
erf2inv: Inverse two-argument error function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions
.. [2] http://functions.wolfram.com/GammaBetaErf/InverseErf/
"""
def fdiff(self, argindex =1):
if argindex == 1:
return sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half
else :
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return erf
@classmethod
def eval(cls, z):
if z is S.NaN:
return S.NaN
elif z is S.NegativeOne:
return S.NegativeInfinity
elif z.is_zero:
return S.Zero
elif z is S.One:
return S.Infinity
if isinstance(z, erf) and z.args[0].is_extended_real:
return z.args[0]
if z.is_zero:
return S.Zero
# Try to pull out factors of -1
nz = z.extract_multiplicatively(-1)
if nz is not None and (isinstance(nz, erf) and (nz.args[0]).is_extended_real):
return -nz.args[0]
def _eval_rewrite_as_erfcinv(self, z, **kwargs):
return erfcinv(1-z)
def _eval_is_zero(self):
return self.args[0].is_zero
class erfcinv (Function):
r"""
Inverse Complementary Error Function. The erfcinv function is defined as:
.. math ::
\mathrm{erfc}(x) = y \quad \Rightarrow \quad \mathrm{erfcinv}(y) = x
Examples
========
>>> from sympy import erfcinv
>>> from sympy.abc import x
Several special values are known:
>>> erfcinv(1)
0
>>> erfcinv(0)
oo
Differentiation with respect to $x$ is supported:
>>> from sympy import diff
>>> diff(erfcinv(x), x)
-sqrt(pi)*exp(erfcinv(x)**2)/2
See Also
========
erf: Gaussian error function.
erfc: Complementary error function.
erfi: Imaginary error function.
erf2: Two-argument error function.
erfinv: Inverse error function.
erf2inv: Inverse two-argument error function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions
.. [2] http://functions.wolfram.com/GammaBetaErf/InverseErfc/
"""
def fdiff(self, argindex =1):
if argindex == 1:
return -sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return erfc
@classmethod
def eval(cls, z):
if z is S.NaN:
return S.NaN
elif z.is_zero:
return S.Infinity
elif z is S.One:
return S.Zero
elif z == 2:
return S.NegativeInfinity
if z.is_zero:
return S.Infinity
def _eval_rewrite_as_erfinv(self, z, **kwargs):
return erfinv(1-z)
def _eval_is_zero(self):
return (self.args[0] - 1).is_zero
def _eval_is_infinite(self):
return self.args[0].is_zero
class erf2inv(Function):
r"""
Two-argument Inverse error function. The erf2inv function is defined as:
.. math ::
\mathrm{erf2}(x, w) = y \quad \Rightarrow \quad \mathrm{erf2inv}(x, y) = w
Examples
========
>>> from sympy import erf2inv, oo
>>> from sympy.abc import x, y
Several special values are known:
>>> erf2inv(0, 0)
0
>>> erf2inv(1, 0)
1
>>> erf2inv(0, 1)
oo
>>> erf2inv(0, y)
erfinv(y)
>>> erf2inv(oo, y)
erfcinv(-y)
Differentiation with respect to $x$ and $y$ is supported:
>>> from sympy import diff
>>> diff(erf2inv(x, y), x)
exp(-x**2 + erf2inv(x, y)**2)
>>> diff(erf2inv(x, y), y)
sqrt(pi)*exp(erf2inv(x, y)**2)/2
See Also
========
erf: Gaussian error function.
erfc: Complementary error function.
erfi: Imaginary error function.
erf2: Two-argument error function.
erfinv: Inverse error function.
erfcinv: Inverse complementary error function.
References
==========
.. [1] http://functions.wolfram.com/GammaBetaErf/InverseErf2/
"""
def fdiff(self, argindex):
x, y = self.args
if argindex == 1:
return exp(self.func(x,y)**2-x**2)
elif argindex == 2:
return sqrt(S.Pi)*S.Half*exp(self.func(x,y)**2)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, x, y):
if x is S.NaN or y is S.NaN:
return S.NaN
elif x.is_zero and y.is_zero:
return S.Zero
elif x.is_zero and y is S.One:
return S.Infinity
elif x is S.One and y.is_zero:
return S.One
elif x.is_zero:
return erfinv(y)
elif x is S.Infinity:
return erfcinv(-y)
elif y.is_zero:
return x
elif y is S.Infinity:
return erfinv(x)
if x.is_zero:
if y.is_zero:
return S.Zero
else:
return erfinv(y)
if y.is_zero:
return x
def _eval_is_zero(self):
x, y = self.args
if x.is_zero and y.is_zero:
return True
###############################################################################
#################### EXPONENTIAL INTEGRALS ####################################
###############################################################################
class Ei(Function):
r"""
The classical exponential integral.
Explanation
===========
For use in SymPy, this function is defined as
.. math:: \operatorname{Ei}(x) = \sum_{n=1}^\infty \frac{x^n}{n\, n!}
+ \log(x) + \gamma,
where $\gamma$ is the Euler-Mascheroni constant.
If $x$ is a polar number, this defines an analytic function on the
Riemann surface of the logarithm. Otherwise this defines an analytic
function in the cut plane $\mathbb{C} \setminus (-\infty, 0]$.
**Background**
The name exponential integral comes from the following statement:
.. math:: \operatorname{Ei}(x) = \int_{-\infty}^x \frac{e^t}{t} \mathrm{d}t
If the integral is interpreted as a Cauchy principal value, this statement
holds for $x > 0$ and $\operatorname{Ei}(x)$ as defined above.
Examples
========
>>> from sympy import Ei, polar_lift, exp_polar, I, pi
>>> from sympy.abc import x
>>> Ei(-1)
Ei(-1)
This yields a real value:
>>> Ei(-1).n(chop=True)
-0.219383934395520
On the other hand the analytic continuation is not real:
>>> Ei(polar_lift(-1)).n(chop=True)
-0.21938393439552 + 3.14159265358979*I
The exponential integral has a logarithmic branch point at the origin:
>>> Ei(x*exp_polar(2*I*pi))
Ei(x) + 2*I*pi
Differentiation is supported:
>>> Ei(x).diff(x)
exp(x)/x
The exponential integral is related to many other special functions.
For example:
>>> from sympy import expint, Shi
>>> Ei(x).rewrite(expint)
-expint(1, x*exp_polar(I*pi)) - I*pi
>>> Ei(x).rewrite(Shi)
Chi(x) + Shi(x)
See Also
========
expint: Generalised exponential integral.
E1: Special case of the generalised exponential integral.
li: Logarithmic integral.
Li: Offset logarithmic integral.
Si: Sine integral.
Ci: Cosine integral.
Shi: Hyperbolic sine integral.
Chi: Hyperbolic cosine integral.
uppergamma: Upper incomplete gamma function.
References
==========
.. [1] http://dlmf.nist.gov/6.6
.. [2] https://en.wikipedia.org/wiki/Exponential_integral
.. [3] Abramowitz & Stegun, section 5: http://people.math.sfu.ca/~cbm/aands/page_228.htm
"""
@classmethod
def eval(cls, z):
if z.is_zero:
return S.NegativeInfinity
elif z is S.Infinity:
return S.Infinity
elif z is S.NegativeInfinity:
return S.Zero
if z.is_zero:
return S.NegativeInfinity
nz, n = z.extract_branch_factor()
if n:
return Ei(nz) + 2*I*pi*n
def fdiff(self, argindex=1):
arg = unpolarify(self.args[0])
if argindex == 1:
return exp(arg)/arg
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
if (self.args[0]/polar_lift(-1)).is_positive:
return Function._eval_evalf(self, prec) + (I*pi)._eval_evalf(prec)
return Function._eval_evalf(self, prec)
def _eval_rewrite_as_uppergamma(self, z, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
# XXX this does not currently work usefully because uppergamma
# immediately turns into expint
return -uppergamma(0, polar_lift(-1)*z) - I*pi
def _eval_rewrite_as_expint(self, z, **kwargs):
return -expint(1, polar_lift(-1)*z) - I*pi
def _eval_rewrite_as_li(self, z, **kwargs):
if isinstance(z, log):
return li(z.args[0])
# TODO:
# Actually it only holds that:
# Ei(z) = li(exp(z))
# for -pi < imag(z) <= pi
return li(exp(z))
def _eval_rewrite_as_Si(self, z, **kwargs):
if z.is_negative:
return Shi(z) + Chi(z) - I*pi
else:
return Shi(z) + Chi(z)
_eval_rewrite_as_Ci = _eval_rewrite_as_Si
_eval_rewrite_as_Chi = _eval_rewrite_as_Si
_eval_rewrite_as_Shi = _eval_rewrite_as_Si
def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
return exp(z) * _eis(z)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy import re
x0 = self.args[0].limit(x, 0)
arg = self.args[0].as_leading_term(x, cdir=cdir)
cdir = arg.dir(x, cdir)
if x0.is_zero:
c, e = arg.as_coeff_exponent(x)
logx = log(x) if logx is None else logx
return log(c) + e*logx + S.EulerGamma - (
S.ImaginaryUnit*pi if re(cdir).is_negative else S.Zero)
return super()._eval_as_leading_term(x, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir=0):
x0 = self.args[0].limit(x, 0)
if x0.is_zero:
f = self._eval_rewrite_as_Si(*self.args)
return f._eval_nseries(x, n, logx)
return super()._eval_nseries(x, n, logx)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
if point is S.Infinity:
z = self.args[0]
s = [factorial(k) / (z)**k for k in range(n)] + \
[Order(1/z**n, x)]
return (exp(z)/z) * Add(*s)
return super(Ei, self)._eval_aseries(n, args0, x, logx)
class expint(Function):
r"""
Generalized exponential integral.
Explanation
===========
This function is defined as
.. math:: \operatorname{E}_\nu(z) = z^{\nu - 1} \Gamma(1 - \nu, z),
where $\Gamma(1 - \nu, z)$ is the upper incomplete gamma function
(``uppergamma``).
Hence for $z$ with positive real part we have
.. math:: \operatorname{E}_\nu(z)
= \int_1^\infty \frac{e^{-zt}}{t^\nu} \mathrm{d}t,
which explains the name.
The representation as an incomplete gamma function provides an analytic
continuation for $\operatorname{E}_\nu(z)$. If $\nu$ is a
non-positive integer, the exponential integral is thus an unbranched
function of $z$, otherwise there is a branch point at the origin.
Refer to the incomplete gamma function documentation for details of the
branching behavior.
Examples
========
>>> from sympy import expint, S
>>> from sympy.abc import nu, z
Differentiation is supported. Differentiation with respect to $z$ further
explains the name: for integral orders, the exponential integral is an
iterated integral of the exponential function.
>>> expint(nu, z).diff(z)
-expint(nu - 1, z)
Differentiation with respect to $\nu$ has no classical expression:
>>> expint(nu, z).diff(nu)
-z**(nu - 1)*meijerg(((), (1, 1)), ((0, 0, 1 - nu), ()), z)
At non-postive integer orders, the exponential integral reduces to the
exponential function:
>>> expint(0, z)
exp(-z)/z
>>> expint(-1, z)
exp(-z)/z + exp(-z)/z**2
At half-integers it reduces to error functions:
>>> expint(S(1)/2, z)
sqrt(pi)*erfc(sqrt(z))/sqrt(z)
At positive integer orders it can be rewritten in terms of exponentials
and ``expint(1, z)``. Use ``expand_func()`` to do this:
>>> from sympy import expand_func
>>> expand_func(expint(5, z))
z**4*expint(1, z)/24 + (-z**3 + z**2 - 2*z + 6)*exp(-z)/24
The generalised exponential integral is essentially equivalent to the
incomplete gamma function:
>>> from sympy import uppergamma
>>> expint(nu, z).rewrite(uppergamma)
z**(nu - 1)*uppergamma(1 - nu, z)
As such it is branched at the origin:
>>> from sympy import exp_polar, pi, I
>>> expint(4, z*exp_polar(2*pi*I))
I*pi*z**3/3 + expint(4, z)
>>> expint(nu, z*exp_polar(2*pi*I))
z**(nu - 1)*(exp(2*I*pi*nu) - 1)*gamma(1 - nu) + expint(nu, z)
See Also
========
Ei: Another related function called exponential integral.
E1: The classical case, returns expint(1, z).
li: Logarithmic integral.
Li: Offset logarithmic integral.
Si: Sine integral.
Ci: Cosine integral.
Shi: Hyperbolic sine integral.
Chi: Hyperbolic cosine integral.
uppergamma
References
==========
.. [1] http://dlmf.nist.gov/8.19
.. [2] http://functions.wolfram.com/GammaBetaErf/ExpIntegralE/
.. [3] https://en.wikipedia.org/wiki/Exponential_integral
"""
@classmethod
def eval(cls, nu, z):
from sympy.functions.special.gamma_functions import (gamma, uppergamma)
nu2 = unpolarify(nu)
if nu != nu2:
return expint(nu2, z)
if nu.is_Integer and nu <= 0 or (not nu.is_Integer and (2*nu).is_Integer):
return unpolarify(expand_mul(z**(nu - 1)*uppergamma(1 - nu, z)))
# Extract branching information. This can be deduced from what is
# explained in lowergamma.eval().
z, n = z.extract_branch_factor()
if n is S.Zero:
return
if nu.is_integer:
if not nu > 0:
return
return expint(nu, z) \
- 2*pi*I*n*S.NegativeOne**(nu - 1)/factorial(nu - 1)*unpolarify(z)**(nu - 1)
else:
return (exp(2*I*pi*nu*n) - 1)*z**(nu - 1)*gamma(1 - nu) + expint(nu, z)
def fdiff(self, argindex):
nu, z = self.args
if argindex == 1:
return -z**(nu - 1)*meijerg([], [1, 1], [0, 0, 1 - nu], [], z)
elif argindex == 2:
return -expint(nu - 1, z)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_uppergamma(self, nu, z, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
return z**(nu - 1)*uppergamma(1 - nu, z)
def _eval_rewrite_as_Ei(self, nu, z, **kwargs):
if nu == 1:
return -Ei(z*exp_polar(-I*pi)) - I*pi
elif nu.is_Integer and nu > 1:
# DLMF, 8.19.7
x = -unpolarify(z)
return x**(nu - 1)/factorial(nu - 1)*E1(z).rewrite(Ei) + \
exp(x)/factorial(nu - 1) * \
Add(*[factorial(nu - k - 2)*x**k for k in range(nu - 1)])
else:
return self
def _eval_expand_func(self, **hints):
return self.rewrite(Ei).rewrite(expint, **hints)
def _eval_rewrite_as_Si(self, nu, z, **kwargs):
if nu != 1:
return self
return Shi(z) - Chi(z)
_eval_rewrite_as_Ci = _eval_rewrite_as_Si
_eval_rewrite_as_Chi = _eval_rewrite_as_Si
_eval_rewrite_as_Shi = _eval_rewrite_as_Si
def _eval_nseries(self, x, n, logx, cdir=0):
if not self.args[0].has(x):
nu = self.args[0]
if nu == 1:
f = self._eval_rewrite_as_Si(*self.args)
return f._eval_nseries(x, n, logx)
elif nu.is_Integer and nu > 1:
f = self._eval_rewrite_as_Ei(*self.args)
return f._eval_nseries(x, n, logx)
return super()._eval_nseries(x, n, logx)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[1]
nu = self.args[0]
if point is S.Infinity:
z = self.args[1]
s = [S.NegativeOne**k * RisingFactorial(nu, k) / z**k for k in range(n)] + [Order(1/z**n, x)]
return (exp(-z)/z) * Add(*s)
return super(expint, self)._eval_aseries(n, args0, x, logx)
def E1(z):
"""
Classical case of the generalized exponential integral.
Explanation
===========
This is equivalent to ``expint(1, z)``.
Examples
========
>>> from sympy import E1
>>> E1(0)
expint(1, 0)
>>> E1(5)
expint(1, 5)
See Also
========
Ei: Exponential integral.
expint: Generalised exponential integral.
li: Logarithmic integral.
Li: Offset logarithmic integral.
Si: Sine integral.
Ci: Cosine integral.
Shi: Hyperbolic sine integral.
Chi: Hyperbolic cosine integral.
"""
return expint(1, z)
class li(Function):
r"""
The classical logarithmic integral.
Explanation
===========
For use in SymPy, this function is defined as
.. math:: \operatorname{li}(x) = \int_0^x \frac{1}{\log(t)} \mathrm{d}t \,.
Examples
========
>>> from sympy import I, oo, li
>>> from sympy.abc import z
Several special values are known:
>>> li(0)
0
>>> li(1)
-oo
>>> li(oo)
oo
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(li(z), z)
1/log(z)
Defining the ``li`` function via an integral:
>>> from sympy import integrate
>>> integrate(li(z))
z*li(z) - Ei(2*log(z))
>>> integrate(li(z),z)
z*li(z) - Ei(2*log(z))
The logarithmic integral can also be defined in terms of ``Ei``:
>>> from sympy import Ei
>>> li(z).rewrite(Ei)
Ei(log(z))
>>> diff(li(z).rewrite(Ei), z)
1/log(z)
We can numerically evaluate the logarithmic integral to arbitrary precision
on the whole complex plane (except the singular points):
>>> li(2).evalf(30)
1.04516378011749278484458888919
>>> li(2*I).evalf(30)
1.0652795784357498247001125598 + 3.08346052231061726610939702133*I
We can even compute Soldner's constant by the help of mpmath:
>>> from mpmath import findroot
>>> findroot(li, 2)
1.45136923488338
Further transformations include rewriting ``li`` in terms of
the trigonometric integrals ``Si``, ``Ci``, ``Shi`` and ``Chi``:
>>> from sympy import Si, Ci, Shi, Chi
>>> li(z).rewrite(Si)
-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))
>>> li(z).rewrite(Ci)
-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))
>>> li(z).rewrite(Shi)
-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))
>>> li(z).rewrite(Chi)
-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))
See Also
========
Li: Offset logarithmic integral.
Ei: Exponential integral.
expint: Generalised exponential integral.
E1: Special case of the generalised exponential integral.
Si: Sine integral.
Ci: Cosine integral.
Shi: Hyperbolic sine integral.
Chi: Hyperbolic cosine integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Logarithmic_integral
.. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html
.. [3] http://dlmf.nist.gov/6
.. [4] http://mathworld.wolfram.com/SoldnersConstant.html
"""
@classmethod
def eval(cls, z):
if z.is_zero:
return S.Zero
elif z is S.One:
return S.NegativeInfinity
elif z is S.Infinity:
return S.Infinity
if z.is_zero:
return S.Zero
def fdiff(self, argindex=1):
arg = self.args[0]
if argindex == 1:
return S.One / log(arg)
else:
raise ArgumentIndexError(self, argindex)
def _eval_conjugate(self):
z = self.args[0]
# Exclude values on the branch cut (-oo, 0)
if not z.is_extended_negative:
return self.func(z.conjugate())
def _eval_rewrite_as_Li(self, z, **kwargs):
return Li(z) + li(2)
def _eval_rewrite_as_Ei(self, z, **kwargs):
return Ei(log(z))
def _eval_rewrite_as_uppergamma(self, z, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
return (-uppergamma(0, -log(z)) +
S.Half*(log(log(z)) - log(S.One/log(z))) - log(-log(z)))
def _eval_rewrite_as_Si(self, z, **kwargs):
return (Ci(I*log(z)) - I*Si(I*log(z)) -
S.Half*(log(S.One/log(z)) - log(log(z))) - log(I*log(z)))
_eval_rewrite_as_Ci = _eval_rewrite_as_Si
def _eval_rewrite_as_Shi(self, z, **kwargs):
return (Chi(log(z)) - Shi(log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))))
_eval_rewrite_as_Chi = _eval_rewrite_as_Shi
def _eval_rewrite_as_hyper(self, z, **kwargs):
return (log(z)*hyper((1, 1), (2, 2), log(z)) +
S.Half*(log(log(z)) - log(S.One/log(z))) + S.EulerGamma)
def _eval_rewrite_as_meijerg(self, z, **kwargs):
return (-log(-log(z)) - S.Half*(log(S.One/log(z)) - log(log(z)))
- meijerg(((), (1,)), ((0, 0), ()), -log(z)))
def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
return z * _eis(log(z))
def _eval_nseries(self, x, n, logx, cdir=0):
z = self.args[0]
s = [(log(z))**k / (factorial(k) * k) for k in range(1, n)]
return S.EulerGamma + log(log(z)) + Add(*s)
def _eval_is_zero(self):
z = self.args[0]
if z.is_zero:
return True
class Li(Function):
r"""
The offset logarithmic integral.
Explanation
===========
For use in SymPy, this function is defined as
.. math:: \operatorname{Li}(x) = \operatorname{li}(x) - \operatorname{li}(2)
Examples
========
>>> from sympy import Li
>>> from sympy.abc import z
The following special value is known:
>>> Li(2)
0
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(Li(z), z)
1/log(z)
The shifted logarithmic integral can be written in terms of $li(z)$:
>>> from sympy import li
>>> Li(z).rewrite(li)
li(z) - li(2)
We can numerically evaluate the logarithmic integral to arbitrary precision
on the whole complex plane (except the singular points):
>>> Li(2).evalf(30)
0
>>> Li(4).evalf(30)
1.92242131492155809316615998938
See Also
========
li: Logarithmic integral.
Ei: Exponential integral.
expint: Generalised exponential integral.
E1: Special case of the generalised exponential integral.
Si: Sine integral.
Ci: Cosine integral.
Shi: Hyperbolic sine integral.
Chi: Hyperbolic cosine integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Logarithmic_integral
.. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html
.. [3] http://dlmf.nist.gov/6
"""
@classmethod
def eval(cls, z):
if z is S.Infinity:
return S.Infinity
elif z == S(2):
return S.Zero
def fdiff(self, argindex=1):
arg = self.args[0]
if argindex == 1:
return S.One / log(arg)
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
return self.rewrite(li).evalf(prec)
def _eval_rewrite_as_li(self, z, **kwargs):
return li(z) - li(2)
def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
return self.rewrite(li).rewrite("tractable", deep=True)
def _eval_nseries(self, x, n, logx, cdir=0):
f = self._eval_rewrite_as_li(*self.args)
return f._eval_nseries(x, n, logx)
###############################################################################
#################### TRIGONOMETRIC INTEGRALS ##################################
###############################################################################
class TrigonometricIntegral(Function):
""" Base class for trigonometric integrals. """
@classmethod
def eval(cls, z):
if z is S.Zero:
return cls._atzero
elif z is S.Infinity:
return cls._atinf()
elif z is S.NegativeInfinity:
return cls._atneginf()
if z.is_zero:
return cls._atzero
nz = z.extract_multiplicatively(polar_lift(I))
if nz is None and cls._trigfunc(0) == 0:
nz = z.extract_multiplicatively(I)
if nz is not None:
return cls._Ifactor(nz, 1)
nz = z.extract_multiplicatively(polar_lift(-I))
if nz is not None:
return cls._Ifactor(nz, -1)
nz = z.extract_multiplicatively(polar_lift(-1))
if nz is None and cls._trigfunc(0) == 0:
nz = z.extract_multiplicatively(-1)
if nz is not None:
return cls._minusfactor(nz)
nz, n = z.extract_branch_factor()
if n == 0 and nz == z:
return
return 2*pi*I*n*cls._trigfunc(0) + cls(nz)
def fdiff(self, argindex=1):
arg = unpolarify(self.args[0])
if argindex == 1:
return self._trigfunc(arg)/arg
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Ei(self, z, **kwargs):
return self._eval_rewrite_as_expint(z).rewrite(Ei)
def _eval_rewrite_as_uppergamma(self, z, **kwargs):
from sympy.functions.special.gamma_functions import uppergamma
return self._eval_rewrite_as_expint(z).rewrite(uppergamma)
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE this is fairly inefficient
n += 1
if self.args[0].subs(x, 0) != 0:
return super()._eval_nseries(x, n, logx)
baseseries = self._trigfunc(x)._eval_nseries(x, n, logx)
if self._trigfunc(0) != 0:
baseseries -= 1
baseseries = baseseries.replace(Pow, lambda t, n: t**n/n, simultaneous=False)
if self._trigfunc(0) != 0:
baseseries += EulerGamma + log(x)
return baseseries.subs(x, self.args[0])._eval_nseries(x, n, logx)
class Si(TrigonometricIntegral):
r"""
Sine integral.
Explanation
===========
This function is defined by
.. math:: \operatorname{Si}(z) = \int_0^z \frac{\sin{t}}{t} \mathrm{d}t.
It is an entire function.
Examples
========
>>> from sympy import Si
>>> from sympy.abc import z
The sine integral is an antiderivative of $sin(z)/z$:
>>> Si(z).diff(z)
sin(z)/z
It is unbranched:
>>> from sympy import exp_polar, I, pi
>>> Si(z*exp_polar(2*I*pi))
Si(z)
Sine integral behaves much like ordinary sine under multiplication by ``I``:
>>> Si(I*z)
I*Shi(z)
>>> Si(-z)
-Si(z)
It can also be expressed in terms of exponential integrals, but beware
that the latter is branched:
>>> from sympy import expint
>>> Si(z).rewrite(expint)
-I*(-expint(1, z*exp_polar(-I*pi/2))/2 +
expint(1, z*exp_polar(I*pi/2))/2) + pi/2
It can be rewritten in the form of sinc function (by definition):
>>> from sympy import sinc
>>> Si(z).rewrite(sinc)
Integral(sinc(t), (t, 0, z))
See Also
========
Ci: Cosine integral.
Shi: Hyperbolic sine integral.
Chi: Hyperbolic cosine integral.
Ei: Exponential integral.
expint: Generalised exponential integral.
sinc: unnormalized sinc function
E1: Special case of the generalised exponential integral.
li: Logarithmic integral.
Li: Offset logarithmic integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
"""
_trigfunc = sin
_atzero = S.Zero
@classmethod
def _atinf(cls):
return pi*S.Half
@classmethod
def _atneginf(cls):
return -pi*S.Half
@classmethod
def _minusfactor(cls, z):
return -Si(z)
@classmethod
def _Ifactor(cls, z, sign):
return I*Shi(z)*sign
def _eval_rewrite_as_expint(self, z, **kwargs):
# XXX should we polarify z?
return pi/2 + (E1(polar_lift(I)*z) - E1(polar_lift(-I)*z))/2/I
def _eval_rewrite_as_sinc(self, z, **kwargs):
from sympy.integrals.integrals import Integral
t = Symbol('t', Dummy=True)
return Integral(sinc(t), (t, 0, z))
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
# Expansion at oo
if point is S.Infinity:
z = self.args[0]
p = [S.NegativeOne**k * factorial(2*k) / z**(2*k)
for k in range(int((n - 1)/2))] + [Order(1/z**n, x)]
q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1)
for k in range(int(n/2) - 1)] + [Order(1/z**n, x)]
return pi/2 - (cos(z)/z)*Add(*p) - (sin(z)/z)*Add(*q)
# All other points are not handled
return super(Si, self)._eval_aseries(n, args0, x, logx)
def _eval_is_zero(self):
z = self.args[0]
if z.is_zero:
return True
class Ci(TrigonometricIntegral):
r"""
Cosine integral.
Explanation
===========
This function is defined for positive $x$ by
.. math:: \operatorname{Ci}(x) = \gamma + \log{x}
+ \int_0^x \frac{\cos{t} - 1}{t} \mathrm{d}t
= -\int_x^\infty \frac{\cos{t}}{t} \mathrm{d}t,
where $\gamma$ is the Euler-Mascheroni constant.
We have
.. math:: \operatorname{Ci}(z) =
-\frac{\operatorname{E}_1\left(e^{i\pi/2} z\right)
+ \operatorname{E}_1\left(e^{-i \pi/2} z\right)}{2}
which holds for all polar $z$ and thus provides an analytic
continuation to the Riemann surface of the logarithm.
The formula also holds as stated
for $z \in \mathbb{C}$ with $\Re(z) > 0$.
By lifting to the principal branch, we obtain an analytic function on the
cut complex plane.
Examples
========
>>> from sympy import Ci
>>> from sympy.abc import z
The cosine integral is a primitive of $\cos(z)/z$:
>>> Ci(z).diff(z)
cos(z)/z
It has a logarithmic branch point at the origin:
>>> from sympy import exp_polar, I, pi
>>> Ci(z*exp_polar(2*I*pi))
Ci(z) + 2*I*pi
The cosine integral behaves somewhat like ordinary $\cos$ under
multiplication by $i$:
>>> from sympy import polar_lift
>>> Ci(polar_lift(I)*z)
Chi(z) + I*pi/2
>>> Ci(polar_lift(-1)*z)
Ci(z) + I*pi
It can also be expressed in terms of exponential integrals:
>>> from sympy import expint
>>> Ci(z).rewrite(expint)
-expint(1, z*exp_polar(-I*pi/2))/2 - expint(1, z*exp_polar(I*pi/2))/2
See Also
========
Si: Sine integral.
Shi: Hyperbolic sine integral.
Chi: Hyperbolic cosine integral.
Ei: Exponential integral.
expint: Generalised exponential integral.
E1: Special case of the generalised exponential integral.
li: Logarithmic integral.
Li: Offset logarithmic integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
"""
_trigfunc = cos
_atzero = S.ComplexInfinity
@classmethod
def _atinf(cls):
return S.Zero
@classmethod
def _atneginf(cls):
return I*pi
@classmethod
def _minusfactor(cls, z):
return Ci(z) + I*pi
@classmethod
def _Ifactor(cls, z, sign):
return Chi(z) + I*pi/2*sign
def _eval_rewrite_as_expint(self, z, **kwargs):
return -(E1(polar_lift(I)*z) + E1(polar_lift(-I)*z))/2
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
arg0 = arg.subs(x, 0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if arg0.is_zero:
c, e = arg.as_coeff_exponent(x)
logx = log(x) if logx is None else logx
return log(c) + e*logx + S.EulerGamma
elif arg0.is_finite:
return self.func(arg0)
else:
return self
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
# Expansion at oo
if point is S.Infinity:
z = self.args[0]
p = [S.NegativeOne**k * factorial(2*k) / z**(2*k)
for k in range(int((n - 1)/2))] + [Order(1/z**n, x)]
q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1)
for k in range(int(n/2) - 1)] + [Order(1/z**n, x)]
return (sin(z)/z)*Add(*p) - (cos(z)/z)*Add(*q)
# All other points are not handled
return super(Ci, self)._eval_aseries(n, args0, x, logx)
class Shi(TrigonometricIntegral):
r"""
Sinh integral.
Explanation
===========
This function is defined by
.. math:: \operatorname{Shi}(z) = \int_0^z \frac{\sinh{t}}{t} \mathrm{d}t.
It is an entire function.
Examples
========
>>> from sympy import Shi
>>> from sympy.abc import z
The Sinh integral is a primitive of $\sinh(z)/z$:
>>> Shi(z).diff(z)
sinh(z)/z
It is unbranched:
>>> from sympy import exp_polar, I, pi
>>> Shi(z*exp_polar(2*I*pi))
Shi(z)
The $\sinh$ integral behaves much like ordinary $\sinh$ under
multiplication by $i$:
>>> Shi(I*z)
I*Si(z)
>>> Shi(-z)
-Shi(z)
It can also be expressed in terms of exponential integrals, but beware
that the latter is branched:
>>> from sympy import expint
>>> Shi(z).rewrite(expint)
expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2
See Also
========
Si: Sine integral.
Ci: Cosine integral.
Chi: Hyperbolic cosine integral.
Ei: Exponential integral.
expint: Generalised exponential integral.
E1: Special case of the generalised exponential integral.
li: Logarithmic integral.
Li: Offset logarithmic integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
"""
_trigfunc = sinh
_atzero = S.Zero
@classmethod
def _atinf(cls):
return S.Infinity
@classmethod
def _atneginf(cls):
return S.NegativeInfinity
@classmethod
def _minusfactor(cls, z):
return -Shi(z)
@classmethod
def _Ifactor(cls, z, sign):
return I*Si(z)*sign
def _eval_rewrite_as_expint(self, z, **kwargs):
# XXX should we polarify z?
return (E1(z) - E1(exp_polar(I*pi)*z))/2 - I*pi/2
def _eval_is_zero(self):
z = self.args[0]
if z.is_zero:
return True
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0].as_leading_term(x)
arg0 = arg.subs(x, 0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if arg0.is_zero:
return arg
elif not arg0.is_infinite:
return self.func(arg0)
else:
return self
class Chi(TrigonometricIntegral):
r"""
Cosh integral.
Explanation
===========
This function is defined for positive $x$ by
.. math:: \operatorname{Chi}(x) = \gamma + \log{x}
+ \int_0^x \frac{\cosh{t} - 1}{t} \mathrm{d}t,
where $\gamma$ is the Euler-Mascheroni constant.
We have
.. math:: \operatorname{Chi}(z) = \operatorname{Ci}\left(e^{i \pi/2}z\right)
- i\frac{\pi}{2},
which holds for all polar $z$ and thus provides an analytic
continuation to the Riemann surface of the logarithm.
By lifting to the principal branch we obtain an analytic function on the
cut complex plane.
Examples
========
>>> from sympy import Chi
>>> from sympy.abc import z
The $\cosh$ integral is a primitive of $\cosh(z)/z$:
>>> Chi(z).diff(z)
cosh(z)/z
It has a logarithmic branch point at the origin:
>>> from sympy import exp_polar, I, pi
>>> Chi(z*exp_polar(2*I*pi))
Chi(z) + 2*I*pi
The $\cosh$ integral behaves somewhat like ordinary $\cosh$ under
multiplication by $i$:
>>> from sympy import polar_lift
>>> Chi(polar_lift(I)*z)
Ci(z) + I*pi/2
>>> Chi(polar_lift(-1)*z)
Chi(z) + I*pi
It can also be expressed in terms of exponential integrals:
>>> from sympy import expint
>>> Chi(z).rewrite(expint)
-expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2
See Also
========
Si: Sine integral.
Ci: Cosine integral.
Shi: Hyperbolic sine integral.
Ei: Exponential integral.
expint: Generalised exponential integral.
E1: Special case of the generalised exponential integral.
li: Logarithmic integral.
Li: Offset logarithmic integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
"""
_trigfunc = cosh
_atzero = S.ComplexInfinity
@classmethod
def _atinf(cls):
return S.Infinity
@classmethod
def _atneginf(cls):
return S.Infinity
@classmethod
def _minusfactor(cls, z):
return Chi(z) + I*pi
@classmethod
def _Ifactor(cls, z, sign):
return Ci(z) + I*pi/2*sign
def _eval_rewrite_as_expint(self, z, **kwargs):
return -I*pi/2 - (E1(z) + E1(exp_polar(I*pi)*z))/2
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
arg0 = arg.subs(x, 0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if arg0.is_zero:
c, e = arg.as_coeff_exponent(x)
logx = log(x) if logx is None else logx
return log(c) + e*logx + S.EulerGamma
elif arg0.is_finite:
return self.func(arg0)
else:
return self
###############################################################################
#################### FRESNEL INTEGRALS ########################################
###############################################################################
class FresnelIntegral(Function):
""" Base class for the Fresnel integrals."""
unbranched = True
@classmethod
def eval(cls, z):
# Values at positive infinities signs
# if any were extracted automatically
if z is S.Infinity:
return S.Half
# Value at zero
if z.is_zero:
return S.Zero
# Try to pull out factors of -1 and I
prefact = S.One
newarg = z
changed = False
nz = newarg.extract_multiplicatively(-1)
if nz is not None:
prefact = -prefact
newarg = nz
changed = True
nz = newarg.extract_multiplicatively(I)
if nz is not None:
prefact = cls._sign*I*prefact
newarg = nz
changed = True
if changed:
return prefact*cls(newarg)
def fdiff(self, argindex=1):
if argindex == 1:
return self._trigfunc(S.Half*pi*self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
def _eval_is_extended_real(self):
return self.args[0].is_extended_real
_eval_is_finite = _eval_is_extended_real
def _eval_is_zero(self):
return self.args[0].is_zero
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
as_real_imag = real_to_real_as_real_imag
class fresnels(FresnelIntegral):
r"""
Fresnel integral S.
Explanation
===========
This function is defined by
.. math:: \operatorname{S}(z) = \int_0^z \sin{\frac{\pi}{2} t^2} \mathrm{d}t.
It is an entire function.
Examples
========
>>> from sympy import I, oo, fresnels
>>> from sympy.abc import z
Several special values are known:
>>> fresnels(0)
0
>>> fresnels(oo)
1/2
>>> fresnels(-oo)
-1/2
>>> fresnels(I*oo)
-I/2
>>> fresnels(-I*oo)
I/2
In general one can pull out factors of -1 and $i$ from the argument:
>>> fresnels(-z)
-fresnels(z)
>>> fresnels(I*z)
-I*fresnels(z)
The Fresnel S integral obeys the mirror symmetry
$\overline{S(z)} = S(\bar{z})$:
>>> from sympy import conjugate
>>> conjugate(fresnels(z))
fresnels(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(fresnels(z), z)
sin(pi*z**2/2)
Defining the Fresnel functions via an integral:
>>> from sympy import integrate, pi, sin, expand_func
>>> integrate(sin(pi*z**2/2), z)
3*fresnels(z)*gamma(3/4)/(4*gamma(7/4))
>>> expand_func(integrate(sin(pi*z**2/2), z))
fresnels(z)
We can numerically evaluate the Fresnel integral to arbitrary precision
on the whole complex plane:
>>> fresnels(2).evalf(30)
0.343415678363698242195300815958
>>> fresnels(-2*I).evalf(30)
0.343415678363698242195300815958*I
See Also
========
fresnelc: Fresnel cosine integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Fresnel_integral
.. [2] http://dlmf.nist.gov/7
.. [3] http://mathworld.wolfram.com/FresnelIntegrals.html
.. [4] http://functions.wolfram.com/GammaBetaErf/FresnelS
.. [5] The converging factors for the fresnel integrals
by John W. Wrench Jr. and Vicki Alley
"""
_trigfunc = sin
_sign = -S.One
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 1:
p = previous_terms[-1]
return (-pi**2*x**4*(4*n - 1)/(8*n*(2*n + 1)*(4*n + 3))) * p
else:
return x**3 * (-x**4)**n * (S(2)**(-2*n - 1)*pi**(2*n + 1)) / ((4*n + 3)*factorial(2*n + 1))
def _eval_rewrite_as_erf(self, z, **kwargs):
return (S.One + I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z))
def _eval_rewrite_as_hyper(self, z, **kwargs):
return pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16)
def _eval_rewrite_as_meijerg(self, z, **kwargs):
return (pi*z**Rational(9, 4) / (sqrt(2)*(z**2)**Rational(3, 4)*(-z)**Rational(3, 4))
* meijerg([], [1], [Rational(3, 4)], [Rational(1, 4), 0], -pi**2*z**4/16))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.series.order import Order
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
arg0 = arg.subs(x, 0)
if arg0 is S.ComplexInfinity:
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if arg0.is_zero:
return pi*arg**3/6
elif arg0 in [S.Infinity, S.NegativeInfinity]:
s = 1 if arg0 is S.Infinity else -1
return s*S.Half + Order(x, x)
else:
return self.func(arg0)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
# Expansion at oo and -oo
if point in [S.Infinity, -S.Infinity]:
z = self.args[0]
# expansion of S(x) = S1(x*sqrt(pi/2)), see reference[5] page 1-8
# as only real infinities are dealt with, sin and cos are O(1)
p = [S.NegativeOne**k * factorial(4*k + 1) /
(2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k))
for k in range(0, n) if 4*k + 3 < n]
q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) /
(2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1))
for k in range(1, n) if 4*k + 1 < n]
p = [-sqrt(2/pi)*t for t in p]
q = [-sqrt(2/pi)*t for t in q]
s = 1 if point is S.Infinity else -1
# The expansion at oo is 1/2 + some odd powers of z
# To get the expansion at -oo, replace z by -z and flip the sign
# The result -1/2 + the same odd powers of z as before.
return s*S.Half + (sin(z**2)*Add(*p) + cos(z**2)*Add(*q)
).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x)
# All other points are not handled
return super()._eval_aseries(n, args0, x, logx)
class fresnelc(FresnelIntegral):
r"""
Fresnel integral C.
Explanation
===========
This function is defined by
.. math:: \operatorname{C}(z) = \int_0^z \cos{\frac{\pi}{2} t^2} \mathrm{d}t.
It is an entire function.
Examples
========
>>> from sympy import I, oo, fresnelc
>>> from sympy.abc import z
Several special values are known:
>>> fresnelc(0)
0
>>> fresnelc(oo)
1/2
>>> fresnelc(-oo)
-1/2
>>> fresnelc(I*oo)
I/2
>>> fresnelc(-I*oo)
-I/2
In general one can pull out factors of -1 and $i$ from the argument:
>>> fresnelc(-z)
-fresnelc(z)
>>> fresnelc(I*z)
I*fresnelc(z)
The Fresnel C integral obeys the mirror symmetry
$\overline{C(z)} = C(\bar{z})$:
>>> from sympy import conjugate
>>> conjugate(fresnelc(z))
fresnelc(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(fresnelc(z), z)
cos(pi*z**2/2)
Defining the Fresnel functions via an integral:
>>> from sympy import integrate, pi, cos, expand_func
>>> integrate(cos(pi*z**2/2), z)
fresnelc(z)*gamma(1/4)/(4*gamma(5/4))
>>> expand_func(integrate(cos(pi*z**2/2), z))
fresnelc(z)
We can numerically evaluate the Fresnel integral to arbitrary precision
on the whole complex plane:
>>> fresnelc(2).evalf(30)
0.488253406075340754500223503357
>>> fresnelc(-2*I).evalf(30)
-0.488253406075340754500223503357*I
See Also
========
fresnels: Fresnel sine integral.
References
==========
.. [1] https://en.wikipedia.org/wiki/Fresnel_integral
.. [2] http://dlmf.nist.gov/7
.. [3] http://mathworld.wolfram.com/FresnelIntegrals.html
.. [4] http://functions.wolfram.com/GammaBetaErf/FresnelC
.. [5] The converging factors for the fresnel integrals
by John W. Wrench Jr. and Vicki Alley
"""
_trigfunc = cos
_sign = S.One
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 1:
p = previous_terms[-1]
return (-pi**2*x**4*(4*n - 3)/(8*n*(2*n - 1)*(4*n + 1))) * p
else:
return x * (-x**4)**n * (S(2)**(-2*n)*pi**(2*n)) / ((4*n + 1)*factorial(2*n))
def _eval_rewrite_as_erf(self, z, **kwargs):
return (S.One - I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z))
def _eval_rewrite_as_hyper(self, z, **kwargs):
return z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16)
def _eval_rewrite_as_meijerg(self, z, **kwargs):
return (pi*z**Rational(3, 4) / (sqrt(2)*root(z**2, 4)*root(-z, 4))
* meijerg([], [1], [Rational(1, 4)], [Rational(3, 4), 0], -pi**2*z**4/16))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.series.order import Order
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
arg0 = arg.subs(x, 0)
if arg0 is S.ComplexInfinity:
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if arg0.is_zero:
return arg
elif arg0 in [S.Infinity, S.NegativeInfinity]:
s = 1 if arg0 is S.Infinity else -1
return s*S.Half + Order(x, x)
else:
return self.func(arg0)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
# Expansion at oo
if point in [S.Infinity, -S.Infinity]:
z = self.args[0]
# expansion of C(x) = C1(x*sqrt(pi/2)), see reference[5] page 1-8
# as only real infinities are dealt with, sin and cos are O(1)
p = [S.NegativeOne**k * factorial(4*k + 1) /
(2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k))
for k in range(n) if 4*k + 3 < n]
q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) /
(2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1))
for k in range(1, n) if 4*k + 1 < n]
p = [-sqrt(2/pi)*t for t in p]
q = [ sqrt(2/pi)*t for t in q]
s = 1 if point is S.Infinity else -1
# The expansion at oo is 1/2 + some odd powers of z
# To get the expansion at -oo, replace z by -z and flip the sign
# The result -1/2 + the same odd powers of z as before.
return s*S.Half + (cos(z**2)*Add(*p) + sin(z**2)*Add(*q)
).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x)
# All other points are not handled
return super()._eval_aseries(n, args0, x, logx)
###############################################################################
#################### HELPER FUNCTIONS #########################################
###############################################################################
class _erfs(Function):
"""
Helper function to make the $\\mathrm{erf}(z)$ function
tractable for the Gruntz algorithm.
"""
@classmethod
def eval(cls, arg):
if arg.is_zero:
return S.One
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
point = args0[0]
# Expansion at oo
if point is S.Infinity:
z = self.args[0]
l = [1/sqrt(S.Pi) * factorial(2*k)*(-S(
4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(n)]
o = Order(1/z**(2*n + 1), x)
# It is very inefficient to first add the order and then do the nseries
return (Add(*l))._eval_nseries(x, n, logx) + o
# Expansion at I*oo
t = point.extract_multiplicatively(S.ImaginaryUnit)
if t is S.Infinity:
z = self.args[0]
# TODO: is the series really correct?
l = [1/sqrt(S.Pi) * factorial(2*k)*(-S(
4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(n)]
o = Order(1/z**(2*n + 1), x)
# It is very inefficient to first add the order and then do the nseries
return (Add(*l))._eval_nseries(x, n, logx) + o
# All other points are not handled
return super()._eval_aseries(n, args0, x, logx)
def fdiff(self, argindex=1):
if argindex == 1:
z = self.args[0]
return -2/sqrt(S.Pi) + 2*z*_erfs(z)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_intractable(self, z, **kwargs):
return (S.One - erf(z))*exp(z**2)
class _eis(Function):
"""
Helper function to make the $\\mathrm{Ei}(z)$ and $\\mathrm{li}(z)$
functions tractable for the Gruntz algorithm.
"""
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
if args0[0] != S.Infinity:
return super(_erfs, self)._eval_aseries(n, args0, x, logx)
z = self.args[0]
l = [factorial(k) * (1/z)**(k + 1) for k in range(n)]
o = Order(1/z**(n + 1), x)
# It is very inefficient to first add the order and then do the nseries
return (Add(*l))._eval_nseries(x, n, logx) + o
def fdiff(self, argindex=1):
if argindex == 1:
z = self.args[0]
return S.One / z - _eis(z)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_intractable(self, z, **kwargs):
return exp(-z)*Ei(z)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
x0 = self.args[0].limit(x, 0)
if x0.is_zero:
f = self._eval_rewrite_as_intractable(*self.args)
return f._eval_as_leading_term(x, logx=logx, cdir=cdir)
return super()._eval_as_leading_term(x, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir=0):
x0 = self.args[0].limit(x, 0)
if x0.is_zero:
f = self._eval_rewrite_as_intractable(*self.args)
return f._eval_nseries(x, n, logx)
return super()._eval_nseries(x, n, logx)
|
1597069d472baac322ee4362bfb40a8e0ccd5f0adc21cfa9a0399ee9b2e0348e | """
This module mainly implements special orthogonal polynomials.
See also functions.combinatorial.numbers which contains some
combinatorial polynomials.
"""
from sympy.core import Rational
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.singleton import S
from sympy.core.symbol import Dummy
from sympy.functions.combinatorial.factorials import binomial, factorial, RisingFactorial
from sympy.functions.elementary.complexes import re
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sec
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import hyper
from sympy.polys.orthopolys import (chebyshevt_poly, chebyshevu_poly,
gegenbauer_poly, hermite_poly, hermite_prob_poly,
jacobi_poly, laguerre_poly, legendre_poly)
_x = Dummy('x')
class OrthogonalPolynomial(Function):
"""Base class for orthogonal polynomials.
"""
@classmethod
def _eval_at_order(cls, n, x):
if n.is_integer and n >= 0:
return cls._ortho_poly(int(n), _x).subs(_x, x)
def _eval_conjugate(self):
return self.func(self.args[0], self.args[1].conjugate())
#----------------------------------------------------------------------------
# Jacobi polynomials
#
class jacobi(OrthogonalPolynomial):
r"""
Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$.
Explanation
===========
``jacobi(n, alpha, beta, x)`` gives the $n$th Jacobi polynomial
in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$.
The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect
to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$.
Examples
========
>>> from sympy import jacobi, S, conjugate, diff
>>> from sympy.abc import a, b, n, x
>>> jacobi(0, a, b, x)
1
>>> jacobi(1, a, b, x)
a/2 - b/2 + x*(a/2 + b/2 + 1)
>>> jacobi(2, a, b, x)
a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 + x**2*(a**2/8 + a*b/4 + 7*a/8 + b**2/8 + 7*b/8 + 3/2) + x*(a**2/4 + 3*a/4 - b**2/4 - 3*b/4) - 1/2
>>> jacobi(n, a, b, x)
jacobi(n, a, b, x)
>>> jacobi(n, a, a, x)
RisingFactorial(a + 1, n)*gegenbauer(n,
a + 1/2, x)/RisingFactorial(2*a + 1, n)
>>> jacobi(n, 0, 0, x)
legendre(n, x)
>>> jacobi(n, S(1)/2, S(1)/2, x)
RisingFactorial(3/2, n)*chebyshevu(n, x)/factorial(n + 1)
>>> jacobi(n, -S(1)/2, -S(1)/2, x)
RisingFactorial(1/2, n)*chebyshevt(n, x)/factorial(n)
>>> jacobi(n, a, b, -x)
(-1)**n*jacobi(n, b, a, x)
>>> jacobi(n, a, b, 0)
gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(2**n*factorial(n)*gamma(a + 1))
>>> jacobi(n, a, b, 1)
RisingFactorial(a + 1, n)/factorial(n)
>>> conjugate(jacobi(n, a, b, x))
jacobi(n, conjugate(a), conjugate(b), conjugate(x))
>>> diff(jacobi(n,a,b,x), x)
(a/2 + b/2 + n/2 + 1/2)*jacobi(n - 1, a + 1, b + 1, x)
See Also
========
gegenbauer,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly,
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials
.. [2] http://mathworld.wolfram.com/JacobiPolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/JacobiP/
"""
@classmethod
def eval(cls, n, a, b, x):
# Simplify to other polynomials
# P^{a, a}_n(x)
if a == b:
if a == Rational(-1, 2):
return RisingFactorial(S.Half, n) / factorial(n) * chebyshevt(n, x)
elif a.is_zero:
return legendre(n, x)
elif a == S.Half:
return RisingFactorial(3*S.Half, n) / factorial(n + 1) * chebyshevu(n, x)
else:
return RisingFactorial(a + 1, n) / RisingFactorial(2*a + 1, n) * gegenbauer(n, a + S.Half, x)
elif b == -a:
# P^{a, -a}_n(x)
return gamma(n + a + 1) / gamma(n + 1) * (1 + x)**(a/2) / (1 - x)**(a/2) * assoc_legendre(n, -a, x)
if not n.is_Number:
# Symbolic result P^{a,b}_n(x)
# P^{a,b}_n(-x) ---> (-1)**n * P^{b,a}_n(-x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * jacobi(n, b, a, -x)
# We can evaluate for some special values of x
if x.is_zero:
return (2**(-n) * gamma(a + n + 1) / (gamma(a + 1) * factorial(n)) *
hyper([-b - n, -n], [a + 1], -1))
if x == S.One:
return RisingFactorial(a + 1, n) / factorial(n)
elif x is S.Infinity:
if n.is_positive:
# Make sure a+b+2*n \notin Z
if (a + b + 2*n).is_integer:
raise ValueError("Error. a + b + 2*n should not be an integer.")
return RisingFactorial(a + b + n + 1, n) * S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
return jacobi_poly(n, a, b, x)
def fdiff(self, argindex=4):
from sympy.concrete.summations import Sum
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt a
n, a, b, x = self.args
k = Dummy("k")
f1 = 1 / (a + b + n + k + 1)
f2 = ((a + b + 2*k + 1) * RisingFactorial(b + k + 1, n - k) /
((n - k) * RisingFactorial(a + b + k + 1, n - k)))
return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1))
elif argindex == 3:
# Diff wrt b
n, a, b, x = self.args
k = Dummy("k")
f1 = 1 / (a + b + n + k + 1)
f2 = (-1)**(n - k) * ((a + b + 2*k + 1) * RisingFactorial(a + k + 1, n - k) /
((n - k) * RisingFactorial(a + b + k + 1, n - k)))
return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1))
elif argindex == 4:
# Diff wrt x
n, a, b, x = self.args
return S.Half * (a + b + n + 1) * jacobi(n - 1, a + 1, b + 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, a, b, x, **kwargs):
from sympy.concrete.summations import Sum
# Make sure n \in N
if n.is_negative or n.is_integer is False:
raise ValueError("Error: n should be a non-negative integer.")
k = Dummy("k")
kern = (RisingFactorial(-n, k) * RisingFactorial(a + b + n + 1, k) * RisingFactorial(a + k + 1, n - k) /
factorial(k) * ((1 - x)/2)**k)
return 1 / factorial(n) * Sum(kern, (k, 0, n))
def _eval_rewrite_as_polynomial(self, n, a, b, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, a, b, x, **kwargs)
def _eval_conjugate(self):
n, a, b, x = self.args
return self.func(n, a.conjugate(), b.conjugate(), x.conjugate())
def jacobi_normalized(n, a, b, x):
r"""
Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$.
Explanation
===========
``jacobi_normalized(n, alpha, beta, x)`` gives the $n$th
Jacobi polynomial in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$.
The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect
to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$.
This functions returns the polynomials normilzed:
.. math::
\int_{-1}^{1}
P_m^{\left(\alpha, \beta\right)}(x)
P_n^{\left(\alpha, \beta\right)}(x)
(1-x)^{\alpha} (1+x)^{\beta} \mathrm{d}x
= \delta_{m,n}
Examples
========
>>> from sympy import jacobi_normalized
>>> from sympy.abc import n,a,b,x
>>> jacobi_normalized(n, a, b, x)
jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)/((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1)))
Parameters
==========
n : integer degree of polynomial
a : alpha value
b : beta value
x : symbol
See Also
========
gegenbauer,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly,
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials
.. [2] http://mathworld.wolfram.com/JacobiPolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/JacobiP/
"""
nfactor = (S(2)**(a + b + 1) * (gamma(n + a + 1) * gamma(n + b + 1))
/ (2*n + a + b + 1) / (factorial(n) * gamma(n + a + b + 1)))
return jacobi(n, a, b, x) / sqrt(nfactor)
#----------------------------------------------------------------------------
# Gegenbauer polynomials
#
class gegenbauer(OrthogonalPolynomial):
r"""
Gegenbauer polynomial $C_n^{\left(\alpha\right)}(x)$.
Explanation
===========
``gegenbauer(n, alpha, x)`` gives the $n$th Gegenbauer polynomial
in $x$, $C_n^{\left(\alpha\right)}(x)$.
The Gegenbauer polynomials are orthogonal on $[-1, 1]$ with
respect to the weight $\left(1-x^2\right)^{\alpha-\frac{1}{2}}$.
Examples
========
>>> from sympy import gegenbauer, conjugate, diff
>>> from sympy.abc import n,a,x
>>> gegenbauer(0, a, x)
1
>>> gegenbauer(1, a, x)
2*a*x
>>> gegenbauer(2, a, x)
-a + x**2*(2*a**2 + 2*a)
>>> gegenbauer(3, a, x)
x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a)
>>> gegenbauer(n, a, x)
gegenbauer(n, a, x)
>>> gegenbauer(n, a, -x)
(-1)**n*gegenbauer(n, a, x)
>>> gegenbauer(n, a, 0)
2**n*sqrt(pi)*gamma(a + n/2)/(gamma(a)*gamma(1/2 - n/2)*gamma(n + 1))
>>> gegenbauer(n, a, 1)
gamma(2*a + n)/(gamma(2*a)*gamma(n + 1))
>>> conjugate(gegenbauer(n, a, x))
gegenbauer(n, conjugate(a), conjugate(x))
>>> diff(gegenbauer(n, a, x), x)
2*a*gegenbauer(n - 1, a + 1, x)
See Also
========
jacobi,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Gegenbauer_polynomials
.. [2] http://mathworld.wolfram.com/GegenbauerPolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/GegenbauerC3/
"""
@classmethod
def eval(cls, n, a, x):
# For negative n the polynomials vanish
# See http://functions.wolfram.com/Polynomials/GegenbauerC3/03/01/03/0012/
if n.is_negative:
return S.Zero
# Some special values for fixed a
if a == S.Half:
return legendre(n, x)
elif a == S.One:
return chebyshevu(n, x)
elif a == S.NegativeOne:
return S.Zero
if not n.is_Number:
# Handle this before the general sign extraction rule
if x == S.NegativeOne:
if (re(a) > S.Half) == True:
return S.ComplexInfinity
else:
return (cos(S.Pi*(a+n)) * sec(S.Pi*a) * gamma(2*a+n) /
(gamma(2*a) * gamma(n+1)))
# Symbolic result C^a_n(x)
# C^a_n(-x) ---> (-1)**n * C^a_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * gegenbauer(n, a, -x)
# We can evaluate for some special values of x
if x.is_zero:
return (2**n * sqrt(S.Pi) * gamma(a + S.Half*n) /
(gamma((1 - n)/2) * gamma(n + 1) * gamma(a)) )
if x == S.One:
return gamma(2*a + n) / (gamma(2*a) * gamma(n + 1))
elif x is S.Infinity:
if n.is_positive:
return RisingFactorial(a, n) * S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
return gegenbauer_poly(n, a, x)
def fdiff(self, argindex=3):
from sympy.concrete.summations import Sum
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt a
n, a, x = self.args
k = Dummy("k")
factor1 = 2 * (1 + (-1)**(n - k)) * (k + a) / ((k +
n + 2*a) * (n - k))
factor2 = 2*(k + 1) / ((k + 2*a) * (2*k + 2*a + 1)) + \
2 / (k + n + 2*a)
kern = factor1*gegenbauer(k, a, x) + factor2*gegenbauer(n, a, x)
return Sum(kern, (k, 0, n - 1))
elif argindex == 3:
# Diff wrt x
n, a, x = self.args
return 2*a*gegenbauer(n - 1, a + 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, a, x, **kwargs):
from sympy.concrete.summations 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)))
def _eval_rewrite_as_polynomial(self, n, a, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, a, x, **kwargs)
def _eval_conjugate(self):
n, a, x = self.args
return self.func(n, a.conjugate(), x.conjugate())
#----------------------------------------------------------------------------
# Chebyshev polynomials of first and second kind
#
class chebyshevt(OrthogonalPolynomial):
r"""
Chebyshev polynomial of the first kind, $T_n(x)$.
Explanation
===========
``chebyshevt(n, x)`` gives the $n$th Chebyshev polynomial (of the first
kind) in $x$, $T_n(x)$.
The Chebyshev polynomials of the first kind are orthogonal on
$[-1, 1]$ with respect to the weight $\frac{1}{\sqrt{1-x^2}}$.
Examples
========
>>> from sympy import chebyshevt, diff
>>> from sympy.abc import n,x
>>> chebyshevt(0, x)
1
>>> chebyshevt(1, x)
x
>>> chebyshevt(2, x)
2*x**2 - 1
>>> chebyshevt(n, x)
chebyshevt(n, x)
>>> chebyshevt(n, -x)
(-1)**n*chebyshevt(n, x)
>>> chebyshevt(-n, x)
chebyshevt(n, x)
>>> chebyshevt(n, 0)
cos(pi*n/2)
>>> chebyshevt(n, -1)
(-1)**n
>>> diff(chebyshevt(n, x), x)
n*chebyshevu(n - 1, x)
See Also
========
jacobi, gegenbauer,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial
.. [2] http://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html
.. [3] http://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html
.. [4] http://functions.wolfram.com/Polynomials/ChebyshevT/
.. [5] http://functions.wolfram.com/Polynomials/ChebyshevU/
"""
_ortho_poly = staticmethod(chebyshevt_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result T_n(x)
# T_n(-x) ---> (-1)**n * T_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * chebyshevt(n, -x)
# T_{-n}(x) ---> T_n(x)
if n.could_extract_minus_sign():
return chebyshevt(-n, x)
# We can evaluate for some special values of x
if x.is_zero:
return cos(S.Half * S.Pi * n)
if x == S.One:
return S.One
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
# T_{-n}(x) == T_n(x)
return cls._eval_at_order(-n, x)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return n * chebyshevu(n - 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, x, **kwargs):
from sympy.concrete.summations 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 _eval_rewrite_as_polynomial(self, n, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, x, **kwargs)
class chebyshevu(OrthogonalPolynomial):
r"""
Chebyshev polynomial of the second kind, $U_n(x)$.
Explanation
===========
``chebyshevu(n, x)`` gives the $n$th Chebyshev polynomial of the second
kind in x, $U_n(x)$.
The Chebyshev polynomials of the second kind are orthogonal on
$[-1, 1]$ with respect to the weight $\sqrt{1-x^2}$.
Examples
========
>>> from sympy import chebyshevu, diff
>>> from sympy.abc import n,x
>>> chebyshevu(0, x)
1
>>> chebyshevu(1, x)
2*x
>>> chebyshevu(2, x)
4*x**2 - 1
>>> chebyshevu(n, x)
chebyshevu(n, x)
>>> chebyshevu(n, -x)
(-1)**n*chebyshevu(n, x)
>>> chebyshevu(-n, x)
-chebyshevu(n - 2, x)
>>> chebyshevu(n, 0)
cos(pi*n/2)
>>> chebyshevu(n, 1)
n + 1
>>> diff(chebyshevu(n, x), x)
(-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial
.. [2] http://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html
.. [3] http://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html
.. [4] http://functions.wolfram.com/Polynomials/ChebyshevT/
.. [5] http://functions.wolfram.com/Polynomials/ChebyshevU/
"""
_ortho_poly = staticmethod(chebyshevu_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result U_n(x)
# U_n(-x) ---> (-1)**n * U_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * chebyshevu(n, -x)
# U_{-n}(x) ---> -U_{n-2}(x)
if n.could_extract_minus_sign():
if n == S.NegativeOne:
# n can not be -1 here
return S.Zero
elif not (-n - 2).could_extract_minus_sign():
return -chebyshevu(-n - 2, x)
# We can evaluate for some special values of x
if x.is_zero:
return cos(S.Half * S.Pi * n)
if x == S.One:
return S.One + n
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
# U_{-n}(x) ---> -U_{n-2}(x)
if n == S.NegativeOne:
return S.Zero
else:
return -cls._eval_at_order(-n - 2, x)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return ((n + 1) * chebyshevt(n + 1, x) - x * chebyshevu(n, x)) / (x**2 - 1)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, x, **kwargs):
from sympy.concrete.summations 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, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, x, **kwargs)
class chebyshevt_root(Function):
r"""
``chebyshev_root(n, k)`` returns the $k$th root (indexed from zero) of
the $n$th Chebyshev polynomial of the first kind; that is, if
$0 \le k < n$, ``chebyshevt(n, chebyshevt_root(n, k)) == 0``.
Examples
========
>>> from sympy import chebyshevt, chebyshevt_root
>>> chebyshevt_root(3, 2)
-sqrt(3)/2
>>> chebyshevt(3, chebyshevt_root(3, 2))
0
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
"""
@classmethod
def eval(cls, n, k):
if not ((0 <= k) and (k < n)):
raise ValueError("must have 0 <= k < n, "
"got k = %s and n = %s" % (k, n))
return cos(S.Pi*(2*k + 1)/(2*n))
class chebyshevu_root(Function):
r"""
``chebyshevu_root(n, k)`` returns the $k$th root (indexed from zero) of the
$n$th Chebyshev polynomial of the second kind; that is, if $0 \le k < n$,
``chebyshevu(n, chebyshevu_root(n, k)) == 0``.
Examples
========
>>> from sympy import chebyshevu, chebyshevu_root
>>> chebyshevu_root(3, 2)
-sqrt(2)/2
>>> chebyshevu(3, chebyshevu_root(3, 2))
0
See Also
========
chebyshevt, chebyshevt_root, chebyshevu,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
"""
@classmethod
def eval(cls, n, k):
if not ((0 <= k) and (k < n)):
raise ValueError("must have 0 <= k < n, "
"got k = %s and n = %s" % (k, n))
return cos(S.Pi*(k + 1)/(n + 1))
#----------------------------------------------------------------------------
# Legendre polynomials and Associated Legendre polynomials
#
class legendre(OrthogonalPolynomial):
r"""
``legendre(n, x)`` gives the $n$th Legendre polynomial of $x$, $P_n(x)$
Explanation
===========
The Legendre polynomials are orthogonal on $[-1, 1]$ with respect to
the constant weight 1. They satisfy $P_n(1) = 1$ for all $n$; further,
$P_n$ is odd for odd $n$ and even for even $n$.
Examples
========
>>> from sympy import legendre, diff
>>> from sympy.abc import x, n
>>> legendre(0, x)
1
>>> legendre(1, x)
x
>>> legendre(2, x)
3*x**2/2 - 1/2
>>> legendre(n, x)
legendre(n, x)
>>> diff(legendre(n,x), x)
n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
assoc_legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Legendre_polynomial
.. [2] http://mathworld.wolfram.com/LegendrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LegendreP/
.. [4] http://functions.wolfram.com/Polynomials/LegendreP2/
"""
_ortho_poly = staticmethod(legendre_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result L_n(x)
# L_n(-x) ---> (-1)**n * L_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * legendre(n, -x)
# L_{-n}(x) ---> L_{n-1}(x)
if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():
return legendre(-n - S.One, x)
# We can evaluate for some special values of x
if x.is_zero:
return sqrt(S.Pi)/(gamma(S.Half - n/2)*gamma(S.One + n/2))
elif x == S.One:
return S.One
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial;
# L_{-n}(x) ---> L_{n-1}(x)
if n.is_negative:
n = -n - S.One
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
# Find better formula, this is unsuitable for x = +/-1
# http://www.autodiff.org/ad16/Oral/Buecker_Legendre.pdf says
# at x = 1:
# n*(n + 1)/2 , m = 0
# oo , m = 1
# -(n-1)*n*(n+1)*(n+2)/4 , m = 2
# 0 , m = 3, 4, ..., n
#
# at x = -1
# (-1)**(n+1)*n*(n + 1)/2 , m = 0
# (-1)**n*oo , m = 1
# (-1)**n*(n-1)*n*(n+1)*(n+2)/4 , m = 2
# 0 , m = 3, 4, ..., n
n, x = self.args
return n/(x**2 - 1)*(x*legendre(n, x) - legendre(n - 1, x))
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, x, **kwargs):
from sympy.concrete.summations import Sum
k = Dummy("k")
kern = S.NegativeOne**k*binomial(n, k)**2*((1 + x)/2)**(n - k)*((1 - x)/2)**k
return Sum(kern, (k, 0, n))
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, x, **kwargs)
class assoc_legendre(Function):
r"""
``assoc_legendre(n, m, x)`` gives $P_n^m(x)$, where $n$ and $m$ are
the degree and order or an expression which is related to the nth
order Legendre polynomial, $P_n(x)$ in the following manner:
.. math::
P_n^m(x) = (-1)^m (1 - x^2)^{\frac{m}{2}}
\frac{\mathrm{d}^m P_n(x)}{\mathrm{d} x^m}
Explanation
===========
Associated Legendre polynomials are orthogonal on $[-1, 1]$ with:
- weight $= 1$ for the same $m$ and different $n$.
- weight $= \frac{1}{1-x^2}$ for the same $n$ and different $m$.
Examples
========
>>> from sympy import assoc_legendre
>>> from sympy.abc import x, m, n
>>> assoc_legendre(0,0, x)
1
>>> assoc_legendre(1,0, x)
x
>>> assoc_legendre(1,1, x)
-sqrt(1 - x**2)
>>> assoc_legendre(n,m,x)
assoc_legendre(n, m, x)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre,
hermite, hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Associated_Legendre_polynomials
.. [2] http://mathworld.wolfram.com/LegendrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LegendreP/
.. [4] http://functions.wolfram.com/Polynomials/LegendreP2/
"""
@classmethod
def _eval_at_order(cls, n, m):
P = legendre_poly(n, _x, polys=True).diff((_x, m))
return S.NegativeOne**m * (1 - _x**2)**Rational(m, 2) * P.as_expr()
@classmethod
def eval(cls, n, m, x):
if m.could_extract_minus_sign():
# P^{-m}_n ---> F * P^m_n
return S.NegativeOne**(-m) * (factorial(m + n)/factorial(n - m)) * assoc_legendre(n, -m, x)
if m == 0:
# P^0_n ---> L_n
return legendre(n, x)
if x == 0:
return 2**m*sqrt(S.Pi) / (gamma((1 - m - n)/2)*gamma(1 - (m - n)/2))
if n.is_Number and m.is_Number and n.is_integer and m.is_integer:
if n.is_negative:
raise ValueError("%s : 1st index must be nonnegative integer (got %r)" % (cls, n))
if abs(m) > n:
raise ValueError("%s : abs('2nd index') must be <= '1st index' (got %r, %r)" % (cls, n, m))
return cls._eval_at_order(int(n), abs(int(m))).subs(_x, x)
def fdiff(self, argindex=3):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt m
raise ArgumentIndexError(self, argindex)
elif argindex == 3:
# Diff wrt x
# Find better formula, this is unsuitable for x = 1
n, m, x = self.args
return 1/(x**2 - 1)*(x*n*assoc_legendre(n, m, x) - (m + n)*assoc_legendre(n - 1, m, x))
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, m, x, **kwargs):
from sympy.concrete.summations import Sum
k = Dummy("k")
kern = factorial(2*n - 2*k)/(2**n*factorial(n - k)*factorial(
k)*factorial(n - 2*k - m))*S.NegativeOne**k*x**(n - m - 2*k)
return (1 - x**2)**(m/2) * Sum(kern, (k, 0, floor((n - m)*S.Half)))
def _eval_rewrite_as_polynomial(self, n, m, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, m, x, **kwargs)
def _eval_conjugate(self):
n, m, x = self.args
return self.func(n, m.conjugate(), x.conjugate())
#----------------------------------------------------------------------------
# Hermite polynomials
#
class hermite(OrthogonalPolynomial):
r"""
``hermite(n, x)`` gives the $n$th Hermite polynomial in $x$, $H_n(x)$.
Explanation
===========
The Hermite polynomials are orthogonal on $(-\infty, \infty)$
with respect to the weight $\exp\left(-x^2\right)$.
Examples
========
>>> from sympy import hermite, diff
>>> from sympy.abc import x, n
>>> hermite(0, x)
1
>>> hermite(1, x)
2*x
>>> hermite(2, x)
4*x**2 - 2
>>> hermite(n, x)
hermite(n, x)
>>> diff(hermite(n,x), x)
2*n*hermite(n - 1, x)
>>> hermite(n, -x)
(-1)**n*hermite(n, x)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite_prob,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermite_polynomial
.. [2] http://mathworld.wolfram.com/HermitePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/HermiteH/
"""
_ortho_poly = staticmethod(hermite_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result H_n(x)
# H_n(-x) ---> (-1)**n * H_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * hermite(n, -x)
# We can evaluate for some special values of x
if x.is_zero:
return 2**n * sqrt(S.Pi) / gamma((S.One - n)/2)
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
raise ValueError(
"The index n must be nonnegative integer (got %r)" % n)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return 2*n*hermite(n - 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, x, **kwargs):
from sympy.concrete.summations import Sum
k = Dummy("k")
kern = S.NegativeOne**k / (factorial(k)*factorial(n - 2*k)) * (2*x)**(n - 2*k)
return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, x, **kwargs)
def _eval_rewrite_as_hermite_prob(self, n, x, **kwargs):
return sqrt(2)**n * hermite_prob(n, x*sqrt(2))
class hermite_prob(OrthogonalPolynomial):
r"""
``hermite_prob(n, x)`` gives the $n$th probabilist's Hermite polynomial
in $x$, $He_n(x)$.
Explanation
===========
The probabilist's Hermite polynomials are orthogonal on $(-\infty, \infty)$
with respect to the weight $\exp\left(-\frac{x^2}{2}\right)$. They are monic
polynomials, related to the plain Hermite polynomials (:py:class:`~.hermite`) by
.. math :: He_n(x) = 2^{-n/2} H_n(x/\sqrt{2})
Examples
========
>>> from sympy import hermite_prob, diff, I
>>> from sympy.abc import x, n
>>> hermite_prob(1, x)
x
>>> hermite_prob(5, x)
x**5 - 10*x**3 + 15*x
>>> diff(hermite_prob(n,x), x)
n*hermite_prob(n - 1, x)
>>> hermite_prob(n, -x)
(-1)**n*hermite_prob(n, x)
The sum of absolute values of coefficients of $He_n(x)$ is the number of
matchings in the complete graph $K_n$ or telephone number, A000085 in the OEIS:
>>> [hermite_prob(n,I) / I**n for n in range(11)]
[1, 1, 2, 4, 10, 26, 76, 232, 764, 2620, 9496]
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermite_polynomial
.. [2] http://mathworld.wolfram.com/HermitePolynomial.html
"""
_ortho_poly = staticmethod(hermite_prob_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
if x.could_extract_minus_sign():
return S.NegativeOne**n * hermite_prob(n, -x)
if x.is_zero:
return sqrt(S.Pi) / gamma((S.One-n) / 2)
elif x is S.Infinity:
return S.Infinity
else:
if n.is_negative:
ValueError("n must be a nonnegative integer, not %r" % n)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 2:
n, x = self.args
return n*hermite_prob(n-1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, x, **kwargs):
from sympy.concrete.summations import Sum
k = Dummy("k")
kern = (-S.Half)**k * x**(n-2*k) / (factorial(k) * factorial(n-2*k))
return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, x, **kwargs)
def _eval_rewrite_as_hermite(self, n, x, **kwargs):
return sqrt(2)**(-n) * hermite(n, x/sqrt(2))
#----------------------------------------------------------------------------
# Laguerre polynomials
#
class laguerre(OrthogonalPolynomial):
r"""
Returns the $n$th Laguerre polynomial in $x$, $L_n(x)$.
Examples
========
>>> from sympy import laguerre, diff
>>> from sympy.abc import x, n
>>> laguerre(0, x)
1
>>> laguerre(1, x)
1 - x
>>> laguerre(2, x)
x**2/2 - 2*x + 1
>>> laguerre(3, x)
-x**3/6 + 3*x**2/2 - 3*x + 1
>>> laguerre(n, x)
laguerre(n, x)
>>> diff(laguerre(n, x), x)
-assoc_laguerre(n - 1, 1, x)
Parameters
==========
n : int
Degree of Laguerre polynomial. Must be `n \ge 0`.
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial
.. [2] http://mathworld.wolfram.com/LaguerrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LaguerreL/
.. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/
"""
_ortho_poly = staticmethod(laguerre_poly)
@classmethod
def eval(cls, n, x):
if n.is_integer is False:
raise ValueError("Error: n should be an integer.")
if not n.is_Number:
# Symbolic result L_n(x)
# L_{n}(-x) ---> exp(-x) * L_{-n-1}(x)
# L_{-n}(x) ---> exp(x) * L_{n-1}(-x)
if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():
return exp(x)*laguerre(-n - 1, -x)
# We can evaluate for some special values of x
if x.is_zero:
return S.One
elif x is S.NegativeInfinity:
return S.Infinity
elif x is S.Infinity:
return S.NegativeOne**n * S.Infinity
else:
if n.is_negative:
return exp(x)*laguerre(-n - 1, -x)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return -assoc_laguerre(n - 1, 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, x, **kwargs):
from sympy.concrete.summations import Sum
# Make sure n \in N_0
if n.is_negative:
return exp(x) * self._eval_rewrite_as_Sum(-n - 1, -x, **kwargs)
if n.is_integer is False:
raise ValueError("Error: n should be an integer.")
k = Dummy("k")
kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k
return Sum(kern, (k, 0, n))
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, x, **kwargs)
class assoc_laguerre(OrthogonalPolynomial):
r"""
Returns the $n$th generalized Laguerre polynomial in $x$, $L_n(x)$.
Examples
========
>>> from sympy import assoc_laguerre, diff
>>> from sympy.abc import x, n, a
>>> assoc_laguerre(0, a, x)
1
>>> assoc_laguerre(1, a, x)
a - x + 1
>>> assoc_laguerre(2, a, x)
a**2/2 + 3*a/2 + x**2/2 + x*(-a - 2) + 1
>>> assoc_laguerre(3, a, x)
a**3/6 + a**2 + 11*a/6 - x**3/6 + x**2*(a/2 + 3/2) +
x*(-a**2/2 - 5*a/2 - 3) + 1
>>> assoc_laguerre(n, a, 0)
binomial(a + n, a)
>>> assoc_laguerre(n, a, x)
assoc_laguerre(n, a, x)
>>> assoc_laguerre(n, 0, x)
laguerre(n, x)
>>> diff(assoc_laguerre(n, a, x), x)
-assoc_laguerre(n - 1, a + 1, x)
>>> diff(assoc_laguerre(n, a, x), a)
Sum(assoc_laguerre(_k, a, x)/(-a + n), (_k, 0, n - 1))
Parameters
==========
n : int
Degree of Laguerre polynomial. Must be `n \ge 0`.
alpha : Expr
Arbitrary expression. For ``alpha=0`` regular Laguerre
polynomials will be generated.
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite, hermite_prob,
laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials
.. [2] http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LaguerreL/
.. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/
"""
@classmethod
def eval(cls, n, alpha, x):
# L_{n}^{0}(x) ---> L_{n}(x)
if alpha.is_zero:
return laguerre(n, x)
if not n.is_Number:
# We can evaluate for some special values of x
if x.is_zero:
return binomial(n + alpha, alpha)
elif x is S.Infinity and n > 0:
return S.NegativeOne**n * S.Infinity
elif x is S.NegativeInfinity and n > 0:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
raise ValueError(
"The index n must be nonnegative integer (got %r)" % n)
else:
return laguerre_poly(n, x, alpha)
def fdiff(self, argindex=3):
from sympy.concrete.summations import Sum
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt alpha
n, alpha, x = self.args
k = Dummy("k")
return Sum(assoc_laguerre(k, alpha, x) / (n - alpha), (k, 0, n - 1))
elif argindex == 3:
# Diff wrt x
n, alpha, x = self.args
return -assoc_laguerre(n - 1, alpha + 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, alpha, x, **kwargs):
from sympy.concrete.summations import Sum
# Make sure n \in N_0
if n.is_negative or n.is_integer is False:
raise ValueError("Error: n should be a non-negative integer.")
k = Dummy("k")
kern = RisingFactorial(
-n, k) / (gamma(k + alpha + 1) * factorial(k)) * x**k
return gamma(n + alpha + 1) / factorial(n) * Sum(kern, (k, 0, n))
def _eval_rewrite_as_polynomial(self, n, alpha, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, alpha, x, **kwargs)
def _eval_conjugate(self):
n, alpha, x = self.args
return self.func(n, alpha.conjugate(), x.conjugate())
|
cb8b02a63acda9a399dfd38897e26b559e2d5fbdb7d0c6ba70351c2442d57f20 | import string
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core.function import (diff, expand_func)
from sympy.core import (EulerGamma, TribonacciConstant)
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.combinatorial.numbers import carmichael
from sympy.functions.elementary.complexes import (im, re)
from sympy.functions.elementary.integers import floor
from sympy.polys.polytools import cancel
from sympy.series.limits import limit, Limit
from sympy.series.order import O
from sympy.functions import (
bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan,
genocchi, andre, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma,
trigamma, polygamma, factorial, sin, cos, cot, polylog, zeta, dirichlet_eta)
from sympy.functions.combinatorial.numbers import _nT
from sympy.core.expr import unchanged
from sympy.core.numbers import GoldenRatio, Integer
from sympy.testing.pytest import raises, nocache_fail, warns_deprecated_sympy
from sympy.abc import x
def test_carmichael():
assert carmichael.find_carmichael_numbers_in_range(0, 561) == []
assert carmichael.find_carmichael_numbers_in_range(561, 562) == [561]
assert carmichael.find_carmichael_numbers_in_range(561, 1105) == carmichael.find_carmichael_numbers_in_range(561,
562)
assert carmichael.find_first_n_carmichaels(5) == [561, 1105, 1729, 2465, 2821]
raises(ValueError, lambda: carmichael.is_carmichael(-2))
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(-2, 2))
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(22, 2))
with warns_deprecated_sympy():
assert carmichael.is_prime(2821) == False
def test_bernoulli():
assert bernoulli(0) == 1
assert bernoulli(1) == Rational(1, 2)
assert bernoulli(2) == Rational(1, 6)
assert bernoulli(3) == 0
assert bernoulli(4) == Rational(-1, 30)
assert bernoulli(5) == 0
assert bernoulli(6) == Rational(1, 42)
assert bernoulli(7) == 0
assert bernoulli(8) == Rational(-1, 30)
assert bernoulli(10) == Rational(5, 66)
assert bernoulli(1000001) == 0
assert bernoulli(0, x) == 1
assert bernoulli(1, x) == x - S.Half
assert bernoulli(2, x) == x**2 - x + Rational(1, 6)
assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2
# Should be fast; computed with mpmath
b = bernoulli(1000)
assert b.p % 10**10 == 7950421099
assert b.q == 342999030
b = bernoulli(10**6, evaluate=False).evalf()
assert str(b) == '-2.23799235765713e+4767529'
# Issue #8527
l = Symbol('l', integer=True)
m = Symbol('m', integer=True, nonnegative=True)
n = Symbol('n', integer=True, positive=True)
assert isinstance(bernoulli(2 * l + 1), bernoulli)
assert isinstance(bernoulli(2 * m + 1), bernoulli)
assert bernoulli(2 * n + 1) == 0
assert bernoulli(x, 1) == bernoulli(x)
assert str(bernoulli(0.0, 2.3).evalf(n=10)) == '1.000000000'
assert str(bernoulli(1.0).evalf(n=10)) == '0.5000000000'
assert str(bernoulli(1.2).evalf(n=10)) == '0.4195995367'
assert str(bernoulli(1.2, 0.8).evalf(n=10)) == '0.2144830348'
assert str(bernoulli(1.2, -0.8).evalf(n=10)) == '-1.158865646 - 0.6745558744*I'
assert str(bernoulli(3.0, 1j).evalf(n=10)) == '1.5 - 0.5*I'
assert str(bernoulli(I).evalf(n=10)) == '0.9268485643 - 0.5821580598*I'
assert str(bernoulli(I, I).evalf(n=10)) == '0.1267792071 + 0.01947413152*I'
assert bernoulli(x).evalf() == bernoulli(x)
def test_bernoulli_rewrite():
from sympy.functions.elementary.piecewise import Piecewise
n = Symbol('n', integer=True, nonnegative=True)
assert bernoulli(-1).rewrite(zeta) == pi**2/6
assert bernoulli(-2).rewrite(zeta) == 2*zeta(3)
assert not bernoulli(n, -3).rewrite(zeta).has(harmonic)
assert bernoulli(-4, x).rewrite(zeta) == 4*zeta(5, x)
assert isinstance(bernoulli(n, x).rewrite(zeta), Piecewise)
assert bernoulli(n+1, x).rewrite(zeta) == -(n+1) * zeta(-n, x)
def test_fibonacci():
assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3]
assert fibonacci(100) == 354224848179261915075
assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7]
assert lucas(100) == 792070839848372253127
assert fibonacci(1, x) == 1
assert fibonacci(2, x) == x
assert fibonacci(3, x) == x**2 + 1
assert fibonacci(4, x) == x**3 + 2*x
# issue #8800
n = Dummy('n')
assert fibonacci(n).limit(n, S.Infinity) is S.Infinity
assert lucas(n).limit(n, S.Infinity) is S.Infinity
assert fibonacci(n).rewrite(sqrt) == \
2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
assert fibonacci(n).rewrite(sqrt).subs(n, 10).expand() == fibonacci(10)
assert fibonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
fibonacci(10)
assert lucas(n).rewrite(sqrt) == \
(fibonacci(n-1).rewrite(sqrt) + fibonacci(n+1).rewrite(sqrt)).simplify()
assert lucas(n).rewrite(sqrt).subs(n, 10).expand() == lucas(10)
raises(ValueError, lambda: fibonacci(-3, x))
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))
@nocache_fail
def test_bell():
assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877]
assert bell(0, x) == 1
assert bell(1, x) == x
assert bell(2, x) == x**2 + x
assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x
assert bell(oo) is S.Infinity
raises(ValueError, lambda: bell(oo, x))
raises(ValueError, lambda: bell(-1))
raises(ValueError, lambda: bell(S.Half))
X = symbols('x:6')
# X = (x0, x1, .. x5)
# at the same time: X[1] = x1, X[2] = x2 for standard readablity.
# but we must supply zero-based indexed object X[1:] = (x1, .. x5)
assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2
assert bell(
6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3
X = (1, 10, 100, 1000, 10000)
assert bell(6, 2, X) == (6 + 15 + 10)*10000
X = (1, 2, 3, 3, 5)
assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2
X = (1, 2, 3, 5)
assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3
# Dobinski's formula
n = Symbol('n', integer=True, nonnegative=True)
# For large numbers, this is too slow
# For nonintegers, there are significant precision errors
for i in [0, 2, 3, 7, 13, 42, 55]:
# Running without the cache this is either very slow or goes into an
# infinite loop.
assert bell(i).evalf() == bell(n).rewrite(Sum).evalf(subs={n: i})
m = Symbol("m")
assert bell(m).rewrite(Sum) == bell(m)
assert bell(n, m).rewrite(Sum) == bell(n, m)
# issue 9184
n = Dummy('n')
assert bell(n).limit(n, S.Infinity) is S.Infinity
def test_harmonic():
n = Symbol("n")
m = Symbol("m")
assert harmonic(n, 0) == n
assert harmonic(n).evalf() == harmonic(n)
assert harmonic(n, 1) == harmonic(n)
assert harmonic(1, n).evalf() == harmonic(1, n)
assert harmonic(0, 1) == 0
assert harmonic(1, 1) == 1
assert harmonic(2, 1) == Rational(3, 2)
assert harmonic(3, 1) == Rational(11, 6)
assert harmonic(4, 1) == Rational(25, 12)
assert harmonic(0, 2) == 0
assert harmonic(1, 2) == 1
assert harmonic(2, 2) == Rational(5, 4)
assert harmonic(3, 2) == Rational(49, 36)
assert harmonic(4, 2) == Rational(205, 144)
assert harmonic(0, 3) == 0
assert harmonic(1, 3) == 1
assert harmonic(2, 3) == Rational(9, 8)
assert harmonic(3, 3) == Rational(251, 216)
assert harmonic(4, 3) == Rational(2035, 1728)
assert harmonic(oo, -1) is S.NaN
assert harmonic(oo, 0) is oo
assert harmonic(oo, S.Half) is oo
assert harmonic(oo, 1) is oo
assert harmonic(oo, 2) == (pi**2)/6
assert harmonic(oo, 3) == zeta(3)
assert harmonic(oo, Dummy(negative=True)) is S.NaN
ip = Dummy(integer=True, positive=True)
if (1/ip <= 1) is True: #---------------------------------+
assert None, 'delete this if-block and the next line' #|
ip = Dummy(even=True, positive=True) #--------------------+
assert harmonic(oo, 1/ip) is oo
assert harmonic(oo, 1 + ip) is zeta(1 + ip)
assert harmonic(0, m) == 0
assert harmonic(-1, -1) == 0
assert harmonic(-1, 0) == -1
assert harmonic(-1, 1) is S.ComplexInfinity
assert harmonic(-1, 2) is S.NaN
assert harmonic(-3, -2) == -5
assert harmonic(-3, -3) == 9
def test_harmonic_rational():
ne = S(6)
no = S(5)
pe = S(8)
po = S(9)
qe = S(10)
qo = S(13)
Heee = harmonic(ne + pe/qe)
Aeee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(13944145, 4720968))
Heeo = harmonic(ne + pe/qo)
Aeeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2 - 2*log(sin(pi/13))*cos(pi*Rational(3, 13))
+ Rational(2422020029, 702257080))
Heoe = harmonic(ne + po/qe)
Aeoe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
+ Rational(11818877030, 4286604231) + pi*sqrt(2*sqrt(5) + 5)/2)
Heoo = harmonic(ne + po/qo)
Aeoo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
- 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(3, 13)) + Rational(11669332571, 3628714320))
Hoee = harmonic(no + pe/qe)
Aoee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(779405, 277704))
Hoeo = harmonic(no + pe/qo)
Aoeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2
- 2*log(sin(pi/13))*cos(pi*Rational(3, 13)) + Rational(53857323, 16331560))
Hooe = harmonic(no + po/qe)
Aooe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
+ Rational(486853480, 186374097) + pi*sqrt(2*sqrt(5) + 5)/2)
Hooo = harmonic(no + po/qo)
Aooo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
- 2*log(sin(pi*Rational(2, 13)))*cos(3*pi/13) + Rational(383693479, 125128080))
H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo]
A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo]
for h, a in zip(H, A):
e = expand_func(h).doit()
assert cancel(e/a) == 1
assert abs(h.n() - a.n()) < 1e-12
def test_harmonic_evalf():
assert str(harmonic(1.5).evalf(n=10)) == '1.280372306'
assert str(harmonic(1.5, 2).evalf(n=10)) == '1.154576311' # issue 7443
assert str(harmonic(4.0, -3).evalf(n=10)) == '100.0000000'
assert str(harmonic(7.0, 1.0).evalf(n=10)) == '2.592857143'
assert str(harmonic(1, pi).evalf(n=10)) == '1.000000000'
assert str(harmonic(2, pi).evalf(n=10)) == '1.113314732'
assert str(harmonic(1000.0, pi).evalf(n=10)) == '1.176241563'
assert str(harmonic(I).evalf(n=10)) == '0.6718659855 + 1.076674047*I'
assert str(harmonic(I, I).evalf(n=10)) == '-0.3970915266 + 1.9629689*I'
assert harmonic(-1.0, 1).evalf() is S.NaN
assert harmonic(-2.0, 2.0).evalf() is S.NaN
def test_harmonic_rewrite():
from sympy.functions.elementary.piecewise import Piecewise
n = Symbol("n")
m = Symbol("m", integer=True, positive=True)
x1 = Symbol("x1", positive=True)
x2 = Symbol("x2", negative=True)
assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2
assert isinstance(harmonic(n,m).rewrite(polygamma), Piecewise)
assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma)
assert harmonic(n, x1).rewrite("tractable") == harmonic(n, x1)
assert harmonic(n, x1 + 1).rewrite("tractable") == zeta(x1 + 1) - zeta(x1 + 1, n + 1)
assert harmonic(n, x2).rewrite("tractable") == zeta(x2) - zeta(x2, n + 1)
_k = Dummy("k")
assert harmonic(n).rewrite(Sum).dummy_eq(Sum(1/_k, (_k, 1, n)))
assert harmonic(n, m).rewrite(Sum).dummy_eq(Sum(_k**(-m), (_k, 1, n)))
def test_harmonic_calculus():
y = Symbol("y", positive=True)
z = Symbol("z", negative=True)
assert harmonic(x, 1).limit(x, 0) == 0
assert harmonic(x, y).limit(x, 0) == 0
assert harmonic(x, 1).series(x, y, 2) == \
harmonic(y) + (x - y)*zeta(2, y + 1) + O((x - y)**2, (x, y))
assert limit(harmonic(x, y), x, oo) == harmonic(oo, y)
assert limit(harmonic(x, y + 1), x, oo) == zeta(y + 1)
assert limit(harmonic(x, y - 1), x, oo) == harmonic(oo, y - 1)
assert limit(harmonic(x, z), x, oo) == Limit(harmonic(x, z), x, oo, dir='-')
assert limit(harmonic(x, z + 1), x, oo) == oo
assert limit(harmonic(x, z + 2), x, oo) == harmonic(oo, z + 2)
assert limit(harmonic(x, z - 1), x, oo) == Limit(harmonic(x, z - 1), x, oo, dir='-')
def test_euler():
assert euler(0) == 1
assert euler(1) == 0
assert euler(2) == -1
assert euler(3) == 0
assert euler(4) == 5
assert euler(6) == -61
assert euler(8) == 1385
assert euler(20, evaluate=False) != 370371188237525
n = Symbol('n', integer=True)
assert euler(n) != -1
assert euler(n).subs(n, 2) == -1
assert euler(-1) == S.Pi / 2
assert euler(-1, 1) == 2*log(2)
assert euler(-2).evalf() == (2*S.Catalan).evalf()
assert euler(-3).evalf() == (S.Pi**3 / 16).evalf()
assert str(euler(2.3).evalf(n=10)) == '-1.052850274'
assert str(euler(1.2, 3.4).evalf(n=10)) == '3.575613489'
assert str(euler(I).evalf(n=10)) == '1.248446443 - 0.7675445124*I'
assert str(euler(I, I).evalf(n=10)) == '0.04812930469 + 0.01052411008*I'
assert euler(20).evalf() == 370371188237525.0
assert euler(20, evaluate=False).evalf() == 370371188237525.0
assert euler(n).rewrite(Sum) == euler(n)
n = Symbol('n', integer=True, nonnegative=True)
assert euler(2*n + 1).rewrite(Sum) == 0
_j = Dummy('j')
_k = Dummy('k')
assert euler(2*n).rewrite(Sum).dummy_eq(
I*Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)*
binomial(_k, _j)/_k, (_j, 0, _k), (_k, 1, 2*n + 1)))
def test_euler_odd():
n = Symbol('n', odd=True, positive=True)
assert euler(n) == 0
n = Symbol('n', odd=True)
assert euler(n) != 0
def test_euler_polynomials():
assert euler(0, x) == 1
assert euler(1, x) == x - S.Half
assert euler(2, x) == x**2 - x
assert euler(3, x) == x**3 - (3*x**2)/2 + Rational(1, 4)
m = Symbol('m')
assert isinstance(euler(m, x), euler)
from sympy.core.numbers import Float
A = Float('-0.46237208575048694923364757452876131e8') # from Maple
B = euler(19, S.Pi).evalf(32)
assert abs((A - B)/A) < 1e-31
def test_euler_polynomial_rewrite():
m = Symbol('m')
A = euler(m, x).rewrite('Sum');
assert A.subs({m:3, x:5}).doit() == euler(3, 5)
def test_catalan():
n = Symbol('n', integer=True)
m = Symbol('m', integer=True, positive=True)
k = Symbol('k', integer=True, nonnegative=True)
p = Symbol('p', nonnegative=True)
catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
for i, c in enumerate(catalans):
assert catalan(i) == c
assert catalan(n).rewrite(factorial).subs(n, i) == c
assert catalan(n).rewrite(Product).subs(n, i).doit() == c
assert unchanged(catalan, x)
assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
assert catalan(S.Half).rewrite(gamma) == 8/(3*pi)
assert catalan(S.Half).rewrite(factorial).rewrite(gamma) ==\
8 / (3 * pi)
assert catalan(3*x).rewrite(gamma) == 4**(
3*x)*gamma(3*x + S.Half)/(sqrt(pi)*gamma(3*x + 2))
assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)
assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
* factorial(n))
assert isinstance(catalan(n).rewrite(Product), catalan)
assert isinstance(catalan(m).rewrite(Product), Product)
assert diff(catalan(x), x) == (polygamma(
0, x + S.Half) - polygamma(0, x + 2) + log(4))*catalan(x)
assert catalan(x).evalf() == catalan(x)
c = catalan(S.Half).evalf()
assert str(c) == '0.848826363156775'
c = catalan(I).evalf(3)
assert str((re(c), im(c))) == '(0.398, -0.0209)'
# Assumptions
assert catalan(p).is_positive is True
assert catalan(k).is_integer is True
assert catalan(m+3).is_composite is True
def test_genocchi():
genocchis = [0, -1, -1, 0, 1, 0, -3, 0, 17]
for n, g in enumerate(genocchis):
assert genocchi(n) == g
m = Symbol('m', integer=True)
n = Symbol('n', integer=True, positive=True)
assert unchanged(genocchi, m)
assert genocchi(2*n + 1) == 0
gn = 2 * (1 - 2**n) * bernoulli(n)
assert genocchi(n).rewrite(bernoulli).factor() == gn.factor()
gnx = 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
assert genocchi(n, x).rewrite(bernoulli).factor() == gnx.factor()
assert genocchi(2 * n).is_odd
assert genocchi(2 * n).is_even is False
assert genocchi(2 * n + 1).is_even
assert genocchi(n).is_integer
assert genocchi(4 * n).is_positive
# these are the only 2 prime Genocchi numbers
assert genocchi(6, evaluate=False).is_prime == S(-3).is_prime
assert genocchi(8, evaluate=False).is_prime
assert genocchi(4 * n + 2).is_negative
assert genocchi(4 * n + 1).is_negative is False
assert genocchi(4 * n - 2).is_negative
g0 = genocchi(0, evaluate=False)
assert g0.is_positive is False
assert g0.is_negative is False
assert g0.is_even is True
assert g0.is_odd is False
assert genocchi(0, x) == 0
assert genocchi(1, x) == -1
assert genocchi(2, x) == 1 - 2*x
assert genocchi(3, x) == 3*x - 3*x**2
assert genocchi(4, x) == -1 + 6*x**2 - 4*x**3
y = Symbol("y")
assert genocchi(5, (x+y)**100) == -5*(x+y)**400 + 10*(x+y)**300 - 5*(x+y)**100
assert str(genocchi(5.0, 4.0).evalf(n=10)) == '-660.0000000'
assert str(genocchi(Rational(5, 4)).evalf(n=10)) == '-1.104286457'
assert str(genocchi(-2).evalf(n=10)) == '3.606170709'
assert str(genocchi(1.3, 3.7).evalf(n=10)) == '-1.847375373'
assert str(genocchi(I, 1.0).evalf(n=10)) == '-0.3161917278 - 1.45311955*I'
n = Symbol('n')
assert genocchi(n, x).rewrite(dirichlet_eta) == -2*n * dirichlet_eta(1-n, x)
def test_andre():
nums = [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
for n, a in enumerate(nums):
assert andre(n) == a
assert andre(S.Infinity) == S.Infinity
assert andre(-1) == -log(2)
assert andre(-2) == -2*S.Catalan
assert andre(-3) == 3*zeta(3)/16
assert andre(-5) == -15*zeta(5)/256
# In fact andre(-2*n) is related to the Dirichlet *beta* function
# at 2*n, but SymPy doesn't implement that (or general L-functions)
assert unchanged(andre, -4)
n = Symbol('n', integer=True, nonnegative=True)
assert unchanged(andre, n)
assert andre(n).is_integer is True
assert andre(n).is_positive is True
assert str(andre(10, evaluate=False).evalf(n=10)) == '50521.00000'
assert str(andre(-1, evaluate=False).evalf(n=10)) == '-0.6931471806'
assert str(andre(-2, evaluate=False).evalf(n=10)) == '-1.831931188'
assert str(andre(-4, evaluate=False).evalf(n=10)) == '1.977889103'
assert str(andre(I, evaluate=False).evalf(n=10)) == '2.378417833 + 0.6343322845*I'
assert andre(x).rewrite(polylog) == \
(-I)**(x+1) * polylog(-x, I) + I**(x+1) * polylog(-x, -I)
assert andre(x).rewrite(zeta) == \
2 * gamma(x+1) / (2*pi)**(x+1) * \
(zeta(x+1, Rational(1,4)) - cos(pi*x) * zeta(x+1, Rational(3,4)))
@nocache_fail
def test_partition():
partition_nums = [1, 1, 2, 3, 5, 7, 11, 15, 22]
for n, p in enumerate(partition_nums):
assert partition(n) == p
x = Symbol('x')
y = Symbol('y', real=True)
m = Symbol('m', integer=True)
n = Symbol('n', integer=True, negative=True)
p = Symbol('p', integer=True, nonnegative=True)
assert partition(m).is_integer
assert not partition(m).is_negative
assert partition(m).is_nonnegative
assert partition(n).is_zero
assert partition(p).is_positive
assert partition(x).subs(x, 7) == 15
assert partition(y).subs(y, 8) == 22
raises(ValueError, lambda: partition(Rational(5, 4)))
def test__nT():
assert [_nT(i, j) for i in range(5) for j in range(i + 2)] == [
1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 2, 1, 1, 0]
check = [_nT(10, i) for i in range(11)]
assert check == [0, 1, 5, 8, 9, 7, 5, 3, 2, 1, 1]
assert all(type(i) is int for i in check)
assert _nT(10, 5) == 7
assert _nT(100, 98) == 2
assert _nT(100, 100) == 1
assert _nT(10, 3) == 8
def test_nC_nP_nT():
from sympy.utilities.iterables import (
multiset_permutations, multiset_combinations, multiset_partitions,
partitions, subsets, permutations)
from sympy.functions.combinatorial.numbers import (
nP, nC, nT, stirling, _stirling1, _stirling2, _multiset_histogram, _AOP_product)
from sympy.combinatorics.permutations import Permutation
from sympy.core.random import choice
c = string.ascii_lowercase
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(8):
check = nP(s, i)
tot += check
assert len(list(multiset_permutations(s, i))) == check
if u:
assert nP(len(s), i) == check
assert nP(s) == tot
except AssertionError:
print(s, i, 'failed perm test')
raise ValueError()
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(8):
check = nC(s, i)
tot += check
assert len(list(multiset_combinations(s, i))) == check
if u:
assert nC(len(s), i) == check
assert nC(s) == tot
if u:
assert nC(len(s)) == tot
except AssertionError:
print(s, i, 'failed combo test')
raise ValueError()
for i in range(1, 10):
tot = 0
for j in range(1, i + 2):
check = nT(i, j)
assert check.is_Integer
tot += check
assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check
assert nT(i) == tot
for i in range(1, 10):
tot = 0
for j in range(1, i + 2):
check = nT(range(i), j)
tot += check
assert len(list(multiset_partitions(list(range(i)), j))) == check
assert nT(range(i)) == tot
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(1, 8):
check = nT(s, i)
tot += check
assert len(list(multiset_partitions(s, i))) == check
if u:
assert nT(range(len(s)), i) == check
if u:
assert nT(range(len(s))) == tot
assert nT(s) == tot
except AssertionError:
print(s, i, 'failed partition test')
raise ValueError()
# tests for Stirling numbers of the first kind that are not tested in the
# above
assert [stirling(9, i, kind=1) for i in range(11)] == [
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0]
perms = list(permutations(range(4)))
assert [sum(1 for p in perms if Permutation(p).cycles == i)
for i in range(5)] == [0, 6, 11, 6, 1] == [
stirling(4, i, kind=1) for i in range(5)]
# http://oeis.org/A008275
assert [stirling(n, k, signed=1)
for n in range(10) for k in range(1, n + 1)] == [
1, -1,
1, 2, -3,
1, -6, 11, -6,
1, 24, -50, 35, -10,
1, -120, 274, -225, 85, -15,
1, 720, -1764, 1624, -735, 175, -21,
1, -5040, 13068, -13132, 6769, -1960, 322, -28,
1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1]
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
assert [stirling(n, k, kind=1)
for n in range(10) for k in range(n+1)] == [
1,
0, 1,
0, 1, 1,
0, 2, 3, 1,
0, 6, 11, 6, 1,
0, 24, 50, 35, 10, 1,
0, 120, 274, 225, 85, 15, 1,
0, 720, 1764, 1624, 735, 175, 21, 1,
0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1,
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1]
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
assert [stirling(n, k, kind=2)
for n in range(10) for k in range(n+1)] == [
1,
0, 1,
0, 1, 1,
0, 1, 3, 1,
0, 1, 7, 6, 1,
0, 1, 15, 25, 10, 1,
0, 1, 31, 90, 65, 15, 1,
0, 1, 63, 301, 350, 140, 21, 1,
0, 1, 127, 966, 1701, 1050, 266, 28, 1,
0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1]
assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0
raises(ValueError, lambda: stirling(-2, 2))
# Assertion that the return type is SymPy Integer.
assert isinstance(_stirling1(6, 3), Integer)
assert isinstance(_stirling2(6, 3), Integer)
def delta(p):
if len(p) == 1:
return oo
return min(abs(i[0] - i[1]) for i in subsets(p, 2))
parts = multiset_partitions(range(5), 3)
d = 2
assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) ==
stirling(5, 3, d=d) == 7)
# other coverage tests
assert nC('abb', 2) == nC('aab', 2) == 2
assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27
assert nP(3, 4) == 0
assert nP('aabc', 5) == 0
assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \
len(list(multiset_combinations('aabbccdd', 2))) == 10
assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24
assert nC(list('abcdd'), 4) == 4
assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5
assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7
assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa
assert dict(_AOP_product((4,1,1,1))) == {
0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1}
# the following was the first t that showed a problem in a previous form of
# the function, so it's not as random as it may appear
t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4)
assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000
raises(ValueError, lambda: _multiset_histogram({1:'a'}))
def test_PR_14617():
from sympy.functions.combinatorial.numbers import nT
for n in (0, []):
for k in (-1, 0, 1):
if k == 0:
assert nT(n, k) == 1
else:
assert nT(n, k) == 0
def test_issue_8496():
n = Symbol("n")
k = Symbol("k")
raises(TypeError, lambda: catalan(n, k))
def test_issue_8601():
n = Symbol('n', integer=True, negative=True)
assert catalan(n - 1) is S.Zero
assert catalan(Rational(-1, 2)) is S.ComplexInfinity
assert catalan(-S.One) == Rational(-1, 2)
c1 = catalan(-5.6).evalf()
assert str(c1) == '6.93334070531408e-5'
c2 = catalan(-35.4).evalf()
assert str(c2) == '-4.14189164517449e-24'
def test_motzkin():
assert motzkin.is_motzkin(4) == True
assert motzkin.is_motzkin(9) == True
assert motzkin.is_motzkin(10) == False
assert motzkin.find_motzkin_numbers_in_range(10,200) == [21, 51, 127]
assert motzkin.find_motzkin_numbers_in_range(10,400) == [21, 51, 127, 323]
assert motzkin.find_motzkin_numbers_in_range(10,1600) == [21, 51, 127, 323, 835]
assert motzkin.find_first_n_motzkins(5) == [1, 1, 2, 4, 9]
assert motzkin.find_first_n_motzkins(7) == [1, 1, 2, 4, 9, 21, 51]
assert motzkin.find_first_n_motzkins(10) == [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
raises(ValueError, lambda: motzkin.eval(77.58))
raises(ValueError, lambda: motzkin.eval(-8))
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(-2,7))
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(13,7))
raises(ValueError, lambda: motzkin.find_first_n_motzkins(112.8))
def test_nD_derangements():
from sympy.utilities.iterables import (partitions, multiset,
multiset_derangements, multiset_permutations)
from sympy.functions.combinatorial.numbers import nD
got = []
for i in partitions(8, k=4):
s = []
it = 0
for k, v in i.items():
for i in range(v):
s.extend([it]*k)
it += 1
ms = multiset(s)
c1 = sum(1 for i in multiset_permutations(s) if
all(i != j for i, j in zip(i, s)))
assert c1 == nD(ms) == nD(ms, 0) == nD(ms, 1)
v = [tuple(i) for i in multiset_derangements(s)]
c2 = len(v)
assert c2 == len(set(v))
assert c1 == c2
got.append(c1)
assert got == [1, 4, 6, 12, 24, 24, 61, 126, 315, 780, 297, 772,
2033, 5430, 14833]
assert nD('1112233456', brute=True) == nD('1112233456') == 16356
assert nD('') == nD([]) == nD({}) == 0
assert nD({1: 0}) == 0
raises(ValueError, lambda: nD({1: -1}))
assert nD('112') == 0
assert nD(i='112') == 0
assert [nD(n=i) for i in range(6)] == [0, 0, 1, 2, 9, 44]
assert nD((i for i in range(4))) == nD('0123') == 9
assert nD(m=(i for i in range(4))) == 3
assert nD(m={0: 1, 1: 1, 2: 1, 3: 1}) == 3
assert nD(m=[0, 1, 2, 3]) == 3
raises(TypeError, lambda: nD(m=0))
raises(TypeError, lambda: nD(-1))
assert nD({-1: 1, -2: 1}) == 1
assert nD(m={0: 3}) == 0
raises(ValueError, lambda: nD(i='123', n=3))
raises(ValueError, lambda: nD(i='123', m=(1,2)))
raises(ValueError, lambda: nD(n=0, m=(1,2)))
raises(ValueError, lambda: nD({1: -1}))
raises(ValueError, lambda: nD(m={-1: 1, 2: 1}))
raises(ValueError, lambda: nD(m={1: -1, 2: 1}))
raises(ValueError, lambda: nD(m=[-1, 2]))
raises(TypeError, lambda: nD({1: x}))
raises(TypeError, lambda: nD(m={1: x}))
raises(TypeError, lambda: nD(m={x: 1}))
|
83b144e02f1df01bb2640a7271b41bab9b8fb3cd5ec91ff861dc0fe80d8fd467 | from sympy.calculus.accumulationbounds import AccumBounds
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.integers import (ceiling, floor, frac)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin, cos, tan
from sympy.core.expr import unchanged
from sympy.testing.pytest import XFAIL
x = Symbol('x')
i = Symbol('i', imaginary=True)
y = Symbol('y', real=True)
k, n = symbols('k,n', integer=True)
def test_floor():
assert floor(nan) is nan
assert floor(oo) is oo
assert floor(-oo) is -oo
assert floor(zoo) is zoo
assert floor(0) == 0
assert floor(1) == 1
assert floor(-1) == -1
assert floor(E) == 2
assert floor(-E) == -3
assert floor(2*E) == 5
assert floor(-2*E) == -6
assert floor(pi) == 3
assert floor(-pi) == -4
assert floor(S.Half) == 0
assert floor(Rational(-1, 2)) == -1
assert floor(Rational(7, 3)) == 2
assert floor(Rational(-7, 3)) == -3
assert floor(-Rational(7, 3)) == -3
assert floor(Float(17.0)) == 17
assert floor(-Float(17.0)) == -17
assert floor(Float(7.69)) == 7
assert floor(-Float(7.69)) == -8
assert floor(I) == I
assert floor(-I) == -I
e = floor(i)
assert e.func is floor and e.args[0] == i
assert floor(oo*I) == oo*I
assert floor(-oo*I) == -oo*I
assert floor(exp(I*pi/4)*oo) == exp(I*pi/4)*oo
assert floor(2*I) == 2*I
assert floor(-2*I) == -2*I
assert floor(I/2) == 0
assert floor(-I/2) == -I
assert floor(E + 17) == 19
assert floor(pi + 2) == 5
assert floor(E + pi) == 5
assert floor(I + pi) == 3 + I
assert floor(floor(pi)) == 3
assert floor(floor(y)) == floor(y)
assert floor(floor(x)) == floor(x)
assert unchanged(floor, x)
assert unchanged(floor, 2*x)
assert unchanged(floor, k*x)
assert floor(k) == k
assert floor(2*k) == 2*k
assert floor(k*n) == k*n
assert unchanged(floor, k/2)
assert unchanged(floor, x + y)
assert floor(x + 3) == floor(x) + 3
assert floor(x + k) == floor(x) + k
assert floor(y + 3) == floor(y) + 3
assert floor(y + k) == floor(y) + k
assert floor(3 + I*y + pi) == 6 + floor(y)*I
assert floor(k + n) == k + n
assert unchanged(floor, x*I)
assert floor(k*I) == k*I
assert floor(Rational(23, 10) - E*I) == 2 - 3*I
assert floor(sin(1)) == 0
assert floor(sin(-1)) == -1
assert floor(exp(2)) == 7
assert floor(log(8)/log(2)) != 2
assert int(floor(log(8)/log(2)).evalf(chop=True)) == 3
assert floor(factorial(50)/exp(1)) == \
11188719610782480504630258070757734324011354208865721592720336800
assert (floor(y) < y) == False
assert (floor(y) <= y) == True
assert (floor(y) > y) == False
assert (floor(y) >= y) == False
assert (floor(x) <= x).is_Relational # x could be non-real
assert (floor(x) > x).is_Relational
assert (floor(x) <= y).is_Relational # arg is not same as rhs
assert (floor(x) > y).is_Relational
assert (floor(y) <= oo) == True
assert (floor(y) < oo) == True
assert (floor(y) >= -oo) == True
assert (floor(y) > -oo) == True
assert floor(y).rewrite(frac) == y - frac(y)
assert floor(y).rewrite(ceiling) == -ceiling(-y)
assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi)
assert floor(y).rewrite(frac).subs(y, E) == floor(E)
assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E)
assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi)
assert Eq(floor(y), y - frac(y))
assert Eq(floor(y), -ceiling(-y))
neg = Symbol('neg', negative=True)
nn = Symbol('nn', nonnegative=True)
pos = Symbol('pos', positive=True)
np = Symbol('np', nonpositive=True)
assert (floor(neg) < 0) == True
assert (floor(neg) <= 0) == True
assert (floor(neg) > 0) == False
assert (floor(neg) >= 0) == False
assert (floor(neg) <= -1) == True
assert (floor(neg) >= -3) == (neg >= -3)
assert (floor(neg) < 5) == (neg < 5)
assert (floor(nn) < 0) == False
assert (floor(nn) >= 0) == True
assert (floor(pos) < 0) == False
assert (floor(pos) <= 0) == (pos < 1)
assert (floor(pos) > 0) == (pos >= 1)
assert (floor(pos) >= 0) == True
assert (floor(pos) >= 3) == (pos >= 3)
assert (floor(np) <= 0) == True
assert (floor(np) > 0) == False
assert floor(neg).is_negative == True
assert floor(neg).is_nonnegative == False
assert floor(nn).is_negative == False
assert floor(nn).is_nonnegative == True
assert floor(pos).is_negative == False
assert floor(pos).is_nonnegative == True
assert floor(np).is_negative is None
assert floor(np).is_nonnegative is None
assert (floor(7, evaluate=False) >= 7) == True
assert (floor(7, evaluate=False) > 7) == False
assert (floor(7, evaluate=False) <= 7) == True
assert (floor(7, evaluate=False) < 7) == False
assert (floor(7, evaluate=False) >= 6) == True
assert (floor(7, evaluate=False) > 6) == True
assert (floor(7, evaluate=False) <= 6) == False
assert (floor(7, evaluate=False) < 6) == False
assert (floor(7, evaluate=False) >= 8) == False
assert (floor(7, evaluate=False) > 8) == False
assert (floor(7, evaluate=False) <= 8) == True
assert (floor(7, evaluate=False) < 8) == True
assert (floor(x) <= 5.5) == Le(floor(x), 5.5, evaluate=False)
assert (floor(x) >= -3.2) == Ge(floor(x), -3.2, evaluate=False)
assert (floor(x) < 2.9) == Lt(floor(x), 2.9, evaluate=False)
assert (floor(x) > -1.7) == Gt(floor(x), -1.7, evaluate=False)
assert (floor(y) <= 5.5) == (y < 6)
assert (floor(y) >= -3.2) == (y >= -3)
assert (floor(y) < 2.9) == (y < 3)
assert (floor(y) > -1.7) == (y >= -1)
assert (floor(y) <= n) == (y < n + 1)
assert (floor(y) >= n) == (y >= n)
assert (floor(y) < n) == (y < n)
assert (floor(y) > n) == (y >= n + 1)
def test_ceiling():
assert ceiling(nan) is nan
assert ceiling(oo) is oo
assert ceiling(-oo) is -oo
assert ceiling(zoo) is zoo
assert ceiling(0) == 0
assert ceiling(1) == 1
assert ceiling(-1) == -1
assert ceiling(E) == 3
assert ceiling(-E) == -2
assert ceiling(2*E) == 6
assert ceiling(-2*E) == -5
assert ceiling(pi) == 4
assert ceiling(-pi) == -3
assert ceiling(S.Half) == 1
assert ceiling(Rational(-1, 2)) == 0
assert ceiling(Rational(7, 3)) == 3
assert ceiling(-Rational(7, 3)) == -2
assert ceiling(Float(17.0)) == 17
assert ceiling(-Float(17.0)) == -17
assert ceiling(Float(7.69)) == 8
assert ceiling(-Float(7.69)) == -7
assert ceiling(I) == I
assert ceiling(-I) == -I
e = ceiling(i)
assert e.func is ceiling and e.args[0] == i
assert ceiling(oo*I) == oo*I
assert ceiling(-oo*I) == -oo*I
assert ceiling(exp(I*pi/4)*oo) == exp(I*pi/4)*oo
assert ceiling(2*I) == 2*I
assert ceiling(-2*I) == -2*I
assert ceiling(I/2) == I
assert ceiling(-I/2) == 0
assert ceiling(E + 17) == 20
assert ceiling(pi + 2) == 6
assert ceiling(E + pi) == 6
assert ceiling(I + pi) == I + 4
assert ceiling(ceiling(pi)) == 4
assert ceiling(ceiling(y)) == ceiling(y)
assert ceiling(ceiling(x)) == ceiling(x)
assert unchanged(ceiling, x)
assert unchanged(ceiling, 2*x)
assert unchanged(ceiling, k*x)
assert ceiling(k) == k
assert ceiling(2*k) == 2*k
assert ceiling(k*n) == k*n
assert unchanged(ceiling, k/2)
assert unchanged(ceiling, x + y)
assert ceiling(x + 3) == ceiling(x) + 3
assert ceiling(x + k) == ceiling(x) + k
assert ceiling(y + 3) == ceiling(y) + 3
assert ceiling(y + k) == ceiling(y) + k
assert ceiling(3 + pi + y*I) == 7 + ceiling(y)*I
assert ceiling(k + n) == k + n
assert unchanged(ceiling, x*I)
assert ceiling(k*I) == k*I
assert ceiling(Rational(23, 10) - E*I) == 3 - 2*I
assert ceiling(sin(1)) == 1
assert ceiling(sin(-1)) == 0
assert ceiling(exp(2)) == 8
assert ceiling(-log(8)/log(2)) != -2
assert int(ceiling(-log(8)/log(2)).evalf(chop=True)) == -3
assert ceiling(factorial(50)/exp(1)) == \
11188719610782480504630258070757734324011354208865721592720336801
assert (ceiling(y) >= y) == True
assert (ceiling(y) > y) == False
assert (ceiling(y) < y) == False
assert (ceiling(y) <= y) == False
assert (ceiling(x) >= x).is_Relational # x could be non-real
assert (ceiling(x) < x).is_Relational
assert (ceiling(x) >= y).is_Relational # arg is not same as rhs
assert (ceiling(x) < y).is_Relational
assert (ceiling(y) >= -oo) == True
assert (ceiling(y) > -oo) == True
assert (ceiling(y) <= oo) == True
assert (ceiling(y) < oo) == True
assert ceiling(y).rewrite(floor) == -floor(-y)
assert ceiling(y).rewrite(frac) == y + frac(-y)
assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi)
assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E)
assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi)
assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E)
assert Eq(ceiling(y), y + frac(-y))
assert Eq(ceiling(y), -floor(-y))
neg = Symbol('neg', negative=True)
nn = Symbol('nn', nonnegative=True)
pos = Symbol('pos', positive=True)
np = Symbol('np', nonpositive=True)
assert (ceiling(neg) <= 0) == True
assert (ceiling(neg) < 0) == (neg <= -1)
assert (ceiling(neg) > 0) == False
assert (ceiling(neg) >= 0) == (neg > -1)
assert (ceiling(neg) > -3) == (neg > -3)
assert (ceiling(neg) <= 10) == (neg <= 10)
assert (ceiling(nn) < 0) == False
assert (ceiling(nn) >= 0) == True
assert (ceiling(pos) < 0) == False
assert (ceiling(pos) <= 0) == False
assert (ceiling(pos) > 0) == True
assert (ceiling(pos) >= 0) == True
assert (ceiling(pos) >= 1) == True
assert (ceiling(pos) > 5) == (pos > 5)
assert (ceiling(np) <= 0) == True
assert (ceiling(np) > 0) == False
assert ceiling(neg).is_positive == False
assert ceiling(neg).is_nonpositive == True
assert ceiling(nn).is_positive is None
assert ceiling(nn).is_nonpositive is None
assert ceiling(pos).is_positive == True
assert ceiling(pos).is_nonpositive == False
assert ceiling(np).is_positive == False
assert ceiling(np).is_nonpositive == True
assert (ceiling(7, evaluate=False) >= 7) == True
assert (ceiling(7, evaluate=False) > 7) == False
assert (ceiling(7, evaluate=False) <= 7) == True
assert (ceiling(7, evaluate=False) < 7) == False
assert (ceiling(7, evaluate=False) >= 6) == True
assert (ceiling(7, evaluate=False) > 6) == True
assert (ceiling(7, evaluate=False) <= 6) == False
assert (ceiling(7, evaluate=False) < 6) == False
assert (ceiling(7, evaluate=False) >= 8) == False
assert (ceiling(7, evaluate=False) > 8) == False
assert (ceiling(7, evaluate=False) <= 8) == True
assert (ceiling(7, evaluate=False) < 8) == True
assert (ceiling(x) <= 5.5) == Le(ceiling(x), 5.5, evaluate=False)
assert (ceiling(x) >= -3.2) == Ge(ceiling(x), -3.2, evaluate=False)
assert (ceiling(x) < 2.9) == Lt(ceiling(x), 2.9, evaluate=False)
assert (ceiling(x) > -1.7) == Gt(ceiling(x), -1.7, evaluate=False)
assert (ceiling(y) <= 5.5) == (y <= 5)
assert (ceiling(y) >= -3.2) == (y > -4)
assert (ceiling(y) < 2.9) == (y <= 2)
assert (ceiling(y) > -1.7) == (y > -2)
assert (ceiling(y) <= n) == (y <= n)
assert (ceiling(y) >= n) == (y > n - 1)
assert (ceiling(y) < n) == (y <= n - 1)
assert (ceiling(y) > n) == (y > n)
def test_frac():
assert isinstance(frac(x), frac)
assert frac(oo) == AccumBounds(0, 1)
assert frac(-oo) == AccumBounds(0, 1)
assert frac(zoo) is nan
assert frac(n) == 0
assert frac(nan) is nan
assert frac(Rational(4, 3)) == Rational(1, 3)
assert frac(-Rational(4, 3)) == Rational(2, 3)
assert frac(Rational(-4, 3)) == Rational(2, 3)
r = Symbol('r', real=True)
assert frac(I*r) == I*frac(r)
assert frac(1 + I*r) == I*frac(r)
assert frac(0.5 + I*r) == 0.5 + I*frac(r)
assert frac(n + I*r) == I*frac(r)
assert frac(n + I*k) == 0
assert unchanged(frac, x + I*x)
assert frac(x + I*n) == frac(x)
assert frac(x).rewrite(floor) == x - floor(x)
assert frac(x).rewrite(ceiling) == x + ceiling(-x)
assert frac(y).rewrite(floor).subs(y, pi) == frac(pi)
assert frac(y).rewrite(floor).subs(y, -E) == frac(-E)
assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi)
assert frac(y).rewrite(ceiling).subs(y, E) == frac(E)
assert Eq(frac(y), y - floor(y))
assert Eq(frac(y), y + ceiling(-y))
r = Symbol('r', real=True)
p_i = Symbol('p_i', integer=True, positive=True)
n_i = Symbol('p_i', integer=True, negative=True)
np_i = Symbol('np_i', integer=True, nonpositive=True)
nn_i = Symbol('nn_i', integer=True, nonnegative=True)
p_r = Symbol('p_r', positive=True)
n_r = Symbol('n_r', negative=True)
np_r = Symbol('np_r', real=True, nonpositive=True)
nn_r = Symbol('nn_r', real=True, nonnegative=True)
# Real frac argument, integer rhs
assert frac(r) <= p_i
assert not frac(r) <= n_i
assert (frac(r) <= np_i).has(Le)
assert (frac(r) <= nn_i).has(Le)
assert frac(r) < p_i
assert not frac(r) < n_i
assert not frac(r) < np_i
assert (frac(r) < nn_i).has(Lt)
assert not frac(r) >= p_i
assert frac(r) >= n_i
assert frac(r) >= np_i
assert (frac(r) >= nn_i).has(Ge)
assert not frac(r) > p_i
assert frac(r) > n_i
assert (frac(r) > np_i).has(Gt)
assert (frac(r) > nn_i).has(Gt)
assert not Eq(frac(r), p_i)
assert not Eq(frac(r), n_i)
assert Eq(frac(r), np_i).has(Eq)
assert Eq(frac(r), nn_i).has(Eq)
assert Ne(frac(r), p_i)
assert Ne(frac(r), n_i)
assert Ne(frac(r), np_i).has(Ne)
assert Ne(frac(r), nn_i).has(Ne)
# Real frac argument, real rhs
assert (frac(r) <= p_r).has(Le)
assert not frac(r) <= n_r
assert (frac(r) <= np_r).has(Le)
assert (frac(r) <= nn_r).has(Le)
assert (frac(r) < p_r).has(Lt)
assert not frac(r) < n_r
assert not frac(r) < np_r
assert (frac(r) < nn_r).has(Lt)
assert (frac(r) >= p_r).has(Ge)
assert frac(r) >= n_r
assert frac(r) >= np_r
assert (frac(r) >= nn_r).has(Ge)
assert (frac(r) > p_r).has(Gt)
assert frac(r) > n_r
assert (frac(r) > np_r).has(Gt)
assert (frac(r) > nn_r).has(Gt)
assert not Eq(frac(r), n_r)
assert Eq(frac(r), p_r).has(Eq)
assert Eq(frac(r), np_r).has(Eq)
assert Eq(frac(r), nn_r).has(Eq)
assert Ne(frac(r), p_r).has(Ne)
assert Ne(frac(r), n_r)
assert Ne(frac(r), np_r).has(Ne)
assert Ne(frac(r), nn_r).has(Ne)
# Real frac argument, +/- oo rhs
assert frac(r) < oo
assert frac(r) <= oo
assert not frac(r) > oo
assert not frac(r) >= oo
assert not frac(r) < -oo
assert not frac(r) <= -oo
assert frac(r) > -oo
assert frac(r) >= -oo
assert frac(r) < 1
assert frac(r) <= 1
assert not frac(r) > 1
assert not frac(r) >= 1
assert not frac(r) < 0
assert (frac(r) <= 0).has(Le)
assert (frac(r) > 0).has(Gt)
assert frac(r) >= 0
# Some test for numbers
assert frac(r) <= sqrt(2)
assert (frac(r) <= sqrt(3) - sqrt(2)).has(Le)
assert not frac(r) <= sqrt(2) - sqrt(3)
assert not frac(r) >= sqrt(2)
assert (frac(r) >= sqrt(3) - sqrt(2)).has(Ge)
assert frac(r) >= sqrt(2) - sqrt(3)
assert not Eq(frac(r), sqrt(2))
assert Eq(frac(r), sqrt(3) - sqrt(2)).has(Eq)
assert not Eq(frac(r), sqrt(2) - sqrt(3))
assert Ne(frac(r), sqrt(2))
assert Ne(frac(r), sqrt(3) - sqrt(2)).has(Ne)
assert Ne(frac(r), sqrt(2) - sqrt(3))
assert frac(p_i, evaluate=False).is_zero
assert frac(p_i, evaluate=False).is_finite
assert frac(p_i, evaluate=False).is_integer
assert frac(p_i, evaluate=False).is_real
assert frac(r).is_finite
assert frac(r).is_real
assert frac(r).is_zero is None
assert frac(r).is_integer is None
assert frac(oo).is_finite
assert frac(oo).is_real
def test_series():
x, y = symbols('x,y')
assert floor(x).nseries(x, y, 100) == floor(y)
assert ceiling(x).nseries(x, y, 100) == ceiling(y)
assert floor(x).nseries(x, pi, 100) == 3
assert ceiling(x).nseries(x, pi, 100) == 4
assert floor(x).nseries(x, 0, 100) == 0
assert ceiling(x).nseries(x, 0, 100) == 1
assert floor(-x).nseries(x, 0, 100) == -1
assert ceiling(-x).nseries(x, 0, 100) == 0
def test_issue_14355():
# This test checks the leading term and series for the floor and ceil
# function when arg0 evaluates to S.NaN.
assert floor((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = 1) == -2
assert floor((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = -1) == -1
assert floor((cos(x) - 1)/x).as_leading_term(x, cdir = 1) == -1
assert floor((cos(x) - 1)/x).as_leading_term(x, cdir = -1) == 0
assert floor(sin(x)/x).as_leading_term(x, cdir = 1) == 0
assert floor(sin(x)/x).as_leading_term(x, cdir = -1) == 0
assert floor(-tan(x)/x).as_leading_term(x, cdir = 1) == -2
assert floor(-tan(x)/x).as_leading_term(x, cdir = -1) == -2
assert floor(sin(x)/x/3).as_leading_term(x, cdir = 1) == 0
assert floor(sin(x)/x/3).as_leading_term(x, cdir = -1) == 0
assert ceiling((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = 1) == -1
assert ceiling((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = -1) == 0
assert ceiling((cos(x) - 1)/x).as_leading_term(x, cdir = 1) == 0
assert ceiling((cos(x) - 1)/x).as_leading_term(x, cdir = -1) == 1
assert ceiling(sin(x)/x).as_leading_term(x, cdir = 1) == 1
assert ceiling(sin(x)/x).as_leading_term(x, cdir = -1) == 1
assert ceiling(-tan(x)/x).as_leading_term(x, cdir = 1) == -1
assert ceiling(-tan(x)/x).as_leading_term(x, cdir = 1) == -1
assert ceiling(sin(x)/x/3).as_leading_term(x, cdir = 1) == 1
assert ceiling(sin(x)/x/3).as_leading_term(x, cdir = -1) == 1
# test for series
assert floor(sin(x)/x).series(x, 0, 100, cdir = 1) == 0
assert floor(sin(x)/x).series(x, 0, 100, cdir = 1) == 0
assert floor((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = 1) == -2
assert floor((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = -1) == -1
assert ceiling(sin(x)/x).series(x, 0, 100, cdir = 1) == 1
assert ceiling(sin(x)/x).series(x, 0, 100, cdir = -1) == 1
assert ceiling((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = 1) == -1
assert ceiling((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = -1) == 0
def test_frac_leading_term():
assert frac(x).as_leading_term(x) == x
assert frac(x).as_leading_term(x, cdir = 1) == x
assert frac(x).as_leading_term(x, cdir = -1) == 1
assert frac(x + S.Half).as_leading_term(x, cdir = 1) == S.Half
assert frac(x + S.Half).as_leading_term(x, cdir = -1) == S.Half
assert frac(-2*x + 1).as_leading_term(x, cdir = 1) == S.One
assert frac(-2*x + 1).as_leading_term(x, cdir = -1) == -2*x
assert frac(sin(x) + 5).as_leading_term(x, cdir = 1) == x
assert frac(sin(x) + 5).as_leading_term(x, cdir = -1) == S.One
assert frac(sin(x**2) + 5).as_leading_term(x, cdir = 1) == x**2
assert frac(sin(x**2) + 5).as_leading_term(x, cdir = -1) == x**2
@XFAIL
def test_issue_4149():
assert floor(3 + pi*I + y*I) == 3 + floor(pi + y)*I
assert floor(3*I + pi*I + y*I) == floor(3 + pi + y)*I
assert floor(3 + E + pi*I + y*I) == 5 + floor(pi + y)*I
def test_issue_21651():
k = Symbol('k', positive=True, integer=True)
exp = 2*2**(-k)
assert isinstance(floor(exp), floor)
def test_issue_11207():
assert floor(floor(x)) == floor(x)
assert floor(ceiling(x)) == ceiling(x)
assert ceiling(floor(x)) == floor(x)
assert ceiling(ceiling(x)) == ceiling(x)
def test_nested_floor_ceiling():
assert floor(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y)
assert ceiling(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y)
assert floor(ceiling(-floor(x**Rational(7, 2)/y))) == -floor(x**Rational(7, 2)/y)
assert -ceiling(-ceiling(floor(x)/y)) == ceiling(floor(x)/y)
def test_issue_18689():
assert floor(floor(floor(x)) + 3) == floor(x) + 3
assert ceiling(ceiling(ceiling(x)) + 1) == ceiling(x) + 1
assert ceiling(ceiling(floor(x)) + 3) == floor(x) + 3
def test_issue_18421():
assert floor(float(0)) is S.Zero
assert ceiling(float(0)) is S.Zero
|
6d0f8c64a29deb22794cbc65fef9319dddfc479697be6cb780d726bf959b45ab | from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import unchanged
from sympy.core.function import (Function, diff, expand)
from sympy.core.mul import Mul
from sympy.core.numbers import (Float, I, Rational, oo, pi, zoo)
from sympy.core.relational import (Eq, Ge, Gt, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, transpose)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import (Piecewise,
piecewise_fold, piecewise_exclusive, Undefined, ExprCondPair)
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.integrals.integrals import (Integral, integrate)
from sympy.logic.boolalg import (And, ITE, Not, Or)
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.printing import srepr
from sympy.sets.contains import Contains
from sympy.sets.sets import Interval
from sympy.solvers.solvers import solve
from sympy.testing.pytest import raises, slow
from sympy.utilities.lambdify import lambdify
a, b, c, d, x, y = symbols('a:d, x, y')
z = symbols('z', nonzero=True)
def test_piecewise1():
# Test canonicalization
assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True))
assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1),
ExprCondPair(0, True))
assert Piecewise((x, x < 1), (0, True), (1, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \
Piecewise((x, x < 1))
assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \
Piecewise((x, Or(x < 1, x < 2)), (0, True))
assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x
assert Piecewise((x, True)) == x
# Explicitly constructed empty Piecewise not accepted
raises(TypeError, lambda: Piecewise())
# False condition is never retained
assert Piecewise((2*x, x < 0), (x, False)) == \
Piecewise((2*x, x < 0), (x, False), evaluate=False) == \
Piecewise((2*x, x < 0))
assert Piecewise((x, False)) == Undefined
raises(TypeError, lambda: Piecewise(x))
assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False
raises(TypeError, lambda: Piecewise((x, 2)))
raises(TypeError, lambda: Piecewise((x, x**2)))
raises(TypeError, lambda: Piecewise(([1], True)))
assert Piecewise(((1, 2), True)) == Tuple(1, 2)
cond = (Piecewise((1, x < 0), (2, True)) < y)
assert Piecewise((1, cond)
) == Piecewise((1, ITE(x < 0, y > 1, y > 2)))
assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))
) == Piecewise((1, x > 0), (2, x > -1))
assert Piecewise((1, x <= 0), (2, (x < 0) & (x > -1))
) == Piecewise((1, x <= 0))
# test for supporting Contains in Piecewise
pwise = Piecewise(
(1, And(x <= 6, x > 1, Contains(x, S.Integers))),
(0, True))
assert pwise.subs(x, pi) == 0
assert pwise.subs(x, 2) == 1
assert pwise.subs(x, 7) == 0
# Test subs
p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0))
p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0))
assert p.subs(x, x**2) == p_x2
assert p.subs(x, -5) == -1
assert p.subs(x, -1) == 1
assert p.subs(x, 1) == log(1)
# More subs tests
p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi))
p3 = Piecewise((1, Eq(x, 0)), (1/x, True))
p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2))
assert p2.subs(x, 2) == 1
assert p2.subs(x, 4) == -1
assert p2.subs(x, 10) == 0
assert p3.subs(x, 0.0) == 1
assert p4.subs(x, 0.0) == 1
f, g, h = symbols('f,g,h', cls=Function)
pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1))
pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1))
assert pg.subs(g, f) == pf
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0
assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1
assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1
assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \
Piecewise((1, Eq(exp(z), cos(z))), (0, True))
p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True))
assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True))
assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)
).subs(x, 1) == Piecewise((-1, y < 1), (2, True))
assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1
p6 = Piecewise((x, x > 0))
n = symbols('n', negative=True)
assert p6.subs(x, n) == Undefined
# Test evalf
assert p.evalf() == Piecewise((-1.0, x < -1), (x**2, x < 0), (log(x), True))
assert p.evalf(subs={x: -2}) == -1
assert p.evalf(subs={x: -1}) == 1
assert p.evalf(subs={x: 1}) == log(1)
assert p6.evalf(subs={x: -5}) == Undefined
# Test doit
f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1))
assert f_int.doit() == Piecewise( (S.Half, x < 1) )
# Test differentiation
f = x
fp = x*p
dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0))
fp_dx = x*dp + p
assert diff(p, x) == dp
assert diff(f*p, x) == fp_dx
# Test simple arithmetic
assert x*p == fp
assert x*p + p == p + x*p
assert p + f == f + p
assert p + dp == dp + p
assert p - dp == -(dp - p)
# Test power
dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0))
assert dp**2 == dp2
# Test _eval_interval
f1 = x*y + 2
f2 = x*y**2 + 3
peval = Piecewise((f1, x < 0), (f2, x > 0))
peval_interval = f1.subs(
x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0)
assert peval._eval_interval(x, 0, 0) == 0
assert peval._eval_interval(x, -1, 1) == peval_interval
peval2 = Piecewise((f1, x < 0), (f2, True))
assert peval2._eval_interval(x, 0, 0) == 0
assert peval2._eval_interval(x, 1, -1) == -peval_interval
assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1)
assert peval2._eval_interval(x, -1, 1) == peval_interval
assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0)
assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1)
# Test integration
assert p.integrate() == Piecewise(
(-x, x < -1),
(x**3/3 + Rational(4, 3), x < 0),
(x*log(x) - x + Rational(4, 3), True))
p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
assert integrate(p, (x, -2, 2)) == Rational(5, 6)
assert integrate(p, (x, 2, -2)) == Rational(-5, 6)
p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True))
assert integrate(p, (x, -oo, oo)) == 2
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
assert integrate(p, (x, -2, 2)) == Undefined
# Test commutativity
assert isinstance(p, Piecewise) and p.is_commutative is True
def test_piecewise_free_symbols():
f = Piecewise((x, a < 0), (y, True))
assert f.free_symbols == {x, y, a}
def test_piecewise_integrate1():
x, y = symbols('x y', real=True)
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
assert integrate(f, (x, -2, 2)) == Rational(14, 3)
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
assert integrate(g, (x, -2, 5)) == Rational(43, 6)
assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2))
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
assert integrate(g, (x, -2, 5)) == Rational(-701, 6)
assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True))
g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True))
assert integrate(g, (x, -2, 2)) == Rational(28, 3)
assert integrate(g, (x, -2, 5)) == Rational(-673, 6)
def test_piecewise_integrate1b():
g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0))
assert integrate(g, (x, -1, 1)) == 0
g = Piecewise((1, x - y < 0), (0, True))
assert integrate(g, (y, -oo, 0)) == -Min(0, x)
assert g.subs(x, -3).integrate((y, -oo, 0)) == 3
assert integrate(g, (y, 0, -oo)) == Min(0, x)
assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo
assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42
assert integrate(g, (y, -oo, oo)) == -x + oo
g = Piecewise((0, x < 0), (x, x <= 1), (1, True))
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
for yy in (-1, S.Half, 2):
assert g.integrate((x, yy, 1)) == gy1.subs(y, yy)
assert g.integrate((x, 1, yy)) == g1y.subs(y, yy)
assert gy1 == Piecewise(
(-Min(1, Max(0, y))**2/2 + S.Half, y < 1),
(-y + 1, True))
assert g1y == Piecewise(
(Min(1, Max(0, y))**2/2 - S.Half, y < 1),
(y - 1, True))
@slow
def test_piecewise_integrate1ca():
y = symbols('y', real=True)
g = Piecewise(
(1 - x, Interval(0, 1).contains(x)),
(1 + x, Interval(-1, 0).contains(x)),
(0, True)
)
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
assert piecewise_fold(gy1.rewrite(Piecewise)
).simplify() == Piecewise(
(1, y <= -1),
(-y**2/2 - y + S.Half, y <= 0),
(y**2/2 - y + S.Half, y < 1),
(0, True))
assert piecewise_fold(g1y.rewrite(Piecewise)
).simplify() == Piecewise(
(-1, y <= -1),
(y**2/2 + y - S.Half, y <= 0),
(-y**2/2 + y - S.Half, y < 1),
(0, True))
assert gy1 == Piecewise(
(
-Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
Min(1, Max(0, y))**2 + S.Half, y < 1),
(0, True)
)
assert g1y == Piecewise(
(
Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
Min(1, Max(0, y))**2 - S.Half, y < 1),
(0, True))
@slow
def test_piecewise_integrate1cb():
y = symbols('y', real=True)
g = Piecewise(
(0, Or(x <= -1, x >= 1)),
(1 - x, x > 0),
(1 + x, True)
)
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
assert piecewise_fold(gy1.rewrite(Piecewise)
).simplify() == Piecewise(
(1, y <= -1),
(-y**2/2 - y + S.Half, y <= 0),
(y**2/2 - y + S.Half, y < 1),
(0, True))
assert piecewise_fold(g1y.rewrite(Piecewise)
).simplify() == Piecewise(
(-1, y <= -1),
(y**2/2 + y - S.Half, y <= 0),
(-y**2/2 + y - S.Half, y < 1),
(0, True))
# g1y and gy1 should simplify if the condition that y < 1
# is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y)
assert gy1 == Piecewise(
(
-Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
Min(1, Max(0, y))**2 + S.Half, y < 1),
(0, True)
)
assert g1y == Piecewise(
(
Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
Min(1, Max(0, y))**2 - S.Half, y < 1),
(0, True))
def test_piecewise_integrate2():
from itertools import permutations
lim = Tuple(x, c, d)
p = Piecewise((1, x < a), (2, x > b), (3, True))
q = p.integrate(lim)
assert q == Piecewise(
(-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d),
(-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True))
for v in permutations((1, 2, 3, 4)):
r = dict(zip((a, b, c, d), v))
assert p.subs(r).integrate(lim.subs(r)) == q.subs(r)
def test_meijer_bypass():
# totally bypass meijerg machinery when dealing
# with Piecewise in integrate
assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3
def test_piecewise_integrate3_inequality_conditions():
from sympy.utilities.iterables import cartes
lim = (x, 0, 5)
# set below includes two pts below range, 2 pts in range,
# 2 pts above range, and the boundaries
N = (-2, -1, 0, 1, 2, 5, 6, 7)
p = Piecewise((1, x > a), (2, x > b), (0, True))
ans = p.integrate(lim)
for i, j in cartes(N, repeat=2):
reps = dict(zip((a, b), (i, j)))
assert ans.subs(reps) == p.subs(reps).integrate(lim)
assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1
p = Piecewise((1, x > a), (2, x < b), (0, True))
ans = p.integrate(lim)
for i, j in cartes(N, repeat=2):
reps = dict(zip((a, b), (i, j)))
assert ans.subs(reps) == p.subs(reps).integrate(lim)
# delete old tests that involved c1 and c2 since those
# reduce to the above except that a value of 0 was used
# for two expressions whereas the above uses 3 different
# values
@slow
def test_piecewise_integrate4_symbolic_conditions():
a = Symbol('a', real=True)
b = Symbol('b', real=True)
x = Symbol('x', real=True)
y = Symbol('y', real=True)
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
p1 = Piecewise((0, x < a), (0, x > b), (1, True))
p2 = Piecewise((0, x > b), (0, x < a), (1, True))
p3 = Piecewise((0, x < a), (1, x < b), (0, True))
p4 = Piecewise((0, x > b), (1, x > a), (0, True))
p5 = Piecewise((1, And(a < x, x < b)), (0, True))
# check values of a=1, b=3 (and reversed) with values
# of y of 0, 1, 2, 3, 4
lim = Tuple(x, -oo, y)
for p in (p0, p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a: 3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
lim = Tuple(x, y, oo)
for p in (p0, p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a:3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
ans = Piecewise(
(0, x <= Min(a, b)),
(x - Min(a, b), x <= b),
(b - Min(a, b), True))
for i in (p0, p1, p2, p4):
assert i.integrate(x) == ans
assert p3.integrate(x) == Piecewise(
(0, x < a),
(-a + x, x <= Max(a, b)),
(-a + Max(a, b), True))
assert p5.integrate(x) == Piecewise(
(0, x <= a),
(-a + x, x <= Max(a, b)),
(-a + Max(a, b), True))
p1 = Piecewise((0, x < a), (0.5, x > b), (1, True))
p2 = Piecewise((0.5, x > b), (0, x < a), (1, True))
p3 = Piecewise((0, x < a), (1, x < b), (0.5, True))
p4 = Piecewise((0.5, x > b), (1, x > a), (0, True))
p5 = Piecewise((1, And(a < x, x < b)), (0.5, x > b), (0, True))
# check values of a=1, b=3 (and reversed) with values
# of y of 0, 1, 2, 3, 4
lim = Tuple(x, -oo, y)
for p in (p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a: 3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
def test_piecewise_integrate5_independent_conditions():
p = Piecewise((0, Eq(y, 0)), (x*y, True))
assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True))
def test_issue_22917():
p = (Piecewise((0, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
(Piecewise((0, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
(2 * Piecewise((0, x - y > 1), (y, True)), True)), True))
+ 2 * Piecewise((1, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
(Piecewise((1, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
(2 * Piecewise((1, x - y > 1), (x, True)), True)), True)))
assert piecewise_fold(p) == Piecewise((2, (x - y > S.Half) | (x - y > 1)),
(2*y + 4, x - y > 1),
(4*x + 2*y, True))
assert piecewise_fold(p > 1).rewrite(ITE) == ITE((x - y > S.Half) | (x - y > 1), True,
ITE(x - y > 1, 2*y + 4 > 1, 4*x + 2*y > 1))
def test_piecewise_simplify():
p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)),
((-1)**x*(-1), True))
assert p.simplify() == \
Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True))
# simplify when there are Eq in conditions
assert Piecewise(
(a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify(
) == Piecewise(
(0, And(Eq(a, 0), Eq(b, 0))), (1, True))
assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)),
Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y
+ a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify(
) == Piecewise(
(2*x, And(Eq(a, 0), Eq(y, 0))),
(2, And(Eq(a, 1), Eq(y, 0))),
(0, True))
args = (2, And(Eq(x, 2), Ge(y, 0))), (x, True)
assert Piecewise(*args).simplify() == Piecewise(*args)
args = (1, Eq(x, 0)), (sin(x)/x, True)
assert Piecewise(*args).simplify() == Piecewise(*args)
assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True)
).simplify() == x
# check that x or f(x) are recognized as being Symbol-like for lhs
args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True))
ans = x + sin(x) + 1
f = Function('f')
assert Piecewise(*args).simplify() == ans
assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x))
# issue 18634
d = Symbol("d", integer=True)
n = Symbol("n", integer=True)
t = Symbol("t", positive=True)
expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True))
assert expr.simplify() == -d + 2*n
# issue 22747
p = Piecewise((0, (t < -2) & (t < -1) & (t < 0)), ((t/2 + 1)*(t +
1)*(t + 2), (t < -1) & (t < 0)), ((S.Half - t/2)*(1 - t)*(t + 1),
(t < -2) & (t < -1) & (t < 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half
- t/2)*(1 - t)), (t < -2) & (t < -1) & (t < 0) & (t < 1)), ((t +
1)*((S.Half - t/2)*(1 - t) + (t/2 + 1)*(t + 2)), (t < -1) & (t <
1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(1 - t)), (t < -1) &
(t < 0) & (t < 1)), (0, (t < -2) & (t < -1)), ((t/2 + 1)*(t +
1)*(t + 2), t < -1), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(t +
1)), (t < 0) & ((t < -2) | (t < 0))), ((S.Half - t/2)*(1 - t)*(t
+ 1), (t < 1) & ((t < -2) | (t < 1))), (0, True)) + Piecewise((0,
(t < -1) & (t < 0) & (t < 1)), ((1 - t)*(t/2 + S.Half)*(t + 1),
(t < 0) & (t < 1)), ((1 - t)*(1 - t/2)*(2 - t), (t < -1) & (t <
0) & (t < 2)), ((1 - t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 -
t)), (t < -1) & (t < 0) & (t < 1) & (t < 2)), ((1 - t)*((1 -
t/2)*(2 - t) + (t/2 + S.Half)*(t + 1)), (t < 0) & (t < 2)), ((1 -
t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 - t)), (t < 0) & (t <
1) & (t < 2)), (0, (t < -1) & (t < 0)), ((1 - t)*(t/2 +
S.Half)*(t + 1), t < 0), ((1 - t)*(t*(1 - t/2) + (1 - t)*(t/2 +
S.Half)), (t < 1) & ((t < -1) | (t < 1))), ((1 - t)*(1 - t/2)*(2
- t), (t < 2) & ((t < -1) | (t < 2))), (0, True))
assert p.simplify() == Piecewise(
(0, t < -2), ((t + 1)*(t + 2)**2/2, t < -1), (-3*t**3/2
- 5*t**2/2 + 1, t < 0), (3*t**3/2 - 5*t**2/2 + 1, t < 1), ((1 -
t)*(t - 2)**2/2, t < 2), (0, True))
# coverage
nan = Undefined
covered = Piecewise((1, x > 3), (2, x < 2), (3, x > 1))
assert covered.simplify().args == covered.args
assert Piecewise((1, x < 2), (2, x < 1), (3, True)).simplify(
) == Piecewise((1, x < 2), (3, True))
assert Piecewise((1, x > 2)).simplify() == Piecewise((1, x > 2),
(nan, True))
assert Piecewise((1, (x >= 2) & (x < oo))
).simplify() == Piecewise((1, (x >= 2) & (x < oo)), (nan, True))
assert Piecewise((1, x < 2), (2, (x > 1) & (x < 3)), (3, True)
). simplify() == Piecewise((1, x < 2), (2, x < 3), (3, True))
assert Piecewise((1, x < 2), (2, (x <= 3) & (x > 1)), (3, True)
).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
assert Piecewise((1, x < 2), (2, (x > 2) & (x < 3)), (3, True)
).simplify() == Piecewise((1, x < 2), (2, (x > 2) & (x < 3)),
(3, True))
assert Piecewise((1, x < 2), (2, (x >= 1) & (x <= 3)), (3, True)
).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
assert Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)), (3, True)
).simplify() == Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)),
(3, True))
def test_piecewise_solve():
abs2 = Piecewise((-x, x <= 0), (x, x > 0))
f = abs2.subs(x, x - 2)
assert solve(f, x) == [2]
assert solve(f - 1, x) == [1, 3]
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
assert solve(f, x) == [2]
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
assert solve(g, x) == [2, 5]
g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
assert solve(g, x) == [2, 5]
g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2), (f, True))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2),
(-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0))
assert solve(g, x) == [5]
# if no symbol is given the piecewise detection must still work
assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5]
f = Piecewise(((x - 2)**2, x >= 0), (0, True))
raises(NotImplementedError, lambda: solve(f, x))
def nona(ans):
return list(filter(lambda x: x is not S.NaN, ans))
p = Piecewise((x**2 - 4, x < y), (x - 2, True))
ans = solve(p, x)
assert nona([i.subs(y, -2) for i in ans]) == [2]
assert nona([i.subs(y, 2) for i in ans]) == [-2, 2]
assert nona([i.subs(y, 3) for i in ans]) == [-2, 2]
assert ans == [
Piecewise((-2, y > -2), (S.NaN, True)),
Piecewise((2, y <= 2), (S.NaN, True)),
Piecewise((2, y > 2), (S.NaN, True))]
# issue 6060
absxm3 = Piecewise(
(x - 3, 0 <= x - 3),
(3 - x, 0 > x - 3)
)
assert solve(absxm3 - y, x) == [
Piecewise((-y + 3, -y < 0), (S.NaN, True)),
Piecewise((y + 3, y >= 0), (S.NaN, True))]
p = Symbol('p', positive=True)
assert solve(absxm3 - p, x) == [-p + 3, p + 3]
# issue 6989
f = Function('f')
assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \
[Piecewise((-1, x > 0), (0, True))]
# issue 8587
f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True))
assert solve(f - 1) == [1/sqrt(2)]
def test_piecewise_fold():
p = Piecewise((x, x < 1), (1, 1 <= x))
assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x))
assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x))
assert piecewise_fold(Piecewise((1, x < 0), (2, True))
+ Piecewise((10, x < 0), (-10, True))) == \
Piecewise((11, x < 0), (-8, True))
p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True))
p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True))
p = 4*p1 + 2*p2
assert integrate(
piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1))
assert piecewise_fold(
Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True)
)) == Piecewise((1, y <= 0), (-2, y >= 0))
assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1)))
) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1))))
a, b = (Piecewise((2, Eq(x, 0)), (0, True)),
Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True)))
assert piecewise_fold(Mul(a, b, evaluate=False)
) == piecewise_fold(Mul(b, a, evaluate=False))
def test_piecewise_fold_piecewise_in_cond():
p1 = Piecewise((cos(x), x < 0), (0, True))
p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True))
assert p2.subs(x, -pi/2) == 0
assert p2.subs(x, 1) == 0
assert p2.subs(x, -pi/4) == 1
p4 = Piecewise((0, Eq(p1, 0)), (1,True))
ans = piecewise_fold(p4)
for i in range(-1, 1):
assert ans.subs(x, i) == p4.subs(x, i)
r1 = 1 < Piecewise((1, x < 1), (3, True))
ans = piecewise_fold(r1)
for i in range(2):
assert ans.subs(x, i) == r1.subs(x, i)
p5 = Piecewise((1, x < 0), (3, True))
p6 = Piecewise((1, x < 1), (3, True))
p7 = Piecewise((1, p5 < p6), (0, True))
ans = piecewise_fold(p7)
for i in range(-1, 2):
assert ans.subs(x, i) == p7.subs(x, i)
def test_piecewise_fold_piecewise_in_cond_2():
p1 = Piecewise((cos(x), x < 0), (0, True))
p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True))
p3 = Piecewise(
(0, (x >= 0) | Eq(cos(x), 0)),
(1/cos(x), x < 0),
(zoo, True)) # redundant b/c all x are already covered
assert(piecewise_fold(p2) == p3)
def test_piecewise_fold_expand():
p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True))
p2 = piecewise_fold(expand((1 - x)*p1))
cond = ((x >= 0) & (x < 1))
assert piecewise_fold(expand((1 - x)*p1), evaluate=False
) == Piecewise((1 - x, cond), (-x, cond), (1, cond), (0, True), evaluate=False)
assert piecewise_fold(expand((1 - x)*p1), evaluate=None
) == Piecewise((1 - x, cond), (0, True))
assert p2 == Piecewise((1 - x, cond), (0, True))
assert p2 == expand(piecewise_fold((1 - x)*p1))
def test_piecewise_duplicate():
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
assert p == Piecewise(*p.args)
def test_doit():
p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x))
assert p2.doit() == p1
assert p2.doit(deep=False) == p2
# issue 17165
p1 = Sum(y**x, (x, -1, oo)).doit()
assert p1.doit() == p1
def test_piecewise_interval():
p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True))
assert p1.subs(x, -0.5) == 0
assert p1.subs(x, 0.5) == 0.5
assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True))
assert integrate(p1, x) == Piecewise(
(0, x <= 0),
(x**2/2, x <= 1),
(S.Half, True))
def test_piecewise_exclusive():
p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
assert piecewise_exclusive(p) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
(1, x > 0), evaluate=False)
assert piecewise_exclusive(p + 2) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
(1, x > 0), evaluate=False) + 2
assert piecewise_exclusive(Piecewise((1, y <= 0),
(-Piecewise((2, y >= 0)), True))) == \
Piecewise((1, y <= 0),
(-Piecewise((2, y >= 0),
(S.NaN, y < 0), evaluate=False), y > 0), evaluate=False)
assert piecewise_exclusive(Piecewise((1, x > y))) == Piecewise((1, x > y),
(S.NaN, x <= y),
evaluate=False)
assert piecewise_exclusive(Piecewise((1, x > y)),
skip_nan=True) == Piecewise((1, x > y))
xr, yr = symbols('xr, yr', real=True)
p1 = Piecewise((1, xr < 0), (2, True), evaluate=False)
p1x = Piecewise((1, xr < 0), (2, xr >= 0), evaluate=False)
p2 = Piecewise((p1, yr < 0), (3, True), evaluate=False)
p2x = Piecewise((p1, yr < 0), (3, yr >= 0), evaluate=False)
p2xx = Piecewise((p1x, yr < 0), (3, yr >= 0), evaluate=False)
assert piecewise_exclusive(p2) == p2xx
assert piecewise_exclusive(p2, deep=False) == p2x
def test_piecewise_collapse():
assert Piecewise((x, True)) == x
a = x < 1
assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a))
assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a))
b = x < 5
def canonical(i):
if isinstance(i, Piecewise):
return Piecewise(*i.args)
return i
for args in [
((1, a), (Piecewise((2, a), (3, b)), b)),
((1, a), (Piecewise((2, a), (3, b.reversed)), b)),
((1, a), (Piecewise((2, a), (3, b)), b), (4, True)),
((1, a), (Piecewise((2, a), (3, b), (4, True)), b)),
((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]:
for i in (0, 2, 10):
assert canonical(
Piecewise(*args, evaluate=False).subs(x, i)
) == canonical(Piecewise(*args).subs(x, i))
r1, r2, r3, r4 = symbols('r1:5')
a = x < r1
b = x < r2
c = x < r3
d = x < r4
assert Piecewise((1, a), (Piecewise(
(2, a), (3, b), (4, c)), b), (5, c)
) == Piecewise((1, a), (3, b), (5, c))
assert Piecewise((1, a), (Piecewise(
(2, a), (3, b), (4, c), (6, True)), c), (5, d)
) == Piecewise((1, a), (Piecewise(
(3, b), (4, c)), c), (5, d))
assert Piecewise((1, Or(a, d)), (Piecewise(
(2, d), (3, b), (4, c)), b), (5, c)
) == Piecewise((1, Or(a, d)), (Piecewise(
(2, d), (3, b)), b), (5, c))
assert Piecewise((1, c), (2, ~c), (3, S.true)
) == Piecewise((1, c), (2, S.true))
assert Piecewise((1, c), (2, And(~c, b)), (3,True)
) == Piecewise((1, c), (2, b), (3, True))
assert Piecewise((1, c), (2, Or(~c, b)), (3,True)
).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2
assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True))
def test_piecewise_lambdify():
p = Piecewise(
(x**2, x < 0),
(x, Interval(0, 1, False, True).contains(x)),
(2 - x, x >= 1),
(0, True)
)
f = lambdify(x, p)
assert f(-2.0) == 4.0
assert f(0.0) == 0.0
assert f(0.5) == 0.5
assert f(2.0) == 0.0
def test_piecewise_series():
from sympy.series.order import O
p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0))
p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0))
assert p1.nseries(x, n=2) == p2
def test_piecewise_as_leading_term():
p1 = Piecewise((1/x, x > 1), (0, True))
p2 = Piecewise((x, x > 1), (0, True))
p3 = Piecewise((1/x, x > 1), (x, True))
p4 = Piecewise((x, x > 1), (1/x, True))
p5 = Piecewise((1/x, x > 1), (x, True))
p6 = Piecewise((1/x, x < 1), (x, True))
p7 = Piecewise((x, x < 1), (1/x, True))
p8 = Piecewise((x, x > 1), (1/x, True))
assert p1.as_leading_term(x) == 0
assert p2.as_leading_term(x) == 0
assert p3.as_leading_term(x) == x
assert p4.as_leading_term(x) == 1/x
assert p5.as_leading_term(x) == x
assert p6.as_leading_term(x) == 1/x
assert p7.as_leading_term(x) == x
assert p8.as_leading_term(x) == 1/x
def test_piecewise_complex():
p1 = Piecewise((2, x < 0), (1, 0 <= x))
p2 = Piecewise((2*I, x < 0), (I, 0 <= x))
p3 = Piecewise((I*x, x > 1), (1 + I, True))
p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True))
assert conjugate(p1) == p1
assert conjugate(p2) == piecewise_fold(-p2)
assert conjugate(p3) == p4
assert p1.is_imaginary is False
assert p1.is_real is True
assert p2.is_imaginary is True
assert p2.is_real is False
assert p3.is_imaginary is None
assert p3.is_real is None
assert p1.as_real_imag() == (p1, 0)
assert p2.as_real_imag() == (0, -I*p2)
def test_conjugate_transpose():
A, B = symbols("A B", commutative=False)
p = Piecewise((A*B**2, x > 0), (A**2*B, True))
assert p.adjoint() == \
Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True))
assert p.conjugate() == \
Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True))
assert p.transpose() == \
Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True))
def test_piecewise_evaluate():
assert Piecewise((x, True)) == x
assert Piecewise((x, True), evaluate=True) == x
assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),)
assert Piecewise((1, Eq(1, x)), evaluate=False).args == (
(1, Eq(1, x)),)
# like the additive and multiplicative identities that
# cannot be kept in Add/Mul, we also do not keep a single True
p = Piecewise((x, True), evaluate=False)
assert p == x
def test_as_expr_set_pairs():
assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \
[(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))]
assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \
[((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))]
def test_S_srepr_is_identity():
p = Piecewise((10, Eq(x, 0)), (12, True))
q = S(srepr(p))
assert p == q
def test_issue_12587():
# sort holes into intervals
p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True))
assert p.integrate((x, -5, 5)) == 23
p = Piecewise((1, x > 1), (2, x < y), (3, True))
lim = x, -3, 3
ans = p.integrate(lim)
for i in range(-1, 3):
assert ans.subs(y, i) == p.subs(y, i).integrate(lim)
def test_issue_11045():
assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3
# handle And with Or arguments
assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)
).integrate((x, 0, 3)) == 1
# hidden false
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
).integrate((x, 0, 3)) == 5
# targetcond is Eq
assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)
).integrate((x, 0, 4)) == 6
# And has Relational needing to be solved
assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True)
).integrate((x, 0, 3)) == 1
# Or has Relational needing to be solved
assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True)
).integrate((x, 0, 3)) == 2
# ignore hidden false (handled in canonicalization)
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
).integrate((x, 0, 3)) == 5
# watch for hidden True Piecewise
assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True)
).integrate((x, 0, 3)) == 6
# overlapping conditions of targetcond are recognized and ignored;
# the condition x > 3 will be pre-empted by the first condition
assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)
).integrate((x, 0, 4)) == 6
# convert Ne to Or
assert Piecewise((1, Ne(x, 0)), (2, True)
).integrate((x, -1, 1)) == 2
# no default but well defined
assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))
).integrate((x, 1, 4)) == 5
p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
nan = Undefined
i = p.integrate((x, 1, y))
assert i == Piecewise(
(y - 1, y < 1),
(Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half,
y <= Min(4, y)),
(nan, True))
assert p.integrate((x, 1, -1)) == i.subs(y, -1)
assert p.integrate((x, 1, 4)) == 5
assert p.integrate((x, 1, 5)) is nan
# handle Not
p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True))
assert p.integrate((x, 0, 3)) == 4
# handle updating of int_expr when there is overlap
p = Piecewise(
(1, And(5 > x, x > 1)),
(2, Or(x < 3, x > 7)),
(4, x < 8))
assert p.integrate((x, 0, 10)) == 20
# And with Eq arg handling
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))
).integrate((x, 0, 3)) is S.NaN
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True)
).integrate((x, 0, 3)) == 7
assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True)
).integrate((x, -1, 1)) == 4
# middle condition doesn't matter: it's a zero width interval
assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)
).integrate((x, 0, 3)) == 7
def test_holes():
nan = Undefined
assert Piecewise((1, x < 2)).integrate(x) == Piecewise(
(x, x < 2), (nan, True))
assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise(
(nan, x < 1), (x, x < 2), (nan, True))
assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan
assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2
# this also tests that the integrate method is used on non-Piecwise
# arguments in _eval_integral
A, B = symbols("A B")
a, b = symbols('a b', real=True)
assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2))
).integrate(x) == Piecewise(
(B*x, (a > 2)),
(Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1),
(Piecewise((B*x, x < 1), (nan, True)), True))
def test_issue_11922():
def f(x):
return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True))
autocorr = lambda k: (
f(x) * f(x + k)).integrate((x, -1, 1))
assert autocorr(1.9) > 0
k = symbols('k')
good_autocorr = lambda k: (
(1 - x**2) * f(x + k)).integrate((x, -1, 1))
a = good_autocorr(k)
assert a.subs(k, 3) == 0
k = symbols('k', positive=True)
a = good_autocorr(k)
assert a.subs(k, 3) == 0
assert Piecewise((0, x < 1), (10, (x >= 1))
).integrate() == Piecewise((0, x < 1), (10*x - 10, True))
def test_issue_5227():
f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539),
(-0.0160799238820171*x + 1.33215984776403, x < 2),
(Piecewise((0.3, x > 123), (0.7, True)) +
Piecewise((0.4, x > 2), (0.6, True)), x <=
123), (-0.00817409766454352*x + 2.10541401273885, x <
380.571428571429), (0, True))
i = integrate(f, (x, -oo, oo))
assert i == Integral(f, (x, -oo, oo)).doit()
assert str(i) == '1.00195081676351'
assert Piecewise((1, x - y < 0), (0, True)
).integrate(y) == Piecewise((0, y <= x), (-x + y, True))
def test_issue_10137():
a = Symbol('a', real=True)
b = Symbol('b', real=True)
x = Symbol('x', real=True)
y = Symbol('y', real=True)
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
p1 = Piecewise((0, Or(a > x, b < x)), (1, True))
assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo))
p3 = Piecewise((1, And(0 < x, x < a)), (0, True))
p4 = Piecewise((1, And(a > x, x > 0)), (0, True))
ip3 = integrate(p3, x)
assert ip3 == Piecewise(
(0, x <= 0),
(x, x <= Max(0, a)),
(Max(0, a), True))
ip4 = integrate(p4, x)
assert ip4 == ip3
assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
def test_stackoverflow_43852159():
f = lambda x: Piecewise((1, (x >= -1) & (x <= 1)), (0, True))
Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo))
cx = Conv(x)
assert cx.subs(x, -1.5) == cx.subs(x, 1.5)
assert cx.subs(x, 3) == 0
assert piecewise_fold(f(x - y)*f(y)) == Piecewise(
(1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)),
(0, True))
def test_issue_12557():
'''
# 3200 seconds to compute the fourier part of issue
import sympy as sym
x,y,z,t = sym.symbols('x y z t')
k = sym.symbols("k", integer=True)
fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2),
(x, -sym.pi, sym.pi))
assert fourier == FourierSeries(
sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2,
Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi),
SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) &
Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n,
0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n,
-k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) &
Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) |
(Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n,
-k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2
- pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 -
2*pi*_n**2*k**2 + pi*k**4) +
(-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4),
True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo))))
'''
x = symbols("x", real=True)
k = symbols('k', integer=True, finite=True)
abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0))
assert integrate(abs2(x), (x, -pi, pi)) == pi**2
func = cos(k*x)*sqrt(x**2)
assert integrate(func, (x, -pi, pi)) == Piecewise(
(2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True))
def test_issue_6900():
from itertools import permutations
t0, t1, T, t = symbols('t0, t1 T t')
f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1))
g = f.integrate(t)
assert g == Piecewise(
(0, t <= t0),
(t*x - t0*x, t <= Max(t0, t1)),
(-t0*x + x*Max(t0, t1), True))
for i in permutations(range(2)):
reps = dict(zip((t0,t1), i))
for tt in range(-1,3):
assert (g.xreplace(reps).subs(t,tt) ==
f.xreplace(reps).integrate(t).subs(t,tt))
lim = Tuple(t, t0, T)
g = f.integrate(lim)
ans = Piecewise(
(-t0*x + x*Min(T, Max(t0, t1)), T > t0),
(0, True))
for i in permutations(range(3)):
reps = dict(zip((t0,t1,T), i))
tru = f.xreplace(reps).integrate(lim.xreplace(reps))
assert tru == ans.xreplace(reps)
assert g == ans
def test_issue_10122():
assert solve(abs(x) + abs(x - 1) - 1 > 0, x
) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo))
def test_issue_4313():
u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True))
e = (u - u.subs(x, y))**2/(x - y)**2
M = Max(0, a)
assert integrate(e, x).expand() == Piecewise(
(Piecewise(
(0, x <= 0),
(-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 +
2*y*log(x - y)/a**2 - y/a**2, x <= M),
(-y**2/(-a**2*y + a**2*M) + 1/(-y + M) -
1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y +
M)/a**2 - y/a**2 + M/a**2, True)),
((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))),
(Piecewise(
(-1/(x - y), x <= 0),
(-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) -
y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a +
2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 -
y/a**2, x <= M),
(-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y +
a**2*M) - y**2/(-a**2*y + a**2*M) +
2*log(-y)/a - 2*log(-y + M)/a + 2/a -
2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 -
y/a**2 + M/a**2, True)),
a <= y),
(Piecewise(
(-y**2/(a**2*x - a**2*y), x <= 0),
(x/a**2 + y/a**2, x <= M),
(a**2/(-a**2*y + a**2*M) -
a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) +
2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) -
y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)),
True))
def test__intervals():
assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == (True, [])
assert Piecewise(
(1, x > x + 1),
(Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
(1, True))._intervals(x) == (True, [(-oo, oo, 1, 1)])
assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == (True,
[(-oo, oo, 1, 0)])
assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
)._intervals(x) == (True,
[(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)])
# the following tests that duplicates are removed and that non-Eq
# generated zero-width intervals are removed
assert Piecewise((1, Abs(x**(-2)) > 1), (0, True)
)._intervals(x) == (True,
[(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)])
def test_containment():
a, b, c, d, e = [1, 2, 3, 4, 5]
p = (Piecewise((d, x > 1), (e, True))*
Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True)))
assert p.integrate(x).diff(x) == Piecewise(
(c*e, x <= 0),
(a*e, x <= 1),
(a*d, x < 2), # this is what we want to get right
(b*d, x < 4),
(c*d, True))
def test_piecewise_with_DiracDelta():
d1 = DiracDelta(x - 1)
assert integrate(d1, (x, -oo, oo)) == 1
assert integrate(d1, (x, 0, 2)) == 1
assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0
assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise(
(Heaviside(x - 1), x < 2), (1, True))
# TODO raise error if function is discontinuous at limit of
# integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise(
# (d1, Eq(x, 1)
def test_issue_10258():
assert Piecewise((0, x < 1), (1, True)).is_zero is None
assert Piecewise((-1, x < 1), (1, True)).is_zero is False
a = Symbol('a', zero=True)
assert Piecewise((0, x < 1), (a, True)).is_zero
assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None
a = Symbol('a')
assert Piecewise((0, x < 1), (a, True)).is_zero is None
assert Piecewise((0, x < 1), (1, True)).is_nonzero is None
assert Piecewise((1, x < 1), (2, True)).is_nonzero
assert Piecewise((0, x < 1), (oo, True)).is_finite is None
assert Piecewise((0, x < 1), (1, True)).is_finite
b = Basic()
assert Piecewise((b, x < 1)).is_finite is None
# 10258
c = Piecewise((1, x < 0), (2, True)) < 3
assert c != True
assert piecewise_fold(c) == True
def test_issue_10087():
a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True))
m = a*b
f = piecewise_fold(m)
for i in (0, 2, 4):
assert m.subs(x, i) == f.subs(x, i)
m = a + b
f = piecewise_fold(m)
for i in (0, 2, 4):
assert m.subs(x, i) == f.subs(x, i)
def test_issue_8919():
c = symbols('c:5')
x = symbols("x")
f1 = Piecewise((c[1], x < 1), (c[2], True))
f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True))
assert integrate(f1*f2, (x, 0, 2)
) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4]
f1 = Piecewise((0, x < 1), (2, True))
f2 = Piecewise((3, x < 2), (0, True))
assert integrate(f1*f2, (x, 0, 3)) == 6
y = symbols("y", positive=True)
a, b, c, x, z = symbols("a,b,c,x,z", real=True)
I = Integral(Piecewise(
(0, (x >= y) | (x < 0) | (b > c)),
(a, True)), (x, 0, z))
ans = I.doit()
assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True))
for cond in (True, False):
for yy in range(1, 3):
for zz in range(-yy, 0, yy):
reps = [(b > c, cond), (y, yy), (z, zz)]
assert ans.subs(reps) == I.subs(reps).doit()
def test_unevaluated_integrals():
f = Function('f')
p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True))
assert p.integrate(x) == Integral(p, x)
assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5))
# test it by replacing f(x) with x%2 which will not
# affect the answer: the integrand is essentially 2 over
# the domain of integration
assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10
# this is a test of using _solve_inequality when
# solve_univariate_inequality fails
assert p.integrate(y) == Piecewise(
(y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))),
(2*y, (x > -oo) & (x < 10)), (0, True))
def test_conditions_as_alternate_booleans():
a, b, c = symbols('a:c')
assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True)))
) == Piecewise((x, ITE(x > 0, y < 1, y > 1)))
def test_Piecewise_rewrite_as_ITE():
a, b, c, d = symbols('a:d')
def _ITE(*args):
return Piecewise(*args).rewrite(ITE)
assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0)
) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, x < 2), (c, True)
) == ITE(x < 1, a, ITE(x < 2, b, c))
assert _ITE((a, x < 1), (b, y < 2), (c, True)
) == ITE(x < 1, a, ITE(y < 2, b, c))
assert _ITE((a, x < 1), (b, x < oo), (c, y < 1)
) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True)
) == ITE(x < 1, a, ITE(y < 1, c, b))
assert _ITE((a, x < 0), (b, Or(x < oo, y < 1))
) == ITE(x < 0, a, b)
raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True)))
# if `a` in the following were replaced with y then the coverage
# is complete but something other than as_set would need to be
# used to detect this
raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a)))
raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3)))
def test_issue_14052():
assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4
def test_issue_14240():
assert piecewise_fold(
Piecewise((1, a), (2, b), (4, True)) +
Piecewise((8, a), (16, True))
) == Piecewise((9, a), (18, b), (20, True))
assert piecewise_fold(
Piecewise((2, a), (3, b), (5, True)) *
Piecewise((7, a), (11, True))
) == Piecewise((14, a), (33, b), (55, True))
# these will hang if naive folding is used
assert piecewise_fold(Add(*[
Piecewise((i, a), (0, True)) for i in range(40)])
) == Piecewise((780, a), (0, True))
assert piecewise_fold(Mul(*[
Piecewise((i, a), (0, True)) for i in range(1, 41)])
) == Piecewise((factorial(40), a), (0, True))
def test_issue_14787():
x = Symbol('x')
f = Piecewise((x, x < 1), ((S(58) / 7), True))
assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))"
def test_issue_8458():
x, y = symbols('x y')
# Original issue
p1 = Piecewise((0, Eq(x, 0)), (sin(x), True))
assert p1.simplify() == sin(x)
# Slightly larger variant
p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
assert p2.simplify() == sin(x)
# Test for problem highlighted during review
p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True))
def test_issue_16417():
z = Symbol('z')
assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True))
x = Symbol('x')
assert unchanged(Piecewise, (S.Pi, re(x) < 0),
(0, Or(re(x) > 0, Ne(im(x), 0))),
(S.NaN, True))
r = Symbol('r', real=True)
p = Piecewise((S.Pi, re(r) < 0),
(0, Or(re(r) > 0, Ne(im(r), 0))),
(S.NaN, True))
assert p == Piecewise((S.Pi, r < 0),
(0, r > 0),
(S.NaN, True), evaluate=False)
# Does not work since imaginary != 0...
#i = Symbol('i', imaginary=True)
#p = Piecewise((S.Pi, re(i) < 0),
# (0, Or(re(i) > 0, Ne(im(i), 0))),
# (S.NaN, True))
#assert p == Piecewise((0, Ne(im(i), 0)),
# (S.NaN, True), evaluate=False)
i = I*r
p = Piecewise((S.Pi, re(i) < 0),
(0, Or(re(i) > 0, Ne(im(i), 0))),
(S.NaN, True))
assert p == Piecewise((0, Ne(im(i), 0)),
(S.NaN, True), evaluate=False)
assert p == Piecewise((0, Ne(r, 0)),
(S.NaN, True), evaluate=False)
def test_eval_rewrite_as_KroneckerDelta():
x, y, z, n, t, m = symbols('x y z n t m')
K = KroneckerDelta
f = lambda p: expand(p.rewrite(K))
p1 = Piecewise((0, Eq(x, y)), (1, True))
assert f(p1) == 1 - K(x, y)
p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True))
assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \
x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t)
p3 = Piecewise((1, Ne(x, y)), (0, True))
assert f(p3) == 1 - K(x, y)
p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True))
assert f(p4) == 4 - 3*K(3, x)
p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True))
assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3
p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True))
assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y)
p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True))
assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1
p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True))
assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1
p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True))
assert f(p9) == 5 * K(1, y) * K(4, x) + 1
p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True))
assert f(p10) == -3 * K(-4, x) * K(1, y) + 4
p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True))
assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1
p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True))
assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1
p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True))
assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1
p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True))
assert f(p14) == 2 * K(0, x) * K(1, y) + 1
p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True))
assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \
2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2
p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\
*Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True))
assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))),
(1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True))
assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True))
assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4
p19 = Piecewise((0, x > 2), (1, True))
assert f(p19) == p19
p20 = Piecewise((0, And(x < 2, x > -5)), (1, True))
assert f(p20) == p20
p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True))
assert f(p21) == p21
p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True))
assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1
@slow
def test_identical_conds_issue():
from sympy.stats import Uniform, density
u1 = Uniform('u1', 0, 1)
u2 = Uniform('u2', 0, 1)
# Result is quite big, so not really important here (and should ideally be
# simpler). Should not give an exception though.
density(u1 + u2)
def test_issue_7370():
f = Piecewise((1, x <= 2400))
v = integrate(f, (x, 0, Float("252.4", 30)))
assert str(v) == '252.400000000000000000000000000'
def test_issue_14933():
x = Symbol('x')
y = Symbol('y')
inp = MatrixSymbol('inp', 1, 1)
rep_dict = {y: inp[0, 0], x: inp[0, 0]}
p = Piecewise((1, ITE(y > 0, x < 0, True)))
assert p.xreplace(rep_dict) == Piecewise((1, ITE(inp[0, 0] > 0, inp[0, 0] < 0, True)))
def test_issue_16715():
raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs())
def test_issue_20360():
t, tau = symbols("t tau", real=True)
n = symbols("n", integer=True)
lam = pi * (n - S.Half)
eq = integrate(exp(lam * tau), (tau, 0, t))
assert eq.simplify() == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1))
def test_piecewise_eval():
# XXX these tests might need modification if this
# simplification is moved out of eval and into
# boolalg or Piecewise simplification functions
f = lambda x: x.args[0].cond
# unsimplified
assert f(Piecewise((x, (x > -oo) & (x < 3)))
) == ((x > -oo) & (x < 3))
assert f(Piecewise((x, (x > -oo) & (x < oo)))
) == ((x > -oo) & (x < oo))
assert f(Piecewise((x, (x > -3) & (x < 3)))
) == ((x > -3) & (x < 3))
assert f(Piecewise((x, (x > -3) & (x < oo)))
) == ((x > -3) & (x < oo))
assert f(Piecewise((x, (x <= 3) & (x > -oo)))
) == ((x <= 3) & (x > -oo))
assert f(Piecewise((x, (x <= 3) & (x > -3)))
) == ((x <= 3) & (x > -3))
assert f(Piecewise((x, (x >= -3) & (x < 3)))
) == ((x >= -3) & (x < 3))
assert f(Piecewise((x, (x >= -3) & (x < oo)))
) == ((x >= -3) & (x < oo))
assert f(Piecewise((x, (x >= -3) & (x <= 3)))
) == ((x >= -3) & (x <= 3))
# could simplify by keeping only the first
# arg of result
assert f(Piecewise((x, (x <= oo) & (x > -oo)))
) == (x > -oo) & (x <= oo)
assert f(Piecewise((x, (x <= oo) & (x > -3)))
) == (x > -3) & (x <= oo)
assert f(Piecewise((x, (x >= -oo) & (x < 3)))
) == (x < 3) & (x >= -oo)
assert f(Piecewise((x, (x >= -oo) & (x < oo)))
) == (x < oo) & (x >= -oo)
assert f(Piecewise((x, (x >= -oo) & (x <= 3)))
) == (x <= 3) & (x >= -oo)
assert f(Piecewise((x, (x >= -oo) & (x <= oo)))
) == (x <= oo) & (x >= -oo) # but cannot be True unless x is real
assert f(Piecewise((x, (x >= -3) & (x <= oo)))
) == (x >= -3) & (x <= oo)
assert f(Piecewise((x, (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)))
) == (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)
def test_issue_22533():
x = Symbol('x', real=True)
f = Piecewise((-1 / x, x <= 0), (1 / x, True))
assert integrate(f, x) == Piecewise((-log(x), x <= 0), (log(x), True))
def test_issue_24072():
assert Piecewise((1, x > 1), (2, x <= 1), (3, x <= 1)
) == Piecewise((1, x > 1), (2, True))
|
125e7a772c88cc9932055ff5807f9b197f2217a2739f4121a662442b9ee0bcab | from sympy.core.containers import Tuple
from sympy.core.function import Derivative
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import (appellf1, hyper, meijerg)
from sympy.series.order import O
from sympy.abc import x, z, k
from sympy.series.limits import limit
from sympy.testing.pytest import raises, slow
from sympy.core.random import (
random_complex_number as randcplx,
verify_numerically as tn,
test_derivative_numerically as td)
def test_TupleParametersBase():
# test that our implementation of the chain rule works
p = hyper((), (), z**2)
assert p.diff(z) == p*2*z
def test_hyper():
raises(TypeError, lambda: hyper(1, 2, z))
assert hyper((1, 2), (1,), z) == hyper(Tuple(1, 2), Tuple(1), z)
h = hyper((1, 2), (3, 4, 5), z)
assert h.ap == Tuple(1, 2)
assert h.bq == Tuple(3, 4, 5)
assert h.argument == z
assert h.is_commutative is True
# just a few checks to make sure that all arguments go where they should
assert tn(hyper(Tuple(), Tuple(), z), exp(z), z)
assert tn(z*hyper((1, 1), Tuple(2), -z), log(1 + z), z)
# differentiation
h = hyper(
(randcplx(), randcplx(), randcplx()), (randcplx(), randcplx()), z)
assert td(h, z)
a1, a2, b1, b2, b3 = symbols('a1:3, b1:4')
assert hyper((a1, a2), (b1, b2, b3), z).diff(z) == \
a1*a2/(b1*b2*b3) * hyper((a1 + 1, a2 + 1), (b1 + 1, b2 + 1, b3 + 1), z)
# differentiation wrt parameters is not supported
assert hyper([z], [], z).diff(z) == Derivative(hyper([z], [], z), z)
# hyper is unbranched wrt parameters
from sympy.functions.elementary.complexes import polar_lift
assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \
hyper([z], [k], polar_lift(x))
# hyper does not automatically evaluate anyway, but the test is to make
# sure that the evaluate keyword is accepted
assert hyper((1, 2), (1,), z, evaluate=False).func is hyper
def test_expand_func():
# evaluation at 1 of Gauss' hypergeometric function:
from sympy.abc import a, b, c
from sympy.core.function import expand_func
a1, b1, c1 = randcplx(), randcplx(), randcplx() + 5
assert expand_func(hyper([a, b], [c], 1)) == \
gamma(c)*gamma(-a - b + c)/(gamma(-a + c)*gamma(-b + c))
assert abs(expand_func(hyper([a1, b1], [c1], 1)).n()
- hyper([a1, b1], [c1], 1).n()) < 1e-10
# hyperexpand wrapper for hyper:
assert expand_func(hyper([], [], z)) == exp(z)
assert expand_func(hyper([1, 2, 3], [], z)) == hyper([1, 2, 3], [], z)
assert expand_func(meijerg([[1, 1], []], [[1], [0]], z)) == log(z + 1)
assert expand_func(meijerg([[1, 1], []], [[], []], z)) == \
meijerg([[1, 1], []], [[], []], z)
def replace_dummy(expr, sym):
from sympy.core.symbol import Dummy
dum = expr.atoms(Dummy)
if not dum:
return expr
assert len(dum) == 1
return expr.xreplace({dum.pop(): sym})
def test_hyper_rewrite_sum():
from sympy.concrete.summations import Sum
from sympy.core.symbol import Dummy
from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
_k = Dummy("k")
assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \
Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) /
RisingFactorial(3, _k), (_k, 0, oo))
assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \
hyper((1, 2, 3), (-1, 3), z)
def test_radius_of_convergence():
assert hyper((1, 2), [3], z).radius_of_convergence == 1
assert hyper((1, 2), [3, 4], z).radius_of_convergence is oo
assert hyper((1, 2, 3), [4], z).radius_of_convergence == 0
assert hyper((0, 1, 2), [4], z).radius_of_convergence is oo
assert hyper((-1, 1, 2), [-4], z).radius_of_convergence == 0
assert hyper((-1, -2, 2), [-1], z).radius_of_convergence is oo
assert hyper((-1, 2), [-1, -2], z).radius_of_convergence == 0
assert hyper([-1, 1, 3], [-2, 2], z).radius_of_convergence == 1
assert hyper([-1, 1], [-2, 2], z).radius_of_convergence is oo
assert hyper([-1, 1, 3], [-2], z).radius_of_convergence == 0
assert hyper((-1, 2, 3, 4), [], z).radius_of_convergence is oo
assert hyper([1, 1], [3], 1).convergence_statement == True
assert hyper([1, 1], [2], 1).convergence_statement == False
assert hyper([1, 1], [2], -1).convergence_statement == True
assert hyper([1, 1], [1], -1).convergence_statement == False
def test_meijer():
raises(TypeError, lambda: meijerg(1, z))
raises(TypeError, lambda: meijerg(((1,), (2,)), (3,), (4,), z))
assert meijerg(((1, 2), (3,)), ((4,), (5,)), z) == \
meijerg(Tuple(1, 2), Tuple(3), Tuple(4), Tuple(5), z)
g = meijerg((1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13, 14), z)
assert g.an == Tuple(1, 2)
assert g.ap == Tuple(1, 2, 3, 4, 5)
assert g.aother == Tuple(3, 4, 5)
assert g.bm == Tuple(6, 7, 8, 9)
assert g.bq == Tuple(6, 7, 8, 9, 10, 11, 12, 13, 14)
assert g.bother == Tuple(10, 11, 12, 13, 14)
assert g.argument == z
assert g.nu == 75
assert g.delta == -1
assert g.is_commutative is True
assert g.is_number is False
#issue 13071
assert meijerg([[],[]], [[S.Half],[0]], 1).is_number is True
assert meijerg([1, 2], [3], [4], [5], z).delta == S.Half
# just a few checks to make sure that all arguments go where they should
assert tn(meijerg(Tuple(), Tuple(), Tuple(0), Tuple(), -z), exp(z), z)
assert tn(sqrt(pi)*meijerg(Tuple(), Tuple(),
Tuple(0), Tuple(S.Half), z**2/4), cos(z), z)
assert tn(meijerg(Tuple(1, 1), Tuple(), Tuple(1), Tuple(0), z),
log(1 + z), z)
# test exceptions
raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((oo,), (2, 0)), x))
raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((1,), (2, 0)), x))
# differentiation
g = meijerg((randcplx(),), (randcplx() + 2*I,), Tuple(),
(randcplx(), randcplx()), z)
assert td(g, z)
g = meijerg(Tuple(), (randcplx(),), Tuple(),
(randcplx(), randcplx()), z)
assert td(g, z)
g = meijerg(Tuple(), Tuple(), Tuple(randcplx()),
Tuple(randcplx(), randcplx()), z)
assert td(g, z)
a1, a2, b1, b2, c1, c2, d1, d2 = symbols('a1:3, b1:3, c1:3, d1:3')
assert meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z).diff(z) == \
(meijerg((a1 - 1, a2), (b1, b2), (c1, c2), (d1, d2), z)
+ (a1 - 1)*meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z))/z
assert meijerg([z, z], [], [], [], z).diff(z) == \
Derivative(meijerg([z, z], [], [], [], z), z)
# meijerg is unbranched wrt parameters
from sympy.functions.elementary.complexes import polar_lift as pl
assert meijerg([pl(a1)], [pl(a2)], [pl(b1)], [pl(b2)], pl(z)) == \
meijerg([a1], [a2], [b1], [b2], pl(z))
# integrand
from sympy.abc import a, b, c, d, s
assert meijerg([a], [b], [c], [d], z).integrand(s) == \
z**s*gamma(c - s)*gamma(-a + s + 1)/(gamma(b - s)*gamma(-d + s + 1))
def test_meijerg_derivative():
assert meijerg([], [1, 1], [0, 0, x], [], z).diff(x) == \
log(z)*meijerg([], [1, 1], [0, 0, x], [], z) \
+ 2*meijerg([], [1, 1, 1], [0, 0, x, 0], [], z)
y = randcplx()
a = 5 # mpmath chokes with non-real numbers, and Mod1 with floats
assert td(meijerg([x], [], [], [], y), x)
assert td(meijerg([x**2], [], [], [], y), x)
assert td(meijerg([], [x], [], [], y), x)
assert td(meijerg([], [], [x], [], y), x)
assert td(meijerg([], [], [], [x], y), x)
assert td(meijerg([x], [a], [a + 1], [], y), x)
assert td(meijerg([x], [a + 1], [a], [], y), x)
assert td(meijerg([x, a], [], [], [a + 1], y), x)
assert td(meijerg([x, a + 1], [], [], [a], y), x)
b = Rational(3, 2)
assert td(meijerg([a + 2], [b], [b - 3, x], [a], y), x)
def test_meijerg_period():
assert meijerg([], [1], [0], [], x).get_period() == 2*pi
assert meijerg([1], [], [], [0], x).get_period() == 2*pi
assert meijerg([], [], [0], [], x).get_period() == 2*pi # exp(x)
assert meijerg(
[], [], [0], [S.Half], x).get_period() == 2*pi # cos(sqrt(x))
assert meijerg(
[], [], [S.Half], [0], x).get_period() == 4*pi # sin(sqrt(x))
assert meijerg([1, 1], [], [1], [0], x).get_period() is oo # log(1 + x)
def test_hyper_unpolarify():
from sympy.functions.elementary.exponential import exp_polar
a = exp_polar(2*pi*I)*x
b = x
assert hyper([], [], a).argument == b
assert hyper([0], [], a).argument == a
assert hyper([0], [0], a).argument == b
assert hyper([0, 1], [0], a).argument == a
assert hyper([0, 1], [0], exp_polar(2*pi*I)).argument == 1
@slow
def test_hyperrep():
from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh,
HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
HyperRep_cosasin, HyperRep_sinasin)
# First test the base class works.
from sympy.functions.elementary.exponential import exp_polar
from sympy.functions.elementary.piecewise import Piecewise
a, b, c, d, z = symbols('a b c d z')
class myrep(HyperRep):
@classmethod
def _expr_small(cls, x):
return a
@classmethod
def _expr_small_minus(cls, x):
return b
@classmethod
def _expr_big(cls, x, n):
return c*n
@classmethod
def _expr_big_minus(cls, x, n):
return d*n
assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True))
assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \
Piecewise((0, abs(z) > 1), (b, True))
assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \
Piecewise((c, abs(z) > 1), (a, True))
assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \
Piecewise((d, abs(z) > 1), (b, True))
assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \
Piecewise((2*c, abs(z) > 1), (a, True))
assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \
Piecewise((2*d, abs(z) > 1), (b, True))
assert myrep(z).rewrite('nonrepsmall') == a
assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b
def t(func, hyp, z):
""" Test that func is a valid representation of hyp. """
# First test that func agrees with hyp for small z
if not tn(func.rewrite('nonrepsmall'), hyp, z,
a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
return False
# Next check that the two small representations agree.
if not tn(
func.rewrite('nonrepsmall').subs(
z, exp_polar(I*pi)*z).replace(exp_polar, exp),
func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'),
z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
return False
# Next check continuity along exp_polar(I*pi)*t
expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep')
if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10:
return False
# Finally check continuity of the big reps.
def dosubs(func, a, b):
rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep')
return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp)
for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]:
expr1 = dosubs(func, 2*I*pi*n, I*pi/2)
expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2)
if not tn(expr1, expr2, z):
return False
expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2)
expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2)
if not tn(expr1, expr2, z):
return False
return True
# Now test the various representatives.
a = Rational(1, 3)
assert t(HyperRep_atanh(z), hyper([S.Half, 1], [Rational(3, 2)], z), z)
assert t(HyperRep_power1(a, z), hyper([-a], [], z), z)
assert t(HyperRep_power2(a, z), hyper([a, a - S.Half], [2*a], z), z)
assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z)
assert t(HyperRep_asin1(z), hyper([S.Half, S.Half], [Rational(3, 2)], z), z)
assert t(HyperRep_asin2(z), hyper([1, 1], [Rational(3, 2)], z), z)
assert t(HyperRep_sqrts1(a, z), hyper([-a, S.Half - a], [S.Half], z), z)
assert t(HyperRep_sqrts2(a, z),
-2*z/(2*a + 1)*hyper([-a - S.Half, -a], [S.Half], z).diff(z), z)
assert t(HyperRep_log2(z), -z/4*hyper([Rational(3, 2), 1, 1], [2, 2], z), z)
assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S.Half], z), z)
assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [Rational(3, 2)], z), z)
@slow
def test_meijerg_eval():
from sympy.functions.elementary.exponential import exp_polar
from sympy.functions.special.bessel import besseli
from sympy.abc import l
a = randcplx()
arg = x*exp_polar(k*pi*I)
expr1 = pi*meijerg([[], [(a + 1)/2]], [[a/2], [-a/2, (a + 1)/2]], arg**2/4)
expr2 = besseli(a, arg)
# Test that the two expressions agree for all arguments.
for x_ in [0.5, 1.5]:
for k_ in [0.0, 0.1, 0.3, 0.5, 0.8, 1, 5.751, 15.3]:
assert abs((expr1 - expr2).n(subs={x: x_, k: k_})) < 1e-10
assert abs((expr1 - expr2).n(subs={x: x_, k: -k_})) < 1e-10
# Test continuity independently
eps = 1e-13
expr2 = expr1.subs(k, l)
for x_ in [0.5, 1.5]:
for k_ in [0.5, Rational(1, 3), 0.25, 0.75, Rational(2, 3), 1.0, 1.5]:
assert abs((expr1 - expr2).n(
subs={x: x_, k: k_ + eps, l: k_ - eps})) < 1e-10
assert abs((expr1 - expr2).n(
subs={x: x_, k: -k_ + eps, l: -k_ - eps})) < 1e-10
expr = (meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(-I*pi)/4)
+ meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(I*pi)/4)) \
/(2*sqrt(pi))
assert (expr - pi/exp(1)).n(chop=True) == 0
def test_limits():
k, x = symbols('k, x')
assert hyper((1,), (Rational(4, 3), Rational(5, 3)), k**2).series(k) == \
1 + 9*k**2/20 + 81*k**4/1120 + O(k**6) # issue 6350
# https://github.com/sympy/sympy/issues/11465
assert limit(1/hyper((1, ), (1, ), x), x, 0) == 1
def test_appellf1():
a, b1, b2, c, x, y = symbols('a b1 b2 c x y')
assert appellf1(a, b2, b1, c, y, x) == appellf1(a, b1, b2, c, x, y)
assert appellf1(a, b1, b1, c, y, x) == appellf1(a, b1, b1, c, x, y)
assert appellf1(a, b1, b2, c, S.Zero, S.Zero) is S.One
f = appellf1(a, b1, b2, c, S.Zero, S.Zero, evaluate=False)
assert f.func is appellf1
assert f.doit() is S.One
def test_derivative_appellf1():
from sympy.core.function import diff
a, b1, b2, c, x, y, z = symbols('a b1 b2 c x y z')
assert diff(appellf1(a, b1, b2, c, x, y), x) == a*b1*appellf1(a + 1, b2, b1 + 1, c + 1, y, x)/c
assert diff(appellf1(a, b1, b2, c, x, y), y) == a*b2*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)/c
assert diff(appellf1(a, b1, b2, c, x, y), z) == 0
assert diff(appellf1(a, b1, b2, c, x, y), a) == Derivative(appellf1(a, b1, b2, c, x, y), a)
def test_eval_nseries():
a1, b1, a2, b2 = symbols('a1 b1 a2 b2')
assert hyper((1,2), (1,2,3), x**2)._eval_nseries(x, 7, None) == 1 + x**2/3 + x**4/24 + x**6/360 + O(x**7)
assert exp(x)._eval_nseries(x,7,None) == hyper((a1, b1), (a1, b1), x)._eval_nseries(x, 7, None)
assert hyper((a1, a2), (b1, b2), x)._eval_nseries(z, 7, None) == hyper((a1, a2), (b1, b2), x) + O(z**7)
|
dabe7dfda0b440e5d0b01357ab1b073ebd8f909131bac23aaaf4b275904f6dfc | from sympy.concrete.summations import Sum
from sympy.core.function import expand_func
from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.complexes import (Abs, polar_lift)
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, riemann_xi, stieltjes, zeta)
from sympy.series.order import O
from sympy.core.function import ArgumentIndexError
from sympy.functions.combinatorial.numbers import bernoulli, factorial, genocchi, harmonic
from sympy.testing.pytest import raises
from sympy.core.random import (test_derivative_numerically as td,
random_complex_number as randcplx, verify_numerically)
x = Symbol('x')
a = Symbol('a')
b = Symbol('b', negative=True)
z = Symbol('z')
s = Symbol('s')
def test_zeta_eval():
assert zeta(nan) is nan
assert zeta(x, nan) is nan
assert zeta(0) == Rational(-1, 2)
assert zeta(0, x) == S.Half - x
assert zeta(0, b) == S.Half - b
assert zeta(1) is zoo
assert zeta(1, 2) is zoo
assert zeta(1, -7) is zoo
assert zeta(1, x) is zoo
assert zeta(2, 1) == pi**2/6
assert zeta(3, 1) == zeta(3)
assert zeta(2) == pi**2/6
assert zeta(4) == pi**4/90
assert zeta(6) == pi**6/945
assert zeta(4, 3) == pi**4/90 - Rational(17, 16)
assert zeta(7, 4) == zeta(7) - Rational(282251, 279936)
assert zeta(S.Half, 2).func == zeta
assert expand_func(zeta(S.Half, 2)) == zeta(S.Half) - 1
assert zeta(x, 3).func == zeta
assert expand_func(zeta(x, 3)) == zeta(x) - 1 - 1/2**x
assert zeta(2, 0) is nan
assert zeta(3, -1) is nan
assert zeta(4, -2) is nan
assert zeta(oo) == 1
assert zeta(-1) == Rational(-1, 12)
assert zeta(-2) == 0
assert zeta(-3) == Rational(1, 120)
assert zeta(-4) == 0
assert zeta(-5) == Rational(-1, 252)
assert zeta(-1, 3) == Rational(-37, 12)
assert zeta(-1, 7) == Rational(-253, 12)
assert zeta(-1, -4) == Rational(-121, 12)
assert zeta(-1, -9) == Rational(-541, 12)
assert zeta(-4, 3) == -17
assert zeta(-4, -8) == 8772
assert zeta(0, 1) == Rational(-1, 2)
assert zeta(0, -1) == Rational(3, 2)
assert zeta(0, 2) == Rational(-3, 2)
assert zeta(0, -2) == Rational(5, 2)
assert zeta(
3).evalf(20).epsilon_eq(Float("1.2020569031595942854", 20), 1e-19)
def test_zeta_series():
assert zeta(x, a).series(a, z, 2) == \
zeta(x, z) - x*(a-z)*zeta(x+1, z) + O((a-z)**2, (a, z))
def test_dirichlet_eta_eval():
assert dirichlet_eta(0) == S.Half
assert dirichlet_eta(-1) == Rational(1, 4)
assert dirichlet_eta(1) == log(2)
assert dirichlet_eta(1, S.Half).simplify() == pi/2
assert dirichlet_eta(1, 2) == 1 - log(2)
assert dirichlet_eta(2) == pi**2/12
assert dirichlet_eta(4) == pi**4*Rational(7, 720)
assert str(dirichlet_eta(I).evalf(n=10)) == '0.5325931818 + 0.2293848577*I'
assert str(dirichlet_eta(I, I).evalf(n=10)) == '3.462349253 + 0.220285771*I'
def test_riemann_xi_eval():
assert riemann_xi(2) == pi/6
assert riemann_xi(0) == Rational(1, 2)
assert riemann_xi(1) == Rational(1, 2)
assert riemann_xi(3).rewrite(zeta) == 3*zeta(3)/(2*pi)
assert riemann_xi(4) == pi**2/15
def test_rewriting():
from sympy.functions.elementary.piecewise import Piecewise
assert isinstance(dirichlet_eta(x).rewrite(zeta), Piecewise)
assert isinstance(dirichlet_eta(x).rewrite(genocchi), Piecewise)
assert zeta(x).rewrite(dirichlet_eta) == dirichlet_eta(x)/(1 - 2**(1 - x))
assert zeta(x).rewrite(dirichlet_eta, a=2) == zeta(x)
assert verify_numerically(dirichlet_eta(x), dirichlet_eta(x).rewrite(zeta), x)
assert verify_numerically(dirichlet_eta(x), dirichlet_eta(x).rewrite(genocchi), x)
assert verify_numerically(zeta(x), zeta(x).rewrite(dirichlet_eta), x)
assert zeta(x, a).rewrite(lerchphi) == lerchphi(1, x, a)
assert polylog(s, z).rewrite(lerchphi) == lerchphi(z, s, 1)*z
assert lerchphi(1, x, a).rewrite(zeta) == zeta(x, a)
assert z*lerchphi(z, s, 1).rewrite(polylog) == polylog(s, z)
def test_derivatives():
from sympy.core.function import Derivative
assert zeta(x, a).diff(x) == Derivative(zeta(x, a), x)
assert zeta(x, a).diff(a) == -x*zeta(x + 1, a)
assert lerchphi(
z, s, a).diff(z) == (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z
assert lerchphi(z, s, a).diff(a) == -s*lerchphi(z, s + 1, a)
assert polylog(s, z).diff(z) == polylog(s - 1, z)/z
b = randcplx()
c = randcplx()
assert td(zeta(b, x), x)
assert td(polylog(b, z), z)
assert td(lerchphi(c, b, x), x)
assert td(lerchphi(x, b, c), x)
raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(2))
raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(4))
raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(1))
raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(3))
def myexpand(func, target):
expanded = expand_func(func)
if target is not None:
return expanded == target
if expanded == func: # it didn't expand
return False
# check to see that the expanded and original evaluate to the same value
subs = {}
for a in func.free_symbols:
subs[a] = randcplx()
return abs(func.subs(subs).n()
- expanded.replace(exp_polar, exp).subs(subs).n()) < 1e-10
def test_polylog_expansion():
assert polylog(s, 0) == 0
assert polylog(s, 1) == zeta(s)
assert polylog(s, -1) == -dirichlet_eta(s)
assert polylog(s, exp_polar(I*pi*Rational(4, 3))) == polylog(s, exp(I*pi*Rational(4, 3)))
assert polylog(s, exp_polar(I*pi)/3) == polylog(s, exp(I*pi)/3)
assert myexpand(polylog(1, z), -log(1 - z))
assert myexpand(polylog(0, z), z/(1 - z))
assert myexpand(polylog(-1, z), z/(1 - z)**2)
assert ((1-z)**3 * expand_func(polylog(-2, z))).simplify() == z*(1 + z)
assert myexpand(polylog(-5, z), None)
def test_polylog_series():
assert polylog(1, z).series(z, n=5) == z + z**2/2 + z**3/3 + z**4/4 + O(z**5)
assert polylog(1, sqrt(z)).series(z, n=3) == z/2 + z**2/4 + sqrt(z)\
+ z**(S(3)/2)/3 + z**(S(5)/2)/5 + O(z**3)
# https://github.com/sympy/sympy/issues/9497
assert polylog(S(3)/2, -z).series(z, 0, 5) == -z + sqrt(2)*z**2/4\
- sqrt(3)*z**3/9 + z**4/8 + O(z**5)
def test_issue_8404():
i = Symbol('i', integer=True)
assert Abs(Sum(1/(3*i + 1)**2, (i, 0, S.Infinity)).doit().n(4)
- 1.122) < 0.001
def test_polylog_values():
assert polylog(2, 2) == pi**2/4 - I*pi*log(2)
assert polylog(2, S.Half) == pi**2/12 - log(2)**2/2
for z in [S.Half, 2, (sqrt(5)-1)/2, -(sqrt(5)-1)/2, -(sqrt(5)+1)/2, (3-sqrt(5))/2]:
assert Abs(polylog(2, z).evalf() - polylog(2, z, evaluate=False).evalf()) < 1e-15
z = Symbol("z")
for s in [-1, 0]:
for _ in range(10):
assert verify_numerically(polylog(s, z), polylog(s, z, evaluate=False),
z, a=-3, b=-2, c=S.Half, d=2)
assert verify_numerically(polylog(s, z), polylog(s, z, evaluate=False),
z, a=2, b=-2, c=5, d=2)
from sympy.integrals.integrals import Integral
assert polylog(0, Integral(1, (x, 0, 1))) == -S.Half
def test_lerchphi_expansion():
assert myexpand(lerchphi(1, s, a), zeta(s, a))
assert myexpand(lerchphi(z, s, 1), polylog(s, z)/z)
# direct summation
assert myexpand(lerchphi(z, -1, a), a/(1 - z) + z/(1 - z)**2)
assert myexpand(lerchphi(z, -3, a), None)
# polylog reduction
assert myexpand(lerchphi(z, s, S.Half),
2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z)
- polylog(s, polar_lift(-1)*sqrt(z))/sqrt(z)))
assert myexpand(lerchphi(z, s, 2), -1/z + polylog(s, z)/z**2)
assert myexpand(lerchphi(z, s, Rational(3, 2)), None)
assert myexpand(lerchphi(z, s, Rational(7, 3)), None)
assert myexpand(lerchphi(z, s, Rational(-1, 3)), None)
assert myexpand(lerchphi(z, s, Rational(-5, 2)), None)
# hurwitz zeta reduction
assert myexpand(lerchphi(-1, s, a),
2**(-s)*zeta(s, a/2) - 2**(-s)*zeta(s, (a + 1)/2))
assert myexpand(lerchphi(I, s, a), None)
assert myexpand(lerchphi(-I, s, a), None)
assert myexpand(lerchphi(exp(I*pi*Rational(2, 5)), s, a), None)
def test_stieltjes():
assert isinstance(stieltjes(x), stieltjes)
assert isinstance(stieltjes(x, a), stieltjes)
# Zero'th constant EulerGamma
assert stieltjes(0) == S.EulerGamma
assert stieltjes(0, 1) == S.EulerGamma
# Not defined
assert stieltjes(nan) is nan
assert stieltjes(0, nan) is nan
assert stieltjes(-1) is S.ComplexInfinity
assert stieltjes(1.5) is S.ComplexInfinity
assert stieltjes(z, 0) is S.ComplexInfinity
assert stieltjes(z, -1) is S.ComplexInfinity
def test_stieltjes_evalf():
assert abs(stieltjes(0).evalf() - 0.577215664) < 1E-9
assert abs(stieltjes(0, 0.5).evalf() - 1.963510026) < 1E-9
assert abs(stieltjes(1, 2).evalf() + 0.072815845) < 1E-9
def test_issue_10475():
a = Symbol('a', extended_real=True)
b = Symbol('b', extended_positive=True)
s = Symbol('s', zero=False)
assert zeta(2 + I).is_finite
assert zeta(1).is_finite is False
assert zeta(x).is_finite is None
assert zeta(x + I).is_finite is None
assert zeta(a).is_finite is None
assert zeta(b).is_finite is None
assert zeta(-b).is_finite is True
assert zeta(b**2 - 2*b + 1).is_finite is None
assert zeta(a + I).is_finite is True
assert zeta(b + 1).is_finite is True
assert zeta(s + 1).is_finite is True
def test_issue_14177():
n = Symbol('n', nonnegative=True, integer=True)
assert zeta(-n).rewrite(bernoulli) == bernoulli(n+1) / (-n-1)
assert zeta(-n, a).rewrite(bernoulli) == bernoulli(n+1, a) / (-n-1)
z2n = -(2*I*pi)**(2*n)*bernoulli(2*n) / (2*factorial(2*n))
assert zeta(2*n).rewrite(bernoulli) == z2n
assert expand_func(zeta(s, n+1)) == zeta(s) - harmonic(n, s)
assert expand_func(zeta(-b, -n)) is nan
assert expand_func(zeta(-b, n)) == zeta(-b, n)
n = Symbol('n')
assert zeta(2*n) == zeta(2*n) # As sign of z (= 2*n) is not determined
|
1b1e9c8de941d1a5c60ca3301b93bec293e3cadeab14955a35e9cd983e506f71 | from itertools import product
from sympy.concrete.summations import Sum
from sympy.core.function import (diff, expand_func)
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import (conjugate, polar_lift)
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import (cosh, sinh)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely, hankel1, hankel2, hn1, hn2, jn, jn_zeros, yn)
from sympy.functions.special.gamma_functions import (gamma, uppergamma)
from sympy.functions.special.hyper import hyper
from sympy.integrals.integrals import Integral
from sympy.series.order import O
from sympy.series.series import series
from sympy.functions.special.bessel import (airyai, airybi,
airyaiprime, airybiprime, marcumq)
from sympy.core.random import (random_complex_number as randcplx,
verify_numerically as tn,
test_derivative_numerically as td,
_randint)
from sympy.simplify import besselsimp
from sympy.testing.pytest import raises, slow
from sympy.abc import z, n, k, x
randint = _randint()
def test_bessel_rand():
for f in [besselj, bessely, besseli, besselk, hankel1, hankel2]:
assert td(f(randcplx(), z), z)
for f in [jn, yn, hn1, hn2]:
assert td(f(randint(-10, 10), z), z)
def test_bessel_twoinputs():
for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn]:
raises(TypeError, lambda: f(1))
raises(TypeError, lambda: f(1, 2, 3))
def test_besselj_leading_term():
assert besselj(0, x).as_leading_term(x) == 1
assert besselj(1, sin(x)).as_leading_term(x) == x/2
assert besselj(1, 2*sqrt(x)).as_leading_term(x) == sqrt(x)
# https://github.com/sympy/sympy/issues/21701
assert (besselj(z, x)/x**z).as_leading_term(x) == 1/(2**z*gamma(z + 1))
def test_bessely_leading_term():
assert bessely(0, x).as_leading_term(x) == (2*log(x) - 2*log(2) + 2*S.EulerGamma)/pi
assert bessely(1, sin(x)).as_leading_term(x) == -2/(pi*x)
assert bessely(1, 2*sqrt(x)).as_leading_term(x) == -1/(pi*sqrt(x))
def test_besseli_leading_term():
assert besseli(0, x).as_leading_term(x) == 1
assert besseli(1, sin(x)).as_leading_term(x) == x/2
assert besseli(1, 2*sqrt(x)).as_leading_term(x) == sqrt(x)
def test_besselk_leading_term():
assert besselk(0, x).as_leading_term(x) == -log(x) - S.EulerGamma + log(2)
assert besselk(1, sin(x)).as_leading_term(x) == 1/x
assert besselk(1, 2*sqrt(x)).as_leading_term(x) == 1/(2*sqrt(x))
def test_besselj_series():
assert besselj(0, x).series(x) == 1 - x**2/4 + x**4/64 + O(x**6)
assert besselj(0, x**(1.1)).series(x) == 1 + x**4.4/64 - x**2.2/4 + O(x**6)
assert besselj(0, x**2 + x).series(x) == 1 - x**2/4 - x**3/2\
- 15*x**4/64 + x**5/16 + O(x**6)
assert besselj(0, sqrt(x) + x).series(x, n=4) == 1 - x/4 - 15*x**2/64\
+ 215*x**3/2304 - x**Rational(3, 2)/2 + x**Rational(5, 2)/16\
+ 23*x**Rational(7, 2)/384 + O(x**4)
assert besselj(0, x/(1 - x)).series(x) == 1 - x**2/4 - x**3/2 - 47*x**4/64\
- 15*x**5/16 + O(x**6)
assert besselj(0, log(1 + x)).series(x) == 1 - x**2/4 + x**3/4\
- 41*x**4/192 + 17*x**5/96 + O(x**6)
assert besselj(1, sin(x)).series(x) == x/2 - 7*x**3/48 + 73*x**5/1920 + O(x**6)
assert besselj(1, 2*sqrt(x)).series(x) == sqrt(x) - x**Rational(3, 2)/2\
+ x**Rational(5, 2)/12 - x**Rational(7, 2)/144 + x**Rational(9, 2)/2880\
- x**Rational(11, 2)/86400 + O(x**6)
assert besselj(-2, sin(x)).series(x, n=4) == besselj(2, sin(x)).series(x, n=4)
def test_bessely_series():
const = 2*S.EulerGamma/pi - 2*log(2)/pi + 2*log(x)/pi
assert bessely(0, x).series(x, n=4) == const + x**2*(-log(x)/(2*pi)\
+ (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x))
assert bessely(1, x).series(x, n=4) == -2/(pi*x) + x*(log(x)/pi - log(2)/pi - \
(1 - 2*S.EulerGamma)/(2*pi)) + x**3*(-log(x)/(8*pi) + \
(S(5)/2 - 2*S.EulerGamma)/(16*pi) + log(2)/(8*pi)) + O(x**4*log(x))
assert bessely(2, x).series(x, n=4) == -4/(pi*x**2) - 1/pi + x**2*(log(x)/(4*pi) - \
log(2)/(4*pi) - (S(3)/2 - 2*S.EulerGamma)/(8*pi)) + O(x**4*log(x))
assert bessely(3, x).series(x, n=4) == -16/(pi*x**3) - 2/(pi*x) - \
x/(4*pi) + x**3*(log(x)/(24*pi) - log(2)/(24*pi) - \
(S(11)/6 - 2*S.EulerGamma)/(48*pi)) + O(x**4*log(x))
assert bessely(0, x**(1.1)).series(x, n=4) == 2*S.EulerGamma/pi\
- 2*log(2)/pi + 2.2*log(x)/pi + x**2.2*(-0.55*log(x)/pi\
+ (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x))
assert bessely(0, x**2 + x).series(x, n=4) == \
const - (2 - 2*S.EulerGamma)*(-x**3/(2*pi) - x**2/(4*pi)) + 2*x/pi\
+ x**2*(-log(x)/(2*pi) - 1/pi + log(2)/(2*pi))\
+ x**3*(-log(x)/pi + 1/(6*pi) + log(2)/pi) + O(x**4*log(x))
assert bessely(0, x/(1 - x)).series(x, n=3) == const\
+ 2*x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\
+ log(2)/(2*pi) + 1/pi) + O(x**3*log(x))
assert bessely(0, log(1 + x)).series(x, n=3) == const\
- x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\
+ log(2)/(2*pi) + 5/(12*pi)) + O(x**3*log(x))
assert bessely(1, sin(x)).series(x, n=4) == -1/(pi*(-x**3/12 + x/2)) - \
(1 - 2*S.EulerGamma)*(-x**3/12 + x/2)/pi + x*(log(x)/pi - log(2)/pi) + \
x**3*(-7*log(x)/(24*pi) - 1/(6*pi) + (S(5)/2 - 2*S.EulerGamma)/(16*pi) +
7*log(2)/(24*pi)) + O(x**4*log(x))
assert bessely(1, 2*sqrt(x)).series(x, n=3) == -1/(pi*sqrt(x)) + \
sqrt(x)*(log(x)/pi - (1 - 2*S.EulerGamma)/pi) + x**(S(3)/2)*(-log(x)/(2*pi) + \
(S(5)/2 - 2*S.EulerGamma)/(2*pi)) + x**(S(5)/2)*(log(x)/(12*pi) - \
(S(10)/3 - 2*S.EulerGamma)/(12*pi)) + O(x**3*log(x))
assert bessely(-2, sin(x)).series(x, n=4) == bessely(2, sin(x)).series(x, n=4)
def test_besseli_series():
assert besseli(0, x).series(x) == 1 + x**2/4 + x**4/64 + O(x**6)
assert besseli(0, x**(1.1)).series(x) == 1 + x**4.4/64 + x**2.2/4 + O(x**6)
assert besseli(0, x**2 + x).series(x) == 1 + x**2/4 + x**3/2 + 17*x**4/64 + \
x**5/16 + O(x**6)
assert besseli(0, sqrt(x) + x).series(x, n=4) == 1 + x/4 + 17*x**2/64 + \
217*x**3/2304 + x**(S(3)/2)/2 + x**(S(5)/2)/16 + 25*x**(S(7)/2)/384 + O(x**4)
assert besseli(0, x/(1 - x)).series(x) == 1 + x**2/4 + x**3/2 + 49*x**4/64 + \
17*x**5/16 + O(x**6)
assert besseli(0, log(1 + x)).series(x) == 1 + x**2/4 - x**3/4 + 47*x**4/192 - \
23*x**5/96 + O(x**6)
assert besseli(1, sin(x)).series(x) == x/2 - x**3/48 - 47*x**5/1920 + O(x**6)
assert besseli(1, 2*sqrt(x)).series(x) == sqrt(x) + x**(S(3)/2)/2 + x**(S(5)/2)/12 + \
x**(S(7)/2)/144 + x**(S(9)/2)/2880 + x**(S(11)/2)/86400 + O(x**6)
assert besseli(-2, sin(x)).series(x, n=4) == besseli(2, sin(x)).series(x, n=4)
def test_besselk_series():
const = log(2) - S.EulerGamma - log(x)
assert besselk(0, x).series(x, n=4) == const + \
x**2*(-log(x)/4 - S.EulerGamma/4 + log(2)/4 + S(1)/4) + O(x**4*log(x))
assert besselk(1, x).series(x, n=4) == 1/x + x*(log(x)/2 - log(2)/2 - \
S(1)/4 + S.EulerGamma/2) + x**3*(log(x)/16 - S(5)/64 - log(2)/16 + \
S.EulerGamma/16) + O(x**4*log(x))
assert besselk(2, x).series(x, n=4) == 2/x**2 - S(1)/2 + x**2*(-log(x)/8 - \
S.EulerGamma/8 + log(2)/8 + S(3)/32) + O(x**4*log(x))
assert besselk(0, x**(1.1)).series(x, n=4) == log(2) - S.EulerGamma - \
1.1*log(x) + x**2.2*(-0.275*log(x) - S.EulerGamma/4 + \
log(2)/4 + S(1)/4) + O(x**4*log(x))
assert besselk(0, x**2 + x).series(x, n=4) == const + \
(2 - 2*S.EulerGamma)*(x**3/4 + x**2/8) - x + x**2*(-log(x)/4 + \
log(2)/4 + S(1)/2) + x**3*(-log(x)/2 - S(7)/12 + log(2)/2) + O(x**4*log(x))
assert besselk(0, x/(1 - x)).series(x, n=3) == const - x + x**2*(-log(x)/4 - \
S(1)/4 - S.EulerGamma/4 + log(2)/4) + O(x**3*log(x))
assert besselk(0, log(1 + x)).series(x, n=3) == const + x/2 + \
x**2*(-log(x)/4 - S.EulerGamma/4 + S(1)/24 + log(2)/4) + O(x**3*log(x))
assert besselk(1, 2*sqrt(x)).series(x, n=3) == 1/(2*sqrt(x)) + \
sqrt(x)*(log(x)/2 - S(1)/2 + S.EulerGamma) + x**(S(3)/2)*(log(x)/4 - S(5)/8 + \
S.EulerGamma/2) + x**(S(5)/2)*(log(x)/24 - S(5)/36 + S.EulerGamma/12) + O(x**3*log(x))
assert besselk(-2, sin(x)).series(x, n=4) == besselk(2, sin(x)).series(x, n=4)
def test_diff():
assert besselj(n, z).diff(z) == besselj(n - 1, z)/2 - besselj(n + 1, z)/2
assert bessely(n, z).diff(z) == bessely(n - 1, z)/2 - bessely(n + 1, z)/2
assert besseli(n, z).diff(z) == besseli(n - 1, z)/2 + besseli(n + 1, z)/2
assert besselk(n, z).diff(z) == -besselk(n - 1, z)/2 - besselk(n + 1, z)/2
assert hankel1(n, z).diff(z) == hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2
assert hankel2(n, z).diff(z) == hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2
def test_rewrite():
assert besselj(n, z).rewrite(jn) == sqrt(2*z/pi)*jn(n - S.Half, z)
assert bessely(n, z).rewrite(yn) == sqrt(2*z/pi)*yn(n - S.Half, z)
assert besseli(n, z).rewrite(besselj) == \
exp(-I*n*pi/2)*besselj(n, polar_lift(I)*z)
assert besselj(n, z).rewrite(besseli) == \
exp(I*n*pi/2)*besseli(n, polar_lift(-I)*z)
nu = randcplx()
assert tn(besselj(nu, z), besselj(nu, z).rewrite(besseli), z)
assert tn(besselj(nu, z), besselj(nu, z).rewrite(bessely), z)
assert tn(besseli(nu, z), besseli(nu, z).rewrite(besselj), z)
assert tn(besseli(nu, z), besseli(nu, z).rewrite(bessely), z)
assert tn(bessely(nu, z), bessely(nu, z).rewrite(besselj), z)
assert tn(bessely(nu, z), bessely(nu, z).rewrite(besseli), z)
assert tn(besselk(nu, z), besselk(nu, z).rewrite(besselj), z)
assert tn(besselk(nu, z), besselk(nu, z).rewrite(besseli), z)
assert tn(besselk(nu, z), besselk(nu, z).rewrite(bessely), z)
# check that a rewrite was triggered, when the order is set to a generic
# symbol 'nu'
assert yn(nu, z) != yn(nu, z).rewrite(jn)
assert hn1(nu, z) != hn1(nu, z).rewrite(jn)
assert hn2(nu, z) != hn2(nu, z).rewrite(jn)
assert jn(nu, z) != jn(nu, z).rewrite(yn)
assert hn1(nu, z) != hn1(nu, z).rewrite(yn)
assert hn2(nu, z) != hn2(nu, z).rewrite(yn)
# rewriting spherical bessel functions (SBFs) w.r.t. besselj, bessely is
# not allowed if a generic symbol 'nu' is used as the order of the SBFs
# to avoid inconsistencies (the order of bessel[jy] is allowed to be
# complex-valued, whereas SBFs are defined only for integer orders)
order = nu
for f in (besselj, bessely):
assert hn1(order, z) == hn1(order, z).rewrite(f)
assert hn2(order, z) == hn2(order, z).rewrite(f)
assert jn(order, z).rewrite(besselj) == sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(order + S.Half, z)/2
assert jn(order, z).rewrite(bessely) == (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-order - S.Half, z)/2
# for integral orders rewriting SBFs w.r.t bessel[jy] is allowed
N = Symbol('n', integer=True)
ri = randint(-11, 10)
for order in (ri, N):
for f in (besselj, bessely):
assert yn(order, z) != yn(order, z).rewrite(f)
assert jn(order, z) != jn(order, z).rewrite(f)
assert hn1(order, z) != hn1(order, z).rewrite(f)
assert hn2(order, z) != hn2(order, z).rewrite(f)
for func, refunc in product((yn, jn, hn1, hn2),
(jn, yn, besselj, bessely)):
assert tn(func(ri, z), func(ri, z).rewrite(refunc), z)
def test_expand():
assert expand_func(besselj(S.Half, z).rewrite(jn)) == \
sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
assert expand_func(bessely(S.Half, z).rewrite(yn)) == \
-sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z))
# XXX: teach sin/cos to work around arguments like
# x*exp_polar(I*pi*n/2). Then change besselsimp -> expand_func
assert besselsimp(besselj(S.Half, z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besselj(Rational(-1, 2), z)) == sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besselj(Rational(5, 2), z)) == \
-sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besselj(Rational(-5, 2), z)) == \
-sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(bessely(S.Half, z)) == \
-(sqrt(2)*cos(z))/(sqrt(pi)*sqrt(z))
assert besselsimp(bessely(Rational(-1, 2), z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(bessely(Rational(5, 2), z)) == \
sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(bessely(Rational(-5, 2), z)) == \
-sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besseli(S.Half, z)) == sqrt(2)*sinh(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besseli(Rational(-1, 2), z)) == \
sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besseli(Rational(5, 2), z)) == \
sqrt(2)*(z**2*sinh(z) - 3*z*cosh(z) + 3*sinh(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besseli(Rational(-5, 2), z)) == \
sqrt(2)*(z**2*cosh(z) - 3*z*sinh(z) + 3*cosh(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besselk(S.Half, z)) == \
besselsimp(besselk(Rational(-1, 2), z)) == sqrt(pi)*exp(-z)/(sqrt(2)*sqrt(z))
assert besselsimp(besselk(Rational(5, 2), z)) == \
besselsimp(besselk(Rational(-5, 2), z)) == \
sqrt(2)*sqrt(pi)*(z**2 + 3*z + 3)*exp(-z)/(2*z**Rational(5, 2))
n = Symbol('n', integer=True, positive=True)
assert expand_func(besseli(n + 2, z)) == \
besseli(n, z) + (-2*n - 2)*(-2*n*besseli(n, z)/z + besseli(n - 1, z))/z
assert expand_func(besselj(n + 2, z)) == \
-besselj(n, z) + (2*n + 2)*(2*n*besselj(n, z)/z - besselj(n - 1, z))/z
assert expand_func(besselk(n + 2, z)) == \
besselk(n, z) + (2*n + 2)*(2*n*besselk(n, z)/z + besselk(n - 1, z))/z
assert expand_func(bessely(n + 2, z)) == \
-bessely(n, z) + (2*n + 2)*(2*n*bessely(n, z)/z - bessely(n - 1, z))/z
assert expand_func(besseli(n + S.Half, z).rewrite(jn)) == \
(sqrt(2)*sqrt(z)*exp(-I*pi*(n + S.Half)/2) *
exp_polar(I*pi/4)*jn(n, z*exp_polar(I*pi/2))/sqrt(pi))
assert expand_func(besselj(n + S.Half, z).rewrite(jn)) == \
sqrt(2)*sqrt(z)*jn(n, z)/sqrt(pi)
r = Symbol('r', real=True)
p = Symbol('p', positive=True)
i = Symbol('i', integer=True)
for besselx in [besselj, bessely, besseli, besselk]:
assert besselx(i, p).is_extended_real is True
assert besselx(i, x).is_extended_real is None
assert besselx(x, z).is_extended_real is None
for besselx in [besselj, besseli]:
assert besselx(i, r).is_extended_real is True
for besselx in [bessely, besselk]:
assert besselx(i, r).is_extended_real is None
for besselx in [besselj, bessely, besseli, besselk]:
assert expand_func(besselx(oo, x)) == besselx(oo, x, evaluate=False)
assert expand_func(besselx(-oo, x)) == besselx(-oo, x, evaluate=False)
# Quite varying time, but often really slow
@slow
def test_slow_expand():
def check(eq, ans):
return tn(eq, ans) and eq == ans
rn = randcplx(a=1, b=0, d=0, c=2)
for besselx in [besselj, bessely, besseli, besselk]:
ri = S(2*randint(-11, 10) + 1) / 2 # half integer in [-21/2, 21/2]
assert tn(besselsimp(besselx(ri, z)), besselx(ri, z))
assert check(expand_func(besseli(rn, x)),
besseli(rn - 2, x) - 2*(rn - 1)*besseli(rn - 1, x)/x)
assert check(expand_func(besseli(-rn, x)),
besseli(-rn + 2, x) + 2*(-rn + 1)*besseli(-rn + 1, x)/x)
assert check(expand_func(besselj(rn, x)),
-besselj(rn - 2, x) + 2*(rn - 1)*besselj(rn - 1, x)/x)
assert check(expand_func(besselj(-rn, x)),
-besselj(-rn + 2, x) + 2*(-rn + 1)*besselj(-rn + 1, x)/x)
assert check(expand_func(besselk(rn, x)),
besselk(rn - 2, x) + 2*(rn - 1)*besselk(rn - 1, x)/x)
assert check(expand_func(besselk(-rn, x)),
besselk(-rn + 2, x) - 2*(-rn + 1)*besselk(-rn + 1, x)/x)
assert check(expand_func(bessely(rn, x)),
-bessely(rn - 2, x) + 2*(rn - 1)*bessely(rn - 1, x)/x)
assert check(expand_func(bessely(-rn, x)),
-bessely(-rn + 2, x) + 2*(-rn + 1)*bessely(-rn + 1, x)/x)
def mjn(n, z):
return expand_func(jn(n, z))
def myn(n, z):
return expand_func(yn(n, z))
def test_jn():
z = symbols("z")
assert jn(0, 0) == 1
assert jn(1, 0) == 0
assert jn(-1, 0) == S.ComplexInfinity
assert jn(z, 0) == jn(z, 0, evaluate=False)
assert jn(0, oo) == 0
assert jn(0, -oo) == 0
assert mjn(0, z) == sin(z)/z
assert mjn(1, z) == sin(z)/z**2 - cos(z)/z
assert mjn(2, z) == (3/z**3 - 1/z)*sin(z) - (3/z**2) * cos(z)
assert mjn(3, z) == (15/z**4 - 6/z**2)*sin(z) + (1/z - 15/z**3)*cos(z)
assert mjn(4, z) == (1/z + 105/z**5 - 45/z**3)*sin(z) + \
(-105/z**4 + 10/z**2)*cos(z)
assert mjn(5, z) == (945/z**6 - 420/z**4 + 15/z**2)*sin(z) + \
(-1/z - 945/z**5 + 105/z**3)*cos(z)
assert mjn(6, z) == (-1/z + 10395/z**7 - 4725/z**5 + 210/z**3)*sin(z) + \
(-10395/z**6 + 1260/z**4 - 21/z**2)*cos(z)
assert expand_func(jn(n, z)) == jn(n, z)
# SBFs not defined for complex-valued orders
assert jn(2+3j, 5.2+0.3j).evalf() == jn(2+3j, 5.2+0.3j)
assert eq([jn(2, 5.2+0.3j).evalf(10)],
[0.09941975672 - 0.05452508024*I])
def test_yn():
z = symbols("z")
assert myn(0, z) == -cos(z)/z
assert myn(1, z) == -cos(z)/z**2 - sin(z)/z
assert myn(2, z) == -((3/z**3 - 1/z)*cos(z) + (3/z**2)*sin(z))
assert expand_func(yn(n, z)) == yn(n, z)
# SBFs not defined for complex-valued orders
assert yn(2+3j, 5.2+0.3j).evalf() == yn(2+3j, 5.2+0.3j)
assert eq([yn(2, 5.2+0.3j).evalf(10)],
[0.185250342 + 0.01489557397*I])
def test_sympify_yn():
assert S(15) in myn(3, pi).atoms()
assert myn(3, pi) == 15/pi**4 - 6/pi**2
def eq(a, b, tol=1e-6):
for u, v in zip(a, b):
if not (abs(u - v) < tol):
return False
return True
def test_jn_zeros():
assert eq(jn_zeros(0, 4), [3.141592, 6.283185, 9.424777, 12.566370])
assert eq(jn_zeros(1, 4), [4.493409, 7.725251, 10.904121, 14.066193])
assert eq(jn_zeros(2, 4), [5.763459, 9.095011, 12.322940, 15.514603])
assert eq(jn_zeros(3, 4), [6.987932, 10.417118, 13.698023, 16.923621])
assert eq(jn_zeros(4, 4), [8.182561, 11.704907, 15.039664, 18.301255])
def test_bessel_eval():
n, m, k = Symbol('n', integer=True), Symbol('m'), Symbol('k', integer=True, zero=False)
for f in [besselj, besseli]:
assert f(0, 0) is S.One
assert f(2.1, 0) is S.Zero
assert f(-3, 0) is S.Zero
assert f(-10.2, 0) is S.ComplexInfinity
assert f(1 + 3*I, 0) is S.Zero
assert f(-3 + I, 0) is S.ComplexInfinity
assert f(-2*I, 0) is S.NaN
assert f(n, 0) != S.One and f(n, 0) != S.Zero
assert f(m, 0) != S.One and f(m, 0) != S.Zero
assert f(k, 0) is S.Zero
assert bessely(0, 0) is S.NegativeInfinity
assert besselk(0, 0) is S.Infinity
for f in [bessely, besselk]:
assert f(1 + I, 0) is S.ComplexInfinity
assert f(I, 0) is S.NaN
for f in [besselj, bessely]:
assert f(m, S.Infinity) is S.Zero
assert f(m, S.NegativeInfinity) is S.Zero
for f in [besseli, besselk]:
assert f(m, I*S.Infinity) is S.Zero
assert f(m, I*S.NegativeInfinity) is S.Zero
for f in [besseli, besselk]:
assert f(-4, z) == f(4, z)
assert f(-3, z) == f(3, z)
assert f(-n, z) == f(n, z)
assert f(-m, z) != f(m, z)
for f in [besselj, bessely]:
assert f(-4, z) == f(4, z)
assert f(-3, z) == -f(3, z)
assert f(-n, z) == (-1)**n*f(n, z)
assert f(-m, z) != (-1)**m*f(m, z)
for f in [besselj, besseli]:
assert f(m, -z) == (-z)**m*z**(-m)*f(m, z)
assert besseli(2, -z) == besseli(2, z)
assert besseli(3, -z) == -besseli(3, z)
assert besselj(0, -z) == besselj(0, z)
assert besselj(1, -z) == -besselj(1, z)
assert besseli(0, I*z) == besselj(0, z)
assert besseli(1, I*z) == I*besselj(1, z)
assert besselj(3, I*z) == -I*besseli(3, z)
def test_bessel_nan():
# FIXME: could have these return NaN; for now just fix infinite recursion
for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, yn, jn]:
assert f(1, S.NaN) == f(1, S.NaN, evaluate=False)
def test_meromorphic():
assert besselj(2, x).is_meromorphic(x, 1) == True
assert besselj(2, x).is_meromorphic(x, 0) == True
assert besselj(2, x).is_meromorphic(x, oo) == False
assert besselj(S(2)/3, x).is_meromorphic(x, 1) == True
assert besselj(S(2)/3, x).is_meromorphic(x, 0) == False
assert besselj(S(2)/3, x).is_meromorphic(x, oo) == False
assert besselj(x, 2*x).is_meromorphic(x, 2) == False
assert besselk(0, x).is_meromorphic(x, 1) == True
assert besselk(2, x).is_meromorphic(x, 0) == True
assert besseli(0, x).is_meromorphic(x, 1) == True
assert besseli(2, x).is_meromorphic(x, 0) == True
assert bessely(0, x).is_meromorphic(x, 1) == True
assert bessely(0, x).is_meromorphic(x, 0) == False
assert bessely(2, x).is_meromorphic(x, 0) == True
assert hankel1(3, x**2 + 2*x).is_meromorphic(x, 1) == True
assert hankel1(0, x).is_meromorphic(x, 0) == False
assert hankel2(11, 4).is_meromorphic(x, 5) == True
assert hn1(6, 7*x**3 + 4).is_meromorphic(x, 7) == True
assert hn2(3, 2*x).is_meromorphic(x, 9) == True
assert jn(5, 2*x + 7).is_meromorphic(x, 4) == True
assert yn(8, x**2 + 11).is_meromorphic(x, 6) == True
def test_conjugate():
n = Symbol('n')
z = Symbol('z', extended_real=False)
x = Symbol('x', extended_real=True)
y = Symbol('y', positive=True)
t = Symbol('t', negative=True)
for f in [besseli, besselj, besselk, bessely, hankel1, hankel2]:
assert f(n, -1).conjugate() != f(conjugate(n), -1)
assert f(n, x).conjugate() != f(conjugate(n), x)
assert f(n, t).conjugate() != f(conjugate(n), t)
rz = randcplx(b=0.5)
for f in [besseli, besselj, besselk, bessely]:
assert f(n, 1 + I).conjugate() == f(conjugate(n), 1 - I)
assert f(n, 0).conjugate() == f(conjugate(n), 0)
assert f(n, 1).conjugate() == f(conjugate(n), 1)
assert f(n, z).conjugate() == f(conjugate(n), conjugate(z))
assert f(n, y).conjugate() == f(conjugate(n), y)
assert tn(f(n, rz).conjugate(), f(conjugate(n), conjugate(rz)))
assert hankel1(n, 1 + I).conjugate() == hankel2(conjugate(n), 1 - I)
assert hankel1(n, 0).conjugate() == hankel2(conjugate(n), 0)
assert hankel1(n, 1).conjugate() == hankel2(conjugate(n), 1)
assert hankel1(n, y).conjugate() == hankel2(conjugate(n), y)
assert hankel1(n, z).conjugate() == hankel2(conjugate(n), conjugate(z))
assert tn(hankel1(n, rz).conjugate(), hankel2(conjugate(n), conjugate(rz)))
assert hankel2(n, 1 + I).conjugate() == hankel1(conjugate(n), 1 - I)
assert hankel2(n, 0).conjugate() == hankel1(conjugate(n), 0)
assert hankel2(n, 1).conjugate() == hankel1(conjugate(n), 1)
assert hankel2(n, y).conjugate() == hankel1(conjugate(n), y)
assert hankel2(n, z).conjugate() == hankel1(conjugate(n), conjugate(z))
assert tn(hankel2(n, rz).conjugate(), hankel1(conjugate(n), conjugate(rz)))
def test_branching():
assert besselj(polar_lift(k), x) == besselj(k, x)
assert besseli(polar_lift(k), x) == besseli(k, x)
n = Symbol('n', integer=True)
assert besselj(n, exp_polar(2*pi*I)*x) == besselj(n, x)
assert besselj(n, polar_lift(x)) == besselj(n, x)
assert besseli(n, exp_polar(2*pi*I)*x) == besseli(n, x)
assert besseli(n, polar_lift(x)) == besseli(n, x)
def tn(func, s):
from sympy.core.random import uniform
c = uniform(1, 5)
expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi))
eps = 1e-15
expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I)
return abs(expr.n() - expr2.n()).n() < 1e-10
nu = Symbol('nu')
assert besselj(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besselj(nu, x)
assert besseli(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besseli(nu, x)
assert tn(besselj, 2)
assert tn(besselj, pi)
assert tn(besselj, I)
assert tn(besseli, 2)
assert tn(besseli, pi)
assert tn(besseli, I)
def test_airy_base():
z = Symbol('z')
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert conjugate(airyai(z)) == airyai(conjugate(z))
assert airyai(x).is_extended_real
assert airyai(x+I*y).as_real_imag() == (
airyai(x - I*y)/2 + airyai(x + I*y)/2,
I*(airyai(x - I*y) - airyai(x + I*y))/2)
def test_airyai():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airyai(z), airyai)
assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3)))
assert airyai(oo) == 0
assert airyai(-oo) == 0
assert diff(airyai(z), z) == airyaiprime(z)
assert series(airyai(z), z, 0, 3) == (
3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3))
assert airyai(z).rewrite(hyper) == (
-3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) +
3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3))))
assert isinstance(airyai(z).rewrite(besselj), airyai)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airyai(z).rewrite(besseli) == (
-z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) +
(z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3)
assert airyai(p).rewrite(besseli) == (
sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) -
besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == (
-sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 +
(1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_airybi():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airybi(z), airybi)
assert airybi(0) == 3**Rational(5, 6)/(3*gamma(Rational(2, 3)))
assert airybi(oo) is oo
assert airybi(-oo) == 0
assert diff(airybi(z), z) == airybiprime(z)
assert series(airybi(z), z, 0, 3) == (
3**Rational(1, 3)*gamma(Rational(1, 3))/(2*pi) + 3**Rational(2, 3)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3))
assert airybi(z).rewrite(hyper) == (
3**Rational(1, 6)*z*hyper((), (Rational(4, 3),), z**3/9)/gamma(Rational(1, 3)) +
3**Rational(5, 6)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3))))
assert isinstance(airybi(z).rewrite(besselj), airybi)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airybi(z).rewrite(besseli) == (
sqrt(3)*(z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(1, 3) +
(z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3))/3)
assert airybi(p).rewrite(besseli) == (
sqrt(3)*sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) +
besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airybi(2*(3*z**5)**Rational(1, 3))) == (
sqrt(3)*(1 - (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2 +
(1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_airyaiprime():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airyaiprime(z), airyaiprime)
assert airyaiprime(0) == -3**Rational(2, 3)/(3*gamma(Rational(1, 3)))
assert airyaiprime(oo) == 0
assert diff(airyaiprime(z), z) == z*airyai(z)
assert series(airyaiprime(z), z, 0, 3) == (
-3**Rational(2, 3)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*z**2/(6*gamma(Rational(2, 3))) + O(z**3))
assert airyaiprime(z).rewrite(hyper) == (
3**Rational(1, 3)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) -
3**Rational(2, 3)*hyper((), (Rational(1, 3),), z**3/9)/(3*gamma(Rational(1, 3))))
assert isinstance(airyaiprime(z).rewrite(besselj), airyaiprime)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airyaiprime(z).rewrite(besseli) == (
z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(2, 3)) -
(z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3)
assert airyaiprime(p).rewrite(besseli) == (
p*(-besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airyaiprime(2*(3*z**5)**Rational(1, 3))) == (
sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/6 +
(z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_airybiprime():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airybiprime(z), airybiprime)
assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3))
assert airybiprime(oo) is oo
assert airybiprime(-oo) == 0
assert diff(airybiprime(z), z) == z*airybi(z)
assert series(airybiprime(z), z, 0, 3) == (
3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3))
assert airybiprime(z).rewrite(hyper) == (
3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) +
3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3)))
assert isinstance(airybiprime(z).rewrite(besselj), airybiprime)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airybiprime(z).rewrite(besseli) == (
sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) +
(z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3)
assert airybiprime(p).rewrite(besseli) == (
sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == (
sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 +
(z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_marcumq():
m = Symbol('m')
a = Symbol('a')
b = Symbol('b')
assert marcumq(0, 0, 0) == 0
assert marcumq(m, 0, b) == uppergamma(m, b**2/2)/gamma(m)
assert marcumq(2, 0, 5) == 27*exp(Rational(-25, 2))/2
assert marcumq(0, a, 0) == 1 - exp(-a**2/2)
assert marcumq(0, pi, 0) == 1 - exp(-pi**2/2)
assert marcumq(1, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2
assert marcumq(2, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2)
assert diff(marcumq(1, a, 3), a) == a*(-marcumq(1, a, 3) + marcumq(2, a, 3))
assert diff(marcumq(2, 3, b), b) == -b**2*exp(-b**2/2 - Rational(9, 2))*besseli(1, 3*b)/3
x = Symbol('x')
assert marcumq(2, 3, 4).rewrite(Integral, x=x) == \
Integral(x**2*exp(-x**2/2 - Rational(9, 2))*besseli(1, 3*x), (x, 4, oo))/3
assert eq([marcumq(5, -2, 3).rewrite(Integral).evalf(10)],
[0.7905769565])
k = Symbol('k')
assert marcumq(-3, -5, -7).rewrite(Sum, k=k) == \
exp(-37)*Sum((Rational(5, 7))**k*besseli(k, 35), (k, 4, oo))
assert eq([marcumq(1, 3, 1).rewrite(Sum).evalf(10)],
[0.9891705502])
assert marcumq(1, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2
assert marcumq(2, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + \
exp(-a**2)*besseli(1, a**2)
assert marcumq(3, a, a).rewrite(besseli) == (besseli(1, a**2) + besseli(2, a**2))*exp(-a**2) + \
S.Half + exp(-a**2)*besseli(0, a**2)/2
assert marcumq(5, 8, 8).rewrite(besseli) == exp(-64)*besseli(0, 64)/2 + \
(besseli(4, 64) + besseli(3, 64) + besseli(2, 64) + besseli(1, 64))*exp(-64) + S.Half
assert marcumq(m, a, a).rewrite(besseli) == marcumq(m, a, a)
x = Symbol('x', integer=True)
assert marcumq(x, a, a).rewrite(besseli) == marcumq(x, a, a)
|
c2e899691fcbc1a33c4a536e1a5dc1d69e1e3870bffb365549730f35fcca441e | from sympy.concrete.summations import Sum
from sympy.core.function import (Derivative, diff)
from sympy.core.numbers import (Rational, oo, pi, zoo)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol)
from sympy.functions.combinatorial.factorials import (RisingFactorial, binomial, factorial)
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import hyper
from sympy.functions.special.polynomials import (assoc_laguerre, assoc_legendre, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, gegenbauer, hermite, hermite_prob, jacobi, jacobi_normalized, laguerre, legendre)
from sympy.polys.orthopolys import laguerre_poly
from sympy.polys.polyroots import roots
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.testing.pytest import raises
x = Symbol('x')
def test_jacobi():
n = Symbol("n")
a = Symbol("a")
b = Symbol("b")
assert jacobi(0, a, b, x) == 1
assert jacobi(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1)
assert jacobi(n, a, a, x) == RisingFactorial(
a + 1, n)*gegenbauer(n, a + S.Half, x)/RisingFactorial(2*a + 1, n)
assert jacobi(n, a, -a, x) == ((-1)**a*(-x + 1)**(-a/2)*(x + 1)**(a/2)*assoc_legendre(n, a, x)*
factorial(-a + n)*gamma(a + n + 1)/(factorial(a + n)*gamma(n + 1)))
assert jacobi(n, -b, b, x) == ((-x + 1)**(b/2)*(x + 1)**(-b/2)*assoc_legendre(n, b, x)*
gamma(-b + n + 1)/gamma(n + 1))
assert jacobi(n, 0, 0, x) == legendre(n, x)
assert jacobi(n, S.Half, S.Half, x) == RisingFactorial(
Rational(3, 2), n)*chebyshevu(n, x)/factorial(n + 1)
assert jacobi(n, Rational(-1, 2), Rational(-1, 2), x) == RisingFactorial(
S.Half, n)*chebyshevt(n, x)/factorial(n)
X = jacobi(n, a, b, x)
assert isinstance(X, jacobi)
assert jacobi(n, a, b, -x) == (-1)**n*jacobi(n, b, a, x)
assert jacobi(n, a, b, 0) == 2**(-n)*gamma(a + n + 1)*hyper(
(-b - n, -n), (a + 1,), -1)/(factorial(n)*gamma(a + 1))
assert jacobi(n, a, b, 1) == RisingFactorial(a + 1, n)/factorial(n)
m = Symbol("m", positive=True)
assert jacobi(m, a, b, oo) == oo*RisingFactorial(a + b + m + 1, m)
assert unchanged(jacobi, n, a, b, oo)
assert conjugate(jacobi(m, a, b, x)) == \
jacobi(m, conjugate(a), conjugate(b), conjugate(x))
_k = Dummy('k')
assert diff(jacobi(n, a, b, x), n) == Derivative(jacobi(n, a, b, x), n)
assert diff(jacobi(n, a, b, x), a).dummy_eq(Sum((jacobi(n, a, b, x) +
(2*_k + a + b + 1)*RisingFactorial(_k + b + 1, -_k + n)*jacobi(_k, a,
b, x)/((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)))/(_k + a
+ b + n + 1), (_k, 0, n - 1)))
assert diff(jacobi(n, a, b, x), b).dummy_eq(Sum(((-1)**(-_k + n)*(2*_k +
a + b + 1)*RisingFactorial(_k + a + 1, -_k + n)*jacobi(_k, a, b, x)/
((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)) + jacobi(n, a,
b, x))/(_k + a + b + n + 1), (_k, 0, n - 1)))
assert diff(jacobi(n, a, b, x), x) == \
(a/2 + b/2 + n/2 + S.Half)*jacobi(n - 1, a + 1, b + 1, x)
assert jacobi_normalized(n, a, b, x) == \
(jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)
/((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1))))
raises(ValueError, lambda: jacobi(-2.1, a, b, x))
raises(ValueError, lambda: jacobi(Dummy(positive=True, integer=True), 1, 2, oo))
assert jacobi(n, a, b, x).rewrite(Sum).dummy_eq(Sum((S.Half - x/2)
**_k*RisingFactorial(-n, _k)*RisingFactorial(_k + a + 1, -_k + n)*
RisingFactorial(a + b + n + 1, _k)/factorial(_k), (_k, 0, n))/factorial(n))
assert jacobi(n, a, b, x).rewrite("polynomial").dummy_eq(Sum((S.Half - x/2)
**_k*RisingFactorial(-n, _k)*RisingFactorial(_k + a + 1, -_k + n)*
RisingFactorial(a + b + n + 1, _k)/factorial(_k), (_k, 0, n))/factorial(n))
raises(ArgumentIndexError, lambda: jacobi(n, a, b, x).fdiff(5))
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(Sum).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))))
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 test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) == ((3*x**2 - 1)/2).expand()
assert legendre(3, x) == ((5*x**3 - 3*x)/2).expand()
assert legendre(4, x) == ((35*x**4 - 30*x**2 + 3)/8).expand()
assert legendre(5, x) == ((63*x**5 - 70*x**3 + 15*x)/8).expand()
assert legendre(6, x) == ((231*x**6 - 315*x**4 + 105*x**2 - 5)/16).expand()
assert legendre(10, -1) == 1
assert legendre(11, -1) == -1
assert legendre(10, 1) == 1
assert legendre(11, 1) == 1
assert legendre(10, 0) != 0
assert legendre(11, 0) == 0
assert legendre(-1, x) == 1
k = Symbol('k')
assert legendre(5 - k, x).subs(k, 2) == ((5*x**3 - 3*x)/2).expand()
assert roots(legendre(4, x), x) == {
sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
-sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
-sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
}
n = Symbol("n")
X = legendre(n, x)
assert isinstance(X, legendre)
assert unchanged(legendre, n, x)
assert legendre(n, 0) == sqrt(pi)/(gamma(S.Half - n/2)*gamma(n/2 + 1))
assert legendre(n, 1) == 1
assert legendre(n, oo) is oo
assert legendre(-n, x) == legendre(n - 1, x)
assert legendre(n, -x) == (-1)**n*legendre(n, x)
assert unchanged(legendre, -n + k, x)
assert conjugate(legendre(n, x)) == legendre(n, conjugate(x))
assert diff(legendre(n, x), x) == \
n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1)
assert diff(legendre(n, x), n) == Derivative(legendre(n, x), n)
_k = Dummy('k')
assert legendre(n, x).rewrite(Sum).dummy_eq(Sum((-1)**_k*(S.Half -
x/2)**_k*(x/2 + S.Half)**(-_k + n)*binomial(n, _k)**2, (_k, 0, n)))
assert legendre(n, x).rewrite("polynomial").dummy_eq(Sum((-1)**_k*(S.Half -
x/2)**_k*(x/2 + S.Half)**(-_k + n)*binomial(n, _k)**2, (_k, 0, n)))
raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(1))
raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(3))
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(Sum).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 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 test_chebyshev():
assert chebyshevt(0, x) == 1
assert chebyshevt(1, x) == x
assert chebyshevt(2, x) == 2*x**2 - 1
assert chebyshevt(3, x) == 4*x**3 - 3*x
for n in range(1, 4):
for k in range(n):
z = chebyshevt_root(n, k)
assert chebyshevt(n, z) == 0
raises(ValueError, lambda: chebyshevt_root(n, n))
for n in range(1, 4):
for k in range(n):
z = chebyshevu_root(n, k)
assert chebyshevu(n, z) == 0
raises(ValueError, lambda: chebyshevu_root(n, n))
n = Symbol("n")
X = chebyshevt(n, x)
assert isinstance(X, chebyshevt)
assert unchanged(chebyshevt, n, x)
assert chebyshevt(n, -x) == (-1)**n*chebyshevt(n, x)
assert chebyshevt(-n, x) == chebyshevt(n, x)
assert chebyshevt(n, 0) == cos(pi*n/2)
assert chebyshevt(n, 1) == 1
assert chebyshevt(n, oo) is oo
assert conjugate(chebyshevt(n, x)) == chebyshevt(n, conjugate(x))
assert diff(chebyshevt(n, x), x) == n*chebyshevu(n - 1, x)
X = chebyshevu(n, x)
assert isinstance(X, chebyshevu)
y = Symbol('y')
assert chebyshevu(n, -x) == (-1)**n*chebyshevu(n, x)
assert chebyshevu(-n, x) == -chebyshevu(n - 2, x)
assert unchanged(chebyshevu, -n + y, x)
assert chebyshevu(n, 0) == cos(pi*n/2)
assert chebyshevu(n, 1) == n + 1
assert chebyshevu(n, oo) is oo
assert conjugate(chebyshevu(n, x)) == chebyshevu(n, conjugate(x))
assert diff(chebyshevu(n, x), x) == \
(-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1)
_k = Dummy('k')
assert chebyshevt(n, x).rewrite(Sum).dummy_eq(Sum(x**(-2*_k + n)
*(x**2 - 1)**_k*binomial(n, 2*_k), (_k, 0, floor(n/2))))
assert chebyshevt(n, x).rewrite("polynomial").dummy_eq(Sum(x**(-2*_k + n)
*(x**2 - 1)**_k*binomial(n, 2*_k), (_k, 0, floor(n/2))))
assert chebyshevu(n, x).rewrite(Sum).dummy_eq(Sum((-1)**_k*(2*x)
**(-2*_k + n)*factorial(-_k + n)/(factorial(_k)*
factorial(-2*_k + n)), (_k, 0, floor(n/2))))
assert chebyshevu(n, x).rewrite("polynomial").dummy_eq(Sum((-1)**_k*(2*x)
**(-2*_k + n)*factorial(-_k + n)/(factorial(_k)*
factorial(-2*_k + n)), (_k, 0, floor(n/2))))
raises(ArgumentIndexError, lambda: chebyshevt(n, x).fdiff(1))
raises(ArgumentIndexError, lambda: chebyshevt(n, x).fdiff(3))
raises(ArgumentIndexError, lambda: chebyshevu(n, x).fdiff(1))
raises(ArgumentIndexError, lambda: chebyshevu(n, x).fdiff(3))
def test_hermite():
assert hermite(0, x) == 1
assert hermite(1, x) == 2*x
assert hermite(2, x) == 4*x**2 - 2
assert hermite(3, x) == 8*x**3 - 12*x
assert hermite(4, x) == 16*x**4 - 48*x**2 + 12
assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
n = Symbol("n")
assert unchanged(hermite, n, x)
assert hermite(n, -x) == (-1)**n*hermite(n, x)
assert unchanged(hermite, -n, x)
assert hermite(n, 0) == 2**n*sqrt(pi)/gamma(S.Half - n/2)
assert hermite(n, oo) is oo
assert conjugate(hermite(n, x)) == hermite(n, conjugate(x))
_k = Dummy('k')
assert hermite(n, x).rewrite(Sum).dummy_eq(factorial(n)*Sum((-1)
**_k*(2*x)**(-2*_k + n)/(factorial(_k)*factorial(-2*_k + n)), (_k,
0, floor(n/2))))
assert hermite(n, x).rewrite("polynomial").dummy_eq(factorial(n)*Sum((-1)
**_k*(2*x)**(-2*_k + n)/(factorial(_k)*factorial(-2*_k + n)), (_k,
0, floor(n/2))))
assert diff(hermite(n, x), x) == 2*n*hermite(n - 1, x)
assert diff(hermite(n, x), n) == Derivative(hermite(n, x), n)
raises(ArgumentIndexError, lambda: hermite(n, x).fdiff(3))
assert hermite(n, x).rewrite(hermite_prob) == \
sqrt(2)**n * hermite_prob(n, x*sqrt(2))
def test_hermite_prob():
assert hermite_prob(0, x) == 1
assert hermite_prob(1, x) == x
assert hermite_prob(2, x) == x**2 - 1
assert hermite_prob(3, x) == x**3 - 3*x
assert hermite_prob(4, x) == x**4 - 6*x**2 + 3
assert hermite_prob(6, x) == x**6 - 15*x**4 + 45*x**2 - 15
n = Symbol("n")
assert unchanged(hermite_prob, n, x)
assert hermite_prob(n, -x) == (-1)**n*hermite_prob(n, x)
assert unchanged(hermite_prob, -n, x)
assert hermite_prob(n, 0) == sqrt(pi)/gamma(S.Half - n/2)
assert hermite_prob(n, oo) is oo
assert conjugate(hermite_prob(n, x)) == hermite_prob(n, conjugate(x))
_k = Dummy('k')
assert hermite_prob(n, x).rewrite(Sum).dummy_eq(factorial(n) *
Sum((-S.Half)**_k * x**(n-2*_k) / (factorial(_k) * factorial(n-2*_k)),
(_k, 0, floor(n/2))))
assert hermite_prob(n, x).rewrite("polynomial").dummy_eq(factorial(n) *
Sum((-S.Half)**_k * x**(n-2*_k) / (factorial(_k) * factorial(n-2*_k)),
(_k, 0, floor(n/2))))
assert diff(hermite_prob(n, x), x) == n*hermite_prob(n-1, x)
assert diff(hermite_prob(n, x), n) == Derivative(hermite_prob(n, x), n)
raises(ArgumentIndexError, lambda: hermite_prob(n, x).fdiff(3))
assert hermite_prob(n, x).rewrite(hermite) == \
sqrt(2)**(-n) * hermite(n, x/sqrt(2))
def test_laguerre():
n = Symbol("n")
m = Symbol("m", negative=True)
# Laguerre polynomials:
assert laguerre(0, x) == 1
assert laguerre(1, x) == -x + 1
assert laguerre(2, x) == x**2/2 - 2*x + 1
assert laguerre(3, x) == -x**3/6 + 3*x**2/2 - 3*x + 1
assert laguerre(-2, x) == (x + 1)*exp(x)
X = laguerre(n, x)
assert isinstance(X, laguerre)
assert laguerre(n, 0) == 1
assert laguerre(n, oo) == (-1)**n*oo
assert laguerre(n, -oo) is oo
assert conjugate(laguerre(n, x)) == laguerre(n, conjugate(x))
_k = Dummy('k')
assert laguerre(n, x).rewrite(Sum).dummy_eq(
Sum(x**_k*RisingFactorial(-n, _k)/factorial(_k)**2, (_k, 0, n)))
assert laguerre(n, x).rewrite("polynomial").dummy_eq(
Sum(x**_k*RisingFactorial(-n, _k)/factorial(_k)**2, (_k, 0, n)))
assert laguerre(m, x).rewrite(Sum).dummy_eq(
exp(x)*Sum((-x)**_k*RisingFactorial(m + 1, _k)/factorial(_k)**2,
(_k, 0, -m - 1)))
assert laguerre(m, x).rewrite("polynomial").dummy_eq(
exp(x)*Sum((-x)**_k*RisingFactorial(m + 1, _k)/factorial(_k)**2,
(_k, 0, -m - 1)))
assert diff(laguerre(n, x), x) == -assoc_laguerre(n - 1, 1, x)
k = Symbol('k')
assert laguerre(-n, x) == exp(x)*laguerre(n - 1, -x)
assert laguerre(-3, x) == exp(x)*laguerre(2, -x)
assert unchanged(laguerre, -n + k, x)
raises(ValueError, lambda: laguerre(-2.1, x))
raises(ValueError, lambda: laguerre(Rational(5, 2), x))
raises(ArgumentIndexError, lambda: laguerre(n, x).fdiff(1))
raises(ArgumentIndexError, lambda: laguerre(n, x).fdiff(3))
def test_assoc_laguerre():
n = Symbol("n")
m = Symbol("m")
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert assoc_laguerre(0, alpha, x) == 1
assert assoc_laguerre(1, alpha, x) == -x + alpha + 1
assert assoc_laguerre(2, alpha, x).expand() == \
(x**2/2 - (alpha + 2)*x + (alpha + 2)*(alpha + 1)/2).expand()
assert assoc_laguerre(3, alpha, x).expand() == \
(-x**3/6 + (alpha + 3)*x**2/2 - (alpha + 2)*(alpha + 3)*x/2 +
(alpha + 1)*(alpha + 2)*(alpha + 3)/6).expand()
# Test the lowest 10 polynomials with laguerre_poly, to make sure it works:
for i in range(10):
assert assoc_laguerre(i, 0, x).expand() == laguerre_poly(i, x)
X = assoc_laguerre(n, m, x)
assert isinstance(X, assoc_laguerre)
assert assoc_laguerre(n, 0, x) == laguerre(n, x)
assert assoc_laguerre(n, alpha, 0) == binomial(alpha + n, alpha)
p = Symbol("p", positive=True)
assert assoc_laguerre(p, alpha, oo) == (-1)**p*oo
assert assoc_laguerre(p, alpha, -oo) is oo
assert diff(assoc_laguerre(n, alpha, x), x) == \
-assoc_laguerre(n - 1, alpha + 1, x)
_k = Dummy('k')
assert diff(assoc_laguerre(n, alpha, x), alpha).dummy_eq(
Sum(assoc_laguerre(_k, alpha, x)/(-alpha + n), (_k, 0, n - 1)))
assert conjugate(assoc_laguerre(n, alpha, x)) == \
assoc_laguerre(n, conjugate(alpha), conjugate(x))
assert assoc_laguerre(n, alpha, x).rewrite(Sum).dummy_eq(
gamma(alpha + n + 1)*Sum(x**_k*RisingFactorial(-n, _k)/
(factorial(_k)*gamma(_k + alpha + 1)), (_k, 0, n))/factorial(n))
assert assoc_laguerre(n, alpha, x).rewrite("polynomial").dummy_eq(
gamma(alpha + n + 1)*Sum(x**_k*RisingFactorial(-n, _k)/
(factorial(_k)*gamma(_k + alpha + 1)), (_k, 0, n))/factorial(n))
raises(ValueError, lambda: assoc_laguerre(-2.1, alpha, x))
raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(1))
raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(4))
|
7b11e6144b7264c2615584d6152065319856761424e8cd9c8e0364bc8983ee8e | from sympy.core.function import expand_func, Subs
from sympy.core import EulerGamma
from sympy.core.numbers import (I, Rational, nan, oo, pi, zoo)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.combinatorial.numbers import harmonic
from sympy.functions.elementary.complexes import (Abs, conjugate, im, re)
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import tanh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin, atan)
from sympy.functions.special.error_functions import (Ei, erf, erfc)
from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, lowergamma, multigamma, polygamma, trigamma, uppergamma)
from sympy.functions.special.zeta_functions import zeta
from sympy.series.order import O
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.testing.pytest import raises
from sympy.core.random import (test_derivative_numerically as td,
random_complex_number as randcplx,
verify_numerically as tn)
x = Symbol('x')
y = Symbol('y')
n = Symbol('n', integer=True)
w = Symbol('w', real=True)
def test_gamma():
assert gamma(nan) is nan
assert gamma(oo) is oo
assert gamma(-100) is zoo
assert gamma(0) is zoo
assert gamma(-100.0) is zoo
assert gamma(1) == 1
assert gamma(2) == 1
assert gamma(3) == 2
assert gamma(102) == factorial(101)
assert gamma(S.Half) == sqrt(pi)
assert gamma(Rational(3, 2)) == sqrt(pi)*S.Half
assert gamma(Rational(5, 2)) == sqrt(pi)*Rational(3, 4)
assert gamma(Rational(7, 2)) == sqrt(pi)*Rational(15, 8)
assert gamma(Rational(-1, 2)) == -2*sqrt(pi)
assert gamma(Rational(-3, 2)) == sqrt(pi)*Rational(4, 3)
assert gamma(Rational(-5, 2)) == sqrt(pi)*Rational(-8, 15)
assert gamma(Rational(-15, 2)) == sqrt(pi)*Rational(256, 2027025)
assert gamma(Rational(
-11, 8)).expand(func=True) == Rational(64, 33)*gamma(Rational(5, 8))
assert gamma(Rational(
-10, 3)).expand(func=True) == Rational(81, 280)*gamma(Rational(2, 3))
assert gamma(Rational(
14, 3)).expand(func=True) == Rational(880, 81)*gamma(Rational(2, 3))
assert gamma(Rational(
17, 7)).expand(func=True) == Rational(30, 49)*gamma(Rational(3, 7))
assert gamma(Rational(
19, 8)).expand(func=True) == Rational(33, 64)*gamma(Rational(3, 8))
assert gamma(x).diff(x) == gamma(x)*polygamma(0, x)
assert gamma(x - 1).expand(func=True) == gamma(x)/(x - 1)
assert gamma(x + 2).expand(func=True, mul=False) == x*(x + 1)*gamma(x)
assert conjugate(gamma(x)) == gamma(conjugate(x))
assert expand_func(gamma(x + Rational(3, 2))) == \
(x + S.Half)*gamma(x + S.Half)
assert expand_func(gamma(x - S.Half)) == \
gamma(S.Half + x)/(x - S.Half)
# Test a bug:
assert expand_func(gamma(x + Rational(3, 4))) == gamma(x + Rational(3, 4))
# XXX: Not sure about these tests. I can fix them by defining e.g.
# exp_polar.is_integer but I'm not sure if that makes sense.
assert gamma(3*exp_polar(I*pi)/4).is_nonnegative is False
assert gamma(3*exp_polar(I*pi)/4).is_extended_nonpositive is True
y = Symbol('y', nonpositive=True, integer=True)
assert gamma(y).is_real == False
y = Symbol('y', positive=True, noninteger=True)
assert gamma(y).is_real == True
assert gamma(-1.0, evaluate=False).is_real == False
assert gamma(0, evaluate=False).is_real == False
assert gamma(-2, evaluate=False).is_real == False
def test_gamma_rewrite():
assert gamma(n).rewrite(factorial) == factorial(n - 1)
def test_gamma_series():
assert gamma(x + 1).series(x, 0, 3) == \
1 - EulerGamma*x + x**2*(EulerGamma**2/2 + pi**2/12) + O(x**3)
assert gamma(x).series(x, -1, 3) == \
-1/(x + 1) + EulerGamma - 1 + (x + 1)*(-1 - pi**2/12 - EulerGamma**2/2 + \
EulerGamma) + (x + 1)**2*(-1 - pi**2/12 - EulerGamma**2/2 + EulerGamma**3/6 - \
polygamma(2, 1)/6 + EulerGamma*pi**2/12 + EulerGamma) + O((x + 1)**3, (x, -1))
def tn_branch(s, func):
from sympy.core.random import uniform
c = uniform(1, 5)
expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi))
eps = 1e-15
expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I)
return abs(expr.n() - expr2.n()).n() < 1e-10
def test_lowergamma():
from sympy.functions.special.error_functions import expint
from sympy.functions.special.hyper import meijerg
assert lowergamma(x, 0) == 0
assert lowergamma(x, y).diff(y) == y**(x - 1)*exp(-y)
assert td(lowergamma(randcplx(), y), y)
assert td(lowergamma(x, randcplx()), x)
assert lowergamma(x, y).diff(x) == \
gamma(x)*digamma(x) - uppergamma(x, y)*log(y) \
- meijerg([], [1, 1], [0, 0, x], [], y)
assert lowergamma(S.Half, x) == sqrt(pi)*erf(sqrt(x))
assert not lowergamma(S.Half - 3, x).has(lowergamma)
assert not lowergamma(S.Half + 3, x).has(lowergamma)
assert lowergamma(S.Half, x, evaluate=False).has(lowergamma)
assert tn(lowergamma(S.Half + 3, x, evaluate=False),
lowergamma(S.Half + 3, x), x)
assert tn(lowergamma(S.Half - 3, x, evaluate=False),
lowergamma(S.Half - 3, x), x)
assert tn_branch(-3, lowergamma)
assert tn_branch(-4, lowergamma)
assert tn_branch(Rational(1, 3), lowergamma)
assert tn_branch(pi, lowergamma)
assert lowergamma(3, exp_polar(4*pi*I)*x) == lowergamma(3, x)
assert lowergamma(y, exp_polar(5*pi*I)*x) == \
exp(4*I*pi*y)*lowergamma(y, x*exp_polar(pi*I))
assert lowergamma(-2, exp_polar(5*pi*I)*x) == \
lowergamma(-2, x*exp_polar(I*pi)) + 2*pi*I
assert conjugate(lowergamma(x, y)) == lowergamma(conjugate(x), conjugate(y))
assert conjugate(lowergamma(x, 0)) == 0
assert unchanged(conjugate, lowergamma(x, -oo))
assert lowergamma(0, x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(S(1)/3, x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(1, x, evaluate=False)._eval_is_meromorphic(x, 0) == True
assert lowergamma(x, x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(x + 1, x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(1/x, x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(0, x + 1)._eval_is_meromorphic(x, 0) == False
assert lowergamma(S(1)/3, x + 1)._eval_is_meromorphic(x, 0) == True
assert lowergamma(1, x + 1, evaluate=False)._eval_is_meromorphic(x, 0) == True
assert lowergamma(x, x + 1)._eval_is_meromorphic(x, 0) == True
assert lowergamma(x + 1, x + 1)._eval_is_meromorphic(x, 0) == True
assert lowergamma(1/x, x + 1)._eval_is_meromorphic(x, 0) == False
assert lowergamma(0, 1/x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(S(1)/3, 1/x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(1, 1/x, evaluate=False)._eval_is_meromorphic(x, 0) == False
assert lowergamma(x, 1/x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(x + 1, 1/x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(1/x, 1/x)._eval_is_meromorphic(x, 0) == False
assert lowergamma(x, 2).series(x, oo, 3) == \
2**x*(1 + 2/(x + 1))*exp(-2)/x + O(exp(x*log(2))/x**3, (x, oo))
assert lowergamma(
x, y).rewrite(expint) == -y**x*expint(-x + 1, y) + gamma(x)
k = Symbol('k', integer=True)
assert lowergamma(
k, y).rewrite(expint) == -y**k*expint(-k + 1, y) + gamma(k)
k = Symbol('k', integer=True, positive=False)
assert lowergamma(k, y).rewrite(expint) == lowergamma(k, y)
assert lowergamma(x, y).rewrite(uppergamma) == gamma(x) - uppergamma(x, y)
assert lowergamma(70, 6) == factorial(69) - 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320 * exp(-6)
assert (lowergamma(S(77) / 2, 6) - lowergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16
assert (lowergamma(-S(77) / 2, 6) - lowergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16
def test_uppergamma():
from sympy.functions.special.error_functions import expint
from sympy.functions.special.hyper import meijerg
assert uppergamma(4, 0) == 6
assert uppergamma(x, y).diff(y) == -y**(x - 1)*exp(-y)
assert td(uppergamma(randcplx(), y), y)
assert uppergamma(x, y).diff(x) == \
uppergamma(x, y)*log(y) + meijerg([], [1, 1], [0, 0, x], [], y)
assert td(uppergamma(x, randcplx()), x)
p = Symbol('p', positive=True)
assert uppergamma(0, p) == -Ei(-p)
assert uppergamma(p, 0) == gamma(p)
assert uppergamma(S.Half, x) == sqrt(pi)*erfc(sqrt(x))
assert not uppergamma(S.Half - 3, x).has(uppergamma)
assert not uppergamma(S.Half + 3, x).has(uppergamma)
assert uppergamma(S.Half, x, evaluate=False).has(uppergamma)
assert tn(uppergamma(S.Half + 3, x, evaluate=False),
uppergamma(S.Half + 3, x), x)
assert tn(uppergamma(S.Half - 3, x, evaluate=False),
uppergamma(S.Half - 3, x), x)
assert unchanged(uppergamma, x, -oo)
assert unchanged(uppergamma, x, 0)
assert tn_branch(-3, uppergamma)
assert tn_branch(-4, uppergamma)
assert tn_branch(Rational(1, 3), uppergamma)
assert tn_branch(pi, uppergamma)
assert uppergamma(3, exp_polar(4*pi*I)*x) == uppergamma(3, x)
assert uppergamma(y, exp_polar(5*pi*I)*x) == \
exp(4*I*pi*y)*uppergamma(y, x*exp_polar(pi*I)) + \
gamma(y)*(1 - exp(4*pi*I*y))
assert uppergamma(-2, exp_polar(5*pi*I)*x) == \
uppergamma(-2, x*exp_polar(I*pi)) - 2*pi*I
assert uppergamma(-2, x) == expint(3, x)/x**2
assert conjugate(uppergamma(x, y)) == uppergamma(conjugate(x), conjugate(y))
assert unchanged(conjugate, uppergamma(x, -oo))
assert uppergamma(x, y).rewrite(expint) == y**x*expint(-x + 1, y)
assert uppergamma(x, y).rewrite(lowergamma) == gamma(x) - lowergamma(x, y)
assert uppergamma(70, 6) == 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320*exp(-6)
assert (uppergamma(S(77) / 2, 6) - uppergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16
assert (uppergamma(-S(77) / 2, 6) - uppergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16
def test_polygamma():
assert polygamma(n, nan) is nan
assert polygamma(0, oo) is oo
assert polygamma(0, -oo) is oo
assert polygamma(0, I*oo) is oo
assert polygamma(0, -I*oo) is oo
assert polygamma(1, oo) == 0
assert polygamma(5, oo) == 0
assert polygamma(0, -9) is zoo
assert polygamma(0, -9) is zoo
assert polygamma(0, -1) is zoo
assert polygamma(Rational(3, 2), -1) is zoo
assert polygamma(0, 0) is zoo
assert polygamma(0, 1) == -EulerGamma
assert polygamma(0, 7) == Rational(49, 20) - EulerGamma
assert polygamma(1, 1) == pi**2/6
assert polygamma(1, 2) == pi**2/6 - 1
assert polygamma(1, 3) == pi**2/6 - Rational(5, 4)
assert polygamma(3, 1) == pi**4 / 15
assert polygamma(3, 5) == 6*(Rational(-22369, 20736) + pi**4/90)
assert polygamma(5, 1) == 8 * pi**6 / 63
assert polygamma(1, S.Half) == pi**2 / 2
assert polygamma(2, S.Half) == -14*zeta(3)
assert polygamma(11, S.Half) == 176896*pi**12
def t(m, n):
x = S(m)/n
r = polygamma(0, x)
if r.has(polygamma):
return False
return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10
assert t(1, 2)
assert t(3, 2)
assert t(-1, 2)
assert t(1, 4)
assert t(-3, 4)
assert t(1, 3)
assert t(4, 3)
assert t(3, 4)
assert t(2, 3)
assert t(123, 5)
assert polygamma(0, x).rewrite(zeta) == polygamma(0, x)
assert polygamma(1, x).rewrite(zeta) == zeta(2, x)
assert polygamma(2, x).rewrite(zeta) == -2*zeta(3, x)
assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2)
n1 = Symbol('n1')
n2 = Symbol('n2', real=True)
n3 = Symbol('n3', integer=True)
n4 = Symbol('n4', positive=True)
n5 = Symbol('n5', positive=True, integer=True)
assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x)
assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x)
assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x)
assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x)
assert polygamma(n5, x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x)
assert polygamma(3, 7*x).diff(x) == 7*polygamma(4, 7*x)
assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma
assert polygamma(2, x).rewrite(harmonic) == 2*harmonic(x - 1, 3) - 2*zeta(3)
ni = Symbol("n", integer=True)
assert polygamma(ni, x).rewrite(harmonic) == (-1)**(ni + 1)*(-harmonic(x - 1, ni + 1)
+ zeta(ni + 1))*factorial(ni)
# Polygamma of non-negative integer order is unbranched:
k = Symbol('n', integer=True, nonnegative=True)
assert polygamma(k, exp_polar(2*I*pi)*x) == polygamma(k, x)
# but negative integers are branched!
k = Symbol('n', integer=True)
assert polygamma(k, exp_polar(2*I*pi)*x).args == (k, exp_polar(2*I*pi)*x)
# Polygamma of order -1 is loggamma:
assert polygamma(-1, x) == loggamma(x) - log(2*pi) / 2
# But smaller orders are iterated integrals and don't have a special name
assert polygamma(-2, x).func is polygamma
# Test a bug
assert polygamma(0, -x).expand(func=True) == polygamma(0, -x)
assert polygamma(2, 2.5).is_positive == False
assert polygamma(2, -2.5).is_positive == False
assert polygamma(3, 2.5).is_positive == True
assert polygamma(3, -2.5).is_positive is True
assert polygamma(-2, -2.5).is_positive is None
assert polygamma(-3, -2.5).is_positive is None
assert polygamma(2, 2.5).is_negative == True
assert polygamma(3, 2.5).is_negative == False
assert polygamma(3, -2.5).is_negative == False
assert polygamma(2, -2.5).is_negative is True
assert polygamma(-2, -2.5).is_negative is None
assert polygamma(-3, -2.5).is_negative is None
assert polygamma(I, 2).is_positive is None
assert polygamma(I, 3).is_negative is None
# issue 17350
assert (I*polygamma(I, pi)).as_real_imag() == \
(-im(polygamma(I, pi)), re(polygamma(I, pi)))
assert (tanh(polygamma(I, 1))).rewrite(exp) == \
(exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1)))
assert (I / polygamma(I, 4)).rewrite(exp) == \
I*exp(-I*atan(im(polygamma(I, 4))/re(polygamma(I, 4))))/Abs(polygamma(I, 4))
# issue 12569
assert unchanged(im, polygamma(0, I))
assert polygamma(Symbol('a', positive=True), Symbol('b', positive=True)).is_real is True
assert polygamma(0, I).is_real is None
assert str(polygamma(pi, 3).evalf(n=10)) == "0.1169314564"
assert str(polygamma(2.3, 1.0).evalf(n=10)) == "-3.003302909"
assert str(polygamma(-1, 1).evalf(n=10)) == "-0.9189385332" # not zero
assert str(polygamma(I, 1).evalf(n=10)) == "-3.109856569 + 1.89089016*I"
assert str(polygamma(1, I).evalf(n=10)) == "-0.5369999034 - 0.7942335428*I"
assert str(polygamma(I, I).evalf(n=10)) == "6.332362889 + 45.92828268*I"
def test_polygamma_expand_func():
assert polygamma(0, x).expand(func=True) == polygamma(0, x)
assert polygamma(0, 2*x).expand(func=True) == \
polygamma(0, x)/2 + polygamma(0, S.Half + x)/2 + log(2)
assert polygamma(1, 2*x).expand(func=True) == \
polygamma(1, x)/4 + polygamma(1, S.Half + x)/4
assert polygamma(2, x).expand(func=True) == \
polygamma(2, x)
assert polygamma(0, -1 + x).expand(func=True) == \
polygamma(0, x) - 1/(x - 1)
assert polygamma(0, 1 + x).expand(func=True) == \
1/x + polygamma(0, x )
assert polygamma(0, 2 + x).expand(func=True) == \
1/x + 1/(1 + x) + polygamma(0, x)
assert polygamma(0, 3 + x).expand(func=True) == \
polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x)
assert polygamma(0, 4 + x).expand(func=True) == \
polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x)
assert polygamma(1, 1 + x).expand(func=True) == \
polygamma(1, x) - 1/x**2
assert polygamma(1, 2 + x).expand(func=True, multinomial=False) == \
polygamma(1, x) - 1/x**2 - 1/(1 + x)**2
assert polygamma(1, 3 + x).expand(func=True, multinomial=False) == \
polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2
assert polygamma(1, 4 + x).expand(func=True, multinomial=False) == \
polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \
1/(2 + x)**2 - 1/(3 + x)**2
assert polygamma(0, x + y).expand(func=True) == \
polygamma(0, x + y)
assert polygamma(1, x + y).expand(func=True) == \
polygamma(1, x + y)
assert polygamma(1, 3 + 4*x + y).expand(func=True, multinomial=False) == \
polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \
1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2
assert polygamma(3, 3 + 4*x + y).expand(func=True, multinomial=False) == \
polygamma(3, y + 4*x) - 6/(y + 4*x)**4 - \
6/(1 + y + 4*x)**4 - 6/(2 + y + 4*x)**4
assert polygamma(3, 4*x + y + 1).expand(func=True, multinomial=False) == \
polygamma(3, y + 4*x) - 6/(y + 4*x)**4
e = polygamma(3, 4*x + y + Rational(3, 2))
assert e.expand(func=True) == e
e = polygamma(3, x + y + Rational(3, 4))
assert e.expand(func=True, basic=False) == e
assert polygamma(-1, x, evaluate=False).expand(func=True) == \
loggamma(x) - log(pi)/2 - log(2)/2
p2 = polygamma(-2, x).expand(func=True) + x**2/2 - x/2 + S(1)/12
assert isinstance(p2, Subs)
assert p2.point == (-1,)
def test_digamma():
assert digamma(nan) == nan
assert digamma(oo) == oo
assert digamma(-oo) == oo
assert digamma(I*oo) == oo
assert digamma(-I*oo) == oo
assert digamma(-9) == zoo
assert digamma(-9) == zoo
assert digamma(-1) == zoo
assert digamma(0) == zoo
assert digamma(1) == -EulerGamma
assert digamma(7) == Rational(49, 20) - EulerGamma
def t(m, n):
x = S(m)/n
r = digamma(x)
if r.has(digamma):
return False
return abs(digamma(x.n()).n() - r.n()).n() < 1e-10
assert t(1, 2)
assert t(3, 2)
assert t(-1, 2)
assert t(1, 4)
assert t(-3, 4)
assert t(1, 3)
assert t(4, 3)
assert t(3, 4)
assert t(2, 3)
assert t(123, 5)
assert digamma(x).rewrite(zeta) == polygamma(0, x)
assert digamma(x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma
assert digamma(I).is_real is None
assert digamma(x,evaluate=False).fdiff() == polygamma(1, x)
assert digamma(x,evaluate=False).is_real is None
assert digamma(x,evaluate=False).is_positive is None
assert digamma(x,evaluate=False).is_negative is None
assert digamma(x,evaluate=False).rewrite(polygamma) == polygamma(0, x)
def test_digamma_expand_func():
assert digamma(x).expand(func=True) == polygamma(0, x)
assert digamma(2*x).expand(func=True) == \
polygamma(0, x)/2 + polygamma(0, Rational(1, 2) + x)/2 + log(2)
assert digamma(-1 + x).expand(func=True) == \
polygamma(0, x) - 1/(x - 1)
assert digamma(1 + x).expand(func=True) == \
1/x + polygamma(0, x )
assert digamma(2 + x).expand(func=True) == \
1/x + 1/(1 + x) + polygamma(0, x)
assert digamma(3 + x).expand(func=True) == \
polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x)
assert digamma(4 + x).expand(func=True) == \
polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x)
assert digamma(x + y).expand(func=True) == \
polygamma(0, x + y)
def test_trigamma():
assert trigamma(nan) == nan
assert trigamma(oo) == 0
assert trigamma(1) == pi**2/6
assert trigamma(2) == pi**2/6 - 1
assert trigamma(3) == pi**2/6 - Rational(5, 4)
assert trigamma(x, evaluate=False).rewrite(zeta) == zeta(2, x)
assert trigamma(x, evaluate=False).rewrite(harmonic) == \
trigamma(x).rewrite(polygamma).rewrite(harmonic)
assert trigamma(x,evaluate=False).fdiff() == polygamma(2, x)
assert trigamma(x,evaluate=False).is_real is None
assert trigamma(x,evaluate=False).is_positive is None
assert trigamma(x,evaluate=False).is_negative is None
assert trigamma(x,evaluate=False).rewrite(polygamma) == polygamma(1, x)
def test_trigamma_expand_func():
assert trigamma(2*x).expand(func=True) == \
polygamma(1, x)/4 + polygamma(1, Rational(1, 2) + x)/4
assert trigamma(1 + x).expand(func=True) == \
polygamma(1, x) - 1/x**2
assert trigamma(2 + x).expand(func=True, multinomial=False) == \
polygamma(1, x) - 1/x**2 - 1/(1 + x)**2
assert trigamma(3 + x).expand(func=True, multinomial=False) == \
polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2
assert trigamma(4 + x).expand(func=True, multinomial=False) == \
polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \
1/(2 + x)**2 - 1/(3 + x)**2
assert trigamma(x + y).expand(func=True) == \
polygamma(1, x + y)
assert trigamma(3 + 4*x + y).expand(func=True, multinomial=False) == \
polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \
1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2
def test_loggamma():
raises(TypeError, lambda: loggamma(2, 3))
raises(ArgumentIndexError, lambda: loggamma(x).fdiff(2))
assert loggamma(-1) is oo
assert loggamma(-2) is oo
assert loggamma(0) is oo
assert loggamma(1) == 0
assert loggamma(2) == 0
assert loggamma(3) == log(2)
assert loggamma(4) == log(6)
n = Symbol("n", integer=True, positive=True)
assert loggamma(n) == log(gamma(n))
assert loggamma(-n) is oo
assert loggamma(n/2) == log(2**(-n + 1)*sqrt(pi)*gamma(n)/gamma(n/2 + S.Half))
assert loggamma(oo) is oo
assert loggamma(-oo) is zoo
assert loggamma(I*oo) is zoo
assert loggamma(-I*oo) is zoo
assert loggamma(zoo) is zoo
assert loggamma(nan) is nan
L = loggamma(Rational(16, 3))
E = -5*log(3) + loggamma(Rational(1, 3)) + log(4) + log(7) + log(10) + log(13)
assert expand_func(L).doit() == E
assert L.n() == E.n()
L = loggamma(Rational(19, 4))
E = -4*log(4) + loggamma(Rational(3, 4)) + log(3) + log(7) + log(11) + log(15)
assert expand_func(L).doit() == E
assert L.n() == E.n()
L = loggamma(Rational(23, 7))
E = -3*log(7) + log(2) + loggamma(Rational(2, 7)) + log(9) + log(16)
assert expand_func(L).doit() == E
assert L.n() == E.n()
L = loggamma(Rational(19, 4) - 7)
E = -log(9) - log(5) + loggamma(Rational(3, 4)) + 3*log(4) - 3*I*pi
assert expand_func(L).doit() == E
assert L.n() == E.n()
L = loggamma(Rational(23, 7) - 6)
E = -log(19) - log(12) - log(5) + loggamma(Rational(2, 7)) + 3*log(7) - 3*I*pi
assert expand_func(L).doit() == E
assert L.n() == E.n()
assert loggamma(x).diff(x) == polygamma(0, x)
s1 = loggamma(1/(x + sin(x)) + cos(x)).nseries(x, n=4)
s2 = (-log(2*x) - 1)/(2*x) - log(x/pi)/2 + (4 - log(2*x))*x/24 + O(x**2) + \
log(x)*x**2/2
assert (s1 - s2).expand(force=True).removeO() == 0
s1 = loggamma(1/x).series(x)
s2 = (1/x - S.Half)*log(1/x) - 1/x + log(2*pi)/2 + \
x/12 - x**3/360 + x**5/1260 + O(x**7)
assert ((s1 - s2).expand(force=True)).removeO() == 0
assert loggamma(x).rewrite('intractable') == log(gamma(x))
s1 = loggamma(x).series(x).cancel()
assert s1 == -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + \
pi**4*x**4/360 + x**5*polygamma(4, 1)/120 + O(x**6)
assert s1 == loggamma(x).rewrite('intractable').series(x).cancel()
assert conjugate(loggamma(x)) == loggamma(conjugate(x))
assert conjugate(loggamma(0)) is oo
assert conjugate(loggamma(1)) == loggamma(conjugate(1))
assert conjugate(loggamma(-oo)) == conjugate(zoo)
assert loggamma(Symbol('v', positive=True)).is_real is True
assert loggamma(Symbol('v', zero=True)).is_real is False
assert loggamma(Symbol('v', negative=True)).is_real is False
assert loggamma(Symbol('v', nonpositive=True)).is_real is False
assert loggamma(Symbol('v', nonnegative=True)).is_real is None
assert loggamma(Symbol('v', imaginary=True)).is_real is None
assert loggamma(Symbol('v', real=True)).is_real is None
assert loggamma(Symbol('v')).is_real is None
assert loggamma(S.Half).is_real is True
assert loggamma(0).is_real is False
assert loggamma(Rational(-1, 2)).is_real is False
assert loggamma(I).is_real is None
assert loggamma(2 + 3*I).is_real is None
def tN(N, M):
assert loggamma(1/x)._eval_nseries(x, n=N).getn() == M
tN(0, 0)
tN(1, 1)
tN(2, 2)
tN(3, 3)
tN(4, 4)
tN(5, 5)
def test_polygamma_expansion():
# A. & S., pa. 259 and 260
assert polygamma(0, 1/x).nseries(x, n=3) == \
-log(x) - x/2 - x**2/12 + O(x**3)
assert polygamma(1, 1/x).series(x, n=5) == \
x + x**2/2 + x**3/6 + O(x**5)
assert polygamma(3, 1/x).nseries(x, n=11) == \
2*x**3 + 3*x**4 + 2*x**5 - x**7 + 4*x**9/3 + O(x**11)
def test_polygamma_leading_term():
expr = -log(1/x) + polygamma(0, 1 + 1/x) + S.EulerGamma
assert expr.as_leading_term(x, logx=-y) == S.EulerGamma
def test_issue_8657():
n = Symbol('n', negative=True, integer=True)
m = Symbol('m', integer=True)
o = Symbol('o', positive=True)
p = Symbol('p', negative=True, integer=False)
assert gamma(n).is_real is False
assert gamma(m).is_real is None
assert gamma(o).is_real is True
assert gamma(p).is_real is True
assert gamma(w).is_real is None
def test_issue_8524():
x = Symbol('x', positive=True)
y = Symbol('y', negative=True)
z = Symbol('z', positive=False)
p = Symbol('p', negative=False)
q = Symbol('q', integer=True)
r = Symbol('r', integer=False)
e = Symbol('e', even=True, negative=True)
assert gamma(x).is_positive is True
assert gamma(y).is_positive is None
assert gamma(z).is_positive is None
assert gamma(p).is_positive is None
assert gamma(q).is_positive is None
assert gamma(r).is_positive is None
assert gamma(e + S.Half).is_positive is True
assert gamma(e - S.Half).is_positive is False
def test_issue_14450():
assert uppergamma(Rational(3, 8), x).evalf() == uppergamma(Rational(3, 8), x)
assert lowergamma(x, Rational(3, 8)).evalf() == lowergamma(x, Rational(3, 8))
# some values from Wolfram Alpha for comparison
assert abs(uppergamma(Rational(3, 8), 2).evalf() - 0.07105675881) < 1e-9
assert abs(lowergamma(Rational(3, 8), 2).evalf() - 2.2993794256) < 1e-9
def test_issue_14528():
k = Symbol('k', integer=True, nonpositive=True)
assert isinstance(gamma(k), gamma)
def test_multigamma():
from sympy.concrete.products import Product
p = Symbol('p')
_k = Dummy('_k')
assert multigamma(x, p).dummy_eq(pi**(p*(p - 1)/4)*\
Product(gamma(x + (1 - _k)/2), (_k, 1, p)))
assert conjugate(multigamma(x, p)).dummy_eq(pi**((conjugate(p) - 1)*\
conjugate(p)/4)*Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p)))
assert conjugate(multigamma(x, 1)) == gamma(conjugate(x))
p = Symbol('p', positive=True)
assert conjugate(multigamma(x, p)).dummy_eq(pi**((p - 1)*p/4)*\
Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p)))
assert multigamma(nan, 1) is nan
assert multigamma(oo, 1).doit() is oo
assert multigamma(1, 1) == 1
assert multigamma(2, 1) == 1
assert multigamma(3, 1) == 2
assert multigamma(102, 1) == factorial(101)
assert multigamma(S.Half, 1) == sqrt(pi)
assert multigamma(1, 2) == pi
assert multigamma(2, 2) == pi/2
assert multigamma(1, 3) is zoo
assert multigamma(2, 3) == pi**2/2
assert multigamma(3, 3) == 3*pi**2/2
assert multigamma(x, 1).diff(x) == gamma(x)*polygamma(0, x)
assert multigamma(x, 2).diff(x) == sqrt(pi)*gamma(x)*gamma(x - S.Half)*\
polygamma(0, x) + sqrt(pi)*gamma(x)*gamma(x - S.Half)*polygamma(0, x - S.Half)
assert multigamma(x - 1, 1).expand(func=True) == gamma(x)/(x - 1)
assert multigamma(x + 2, 1).expand(func=True, mul=False) == x*(x + 1)*\
gamma(x)
assert multigamma(x - 1, 2).expand(func=True) == sqrt(pi)*gamma(x)*\
gamma(x + S.Half)/(x**3 - 3*x**2 + x*Rational(11, 4) - Rational(3, 4))
assert multigamma(x - 1, 3).expand(func=True) == pi**Rational(3, 2)*gamma(x)**2*\
gamma(x + S.Half)/(x**5 - 6*x**4 + 55*x**3/4 - 15*x**2 + x*Rational(31, 4) - Rational(3, 2))
assert multigamma(n, 1).rewrite(factorial) == factorial(n - 1)
assert multigamma(n, 2).rewrite(factorial) == sqrt(pi)*\
factorial(n - Rational(3, 2))*factorial(n - 1)
assert multigamma(n, 3).rewrite(factorial) == pi**Rational(3, 2)*\
factorial(n - 2)*factorial(n - Rational(3, 2))*factorial(n - 1)
assert multigamma(Rational(-1, 2), 3, evaluate=False).is_real == False
assert multigamma(S.Half, 3, evaluate=False).is_real == False
assert multigamma(0, 1, evaluate=False).is_real == False
assert multigamma(1, 3, evaluate=False).is_real == False
assert multigamma(-1.0, 3, evaluate=False).is_real == False
assert multigamma(0.7, 3, evaluate=False).is_real == True
assert multigamma(3, 3, evaluate=False).is_real == True
def test_gamma_as_leading_term():
assert gamma(x).as_leading_term(x) == 1/x
assert gamma(2 + x).as_leading_term(x) == S(1)
assert gamma(cos(x)).as_leading_term(x) == S(1)
assert gamma(sin(x)).as_leading_term(x) == 1/x
|
d14efc6a23bdcef18eaea43bb62553521aa7a63d050c3f6c84d6fef003a1a7af | from sympy.core.function import (diff, expand, expand_func)
from sympy.core import EulerGamma
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import (conjugate, im, polar_lift, re)
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import (cosh, sinh)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
from sympy.functions.special.error_functions import (Chi, Ci, E1, Ei, Li, Shi, Si, erf, erf2, erf2inv, erfc, erfcinv, erfi, erfinv, expint, fresnelc, fresnels, li)
from sympy.functions.special.gamma_functions import (gamma, uppergamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.integrals.integrals import (Integral, integrate)
from sympy.series.gruntz import gruntz
from sympy.series.limits import limit
from sympy.series.order import O
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.functions.special.error_functions import _erfs, _eis
from sympy.testing.pytest import raises
x, y, z = symbols('x,y,z')
w = Symbol("w", real=True)
n = Symbol("n", integer=True)
def test_erf():
assert erf(nan) is nan
assert erf(oo) == 1
assert erf(-oo) == -1
assert erf(0) is S.Zero
assert erf(I*oo) == oo*I
assert erf(-I*oo) == -oo*I
assert erf(-2) == -erf(2)
assert erf(-x*y) == -erf(x*y)
assert erf(-x - y) == -erf(x + y)
assert erf(erfinv(x)) == x
assert erf(erfcinv(x)) == 1 - x
assert erf(erf2inv(0, x)) == x
assert erf(erf2inv(0, x, evaluate=False)) == x # To cover code in erf
assert erf(erf2inv(0, erf(erfcinv(1 - erf(erfinv(x)))))) == x
assert erf(I).is_real is False
assert erf(0, evaluate=False).is_real
assert erf(0, evaluate=False).is_zero
assert conjugate(erf(z)) == erf(conjugate(z))
assert erf(x).as_leading_term(x) == 2*x/sqrt(pi)
assert erf(x*y).as_leading_term(y) == 2*x*y/sqrt(pi)
assert (erf(x*y)/erf(y)).as_leading_term(y) == x
assert erf(1/x).as_leading_term(x) == S.One
assert erf(z).rewrite('uppergamma') == sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z
assert erf(z).rewrite('erfc') == S.One - erfc(z)
assert erf(z).rewrite('erfi') == -I*erfi(I*z)
assert erf(z).rewrite('fresnels') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) -
I*fresnels(z*(1 - I)/sqrt(pi)))
assert erf(z).rewrite('fresnelc') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) -
I*fresnels(z*(1 - I)/sqrt(pi)))
assert erf(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi)
assert erf(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi)
assert erf(z).rewrite('expint') == sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi)
assert limit(exp(x)*exp(x**2)*(erf(x + 1/exp(x)) - erf(x)), x, oo) == \
2/sqrt(pi)
assert limit((1 - erf(z))*exp(z**2)*z, z, oo) == 1/sqrt(pi)
assert limit((1 - erf(x))*exp(x**2)*sqrt(pi)*x, x, oo) == 1
assert limit(((1 - erf(x))*exp(x**2)*sqrt(pi)*x - 1)*2*x**2, x, oo) == -1
assert limit(erf(x)/x, x, 0) == 2/sqrt(pi)
assert limit(x**(-4) - sqrt(pi)*erf(x**2) / (2*x**6), x, 0) == S(1)/3
assert erf(x).as_real_imag() == \
(erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2,
-I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2)
assert erf(x).as_real_imag(deep=False) == \
(erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2,
-I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2)
assert erf(w).as_real_imag() == (erf(w), 0)
assert erf(w).as_real_imag(deep=False) == (erf(w), 0)
# issue 13575
assert erf(I).as_real_imag() == (0, -I*erf(I))
raises(ArgumentIndexError, lambda: erf(x).fdiff(2))
assert erf(x).inverse() == erfinv
def test_erf_series():
assert erf(x).series(x, 0, 7) == 2*x/sqrt(pi) - \
2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7)
assert erf(x).series(x, oo) == \
-exp(-x**2)*(3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))/sqrt(pi) + 1
assert erf(x**2).series(x, oo, n=8) == \
(-1/(2*x**6) + x**(-2) + O(x**(-8), (x, oo)))*exp(-x**4)/sqrt(pi)*-1 + 1
assert erf(sqrt(x)).series(x, oo, n=3) == (sqrt(1/x) - (1/x)**(S(3)/2)/2\
+ 3*(1/x)**(S(5)/2)/4 + O(x**(-3), (x, oo)))*exp(-x)/sqrt(pi)*-1 + 1
def test_erf_evalf():
assert abs( erf(Float(2.0)) - 0.995322265 ) < 1E-8 # XXX
def test__erfs():
assert _erfs(z).diff(z) == -2/sqrt(S.Pi) + 2*z*_erfs(z)
assert _erfs(1/z).series(z) == \
z/sqrt(pi) - z**3/(2*sqrt(pi)) + 3*z**5/(4*sqrt(pi)) + O(z**6)
assert expand(erf(z).rewrite('tractable').diff(z).rewrite('intractable')) \
== erf(z).diff(z)
assert _erfs(z).rewrite("intractable") == (-erf(z) + 1)*exp(z**2)
raises(ArgumentIndexError, lambda: _erfs(z).fdiff(2))
def test_erfc():
assert erfc(nan) is nan
assert erfc(oo) is S.Zero
assert erfc(-oo) == 2
assert erfc(0) == 1
assert erfc(I*oo) == -oo*I
assert erfc(-I*oo) == oo*I
assert erfc(-x) == S(2) - erfc(x)
assert erfc(erfcinv(x)) == x
assert erfc(I).is_real is False
assert erfc(0, evaluate=False).is_real
assert erfc(0, evaluate=False).is_zero is False
assert erfc(erfinv(x)) == 1 - x
assert conjugate(erfc(z)) == erfc(conjugate(z))
assert erfc(x).as_leading_term(x) is S.One
assert erfc(1/x).as_leading_term(x) == S.Zero
assert erfc(z).rewrite('erf') == 1 - erf(z)
assert erfc(z).rewrite('erfi') == 1 + I*erfi(I*z)
assert erfc(z).rewrite('fresnels') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) -
I*fresnels(z*(1 - I)/sqrt(pi)))
assert erfc(z).rewrite('fresnelc') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) -
I*fresnels(z*(1 - I)/sqrt(pi)))
assert erfc(z).rewrite('hyper') == 1 - 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi)
assert erfc(z).rewrite('meijerg') == 1 - z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi)
assert erfc(z).rewrite('uppergamma') == 1 - sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z
assert erfc(z).rewrite('expint') == S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi)
assert erfc(z).rewrite('tractable') == _erfs(z)*exp(-z**2)
assert expand_func(erf(x) + erfc(x)) is S.One
assert erfc(x).as_real_imag() == \
(erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2,
-I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2)
assert erfc(x).as_real_imag(deep=False) == \
(erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2,
-I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2)
assert erfc(w).as_real_imag() == (erfc(w), 0)
assert erfc(w).as_real_imag(deep=False) == (erfc(w), 0)
raises(ArgumentIndexError, lambda: erfc(x).fdiff(2))
assert erfc(x).inverse() == erfcinv
def test_erfc_series():
assert erfc(x).series(x, 0, 7) == 1 - 2*x/sqrt(pi) + \
2*x**3/3/sqrt(pi) - x**5/5/sqrt(pi) + O(x**7)
assert erfc(x).series(x, oo) == \
(3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(-x**2)/sqrt(pi)
def test_erfc_evalf():
assert abs( erfc(Float(2.0)) - 0.00467773 ) < 1E-8 # XXX
def test_erfi():
assert erfi(nan) is nan
assert erfi(oo) is S.Infinity
assert erfi(-oo) is S.NegativeInfinity
assert erfi(0) is S.Zero
assert erfi(I*oo) == I
assert erfi(-I*oo) == -I
assert erfi(-x) == -erfi(x)
assert erfi(I*erfinv(x)) == I*x
assert erfi(I*erfcinv(x)) == I*(1 - x)
assert erfi(I*erf2inv(0, x)) == I*x
assert erfi(I*erf2inv(0, x, evaluate=False)) == I*x # To cover code in erfi
assert erfi(I).is_real is False
assert erfi(0, evaluate=False).is_real
assert erfi(0, evaluate=False).is_zero
assert conjugate(erfi(z)) == erfi(conjugate(z))
assert erfi(x).as_leading_term(x) == 2*x/sqrt(pi)
assert erfi(x*y).as_leading_term(y) == 2*x*y/sqrt(pi)
assert (erfi(x*y)/erfi(y)).as_leading_term(y) == x
assert erfi(1/x).as_leading_term(x) == erfi(1/x)
assert erfi(z).rewrite('erf') == -I*erf(I*z)
assert erfi(z).rewrite('erfc') == I*erfc(I*z) - I
assert erfi(z).rewrite('fresnels') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) -
I*fresnels(z*(1 + I)/sqrt(pi)))
assert erfi(z).rewrite('fresnelc') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) -
I*fresnels(z*(1 + I)/sqrt(pi)))
assert erfi(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], z**2)/sqrt(pi)
assert erfi(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2)/sqrt(pi)
assert erfi(z).rewrite('uppergamma') == (sqrt(-z**2)/z*(uppergamma(S.Half,
-z**2)/sqrt(S.Pi) - S.One))
assert erfi(z).rewrite('expint') == sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi)
assert erfi(z).rewrite('tractable') == -I*(-_erfs(I*z)*exp(z**2) + 1)
assert expand_func(erfi(I*z)) == I*erf(z)
assert erfi(x).as_real_imag() == \
(erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2,
-I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2)
assert erfi(x).as_real_imag(deep=False) == \
(erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2,
-I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2)
assert erfi(w).as_real_imag() == (erfi(w), 0)
assert erfi(w).as_real_imag(deep=False) == (erfi(w), 0)
raises(ArgumentIndexError, lambda: erfi(x).fdiff(2))
def test_erfi_series():
assert erfi(x).series(x, 0, 7) == 2*x/sqrt(pi) + \
2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7)
assert erfi(x).series(x, oo) == \
(3/(4*x**5) + 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(x**2)/sqrt(pi) - I
def test_erfi_evalf():
assert abs( erfi(Float(2.0)) - 18.5648024145756 ) < 1E-13 # XXX
def test_erf2():
assert erf2(0, 0) is S.Zero
assert erf2(x, x) is S.Zero
assert erf2(nan, 0) is nan
assert erf2(-oo, y) == erf(y) + 1
assert erf2( oo, y) == erf(y) - 1
assert erf2( x, oo) == 1 - erf(x)
assert erf2( x,-oo) == -1 - erf(x)
assert erf2(x, erf2inv(x, y)) == y
assert erf2(-x, -y) == -erf2(x,y)
assert erf2(-x, y) == erf(y) + erf(x)
assert erf2( x, -y) == -erf(y) - erf(x)
assert erf2(x, y).rewrite('fresnels') == erf(y).rewrite(fresnels)-erf(x).rewrite(fresnels)
assert erf2(x, y).rewrite('fresnelc') == erf(y).rewrite(fresnelc)-erf(x).rewrite(fresnelc)
assert erf2(x, y).rewrite('hyper') == erf(y).rewrite(hyper)-erf(x).rewrite(hyper)
assert erf2(x, y).rewrite('meijerg') == erf(y).rewrite(meijerg)-erf(x).rewrite(meijerg)
assert erf2(x, y).rewrite('uppergamma') == erf(y).rewrite(uppergamma) - erf(x).rewrite(uppergamma)
assert erf2(x, y).rewrite('expint') == erf(y).rewrite(expint)-erf(x).rewrite(expint)
assert erf2(I, 0).is_real is False
assert erf2(0, 0, evaluate=False).is_real
assert erf2(0, 0, evaluate=False).is_zero
assert erf2(x, x, evaluate=False).is_zero
assert erf2(x, y).is_zero is None
assert expand_func(erf(x) + erf2(x, y)) == erf(y)
assert conjugate(erf2(x, y)) == erf2(conjugate(x), conjugate(y))
assert erf2(x, y).rewrite('erf') == erf(y) - erf(x)
assert erf2(x, y).rewrite('erfc') == erfc(x) - erfc(y)
assert erf2(x, y).rewrite('erfi') == I*(erfi(I*x) - erfi(I*y))
assert erf2(x, y).diff(x) == erf2(x, y).fdiff(1)
assert erf2(x, y).diff(y) == erf2(x, y).fdiff(2)
assert erf2(x, y).diff(x) == -2*exp(-x**2)/sqrt(pi)
assert erf2(x, y).diff(y) == 2*exp(-y**2)/sqrt(pi)
raises(ArgumentIndexError, lambda: erf2(x, y).fdiff(3))
assert erf2(x, y).is_extended_real is None
xr, yr = symbols('xr yr', extended_real=True)
assert erf2(xr, yr).is_extended_real is True
def test_erfinv():
assert erfinv(0) is S.Zero
assert erfinv(1) is S.Infinity
assert erfinv(nan) is S.NaN
assert erfinv(-1) is S.NegativeInfinity
assert erfinv(erf(w)) == w
assert erfinv(erf(-w)) == -w
assert erfinv(x).diff() == sqrt(pi)*exp(erfinv(x)**2)/2
raises(ArgumentIndexError, lambda: erfinv(x).fdiff(2))
assert erfinv(z).rewrite('erfcinv') == erfcinv(1-z)
assert erfinv(z).inverse() == erf
def test_erfinv_evalf():
assert abs( erfinv(Float(0.2)) - 0.179143454621292 ) < 1E-13
def test_erfcinv():
assert erfcinv(1) is S.Zero
assert erfcinv(0) is S.Infinity
assert erfcinv(nan) is S.NaN
assert erfcinv(x).diff() == -sqrt(pi)*exp(erfcinv(x)**2)/2
raises(ArgumentIndexError, lambda: erfcinv(x).fdiff(2))
assert erfcinv(z).rewrite('erfinv') == erfinv(1-z)
assert erfcinv(z).inverse() == erfc
def test_erf2inv():
assert erf2inv(0, 0) is S.Zero
assert erf2inv(0, 1) is S.Infinity
assert erf2inv(1, 0) is S.One
assert erf2inv(0, y) == erfinv(y)
assert erf2inv(oo, y) == erfcinv(-y)
assert erf2inv(x, 0) == x
assert erf2inv(x, oo) == erfinv(x)
assert erf2inv(nan, 0) is nan
assert erf2inv(0, nan) is nan
assert erf2inv(x, y).diff(x) == exp(-x**2 + erf2inv(x, y)**2)
assert erf2inv(x, y).diff(y) == sqrt(pi)*exp(erf2inv(x, y)**2)/2
raises(ArgumentIndexError, lambda: erf2inv(x, y).fdiff(3))
# NOTE we multiply by exp_polar(I*pi) and need this to be on the principal
# branch, hence take x in the lower half plane (d=0).
def mytn(expr1, expr2, expr3, x, d=0):
from sympy.core.random import verify_numerically, random_complex_number
subs = {}
for a in expr1.free_symbols:
if a != x:
subs[a] = random_complex_number()
return expr2 == expr3 and verify_numerically(expr1.subs(subs),
expr2.subs(subs), x, d=d)
def mytd(expr1, expr2, x):
from sympy.core.random import test_derivative_numerically, \
random_complex_number
subs = {}
for a in expr1.free_symbols:
if a != x:
subs[a] = random_complex_number()
return expr1.diff(x) == expr2 and test_derivative_numerically(expr1.subs(subs), x)
def tn_branch(func, s=None):
from sympy.core.random import uniform
def fn(x):
if s is None:
return func(x)
return func(s, x)
c = uniform(1, 5)
expr = fn(c*exp_polar(I*pi)) - fn(c*exp_polar(-I*pi))
eps = 1e-15
expr2 = fn(-c + eps*I) - fn(-c - eps*I)
return abs(expr.n() - expr2.n()).n() < 1e-10
def test_ei():
assert Ei(0) is S.NegativeInfinity
assert Ei(oo) is S.Infinity
assert Ei(-oo) is S.Zero
assert tn_branch(Ei)
assert mytd(Ei(x), exp(x)/x, x)
assert mytn(Ei(x), Ei(x).rewrite(uppergamma),
-uppergamma(0, x*polar_lift(-1)) - I*pi, x)
assert mytn(Ei(x), Ei(x).rewrite(expint),
-expint(1, x*polar_lift(-1)) - I*pi, x)
assert Ei(x).rewrite(expint).rewrite(Ei) == Ei(x)
assert Ei(x*exp_polar(2*I*pi)) == Ei(x) + 2*I*pi
assert Ei(x*exp_polar(-2*I*pi)) == Ei(x) - 2*I*pi
assert mytn(Ei(x), Ei(x).rewrite(Shi), Chi(x) + Shi(x), x)
assert mytn(Ei(x*polar_lift(I)), Ei(x*polar_lift(I)).rewrite(Si),
Ci(x) + I*Si(x) + I*pi/2, x)
assert Ei(log(x)).rewrite(li) == li(x)
assert Ei(2*log(x)).rewrite(li) == li(x**2)
assert gruntz(Ei(x+exp(-x))*exp(-x)*x, x, oo) == 1
assert Ei(x).series(x) == EulerGamma + log(x) + x + x**2/4 + \
x**3/18 + x**4/96 + x**5/600 + O(x**6)
assert Ei(x).series(x, 1, 3) == Ei(1) + E*(x - 1) + O((x - 1)**3, (x, 1))
assert Ei(x).series(x, oo) == \
(120/x**5 + 24/x**4 + 6/x**3 + 2/x**2 + 1/x + 1 + O(x**(-6), (x, oo)))*exp(x)/x
assert str(Ei(cos(2)).evalf(n=10)) == '-0.6760647401'
raises(ArgumentIndexError, lambda: Ei(x).fdiff(2))
def test_expint():
assert mytn(expint(x, y), expint(x, y).rewrite(uppergamma),
y**(x - 1)*uppergamma(1 - x, y), x)
assert mytd(
expint(x, y), -y**(x - 1)*meijerg([], [1, 1], [0, 0, 1 - x], [], y), x)
assert mytd(expint(x, y), -expint(x - 1, y), y)
assert mytn(expint(1, x), expint(1, x).rewrite(Ei),
-Ei(x*polar_lift(-1)) + I*pi, x)
assert expint(-4, x) == exp(-x)/x + 4*exp(-x)/x**2 + 12*exp(-x)/x**3 \
+ 24*exp(-x)/x**4 + 24*exp(-x)/x**5
assert expint(Rational(-3, 2), x) == \
exp(-x)/x + 3*exp(-x)/(2*x**2) + 3*sqrt(pi)*erfc(sqrt(x))/(4*x**S('5/2'))
assert tn_branch(expint, 1)
assert tn_branch(expint, 2)
assert tn_branch(expint, 3)
assert tn_branch(expint, 1.7)
assert tn_branch(expint, pi)
assert expint(y, x*exp_polar(2*I*pi)) == \
x**(y - 1)*(exp(2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x)
assert expint(y, x*exp_polar(-2*I*pi)) == \
x**(y - 1)*(exp(-2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x)
assert expint(2, x*exp_polar(2*I*pi)) == 2*I*pi*x + expint(2, x)
assert expint(2, x*exp_polar(-2*I*pi)) == -2*I*pi*x + expint(2, x)
assert expint(1, x).rewrite(Ei).rewrite(expint) == expint(1, x)
assert expint(x, y).rewrite(Ei) == expint(x, y)
assert expint(x, y).rewrite(Ci) == expint(x, y)
assert mytn(E1(x), E1(x).rewrite(Shi), Shi(x) - Chi(x), x)
assert mytn(E1(polar_lift(I)*x), E1(polar_lift(I)*x).rewrite(Si),
-Ci(x) + I*Si(x) - I*pi/2, x)
assert mytn(expint(2, x), expint(2, x).rewrite(Ei).rewrite(expint),
-x*E1(x) + exp(-x), x)
assert mytn(expint(3, x), expint(3, x).rewrite(Ei).rewrite(expint),
x**2*E1(x)/2 + (1 - x)*exp(-x)/2, x)
assert expint(Rational(3, 2), z).nseries(z) == \
2 + 2*z - z**2/3 + z**3/15 - z**4/84 + z**5/540 - \
2*sqrt(pi)*sqrt(z) + O(z**6)
assert E1(z).series(z) == -EulerGamma - log(z) + z - \
z**2/4 + z**3/18 - z**4/96 + z**5/600 + O(z**6)
assert expint(4, z).series(z) == Rational(1, 3) - z/2 + z**2/2 + \
z**3*(log(z)/6 - Rational(11, 36) + EulerGamma/6 - I*pi/6) - z**4/24 + \
z**5/240 + O(z**6)
assert expint(n, x).series(x, oo, n=3) == \
(n*(n + 1)/x**2 - n/x + 1 + O(x**(-3), (x, oo)))*exp(-x)/x
assert expint(z, y).series(z, 0, 2) == exp(-y)/y - z*meijerg(((), (1, 1)),
((0, 0, 1), ()), y)/y + O(z**2)
raises(ArgumentIndexError, lambda: expint(x, y).fdiff(3))
neg = Symbol('neg', negative=True)
assert Ei(neg).rewrite(Si) == Shi(neg) + Chi(neg) - I*pi
def test__eis():
assert _eis(z).diff(z) == -_eis(z) + 1/z
assert _eis(1/z).series(z) == \
z + z**2 + 2*z**3 + 6*z**4 + 24*z**5 + O(z**6)
assert Ei(z).rewrite('tractable') == exp(z)*_eis(z)
assert li(z).rewrite('tractable') == z*_eis(log(z))
assert _eis(z).rewrite('intractable') == exp(-z)*Ei(z)
assert expand(li(z).rewrite('tractable').diff(z).rewrite('intractable')) \
== li(z).diff(z)
assert expand(Ei(z).rewrite('tractable').diff(z).rewrite('intractable')) \
== Ei(z).diff(z)
assert _eis(z).series(z, n=3) == EulerGamma + log(z) + z*(-log(z) - \
EulerGamma + 1) + z**2*(log(z)/2 - Rational(3, 4) + EulerGamma/2)\
+ O(z**3*log(z))
raises(ArgumentIndexError, lambda: _eis(z).fdiff(2))
def tn_arg(func):
def test(arg, e1, e2):
from sympy.core.random import uniform
v = uniform(1, 5)
v1 = func(arg*x).subs(x, v).n()
v2 = func(e1*v + e2*1e-15).n()
return abs(v1 - v2).n() < 1e-10
return test(exp_polar(I*pi/2), I, 1) and \
test(exp_polar(-I*pi/2), -I, 1) and \
test(exp_polar(I*pi), -1, I) and \
test(exp_polar(-I*pi), -1, -I)
def test_li():
z = Symbol("z")
zr = Symbol("z", real=True)
zp = Symbol("z", positive=True)
zn = Symbol("z", negative=True)
assert li(0) is S.Zero
assert li(1) is -oo
assert li(oo) is oo
assert isinstance(li(z), li)
assert unchanged(li, -zp)
assert unchanged(li, zn)
assert diff(li(z), z) == 1/log(z)
assert conjugate(li(z)) == li(conjugate(z))
assert conjugate(li(-zr)) == li(-zr)
assert unchanged(conjugate, li(-zp))
assert unchanged(conjugate, li(zn))
assert li(z).rewrite(Li) == Li(z) + li(2)
assert li(z).rewrite(Ei) == Ei(log(z))
assert li(z).rewrite(uppergamma) == (-log(1/log(z))/2 - log(-log(z)) +
log(log(z))/2 - expint(1, -log(z)))
assert li(z).rewrite(Si) == (-log(I*log(z)) - log(1/log(z))/2 +
log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)))
assert li(z).rewrite(Ci) == (-log(I*log(z)) - log(1/log(z))/2 +
log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)))
assert li(z).rewrite(Shi) == (-log(1/log(z))/2 + log(log(z))/2 +
Chi(log(z)) - Shi(log(z)))
assert li(z).rewrite(Chi) == (-log(1/log(z))/2 + log(log(z))/2 +
Chi(log(z)) - Shi(log(z)))
assert li(z).rewrite(hyper) ==(log(z)*hyper((1, 1), (2, 2), log(z)) -
log(1/log(z))/2 + log(log(z))/2 + EulerGamma)
assert li(z).rewrite(meijerg) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 -
meijerg(((), (1,)), ((0, 0), ()), -log(z)))
assert gruntz(1/li(z), z, oo) is S.Zero
assert li(z).series(z) == log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + \
log(z) + log(log(z)) + EulerGamma
raises(ArgumentIndexError, lambda: li(z).fdiff(2))
def test_Li():
assert Li(2) is S.Zero
assert Li(oo) is oo
assert isinstance(Li(z), Li)
assert diff(Li(z), z) == 1/log(z)
assert gruntz(1/Li(z), z, oo) is S.Zero
assert Li(z).rewrite(li) == li(z) - li(2)
assert Li(z).series(z) == \
log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + log(z) + log(log(z)) - li(2) + EulerGamma
raises(ArgumentIndexError, lambda: Li(z).fdiff(2))
def test_si():
assert Si(I*x) == I*Shi(x)
assert Shi(I*x) == I*Si(x)
assert Si(-I*x) == -I*Shi(x)
assert Shi(-I*x) == -I*Si(x)
assert Si(-x) == -Si(x)
assert Shi(-x) == -Shi(x)
assert Si(exp_polar(2*pi*I)*x) == Si(x)
assert Si(exp_polar(-2*pi*I)*x) == Si(x)
assert Shi(exp_polar(2*pi*I)*x) == Shi(x)
assert Shi(exp_polar(-2*pi*I)*x) == Shi(x)
assert Si(oo) == pi/2
assert Si(-oo) == -pi/2
assert Shi(oo) is oo
assert Shi(-oo) is -oo
assert mytd(Si(x), sin(x)/x, x)
assert mytd(Shi(x), sinh(x)/x, x)
assert mytn(Si(x), Si(x).rewrite(Ei),
-I*(-Ei(x*exp_polar(-I*pi/2))/2
+ Ei(x*exp_polar(I*pi/2))/2 - I*pi) + pi/2, x)
assert mytn(Si(x), Si(x).rewrite(expint),
-I*(-expint(1, x*exp_polar(-I*pi/2))/2 +
expint(1, x*exp_polar(I*pi/2))/2) + pi/2, x)
assert mytn(Shi(x), Shi(x).rewrite(Ei),
Ei(x)/2 - Ei(x*exp_polar(I*pi))/2 + I*pi/2, x)
assert mytn(Shi(x), Shi(x).rewrite(expint),
expint(1, x)/2 - expint(1, x*exp_polar(I*pi))/2 - I*pi/2, x)
assert tn_arg(Si)
assert tn_arg(Shi)
assert Si(x).nseries(x, n=8) == \
x - x**3/18 + x**5/600 - x**7/35280 + O(x**9)
assert Shi(x).nseries(x, n=8) == \
x + x**3/18 + x**5/600 + x**7/35280 + O(x**9)
assert Si(sin(x)).nseries(x, n=5) == x - 2*x**3/9 + 17*x**5/450 + O(x**6)
assert Si(x).nseries(x, 1, n=3) == \
Si(1) + (x - 1)*sin(1) + (x - 1)**2*(-sin(1)/2 + cos(1)/2) + O((x - 1)**3, (x, 1))
assert Si(x).series(x, oo) == pi/2 - (- 6/x**3 + 1/x \
+ O(x**(-7), (x, oo)))*sin(x)/x - (24/x**4 - 2/x**2 + 1 \
+ O(x**(-7), (x, oo)))*cos(x)/x
t = Symbol('t', Dummy=True)
assert Si(x).rewrite(sinc) == Integral(sinc(t), (t, 0, x))
assert limit(Shi(x), x, S.Infinity) == S.Infinity
assert limit(Shi(x), x, S.NegativeInfinity) == S.NegativeInfinity
def test_ci():
m1 = exp_polar(I*pi)
m1_ = exp_polar(-I*pi)
pI = exp_polar(I*pi/2)
mI = exp_polar(-I*pi/2)
assert Ci(m1*x) == Ci(x) + I*pi
assert Ci(m1_*x) == Ci(x) - I*pi
assert Ci(pI*x) == Chi(x) + I*pi/2
assert Ci(mI*x) == Chi(x) - I*pi/2
assert Chi(m1*x) == Chi(x) + I*pi
assert Chi(m1_*x) == Chi(x) - I*pi
assert Chi(pI*x) == Ci(x) + I*pi/2
assert Chi(mI*x) == Ci(x) - I*pi/2
assert Ci(exp_polar(2*I*pi)*x) == Ci(x) + 2*I*pi
assert Chi(exp_polar(-2*I*pi)*x) == Chi(x) - 2*I*pi
assert Chi(exp_polar(2*I*pi)*x) == Chi(x) + 2*I*pi
assert Ci(exp_polar(-2*I*pi)*x) == Ci(x) - 2*I*pi
assert Ci(oo) is S.Zero
assert Ci(-oo) == I*pi
assert Chi(oo) is oo
assert Chi(-oo) is oo
assert mytd(Ci(x), cos(x)/x, x)
assert mytd(Chi(x), cosh(x)/x, x)
assert mytn(Ci(x), Ci(x).rewrite(Ei),
Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2, x)
assert mytn(Chi(x), Chi(x).rewrite(Ei),
Ei(x)/2 + Ei(x*exp_polar(I*pi))/2 - I*pi/2, x)
assert tn_arg(Ci)
assert tn_arg(Chi)
assert Ci(x).nseries(x, n=4) == \
EulerGamma + log(x) - x**2/4 + x**4/96 + O(x**5)
assert Chi(x).nseries(x, n=4) == \
EulerGamma + log(x) + x**2/4 + x**4/96 + O(x**5)
assert Ci(x).series(x, oo) == -cos(x)*(-6/x**3 + 1/x \
+ O(x**(-7), (x, oo)))/x + (24/x**4 - 2/x**2 + 1 \
+ O(x**(-7), (x, oo)))*sin(x)/x
assert limit(log(x) - Ci(2*x), x, 0) == -log(2) - EulerGamma
assert Ci(x).rewrite(uppergamma) == -expint(1, x*exp_polar(-I*pi/2))/2 -\
expint(1, x*exp_polar(I*pi/2))/2
assert Ci(x).rewrite(expint) == -expint(1, x*exp_polar(-I*pi/2))/2 -\
expint(1, x*exp_polar(I*pi/2))/2
raises(ArgumentIndexError, lambda: Ci(x).fdiff(2))
def test_fresnel():
assert fresnels(0) is S.Zero
assert fresnels(oo) is S.Half
assert fresnels(-oo) == Rational(-1, 2)
assert fresnels(I*oo) == -I*S.Half
assert unchanged(fresnels, z)
assert fresnels(-z) == -fresnels(z)
assert fresnels(I*z) == -I*fresnels(z)
assert fresnels(-I*z) == I*fresnels(z)
assert conjugate(fresnels(z)) == fresnels(conjugate(z))
assert fresnels(z).diff(z) == sin(pi*z**2/2)
assert fresnels(z).rewrite(erf) == (S.One + I)/4 * (
erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z))
assert fresnels(z).rewrite(hyper) == \
pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16)
assert fresnels(z).series(z, n=15) == \
pi*z**3/6 - pi**3*z**7/336 + pi**5*z**11/42240 + O(z**15)
assert fresnels(w).is_extended_real is True
assert fresnels(w).is_finite is True
assert fresnels(z).is_extended_real is None
assert fresnels(z).is_finite is None
assert fresnels(z).as_real_imag() == (fresnels(re(z) - I*im(z))/2 +
fresnels(re(z) + I*im(z))/2,
-I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2)
assert fresnels(z).as_real_imag(deep=False) == (fresnels(re(z) - I*im(z))/2 +
fresnels(re(z) + I*im(z))/2,
-I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2)
assert fresnels(w).as_real_imag() == (fresnels(w), 0)
assert fresnels(w).as_real_imag(deep=True) == (fresnels(w), 0)
assert fresnels(2 + 3*I).as_real_imag() == (
fresnels(2 + 3*I)/2 + fresnels(2 - 3*I)/2,
-I*(fresnels(2 + 3*I) - fresnels(2 - 3*I))/2
)
assert expand_func(integrate(fresnels(z), z)) == \
z*fresnels(z) + cos(pi*z**2/2)/pi
assert fresnels(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(9, 4) * \
meijerg(((), (1,)), ((Rational(3, 4),),
(Rational(1, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(3, 4)*(z**2)**Rational(3, 4))
assert fresnelc(0) is S.Zero
assert fresnelc(oo) == S.Half
assert fresnelc(-oo) == Rational(-1, 2)
assert fresnelc(I*oo) == I*S.Half
assert unchanged(fresnelc, z)
assert fresnelc(-z) == -fresnelc(z)
assert fresnelc(I*z) == I*fresnelc(z)
assert fresnelc(-I*z) == -I*fresnelc(z)
assert conjugate(fresnelc(z)) == fresnelc(conjugate(z))
assert fresnelc(z).diff(z) == cos(pi*z**2/2)
assert fresnelc(z).rewrite(erf) == (S.One - I)/4 * (
erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z))
assert fresnelc(z).rewrite(hyper) == \
z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16)
assert fresnelc(w).is_extended_real is True
assert fresnelc(z).as_real_imag() == \
(fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2,
-I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2)
assert fresnelc(z).as_real_imag(deep=False) == \
(fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2,
-I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2)
assert fresnelc(2 + 3*I).as_real_imag() == (
fresnelc(2 - 3*I)/2 + fresnelc(2 + 3*I)/2,
-I*(fresnelc(2 + 3*I) - fresnelc(2 - 3*I))/2
)
assert expand_func(integrate(fresnelc(z), z)) == \
z*fresnelc(z) - sin(pi*z**2/2)/pi
assert fresnelc(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(3, 4) * \
meijerg(((), (1,)), ((Rational(1, 4),),
(Rational(3, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(1, 4)*(z**2)**Rational(1, 4))
from sympy.core.random import verify_numerically
verify_numerically(re(fresnels(z)), fresnels(z).as_real_imag()[0], z)
verify_numerically(im(fresnels(z)), fresnels(z).as_real_imag()[1], z)
verify_numerically(fresnels(z), fresnels(z).rewrite(hyper), z)
verify_numerically(fresnels(z), fresnels(z).rewrite(meijerg), z)
verify_numerically(re(fresnelc(z)), fresnelc(z).as_real_imag()[0], z)
verify_numerically(im(fresnelc(z)), fresnelc(z).as_real_imag()[1], z)
verify_numerically(fresnelc(z), fresnelc(z).rewrite(hyper), z)
verify_numerically(fresnelc(z), fresnelc(z).rewrite(meijerg), z)
raises(ArgumentIndexError, lambda: fresnels(z).fdiff(2))
raises(ArgumentIndexError, lambda: fresnelc(z).fdiff(2))
assert fresnels(x).taylor_term(-1, x) is S.Zero
assert fresnelc(x).taylor_term(-1, x) is S.Zero
assert fresnelc(x).taylor_term(1, x) == -pi**2*x**5/40
def test_fresnel_series():
assert fresnelc(z).series(z, n=15) == \
z - pi**2*z**5/40 + pi**4*z**9/3456 - pi**6*z**13/599040 + O(z**15)
# issues 6510, 10102
fs = (S.Half - sin(pi*z**2/2)/(pi**2*z**3)
+ (-1/(pi*z) + 3/(pi**3*z**5))*cos(pi*z**2/2))
fc = (S.Half - cos(pi*z**2/2)/(pi**2*z**3)
+ (1/(pi*z) - 3/(pi**3*z**5))*sin(pi*z**2/2))
assert fresnels(z).series(z, oo) == fs + O(z**(-6), (z, oo))
assert fresnelc(z).series(z, oo) == fc + O(z**(-6), (z, oo))
assert (fresnels(z).series(z, -oo) + fs.subs(z, -z)).expand().is_Order
assert (fresnelc(z).series(z, -oo) + fc.subs(z, -z)).expand().is_Order
assert (fresnels(1/z).series(z) - fs.subs(z, 1/z)).expand().is_Order
assert (fresnelc(1/z).series(z) - fc.subs(z, 1/z)).expand().is_Order
assert ((2*fresnels(3*z)).series(z, oo) - 2*fs.subs(z, 3*z)).expand().is_Order
assert ((3*fresnelc(2*z)).series(z, oo) - 3*fc.subs(z, 2*z)).expand().is_Order
|
e343e51c7623914625720fd6c05d0cb3d09f75014d878dabbfec0952c5542c40 | from sympy.assumptions.ask import (Q, ask)
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import (Derivative, Function, diff)
from sympy.core.mul import Mul
from sympy.core import (GoldenRatio, TribonacciConstant)
from sympy.core.numbers import (E, Float, I, Rational, oo, pi)
from sympy.core.relational import (Eq, Gt, Lt, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import binomial
from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, re)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (atanh, cosh, sinh, tanh)
from sympy.functions.elementary.miscellaneous import (cbrt, root, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, atan2, cos, sec, sin, tan)
from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv)
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import (And, Or)
from sympy.matrices.dense import Matrix
from sympy.matrices import SparseMatrix
from sympy.polys.polytools import Poly
from sympy.printing.str import sstr
from sympy.simplify.radsimp import denom
from sympy.solvers.solvers import (nsolve, solve, solve_linear)
from sympy.core.function import nfloat
from sympy.solvers import solve_linear_system, solve_linear_system_LU, \
solve_undetermined_coeffs
from sympy.solvers.bivariate import _filtered_gens, _solve_lambert, _lambert
from sympy.solvers.solvers import _invert, unrad, checksol, posify, _ispow, \
det_quick, det_perm, det_minor, _simple_dens, denoms
from sympy.physics.units import cm
from sympy.polys.rootoftools import CRootOf
from sympy.testing.pytest import slow, XFAIL, SKIP, raises
from sympy.core.random import verify_numerically as tn
from sympy.abc import a, b, c, d, e, k, h, p, x, y, z, t, q, m, R
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_swap_back():
f, g = map(Function, 'fg')
fx, gx = f(x), g(x)
assert solve([fx + y - 2, fx - gx - 5], fx, y, gx) == \
{fx: gx + 5, y: -gx - 3}
assert solve(fx + gx*x - 2, [fx, gx], dict=True) == [{fx: 2, gx: 0}]
assert solve(fx + gx**2*x - y, [fx, gx], dict=True) == [{fx: y, gx: 0}]
assert solve([f(1) - 2, x + 2], dict=True) == [{x: -2, f(1): 2}]
def guess_solve_strategy(eq, symbol):
try:
solve(eq, symbol)
return True
except (TypeError, NotImplementedError):
return False
def test_guess_poly():
# polynomial equations
assert guess_solve_strategy( S(4), x ) # == GS_POLY
assert guess_solve_strategy( x, x ) # == GS_POLY
assert guess_solve_strategy( x + a, x ) # == GS_POLY
assert guess_solve_strategy( 2*x, x ) # == GS_POLY
assert guess_solve_strategy( x + sqrt(2), x) # == GS_POLY
assert guess_solve_strategy( x + 2**Rational(1, 4), x) # == GS_POLY
assert guess_solve_strategy( x**2 + 1, x ) # == GS_POLY
assert guess_solve_strategy( x**2 - 1, x ) # == GS_POLY
assert guess_solve_strategy( x*y + y, x ) # == GS_POLY
assert guess_solve_strategy( x*exp(y) + y, x) # == GS_POLY
assert guess_solve_strategy(
(x - y**3)/(y**2*sqrt(1 - y**2)), x) # == GS_POLY
def test_guess_poly_cv():
# polynomial equations via a change of variable
assert guess_solve_strategy( sqrt(x) + 1, x ) # == GS_POLY_CV_1
assert guess_solve_strategy(
x**Rational(1, 3) + sqrt(x) + 1, x ) # == GS_POLY_CV_1
assert guess_solve_strategy( 4*x*(1 - sqrt(x)), x ) # == GS_POLY_CV_1
# polynomial equation multiplying both sides by x**n
assert guess_solve_strategy( x + 1/x + y, x ) # == GS_POLY_CV_2
def test_guess_rational_cv():
# rational functions
assert guess_solve_strategy( (x + 1)/(x**2 + 2), x) # == GS_RATIONAL
assert guess_solve_strategy(
(x - y**3)/(y**2*sqrt(1 - y**2)), y) # == GS_RATIONAL_CV_1
# rational functions via the change of variable y -> x**n
assert guess_solve_strategy( (sqrt(x) + 1)/(x**Rational(1, 3) + sqrt(x) + 1), x ) \
#== GS_RATIONAL_CV_1
def test_guess_transcendental():
#transcendental functions
assert guess_solve_strategy( exp(x) + 1, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy( 2*cos(x) - y, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(
exp(x) + exp(-x) - y, x ) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(3**x - 10, x) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(-3**x + 10, x) # == GS_TRANSCENDENTAL
assert guess_solve_strategy(a*x**b - y, x) # == GS_TRANSCENDENTAL
def test_solve_args():
# equation container, issue 5113
ans = {x: -3, y: 1}
eqs = (x + 5*y - 2, -3*x + 6*y - 15)
assert all(solve(container(eqs), x, y) == ans for container in
(tuple, list, set, frozenset))
assert solve(Tuple(*eqs), x, y) == ans
# implicit symbol to solve for
assert set(solve(x**2 - 4)) == {S(2), -S(2)}
assert solve([x + y - 3, x - y - 5]) == {x: 4, y: -1}
assert solve(x - exp(x), x, implicit=True) == [exp(x)]
# no symbol to solve for
assert solve(42) == solve(42, x) == []
assert solve([1, 2]) == []
assert solve([sqrt(2)],[x]) == []
# duplicate symbols raises
raises(ValueError, lambda: solve((x - 3, y + 2), x, y, x))
raises(ValueError, lambda: solve(x, x, x))
# no error in exclude
assert solve(x, x, exclude=[y, y]) == [0]
# duplicate symbols raises
raises(ValueError, lambda: solve((x - 3, y + 2), x, y, x))
raises(ValueError, lambda: solve(x, x, x))
# no error in exclude
assert solve(x, x, exclude=[y, y]) == [0]
# unordered symbols
# only 1
assert solve(y - 3, {y}) == [3]
# more than 1
assert solve(y - 3, {x, y}) == [{y: 3}]
# multiple symbols: take the first linear solution+
# - return as tuple with values for all requested symbols
assert solve(x + y - 3, [x, y]) == [(3 - y, y)]
# - unless dict is True
assert solve(x + y - 3, [x, y], dict=True) == [{x: 3 - y}]
# - or no symbols are given
assert solve(x + y - 3) == [{x: 3 - y}]
# multiple symbols might represent an undetermined coefficients system
assert solve(a + b*x - 2, [a, b]) == {a: 2, b: 0}
assert solve((a + b)*x + b - c, [a, b]) == {a: -c, b: c}
eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p
# - check that flags are obeyed
sol = solve(eq, [h, p, k], exclude=[a, b, c])
assert sol == {h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)}
assert solve(eq, [h, p, k], dict=True) == [sol]
assert solve(eq, [h, p, k], set=True) == \
([h, p, k], {(-b/(2*a), 1/(4*a), (4*a*c - b**2)/(4*a))})
# issue 23889 - polysys not simplified
assert solve(eq, [h, p, k], exclude=[a, b, c], simplify=False) == \
{h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)}
# but this only happens when system has a single solution
args = (a + b)*x - b**2 + 2, a, b
assert solve(*args) == [((b**2 - b*x - 2)/x, b)]
# and if the system has a solution; the following doesn't so
# an algebraic solution is returned
assert solve(a*x + b**2/(x + 4) - 3*x - 4/x, a, b, dict=True) == \
[{a: (-b**2*x + 3*x**3 + 12*x**2 + 4*x + 16)/(x**2*(x + 4))}]
# failed single equation
assert solve(1/(1/x - y + exp(y))) == []
raises(
NotImplementedError, lambda: solve(exp(x) + sin(x) + exp(y) + sin(y)))
# failed system
# -- when no symbols given, 1 fails
assert solve([y, exp(x) + x]) == [{x: -LambertW(1), y: 0}]
# both fail
assert solve(
(exp(x) - x, exp(y) - y)) == [{x: -LambertW(-1), y: -LambertW(-1)}]
# -- when symbols given
assert solve([y, exp(x) + x], x, y) == [(-LambertW(1), 0)]
# symbol is a number
assert solve(x**2 - pi, pi) == [x**2]
# no equations
assert solve([], [x]) == []
# nonlinear systen
assert solve((x**2 - 4, y - 2), x, y) == [(-2, 2), (2, 2)]
assert solve((x**2 - 4, y - 2), y, x) == [(2, -2), (2, 2)]
assert solve((x**2 - 4 + z, y - 2 - z), a, z, y, x, set=True
) == ([a, z, y, x], {
(a, z, z + 2, -sqrt(4 - z)),
(a, z, z + 2, sqrt(4 - z))})
# overdetermined system
# - nonlinear
assert solve([(x + y)**2 - 4, x + y - 2]) == [{x: -y + 2}]
# - linear
assert solve((x + y - 2, 2*x + 2*y - 4)) == {x: -y + 2}
# When one or more args are Boolean
assert solve(Eq(x**2, 0.0)) == [0] # issue 19048
assert solve([True, Eq(x, 0)], [x], dict=True) == [{x: 0}]
assert solve([Eq(x, x), Eq(x, 0), Eq(x, x+1)], [x], dict=True) == []
assert not solve([Eq(x, x+1), x < 2], x)
assert solve([Eq(x, 0), x+1<2]) == Eq(x, 0)
assert solve([Eq(x, x), Eq(x, x+1)], x) == []
assert solve(True, x) == []
assert solve([x - 1, False], [x], set=True) == ([], set())
assert solve([-y*(x + y - 1)/2, (y - 1)/x/y + 1/y],
set=True, check=False) == ([x, y], {(1 - y, y), (x, 0)})
# ordering should be canonical, fastest to order by keys instead
# of by size
assert list(solve((y - 1, x - sqrt(3)*z)).keys()) == [x, y]
# as set always returns as symbols, set even if no solution
assert solve([x - 1, x], (y, x), set=True) == ([y, x], set())
assert solve([x - 1, x], {y, x}, set=True) == ([x, y], set())
def test_solve_polynomial1():
assert solve(3*x - 2, x) == [Rational(2, 3)]
assert solve(Eq(3*x, 2), x) == [Rational(2, 3)]
assert set(solve(x**2 - 1, x)) == {-S.One, S.One}
assert set(solve(Eq(x**2, 1), x)) == {-S.One, S.One}
assert solve(x - y**3, x) == [y**3]
rx = root(x, 3)
assert solve(x - y**3, y) == [
rx, -rx/2 - sqrt(3)*I*rx/2, -rx/2 + sqrt(3)*I*rx/2]
a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2')
assert solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) == \
{
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21),
y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
}
solution = {x: S.Zero, y: S.Zero}
assert solve((x - y, x + y), x, y ) == solution
assert solve((x - y, x + y), (x, y)) == solution
assert solve((x - y, x + y), [x, y]) == solution
assert set(solve(x**3 - 15*x - 4, x)) == {
-2 + 3**S.Half,
S(4),
-2 - 3**S.Half
}
assert set(solve((x**2 - 1)**2 - a, x)) == \
{sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)),
sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))}
def test_solve_polynomial2():
assert solve(4, x) == []
def test_solve_polynomial_cv_1a():
"""
Test for solving on equations that can be converted to a polynomial equation
using the change of variable y -> x**Rational(p, q)
"""
assert solve( sqrt(x) - 1, x) == [1]
assert solve( sqrt(x) - 2, x) == [4]
assert solve( x**Rational(1, 4) - 2, x) == [16]
assert solve( x**Rational(1, 3) - 3, x) == [27]
assert solve(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == [0]
def test_solve_polynomial_cv_1b():
assert set(solve(4*x*(1 - a*sqrt(x)), x)) == {S.Zero, 1/a**2}
assert set(solve(x*(root(x, 3) - 3), x)) == {S.Zero, S(27)}
def test_solve_polynomial_cv_2():
"""
Test for solving on equations that can be converted to a polynomial equation
multiplying both sides of the equation by x**m
"""
assert solve(x + 1/x - 1, x) in \
[[ S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2],
[ S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]]
def test_quintics_1():
f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979
s = solve(f, check=False)
for r in s:
res = f.subs(x, r.n()).n()
assert tn(res, 0)
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = solve(f)
for r in s:
assert r.func == CRootOf
# if one uses solve to get the roots of a polynomial that has a CRootOf
# solution, make sure that the use of nfloat during the solve process
# doesn't fail. Note: if you want numerical solutions to a polynomial
# it is *much* faster to use nroots to get them than to solve the
# equation only to get RootOf solutions which are then numerically
# evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather
# than [i.n() for i in solve(eq)] to get the numerical roots of eq.
assert nfloat(solve(x**5 + 3*x**3 + 7)[0], exponent=False) == \
CRootOf(x**5 + 3*x**3 + 7, 0).n()
def test_quintics_2():
f = x**5 + 15*x + 12
s = solve(f, check=False)
for r in s:
res = f.subs(x, r.n()).n()
assert tn(res, 0)
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = solve(f)
for r in s:
assert r.func == CRootOf
assert solve(x**5 - 6*x**3 - 6*x**2 + x - 6) == [
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 0),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 1),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 2),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 3),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 4)]
def test_quintics_3():
y = x**5 + x**3 - 2**Rational(1, 3)
assert solve(y) == solve(-y) == []
def test_highorder_poly():
# just testing that the uniq generator is unpacked
sol = solve(x**6 - 2*x + 2)
assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6
def test_solve_rational():
"""Test solve for rational functions"""
assert solve( ( x - y**3 )/( (y**2)*sqrt(1 - y**2) ), x) == [y**3]
def test_solve_conjugate():
"""Test solve for simple conjugate functions"""
assert solve(conjugate(x) -3 + I) == [3 + I]
def test_solve_nonlinear():
assert solve(x**2 - y**2, x, y, dict=True) == [{x: -y}, {x: y}]
assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: -x*sqrt(exp(x))},
{y: x*sqrt(exp(x))}]
def test_issue_8666():
x = symbols('x')
assert solve(Eq(x**2 - 1/(x**2 - 4), 4 - 1/(x**2 - 4)), x) == []
assert solve(Eq(x + 1/x, 1/x), x) == []
def test_issue_7228():
assert solve(4**(2*(x**2) + 2*x) - 8, x) == [Rational(-3, 2), S.Half]
def test_issue_7190():
assert solve(log(x-3) + log(x+3), x) == [sqrt(10)]
def test_issue_21004():
x = symbols('x')
f = x/sqrt(x**2+1)
f_diff = f.diff(x)
assert solve(f_diff, x) == []
def test_linear_system():
x, y, z, t, n = symbols('x, y, z, t, n')
assert solve([x - 1, x - y, x - 2*y, y - 1], [x, y]) == []
assert solve([x - 1, x - y, x - 2*y, x - 1], [x, y]) == []
assert solve([x - 1, x - 1, x - y, x - 2*y], [x, y]) == []
assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == {x: -3, y: 1}
M = Matrix([[0, 0, n*(n + 1), (n + 1)**2, 0],
[n + 1, n + 1, -2*n - 1, -(n + 1), 0],
[-1, 0, 1, 0, 0]])
assert solve_linear_system(M, x, y, z, t) == \
{x: t*(-n-1)/n, y: 0, z: t*(-n-1)/n}
assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t}
@XFAIL
def test_linear_system_xfail():
# https://github.com/sympy/sympy/issues/6420
M = Matrix([[0, 15.0, 10.0, 700.0],
[1, 1, 1, 100.0],
[0, 10.0, 5.0, 200.0],
[-5.0, 0, 0, 0 ]])
assert solve_linear_system(M, x, y, z) == {x: 0, y: -60.0, z: 160.0}
def test_linear_system_function():
a = Function('a')
assert solve([a(0, 0) + a(0, 1) + a(1, 0) + a(1, 1), -a(1, 0) - a(1, 1)],
a(0, 0), a(0, 1), a(1, 0), a(1, 1)) == {a(1, 0): -a(1, 1), a(0, 0): -a(0, 1)}
def test_linear_system_symbols_doesnt_hang_1():
def _mk_eqs(wy):
# Equations for fitting a wy*2 - 1 degree polynomial between two points,
# at end points derivatives are known up to order: wy - 1
order = 2*wy - 1
x, x0, x1 = symbols('x, x0, x1', real=True)
y0s = symbols('y0_:{}'.format(wy), real=True)
y1s = symbols('y1_:{}'.format(wy), real=True)
c = symbols('c_:{}'.format(order+1), real=True)
expr = sum([coeff*x**o for o, coeff in enumerate(c)])
eqs = []
for i in range(wy):
eqs.append(expr.diff(x, i).subs({x: x0}) - y0s[i])
eqs.append(expr.diff(x, i).subs({x: x1}) - y1s[i])
return eqs, c
#
# The purpose of this test is just to see that these calls don't hang. The
# expressions returned are complicated so are not included here. Testing
# their correctness takes longer than solving the system.
#
for n in range(1, 7+1):
eqs, c = _mk_eqs(n)
solve(eqs, c)
def test_linear_system_symbols_doesnt_hang_2():
M = Matrix([
[66, 24, 39, 50, 88, 40, 37, 96, 16, 65, 31, 11, 37, 72, 16, 19, 55, 37, 28, 76],
[10, 93, 34, 98, 59, 44, 67, 74, 74, 94, 71, 61, 60, 23, 6, 2, 57, 8, 29, 78],
[19, 91, 57, 13, 64, 65, 24, 53, 77, 34, 85, 58, 87, 39, 39, 7, 36, 67, 91, 3],
[74, 70, 15, 53, 68, 43, 86, 83, 81, 72, 25, 46, 67, 17, 59, 25, 78, 39, 63, 6],
[69, 40, 67, 21, 67, 40, 17, 13, 93, 44, 46, 89, 62, 31, 30, 38, 18, 20, 12, 81],
[50, 22, 74, 76, 34, 45, 19, 76, 28, 28, 11, 99, 97, 82, 8, 46, 99, 57, 68, 35],
[58, 18, 45, 88, 10, 64, 9, 34, 90, 82, 17, 41, 43, 81, 45, 83, 22, 88, 24, 39],
[42, 21, 70, 68, 6, 33, 64, 81, 83, 15, 86, 75, 86, 17, 77, 34, 62, 72, 20, 24],
[ 7, 8, 2, 72, 71, 52, 96, 5, 32, 51, 31, 36, 79, 88, 25, 77, 29, 26, 33, 13],
[19, 31, 30, 85, 81, 39, 63, 28, 19, 12, 16, 49, 37, 66, 38, 13, 3, 71, 61, 51],
[29, 82, 80, 49, 26, 85, 1, 37, 2, 74, 54, 82, 26, 47, 54, 9, 35, 0, 99, 40],
[15, 49, 82, 91, 93, 57, 45, 25, 45, 97, 15, 98, 48, 52, 66, 24, 62, 54, 97, 37],
[62, 23, 73, 53, 52, 86, 28, 38, 0, 74, 92, 38, 97, 70, 71, 29, 26, 90, 67, 45],
[ 2, 32, 23, 24, 71, 37, 25, 71, 5, 41, 97, 65, 93, 13, 65, 45, 25, 88, 69, 50],
[40, 56, 1, 29, 79, 98, 79, 62, 37, 28, 45, 47, 3, 1, 32, 74, 98, 35, 84, 32],
[33, 15, 87, 79, 65, 9, 14, 63, 24, 19, 46, 28, 74, 20, 29, 96, 84, 91, 93, 1],
[97, 18, 12, 52, 1, 2, 50, 14, 52, 76, 19, 82, 41, 73, 51, 79, 13, 3, 82, 96],
[40, 28, 52, 10, 10, 71, 56, 78, 82, 5, 29, 48, 1, 26, 16, 18, 50, 76, 86, 52],
[38, 89, 83, 43, 29, 52, 90, 77, 57, 0, 67, 20, 81, 88, 48, 96, 88, 58, 14, 3]])
syms = x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18 = symbols('x:19')
sol = {
x0: -S(1967374186044955317099186851240896179)/3166636564687820453598895768302256588,
x1: -S(84268280268757263347292368432053826)/791659141171955113399723942075564147,
x2: -S(229962957341664730974463872411844965)/1583318282343910226799447884151128294,
x3: S(990156781744251750886760432229180537)/6333273129375640907197791536604513176,
x4: -S(2169830351210066092046760299593096265)/18999819388126922721593374609813539528,
x5: S(4680868883477577389628494526618745355)/9499909694063461360796687304906769764,
x6: -S(1590820774344371990683178396480879213)/3166636564687820453598895768302256588,
x7: -S(54104723404825537735226491634383072)/339282489073695048599881689460956063,
x8: S(3182076494196560075964847771774733847)/6333273129375640907197791536604513176,
x9: -S(10870817431029210431989147852497539675)/18999819388126922721593374609813539528,
x10: -S(13118019242576506476316318268573312603)/18999819388126922721593374609813539528,
x11: -S(5173852969886775824855781403820641259)/4749954847031730680398343652453384882,
x12: S(4261112042731942783763341580651820563)/4749954847031730680398343652453384882,
x13: -S(821833082694661608993818117038209051)/6333273129375640907197791536604513176,
x14: S(906881575107250690508618713632090559)/904753304196520129599684505229216168,
x15: -S(732162528717458388995329317371283987)/6333273129375640907197791536604513176,
x16: S(4524215476705983545537087360959896817)/9499909694063461360796687304906769764,
x17: -S(3898571347562055611881270844646055217)/6333273129375640907197791536604513176,
x18: S(7513502486176995632751685137907442269)/18999819388126922721593374609813539528
}
eqs = list(M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
y = Symbol('y')
eqs = list(y * M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
def test_linear_systemLU():
n = Symbol('n')
M = Matrix([[1, 2, 0, 1], [1, 3, 2*n, 1], [4, -1, n**2, 1]])
assert solve_linear_system_LU(M, [x, y, z]) == {z: -3/(n**2 + 18*n),
x: 1 - 12*n/(n**2 + 18*n),
y: 6*n/(n**2 + 18*n)}
# Note: multiple solutions exist for some of these equations, so the tests
# should be expected to break if the implementation of the solver changes
# in such a way that a different branch is chosen
@slow
def test_solve_transcendental():
from sympy.abc import a, b
assert solve(exp(x) - 3, x) == [log(3)]
assert set(solve((a*x + b)*(exp(x) - 3), x)) == {-b/a, log(3)}
assert solve(cos(x) - y, x) == [-acos(y) + 2*pi, acos(y)]
assert solve(2*cos(x) - y, x) == [-acos(y/2) + 2*pi, acos(y/2)]
assert solve(Eq(cos(x), sin(x)), x) == [pi/4]
assert set(solve(exp(x) + exp(-x) - y, x)) in [{
log(y/2 - sqrt(y**2 - 4)/2),
log(y/2 + sqrt(y**2 - 4)/2),
}, {
log(y - sqrt(y**2 - 4)) - log(2),
log(y + sqrt(y**2 - 4)) - log(2)},
{
log(y/2 - sqrt((y - 2)*(y + 2))/2),
log(y/2 + sqrt((y - 2)*(y + 2))/2)}]
assert solve(exp(x) - 3, x) == [log(3)]
assert solve(Eq(exp(x), 3), x) == [log(3)]
assert solve(log(x) - 3, x) == [exp(3)]
assert solve(sqrt(3*x) - 4, x) == [Rational(16, 3)]
assert solve(3**(x + 2), x) == []
assert solve(3**(2 - x), x) == []
assert solve(x + 2**x, x) == [-LambertW(log(2))/log(2)]
assert solve(2*x + 5 + log(3*x - 2), x) == \
[Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2]
assert solve(3*x + log(4*x), x) == [LambertW(Rational(3, 4))/3]
assert set(solve((2*x + 8)*(8 + exp(x)), x)) == {S(-4), log(8) + pi*I}
eq = 2*exp(3*x + 4) - 3
ans = solve(eq, x) # this generated a failure in flatten
assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans)
assert solve(2*log(3*x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4)/3]
assert solve(exp(x) + 1, x) == [pi*I]
eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9)
result = solve(eq, x)
x0 = -log(2401)
x1 = 3**Rational(1, 5)
x2 = log(7**(7*x1/20))
x3 = sqrt(2)
x4 = sqrt(5)
x5 = x3*sqrt(x4 - 5)
x6 = x4 + 1
x7 = 1/(3*log(7))
x8 = -x4
x9 = x3*sqrt(x8 - 5)
x10 = x8 + 1
ans = [x7*(x0 - 5*LambertW(x2*(-x5 + x6))),
x7*(x0 - 5*LambertW(x2*(x5 + x6))),
x7*(x0 - 5*LambertW(x2*(x10 - x9))),
x7*(x0 - 5*LambertW(x2*(x10 + x9))),
x7*(x0 - 5*LambertW(-log(7**(7*x1/5))))]
assert result == ans, result
# it works if expanded, too
assert solve(eq.expand(), x) == result
assert solve(z*cos(x) - y, x) == [-acos(y/z) + 2*pi, acos(y/z)]
assert solve(z*cos(2*x) - y, x) == [-acos(y/z)/2 + pi, acos(y/z)/2]
assert solve(z*cos(sin(x)) - y, x) == [
pi - asin(acos(y/z)), asin(acos(y/z) - 2*pi) + pi,
-asin(acos(y/z) - 2*pi), asin(acos(y/z))]
assert solve(z*cos(x), x) == [pi/2, pi*Rational(3, 2)]
# issue 4508
assert solve(y - b*x/(a + x), x) in [[-a*y/(y - b)], [a*y/(b - y)]]
assert solve(y - b*exp(a/x), x) == [a/log(y/b)]
# issue 4507
assert solve(y - b/(1 + a*x), x) in [[(b - y)/(a*y)], [-((y - b)/(a*y))]]
# issue 4506
assert solve(y - a*x**b, x) == [(y/a)**(1/b)]
# issue 4505
assert solve(z**x - y, x) == [log(y)/log(z)]
# issue 4504
assert solve(2**x - 10, x) == [1 + log(5)/log(2)]
# issue 6744
assert solve(x*y) == [{x: 0}, {y: 0}]
assert solve([x*y]) == [{x: 0}, {y: 0}]
assert solve(x**y - 1) == [{x: 1}, {y: 0}]
assert solve([x**y - 1]) == [{x: 1}, {y: 0}]
assert solve(x*y*(x**2 - y**2)) == [{x: 0}, {x: -y}, {x: y}, {y: 0}]
assert solve([x*y*(x**2 - y**2)]) == [{x: 0}, {x: -y}, {x: y}, {y: 0}]
# issue 4739
assert solve(exp(log(5)*x) - 2**x, x) == [0]
# issue 14791
assert solve(exp(log(5)*x) - exp(log(2)*x), x) == [0]
f = Function('f')
assert solve(y*f(log(5)*x) - y*f(log(2)*x), x) == [0]
assert solve(f(x) - f(0), x) == [0]
assert solve(f(x) - f(2 - x), x) == [1]
raises(NotImplementedError, lambda: solve(f(x, y) - f(1, 2), x))
raises(NotImplementedError, lambda: solve(f(x, y) - f(2 - x, 2), x))
raises(ValueError, lambda: solve(f(x, y) - f(1 - x), x))
raises(ValueError, lambda: solve(f(x, y) - f(1), x))
# misc
# make sure that the right variables is picked up in tsolve
# shouldn't generate a GeneratorsNeeded error in _tsolve when the NaN is generated
# for eq_down. Actual answers, as determined numerically are approx. +/- 0.83
raises(NotImplementedError, lambda:
solve(sinh(x)*sinh(sinh(x)) + cosh(x)*cosh(sinh(x)) - 3))
# watch out for recursive loop in tsolve
raises(NotImplementedError, lambda: solve((x + 2)**y*x - 3, x))
# issue 7245
assert solve(sin(sqrt(x))) == [0, pi**2]
# issue 7602
a, b = symbols('a, b', real=True, negative=False)
assert str(solve(Eq(a, 0.5 - cos(pi*b)/2), b)) == \
'[2.0 - 0.318309886183791*acos(1.0 - 2.0*a), 0.318309886183791*acos(1.0 - 2.0*a)]'
# issue 15325
assert solve(y**(1/x) - z, x) == [log(y)/log(z)]
def test_solve_for_functions_derivatives():
t = Symbol('t')
x = Function('x')(t)
y = Function('y')(t)
a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2')
soln = solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y)
assert soln == {
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21),
y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
}
assert solve(x - 1, x) == [1]
assert solve(3*x - 2, x) == [Rational(2, 3)]
soln = solve([a11*x.diff(t) + a12*y.diff(t) - b1, a21*x.diff(t) +
a22*y.diff(t) - b2], x.diff(t), y.diff(t))
assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
x.diff(t): (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }
assert solve(x.diff(t) - 1, x.diff(t)) == [1]
assert solve(3*x.diff(t) - 2, x.diff(t)) == [Rational(2, 3)]
eqns = {3*x - 1, 2*y - 4}
assert solve(eqns, {x, y}) == { x: Rational(1, 3), y: 2 }
x = Symbol('x')
f = Function('f')
F = x**2 + f(x)**2 - 4*x - 1
assert solve(F.diff(x), diff(f(x), x)) == [(-x + 2)/f(x)]
# Mixed cased with a Symbol and a Function
x = Symbol('x')
y = Function('y')(t)
soln = solve([a11*x + a12*y.diff(t) - b1, a21*x +
a22*y.diff(t) - b2], x, y.diff(t))
assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }
# issue 13263
x = Symbol('x')
f = Function('f')
soln = solve([f(x).diff(x) + f(x).diff(x, 2) - 1, f(x).diff(x) - f(x).diff(x, 2)],
f(x).diff(x), f(x).diff(x, 2))
assert soln == { f(x).diff(x, 2): 1/2, f(x).diff(x): 1/2 }
soln = solve([f(x).diff(x, 2) + f(x).diff(x, 3) - 1, 1 - f(x).diff(x, 2) -
f(x).diff(x, 3), 1 - f(x).diff(x,3)], f(x).diff(x, 2), f(x).diff(x, 3))
assert soln == { f(x).diff(x, 2): 0, f(x).diff(x, 3): 1 }
def test_issue_3725():
f = Function('f')
F = x**2 + f(x)**2 - 4*x - 1
e = F.diff(x)
assert solve(e, f(x).diff(x)) in [[(2 - x)/f(x)], [-((x - 2)/f(x))]]
def test_issue_3870():
a, b, c, d = symbols('a b c d')
A = Matrix(2, 2, [a, b, c, d])
B = Matrix(2, 2, [0, 2, -3, 0])
C = Matrix(2, 2, [1, 2, 3, 4])
assert solve(A*B - C, [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1}
assert solve([A*B - C], [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1}
assert solve(Eq(A*B, C), [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1}
assert solve([A*B - B*A], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c}
assert solve([A*C - C*A], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c}
assert solve([A*B - B*A, A*C - C*A], [a, b, c, d]) == {a: d, b: 0, c: 0}
assert solve([Eq(A*B, B*A)], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c}
assert solve([Eq(A*C, C*A)], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c}
assert solve([Eq(A*B, B*A), Eq(A*C, C*A)], [a, b, c, d]) == {a: d, b: 0, c: 0}
def test_solve_linear():
w = Wild('w')
assert solve_linear(x, x) == (0, 1)
assert solve_linear(x, exclude=[x]) == (0, 1)
assert solve_linear(x, symbols=[w]) == (0, 1)
assert solve_linear(x, y - 2*x) in [(x, y/3), (y, 3*x)]
assert solve_linear(x, y - 2*x, exclude=[x]) == (y, 3*x)
assert solve_linear(3*x - y, 0) in [(x, y/3), (y, 3*x)]
assert solve_linear(3*x - y, 0, [x]) == (x, y/3)
assert solve_linear(3*x - y, 0, [y]) == (y, 3*x)
assert solve_linear(x**2/y, 1) == (y, x**2)
assert solve_linear(w, x) in [(w, x), (x, w)]
assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y) == \
(y, -2 - cos(x)**2 - sin(x)**2)
assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y, symbols=[x]) == (0, 1)
assert solve_linear(Eq(x, 3)) == (x, 3)
assert solve_linear(1/(1/x - 2)) == (0, 0)
assert solve_linear((x + 1)*exp(-x), symbols=[x]) == (x, -1)
assert solve_linear((x + 1)*exp(x), symbols=[x]) == ((x + 1)*exp(x), 1)
assert solve_linear(x*exp(-x**2), symbols=[x]) == (x, 0)
assert solve_linear(0**x - 1) == (0**x - 1, 1)
assert solve_linear(1 + 1/(x - 1)) == (x, 0)
eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0
assert solve_linear(eq) == (0, 1)
eq = cos(x)**2 + sin(x)**2 # = 1
assert solve_linear(eq) == (0, 1)
raises(ValueError, lambda: solve_linear(Eq(x, 3), 3))
def test_solve_undetermined_coeffs():
assert solve_undetermined_coeffs(
a*x**2 + b*x**2 + b*x + 2*c*x + c + 1, [a, b, c], x
) == {a: -2, b: 2, c: -1}
# Test that rational functions work
assert solve_undetermined_coeffs(a/x + b/(x + 1)
- (2*x + 1)/(x**2 + x), [a, b], x) == {a: 1, b: 1}
# Test cancellation in rational functions
assert solve_undetermined_coeffs(
((c + 1)*a*x**2 + (c + 1)*b*x**2 +
(c + 1)*b*x + (c + 1)*2*c*x + (c + 1)**2)/(c + 1),
[a, b, c], x) == \
{a: -2, b: 2, c: -1}
# multivariate
X, Y, Z = y, x**y, y*x**y
eq = a*X + b*Y + c*Z - X - 2*Y - 3*Z
coeffs = a, b, c
syms = x, y
assert solve_undetermined_coeffs(eq, coeffs) == {
a: 1, b: 2, c: 3}
assert solve_undetermined_coeffs(eq, coeffs, syms) == {
a: 1, b: 2, c: 3}
assert solve_undetermined_coeffs(eq, coeffs, *syms) == {
a: 1, b: 2, c: 3}
# check output format
assert solve_undetermined_coeffs(a*x + a - 2, [a]) == []
assert solve_undetermined_coeffs(a**2*x - 4*x, [a]) == [
{a: -2}, {a: 2}]
assert solve_undetermined_coeffs(0, [a]) == []
assert solve_undetermined_coeffs(0, [a], dict=True) == []
assert solve_undetermined_coeffs(0, [a], set=True) == ([], {})
assert solve_undetermined_coeffs(1, [a]) == []
abeq = a*x - 2*x + b - 3
s = {b, a}
assert solve_undetermined_coeffs(abeq, s, x) == {a: 2, b: 3}
assert solve_undetermined_coeffs(abeq, s, x, set=True) == ([a, b], {(2, 3)})
assert solve_undetermined_coeffs(sin(a*x) - sin(2*x), (a,)) is None
assert solve_undetermined_coeffs(a*x + b*x - 2*x, (a, b)) == {a: 2 - b}
def test_solve_inequalities():
x = Symbol('x')
sol = And(S.Zero < x, x < oo)
assert solve(x + 1 > 1) == sol
assert solve([x + 1 > 1]) == sol
assert solve([x + 1 > 1], x) == sol
assert solve([x + 1 > 1], [x]) == sol
system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]
assert solve(system) == \
And(Or(And(Lt(-sqrt(2), x), Lt(x, -1)),
And(Lt(1, x), Lt(x, sqrt(2)))), Eq(0, 0))
x = Symbol('x', real=True)
system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]
assert solve(system) == \
Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2))))
# issues 6627, 3448
assert solve((x - 3)/(x - 2) < 0, x) == And(Lt(2, x), Lt(x, 3))
assert solve(x/(x + 1) > 1, x) == And(Lt(-oo, x), Lt(x, -1))
assert solve(sin(x) > S.Half) == And(pi/6 < x, x < pi*Rational(5, 6))
assert solve(Eq(False, x < 1)) == (S.One <= x) & (x < oo)
assert solve(Eq(True, x < 1)) == (-oo < x) & (x < 1)
assert solve(Eq(x < 1, False)) == (S.One <= x) & (x < oo)
assert solve(Eq(x < 1, True)) == (-oo < x) & (x < 1)
assert solve(Eq(False, x)) == False
assert solve(Eq(0, x)) == [0]
assert solve(Eq(True, x)) == True
assert solve(Eq(1, x)) == [1]
assert solve(Eq(False, ~x)) == True
assert solve(Eq(True, ~x)) == False
assert solve(Ne(True, x)) == False
assert solve(Ne(1, x)) == (x > -oo) & (x < oo) & Ne(x, 1)
def test_issue_4793():
assert solve(1/x) == []
assert solve(x*(1 - 5/x)) == [5]
assert solve(x + sqrt(x) - 2) == [1]
assert solve(-(1 + x)/(2 + x)**2 + 1/(2 + x)) == []
assert solve(-x**2 - 2*x + (x + 1)**2 - 1) == []
assert solve((x/(x + 1) + 3)**(-2)) == []
assert solve(x/sqrt(x**2 + 1), x) == [0]
assert solve(exp(x) - y, x) == [log(y)]
assert solve(exp(x)) == []
assert solve(x**2 + x + sin(y)**2 + cos(y)**2 - 1, x) in [[0, -1], [-1, 0]]
eq = 4*3**(5*x + 2) - 7
ans = solve(eq, x)
assert len(ans) == 5 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans)
assert solve(log(x**2) - y**2/exp(x), x, y, set=True) == (
[x, y],
{(x, sqrt(exp(x) * log(x ** 2))), (x, -sqrt(exp(x) * log(x ** 2)))})
assert solve(x**2*z**2 - z**2*y**2) == [{x: -y}, {x: y}, {z: 0}]
assert solve((x - 1)/(1 + 1/(x - 1))) == []
assert solve(x**(y*z) - x, x) == [1]
raises(NotImplementedError, lambda: solve(log(x) - exp(x), x))
raises(NotImplementedError, lambda: solve(2**x - exp(x) - 3))
def test_PR1964():
# issue 5171
assert solve(sqrt(x)) == solve(sqrt(x**3)) == [0]
assert solve(sqrt(x - 1)) == [1]
# issue 4462
a = Symbol('a')
assert solve(-3*a/sqrt(x), x) == []
# issue 4486
assert solve(2*x/(x + 2) - 1, x) == [2]
# issue 4496
assert set(solve((x**2/(7 - x)).diff(x))) == {S.Zero, S(14)}
# issue 4695
f = Function('f')
assert solve((3 - 5*x/f(x))*f(x), f(x)) == [x*Rational(5, 3)]
# issue 4497
assert solve(1/root(5 + x, 5) - 9, x) == [Rational(-295244, 59049)]
assert solve(sqrt(x) + sqrt(sqrt(x)) - 4) == [(Rational(-1, 2) + sqrt(17)/2)**4]
assert set(solve(Poly(sqrt(exp(x)) + sqrt(exp(-x)) - 4))) in \
[
{log((-sqrt(3) + 2)**2), log((sqrt(3) + 2)**2)},
{2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)},
{log(-4*sqrt(3) + 7), log(4*sqrt(3) + 7)},
]
assert set(solve(Poly(exp(x) + exp(-x) - 4))) == \
{log(-sqrt(3) + 2), log(sqrt(3) + 2)}
assert set(solve(x**y + x**(2*y) - 1, x)) == \
{(Rational(-1, 2) + sqrt(5)/2)**(1/y), (Rational(-1, 2) - sqrt(5)/2)**(1/y)}
assert solve(exp(x/y)*exp(-z/y) - 2, y) == [(x - z)/log(2)]
assert solve(
x**z*y**z - 2, z) in [[log(2)/(log(x) + log(y))], [log(2)/(log(x*y))]]
# if you do inversion too soon then multiple roots (as for the following)
# will be missed, e.g. if exp(3*x) = exp(3) -> 3*x = 3
E = S.Exp1
assert solve(exp(3*x) - exp(3), x) in [
[1, log(E*(Rational(-1, 2) - sqrt(3)*I/2)), log(E*(Rational(-1, 2) + sqrt(3)*I/2))],
[1, log(-E/2 - sqrt(3)*E*I/2), log(-E/2 + sqrt(3)*E*I/2)],
]
# coverage test
p = Symbol('p', positive=True)
assert solve((1/p + 1)**(p + 1)) == []
def test_issue_5197():
x = Symbol('x', real=True)
assert solve(x**2 + 1, x) == []
n = Symbol('n', integer=True, positive=True)
assert solve((n - 1)*(n + 2)*(2*n - 1), n) == [1]
x = Symbol('x', positive=True)
y = Symbol('y')
assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == []
# not {x: -3, y: 1} b/c x is positive
# The solution following should not contain (-sqrt(2), sqrt(2))
assert solve([(x + y), 2 - y**2], x, y) == [(sqrt(2), -sqrt(2))]
y = Symbol('y', positive=True)
# The solution following should not contain {y: -x*exp(x/2)}
assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: x*exp(x/2)}]
x, y, z = symbols('x y z', positive=True)
assert solve(z**2*x**2 - z**2*y**2/exp(x), y, x, z, dict=True) == [{y: x*exp(x/2)}]
def test_checking():
assert set(
solve(x*(x - y/x), x, check=False)) == {sqrt(y), S.Zero, -sqrt(y)}
assert set(solve(x*(x - y/x), x, check=True)) == {sqrt(y), -sqrt(y)}
# {x: 0, y: 4} sets denominator to 0 in the following so system should return None
assert solve((1/(1/x + 2), 1/(y - 3) - 1)) == []
# 0 sets denominator of 1/x to zero so None is returned
assert solve(1/(1/x + 2)) == []
def test_issue_4671_4463_4467():
assert solve(sqrt(x**2 - 1) - 2) in ([sqrt(5), -sqrt(5)],
[-sqrt(5), sqrt(5)])
assert solve((2**exp(y**2/x) + 2)/(x**2 + 15), y) == [
-sqrt(x*log(1 + I*pi/log(2))), sqrt(x*log(1 + I*pi/log(2)))]
C1, C2 = symbols('C1 C2')
f = Function('f')
assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))]
a = Symbol('a')
E = S.Exp1
assert solve(1 - log(a + 4*x**2), x) in (
[-sqrt(-a + E)/2, sqrt(-a + E)/2],
[sqrt(-a + E)/2, -sqrt(-a + E)/2]
)
assert solve(log(a**(-3) - x**2)/a, x) in (
[-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))],
[sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],)
assert solve(1 - log(a + 4*x**2), x) in (
[-sqrt(-a + E)/2, sqrt(-a + E)/2],
[sqrt(-a + E)/2, -sqrt(-a + E)/2],)
assert solve((a**2 + 1)*(sin(a*x) + cos(a*x)), x) == [-pi/(4*a)]
assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [log(3)/a]
assert set(solve(3 - (sinh(a*x) + cosh(a*x)**2), x)) == \
{log(-2 + sqrt(5))/a, log(-sqrt(2) + 1)/a,
log(-sqrt(5) - 2)/a, log(1 + sqrt(2))/a}
assert solve(atan(x) - 1) == [tan(1)]
def test_issue_5132():
r, t = symbols('r,t')
assert set(solve([r - x**2 - y**2, tan(t) - y/x], [x, y])) == \
{(
-sqrt(r*cos(t)**2), -1*sqrt(r*cos(t)**2)*tan(t)),
(sqrt(r*cos(t)**2), sqrt(r*cos(t)**2)*tan(t))}
assert solve([exp(x) - sin(y), 1/y - 3], [x, y]) == \
[(log(sin(Rational(1, 3))), Rational(1, 3))]
assert solve([exp(x) - sin(y), 1/exp(y) - 3], [x, y]) == \
[(log(-sin(log(3))), -log(3))]
assert set(solve([exp(x) - sin(y), y**2 - 4], [x, y])) == \
{(log(-sin(2)), -S(2)), (log(sin(2)), S(2))}
eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3]
assert solve(eqs, set=True) == \
([y, z], {
(-log(3), sqrt(-exp(2*x) - sin(log(3)))),
(-log(3), -sqrt(-exp(2*x) - sin(log(3))))})
assert solve(eqs, x, z, set=True) == (
[x, z],
{(x, sqrt(-exp(2*x) + sin(y))), (x, -sqrt(-exp(2*x) + sin(y)))})
assert set(solve(eqs, x, y)) == \
{
(log(-sqrt(-z**2 - sin(log(3)))), -log(3)),
(log(-z**2 - sin(log(3)))/2, -log(3))}
assert set(solve(eqs, y, z)) == \
{
(-log(3), -sqrt(-exp(2*x) - sin(log(3)))),
(-log(3), sqrt(-exp(2*x) - sin(log(3))))}
eqs = [exp(x)**2 - sin(y) + z, 1/exp(y) - 3]
assert solve(eqs, set=True) == ([y, z], {
(-log(3), -exp(2*x) - sin(log(3)))})
assert solve(eqs, x, z, set=True) == (
[x, z], {(x, -exp(2*x) + sin(y))})
assert set(solve(eqs, x, y)) == {
(log(-sqrt(-z - sin(log(3)))), -log(3)),
(log(-z - sin(log(3)))/2, -log(3))}
assert solve(eqs, z, y) == \
[(-exp(2*x) - sin(log(3)), -log(3))]
assert solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), set=True) == (
[x, y], {(S.One, S(3)), (S(3), S.One)})
assert set(solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), x, y)) == \
{(S.One, S(3)), (S(3), S.One)}
def test_issue_5335():
lam, a0, conc = symbols('lam a0 conc')
a = 0.005
b = 0.743436700916726
eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x,
a0*(1 - x/2)*x - 1*y - b*y,
x + y - conc]
sym = [x, y, a0]
# there are 4 solutions obtained manually but only two are valid
assert len(solve(eqs, sym, manual=True, minimal=True)) == 2
assert len(solve(eqs, sym)) == 2 # cf below with rational=False
@SKIP("Hangs")
def _test_issue_5335_float():
# gives ZeroDivisionError: polynomial division
lam, a0, conc = symbols('lam a0 conc')
a = 0.005
b = 0.743436700916726
eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x,
a0*(1 - x/2)*x - 1*y - b*y,
x + y - conc]
sym = [x, y, a0]
assert len(solve(eqs, sym, rational=False)) == 2
def test_issue_5767():
assert set(solve([x**2 + y + 4], [x])) == \
{(-sqrt(-y - 4),), (sqrt(-y - 4),)}
def test_polysys():
assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \
{(S.One, S(2)), (1 + sqrt(5), 2 - sqrt(5)),
(1 - sqrt(5), 2 + sqrt(5))}
assert solve([x**2 + y - 2, x**2 + y]) == []
# the ordering should be whatever the user requested
assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 +
y - 3, x - y - 4], (y, x))
@slow
def test_unrad1():
raises(NotImplementedError, lambda:
unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
raises(NotImplementedError, lambda:
unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y)))
s = symbols('s', cls=Dummy)
# checkers to deal with possibility of answer coming
# back with a sign change (cf issue 5203)
def check(rv, ans):
assert bool(rv[1]) == bool(ans[1])
if ans[1]:
return s_check(rv, ans)
e = rv[0].expand()
a = ans[0].expand()
return e in [a, -a] and rv[1] == ans[1]
def s_check(rv, ans):
# get the dummy
rv = list(rv)
d = rv[0].atoms(Dummy)
reps = list(zip(d, [s]*len(d)))
# replace s with this dummy
rv = (rv[0].subs(reps).expand(), [rv[1][0].subs(reps), rv[1][1].subs(reps)])
ans = (ans[0].subs(reps).expand(), [ans[1][0].subs(reps), ans[1][1].subs(reps)])
return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
str(rv[1]) == str(ans[1])
assert unrad(1) is None
assert check(unrad(sqrt(x)),
(x, []))
assert check(unrad(sqrt(x) + 1),
(x - 1, []))
assert check(unrad(sqrt(x) + root(x, 3) + 2),
(s**3 + s**2 + 2, [s, s**6 - x]))
assert check(unrad(sqrt(x)*root(x, 3) + 2),
(x**5 - 64, []))
assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)),
(x**3 - (x + 1)**2, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)),
(-2*sqrt(2)*x - 2*x + 1, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + 2),
(16*x - 9, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
(5*x**2 - 4*x, []))
assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)),
((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, []))
assert check(unrad(sqrt(x) + sqrt(1 - x)),
(2*x - 1, []))
assert check(unrad(sqrt(x) + sqrt(1 - x) - 3),
(x**2 - x + 16, []))
assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
(5*x**2 - 2*x + 1, []))
assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [
(25*x**4 + 376*x**3 + 1256*x**2 - 2272*x + 784, []),
(25*x**8 - 476*x**6 + 2534*x**4 - 1468*x**2 + 169, [])]
assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \
(41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, []) # orig root at 0.487
assert check(unrad(sqrt(x) + sqrt(x + 1)), (S.One, []))
eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
assert check(unrad(eq),
(16*x**2 - 9*x, []))
assert set(solve(eq, check=False)) == {S.Zero, Rational(9, 16)}
assert solve(eq) == []
# but this one really does have those solutions
assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \
{S.Zero, Rational(9, 16)}
assert check(unrad(sqrt(x) + root(x + 1, 3) + 2*sqrt(y), y),
(S('2*sqrt(x)*(x + 1)**(1/3) + x - 4*y + (x + 1)**(2/3)'), []))
assert check(unrad(sqrt(x/(1 - x)) + (x + 1)**Rational(1, 3)),
(x**5 - x**4 - x**3 + 2*x**2 + x - 1, []))
assert check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y),
(4*x*y + x - 4*y, []))
assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x),
(x**2 - x + 4, []))
# http://tutorial.math.lamar.edu/
# Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
assert solve(Eq(x, sqrt(x + 6))) == [3]
assert solve(Eq(x + sqrt(x - 4), 4)) == [4]
assert solve(Eq(1, x + sqrt(2*x - 3))) == []
assert set(solve(Eq(sqrt(5*x + 6) - 2, x))) == {-S.One, S(2)}
assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == {S(5), S(13)}
assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6]
# http://www.purplemath.com/modules/solverad.htm
assert solve((2*x - 5)**Rational(1, 3) - 3) == [16]
assert set(solve(x + 1 - root(x**4 + 4*x**3 - x, 4))) == \
{Rational(-1, 2), Rational(-1, 3)}
assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == {-S(8), S(2)}
assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0]
assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [5]
assert solve(sqrt(x)*sqrt(x - 7) - 12) == [16]
assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4]
assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [0]
assert solve(sqrt(x) - 2 - 5) == [49]
assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
assert solve(sqrt(x - 1) - x + 7) == [10]
assert solve(sqrt(x - 2) - 5) == [27]
assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [3]
assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []
# don't posify the expression in unrad and do use _mexpand
z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x)
p = posify(z)[0]
assert solve(p) == []
assert solve(z) == []
assert solve(z + 6*I) == [Rational(-1, 11)]
assert solve(p + 6*I) == []
# issue 8622
assert unrad(root(x + 1, 5) - root(x, 3)) == (
-(x**5 - x**3 - 3*x**2 - 3*x - 1), [])
# issue #8679
assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x),
(s**3 + s**2 + s + sqrt(y), [s, s**3 - x]))
# for coverage
assert check(unrad(sqrt(x) + root(x, 3) + y),
(s**3 + s**2 + y, [s, s**6 - x]))
assert solve(sqrt(x) + root(x, 3) - 2) == [1]
raises(NotImplementedError, lambda:
solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2))
# fails through a different code path
raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x)/x))
# unrad some
assert solve(sqrt(x + root(x, 3))+root(x - y, 5), y) == [
x + (x**Rational(1, 3) + x)**Rational(5, 2)]
assert check(unrad(sqrt(x) - root(x + 1, 3)*sqrt(x + 2) + 2),
(s**10 + 8*s**8 + 24*s**6 - 12*s**5 - 22*s**4 - 160*s**3 - 212*s**2 -
192*s - 56, [s, s**2 - x]))
e = root(x + 1, 3) + root(x, 3)
assert unrad(e) == (2*x + 1, [])
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
assert check(unrad(eq),
(15625*x**4 + 173000*x**3 + 355600*x**2 - 817920*x + 331776, []))
assert check(unrad(root(x, 4) + root(x, 4)**3 - 1),
(s**3 + s - 1, [s, s**4 - x]))
assert check(unrad(root(x, 2) + root(x, 2)**3 - 1),
(x**3 + 2*x**2 + x - 1, []))
assert unrad(x**0.5) is None
assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3),
(s**3 + s + t, [s, s**5 - x - y]))
assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y),
(s**3 + s + x, [s, s**5 - x - y]))
assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x),
(s**5 + s**3 + s - y, [s, s**5 - x - y]))
assert check(unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)),
(s**5 + 5*2**Rational(1, 5)*s**4 + s**3 + 10*2**Rational(2, 5)*s**3 +
10*2**Rational(3, 5)*s**2 + 5*2**Rational(4, 5)*s + 4, [s, s**3 - x + 1]))
raises(NotImplementedError, lambda:
unrad((root(x, 2) + root(x, 3) + root(x, 4)).subs(x, x**5 - x + 1)))
# the simplify flag should be reset to False for unrad results;
# if it's not then this next test will take a long time
assert solve(root(x, 3) + root(x, 5) - 2) == [1]
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
assert check(unrad(eq),
((5*x - 4)*(3125*x**3 + 37100*x**2 + 100800*x - 82944), []))
ans = S('''
[4/5, -1484/375 + 172564/(140625*(114*sqrt(12657)/78125 +
12459439/52734375)**(1/3)) +
4*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)]''')
assert solve(eq) == ans
# duplicate radical handling
assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2),
(s**3 - s**2 - 3*s - 5, [s, s**3 - x - 1]))
# cov post-processing
e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2
assert check(unrad(e),
(s**5 - 10*s**4 + 39*s**3 - 80*s**2 + 80*s - 30,
[s, s**3 - x**2 - 1]))
e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2
assert check(unrad(e),
(s**6 - 2*s**5 - 7*s**4 - 3*s**3 + 26*s**2 + 40*s + 25,
[s, s**3 - x - 1]))
assert check(unrad(e, _reverse=True),
(s**6 - 14*s**5 + 73*s**4 - 187*s**3 + 276*s**2 - 228*s + 89,
[s, s**2 - x - sqrt(x + 1)]))
# this one needs r0, r1 reversal to work
assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2),
(s**12 - 2*s**8 - 8*s**7 - 8*s**6 + s**4 + 8*s**3 + 23*s**2 +
32*s + 17, [s, s**6 - x]))
# why does this pass
assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == (
-(x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5
- cosh(x)**5), [])
# and this fail?
#assert unrad(sqrt(cosh(x)/x) + root(x + 1, 3)*sqrt(x) - 1) == (
# -s**6 + 6*s**5 - 15*s**4 + 20*s**3 - 15*s**2 + 6*s + x**5 +
# 2*x**4 + x**3 - 1, [s, s**2 - cosh(x)/x])
# watch for symbols in exponents
assert unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1')) is None
assert check(unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1'), x),
(s**(2*y) + s + 1, [s, s**3 - x - y]))
# should _Q be so lenient?
assert unrad(x**(S.Half/y) + y, x) == (x**(1/y) - y**2, [])
# This tests two things: that if full unrad is attempted and fails
# the solution should still be found; also it tests that the use of
# composite
assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3
assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 -
1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3
# watch out for when the cov doesn't involve the symbol of interest
eq = S('-x + (7*y/8 - (27*x/2 + 27*sqrt(x**2)/2)**(1/3)/3)**3 - 1')
assert solve(eq, y) == [
2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 +
S(512)/343)**(S(1)/3)*(-S(1)/2 - sqrt(3)*I/2), 2**(S(2)/3)*(27*x +
27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 +
S(512)/343)**(S(1)/3)*(-S(1)/2 + sqrt(3)*I/2), 2**(S(2)/3)*(27*x +
27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)]
eq = root(x + 1, 3) - (root(x, 3) + root(x, 5))
assert check(unrad(eq),
(3*s**13 + 3*s**11 + s**9 - 1, [s, s**15 - x]))
assert check(unrad(eq - 2),
(3*s**13 + 3*s**11 + 6*s**10 + s**9 + 12*s**8 + 6*s**6 + 12*s**5 +
12*s**3 + 7, [s, s**15 - x]))
assert check(unrad(root(x, 3) - root(x + 1, 4)/2 + root(x + 2, 3)),
(s*(4096*s**9 + 960*s**8 + 48*s**7 - s**6 - 1728),
[s, s**4 - x - 1])) # orig expr has two real roots: -1, -.389
assert check(unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3)/2),
(343*s**13 + 2904*s**12 + 1344*s**11 + 512*s**10 - 1323*s**9 -
3024*s**8 - 1728*s**7 + 1701*s**5 + 216*s**4 - 729*s, [s, s**4 - x -
1])) # orig expr has one real root: -0.048
assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3)),
(729*s**13 - 216*s**12 + 1728*s**11 - 512*s**10 + 1701*s**9 -
3024*s**8 + 1344*s**7 + 1323*s**5 - 2904*s**4 + 343*s, [s, s**4 - x -
1])) # orig expr has 2 real roots: -0.91, -0.15
assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3) - 2),
(729*s**13 + 1242*s**12 + 18496*s**10 + 129701*s**9 + 388602*s**8 +
453312*s**7 - 612864*s**6 - 3337173*s**5 - 6332418*s**4 - 7134912*s**3
- 5064768*s**2 - 2111913*s - 398034, [s, s**4 - x - 1]))
# orig expr has 1 real root: 19.53
ans = solve(sqrt(x) + sqrt(x + 1) -
sqrt(1 - x) - sqrt(2 + x))
assert len(ans) == 1 and NS(ans[0])[:4] == '0.73'
# the fence optimization problem
# https://github.com/sympy/sympy/issues/4793#issuecomment-36994519
F = Symbol('F')
eq = F - (2*x + 2*y + sqrt(x**2 + y**2))
ans = F*Rational(2, 7) - sqrt(2)*F/14
X = solve(eq, x, check=False)
for xi in reversed(X): # reverse since currently, ans is the 2nd one
Y = solve((x*y).subs(x, xi).diff(y), y, simplify=False, check=False)
if any((a - ans).expand().is_zero for a in Y):
break
else:
assert None # no answer was found
assert solve(sqrt(x + 1) + root(x, 3) - 2) == S('''
[(-11/(9*(47/54 + sqrt(93)/6)**(1/3)) + 1/3 + (47/54 +
sqrt(93)/6)**(1/3))**3]''')
assert solve(sqrt(sqrt(x + 1)) + x**Rational(1, 3) - 2) == S('''
[(-sqrt(-2*(-1/16 + sqrt(6913)/16)**(1/3) + 6/(-1/16 +
sqrt(6913)/16)**(1/3) + 17/2 + 121/(4*sqrt(-6/(-1/16 +
sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)))/2 +
sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 +
sqrt(6913)/16)**(1/3) + 17/4)/2 + 9/4)**3]''')
assert solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) == S('''
[(-(81/2 + 3*sqrt(741)/2)**(1/3)/3 + (81/2 + 3*sqrt(741)/2)**(-1/3) +
2)**2]''')
eq = S('''
-x + (1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3
+ x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3) + 34/(3*(1/2 -
sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2
- 34) + 90)**2/4 - 39304/27) - 45)**(1/3))''')
assert check(unrad(eq),
(s*-(-s**6 + sqrt(3)*s**6*I - 153*2**Rational(2, 3)*3**Rational(1, 3)*s**4 +
51*12**Rational(1, 3)*s**4 - 102*2**Rational(2, 3)*3**Rational(5, 6)*s**4*I - 1620*s**3 +
1620*sqrt(3)*s**3*I + 13872*18**Rational(1, 3)*s**2 - 471648 +
471648*sqrt(3)*I), [s, s**3 - 306*x - sqrt(3)*sqrt(31212*x**2 -
165240*x + 61484) + 810]))
assert solve(eq) == [] # not other code errors
eq = root(x, 3) - root(y, 3) + root(x, 5)
assert check(unrad(eq),
(s**15 + 3*s**13 + 3*s**11 + s**9 - y, [s, s**15 - x]))
eq = root(x, 3) + root(y, 3) + root(x*y, 4)
assert check(unrad(eq),
(s*y*(-s**12 - 3*s**11*y - 3*s**10*y**2 - s**9*y**3 -
3*s**8*y**2 + 21*s**7*y**3 - 3*s**6*y**4 - 3*s**4*y**4 -
3*s**3*y**5 - y**6), [s, s**4 - x*y]))
raises(NotImplementedError,
lambda: unrad(root(x, 3) + root(y, 3) + root(x*y, 5)))
# Test unrad with an Equality
eq = Eq(-x**(S(1)/5) + x**(S(1)/3), -3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5))
assert check(unrad(eq),
(-s**5 + s**3 - 3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5), [s, s**15 - x]))
# make sure buried radicals are exposed
s = sqrt(x) - 1
assert unrad(s**2 - s**3) == (x**3 - 6*x**2 + 9*x - 4, [])
# make sure numerators which are already polynomial are rejected
assert unrad((x/(x + 1) + 3)**(-2), x) is None
# https://github.com/sympy/sympy/issues/23707
eq = sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y))
assert solve(eq, y) == [x - 1]
assert unrad(eq) is None
@slow
def test_unrad_slow():
# this has roots with multiplicity > 1; there should be no
# repeats in roots obtained, however
eq = (sqrt(1 + sqrt(1 - 4*x**2)) - x*(1 + sqrt(1 + 2*sqrt(1 - 4*x**2))))
assert solve(eq) == [S.Half]
@XFAIL
def test_unrad_fail():
# this only works if we check real_root(eq.subs(x, Rational(1, 3)))
# but checksol doesn't work like that
assert solve(root(x**3 - 3*x**2, 3) + 1 - x) == [Rational(1, 3)]
assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == [
-1, -1 + CRootOf(x**5 + x**4 + 5*x**3 + 8*x**2 + 10*x + 5, 0)**3]
def test_checksol():
x, y, r, t = symbols('x, y, r, t')
eq = r - x**2 - y**2
dict_var_soln = {y: - sqrt(r) / sqrt(tan(t)**2 + 1),
x: -sqrt(r)*tan(t)/sqrt(tan(t)**2 + 1)}
assert checksol(eq, dict_var_soln) == True
assert checksol(Eq(x, False), {x: False}) is True
assert checksol(Ne(x, False), {x: False}) is False
assert checksol(Eq(x < 1, True), {x: 0}) is True
assert checksol(Eq(x < 1, True), {x: 1}) is False
assert checksol(Eq(x < 1, False), {x: 1}) is True
assert checksol(Eq(x < 1, False), {x: 0}) is False
assert checksol(Eq(x + 1, x**2 + 1), {x: 1}) is True
assert checksol([x - 1, x**2 - 1], x, 1) is True
assert checksol([x - 1, x**2 - 2], x, 1) is False
assert checksol(Poly(x**2 - 1), x, 1) is True
assert checksol(0, {}) is True
assert checksol([1e-10, x - 2], x, 2) is False
assert checksol([0.5, 0, x], x, 0) is False
assert checksol(y, x, 2) is False
assert checksol(x+1e-10, x, 0, numerical=True) is True
assert checksol(x+1e-10, x, 0, numerical=False) is False
raises(ValueError, lambda: checksol(x, 1))
raises(ValueError, lambda: checksol([], x, 1))
def test__invert():
assert _invert(x - 2) == (2, x)
assert _invert(2) == (2, 0)
assert _invert(exp(1/x) - 3, x) == (1/log(3), x)
assert _invert(exp(1/x + a/x) - 3, x) == ((a + 1)/log(3), x)
assert _invert(a, x) == (a, 0)
def test_issue_4463():
assert solve(-a*x + 2*x*log(x), x) == [exp(a/2)]
assert solve(x**x) == []
assert solve(x**x - 2) == [exp(LambertW(log(2)))]
assert solve(((x - 3)*(x - 2))**((x - 3)*(x - 4))) == [2]
@slow
def test_issue_5114_solvers():
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('a:r')
# there is no 'a' in the equation set but this is how the
# problem was originally posed
syms = a, b, c, f, h, k, n
eqs = [b + r/d - c/d,
c*(1/d + 1/e + 1/g) - f/g - r/d,
f*(1/g + 1/i + 1/j) - c/g - h/i,
h*(1/i + 1/l + 1/m) - f/i - k/m,
k*(1/m + 1/o + 1/p) - h/m - n/p,
n*(1/p + 1/q) - k/p]
assert len(solve(eqs, syms, manual=True, check=False, simplify=False)) == 1
def test_issue_5849():
#
# XXX: This system does not have a solution for most values of the
# parameters. Generally solve returns the empty set for systems that are
# generically inconsistent.
#
I1, I2, I3, I4, I5, I6 = symbols('I1:7')
dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4')
e = (
I1 - I2 - I3,
I3 - I4 - I5,
I4 + I5 - I6,
-I1 + I2 + I6,
-2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12,
-I4 + dQ4,
-I2 + dQ2,
2*I3 + 2*I5 + 3*I6 - Q2,
I4 - 2*I5 + 2*Q4 + dI4
)
ans = [{
I1: I2 + I3,
dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24,
I4: I3 - I5,
dQ4: I3 - I5,
Q4: -I3/2 + 3*I5/2 - dI4/2,
dQ2: I2,
Q2: 2*I3 + 2*I5 + 3*I6}]
v = I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4
assert solve(e, *v, manual=True, check=False, dict=True) == ans
assert solve(e, *v, manual=True, check=False) == [
tuple([a.get(i, i) for i in v]) for a in ans]
assert solve(e, *v, manual=True) == []
assert solve(e, *v) == []
# the matrix solver (tested below) doesn't like this because it produces
# a zero row in the matrix. Is this related to issue 4551?
assert [ei.subs(
ans[0]) for ei in e] == [0, 0, I3 - I6, -I3 + I6, 0, 0, 0, 0, 0]
def test_issue_5849_matrix():
'''Same as test_issue_5849 but solved with the matrix solver.
A solution only exists if I3 == I6 which is not generically true,
but `solve` does not return conditions under which the solution is
valid, only a solution that is canonical and consistent with the input.
'''
# a simple example with the same issue
# assert solve([x+y+z, x+y], [x, y]) == {x: y}
# the longer example
I1, I2, I3, I4, I5, I6 = symbols('I1:7')
dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4')
e = (
I1 - I2 - I3,
I3 - I4 - I5,
I4 + I5 - I6,
-I1 + I2 + I6,
-2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12,
-I4 + dQ4,
-I2 + dQ2,
2*I3 + 2*I5 + 3*I6 - Q2,
I4 - 2*I5 + 2*Q4 + dI4
)
assert solve(e, I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4) == []
def test_issue_21882():
a, b, c, d, f, g, k = unknowns = symbols('a, b, c, d, f, g, k')
equations = [
-k*a + b + 5*f/6 + 2*c/9 + 5*d/6 + 4*a/3,
-k*f + 4*f/3 + d/2,
-k*d + f/6 + d,
13*b/18 + 13*c/18 + 13*a/18,
-k*c + b/2 + 20*c/9 + a,
-k*b + b + c/18 + a/6,
5*b/3 + c/3 + a,
2*b/3 + 2*c + 4*a/3,
-g,
]
answer = [
{a: 0, f: 0, b: 0, d: 0, c: 0, g: 0},
{a: 0, f: -d, b: 0, k: S(5)/6, c: 0, g: 0},
{a: -2*c, f: 0, b: c, d: 0, k: S(13)/18, g: 0}]
# but not {a: 0, f: 0, b: 0, k: S(3)/2, c: 0, d: 0, g: 0}
# since this is already covered by the first solution
got = solve(equations, unknowns, dict=True)
assert got == answer, (got,answer)
def test_issue_5901():
f, g, h = map(Function, 'fgh')
a = Symbol('a')
D = Derivative(f(x), x)
G = Derivative(g(a), a)
assert solve(f(x) + f(x).diff(x), f(x)) == \
[-D]
assert solve(f(x) - 3, f(x)) == \
[3]
assert solve(f(x) - 3*f(x).diff(x), f(x)) == \
[3*D]
assert solve([f(x) - 3*f(x).diff(x)], f(x)) == \
{f(x): 3*D}
assert solve([f(x) - 3*f(x).diff(x), f(x)**2 - y + 4], f(x), y) == \
[(3*D, 9*D**2 + 4)]
assert solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a),
h(a), g(a), set=True) == \
([h(a), g(a)], {
(-sqrt(f(a)**2*g(a)**2 - G)/f(a), g(a)),
(sqrt(f(a)**2*g(a)**2 - G)/f(a), g(a))}), solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a),
h(a), g(a), set=True)
args = [[f(x).diff(x, 2)*(f(x) + g(x)), 2 - g(x)**2], f(x), g(x)]
assert solve(*args, set=True)[1] == \
{(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))}
eqs = [f(x)**2 + g(x) - 2*f(x).diff(x), g(x)**2 - 4]
assert solve(eqs, f(x), g(x), set=True) == \
([f(x), g(x)], {
(-sqrt(2*D - 2), S(2)),
(sqrt(2*D - 2), S(2)),
(-sqrt(2*D + 2), -S(2)),
(sqrt(2*D + 2), -S(2))})
# the underlying problem was in solve_linear that was not masking off
# anything but a Mul or Add; it now raises an error if it gets anything
# but a symbol and solve handles the substitutions necessary so solve_linear
# won't make this error
raises(
ValueError, lambda: solve_linear(f(x) + f(x).diff(x), symbols=[f(x)]))
assert solve_linear(f(x) + f(x).diff(x), symbols=[x]) == \
(f(x) + Derivative(f(x), x), 1)
assert solve_linear(f(x) + Integral(x, (x, y)), symbols=[x]) == \
(f(x) + Integral(x, (x, y)), 1)
assert solve_linear(f(x) + Integral(x, (x, y)) + x, symbols=[x]) == \
(x + f(x) + Integral(x, (x, y)), 1)
assert solve_linear(f(y) + Integral(x, (x, y)) + x, symbols=[x]) == \
(x, -f(y) - Integral(x, (x, y)))
assert solve_linear(x - f(x)/a + (f(x) - 1)/a, symbols=[x]) == \
(x, 1/a)
assert solve_linear(x + Derivative(2*x, x)) == \
(x, -2)
assert solve_linear(x + Integral(x, y), symbols=[x]) == \
(x, 0)
assert solve_linear(x + Integral(x, y) - 2, symbols=[x]) == \
(x, 2/(y + 1))
assert set(solve(x + exp(x)**2, exp(x))) == \
{-sqrt(-x), sqrt(-x)}
assert solve(x + exp(x), x, implicit=True) == \
[-exp(x)]
assert solve(cos(x) - sin(x), x, implicit=True) == []
assert solve(x - sin(x), x, implicit=True) == \
[sin(x)]
assert solve(x**2 + x - 3, x, implicit=True) == \
[-x**2 + 3]
assert solve(x**2 + x - 3, x**2, implicit=True) == \
[-x + 3]
def test_issue_5912():
assert set(solve(x**2 - x - 0.1, rational=True)) == \
{S.Half + sqrt(35)/10, -sqrt(35)/10 + S.Half}
ans = solve(x**2 - x - 0.1, rational=False)
assert len(ans) == 2 and all(a.is_Number for a in ans)
ans = solve(x**2 - x - 0.1)
assert len(ans) == 2 and all(a.is_Number for a in ans)
def test_float_handling():
def test(e1, e2):
return len(e1.atoms(Float)) == len(e2.atoms(Float))
assert solve(x - 0.5, rational=True)[0].is_Rational
assert solve(x - 0.5, rational=False)[0].is_Float
assert solve(x - S.Half, rational=False)[0].is_Rational
assert solve(x - 0.5, rational=None)[0].is_Float
assert solve(x - S.Half, rational=None)[0].is_Rational
assert test(nfloat(1 + 2*x), 1.0 + 2.0*x)
for contain in [list, tuple, set]:
ans = nfloat(contain([1 + 2*x]))
assert type(ans) is contain and test(list(ans)[0], 1.0 + 2.0*x)
k, v = list(nfloat({2*x: [1 + 2*x]}).items())[0]
assert test(k, 2*x) and test(v[0], 1.0 + 2.0*x)
assert test(nfloat(cos(2*x)), cos(2.0*x))
assert test(nfloat(3*x**2), 3.0*x**2)
assert test(nfloat(3*x**2, exponent=True), 3.0*x**2.0)
assert test(nfloat(exp(2*x)), exp(2.0*x))
assert test(nfloat(x/3), x/3.0)
assert test(nfloat(x**4 + 2*x + cos(Rational(1, 3)) + 1),
x**4 + 2.0*x + 1.94495694631474)
# don't call nfloat if there is no solution
tot = 100 + c + z + t
assert solve(((.7 + c)/tot - .6, (.2 + z)/tot - .3, t/tot - .1)) == []
def test_check_assumptions():
x = symbols('x', positive=True)
assert solve(x**2 - 1) == [1]
def test_issue_6056():
assert solve(tanh(x + 3)*tanh(x - 3) - 1) == []
assert solve(tanh(x - 1)*tanh(x + 1) + 1) == \
[I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)]
assert solve((tanh(x + 3)*tanh(x - 3) + 1)**2) == \
[I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)]
def test_issue_5673():
eq = -x + exp(exp(LambertW(log(x)))*LambertW(log(x)))
assert checksol(eq, x, 2) is True
assert checksol(eq, x, 2, numerical=False) is None
def test_exclude():
R, C, Ri, Vout, V1, Vminus, Vplus, s = \
symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s')
Rf = symbols('Rf', positive=True) # to eliminate Rf = 0 soln
eqs = [C*V1*s + Vplus*(-2*C*s - 1/R),
Vminus*(-1/Ri - 1/Rf) + Vout/Rf,
C*Vplus*s + V1*(-C*s - 1/R) + Vout/R,
-Vminus + Vplus]
assert solve(eqs, exclude=s*C*R) == [
{
Rf: Ri*(C*R*s + 1)**2/(C*R*s),
Vminus: Vplus,
V1: 2*Vplus + Vplus/(C*R*s),
Vout: C*R*Vplus*s + 3*Vplus + Vplus/(C*R*s)},
{
Vplus: 0,
Vminus: 0,
V1: 0,
Vout: 0},
]
# TODO: Investigate why currently solution [0] is preferred over [1].
assert solve(eqs, exclude=[Vplus, s, C]) in [[{
Vminus: Vplus,
V1: Vout/2 + Vplus/2 + sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2,
R: (Vout - 3*Vplus - sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s),
Rf: Ri*(Vout - Vplus)/Vplus,
}, {
Vminus: Vplus,
V1: Vout/2 + Vplus/2 - sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2,
R: (Vout - 3*Vplus + sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s),
Rf: Ri*(Vout - Vplus)/Vplus,
}], [{
Vminus: Vplus,
Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus),
Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)),
R: Vplus/(C*s*(V1 - 2*Vplus)),
}]]
def test_high_order_roots():
s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4)
assert set(solve(s)) == set(Poly(s*4, domain='ZZ').all_roots())
def test_minsolve_linear_system():
pqt = dict(quick=True, particular=True)
pqf = dict(quick=False, particular=True)
assert solve([x + y - 5, 2*x - y - 1], **pqt) == {x: 2, y: 3}
assert solve([x + y - 5, 2*x - y - 1], **pqf) == {x: 2, y: 3}
def count(dic):
return len([x for x in dic.values() if x == 0])
assert count(solve([x + y + z, y + z + a + t], **pqt)) == 3
assert count(solve([x + y + z, y + z + a + t], **pqf)) == 3
assert count(solve([x + y + z, y + z + a], **pqt)) == 1
assert count(solve([x + y + z, y + z + a], **pqf)) == 2
# issue 22718
A = Matrix([
[ 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0],
[ 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, -1, -1, 0, 0],
[-1, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 1, 0, 1],
[ 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, -1, 0, -1, 0],
[-1, 0, -1, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 1],
[-1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1],
[ 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, -1, -1, 0],
[ 0, -1, -1, 0, 0, 0, 0, -1, 0, 0, 0, 1, 1, 1],
[ 0, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, -1, 0, -1],
[ 0, 0, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, -1, -1],
[ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[ 0, 0, 0, 0, -1, -1, 0, -1, 0, 0, 0, 0, 0, 0]])
v = Matrix(symbols("v:14", integer=True))
B = Matrix([[2], [-2], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0]])
eqs = A@v-B
assert solve(eqs) == []
assert solve(eqs, particular=True) == [] # assumption violated
assert all(v for v in solve([x + y + z, y + z + a]).values())
for _q in (True, False):
assert not all(v for v in solve(
[x + y + z, y + z + a], quick=_q,
particular=True).values())
# raise error if quick used w/o particular=True
raises(ValueError, lambda: solve([x + 1], quick=_q))
raises(ValueError, lambda: solve([x + 1], quick=_q, particular=False))
# and give a good error message if someone tries to use
# particular with a single equation
raises(ValueError, lambda: solve(x + 1, particular=True))
def test_real_roots():
# cf. issue 6650
x = Symbol('x', real=True)
assert len(solve(x**5 + x**3 + 1)) == 1
def test_issue_6528():
eqs = [
327600995*x**2 - 37869137*x + 1809975124*y**2 - 9998905626,
895613949*x**2 - 273830224*x*y + 530506983*y**2 - 10000000000]
# two expressions encountered are > 1400 ops long so if this hangs
# it is likely because simplification is being done
assert len(solve(eqs, y, x, check=False)) == 4
def test_overdetermined():
x = symbols('x', real=True)
eqs = [Abs(4*x - 7) - 5, Abs(3 - 8*x) - 1]
assert solve(eqs, x) == [(S.Half,)]
assert solve(eqs, x, manual=True) == [(S.Half,)]
assert solve(eqs, x, manual=True, check=False) == [(S.Half,), (S(3),)]
def test_issue_6605():
x = symbols('x')
assert solve(4**(x/2) - 2**(x/3)) == [0, 3*I*pi/log(2)]
# while the first one passed, this one failed
x = symbols('x', real=True)
assert solve(5**(x/2) - 2**(x/3)) == [0]
b = sqrt(6)*sqrt(log(2))/sqrt(log(5))
assert solve(5**(x/2) - 2**(3/x)) == [-b, b]
def test__ispow():
assert _ispow(x**2)
assert not _ispow(x)
assert not _ispow(True)
def test_issue_6644():
eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2)
sol = solve(eq, q, simplify=False, check=False)
assert len(sol) == 5
def test_issue_6752():
assert solve([a**2 + a, a - b], [a, b]) == [(-1, -1), (0, 0)]
assert solve([a**2 + a*c, a - b], [a, b]) == [(0, 0), (-c, -c)]
def test_issue_6792():
assert solve(x*(x - 1)**2*(x + 1)*(x**6 - x + 1)) == [
-1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1),
CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3),
CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)]
def test_issues_6819_6820_6821_6248_8692():
# issue 6821
x, y = symbols('x y', real=True)
assert solve(abs(x + 3) - 2*abs(x - 3)) == [1, 9]
assert solve([abs(x) - 2, arg(x) - pi], x) == [(-2,)]
assert set(solve(abs(x - 7) - 8)) == {-S.One, S(15)}
# issue 8692
assert solve(Eq(Abs(x + 1) + Abs(x**2 - 7), 9), x) == [
Rational(-1, 2) + sqrt(61)/2, -sqrt(69)/2 + S.Half]
# issue 7145
assert solve(2*abs(x) - abs(x - 1)) == [-1, Rational(1, 3)]
x = symbols('x')
assert solve([re(x) - 1, im(x) - 2], x) == [
{re(x): 1, x: 1 + 2*I, im(x): 2}]
# check for 'dict' handling of solution
eq = sqrt(re(x)**2 + im(x)**2) - 3
assert solve(eq) == solve(eq, x)
i = symbols('i', imaginary=True)
assert solve(abs(i) - 3) == [-3*I, 3*I]
raises(NotImplementedError, lambda: solve(abs(x) - 3))
w = symbols('w', integer=True)
assert solve(2*x**w - 4*y**w, w) == solve((x/y)**w - 2, w)
x, y = symbols('x y', real=True)
assert solve(x + y*I + 3) == {y: 0, x: -3}
# issue 2642
assert solve(x*(1 + I)) == [0]
x, y = symbols('x y', imaginary=True)
assert solve(x + y*I + 3 + 2*I) == {x: -2*I, y: 3*I}
x = symbols('x', real=True)
assert solve(x + y + 3 + 2*I) == {x: -3, y: -2*I}
# issue 6248
f = Function('f')
assert solve(f(x + 1) - f(2*x - 1)) == [2]
assert solve(log(x + 1) - log(2*x - 1)) == [2]
x = symbols('x')
assert solve(2**x + 4**x) == [I*pi/log(2)]
def test_issue_14607():
# issue 14607
s, tau_c, tau_1, tau_2, phi, K = symbols(
's, tau_c, tau_1, tau_2, phi, K')
target = (s**2*tau_1*tau_2 + s*tau_1 + s*tau_2 + 1)/(K*s*(-phi + tau_c))
K_C, tau_I, tau_D = symbols('K_C, tau_I, tau_D',
positive=True, nonzero=True)
PID = K_C*(1 + 1/(tau_I*s) + tau_D*s)
eq = (target - PID).together()
eq *= denom(eq).simplify()
eq = Poly(eq, s)
c = eq.coeffs()
vars = [K_C, tau_I, tau_D]
s = solve(c, vars, dict=True)
assert len(s) == 1
knownsolution = {K_C: -(tau_1 + tau_2)/(K*(phi - tau_c)),
tau_I: tau_1 + tau_2,
tau_D: tau_1*tau_2/(tau_1 + tau_2)}
for var in vars:
assert s[0][var].simplify() == knownsolution[var].simplify()
def test_lambert_multivariate():
from sympy.abc import x, y
assert _filtered_gens(Poly(x + 1/x + exp(x) + y), x) == {x, exp(x)}
assert _lambert(x, x) == []
assert solve((x**2 - 2*x + 1).subs(x, log(x) + 3*x)) == [LambertW(3*S.Exp1)/3]
assert solve((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1)) == \
[LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3]
assert solve((x**2 - 2*x - 2).subs(x, log(x) + 3*x)) == \
[LambertW(3*exp(1 - sqrt(3)))/3, LambertW(3*exp(1 + sqrt(3)))/3]
eq = (x*exp(x) - 3).subs(x, x*exp(x))
assert solve(eq) == [LambertW(3*exp(-LambertW(3)))]
# coverage test
raises(NotImplementedError, lambda: solve(x - sin(x)*log(y - x), x))
ans = [3, -3*LambertW(-log(3)/3)/log(3)] # 3 and 2.478...
assert solve(x**3 - 3**x, x) == ans
assert set(solve(3*log(x) - x*log(3))) == set(ans)
assert solve(LambertW(2*x) - y, x) == [y*exp(y)/2]
@XFAIL
def test_other_lambert():
assert solve(3*sin(x) - x*sin(3), x) == [3]
assert set(solve(x**a - a**x), x) == {
a, -a*LambertW(-log(a)/a)/log(a)}
@slow
def test_lambert_bivariate():
# tests passing current implementation
assert solve((x**2 + x)*exp(x**2 + x) - 1) == [
Rational(-1, 2) + sqrt(1 + 4*LambertW(1))/2,
Rational(-1, 2) - sqrt(1 + 4*LambertW(1))/2]
assert solve((x**2 + x)*exp((x**2 + x)*2) - 1) == [
Rational(-1, 2) + sqrt(1 + 2*LambertW(2))/2,
Rational(-1, 2) - sqrt(1 + 2*LambertW(2))/2]
assert solve(a/x + exp(x/2), x) == [2*LambertW(-a/2)]
assert solve((a/x + exp(x/2)).diff(x), x) == \
[4*LambertW(-sqrt(2)*sqrt(a)/4), 4*LambertW(sqrt(2)*sqrt(a)/4)]
assert solve((1/x + exp(x/2)).diff(x), x) == \
[4*LambertW(-sqrt(2)/4),
4*LambertW(sqrt(2)/4), # nsimplifies as 2*2**(141/299)*3**(206/299)*5**(205/299)*7**(37/299)/21
4*LambertW(-sqrt(2)/4, -1)]
assert solve(x*log(x) + 3*x + 1, x) == \
[exp(-3 + LambertW(-exp(3)))]
assert solve(-x**2 + 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)]
assert solve(x**2 - 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)]
ans = solve(3*x + 5 + 2**(-5*x + 3), x)
assert len(ans) == 1 and ans[0].expand() == \
Rational(-5, 3) + LambertW(-10240*root(2, 3)*log(2)/3)/(5*log(2))
assert solve(5*x - 1 + 3*exp(2 - 7*x), x) == \
[Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7]
assert solve((log(x) + x).subs(x, x**2 + 1)) == [
-I*sqrt(-LambertW(1) + 1), sqrt(-1 + LambertW(1))]
# check collection
ax = a**(3*x + 5)
ans = solve(3*log(ax) + b*log(ax) + ax, x)
x0 = 1/log(a)
x1 = sqrt(3)*I
x2 = b + 3
x3 = x2*LambertW(1/x2)/a**5
x4 = x3**Rational(1, 3)/2
assert ans == [
x0*log(x4*(-x1 - 1)),
x0*log(x4*(x1 - 1)),
x0*log(x3)/3]
x1 = LambertW(Rational(1, 3))
x2 = a**(-5)
x3 = -3**Rational(1, 3)
x4 = 3**Rational(5, 6)*I
x5 = x1**Rational(1, 3)*x2**Rational(1, 3)/2
ans = solve(3*log(ax) + ax, x)
assert ans == [
x0*log(3*x1*x2)/3,
x0*log(x5*(x3 - x4)),
x0*log(x5*(x3 + x4))]
# coverage
p = symbols('p', positive=True)
eq = 4*2**(2*p + 3) - 2*p - 3
assert _solve_lambert(eq, p, _filtered_gens(Poly(eq), p)) == [
Rational(-3, 2) - LambertW(-4*log(2))/(2*log(2))]
assert set(solve(3**cos(x) - cos(x)**3)) == {
acos(3), acos(-3*LambertW(-log(3)/3)/log(3))}
# should give only one solution after using `uniq`
assert solve(2*log(x) - 2*log(z) + log(z + log(x) + log(z)), x) == [
exp(-z + LambertW(2*z**4*exp(2*z))/2)/z]
# cases when p != S.One
# issue 4271
ans = solve((a/x + exp(x/2)).diff(x, 2), x)
x0 = (-a)**Rational(1, 3)
x1 = sqrt(3)*I
x2 = x0/6
assert ans == [
6*LambertW(x0/3),
6*LambertW(x2*(-x1 - 1)),
6*LambertW(x2*(x1 - 1))]
assert solve((1/x + exp(x/2)).diff(x, 2), x) == \
[6*LambertW(Rational(-1, 3)), 6*LambertW(Rational(1, 6) - sqrt(3)*I/6), \
6*LambertW(Rational(1, 6) + sqrt(3)*I/6), 6*LambertW(Rational(-1, 3), -1)]
assert solve(x**2 - y**2/exp(x), x, y, dict=True) == \
[{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}]
# this is slow but not exceedingly slow
assert solve((x**3)**(x/2) + pi/2, x) == [
exp(LambertW(-2*log(2)/3 + 2*log(pi)/3 + I*pi*Rational(2, 3)))]
# issue 23253
assert solve((1/log(sqrt(x) + 2)**2 - 1/x)) == [
(LambertW(-exp(-2), -1) + 2)**2]
assert solve((1/log(1/sqrt(x) + 2)**2 - x)) == [
(LambertW(-exp(-2), -1) + 2)**-2]
assert solve((1/log(x**2 + 2)**2 - x**-4)) == [
-I*sqrt(2 - LambertW(exp(2))),
-I*sqrt(LambertW(-exp(-2)) + 2),
sqrt(-2 - LambertW(-exp(-2))),
sqrt(-2 + LambertW(exp(2))),
-sqrt(-2 - LambertW(-exp(-2), -1)),
sqrt(-2 - LambertW(-exp(-2), -1))]
def test_rewrite_trig():
assert solve(sin(x) + tan(x)) == [0, -pi, pi, 2*pi]
assert solve(sin(x) + sec(x)) == [
-2*atan(Rational(-1, 2) + sqrt(2)*sqrt(1 - sqrt(3)*I)/2 + sqrt(3)*I/2),
2*atan(S.Half - sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half
+ sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half -
sqrt(3)*I/2 + sqrt(2)*sqrt(1 - sqrt(3)*I)/2)]
assert solve(sinh(x) + tanh(x)) == [0, I*pi]
# issue 6157
assert solve(2*sin(x) - cos(x), x) == [atan(S.Half)]
@XFAIL
def test_rewrite_trigh():
# if this import passes then the test below should also pass
from sympy.functions.elementary.hyperbolic import sech
assert solve(sinh(x) + sech(x)) == [
2*atanh(Rational(-1, 2) + sqrt(5)/2 - sqrt(-2*sqrt(5) + 2)/2),
2*atanh(Rational(-1, 2) + sqrt(5)/2 + sqrt(-2*sqrt(5) + 2)/2),
2*atanh(-sqrt(5)/2 - S.Half + sqrt(2 + 2*sqrt(5))/2),
2*atanh(-sqrt(2 + 2*sqrt(5))/2 - sqrt(5)/2 - S.Half)]
def test_uselogcombine():
eq = z - log(x) + log(y/(x*(-1 + y**2/x**2)))
assert solve(eq, x, force=True) == [-sqrt(y*(y - exp(z))), sqrt(y*(y - exp(z)))]
assert solve(log(x + 3) + log(1 + 3/x) - 3) in [
[-3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2,
-sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2],
[-3 + sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2,
-3 - sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2],
]
assert solve(log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2)) == []
def test_atan2():
assert solve(atan2(x, 2) - pi/3, x) == [2*sqrt(3)]
def test_errorinverses():
assert solve(erf(x) - y, x) == [erfinv(y)]
assert solve(erfinv(x) - y, x) == [erf(y)]
assert solve(erfc(x) - y, x) == [erfcinv(y)]
assert solve(erfcinv(x) - y, x) == [erfc(y)]
def test_issue_2725():
R = Symbol('R')
eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1)
sol = solve(eq, R, set=True)[1]
assert sol == {(Rational(5, 3) + (Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3) + 40/(9*((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3))),), (Rational(5, 3) + 40/(9*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3)) + (Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3),)}
def test_issue_5114_6611():
# See that it doesn't hang; this solves in about 2 seconds.
# Also check that the solution is relatively small.
# Note: the system in issue 6611 solves in about 5 seconds and has
# an op-count of 138336 (with simplify=False).
b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('b:r')
eqs = Matrix([
[b - c/d + r/d], [c*(1/g + 1/e + 1/d) - f/g - r/d],
[-c/g + f*(1/j + 1/i + 1/g) - h/i], [-f/i + h*(1/m + 1/l + 1/i) - k/m],
[-h/m + k*(1/p + 1/o + 1/m) - n/p], [-k/p + n*(1/q + 1/p)]])
v = Matrix([f, h, k, n, b, c])
ans = solve(list(eqs), list(v), simplify=False)
# If time is taken to simplify then then 2617 below becomes
# 1168 and the time is about 50 seconds instead of 2.
assert sum([s.count_ops() for s in ans.values()]) <= 3270
def test_det_quick():
m = Matrix(3, 3, symbols('a:9'))
assert m.det() == det_quick(m) # calls det_perm
m[0, 0] = 1
assert m.det() == det_quick(m) # calls det_minor
m = Matrix(3, 3, list(range(9)))
assert m.det() == det_quick(m) # defaults to .det()
# make sure they work with Sparse
s = SparseMatrix(2, 2, (1, 2, 1, 4))
assert det_perm(s) == det_minor(s) == s.det()
def test_real_imag_splitting():
a, b = symbols('a b', real=True)
assert solve(sqrt(a**2 + b**2) - 3, a) == \
[-sqrt(-b**2 + 9), sqrt(-b**2 + 9)]
a, b = symbols('a b', imaginary=True)
assert solve(sqrt(a**2 + b**2) - 3, a) == []
def test_issue_7110():
y = -2*x**3 + 4*x**2 - 2*x + 5
assert any(ask(Q.real(i)) for i in solve(y))
def test_units():
assert solve(1/x - 1/(2*cm)) == [2*cm]
def test_issue_7547():
A, B, V = symbols('A,B,V')
eq1 = Eq(630.26*(V - 39.0)*V*(V + 39) - A + B, 0)
eq2 = Eq(B, 1.36*10**8*(V - 39))
eq3 = Eq(A, 5.75*10**5*V*(V + 39.0))
sol = Matrix(nsolve(Tuple(eq1, eq2, eq3), [A, B, V], (0, 0, 0)))
assert str(sol) == str(Matrix(
[['4442890172.68209'],
['4289299466.1432'],
['70.5389666628177']]))
def test_issue_7895():
r = symbols('r', real=True)
assert solve(sqrt(r) - 2) == [4]
def test_issue_2777():
# the equations represent two circles
x, y = symbols('x y', real=True)
e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3
a, b = Rational(191, 20), 3*sqrt(391)/20
ans = [(a, -b), (a, b)]
assert solve((e1, e2), (x, y)) == ans
assert solve((e1, e2/(x - a)), (x, y)) == []
# make the 2nd circle's radius be -3
e2 += 6
assert solve((e1, e2), (x, y)) == []
assert solve((e1, e2), (x, y), check=False) == ans
def test_issue_7322():
number = 5.62527e-35
assert solve(x - number, x)[0] == number
def test_nsolve():
raises(ValueError, lambda: nsolve(x, (-1, 1), method='bisect'))
raises(TypeError, lambda: nsolve((x - y + 3,x + y,z - y),(x,y,z),(-50,50)))
raises(TypeError, lambda: nsolve((x + y, x - y), (0, 1)))
@slow
def test_high_order_multivariate():
assert len(solve(a*x**3 - x + 1, x)) == 3
assert len(solve(a*x**4 - x + 1, x)) == 4
assert solve(a*x**5 - x + 1, x) == [] # incomplete solution allowed
raises(NotImplementedError, lambda:
solve(a*x**5 - x + 1, x, incomplete=False))
# result checking must always consider the denominator and CRootOf
# must be checked, too
d = x**5 - x + 1
assert solve(d*(1 + 1/d)) == [CRootOf(d + 1, i) for i in range(5)]
d = x - 1
assert solve(d*(2 + 1/d)) == [S.Half]
def test_base_0_exp_0():
assert solve(0**x - 1) == [0]
assert solve(0**(x - 2) - 1) == [2]
assert solve(S('x*(1/x**0 - x)', evaluate=False)) == \
[0, 1]
def test__simple_dens():
assert _simple_dens(1/x**0, [x]) == set()
assert _simple_dens(1/x**y, [x]) == {x**y}
assert _simple_dens(1/root(x, 3), [x]) == {x}
def test_issue_8755():
# This tests two things: that if full unrad is attempted and fails
# the solution should still be found; also it tests the use of
# keyword `composite`.
assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3
assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 -
1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3
@slow
def test_issue_8828():
x1 = 0
y1 = -620
r1 = 920
x2 = 126
y2 = 276
x3 = 51
y3 = 205
r3 = 104
v = x, y, z
f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2
f2 = (x - x2)**2 + (y - y2)**2 - z**2
f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2
F = f1,f2,f3
g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1
g2 = f2
g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3
G = g1,g2,g3
A = solve(F, v)
B = solve(G, v)
C = solve(G, v, manual=True)
p, q, r = [{tuple(i.evalf(2) for i in j) for j in R} for R in [A, B, C]]
assert p == q == r
@slow
def test_issue_2840_8155():
assert solve(sin(3*x) + sin(6*x)) == [
0, pi*Rational(-5, 3), pi*Rational(-4, 3), -pi, pi*Rational(-2, 3),
pi*Rational(-4, 9), -pi/3, pi*Rational(-2, 9), pi*Rational(2, 9),
pi/3, pi*Rational(4, 9), pi*Rational(2, 3), pi, pi*Rational(4, 3),
pi*Rational(14, 9), pi*Rational(5, 3), pi*Rational(16, 9), 2*pi,
-2*I*log(-(-1)**Rational(1, 9)), -2*I*log(-(-1)**Rational(2, 9)),
-2*I*log(-sin(pi/18) - I*cos(pi/18)),
-2*I*log(-sin(pi/18) + I*cos(pi/18)),
-2*I*log(sin(pi/18) - I*cos(pi/18)),
-2*I*log(sin(pi/18) + I*cos(pi/18))]
assert solve(2*sin(x) - 2*sin(2*x)) == [
0, pi*Rational(-5, 3), -pi, -pi/3, pi/3, pi, pi*Rational(5, 3)]
def test_issue_9567():
assert solve(1 + 1/(x - 1)) == [0]
def test_issue_11538():
assert solve(x + E) == [-E]
assert solve(x**2 + E) == [-I*sqrt(E), I*sqrt(E)]
assert solve(x**3 + 2*E) == [
-cbrt(2 * E),
cbrt(2)*cbrt(E)/2 - cbrt(2)*sqrt(3)*I*cbrt(E)/2,
cbrt(2)*cbrt(E)/2 + cbrt(2)*sqrt(3)*I*cbrt(E)/2]
assert solve([x + 4, y + E], x, y) == {x: -4, y: -E}
assert solve([x**2 + 4, y + E], x, y) == [
(-2*I, -E), (2*I, -E)]
e1 = x - y**3 + 4
e2 = x + y + 4 + 4 * E
assert len(solve([e1, e2], x, y)) == 3
@slow
def test_issue_12114():
a, b, c, d, e, f, g = symbols('a,b,c,d,e,f,g')
terms = [1 + a*b + d*e, 1 + a*c + d*f, 1 + b*c + e*f,
g - a**2 - d**2, g - b**2 - e**2, g - c**2 - f**2]
sol = solve(terms, [a, b, c, d, e, f, g], dict=True)
s = sqrt(-f**2 - 1)
s2 = sqrt(2 - f**2)
s3 = sqrt(6 - 3*f**2)
s4 = sqrt(3)*f
s5 = sqrt(3)*s2
assert sol == [
{a: -s, b: -s, c: -s, d: f, e: f, g: -1},
{a: s, b: s, c: s, d: f, e: f, g: -1},
{a: -s4/2 - s2/2, b: s4/2 - s2/2, c: s2,
d: -f/2 + s3/2, e: -f/2 - s5/2, g: 2},
{a: -s4/2 + s2/2, b: s4/2 + s2/2, c: -s2,
d: -f/2 - s3/2, e: -f/2 + s5/2, g: 2},
{a: s4/2 - s2/2, b: -s4/2 - s2/2, c: s2,
d: -f/2 - s3/2, e: -f/2 + s5/2, g: 2},
{a: s4/2 + s2/2, b: -s4/2 + s2/2, c: -s2,
d: -f/2 + s3/2, e: -f/2 - s5/2, g: 2}]
def test_inf():
assert solve(1 - oo*x) == []
assert solve(oo*x, x) == []
assert solve(oo*x - oo, x) == []
def test_issue_12448():
f = Function('f')
fun = [f(i) for i in range(15)]
sym = symbols('x:15')
reps = dict(zip(fun, sym))
(x, y, z), c = sym[:3], sym[3:]
ssym = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3]
for i in range(3)], (x, y, z))
(x, y, z), c = fun[:3], fun[3:]
sfun = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3]
for i in range(3)], (x, y, z))
assert sfun[fun[0]].xreplace(reps).count_ops() == \
ssym[sym[0]].count_ops()
def test_denoms():
assert denoms(x/2 + 1/y) == {2, y}
assert denoms(x/2 + 1/y, y) == {y}
assert denoms(x/2 + 1/y, [y]) == {y}
assert denoms(1/x + 1/y + 1/z, [x, y]) == {x, y}
assert denoms(1/x + 1/y + 1/z, x, y) == {x, y}
assert denoms(1/x + 1/y + 1/z, {x, y}) == {x, y}
def test_issue_12476():
x0, x1, x2, x3, x4, x5 = symbols('x0 x1 x2 x3 x4 x5')
eqns = [x0**2 - x0, x0*x1 - x1, x0*x2 - x2, x0*x3 - x3, x0*x4 - x4, x0*x5 - x5,
x0*x1 - x1, -x0/3 + x1**2 - 2*x2/3, x1*x2 - x1/3 - x2/3 - x3/3,
x1*x3 - x2/3 - x3/3 - x4/3, x1*x4 - 2*x3/3 - x5/3, x1*x5 - x4, x0*x2 - x2,
x1*x2 - x1/3 - x2/3 - x3/3, -x0/6 - x1/6 + x2**2 - x2/6 - x3/3 - x4/6,
-x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, x2*x4 - x2/3 - x3/3 - x4/3,
x2*x5 - x3, x0*x3 - x3, x1*x3 - x2/3 - x3/3 - x4/3,
-x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6,
-x0/6 - x1/6 - x2/6 + x3**2 - x3/3 - x4/6, -x1/3 - x2/3 + x3*x4 - x3/3,
-x2 + x3*x5, x0*x4 - x4, x1*x4 - 2*x3/3 - x5/3, x2*x4 - x2/3 - x3/3 - x4/3,
-x1/3 - x2/3 + x3*x4 - x3/3, -x0/3 - 2*x2/3 + x4**2, -x1 + x4*x5, x0*x5 - x5,
x1*x5 - x4, x2*x5 - x3, -x2 + x3*x5, -x1 + x4*x5, -x0 + x5**2, x0 - 1]
sols = [{x0: 1, x3: Rational(1, 6), x2: Rational(1, 6), x4: Rational(-2, 3), x1: Rational(-2, 3), x5: 1},
{x0: 1, x3: S.Half, x2: Rational(-1, 2), x4: 0, x1: 0, x5: -1},
{x0: 1, x3: Rational(-1, 3), x2: Rational(-1, 3), x4: Rational(1, 3), x1: Rational(1, 3), x5: 1},
{x0: 1, x3: 1, x2: 1, x4: 1, x1: 1, x5: 1},
{x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: sqrt(5)/3, x1: -sqrt(5)/3, x5: -1},
{x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: -sqrt(5)/3, x1: sqrt(5)/3, x5: -1}]
assert solve(eqns) == sols
def test_issue_13849():
t = symbols('t')
assert solve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) == []
def test_issue_14860():
from sympy.physics.units import newton, kilo
assert solve(8*kilo*newton + x + y, x) == [-8000*newton - y]
def test_issue_14721():
k, h, a, b = symbols(':4')
assert solve([
-1 + (-k + 1)**2/b**2 + (-h - 1)**2/a**2,
-1 + (-k + 1)**2/b**2 + (-h + 1)**2/a**2,
h, k + 2], h, k, a, b) == [
(0, -2, -b*sqrt(1/(b**2 - 9)), b),
(0, -2, b*sqrt(1/(b**2 - 9)), b)]
assert solve([
h, h/a + 1/b**2 - 2, -h/2 + 1/b**2 - 2], a, h, b) == [
(a, 0, -sqrt(2)/2), (a, 0, sqrt(2)/2)]
assert solve((a + b**2 - 1, a + b**2 - 2)) == []
def test_issue_14779():
x = symbols('x', real=True)
assert solve(sqrt(x**4 - 130*x**2 + 1089) + sqrt(x**4 - 130*x**2
+ 3969) - 96*Abs(x)/x,x) == [sqrt(130)]
def test_issue_15307():
assert solve((y - 2, Mul(x + 3,x - 2, evaluate=False))) == \
[{x: -3, y: 2}, {x: 2, y: 2}]
assert solve((y - 2, Mul(3, x - 2, evaluate=False))) == \
{x: 2, y: 2}
assert solve((y - 2, Add(x + 4, x - 2, evaluate=False))) == \
{x: -1, y: 2}
eq1 = Eq(12513*x + 2*y - 219093, -5726*x - y)
eq2 = Eq(-2*x + 8, 2*x - 40)
assert solve([eq1, eq2]) == {x:12, y:75}
def test_issue_15415():
assert solve(x - 3, x) == [3]
assert solve([x - 3], x) == {x:3}
assert solve(Eq(y + 3*x**2/2, y + 3*x), y) == []
assert solve([Eq(y + 3*x**2/2, y + 3*x)], y) == []
assert solve([Eq(y + 3*x**2/2, y + 3*x), Eq(x, 1)], y) == []
@slow
def test_issue_15731():
# f(x)**g(x)=c
assert solve(Eq((x**2 - 7*x + 11)**(x**2 - 13*x + 42), 1)) == [2, 3, 4, 5, 6, 7]
assert solve((x)**(x + 4) - 4) == [-2]
assert solve((-x)**(-x + 4) - 4) == [2]
assert solve((x**2 - 6)**(x**2 - 2) - 4) == [-2, 2]
assert solve((x**2 - 2*x - 1)**(x**2 - 3) - 1/(1 - 2*sqrt(2))) == [sqrt(2)]
assert solve(x**(x + S.Half) - 4*sqrt(2)) == [S(2)]
assert solve((x**2 + 1)**x - 25) == [2]
assert solve(x**(2/x) - 2) == [2, 4]
assert solve((x/2)**(2/x) - sqrt(2)) == [4, 8]
assert solve(x**(x + S.Half) - Rational(9, 4)) == [Rational(3, 2)]
# a**g(x)=c
assert solve((-sqrt(sqrt(2)))**x - 2) == [4, log(2)/(log(2**Rational(1, 4)) + I*pi)]
assert solve((sqrt(2))**x - sqrt(sqrt(2))) == [S.Half]
assert solve((-sqrt(2))**x + 2*(sqrt(2))) == [3,
(3*log(2)**2 + 4*pi**2 - 4*I*pi*log(2))/(log(2)**2 + 4*pi**2)]
assert solve((sqrt(2))**x - 2*(sqrt(2))) == [3]
assert solve(I**x + 1) == [2]
assert solve((1 + I)**x - 2*I) == [2]
assert solve((sqrt(2) + sqrt(3))**x - (2*sqrt(6) + 5)**Rational(1, 3)) == [Rational(2, 3)]
# bases of both sides are equal
b = Symbol('b')
assert solve(b**x - b**2, x) == [2]
assert solve(b**x - 1/b, x) == [-1]
assert solve(b**x - b, x) == [1]
b = Symbol('b', positive=True)
assert solve(b**x - b**2, x) == [2]
assert solve(b**x - 1/b, x) == [-1]
def test_issue_10933():
assert solve(x**4 + y*(x + 0.1), x) # doesn't fail
assert solve(I*x**4 + x**3 + x**2 + 1.) # doesn't fail
def test_Abs_handling():
x = symbols('x', real=True)
assert solve(abs(x/y), x) == [0]
def test_issue_7982():
x = Symbol('x')
# Test that no exception happens
assert solve([2*x**2 + 5*x + 20 <= 0, x >= 1.5], x) is S.false
# From #8040
assert solve([x**3 - 8.08*x**2 - 56.48*x/5 - 106 >= 0, x - 1 <= 0], [x]) is S.false
def test_issue_14645():
x, y = symbols('x y')
assert solve([x*y - x - y, x*y - x - y], [x, y]) == [(y/(y - 1), y)]
def test_issue_12024():
x, y = symbols('x y')
assert solve(Piecewise((0.0, x < 0.1), (x, x >= 0.1)) - y) == \
[{y: Piecewise((0.0, x < 0.1), (x, True))}]
def test_issue_17452():
assert solve((7**x)**x + pi, x) == [-sqrt(log(pi) + I*pi)/sqrt(log(7)),
sqrt(log(pi) + I*pi)/sqrt(log(7))]
assert solve(x**(x/11) + pi/11, x) == [exp(LambertW(-11*log(11) + 11*log(pi) + 11*I*pi))]
def test_issue_17799():
assert solve(-erf(x**(S(1)/3))**pi + I, x) == []
def test_issue_17650():
x = Symbol('x', real=True)
assert solve(abs(abs(x**2 - 1) - x) - x) == [1, -1 + sqrt(2), 1 + sqrt(2)]
def test_issue_17882():
eq = -8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3))
assert unrad(eq) is None
def test_issue_17949():
assert solve(exp(+x+x**2), x) == []
assert solve(exp(-x+x**2), x) == []
assert solve(exp(+x-x**2), x) == []
assert solve(exp(-x-x**2), x) == []
def test_issue_10993():
assert solve(Eq(binomial(x, 2), 3)) == [-2, 3]
assert solve(Eq(pow(x, 2) + binomial(x, 3), x)) == [-4, 0, 1]
assert solve(Eq(binomial(x, 2), 0)) == [0, 1]
assert solve(a+binomial(x, 3), a) == [-binomial(x, 3)]
assert solve(x-binomial(a, 3) + binomial(y, 2) + sin(a), x) == [-sin(a) + binomial(a, 3) - binomial(y, 2)]
assert solve((x+1)-binomial(x+1, 3), x) == [-2, -1, 3]
def test_issue_11553():
eq1 = x + y + 1
eq2 = x + GoldenRatio
assert solve([eq1, eq2], x, y) == {x: -GoldenRatio, y: -1 + GoldenRatio}
eq3 = x + 2 + TribonacciConstant
assert solve([eq1, eq3], x, y) == {x: -2 - TribonacciConstant, y: 1 + TribonacciConstant}
def test_issue_19113_19102():
t = S(1)/3
solve(cos(x)**5-sin(x)**5)
assert solve(4*cos(x)**3 - 2*sin(x)**3) == [
atan(2**(t)), -atan(2**(t)*(1 - sqrt(3)*I)/2),
-atan(2**(t)*(1 + sqrt(3)*I)/2)]
h = S.Half
assert solve(cos(x)**2 + sin(x)) == [
2*atan(-h + sqrt(5)/2 + sqrt(2)*sqrt(1 - sqrt(5))/2),
-2*atan(h + sqrt(5)/2 + sqrt(2)*sqrt(1 + sqrt(5))/2),
-2*atan(-sqrt(5)/2 + h + sqrt(2)*sqrt(1 - sqrt(5))/2),
-2*atan(-sqrt(2)*sqrt(1 + sqrt(5))/2 + h + sqrt(5)/2)]
assert solve(3*cos(x) - sin(x)) == [atan(3)]
def test_issue_19509():
a = S(3)/4
b = S(5)/8
c = sqrt(5)/8
d = sqrt(5)/4
assert solve(1/(x -1)**5 - 1) == [2,
-d + a - sqrt(-b + c),
-d + a + sqrt(-b + c),
d + a - sqrt(-b - c),
d + a + sqrt(-b - c)]
def test_issue_20747():
THT, HT, DBH, dib, c0, c1, c2, c3, c4 = symbols('THT HT DBH dib c0 c1 c2 c3 c4')
f = DBH*c3 + THT*c4 + c2
rhs = 1 - ((HT - 1)/(THT - 1))**c1*(1 - exp(c0/f))
eq = dib - DBH*(c0 - f*log(rhs))
term = ((1 - exp((DBH*c0 - dib)/(DBH*(DBH*c3 + THT*c4 + c2))))
/ (1 - exp(c0/(DBH*c3 + THT*c4 + c2))))
sol = [THT*term**(1/c1) - term**(1/c1) + 1]
assert solve(eq, HT) == sol
def test_issue_20902():
f = (t / ((1 + t) ** 2))
assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3)
assert solve(f.subs({t: 3 * x + 3}).diff(x) > 0, x) == (S(-4)/3 < x) & (x < S(-2)/3)
assert solve(f.subs({t: 3 * x + 4}).diff(x) > 0, x) == (S(-5)/3 < x) & (x < S(-1))
assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3)
def test_issue_21034():
a = symbols('a', real=True)
system = [x - cosh(cos(4)), y - sinh(cos(a)), z - tanh(x)]
# constants inside hyperbolic functions should not be rewritten in terms of exp
assert solve(system, x, y, z) == [(cosh(cos(4)), sinh(cos(a)), tanh(cosh(cos(4))))]
# but if the variable of interest is present in a hyperbolic function,
# then it should be rewritten in terms of exp and solved further
newsystem = [(exp(x) - exp(-x)) - tanh(x)*(exp(x) + exp(-x)) + x - 5]
assert solve(newsystem, x) == {x: 5}
def test_issue_4886():
z = a*sqrt(R**2*a**2 + R**2*b**2 - c**2)/(a**2 + b**2)
t = b*c/(a**2 + b**2)
sol = [((b*(t - z) - c)/(-a), t - z), ((b*(t + z) - c)/(-a), t + z)]
assert solve([x**2 + y**2 - R**2, a*x + b*y - c], x, y) == sol
def test_issue_6819():
a, b, c, d = symbols('a b c d', positive=True)
assert solve(a*b**x - c*d**x, x) == [log(c/a)/log(b/d)]
def test_issue_17454():
x = Symbol('x')
assert solve((1 - x - I)**4, x) == [1 - I]
def test_issue_21852():
solution = [21 - 21*sqrt(2)/2]
assert solve(2*x + sqrt(2*x**2) - 21) == solution
def test_issue_21942():
eq = -d + (a*c**(1 - e) + b**(1 - e)*(1 - a))**(1/(1 - e))
sol = solve(eq, c, simplify=False, check=False)
assert sol == [((a*b**(1 - e) - b**(1 - e) +
d**(1 - e))/a)**(1/(1 - e))]
def test_solver_flags():
root = solve(x**5 + x**2 - x - 1, cubics=False)
rad = solve(x**5 + x**2 - x - 1, cubics=True)
assert root != rad
def test_issue_22768():
eq = 2*x**3 - 16*(y - 1)**6*z**3
assert solve(eq.expand(), x, simplify=False
) == [2*z*(y - 1)**2, z*(-1 + sqrt(3)*I)*(y - 1)**2,
-z*(1 + sqrt(3)*I)*(y - 1)**2]
def test_issue_22717():
assert solve((-y**2 + log(y**2/x) + 2, -2*x*y + 2*x/y)) == [
{y: -1, x: E}, {y: 1, x: E}]
def test_issue_10169():
eq = S(-8*a - x**5*(a + b + c + e) - x**4*(4*a - 2**Rational(3,4)*c + 4*c +
d + 2**Rational(3,4)*e + 4*e + k) - x**3*(-4*2**Rational(3,4)*c + sqrt(2)*c -
2**Rational(3,4)*d + 4*d + sqrt(2)*e + 4*2**Rational(3,4)*e + 2**Rational(3,4)*k + 4*k) -
x**2*(4*sqrt(2)*c - 4*2**Rational(3,4)*d + sqrt(2)*d + 4*sqrt(2)*e +
sqrt(2)*k + 4*2**Rational(3,4)*k) - x*(2*a + 2*b + 4*sqrt(2)*d +
4*sqrt(2)*k) + 5)
assert solve_undetermined_coeffs(eq, [a, b, c, d, e, k], x) == {
a: Rational(5,8),
b: Rational(-5,1032),
c: Rational(-40,129) - 5*2**Rational(3,4)/129 + 5*2**Rational(1,4)/1032,
d: -20*2**Rational(3,4)/129 - 10*sqrt(2)/129 - 5*2**Rational(1,4)/258,
e: Rational(-40,129) - 5*2**Rational(1,4)/1032 + 5*2**Rational(3,4)/129,
k: -10*sqrt(2)/129 + 5*2**Rational(1,4)/258 + 20*2**Rational(3,4)/129
}
def test_solve_undetermined_coeffs_issue_23927():
A, B, r, phi = symbols('A, B, r, phi')
eq = Eq(A*sin(t) + B*cos(t), r*sin(t - phi)).rewrite(Add).expand(trig=True)
soln = solve_undetermined_coeffs(eq, (r, phi), t)
assert soln == [{
phi: 2*atan((A - sqrt(A**2 + B**2))/B),
r: (-A**2 + A*sqrt(A**2 + B**2) - B**2)/(A - sqrt(A**2 + B**2))
}, {
phi: 2*atan((A + sqrt(A**2 + B**2))/B),
r: (A**2 + A*sqrt(A**2 + B**2) + B**2)/(A + sqrt(A**2 + B**2))/-1
}]
|
f8e7a0852835e8614def4cbf4545c2e8217a554fdbecd5da2836de8ed452a1c8 | from sympy.core.function import (Function, Lambda, expand)
from sympy.core.numbers import (I, Rational)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.combinatorial.factorials import (rf, binomial, factorial)
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.polys.polytools import factor
from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio
from sympy.testing.pytest import raises, slow, XFAIL
from sympy.abc import a, b
y = Function('y')
n, k = symbols('n,k', integer=True)
C0, C1, C2 = symbols('C0,C1,C2')
def test_rsolve_poly():
assert rsolve_poly([-1, -1, 1], 0, n) == 0
assert rsolve_poly([-1, -1, 1], 1, n) == -1
assert rsolve_poly([-1, n + 1], n, n) == 1
assert rsolve_poly([-1, 1], n, n) == C0 + (n**2 - n)/2
assert rsolve_poly([-n - 1, n], 1, n) == C0*n - 1
assert rsolve_poly([-4*n - 2, 1], 4*n + 1, n) == -1
assert rsolve_poly([-1, 1], n**5 + n**3, n) == \
C0 - n**3 / 2 - n**5 / 2 + n**2 / 6 + n**6 / 6 + 2*n**4 / 3
def test_rsolve_ratio():
solution = rsolve_ratio([-2*n**3 + n**2 + 2*n - 1, 2*n**3 + n**2 - 6*n,
-2*n**3 - 11*n**2 - 18*n - 9, 2*n**3 + 13*n**2 + 22*n + 8], 0, n)
assert solution == C0*(2*n - 3)/(n**2 - 1)/2
def test_rsolve_hyper():
assert rsolve_hyper([-1, -1, 1], 0, n) in [
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
]
assert rsolve_hyper([n**2 - 2, -2*n - 1, 1], 0, n) in [
C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n),
C1*rf(sqrt(2), n) + C0*rf(-sqrt(2), n),
]
assert rsolve_hyper([n**2 - k, -2*n - 1, 1], 0, n) in [
C0*rf(sqrt(k), n) + C1*rf(-sqrt(k), n),
C1*rf(sqrt(k), n) + C0*rf(-sqrt(k), n),
]
assert rsolve_hyper(
[2*n*(n + 1), -n**2 - 3*n + 2, n - 1], 0, n) == C1*factorial(n) + C0*2**n
assert rsolve_hyper(
[n + 2, -(2*n + 3)*(17*n**2 + 51*n + 39), n + 1], 0, n) == 0
assert rsolve_hyper([-n - 1, -1, 1], 0, n) == 0
assert rsolve_hyper([-1, 1], n, n).expand() == C0 + n**2/2 - n/2
assert rsolve_hyper([-1, 1], 1 + n, n).expand() == C0 + n**2/2 + n/2
assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n
assert rsolve_hyper([-a, 1],0,n).expand() == C0*a**n
assert rsolve_hyper([-a, 0, 1], 0, n).expand() == (-1)**n*C1*a**(n/2) + C0*a**(n/2)
assert rsolve_hyper([1, 1, 1], 0, n).expand() == \
C0*(Rational(-1, 2) - sqrt(3)*I/2)**n + C1*(Rational(-1, 2) + sqrt(3)*I/2)**n
assert rsolve_hyper([1, -2*n/a - 2/a, 1], 0, n) == 0
@XFAIL
def test_rsolve_ratio_missed():
# this arises during computation
# assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n
assert rsolve_ratio([-n, n + 2], n, n) is not None
def recurrence_term(c, f):
"""Compute RHS of recurrence in f(n) with coefficients in c."""
return sum(c[i]*f.subs(n, n + i) for i in range(len(c)))
def test_rsolve_bulk():
"""Some bulk-generated tests."""
funcs = [ n, n + 1, n**2, n**3, n**4, n + n**2, 27*n + 52*n**2 - 3*
n**3 + 12*n**4 - 52*n**5 ]
coeffs = [ [-2, 1], [-2, -1, 1], [-1, 1, 1, -1, 1], [-n, 1], [n**2 -
n + 12, 1] ]
for p in funcs:
# compute difference
for c in coeffs:
q = recurrence_term(c, p)
if p.is_polynomial(n):
assert rsolve_poly(c, q, n) == p
# See issue 3956:
if p.is_hypergeometric(n) and len(c) <= 3:
assert rsolve_hyper(c, q, n).subs(zip(symbols('C:3'), [0, 0, 0])).expand() == p
def test_rsolve_0_sol_homogeneous():
# fixed by cherry-pick from
# https://github.com/diofant/diofant/commit/e1d2e52125199eb3df59f12e8944f8a5f24b00a5
assert rsolve_hyper([n**2 - n + 12, 1], n*(n**2 - n + 12) + n + 1, n) == n
def test_rsolve():
f = y(n + 2) - y(n + 1) - y(n)
h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
- sqrt(5)*(S.Half - S.Half*sqrt(5))**n
assert rsolve(f, y(n)) in [
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
]
assert rsolve(f, y(n), [0, 5]) == h
assert rsolve(f, y(n), {0: 0, 1: 5}) == h
assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h
assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h
assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n)
g = C1*factorial(n) + C0*2**n
h = -3*factorial(n) + 3*2**n
assert rsolve(f, y(n)) == g
assert rsolve(f, y(n), []) == g
assert rsolve(f, y(n), {}) == g
assert rsolve(f, y(n), [0, 3]) == h
assert rsolve(f, y(n), {0: 0, 1: 3}) == h
assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = y(n) - y(n - 1) - 2
assert rsolve(f, y(n), {y(0): 0}) == 2*n
assert rsolve(f, y(n), {y(0): 1}) == 2*n + 1
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = 3*y(n - 1) - y(n) - 1
assert rsolve(f, y(n), {y(0): 0}) == -3**n/2 + S.Half
assert rsolve(f, y(n), {y(0): 1}) == 3**n/2 + S.Half
assert rsolve(f, y(n), {y(0): 2}) == 3*3**n/2 + S.Half
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = y(n) - 1/n*y(n - 1)
assert rsolve(f, y(n)) == C0/factorial(n)
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = y(n) - 1/n*y(n - 1) - 1
assert rsolve(f, y(n)) is None
f = 2*y(n - 1) + (1 - n)*y(n)/n
assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1)*n
assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1)*n*2
assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1)*n*3
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
f = (n - 1)*(n - 2)*y(n + 2) - (n + 1)*(n + 2)*y(n)
assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n*(n - 1)*(n - 2)
assert rsolve(
f, y(n), {y(3): 6, y(4): -24}) == -n*(n - 1)*(n - 2)*(-1)**(n)
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
assert rsolve(Eq(y(n + 1), a*y(n)), y(n), {y(1): a}).simplify() == a**n
assert rsolve(y(n) - a*y(n-2),y(n), \
{y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \
a**(n/2 + 1) - b*(-sqrt(a))**n
f = (-16*n**2 + 32*n - 12)*y(n - 1) + (4*n**2 - 12*n + 9)*y(n)
yn = rsolve(f, y(n), {y(1): binomial(2*n + 1, 3)})
sol = 2**(2*n)*n*(2*n - 1)**2*(2*n + 1)/12
assert factor(expand(yn, func=True)) == sol
sol = rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n))
assert str(sol) == 'C0*((-sqrt(1 - a**2) - 1)/a)**n + C1*((sqrt(1 - a**2) - 1)/a)**n'
assert rsolve((k + 1)*y(k), y(k)) is None
assert (rsolve((k + 1)*y(k) + (k + 3)*y(k + 1) + (k + 5)*y(k + 2), y(k))
is None)
assert rsolve(y(n) + y(n + 1) + 2**n + 3**n, y(n)) == (-1)**n*C0 - 2**n/3 - 3**n/4
def test_rsolve_raises():
x = Function('x')
raises(ValueError, lambda: rsolve(y(n) - y(k + 1), y(n)))
raises(ValueError, lambda: rsolve(y(n) - y(n + 1), x(n)))
raises(ValueError, lambda: rsolve(y(n) - x(n + 1), y(n)))
raises(ValueError, lambda: rsolve(y(n) - sqrt(n)*y(n + 1), y(n)))
raises(ValueError, lambda: rsolve(y(n) - y(n + 1), y(n), {x(0): 0}))
raises(ValueError, lambda: rsolve(y(n) + y(n + 1) + 2**n + cos(n), y(n)))
def test_issue_6844():
f = y(n + 2) - y(n + 1) + y(n)/4
assert rsolve(f, y(n)) == 2**(-n + 1)*C1*n + 2**(-n)*C0
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2**(1 - n)*n
def test_issue_18751():
r = Symbol('r', positive=True)
theta = Symbol('theta', real=True)
f = y(n) - 2 * r * cos(theta) * y(n - 1) + r**2 * y(n - 2)
assert rsolve(f, y(n)) == \
C0*(r*(cos(theta) - I*Abs(sin(theta))))**n + C1*(r*(cos(theta) + I*Abs(sin(theta))))**n
def test_constant_naming():
#issue 8697
assert rsolve(y(n+3) - y(n+2) - y(n+1) + y(n), y(n)) == (-1)**n*C1 + C0 + C2*n
assert rsolve(y(n+3)+3*y(n+2)+3*y(n+1)+y(n), y(n)).expand() == (-1)**n*C0 - (-1)**n*C1*n - (-1)**n*C2*n**2
assert rsolve(y(n) - 2*y(n - 3) + 5*y(n - 2) - 4*y(n - 1),y(n),[1,3,8]) == 3*2**n - n - 2
#issue 19630
assert rsolve(y(n+3) - 3*y(n+1) + 2*y(n), y(n), {y(1):0, y(2):8, y(3):-2}) == (-2)**n + 2*n
@slow
def test_issue_15751():
f = y(n) + 21*y(n + 1) - 273*y(n + 2) - 1092*y(n + 3) + 1820*y(n + 4) + 1092*y(n + 5) - 273*y(n + 6) - 21*y(n + 7) + y(n + 8)
assert rsolve(f, y(n)) is not None
def test_issue_17990():
f = -10*y(n) + 4*y(n + 1) + 6*y(n + 2) + 46*y(n + 3)
sol = rsolve(f, y(n))
expected = C0*((86*18**(S(1)/3)/69 + (-12 + (-1 + sqrt(3)*I)*(290412 +
3036*sqrt(9165))**(S(1)/3))*(1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**
(S(1)/3)/276)/((1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
)**n + C1*((86*18**(S(1)/3)/69 + (-12 + (-1 - sqrt(3)*I)*(290412 + 3036
*sqrt(9165))**(S(1)/3))*(1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**
(S(1)/3)/276)/((1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
)**n + C2*(-43*18**(S(1)/3)/(69*(24201 + 253*sqrt(9165))**(S(1)/3)) -
S(1)/23 + (290412 + 3036*sqrt(9165))**(S(1)/3)/138)**n
assert sol == expected
e = sol.subs({C0: 1, C1: 1, C2: 1, n: 1}).evalf()
assert abs(e + 0.130434782608696) < 1e-13
def test_issue_8697():
a = Function('a')
eq = a(n + 3) - a(n + 2) - a(n + 1) + a(n)
assert rsolve(eq, a(n)) == (-1)**n*C1 + C0 + C2*n
eq2 = a(n + 3) + 3*a(n + 2) + 3*a(n + 1) + a(n)
assert (rsolve(eq2, a(n)) ==
(-1)**n*C0 + (-1)**(n + 1)*C1*n + (-1)**(n + 1)*C2*n**2)
assert rsolve(a(n) - 2*a(n - 3) + 5*a(n - 2) - 4*a(n - 1),
a(n), {a(0): 1, a(1): 3, a(2): 8}) == 3*2**n - n - 2
# From issue thread (but fixed by https://github.com/diofant/diofant/commit/da9789c6cd7d0c2ceeea19fbf59645987125b289):
assert rsolve(a(n) - 2*a(n - 1) - n, a(n), {a(0): 1}) == 3*2**n - n - 2
def test_diofantissue_294():
f = y(n) - y(n - 1) - 2*y(n - 2) - 2*n
assert rsolve(f, y(n)) == (-1)**n*C0 + 2**n*C1 - n - Rational(5, 2)
# issue sympy/sympy#11261
assert rsolve(f, y(n), {y(0): -1, y(1): 1}) == (-(-1)**n/2 + 2*2**n -
n - Rational(5, 2))
# issue sympy/sympy#7055
assert rsolve(-2*y(n) + y(n + 1) + n - 1, y(n)) == 2**n*C0 + n
def test_issue_15553():
f = Function("f")
assert rsolve(Eq(f(n), 2*f(n - 1) + n), f(n)) == 2**n*C0 - n - 2
assert rsolve(Eq(f(n + 1), 2*f(n) + n**2 + 1), f(n)) == 2**n*C0 - n**2 - 2*n - 4
assert rsolve(Eq(f(n + 1), 2*f(n) + n**2 + 1), f(n), {f(1): 0}) == 7*2**n/2 - n**2 - 2*n - 4
assert rsolve(Eq(f(n), 2*f(n - 1) + 3*n**2), f(n)) == 2**n*C0 - 3*n**2 - 12*n - 18
assert rsolve(Eq(f(n), 2*f(n - 1) + n**2), f(n)) == 2**n*C0 - n**2 - 4*n - 6
assert rsolve(Eq(f(n), 2*f(n - 1) + n), f(n), {f(0): 1}) == 3*2**n - n - 2
|
c0f8cd516307668bce70e7d72c3ab46ea4c2d6ab450ced8d4a7ce973b46630cd | import glob
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from sysconfig import get_config_var, get_config_vars, get_path
from .runners import (
CCompilerRunner,
CppCompilerRunner,
FortranCompilerRunner
)
from .util import (
get_abspath, make_dirs, copy, Glob, ArbitraryDepthGlob,
glob_at_depth, import_module_from_file, pyx_is_cplus,
sha256_of_string, sha256_of_file, CompileError
)
if os.name == 'posix':
objext = '.o'
elif os.name == 'nt':
objext = '.obj'
else:
warnings.warn("Unknown os.name: {}".format(os.name))
objext = '.o'
def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False,
per_file_kwargs=None, **kwargs):
""" Compile source code files to object files.
Parameters
==========
files : iterable of str
Paths to source files, if ``cwd`` is given, the paths are taken as relative.
Runner: CompilerRunner subclass (optional)
Could be e.g. ``FortranCompilerRunner``. Will be inferred from filename
extensions if missing.
destdir: str
Output directory, if cwd is given, the path is taken as relative.
cwd: str
Working directory. Specify to have compiler run in other directory.
also used as root of relative paths.
keep_dir_struct: bool
Reproduce directory structure in `destdir`. default: ``False``
per_file_kwargs: dict
Dict mapping instances in ``files`` to keyword arguments.
\\*\\*kwargs: dict
Default keyword arguments to pass to ``Runner``.
"""
_per_file_kwargs = {}
if per_file_kwargs is not None:
for k, v in per_file_kwargs.items():
if isinstance(k, Glob):
for path in glob.glob(k.pathname):
_per_file_kwargs[path] = v
elif isinstance(k, ArbitraryDepthGlob):
for path in glob_at_depth(k.filename, cwd):
_per_file_kwargs[path] = v
else:
_per_file_kwargs[k] = v
# Set up destination directory
destdir = destdir or '.'
if not os.path.isdir(destdir):
if os.path.exists(destdir):
raise OSError("{} is not a directory".format(destdir))
else:
make_dirs(destdir)
if cwd is None:
cwd = '.'
for f in files:
copy(f, destdir, only_update=True, dest_is_dir=True)
# Compile files and return list of paths to the objects
dstpaths = []
for f in files:
if keep_dir_struct:
name, ext = os.path.splitext(f)
else:
name, ext = os.path.splitext(os.path.basename(f))
file_kwargs = kwargs.copy()
file_kwargs.update(_per_file_kwargs.get(f, {}))
dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs))
return dstpaths
def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None):
vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu')
if vendor.lower() == 'intel':
if cplus:
return (FortranCompilerRunner,
{'flags': ['-nofor_main', '-cxxlib']}, vendor)
else:
return (FortranCompilerRunner,
{'flags': ['-nofor_main']}, vendor)
elif vendor.lower() == 'gnu' or 'llvm':
if cplus:
return (CppCompilerRunner,
{'lib_options': ['fortran']}, vendor)
else:
return (FortranCompilerRunner,
{}, vendor)
else:
raise ValueError("No vendor found.")
def link(obj_files, out_file=None, shared=False, Runner=None,
cwd=None, cplus=False, fort=False, **kwargs):
""" Link object files.
Parameters
==========
obj_files: iterable of str
Paths to object files.
out_file: str (optional)
Path to executable/shared library, if ``None`` it will be
deduced from the last item in obj_files.
shared: bool
Generate a shared library?
Runner: CompilerRunner subclass (optional)
If not given the ``cplus`` and ``fort`` flags will be inspected
(fallback is the C compiler).
cwd: str
Path to the root of relative paths and working directory for compiler.
cplus: bool
C++ objects? default: ``False``.
fort: bool
Fortran objects? default: ``False``.
\\*\\*kwargs: dict
Keyword arguments passed to ``Runner``.
Returns
=======
The absolute path to the generated shared object / executable.
"""
if out_file is None:
out_file, ext = os.path.splitext(os.path.basename(obj_files[-1]))
if shared:
out_file += get_config_var('EXT_SUFFIX')
if not Runner:
if fort:
Runner, extra_kwargs, vendor = \
get_mixed_fort_c_linker(
vendor=kwargs.get('vendor', None),
cplus=cplus,
cwd=cwd,
)
for k, v in extra_kwargs.items():
if k in kwargs:
kwargs[k].expand(v)
else:
kwargs[k] = v
else:
if cplus:
Runner = CppCompilerRunner
else:
Runner = CCompilerRunner
flags = kwargs.pop('flags', [])
if shared:
if '-shared' not in flags:
flags.append('-shared')
run_linker = kwargs.pop('run_linker', True)
if not run_linker:
raise ValueError("run_linker was set to False (nonsensical).")
out_file = get_abspath(out_file, cwd=cwd)
runner = Runner(obj_files, out_file, flags, cwd=cwd, **kwargs)
runner.run()
return out_file
def link_py_so(obj_files, so_file=None, cwd=None, libraries=None,
cplus=False, fort=False, **kwargs):
""" Link Python extension module (shared object) for importing
Parameters
==========
obj_files: iterable of str
Paths to object files to be linked.
so_file: str
Name (path) of shared object file to create. If not specified it will
have the basname of the last object file in `obj_files` but with the
extension '.so' (Unix).
cwd: path string
Root of relative paths and working directory of linker.
libraries: iterable of strings
Libraries to link against, e.g. ['m'].
cplus: bool
Any C++ objects? default: ``False``.
fort: bool
Any Fortran objects? default: ``False``.
kwargs**: dict
Keyword arguments passed to ``link(...)``.
Returns
=======
Absolute path to the generate shared object.
"""
libraries = libraries or []
include_dirs = kwargs.pop('include_dirs', [])
library_dirs = kwargs.pop('library_dirs', [])
# Add Python include and library directories
# PY_LDFLAGS does not available on all python implementations
# e.g. when with pypy, so it's LDFLAGS we need to use
if sys.platform == "win32":
warnings.warn("Windows not yet supported.")
elif sys.platform == 'darwin':
cfgDict = get_config_vars()
kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']]
library_dirs += [cfgDict['LIBDIR']]
# In macOS, linker needs to compile frameworks
# e.g. "-framework CoreFoundation"
is_framework = False
for opt in cfgDict['LIBS'].split():
if is_framework:
kwargs['linkline'] = kwargs.get('linkline', []) + ['-framework', opt]
is_framework = False
elif opt.startswith('-l'):
libraries.append(opt[2:])
elif opt.startswith('-framework'):
is_framework = True
# The python library is not included in LIBS
libfile = cfgDict['LIBRARY']
libname = ".".join(libfile.split('.')[:-1])[3:]
libraries.append(libname)
elif sys.platform[:3] == 'aix':
# Don't use the default code below
pass
else:
if get_config_var('Py_ENABLE_SHARED'):
cfgDict = get_config_vars()
kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']]
library_dirs += [cfgDict['LIBDIR']]
for opt in cfgDict['BLDLIBRARY'].split():
if opt.startswith('-l'):
libraries += [opt[2:]]
else:
pass
flags = kwargs.pop('flags', [])
needed_flags = ('-pthread',)
for flag in needed_flags:
if flag not in flags:
flags.append(flag)
return link(obj_files, shared=True, flags=flags, cwd=cwd,
cplus=cplus, fort=fort, include_dirs=include_dirs,
libraries=libraries, library_dirs=library_dirs, **kwargs)
def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
""" Generates a C file from a Cython source file.
Parameters
==========
src: str
Path to Cython source.
destdir: str (optional)
Path to output directory (default: '.').
cwd: path string (optional)
Root of relative paths (default: '.').
**cy_kwargs:
Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``,
else a .c file.
"""
from Cython.Compiler.Main import (
default_options, CompilationOptions
)
from Cython.Compiler.Main import compile as cy_compile
assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
cwd = cwd or '.'
destdir = destdir or '.'
ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
c_name = os.path.splitext(os.path.basename(src))[0] + ext
dstfile = os.path.join(destdir, c_name)
if cwd:
ori_dir = os.getcwd()
else:
ori_dir = '.'
os.chdir(cwd)
try:
cy_options = CompilationOptions(default_options)
cy_options.__dict__.update(cy_kwargs)
# Set language_level if not set by cy_kwargs
# as not setting it is deprecated
if 'language_level' not in cy_kwargs:
cy_options.__dict__['language_level'] = 3
cy_result = cy_compile([src], cy_options)
if cy_result.num_errors > 0:
raise ValueError("Cython compilation failed.")
# Move generated C file to destination
# In macOS, the generated C file is in the same directory as the source
# but the /var is a symlink to /private/var, so we need to use realpath
if os.path.realpath(os.path.dirname(src)) != os.path.realpath(destdir):
if os.path.exists(dstfile):
os.unlink(dstfile)
shutil.move(os.path.join(os.path.dirname(src), c_name), destdir)
finally:
os.chdir(ori_dir)
return dstfile
extension_mapping = {
'.c': (CCompilerRunner, None),
'.cpp': (CppCompilerRunner, None),
'.cxx': (CppCompilerRunner, None),
'.f': (FortranCompilerRunner, None),
'.for': (FortranCompilerRunner, None),
'.ftn': (FortranCompilerRunner, None),
'.f90': (FortranCompilerRunner, None), # ifort only knows about .f90
'.f95': (FortranCompilerRunner, 'f95'),
'.f03': (FortranCompilerRunner, 'f2003'),
'.f08': (FortranCompilerRunner, 'f2008'),
}
def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs):
""" Compiles a source code file to an object file.
Files ending with '.pyx' assumed to be cython files and
are dispatched to pyx2obj.
Parameters
==========
srcpath: str
Path to source file.
Runner: CompilerRunner subclass (optional)
If ``None``: deduced from extension of srcpath.
objpath : str (optional)
Path to generated object. If ``None``: deduced from ``srcpath``.
cwd: str (optional)
Working directory and root of relative paths. If ``None``: current dir.
inc_py: bool
Add Python include path to kwarg "include_dirs". Default: False
\\*\\*kwargs: dict
keyword arguments passed to Runner or pyx2obj
"""
name, ext = os.path.splitext(os.path.basename(srcpath))
if objpath is None:
if os.path.isabs(srcpath):
objpath = '.'
else:
objpath = os.path.dirname(srcpath)
objpath = objpath or '.' # avoid objpath == ''
if os.path.isdir(objpath):
objpath = os.path.join(objpath, name + objext)
include_dirs = kwargs.pop('include_dirs', [])
if inc_py:
py_inc_dir = get_path('include')
if py_inc_dir not in include_dirs:
include_dirs.append(py_inc_dir)
if ext.lower() == '.pyx':
return pyx2obj(srcpath, objpath=objpath, include_dirs=include_dirs, cwd=cwd,
**kwargs)
if Runner is None:
Runner, std = extension_mapping[ext.lower()]
if 'std' not in kwargs:
kwargs['std'] = std
flags = kwargs.pop('flags', [])
needed_flags = ('-fPIC',)
for flag in needed_flags:
if flag not in flags:
flags.append(flag)
# src2obj implies not running the linker...
run_linker = kwargs.pop('run_linker', False)
if run_linker:
raise CompileError("src2obj called with run_linker=True")
runner = Runner([srcpath], objpath, include_dirs=include_dirs,
run_linker=run_linker, cwd=cwd, flags=flags, **kwargs)
runner.run()
return objpath
def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None,
include_dirs=None, cy_kwargs=None, cplus=None, **kwargs):
"""
Convenience function
If cwd is specified, pyxpath and dst are taken to be relative
If only_update is set to `True` the modification time is checked
and compilation is only run if the source is newer than the
destination
Parameters
==========
pyxpath: str
Path to Cython source file.
objpath: str (optional)
Path to object file to generate.
destdir: str (optional)
Directory to put generated C file. When ``None``: directory of ``objpath``.
cwd: str (optional)
Working directory and root of relative paths.
include_dirs: iterable of path strings (optional)
Passed onto src2obj and via cy_kwargs['include_path']
to simple_cythonize.
cy_kwargs: dict (optional)
Keyword arguments passed onto `simple_cythonize`
cplus: bool (optional)
Indicate whether C++ is used. default: auto-detect using ``.util.pyx_is_cplus``.
compile_kwargs: dict
keyword arguments passed onto src2obj
Returns
=======
Absolute path of generated object file.
"""
assert pyxpath.endswith('.pyx')
cwd = cwd or '.'
objpath = objpath or '.'
destdir = destdir or os.path.dirname(objpath)
abs_objpath = get_abspath(objpath, cwd=cwd)
if os.path.isdir(abs_objpath):
pyx_fname = os.path.basename(pyxpath)
name, ext = os.path.splitext(pyx_fname)
objpath = os.path.join(objpath, name + objext)
cy_kwargs = cy_kwargs or {}
cy_kwargs['output_dir'] = cwd
if cplus is None:
cplus = pyx_is_cplus(pyxpath)
cy_kwargs['cplus'] = cplus
interm_c_file = simple_cythonize(pyxpath, destdir=destdir, cwd=cwd, **cy_kwargs)
include_dirs = include_dirs or []
flags = kwargs.pop('flags', [])
needed_flags = ('-fwrapv', '-pthread', '-fPIC')
for flag in needed_flags:
if flag not in flags:
flags.append(flag)
options = kwargs.pop('options', [])
if kwargs.pop('strict_aliasing', False):
raise CompileError("Cython requires strict aliasing to be disabled.")
# Let's be explicit about standard
if cplus:
std = kwargs.pop('std', 'c++98')
else:
std = kwargs.pop('std', 'c99')
return src2obj(interm_c_file, objpath=objpath, cwd=cwd,
include_dirs=include_dirs, flags=flags, std=std,
options=options, inc_py=True, strict_aliasing=False,
**kwargs)
def _any_X(srcs, cls):
for src in srcs:
name, ext = os.path.splitext(src)
key = ext.lower()
if key in extension_mapping:
if extension_mapping[key][0] == cls:
return True
return False
def any_fortran_src(srcs):
return _any_X(srcs, FortranCompilerRunner)
def any_cplus_src(srcs):
return _any_X(srcs, CppCompilerRunner)
def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None,
link_kwargs=None):
""" Compiles sources to a shared object (Python extension) and imports it
Sources in ``sources`` which is imported. If shared object is newer than the sources, they
are not recompiled but instead it is imported.
Parameters
==========
sources : string
List of paths to sources.
extname : string
Name of extension (default: ``None``).
If ``None``: taken from the last file in ``sources`` without extension.
build_dir: str
Path to directory in which objects files etc. are generated.
compile_kwargs: dict
keyword arguments passed to ``compile_sources``
link_kwargs: dict
keyword arguments passed to ``link_py_so``
Returns
=======
The imported module from of the Python extension.
"""
if extname is None:
extname = os.path.splitext(os.path.basename(sources[-1]))[0]
compile_kwargs = compile_kwargs or {}
link_kwargs = link_kwargs or {}
try:
mod = import_module_from_file(os.path.join(build_dir, extname), sources)
except ImportError:
objs = compile_sources(list(map(get_abspath, sources)), destdir=build_dir,
cwd=build_dir, **compile_kwargs)
so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources),
cplus=any_cplus_src(sources), **link_kwargs)
mod = import_module_from_file(so)
return mod
def _write_sources_to_build_dir(sources, build_dir):
build_dir = build_dir or tempfile.mkdtemp()
if not os.path.isdir(build_dir):
raise OSError("Non-existent directory: ", build_dir)
source_files = []
for name, src in sources:
dest = os.path.join(build_dir, name)
differs = True
sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest()
if os.path.exists(dest):
if os.path.exists(dest + '.sha256'):
with open(dest + '.sha256') as fh:
sha256_on_disk = fh.read()
else:
sha256_on_disk = sha256_of_file(dest).hexdigest()
differs = sha256_on_disk != sha256_in_mem
if differs:
with open(dest, 'wt') as fh:
fh.write(src)
with open(dest + '.sha256', 'wt') as fh:
fh.write(sha256_in_mem)
source_files.append(dest)
return source_files, build_dir
def compile_link_import_strings(sources, build_dir=None, **kwargs):
""" Compiles, links and imports extension module from source.
Parameters
==========
sources : iterable of name/source pair tuples
build_dir : string (default: None)
Path. ``None`` implies use a temporary directory.
**kwargs:
Keyword arguments passed onto `compile_link_import_py_ext`.
Returns
=======
mod : module
The compiled and imported extension module.
info : dict
Containing ``build_dir`` as 'build_dir'.
"""
source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
mod = compile_link_import_py_ext(source_files, build_dir=build_dir, **kwargs)
info = dict(build_dir=build_dir)
return mod, info
def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None):
""" Compiles, links and runs a program built from sources.
Parameters
==========
sources : iterable of name/source pair tuples
build_dir : string (default: None)
Path. ``None`` implies use a temporary directory.
clean : bool
Whether to remove build_dir after use. This will only have an
effect if ``build_dir`` is ``None`` (which creates a temporary directory).
Passing ``clean == True`` and ``build_dir != None`` raises a ``ValueError``.
This will also set ``build_dir`` in returned info dictionary to ``None``.
compile_kwargs: dict
Keyword arguments passed onto ``compile_sources``
link_kwargs: dict
Keyword arguments passed onto ``link``
Returns
=======
(stdout, stderr): pair of strings
info: dict
Containing exit status as 'exit_status' and ``build_dir`` as 'build_dir'
"""
if clean and build_dir is not None:
raise ValueError("Automatic removal of build_dir is only available for temporary directory.")
try:
source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
objs = compile_sources(list(map(get_abspath, source_files)), destdir=build_dir,
cwd=build_dir, **(compile_kwargs or {}))
prog = link(objs, cwd=build_dir,
fort=any_fortran_src(source_files),
cplus=any_cplus_src(source_files), **(link_kwargs or {}))
p = subprocess.Popen([prog], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
exit_status = p.wait()
stdout, stderr = [txt.decode('utf-8') for txt in p.communicate()]
finally:
if clean and os.path.isdir(build_dir):
shutil.rmtree(build_dir)
build_dir = None
info = dict(exit_status=exit_status, build_dir=build_dir)
return (stdout, stderr), info
|
e268a3ac363e9dcbef0f81488836891ba07f3a1f102ae942ab97dcad61157d2a | from itertools import product
import math
import inspect
import mpmath
from sympy.testing.pytest import raises, warns_deprecated_sympy
from sympy.concrete.summations import Sum
from sympy.core.function import (Function, Lambda, diff)
from sympy.core.numbers import (E, Float, I, Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.hyperbolic import acosh
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, cos, cot, sin,
sinc, tan)
from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely)
from sympy.functions.special.beta_functions import (beta, betainc, betainc_regularized)
from sympy.functions.special.delta_functions import (Heaviside)
from sympy.functions.special.error_functions import (Ei, erf, erfc, fresnelc, fresnels)
from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma)
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import (And, false, ITE, Not, Or, true)
from sympy.matrices.expressions.dotproduct import DotProduct
from sympy.tensor.array import derive_by_array, Array
from sympy.tensor.indexed import IndexedBase
from sympy.utilities.lambdify import lambdify
from sympy.core.expr import UnevaluatedExpr
from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, log10, hypot
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.scipy_nodes import cosm1
from sympy.functions.elementary.complexes import re, im, arg
from sympy.functions.special.polynomials import \
chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, \
assoc_legendre, assoc_laguerre, jacobi
from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.numpy import NumPyPrinter
from sympy.utilities.lambdify import implemented_function, lambdastr
from sympy.testing.pytest import skip
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.utilities.exceptions import ignore_warnings
from sympy.external import import_module
from sympy.functions.special.gamma_functions import uppergamma, lowergamma
import sympy
MutableDenseMatrix = Matrix
numpy = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
numexpr = import_module('numexpr')
tensorflow = import_module('tensorflow')
cupy = import_module('cupy')
jax = import_module('jax')
numba = import_module('numba')
if tensorflow:
# Hide Tensorflow warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
w, x, y, z = symbols('w,x,y,z')
#================== Test different arguments =======================
def test_no_args():
f = lambdify([], 1)
raises(TypeError, lambda: f(-1))
assert f() == 1
def test_single_arg():
f = lambdify(x, 2*x)
assert f(1) == 2
def test_list_args():
f = lambdify([x, y], x + y)
assert f(1, 2) == 3
def test_nested_args():
f1 = lambdify([[w, x]], [w, x])
assert f1([91, 2]) == [91, 2]
raises(TypeError, lambda: f1(1, 2))
f2 = lambdify([(w, x), (y, z)], [w, x, y, z])
assert f2((18, 12), (73, 4)) == [18, 12, 73, 4]
raises(TypeError, lambda: f2(3, 4))
f3 = lambdify([w, [[[x]], y], z], [w, x, y, z])
assert f3(10, [[[52]], 31], 44) == [10, 52, 31, 44]
def test_str_args():
f = lambdify('x,y,z', 'z,y,x')
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_own_namespace_1():
myfunc = lambda x: 1
f = lambdify(x, sin(x), {"sin": myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_namespace_2():
def myfunc(x):
return 1
f = lambdify(x, sin(x), {'sin': myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_module():
f = lambdify(x, sin(x), math)
assert f(0) == 0.0
p, q, r = symbols("p q r", real=True)
ae = abs(exp(p+UnevaluatedExpr(q+r)))
f = lambdify([p, q, r], [ae, ae], modules=math)
results = f(1.0, 1e18, -1e18)
refvals = [math.exp(1.0)]*2
for res, ref in zip(results, refvals):
assert abs((res-ref)/ref) < 1e-15
def test_bad_args():
# no vargs given
raises(TypeError, lambda: lambdify(1))
# same with vector exprs
raises(TypeError, lambda: lambdify([1, 2]))
def test_atoms():
# Non-Symbol atoms should not be pulled out from the expression namespace
f = lambdify(x, pi + x, {"pi": 3.14})
assert f(0) == 3.14
f = lambdify(x, I + x, {"I": 1j})
assert f(1) == 1 + 1j
#================== Test different modules =========================
# high precision output of sin(0.2*pi) is used to detect if precision is lost unwanted
@conserve_mpmath_dps
def test_sympy_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "sympy")
assert f(x) == sin(x)
prec = 1e-15
assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec
# arctan is in numpy module and should not be available
# The arctan below gives NameError. What is this supposed to test?
# raises(NameError, lambda: lambdify(x, arctan(x), "sympy"))
@conserve_mpmath_dps
def test_math_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "math")
prec = 1e-15
assert -prec < f(0.2) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a Python math function
@conserve_mpmath_dps
def test_mpmath_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a mpmath function
@conserve_mpmath_dps
def test_number_precision():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin02, "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(0) - sin02 < prec
@conserve_mpmath_dps
def test_mpmath_precision():
mpmath.mp.dps = 100
assert str(lambdify((), pi.evalf(100), 'mpmath')()) == str(pi.evalf(100))
#================== Test Translations ==============================
# We can only check if all translated functions are valid. It has to be checked
# by hand if they are complete.
def test_math_transl():
from sympy.utilities.lambdify import MATH_TRANSLATIONS
for sym, mat in MATH_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert mat in math.__dict__
def test_mpmath_transl():
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
for sym, mat in MPMATH_TRANSLATIONS.items():
assert sym in sympy.__dict__ or sym == 'Matrix'
assert mat in mpmath.__dict__
def test_numpy_transl():
if not numpy:
skip("numpy not installed.")
from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
for sym, nump in NUMPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert nump in numpy.__dict__
def test_scipy_transl():
if not scipy:
skip("scipy not installed.")
from sympy.utilities.lambdify import SCIPY_TRANSLATIONS
for sym, scip in SCIPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert scip in scipy.__dict__ or scip in scipy.special.__dict__
def test_numpy_translation_abs():
if not numpy:
skip("numpy not installed.")
f = lambdify(x, Abs(x), "numpy")
assert f(-1) == 1
assert f(1) == 1
def test_numexpr_printer():
if not numexpr:
skip("numexpr not installed.")
# if translation/printing is done incorrectly then evaluating
# a lambdified numexpr expression will throw an exception
from sympy.printing.lambdarepr import NumExprPrinter
blacklist = ('where', 'complex', 'contains')
arg_tuple = (x, y, z) # some functions take more than one argument
for sym in NumExprPrinter._numexpr_functions.keys():
if sym in blacklist:
continue
ssym = S(sym)
if hasattr(ssym, '_nargs'):
nargs = ssym._nargs[0]
else:
nargs = 1
args = arg_tuple[:nargs]
f = lambdify(args, ssym(*args), modules='numexpr')
assert f(*(1, )*nargs) is not None
def test_issue_9334():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
expr = S('b*a - sqrt(a**2)')
a, b = sorted(expr.free_symbols, key=lambda s: s.name)
func_numexpr = lambdify((a,b), expr, modules=[numexpr], dummify=False)
foo, bar = numpy.random.random((2, 4))
func_numexpr(foo, bar)
def test_issue_12984():
if not numexpr:
skip("numexpr not installed.")
func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr)
with ignore_warnings(RuntimeWarning):
assert func_numexpr(1, 24, 42) == 24
assert str(func_numexpr(-1, 24, 42)) == 'nan'
def test_empty_modules():
x, y = symbols('x y')
expr = -(x % y)
no_modules = lambdify([x, y], expr)
empty_modules = lambdify([x, y], expr, modules=[])
assert no_modules(3, 7) == empty_modules(3, 7)
assert no_modules(3, 7) == -3
def test_exponentiation():
f = lambdify(x, x**2)
assert f(-1) == 1
assert f(0) == 0
assert f(1) == 1
assert f(-2) == 4
assert f(2) == 4
assert f(2.5) == 6.25
def test_sqrt():
f = lambdify(x, sqrt(x))
assert f(0) == 0.0
assert f(1) == 1.0
assert f(4) == 2.0
assert abs(f(2) - 1.414) < 0.001
assert f(6.25) == 2.5
def test_trig():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
prec = 1e-11
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
d = f(3.14159)
prec = 1e-5
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
def test_integral():
if numpy and not scipy:
skip("scipy not installed.")
f = Lambda(x, exp(-x**2))
l = lambdify(y, Integral(f(x), (x, y, oo)))
d = l(-oo)
assert 1.77245385 < d < 1.772453851
def test_double_integral():
if numpy and not scipy:
skip("scipy not installed.")
# example from http://mpmath.org/doc/current/calculus/integration.html
i = Integral(1/(1 - x**2*y**2), (x, 0, 1), (y, 0, z))
l = lambdify([z], i)
d = l(1)
assert 1.23370055 < d < 1.233700551
#================== Test vectors ===================================
def test_vector_simple():
f = lambdify((x, y, z), (z, y, x))
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_vector_discontinuous():
f = lambdify(x, (-1/x, 1/x))
raises(ZeroDivisionError, lambda: f(0))
assert f(1) == (-1.0, 1.0)
assert f(2) == (-0.5, 0.5)
assert f(-2) == (0.5, -0.5)
def test_trig_symbolic():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_trig_float():
f = lambdify([x], [cos(x), sin(x)])
d = f(3.14159)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_docs():
f = lambdify(x, x**2)
assert f(2) == 4
f = lambdify([x, y, z], [z, y, x])
assert f(1, 2, 3) == [3, 2, 1]
f = lambdify(x, sqrt(x))
assert f(4) == 2.0
f = lambdify((x, y), sin(x*y)**2)
assert f(0, 5) == 0
def test_math():
f = lambdify((x, y), sin(x), modules="math")
assert f(0, 5) == 0
def test_sin():
f = lambdify(x, sin(x)**2)
assert isinstance(f(2), float)
f = lambdify(x, sin(x)**2, modules="math")
assert isinstance(f(2), float)
def test_matrix():
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol = Matrix([[1, 2], [sin(3) + 4, 1]])
f = lambdify((x, y, z), A, modules="sympy")
assert f(1, 2, 3) == sol
f = lambdify((x, y, z), (A, [A]), modules="sympy")
assert f(1, 2, 3) == (sol, [sol])
J = Matrix((x, x + y)).jacobian((x, y))
v = Matrix((x, y))
sol = Matrix([[1, 0], [1, 1]])
assert lambdify(v, J, modules='sympy')(1, 2) == sol
assert lambdify(v.T, J, modules='sympy')(1, 2) == sol
def test_numpy_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
#Lambdify array first, to ensure return to array as default
f = lambdify((x, y, z), A, ['numpy'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
#Check that the types are arrays and matrices
assert isinstance(f(1, 2, 3), numpy.ndarray)
# gh-15071
class dot(Function):
pass
x_dot_mtx = dot(x, Matrix([[2], [1], [0]]))
f_dot1 = lambdify(x, x_dot_mtx)
inp = numpy.zeros((17, 3))
assert numpy.all(f_dot1(inp) == 0)
strict_kw = dict(allow_unknown_functions=False, inline=True, fully_qualified_modules=False)
p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw))
f_dot2 = lambdify(x, x_dot_mtx, printer=p2)
assert numpy.all(f_dot2(inp) == 0)
p3 = NumPyPrinter(strict_kw)
# The line below should probably fail upon construction (before calling with "(inp)"):
raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp))
def test_numpy_transpose():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A.T, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]]))
def test_numpy_dotproduct():
if not numpy:
skip("numpy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='numpy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='numpy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
numpy.array([14])
def test_numpy_inverse():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A**-1, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]]))
def test_numpy_old_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy'])
with ignore_warnings(PendingDeprecationWarning):
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.matrix)
def test_scipy_sparse_matrix():
if not scipy:
skip("scipy not installed.")
A = SparseMatrix([[x, 0], [0, y]])
f = lambdify((x, y), A, modules="scipy")
B = f(1, 2)
assert isinstance(B, scipy.sparse.coo_matrix)
def test_python_div_zero_issue_11306():
if not numpy:
skip("numpy not installed.")
p = Piecewise((1 / x, y < -1), (x, y < 1), (1 / x, True))
f = lambdify([x, y], p, modules='numpy')
numpy.seterr(divide='ignore')
assert float(f(numpy.array([0]),numpy.array([0.5]))) == 0
assert str(float(f(numpy.array([0]),numpy.array([1])))) == 'inf'
numpy.seterr(divide='warn')
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 test_issue_9871():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
r = sqrt(x**2 + y**2)
expr = diff(1/r, x)
xn = yn = numpy.linspace(1, 10, 16)
# expr(xn, xn) = -xn/(sqrt(2)*xn)^3
fv_exact = -numpy.sqrt(2.)**-3 * xn**-2
fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn)
fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn)
numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10)
numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10)
def test_numpy_piecewise():
if not numpy:
skip("numpy not installed.")
pieces = Piecewise((x, x < 3), (x**2, x > 5), (0, True))
f = lambdify(x, pieces, modules="numpy")
numpy.testing.assert_array_equal(f(numpy.arange(10)),
numpy.array([0, 1, 2, 0, 0, 0, 36, 49, 64, 81]))
# If we evaluate somewhere all conditions are False, we should get back NaN
nodef_func = lambdify(x, Piecewise((x, x > 0), (-x, x < 0)))
numpy.testing.assert_array_equal(nodef_func(numpy.array([-1, 0, 1])),
numpy.array([1, numpy.nan, 1]))
def test_numpy_logical_ops():
if not numpy:
skip("numpy not installed.")
and_func = lambdify((x, y), And(x, y), modules="numpy")
and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy")
or_func = lambdify((x, y), Or(x, y), modules="numpy")
or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy")
not_func = lambdify((x), Not(x), modules="numpy")
arr1 = numpy.array([True, True])
arr2 = numpy.array([False, True])
arr3 = numpy.array([True, False])
numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True]))
numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False]))
numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True]))
numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True]))
numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
def test_numpy_matmul():
if not numpy:
skip("numpy not installed.")
xmat = Matrix([[x, y], [z, 1+z]])
ymat = Matrix([[x**2], [Abs(x)]])
mat_func = lambdify((x, y, z), xmat*ymat, modules="numpy")
numpy.testing.assert_array_equal(mat_func(0.5, 3, 4), numpy.array([[1.625], [3.5]]))
numpy.testing.assert_array_equal(mat_func(-0.5, 3, 4), numpy.array([[1.375], [3.5]]))
# Multiple matrices chained together in multiplication
f = lambdify((x, y, z), xmat*xmat*xmat, modules="numpy")
numpy.testing.assert_array_equal(f(0.5, 3, 4), numpy.array([[72.125, 119.25],
[159, 251]]))
def test_numpy_numexpr():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b, c = numpy.random.randn(3, 128, 128)
# ensure that numpy and numexpr return same value for complicated expression
expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \
Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2)
npfunc = lambdify((x, y, z), expr, modules='numpy')
nefunc = lambdify((x, y, z), expr, modules='numexpr')
assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c))
def test_numexpr_userfunctions():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b = numpy.random.randn(2, 10)
uf = type('uf', (Function, ),
{'eval' : classmethod(lambda x, y : y**2+1)})
func = lambdify(x, 1-uf(x), modules='numexpr')
assert numpy.allclose(func(a), -(a**2))
uf = implemented_function(Function('uf'), lambda x, y : 2*x*y+1)
func = lambdify((x, y), uf(x, y), modules='numexpr')
assert numpy.allclose(func(a, b), 2*a*b+1)
def test_tensorflow_basic_math():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.constant(0, dtype=tensorflow.float32)
assert func(a).eval(session=s) == 0.5
def test_tensorflow_placeholders():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.compat.v1.placeholder(dtype=tensorflow.float32)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_variables():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.Variable(0, dtype=tensorflow.float32)
s.run(a.initializer)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_logical_operations():
if not tensorflow:
skip("tensorflow not installed.")
expr = Not(And(Or(x, y), y))
func = lambdify([x, y], expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(False, True).eval(session=s) == False
def test_tensorflow_piecewise():
if not tensorflow:
skip("tensorflow not installed.")
expr = Piecewise((0, Eq(x,0)), (-1, x < 0), (1, x > 0))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-1).eval(session=s) == -1
assert func(0).eval(session=s) == 0
assert func(1).eval(session=s) == 1
def test_tensorflow_multi_max():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == 4
def test_tensorflow_multi_min():
if not tensorflow:
skip("tensorflow not installed.")
expr = Min(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == -2
def test_tensorflow_relational():
if not tensorflow:
skip("tensorflow not installed.")
expr = x >= 0
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(1).eval(session=s) == True
def test_tensorflow_complexes():
if not tensorflow:
skip("tensorflow not installed")
func1 = lambdify(x, re(x), modules="tensorflow")
func2 = lambdify(x, im(x), modules="tensorflow")
func3 = lambdify(x, Abs(x), modules="tensorflow")
func4 = lambdify(x, arg(x), modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
# For versions before
# https://github.com/tensorflow/tensorflow/issues/30029
# resolved, using Python numeric types may not work
a = tensorflow.constant(1+2j)
assert func1(a).eval(session=s) == 1
assert func2(a).eval(session=s) == 2
tensorflow_result = func3(a).eval(session=s)
sympy_result = Abs(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
tensorflow_result = func4(a).eval(session=s)
sympy_result = arg(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
def test_tensorflow_array_arg():
# Test for issue 14655 (tensorflow part)
if not tensorflow:
skip("tensorflow not installed.")
f = lambdify([[x, y]], x*x + y, 'tensorflow')
with tensorflow.compat.v1.Session() as s:
fcall = f(tensorflow.constant([2.0, 1.0]))
assert fcall.eval(session=s) == 5.0
#================== Test symbolic ==================================
def test_sym_single_arg():
f = lambdify(x, x * y)
assert f(z) == z * y
def test_sym_list_args():
f = lambdify([x, y], x + y + z)
assert f(1, 2) == 3 + z
def test_sym_integral():
f = Lambda(x, exp(-x**2))
l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
assert l(y) == Integral(exp(-y**2), (y, -oo, oo))
assert l(y).doit() == sqrt(pi)
def test_namespace_order():
# lambdify had a bug, such that module dictionaries or cached module
# dictionaries would pull earlier namespaces into themselves.
# Because the module dictionaries form the namespace of the
# generated lambda, this meant that the behavior of a previously
# generated lambda function could change as a result of later calls
# to lambdify.
n1 = {'f': lambda x: 'first f'}
n2 = {'f': lambda x: 'second f',
'g': lambda x: 'function g'}
f = sympy.Function('f')
g = sympy.Function('g')
if1 = lambdify(x, f(x), modules=(n1, "sympy"))
assert if1(1) == 'first f'
if2 = lambdify(x, g(x), modules=(n2, "sympy"))
# previously gave 'second f'
assert if1(1) == 'first f'
assert if2(1) == 'function g'
def test_imps():
# Here we check if the default returned functions are anonymous - in
# the sense that we can have more than one function with the same name
f = implemented_function('f', lambda x: 2*x)
g = implemented_function('f', lambda x: math.sqrt(x))
l1 = lambdify(x, f(x))
l2 = lambdify(x, g(x))
assert str(f(x)) == str(g(x))
assert l1(3) == 6
assert l2(3) == math.sqrt(3)
# check that we can pass in a Function as input
func = sympy.Function('myfunc')
assert not hasattr(func, '_imp_')
my_f = implemented_function(func, lambda x: 2*x)
assert hasattr(my_f, '_imp_')
# Error for functions with same name and different implementation
f2 = implemented_function("f", lambda x: x + 101)
raises(ValueError, lambda: lambdify(x, f(f2(x))))
def test_imps_errors():
# Test errors that implemented functions can return, and still be able to
# form expressions.
# See: https://github.com/sympy/sympy/issues/10810
#
# XXX: Removed AttributeError here. This test was added due to issue 10810
# but that issue was about ValueError. It doesn't seem reasonable to
# "support" catching AttributeError in the same context...
for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)):
def myfunc(a):
if a == 0:
raise error_class
return 1
f = implemented_function('f', myfunc)
expr = f(val)
assert expr == f(val)
def test_imps_wrong_args():
raises(ValueError, lambda: implemented_function(sin, lambda x: x))
def test_lambdify_imps():
# Test lambdify with implemented functions
# first test basic (sympy) lambdify
f = sympy.cos
assert lambdify(x, f(x))(0) == 1
assert lambdify(x, 1 + f(x))(0) == 2
assert lambdify((x, y), y + f(x))(0, 1) == 2
# make an implemented function and test
f = implemented_function("f", lambda x: x + 100)
assert lambdify(x, f(x))(0) == 100
assert lambdify(x, 1 + f(x))(0) == 101
assert lambdify((x, y), y + f(x))(0, 1) == 101
# Can also handle tuples, lists, dicts as expressions
lam = lambdify(x, (f(x), x))
assert lam(3) == (103, 3)
lam = lambdify(x, [f(x), x])
assert lam(3) == [103, 3]
lam = lambdify(x, [f(x), (f(x), x)])
assert lam(3) == [103, (103, 3)]
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {x: f(x)})
assert lam(3) == {3: 103}
# Check that imp preferred to other namespaces by default
d = {'f': lambda x: x + 99}
lam = lambdify(x, f(x), d)
assert lam(3) == 103
# Unless flag passed
lam = lambdify(x, f(x), d, use_imps=False)
assert lam(3) == 102
def test_dummification():
t = symbols('t')
F = Function('F')
G = Function('G')
#"\alpha" is not a valid Python variable name
#lambdify should sub in a dummy for it, and return
#without a syntax error
alpha = symbols(r'\alpha')
some_expr = 2 * F(t)**2 / G(t)
lam = lambdify((F(t), G(t)), some_expr)
assert lam(3, 9) == 2
lam = lambdify(sin(t), 2 * sin(t)**2)
assert lam(F(t)) == 2 * F(t)**2
#Test that \alpha was properly dummified
lam = lambdify((alpha, t), 2*alpha + t)
assert lam(2, 1) == 5
raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5))
def test_curly_matrix_symbol():
# Issue #15009
curlyv = sympy.MatrixSymbol("{v}", 2, 1)
lam = lambdify(curlyv, curlyv)
assert lam(1)==1
lam = lambdify(curlyv, curlyv, dummify=True)
assert lam(1)==1
def test_python_keywords():
# Test for issue 7452. The automatic dummification should ensure use of
# Python reserved keywords as symbol names will create valid lambda
# functions. This is an additional regression test.
python_if = symbols('if')
expr = python_if / 2
f = lambdify(python_if, expr)
assert f(4.0) == 2.0
def test_lambdify_docstring():
func = lambdify((w, x, y, z), w + x + y + z)
ref = (
"Created with lambdify. Signature:\n\n"
"func(w, x, y, z)\n\n"
"Expression:\n\n"
"w + x + y + z"
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
syms = symbols('a1:26')
func = lambdify(syms, sum(syms))
ref = (
"Created with lambdify. Signature:\n\n"
"func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n"
" a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n"
"Expression:\n\n"
"a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..."
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
#================== Test special printers ==========================
def test_special_printers():
from sympy.printing.lambdarepr import IntervalPrinter
def intervalrepr(expr):
return IntervalPrinter().doprint(expr)
expr = sqrt(sqrt(2) + sqrt(3)) + S.Half
func0 = lambdify((), expr, modules="mpmath", printer=intervalrepr)
func1 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter)
func2 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter())
mpi = type(mpmath.mpi(1, 2))
assert isinstance(func0(), mpi)
assert isinstance(func1(), mpi)
assert isinstance(func2(), mpi)
# To check Is lambdify loggamma works for mpmath or not
exp1 = lambdify(x, loggamma(x), 'mpmath')(5)
exp2 = lambdify(x, loggamma(x), 'mpmath')(1.8)
exp3 = lambdify(x, loggamma(x), 'mpmath')(15)
exp_ls = [exp1, exp2, exp3]
sol1 = mpmath.loggamma(5)
sol2 = mpmath.loggamma(1.8)
sol3 = mpmath.loggamma(15)
sol_ls = [sol1, sol2, sol3]
assert exp_ls == sol_ls
def test_true_false():
# We want exact is comparison here, not just ==
assert lambdify([], true)() is True
assert lambdify([], false)() is False
def test_issue_2790():
assert lambdify((x, (y, z)), x + y)(1, (2, 4)) == 3
assert lambdify((x, (y, (w, z))), w + x + y + z)(1, (2, (3, 4))) == 10
assert lambdify(x, x + 1, dummify=False)(1) == 2
def test_issue_12092():
f = implemented_function('f', lambda x: x**2)
assert f(f(2)).evalf() == Float(16)
def test_issue_14911():
class Variable(sympy.Symbol):
def _sympystr(self, printer):
return printer.doprint(self.name)
_lambdacode = _sympystr
_numpycode = _sympystr
x = Variable('x')
y = 2 * x
code = LambdaPrinter().doprint(y)
assert code.replace(' ', '') == '2*x'
def test_ITE():
assert lambdify((x, y, z), ITE(x, y, z))(True, 5, 3) == 5
assert lambdify((x, y, z), ITE(x, y, z))(False, 5, 3) == 3
def test_Min_Max():
# see gh-10375
assert lambdify((x, y, z), Min(x, y, z))(1, 2, 3) == 1
assert lambdify((x, y, z), Max(x, y, z))(1, 2, 3) == 3
def test_Indexed():
# Issue #10934
if not numpy:
skip("numpy not installed")
a = IndexedBase('a')
i, j = symbols('i j')
b = numpy.array([[1, 2], [3, 4]])
assert lambdify(a, Sum(a[x, y], (x, 0, 1), (y, 0, 1)))(b) == 10
def test_issue_12173():
#test for issue 12173
expr1 = lambdify((x, y), uppergamma(x, y),"mpmath")(1, 2)
expr2 = lambdify((x, y), lowergamma(x, y),"mpmath")(1, 2)
assert expr1 == uppergamma(1, 2).evalf()
assert expr2 == lowergamma(1, 2).evalf()
def test_issue_13642():
if not numpy:
skip("numpy not installed")
f = lambdify(x, sinc(x))
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_sinc_mpmath():
f = lambdify(x, sinc(x), "mpmath")
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_lambdify_dummy_arg():
d1 = Dummy()
f1 = lambdify(d1, d1 + 1, dummify=False)
assert f1(2) == 3
f1b = lambdify(d1, d1 + 1)
assert f1b(2) == 3
d2 = Dummy('x')
f2 = lambdify(d2, d2 + 1)
assert f2(2) == 3
f3 = lambdify([[d2]], d2 + 1)
assert f3([2]) == 3
def test_lambdify_mixed_symbol_dummy_args():
d = Dummy()
# Contrived example of name clash
dsym = symbols(str(d))
f = lambdify([d, dsym], d - dsym)
assert f(4, 1) == 3
def test_numpy_array_arg():
# Test for issue 14655 (numpy part)
if not numpy:
skip("numpy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
assert f(numpy.array([2.0, 1.0])) == 5
def test_scipy_fns():
if not scipy:
skip("scipy not installed")
single_arg_sympy_fns = [Ei, erf, erfc, factorial, gamma, loggamma, digamma]
single_arg_scipy_fns = [scipy.special.expi, scipy.special.erf, scipy.special.erfc,
scipy.special.factorial, scipy.special.gamma, scipy.special.gammaln,
scipy.special.psi]
numpy.random.seed(0)
for (sympy_fn, scipy_fn) in zip(single_arg_sympy_fns, single_arg_scipy_fns):
f = lambdify(x, sympy_fn(x), modules="scipy")
for i in range(20):
tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy thinks that factorial(z) is 0 when re(z) < 0 and
# does not support complex numbers.
# SymPy does not think so.
if sympy_fn == factorial:
tv = numpy.abs(tv)
# SciPy supports gammaln for real arguments only,
# and there is also a branch cut along the negative real axis
if sympy_fn == loggamma:
tv = numpy.abs(tv)
# SymPy's digamma evaluates as polygamma(0, z)
# which SciPy supports for real arguments only
if sympy_fn == digamma:
tv = numpy.real(tv)
sympy_result = sympy_fn(tv).evalf()
assert abs(f(tv) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv) - scipy_fn(tv)) < 1e-13*(1 + abs(sympy_result))
double_arg_sympy_fns = [RisingFactorial, besselj, bessely, besseli,
besselk]
double_arg_scipy_fns = [scipy.special.poch, scipy.special.jv,
scipy.special.yv, scipy.special.iv, scipy.special.kv]
for (sympy_fn, scipy_fn) in zip(double_arg_sympy_fns, double_arg_scipy_fns):
f = lambdify((x, y), sympy_fn(x, y), modules="scipy")
for i in range(20):
# SciPy supports only real orders of Bessel functions
tv1 = numpy.random.uniform(-10, 10)
tv2 = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy supports poch for real arguments only
if sympy_fn == RisingFactorial:
tv2 = numpy.real(tv2)
sympy_result = sympy_fn(tv1, tv2).evalf()
assert abs(f(tv1, tv2) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv1, tv2) - scipy_fn(tv1, tv2)) < 1e-13*(1 + abs(sympy_result))
def test_scipy_polys():
if not scipy:
skip("scipy not installed")
numpy.random.seed(0)
params = symbols('n k a b')
# list polynomials with the number of parameters
polys = [
(chebyshevt, 1),
(chebyshevu, 1),
(legendre, 1),
(hermite, 1),
(laguerre, 1),
(gegenbauer, 2),
(assoc_legendre, 2),
(assoc_laguerre, 2),
(jacobi, 3)
]
msg = \
"The random test of the function {func} with the arguments " \
"{args} had failed because the SymPy result {sympy_result} " \
"and SciPy result {scipy_result} had failed to converge " \
"within the tolerance {tol} " \
"(Actual absolute difference : {diff})"
for sympy_fn, num_params in polys:
args = params[:num_params] + (x,)
f = lambdify(args, sympy_fn(*args))
for _ in range(10):
tn = numpy.random.randint(3, 10)
tparams = tuple(numpy.random.uniform(0, 5, size=num_params-1))
tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy supports hermite for real arguments only
if sympy_fn == hermite:
tv = numpy.real(tv)
# assoc_legendre needs x in (-1, 1) and integer param at most n
if sympy_fn == assoc_legendre:
tv = numpy.random.uniform(-1, 1)
tparams = tuple(numpy.random.randint(1, tn, size=1))
vals = (tn,) + tparams + (tv,)
scipy_result = f(*vals)
sympy_result = sympy_fn(*vals).evalf()
atol = 1e-9*(1 + abs(sympy_result))
diff = abs(scipy_result - sympy_result)
try:
assert diff < atol
except TypeError:
raise AssertionError(
msg.format(
func=repr(sympy_fn),
args=repr(vals),
sympy_result=repr(sympy_result),
scipy_result=repr(scipy_result),
diff=diff,
tol=atol)
)
def test_lambdify_inspect():
f = lambdify(x, x**2)
# Test that inspect.getsource works but don't hard-code implementation
# details
assert 'x**2' in inspect.getsource(f)
def test_issue_14941():
x, y = Dummy(), Dummy()
# test dict
f1 = lambdify([x, y], {x: 3, y: 3}, 'sympy')
assert f1(2, 3) == {2: 3, 3: 3}
# test tuple
f2 = lambdify([x, y], (y, x), 'sympy')
assert f2(2, 3) == (3, 2)
f2b = lambdify([], (1,)) # gh-23224
assert f2b() == (1,)
# test list
f3 = lambdify([x, y], [y, x], 'sympy')
assert f3(2, 3) == [3, 2]
def test_lambdify_Derivative_arg_issue_16468():
f = Function('f')(x)
fx = f.diff()
assert lambdify((f, fx), f + fx)(10, 5) == 15
assert eval(lambdastr((f, fx), f/fx))(10, 5) == 2
raises(SyntaxError, lambda:
eval(lambdastr((f, fx), f/fx, dummify=False)))
assert eval(lambdastr((f, fx), f/fx, dummify=True))(10, 5) == 2
assert eval(lambdastr((fx, f), f/fx, dummify=True))(S(10), 5) == S.Half
assert lambdify(fx, 1 + fx)(41) == 42
assert eval(lambdastr(fx, 1 + fx, dummify=True))(41) == 42
def test_imag_real():
f_re = lambdify([z], sympy.re(z))
val = 3+2j
assert f_re(val) == val.real
f_im = lambdify([z], sympy.im(z)) # see #15400
assert f_im(val) == val.imag
def test_MatrixSymbol_issue_15578():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol('A', 2, 2)
A0 = numpy.array([[1, 2], [3, 4]])
f = lambdify(A, A**(-1))
assert numpy.allclose(f(A0), numpy.array([[-2., 1.], [1.5, -0.5]]))
g = lambdify(A, A**3)
assert numpy.allclose(g(A0), numpy.array([[37, 54], [81, 118]]))
def test_issue_15654():
if not scipy:
skip("scipy not installed")
from sympy.abc import n, l, r, Z
from sympy.physics import hydrogen
nv, lv, rv, Zv = 1, 0, 3, 1
sympy_value = hydrogen.R_nl(nv, lv, rv, Zv).evalf()
f = lambdify((n, l, r, Z), hydrogen.R_nl(n, l, r, Z))
scipy_value = f(nv, lv, rv, Zv)
assert abs(sympy_value - scipy_value) < 1e-15
def test_issue_15827():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 2, 3)
C = MatrixSymbol("C", 3, 4)
D = MatrixSymbol("D", 4, 5)
k=symbols("k")
f = lambdify(A, (2*k)*A)
g = lambdify(A, (2+k)*A)
h = lambdify(A, 2*A)
i = lambdify((B, C, D), 2*B*C*D)
assert numpy.array_equal(f(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2*k, 4*k, 6*k], [2*k, 4*k, 6*k], [2*k, 4*k, 6*k]], dtype=object))
assert numpy.array_equal(g(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[k + 2, 2*k + 4, 3*k + 6], [k + 2, 2*k + 4, 3*k + 6], \
[k + 2, 2*k + 4, 3*k + 6]], dtype=object))
assert numpy.array_equal(h(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2, 4, 6], [2, 4, 6], [2, 4, 6]]))
assert numpy.array_equal(i(numpy.array([[1, 2, 3], [1, 2, 3]]), numpy.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]), \
numpy.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])), numpy.array([[ 120, 240, 360, 480, 600], \
[ 120, 240, 360, 480, 600]]))
def test_issue_16930():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f = lambda x: S.GoldenRatio * x**2
f_ = lambdify(x, f(x), modules='scipy')
assert f_(1) == scipy.constants.golden_ratio
def test_issue_17898():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f_ = lambdify([x], sympy.LambertW(x,-1), modules='scipy')
assert f_(0.1) == mpmath.lambertw(0.1, -1)
def test_issue_13167_21411():
if not numpy:
skip("numpy not installed")
f1 = lambdify(x, sympy.Heaviside(x))
f2 = lambdify(x, sympy.Heaviside(x, 1))
res1 = f1([-1, 0, 1])
res2 = f2([-1, 0, 1])
assert Abs(res1[0]).n() < 1e-15 # First functionality: only one argument passed
assert Abs(res1[1] - 1/2).n() < 1e-15
assert Abs(res1[2] - 1).n() < 1e-15
assert Abs(res2[0]).n() < 1e-15 # Second functionality: two arguments passed
assert Abs(res2[1] - 1).n() < 1e-15
assert Abs(res2[2] - 1).n() < 1e-15
def test_single_e():
f = lambdify(x, E)
assert f(23) == exp(1.0)
def test_issue_16536():
if not scipy:
skip("scipy not installed")
a = symbols('a')
f1 = lowergamma(a, x)
F = lambdify((a, x), f1, modules='scipy')
assert abs(lowergamma(1, 3) - F(1, 3)) <= 1e-10
f2 = uppergamma(a, x)
F = lambdify((a, x), f2, modules='scipy')
assert abs(uppergamma(1, 3) - F(1, 3)) <= 1e-10
def test_issue_22726():
if not numpy:
skip("numpy not installed")
x1, x2 = symbols('x1 x2')
f = Max(S.Zero, Min(x1, x2))
g = derive_by_array(f, (x1, x2))
G = lambdify((x1, x2), g, modules='numpy')
point = {x1: 1, x2: 2}
assert (abs(g.subs(point) - G(*point.values())) <= 1e-10).all()
def test_issue_22739():
if not numpy:
skip("numpy not installed")
x1, x2 = symbols('x1 x2')
f = Heaviside(Min(x1, x2))
F = lambdify((x1, x2), f, modules='numpy')
point = {x1: 1, x2: 2}
assert abs(f.subs(point) - F(*point.values())) <= 1e-10
def test_issue_22992():
if not numpy:
skip("numpy not installed")
a, t = symbols('a t')
expr = a*(log(cot(t/2)) - cos(t))
F = lambdify([a, t], expr, 'numpy')
point = {a: 10, t: 2}
assert abs(expr.subs(point) - F(*point.values())) <= 1e-10
# Standard math
F = lambdify([a, t], expr)
assert abs(expr.subs(point) - F(*point.values())) <= 1e-10
def test_issue_19764():
if not numpy:
skip("numpy not installed")
expr = Array([x, x**2])
f = lambdify(x, expr, 'numpy')
assert f(1).__class__ == numpy.ndarray
def test_issue_20070():
if not numba:
skip("numba not installed")
f = lambdify(x, sin(x), 'numpy')
assert numba.jit(f)(1)==0.8414709848078965
def test_fresnel_integrals_scipy():
if not scipy:
skip("scipy not installed")
f1 = fresnelc(x)
f2 = fresnels(x)
F1 = lambdify(x, f1, modules='scipy')
F2 = lambdify(x, f2, modules='scipy')
assert abs(fresnelc(1.3) - F1(1.3)) <= 1e-10
assert abs(fresnels(1.3) - F2(1.3)) <= 1e-10
def test_beta_scipy():
if not scipy:
skip("scipy not installed")
f = beta(x, y)
F = lambdify((x, y), f, modules='scipy')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_beta_math():
f = beta(x, y)
F = lambdify((x, y), f, modules='math')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_betainc_scipy():
if not scipy:
skip("scipy not installed")
f = betainc(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc(1.4, 3.1, 0.1, 0.5) - F(1.4, 3.1, 0.1, 0.5)) <= 1e-10
def test_betainc_regularized_scipy():
if not scipy:
skip("scipy not installed")
f = betainc_regularized(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc_regularized(0.2, 3.5, 0.1, 1) - F(0.2, 3.5, 0.1, 1)) <= 1e-10
def test_numpy_special_math():
if not numpy:
skip("numpy not installed")
funcs = [expm1, log1p, exp2, log2, log10, hypot, logaddexp, logaddexp2]
for func in funcs:
if 2 in func.nargs:
expr = func(x, y)
args = (x, y)
num_args = (0.3, 0.4)
elif 1 in func.nargs:
expr = func(x)
args = (x,)
num_args = (0.3,)
else:
raise NotImplementedError("Need to handle other than unary & binary functions in test")
f = lambdify(args, expr)
result = f(*num_args)
reference = expr.subs(dict(zip(args, num_args))).evalf()
assert numpy.allclose(result, float(reference))
lae2 = lambdify((x, y), logaddexp2(log2(x), log2(y)))
assert abs(2.0**lae2(1e-50, 2.5e-50) - 3.5e-50) < 1e-62 # from NumPy's docstring
def test_scipy_special_math():
if not scipy:
skip("scipy not installed")
cm1 = lambdify((x,), cosm1(x), modules='scipy')
assert abs(cm1(1e-20) + 5e-41) < 1e-200
def test_scipy_bernoulli():
if not scipy:
skip("scipy not installed")
bern = lambdify((x,), bernoulli(x), modules='scipy')
assert bern(1) == 0.5
def test_scipy_harmonic():
if not scipy:
skip("scipy not installed")
hn = lambdify((x,), harmonic(x), modules='scipy')
assert hn(2) == 1.5
hnm = lambdify((x, y), harmonic(x, y), modules='scipy')
assert hnm(2, 2) == 1.25
def test_cupy_array_arg():
if not cupy:
skip("CuPy not installed")
f = lambdify([[x, y]], x*x + y, 'cupy')
result = f(cupy.array([2.0, 1.0]))
assert result == 5
assert "cupy" in str(type(result))
def test_cupy_array_arg_using_numpy():
# numpy functions can be run on cupy arrays
# unclear if we can "officialy" support this,
# depends on numpy __array_function__ support
if not cupy:
skip("CuPy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
result = f(cupy.array([2.0, 1.0]))
assert result == 5
assert "cupy" in str(type(result))
def test_cupy_dotproduct():
if not cupy:
skip("CuPy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='cupy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='cupy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
cupy.array([14])
def test_jax_array_arg():
if not jax:
skip("JAX not installed")
f = lambdify([[x, y]], x*x + y, 'jax')
result = f(jax.numpy.array([2.0, 1.0]))
assert result == 5
assert "jax" in str(type(result))
def test_jax_array_arg_using_numpy():
if not jax:
skip("JAX not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
result = f(jax.numpy.array([2.0, 1.0]))
assert result == 5
assert "jax" in str(type(result))
def test_jax_dotproduct():
if not jax:
skip("JAX not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='jax')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='jax')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
jax.numpy.array([14])
def test_lambdify_cse():
def dummy_cse(exprs):
return (), exprs
def minmem(exprs):
from sympy.simplify.cse_main import cse_release_variables, cse
return cse(exprs, postprocess=cse_release_variables)
class Case:
def __init__(self, *, args, exprs, num_args, requires_numpy=False):
self.args = args
self.exprs = exprs
self.num_args = num_args
subs_dict = dict(zip(self.args, self.num_args))
self.ref = [e.subs(subs_dict).evalf() for e in exprs]
self.requires_numpy = requires_numpy
def lambdify(self, *, cse):
return lambdify(self.args, self.exprs, cse=cse)
def assertAllClose(self, result, *, abstol=1e-15, reltol=1e-15):
if self.requires_numpy:
assert all(numpy.allclose(result[i], numpy.asarray(r, dtype=float),
rtol=reltol, atol=abstol)
for i, r in enumerate(self.ref))
return
for i, r in enumerate(self.ref):
abs_err = abs(result[i] - r)
if r == 0:
assert abs_err < abstol
else:
assert abs_err/abs(r) < reltol
cases = [
Case(
args=(x, y, z),
exprs=[
x + y + z,
x + y - z,
2*x + 2*y - z,
(x+y)**2 + (y+z)**2,
],
num_args=(2., 3., 4.)
),
Case(
args=(x, y, z),
exprs=[
x + sympy.Heaviside(x),
y + sympy.Heaviside(x),
z + sympy.Heaviside(x, 1),
z/sympy.Heaviside(x, 1)
],
num_args=(0., 3., 4.)
),
Case(
args=(x, y, z),
exprs=[
x + sinc(y),
y + sinc(y),
z - sinc(y)
],
num_args=(0.1, 0.2, 0.3)
),
Case(
args=(x, y, z),
exprs=[
Matrix([[x, x*y], [sin(z) + 4, x**z]]),
x*y+sin(z)-x**z,
Matrix([x*x, sin(z), x**z])
],
num_args=(1.,2.,3.),
requires_numpy=True
),
Case(
args=(x, y),
exprs=[(x + y - 1)**2, x, x + y,
(x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)],
num_args=(1,2)
)
]
for case in cases:
if not numpy and case.requires_numpy:
continue
for cse in [False, True, minmem, dummy_cse]:
f = case.lambdify(cse=cse)
result = f(*case.num_args)
case.assertAllClose(result)
def test_deprecated_set():
with warns_deprecated_sympy():
lambdify({x, y}, x + y)
def test_23536_lambdify_cse_dummy():
f = Function('x')(y)
g = Function('w')(y)
expr = z + (f**4 + g**5)*(f**3 + (g*f)**3)
expr = expr.expand()
eval_expr = lambdify(((f, g), z), expr, cse=True)
ans = eval_expr((1.0, 2.0), 3.0) # shouldn't raise NameError
assert ans == 300.0 # not a list and value is 300
|
fcc8574f3afc9ac78abfda2ccdc554046a3d1f2594959ed7264e36fbfbb71340 | """ Tests from Michael Wester's 1999 paper "Review of CAS mathematical
capabilities".
http://www.math.unm.edu/~wester/cas/book/Wester.pdf
See also http://math.unm.edu/~wester/cas_review.html for detailed output of
each tested system.
"""
from sympy.assumptions.ask import Q, ask
from sympy.assumptions.refine import refine
from sympy.concrete.products import product
from sympy.core import EulerGamma
from sympy.core.evalf import N
from sympy.core.function import (Derivative, Function, Lambda, Subs,
diff, expand, expand_func)
from sympy.core.mul import Mul
from sympy.core.numbers import (AlgebraicNumber, E, I, Rational, igcd,
nan, oo, pi, zoo)
from sympy.core.relational import Eq, Lt
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol, symbols
from sympy.functions.combinatorial.factorials import (rf, binomial,
factorial, factorial2)
from sympy.functions.combinatorial.numbers import bernoulli, fibonacci
from sympy.functions.elementary.complexes import (conjugate, im, re,
sign)
from sympy.functions.elementary.exponential import LambertW, exp, log
from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh,
tanh)
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, acot, asin,
atan, cos, cot, csc, sec, sin, tan)
from sympy.functions.special.bessel import besselj
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.elliptic_integrals import (elliptic_e,
elliptic_f)
from sympy.functions.special.gamma_functions import gamma, polygamma
from sympy.functions.special.hyper import hyper
from sympy.functions.special.polynomials import (assoc_legendre,
chebyshevt)
from sympy.functions.special.zeta_functions import polylog
from sympy.geometry.util import idiff
from sympy.logic.boolalg import And
from sympy.matrices.dense import hessian, wronskian
from sympy.matrices.expressions.matmul import MatMul
from sympy.ntheory.continued_fraction import (
continued_fraction_convergents as cf_c,
continued_fraction_iterator as cf_i, continued_fraction_periodic as
cf_p, continued_fraction_reduce as cf_r)
from sympy.ntheory.factor_ import factorint, totient
from sympy.ntheory.generate import primerange
from sympy.ntheory.partitions_ import npartitions
from sympy.polys.domains.integerring import ZZ
from sympy.polys.orthopolys import legendre_poly
from sympy.polys.partfrac import apart
from sympy.polys.polytools import Poly, factor, gcd, resultant
from sympy.series.limits import limit
from sympy.series.order import O
from sympy.series.residues import residue
from sympy.series.series import series
from sympy.sets.fancysets import ImageSet
from sympy.sets.sets import FiniteSet, Intersection, Interval, Union
from sympy.simplify.combsimp import combsimp
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.powsimp import powdenest, powsimp
from sympy.simplify.radsimp import radsimp
from sympy.simplify.simplify import logcombine, simplify
from sympy.simplify.sqrtdenest import sqrtdenest
from sympy.simplify.trigsimp import trigsimp
from sympy.solvers.solvers import solve
import mpmath
from sympy.functions.combinatorial.numbers import stirling
from sympy.functions.special.delta_functions import Heaviside
from sympy.functions.special.error_functions import Ci, Si, erf
from sympy.functions.special.zeta_functions import zeta
from sympy.testing.pytest import (XFAIL, slow, SKIP, skip, ON_TRAVIS,
raises)
from sympy.utilities.iterables import partitions
from mpmath import mpi, mpc
from sympy.matrices import Matrix, GramSchmidt, eye
from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse
from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix
from sympy.physics.quantum import Commutator
from sympy.polys.rings import PolyRing
from sympy.polys.fields import FracField
from sympy.polys.solvers import solve_lin_sys
from sympy.concrete import Sum
from sympy.concrete.products import Product
from sympy.integrals import integrate
from sympy.integrals.transforms import laplace_transform,\
inverse_laplace_transform, LaplaceTransform, fourier_transform,\
mellin_transform
from sympy.solvers.recurr import rsolve
from sympy.solvers.solveset import solveset, solveset_real, linsolve
from sympy.solvers.ode import dsolve
from sympy.core.relational import Equality
from itertools import islice, takewhile
from sympy.series.formal import fps
from sympy.series.fourier import fourier_series
from sympy.calculus.util import minimum
EmptySet = S.EmptySet
R = Rational
x, y, z = symbols('x y z')
i, j, k, l, m, n = symbols('i j k l m n', integer=True)
f = Function('f')
g = Function('g')
# A. Boolean Logic and Quantifier Elimination
# Not implemented.
# B. Set Theory
def test_B1():
assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) |
FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m)
def test_B2():
assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) &
FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l})
# Previous output below. Not sure why that should be the expected output.
# There should probably be a way to rewrite Intersections that way but I
# don't see why an Intersection should evaluate like that:
#
# == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l}))))
def test_B3():
assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) ==
FiniteSet(i, k, l, m))
def test_B4():
assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) ==
FiniteSet((i, k), (i, l), (j, k), (j, l)))
# C. Numbers
def test_C1():
assert (factorial(50) ==
30414093201713378043612608166064768844377641568960512000000000000)
def test_C2():
assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8,
11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1,
41: 1, 43: 1, 47: 1})
def test_C3():
assert (factorial2(10), factorial2(9)) == (3840, 945)
# Base conversions; not really implemented by SymPy
# Whatever. Take credit!
def test_C4():
assert 0xABC == 2748
def test_C5():
assert 123 == int('234', 7)
def test_C6():
assert int('677', 8) == int('1BF', 16) == 447
def test_C7():
assert log(32768, 8) == 5
def test_C8():
# Modular multiplicative inverse. Would be nice if divmod could do this.
assert ZZ.invert(5, 7) == 3
assert ZZ.invert(5, 6) == 5
def test_C9():
assert igcd(igcd(1776, 1554), 5698) == 74
def test_C10():
x = 0
for n in range(2, 11):
x += R(1, n)
assert x == R(4861, 2520)
def test_C11():
assert R(1, 7) == S('0.[142857]')
def test_C12():
assert R(7, 11) * R(22, 7) == 2
def test_C13():
test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3)
good = 3 ** R(1, 3)
assert test == good
def test_C14():
assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3)
def test_C15():
test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2))))))
good = sqrt(2) + 3
assert test == good
def test_C16():
test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15)))
good = sqrt(2) + sqrt(3) + sqrt(5)
assert test == good
def test_C17():
test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2)))
good = 5 + 2*sqrt(6)
assert test == good
def test_C18():
assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3
@XFAIL
def test_C19():
assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7)
def test_C20():
inside = (135 + 78*sqrt(3))
test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3))
assert simplify(test) == AlgebraicNumber(12)
def test_C21():
assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \
AlgebraicNumber(1 + sqrt(2))
@XFAIL
def test_C22():
test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17
- 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72))
good = sqrt(2)/3 - log(sqrt(2) - 1)/3
assert test == good
def test_C23():
assert 2 * oo - 3 is oo
@XFAIL
def test_C24():
raise NotImplementedError("2**aleph_null == aleph_1")
# D. Numerical Analysis
def test_D1():
assert 0.0 / sqrt(2) == 0.0
def test_D2():
assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295'
def test_D3():
assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744)
def test_D4():
assert floor(R(-5, 3)) == -2
assert ceiling(R(-5, 3)) == -1
@XFAIL
def test_D5():
raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8")
@XFAIL
def test_D6():
raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN")
@XFAIL
def test_D7():
raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C")
@XFAIL
def test_D8():
# One way is to cheat by converting the sum to a string,
# and replacing the '[' and ']' with ''.
# E.g., horner(S(str(_).replace('[','').replace(']','')))
raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))")
@XFAIL
def test_D9():
raise NotImplementedError("translate D8 to FORTRAN")
@XFAIL
def test_D10():
raise NotImplementedError("translate D8 to C")
@XFAIL
def test_D11():
#Is there a way to use count_ops?
raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))")
@XFAIL
def test_D12():
assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9)
@XFAIL
def test_D13():
raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)")
# E. Statistics
# See scipy; all of this is numerical.
# F. Combinatorial Theory.
def test_F1():
assert rf(x, 3) == x*(1 + x)*(2 + x)
def test_F2():
assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6
@XFAIL
def test_F3():
assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n)
@XFAIL
def test_F4():
assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n)
@XFAIL
def test_F5():
assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2
def test_F6():
partTest = [p.copy() for p in partitions(4)]
partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}]
assert partTest == partDesired
def test_F7():
assert npartitions(4) == 5
def test_F8():
assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1
def test_F9():
assert totient(1776) == 576
# G. Number Theory
def test_G1():
assert list(primerange(999983, 1000004)) == [999983, 1000003]
@XFAIL
def test_G2():
raise NotImplementedError("find the primitive root of 191 == 19")
@XFAIL
def test_G3():
raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime")
# ... G14 Modular equations are not implemented.
def test_G15():
assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15)
assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \
R(26, 15)
def test_G16():
assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1]
def test_G17():
assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]]
def test_G18():
assert cf_p(1, 2, 5) == [[1]]
assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2
@XFAIL
def test_G19():
s = symbols('s', integer=True, positive=True)
it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1))
assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s]
def test_G20():
s = symbols('s', integer=True, positive=True)
# Wester erroneously has this as -s + sqrt(s**2 + 1)
assert cf_r([[2*s]]) == s + sqrt(s**2 + 1)
@XFAIL
def test_G20b():
s = symbols('s', integer=True, positive=True)
assert cf_p(s, 1, s**2 + 1) == [[2*s]]
# H. Algebra
def test_H1():
assert simplify(2*2**n) == simplify(2**(n + 1))
assert powdenest(2*2**n) == simplify(2**(n + 1))
def test_H2():
assert powsimp(4 * 2**n) == 2**(n + 2)
def test_H3():
assert (-1)**(n*(n + 1)) == 1
def test_H4():
expr = factor(6*x - 10)
assert type(expr) is Mul
assert expr.args[0] == 2
assert expr.args[1] == 3*x - 5
p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81
p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81
q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86
def test_H5():
assert gcd(p1, p2, x) == 1
def test_H6():
assert gcd(expand(p1 * q), expand(p2 * q)) == q
def test_H7():
p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
assert gcd(p1, p2, x, y, z) == 1
def test_H8():
p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8
assert gcd(p1 * q, p2 * q, x, y, z) == q
def test_H9():
x = Symbol('x', zero=False)
p1 = 2*x**(n + 4) - x**(n + 2)
p2 = 4*x**(n + 1) + 3*x**n
assert gcd(p1, p2) == x**n
def test_H10():
p1 = 3*x**4 + 3*x**3 + x**2 - x - 2
p2 = x**3 - 3*x**2 + x + 5
assert resultant(p1, p2, x) == 0
def test_H11():
assert resultant(p1 * q, p2 * q, x) == 0
def test_H12():
num = x**2 - 4
den = x**2 + 4*x + 4
assert simplify(num/den) == (x - 2)/(x + 2)
@XFAIL
def test_H13():
assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1
def test_H14():
p = (x + 1) ** 20
ep = expand(p)
assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5
+ 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10
+ 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15
+ 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20)
dep = diff(ep, x)
assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4
+ 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9
+ 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13
+ 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18
+ 20*x**19)
assert factor(dep) == 20*(1 + x)**19
def test_H15():
assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7
def test_H16():
assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3
+ x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4
- x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10
+ x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1))
def test_H17():
assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0
@XFAIL
def test_H18():
# Factor over complex rationals.
test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153)
good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I)
assert test == good
def test_H19():
a = symbols('a')
# The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1")
assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1
@XFAIL
def test_H20():
raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - "
+ "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)")
@XFAIL
def test_H21():
raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \
Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9")
def test_H22():
assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2
def test_H23():
f = x**11 + x + 1
g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1)
assert factor(f, modulus=65537) == g
def test_H24():
phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi')
assert factor(x**4 - 3*x**2 + 1, extension=phi) == \
(x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi)
def test_H25():
e = (x - 2*y**2 + 3*z**3) ** 20
assert factor(expand(e)) == e
def test_H26():
g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20)
assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20
def test_H27():
f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
h = -2*z*y**7 \
*(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \
*(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5)
assert factor(expand(f*g)) == h
@XFAIL
def test_H28():
raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * "
+ "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.")
@XFAIL
def test_H29():
assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y)
def test_H30():
test = factor(x**3 + y**3, extension=sqrt(-3))
answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I))
assert answer == test
def test_H31():
f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2)
g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2)
assert apart(f) == g
@XFAIL
def test_H32(): # issue 6558
raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \
of a non-commuting product and its inverse)")
def test_H33():
A, B, C = symbols('A, B, C', commutative=False)
assert (Commutator(A, Commutator(B, C))
+ Commutator(B, Commutator(C, A))
+ Commutator(C, Commutator(A, B))).doit().expand() == 0
# I. Trigonometry
def test_I1():
assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5))
@XFAIL
def test_I2():
assert sqrt((1 + cos(6))/2) == -cos(3)
def test_I3():
assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1
def test_I4():
assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1
@XFAIL
def test_I5():
assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0
@XFAIL
def test_I6():
raise NotImplementedError("assuming -3*pi<x<-5*pi/2, abs(cos(x)) == -cos(x), abs(sin(x)) == -sin(x)")
@XFAIL
def test_I7():
assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2
@XFAIL
def test_I8():
assert cos(3*x)/cos(x) == 2*cos(2*x) - 1
@XFAIL
def test_I9():
# Supposed to do this with rewrite rules.
assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2
def test_I10():
assert trigsimp((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1)) is nan
@SKIP("hangs")
@XFAIL
def test_I11():
assert limit((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x, 0) != 0
@XFAIL
def test_I12():
# This should fail or return nan or something.
res = diff((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x)
assert res is nan # trigsimp(res) gives nan
# J. Special functions.
def test_J1():
assert bernoulli(16) == R(-3617, 510)
def test_J2():
assert diff(elliptic_e(x, y**2), y) == (elliptic_e(x, y**2) - elliptic_f(x, y**2))/y
@XFAIL
def test_J3():
raise NotImplementedError("Jacobi elliptic functions: diff(dn(u,k), u) == -k**2*sn(u,k)*cn(u,k)")
def test_J4():
assert gamma(R(-1, 2)) == -2*sqrt(pi)
def test_J5():
assert polygamma(0, R(1, 3)) == -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3))
def test_J6():
assert mpmath.besselj(2, 1 + 1j).ae(mpc('0.04157988694396212', '0.24739764151330632'))
def test_J7():
assert simplify(besselj(R(-5,2), pi/2)) == 12/(pi**2)
def test_J8():
p = besselj(R(3,2), z)
q = (sin(z)/z - cos(z))/sqrt(pi*z/2)
assert simplify(expand_func(p) -q) == 0
def test_J9():
assert besselj(0, z).diff(z) == - besselj(1, z)
def test_J10():
mu, nu = symbols('mu, nu', integer=True)
assert assoc_legendre(nu, mu, 0) == 2**mu*sqrt(pi)/gamma((nu - mu)/2 + 1)/gamma((-nu - mu + 1)/2)
def test_J11():
assert simplify(assoc_legendre(3, 1, x)) == simplify(-R(3, 2)*sqrt(1 - x**2)*(5*x**2 - 1))
@slow
def test_J12():
assert simplify(chebyshevt(1008, x) - 2*x*chebyshevt(1007, x) + chebyshevt(1006, x)) == 0
def test_J13():
a = symbols('a', integer=True, negative=False)
assert chebyshevt(a, -1) == (-1)**a
def test_J14():
p = hyper([S.Half, S.Half], [R(3, 2)], z**2)
assert hyperexpand(p) == asin(z)/z
@XFAIL
def test_J15():
raise NotImplementedError("F((n+2)/2,-(n-2)/2,R(3,2),sin(z)**2) == sin(n*z)/(n*sin(z)*cos(z)); F(.) is hypergeometric function")
@XFAIL
def test_J16():
raise NotImplementedError("diff(zeta(x), x) @ x=0 == -log(2*pi)/2")
def test_J17():
assert integrate(f((x + 2)/5)*DiracDelta((x - 2)/3) - g(x)*diff(DiracDelta(x - 1), x), (x, 0, 3)) == 3*f(R(4, 5)) + Subs(Derivative(g(x), x), x, 1)
@XFAIL
def test_J18():
raise NotImplementedError("define an antisymmetric function")
# K. The Complex Domain
def test_K1():
z1, z2 = symbols('z1, z2', complex=True)
assert re(z1 + I*z2) == -im(z2) + re(z1)
assert im(z1 + I*z2) == im(z1) + re(z2)
def test_K2():
assert abs(3 - sqrt(7) + I*sqrt(6*sqrt(7) - 15)) == 1
@XFAIL
def test_K3():
a, b = symbols('a, b', real=True)
assert simplify(abs(1/(a + I/a + I*b))) == 1/sqrt(a**2 + (I/a + b)**2)
def test_K4():
assert log(3 + 4*I).expand(complex=True) == log(5) + I*atan(R(4, 3))
def test_K5():
x, y = symbols('x, y', real=True)
assert tan(x + I*y).expand(complex=True) == (sin(2*x)/(cos(2*x) +
cosh(2*y)) + I*sinh(2*y)/(cos(2*x) + cosh(2*y)))
def test_K6():
assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) == sqrt(x*y)/sqrt(x)
assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) != sqrt(y)
def test_K7():
y = symbols('y', real=True, negative=False)
expr = sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z))
sexpr = simplify(expr)
assert sexpr == sqrt(y)
def test_K8():
z = symbols('z', complex=True)
assert simplify(sqrt(1/z) - 1/sqrt(z)) != 0 # Passes
z = symbols('z', complex=True, negative=False)
assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 # Fails
def test_K9():
z = symbols('z', positive=True)
assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0
def test_K10():
z = symbols('z', negative=True)
assert simplify(sqrt(1/z) + 1/sqrt(z)) == 0
# This goes up to K25
# L. Determining Zero Equivalence
def test_L1():
assert sqrt(997) - (997**3)**R(1, 6) == 0
def test_L2():
assert sqrt(999983) - (999983**3)**R(1, 6) == 0
def test_L3():
assert simplify((2**R(1, 3) + 4**R(1, 3))**3 - 6*(2**R(1, 3) + 4**R(1, 3)) - 6) == 0
def test_L4():
assert trigsimp(cos(x)**3 + cos(x)*sin(x)**2 - cos(x)) == 0
@XFAIL
def test_L5():
assert log(tan(R(1, 2)*x + pi/4)) - asinh(tan(x)) == 0
def test_L6():
assert (log(tan(x/2 + pi/4)) - asinh(tan(x))).diff(x).subs({x: 0}) == 0
@XFAIL
def test_L7():
assert simplify(log((2*sqrt(x) + 1)/(sqrt(4*x + 4*sqrt(x) + 1)))) == 0
@XFAIL
def test_L8():
assert simplify((4*x + 4*sqrt(x) + 1)**(sqrt(x)/(2*sqrt(x) + 1)) \
*(2*sqrt(x) + 1)**(1/(2*sqrt(x) + 1)) - 2*sqrt(x) - 1) == 0
@XFAIL
def test_L9():
z = symbols('z', complex=True)
assert simplify(2**(1 - z)*gamma(z)*zeta(z)*cos(z*pi/2) - pi**2*zeta(1 - z)) == 0
# M. Equations
@XFAIL
def test_M1():
assert Equality(x, 2)/2 + Equality(1, 1) == Equality(x/2 + 1, 2)
def test_M2():
# The roots of this equation should all be real. Note that this
# doesn't test that they are correct.
sol = solveset(3*x**3 - 18*x**2 + 33*x - 19, x)
assert all(s.expand(complex=True).is_real for s in sol)
@XFAIL
def test_M5():
assert solveset(x**6 - 9*x**4 - 4*x**3 + 27*x**2 - 36*x - 23, x) == FiniteSet(2**(1/3) + sqrt(3), 2**(1/3) - sqrt(3), +sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), +sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3))
def test_M6():
assert set(solveset(x**7 - 1, x)) == \
{cos(n*pi*R(2, 7)) + I*sin(n*pi*R(2, 7)) for n in range(0, 7)}
# The paper asks for exp terms, but sin's and cos's may be acceptable;
# if the results are simplified, exp terms appear for all but
# -sin(pi/14) - I*cos(pi/14) and -sin(pi/14) + I*cos(pi/14) which
# will simplify if you apply the transformation foo.rewrite(exp).expand()
def test_M7():
# TODO: Replace solve with solveset, as of now test fails for solveset
assert set(solve(x**8 - 8*x**7 + 34*x**6 - 92*x**5 + 175*x**4 - 236*x**3 +
226*x**2 - 140*x + 46, x)) == set([
1 - sqrt(2)*I*sqrt(-sqrt(-3 + 4*sqrt(3)) + 3)/2,
1 - sqrt(2)*sqrt(-3 + I*sqrt(3 + 4*sqrt(3)))/2,
1 - sqrt(2)*I*sqrt(sqrt(-3 + 4*sqrt(3)) + 3)/2,
1 - sqrt(2)*sqrt(-3 - I*sqrt(3 + 4*sqrt(3)))/2,
1 + sqrt(2)*I*sqrt(sqrt(-3 + 4*sqrt(3)) + 3)/2,
1 + sqrt(2)*sqrt(-3 - I*sqrt(3 + 4*sqrt(3)))/2,
1 + sqrt(2)*sqrt(-3 + I*sqrt(3 + 4*sqrt(3)))/2,
1 + sqrt(2)*I*sqrt(-sqrt(-3 + 4*sqrt(3)) + 3)/2,
])
@XFAIL # There are an infinite number of solutions.
def test_M8():
x = Symbol('x')
z = symbols('z', complex=True)
assert solveset(exp(2*x) + 2*exp(x) + 1 - z, x, S.Reals) == \
FiniteSet(log(1 + z - 2*sqrt(z))/2, log(1 + z + 2*sqrt(z))/2)
# This one could be simplified better (the 1/2 could be pulled into the log
# as a sqrt, and the function inside the log can be factored as a square,
# giving [log(sqrt(z) - 1), log(sqrt(z) + 1)]). Also, there should be an
# infinite number of solutions.
# x = {log(sqrt(z) - 1), log(sqrt(z) + 1) + i pi} [+ n 2 pi i, + n 2 pi i]
# where n is an arbitrary integer. See url of detailed output above.
@XFAIL
def test_M9():
# x = symbols('x')
raise NotImplementedError("solveset(exp(2-x**2)-exp(-x),x) has complex solutions.")
def test_M10():
# TODO: Replace solve with solveset, as of now test fails for solveset
assert solve(exp(x) - x, x) == [-LambertW(-1)]
@XFAIL
def test_M11():
assert solveset(x**x - x, x) == FiniteSet(-1, 1)
def test_M12():
# TODO: x = [-1, 2*(+/-asinh(1)*I + n*pi}, 3*(pi/6 + n*pi/3)]
# TODO: Replace solve with solveset, as of now test fails for solveset
assert solve((x + 1)*(sin(x)**2 + 1)**2*cos(3*x)**3, x) == [
-1, pi/6, pi/2,
- I*log(1 + sqrt(2)), I*log(1 + sqrt(2)),
pi - I*log(1 + sqrt(2)), pi + I*log(1 + sqrt(2)),
]
@XFAIL
def test_M13():
n = Dummy('n')
assert solveset_real(sin(x) - cos(x), x) == ImageSet(Lambda(n, n*pi - pi*R(7, 4)), S.Integers)
@XFAIL
def test_M14():
n = Dummy('n')
assert solveset_real(tan(x) - 1, x) == ImageSet(Lambda(n, n*pi + pi/4), S.Integers)
def test_M15():
n = Dummy('n')
got = solveset(sin(x) - S.Half)
assert any(got.dummy_eq(i) for i in (
Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers),
ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers)),
Union(ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers),
ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers))))
@XFAIL
def test_M16():
n = Dummy('n')
assert solveset(sin(x) - tan(x), x) == ImageSet(Lambda(n, n*pi), S.Integers)
@XFAIL
def test_M17():
assert solveset_real(asin(x) - atan(x), x) == FiniteSet(0)
@XFAIL
def test_M18():
assert solveset_real(acos(x) - atan(x), x) == FiniteSet(sqrt((sqrt(5) - 1)/2))
def test_M19():
# TODO: Replace solve with solveset, as of now test fails for solveset
assert solve((x - 2)/x**R(1, 3), x) == [2]
def test_M20():
assert solveset(sqrt(x**2 + 1) - x + 2, x) == EmptySet
def test_M21():
assert solveset(x + sqrt(x) - 2) == FiniteSet(1)
def test_M22():
assert solveset(2*sqrt(x) + 3*x**R(1, 4) - 2) == FiniteSet(R(1, 16))
def test_M23():
x = symbols('x', complex=True)
# TODO: Replace solve with solveset, as of now test fails for solveset
assert solve(x - 1/sqrt(1 + x**2)) == [
-I*sqrt(S.Half + sqrt(5)/2), sqrt(Rational(-1, 2) + sqrt(5)/2)]
def test_M24():
# TODO: Replace solve with solveset, as of now test fails for solveset
solution = solve(1 - binomial(m, 2)*2**k, k)
answer = log(2/(m*(m - 1)), 2)
assert solution[0].expand() == answer.expand()
def test_M25():
a, b, c, d = symbols(':d', positive=True)
x = symbols('x')
# TODO: Replace solve with solveset, as of now test fails for solveset
assert solve(a*b**x - c*d**x, x)[0].expand() == (log(c/a)/log(b/d)).expand()
def test_M26():
# TODO: Replace solve with solveset, as of now test fails for solveset
assert solve(sqrt(log(x)) - log(sqrt(x))) == [1, exp(4)]
def test_M27():
x = symbols('x', real=True)
b = symbols('b', real=True)
# TODO: Replace solve with solveset which gives both [+/- current answer]
# note that there is a typo in this test in the wester.pdf; there is no
# real solution for the equation as it appears in wester.pdf
assert solve(log(acos(asin(x**R(2, 3) - b)) - 1) + 2, x
) == [(b + sin(cos(exp(-2) + 1)))**R(3, 2)]
@XFAIL
def test_M28():
assert solveset_real(5*x + exp((x - 5)/2) - 8*x**3, x, assume=Q.real(x)) == [-0.784966, -0.016291, 0.802557]
def test_M29():
x = symbols('x')
assert solveset(abs(x - 1) - 2, domain=S.Reals) == FiniteSet(-1, 3)
def test_M30():
# TODO: Replace solve with solveset, as of now
# solveset doesn't supports assumptions
# assert solve(abs(2*x + 5) - abs(x - 2),x, assume=Q.real(x)) == [-1, -7]
assert solveset_real(abs(2*x + 5) - abs(x - 2), x) == FiniteSet(-1, -7)
def test_M31():
# TODO: Replace solve with solveset, as of now
# solveset doesn't supports assumptions
# assert solve(1 - abs(x) - max(-x - 2, x - 2),x, assume=Q.real(x)) == [-3/2, 3/2]
assert solveset_real(1 - abs(x) - Max(-x - 2, x - 2), x) == FiniteSet(R(-3, 2), R(3, 2))
@XFAIL
def test_M32():
# TODO: Replace solve with solveset, as of now
# solveset doesn't supports assumptions
assert solveset_real(Max(2 - x**2, x)- Max(-x, (x**3)/9), x) == FiniteSet(-1, 3)
@XFAIL
def test_M33():
# TODO: Replace solve with solveset, as of now
# solveset doesn't supports assumptions
# Second answer can be written in another form. The second answer is the root of x**3 + 9*x**2 - 18 = 0 in the interval (-2, -1).
assert solveset_real(Max(2 - x**2, x) - x**3/9, x) == FiniteSet(-3, -1.554894, 3)
@XFAIL
def test_M34():
z = symbols('z', complex=True)
assert solveset((1 + I) * z + (2 - I) * conjugate(z) + 3*I, z) == FiniteSet(2 + 3*I)
def test_M35():
x, y = symbols('x y', real=True)
assert linsolve((3*x - 2*y - I*y + 3*I).as_real_imag(), y, x) == FiniteSet((3, 2))
def test_M36():
# TODO: Replace solve with solveset, as of now
# solveset doesn't supports solving for function
# assert solve(f**2 + f - 2, x) == [Eq(f(x), 1), Eq(f(x), -2)]
assert solveset(f(x)**2 + f(x) - 2, f(x)) == FiniteSet(-2, 1)
def test_M37():
assert linsolve([x + y + z - 6, 2*x + y + 2*z - 10, x + 3*y + z - 10 ], x, y, z) == \
FiniteSet((-z + 4, 2, z))
def test_M38():
a, b, c = symbols('a, b, c')
domain = FracField([a, b, c], ZZ).to_domain()
ring = PolyRing('k1:50', domain)
(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10,
k11, k12, k13, k14, k15, k16, k17, k18, k19, k20,
k21, k22, k23, k24, k25, k26, k27, k28, k29, k30,
k31, k32, k33, k34, k35, k36, k37, k38, k39, k40,
k41, k42, k43, k44, k45, k46, k47, k48, k49) = ring.gens
system = [
-b*k8/a + c*k8/a, -b*k11/a + c*k11/a, -b*k10/a + c*k10/a + k2, -k3 - b*k9/a + c*k9/a,
-b*k14/a + c*k14/a, -b*k15/a + c*k15/a, -b*k18/a + c*k18/a - k2, -b*k17/a + c*k17/a,
-b*k16/a + c*k16/a + k4, -b*k13/a + c*k13/a - b*k21/a + c*k21/a + b*k5/a - c*k5/a,
b*k44/a - c*k44/a, -b*k45/a + c*k45/a, -b*k20/a + c*k20/a, -b*k44/a + c*k44/a,
b*k46/a - c*k46/a, b**2*k47/a**2 - 2*b*c*k47/a**2 + c**2*k47/a**2, k3, -k4,
-b*k12/a + c*k12/a - a*k6/b + c*k6/b, -b*k19/a + c*k19/a + a*k7/c - b*k7/c,
b*k45/a - c*k45/a, -b*k46/a + c*k46/a, -k48 + c*k48/a + c*k48/b - c**2*k48/(a*b),
-k49 + b*k49/a + b*k49/c - b**2*k49/(a*c), a*k1/b - c*k1/b, a*k4/b - c*k4/b,
a*k3/b - c*k3/b + k9, -k10 + a*k2/b - c*k2/b, a*k7/b - c*k7/b, -k9, k11,
b*k12/a - c*k12/a + a*k6/b - c*k6/b, a*k15/b - c*k15/b, k10 + a*k18/b - c*k18/b,
-k11 + a*k17/b - c*k17/b, a*k16/b - c*k16/b, -a*k13/b + c*k13/b + a*k21/b - c*k21/b + a*k5/b - c*k5/b,
-a*k44/b + c*k44/b, a*k45/b - c*k45/b, a*k14/c - b*k14/c + a*k20/b - c*k20/b,
a*k44/b - c*k44/b, -a*k46/b + c*k46/b, -k47 + c*k47/a + c*k47/b - c**2*k47/(a*b),
a*k19/b - c*k19/b, -a*k45/b + c*k45/b, a*k46/b - c*k46/b, a**2*k48/b**2 - 2*a*c*k48/b**2 + c**2*k48/b**2,
-k49 + a*k49/b + a*k49/c - a**2*k49/(b*c), k16, -k17, -a*k1/c + b*k1/c,
-k16 - a*k4/c + b*k4/c, -a*k3/c + b*k3/c, k18 - a*k2/c + b*k2/c, b*k19/a - c*k19/a - a*k7/c + b*k7/c,
-a*k6/c + b*k6/c, -a*k8/c + b*k8/c, -a*k11/c + b*k11/c + k17, -a*k10/c + b*k10/c - k18,
-a*k9/c + b*k9/c, -a*k14/c + b*k14/c - a*k20/b + c*k20/b, -a*k13/c + b*k13/c + a*k21/c - b*k21/c - a*k5/c + b*k5/c,
a*k44/c - b*k44/c, -a*k45/c + b*k45/c, -a*k44/c + b*k44/c, a*k46/c - b*k46/c,
-k47 + b*k47/a + b*k47/c - b**2*k47/(a*c), -a*k12/c + b*k12/c, a*k45/c - b*k45/c,
-a*k46/c + b*k46/c, -k48 + a*k48/b + a*k48/c - a**2*k48/(b*c),
a**2*k49/c**2 - 2*a*b*k49/c**2 + b**2*k49/c**2, k8, k11, -k15, k10 - k18,
-k17, k9, -k16, -k29, k14 - k32, -k21 + k23 - k31, -k24 - k30, -k35, k44,
-k45, k36, k13 - k23 + k39, -k20 + k38, k25 + k37, b*k26/a - c*k26/a - k34 + k42,
-2*k44, k45, k46, b*k47/a - c*k47/a, k41, k44, -k46, -b*k47/a + c*k47/a,
k12 + k24, -k19 - k25, -a*k27/b + c*k27/b - k33, k45, -k46, -a*k48/b + c*k48/b,
a*k28/c - b*k28/c + k40, -k45, k46, a*k48/b - c*k48/b, a*k49/c - b*k49/c,
-a*k49/c + b*k49/c, -k1, -k4, -k3, k15, k18 - k2, k17, k16, k22, k25 - k7,
k24 + k30, k21 + k23 - k31, k28, -k44, k45, -k30 - k6, k20 + k32, k27 + b*k33/a - c*k33/a,
k44, -k46, -b*k47/a + c*k47/a, -k36, k31 - k39 - k5, -k32 - k38, k19 - k37,
k26 - a*k34/b + c*k34/b - k42, k44, -2*k45, k46, a*k48/b - c*k48/b,
a*k35/c - b*k35/c - k41, -k44, k46, b*k47/a - c*k47/a, -a*k49/c + b*k49/c,
-k40, k45, -k46, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k1, k4, k3, -k8,
-k11, -k10 + k2, -k9, k37 + k7, -k14 - k38, -k22, -k25 - k37, -k24 + k6,
-k13 - k23 + k39, -k28 + b*k40/a - c*k40/a, k44, -k45, -k27, -k44, k46,
b*k47/a - c*k47/a, k29, k32 + k38, k31 - k39 + k5, -k12 + k30, k35 - a*k41/b + c*k41/b,
-k44, k45, -k26 + k34 + a*k42/c - b*k42/c, k44, k45, -2*k46, -b*k47/a + c*k47/a,
-a*k48/b + c*k48/b, a*k49/c - b*k49/c, k33, -k45, k46, a*k48/b - c*k48/b,
-a*k49/c + b*k49/c
]
solution = {
k49: 0, k48: 0, k47: 0, k46: 0, k45: 0, k44: 0, k41: 0, k40: 0,
k38: 0, k37: 0, k36: 0, k35: 0, k33: 0, k32: 0, k30: 0, k29: 0,
k28: 0, k27: 0, k25: 0, k24: 0, k22: 0, k21: 0, k20: 0, k19: 0,
k18: 0, k17: 0, k16: 0, k15: 0, k14: 0, k13: 0, k12: 0, k11: 0,
k10: 0, k9: 0, k8: 0, k7: 0, k6: 0, k5: 0, k4: 0, k3: 0,
k2: 0, k1: 0,
k34: b/c*k42, k31: k39, k26: a/c*k42, k23: k39
}
assert solve_lin_sys(system, ring) == solution
def test_M39():
x, y, z = symbols('x y z', complex=True)
# TODO: Replace solve with solveset, as of now
# solveset doesn't supports non-linear multivariate
assert solve([x**2*y + 3*y*z - 4, -3*x**2*z + 2*y**2 + 1, 2*y*z**2 - z**2 - 1 ]) ==\
[{y: 1, z: 1, x: -1}, {y: 1, z: 1, x: 1},\
{y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: -sqrt(-1 - sqrt(2)*I)},\
{y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: sqrt(-1 - sqrt(2)*I)},\
{y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: -sqrt(-1 + sqrt(2)*I)},\
{y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: sqrt(-1 + sqrt(2)*I)}]
# N. Inequalities
def test_N1():
assert ask(E**pi > pi**E)
@XFAIL
def test_N2():
x = symbols('x', real=True)
assert ask(x**4 - x + 1 > 0) is True
assert ask(x**4 - x + 1 > 1) is False
@XFAIL
def test_N3():
x = symbols('x', real=True)
assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 )
@XFAIL
def test_N4():
x, y = symbols('x y', real=True)
assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True
@XFAIL
def test_N5():
x, y, k = symbols('x y k', real=True)
assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True
@slow
@XFAIL
def test_N6():
x, y, k, n = symbols('x y k n', real=True)
assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True
@XFAIL
def test_N7():
x, y = symbols('x y', real=True)
assert ask(y > 0, (x > 1) & (y >= x - 1)) is True
@XFAIL
@slow
def test_N8():
x, y, z = symbols('x y z', real=True)
assert ask(Eq(x, y) & Eq(y, z),
(x >= y) & (y >= z) & (z >= x))
def test_N9():
x = Symbol('x')
assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True),
Interval(3, oo, True))
def test_N10():
x = Symbol('x')
p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5)
assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True),
Interval(2, 3, True, True),
Interval(4, 5, True, True))
def test_N11():
x = Symbol('x')
assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo))
def test_N12():
x = Symbol('x')
assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True)
def test_N13():
x = Symbol('x')
assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals
@XFAIL
def test_N14():
x = Symbol('x')
# Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true),
# Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))'
# which is not the correct answer, but the provided also seems wrong.
assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True),
Interval(pi/2, oo, True, True))
def test_N15():
r, t = symbols('r t')
# raises NotImplementedError: only univariate inequalities are supported
solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals)
def test_N16():
r, t = symbols('r t')
solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals)
@XFAIL
def test_N17():
# currently only univariate inequalities are supported
assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y)
def test_O1():
M = Matrix((1 + I, -2, 3*I))
assert sqrt(expand(M.dot(M.H))) == sqrt(15)
def test_O2():
assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11],
[-5],
[4]])
# The vector module has no way of representing vectors symbolically (without
# respect to a basis)
@XFAIL
def test_O3():
# assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc)
raise NotImplementedError("""The vector module has no way of representing
vectors symbolically (without respect to a basis)""")
def test_O4():
from sympy.vector import CoordSys3D, Del
N = CoordSys3D("N")
delop = Del()
i, j, k = N.base_vectors()
x, y, z = N.base_scalars()
F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3))
assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k
@XFAIL
def test_O5():
#assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0
raise NotImplementedError("""The vector module has no way of representing
vectors symbolically (without respect to a basis)""")
#testO8-O9 MISSING!!
def test_O10():
L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])]
assert GramSchmidt(L) == [Matrix([
[2],
[3],
[5]]),
Matrix([
[R(23, 19)],
[R(63, 19)],
[R(-47, 19)]]),
Matrix([
[R(1692, 353)],
[R(-1551, 706)],
[R(-423, 706)]])]
def test_P1():
assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix(
1, 2, [-1, -1])
def test_P2():
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
M.row_del(1)
M.col_del(2)
assert M == Matrix([[1, 2],
[7, 8]])
def test_P3():
A = Matrix([
[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34],
[41, 42, 43, 44]])
A11 = A[0:3, 1:4]
A12 = A[(0, 1, 3), (2, 0, 3)]
A21 = A
A221 = -A[0:2, 2:4]
A222 = -A[(3, 0), (2, 1)]
A22 = BlockMatrix([[A221, A222]]).T
rows = [[-A11, A12], [A21, A22]]
raises(ValueError, lambda: BlockMatrix(rows))
B = Matrix(rows)
assert B == Matrix([
[-12, -13, -14, 13, 11, 14],
[-22, -23, -24, 23, 21, 24],
[-32, -33, -34, 43, 41, 44],
[11, 12, 13, 14, -13, -23],
[21, 22, 23, 24, -14, -24],
[31, 32, 33, 34, -43, -13],
[41, 42, 43, 44, -42, -12]])
@XFAIL
def test_P4():
raise NotImplementedError("Block matrix diagonalization not supported")
def test_P5():
M = Matrix([[7, 11],
[3, 8]])
assert M % 2 == Matrix([[1, 1],
[1, 0]])
def test_P6():
M = Matrix([[cos(x), sin(x)],
[-sin(x), cos(x)]])
assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)],
[sin(x), -cos(x)]])
def test_P7():
M = Matrix([[x, y]])*(
z*Matrix([[1, 3, 5],
[2, 4, 6]]) + Matrix([[7, -9, 11],
[-8, 10, -12]]))
assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10),
x*(5*z + 11) + y*(6*z - 12)]])
def test_P8():
M = Matrix([[1, -2*I],
[-3*I, 4]])
assert M.norm(ord=S.Infinity) == 7
def test_P9():
a, b, c = symbols('a b c', nonzero=True)
M = Matrix([[a/(b*c), 1/c, 1/b],
[1/c, b/(a*c), 1/a],
[1/b, 1/a, c/(a*b)]])
assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c))
@XFAIL
def test_P10():
M = Matrix([[1, 2 + 3*I],
[f(4 - 5*I), 6]])
# conjugate(f(4 - 5*i)) is not simplified to f(4+5*I)
assert M.H == Matrix([[1, f(4 + 5*I)],
[2 + 3*I, 6]])
@XFAIL
def test_P11():
# raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv()
# not simplifying to extract common factor")
assert Matrix([[x, y],
[1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1],
[-1/y, x/y]])
def test_P11_workaround():
# This test was changed to inverse method ADJ because it depended on the
# specific form of inverse returned from the 'GE' method which has changed.
M = Matrix([[x, y], [1, x*y]]).inv('ADJ')
c = gcd(tuple(M))
assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([
[x*y, -y],
[ -1, x]]), evaluate=False)
def test_P12():
A11 = MatrixSymbol('A11', n, n)
A12 = MatrixSymbol('A12', n, n)
A22 = MatrixSymbol('A22', n, n)
B = BlockMatrix([[A11, A12],
[ZeroMatrix(n, n), A22]])
assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I],
[ZeroMatrix(n, n), A22.I]])
def test_P13():
M = Matrix([[1, x - 2, x - 3],
[x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2],
[x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]])
L, U, _ = M.LUdecomposition()
assert simplify(L) == Matrix([[1, 0, 0],
[x - 1, 1, 0],
[x - 2, x - 3, 1]])
assert simplify(U) == Matrix([[1, x - 2, x - 3],
[0, 4, x - 5],
[0, 0, x - 7]])
def test_P14():
M = Matrix([[1, 2, 3, 1, 3],
[3, 2, 1, 1, 7],
[0, 2, 4, 1, 1],
[1, 1, 1, 1, 4]])
R, _ = M.rref()
assert R == Matrix([[1, 0, -1, 0, 2],
[0, 1, 2, 0, -1],
[0, 0, 0, 1, 3],
[0, 0, 0, 0, 0]])
def test_P15():
M = Matrix([[-1, 3, 7, -5],
[4, -2, 1, 3],
[2, 4, 15, -7]])
assert M.rank() == 2
def test_P16():
M = Matrix([[2*sqrt(2), 8],
[6*sqrt(6), 24*sqrt(3)]])
assert M.rank() == 1
def test_P17():
t = symbols('t', real=True)
M=Matrix([
[sin(2*t), cos(2*t)],
[2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]])
assert M.rank() == 1
def test_P18():
M = Matrix([[1, 0, -2, 0],
[-2, 1, 0, 3],
[-1, 2, -6, 6]])
assert M.nullspace() == [Matrix([[2],
[4],
[1],
[0]]),
Matrix([[0],
[-3],
[0],
[1]])]
def test_P19():
w = symbols('w')
M = Matrix([[1, 1, 1, 1],
[w, x, y, z],
[w**2, x**2, y**2, z**2],
[w**3, x**3, y**3, z**3]])
assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2
+ w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z
+ w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3
+ w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3
+ w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2
+ x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3
)
@XFAIL
def test_P20():
raise NotImplementedError("Matrix minimal polynomial not supported")
def test_P21():
M = Matrix([[5, -3, -7],
[-2, 1, 2],
[2, -3, -4]])
assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6
def test_P22():
d = 100
M = (2 - x)*eye(d)
assert M.eigenvals() == {-x + 2: d}
def test_P23():
M = Matrix([
[2, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[0, 1, 2, 1, 0],
[0, 0, 1, 2, 1],
[0, 0, 0, 1, 2]])
assert M.eigenvals() == {
S('1'): 1,
S('2'): 1,
S('3'): 1,
S('sqrt(3) + 2'): 1,
S('-sqrt(3) + 2'): 1}
def test_P24():
M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29],
[196, 899, 113, -192, -71, -43, -8, -44],
[-192, 113, 899, 196, 61, 49, 8, 52],
[ 407, -192, 196, 611, 8, 44, 59, -23],
[ -8, -71, 61, 8, 411, -599, 208, 208],
[ -52, -43, 49, 44, -599, 411, 208, 208],
[ -49, -8, 8, 59, 208, 208, 99, -911],
[ 29, -44, 52, -23, 208, 208, -911, 99]])
assert M.eigenvals() == {
S('0'): 1,
S('10*sqrt(10405)'): 1,
S('100*sqrt(26) + 510'): 1,
S('1000'): 2,
S('-100*sqrt(26) + 510'): 1,
S('-10*sqrt(10405)'): 1,
S('1020'): 1}
def test_P25():
MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29],
[ 196, 899, 113, -192, -71, -43, -8, -44],
[-192, 113, 899, 196, 61, 49, 8, 52],
[ 407, -192, 196, 611, 8, 44, 59, -23],
[ -8, -71, 61, 8, 411, -599, 208, 208],
[ -52, -43, 49, 44, -599, 411, 208, 208],
[ -49, -8, 8, 59, 208, 208, 99, -911],
[ 29, -44, 52, -23, 208, 208, -911, 99]]))
ev_1 = sorted(MF.eigenvals(multiple=True))
ev_2 = sorted(
[-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0,
1019.9019513592784, 1020.0, 1020.0490184299969])
for x, y in zip(ev_1, ev_2):
assert abs(x - y) < 1e-12
def test_P26():
a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4')
M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0],
[ 1, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 1, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 1, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, -1, -1, 0, 0],
[ 0, 0, 0, 0, 0, 1, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 1, -1, -1],
[ 0, 0, 0, 0, 0, 0, 0, 1, 0]])
assert M.eigenvals(error_when_incomplete=False) == {
S('-1/2 - sqrt(3)*I/2'): 2,
S('-1/2 + sqrt(3)*I/2'): 2}
def test_P27():
a = symbols('a')
M = Matrix([[a, 0, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, a, 0, 0],
[0, 0, 0, a, 0],
[0, -2, 0, 0, 2]])
assert M.eigenvects() == [
(a, 3, [
Matrix([1, 0, 0, 0, 0]),
Matrix([0, 0, 1, 0, 0]),
Matrix([0, 0, 0, 1, 0])
]),
(1 - I, 1, [
Matrix([0, (1 + I)/2, 0, 0, 1])
]),
(1 + I, 1, [
Matrix([0, (1 - I)/2, 0, 0, 1])
]),
]
@XFAIL
def test_P28():
raise NotImplementedError("Generalized eigenvectors not supported \
https://github.com/sympy/sympy/issues/5293")
@XFAIL
def test_P29():
raise NotImplementedError("Generalized eigenvectors not supported \
https://github.com/sympy/sympy/issues/5293")
def test_P30():
M = Matrix([[1, 0, 0, 1, -1],
[0, 1, -2, 3, -3],
[0, 0, -1, 2, -2],
[1, -1, 1, 0, 1],
[1, -1, 1, -1, 2]])
_, J = M.jordan_form()
assert J == Matrix([[-1, 0, 0, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 1]])
@XFAIL
def test_P31():
raise NotImplementedError("Smith normal form not implemented")
def test_P32():
M = Matrix([[1, -2],
[2, 1]])
assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)],
[E*sin(2), E*cos(2)]])
def test_P33():
w, t = symbols('w t')
M = Matrix([[0, 1, 0, 0],
[0, 0, 0, 2*w],
[0, 0, 0, 1],
[0, -2*w, 3*w**2, 0]])
assert exp(M*t).rewrite(cos).expand() == Matrix([
[1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w],
[0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)],
[0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w],
[0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]])
@XFAIL
def test_P34():
a, b, c = symbols('a b c', real=True)
M = Matrix([[a, 1, 0, 0, 0, 0],
[0, a, 0, 0, 0, 0],
[0, 0, b, 0, 0, 0],
[0, 0, 0, c, 1, 0],
[0, 0, 0, 0, c, 1],
[0, 0, 0, 0, 0, c]])
# raises exception, sin(M) not supported. exp(M*I) also not supported
# https://github.com/sympy/sympy/issues/6218
assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0],
[0, sin(a), 0, 0, 0, 0],
[0, 0, sin(b), 0, 0, 0],
[0, 0, 0, sin(c), cos(c), -sin(c)/2],
[0, 0, 0, 0, sin(c), cos(c)],
[0, 0, 0, 0, 0, sin(c)]])
@XFAIL
def test_P35():
M = pi/2*Matrix([[2, 1, 1],
[2, 3, 2],
[1, 1, 2]])
# raises exception, sin(M) not supported. exp(M*I) also not supported
# https://github.com/sympy/sympy/issues/6218
assert sin(M) == eye(3)
@XFAIL
def test_P36():
M = Matrix([[10, 7],
[7, 17]])
assert sqrt(M) == Matrix([[3, 1],
[1, 4]])
def test_P37():
M = Matrix([[1, 1, 0],
[0, 1, 0],
[0, 0, 1]])
assert M**S.Half == Matrix([[1, R(1, 2), 0],
[0, 1, 0],
[0, 0, 1]])
@XFAIL
def test_P38():
M=Matrix([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
with raises(AssertionError):
# raises ValueError: Matrix det == 0; not invertible
M**S.Half
# if it doesn't raise then this assertion will be
# raised and the test will be flagged as not XFAILing
assert None
@XFAIL
def test_P39():
"""
M=Matrix([
[1, 1],
[2, 2],
[3, 3]])
M.SVD()
"""
raise NotImplementedError("Singular value decomposition not implemented")
def test_P40():
r, t = symbols('r t', real=True)
M = Matrix([r*cos(t), r*sin(t)])
assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)],
[sin(t), r*cos(t)]])
def test_P41():
r, t = symbols('r t', real=True)
assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)],
[2*r*cos(t), -r**2*sin(t)]])
def test_P42():
assert wronskian([cos(x), sin(x)], x).simplify() == 1
def test_P43():
def __my_jacobian(M, Y):
return Matrix([M.diff(v).T for v in Y]).T
r, t = symbols('r t', real=True)
M = Matrix([r*cos(t), r*sin(t)])
assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)],
[sin(t), r*cos(t)]])
def test_P44():
def __my_hessian(f, Y):
V = Matrix([diff(f, v) for v in Y])
return Matrix([V.T.diff(v) for v in Y])
r, t = symbols('r t', real=True)
assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([
[ 2*sin(t), 2*r*cos(t)],
[2*r*cos(t), -r**2*sin(t)]])
def test_P45():
def __my_wronskian(Y, v):
M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))])
return M.det()
assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1
# Q1-Q6 Tensor tests missing
@XFAIL
def test_R1():
i, j, n = symbols('i j n', integer=True, positive=True)
xn = MatrixSymbol('xn', n, 1)
Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1))
# sum does not calculate
# Unknown result
Sm.doit()
raise NotImplementedError('Unknown result')
@XFAIL
def test_R2():
m, b = symbols('m b')
i, n = symbols('i n', integer=True, positive=True)
xn = MatrixSymbol('xn', n, 1)
yn = MatrixSymbol('yn', n, 1)
f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1))
f1 = diff(f, m)
f2 = diff(f, b)
# raises TypeError: solveset() takes at most 2 arguments (3 given)
solveset((f1, f2), (m, b), domain=S.Reals)
@XFAIL
def test_R3():
n, k = symbols('n k', integer=True, positive=True)
sk = ((-1)**k) * (binomial(2*n, k))**2
Sm = Sum(sk, (k, 1, oo))
T = Sm.doit()
T2 = T.combsimp()
# returns -((-1)**n*factorial(2*n)
# - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2
assert T2 == (-1)**n*binomial(2*n, n)
@XFAIL
def test_R4():
# Macsyma indefinite sum test case:
#(c15) /* Check whether the full Gosper algorithm is implemented
# => 1/2^(n + 1) binomial(n, k - 1) */
#closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k));
#Time= 2690 msecs
# (- n + k - 1) binomial(n + 1, k)
#(d15) - --------------------------------
# n
# 2 2 (n + 1)
#
#(c16) factcomb(makefact(%));
#Time= 220 msecs
# n!
#(d16) ----------------
# n
# 2 k! 2 (n - k)!
# Might be possible after fixing https://github.com/sympy/sympy/pull/1879
raise NotImplementedError("Indefinite sum not supported")
@XFAIL
def test_R5():
a, b, c, n, k = symbols('a b c n k', integer=True, positive=True)
sk = ((-1)**k)*(binomial(a + b, a + k)
*binomial(b + c, b + k)*binomial(c + a, c + k))
Sm = Sum(sk, (k, 1, oo))
T = Sm.doit() # hypergeometric series not calculated
assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c))
def test_R6():
n, k = symbols('n k', integer=True, positive=True)
gn = MatrixSymbol('gn', n + 2, 1)
Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1))
assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0]
def test_R7():
n, k = symbols('n k', integer=True, positive=True)
T = Sum(k**3,(k,1,n)).doit()
assert T.factor() == n**2*(n + 1)**2/4
@XFAIL
def test_R8():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(k**2*binomial(n, k), (k, 1, n))
T = Sm.doit() #returns Piecewise function
assert T.combsimp() == n*(n + 1)*2**(n - 2)
def test_R9():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1))
assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1)
@XFAIL
def test_R10():
n, m, r, k = symbols('n m r k', integer=True, positive=True)
Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r))
T = Sm.doit()
T2 = T.combsimp().rewrite(factorial)
assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r))
assert T2 == binomial(m + n, r).rewrite(factorial)
# rewrite(binomial) is not working.
# https://github.com/sympy/sympy/issues/7135
T3 = T2.rewrite(binomial)
assert T3 == binomial(m + n, r)
@XFAIL
def test_R11():
n, k = symbols('n k', integer=True, positive=True)
sk = binomial(n, k)*fibonacci(k)
Sm = Sum(sk, (k, 0, n))
T = Sm.doit()
# Fibonacci simplification not implemented
# https://github.com/sympy/sympy/issues/7134
assert T == fibonacci(2*n)
@XFAIL
def test_R12():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(fibonacci(k)**2, (k, 0, n))
T = Sm.doit()
assert T == fibonacci(n)*fibonacci(n + 1)
@XFAIL
def test_R13():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(sin(k*x), (k, 1, n))
T = Sm.doit() # Sum is not calculated
assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2))
@XFAIL
def test_R14():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(sin((2*k - 1)*x), (k, 1, n))
T = Sm.doit() # Sum is not calculated
assert T.simplify() == sin(n*x)**2/sin(x)
@XFAIL
def test_R15():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2)))
T = Sm.doit() # Sum is not calculated
assert T.simplify() == fibonacci(n + 1)
def test_R16():
k = symbols('k', integer=True, positive=True)
Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo))
assert Sm.doit() == zeta(3) + pi**2/6
def test_R17():
k = symbols('k', integer=True, positive=True)
assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo)))
- 2.8469909700078206) < 1e-15
def test_R18():
k = symbols('k', integer=True, positive=True)
Sm = Sum(1/(2**k*k**2), (k, 1, oo))
T = Sm.doit()
assert T.simplify() == -log(2)**2/2 + pi**2/12
@slow
@XFAIL
def test_R19():
k = symbols('k', integer=True, positive=True)
Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo))
T = Sm.doit()
# assert fails, T not simplified
assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12
@XFAIL
def test_R20():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(binomial(n, 4*k), (k, 0, oo))
T = Sm.doit()
# assert fails, T not simplified
assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2
@XFAIL
def test_R21():
k = symbols('k', integer=True, positive=True)
Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo))
T = Sm.doit() # Sum not calculated
assert T.simplify() == 1
# test_R22 answer not available in Wester samples
# Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k),
# (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1?
@XFAIL
def test_R23():
n, k = symbols('n k', integer=True, positive=True)
Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))*
(x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo))
# Missing how to express constraint abs(x*y)<1?
T = Sm.doit() # Sum not calculated
assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1)
def test_R24():
m, k = symbols('m k', integer=True, positive=True)
Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo))
assert Sm.doit() == pi/2
def test_S1():
k = symbols('k', integer=True, positive=True)
Pr = Product(gamma(k/3), (k, 1, 8))
assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561
def test_S2():
n, k = symbols('n k', integer=True, positive=True)
assert Product(k, (k, 1, n)).doit() == factorial(n)
def test_S3():
n, k = symbols('n k', integer=True, positive=True)
assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2)
def test_S4():
n, k = symbols('n k', integer=True, positive=True)
assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n
def test_S5():
n, k = symbols('n k', integer=True, positive=True)
assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() ==
gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1)))
@XFAIL
def test_S6():
n, k = symbols('n k', integer=True, positive=True)
# Product does not evaluate
assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify()
== (x**(2*n) - 1)/(x**2 - 1))
@XFAIL
def test_S7():
k = symbols('k', integer=True, positive=True)
Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo))
T = Pr.doit() # Product does not evaluate
assert T.simplify() == R(2, 3)
@XFAIL
def test_S8():
k = symbols('k', integer=True, positive=True)
Pr = Product(1 - 1/(2*k)**2, (k, 1, oo))
T = Pr.doit()
# Product does not evaluate
assert T.simplify() == 2/pi
@XFAIL
def test_S9():
k = symbols('k', integer=True, positive=True)
Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo))
T = Pr.doit()
# Product produces 0
# https://github.com/sympy/sympy/issues/7133
assert T.simplify() == sqrt(2)
@XFAIL
def test_S10():
k = symbols('k', integer=True, positive=True)
Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo))
T = Pr.doit()
# Product does not evaluate
assert T.simplify() == -1
def test_T1():
assert limit((1 + 1/n)**n, n, oo) == E
assert limit((1 - cos(x))/x**2, x, 0) == S.Half
def test_T2():
assert limit((3**x + 5**x)**(1/x), x, oo) == 5
def test_T3():
assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1
def test_T4():
assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1))))
- exp(x))/x, x, oo) == -exp(2)
def test_T5():
assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2
+ 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3)
def test_T6():
assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1)
def test_T7():
limit(1/n * gamma(n + 1)**(1/n), n, oo)
def test_T8():
a, z = symbols('a z', positive=True)
assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1
@XFAIL
def test_T9():
z, k = symbols('z k', positive=True)
# raises NotImplementedError:
# Don't know how to calculate the mrv of '(1, k)'
assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z)
@XFAIL
def test_T10():
# No longer raises PoleError, but should return euler-mascheroni constant
assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo))
@XFAIL
def test_T11():
n, k = symbols('n k', integer=True, positive=True)
# evaluates to 0
assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x)
def test_T12():
x, t = symbols('x t', real=True)
# Does not evaluate the limit but returns an expression with erf
assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)),
x, 0) == 1
def test_T13():
x = symbols('x', real=True)
assert [limit(x/abs(x), x, 0, dir='-'),
limit(x/abs(x), x, 0, dir='+')] == [-1, 1]
def test_T14():
x = symbols('x', real=True)
assert limit(atan(-log(x)), x, 0, dir='+') == pi/2
def test_U1():
x = symbols('x', real=True)
assert diff(abs(x), x) == sign(x)
def test_U2():
f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0)))
assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0))
def test_U3():
f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1)))
f1 = Lambda(x, diff(f(x), x))
assert f1(x) == 3*x**2
assert f1(1) == 3
@XFAIL
def test_U4():
n = symbols('n', integer=True, positive=True)
x = symbols('x', real=True)
d = diff(x**n, x, n)
assert d.rewrite(factorial) == factorial(n)
def test_U5():
# issue 6681
t = symbols('t')
ans = (
Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) +
Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2)
assert f(g(t)).diff(t, 2) == ans
assert ans.doit() == ans
def test_U6():
h = Function('h')
T = integrate(f(y), (y, h(x), g(x)))
assert T.diff(x) == (
f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x))
@XFAIL
def test_U7():
p, t = symbols('p t', real=True)
# Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT
# raises ValueError: Since there is more than one variable in the
# expression, the variable(s) of differentiation must be supplied to
# differentiate f(p,t)
diff(f(p, t))
def test_U8():
x, y = symbols('x y', real=True)
eq = cos(x*y) + x
# If SymPy had implicit_diff() function this hack could be avoided
# TODO: Replace solve with solveset, current test fails for solveset
assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1)
def test_U9():
# Wester sample case for Maple:
# O29 := diff(f(x, y), x) + diff(f(x, y), y);
# /d \ /d \
# |-- f(x, y)| + |-- f(x, y)|
# \dx / \dy /
#
# O30 := factor(subs(f(x, y) = g(x^2 + y^2), %));
# 2 2
# 2 D(g)(x + y ) (x + y)
x, y = symbols('x y', real=True)
su = diff(f(x, y), x) + diff(f(x, y), y)
s2 = su.subs(f(x, y), g(x**2 + y**2))
s3 = s2.doit().factor()
# Subs not performed, s3 = 2*(x + y)*Subs(Derivative(
# g(_xi_1), _xi_1), _xi_1, x**2 + y**2)
# Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy,
# and probably will remain that way. You can take derivatives with respect
# to other expressions only if they are atomic, like a symbol or a
# function.
# D operator should be added to SymPy
# See https://github.com/sympy/sympy/issues/4719.
assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2
def test_U10():
# see issue 2519:
assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4)
@XFAIL
def test_U11():
# assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz
raise NotImplementedError
@XFAIL
def test_U12():
# Wester sample case:
# (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy)
# => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */
# factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy));
# 4
# (d41) (10 x y + 15 x + 8) dx dy dz
raise NotImplementedError(
"External diff of differential form not supported")
def test_U13():
assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1
@XFAIL
def test_U14():
#f = 1/(x**2 + y**2 + 1)
#assert [minimize(f), maximize(f)] == [0,1]
raise NotImplementedError("minimize(), maximize() not supported")
@XFAIL
def test_U15():
raise NotImplementedError("minimize() not supported and also solve does \
not support multivariate inequalities")
@XFAIL
def test_U16():
raise NotImplementedError("minimize() not supported in SymPy and also \
solve does not support multivariate inequalities")
@XFAIL
def test_U17():
raise NotImplementedError("Linear programming, symbolic simplex not \
supported in SymPy")
def test_V1():
x = symbols('x', real=True)
assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True))
def test_V2():
assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x
) == Piecewise((-x**2/2, x < 0), (x**2/2, True))
def test_V3():
assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2)
def test_V4():
assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2)
@XFAIL
def test_V5():
# Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1))
assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() ==
(-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2)))
@XFAIL
def test_V6():
# returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m
assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*(
log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m))
def test_V7():
r1 = integrate(sinh(x)**4/cosh(x)**2)
assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2
@XFAIL
def test_V8_V9():
#Macsyma test case:
#(c27) /* This example involves several symbolic parameters
# => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/
# [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2)
# [Gradshteyn and Ryzhik 2.553(3)] */
#assume(b^2 > a^2)$
#(c28) integrate(1/(a + b*cos(x)), x);
#(c29) trigsimp(ratsimp(diff(%, x)));
# 1
#(d29) ------------
# b cos(x) + a
raise NotImplementedError(
"Integrate with assumption not supported")
def test_V10():
assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(4*tan(x/2) + 3)/4
def test_V11():
r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x)
r2 = factor(r1)
assert (logcombine(r2, force=True) ==
log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3)))
def test_V12():
r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x)
assert r1 == -1/(tan(x/2) + 2)
@XFAIL
def test_V13():
r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x)
# expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3
# - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11
assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11
@slow
@XFAIL
def test_V14():
r1 = integrate(log(abs(x**2 - y**2)), x)
# Piecewise result does not simplify to the desired result.
assert (r1.simplify() == x*log(abs(x**2 - y**2))
+ y*log(x + y) - y*log(x - y) - 2*x)
def test_V15():
r1 = integrate(x*acot(x/y), x)
assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0
@XFAIL
def test_V16():
# Integral not calculated
assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10
@XFAIL
def test_V17():
r1 = integrate((diff(f(x), x)*g(x)
- f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x)
# integral not calculated
assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0
@XFAIL
def test_W1():
# The function has a pole at y.
# The integral has a Cauchy principal value of zero but SymPy returns -I*pi
# https://github.com/sympy/sympy/issues/7159
assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0
@XFAIL
def test_W2():
# The function has a pole at y.
# The integral is divergent but SymPy returns -2
# https://github.com/sympy/sympy/issues/7160
# Test case in Macsyma:
# (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1));
# Integral is divergent
assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo
@XFAIL
@slow
def test_W3():
# integral is not calculated
# https://github.com/sympy/sympy/issues/7161
assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3)
@XFAIL
@slow
def test_W4():
# integral is not calculated
assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3)
@XFAIL
@slow
def test_W5():
# integral is not calculated
assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3)
@XFAIL
@slow
def test_W6():
# integral is not calculated
assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2)
def test_W7():
a = symbols('a', positive=True)
r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo))
assert r1.simplify() == pi*exp(-a)/a
@XFAIL
def test_W8():
# Test case in Mathematica:
# In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity},
# Assumptions -> 0 < a < 1]
# Out[19]= Pi Csc[a Pi]
raise NotImplementedError(
"Integrate with assumption 0 < a < 1 not supported")
@XFAIL
@slow
def test_W9():
# Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)]
# (principal value) [Levinson and Redheffer, p. 234] *)
r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo))
r2 = r1.doit()
assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8))
@XFAIL
def test_W10():
# integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) =
# 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1])
# [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */
r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo))
r2 = r1.doit()
assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5
@XFAIL
def test_W11():
# integral not calculated
assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) ==
pi*(-1 + sqrt(2)))
def test_W12():
p = symbols('p', positive=True)
q = symbols('q', real=True)
r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo))
assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2)
@XFAIL
def test_W13():
# Integral not calculated. Expected result is 2*(Euler_mascheroni_constant)
r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1))
assert r1 == 2*EulerGamma
def test_W14():
assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0
@XFAIL
def test_W15():
# integral not calculated
assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12)
def test_W16():
assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x),
(x, -1, 1)) == R(36, 35)
def test_W17():
a, b = symbols('a b', positive=True)
assert integrate(exp(-a*x)*besselj(0, b*x),
(x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1))
def test_W18():
assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi)
@XFAIL
def test_W19():
# Integral not calculated
# Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)]
assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7
@XFAIL
def test_W20():
# integral not calculated
assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) ==
-pi**2/36 - R(17, 108) + zeta(3)/4 +
(-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9)
def test_W21():
assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)))
- 0.210882859565594) < 1e-15
def test_W22():
t, u = symbols('t u', real=True)
s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True)))
assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise(
(0, u < 0),
(-sin(Min(1, u)) + sin(Min(2, u)), True))
@slow
def test_W23():
a, b = symbols('a b', positive=True)
r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo))
assert r1.collect(pi).cancel() == -pi*a + pi*b
def test_W23b():
# like W23 but limits are reversed
a, b = symbols('a b', positive=True)
r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b))
assert r2.collect(pi) == pi*(-a + b)
@XFAIL
@slow
def test_W24():
if ON_TRAVIS:
skip("Too slow for travis.")
# Not that slow, but does not fully evaluate so simplify is slow.
# Maybe also require doit()
x, y = symbols('x y', real=True)
r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1))
assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0
@XFAIL
@slow
def test_W25():
if ON_TRAVIS:
skip("Too slow for travis.")
a, x, y = symbols('a x y', real=True)
i1 = integrate(
sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2),
(x, 0, pi/2))
i2 = integrate(i1, (y, 0, pi/2))
assert (i2 - pi*a/2).simplify() == 0
def test_W26():
x, y = symbols('x y', real=True)
assert integrate(integrate(abs(y - x**2), (y, 0, 2)),
(x, -1, 1)) == R(46, 15)
def test_W27():
a, b, c = symbols('a b c')
assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))),
(y, 0, b*(1 - x/a))),
(x, 0, a)) == a*b*c/6
def test_X1():
v, c = symbols('v c', real=True)
assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) ==
5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8))
def test_X2():
v, c = symbols('v c', real=True)
s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8)
assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8)
def test_X3():
s1 = (sin(x).series()/cos(x).series()).series()
s2 = tan(x).series()
assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6)
assert s1 == s2
def test_X4():
s1 = log(sin(x)/x).series()
assert s1 == -x**2/6 - x**4/180 + O(x**6)
assert log(series(sin(x)/x)).series() == s1
@XFAIL
def test_X5():
# test case in Mathematica syntax:
# In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)]
# + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *)
# In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}]
# Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x]
# In[23]:= Series[%, {x, d, 1}]
# Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) +
# 2 2
# (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x]
h = Function('h')
a, b, c, d = symbols('a b c d', real=True)
# series() raises NotImplementedError:
# The _eval_nseries method should be added to <class
# 'sympy.core.function.Subs'> to give terms up to O(x**n) at x=0
series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)),
x, x0=d, n=2)
# assert missing, until exception is removed
def test_X6():
# Taylor series of nonscalar objects (noncommutative multiplication)
# expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg]
a, b = symbols('a b', commutative=False, scalar=False)
assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) ==
x**2*(-a*b/2 + b*a/2) + O(x**3))
def test_X7():
# => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity )
# = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6)
# [Levinson and Redheffer, p. 173]
assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) +
R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7))
def test_X8():
# Puiseux series (terms with fractional degree):
# => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2))
# see issue 7167:
x = symbols('x', real=True)
assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) ==
1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 +
(x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2))))
def test_X9():
assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 +
x**3*log(x)**3/6 + O(x**4*log(x)**4))
def test_X10():
z, w = symbols('z w')
assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) ==
log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2))
def test_X11():
z, w = symbols('z w')
assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) ==
log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2))
@XFAIL
def test_X12():
# Look at the generalized Taylor series around x = 1
# Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)]
a, b, x = symbols('a b x', real=True)
# series returns O(log(x-1)**2)
# https://github.com/sympy/sympy/issues/7168
assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) ==
(x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2)))
def test_X13():
assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo))
@XFAIL
def test_X14():
# Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385]
assert series(1/2**(2*n)*binomial(2*n, n),
n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo))
@SKIP("https://github.com/sympy/sympy/issues/7164")
def test_X15():
# => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544]
x, t = symbols('x t', real=True)
# raises RuntimeError: maximum recursion depth exceeded
# https://github.com/sympy/sympy/issues/7164
# 2019-02-17: Raises
# PoleError:
# Asymptotic expansion of Ei around [-oo] is not implemented.
e1 = integrate(exp(-t)/t, (t, x, oo))
assert (series(e1, x, x0=oo, n=5) ==
6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo)))
def test_X16():
# Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4)
assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 +
O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y))
@XFAIL
def test_X17():
# Power series (compute the general formula)
# (c41) powerseries(log(sin(x)/x), x, 0);
# /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded.
# inf
# ==== i1 2 i1 2 i1
# \ (- 1) 2 bern(2 i1) x
# (d41) > ------------------------------
# / 2 i1 (2 i1)!
# ====
# i1 = 1
# fps does not calculate
assert fps(log(sin(x)/x)) == \
Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo))
@XFAIL
def test_X18():
# Power series (compute the general formula). Maple FPS:
# > FormalPowerSeries(exp(-x)*sin(x), x = 0);
# infinity
# ----- (1/2 k) k
# \ 2 sin(3/4 k Pi) x
# ) -------------------------
# / k!
# -----
#
# Now, SymPy returns
# oo
# _____
# \ `
# \ / k k\
# \ k |I*(-1 - I) I*(-1 + I) |
# \ x *|----------- - -----------|
# / \ 2 2 /
# / ------------------------------
# / k!
# /____,
# k = 0
k = Dummy('k')
assert fps(exp(-x)*sin(x)) == \
Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo))
@XFAIL
def test_X19():
# (c45) /* Derive an explicit Taylor series solution of y as a function of
# x from the following implicit relation:
# y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 +
# 17/10 (x - 1)^5 + ...
# */
# x = sin(y) + cos(y);
# Time= 0 msecs
# (d45) x = sin(y) + cos(y)
#
# (c46) taylor_revert(%, y, 7);
raise NotImplementedError("Solve using series not supported. \
Inverse Taylor series expansion also not supported")
@XFAIL
def test_X20():
# Pade (rational function) approximation => (2 - x)/(2 + x)
# > numapprox[pade](exp(-x), x = 0, [1, 1]);
# bytes used=9019816, alloc=3669344, time=13.12
# 1 - 1/2 x
# ---------
# 1 + 1/2 x
# mpmath support numeric Pade approximant but there is
# no symbolic implementation in SymPy
# https://en.wikipedia.org/wiki/Pad%C3%A9_approximant
raise NotImplementedError("Symbolic Pade approximant not supported")
def test_X21():
"""
Test whether `fourier_series` of x periodical on the [-p, p] interval equals
`- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`.
"""
p = symbols('p', positive=True)
n = symbols('n', positive=True, integer=True)
s = fourier_series(x, (x, -p, p))
# All cosine coefficients are equal to 0
assert s.an.formula == 0
# Check for sine coefficients
assert s.bn.formula.subs(s.bn.variables[0], 0) == 0
assert s.bn.formula.subs(s.bn.variables[0], n) == \
-2*p/pi * (-1)**n / n * sin(n*pi*x/p)
@XFAIL
def test_X22():
# (c52) /* => p / 2
# - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2,
# n = 1..infinity ) */
# fourier_series(abs(x), x, p);
# p
# (e52) a = -
# 0 2
#
# %nn
# (2 (- 1) - 2) p
# (e53) a = ------------------
# %nn 2 2
# %pi %nn
#
# (e54) b = 0
# %nn
#
# Time= 5290 msecs
# inf %nn %pi %nn x
# ==== (2 (- 1) - 2) cos(---------)
# \ p
# p > -------------------------------
# / 2
# ==== %nn
# %nn = 1 p
# (d54) ----------------------------------------- + -
# 2 2
# %pi
raise NotImplementedError("Fourier series not supported")
def test_Y1():
t = symbols('t', positive=True)
w = symbols('w', real=True)
s = symbols('s')
F, _, _ = laplace_transform(cos((w - 1)*t), t, s)
assert F == s/(s**2 + (w - 1)**2)
def test_Y2():
t = symbols('t', positive=True)
w = symbols('w', real=True)
s = symbols('s')
f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t)
assert f == cos(t*(w - 1))
def test_Y3():
t = symbols('t', positive=True)
w = symbols('w', real=True)
s = symbols('s')
F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s)
assert F == w/(s**2 - 4*w**2)
def test_Y4():
t = symbols('t', positive=True)
s = symbols('s')
F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s)
assert F == (1 - exp(-6*sqrt(s)))/s
def test_Y5_Y6():
# Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the
# Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and
# duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T.
# Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing
# Company, 1983, p. 211. First, take the Laplace transform of the ODE
# => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)]
# where Y(s) is the Laplace transform of y(t)
t = symbols('t', positive=True)
s = symbols('s')
y = Function('y')
F, _, _ = laplace_transform(diff(y(t), t, 2)
+ y(t)
- 4*(Heaviside(t - 1)
- Heaviside(t - 2)), t, s)
assert (F == s**2*LaplaceTransform(y(t), t, s) - s*y(0) +
LaplaceTransform(y(t), t, s) - Subs(Derivative(y(t), t), t, 0) -
4*exp(-s)/s + 4*exp(-2*s)/s)
# TODO implement second part of test case
# Now, solve for Y(s) and then take the inverse Laplace transform
# => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)]
# => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)}
@XFAIL
def test_Y7():
# What is the Laplace transform of an infinite square wave?
# => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity )
# [Sanchez, Allen and Kyner, p. 213]
t = symbols('t', positive=True)
a = symbols('a', real=True)
s = symbols('s')
F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a),
(n, 1, oo)), t, s)
# returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t),
# (n, 1, oo)), t, s) + 1/s
# https://github.com/sympy/sympy/issues/7177
assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s
@XFAIL
def test_Y8():
assert fourier_transform(1, x, z) == DiracDelta(z)
def test_Y9():
assert (fourier_transform(exp(-9*x**2), x, z) ==
sqrt(pi)*exp(-pi**2*z**2/9)/3)
def test_Y10():
assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() ==
(-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81))
@SKIP("https://github.com/sympy/sympy/issues/7181")
@slow
def test_Y11():
# => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)]
x, s = symbols('x s')
# raises RuntimeError: maximum recursion depth exceeded
# https://github.com/sympy/sympy/issues/7181
# Update 2019-02-17 raises:
# TypeError: cannot unpack non-iterable MellinTransform object
F, _, _ = mellin_transform(1/(1 - x), x, s)
assert F == pi*cot(pi*s)
@XFAIL
def test_Y12():
# => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1)
# [Gradshteyn and Ryzhik 17.43(16)]
x, s = symbols('x s')
# returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1)
# https://github.com/sympy/sympy/issues/7182
F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s)
assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4)
@XFAIL
def test_Y13():
# Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z
raise NotImplementedError("z-transform not supported")
@XFAIL
def test_Y14():
# Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function)
raise NotImplementedError("z-transform not supported")
def test_Z1():
r = Function('r')
assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n),
{r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1)
def test_Z2():
r = Function('r')
assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1})
== -2**n + 3**n)
def test_Z3():
# => r(n) = Fibonacci[n + 1] [Cohen, p. 83]
r = Function('r')
# recurrence solution is correct, Wester expects it to be simplified to
# fibonacci(n+1), but that is quite hard
expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10)
+ (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2))
sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2})
assert sol == expected
@XFAIL
def test_Z4():
# => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)]
# [Joan Z. Yu and Robert Israel in sci.math.symbolic]
r = Function('r')
c = symbols('c')
# raises ValueError: Polynomial or rational function expected,
# got '(c**2 - c**n)/(c - c**n)
s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1)
- c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1),
r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)})
assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) +
(n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0)
@XFAIL
def test_Z5():
# Second order ODE with initial conditions---solve directly
# transform: f(t) = sin(2 t)/8 - t cos(2 t)/4
C1, C2 = symbols('C1 C2')
# initial conditions not supported, this is a manual workaround
# https://github.com/sympy/sympy/issues/4720
eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x)
sol = dsolve(eq, f(x))
f0 = Lambda(x, sol.rhs)
assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x)
f1 = Lambda(x, diff(f0(x), x))
# TODO: Replace solve with solveset, when it works for solveset
const_dict = solve((f0(0), f1(0)))
result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2])
assert result == -x*cos(2*x)/4 + sin(2*x)/8
# Result is OK, but ODE solving with initial conditions should be
# supported without all this manual work
raise NotImplementedError('ODE solving with initial conditions \
not supported')
@XFAIL
def test_Z6():
# Second order ODE with initial conditions---solve using Laplace
# transform: f(t) = sin(2 t)/8 - t cos(2 t)/4
t = symbols('t', positive=True)
s = symbols('s')
eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t)
F, _, _ = laplace_transform(eq, t, s)
# Laplace transform for diff() not calculated
# https://github.com/sympy/sympy/issues/7176
assert (F == s**2*LaplaceTransform(f(t), t, s) +
4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4))
# rest of test case not implemented
|
f0bdb3c195fcfd0b8dc1cc76e2cc1c4144ef5d84cefb98be62b3cbd614d15152 | from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.function import (Function, Lambda, diff)
from sympy.core.mod import Mod
from sympy.core import (Catalan, EulerGamma, GoldenRatio)
from sympy.core.numbers import (E, Float, I, Integer, Rational, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (conjugate, sign)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import Integral
from sympy.sets.fancysets import Range
from sympy.codegen import For, Assignment, aug_assign
from sympy.codegen.ast import Declaration, Variable, float32, float64, \
value_const, real, bool_, While, FunctionPrototype, FunctionDefinition, \
integer, Return, Element
from sympy.core.expr import UnevaluatedExpr
from sympy.core.relational import Relational
from sympy.logic.boolalg import And, Or, Not, Equivalent, Xor
from sympy.matrices import Matrix, MatrixSymbol
from sympy.printing.fortran import fcode, FCodePrinter
from sympy.tensor import IndexedBase, Idx
from sympy.tensor.array.expressions import ArraySymbol, ArrayElement
from sympy.utilities.lambdify import implemented_function
from sympy.testing.pytest import raises
def test_UnevaluatedExpr():
p, q, r = symbols("p q r", real=True)
q_r = UnevaluatedExpr(q + r)
expr = abs(exp(p+q_r))
assert fcode(expr, source_format="free") == "exp(p + (q + r))"
x, y, z = symbols("x y z")
y_z = UnevaluatedExpr(y + z)
expr2 = abs(exp(x+y_z))
assert fcode(expr2, human=False)[2].lstrip() == "exp(re(x) + re(y + z))"
assert fcode(expr2, user_functions={"re": "realpart"}).lstrip() == "exp(realpart(x) + realpart(y + z))"
def test_printmethod():
x = symbols('x')
class nint(Function):
def _fcode(self, printer):
return "nint(%s)" % printer._print(self.args[0])
assert fcode(nint(x)) == " nint(x)"
def test_fcode_sign(): #issue 12267
x=symbols('x')
y=symbols('y', integer=True)
z=symbols('z', complex=True)
assert fcode(sign(x), standard=95, source_format='free') == "merge(0d0, dsign(1d0, x), x == 0d0)"
assert fcode(sign(y), standard=95, source_format='free') == "merge(0, isign(1, y), y == 0)"
assert fcode(sign(z), standard=95, source_format='free') == "merge(cmplx(0d0, 0d0), z/abs(z), abs(z) == 0d0)"
raises(NotImplementedError, lambda: fcode(sign(x)))
def test_fcode_Pow():
x, y = symbols('x,y')
n = symbols('n', integer=True)
assert fcode(x**3) == " x**3"
assert fcode(x**(y**3)) == " x**(y**3)"
assert fcode(1/(sin(x)*3.5)**(x - y**x)/(x**2 + y)) == \
" (3.5d0*sin(x))**(-x + y**x)/(x**2 + y)"
assert fcode(sqrt(x)) == ' sqrt(x)'
assert fcode(sqrt(n)) == ' sqrt(dble(n))'
assert fcode(x**0.5) == ' sqrt(x)'
assert fcode(sqrt(x)) == ' sqrt(x)'
assert fcode(sqrt(10)) == ' sqrt(10.0d0)'
assert fcode(x**-1.0) == ' 1d0/x'
assert fcode(x**-2.0, 'y', source_format='free') == 'y = x**(-2.0d0)' # 2823
assert fcode(x**Rational(3, 7)) == ' x**(3.0d0/7.0d0)'
def test_fcode_Rational():
x = symbols('x')
assert fcode(Rational(3, 7)) == " 3.0d0/7.0d0"
assert fcode(Rational(18, 9)) == " 2"
assert fcode(Rational(3, -7)) == " -3.0d0/7.0d0"
assert fcode(Rational(-3, -7)) == " 3.0d0/7.0d0"
assert fcode(x + Rational(3, 7)) == " x + 3.0d0/7.0d0"
assert fcode(Rational(3, 7)*x) == " (3.0d0/7.0d0)*x"
def test_fcode_Integer():
assert fcode(Integer(67)) == " 67"
assert fcode(Integer(-1)) == " -1"
def test_fcode_Float():
assert fcode(Float(42.0)) == " 42.0000000000000d0"
assert fcode(Float(-1e20)) == " -1.00000000000000d+20"
def test_fcode_functions():
x, y = symbols('x,y')
assert fcode(sin(x) ** cos(y)) == " sin(x)**cos(y)"
raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=66))
raises(NotImplementedError, lambda: fcode(x % y, standard=66))
raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=77))
raises(NotImplementedError, lambda: fcode(x % y, standard=77))
for standard in [90, 95, 2003, 2008]:
assert fcode(Mod(x, y), standard=standard) == " modulo(x, y)"
assert fcode(x % y, standard=standard) == " modulo(x, y)"
def test_case():
ob = FCodePrinter()
x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y')
assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \
' exp(x_) + sin(x*y) + cos(X__*Y_)'
assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \
' 2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)'
assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \
' exp(x_) + sin(x*y) + cos(X*Y)'
assert fcode(x - cos(X), name_mangling=False) == ' x - cos(X)'
assert ob.doprint(X*sin(x) + x_, assign_to='me') == ' me = X*sin(x_) + x__'
assert ob.doprint(X*sin(x), assign_to='mu') == ' mu = X*sin(x_)'
assert ob.doprint(x_, assign_to='ad') == ' ad = x__'
n, m = symbols('n,m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
I = Idx('I', n)
assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == (
"do i = 1, m\n"
" y(i) = 0\n"
"end do\n"
"do i = 1, m\n"
" do I_ = 1, n\n"
" y(i) = A(i, I_)*x(I_) + y(i)\n"
" end do\n"
"end do" )
#issue 6814
def test_fcode_functions_with_integers():
x= symbols('x')
log10_17 = log(10).evalf(17)
loglog10_17 = '0.8340324452479558d0'
assert fcode(x * log(10)) == " x*%sd0" % log10_17
assert fcode(x * log(10)) == " x*%sd0" % log10_17
assert fcode(x * log(S(10))) == " x*%sd0" % log10_17
assert fcode(log(S(10))) == " %sd0" % log10_17
assert fcode(exp(10)) == " %sd0" % exp(10).evalf(17)
assert fcode(x * log(log(10))) == " x*%s" % loglog10_17
assert fcode(x * log(log(S(10)))) == " x*%s" % loglog10_17
def test_fcode_NumberSymbol():
prec = 17
p = FCodePrinter()
assert fcode(Catalan) == ' parameter (Catalan = %sd0)\n Catalan' % Catalan.evalf(prec)
assert fcode(EulerGamma) == ' parameter (EulerGamma = %sd0)\n EulerGamma' % EulerGamma.evalf(prec)
assert fcode(E) == ' parameter (E = %sd0)\n E' % E.evalf(prec)
assert fcode(GoldenRatio) == ' parameter (GoldenRatio = %sd0)\n GoldenRatio' % GoldenRatio.evalf(prec)
assert fcode(pi) == ' parameter (pi = %sd0)\n pi' % pi.evalf(prec)
assert fcode(
pi, precision=5) == ' parameter (pi = %sd0)\n pi' % pi.evalf(5)
assert fcode(Catalan, human=False) == ({
(Catalan, p._print(Catalan.evalf(prec)))}, set(), ' Catalan')
assert fcode(EulerGamma, human=False) == ({(EulerGamma, p._print(
EulerGamma.evalf(prec)))}, set(), ' EulerGamma')
assert fcode(E, human=False) == (
{(E, p._print(E.evalf(prec)))}, set(), ' E')
assert fcode(GoldenRatio, human=False) == ({(GoldenRatio, p._print(
GoldenRatio.evalf(prec)))}, set(), ' GoldenRatio')
assert fcode(pi, human=False) == (
{(pi, p._print(pi.evalf(prec)))}, set(), ' pi')
assert fcode(pi, precision=5, human=False) == (
{(pi, p._print(pi.evalf(5)))}, set(), ' pi')
def test_fcode_complex():
assert fcode(I) == " cmplx(0,1)"
x = symbols('x')
assert fcode(4*I) == " cmplx(0,4)"
assert fcode(3 + 4*I) == " cmplx(3,4)"
assert fcode(3 + 4*I + x) == " cmplx(3,4) + x"
assert fcode(I*x) == " cmplx(0,1)*x"
assert fcode(3 + 4*I - x) == " cmplx(3,4) - x"
x = symbols('x', imaginary=True)
assert fcode(5*x) == " 5*x"
assert fcode(I*x) == " cmplx(0,1)*x"
assert fcode(3 + x) == " x + 3"
def test_implicit():
x, y = symbols('x,y')
assert fcode(sin(x)) == " sin(x)"
assert fcode(atan2(x, y)) == " atan2(x, y)"
assert fcode(conjugate(x)) == " conjg(x)"
def test_not_fortran():
x = symbols('x')
g = Function('g')
gamma_f = fcode(gamma(x))
assert gamma_f == "C Not supported in Fortran:\nC gamma\n gamma(x)"
assert fcode(Integral(sin(x))) == "C Not supported in Fortran:\nC Integral\n Integral(sin(x), x)"
assert fcode(g(x)) == "C Not supported in Fortran:\nC g\n g(x)"
def test_user_functions():
x = symbols('x')
assert fcode(sin(x), user_functions={"sin": "zsin"}) == " zsin(x)"
x = symbols('x')
assert fcode(
gamma(x), user_functions={"gamma": "mygamma"}) == " mygamma(x)"
g = Function('g')
assert fcode(g(x), user_functions={"g": "great"}) == " great(x)"
n = symbols('n', integer=True)
assert fcode(
factorial(n), user_functions={"factorial": "fct"}) == " fct(n)"
def test_inline_function():
x = symbols('x')
g = implemented_function('g', Lambda(x, 2*x))
assert fcode(g(x)) == " 2*x"
g = implemented_function('g', Lambda(x, 2*pi/x))
assert fcode(g(x)) == (
" parameter (pi = %sd0)\n"
" 2*pi/x"
) % pi.evalf(17)
A = IndexedBase('A')
i = Idx('i', symbols('n', integer=True))
g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
assert fcode(g(A[i]), assign_to=A[i]) == (
" do i = 1, n\n"
" A(i) = (A(i) + 1)*(A(i) + 2)*A(i)\n"
" end do"
)
def test_assign_to():
x = symbols('x')
assert fcode(sin(x), assign_to="s") == " s = sin(x)"
def test_line_wrapping():
x, y = symbols('x,y')
assert fcode(((x + y)**10).expand(), assign_to="var") == (
" var = x**10 + 10*x**9*y + 45*x**8*y**2 + 120*x**7*y**3 + 210*x**6*\n"
" @ y**4 + 252*x**5*y**5 + 210*x**4*y**6 + 120*x**3*y**7 + 45*x**2*y\n"
" @ **8 + 10*x*y**9 + y**10"
)
e = [x**i for i in range(11)]
assert fcode(Add(*e)) == (
" x**10 + x**9 + x**8 + x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x\n"
" @ + 1"
)
def test_fcode_precedence():
x, y = symbols("x y")
assert fcode(And(x < y, y < x + 1), source_format="free") == \
"x < y .and. y < x + 1"
assert fcode(Or(x < y, y < x + 1), source_format="free") == \
"x < y .or. y < x + 1"
assert fcode(Xor(x < y, y < x + 1, evaluate=False),
source_format="free") == "x < y .neqv. y < x + 1"
assert fcode(Equivalent(x < y, y < x + 1), source_format="free") == \
"x < y .eqv. y < x + 1"
def test_fcode_Logical():
x, y, z = symbols("x y z")
# unary Not
assert fcode(Not(x), source_format="free") == ".not. x"
# binary And
assert fcode(And(x, y), source_format="free") == "x .and. y"
assert fcode(And(x, Not(y)), source_format="free") == "x .and. .not. y"
assert fcode(And(Not(x), y), source_format="free") == "y .and. .not. x"
assert fcode(And(Not(x), Not(y)), source_format="free") == \
".not. x .and. .not. y"
assert fcode(Not(And(x, y), evaluate=False), source_format="free") == \
".not. (x .and. y)"
# binary Or
assert fcode(Or(x, y), source_format="free") == "x .or. y"
assert fcode(Or(x, Not(y)), source_format="free") == "x .or. .not. y"
assert fcode(Or(Not(x), y), source_format="free") == "y .or. .not. x"
assert fcode(Or(Not(x), Not(y)), source_format="free") == \
".not. x .or. .not. y"
assert fcode(Not(Or(x, y), evaluate=False), source_format="free") == \
".not. (x .or. y)"
# mixed And/Or
assert fcode(And(Or(y, z), x), source_format="free") == "x .and. (y .or. z)"
assert fcode(And(Or(z, x), y), source_format="free") == "y .and. (x .or. z)"
assert fcode(And(Or(x, y), z), source_format="free") == "z .and. (x .or. y)"
assert fcode(Or(And(y, z), x), source_format="free") == "x .or. y .and. z"
assert fcode(Or(And(z, x), y), source_format="free") == "y .or. x .and. z"
assert fcode(Or(And(x, y), z), source_format="free") == "z .or. x .and. y"
# trinary And
assert fcode(And(x, y, z), source_format="free") == "x .and. y .and. z"
assert fcode(And(x, y, Not(z)), source_format="free") == \
"x .and. y .and. .not. z"
assert fcode(And(x, Not(y), z), source_format="free") == \
"x .and. z .and. .not. y"
assert fcode(And(Not(x), y, z), source_format="free") == \
"y .and. z .and. .not. x"
assert fcode(Not(And(x, y, z), evaluate=False), source_format="free") == \
".not. (x .and. y .and. z)"
# trinary Or
assert fcode(Or(x, y, z), source_format="free") == "x .or. y .or. z"
assert fcode(Or(x, y, Not(z)), source_format="free") == \
"x .or. y .or. .not. z"
assert fcode(Or(x, Not(y), z), source_format="free") == \
"x .or. z .or. .not. y"
assert fcode(Or(Not(x), y, z), source_format="free") == \
"y .or. z .or. .not. x"
assert fcode(Not(Or(x, y, z), evaluate=False), source_format="free") == \
".not. (x .or. y .or. z)"
def test_fcode_Xlogical():
x, y, z = symbols("x y z")
# binary Xor
assert fcode(Xor(x, y, evaluate=False), source_format="free") == \
"x .neqv. y"
assert fcode(Xor(x, Not(y), evaluate=False), source_format="free") == \
"x .neqv. .not. y"
assert fcode(Xor(Not(x), y, evaluate=False), source_format="free") == \
"y .neqv. .not. x"
assert fcode(Xor(Not(x), Not(y), evaluate=False),
source_format="free") == ".not. x .neqv. .not. y"
assert fcode(Not(Xor(x, y, evaluate=False), evaluate=False),
source_format="free") == ".not. (x .neqv. y)"
# binary Equivalent
assert fcode(Equivalent(x, y), source_format="free") == "x .eqv. y"
assert fcode(Equivalent(x, Not(y)), source_format="free") == \
"x .eqv. .not. y"
assert fcode(Equivalent(Not(x), y), source_format="free") == \
"y .eqv. .not. x"
assert fcode(Equivalent(Not(x), Not(y)), source_format="free") == \
".not. x .eqv. .not. y"
assert fcode(Not(Equivalent(x, y), evaluate=False),
source_format="free") == ".not. (x .eqv. y)"
# mixed And/Equivalent
assert fcode(Equivalent(And(y, z), x), source_format="free") == \
"x .eqv. y .and. z"
assert fcode(Equivalent(And(z, x), y), source_format="free") == \
"y .eqv. x .and. z"
assert fcode(Equivalent(And(x, y), z), source_format="free") == \
"z .eqv. x .and. y"
assert fcode(And(Equivalent(y, z), x), source_format="free") == \
"x .and. (y .eqv. z)"
assert fcode(And(Equivalent(z, x), y), source_format="free") == \
"y .and. (x .eqv. z)"
assert fcode(And(Equivalent(x, y), z), source_format="free") == \
"z .and. (x .eqv. y)"
# mixed Or/Equivalent
assert fcode(Equivalent(Or(y, z), x), source_format="free") == \
"x .eqv. y .or. z"
assert fcode(Equivalent(Or(z, x), y), source_format="free") == \
"y .eqv. x .or. z"
assert fcode(Equivalent(Or(x, y), z), source_format="free") == \
"z .eqv. x .or. y"
assert fcode(Or(Equivalent(y, z), x), source_format="free") == \
"x .or. (y .eqv. z)"
assert fcode(Or(Equivalent(z, x), y), source_format="free") == \
"y .or. (x .eqv. z)"
assert fcode(Or(Equivalent(x, y), z), source_format="free") == \
"z .or. (x .eqv. y)"
# mixed Xor/Equivalent
assert fcode(Equivalent(Xor(y, z, evaluate=False), x),
source_format="free") == "x .eqv. (y .neqv. z)"
assert fcode(Equivalent(Xor(z, x, evaluate=False), y),
source_format="free") == "y .eqv. (x .neqv. z)"
assert fcode(Equivalent(Xor(x, y, evaluate=False), z),
source_format="free") == "z .eqv. (x .neqv. y)"
assert fcode(Xor(Equivalent(y, z), x, evaluate=False),
source_format="free") == "x .neqv. (y .eqv. z)"
assert fcode(Xor(Equivalent(z, x), y, evaluate=False),
source_format="free") == "y .neqv. (x .eqv. z)"
assert fcode(Xor(Equivalent(x, y), z, evaluate=False),
source_format="free") == "z .neqv. (x .eqv. y)"
# mixed And/Xor
assert fcode(Xor(And(y, z), x, evaluate=False), source_format="free") == \
"x .neqv. y .and. z"
assert fcode(Xor(And(z, x), y, evaluate=False), source_format="free") == \
"y .neqv. x .and. z"
assert fcode(Xor(And(x, y), z, evaluate=False), source_format="free") == \
"z .neqv. x .and. y"
assert fcode(And(Xor(y, z, evaluate=False), x), source_format="free") == \
"x .and. (y .neqv. z)"
assert fcode(And(Xor(z, x, evaluate=False), y), source_format="free") == \
"y .and. (x .neqv. z)"
assert fcode(And(Xor(x, y, evaluate=False), z), source_format="free") == \
"z .and. (x .neqv. y)"
# mixed Or/Xor
assert fcode(Xor(Or(y, z), x, evaluate=False), source_format="free") == \
"x .neqv. y .or. z"
assert fcode(Xor(Or(z, x), y, evaluate=False), source_format="free") == \
"y .neqv. x .or. z"
assert fcode(Xor(Or(x, y), z, evaluate=False), source_format="free") == \
"z .neqv. x .or. y"
assert fcode(Or(Xor(y, z, evaluate=False), x), source_format="free") == \
"x .or. (y .neqv. z)"
assert fcode(Or(Xor(z, x, evaluate=False), y), source_format="free") == \
"y .or. (x .neqv. z)"
assert fcode(Or(Xor(x, y, evaluate=False), z), source_format="free") == \
"z .or. (x .neqv. y)"
# trinary Xor
assert fcode(Xor(x, y, z, evaluate=False), source_format="free") == \
"x .neqv. y .neqv. z"
assert fcode(Xor(x, y, Not(z), evaluate=False), source_format="free") == \
"x .neqv. y .neqv. .not. z"
assert fcode(Xor(x, Not(y), z, evaluate=False), source_format="free") == \
"x .neqv. z .neqv. .not. y"
assert fcode(Xor(Not(x), y, z, evaluate=False), source_format="free") == \
"y .neqv. z .neqv. .not. x"
def test_fcode_Relational():
x, y = symbols("x y")
assert fcode(Relational(x, y, "=="), source_format="free") == "x == y"
assert fcode(Relational(x, y, "!="), source_format="free") == "x /= y"
assert fcode(Relational(x, y, ">="), source_format="free") == "x >= y"
assert fcode(Relational(x, y, "<="), source_format="free") == "x <= y"
assert fcode(Relational(x, y, ">"), source_format="free") == "x > y"
assert fcode(Relational(x, y, "<"), source_format="free") == "x < y"
def test_fcode_Piecewise():
x = symbols('x')
expr = Piecewise((x, x < 1), (x**2, True))
# Check that inline conditional (merge) fails if standard isn't 95+
raises(NotImplementedError, lambda: fcode(expr))
code = fcode(expr, standard=95)
expected = " merge(x, x**2, x < 1)"
assert code == expected
assert fcode(Piecewise((x, x < 1), (x**2, True)), assign_to="var") == (
" if (x < 1) then\n"
" var = x\n"
" else\n"
" var = x**2\n"
" end if"
)
a = cos(x)/x
b = sin(x)/x
for i in range(10):
a = diff(a, x)
b = diff(b, x)
expected = (
" if (x < 0) then\n"
" weird_name = -cos(x)/x + 10*sin(x)/x**2 + 90*cos(x)/x**3 - 720*\n"
" @ sin(x)/x**4 - 5040*cos(x)/x**5 + 30240*sin(x)/x**6 + 151200*cos(x\n"
" @ )/x**7 - 604800*sin(x)/x**8 - 1814400*cos(x)/x**9 + 3628800*sin(x\n"
" @ )/x**10 + 3628800*cos(x)/x**11\n"
" else\n"
" weird_name = -sin(x)/x - 10*cos(x)/x**2 + 90*sin(x)/x**3 + 720*\n"
" @ cos(x)/x**4 - 5040*sin(x)/x**5 - 30240*cos(x)/x**6 + 151200*sin(x\n"
" @ )/x**7 + 604800*cos(x)/x**8 - 1814400*sin(x)/x**9 - 3628800*cos(x\n"
" @ )/x**10 + 3628800*sin(x)/x**11\n"
" end if"
)
code = fcode(Piecewise((a, x < 0), (b, True)), assign_to="weird_name")
assert code == expected
code = fcode(Piecewise((x, x < 1), (x**2, x > 1), (sin(x), True)), standard=95)
expected = " merge(x, merge(x**2, sin(x), x > 1), x < 1)"
assert code == expected
# Check that Piecewise without a True (default) condition error
expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
raises(ValueError, lambda: fcode(expr))
def test_wrap_fortran():
# "########################################################################"
printer = FCodePrinter()
lines = [
"C This is a long comment on a single line that must be wrapped properly to produce nice output",
" this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly",
]
wrapped_lines = printer._wrap_fortran(lines)
expected_lines = [
"C This is a long comment on a single line that must be wrapped",
"C properly to produce nice output",
" this = is + a + long + and + nasty + fortran + statement + that *",
" @ must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that *",
" @ must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that",
" @ * must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that*",
" @ must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that*",
" @ must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that",
" @ *must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement +",
" @ that*must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that**",
" @ must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that**",
" @ must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that",
" @ **must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement + that",
" @ **must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement +",
" @ that**must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement(that)/",
" @ must + be + wrapped + properly",
" this = is + a + long + and + nasty + fortran + statement(that)",
" @ /must + be + wrapped + properly",
]
for line in wrapped_lines:
assert len(line) <= 72
for w, e in zip(wrapped_lines, expected_lines):
assert w == e
assert len(wrapped_lines) == len(expected_lines)
def test_wrap_fortran_keep_d0():
printer = FCodePrinter()
lines = [
' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break =1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break = 10.0d0'
]
expected = [
' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break =',
' @ 1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break =',
' @ 1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break =',
' @ 1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break =',
' @ 1.0d0',
' this_variable_is_very_long_because_we_try_to_test_line_break =',
' @ 10.0d0'
]
assert printer._wrap_fortran(lines) == expected
def test_settings():
raises(TypeError, lambda: fcode(S(4), method="garbage"))
def test_free_form_code_line():
x, y = symbols('x,y')
assert fcode(cos(x) + sin(y), source_format='free') == "sin(y) + cos(x)"
def test_free_form_continuation_line():
x, y = symbols('x,y')
result = fcode(((cos(x) + sin(y))**(7)).expand(), source_format='free')
expected = (
'sin(y)**7 + 7*sin(y)**6*cos(x) + 21*sin(y)**5*cos(x)**2 + 35*sin(y)**4* &\n'
' cos(x)**3 + 35*sin(y)**3*cos(x)**4 + 21*sin(y)**2*cos(x)**5 + 7* &\n'
' sin(y)*cos(x)**6 + cos(x)**7'
)
assert result == expected
def test_free_form_comment_line():
printer = FCodePrinter({'source_format': 'free'})
lines = [ "! This is a long comment on a single line that must be wrapped properly to produce nice output"]
expected = [
'! This is a long comment on a single line that must be wrapped properly',
'! to produce nice output']
assert printer._wrap_fortran(lines) == expected
def test_loops():
n, m = symbols('n,m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
expected = (
'do i = 1, m\n'
' y(i) = 0\n'
'end do\n'
'do i = 1, m\n'
' do j = 1, n\n'
' y(i) = %(rhs)s\n'
' end do\n'
'end do'
)
code = fcode(A[i, j]*x[j], assign_to=y[i], source_format='free')
assert (code == expected % {'rhs': 'y(i) + A(i, j)*x(j)'} or
code == expected % {'rhs': 'y(i) + x(j)*A(i, j)'} or
code == expected % {'rhs': 'x(j)*A(i, j) + y(i)'} or
code == expected % {'rhs': 'A(i, j)*x(j) + y(i)'})
def test_dummy_loops():
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'do i_%(icount)i = 1, m_%(mcount)i\n'
' y(i_%(icount)i) = x(i_%(icount)i)\n'
'end do'
) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
code = fcode(x[i], assign_to=y[i], source_format='free')
assert code == expected
def test_fcode_Indexed_without_looking_for_contraction():
len_y = 5
y = IndexedBase('y', shape=(len_y,))
x = IndexedBase('x', shape=(len_y,))
Dy = IndexedBase('Dy', shape=(len_y-1,))
i = Idx('i', len_y-1)
e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
code0 = fcode(e.rhs, assign_to=e.lhs, contract=False)
assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
def test_element_like_objects():
len_y = 5
y = ArraySymbol('y', shape=(len_y,))
x = ArraySymbol('x', shape=(len_y,))
Dy = ArraySymbol('Dy', shape=(len_y-1,))
i = Idx('i', len_y-1)
e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
code0 = fcode(Assignment(e.lhs, e.rhs))
assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
class ElementExpr(Element, Expr):
pass
e = e.subs((a, ElementExpr(a.name, a.indices)) for a in e.atoms(ArrayElement) )
e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
code0 = fcode(Assignment(e.lhs, e.rhs))
assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
def test_derived_classes():
class MyFancyFCodePrinter(FCodePrinter):
_default_settings = FCodePrinter._default_settings.copy()
printer = MyFancyFCodePrinter()
x = symbols('x')
assert printer.doprint(sin(x), "bork") == " bork = sin(x)"
def test_indent():
codelines = (
'subroutine test(a)\n'
'integer :: a, i, j\n'
'\n'
'do\n'
'do \n'
'do j = 1, 5\n'
'if (a>b) then\n'
'if(b>0) then\n'
'a = 3\n'
'donot_indent_me = 2\n'
'do_not_indent_me_either = 2\n'
'ifIam_indented_something_went_wrong = 2\n'
'if_I_am_indented_something_went_wrong = 2\n'
'end should not be unindented here\n'
'end if\n'
'endif\n'
'end do\n'
'end do\n'
'enddo\n'
'end subroutine\n'
'\n'
'subroutine test2(a)\n'
'integer :: a\n'
'do\n'
'a = a + 1\n'
'end do \n'
'end subroutine\n'
)
expected = (
'subroutine test(a)\n'
'integer :: a, i, j\n'
'\n'
'do\n'
' do \n'
' do j = 1, 5\n'
' if (a>b) then\n'
' if(b>0) then\n'
' a = 3\n'
' donot_indent_me = 2\n'
' do_not_indent_me_either = 2\n'
' ifIam_indented_something_went_wrong = 2\n'
' if_I_am_indented_something_went_wrong = 2\n'
' end should not be unindented here\n'
' end if\n'
' endif\n'
' end do\n'
' end do\n'
'enddo\n'
'end subroutine\n'
'\n'
'subroutine test2(a)\n'
'integer :: a\n'
'do\n'
' a = a + 1\n'
'end do \n'
'end subroutine\n'
)
p = FCodePrinter({'source_format': 'free'})
result = p.indent_code(codelines)
assert result == expected
def test_Matrix_printing():
x, y, z = symbols('x,y,z')
# Test returning a Matrix
mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
A = MatrixSymbol('A', 3, 1)
assert fcode(mat, A) == (
" A(1, 1) = x*y\n"
" if (y > 0) then\n"
" A(2, 1) = x + 2\n"
" else\n"
" A(2, 1) = y\n"
" end if\n"
" A(3, 1) = sin(z)")
# Test using MatrixElements in expressions
expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
assert fcode(expr, standard=95) == (
" merge(2*A(3, 1), A(3, 1), x > 0) + sin(A(2, 1)) + A(1, 1)")
# Test using MatrixElements in a Matrix
q = MatrixSymbol('q', 5, 1)
M = MatrixSymbol('M', 3, 3)
m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
[q[1,0] + q[2,0], q[3, 0], 5],
[2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
assert fcode(m, M) == (
" M(1, 1) = sin(q(2, 1))\n"
" M(2, 1) = q(2, 1) + q(3, 1)\n"
" M(3, 1) = 2*q(5, 1)/q(2, 1)\n"
" M(1, 2) = 0\n"
" M(2, 2) = q(4, 1)\n"
" M(3, 2) = sqrt(q(1, 1)) + 4\n"
" M(1, 3) = cos(q(3, 1))\n"
" M(2, 3) = 5\n"
" M(3, 3) = 0")
def test_fcode_For():
x, y = symbols('x y')
f = For(x, Range(0, 10, 2), [Assignment(y, x * y)])
sol = fcode(f)
assert sol == (" do x = 0, 9, 2\n"
" y = x*y\n"
" end do")
def test_fcode_Declaration():
def check(expr, ref, **kwargs):
assert fcode(expr, standard=95, source_format='free', **kwargs) == ref
i = symbols('i', integer=True)
var1 = Variable.deduced(i)
dcl1 = Declaration(var1)
check(dcl1, "integer*4 :: i")
x, y = symbols('x y')
var2 = Variable(x, float32, value=42, attrs={value_const})
dcl2b = Declaration(var2)
check(dcl2b, 'real*4, parameter :: x = 42')
var3 = Variable(y, type=bool_)
dcl3 = Declaration(var3)
check(dcl3, 'logical :: y')
check(float32, "real*4")
check(float64, "real*8")
check(real, "real*4", type_aliases={real: float32})
check(real, "real*8", type_aliases={real: float64})
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
assert(fcode(A[0, 0]) == " A(1, 1)")
assert(fcode(3 * A[0, 0]) == " 3*A(1, 1)")
F = C[0, 0].subs(C, A - B)
assert(fcode(F) == " (A - B)(1, 1)")
def test_aug_assign():
x = symbols('x')
assert fcode(aug_assign(x, '+', 1), source_format='free') == 'x = x + 1'
def test_While():
x = symbols('x')
assert fcode(While(abs(x) > 1, [aug_assign(x, '-', 1)]), source_format='free') == (
'do while (abs(x) > 1)\n'
' x = x - 1\n'
'end do'
)
def test_FunctionPrototype_print():
x = symbols('x')
n = symbols('n', integer=True)
vx = Variable(x, type=real)
vn = Variable(n, type=integer)
fp1 = FunctionPrototype(real, 'power', [vx, vn])
# Should be changed to proper test once multi-line generation is working
# see https://github.com/sympy/sympy/issues/15824
raises(NotImplementedError, lambda: fcode(fp1))
def test_FunctionDefinition_print():
x = symbols('x')
n = symbols('n', integer=True)
vx = Variable(x, type=real)
vn = Variable(n, type=integer)
body = [Assignment(x, x**n), Return(x)]
fd1 = FunctionDefinition(real, 'power', [vx, vn], body)
# Should be changed to proper test once multi-line generation is working
# see https://github.com/sympy/sympy/issues/15824
raises(NotImplementedError, lambda: fcode(fd1))
|
c31776a0f80489f0e29b7f99ea1aa47d33dcc289675e2b20fe55a0f32159d154 | from sympy import MatAdd, MatMul, Array
from sympy.algebras.quaternion import Quaternion
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.combinatorics.permutations import Cycle, Permutation, AppliedPermutation
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core.containers import Tuple, Dict
from sympy.core.expr import UnevaluatedExpr
from sympy.core.function import (Derivative, Function, Lambda, Subs, diff)
from sympy.core.mod import Mod
from sympy.core.mul import Mul
from sympy.core.numbers import (AlgebraicNumber, Float, I, Integer, Rational, oo, pi)
from sympy.core.power import Pow
from sympy.core.relational import Eq, Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, Wild, symbols)
from sympy.functions.combinatorial.factorials import (FallingFactorial, RisingFactorial, binomial, factorial, factorial2, subfactorial)
from sympy.functions.combinatorial.numbers import bernoulli, bell, catalan, euler, genocchi, lucas, fibonacci, tribonacci
from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, polar_lift, re)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (asinh, coth)
from sympy.functions.elementary.integers import (ceiling, floor, frac)
from sympy.functions.elementary.miscellaneous import (Max, Min, root, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acsc, asin, cos, cot, sin, tan)
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f, elliptic_k, elliptic_pi)
from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint)
from sympy.functions.special.gamma_functions import (gamma, uppergamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.functions.special.mathieu_functions import (mathieuc, mathieucprime, mathieus, mathieusprime)
from sympy.functions.special.polynomials import (assoc_laguerre, assoc_legendre, chebyshevt, chebyshevu, gegenbauer, hermite, jacobi, laguerre, legendre)
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.spherical_harmonics import (Ynm, Znm)
from sympy.functions.special.tensor_functions import (KroneckerDelta, LeviCivita)
from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, stieltjes, zeta)
from sympy.integrals.integrals import Integral
from sympy.integrals.transforms import (CosineTransform, FourierTransform, InverseCosineTransform, InverseFourierTransform, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, LaplaceTransform, MellinTransform, SineTransform)
from sympy.logic import Implies
from sympy.logic.boolalg import (And, Or, Xor, Equivalent, false, Not, true)
from sympy.matrices.dense import Matrix
from sympy.matrices.expressions.kronecker import KroneckerProduct
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.permutation import PermutationMatrix
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback
from sympy.ntheory.factor_ import (divisor_sigma, primenu, primeomega, reduced_totient, totient, udivisor_sigma)
from sympy.physics.quantum import Commutator, Operator
from sympy.physics.quantum.trace import Tr
from sympy.physics.units import meter, gibibyte, gram, microgram, second, milli, micro
from sympy.polys.domains.integerring import ZZ
from sympy.polys.fields import field
from sympy.polys.polytools import Poly
from sympy.polys.rings import ring
from sympy.polys.rootoftools import (RootSum, rootof)
from sympy.series.formal import fps
from sympy.series.fourier import fourier_series
from sympy.series.limits import Limit
from sympy.series.order import Order
from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer)
from sympy.sets.conditionset import ConditionSet
from sympy.sets.contains import Contains
from sympy.sets.fancysets import (ComplexRegion, ImageSet, Range)
from sympy.sets.ordinals import Ordinal, OrdinalOmega, OmegaPower
from sympy.sets.powerset import PowerSet
from sympy.sets.sets import (FiniteSet, Interval, Union, Intersection, Complement, SymmetricDifference, ProductSet)
from sympy.sets.setexpr import SetExpr
from sympy.stats.crv_types import Normal
from sympy.stats.symbolic_probability import (Covariance, Expectation,
Probability, Variance)
from sympy.tensor.array import (ImmutableDenseNDimArray,
ImmutableSparseNDimArray,
MutableSparseNDimArray,
MutableDenseNDimArray,
tensorproduct)
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement
from sympy.tensor.indexed import (Idx, Indexed, IndexedBase)
from sympy.tensor.toperators import PartialDerivative
from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian
from sympy.testing.pytest import (XFAIL, raises, _both_exp_pow,
warns_deprecated_sympy)
from sympy.printing.latex import (latex, translate, greek_letters_set,
tex_greek_dictionary, multiline_latex,
latex_escape, LatexPrinter)
import sympy as sym
from sympy.abc import mu, tau
class lowergamma(sym.lowergamma):
pass # testing notation inheritance by a subclass with same name
x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p')
k, m, n = symbols('k m n', integer=True)
def test_printmethod():
class R(Abs):
def _latex(self, printer):
return "foo(%s)" % printer._print(self.args[0])
assert latex(R(x)) == r"foo(x)"
class R(Abs):
def _latex(self, printer):
return "foo"
assert latex(R(x)) == r"foo"
def test_latex_basic():
assert latex(1 + x) == r"x + 1"
assert latex(x**2) == r"x^{2}"
assert latex(x**(1 + x)) == r"x^{x + 1}"
assert latex(x**3 + x + 1 + x**2) == r"x^{3} + x^{2} + x + 1"
assert latex(2*x*y) == r"2 x y"
assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y"
assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y"
assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}"
assert latex(x**S.Half**5) == r"\sqrt[32]{x}"
assert latex(Mul(S.Half, x**2, -5, evaluate=False)) == r"\frac{1}{2} x^{2} \left(-5\right)"
assert latex(Mul(S.Half, x**2, 5, evaluate=False)) == r"\frac{1}{2} x^{2} \cdot 5"
assert latex(Mul(-5, -5, evaluate=False)) == r"\left(-5\right) \left(-5\right)"
assert latex(Mul(5, -5, evaluate=False)) == r"5 \left(-5\right)"
assert latex(Mul(S.Half, -5, S.Half, evaluate=False)) == r"\frac{1}{2} \left(-5\right) \frac{1}{2}"
assert latex(Mul(5, I, 5, evaluate=False)) == r"5 i 5"
assert latex(Mul(5, I, -5, evaluate=False)) == r"5 i \left(-5\right)"
assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1'
assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0'
assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1'
assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1'
assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1'
assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2'
assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \cdot \frac{1}{2}'
assert latex(Mul(1, 1, S.Half, evaluate=False)) == \
r'1 \cdot 1 \cdot \frac{1}{2}'
assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \
r'1 \cdot 1 \cdot 2 \cdot 3 x'
assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)'
assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \
r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x'
assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \
r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x'
assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \
r'\frac{2}{3} \cdot \frac{5}{7}'
assert latex(1/x) == r"\frac{1}{x}"
assert latex(1/x, fold_short_frac=True) == r"1 / x"
assert latex(-S(3)/2) == r"- \frac{3}{2}"
assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2"
assert latex(1/x**2) == r"\frac{1}{x^{2}}"
assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}"
assert latex(x/2) == r"\frac{x}{2}"
assert latex(x/2, fold_short_frac=True) == r"x / 2"
assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}"
assert latex((x + y)/(2*x), fold_short_frac=True) == \
r"\left(x + y\right) / 2 x"
assert latex((x + y)/(2*x), long_frac_ratio=0) == \
r"\frac{1}{2 x} \left(x + y\right)"
assert latex((x + y)/x) == r"\frac{x + y}{x}"
assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}"
assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}"
assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \
r"\frac{2 x}{3} \sqrt{2}"
assert latex(binomial(x, y)) == r"{\binom{x}{y}}"
x_star = Symbol('x^*')
f = Function('f')
assert latex(x_star**2) == r"\left(x^{*}\right)^{2}"
assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}"
assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}"
assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}"
assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}"
assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \
r"\left(2 \int x\, dx\right) / 3"
assert latex(sqrt(x)) == r"\sqrt{x}"
assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}"
assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}"
assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}"
assert latex(sqrt(x), itex=True) == r"\sqrt{x}"
assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}"
assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}"
assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}"
assert latex(x**Rational(3, 4), fold_frac_powers=True) == r"x^{3/4}"
assert latex((x + 1)**Rational(3, 4)) == \
r"\left(x + 1\right)^{\frac{3}{4}}"
assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \
r"\left(x + 1\right)^{3/4}"
assert latex(AlgebraicNumber(sqrt(2))) == r"\sqrt{2}"
assert latex(AlgebraicNumber(sqrt(2), [3, -7])) == r"-7 + 3 \sqrt{2}"
assert latex(AlgebraicNumber(sqrt(2), alias='alpha')) == r"\alpha"
assert latex(AlgebraicNumber(sqrt(2), [3, -7], alias='alpha')) == \
r"3 \alpha - 7"
assert latex(AlgebraicNumber(2**(S(1)/3), [1, 3, -7], alias='beta')) == \
r"\beta^{2} + 3 \beta - 7"
k = ZZ.cyclotomic_field(5)
assert latex(k.ext.field_element([1, 2, 3, 4])) == \
r"\zeta^{3} + 2 \zeta^{2} + 3 \zeta + 4"
assert latex(k.ext.field_element([1, 2, 3, 4]), order='old') == \
r"4 + 3 \zeta + 2 \zeta^{2} + \zeta^{3}"
assert latex(k.primes_above(19)[0]) == \
r"\left(19, \zeta^{2} + 5 \zeta + 1\right)"
assert latex(k.primes_above(19)[0], order='old') == \
r"\left(19, 1 + 5 \zeta + \zeta^{2}\right)"
assert latex(k.primes_above(7)[0]) == r"\left(7\right)"
assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x"
assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x"
assert latex(1.5e20*x, mul_symbol='times') == \
r"1.5 \times 10^{20} \times x"
assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}"
assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}"
assert latex(sin(x)**Rational(3, 2)) == \
r"\sin^{\frac{3}{2}}{\left(x \right)}"
assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \
r"\sin^{3/2}{\left(x \right)}"
assert latex(~x) == r"\neg x"
assert latex(x & y) == r"x \wedge y"
assert latex(x & y & z) == r"x \wedge y \wedge z"
assert latex(x | y) == r"x \vee y"
assert latex(x | y | z) == r"x \vee y \vee z"
assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)"
assert latex(Implies(x, y)) == r"x \Rightarrow y"
assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y"
assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z"
assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)"
assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)"
assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i"
assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \
r"x_i \wedge y_i"
assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
r"x_i \wedge y_i \wedge z_i"
assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i"
assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
r"x_i \vee y_i \vee z_i"
assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
r"z_i \vee \left(x_i \wedge y_i\right)"
assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \
r"x_i \Rightarrow y_i"
assert latex(Pow(Rational(1, 3), -1, evaluate=False)) == r"\frac{1}{\frac{1}{3}}"
assert latex(Pow(Rational(1, 3), -2, evaluate=False)) == r"\frac{1}{(\frac{1}{3})^{2}}"
assert latex(Pow(Integer(1)/100, -1, evaluate=False)) == r"\frac{1}{\frac{1}{100}}"
p = Symbol('p', positive=True)
assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}"
def test_latex_builtins():
assert latex(True) == r"\text{True}"
assert latex(False) == r"\text{False}"
assert latex(None) == r"\text{None}"
assert latex(true) == r"\text{True}"
assert latex(false) == r'\text{False}'
def test_latex_SingularityFunction():
assert latex(SingularityFunction(x, 4, 5)) == \
r"{\left\langle x - 4 \right\rangle}^{5}"
assert latex(SingularityFunction(x, -3, 4)) == \
r"{\left\langle x + 3 \right\rangle}^{4}"
assert latex(SingularityFunction(x, 0, 4)) == \
r"{\left\langle x \right\rangle}^{4}"
assert latex(SingularityFunction(x, a, n)) == \
r"{\left\langle - a + x \right\rangle}^{n}"
assert latex(SingularityFunction(x, 4, -2)) == \
r"{\left\langle x - 4 \right\rangle}^{-2}"
assert latex(SingularityFunction(x, 4, -1)) == \
r"{\left\langle x - 4 \right\rangle}^{-1}"
assert latex(SingularityFunction(x, 4, 5)**3) == \
r"{\left({\langle x - 4 \rangle}^{5}\right)}^{3}"
assert latex(SingularityFunction(x, -3, 4)**3) == \
r"{\left({\langle x + 3 \rangle}^{4}\right)}^{3}"
assert latex(SingularityFunction(x, 0, 4)**3) == \
r"{\left({\langle x \rangle}^{4}\right)}^{3}"
assert latex(SingularityFunction(x, a, n)**3) == \
r"{\left({\langle - a + x \rangle}^{n}\right)}^{3}"
assert latex(SingularityFunction(x, 4, -2)**3) == \
r"{\left({\langle x - 4 \rangle}^{-2}\right)}^{3}"
assert latex((SingularityFunction(x, 4, -1)**3)**3) == \
r"{\left({\langle x - 4 \rangle}^{-1}\right)}^{9}"
def test_latex_cycle():
assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)"
assert latex(Cycle(1, 2)(4, 5, 6)) == \
r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)"
assert latex(Cycle()) == r"\left( \right)"
def test_latex_permutation():
assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)"
assert latex(Permutation(1, 2)(4, 5, 6)) == \
r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)"
assert latex(Permutation()) == r"\left( \right)"
assert latex(Permutation(2, 4)*Permutation(5)) == \
r"\left( 2\; 4\right)\left( 5\right)"
assert latex(Permutation(5)) == r"\left( 5\right)"
assert latex(Permutation(0, 1), perm_cyclic=False) == \
r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}"
assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \
r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}"
assert latex(Permutation(), perm_cyclic=False) == \
r"\left( \right)"
with warns_deprecated_sympy():
old_print_cyclic = Permutation.print_cyclic
Permutation.print_cyclic = False
assert latex(Permutation(0, 1)(2, 3)) == \
r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}"
Permutation.print_cyclic = old_print_cyclic
def test_latex_Float():
assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}"
assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}"
assert latex(Float(1.0e-100), mul_symbol="times") == \
r"1.0 \times 10^{-100}"
assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \
r"1.0 \cdot 10^{4}"
assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \
r"1.0 \cdot 10^{4}"
assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \
r"10000.0"
assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \
r"9.99990000000000 \cdot 10^{-2}"
def test_latex_vector_expressions():
A = CoordSys3D('A')
assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \
r"\mathbf{\hat{i}_{A}} \times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)"
assert latex(Cross(A.i, A.j)) == \
r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}"
assert latex(x*Cross(A.i, A.j)) == \
r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)"
assert latex(Cross(x*A.i, A.j)) == \
r'- \mathbf{\hat{j}_{A}} \times \left(\left(x\right)\mathbf{\hat{i}_{A}}\right)'
assert latex(Curl(3*A.x*A.j)) == \
r"\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*A.x*A.j+A.i)) == \
r"\nabla\times \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*x*A.x*A.j)) == \
r"\nabla\times \left(\left(3 \mathbf{{x}_{A}} x\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Curl(3*A.x*A.j)) == \
r"x \left(\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)\right)"
assert latex(Divergence(3*A.x*A.j+A.i)) == \
r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(Divergence(3*A.x*A.j)) == \
r"\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Divergence(3*A.x*A.j)) == \
r"x \left(\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)\right)"
assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \
r"\mathbf{\hat{i}_{A}} \cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)"
assert latex(Dot(A.i, A.j)) == \
r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}"
assert latex(Dot(x*A.i, A.j)) == \
r"\mathbf{\hat{j}_{A}} \cdot \left(\left(x\right)\mathbf{\hat{i}_{A}}\right)"
assert latex(x*Dot(A.i, A.j)) == \
r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)"
assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}"
assert latex(Gradient(A.x + 3*A.y)) == \
r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)"
assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)"
assert latex(Laplacian(A.x)) == r"\Delta \mathbf{{x}_{A}}"
assert latex(Laplacian(A.x + 3*A.y)) == \
r"\Delta \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
assert latex(x*Laplacian(A.x)) == r"x \left(\Delta \mathbf{{x}_{A}}\right)"
assert latex(Laplacian(x*A.x)) == r"\Delta \left(\mathbf{{x}_{A}} x\right)"
def test_latex_symbols():
Gamma, lmbda, rho = symbols('Gamma, lambda, rho')
tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU')
assert latex(tau) == r"\tau"
assert latex(Tau) == r"\mathrm{T}"
assert latex(TAU) == r"\tau"
assert latex(taU) == r"\tau"
# Check that all capitalized greek letters are handled explicitly
capitalized_letters = {l.capitalize() for l in greek_letters_set}
assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0
assert latex(Gamma + lmbda) == r"\Gamma + \lambda"
assert latex(Gamma * lmbda) == r"\Gamma \lambda"
assert latex(Symbol('q1')) == r"q_{1}"
assert latex(Symbol('q21')) == r"q_{21}"
assert latex(Symbol('epsilon0')) == r"\epsilon_{0}"
assert latex(Symbol('omega1')) == r"\omega_{1}"
assert latex(Symbol('91')) == r"91"
assert latex(Symbol('alpha_new')) == r"\alpha_{new}"
assert latex(Symbol('C^orig')) == r"C^{orig}"
assert latex(Symbol('x^alpha')) == r"x^{\alpha}"
assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}"
assert latex(Symbol('e^Alpha')) == r"e^{\mathrm{A}}"
assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}"
assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}"
@XFAIL
def test_latex_symbols_failing():
rho, mass, volume = symbols('rho, mass, volume')
assert latex(
volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}"
assert latex(volume / mass * rho == 1) == \
r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1"
assert latex(mass**3 * volume**3) == \
r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}"
@_both_exp_pow
def test_latex_functions():
assert latex(exp(x)) == r"e^{x}"
assert latex(exp(1) + exp(2)) == r"e + e^{2}"
f = Function('f')
assert latex(f(x)) == r'f{\left(x \right)}'
assert latex(f) == r'f'
g = Function('g')
assert latex(g(x, y)) == r'g{\left(x,y \right)}'
assert latex(g) == r'g'
h = Function('h')
assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}'
assert latex(h) == r'h'
Li = Function('Li')
assert latex(Li) == r'\operatorname{Li}'
assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}'
mybeta = Function('beta')
# not to be confused with the beta function
assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}"
assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)'
assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)'
assert latex(mybeta(x)) == r"\beta{\left(x \right)}"
assert latex(mybeta) == r"\beta"
g = Function('gamma')
# not to be confused with the gamma function
assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}"
assert latex(g(x)) == r"\gamma{\left(x \right)}"
assert latex(g) == r"\gamma"
a_1 = Function('a_1')
assert latex(a_1) == r"a_{1}"
assert latex(a_1(x)) == r"a_{1}{\left(x \right)}"
assert latex(Function('a_1')) == r"a_{1}"
# Issue #16925
# multi letter function names
# > simple
assert latex(Function('ab')) == r"\operatorname{ab}"
assert latex(Function('ab1')) == r"\operatorname{ab}_{1}"
assert latex(Function('ab12')) == r"\operatorname{ab}_{12}"
assert latex(Function('ab_1')) == r"\operatorname{ab}_{1}"
assert latex(Function('ab_12')) == r"\operatorname{ab}_{12}"
assert latex(Function('ab_c')) == r"\operatorname{ab}_{c}"
assert latex(Function('ab_cd')) == r"\operatorname{ab}_{cd}"
# > with argument
assert latex(Function('ab')(Symbol('x'))) == r"\operatorname{ab}{\left(x \right)}"
assert latex(Function('ab1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}"
assert latex(Function('ab12')(Symbol('x'))) == r"\operatorname{ab}_{12}{\left(x \right)}"
assert latex(Function('ab_1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}"
assert latex(Function('ab_c')(Symbol('x'))) == r"\operatorname{ab}_{c}{\left(x \right)}"
assert latex(Function('ab_cd')(Symbol('x'))) == r"\operatorname{ab}_{cd}{\left(x \right)}"
# > with power
# does not work on functions without brackets
# > with argument and power combined
assert latex(Function('ab')()**2) == r"\operatorname{ab}^{2}{\left( \right)}"
assert latex(Function('ab1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}"
assert latex(Function('ab12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}"
assert latex(Function('ab_1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}"
assert latex(Function('ab_12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}"
assert latex(Function('ab')(Symbol('x'))**2) == r"\operatorname{ab}^{2}{\left(x \right)}"
assert latex(Function('ab1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}"
assert latex(Function('ab12')(Symbol('x'))**2) == r"\operatorname{ab}_{12}^{2}{\left(x \right)}"
assert latex(Function('ab_1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}"
assert latex(Function('ab_12')(Symbol('x'))**2) == \
r"\operatorname{ab}_{12}^{2}{\left(x \right)}"
# single letter function names
# > simple
assert latex(Function('a')) == r"a"
assert latex(Function('a1')) == r"a_{1}"
assert latex(Function('a12')) == r"a_{12}"
assert latex(Function('a_1')) == r"a_{1}"
assert latex(Function('a_12')) == r"a_{12}"
# > with argument
assert latex(Function('a')()) == r"a{\left( \right)}"
assert latex(Function('a1')()) == r"a_{1}{\left( \right)}"
assert latex(Function('a12')()) == r"a_{12}{\left( \right)}"
assert latex(Function('a_1')()) == r"a_{1}{\left( \right)}"
assert latex(Function('a_12')()) == r"a_{12}{\left( \right)}"
# > with power
# does not work on functions without brackets
# > with argument and power combined
assert latex(Function('a')()**2) == r"a^{2}{\left( \right)}"
assert latex(Function('a1')()**2) == r"a_{1}^{2}{\left( \right)}"
assert latex(Function('a12')()**2) == r"a_{12}^{2}{\left( \right)}"
assert latex(Function('a_1')()**2) == r"a_{1}^{2}{\left( \right)}"
assert latex(Function('a_12')()**2) == r"a_{12}^{2}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**2) == r"a^{2}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}"
assert latex(Function('a')()**32) == r"a^{32}{\left( \right)}"
assert latex(Function('a1')()**32) == r"a_{1}^{32}{\left( \right)}"
assert latex(Function('a12')()**32) == r"a_{12}^{32}{\left( \right)}"
assert latex(Function('a_1')()**32) == r"a_{1}^{32}{\left( \right)}"
assert latex(Function('a_12')()**32) == r"a_{12}^{32}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**32) == r"a^{32}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}"
assert latex(Function('a')()**a) == r"a^{a}{\left( \right)}"
assert latex(Function('a1')()**a) == r"a_{1}^{a}{\left( \right)}"
assert latex(Function('a12')()**a) == r"a_{12}^{a}{\left( \right)}"
assert latex(Function('a_1')()**a) == r"a_{1}^{a}{\left( \right)}"
assert latex(Function('a_12')()**a) == r"a_{12}^{a}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**a) == r"a^{a}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}"
ab = Symbol('ab')
assert latex(Function('a')()**ab) == r"a^{ab}{\left( \right)}"
assert latex(Function('a1')()**ab) == r"a_{1}^{ab}{\left( \right)}"
assert latex(Function('a12')()**ab) == r"a_{12}^{ab}{\left( \right)}"
assert latex(Function('a_1')()**ab) == r"a_{1}^{ab}{\left( \right)}"
assert latex(Function('a_12')()**ab) == r"a_{12}^{ab}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**ab) == r"a^{ab}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}"
assert latex(Function('a^12')(x)) == R"a^{12}{\left(x \right)}"
assert latex(Function('a^12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}"
assert latex(Function('a__12')(x)) == R"a^{12}{\left(x \right)}"
assert latex(Function('a__12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}"
assert latex(Function('a_1__1_2')(x)) == R"a^{1}_{1 2}{\left(x \right)}"
# issue 5868
omega1 = Function('omega1')
assert latex(omega1) == r"\omega_{1}"
assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}"
assert latex(sin(x)) == r"\sin{\left(x \right)}"
assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
assert latex(sin(2*x**2), fold_func_brackets=True) == \
r"\sin {2 x^{2}}"
assert latex(sin(x**2), fold_func_brackets=True) == \
r"\sin {x^{2}}"
assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}"
assert latex(asin(x)**2, inv_trig_style="full") == \
r"\arcsin^{2}{\left(x \right)}"
assert latex(asin(x)**2, inv_trig_style="power") == \
r"\sin^{-1}{\left(x \right)}^{2}"
assert latex(asin(x**2), inv_trig_style="power",
fold_func_brackets=True) == \
r"\sin^{-1} {x^{2}}"
assert latex(acsc(x), inv_trig_style="full") == \
r"\operatorname{arccsc}{\left(x \right)}"
assert latex(asinh(x), inv_trig_style="full") == \
r"\operatorname{arsinh}{\left(x \right)}"
assert latex(factorial(k)) == r"k!"
assert latex(factorial(-k)) == r"\left(- k\right)!"
assert latex(factorial(k)**2) == r"k!^{2}"
assert latex(subfactorial(k)) == r"!k"
assert latex(subfactorial(-k)) == r"!\left(- k\right)"
assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}"
assert latex(factorial2(k)) == r"k!!"
assert latex(factorial2(-k)) == r"\left(- k\right)!!"
assert latex(factorial2(k)**2) == r"k!!^{2}"
assert latex(binomial(2, k)) == r"{\binom{2}{k}}"
assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}"
assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}"
assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}"
assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor"
assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil"
assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}"
assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}"
assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}"
assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}"
assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
assert latex(Abs(x)) == r"\left|{x}\right|"
assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}"
assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}"
assert latex(re(x + y)) == \
r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}"
assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}"
assert latex(conjugate(x)) == r"\overline{x}"
assert latex(conjugate(x)**2) == r"\overline{x}^{2}"
assert latex(conjugate(x**2)) == r"\overline{x}^{2}"
assert latex(gamma(x)) == r"\Gamma\left(x\right)"
w = Wild('w')
assert latex(gamma(w)) == r"\Gamma\left(w\right)"
assert latex(Order(x)) == r"O\left(x\right)"
assert latex(Order(x, x)) == r"O\left(x\right)"
assert latex(Order(x, (x, 0))) == r"O\left(x\right)"
assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)"
assert latex(Order(x - y, (x, y))) == \
r"O\left(x - y; x\rightarrow y\right)"
assert latex(Order(x, x, y)) == \
r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)"
assert latex(Order(x, x, y)) == \
r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)"
assert latex(Order(x, (x, oo), (y, oo))) == \
r"O\left(x; \left( x, \ y\right)\rightarrow \left( \infty, \ \infty\right)\right)"
assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)'
assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'
assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)'
assert latex(cot(x)) == r'\cot{\left(x \right)}'
assert latex(coth(x)) == r'\coth{\left(x \right)}'
assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}'
assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}'
assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
assert latex(arg(x)) == r'\arg{\left(x \right)}'
assert latex(zeta(x)) == r"\zeta\left(x\right)"
assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
assert latex(
polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"
assert latex(stieltjes(x)) == r"\gamma_{x}"
assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}"
assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)"
assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}"
assert latex(elliptic_k(z)) == r"K\left(z\right)"
assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)"
assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)"
assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)"
assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)"
assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)"
assert latex(elliptic_e(z)) == r"E\left(z\right)"
assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)"
assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)"
assert latex(elliptic_pi(x, y, z)**2) == \
r"\Pi^{2}\left(x; y\middle| z\right)"
assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)"
assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)"
assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}'
assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}'
assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)'
assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}'
assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}'
assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}'
assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)'
assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)'
assert latex(jacobi(n, a, b, x)) == \
r'P_{n}^{\left(a,b\right)}\left(x\right)'
assert latex(jacobi(n, a, b, x)**2) == \
r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
assert latex(gegenbauer(n, a, x)) == \
r'C_{n}^{\left(a\right)}\left(x\right)'
assert latex(gegenbauer(n, a, x)**2) == \
r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
assert latex(chebyshevt(n, x)**2) == \
r'\left(T_{n}\left(x\right)\right)^{2}'
assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
assert latex(chebyshevu(n, x)**2) == \
r'\left(U_{n}\left(x\right)\right)^{2}'
assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
assert latex(assoc_legendre(n, a, x)) == \
r'P_{n}^{\left(a\right)}\left(x\right)'
assert latex(assoc_legendre(n, a, x)**2) == \
r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
assert latex(assoc_laguerre(n, a, x)) == \
r'L_{n}^{\left(a\right)}\left(x\right)'
assert latex(assoc_laguerre(n, a, x)**2) == \
r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'
theta = Symbol("theta", real=True)
phi = Symbol("phi", real=True)
assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)'
assert latex(Ynm(n, m, theta, phi)**3) == \
r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)'
assert latex(Znm(n, m, theta, phi)**3) == \
r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
# Test latex printing of function names with "_"
assert latex(polar_lift(0)) == \
r"\operatorname{polar\_lift}{\left(0 \right)}"
assert latex(polar_lift(0)**3) == \
r"\operatorname{polar\_lift}^{3}{\left(0 \right)}"
assert latex(totient(n)) == r'\phi\left(n\right)'
assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}'
assert latex(reduced_totient(n)) == r'\lambda\left(n\right)'
assert latex(reduced_totient(n) ** 2) == \
r'\left(\lambda\left(n\right)\right)^{2}'
assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)"
assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)"
assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)"
assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)"
assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)"
assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)"
assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)"
assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)"
assert latex(primenu(n)) == r'\nu\left(n\right)'
assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}'
assert latex(primeomega(n)) == r'\Omega\left(n\right)'
assert latex(primeomega(n) ** 2) == \
r'\left(\Omega\left(n\right)\right)^{2}'
assert latex(LambertW(n)) == r'W\left(n\right)'
assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)'
assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)'
assert latex(LambertW(n) * LambertW(n)) == r"W^{2}\left(n\right)"
assert latex(Pow(LambertW(n), 2)) == r"W^{2}\left(n\right)"
assert latex(LambertW(n)**k) == r"W^{k}\left(n\right)"
assert latex(LambertW(n, k)**p) == r"W^{p}_{k}\left(n\right)"
assert latex(Mod(x, 7)) == r'x \bmod 7'
assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right) \bmod 7'
assert latex(Mod(7, x + 1)) == r'7 \bmod \left(x + 1\right)'
assert latex(Mod(2 * x, 7)) == r'2 x \bmod 7'
assert latex(Mod(7, 2 * x)) == r'7 \bmod 2 x'
assert latex(Mod(x, 7) + 1) == r'\left(x \bmod 7\right) + 1'
assert latex(2 * Mod(x, 7)) == r'2 \left(x \bmod 7\right)'
assert latex(Mod(7, 2 * x)**n) == r'\left(7 \bmod 2 x\right)^{n}'
# some unknown function name should get rendered with \operatorname
fjlkd = Function('fjlkd')
assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}'
# even when it is referred to without an argument
assert latex(fjlkd) == r'\operatorname{fjlkd}'
# test that notation passes to subclasses of the same name only
def test_function_subclass_different_name():
class mygamma(gamma):
pass
assert latex(mygamma) == r"\operatorname{mygamma}"
assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}"
def test_hyper_printing():
from sympy.abc import x, z
assert latex(meijerg(Tuple(pi, pi, x), Tuple(1),
(0, 1), Tuple(1, 2, 3/pi), z)) == \
r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\
r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}'
assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \
r'{G_{1, 1}^{1, 0}\left(\begin{matrix} & 1 \\0 & \end{matrix} \middle| {z} \right)}'
assert latex(hyper((x, 2), (3,), z)) == \
r'{{}_{2}F_{1}\left(\begin{matrix} x, 2 ' \
r'\\ 3 \end{matrix}\middle| {z} \right)}'
assert latex(hyper(Tuple(), Tuple(1), z)) == \
r'{{}_{0}F_{1}\left(\begin{matrix} ' \
r'\\ 1 \end{matrix}\middle| {z} \right)}'
def test_latex_bessel():
from sympy.functions.special.bessel import (besselj, bessely, besseli,
besselk, hankel1, hankel2,
jn, yn, hn1, hn2)
from sympy.abc import z
assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)'
assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)'
assert latex(besseli(n, z)) == r'I_{n}\left(z\right)'
assert latex(besselk(n, z)) == r'K_{n}\left(z\right)'
assert latex(hankel1(n, z**2)**2) == \
r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}'
assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)'
assert latex(jn(n, z)) == r'j_{n}\left(z\right)'
assert latex(yn(n, z)) == r'y_{n}\left(z\right)'
assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)'
assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)'
def test_latex_fresnel():
from sympy.functions.special.error_functions import (fresnels, fresnelc)
from sympy.abc import z
assert latex(fresnels(z)) == r'S\left(z\right)'
assert latex(fresnelc(z)) == r'C\left(z\right)'
assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)'
assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)'
def test_latex_brackets():
assert latex((-1)**x) == r"\left(-1\right)^{x}"
def test_latex_indexed():
Psi_symbol = Symbol('Psi_0', complex=True, real=False)
Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False))
symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol))
indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0]))
# \\overline{{\\Psi}_{0}} {\\Psi}_{0} vs. \\Psi_{0} \\overline{\\Psi_{0}}
assert symbol_latex == r'\Psi_{0} \overline{\Psi_{0}}'
assert indexed_latex == r'\overline{{\Psi}_{0}} {\Psi}_{0}'
# Symbol('gamma') gives r'\gamma'
interval = '\\mathrel{..}\\nobreak '
assert latex(Indexed('x1', Symbol('i'))) == r'{x_{1}}_{i}'
assert latex(Indexed('x2', Idx('i'))) == r'{x_{2}}_{i}'
assert latex(Indexed('x3', Idx('i', Symbol('N')))) == r'{x_{3}}_{{i}_{0'+interval+'N - 1}}'
assert latex(Indexed('x3', Idx('i', Symbol('N')+1))) == r'{x_{3}}_{{i}_{0'+interval+'N}}'
assert latex(Indexed('x4', Idx('i', (Symbol('a'),Symbol('b'))))) == r'{x_{4}}_{{i}_{a'+interval+'b}}'
assert latex(IndexedBase('gamma')) == r'\gamma'
assert latex(IndexedBase('a b')) == r'a b'
assert latex(IndexedBase('a_b')) == r'a_{b}'
def test_latex_derivatives():
# regular "d" for ordinary derivatives
assert latex(diff(x**3, x, evaluate=False)) == \
r"\frac{d}{d x} x^{3}"
assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \
r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)"
assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\
== \
r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)"
assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \
r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)"
# \partial for partial derivatives
assert latex(diff(sin(x * y), x, evaluate=False)) == \
r"\frac{\partial}{\partial x} \sin{\left(x y \right)}"
assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \
r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)"
assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \
r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)"
assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \
r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)"
# mixed partial derivatives
f = Function("f")
assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \
r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y))
assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \
r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y))
# for negative nested Derivative
assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)'
assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \
r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)'
# use ordinary d when one of the variables has been integrated out
assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \
r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx"
# Derivative wrapped in power:
assert latex(diff(x, x, evaluate=False)**2) == \
r"\left(\frac{d}{d x} x\right)^{2}"
assert latex(diff(f(x), x)**2) == \
r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}"
assert latex(diff(f(x), (x, n))) == \
r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}"
x1 = Symbol('x1')
x2 = Symbol('x2')
assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}'
n1 = Symbol('n1')
assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}'
n2 = Symbol('n2')
assert latex(diff(f(x), (x, Max(n1, n2)))) == \
r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}'
# set diff operator
assert latex(diff(f(x), x), diff_operator="rd") == r'\frac{\mathrm{d}}{\mathrm{d} x} f{\left(x \right)}'
def test_latex_subs():
assert latex(Subs(x*y, (x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}'
def test_latex_integrals():
assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx"
assert latex(Integral(x**2, (x, 0, 1))) == \
r"\int\limits_{0}^{1} x^{2}\, dx"
assert latex(Integral(x**2, (x, 10, 20))) == \
r"\int\limits_{10}^{20} x^{2}\, dx"
assert latex(Integral(y*x**2, (x, 0, 1), y)) == \
r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy"
assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \
r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}"
assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \
== r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$"
assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx"
assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy"
assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz"
assert latex(Integral(x*y*z*t, x, y, z, t)) == \
r"\iiiint t x y z\, dx\, dy\, dz\, dt"
assert latex(Integral(x, x, x, x, x, x, x)) == \
r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx"
assert latex(Integral(x, x, y, (z, 0, 1))) == \
r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz"
# for negative nested Integral
assert latex(Integral(-Integral(y**2,x),x)) == \
r'\int \left(- \int y^{2}\, dx\right)\, dx'
assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \
r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx'
# fix issue #10806
assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}"
assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz"
assert latex(Integral(x+z/2, z)) == \
r"\int \left(x + \frac{z}{2}\right)\, dz"
assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz"
# set diff operator
assert latex(Integral(x, x), diff_operator="rd") == r'\int x\, \mathrm{d}x'
assert latex(Integral(x, (x, 0, 1)), diff_operator="rd") == r'\int\limits_{0}^{1} x\, \mathrm{d}x'
def test_latex_sets():
for s in (frozenset, set):
assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}"
assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}"
assert latex(s(range(1, 13))) == \
r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}"
s = FiniteSet
assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}"
assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}"
assert latex(s(*range(1, 13))) == \
r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}"
def test_latex_SetExpr():
iv = Interval(1, 3)
se = SetExpr(iv)
assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)"
def test_latex_Range():
assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}'
assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}'
assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}'
assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}'
assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}'
assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}'
assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}'
assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}'
assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}'
assert latex(Range(oo, -oo, -1)) == r'\left\{\ldots, 1, 0, -1, \ldots\right\}'
a, b, c = symbols('a:c')
assert latex(Range(a, b, c)) == r'\text{Range}\left(a, b, c\right)'
assert latex(Range(a, 10, 1)) == r'\text{Range}\left(a, 10\right)'
assert latex(Range(0, b, 1)) == r'\text{Range}\left(b\right)'
assert latex(Range(0, 10, c)) == r'\text{Range}\left(0, 10, c\right)'
i = Symbol('i', integer=True)
n = Symbol('n', negative=True, integer=True)
p = Symbol('p', positive=True, integer=True)
assert latex(Range(i, i + 3)) == r'\left\{i, i + 1, i + 2\right\}'
assert latex(Range(-oo, n, 2)) == r'\left\{\ldots, n - 4, n - 2\right\}'
assert latex(Range(p, oo)) == r'\left\{p, p + 1, \ldots\right\}'
# The following will work if __iter__ is improved
# assert latex(Range(-3, p + 7)) == r'\left\{-3, -2, \ldots, p + 6\right\}'
# Must have integer assumptions
assert latex(Range(a, a + 3)) == r'\text{Range}\left(a, a + 3\right)'
def test_latex_sequences():
s1 = SeqFormula(a**2, (0, oo))
s2 = SeqPer((1, 2))
latex_str = r'\left[0, 1, 4, 9, \ldots\right]'
assert latex(s1) == latex_str
latex_str = r'\left[1, 2, 1, 2, \ldots\right]'
assert latex(s2) == latex_str
s3 = SeqFormula(a**2, (0, 2))
s4 = SeqPer((1, 2), (0, 2))
latex_str = r'\left[0, 1, 4\right]'
assert latex(s3) == latex_str
latex_str = r'\left[1, 2, 1\right]'
assert latex(s4) == latex_str
s5 = SeqFormula(a**2, (-oo, 0))
s6 = SeqPer((1, 2), (-oo, 0))
latex_str = r'\left[\ldots, 9, 4, 1, 0\right]'
assert latex(s5) == latex_str
latex_str = r'\left[\ldots, 2, 1, 2, 1\right]'
assert latex(s6) == latex_str
latex_str = r'\left[1, 3, 5, 11, \ldots\right]'
assert latex(SeqAdd(s1, s2)) == latex_str
latex_str = r'\left[1, 3, 5\right]'
assert latex(SeqAdd(s3, s4)) == latex_str
latex_str = r'\left[\ldots, 11, 5, 3, 1\right]'
assert latex(SeqAdd(s5, s6)) == latex_str
latex_str = r'\left[0, 2, 4, 18, \ldots\right]'
assert latex(SeqMul(s1, s2)) == latex_str
latex_str = r'\left[0, 2, 4\right]'
assert latex(SeqMul(s3, s4)) == latex_str
latex_str = r'\left[\ldots, 18, 4, 2, 0\right]'
assert latex(SeqMul(s5, s6)) == latex_str
# Sequences with symbolic limits, issue 12629
s7 = SeqFormula(a**2, (a, 0, x))
latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}'
assert latex(s7) == latex_str
b = Symbol('b')
s8 = SeqFormula(b*a**2, (a, 0, 2))
latex_str = r'\left[0, b, 4 b\right]'
assert latex(s8) == latex_str
def test_latex_FourierSeries():
latex_str = \
r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots'
assert latex(fourier_series(x, (x, -pi, pi))) == latex_str
def test_latex_FormalPowerSeries():
latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}'
assert latex(fps(log(1 + x))) == latex_str
def test_latex_intervals():
a = Symbol('a', real=True)
assert latex(Interval(0, 0)) == r"\left\{0\right\}"
assert latex(Interval(0, a)) == r"\left[0, a\right]"
assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]"
assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]"
assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)"
assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)"
def test_latex_AccumuBounds():
a = Symbol('a', real=True)
assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle"
assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle"
assert latex(AccumBounds(a + 1, a + 2)) == \
r"\left\langle a + 1, a + 2\right\rangle"
def test_latex_emptyset():
assert latex(S.EmptySet) == r"\emptyset"
def test_latex_universalset():
assert latex(S.UniversalSet) == r"\mathbb{U}"
def test_latex_commutator():
A = Operator('A')
B = Operator('B')
comm = Commutator(B, A)
assert latex(comm.doit()) == r"- (A B - B A)"
def test_latex_union():
assert latex(Union(Interval(0, 1), Interval(2, 3))) == \
r"\left[0, 1\right] \cup \left[2, 3\right]"
assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \
r"\left\{1, 2\right\} \cup \left[3, 4\right]"
def test_latex_intersection():
assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \
r"\left[0, 1\right] \cap \left[x, y\right]"
def test_latex_symmetric_difference():
assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7),
evaluate=False)) == \
r'\left[2, 5\right] \triangle \left[4, 7\right]'
def test_latex_Complement():
assert latex(Complement(S.Reals, S.Naturals)) == \
r"\mathbb{R} \setminus \mathbb{N}"
def test_latex_productset():
line = Interval(0, 1)
bigline = Interval(0, 10)
fset = FiniteSet(1, 2, 3)
assert latex(line**2) == r"%s^{2}" % latex(line)
assert latex(line**10) == r"%s^{10}" % latex(line)
assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % (
latex(line), latex(bigline), latex(fset))
def test_latex_powerset():
fset = FiniteSet(1, 2, 3)
assert latex(PowerSet(fset)) == r'\mathcal{P}\left(\left\{1, 2, 3\right\}\right)'
def test_latex_ordinals():
w = OrdinalOmega()
assert latex(w) == r"\omega"
wp = OmegaPower(2, 3)
assert latex(wp) == r'3 \omega^{2}'
assert latex(Ordinal(wp, OmegaPower(1, 1))) == r'3 \omega^{2} + \omega'
assert latex(Ordinal(OmegaPower(2, 1), OmegaPower(1, 2))) == r'\omega^{2} + 2 \omega'
def test_set_operators_parenthesis():
a, b, c, d = symbols('a:d')
A = FiniteSet(a)
B = FiniteSet(b)
C = FiniteSet(c)
D = FiniteSet(d)
U1 = Union(A, B, evaluate=False)
U2 = Union(C, D, evaluate=False)
I1 = Intersection(A, B, evaluate=False)
I2 = Intersection(C, D, evaluate=False)
C1 = Complement(A, B, evaluate=False)
C2 = Complement(C, D, evaluate=False)
D1 = SymmetricDifference(A, B, evaluate=False)
D2 = SymmetricDifference(C, D, evaluate=False)
# XXX ProductSet does not support evaluate keyword
P1 = ProductSet(A, B)
P2 = ProductSet(C, D)
assert latex(Intersection(A, U2, evaluate=False)) == \
r'\left\{a\right\} \cap ' \
r'\left(\left\{c\right\} \cup \left\{d\right\}\right)'
assert latex(Intersection(U1, U2, evaluate=False)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\cap \left(\left\{c\right\} \cup \left\{d\right\}\right)'
assert latex(Intersection(C1, C2, evaluate=False)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(Intersection(D1, D2, evaluate=False)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \
r'\triangle \left\{d\right\}\right)'
assert latex(Intersection(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
r'\cap \left(\left\{c\right\} \times ' \
r'\left\{d\right\}\right)'
assert latex(Union(A, I2, evaluate=False)) == \
r'\left\{a\right\} \cup ' \
r'\left(\left\{c\right\} \cap \left\{d\right\}\right)'
assert latex(Union(I1, I2, evaluate=False)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\cup \left(\left\{c\right\} \cap \left\{d\right\}\right)'
assert latex(Union(C1, C2, evaluate=False)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(Union(D1, D2, evaluate=False)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \
r'\triangle \left\{d\right\}\right)'
assert latex(Union(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
r'\cup \left(\left\{c\right\} \times ' \
r'\left\{d\right\}\right)'
assert latex(Complement(A, C2, evaluate=False)) == \
r'\left\{a\right\} \setminus \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(Complement(U1, U2, evaluate=False)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\setminus \left(\left\{c\right\} \cup ' \
r'\left\{d\right\}\right)'
assert latex(Complement(I1, I2, evaluate=False)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\setminus \left(\left\{c\right\} \cap ' \
r'\left\{d\right\}\right)'
assert latex(Complement(D1, D2, evaluate=False)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \setminus ' \
r'\left(\left\{c\right\} \triangle \left\{d\right\}\right)'
assert latex(Complement(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) '\
r'\setminus \left(\left\{c\right\} \times '\
r'\left\{d\right\}\right)'
assert latex(SymmetricDifference(A, D2, evaluate=False)) == \
r'\left\{a\right\} \triangle \left(\left\{c\right\} ' \
r'\triangle \left\{d\right\}\right)'
assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\triangle \left(\left\{c\right\} \cup ' \
r'\left\{d\right\}\right)'
assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\triangle \left(\left\{c\right\} \cap ' \
r'\left\{d\right\}\right)'
assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \triangle ' \
r'\left(\left\{c\right\} \setminus \left\{d\right\}\right)'
assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
r'\triangle \left(\left\{c\right\} \times ' \
r'\left\{d\right\}\right)'
# XXX This can be incorrect since cartesian product is not associative
assert latex(ProductSet(A, P2).flatten()) == \
r'\left\{a\right\} \times \left\{c\right\} \times ' \
r'\left\{d\right\}'
assert latex(ProductSet(U1, U2)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\times \left(\left\{c\right\} \cup ' \
r'\left\{d\right\}\right)'
assert latex(ProductSet(I1, I2)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\times \left(\left\{c\right\} \cap ' \
r'\left\{d\right\}\right)'
assert latex(ProductSet(C1, C2)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(ProductSet(D1, D2)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \
r'\triangle \left\{d\right\}\right)'
def test_latex_Complexes():
assert latex(S.Complexes) == r"\mathbb{C}"
def test_latex_Naturals():
assert latex(S.Naturals) == r"\mathbb{N}"
def test_latex_Naturals0():
assert latex(S.Naturals0) == r"\mathbb{N}_0"
def test_latex_Integers():
assert latex(S.Integers) == r"\mathbb{Z}"
def test_latex_ImageSet():
x = Symbol('x')
assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \
r"\left\{x^{2}\; \middle|\; x \in \mathbb{N}\right\}"
y = Symbol('y')
imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4})
assert latex(imgset) == \
r"\left\{x + y\; \middle|\; x \in \left\{1, 2, 3\right\}, y \in \left\{3, 4\right\}\right\}"
imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4}))
assert latex(imgset) == \
r"\left\{x + y\; \middle|\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}"
def test_latex_ConditionSet():
x = Symbol('x')
assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \
r"\left\{x\; \middle|\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \
r"\left\{x\; \middle|\; x^{2} = 1 \right\}"
def test_latex_ComplexRegion():
assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \
r"\left\{x + y i\; \middle|\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\
r"\right)}\right)\; \middle|\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
def test_latex_Contains():
x = Symbol('x')
assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}"
def test_latex_sum():
assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \
r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
assert latex(Sum(x**2, (x, -2, 2))) == \
r"\sum_{x=-2}^{2} x^{2}"
assert latex(Sum(x**2 + y, (x, -2, 2))) == \
r"\sum_{x=-2}^{2} \left(x^{2} + y\right)"
assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \
r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}"
def test_latex_product():
assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \
r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
assert latex(Product(x**2, (x, -2, 2))) == \
r"\prod_{x=-2}^{2} x^{2}"
assert latex(Product(x**2 + y, (x, -2, 2))) == \
r"\prod_{x=-2}^{2} \left(x^{2} + y\right)"
assert latex(Product(x, (x, -2, 2))**2) == \
r"\left(\prod_{x=-2}^{2} x\right)^{2}"
def test_latex_limits():
assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x"
# issue 8175
f = Function('f')
assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}"
assert latex(Limit(f(x), x, 0, "-")) == \
r"\lim_{x \to 0^-} f{\left(x \right)}"
# issue #10806
assert latex(Limit(f(x), x, 0)**2) == \
r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}"
# bi-directional limit
assert latex(Limit(f(x), x, 0, dir='+-')) == \
r"\lim_{x \to 0} f{\left(x \right)}"
def test_latex_log():
assert latex(log(x)) == r"\log{\left(x \right)}"
assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}"
assert latex(log(x) + log(y)) == \
r"\log{\left(x \right)} + \log{\left(y \right)}"
assert latex(log(x) + log(y), ln_notation=True) == \
r"\ln{\left(x \right)} + \ln{\left(y \right)}"
assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}"
assert latex(pow(log(x), x), ln_notation=True) == \
r"\ln{\left(x \right)}^{x}"
def test_issue_3568():
beta = Symbol(r'\beta')
y = beta + x
assert latex(y) in [r'\beta + x', r'x + \beta']
beta = Symbol(r'beta')
y = beta + x
assert latex(y) in [r'\beta + x', r'x + \beta']
def test_latex():
assert latex((2*tau)**Rational(7, 2)) == r"8 \sqrt{2} \tau^{\frac{7}{2}}"
assert latex((2*mu)**Rational(7, 2), mode='equation*') == \
r"\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}"
assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \
r"$$8 \sqrt{2} \mu^{\frac{7}{2}}$$"
assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \ y\right]"
def test_latex_dict():
d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4}
assert latex(d) == \
r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}'
D = Dict(d)
assert latex(D) == \
r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}'
def test_latex_list():
ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')]
assert latex(ll) == r'\left[ \omega_{1}, \ a, \ \alpha\right]'
def test_latex_NumberSymbols():
assert latex(S.Catalan) == "G"
assert latex(S.EulerGamma) == r"\gamma"
assert latex(S.Exp1) == "e"
assert latex(S.GoldenRatio) == r"\phi"
assert latex(S.Pi) == r"\pi"
assert latex(S.TribonacciConstant) == r"\text{TribonacciConstant}"
def test_latex_rational():
# tests issue 3973
assert latex(-Rational(1, 2)) == r"- \frac{1}{2}"
assert latex(Rational(-1, 2)) == r"- \frac{1}{2}"
assert latex(Rational(1, -2)) == r"- \frac{1}{2}"
assert latex(-Rational(-1, 2)) == r"\frac{1}{2}"
assert latex(-Rational(1, 2)*x) == r"- \frac{x}{2}"
assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \
r"- \frac{x}{2} - \frac{2 y}{3}"
def test_latex_inverse():
# tests issue 4129
assert latex(1/x) == r"\frac{1}{x}"
assert latex(1/(x + y)) == r"\frac{1}{x + y}"
def test_latex_DiracDelta():
assert latex(DiracDelta(x)) == r"\delta\left(x\right)"
assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}"
assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)"
assert latex(DiracDelta(x, 5)) == \
r"\delta^{\left( 5 \right)}\left( x \right)"
assert latex(DiracDelta(x, 5)**2) == \
r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}"
def test_latex_Heaviside():
assert latex(Heaviside(x)) == r"\theta\left(x\right)"
assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}"
def test_latex_KroneckerDelta():
assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}"
assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}"
# issue 6578
assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}"
assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \
r"\left(\delta_{x y}\right)^{2}"
def test_latex_LeviCivita():
assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}"
assert latex(LeviCivita(x, y, z)**2) == \
r"\left(\varepsilon_{x y z}\right)^{2}"
assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}"
assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}"
assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}"
def test_mode():
expr = x + y
assert latex(expr) == r'x + y'
assert latex(expr, mode='plain') == r'x + y'
assert latex(expr, mode='inline') == r'$x + y$'
assert latex(
expr, mode='equation*') == r'\begin{equation*}x + y\end{equation*}'
assert latex(
expr, mode='equation') == r'\begin{equation}x + y\end{equation}'
raises(ValueError, lambda: latex(expr, mode='foo'))
def test_latex_mathieu():
assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)"
assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)"
assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}"
assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}"
assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)"
assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)"
assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}"
assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}"
def test_latex_Piecewise():
p = Piecewise((x, x < 1), (x**2, True))
assert latex(p) == r"\begin{cases} x & \text{for}\: x < 1 \\x^{2} &" \
r" \text{otherwise} \end{cases}"
assert latex(p, itex=True) == \
r"\begin{cases} x & \text{for}\: x \lt 1 \\x^{2} &" \
r" \text{otherwise} \end{cases}"
p = Piecewise((x, x < 0), (0, x >= 0))
assert latex(p) == r'\begin{cases} x & \text{for}\: x < 0 \\0 &' \
r' \text{otherwise} \end{cases}'
A, B = symbols("A B", commutative=False)
p = Piecewise((A**2, Eq(A, B)), (A*B, True))
s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}"
assert latex(p) == s
assert latex(A*p) == r"A \left(%s\right)" % s
assert latex(p*A) == r"\left(%s\right) A" % s
assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \
r'\begin{cases} x & ' \
r'\text{for}\: x < 1 \\x^{2} & \text{for}\: x < 2 \end{cases}'
def test_latex_Matrix():
M = Matrix([[1 + x, y], [y, x - 1]])
assert latex(M) == \
r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]'
assert latex(M, mode='inline') == \
r'$\left[\begin{smallmatrix}x + 1 & y\\' \
r'y & x - 1\end{smallmatrix}\right]$'
assert latex(M, mat_str='array') == \
r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]'
assert latex(M, mat_str='bmatrix') == \
r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]'
assert latex(M, mat_delim=None, mat_str='bmatrix') == \
r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}'
M2 = Matrix(1, 11, range(11))
assert latex(M2) == \
r'\left[\begin{array}{ccccccccccc}' \
r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]'
def test_latex_matrix_with_functions():
t = symbols('t')
theta1 = symbols('theta1', cls=Function)
M = Matrix([[sin(theta1(t)), cos(theta1(t))],
[cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]])
expected = (r'\left[\begin{matrix}\sin{\left('
r'\theta_{1}{\left(t \right)} \right)} & '
r'\cos{\left(\theta_{1}{\left(t \right)} \right)'
r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t '
r'\right)} \right)} & \sin{\left(\frac{d}{d t} '
r'\theta_{1}{\left(t \right)} \right'
r')}\end{matrix}\right]')
assert latex(M) == expected
def test_latex_NDimArray():
x, y, z, w = symbols("x y z w")
for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray,
MutableDenseNDimArray, MutableSparseNDimArray):
# Basic: scalar array
M = ArrayType(x)
assert latex(M) == r"x"
M = ArrayType([[1 / x, y], [z, w]])
M1 = ArrayType([1 / x, y, z])
M2 = tensorproduct(M1, M)
M3 = tensorproduct(M, M)
assert latex(M) == \
r'\left[\begin{matrix}\frac{1}{x} & y\\z & w\end{matrix}\right]'
assert latex(M1) == \
r"\left[\begin{matrix}\frac{1}{x} & y & z\end{matrix}\right]"
assert latex(M2) == \
r"\left[\begin{matrix}" \
r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \
r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \
r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \
r"\end{matrix}\right]"
assert latex(M3) == \
r"""\left[\begin{matrix}"""\
r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\
r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\
r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\
r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\
r"""\end{matrix}\right]"""
Mrow = ArrayType([[x, y, 1/z]])
Mcolumn = ArrayType([[x], [y], [1/z]])
Mcol2 = ArrayType([Mcolumn.tolist()])
assert latex(Mrow) == \
r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]"
assert latex(Mcolumn) == \
r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]"
assert latex(Mcol2) == \
r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]'
def test_latex_mul_symbol():
assert latex(4*4**x, mul_symbol='times') == r"4 \times 4^{x}"
assert latex(4*4**x, mul_symbol='dot') == r"4 \cdot 4^{x}"
assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}"
assert latex(4*x, mul_symbol='times') == r"4 \times x"
assert latex(4*x, mul_symbol='dot') == r"4 \cdot x"
assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x"
def test_latex_issue_4381():
y = 4*4**log(2)
assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}'
assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}'
def test_latex_issue_4576():
assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}"
assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}"
assert latex(Symbol("beta_13")) == r"\beta_{13}"
assert latex(Symbol("x_a_b")) == r"x_{a b}"
assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}"
assert latex(Symbol("x_a_b1")) == r"x_{a b1}"
assert latex(Symbol("x_a_1")) == r"x_{a 1}"
assert latex(Symbol("x_1_a")) == r"x_{1 a}"
assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}"
assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}"
assert latex(Symbol("x_11^a")) == r"x^{a}_{11}"
assert latex(Symbol("x_11__a")) == r"x^{a}_{11}"
assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}"
assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}"
assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}"
assert latex(Symbol("alpha_11")) == r"\alpha_{11}"
assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}"
assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}"
assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}"
assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}"
def test_latex_pow_fraction():
x = Symbol('x')
# Testing exp
assert r'e^{-x}' in latex(exp(-x)/2).replace(' ', '') # Remove Whitespace
# Testing e^{-x} in case future changes alter behavior of muls or fracs
# In particular current output is \frac{1}{2}e^{- x} but perhaps this will
# change to \frac{e^{-x}}{2}
# Testing general, non-exp, power
assert r'3^{-x}' in latex(3**-x/2).replace(' ', '')
def test_noncommutative():
A, B, C = symbols('A,B,C', commutative=False)
assert latex(A*B*C**-1) == r"A B C^{-1}"
assert latex(C**-1*A*B) == r"C^{-1} A B"
assert latex(A*C**-1*B) == r"A C^{-1} B"
def test_latex_order():
expr = x**3 + x**2*y + y**4 + 3*x*y**3
assert latex(expr, order='lex') == r"x^{3} + x^{2} y + 3 x y^{3} + y^{4}"
assert latex(
expr, order='rev-lex') == r"y^{4} + 3 x y^{3} + x^{2} y + x^{3}"
assert latex(expr, order='none') == r"x^{3} + y^{4} + y x^{2} + 3 x y^{3}"
def test_latex_Lambda():
assert latex(Lambda(x, x + 1)) == r"\left( x \mapsto x + 1 \right)"
assert latex(Lambda((x, y), x + 1)) == r"\left( \left( x, \ y\right) \mapsto x + 1 \right)"
assert latex(Lambda(x, x)) == r"\left( x \mapsto x \right)"
def test_latex_PolyElement():
Ruv, u, v = ring("u,v", ZZ)
Rxyz, x, y, z = ring("x,y,z", Ruv)
assert latex(x - x) == r"0"
assert latex(x - 1) == r"x - 1"
assert latex(x + 1) == r"x + 1"
assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \
r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1"
assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \
r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x"
assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \
r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1"
assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \
r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1"
assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \
r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1"
assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \
r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1"
def test_latex_FracElement():
Fuv, u, v = field("u,v", ZZ)
Fxyzt, x, y, z, t = field("x,y,z,t", Fuv)
assert latex(x - x) == r"0"
assert latex(x - 1) == r"x - 1"
assert latex(x + 1) == r"x + 1"
assert latex(x/3) == r"\frac{x}{3}"
assert latex(x/z) == r"\frac{x}{z}"
assert latex(x*y/z) == r"\frac{x y}{z}"
assert latex(x/(z*t)) == r"\frac{x}{z t}"
assert latex(x*y/(z*t)) == r"\frac{x y}{z t}"
assert latex((x - 1)/y) == r"\frac{x - 1}{y}"
assert latex((x + 1)/y) == r"\frac{x + 1}{y}"
assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}"
assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}"
assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}"
assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}"
assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \
r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}"
assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \
r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}"
def test_latex_Poly():
assert latex(Poly(x**2 + 2 * x, x)) == \
r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}"
assert latex(Poly(x/y, x)) == \
r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}"
assert latex(Poly(2.0*x + y)) == \
r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}"
def test_latex_Poly_order():
assert latex(Poly([a, 1, b, 2, c, 3], x)) == \
r'\operatorname{Poly}{\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\
r' x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}'
assert latex(Poly([a, 1, b+c, 2, 3], x)) == \
r'\operatorname{Poly}{\left( a x^{4} + x^{3} + \left(b + c\right) '\
r'x^{2} + 2 x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}'
assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b,
(x, y))) == \
r'\operatorname{Poly}{\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\
r'a x - c y^{3} + y + b, x, y, domain=\mathbb{Z}\left[a, b, c\right] \right)}'
def test_latex_ComplexRootOf():
assert latex(rootof(x**5 + x + 3, 0)) == \
r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}"
def test_latex_RootSum():
assert latex(RootSum(x**5 + x + 3, sin)) == \
r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}"
def test_settings():
raises(TypeError, lambda: latex(x*y, method="garbage"))
def test_latex_numbers():
assert latex(catalan(n)) == r"C_{n}"
assert latex(catalan(n)**2) == r"C_{n}^{2}"
assert latex(bernoulli(n)) == r"B_{n}"
assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)"
assert latex(bernoulli(n)**2) == r"B_{n}^{2}"
assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)"
assert latex(genocchi(n)) == r"G_{n}"
assert latex(genocchi(n, x)) == r"G_{n}\left(x\right)"
assert latex(genocchi(n)**2) == r"G_{n}^{2}"
assert latex(genocchi(n, x)**2) == r"G_{n}^{2}\left(x\right)"
assert latex(bell(n)) == r"B_{n}"
assert latex(bell(n, x)) == r"B_{n}\left(x\right)"
assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)"
assert latex(bell(n)**2) == r"B_{n}^{2}"
assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)"
assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)"
assert latex(fibonacci(n)) == r"F_{n}"
assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)"
assert latex(fibonacci(n)**2) == r"F_{n}^{2}"
assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)"
assert latex(lucas(n)) == r"L_{n}"
assert latex(lucas(n)**2) == r"L_{n}^{2}"
assert latex(tribonacci(n)) == r"T_{n}"
assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)"
assert latex(tribonacci(n)**2) == r"T_{n}^{2}"
assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)"
def test_latex_euler():
assert latex(euler(n)) == r"E_{n}"
assert latex(euler(n, x)) == r"E_{n}\left(x\right)"
assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)"
def test_lamda():
assert latex(Symbol('lamda')) == r"\lambda"
assert latex(Symbol('Lamda')) == r"\Lambda"
def test_custom_symbol_names():
x = Symbol('x')
y = Symbol('y')
assert latex(x) == r"x"
assert latex(x, symbol_names={x: "x_i"}) == r"x_i"
assert latex(x + y, symbol_names={x: "x_i"}) == r"x_i + y"
assert latex(x**2, symbol_names={x: "x_i"}) == r"x_i^{2}"
assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == r"x_i + y_j"
def test_matAdd():
C = MatrixSymbol('C', 5, 5)
B = MatrixSymbol('B', 5, 5)
n = symbols("n")
h = MatrixSymbol("h", 1, 1)
assert latex(C - 2*B) in [r'- 2 B + C', r'C -2 B']
assert latex(C + 2*B) in [r'2 B + C', r'C + 2 B']
assert latex(B - 2*C) in [r'B - 2 C', r'- 2 C + B']
assert latex(B + 2*C) in [r'B + 2 C', r'2 C + B']
assert latex(n * h - (-h + h.T) * (h + h.T)) == 'n h - \\left(- h + h^{T}\\right) \\left(h + h^{T}\\right)'
assert latex(MatAdd(MatAdd(h, h), MatAdd(h, h))) == '\\left(h + h\\right) + \\left(h + h\\right)'
assert latex(MatMul(MatMul(h, h), MatMul(h, h))) == '\\left(h h\\right) \\left(h h\\right)'
def test_matMul():
A = MatrixSymbol('A', 5, 5)
B = MatrixSymbol('B', 5, 5)
x = Symbol('x')
assert latex(2*A) == r'2 A'
assert latex(2*x*A) == r'2 x A'
assert latex(-2*A) == r'- 2 A'
assert latex(1.5*A) == r'1.5 A'
assert latex(sqrt(2)*A) == r'\sqrt{2} A'
assert latex(-sqrt(2)*A) == r'- \sqrt{2} A'
assert latex(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A'
assert latex(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)',
r'- 2 A \left(2 B + A\right)']
def test_latex_MatrixSlice():
n = Symbol('n', integer=True)
x, y, z, w, t, = symbols('x y z w t')
X = MatrixSymbol('X', n, n)
Y = MatrixSymbol('Y', 10, 10)
Z = MatrixSymbol('Z', 10, 10)
assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]'
assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]'
assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]'
assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
assert latex(X[x:, :y]) == r'X\left[x:, :y\right]'
assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]'
assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]'
assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]'
assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]'
assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]'
assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]'
assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]'
assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]'
assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]'
assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]'
assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]'
assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]'
assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]'
assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]'
assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 2:\right]'
def test_latex_RandomDomain():
from sympy.stats import Normal, Die, Exponential, pspace, where
from sympy.stats.rv import RandomDomain
X = Normal('x1', 0, 1)
assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty"
D = Die('d1', 6)
assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6"
A = Exponential('a', 1)
B = Exponential('b', 1)
assert latex(
pspace(Tuple(A, B)).domain) == \
r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty"
assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \
r'\text{Domain: }\left\{x\right\} \in \left\{1, 2\right\}'
def test_PrettyPoly():
from sympy.polys.domains import QQ
F = QQ.frac_field(x, y)
R = QQ[x, y]
assert latex(F.convert(x/(x + y))) == latex(x/(x + y))
assert latex(R.convert(x + y)) == latex(x + y)
def test_integral_transforms():
x = Symbol("x")
k = Symbol("k")
f = Function("f")
a = Symbol("a")
b = Symbol("b")
assert latex(MellinTransform(f(x), x, k)) == \
r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \
r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(LaplaceTransform(f(x), x, k)) == \
r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \
r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(FourierTransform(f(x), x, k)) == \
r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseFourierTransform(f(k), k, x)) == \
r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(CosineTransform(f(x), x, k)) == \
r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseCosineTransform(f(k), k, x)) == \
r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
assert latex(SineTransform(f(x), x, k)) == \
r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
assert latex(InverseSineTransform(f(k), k, x)) == \
r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
def test_PolynomialRingBase():
from sympy.polys.domains import QQ
assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]"
assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \
r"S_<^{-1}\mathbb{Q}\left[x, y\right]"
def test_categories():
from sympy.categories import (Object, IdentityMorphism,
NamedMorphism, Category, Diagram,
DiagramGrid)
A1 = Object("A1")
A2 = Object("A2")
A3 = Object("A3")
f1 = NamedMorphism(A1, A2, "f1")
f2 = NamedMorphism(A2, A3, "f2")
id_A1 = IdentityMorphism(A1)
K1 = Category("K1")
assert latex(A1) == r"A_{1}"
assert latex(f1) == r"f_{1}:A_{1}\rightarrow A_{2}"
assert latex(id_A1) == r"id:A_{1}\rightarrow A_{1}"
assert latex(f2*f1) == r"f_{2}\circ f_{1}:A_{1}\rightarrow A_{3}"
assert latex(K1) == r"\mathbf{K_{1}}"
d = Diagram()
assert latex(d) == r"\emptyset"
d = Diagram({f1: "unique", f2: S.EmptySet})
assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \
r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \
r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \
r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \
r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \
r"\ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}"
d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"})
assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \
r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \
r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \
r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \
r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \
r" \ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \
r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \
r"\rightarrow A_{3} : \left\{unique\right\}\right\}"
# A linear diagram.
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
d = Diagram([f, g])
grid = DiagramGrid(d)
assert latex(grid) == r"\begin{array}{cc}" + "\n" \
r"A & B \\" + "\n" \
r" & C " + "\n" \
r"\end{array}" + "\n"
def test_Modules():
from sympy.polys.domains import QQ
from sympy.polys.agca import homomorphism
R = QQ.old_poly_ring(x, y)
F = R.free_module(2)
M = F.submodule([x, y], [1, x**2])
assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}"
assert latex(M) == \
r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle"
I = R.ideal(x**2, y)
assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle"
Q = F / M
assert latex(Q) == \
r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\
r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}"
assert latex(Q.submodule([1, x**3/2], [2, y])) == \
r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\
r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\
r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\
r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle"
h = homomorphism(QQ.old_poly_ring(x).free_module(2),
QQ.old_poly_ring(x).free_module(2), [0, 0])
assert latex(h) == \
r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\
r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}"
def test_QuotientRing():
from sympy.polys.domains import QQ
R = QQ.old_poly_ring(x)/[x**2 + 1]
assert latex(R) == \
r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}"
assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}"
def test_Tr():
#TODO: Handle indices
A, B = symbols('A B', commutative=False)
t = Tr(A*B)
assert latex(t) == r'\operatorname{tr}\left(A B\right)'
def test_Determinant():
from sympy.matrices import Determinant, Inverse, BlockMatrix, OneMatrix, ZeroMatrix
m = Matrix(((1, 2), (3, 4)))
assert latex(Determinant(m)) == '\\left|{\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}}\\right|'
assert latex(Determinant(Inverse(m))) == \
'\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{-1}}\\right|'
X = MatrixSymbol('X', 2, 2)
assert latex(Determinant(X)) == '\\left|{X}\\right|'
assert latex(Determinant(X + m)) == \
'\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X}\\right|'
assert latex(Determinant(BlockMatrix(((OneMatrix(2, 2), X),
(m, ZeroMatrix(2, 2)))))) == \
'\\left|{\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}}\\right|'
def test_Adjoint():
from sympy.matrices import Adjoint, Inverse, Transpose
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(Adjoint(X)) == r'X^{\dagger}'
assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}'
assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}'
assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}'
assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}'
assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}'
assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}'
assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}'
assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}'
assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}'
assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}'
assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}'
m = Matrix(((1, 2), (3, 4)))
assert latex(Adjoint(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{\\dagger}'
assert latex(Adjoint(m+X)) == \
'\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{\\dagger}'
from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix
assert latex(Adjoint(BlockMatrix(((OneMatrix(2, 2), X),
(m, ZeroMatrix(2, 2)))))) == \
'\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{\\dagger}'
# Issue 20959
Mx = MatrixSymbol('M^x', 2, 2)
assert latex(Adjoint(Mx)) == r'\left(M^{x}\right)^{\dagger}'
def test_Transpose():
from sympy.matrices import Transpose, MatPow, HadamardPower
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(Transpose(X)) == r'X^{T}'
assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}'
assert latex(Transpose(HadamardPower(X, 2))) == r'\left(X^{\circ {2}}\right)^{T}'
assert latex(HadamardPower(Transpose(X), 2)) == r'\left(X^{T}\right)^{\circ {2}}'
assert latex(Transpose(MatPow(X, 2))) == r'\left(X^{2}\right)^{T}'
assert latex(MatPow(Transpose(X), 2)) == r'\left(X^{T}\right)^{2}'
m = Matrix(((1, 2), (3, 4)))
assert latex(Transpose(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{T}'
assert latex(Transpose(m+X)) == \
'\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{T}'
from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix
assert latex(Transpose(BlockMatrix(((OneMatrix(2, 2), X),
(m, ZeroMatrix(2, 2)))))) == \
'\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{T}'
# Issue 20959
Mx = MatrixSymbol('M^x', 2, 2)
assert latex(Transpose(Mx)) == r'\left(M^{x}\right)^{T}'
def test_Hadamard():
from sympy.matrices import HadamardProduct, HadamardPower
from sympy.matrices.expressions import MatAdd, MatMul, MatPow
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}'
assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y'
assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}'
assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}'
assert latex(HadamardPower(MatAdd(X, Y), 2)) == \
r'\left(X + Y\right)^{\circ {2}}'
assert latex(HadamardPower(MatMul(X, Y), 2)) == \
r'\left(X Y\right)^{\circ {2}}'
assert latex(HadamardPower(MatPow(X, -1), -1)) == \
r'\left(X^{-1}\right)^{\circ \left({-1}\right)}'
assert latex(MatPow(HadamardPower(X, -1), -1)) == \
r'\left(X^{\circ \left({-1}\right)}\right)^{-1}'
assert latex(HadamardPower(X, n+1)) == \
r'X^{\circ \left({n + 1}\right)}'
def test_MatPow():
from sympy.matrices.expressions import MatPow
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(MatPow(X, 2)) == 'X^{2}'
assert latex(MatPow(X*X, 2)) == '\\left(X^{2}\\right)^{2}'
assert latex(MatPow(X*Y, 2)) == '\\left(X Y\\right)^{2}'
assert latex(MatPow(X + Y, 2)) == '\\left(X + Y\\right)^{2}'
assert latex(MatPow(X + X, 2)) == '\\left(2 X\\right)^{2}'
# Issue 20959
Mx = MatrixSymbol('M^x', 2, 2)
assert latex(MatPow(Mx, 2)) == r'\left(M^{x}\right)^{2}'
def test_ElementwiseApplyFunction():
X = MatrixSymbol('X', 2, 2)
expr = (X.T*X).applyfunc(sin)
assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)"
expr = X.applyfunc(Lambda(x, 1/x))
assert latex(expr) == r'{\left( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)'
def test_ZeroMatrix():
from sympy.matrices.expressions.special import ZeroMatrix
assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"0"
assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}"
def test_OneMatrix():
from sympy.matrices.expressions.special import OneMatrix
assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"1"
assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}"
def test_Identity():
from sympy.matrices.expressions.special import Identity
assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}"
assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}"
def test_latex_DFT_IDFT():
from sympy.matrices.expressions.fourier import DFT, IDFT
assert latex(DFT(13)) == r"\text{DFT}_{13}"
assert latex(IDFT(x)) == r"\text{IDFT}_{x}"
def test_boolean_args_order():
syms = symbols('a:f')
expr = And(*syms)
assert latex(expr) == r'a \wedge b \wedge c \wedge d \wedge e \wedge f'
expr = Or(*syms)
assert latex(expr) == r'a \vee b \vee c \vee d \vee e \vee f'
expr = Equivalent(*syms)
assert latex(expr) == \
r'a \Leftrightarrow b \Leftrightarrow c \Leftrightarrow d \Leftrightarrow e \Leftrightarrow f'
expr = Xor(*syms)
assert latex(expr) == \
r'a \veebar b \veebar c \veebar d \veebar e \veebar f'
def test_imaginary():
i = sqrt(-1)
assert latex(i) == r'i'
def test_builtins_without_args():
assert latex(sin) == r'\sin'
assert latex(cos) == r'\cos'
assert latex(tan) == r'\tan'
assert latex(log) == r'\log'
assert latex(Ei) == r'\operatorname{Ei}'
assert latex(zeta) == r'\zeta'
def test_latex_greek_functions():
# bug because capital greeks that have roman equivalents should not use
# \Alpha, \Beta, \Eta, etc.
s = Function('Alpha')
assert latex(s) == r'\mathrm{A}'
assert latex(s(x)) == r'\mathrm{A}{\left(x \right)}'
s = Function('Beta')
assert latex(s) == r'\mathrm{B}'
s = Function('Eta')
assert latex(s) == r'\mathrm{H}'
assert latex(s(x)) == r'\mathrm{H}{\left(x \right)}'
# bug because sympy.core.numbers.Pi is special
p = Function('Pi')
# assert latex(p(x)) == r'\Pi{\left(x \right)}'
assert latex(p) == r'\Pi'
# bug because not all greeks are included
c = Function('chi')
assert latex(c(x)) == r'\chi{\left(x \right)}'
assert latex(c) == r'\chi'
def test_translate():
s = 'Alpha'
assert translate(s) == r'\mathrm{A}'
s = 'Beta'
assert translate(s) == r'\mathrm{B}'
s = 'Eta'
assert translate(s) == r'\mathrm{H}'
s = 'omicron'
assert translate(s) == r'o'
s = 'Pi'
assert translate(s) == r'\Pi'
s = 'pi'
assert translate(s) == r'\pi'
s = 'LamdaHatDOT'
assert translate(s) == r'\dot{\hat{\Lambda}}'
def test_other_symbols():
from sympy.printing.latex import other_symbols
for s in other_symbols:
assert latex(symbols(s)) == r"" "\\" + s
def test_modifiers():
# Test each modifier individually in the simplest case
# (with funny capitalizations)
assert latex(symbols("xMathring")) == r"\mathring{x}"
assert latex(symbols("xCheck")) == r"\check{x}"
assert latex(symbols("xBreve")) == r"\breve{x}"
assert latex(symbols("xAcute")) == r"\acute{x}"
assert latex(symbols("xGrave")) == r"\grave{x}"
assert latex(symbols("xTilde")) == r"\tilde{x}"
assert latex(symbols("xPrime")) == r"{x}'"
assert latex(symbols("xddDDot")) == r"\ddddot{x}"
assert latex(symbols("xDdDot")) == r"\dddot{x}"
assert latex(symbols("xDDot")) == r"\ddot{x}"
assert latex(symbols("xBold")) == r"\boldsymbol{x}"
assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|"
assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle"
assert latex(symbols("xHat")) == r"\hat{x}"
assert latex(symbols("xDot")) == r"\dot{x}"
assert latex(symbols("xBar")) == r"\bar{x}"
assert latex(symbols("xVec")) == r"\vec{x}"
assert latex(symbols("xAbs")) == r"\left|{x}\right|"
assert latex(symbols("xMag")) == r"\left|{x}\right|"
assert latex(symbols("xPrM")) == r"{x}'"
assert latex(symbols("xBM")) == r"\boldsymbol{x}"
# Test strings that are *only* the names of modifiers
assert latex(symbols("Mathring")) == r"Mathring"
assert latex(symbols("Check")) == r"Check"
assert latex(symbols("Breve")) == r"Breve"
assert latex(symbols("Acute")) == r"Acute"
assert latex(symbols("Grave")) == r"Grave"
assert latex(symbols("Tilde")) == r"Tilde"
assert latex(symbols("Prime")) == r"Prime"
assert latex(symbols("DDot")) == r"\dot{D}"
assert latex(symbols("Bold")) == r"Bold"
assert latex(symbols("NORm")) == r"NORm"
assert latex(symbols("AVG")) == r"AVG"
assert latex(symbols("Hat")) == r"Hat"
assert latex(symbols("Dot")) == r"Dot"
assert latex(symbols("Bar")) == r"Bar"
assert latex(symbols("Vec")) == r"Vec"
assert latex(symbols("Abs")) == r"Abs"
assert latex(symbols("Mag")) == r"Mag"
assert latex(symbols("PrM")) == r"PrM"
assert latex(symbols("BM")) == r"BM"
assert latex(symbols("hbar")) == r"\hbar"
# Check a few combinations
assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}"
assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}"
assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|"
# Check a couple big, ugly combinations
assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \
r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}"
assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \
r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}"
def test_greek_symbols():
assert latex(Symbol('alpha')) == r'\alpha'
assert latex(Symbol('beta')) == r'\beta'
assert latex(Symbol('gamma')) == r'\gamma'
assert latex(Symbol('delta')) == r'\delta'
assert latex(Symbol('epsilon')) == r'\epsilon'
assert latex(Symbol('zeta')) == r'\zeta'
assert latex(Symbol('eta')) == r'\eta'
assert latex(Symbol('theta')) == r'\theta'
assert latex(Symbol('iota')) == r'\iota'
assert latex(Symbol('kappa')) == r'\kappa'
assert latex(Symbol('lambda')) == r'\lambda'
assert latex(Symbol('mu')) == r'\mu'
assert latex(Symbol('nu')) == r'\nu'
assert latex(Symbol('xi')) == r'\xi'
assert latex(Symbol('omicron')) == r'o'
assert latex(Symbol('pi')) == r'\pi'
assert latex(Symbol('rho')) == r'\rho'
assert latex(Symbol('sigma')) == r'\sigma'
assert latex(Symbol('tau')) == r'\tau'
assert latex(Symbol('upsilon')) == r'\upsilon'
assert latex(Symbol('phi')) == r'\phi'
assert latex(Symbol('chi')) == r'\chi'
assert latex(Symbol('psi')) == r'\psi'
assert latex(Symbol('omega')) == r'\omega'
assert latex(Symbol('Alpha')) == r'\mathrm{A}'
assert latex(Symbol('Beta')) == r'\mathrm{B}'
assert latex(Symbol('Gamma')) == r'\Gamma'
assert latex(Symbol('Delta')) == r'\Delta'
assert latex(Symbol('Epsilon')) == r'\mathrm{E}'
assert latex(Symbol('Zeta')) == r'\mathrm{Z}'
assert latex(Symbol('Eta')) == r'\mathrm{H}'
assert latex(Symbol('Theta')) == r'\Theta'
assert latex(Symbol('Iota')) == r'\mathrm{I}'
assert latex(Symbol('Kappa')) == r'\mathrm{K}'
assert latex(Symbol('Lambda')) == r'\Lambda'
assert latex(Symbol('Mu')) == r'\mathrm{M}'
assert latex(Symbol('Nu')) == r'\mathrm{N}'
assert latex(Symbol('Xi')) == r'\Xi'
assert latex(Symbol('Omicron')) == r'\mathrm{O}'
assert latex(Symbol('Pi')) == r'\Pi'
assert latex(Symbol('Rho')) == r'\mathrm{P}'
assert latex(Symbol('Sigma')) == r'\Sigma'
assert latex(Symbol('Tau')) == r'\mathrm{T}'
assert latex(Symbol('Upsilon')) == r'\Upsilon'
assert latex(Symbol('Phi')) == r'\Phi'
assert latex(Symbol('Chi')) == r'\mathrm{X}'
assert latex(Symbol('Psi')) == r'\Psi'
assert latex(Symbol('Omega')) == r'\Omega'
assert latex(Symbol('varepsilon')) == r'\varepsilon'
assert latex(Symbol('varkappa')) == r'\varkappa'
assert latex(Symbol('varphi')) == r'\varphi'
assert latex(Symbol('varpi')) == r'\varpi'
assert latex(Symbol('varrho')) == r'\varrho'
assert latex(Symbol('varsigma')) == r'\varsigma'
assert latex(Symbol('vartheta')) == r'\vartheta'
def test_fancyset_symbols():
assert latex(S.Rationals) == r'\mathbb{Q}'
assert latex(S.Naturals) == r'\mathbb{N}'
assert latex(S.Naturals0) == r'\mathbb{N}_0'
assert latex(S.Integers) == r'\mathbb{Z}'
assert latex(S.Reals) == r'\mathbb{R}'
assert latex(S.Complexes) == r'\mathbb{C}'
@XFAIL
def test_builtin_without_args_mismatched_names():
assert latex(CosineTransform) == r'\mathcal{COS}'
def test_builtin_no_args():
assert latex(Chi) == r'\operatorname{Chi}'
assert latex(beta) == r'\operatorname{B}'
assert latex(gamma) == r'\Gamma'
assert latex(KroneckerDelta) == r'\delta'
assert latex(DiracDelta) == r'\delta'
assert latex(lowergamma) == r'\gamma'
def test_issue_6853():
p = Function('Pi')
assert latex(p(x)) == r"\Pi{\left(x \right)}"
def test_Mul():
e = Mul(-2, x + 1, evaluate=False)
assert latex(e) == r'- 2 \left(x + 1\right)'
e = Mul(2, x + 1, evaluate=False)
assert latex(e) == r'2 \left(x + 1\right)'
e = Mul(S.Half, x + 1, evaluate=False)
assert latex(e) == r'\frac{x + 1}{2}'
e = Mul(y, x + 1, evaluate=False)
assert latex(e) == r'y \left(x + 1\right)'
e = Mul(-y, x + 1, evaluate=False)
assert latex(e) == r'- y \left(x + 1\right)'
e = Mul(-2, x + 1)
assert latex(e) == r'- 2 x - 2'
e = Mul(2, x + 1)
assert latex(e) == r'2 x + 2'
def test_Pow():
e = Pow(2, 2, evaluate=False)
assert latex(e) == r'2^{2}'
assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}'
x2 = Symbol(r'x^2')
assert latex(x2**2) == r'\left(x^{2}\right)^{2}'
def test_issue_7180():
assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y"
assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y"
def test_issue_8409():
assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}"
def test_issue_8470():
from sympy.parsing.sympy_parser import parse_expr
e = parse_expr("-B*A", evaluate=False)
assert latex(e) == r"A \left(- B\right)"
def test_issue_15439():
x = MatrixSymbol('x', 2, 2)
y = MatrixSymbol('y', 2, 2)
assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)"
assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)"
assert latex((x * y).subs(x, -x)) == r"\left(- x\right) y"
def test_issue_2934():
assert latex(Symbol(r'\frac{a_1}{b_1}')) == r'\frac{a_1}{b_1}'
def test_issue_10489():
latexSymbolWithBrace = r'C_{x_{0}}'
s = Symbol(latexSymbolWithBrace)
assert latex(s) == latexSymbolWithBrace
assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}'
def test_issue_12886():
m__1, l__1 = symbols('m__1, l__1')
assert latex(m__1**2 + l__1**2) == \
r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}'
def test_issue_13559():
from sympy.parsing.sympy_parser import parse_expr
expr = parse_expr('5/1', evaluate=False)
assert latex(expr) == r"\frac{5}{1}"
def test_issue_13651():
expr = c + Mul(-1, a + b, evaluate=False)
assert latex(expr) == r"c - \left(a + b\right)"
def test_latex_UnevaluatedExpr():
x = symbols("x")
he = UnevaluatedExpr(1/x)
assert latex(he) == latex(1/x) == r"\frac{1}{x}"
assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}"
assert latex(he + 1) == r"1 + \frac{1}{x}"
assert latex(x*he) == r"x \frac{1}{x}"
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
assert latex(A[0, 0]) == r"A_{0, 0}"
assert latex(3 * A[0, 0]) == r"3 A_{0, 0}"
F = C[0, 0].subs(C, A - B)
assert latex(F) == r"\left(A - B\right)_{0, 0}"
i, j, k = symbols("i j k")
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
assert latex((M*N)[i, j]) == \
r'\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}'
def test_MatrixSymbol_printing():
# test cases for issue #14237
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
assert latex(-A) == r"- A"
assert latex(A - A*B - B) == r"A - A B - B"
assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B"
def test_KroneckerProduct_printing():
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 2, 2)
assert latex(KroneckerProduct(A, B)) == r'A \otimes B'
def test_Series_printing():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
assert latex(Series(tf1, tf2)) == \
r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right)'
assert latex(Series(tf1, tf2, tf3)) == \
r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right) \left(\frac{t x^{2} - t^{w} x + w}{t - y}\right)'
assert latex(Series(-tf2, tf1)) == \
r'\left(\frac{- x + y}{x + y}\right) \left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right)'
M_1 = Matrix([[5/s], [5/(2*s)]])
T_1 = TransferFunctionMatrix.from_Matrix(M_1, s)
M_2 = Matrix([[5, 6*s**3]])
T_2 = TransferFunctionMatrix.from_Matrix(M_2, s)
# Brackets
assert latex(T_1*(T_2 + T_2)) == \
r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left(\left[\begin{matrix}\frac{5}{1} &' \
r' \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau\right)' \
== latex(MIMOSeries(MIMOParallel(T_2, T_2), T_1))
# No Brackets
M_3 = Matrix([[5, 6], [6, 5/s]])
T_3 = TransferFunctionMatrix.from_Matrix(M_3, s)
assert latex(T_1*T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}' \
r'\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & ' \
r'\frac{5}{s}\end{matrix}\right]_\tau' == latex(MIMOParallel(MIMOSeries(T_2, T_1), T_3))
def test_TransferFunction_printing():
tf1 = TransferFunction(x - 1, x + 1, x)
assert latex(tf1) == r"\frac{x - 1}{x + 1}"
tf2 = TransferFunction(x + 1, 2 - y, x)
assert latex(tf2) == r"\frac{x + 1}{2 - y}"
tf3 = TransferFunction(y, y**2 + 2*y + 3, y)
assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}"
def test_Parallel_printing():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
assert latex(Parallel(tf1, tf2)) == \
r'\frac{x y^{2} - z}{- t^{3} + y^{3}} + \frac{x - y}{x + y}'
assert latex(Parallel(-tf2, tf1)) == \
r'\frac{- x + y}{x + y} + \frac{x y^{2} - z}{- t^{3} + y^{3}}'
M_1 = Matrix([[5, 6], [6, 5/s]])
T_1 = TransferFunctionMatrix.from_Matrix(M_1, s)
M_2 = Matrix([[5/s, 6], [6, 5/(s - 1)]])
T_2 = TransferFunctionMatrix.from_Matrix(M_2, s)
M_3 = Matrix([[6, 5/(s*(s - 1))], [5, 6]])
T_3 = TransferFunctionMatrix.from_Matrix(M_3, s)
assert latex(T_1 + T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s}\end{matrix}\right]' \
r'_\tau + \left[\begin{matrix}\frac{5}{s} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s - 1}\end{matrix}\right]_\tau + \left[\begin{matrix}' \
r'\frac{6}{1} & \frac{5}{s \left(s - 1\right)}\\\frac{5}{1} & \frac{6}{1}\end{matrix}\right]_\tau' \
== latex(MIMOParallel(T_1, T_2, T_3)) == latex(MIMOParallel(T_1, MIMOParallel(T_2, T_3))) == latex(MIMOParallel(MIMOParallel(T_1, T_2), T_3))
def test_TransferFunctionMatrix_printing():
tf1 = TransferFunction(p, p + x, p)
tf2 = TransferFunction(-s + p, p + s, p)
tf3 = TransferFunction(p, y**2 + 2*y + 3, p)
assert latex(TransferFunctionMatrix([[tf1], [tf2]])) == \
r'\left[\begin{matrix}\frac{p}{p + x}\\\frac{p - s}{p + s}\end{matrix}\right]_\tau'
assert latex(TransferFunctionMatrix([[tf1, tf2], [tf3, -tf1]])) == \
r'\left[\begin{matrix}\frac{p}{p + x} & \frac{p - s}{p + s}\\\frac{p}{y^{2} + 2 y + 3} & \frac{\left(-1\right) p}{p + x}\end{matrix}\right]_\tau'
def test_Feedback_printing():
tf1 = TransferFunction(p, p + x, p)
tf2 = TransferFunction(-s + p, p + s, p)
# Negative Feedback (Default)
assert latex(Feedback(tf1, tf2)) == \
r'\frac{\frac{p}{p + x}}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \
r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
# Positive Feedback
assert latex(Feedback(tf1, tf2, 1)) == \
r'\frac{\frac{p}{p + x}}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
assert latex(Feedback(tf1*tf2, sign=1)) == \
r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
def test_MIMOFeedback_printing():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**2 - 1, s)
tf3 = TransferFunction(s, s - 1, s)
tf4 = TransferFunction(s**2, s**2 - 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf4, tf3], [tf2, tf1]])
# Negative Feedback (Default)
assert latex(MIMOFeedback(tfm_1, tfm_2)) == \
r'\left(I_{\tau} + \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[' \
r'\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}' \
r'\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau'
# Positive Feedback
assert latex(MIMOFeedback(tfm_1*tfm_2, tfm_1, 1)) == \
r'\left(I_{\tau} - \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left' \
r'[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \
r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \
r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1}' \
r' & \frac{1}{s}\end{matrix}\right]_\tau'
def test_Quaternion_latex_printing():
q = Quaternion(x, y, z, t)
assert latex(q) == r"x + y i + z j + t k"
q = Quaternion(x, y, z, x*t)
assert latex(q) == r"x + y i + z j + t x k"
q = Quaternion(x, y, z, x + t)
assert latex(q) == r"x + y i + z j + \left(t + x\right) k"
def test_TensorProduct_printing():
from sympy.tensor.functions import TensorProduct
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
assert latex(TensorProduct(A, B)) == r"A \otimes B"
def test_WedgeProduct_printing():
from sympy.diffgeom.rn import R2
from sympy.diffgeom import WedgeProduct
wp = WedgeProduct(R2.dx, R2.dy)
assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y"
def test_issue_9216():
expr_1 = Pow(1, -1, evaluate=False)
assert latex(expr_1) == r"1^{-1}"
expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False)
assert latex(expr_2) == r"1^{1^{-1}}"
expr_3 = Pow(3, -2, evaluate=False)
assert latex(expr_3) == r"\frac{1}{9}"
expr_4 = Pow(1, -2, evaluate=False)
assert latex(expr_4) == r"1^{-2}"
def test_latex_printer_tensor():
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads
L = TensorIndexType("L")
i, j, k, l = tensor_indices("i j k l", L)
i0 = tensor_indices("i_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
K = TensorHead("K", [L, L, L, L])
assert latex(i) == r"{}^{i}"
assert latex(-i) == r"{}_{i}"
expr = A(i)
assert latex(expr) == r"A{}^{i}"
expr = A(i0)
assert latex(expr) == r"A{}^{i_{0}}"
expr = A(-i)
assert latex(expr) == r"A{}_{i}"
expr = -3*A(i)
assert latex(expr) == r"-3A{}^{i}"
expr = K(i, j, -k, -i0)
assert latex(expr) == r"K{}^{ij}{}_{ki_{0}}"
expr = K(i, -j, -k, i0)
assert latex(expr) == r"K{}^{i}{}_{jk}{}^{i_{0}}"
expr = K(i, -j, k, -i0)
assert latex(expr) == r"K{}^{i}{}_{j}{}^{k}{}_{i_{0}}"
expr = H(i, -j)
assert latex(expr) == r"H{}^{i}{}_{j}"
expr = H(i, j)
assert latex(expr) == r"H{}^{ij}"
expr = H(-i, -j)
assert latex(expr) == r"H{}_{ij}"
expr = (1+x)*A(i)
assert latex(expr) == r"\left(x + 1\right)A{}^{i}"
expr = H(i, -i)
assert latex(expr) == r"H{}^{L_{0}}{}_{L_{0}}"
expr = H(i, -j)*A(j)*B(k)
assert latex(expr) == r"H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}"
expr = A(i) + 3*B(i)
assert latex(expr) == r"3B{}^{i} + A{}^{i}"
# Test ``TensorElement``:
from sympy.tensor.tensor import TensorElement
expr = TensorElement(K(i, j, k, l), {i: 3, k: 2})
assert latex(expr) == r'K{}^{i=3,j,k=2,l}'
expr = TensorElement(K(i, j, k, l), {i: 3})
assert latex(expr) == r'K{}^{i=3,jkl}'
expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2})
assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2,l}'
expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2})
assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2})
assert latex(expr) == r'K{}^{i=3,j}{}_{k=2,l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3})
assert latex(expr) == r'K{}^{i=3,j}{}_{kl}'
expr = PartialDerivative(A(i), A(i))
assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}"
expr = PartialDerivative(A(-i), A(-j))
assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}"
expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n))
assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}"
expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n))
assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}"
expr = PartialDerivative(3*A(-i), A(-j), A(-n))
assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}"
def test_multiline_latex():
a, b, c, d, e, f = symbols('a b c d e f')
expr = -a + 2*b -3*c +4*d -5*e
expected = r"\begin{eqnarray}" + "\n"\
r"f & = &- a \nonumber\\" + "\n"\
r"& & + 2 b \nonumber\\" + "\n"\
r"& & - 3 c \nonumber\\" + "\n"\
r"& & + 4 d \nonumber\\" + "\n"\
r"& & - 5 e " + "\n"\
r"\end{eqnarray}"
assert multiline_latex(f, expr, environment="eqnarray") == expected
expected2 = r'\begin{eqnarray}' + '\n'\
r'f & = &- a + 2 b \nonumber\\' + '\n'\
r'& & - 3 c + 4 d \nonumber\\' + '\n'\
r'& & - 5 e ' + '\n'\
r'\end{eqnarray}'
assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2
expected3 = r'\begin{eqnarray}' + '\n'\
r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\
r'& & + 4 d - 5 e ' + '\n'\
r'\end{eqnarray}'
assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3
expected3dots = r'\begin{eqnarray}' + '\n'\
r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\
r'& & + 4 d - 5 e ' + '\n'\
r'\end{eqnarray}'
assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots
expected3align = r'\begin{align*}' + '\n'\
r'f = &- a + 2 b - 3 c \\'+ '\n'\
r'& + 4 d - 5 e ' + '\n'\
r'\end{align*}'
assert multiline_latex(f, expr, 3) == expected3align
assert multiline_latex(f, expr, 3, environment='align*') == expected3align
expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\
r'f & = &- a + 2 b \nonumber\\' + '\n'\
r'& & - 3 c + 4 d \nonumber\\' + '\n'\
r'& & - 5 e ' + '\n'\
r'\end{IEEEeqnarray}'
assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee
raises(ValueError, lambda: multiline_latex(f, expr, environment="foo"))
def test_issue_15353():
a, x = symbols('a x')
# Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a])
sol = ConditionSet(
Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2)
assert latex(sol) == \
r'\left\{\left( x, \ a\right)\; \middle|\; \left( x, \ a\right) \in ' \
r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \
r'\cos{\left(a x \right)} = 0 \right\}'
def test_latex_symbolic_probability():
mu = symbols("mu")
sigma = symbols("sigma", positive=True)
X = Normal("X", mu, sigma)
assert latex(Expectation(X)) == r'\operatorname{E}\left[X\right]'
assert latex(Variance(X)) == r'\operatorname{Var}\left(X\right)'
assert latex(Probability(X > 0)) == r'\operatorname{P}\left(X > 0\right)'
Y = Normal("Y", mu, sigma)
assert latex(Covariance(X, Y)) == r'\operatorname{Cov}\left(X, Y\right)'
def test_trace():
# Issue 15303
from sympy.matrices.expressions.trace import trace
A = MatrixSymbol("A", 2, 2)
assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)"
assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)"
def test_print_basic():
# Issue 15303
from sympy.core.basic import Basic
from sympy.core.expr import Expr
# dummy class for testing printing where the function is not
# implemented in latex.py
class UnimplementedExpr(Expr):
def __new__(cls, e):
return Basic.__new__(cls, e)
# dummy function for testing
def unimplemented_expr(expr):
return UnimplementedExpr(expr).doit()
# override class name to use superscript / subscript
def unimplemented_expr_sup_sub(expr):
result = UnimplementedExpr(expr)
result.__class__.__name__ = 'UnimplementedExpr_x^1'
return result
assert latex(unimplemented_expr(x)) == r'\operatorname{UnimplementedExpr}\left(x\right)'
assert latex(unimplemented_expr(x**2)) == \
r'\operatorname{UnimplementedExpr}\left(x^{2}\right)'
assert latex(unimplemented_expr_sup_sub(x)) == \
r'\operatorname{UnimplementedExpr^{1}_{x}}\left(x\right)'
def test_MatrixSymbol_bold():
# Issue #15871
from sympy.matrices.expressions.trace import trace
A = MatrixSymbol("A", 2, 2)
assert latex(trace(A), mat_symbol_style='bold') == \
r"\operatorname{tr}\left(\mathbf{A} \right)"
assert latex(trace(A), mat_symbol_style='plain') == \
r"\operatorname{tr}\left(A \right)"
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}"
assert latex(A - A*B - B, mat_symbol_style='bold') == \
r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}"
assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \
r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}"
A_k = MatrixSymbol("A_k", 3, 3)
assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}"
A = MatrixSymbol(r"\nabla_k", 3, 3)
assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{k}"
def test_AppliedPermutation():
p = Permutation(0, 1, 2)
x = Symbol('x')
assert latex(AppliedPermutation(p, x)) == \
r'\sigma_{\left( 0\; 1\; 2\right)}(x)'
def test_PermutationMatrix():
p = Permutation(0, 1, 2)
assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}'
p = Permutation(0, 3)(1, 2)
assert latex(PermutationMatrix(p)) == \
r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}'
def test_issue_21758():
from sympy.functions.elementary.piecewise import piecewise_fold
from sympy.series.fourier import FourierSeries
x = Symbol('x')
k, n = symbols('k n')
fo = FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)), SeqFormula(
Piecewise((-2*pi*cos(n*pi)/n + 2*sin(n*pi)/n**2, (n > -oo) & (n < oo) & Ne(n, 0)),
(0, True))*sin(n*x)/pi, (n, 1, oo))))
assert latex(piecewise_fold(fo)) == '\\begin{cases} 2 \\sin{\\left(x \\right)}' \
' - \\sin{\\left(2 x \\right)} + \\frac{2 \\sin{\\left(3 x \\right)}}{3} +' \
' \\ldots & \\text{for}\\: n > -\\infty \\wedge n < \\infty \\wedge ' \
'n \\neq 0 \\\\0 & \\text{otherwise} \\end{cases}'
assert latex(FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)),
SeqFormula(0, (n, 1, oo))))) == '0'
def test_imaginary_unit():
assert latex(1 + I) == r'1 + i'
assert latex(1 + I, imaginary_unit='i') == r'1 + i'
assert latex(1 + I, imaginary_unit='j') == r'1 + j'
assert latex(1 + I, imaginary_unit='foo') == r'1 + foo'
assert latex(I, imaginary_unit="ti") == r'\text{i}'
assert latex(I, imaginary_unit="tj") == r'\text{j}'
def test_text_re_im():
assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}'
assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}'
assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}'
assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}'
def test_latex_diffgeom():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
from sympy.diffgeom.rn import R2
x,y = symbols('x y', real=True)
m = Manifold('M', 2)
assert latex(m) == r'\text{M}'
p = Patch('P', m)
assert latex(p) == r'\text{P}_{\text{M}}'
rect = CoordSystem('rect', p, [x, y])
assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}'
b = BaseScalarField(rect, 0)
assert latex(b) == r'\mathbf{x}'
g = Function('g')
s_field = g(R2.x, R2.y)
assert latex(Differential(s_field)) == \
r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)'
def test_unit_printing():
assert latex(5*meter) == r'5 \text{m}'
assert latex(3*gibibyte) == r'3 \text{gibibyte}'
assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}'
assert latex(4*micro*gram/second) == r'\frac{4 \mu \text{g}}{\text{s}}'
assert latex(5*milli*meter) == r'5 \text{m} \text{m}'
assert latex(milli) == r'\text{m}'
def test_issue_17092():
x_star = Symbol('x^*')
assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}'
def test_latex_decimal_separator():
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
# comma decimal_separator
assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \ 2{,}3; \ 4{,}5\right]')
assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}')
assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \ 2{,}3; \ 4{,}6\right)')
assert(latex((1,), decimal_separator='comma') == r'\left( 1;\right)')
# period decimal_separator
assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \ 2.3, \ 4.5\right]' )
assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}')
assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \ 2.3, \ 4.6\right)')
assert(latex((1,), decimal_separator='period') == r'\left( 1,\right)')
# default decimal_separator
assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \ 2.3, \ 4.5\right]')
assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}')
assert(latex((1, 2.3, 4.6)) == r'\left( 1, \ 2.3, \ 4.6\right)')
assert(latex((1,)) == r'\left( 1,\right)')
assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') == r'18{,}02')
assert(latex(3.4*5.3, decimal_separator = 'comma') == r'18{,}02')
x = symbols('x')
y = symbols('y')
z = symbols('z')
assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma') == r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5')
assert(latex(0.987, decimal_separator='comma') == r'0{,}987')
assert(latex(S(0.987), decimal_separator='comma') == r'0{,}987')
assert(latex(.3, decimal_separator='comma') == r'0{,}3')
assert(latex(S(.3), decimal_separator='comma') == r'0{,}3')
assert(latex(5.8*10**(-7), decimal_separator='comma') == r'5{,}8 \cdot 10^{-7}')
assert(latex(S(5.7)*10**(-7), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}')
assert(latex(S(5.7*10**(-7)), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}')
x = symbols('x')
assert(latex(1.2*x+3.4, decimal_separator='comma') == r'1{,}2 x + 3{,}4')
assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}')
# Error Handling tests
raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list'))
raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set'))
raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple'))
def test_Str():
from sympy.core.symbol import Str
assert str(Str('x')) == r'x'
def test_latex_escape():
assert latex_escape(r"~^\&%$#_{}") == "".join([
r'\textasciitilde',
r'\textasciicircum',
r'\textbackslash',
r'\&',
r'\%',
r'\$',
r'\#',
r'\_',
r'\{',
r'\}',
])
def test_emptyPrinter():
class MyObject:
def __repr__(self):
return "<MyObject with {...}>"
# unknown objects are monospaced
assert latex(MyObject()) == r"\mathtt{\text{<MyObject with \{...\}>}}"
# even if they are nested within other objects
assert latex((MyObject(),)) == r"\left( \mathtt{\text{<MyObject with \{...\}>}},\right)"
def test_global_settings():
import inspect
# settings should be visible in the signature of `latex`
assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i'
assert latex(I) == r'i'
try:
# but changing the defaults...
LatexPrinter.set_global_settings(imaginary_unit='j')
# ... should change the signature
assert inspect.signature(latex).parameters['imaginary_unit'].default == r'j'
assert latex(I) == r'j'
finally:
# there's no public API to undo this, but we need to make sure we do
# so as not to impact other tests
del LatexPrinter._global_settings['imaginary_unit']
# check we really did undo it
assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i'
assert latex(I) == r'i'
def test_pickleable():
# this tests that the _PrintFunction instance is pickleable
import pickle
assert pickle.loads(pickle.dumps(latex)) is latex
def test_printing_latex_array_expressions():
assert latex(ArraySymbol("A", (2, 3, 4))) == "A"
assert latex(ArrayElement("A", (2, 1/(1-x), 0))) == "{{A}_{2, \\frac{1}{1 - x}, 0}}"
M = MatrixSymbol("M", 3, 3)
N = MatrixSymbol("N", 3, 3)
assert latex(ArrayElement(M*N, [x, 0])) == "{{\\left(M N\\right)}_{x, 0}}"
def test_Array():
arr = Array(range(10))
assert latex(arr) == r'\left[\begin{matrix}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\end{matrix}\right]'
arr = Array(range(11))
# added empty arguments {}
assert latex(arr) == r'\left[\begin{array}{}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]'
|
86e7135f421220e396c9c78f0d4b612acf0be6b2bc9d3957e263a54cfa6e07b0 | from sympy.core import (S, pi, oo, Symbol, symbols, Rational, Integer,
GoldenRatio, EulerGamma, Catalan, Lambda, Dummy)
from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
gamma, sign, Max, Min, factorial, beta)
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
from sympy.sets import Range
from sympy.logic import ITE
from sympy.codegen import For, aug_assign, Assignment
from sympy.testing.pytest import raises
from sympy.printing.rcode import RCodePrinter
from sympy.utilities.lambdify import implemented_function
from sympy.tensor import IndexedBase, Idx
from sympy.matrices import Matrix, MatrixSymbol
from sympy.printing.rcode import rcode
x, y, z = symbols('x,y,z')
def test_printmethod():
class fabs(Abs):
def _rcode(self, printer):
return "abs(%s)" % printer._print(self.args[0])
assert rcode(fabs(x)) == "abs(x)"
def test_rcode_sqrt():
assert rcode(sqrt(x)) == "sqrt(x)"
assert rcode(x**0.5) == "sqrt(x)"
assert rcode(sqrt(x)) == "sqrt(x)"
def test_rcode_Pow():
assert rcode(x**3) == "x^3"
assert rcode(x**(y**3)) == "x^(y^3)"
g = implemented_function('g', Lambda(x, 2*x))
assert rcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
"(3.5*2*x)^(-x + y^x)/(x^2 + y)"
assert rcode(x**-1.0) == '1.0/x'
assert rcode(x**Rational(2, 3)) == 'x^(2.0/3.0)'
_cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"),
(lambda base, exp: not exp.is_integer, "pow")]
assert rcode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)'
assert rcode(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 3.2)'
def test_rcode_Max():
# Test for gh-11926
assert rcode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))'
def test_rcode_constants_mathh():
assert rcode(exp(1)) == "exp(1)"
assert rcode(pi) == "pi"
assert rcode(oo) == "Inf"
assert rcode(-oo) == "-Inf"
def test_rcode_constants_other():
assert rcode(2*GoldenRatio) == "GoldenRatio = 1.61803398874989;\n2*GoldenRatio"
assert rcode(
2*Catalan) == "Catalan = 0.915965594177219;\n2*Catalan"
assert rcode(2*EulerGamma) == "EulerGamma = 0.577215664901533;\n2*EulerGamma"
def test_rcode_Rational():
assert rcode(Rational(3, 7)) == "3.0/7.0"
assert rcode(Rational(18, 9)) == "2"
assert rcode(Rational(3, -7)) == "-3.0/7.0"
assert rcode(Rational(-3, -7)) == "3.0/7.0"
assert rcode(x + Rational(3, 7)) == "x + 3.0/7.0"
assert rcode(Rational(3, 7)*x) == "(3.0/7.0)*x"
def test_rcode_Integer():
assert rcode(Integer(67)) == "67"
assert rcode(Integer(-1)) == "-1"
def test_rcode_functions():
assert rcode(sin(x) ** cos(x)) == "sin(x)^cos(x)"
assert rcode(factorial(x) + gamma(y)) == "factorial(x) + gamma(y)"
assert rcode(beta(Min(x, y), Max(x, y))) == "beta(min(x, y), max(x, y))"
def test_rcode_inline_function():
x = symbols('x')
g = implemented_function('g', Lambda(x, 2*x))
assert rcode(g(x)) == "2*x"
g = implemented_function('g', Lambda(x, 2*x/Catalan))
assert rcode(
g(x)) == "Catalan = %s;\n2*x/Catalan" % Catalan.n()
A = IndexedBase('A')
i = Idx('i', symbols('n', integer=True))
g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
res=rcode(g(A[i]), assign_to=A[i])
ref=(
"for (i in 1:n){\n"
" A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
"}"
)
assert res == ref
def test_rcode_exceptions():
assert rcode(ceiling(x)) == "ceiling(x)"
assert rcode(Abs(x)) == "abs(x)"
assert rcode(gamma(x)) == "gamma(x)"
def test_rcode_user_functions():
x = symbols('x', integer=False)
n = symbols('n', integer=True)
custom_functions = {
"ceiling": "myceil",
"Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
}
assert rcode(ceiling(x), user_functions=custom_functions) == "myceil(x)"
assert rcode(Abs(x), user_functions=custom_functions) == "fabs(x)"
assert rcode(Abs(n), user_functions=custom_functions) == "abs(n)"
def test_rcode_boolean():
assert rcode(True) == "True"
assert rcode(S.true) == "True"
assert rcode(False) == "False"
assert rcode(S.false) == "False"
assert rcode(x & y) == "x & y"
assert rcode(x | y) == "x | y"
assert rcode(~x) == "!x"
assert rcode(x & y & z) == "x & y & z"
assert rcode(x | y | z) == "x | y | z"
assert rcode((x & y) | z) == "z | x & y"
assert rcode((x | y) & z) == "z & (x | y)"
def test_rcode_Relational():
assert rcode(Eq(x, y)) == "x == y"
assert rcode(Ne(x, y)) == "x != y"
assert rcode(Le(x, y)) == "x <= y"
assert rcode(Lt(x, y)) == "x < y"
assert rcode(Gt(x, y)) == "x > y"
assert rcode(Ge(x, y)) == "x >= y"
def test_rcode_Piecewise():
expr = Piecewise((x, x < 1), (x**2, True))
res=rcode(expr)
ref="ifelse(x < 1,x,x^2)"
assert res == ref
tau=Symbol("tau")
res=rcode(expr,tau)
ref="tau = ifelse(x < 1,x,x^2);"
assert res == ref
expr = 2*Piecewise((x, x < 1), (x**2, x<2), (x**3,True))
assert rcode(expr) == "2*ifelse(x < 1,x,ifelse(x < 2,x^2,x^3))"
res = rcode(expr, assign_to='c')
assert res == "c = 2*ifelse(x < 1,x,ifelse(x < 2,x^2,x^3));"
# Check that Piecewise without a True (default) condition error
#expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
#raises(ValueError, lambda: rcode(expr))
expr = 2*Piecewise((x, x < 1), (x**2, x<2))
assert(rcode(expr))== "2*ifelse(x < 1,x,ifelse(x < 2,x^2,NA))"
def test_rcode_sinc():
from sympy.functions.elementary.trigonometric import sinc
expr = sinc(x)
res = rcode(expr)
ref = "ifelse(x != 0,sin(x)/x,1)"
assert res == ref
def test_rcode_Piecewise_deep():
p = rcode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)))
assert p == "2*ifelse(x < 1,x,ifelse(x < 2,x + 1,x^2))"
expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1
p = rcode(expr)
ref="x^2 + x*y*z + y^2 + ifelse(x < 0.5,0,1) + cos(z) - 1"
assert p == ref
ref="c = x^2 + x*y*z + y^2 + ifelse(x < 0.5,0,1) + cos(z) - 1;"
p = rcode(expr, assign_to='c')
assert p == ref
def test_rcode_ITE():
expr = ITE(x < 1, y, z)
p = rcode(expr)
ref="ifelse(x < 1,y,z)"
assert p == ref
def test_rcode_settings():
raises(TypeError, lambda: rcode(sin(x), method="garbage"))
def test_rcode_Indexed():
n, m, o = symbols('n m o', integer=True)
i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
p = RCodePrinter()
p._not_r = set()
x = IndexedBase('x')[j]
assert p._print_Indexed(x) == 'x[j]'
A = IndexedBase('A')[i, j]
assert p._print_Indexed(A) == 'A[i, j]'
B = IndexedBase('B')[i, j, k]
assert p._print_Indexed(B) == 'B[i, j, k]'
assert p._not_r == set()
def test_rcode_Indexed_without_looking_for_contraction():
len_y = 5
y = IndexedBase('y', shape=(len_y,))
x = IndexedBase('x', shape=(len_y,))
Dy = IndexedBase('Dy', shape=(len_y-1,))
i = Idx('i', len_y-1)
e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
code0 = rcode(e.rhs, assign_to=e.lhs, contract=False)
assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1)
def test_rcode_loops_matrix_vector():
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
s = (
'for (i in 1:m){\n'
' y[i] = 0;\n'
'}\n'
'for (i in 1:m){\n'
' for (j in 1:n){\n'
' y[i] = A[i, j]*x[j] + y[i];\n'
' }\n'
'}'
)
c = rcode(A[i, j]*x[j], assign_to=y[i])
assert c == s
def test_dummy_loops():
# the following line could also be
# [Dummy(s, integer=True) for s in 'im']
# or [Dummy(integer=True) for s in 'im']
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'for (i_%(icount)i in 1:m_%(mcount)i){\n'
' y[i_%(icount)i] = x[i_%(icount)i];\n'
'}'
) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
code = rcode(x[i], assign_to=y[i])
assert code == expected
def test_rcode_loops_add():
n, m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
z = IndexedBase('z')
i = Idx('i', m)
j = Idx('j', n)
s = (
'for (i in 1:m){\n'
' y[i] = x[i] + z[i];\n'
'}\n'
'for (i in 1:m){\n'
' for (j in 1:n){\n'
' y[i] = A[i, j]*x[j] + y[i];\n'
' }\n'
'}'
)
c = rcode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i])
assert c == s
def test_rcode_loops_multiple_contractions():
n, m, o, p = symbols('n m o p', integer=True)
a = IndexedBase('a')
b = IndexedBase('b')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
s = (
'for (i in 1:m){\n'
' y[i] = 0;\n'
'}\n'
'for (i in 1:m){\n'
' for (j in 1:n){\n'
' for (k in 1:o){\n'
' for (l in 1:p){\n'
' y[i] = a[i, j, k, l]*b[j, k, l] + y[i];\n'
' }\n'
' }\n'
' }\n'
'}'
)
c = rcode(b[j, k, l]*a[i, j, k, l], assign_to=y[i])
assert c == s
def test_rcode_loops_addfactor():
n, m, o, p = symbols('n m o p', integer=True)
a = IndexedBase('a')
b = IndexedBase('b')
c = IndexedBase('c')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
l = Idx('l', p)
s = (
'for (i in 1:m){\n'
' y[i] = 0;\n'
'}\n'
'for (i in 1:m){\n'
' for (j in 1:n){\n'
' for (k in 1:o){\n'
' for (l in 1:p){\n'
' y[i] = (a[i, j, k, l] + b[i, j, k, l])*c[j, k, l] + y[i];\n'
' }\n'
' }\n'
' }\n'
'}'
)
c = rcode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
assert c == s
def test_rcode_loops_multiple_terms():
n, m, o, p = symbols('n m o p', integer=True)
a = IndexedBase('a')
b = IndexedBase('b')
c = IndexedBase('c')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)
k = Idx('k', o)
s0 = (
'for (i in 1:m){\n'
' y[i] = 0;\n'
'}\n'
)
s1 = (
'for (i in 1:m){\n'
' for (j in 1:n){\n'
' for (k in 1:o){\n'
' y[i] = b[j]*b[k]*c[i, j, k] + y[i];\n'
' }\n'
' }\n'
'}\n'
)
s2 = (
'for (i in 1:m){\n'
' for (k in 1:o){\n'
' y[i] = a[i, k]*b[k] + y[i];\n'
' }\n'
'}\n'
)
s3 = (
'for (i in 1:m){\n'
' for (j in 1:n){\n'
' y[i] = a[i, j]*b[j] + y[i];\n'
' }\n'
'}\n'
)
c = rcode(
b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i])
ref=dict()
ref[0] = s0 + s1 + s2 + s3[:-1]
ref[1] = s0 + s1 + s3 + s2[:-1]
ref[2] = s0 + s2 + s1 + s3[:-1]
ref[3] = s0 + s2 + s3 + s1[:-1]
ref[4] = s0 + s3 + s1 + s2[:-1]
ref[5] = s0 + s3 + s2 + s1[:-1]
assert (c == ref[0] or
c == ref[1] or
c == ref[2] or
c == ref[3] or
c == ref[4] or
c == ref[5])
def test_dereference_printing():
expr = x + y + sin(z) + z
assert rcode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))"
def test_Matrix_printing():
# Test returning a Matrix
mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
A = MatrixSymbol('A', 3, 1)
p = rcode(mat, A)
assert p == (
"A[0] = x*y;\n"
"A[1] = ifelse(y > 0,x + 2,y);\n"
"A[2] = sin(z);")
# Test using MatrixElements in expressions
expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
p = rcode(expr)
assert p == ("ifelse(x > 0,2*A[2],A[2]) + sin(A[1]) + A[0]")
# Test using MatrixElements in a Matrix
q = MatrixSymbol('q', 5, 1)
M = MatrixSymbol('M', 3, 3)
m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
[q[1,0] + q[2,0], q[3, 0], 5],
[2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
assert rcode(m, M) == (
"M[0] = sin(q[1]);\n"
"M[1] = 0;\n"
"M[2] = cos(q[2]);\n"
"M[3] = q[1] + q[2];\n"
"M[4] = q[3];\n"
"M[5] = 5;\n"
"M[6] = 2*q[4]/q[1];\n"
"M[7] = sqrt(q[0]) + 4;\n"
"M[8] = 0;")
def test_rcode_sgn():
expr = sign(x) * y
assert rcode(expr) == 'y*sign(x)'
p = rcode(expr, 'z')
assert p == 'z = y*sign(x);'
p = rcode(sign(2 * x + x**2) * x + x**2)
assert p == "x^2 + x*sign(x^2 + 2*x)"
expr = sign(cos(x))
p = rcode(expr)
assert p == 'sign(cos(x))'
def test_rcode_Assignment():
assert rcode(Assignment(x, y + z)) == 'x = y + z;'
assert rcode(aug_assign(x, '+', y + z)) == 'x += y + z;'
def test_rcode_For():
f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)])
sol = rcode(f)
assert sol == ("for(x in seq(from=0, to=9, by=2){\n"
" y *= x;\n"
"}")
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
assert(rcode(A[0, 0]) == "A[0]")
assert(rcode(3 * A[0, 0]) == "3*A[0]")
F = C[0, 0].subs(C, A - B)
assert(rcode(F) == "(A - B)[0]")
|
ca7f2b467b649e2d0a9aa061fcbe85fe3390edba5b6ae480b4ae6867da72d0cb | from typing import Callable
import sympy
from sympy import Add, Implies, sqrt
from sympy.core import Mul, Pow
from sympy.core import (S, pi, symbols, Function, Rational, Integer,
Symbol, Eq, Ne, Le, Lt, Gt, Ge)
from sympy.functions import Piecewise, exp, sin, cos
from sympy.printing.smtlib import smtlib_code
from sympy.testing.pytest import raises
x, y, z = symbols('x,y,z')
def test_Integer():
assert smtlib_code(Integer(67)) == "67"
assert smtlib_code(Integer(-1)) == "-1"
def test_Rational():
assert smtlib_code(Rational(3, 7)) == "(/ 3 7)"
assert smtlib_code(Rational(18, 9)) == "2"
assert smtlib_code(Rational(3, -7)) == "(/ -3 7)"
assert smtlib_code(Rational(-3, -7)) == "(/ 3 7)"
assert smtlib_code(x + Rational(3, 7), auto_declare=False) == "(+ (/ 3 7) x)"
assert smtlib_code(Rational(3, 7) * x) == "(declare-const x Real)\n" \
"(* (/ 3 7) x)"
def test_Relational():
assert smtlib_code(Eq(x, y), auto_declare=False) == "(assert (= x y))"
assert smtlib_code(Ne(x, y), auto_declare=False) == "(assert (not (= x y)))"
assert smtlib_code(Le(x, y), auto_declare=False) == "(assert (<= x y))"
assert smtlib_code(Lt(x, y), auto_declare=False) == "(assert (< x y))"
assert smtlib_code(Gt(x, y), auto_declare=False) == "(assert (> x y))"
assert smtlib_code(Ge(x, y), auto_declare=False) == "(assert (>= x y))"
def test_Function():
assert smtlib_code(sin(x) ** cos(x), auto_declare=False) == "(pow (sin x) (cos x))"
assert smtlib_code(
abs(x),
symbol_table={x: int, y: bool},
known_types={int: "INTEGER_TYPE"},
known_functions={sympy.Abs: "ABSOLUTE_VALUE_OF"}
) == "(declare-const x INTEGER_TYPE)\n" \
"(ABSOLUTE_VALUE_OF x)"
my_fun1 = Function('f1')
assert smtlib_code(
my_fun1(x),
symbol_table={my_fun1: Callable[[bool], float]},
) == "(declare-const x Bool)\n" \
"(declare-fun f1 (Bool) Real)\n" \
"(f1 x)"
assert smtlib_code(
my_fun1(x),
symbol_table={my_fun1: Callable[[bool], bool]},
) == "(declare-const x Bool)\n" \
"(declare-fun f1 (Bool) Bool)\n" \
"(assert (f1 x))"
assert smtlib_code(
Eq(my_fun1(x, z), y),
symbol_table={my_fun1: Callable[[int, bool], bool]},
) == "(declare-const x Int)\n" \
"(declare-const y Bool)\n" \
"(declare-const z Bool)\n" \
"(declare-fun f1 (Int Bool) Bool)\n" \
"(assert (= (f1 x z) y))"
assert smtlib_code(
Eq(my_fun1(x, z), y),
symbol_table={my_fun1: Callable[[int, bool], bool]},
known_functions={my_fun1: "MY_KNOWN_FUN", Eq: '=='}
) == "(declare-const x Int)\n" \
"(declare-const y Bool)\n" \
"(declare-const z Bool)\n" \
"(assert (== (MY_KNOWN_FUN x z) y))"
assert smtlib_code(
Eq(my_fun1(x, z), y),
known_functions={my_fun1: "MY_KNOWN_FUN", Eq: '=='}
) == "(declare-const x Real)\n" \
"(declare-const y Real)\n" \
"(declare-const z Real)\n" \
"(assert (== (MY_KNOWN_FUN x z) y))"
def test_Pow():
assert smtlib_code(x ** 3, auto_declare=False) == "(pow x 3)"
assert smtlib_code(x ** (y ** 3), auto_declare=False) == "(pow x (pow y 3))"
assert smtlib_code(x ** Rational(2, 3), auto_declare=False) == '(pow x (/ 2 3))'
a = Symbol('a', integer=True)
b = Symbol('b', real=True)
c = Symbol('c')
def g(x): return 2 * x
# if x=1, y=2, then expr=2.333...
expr = 1 / (g(a) * 3.5) ** (a - b ** a) / (a ** 2 + b)
assert smtlib_code([
Eq(a < 2, c),
Eq(b > a, c),
c & True,
Eq(expr, 2 + Rational(1, 3))
]) == '(declare-const a Int)\n' \
'(declare-const b Real)\n' \
'(declare-const c Bool)\n' \
'(assert (= (< a 2) c))\n' \
'(assert (= (> b a) c))\n' \
'(assert c)\n' \
'(assert (= ' \
'(* (pow (* 7. a) (+ (pow b a) (* -1 a))) (pow (+ b (pow a 2)) -1)) ' \
'(/ 7 3)' \
'))'
assert smtlib_code(
Mul(-2, c, Pow(Mul(b, b, evaluate=False), -1, evaluate=False), evaluate=False)
) == '(declare-const b Real)\n' \
'(declare-const c Real)\n' \
'(* -2 c (pow (* b b) -1))'
def test_basic_ops():
assert smtlib_code(x * y, auto_declare=False) == "(* x y)"
assert smtlib_code(x + y, auto_declare=False) == "(+ x y)"
# todo: implement re-write, currently does '(+ x (* -1 y))' instead
# assert smtlib_code(x - y, auto_declare=False) == "(- x y)"
assert smtlib_code(-x, auto_declare=False) == "(* -1 x)"
def test_quantifier_extensions():
from sympy.logic.boolalg import Boolean
from sympy import Interval, Tuple, sympify
# start For-all quantifier class example
class ForAll(Boolean):
def _smtlib(self, printer):
bound_symbol_declarations = [
printer._s_expr(sym.name, [
printer._known_types[printer.symbol_table[sym]],
Interval(start, end)
]) for sym, start, end in self.limits
]
return printer._s_expr('forall', [
printer._s_expr('', bound_symbol_declarations),
self.function
])
@property
def bound_symbols(self):
return {s for s, _, _ in self.limits}
@property
def free_symbols(self):
bound_symbol_names = {s.name for s in self.bound_symbols}
return {
s for s in self.function.free_symbols
if s.name not in bound_symbol_names
}
def __new__(cls, *args):
limits = [sympify(a) for a in args if isinstance(a, tuple) or isinstance(a, Tuple)]
function = [sympify(a) for a in args if isinstance(a, Boolean)]
assert len(limits) + len(function) == len(args)
assert len(function) == 1
function = function[0]
if isinstance(function, ForAll): return ForAll.__new__(
ForAll, *(limits + function.limits), function.function
)
inst = Boolean.__new__(cls)
inst._args = tuple(limits + [function])
inst.limits = limits
inst.function = function
return inst
# end For-All Quantifier class example
f = Function('f')
assert smtlib_code(
ForAll((x, -42, +21), Eq(f(x), f(x))),
symbol_table={f: Callable[[float], float]}
) == '(assert (forall ( (x Real [-42, 21])) true))'
assert smtlib_code(
ForAll(
(x, -42, +21), (y, -100, 3),
Implies(Eq(x, y), Eq(f(x), f(y)))
),
symbol_table={f: Callable[[float], float]}
) == '(declare-fun f (Real) Real)\n' \
'(assert (' \
'forall ( (x Real [-42, 21]) (y Real [-100, 3])) ' \
'(=> (= x y) (= (f x) (f y)))' \
'))'
a = Symbol('a', integer=True)
b = Symbol('b', real=True)
c = Symbol('c')
assert smtlib_code(
ForAll(
(a, 2, 100), ForAll(
(b, 2, 100),
Implies(a < b, sqrt(a) < b) | c
))
) == '(declare-const c Bool)\n' \
'(assert (forall ( (a Int [2, 100]) (b Real [2, 100])) ' \
'(or c (=> (< a b) (< (pow a (/ 1 2)) b)))' \
'))'
def test_mix_number_mult_symbols():
assert smtlib_code(
1 / pi,
known_constants={pi: "MY_PI"}
) == '(pow MY_PI -1)'
assert smtlib_code(
[
Eq(pi, 3.14, evaluate=False),
1 / pi,
],
known_constants={pi: "MY_PI"}
) == '(assert (= MY_PI 3.14))\n' \
'(pow MY_PI -1)'
assert smtlib_code(
Add(S.Zero, S.One, S.NegativeOne, S.Half,
S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
known_constants={
S.Pi: 'p', S.GoldenRatio: 'g',
S.Exp1: 'e'
},
known_functions={
Add: 'plus',
exp: 'exp'
},
precision=3
) == '(plus 0 1 -1 (/ 1 2) (exp 1) p g)'
assert smtlib_code(
Add(S.Zero, S.One, S.NegativeOne, S.Half,
S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
known_constants={
S.Pi: 'p'
},
known_functions={
Add: 'plus',
exp: 'exp'
},
precision=3
) == '(plus 0 1 -1 (/ 1 2) (exp 1) p 1.62)'
assert smtlib_code(
Add(S.Zero, S.One, S.NegativeOne, S.Half,
S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
known_functions={Add: 'plus'},
precision=3
) == '(plus 0 1 -1 (/ 1 2) 2.72 3.14 1.62)'
assert smtlib_code(
Add(S.Zero, S.One, S.NegativeOne, S.Half,
S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
known_constants={S.Exp1: 'e'},
known_functions={Add: 'plus'},
precision=3
) == '(plus 0 1 -1 (/ 1 2) e 3.14 1.62)'
def test_boolean():
assert smtlib_code(x & y) == '(declare-const x Bool)\n' \
'(declare-const y Bool)\n' \
'(assert (and x y))'
assert smtlib_code(x | y) == '(declare-const x Bool)\n' \
'(declare-const y Bool)\n' \
'(assert (or x y))'
assert smtlib_code(~x) == '(declare-const x Bool)\n' \
'(assert (not x))'
assert smtlib_code(x & y & z) == '(declare-const x Bool)\n' \
'(declare-const y Bool)\n' \
'(declare-const z Bool)\n' \
'(assert (and x y z))'
assert smtlib_code((x & ~y) | (z > 3)) == '(declare-const x Bool)\n' \
'(declare-const y Bool)\n' \
'(declare-const z Real)\n' \
'(assert (or (> z 3) (and x (not y))))'
f = Function('f')
g = Function('g')
h = Function('h')
assert smtlib_code([
Gt(f(x), y),
Lt(y, g(z))
], symbol_table={
f: Callable[[bool], int], g: Callable[[bool], int],
}) == '(declare-const x Bool)\n' \
'(declare-const y Real)\n' \
'(declare-const z Bool)\n' \
'(declare-fun f (Bool) Int)\n' \
'(declare-fun g (Bool) Int)\n' \
'(assert (> (f x) y))\n' \
'(assert (< y (g z)))'
assert smtlib_code([
Eq(f(x), y),
Lt(y, g(z))
], symbol_table={
f: Callable[[bool], int], g: Callable[[bool], int],
}) == '(declare-const x Bool)\n' \
'(declare-const y Int)\n' \
'(declare-const z Bool)\n' \
'(declare-fun f (Bool) Int)\n' \
'(declare-fun g (Bool) Int)\n' \
'(assert (= (f x) y))\n' \
'(assert (< y (g z)))'
assert smtlib_code(
[Eq(f(x), y),
Eq(g(f(x)), z),
Eq(h(g(f(x))), x)],
symbol_table={
f: Callable[[float], int],
g: Callable[[int], bool],
h: Callable[[bool], float]
}
) == '(declare-const x Real)\n' \
'(declare-const y Int)\n' \
'(declare-const z Bool)\n' \
'(declare-fun f (Real) Int)\n' \
'(declare-fun g (Int) Bool)\n' \
'(declare-fun h (Bool) Real)\n' \
'(assert (= (f x) y))\n' \
'(assert (= (g (f x)) z))\n' \
'(assert (= (h (g (f x))) x))'
# todo: make smtlib_code support arrays
# def test_containers():
# assert julia_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
# "Any[1, 2, 3, Any[4, 5, Any[6, 7]], 8, Any[9, 10], 11]"
# assert julia_code((1, 2, (3, 4))) == "(1, 2, (3, 4))"
# assert julia_code([1]) == "Any[1]"
# assert julia_code((1,)) == "(1,)"
# assert julia_code(Tuple(*[1, 2, 3])) == "(1, 2, 3)"
# assert julia_code((1, x * y, (3, x ** 2))) == "(1, x .* y, (3, x .^ 2))"
# # scalar, matrix, empty matrix and empty list
# assert julia_code((1, eye(3), Matrix(0, 0, []), [])) == "(1, [1 0 0;\n0 1 0;\n0 0 1], zeros(0, 0), Any[])"
def test_smtlib_piecewise():
assert smtlib_code(
Piecewise((x, x < 1),
(x ** 2, True)),
auto_declare=False
) == '(ite (< x 1) x (pow x 2))'
assert smtlib_code(
Piecewise((x ** 2, x < 1),
(x ** 3, x < 2),
(x ** 4, x < 3),
(x ** 5, True)),
auto_declare=False
) == '(ite (< x 1) (pow x 2) ' \
'(ite (< x 2) (pow x 3) ' \
'(ite (< x 3) (pow x 4) ' \
'(pow x 5))))'
# Check that Piecewise without a True (default) condition error
expr = Piecewise((x, x < 1), (x ** 2, x > 1), (sin(x), x > 0))
raises(AssertionError, lambda: smtlib_code(expr))
def test_smtlib_piecewise_times_const():
pw = Piecewise((x, x < 1), (x ** 2, True))
assert smtlib_code(2 * pw) == '(declare-const x Real)\n(* 2 (ite (< x 1) x (pow x 2)))'
assert smtlib_code(pw / x) == '(declare-const x Real)\n(* (pow x -1) (ite (< x 1) x (pow x 2)))'
assert smtlib_code(pw / (x * y)) == '(declare-const x Real)\n(declare-const y Real)\n(* (pow x -1) (pow y -1) (ite (< x 1) x (pow x 2)))'
assert smtlib_code(pw / 3) == '(declare-const x Real)\n(* (/ 1 3) (ite (< x 1) x (pow x 2)))'
# todo: make smtlib_code support arrays / matrices ?
# def test_smtlib_matrix_assign_to():
# A = Matrix([[1, 2, 3]])
# assert smtlib_code(A, assign_to='a') == "a = [1 2 3]"
# A = Matrix([[1, 2], [3, 4]])
# assert smtlib_code(A, assign_to='A') == "A = [1 2;\n3 4]"
# def test_julia_matrix_1x1():
# A = Matrix([[3]])
# B = MatrixSymbol('B', 1, 1)
# C = MatrixSymbol('C', 1, 2)
# assert julia_code(A, assign_to=B) == "B = [3]"
# raises(ValueError, lambda: julia_code(A, assign_to=C))
# def test_julia_matrix_elements():
# A = Matrix([[x, 2, x * y]])
# assert julia_code(A[0, 0] ** 2 + A[0, 1] + A[0, 2]) == "x .^ 2 + x .* y + 2"
# A = MatrixSymbol('AA', 1, 3)
# assert julia_code(A) == "AA"
# assert julia_code(A[0, 0] ** 2 + sin(A[0, 1]) + A[0, 2]) == \
# "sin(AA[1,2]) + AA[1,1] .^ 2 + AA[1,3]"
# assert julia_code(sum(A)) == "AA[1,1] + AA[1,2] + AA[1,3]"
def test_smtlib_boolean():
assert smtlib_code(True, auto_assert=False) == 'true'
assert smtlib_code(True) == '(assert true)'
assert smtlib_code(S.true) == '(assert true)'
assert smtlib_code(S.false) == '(assert false)'
assert smtlib_code(False) == '(assert false)'
assert smtlib_code(False, auto_assert=False) == 'false'
def test_not_supported():
f = Function('f')
raises(KeyError, lambda: smtlib_code(f(x).diff(x), symbol_table={f: Callable[[float], float]}))
raises(KeyError, lambda: smtlib_code(S.ComplexInfinity))
|
c48151217b531dcb94e998415bc1edfca8d43dec09a02110d1be465554723fb8 | from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer,
Tuple, Symbol, EulerGamma, GoldenRatio, Catalan,
Lambda, Mul, Pow, Mod, Eq, Ne, Le, Lt, Gt, Ge)
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.functions import (arg, atan2, bernoulli, beta, ceiling, chebyshevu,
chebyshevt, conjugate, DiracDelta, exp, expint,
factorial, floor, harmonic, Heaviside, im,
laguerre, LambertW, log, Max, Min, Piecewise,
polylog, re, RisingFactorial, sign, sinc, sqrt,
zeta, binomial, legendre, dirichlet_eta,
riemann_xi)
from sympy.functions import (sin, cos, tan, cot, sec, csc, asin, acos, acot,
atan, asec, acsc, sinh, cosh, tanh, coth, csch,
sech, asinh, acosh, atanh, acoth, asech, acsch)
from sympy.testing.pytest import raises, XFAIL
from sympy.utilities.lambdify import implemented_function
from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity,
HadamardProduct, SparseMatrix, HadamardPower)
from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli,
besselk, hankel1, hankel2, airyai,
airybi, airyaiprime, airybiprime)
from sympy.functions.special.gamma_functions import (gamma, lowergamma,
uppergamma, loggamma,
polygamma)
from sympy.functions.special.error_functions import (Chi, Ci, erf, erfc, erfi,
erfcinv, erfinv, fresnelc,
fresnels, li, Shi, Si, Li,
erf2, Ei)
from sympy.printing.octave import octave_code, octave_code as mcode
x, y, z = symbols('x,y,z')
def test_Integer():
assert mcode(Integer(67)) == "67"
assert mcode(Integer(-1)) == "-1"
def test_Rational():
assert mcode(Rational(3, 7)) == "3/7"
assert mcode(Rational(18, 9)) == "2"
assert mcode(Rational(3, -7)) == "-3/7"
assert mcode(Rational(-3, -7)) == "3/7"
assert mcode(x + Rational(3, 7)) == "x + 3/7"
assert mcode(Rational(3, 7)*x) == "3*x/7"
def test_Relational():
assert mcode(Eq(x, y)) == "x == y"
assert mcode(Ne(x, y)) == "x != y"
assert mcode(Le(x, y)) == "x <= y"
assert mcode(Lt(x, y)) == "x < y"
assert mcode(Gt(x, y)) == "x > y"
assert mcode(Ge(x, y)) == "x >= y"
def test_Function():
assert mcode(sin(x) ** cos(x)) == "sin(x).^cos(x)"
assert mcode(sign(x)) == "sign(x)"
assert mcode(exp(x)) == "exp(x)"
assert mcode(log(x)) == "log(x)"
assert mcode(factorial(x)) == "factorial(x)"
assert mcode(floor(x)) == "floor(x)"
assert mcode(atan2(y, x)) == "atan2(y, x)"
assert mcode(beta(x, y)) == 'beta(x, y)'
assert mcode(polylog(x, y)) == 'polylog(x, y)'
assert mcode(harmonic(x)) == 'harmonic(x)'
assert mcode(bernoulli(x)) == "bernoulli(x)"
assert mcode(bernoulli(x, y)) == "bernoulli(x, y)"
assert mcode(legendre(x, y)) == "legendre(x, y)"
def test_Function_change_name():
assert mcode(abs(x)) == "abs(x)"
assert mcode(ceiling(x)) == "ceil(x)"
assert mcode(arg(x)) == "angle(x)"
assert mcode(im(x)) == "imag(x)"
assert mcode(re(x)) == "real(x)"
assert mcode(conjugate(x)) == "conj(x)"
assert mcode(chebyshevt(y, x)) == "chebyshevT(y, x)"
assert mcode(chebyshevu(y, x)) == "chebyshevU(y, x)"
assert mcode(laguerre(x, y)) == "laguerreL(x, y)"
assert mcode(Chi(x)) == "coshint(x)"
assert mcode(Shi(x)) == "sinhint(x)"
assert mcode(Ci(x)) == "cosint(x)"
assert mcode(Si(x)) == "sinint(x)"
assert mcode(li(x)) == "logint(x)"
assert mcode(loggamma(x)) == "gammaln(x)"
assert mcode(polygamma(x, y)) == "psi(x, y)"
assert mcode(RisingFactorial(x, y)) == "pochhammer(x, y)"
assert mcode(DiracDelta(x)) == "dirac(x)"
assert mcode(DiracDelta(x, 3)) == "dirac(3, x)"
assert mcode(Heaviside(x)) == "heaviside(x, 1/2)"
assert mcode(Heaviside(x, y)) == "heaviside(x, y)"
assert mcode(binomial(x, y)) == "bincoeff(x, y)"
assert mcode(Mod(x, y)) == "mod(x, y)"
def test_minmax():
assert mcode(Max(x, y) + Min(x, y)) == "max(x, y) + min(x, y)"
assert mcode(Max(x, y, z)) == "max(x, max(y, z))"
assert mcode(Min(x, y, z)) == "min(x, min(y, z))"
def test_Pow():
assert mcode(x**3) == "x.^3"
assert mcode(x**(y**3)) == "x.^(y.^3)"
assert mcode(x**Rational(2, 3)) == 'x.^(2/3)'
g = implemented_function('g', Lambda(x, 2*x))
assert mcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
"(3.5*2*x).^(-x + y.^x)./(x.^2 + y)"
# For issue 14160
assert mcode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
evaluate=False)) == '-2*x./(y.*y)'
def test_basic_ops():
assert mcode(x*y) == "x.*y"
assert mcode(x + y) == "x + y"
assert mcode(x - y) == "x - y"
assert mcode(-x) == "-x"
def test_1_over_x_and_sqrt():
# 1.0 and 0.5 would do something different in regular StrPrinter,
# but these are exact in IEEE floating point so no different here.
assert mcode(1/x) == '1./x'
assert mcode(x**-1) == mcode(x**-1.0) == '1./x'
assert mcode(1/sqrt(x)) == '1./sqrt(x)'
assert mcode(x**-S.Half) == mcode(x**-0.5) == '1./sqrt(x)'
assert mcode(sqrt(x)) == 'sqrt(x)'
assert mcode(x**S.Half) == mcode(x**0.5) == 'sqrt(x)'
assert mcode(1/pi) == '1/pi'
assert mcode(pi**-1) == mcode(pi**-1.0) == '1/pi'
assert mcode(pi**-0.5) == '1/sqrt(pi)'
def test_mix_number_mult_symbols():
assert mcode(3*x) == "3*x"
assert mcode(pi*x) == "pi*x"
assert mcode(3/x) == "3./x"
assert mcode(pi/x) == "pi./x"
assert mcode(x/3) == "x/3"
assert mcode(x/pi) == "x/pi"
assert mcode(x*y) == "x.*y"
assert mcode(3*x*y) == "3*x.*y"
assert mcode(3*pi*x*y) == "3*pi*x.*y"
assert mcode(x/y) == "x./y"
assert mcode(3*x/y) == "3*x./y"
assert mcode(x*y/z) == "x.*y./z"
assert mcode(x/y*z) == "x.*z./y"
assert mcode(1/x/y) == "1./(x.*y)"
assert mcode(2*pi*x/y/z) == "2*pi*x./(y.*z)"
assert mcode(3*pi/x) == "3*pi./x"
assert mcode(S(3)/5) == "3/5"
assert mcode(S(3)/5*x) == "3*x/5"
assert mcode(x/y/z) == "x./(y.*z)"
assert mcode((x+y)/z) == "(x + y)./z"
assert mcode((x+y)/(z+x)) == "(x + y)./(x + z)"
assert mcode((x+y)/EulerGamma) == "(x + y)/%s" % EulerGamma.evalf(17)
assert mcode(x/3/pi) == "x/(3*pi)"
assert mcode(S(3)/5*x*y/pi) == "3*x.*y/(5*pi)"
def test_mix_number_pow_symbols():
assert mcode(pi**3) == 'pi^3'
assert mcode(x**2) == 'x.^2'
assert mcode(x**(pi**3)) == 'x.^(pi^3)'
assert mcode(x**y) == 'x.^y'
assert mcode(x**(y**z)) == 'x.^(y.^z)'
assert mcode((x**y)**z) == '(x.^y).^z'
def test_imag():
I = S('I')
assert mcode(I) == "1i"
assert mcode(5*I) == "5i"
assert mcode((S(3)/2)*I) == "3*1i/2"
assert mcode(3+4*I) == "3 + 4i"
assert mcode(sqrt(3)*I) == "sqrt(3)*1i"
def test_constants():
assert mcode(pi) == "pi"
assert mcode(oo) == "inf"
assert mcode(-oo) == "-inf"
assert mcode(S.NegativeInfinity) == "-inf"
assert mcode(S.NaN) == "NaN"
assert mcode(S.Exp1) == "exp(1)"
assert mcode(exp(1)) == "exp(1)"
def test_constants_other():
assert mcode(2*GoldenRatio) == "2*(1+sqrt(5))/2"
assert mcode(2*Catalan) == "2*%s" % Catalan.evalf(17)
assert mcode(2*EulerGamma) == "2*%s" % EulerGamma.evalf(17)
def test_boolean():
assert mcode(x & y) == "x & y"
assert mcode(x | y) == "x | y"
assert mcode(~x) == "~x"
assert mcode(x & y & z) == "x & y & z"
assert mcode(x | y | z) == "x | y | z"
assert mcode((x & y) | z) == "z | x & y"
assert mcode((x | y) & z) == "z & (x | y)"
def test_KroneckerDelta():
from sympy.functions import KroneckerDelta
assert mcode(KroneckerDelta(x, y)) == "double(x == y)"
assert mcode(KroneckerDelta(x, y + 1)) == "double(x == (y + 1))"
assert mcode(KroneckerDelta(2**x, y)) == "double((2.^x) == y)"
def test_Matrices():
assert mcode(Matrix(1, 1, [10])) == "10"
A = Matrix([[1, sin(x/2), abs(x)],
[0, 1, pi],
[0, exp(1), ceiling(x)]]);
expected = "[1 sin(x/2) abs(x); 0 1 pi; 0 exp(1) ceil(x)]"
assert mcode(A) == expected
# row and columns
assert mcode(A[:,0]) == "[1; 0; 0]"
assert mcode(A[0,:]) == "[1 sin(x/2) abs(x)]"
# empty matrices
assert mcode(Matrix(0, 0, [])) == '[]'
assert mcode(Matrix(0, 3, [])) == 'zeros(0, 3)'
# annoying to read but correct
assert mcode(Matrix([[x, x - y, -y]])) == "[x x - y -y]"
def test_vector_entries_hadamard():
# For a row or column, user might to use the other dimension
A = Matrix([[1, sin(2/x), 3*pi/x/5]])
assert mcode(A) == "[1 sin(2./x) 3*pi./(5*x)]"
assert mcode(A.T) == "[1; sin(2./x); 3*pi./(5*x)]"
@XFAIL
def test_Matrices_entries_not_hadamard():
# For Matrix with col >= 2, row >= 2, they need to be scalars
# FIXME: is it worth worrying about this? Its not wrong, just
# leave it user's responsibility to put scalar data for x.
A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]])
expected = ("[1 sin(2/x) 3*pi/(5*x);\n"
"1 2 x*y]") # <- we give x.*y
assert mcode(A) == expected
def test_MatrixSymbol():
n = Symbol('n', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
assert mcode(A*B) == "A*B"
assert mcode(B*A) == "B*A"
assert mcode(2*A*B) == "2*A*B"
assert mcode(B*2*A) == "2*B*A"
assert mcode(A*(B + 3*Identity(n))) == "A*(3*eye(n) + B)"
assert mcode(A**(x**2)) == "A^(x.^2)"
assert mcode(A**3) == "A^3"
assert mcode(A**S.Half) == "A^(1/2)"
def test_MatrixSolve():
n = Symbol('n', integer=True)
A = MatrixSymbol('A', n, n)
x = MatrixSymbol('x', n, 1)
assert mcode(MatrixSolve(A, x)) == "A \\ x"
def test_special_matrices():
assert mcode(6*Identity(3)) == "6*eye(3)"
def test_containers():
assert mcode([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
"{1, 2, 3, {4, 5, {6, 7}}, 8, {9, 10}, 11}"
assert mcode((1, 2, (3, 4))) == "{1, 2, {3, 4}}"
assert mcode([1]) == "{1}"
assert mcode((1,)) == "{1}"
assert mcode(Tuple(*[1, 2, 3])) == "{1, 2, 3}"
assert mcode((1, x*y, (3, x**2))) == "{1, x.*y, {3, x.^2}}"
# scalar, matrix, empty matrix and empty list
assert mcode((1, eye(3), Matrix(0, 0, []), [])) == "{1, [1 0 0; 0 1 0; 0 0 1], [], {}}"
def test_octave_noninline():
source = mcode((x+y)/Catalan, assign_to='me', inline=False)
expected = (
"Catalan = %s;\n"
"me = (x + y)/Catalan;"
) % Catalan.evalf(17)
assert source == expected
def test_octave_piecewise():
expr = Piecewise((x, x < 1), (x**2, True))
assert mcode(expr) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))"
assert mcode(expr, assign_to="r") == (
"r = ((x < 1).*(x) + (~(x < 1)).*(x.^2));")
assert mcode(expr, assign_to="r", inline=False) == (
"if (x < 1)\n"
" r = x;\n"
"else\n"
" r = x.^2;\n"
"end")
expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True))
expected = ("((x < 1).*(x.^2) + (~(x < 1)).*( ...\n"
"(x < 2).*(x.^3) + (~(x < 2)).*( ...\n"
"(x < 3).*(x.^4) + (~(x < 3)).*(x.^5))))")
assert mcode(expr) == expected
assert mcode(expr, assign_to="r") == "r = " + expected + ";"
assert mcode(expr, assign_to="r", inline=False) == (
"if (x < 1)\n"
" r = x.^2;\n"
"elseif (x < 2)\n"
" r = x.^3;\n"
"elseif (x < 3)\n"
" r = x.^4;\n"
"else\n"
" r = x.^5;\n"
"end")
# Check that Piecewise without a True (default) condition error
expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
raises(ValueError, lambda: mcode(expr))
def test_octave_piecewise_times_const():
pw = Piecewise((x, x < 1), (x**2, True))
assert mcode(2*pw) == "2*((x < 1).*(x) + (~(x < 1)).*(x.^2))"
assert mcode(pw/x) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./x"
assert mcode(pw/(x*y)) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./(x.*y)"
assert mcode(pw/3) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))/3"
def test_octave_matrix_assign_to():
A = Matrix([[1, 2, 3]])
assert mcode(A, assign_to='a') == "a = [1 2 3];"
A = Matrix([[1, 2], [3, 4]])
assert mcode(A, assign_to='A') == "A = [1 2; 3 4];"
def test_octave_matrix_assign_to_more():
# assigning to Symbol or MatrixSymbol requires lhs/rhs match
A = Matrix([[1, 2, 3]])
B = MatrixSymbol('B', 1, 3)
C = MatrixSymbol('C', 2, 3)
assert mcode(A, assign_to=B) == "B = [1 2 3];"
raises(ValueError, lambda: mcode(A, assign_to=x))
raises(ValueError, lambda: mcode(A, assign_to=C))
def test_octave_matrix_1x1():
A = Matrix([[3]])
B = MatrixSymbol('B', 1, 1)
C = MatrixSymbol('C', 1, 2)
assert mcode(A, assign_to=B) == "B = 3;"
# FIXME?
#assert mcode(A, assign_to=x) == "x = 3;"
raises(ValueError, lambda: mcode(A, assign_to=C))
def test_octave_matrix_elements():
A = Matrix([[x, 2, x*y]])
assert mcode(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x.^2 + x.*y + 2"
A = MatrixSymbol('AA', 1, 3)
assert mcode(A) == "AA"
assert mcode(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \
"sin(AA(1, 2)) + AA(1, 1).^2 + AA(1, 3)"
assert mcode(sum(A)) == "AA(1, 1) + AA(1, 2) + AA(1, 3)"
def test_octave_boolean():
assert mcode(True) == "true"
assert mcode(S.true) == "true"
assert mcode(False) == "false"
assert mcode(S.false) == "false"
def test_octave_not_supported():
assert mcode(S.ComplexInfinity) == (
"% Not supported in Octave:\n"
"% ComplexInfinity\n"
"zoo"
)
f = Function('f')
assert mcode(f(x).diff(x)) == (
"% Not supported in Octave:\n"
"% Derivative\n"
"Derivative(f(x), x)"
)
def test_octave_not_supported_not_on_whitelist():
from sympy.functions.special.polynomials import assoc_laguerre
assert mcode(assoc_laguerre(x, y, z)) == (
"% Not supported in Octave:\n"
"% assoc_laguerre\n"
"assoc_laguerre(x, y, z)"
)
def test_octave_expint():
assert mcode(expint(1, x)) == "expint(x)"
assert mcode(expint(2, x)) == (
"% Not supported in Octave:\n"
"% expint\n"
"expint(2, x)"
)
assert mcode(expint(y, x)) == (
"% Not supported in Octave:\n"
"% expint\n"
"expint(y, x)"
)
def test_trick_indent_with_end_else_words():
# words starting with "end" or "else" do not confuse the indenter
t1 = S('endless');
t2 = S('elsewhere');
pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True))
assert mcode(pw, inline=False) == (
"if (x < 0)\n"
" endless\n"
"elseif (x <= 1)\n"
" elsewhere\n"
"else\n"
" 1\n"
"end")
def test_hadamard():
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 3, 3)
v = MatrixSymbol('v', 3, 1)
h = MatrixSymbol('h', 1, 3)
C = HadamardProduct(A, B)
n = Symbol('n')
assert mcode(C) == "A.*B"
assert mcode(C*v) == "(A.*B)*v"
assert mcode(h*C*v) == "h*(A.*B)*v"
assert mcode(C*A) == "(A.*B)*A"
# mixing Hadamard and scalar strange b/c we vectorize scalars
assert mcode(C*x*y) == "(x.*y)*(A.*B)"
# Testing HadamardPower:
assert mcode(HadamardPower(A, n)) == "A.**n"
assert mcode(HadamardPower(A, 1+n)) == "A.**(n + 1)"
assert mcode(HadamardPower(A*B.T, 1+n)) == "(A*B.T).**(n + 1)"
def test_sparse():
M = SparseMatrix(5, 6, {})
M[2, 2] = 10;
M[1, 2] = 20;
M[1, 3] = 22;
M[0, 3] = 30;
M[3, 0] = x*y;
assert mcode(M) == (
"sparse([4 2 3 1 2], [1 3 3 4 4], [x.*y 20 10 30 22], 5, 6)"
)
def test_sinc():
assert mcode(sinc(x)) == 'sinc(x/pi)'
assert mcode(sinc(x + 3)) == 'sinc((x + 3)/pi)'
assert mcode(sinc(pi*(x + 3))) == 'sinc(x + 3)'
def test_trigfun():
for f in (sin, cos, tan, cot, sec, csc, asin, acos, acot, atan, asec, acsc,
sinh, cosh, tanh, coth, csch, sech, asinh, acosh, atanh, acoth,
asech, acsch):
assert octave_code(f(x) == f.__name__ + '(x)')
def test_specfun():
n = Symbol('n')
for f in [besselj, bessely, besseli, besselk]:
assert octave_code(f(n, x)) == f.__name__ + '(n, x)'
for f in (erfc, erfi, erf, erfinv, erfcinv, fresnelc, fresnels, gamma):
assert octave_code(f(x)) == f.__name__ + '(x)'
assert octave_code(hankel1(n, x)) == 'besselh(n, 1, x)'
assert octave_code(hankel2(n, x)) == 'besselh(n, 2, x)'
assert octave_code(airyai(x)) == 'airy(0, x)'
assert octave_code(airyaiprime(x)) == 'airy(1, x)'
assert octave_code(airybi(x)) == 'airy(2, x)'
assert octave_code(airybiprime(x)) == 'airy(3, x)'
assert octave_code(uppergamma(n, x)) == '(gammainc(x, n, \'upper\').*gamma(n))'
assert octave_code(lowergamma(n, x)) == '(gammainc(x, n).*gamma(n))'
assert octave_code(z**lowergamma(n, x)) == 'z.^(gammainc(x, n).*gamma(n))'
assert octave_code(jn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*besselj(n + 1/2, x)/2'
assert octave_code(yn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*bessely(n + 1/2, x)/2'
assert octave_code(LambertW(x)) == 'lambertw(x)'
assert octave_code(LambertW(x, n)) == 'lambertw(n, x)'
# Automatic rewrite
assert octave_code(Ei(x)) == 'logint(exp(x))'
assert octave_code(dirichlet_eta(x)) == '((x == 1).*(log(2)) + (~(x == 1)).*((1 - 2.^(1 - x)).*zeta(x)))'
assert octave_code(riemann_xi(x)) == 'pi.^(-x/2).*x.*(x - 1).*gamma(x/2).*zeta(x)/2'
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
assert mcode(A[0, 0]) == "A(1, 1)"
assert mcode(3 * A[0, 0]) == "3*A(1, 1)"
F = C[0, 0].subs(C, A - B)
assert mcode(F) == "(A - B)(1, 1)"
def test_zeta_printing_issue_14820():
assert octave_code(zeta(x)) == 'zeta(x)'
assert octave_code(zeta(x, y)) == '% Not supported in Octave:\n% zeta\nzeta(x, y)'
def test_automatic_rewrite():
assert octave_code(Li(x)) == 'logint(x) - logint(2)'
assert octave_code(erf2(x, y)) == '-erf(x) + erf(y)'
|
6fe18597f820929c88cb362e4eca711fb9e1bd059efd13296fb939b9e2326769 | import random
from sympy.core.function import Derivative
from sympy.core.symbol import symbols
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
PermuteDims, ArrayDiagonal
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
from sympy.external import import_module
from sympy.functions import \
Abs, ceiling, exp, floor, sign, sin, asin, sqrt, cos, \
acos, tan, atan, atan2, cosh, acosh, sinh, asinh, tanh, atanh, \
re, im, arg, erf, loggamma, log
from sympy.matrices import Matrix, MatrixBase, eye, randMatrix
from sympy.matrices.expressions import \
Determinant, HadamardProduct, Inverse, MatrixSymbol, Trace
from sympy.printing.tensorflow import tensorflow_code
from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
from sympy.utilities.lambdify import lambdify
from sympy.testing.pytest import skip
from sympy.testing.pytest import XFAIL
tf = tensorflow = import_module("tensorflow")
if tensorflow:
# Hide Tensorflow warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
M = MatrixSymbol("M", 3, 3)
N = MatrixSymbol("N", 3, 3)
P = MatrixSymbol("P", 3, 3)
Q = MatrixSymbol("Q", 3, 3)
x, y, z, t = symbols("x y z t")
if tf is not None:
llo = [[j for j in range(i, i+3)] for i in range(0, 9, 3)]
m3x3 = tf.constant(llo)
m3x3sympy = Matrix(llo)
def _compare_tensorflow_matrix(variables, expr, use_float=False):
f = lambdify(variables, expr, 'tensorflow')
if not use_float:
random_matrices = [randMatrix(v.rows, v.cols) for v in variables]
else:
random_matrices = [randMatrix(v.rows, v.cols)/100. for v in variables]
graph = tf.Graph()
r = None
with graph.as_default():
random_variables = [eval(tensorflow_code(i)) for i in random_matrices]
session = tf.compat.v1.Session(graph=graph)
r = session.run(f(*random_variables))
e = expr.subs({k: v for k, v in zip(variables, random_matrices)})
e = e.doit()
if e.is_Matrix:
if not isinstance(e, MatrixBase):
e = e.as_explicit()
e = e.tolist()
if not use_float:
assert (r == e).all()
else:
r = [i for row in r for i in row]
e = [i for row in e for i in row]
assert all(
abs(a-b) < 10**-(4-int(log(abs(a), 10))) for a, b in zip(r, e))
# Creating a custom inverse test.
# See https://github.com/sympy/sympy/issues/18469
def _compare_tensorflow_matrix_inverse(variables, expr, use_float=False):
f = lambdify(variables, expr, 'tensorflow')
if not use_float:
random_matrices = [eye(v.rows, v.cols)*4 for v in variables]
else:
random_matrices = [eye(v.rows, v.cols)*3.14 for v in variables]
graph = tf.Graph()
r = None
with graph.as_default():
random_variables = [eval(tensorflow_code(i)) for i in random_matrices]
session = tf.compat.v1.Session(graph=graph)
r = session.run(f(*random_variables))
e = expr.subs({k: v for k, v in zip(variables, random_matrices)})
e = e.doit()
if e.is_Matrix:
if not isinstance(e, MatrixBase):
e = e.as_explicit()
e = e.tolist()
if not use_float:
assert (r == e).all()
else:
r = [i for row in r for i in row]
e = [i for row in e for i in row]
assert all(
abs(a-b) < 10**-(4-int(log(abs(a), 10))) for a, b in zip(r, e))
def _compare_tensorflow_matrix_scalar(variables, expr):
f = lambdify(variables, expr, 'tensorflow')
random_matrices = [
randMatrix(v.rows, v.cols).evalf() / 100 for v in variables]
graph = tf.Graph()
r = None
with graph.as_default():
random_variables = [eval(tensorflow_code(i)) for i in random_matrices]
session = tf.compat.v1.Session(graph=graph)
r = session.run(f(*random_variables))
e = expr.subs({k: v for k, v in zip(variables, random_matrices)})
e = e.doit()
assert abs(r-e) < 10**-6
def _compare_tensorflow_scalar(
variables, expr, rng=lambda: random.randint(0, 10)):
f = lambdify(variables, expr, 'tensorflow')
rvs = [rng() for v in variables]
graph = tf.Graph()
r = None
with graph.as_default():
tf_rvs = [eval(tensorflow_code(i)) for i in rvs]
session = tf.compat.v1.Session(graph=graph)
r = session.run(f(*tf_rvs))
e = expr.subs({k: v for k, v in zip(variables, rvs)}).evalf().doit()
assert abs(r-e) < 10**-6
def _compare_tensorflow_relational(
variables, expr, rng=lambda: random.randint(0, 10)):
f = lambdify(variables, expr, 'tensorflow')
rvs = [rng() for v in variables]
graph = tf.Graph()
r = None
with graph.as_default():
tf_rvs = [eval(tensorflow_code(i)) for i in rvs]
session = tf.compat.v1.Session(graph=graph)
r = session.run(f(*tf_rvs))
e = expr.subs({k: v for k, v in zip(variables, rvs)}).doit()
assert r == e
def test_tensorflow_printing():
assert tensorflow_code(eye(3)) == \
"tensorflow.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])"
expr = Matrix([[x, sin(y)], [exp(z), -t]])
assert tensorflow_code(expr) == \
"tensorflow.Variable(" \
"[[x, tensorflow.math.sin(y)]," \
" [tensorflow.math.exp(z), -t]])"
# This (random) test is XFAIL because it fails occasionally
# See https://github.com/sympy/sympy/issues/18469
@XFAIL
def test_tensorflow_math():
if not tf:
skip("TensorFlow not installed")
expr = Abs(x)
assert tensorflow_code(expr) == "tensorflow.math.abs(x)"
_compare_tensorflow_scalar((x,), expr)
expr = sign(x)
assert tensorflow_code(expr) == "tensorflow.math.sign(x)"
_compare_tensorflow_scalar((x,), expr)
expr = ceiling(x)
assert tensorflow_code(expr) == "tensorflow.math.ceil(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = floor(x)
assert tensorflow_code(expr) == "tensorflow.math.floor(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = exp(x)
assert tensorflow_code(expr) == "tensorflow.math.exp(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = sqrt(x)
assert tensorflow_code(expr) == "tensorflow.math.sqrt(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = x ** 4
assert tensorflow_code(expr) == "tensorflow.math.pow(x, 4)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = cos(x)
assert tensorflow_code(expr) == "tensorflow.math.cos(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = acos(x)
assert tensorflow_code(expr) == "tensorflow.math.acos(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(0, 0.95))
expr = sin(x)
assert tensorflow_code(expr) == "tensorflow.math.sin(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = asin(x)
assert tensorflow_code(expr) == "tensorflow.math.asin(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = tan(x)
assert tensorflow_code(expr) == "tensorflow.math.tan(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = atan(x)
assert tensorflow_code(expr) == "tensorflow.math.atan(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = atan2(y, x)
assert tensorflow_code(expr) == "tensorflow.math.atan2(y, x)"
_compare_tensorflow_scalar((y, x), expr, rng=lambda: random.random())
expr = cosh(x)
assert tensorflow_code(expr) == "tensorflow.math.cosh(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
expr = acosh(x)
assert tensorflow_code(expr) == "tensorflow.math.acosh(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
expr = sinh(x)
assert tensorflow_code(expr) == "tensorflow.math.sinh(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
expr = asinh(x)
assert tensorflow_code(expr) == "tensorflow.math.asinh(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
expr = tanh(x)
assert tensorflow_code(expr) == "tensorflow.math.tanh(x)"
_compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
expr = atanh(x)
assert tensorflow_code(expr) == "tensorflow.math.atanh(x)"
_compare_tensorflow_scalar(
(x,), expr, rng=lambda: random.uniform(-.5, .5))
expr = erf(x)
assert tensorflow_code(expr) == "tensorflow.math.erf(x)"
_compare_tensorflow_scalar(
(x,), expr, rng=lambda: random.random())
expr = loggamma(x)
assert tensorflow_code(expr) == "tensorflow.math.lgamma(x)"
_compare_tensorflow_scalar(
(x,), expr, rng=lambda: random.random())
def test_tensorflow_complexes():
assert tensorflow_code(re(x)) == "tensorflow.math.real(x)"
assert tensorflow_code(im(x)) == "tensorflow.math.imag(x)"
assert tensorflow_code(arg(x)) == "tensorflow.math.angle(x)"
def test_tensorflow_relational():
if not tf:
skip("TensorFlow not installed")
expr = Eq(x, y)
assert tensorflow_code(expr) == "tensorflow.math.equal(x, y)"
_compare_tensorflow_relational((x, y), expr)
expr = Ne(x, y)
assert tensorflow_code(expr) == "tensorflow.math.not_equal(x, y)"
_compare_tensorflow_relational((x, y), expr)
expr = Ge(x, y)
assert tensorflow_code(expr) == "tensorflow.math.greater_equal(x, y)"
_compare_tensorflow_relational((x, y), expr)
expr = Gt(x, y)
assert tensorflow_code(expr) == "tensorflow.math.greater(x, y)"
_compare_tensorflow_relational((x, y), expr)
expr = Le(x, y)
assert tensorflow_code(expr) == "tensorflow.math.less_equal(x, y)"
_compare_tensorflow_relational((x, y), expr)
expr = Lt(x, y)
assert tensorflow_code(expr) == "tensorflow.math.less(x, y)"
_compare_tensorflow_relational((x, y), expr)
# This (random) test is XFAIL because it fails occasionally
# See https://github.com/sympy/sympy/issues/18469
@XFAIL
def test_tensorflow_matrices():
if not tf:
skip("TensorFlow not installed")
expr = M
assert tensorflow_code(expr) == "M"
_compare_tensorflow_matrix((M,), expr)
expr = M + N
assert tensorflow_code(expr) == "tensorflow.math.add(M, N)"
_compare_tensorflow_matrix((M, N), expr)
expr = M * N
assert tensorflow_code(expr) == "tensorflow.linalg.matmul(M, N)"
_compare_tensorflow_matrix((M, N), expr)
expr = HadamardProduct(M, N)
assert tensorflow_code(expr) == "tensorflow.math.multiply(M, N)"
_compare_tensorflow_matrix((M, N), expr)
expr = M*N*P*Q
assert tensorflow_code(expr) == \
"tensorflow.linalg.matmul(" \
"tensorflow.linalg.matmul(" \
"tensorflow.linalg.matmul(M, N), P), Q)"
_compare_tensorflow_matrix((M, N, P, Q), expr)
expr = M**3
assert tensorflow_code(expr) == \
"tensorflow.linalg.matmul(tensorflow.linalg.matmul(M, M), M)"
_compare_tensorflow_matrix((M,), expr)
expr = Trace(M)
assert tensorflow_code(expr) == "tensorflow.linalg.trace(M)"
_compare_tensorflow_matrix((M,), expr)
expr = Determinant(M)
assert tensorflow_code(expr) == "tensorflow.linalg.det(M)"
_compare_tensorflow_matrix_scalar((M,), expr)
expr = Inverse(M)
assert tensorflow_code(expr) == "tensorflow.linalg.inv(M)"
_compare_tensorflow_matrix_inverse((M,), expr, use_float=True)
expr = M.T
assert tensorflow_code(expr, tensorflow_version='1.14') == \
"tensorflow.linalg.matrix_transpose(M)"
assert tensorflow_code(expr, tensorflow_version='1.13') == \
"tensorflow.matrix_transpose(M)"
_compare_tensorflow_matrix((M,), expr)
def test_codegen_einsum():
if not tf:
skip("TensorFlow not installed")
graph = tf.Graph()
with graph.as_default():
session = tf.compat.v1.Session(graph=graph)
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
cg = convert_matrix_to_array(M * N)
f = lambdify((M, N), cg, 'tensorflow')
ma = tf.constant([[1, 2], [3, 4]])
mb = tf.constant([[1,-2], [-1, 3]])
y = session.run(f(ma, mb))
c = session.run(tf.matmul(ma, mb))
assert (y == c).all()
def test_codegen_extra():
if not tf:
skip("TensorFlow not installed")
graph = tf.Graph()
with graph.as_default():
session = tf.compat.v1.Session()
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
P = MatrixSymbol("P", 2, 2)
Q = MatrixSymbol("Q", 2, 2)
ma = tf.constant([[1, 2], [3, 4]])
mb = tf.constant([[1,-2], [-1, 3]])
mc = tf.constant([[2, 0], [1, 2]])
md = tf.constant([[1,-1], [4, 7]])
cg = ArrayTensorProduct(M, N)
assert tensorflow_code(cg) == \
'tensorflow.linalg.einsum("ab,cd", M, N)'
f = lambdify((M, N), cg, 'tensorflow')
y = session.run(f(ma, mb))
c = session.run(tf.einsum("ij,kl", ma, mb))
assert (y == c).all()
cg = ArrayAdd(M, N)
assert tensorflow_code(cg) == 'tensorflow.math.add(M, N)'
f = lambdify((M, N), cg, 'tensorflow')
y = session.run(f(ma, mb))
c = session.run(ma + mb)
assert (y == c).all()
cg = ArrayAdd(M, N, P)
assert tensorflow_code(cg) == \
'tensorflow.math.add(tensorflow.math.add(M, N), P)'
f = lambdify((M, N, P), cg, 'tensorflow')
y = session.run(f(ma, mb, mc))
c = session.run(ma + mb + mc)
assert (y == c).all()
cg = ArrayAdd(M, N, P, Q)
assert tensorflow_code(cg) == \
'tensorflow.math.add(' \
'tensorflow.math.add(tensorflow.math.add(M, N), P), Q)'
f = lambdify((M, N, P, Q), cg, 'tensorflow')
y = session.run(f(ma, mb, mc, md))
c = session.run(ma + mb + mc + md)
assert (y == c).all()
cg = PermuteDims(M, [1, 0])
assert tensorflow_code(cg) == 'tensorflow.transpose(M, [1, 0])'
f = lambdify((M,), cg, 'tensorflow')
y = session.run(f(ma))
c = session.run(tf.transpose(ma))
assert (y == c).all()
cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
assert tensorflow_code(cg) == \
'tensorflow.transpose(' \
'tensorflow.linalg.einsum("ab,cd", M, N), [1, 2, 3, 0])'
f = lambdify((M, N), cg, 'tensorflow')
y = session.run(f(ma, mb))
c = session.run(tf.transpose(tf.einsum("ab,cd", ma, mb), [1, 2, 3, 0]))
assert (y == c).all()
cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
assert tensorflow_code(cg) == \
'tensorflow.linalg.einsum("ab,bc->acb", M, N)'
f = lambdify((M, N), cg, 'tensorflow')
y = session.run(f(ma, mb))
c = session.run(tf.einsum("ab,bc->acb", ma, mb))
assert (y == c).all()
def test_MatrixElement_printing():
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
assert tensorflow_code(A[0, 0]) == "A[0, 0]"
assert tensorflow_code(3 * A[0, 0]) == "3*A[0, 0]"
F = C[0, 0].subs(C, A - B)
assert tensorflow_code(F) == "(tensorflow.math.add((-1)*B, A))[0, 0]"
def test_tensorflow_Derivative():
expr = Derivative(sin(x), x)
assert tensorflow_code(expr) == \
"tensorflow.gradients(tensorflow.math.sin(x), x)[0]"
|
b93efa108851a220334a7f046518b4eaf0b9aa5587e5423b4e147af694bf1064 | from sympy.concrete.summations import Sum
from sympy.core.mod import Mod
from sympy.core.relational import (Equality, Unequality)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.utilities.lambdify import lambdify
from sympy.abc import x, i, j, a, b, c, d
from sympy.core import Pow
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
from sympy.tensor.array import Array
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
PermuteDims, ArrayDiagonal
from sympy.printing.numpy import NumPyPrinter, SciPyPrinter, _numpy_known_constants, \
_numpy_known_functions, _scipy_known_constants, _scipy_known_functions
from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
from sympy.testing.pytest import skip, raises
from sympy.external import import_module
np = import_module('numpy')
if np:
deafult_float_info = np.finfo(np.array([]).dtype)
NUMPY_DEFAULT_EPSILON = deafult_float_info.eps
def test_numpy_piecewise_regression():
"""
NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
See gh-9747 and gh-9749 for details.
"""
printer = NumPyPrinter()
p = Piecewise((1, x < 0), (0, True))
assert printer.doprint(p) == \
'numpy.select([numpy.less(x, 0),True], [1,0], default=numpy.nan)'
assert printer.module_imports == {'numpy': {'select', 'less', 'nan'}}
def test_numpy_logaddexp():
lae = logaddexp(a, b)
assert NumPyPrinter().doprint(lae) == 'numpy.logaddexp(a, b)'
lae2 = logaddexp2(a, b)
assert NumPyPrinter().doprint(lae2) == 'numpy.logaddexp2(a, b)'
def test_sum():
if not np:
skip("NumPy not installed")
s = Sum(x ** i, (i, a, b))
f = lambdify((a, b, x), s, 'numpy')
a_, b_ = 0, 10
x_ = np.linspace(-1, +1, 10)
assert np.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
s = Sum(i * x, (i, a, b))
f = lambdify((a, b, x), s, 'numpy')
a_, b_ = 0, 10
x_ = np.linspace(-1, +1, 10)
assert np.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
def test_multiple_sums():
if not np:
skip("NumPy not installed")
s = Sum((x + j) * i, (i, a, b), (j, c, d))
f = lambdify((a, b, c, d, x), s, 'numpy')
a_, b_ = 0, 10
c_, d_ = 11, 21
x_ = np.linspace(-1, +1, 10)
assert np.allclose(f(a_, b_, c_, d_, x_),
sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1)))
def test_codegen_einsum():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
cg = convert_matrix_to_array(M * N)
f = lambdify((M, N), cg, 'numpy')
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
assert (f(ma, mb) == np.matmul(ma, mb)).all()
def test_codegen_extra():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
P = MatrixSymbol("P", 2, 2)
Q = MatrixSymbol("Q", 2, 2)
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
mc = np.array([[2, 0], [1, 2]])
md = np.array([[1,-1], [4, 7]])
cg = ArrayTensorProduct(M, N)
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == np.einsum(ma, [0, 1], mb, [2, 3])).all()
cg = ArrayAdd(M, N)
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == ma+mb).all()
cg = ArrayAdd(M, N, P)
f = lambdify((M, N, P), cg, 'numpy')
assert (f(ma, mb, mc) == ma+mb+mc).all()
cg = ArrayAdd(M, N, P, Q)
f = lambdify((M, N, P, Q), cg, 'numpy')
assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
cg = PermuteDims(M, [1, 0])
f = lambdify((M,), cg, 'numpy')
assert (f(ma) == ma.T).all()
cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == np.transpose(np.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all()
cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == np.diagonal(np.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all()
def test_relational():
if not np:
skip("NumPy not installed")
e = Equality(x, 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [False, True, False])
e = Unequality(x, 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [True, False, True])
e = (x < 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [True, False, False])
e = (x <= 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [True, True, False])
e = (x > 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [False, False, True])
e = (x >= 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [False, True, True])
def test_mod():
if not np:
skip("NumPy not installed")
e = Mod(a, b)
f = lambdify((a, b), e)
a_ = np.array([0, 1, 2, 3])
b_ = 2
assert np.array_equal(f(a_, b_), [0, 1, 0, 1])
a_ = np.array([0, 1, 2, 3])
b_ = np.array([2, 2, 2, 2])
assert np.array_equal(f(a_, b_), [0, 1, 0, 1])
a_ = np.array([2, 3, 4, 5])
b_ = np.array([2, 3, 4, 5])
assert np.array_equal(f(a_, b_), [0, 0, 0, 0])
def test_pow():
if not np:
skip('NumPy not installed')
expr = Pow(2, -1, evaluate=False)
f = lambdify([], expr, 'numpy')
assert f() == 0.5
def test_expm1():
if not np:
skip("NumPy not installed")
f = lambdify((a,), expm1(a), 'numpy')
assert abs(f(1e-10) - 1e-10 - 5e-21) <= 1e-10 * NUMPY_DEFAULT_EPSILON
def test_log1p():
if not np:
skip("NumPy not installed")
f = lambdify((a,), log1p(a), 'numpy')
assert abs(f(1e-99) - 1e-99) <= 1e-99 * NUMPY_DEFAULT_EPSILON
def test_hypot():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a, b), hypot(a, b), 'numpy')(3, 4) - 5) <= NUMPY_DEFAULT_EPSILON
def test_log10():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), log10(a), 'numpy')(100) - 2) <= NUMPY_DEFAULT_EPSILON
def test_exp2():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), exp2(a), 'numpy')(5) - 32) <= NUMPY_DEFAULT_EPSILON
def test_log2():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), log2(a), 'numpy')(256) - 8) <= NUMPY_DEFAULT_EPSILON
def test_Sqrt():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), Sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
def test_sqrt():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
def test_matsolve():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 3, 3)
x = MatrixSymbol("x", 3, 1)
expr = M**(-1) * x + x
matsolve_expr = MatrixSolve(M, x) + x
f = lambdify((M, x), expr)
f_matsolve = lambdify((M, x), matsolve_expr)
m0 = np.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]])
assert np.linalg.matrix_rank(m0) == 3
x0 = np.array([3, 4, 5])
assert np.allclose(f_matsolve(m0, x0), f(m0, x0))
def test_16857():
if not np:
skip("NumPy not installed")
a_1 = MatrixSymbol('a_1', 10, 3)
a_2 = MatrixSymbol('a_2', 10, 3)
a_3 = MatrixSymbol('a_3', 10, 3)
a_4 = MatrixSymbol('a_4', 10, 3)
A = BlockMatrix([[a_1, a_2], [a_3, a_4]])
assert A.shape == (20, 6)
printer = NumPyPrinter()
assert printer.doprint(A) == 'numpy.block([[a_1, a_2], [a_3, a_4]])'
def test_issue_17006():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 2, 2)
f = lambdify(M, M + Identity(2))
ma = np.array([[1, 2], [3, 4]])
mr = np.array([[2, 2], [3, 5]])
assert (f(ma) == mr).all()
from sympy.core.symbol import symbols
n = symbols('n', integer=True)
N = MatrixSymbol("M", n, n)
raises(NotImplementedError, lambda: lambdify(N, N + Identity(n)))
def test_numpy_array():
assert NumPyPrinter().doprint(Array(((1, 2), (3, 5)))) == 'numpy.array([[1, 2], [3, 5]])'
assert NumPyPrinter().doprint(Array((1, 2))) == 'numpy.array((1, 2))'
def test_numpy_known_funcs_consts():
assert _numpy_known_constants['NaN'] == 'numpy.nan'
assert _numpy_known_constants['EulerGamma'] == 'numpy.euler_gamma'
assert _numpy_known_functions['acos'] == 'numpy.arccos'
assert _numpy_known_functions['log'] == 'numpy.log'
def test_scipy_known_funcs_consts():
assert _scipy_known_constants['GoldenRatio'] == 'scipy.constants.golden_ratio'
assert _scipy_known_constants['Pi'] == 'scipy.constants.pi'
assert _scipy_known_functions['erf'] == 'scipy.special.erf'
assert _scipy_known_functions['factorial'] == 'scipy.special.factorial'
def test_numpy_print_methods():
prntr = NumPyPrinter()
assert hasattr(prntr, '_print_acos')
assert hasattr(prntr, '_print_log')
def test_scipy_print_methods():
prntr = SciPyPrinter()
assert hasattr(prntr, '_print_acos')
assert hasattr(prntr, '_print_log')
assert hasattr(prntr, '_print_erf')
assert hasattr(prntr, '_print_factorial')
assert hasattr(prntr, '_print_chebyshevt')
|
0a2b4194c01b898e518d22456099c07f6fc9913c9a54e8bf7585990269d8a439 | import math
from sympy.concrete.summations import (Sum, summation)
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, Function, Lambda, diff)
from sympy.core import EulerGamma
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
from sympy.core.relational import (Eq, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import (Abs, im, polar_lift, re, sign)
from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import (acosh, asinh, cosh, coth, csch, sinh, tanh, sech)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan, sec)
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.error_functions import (Ci, Ei, Si, erf, erfc, erfi, fresnelc, li)
from sympy.functions.special.gamma_functions import (gamma, polygamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.zeta_functions import lerchphi
from sympy.integrals.integrals import integrate
from sympy.logic.boolalg import And
from sympy.matrices.dense import Matrix
from sympy.polys.polytools import (Poly, factor)
from sympy.printing.str import sstr
from sympy.series.order import O
from sympy.sets.sets import Interval
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.simplify import simplify
from sympy.simplify.trigsimp import trigsimp
from sympy.tensor.indexed import (Idx, IndexedBase)
from sympy.core.expr import unchanged
from sympy.functions.elementary.integers import floor
from sympy.integrals.integrals import Integral
from sympy.integrals.risch import NonElementaryIntegral
from sympy.physics import units
from sympy.testing.pytest import (raises, slow, skip, ON_TRAVIS,
warns_deprecated_sympy, warns)
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.core.random import verify_numerically
x, y, z, a, b, c, d, e, s, t, x_1, x_2 = symbols('x y z a b c d e s t x_1 x_2')
n = Symbol('n', integer=True)
f = Function('f')
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_poly_deprecated():
p = Poly(2*x, x)
assert p.integrate(x) == Poly(x**2, x, domain='QQ')
# The stacklevel is based on Integral(Poly)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
integrate(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Integral(p, (x,))
@slow
def test_principal_value():
g = 1 / x
assert Integral(g, (x, -oo, oo)).principal_value() == 0
assert Integral(g, (y, -oo, oo)).principal_value() == oo * sign(1 / x)
raises(ValueError, lambda: Integral(g, (x)).principal_value())
raises(ValueError, lambda: Integral(g).principal_value())
l = 1 / ((x ** 3) - 1)
assert Integral(l, (x, -oo, oo)).principal_value().together() == -sqrt(3)*pi/3
raises(ValueError, lambda: Integral(l, (x, -oo, 1)).principal_value())
d = 1 / (x ** 2 - 1)
assert Integral(d, (x, -oo, oo)).principal_value() == 0
assert Integral(d, (x, -2, 2)).principal_value() == -log(3)
v = x / (x ** 2 - 1)
assert Integral(v, (x, -oo, oo)).principal_value() == 0
assert Integral(v, (x, -2, 2)).principal_value() == 0
s = x ** 2 / (x ** 2 - 1)
assert Integral(s, (x, -oo, oo)).principal_value() is oo
assert Integral(s, (x, -2, 2)).principal_value() == -log(3) + 4
f = 1 / ((x ** 2 - 1) * (1 + x ** 2))
assert Integral(f, (x, -oo, oo)).principal_value() == -pi / 2
assert Integral(f, (x, -2, 2)).principal_value() == -atan(2) - log(3) / 2
def diff_test(i):
"""Return the set of symbols, s, which were used in testing that
i.diff(s) agrees with i.doit().diff(s). If there is an error then
the assertion will fail, causing the test to fail."""
syms = i.free_symbols
for s in syms:
assert (i.diff(s).doit() - i.doit().diff(s)).expand() == 0
return syms
def test_improper_integral():
assert integrate(log(x), (x, 0, 1)) == -1
assert integrate(x**(-2), (x, 1, oo)) == 1
assert integrate(1/(1 + exp(x)), (x, 0, oo)) == log(2)
def test_constructor():
# this is shared by Sum, so testing Integral's constructor
# is equivalent to testing Sum's
s1 = Integral(n, n)
assert s1.limits == (Tuple(n),)
s2 = Integral(n, (n,))
assert s2.limits == (Tuple(n),)
s3 = Integral(Sum(x, (x, 1, y)))
assert s3.limits == (Tuple(y),)
s4 = Integral(n, Tuple(n,))
assert s4.limits == (Tuple(n),)
s5 = Integral(n, (n, Interval(1, 2)))
assert s5.limits == (Tuple(n, 1, 2),)
# Testing constructor with inequalities:
s6 = Integral(n, n > 10)
assert s6.limits == (Tuple(n, 10, oo),)
s7 = Integral(n, (n > 2) & (n < 5))
assert s7.limits == (Tuple(n, 2, 5),)
def test_basics():
assert Integral(0, x) != 0
assert Integral(x, (x, 1, 1)) != 0
assert Integral(oo, x) != oo
assert Integral(S.NaN, x) is S.NaN
assert diff(Integral(y, y), x) == 0
assert diff(Integral(x, (x, 0, 1)), x) == 0
assert diff(Integral(x, x), x) == x
assert diff(Integral(t, (t, 0, x)), x) == x
e = (t + 1)**2
assert diff(integrate(e, (t, 0, x)), x) == \
diff(Integral(e, (t, 0, x)), x).doit().expand() == \
((1 + x)**2).expand()
assert diff(integrate(e, (t, 0, x)), t) == \
diff(Integral(e, (t, 0, x)), t) == 0
assert diff(integrate(e, (t, 0, x)), a) == \
diff(Integral(e, (t, 0, x)), a) == 0
assert diff(integrate(e, t), a) == diff(Integral(e, t), a) == 0
assert integrate(e, (t, a, x)).diff(x) == \
Integral(e, (t, a, x)).diff(x).doit().expand()
assert Integral(e, (t, a, x)).diff(x).doit() == ((1 + x)**2)
assert integrate(e, (t, x, a)).diff(x).doit() == (-(1 + x)**2).expand()
assert integrate(t**2, (t, x, 2*x)).diff(x) == 7*x**2
assert Integral(x, x).atoms() == {x}
assert Integral(f(x), (x, 0, 1)).atoms() == {S.Zero, S.One, x}
assert diff_test(Integral(x, (x, 3*y))) == {y}
assert diff_test(Integral(x, (a, 3*y))) == {x, y}
assert integrate(x, (x, oo, oo)) == 0 #issue 8171
assert integrate(x, (x, -oo, -oo)) == 0
# sum integral of terms
assert integrate(y + x + exp(x), x) == x*y + x**2/2 + exp(x)
assert Integral(x).is_commutative
n = Symbol('n', commutative=False)
assert Integral(n + x, x).is_commutative is False
def test_diff_wrt():
class Test(Expr):
_diff_wrt = True
is_commutative = True
t = Test()
assert integrate(t + 1, t) == t**2/2 + t
assert integrate(t + 1, (t, 0, 1)) == Rational(3, 2)
raises(ValueError, lambda: integrate(x + 1, x + 1))
raises(ValueError, lambda: integrate(x + 1, (x + 1, 0, 1)))
def test_basics_multiple():
assert diff_test(Integral(x, (x, 3*x, 5*y), (y, x, 2*x))) == {x}
assert diff_test(Integral(x, (x, 5*y), (y, x, 2*x))) == {x}
assert diff_test(Integral(x, (x, 5*y), (y, y, 2*x))) == {x, y}
assert diff_test(Integral(y, y, x)) == {x, y}
assert diff_test(Integral(y*x, x, y)) == {x, y}
assert diff_test(Integral(x + y, y, (y, 1, x))) == {x}
assert diff_test(Integral(x + y, (x, x, y), (y, y, x))) == {x, y}
def test_conjugate_transpose():
A, B = symbols("A B", commutative=False)
x = Symbol("x", complex=True)
p = Integral(A*B, (x,))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
x = Symbol("x", real=True)
p = Integral(A*B, (x,))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
def test_integration():
assert integrate(0, (t, 0, x)) == 0
assert integrate(3, (t, 0, x)) == 3*x
assert integrate(t, (t, 0, x)) == x**2/2
assert integrate(3*t, (t, 0, x)) == 3*x**2/2
assert integrate(3*t**2, (t, 0, x)) == x**3
assert integrate(1/t, (t, 1, x)) == log(x)
assert integrate(-1/t**2, (t, 1, x)) == 1/x - 1
assert integrate(t**2 + 5*t - 8, (t, 0, x)) == x**3/3 + 5*x**2/2 - 8*x
assert integrate(x**2, x) == x**3/3
assert integrate((3*t*x)**5, x) == (3*t)**5 * x**6 / 6
b = Symbol("b")
c = Symbol("c")
assert integrate(a*t, (t, 0, x)) == a*x**2/2
assert integrate(a*t**4, (t, 0, x)) == a*x**5/5
assert integrate(a*t**2 + b*t + c, (t, 0, x)) == a*x**3/3 + b*x**2/2 + c*x
def test_multiple_integration():
assert integrate((x**2)*(y**2), (x, 0, 1), (y, -1, 2)) == Rational(1)
assert integrate((y**2)*(x**2), x, y) == Rational(1, 9)*(x**3)*(y**3)
assert integrate(1/(x + 3)/(1 + x)**3, x) == \
log(3 + x)*Rational(-1, 8) + log(1 + x)*Rational(1, 8) + x/(4 + 8*x + 4*x**2)
assert integrate(sin(x*y)*y, (x, 0, 1), (y, 0, 1)) == -sin(1) + 1
def test_issue_3532():
assert integrate(exp(-x), (x, 0, oo)) == 1
def test_issue_3560():
assert integrate(sqrt(x)**3, x) == 2*sqrt(x)**5/5
assert integrate(sqrt(x), x) == 2*sqrt(x)**3/3
assert integrate(1/sqrt(x)**3, x) == -2/sqrt(x)
def test_issue_18038():
raises(AttributeError, lambda: integrate((x, x)))
def test_integrate_poly():
p = Poly(x + x**2*y + y**3, x, y)
# The stacklevel is based on Integral(Poly)
with warns_deprecated_sympy():
qx = Integral(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
qx = integrate(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
qy = integrate(p, y)
assert isinstance(qx, Poly) is True
assert isinstance(qy, Poly) is True
assert qx.gens == (x, y)
assert qy.gens == (x, y)
assert qx.as_expr() == x**2/2 + x**3*y/3 + x*y**3
assert qy.as_expr() == x*y + x**2*y**2/2 + y**4/4
def test_integrate_poly_definite():
p = Poly(x + x**2*y + y**3, x, y)
with warns_deprecated_sympy():
Qx = Integral(p, (x, 0, 1))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Qx = integrate(p, (x, 0, 1))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Qy = integrate(p, (y, 0, pi))
assert isinstance(Qx, Poly) is True
assert isinstance(Qy, Poly) is True
assert Qx.gens == (y,)
assert Qy.gens == (x,)
assert Qx.as_expr() == S.Half + y/3 + y**3
assert Qy.as_expr() == pi**4/4 + pi*x + pi**2*x**2/2
def test_integrate_omit_var():
y = Symbol('y')
assert integrate(x) == x**2/2
raises(ValueError, lambda: integrate(2))
raises(ValueError, lambda: integrate(x*y))
def test_integrate_poly_accurately():
y = Symbol('y')
assert integrate(x*sin(y), x) == x**2*sin(y)/2
# when passed to risch_norman, this will be a CPU hog, so this really
# checks, that integrated function is recognized as polynomial
assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001
def test_issue_3635():
y = Symbol('y')
assert integrate(x**2, y) == x**2*y
assert integrate(x**2, (y, -1, 1)) == 2*x**2
# works in SymPy and py.test but hangs in `setup.py test`
def test_integrate_linearterm_pow():
# check integrate((a*x+b)^c, x) -- issue 3499
y = Symbol('y', positive=True)
# TODO: Remove conds='none' below, let the assumption take care of it.
assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1)
assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \
exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y))
def test_issue_3618():
assert integrate(pi*sqrt(x), x) == 2*pi*sqrt(x)**3/3
assert integrate(pi*sqrt(x) + E*sqrt(x)**3, x) == \
2*pi*sqrt(x)**3/3 + 2*E *sqrt(x)**5/5
def test_issue_3623():
assert integrate(cos((n + 1)*x), x) == Piecewise(
(sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True))
assert integrate(cos((n - 1)*x), x) == Piecewise(
(sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True))
assert integrate(cos((n + 1)*x) + cos((n - 1)*x), x) == \
Piecewise((sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) + \
Piecewise((sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True))
def test_issue_3664():
n = Symbol('n', integer=True, nonzero=True)
assert integrate(-1./2 * x * sin(n * pi * x/2), [x, -2, 0]) == \
2.0*cos(pi*n)/(pi*n)
assert integrate(x * sin(n * pi * x/2) * Rational(-1, 2), [x, -2, 0]) == \
2*cos(pi*n)/(pi*n)
def test_issue_3679():
# definite integration of rational functions gives wrong answers
assert NS(Integral(1/(x**2 - 8*x + 17), (x, 2, 4))) == '1.10714871779409'
def test_issue_3686(): # remove this when fresnel itegrals are implemented
from sympy.core.function import expand_func
from sympy.functions.special.error_functions import fresnels
assert expand_func(integrate(sin(x**2), x)) == \
sqrt(2)*sqrt(pi)*fresnels(sqrt(2)*x/sqrt(pi))/2
def test_integrate_units():
m = units.m
s = units.s
assert integrate(x * m/s, (x, 1*s, 5*s)) == 12*m*s
def test_transcendental_functions():
assert integrate(LambertW(2*x), x) == \
-x + x*LambertW(2*x) + x/LambertW(2*x)
def test_log_polylog():
assert integrate(log(1 - x)/x, (x, 0, 1)) == -pi**2/6
assert integrate(log(x)*(1 - x)**(-1), (x, 0, 1)) == -pi**2/6
def test_issue_3740():
f = 4*log(x) - 2*log(x)**2
fid = diff(integrate(f, x), x)
assert abs(f.subs(x, 42).evalf() - fid.subs(x, 42).evalf()) < 1e-10
def test_issue_3788():
assert integrate(1/(1 + x**2), x) == atan(x)
def test_issue_3952():
f = sin(x)
assert integrate(f, x) == -cos(x)
raises(ValueError, lambda: integrate(f, 2*x))
def test_issue_4516():
assert integrate(2**x - 2*x, x) == 2**x/log(2) - x**2
def test_issue_7450():
ans = integrate(exp(-(1 + I)*x), (x, 0, oo))
assert re(ans) == S.Half and im(ans) == Rational(-1, 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 test_issue_9569():
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)) + pi*floor((x/2 - pi/2)/pi))/3
def test_issue_13733():
s = Symbol('s', positive=True)
pz = exp(-(z - y)**2/(2*s*s))/sqrt(2*pi*s*s)
pzgx = integrate(pz, (z, x, oo))
assert integrate(pzgx, (x, 0, oo)) == sqrt(2)*s*exp(-y**2/(2*s**2))/(2*sqrt(pi)) + \
y*erf(sqrt(2)*y/(2*s))/2 + y/2
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 test_issue_18133():
assert integrate(exp(x)/(1 + x)**2, x) == NonElementaryIntegral(exp(x)/(x + 1)**2, x)
def test_issue_21741():
a = Float('3999999.9999999995', precision=53)
b = Float('2.5000000000000004e-7', precision=53)
r = Piecewise((b*I*exp(-a*I*pi*t*y)*exp(-a*I*pi*x*z)/(pi*x),
Ne(1.0*pi*x*exp(a*I*pi*t*y), 0)),
(z*exp(-a*I*pi*t*y), True))
fun = E**((-2*I*pi*(z*x+t*y))/(500*10**(-9)))
assert integrate(fun, z) == r
def test_matrices():
M = Matrix(2, 2, lambda i, j: (i + j + 1)*sin((i + j + 1)*x))
assert integrate(M, x) == Matrix([
[-cos(x), -cos(2*x)],
[-cos(2*x), -cos(3*x)],
])
def test_integrate_functions():
# issue 4111
assert integrate(f(x), x) == Integral(f(x), x)
assert integrate(f(x), (x, 0, 1)) == Integral(f(x), (x, 0, 1))
assert integrate(f(x)*diff(f(x), x), x) == f(x)**2/2
assert integrate(diff(f(x), x) / f(x), x) == log(f(x))
def test_integrate_derivatives():
assert integrate(Derivative(f(x), x), x) == f(x)
assert integrate(Derivative(f(y), y), x) == x*Derivative(f(y), y)
assert integrate(Derivative(f(x), x)**2, x) == \
Integral(Derivative(f(x), x)**2, x)
def test_transform():
a = Integral(x**2 + 1, (x, -1, 2))
fx = x
fy = 3*y + 1
assert a.doit() == a.transform(fx, fy).doit()
assert a.transform(fx, fy).transform(fy, fx) == a
fx = 3*x + 1
fy = y
assert a.transform(fx, fy).transform(fy, fx) == a
a = Integral(sin(1/x), (x, 0, 1))
assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo))
assert a.transform(x, 1/y).transform(y, 1/x) == a
a = Integral(exp(-x**2), (x, -oo, oo))
assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo))
# < 3 arg limit handled properly
assert Integral(x, x).transform(x, a*y).doit() == \
Integral(y*a**2, y).doit()
_3 = S(3)
assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \
Integral(-1/x**3, (x, -oo, -1/_3)).doit()
assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \
Integral(y**(-3), (y, 1/_3, oo))
# issue 8400
i = Integral(x + y, (x, 1, 2), (y, 1, 2))
assert i.transform(x, (x + 2*y, x)).doit() == \
i.transform(x, (x + 2*z, x)).doit() == 3
i = Integral(x, (x, a, b))
assert i.transform(x, 2*s) == Integral(4*s, (s, a/2, b/2))
raises(ValueError, lambda: i.transform(x, 1))
raises(ValueError, lambda: i.transform(x, s*t))
raises(ValueError, lambda: i.transform(x, -s))
raises(ValueError, lambda: i.transform(x, (s, t)))
raises(ValueError, lambda: i.transform(2*x, 2*s))
i = Integral(x**2, (x, 1, 2))
raises(ValueError, lambda: i.transform(x**2, s))
am = Symbol('a', negative=True)
bp = Symbol('b', positive=True)
i = Integral(x, (x, bp, am))
i.transform(x, 2*s)
assert i.transform(x, 2*s) == Integral(-4*s, (s, am/2, bp/2))
i = Integral(x, (x, a))
assert i.transform(x, 2*s) == Integral(4*s, (s, a/2))
def test_issue_4052():
f = S.Half*asin(x) + x*sqrt(1 - x**2)/2
assert integrate(cos(asin(x)), x) == f
assert integrate(sin(acos(x)), x) == f
@slow
def test_evalf_integrals():
assert NS(Integral(x, (x, 2, 5)), 15) == '10.5000000000000'
gauss = Integral(exp(-x**2), (x, -oo, oo))
assert NS(gauss, 15) == '1.77245385090552'
assert NS(gauss**2 - pi + E*Rational(
1, 10**20), 15) in ('2.71828182845904e-20', '2.71828182845905e-20')
# A monster of an integral from http://mathworld.wolfram.com/DefiniteIntegral.html
t = Symbol('t')
a = 8*sqrt(3)/(1 + 3*t**2)
b = 16*sqrt(2)*(3*t + 1)*sqrt(4*t**2 + t + 1)**3
c = (3*t**2 + 1)*(11*t**2 + 2*t + 3)**2
d = sqrt(2)*(249*t**2 + 54*t + 65)/(11*t**2 + 2*t + 3)**2
f = a - b/c - d
assert NS(Integral(f, (t, 0, 1)), 50) == \
NS((3*sqrt(2) - 49*pi + 162*atan(sqrt(2)))/12, 50)
# http://mathworld.wolfram.com/VardisIntegral.html
assert NS(Integral(log(log(1/x))/(1 + x + x**2), (x, 0, 1)), 15) == \
NS('pi/sqrt(3) * log(2*pi**(5/6) / gamma(1/6))', 15)
# http://mathworld.wolfram.com/AhmedsIntegral.html
assert NS(Integral(atan(sqrt(x**2 + 2))/(sqrt(x**2 + 2)*(x**2 + 1)), (x,
0, 1)), 15) == NS(5*pi**2/96, 15)
# http://mathworld.wolfram.com/AbelsIntegral.html
assert NS(Integral(x/((exp(pi*x) - exp(
-pi*x))*(x**2 + 1)), (x, 0, oo)), 15) == NS('log(2)/2-1/4', 15)
# Complex part trimming
# http://mathworld.wolfram.com/VardisIntegral.html
assert NS(Integral(log(log(sin(x)/cos(x))), (x, pi/4, pi/2)), 15, chop=True) == \
NS('pi/4*log(4*pi**3/gamma(1/4)**4)', 15)
#
# Endpoints causing trouble (rounding error in integration points -> complex log)
assert NS(
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 17, chop=True) == NS(2, 17)
assert NS(
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 20, chop=True) == NS(2, 20)
assert NS(
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 22, chop=True) == NS(2, 22)
# Needs zero handling
assert NS(pi - 4*Integral(
'sqrt(1-x**2)', (x, 0, 1)), 15, maxn=30, chop=True) in ('0.0', '0')
# Oscillatory quadrature
a = Integral(sin(x)/x**2, (x, 1, oo)).evalf(maxn=15)
assert 0.49 < a < 0.51
assert NS(
Integral(sin(x)/x**2, (x, 1, oo)), quad='osc') == '0.504067061906928'
assert NS(Integral(
cos(pi*x + 1)/x, (x, -oo, -1)), quad='osc') == '0.276374705640365'
# indefinite integrals aren't evaluated
assert NS(Integral(x, x)) == 'Integral(x, x)'
assert NS(Integral(x, (x, y))) == 'Integral(x, (x, y))'
def test_evalf_issue_939():
# https://github.com/sympy/sympy/issues/4038
# The output form of an integral may differ by a step function between
# revisions, making this test a bit useless. This can't be said about
# other two tests. For now, all values of this evaluation are used here,
# but in future this should be reconsidered.
assert NS(integrate(1/(x**5 + 1), x).subs(x, 4), chop=True) in \
['-0.000976138910649103', '0.965906660135753', '1.93278945918216']
assert NS(Integral(1/(x**5 + 1), (x, 2, 4))) == '0.0144361088886740'
assert NS(
integrate(1/(x**5 + 1), (x, 2, 4)), chop=True) == '0.0144361088886740'
def test_double_previously_failing_integrals():
# Double integrals not implemented <- Sure it is!
res = integrate(sqrt(x) + x*y, (x, 1, 2), (y, -1, 1))
# Old numerical test
assert NS(res, 15) == '2.43790283299492'
# Symbolic test
assert res == Rational(-4, 3) + 8*sqrt(2)/3
# double integral + zero detection
assert integrate(sin(x + x*y), (x, -1, 1), (y, -1, 1)) is S.Zero
def test_integrate_SingularityFunction():
in_1 = SingularityFunction(x, a, 3) + SingularityFunction(x, 5, -1)
out_1 = SingularityFunction(x, a, 4)/4 + SingularityFunction(x, 5, 0)
assert integrate(in_1, x) == out_1
in_2 = 10*SingularityFunction(x, 4, 0) - 5*SingularityFunction(x, -6, -2)
out_2 = 10*SingularityFunction(x, 4, 1) - 5*SingularityFunction(x, -6, -1)
assert integrate(in_2, x) == out_2
in_3 = 2*x**2*y -10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -2)
out_3_1 = 2*x**3*y/3 - 2*x*SingularityFunction(y, 10, -2) - 5*SingularityFunction(x, -4, 8)/4
out_3_2 = x**2*y**2 - 10*y*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -1)
assert integrate(in_3, x) == out_3_1
assert integrate(in_3, y) == out_3_2
assert unchanged(Integral, in_3, (x,))
assert Integral(in_3, x) == Integral(in_3, (x,))
assert Integral(in_3, x).doit() == out_3_1
in_4 = 10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(x, 10, -2)
out_4 = 5*SingularityFunction(x, -4, 8)/4 - 2*SingularityFunction(x, 10, -1)
assert integrate(in_4, (x, -oo, x)) == out_4
assert integrate(SingularityFunction(x, 5, -1), x) == SingularityFunction(x, 5, 0)
assert integrate(SingularityFunction(x, 0, -1), (x, -oo, oo)) == 1
assert integrate(5*SingularityFunction(x, 5, -1), (x, -oo, oo)) == 5
assert integrate(SingularityFunction(x, 5, -1) * f(x), (x, -oo, oo)) == f(5)
def test_integrate_DiracDelta():
# This is here to check that deltaintegrate is being called, but also
# to test definite integrals. More tests are in test_deltafunctions.py
assert integrate(DiracDelta(x) * f(x), (x, -oo, oo)) == f(0)
assert integrate(DiracDelta(x)**2, (x, -oo, oo)) == DiracDelta(0)
# issue 4522
assert integrate(integrate((4 - 4*x + x*y - 4*y) * \
DiracDelta(x)*DiracDelta(y - 1), (x, 0, 1)), (y, 0, 1)) == 0
# issue 5729
p = exp(-(x**2 + y**2))/pi
assert integrate(p*DiracDelta(x - 10*y), (x, -oo, oo), (y, -oo, oo)) == \
integrate(p*DiracDelta(x - 10*y), (y, -oo, oo), (x, -oo, oo)) == \
integrate(p*DiracDelta(10*x - y), (x, -oo, oo), (y, -oo, oo)) == \
integrate(p*DiracDelta(10*x - y), (y, -oo, oo), (x, -oo, oo)) == \
1/sqrt(101*pi)
def test_integrate_returns_piecewise():
assert integrate(x**y, x) == Piecewise(
(x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True))
assert integrate(x**y, y) == Piecewise(
(x**y/log(x), Ne(log(x), 0)), (y, True))
assert integrate(exp(n*x), x) == Piecewise(
(exp(n*x)/n, Ne(n, 0)), (x, True))
assert integrate(x*exp(n*x), x) == Piecewise(
((n*x - 1)*exp(n*x)/n**2, Ne(n**2, 0)), (x**2/2, True))
assert integrate(x**(n*y), x) == Piecewise(
(x**(n*y + 1)/(n*y + 1), Ne(n*y, -1)), (log(x), True))
assert integrate(x**(n*y), y) == Piecewise(
(x**(n*y)/(n*log(x)), Ne(n*log(x), 0)), (y, True))
assert integrate(cos(n*x), x) == Piecewise(
(sin(n*x)/n, Ne(n, 0)), (x, True))
assert integrate(cos(n*x)**2, x) == Piecewise(
((n*x/2 + sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (x, True))
assert integrate(x*cos(n*x), x) == Piecewise(
(x*sin(n*x)/n + cos(n*x)/n**2, Ne(n, 0)), (x**2/2, True))
assert integrate(sin(n*x), x) == Piecewise(
(-cos(n*x)/n, Ne(n, 0)), (0, True))
assert integrate(sin(n*x)**2, x) == Piecewise(
((n*x/2 - sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (0, True))
assert integrate(x*sin(n*x), x) == Piecewise(
(-x*cos(n*x)/n + sin(n*x)/n**2, Ne(n, 0)), (0, True))
assert integrate(exp(x*y), (x, 0, z)) == Piecewise(
(exp(y*z)/y - 1/y, (y > -oo) & (y < oo) & Ne(y, 0)), (z, True))
# https://github.com/sympy/sympy/issues/23707
assert integrate(exp(t)*exp(-t*sqrt(x - y)), t) == Piecewise(
(-exp(t)/(sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y))),
Ne(x, y + 1)), (t, True))
def test_integrate_max_min():
x = symbols('x', real=True)
assert integrate(Min(x, 2), (x, 0, 3)) == 4
assert integrate(Max(x**2, x**3), (x, 0, 2)) == Rational(49, 12)
assert integrate(Min(exp(x), exp(-x))**2, x) == Piecewise( \
(exp(2*x)/2, x <= 0), (1 - exp(-2*x)/2, True))
# issue 7907
c = symbols('c', extended_real=True)
int1 = integrate(Max(c, x)*exp(-x**2), (x, -oo, oo))
int2 = integrate(c*exp(-x**2), (x, -oo, c))
int3 = integrate(x*exp(-x**2), (x, c, oo))
assert int1 == int2 + int3 == sqrt(pi)*c*erf(c)/2 + \
sqrt(pi)*c/2 + exp(-c**2)/2
def test_integrate_Abs_sign():
assert integrate(Abs(x), (x, -2, 1)) == Rational(5, 2)
assert integrate(Abs(x), (x, 0, 1)) == S.Half
assert integrate(Abs(x + 1), (x, 0, 1)) == Rational(3, 2)
assert integrate(Abs(x**2 - 1), (x, -2, 2)) == 4
assert integrate(Abs(x**2 - 3*x), (x, -15, 15)) == 2259
assert integrate(sign(x), (x, -1, 2)) == 1
assert integrate(sign(x)*sin(x), (x, -pi, pi)) == 4
assert integrate(sign(x - 2) * x**2, (x, 0, 3)) == Rational(11, 3)
t, s = symbols('t s', real=True)
assert integrate(Abs(t), t) == Piecewise(
(-t**2/2, t <= 0), (t**2/2, True))
assert integrate(Abs(2*t - 6), t) == Piecewise(
(-t**2 + 6*t, t <= 3), (t**2 - 6*t + 18, True))
assert (integrate(abs(t - s**2), (t, 0, 2)) ==
2*s**2*Min(2, s**2) - 2*s**2 - Min(2, s**2)**2 + 2)
assert integrate(exp(-Abs(t)), t) == Piecewise(
(exp(t), t <= 0), (2 - exp(-t), True))
assert integrate(sign(2*t - 6), t) == Piecewise(
(-t, t < 3), (t - 6, True))
assert integrate(2*t*sign(t**2 - 1), t) == Piecewise(
(t**2, t < -1), (-t**2 + 2, t < 1), (t**2, True))
assert integrate(sign(t), (t, s + 1)) == Piecewise(
(s + 1, s + 1 > 0), (-s - 1, s + 1 < 0), (0, True))
def test_subs1():
e = Integral(exp(x - y), x)
assert e.subs(y, 3) == Integral(exp(x - 3), x)
e = Integral(exp(x - y), (x, 0, 1))
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(x - y)*f(y), (y, -oo, oo))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo))
def test_subs2():
e = Integral(exp(x - y), x, t)
assert e.subs(y, 3) == Integral(exp(x - 3), x, t)
e = Integral(exp(x - y), (x, 0, 1), (t, 0, 1))
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1), (t, 0, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, 0, 1))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
def test_subs3():
e = Integral(exp(x - y), (x, 0, y), (t, y, 1))
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 3), (t, 3, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, x, 1))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
def test_subs4():
e = Integral(exp(x), (x, 0, y), (t, y, 1))
assert e.subs(y, 3) == Integral(exp(x), (x, 0, 3), (t, 3, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(y)*f(y), (y, -oo, oo), (t, x, 1))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
def test_subs5():
e = Integral(exp(-x**2), (x, -oo, oo))
assert e.subs(x, 5) == e
e = Integral(exp(-x**2 + y), x)
assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x)
e = Integral(exp(-x**2 + y), (x, x))
assert e.subs(x, 5) == Integral(exp(y - x**2), (x, 5))
assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x)
e = Integral(exp(-x**2 + y), (y, -oo, oo), (x, -oo, oo))
assert e.subs(x, 5) == e
assert e.subs(y, 5) == e
# Test evaluation of antiderivatives
e = Integral(exp(-x**2), (x, x))
assert e.subs(x, 5) == Integral(exp(-x**2), (x, 5))
e = Integral(exp(x), x)
assert (e.subs(x,1) - e.subs(x,0) - Integral(exp(x), (x, 0, 1))
).doit().is_zero
def test_subs6():
a, b = symbols('a b')
e = Integral(x*y, (x, f(x), f(y)))
assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)))
assert e.subs(y, 1) == Integral(x, (x, f(x), f(1)))
e = Integral(x*y, (x, f(x), f(y)), (y, f(x), f(y)))
assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)), (y, f(1), f(y)))
assert e.subs(y, 1) == Integral(x*y, (x, f(x), f(y)), (y, f(x), f(1)))
e = Integral(x*y, (x, f(x), f(a)), (y, f(x), f(a)))
assert e.subs(a, 1) == Integral(x*y, (x, f(x), f(1)), (y, f(x), f(1)))
def test_subs7():
e = Integral(x, (x, 1, y), (y, 1, 2))
assert e.subs({x: 1, y: 2}) == e
e = Integral(sin(x) + sin(y), (x, sin(x), sin(y)),
(y, 1, 2))
assert e.subs(sin(y), 1) == e
assert e.subs(sin(x), 1) == Integral(sin(x) + sin(y), (x, 1, sin(y)),
(y, 1, 2))
def test_expand():
e = Integral(f(x)+f(x**2), (x, 1, y))
assert e.expand() == Integral(f(x), (x, 1, y)) + Integral(f(x**2), (x, 1, y))
e = Integral(f(x)+f(x**2), (x, 1, oo))
assert e.expand() == e
assert e.expand(force=True) == Integral(f(x), (x, 1, oo)) + \
Integral(f(x**2), (x, 1, oo))
def test_integration_variable():
raises(ValueError, lambda: Integral(exp(-x**2), 3))
raises(ValueError, lambda: Integral(exp(-x**2), (3, -oo, oo)))
def test_expand_integral():
assert Integral(cos(x**2)*(sin(x**2) + 1), (x, 0, 1)).expand() == \
Integral(cos(x**2)*sin(x**2), (x, 0, 1)) + \
Integral(cos(x**2), (x, 0, 1))
assert Integral(cos(x**2)*(sin(x**2) + 1), x).expand() == \
Integral(cos(x**2)*sin(x**2), x) + \
Integral(cos(x**2), x)
def test_as_sum_midpoint1():
e = Integral(sqrt(x**3 + 1), (x, 2, 10))
assert e.as_sum(1, method="midpoint") == 8*sqrt(217)
assert e.as_sum(2, method="midpoint") == 4*sqrt(65) + 12*sqrt(57)
assert e.as_sum(3, method="midpoint") == 8*sqrt(217)/3 + \
8*sqrt(3081)/27 + 8*sqrt(52809)/27
assert e.as_sum(4, method="midpoint") == 2*sqrt(730) + \
4*sqrt(7) + 4*sqrt(86) + 6*sqrt(14)
assert abs(e.as_sum(4, method="midpoint").n() - e.n()) < 0.5
e = Integral(sqrt(x**3 + y**3), (x, 2, 10), (y, 0, 10))
raises(NotImplementedError, lambda: e.as_sum(4))
def test_as_sum_midpoint2():
e = Integral((x + y)**2, (x, 0, 1))
n = Symbol('n', positive=True, integer=True)
assert e.as_sum(1, method="midpoint").expand() == Rational(1, 4) + y + y**2
assert e.as_sum(2, method="midpoint").expand() == Rational(5, 16) + y + y**2
assert e.as_sum(3, method="midpoint").expand() == Rational(35, 108) + y + y**2
assert e.as_sum(4, method="midpoint").expand() == Rational(21, 64) + y + y**2
assert e.as_sum(n, method="midpoint").expand() == \
y**2 + y + Rational(1, 3) - 1/(12*n**2)
def test_as_sum_left():
e = Integral((x + y)**2, (x, 0, 1))
assert e.as_sum(1, method="left").expand() == y**2
assert e.as_sum(2, method="left").expand() == Rational(1, 8) + y/2 + y**2
assert e.as_sum(3, method="left").expand() == Rational(5, 27) + y*Rational(2, 3) + y**2
assert e.as_sum(4, method="left").expand() == Rational(7, 32) + y*Rational(3, 4) + y**2
assert e.as_sum(n, method="left").expand() == \
y**2 + y + Rational(1, 3) - y/n - 1/(2*n) + 1/(6*n**2)
assert e.as_sum(10, method="left", evaluate=False).has(Sum)
def test_as_sum_right():
e = Integral((x + y)**2, (x, 0, 1))
assert e.as_sum(1, method="right").expand() == 1 + 2*y + y**2
assert e.as_sum(2, method="right").expand() == Rational(5, 8) + y*Rational(3, 2) + y**2
assert e.as_sum(3, method="right").expand() == Rational(14, 27) + y*Rational(4, 3) + y**2
assert e.as_sum(4, method="right").expand() == Rational(15, 32) + y*Rational(5, 4) + y**2
assert e.as_sum(n, method="right").expand() == \
y**2 + y + Rational(1, 3) + y/n + 1/(2*n) + 1/(6*n**2)
def test_as_sum_trapezoid():
e = Integral((x + y)**2, (x, 0, 1))
assert e.as_sum(1, method="trapezoid").expand() == y**2 + y + S.Half
assert e.as_sum(2, method="trapezoid").expand() == y**2 + y + Rational(3, 8)
assert e.as_sum(3, method="trapezoid").expand() == y**2 + y + Rational(19, 54)
assert e.as_sum(4, method="trapezoid").expand() == y**2 + y + Rational(11, 32)
assert e.as_sum(n, method="trapezoid").expand() == \
y**2 + y + Rational(1, 3) + 1/(6*n**2)
assert Integral(sign(x), (x, 0, 1)).as_sum(1, 'trapezoid') == S.Half
def test_as_sum_raises():
e = Integral((x + y)**2, (x, 0, 1))
raises(ValueError, lambda: e.as_sum(-1))
raises(ValueError, lambda: e.as_sum(0))
raises(ValueError, lambda: Integral(x).as_sum(3))
raises(ValueError, lambda: e.as_sum(oo))
raises(ValueError, lambda: e.as_sum(3, method='xxxx2'))
def test_nested_doit():
e = Integral(Integral(x, x), x)
f = Integral(x, x, x)
assert e.doit() == f.doit()
def test_issue_4665():
# Allow only upper or lower limit evaluation
e = Integral(x**2, (x, None, 1))
f = Integral(x**2, (x, 1, None))
assert e.doit() == Rational(1, 3)
assert f.doit() == Rational(-1, 3)
assert Integral(x*y, (x, None, y)).subs(y, t) == Integral(x*t, (x, None, t))
assert Integral(x*y, (x, y, None)).subs(y, t) == Integral(x*t, (x, t, None))
assert integrate(x**2, (x, None, 1)) == Rational(1, 3)
assert integrate(x**2, (x, 1, None)) == Rational(-1, 3)
assert integrate("x**2", ("x", "1", None)) == Rational(-1, 3)
def test_integral_reconstruct():
e = Integral(x**2, (x, -1, 1))
assert e == Integral(*e.args)
def test_doit_integrals():
e = Integral(Integral(2*x), (x, 0, 1))
assert e.doit() == Rational(1, 3)
assert e.doit(deep=False) == Rational(1, 3)
f = Function('f')
# doesn't matter if the integral can't be performed
assert Integral(f(x), (x, 1, 1)).doit() == 0
# doesn't matter if the limits can't be evaluated
assert Integral(0, (x, 1, Integral(f(x), x))).doit() == 0
assert Integral(x, (a, 0)).doit() == 0
limits = ((a, 1, exp(x)), (x, 0))
assert Integral(a, *limits).doit() == Rational(1, 4)
assert Integral(a, *list(reversed(limits))).doit() == 0
def test_issue_4884():
assert integrate(sqrt(x)*(1 + x)) == \
Piecewise(
(2*sqrt(x)*(x + 1)**2/5 - 2*sqrt(x)*(x + 1)/15 - 4*sqrt(x)/15,
Abs(x + 1) > 1),
(2*I*sqrt(-x)*(x + 1)**2/5 - 2*I*sqrt(-x)*(x + 1)/15 -
4*I*sqrt(-x)/15, True))
assert integrate(x**x*(1 + log(x))) == x**x
def test_issue_18153():
assert integrate(x**n*log(x),x) == \
Piecewise(
(n*x*x**n*log(x)/(n**2 + 2*n + 1) +
x*x**n*log(x)/(n**2 + 2*n + 1) - x*x**n/(n**2 + 2*n + 1)
, Ne(n, -1)), (log(x)**2/2, True)
)
def test_is_number():
from sympy.abc import x, y, z
assert Integral(x).is_number is False
assert Integral(1, x).is_number is False
assert Integral(1, (x, 1)).is_number is True
assert Integral(1, (x, 1, 2)).is_number is True
assert Integral(1, (x, 1, y)).is_number is False
assert Integral(1, (x, y)).is_number is False
assert Integral(x, y).is_number is False
assert Integral(x, (y, 1, x)).is_number is False
assert Integral(x, (y, 1, 2)).is_number is False
assert Integral(x, (x, 1, 2)).is_number is True
# `foo.is_number` should always be equivalent to `not foo.free_symbols`
# in each of these cases, there are pseudo-free symbols
i = Integral(x, (y, 1, 1))
assert i.is_number is False and i.n() == 0
i = Integral(x, (y, z, z))
assert i.is_number is False and i.n() == 0
i = Integral(1, (y, z, z + 2))
assert i.is_number is False and i.n() == 2
assert Integral(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
assert Integral(x*y, (x, 1, 2), (y, 1, z)).is_number is False
assert Integral(x, (x, 1)).is_number is True
assert Integral(x, (x, 1, Integral(y, (y, 1, 2)))).is_number is True
assert Integral(Sum(z, (z, 1, 2)), (x, 1, 2)).is_number is True
# it is possible to get a false negative if the integrand is
# actually an unsimplified zero, but this is true of is_number in general.
assert Integral(sin(x)**2 + cos(x)**2 - 1, x).is_number is False
assert Integral(f(x), (x, 0, 1)).is_number is True
def test_free_symbols():
from sympy.abc import x, y, z
assert Integral(0, x).free_symbols == {x}
assert Integral(x).free_symbols == {x}
assert Integral(x, (x, None, y)).free_symbols == {y}
assert Integral(x, (x, y, None)).free_symbols == {y}
assert Integral(x, (x, 1, y)).free_symbols == {y}
assert Integral(x, (x, y, 1)).free_symbols == {y}
assert Integral(x, (x, x, y)).free_symbols == {x, y}
assert Integral(x, x, y).free_symbols == {x, y}
assert Integral(x, (x, 1, 2)).free_symbols == set()
assert Integral(x, (y, 1, 2)).free_symbols == {x}
# pseudo-free in this case
assert Integral(x, (y, z, z)).free_symbols == {x, z}
assert Integral(x, (y, 1, 2), (y, None, None)
).free_symbols == {x, y}
assert Integral(x, (y, 1, 2), (x, 1, y)
).free_symbols == {y}
assert Integral(2, (y, 1, 2), (y, 1, x), (x, 1, 2)
).free_symbols == set()
assert Integral(2, (y, x, 2), (y, 1, x), (x, 1, 2)
).free_symbols == set()
assert Integral(2, (x, 1, 2), (y, x, 2), (y, 1, 2)
).free_symbols == {x}
assert Integral(f(x), (f(x), 1, y)).free_symbols == {y}
assert Integral(f(x), (f(x), 1, x)).free_symbols == {x}
def test_is_zero():
from sympy.abc import x, m
assert Integral(0, (x, 1, x)).is_zero
assert Integral(1, (x, 1, 1)).is_zero
assert Integral(1, (x, 1, 2), (y, 2)).is_zero is False
assert Integral(x, (m, 0)).is_zero
assert Integral(x + m, (m, 0)).is_zero is None
i = Integral(m, (m, 1, exp(x)), (x, 0))
assert i.is_zero is None
assert Integral(m, (x, 0), (m, 1, exp(x))).is_zero is True
assert Integral(x, (x, oo, oo)).is_zero # issue 8171
assert Integral(x, (x, -oo, -oo)).is_zero
# this is zero but is beyond the scope of what is_zero
# should be doing
assert Integral(sin(x), (x, 0, 2*pi)).is_zero is None
def test_series():
from sympy.abc import x
i = Integral(cos(x), (x, x))
e = i.lseries(x)
assert i.nseries(x, n=8).removeO() == Add(*[next(e) for j in range(4)])
def test_trig_nonelementary_integrals():
x = Symbol('x')
assert integrate((1 + sin(x))/x, x) == log(x) + Si(x)
# next one comes out as log(x) + log(x**2)/2 + Ci(x)
# so not hardcoding this log ugliness
assert integrate((cos(x) + 2)/x, x).has(Ci)
def test_issue_4403():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z', positive=True)
assert integrate(sqrt(x**2 + z**2), x) == \
z**2*asinh(x/z)/2 + x*sqrt(x**2 + z**2)/2
assert integrate(sqrt(x**2 - z**2), x) == \
x*sqrt(x**2 - z**2)/2 - z**2*log(x + sqrt(x**2 - z**2))/2
x = Symbol('x', real=True)
y = Symbol('y', positive=True)
assert integrate(1/(x**2 + y**2)**S('3/2'), x) == \
x/(y**2*sqrt(x**2 + y**2))
# If y is real and nonzero, we get x*Abs(y)/(y**3*sqrt(x**2 + y**2)),
# which results from sqrt(1 + x**2/y**2) = sqrt(x**2 + y**2)/|y|.
def test_issue_4403_2():
assert integrate(sqrt(-x**2 - 4), x) == \
-2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2
def test_issue_4100():
R = Symbol('R', positive=True)
assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4
def test_issue_5167():
from sympy.abc import w, x, y, z
f = Function('f')
assert Integral(Integral(f(x), x), x) == Integral(f(x), x, x)
assert Integral(f(x)).args == (f(x), Tuple(x))
assert Integral(Integral(f(x))).args == (f(x), Tuple(x), Tuple(x))
assert Integral(Integral(f(x)), y).args == (f(x), Tuple(x), Tuple(y))
assert Integral(Integral(f(x), z), y).args == (f(x), Tuple(z), Tuple(y))
assert Integral(Integral(Integral(f(x), x), y), z).args == \
(f(x), Tuple(x), Tuple(y), Tuple(z))
assert integrate(Integral(f(x), x), x) == Integral(f(x), x, x)
assert integrate(Integral(f(x), y), x) == y*Integral(f(x), x)
assert integrate(Integral(f(x), x), y) in [Integral(y*f(x), x), y*Integral(f(x), x)]
assert integrate(Integral(2, x), x) == x**2
assert integrate(Integral(2, x), y) == 2*x*y
# don't re-order given limits
assert Integral(1, x, y).args != Integral(1, y, x).args
# do as many as possible
assert Integral(f(x), y, x, y, x).doit() == y**2*Integral(f(x), x, x)/2
assert Integral(f(x), (x, 1, 2), (w, 1, x), (z, 1, y)).doit() == \
y*(x - 1)*Integral(f(x), (x, 1, 2)) - (x - 1)*Integral(f(x), (x, 1, 2))
def test_issue_4890():
z = Symbol('z', positive=True)
assert integrate(exp(-log(x)**2), x) == \
sqrt(pi)*exp(Rational(1, 4))*erf(log(x) - S.Half)/2
assert integrate(exp(log(x)**2), x) == \
sqrt(pi)*exp(Rational(-1, 4))*erfi(log(x)+S.Half)/2
assert integrate(exp(-z*log(x)**2), x) == \
sqrt(pi)*exp(1/(4*z))*erf(sqrt(z)*log(x) - 1/(2*sqrt(z)))/(2*sqrt(z))
def test_issue_4551():
assert not integrate(1/(x*sqrt(1 - x**2)), x).has(Integral)
def test_issue_4376():
n = Symbol('n', integer=True, positive=True)
assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) -
(n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0
def test_issue_4517():
assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \
6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11
def test_issue_4527():
k, m = symbols('k m', integer=True)
assert integrate(sin(k*x)*sin(m*x), (x, 0, pi)).simplify() == \
Piecewise((0, Eq(k, 0) | Eq(m, 0)),
(-pi/2, Eq(k, -m) | (Eq(k, 0) & Eq(m, 0))),
(pi/2, Eq(k, m) | (Eq(k, 0) & Eq(m, 0))),
(0, True))
# Should be possible to further simplify to:
# Piecewise(
# (0, Eq(k, 0) | Eq(m, 0)),
# (-pi/2, Eq(k, -m)),
# (pi/2, Eq(k, m)),
# (0, True))
assert integrate(sin(k*x)*sin(m*x), (x,)) == Piecewise(
(0, And(Eq(k, 0), Eq(m, 0))),
(-x*sin(m*x)**2/2 - x*cos(m*x)**2/2 + sin(m*x)*cos(m*x)/(2*m), Eq(k, -m)),
(x*sin(m*x)**2/2 + x*cos(m*x)**2/2 - sin(m*x)*cos(m*x)/(2*m), Eq(k, m)),
(m*sin(k*x)*cos(m*x)/(k**2 - m**2) -
k*sin(m*x)*cos(k*x)/(k**2 - m**2), True))
def test_issue_4199():
ypos = Symbol('y', positive=True)
# TODO: Remove conds='none' below, let the assumption take care of it.
assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \
Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo))
def test_issue_3940():
a, b, c, d = symbols('a:d', positive=True)
assert integrate(exp(-x**2 + I*c*x), x) == \
-sqrt(pi)*exp(-c**2/4)*erf(I*c/2 - x)/2
assert integrate(exp(a*x**2 + b*x + c), x) == \
sqrt(pi)*exp(c)*exp(-b**2/(4*a))*erfi(sqrt(a)*x + b/(2*sqrt(a)))/(2*sqrt(a))
from sympy.core.function import expand_mul
from sympy.abc import k
assert expand_mul(integrate(exp(-x**2)*exp(I*k*x), (x, -oo, oo))) == \
sqrt(pi)*exp(-k**2/4)
a, d = symbols('a d', positive=True)
assert expand_mul(integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))) == \
sqrt(pi)*exp(d**2/a)/sqrt(a)
def test_issue_5413():
# Note that this is not the same as testing ratint() because integrate()
# pulls out the coefficient.
assert integrate(-a/(a**2 + x**2), x) == I*log(-I*a + x)/2 - I*log(I*a + x)/2
def test_issue_4892a():
A, z = symbols('A z')
c = Symbol('c', nonzero=True)
P1 = -A*exp(-z)
P2 = -A/(c*t)*(sin(x)**2 + cos(y)**2)
h1 = -sin(x)**2 - cos(y)**2
h2 = -sin(x)**2 + sin(y)**2 - 1
# there is still some non-deterministic behavior in integrate
# or trigsimp which permits one of the following
assert integrate(c*(P2 - P1), t) in [
c*(-A*(-h1)*log(c*t)/c + A*t*exp(-z)),
c*(-A*(-h2)*log(c*t)/c + A*t*exp(-z)),
c*( A* h1 *log(c*t)/c + A*t*exp(-z)),
c*( A* h2 *log(c*t)/c + A*t*exp(-z)),
(A*c*t - A*(-h1)*log(t)*exp(z))*exp(-z),
(A*c*t - A*(-h2)*log(t)*exp(z))*exp(-z),
]
def test_issue_4892b():
# Issues relating to issue 4596 are making the actual result of this hard
# to test. The answer should be something like
#
# (-sin(y) + sqrt(-72 + 48*cos(y) - 8*cos(y)**2)/2)*log(x + sqrt(-72 +
# 48*cos(y) - 8*cos(y)**2)/(2*(3 - cos(y)))) + (-sin(y) - sqrt(-72 +
# 48*cos(y) - 8*cos(y)**2)/2)*log(x - sqrt(-72 + 48*cos(y) -
# 8*cos(y)**2)/(2*(3 - cos(y)))) + x**2*sin(y)/2 + 2*x*cos(y)
expr = (sin(y)*x**3 + 2*cos(y)*x**2 + 12)/(x**2 + 2)
assert trigsimp(factor(integrate(expr, x).diff(x) - expr)) == 0
def test_issue_5178():
assert integrate(sin(x)*f(y, z), (x, 0, pi), (y, 0, pi), (z, 0, pi)) == \
2*Integral(f(y, z), (y, 0, pi), (z, 0, pi))
def test_integrate_series():
f = sin(x).series(x, 0, 10)
g = x**2/2 - x**4/24 + x**6/720 - x**8/40320 + x**10/3628800 + O(x**11)
assert integrate(f, x) == g
assert diff(integrate(f, x), x) == f
assert integrate(O(x**5), x) == O(x**6)
def test_atom_bug():
from sympy.integrals.heurisch import heurisch
assert heurisch(meijerg([], [], [1], [], x), x) is None
def test_limit_bug():
z = Symbol('z', zero=False)
assert integrate(sin(x*y*z), (x, 0, pi), (y, 0, pi)).together() == \
(log(z) - Ci(pi**2*z) + EulerGamma + 2*log(pi))/z
def test_issue_4703():
g = Function('g')
assert integrate(exp(x)*g(x), x).has(Integral)
def test_issue_1888():
f = Function('f')
assert integrate(f(x).diff(x)**2, x).has(Integral)
# The following tests work using meijerint.
def test_issue_3558():
assert integrate(cos(x*y), (x, -pi/2, pi/2), (y, 0, pi)) == 2*Si(pi**2/2)
def test_issue_4422():
assert integrate(1/sqrt(16 + 4*x**2), x) == asinh(x/2) / 2
def test_issue_4493():
assert simplify(integrate(x*sqrt(1 + 2*x), x)) == \
sqrt(2*x + 1)*(6*x**2 + x - 1)/15
def test_issue_4737():
assert integrate(sin(x)/x, (x, -oo, oo)) == pi
assert integrate(sin(x)/x, (x, 0, oo)) == pi/2
assert integrate(sin(x)/x, x) == Si(x)
def test_issue_4992():
# Note: psi in _check_antecedents becomes NaN.
from sympy.core.function import expand_func
a = Symbol('a', positive=True)
assert simplify(expand_func(integrate(exp(-x)*log(x)*x**a, (x, 0, oo)))) == \
(a*polygamma(0, a) + 1)*gamma(a)
def test_issue_4487():
from sympy.functions.special.gamma_functions import lowergamma
assert simplify(integrate(exp(-x)*x**y, x)) == lowergamma(y + 1, x)
def test_issue_4215():
x = Symbol("x")
assert integrate(1/(x**2), (x, -1, 1)) is oo
def test_issue_4400():
n = Symbol('n', integer=True, positive=True)
assert integrate((x**n)*log(x), x) == \
n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - \
x*x**n/(n**2 + 2*n + 1)
def test_issue_6253():
# Note: this used to raise NotImplementedError
# Note: psi in _check_antecedents becomes NaN.
assert integrate((sqrt(1 - x) + sqrt(1 + x))**2/x, x, meijerg=True) == \
Integral((sqrt(-x + 1) + sqrt(x + 1))**2/x, x)
def test_issue_4153():
assert integrate(1/(1 + x + y + z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) in [
-12*log(3) - 3*log(6)/2 + 3*log(8)/2 + 5*log(2) + 7*log(4),
6*log(2) + 8*log(4) - 27*log(3)/2, 22*log(2) - 27*log(3)/2,
-12*log(3) - 3*log(6)/2 + 47*log(2)/2]
def test_issue_4326():
R, b, h = symbols('R b h')
# It doesn't matter if we can do the integral. Just make sure the result
# doesn't contain nan. This is really a test against _eval_interval.
e = integrate(((h*(x - R + b))/b)*sqrt(R**2 - x**2), (x, R - b, R))
assert not e.has(nan)
# See that it evaluates
assert not e.has(Integral)
def test_powers():
assert integrate(2**x + 3**x, x) == 2**x/log(2) + 3**x/log(3)
def test_manual_option():
raises(ValueError, lambda: integrate(1/x, x, manual=True, meijerg=True))
# an example of a function that manual integration cannot handle
assert integrate(log(1+x)/x, (x, 0, 1), manual=True).has(Integral)
def test_meijerg_option():
raises(ValueError, lambda: integrate(1/x, x, meijerg=True, risch=True))
# an example of a function that meijerg integration cannot handle
assert integrate(tan(x), x, meijerg=True) == Integral(tan(x), x)
def test_risch_option():
# risch=True only allowed on indefinite integrals
raises(ValueError, lambda: integrate(1/log(x), (x, 0, oo), risch=True))
assert integrate(exp(-x**2), x, risch=True) == NonElementaryIntegral(exp(-x**2), x)
assert integrate(log(1/x)*y, x, y, risch=True) == y**2*(x*log(1/x)/2 + x/2)
assert integrate(erf(x), x, risch=True) == Integral(erf(x), x)
# TODO: How to test risch=False?
@slow
def test_heurisch_option():
raises(ValueError, lambda: integrate(1/x, x, risch=True, heurisch=True))
# an integral that heurisch can handle
assert integrate(exp(x**2), x, heurisch=True) == sqrt(pi)*erfi(x)/2
# an integral that heurisch currently cannot handle
assert integrate(exp(x)/x, x, heurisch=True) == Integral(exp(x)/x, x)
# an integral where heurisch currently hangs, issue 15471
assert integrate(log(x)*cos(log(x))/x**Rational(3, 4), x, heurisch=False) == (
-128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 +
(16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x))
def test_issue_6828():
f = 1/(1.08*x**2 - 4.3)
g = integrate(f, x).diff(x)
assert verify_numerically(f, g, tol=1e-12)
def test_issue_4803():
x_max = Symbol("x_max")
assert integrate(y/pi*exp(-(x_max - x)/cos(a)), x) == \
y*exp((x - x_max)/cos(a))*cos(a)/pi
def test_issue_4234():
assert integrate(1/sqrt(1 + tan(x)**2)) == tan(x)/sqrt(1 + tan(x)**2)
def test_issue_4492():
assert simplify(integrate(x**2 * sqrt(5 - x**2), x)).factor(
deep=True) == Piecewise(
(I*(2*x**5 - 15*x**3 + 25*x - 25*sqrt(x**2 - 5)*acosh(sqrt(5)*x/5)) /
(8*sqrt(x**2 - 5)), (x > sqrt(5)) | (x < -sqrt(5))),
((2*x**5 - 15*x**3 + 25*x - 25*sqrt(5 - x**2)*asin(sqrt(5)*x/5)) /
(-8*sqrt(-x**2 + 5)), True))
def test_issue_2708():
# This test needs to use an integration function that can
# not be evaluated in closed form. Update as needed.
f = 1/(a + z + log(z))
integral_f = NonElementaryIntegral(f, (z, 2, 3))
assert Integral(f, (z, 2, 3)).doit() == integral_f
assert integrate(f + exp(z), (z, 2, 3)) == integral_f - exp(2) + exp(3)
assert integrate(2*f + exp(z), (z, 2, 3)) == \
2*integral_f - exp(2) + exp(3)
assert integrate(exp(1.2*n*s*z*(-t + z)/t), (z, 0, x)) == \
NonElementaryIntegral(exp(-1.2*n*s*z)*exp(1.2*n*s*z**2/t),
(z, 0, x))
def test_issue_2884():
f = (4.000002016020*x + 4.000002016020*y + 4.000006024032)*exp(10.0*x)
e = integrate(f, (x, 0.1, 0.2))
assert str(e) == '1.86831064982608*y + 2.16387491480008'
def test_issue_8368i():
from sympy.functions.elementary.complexes import arg, Abs
assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \
Piecewise(
( pi*Piecewise(
( -s/(pi*(-s**2 + 1)),
Abs(s**2) < 1),
( 1/(pi*s*(1 - 1/s**2)),
Abs(s**(-2)) < 1),
( meijerg(
((S.Half,), (0, 0)),
((0, S.Half), (0,)),
polar_lift(s)**2),
True)
),
s**2 > 1
),
(
Integral(exp(-s*x)*cosh(x), (x, 0, oo)),
True))
assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \
Piecewise(
( -1/(s + 1)/2 - 1/(-s + 1)/2,
And(
Abs(s) > 1,
Abs(arg(s)) < pi/2,
Abs(arg(s)) <= pi/2
)),
( Integral(exp(-s*x)*sinh(x), (x, 0, oo)),
True))
def test_issue_8901():
assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x)
assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1)
assert integrate(tanh(x)) == x - log(tanh(x) + 1)
@slow
def test_issue_8945():
assert integrate(sin(x)**3/x, (x, 0, 1)) == -Si(3)/4 + 3*Si(1)/4
assert integrate(sin(x)**3/x, (x, 0, oo)) == pi/4
assert integrate(cos(x)**2/x**2, x) == -Si(2*x) - cos(2*x)/(2*x) - 1/(2*x)
@slow
def test_issue_7130():
if ON_TRAVIS:
skip("Too slow for travis.")
i, L, a, b = symbols('i L a b')
integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp)
assert x not in integrate(integrand, (x, 0, L)).free_symbols
def test_issue_10567():
a, b, c, t = symbols('a b c t')
vt = Matrix([a*t, b, c])
assert integrate(vt, t) == Integral(vt, t).doit()
assert integrate(vt, t) == Matrix([[a*t**2/2], [b*t], [c*t]])
def test_issue_11742():
assert integrate(sqrt(-x**2 + 8*x + 48), (x, 4, 12)) == 16*pi
def test_issue_11856():
t = symbols('t')
assert integrate(sinc(pi*t), t) == Si(pi*t)/pi
@slow
def test_issue_11876():
assert integrate(sqrt(log(1/x)), (x, 0, 1)) == sqrt(pi)/2
def test_issue_4950():
assert integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) ==\
-2.4*exp(8*x) - 12.0*exp(5*x)
def test_issue_4968():
assert integrate(sin(log(x**2))) == x*sin(log(x**2))/5 - 2*x*cos(log(x**2))/5
def test_singularities():
assert integrate(1/x**2, (x, -oo, oo)) is oo
assert integrate(1/x**2, (x, -1, 1)) is oo
assert integrate(1/(x - 1)**2, (x, -2, 2)) is oo
assert integrate(1/x**2, (x, 1, -1)) is -oo
assert integrate(1/(x - 1)**2, (x, 2, -2)) is -oo
def test_issue_12645():
x, y = symbols('x y', real=True)
assert (integrate(sin(x*x*x + y*y),
(x, -sqrt(pi - y*y), sqrt(pi - y*y)),
(y, -sqrt(pi), sqrt(pi)))
== Integral(sin(x**3 + y**2),
(x, -sqrt(-y**2 + pi), sqrt(-y**2 + pi)),
(y, -sqrt(pi), sqrt(pi))))
def test_issue_12677():
assert integrate(sin(x) / (cos(x)**3), (x, 0, pi/6)) == Rational(1, 6)
def test_issue_14078():
assert integrate((cos(3*x)-cos(x))/x, (x, 0, oo)) == -log(3)
def test_issue_14064():
assert integrate(1/cosh(x), (x, 0, oo)) == pi/2
def test_issue_14027():
assert integrate(1/(1 + exp(x - S.Half)/(1 + exp(x))), x) == \
x - exp(S.Half)*log(exp(x) + exp(S.Half)/(1 + exp(S.Half)))/(exp(S.Half) + E)
def test_issue_8170():
assert integrate(tan(x), (x, 0, pi/2)) is S.Infinity
def test_issue_8440_14040():
assert integrate(1/x, (x, -1, 1)) is S.NaN
assert integrate(1/(x + 1), (x, -2, 3)) is S.NaN
def test_issue_14096():
assert integrate(1/(x + y)**2, (x, 0, 1)) == -1/(y + 1) + 1/y
assert integrate(1/(1 + x + y + z)**2, (x, 0, 1), (y, 0, 1), (z, 0, 1)) == \
-4*log(4) - 6*log(2) + 9*log(3)
def test_issue_14144():
assert Abs(integrate(1/sqrt(1 - x**3), (x, 0, 1)).n() - 1.402182) < 1e-6
assert Abs(integrate(sqrt(1 - x**3), (x, 0, 1)).n() - 0.841309) < 1e-6
def test_issue_14375():
# This raised a TypeError. The antiderivative has exp_polar, which
# may be possible to unpolarify, so the exact output is not asserted here.
assert integrate(exp(I*x)*log(x), x).has(Ei)
def test_issue_14437():
f = Function('f')(x, y, z)
assert integrate(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) == \
Integral(f, (x, 0, 1), (y, 0, 2), (z, 0, 3))
def test_issue_14470():
assert integrate(1/sqrt(exp(x) + 1), x) == log(sqrt(exp(x) + 1) - 1) - log(sqrt(exp(x) + 1) + 1)
def test_issue_14877():
f = exp(1 - exp(x**2)*x + 2*x**2)*(2*x**3 + x)/(1 - exp(x**2)*x)**2
assert integrate(f, x) == \
-exp(2*x**2 - x*exp(x**2) + 1)/(x*exp(3*x**2) - exp(2*x**2))
def test_issue_14782():
f = sqrt(-x**2 + 1)*(-x**2 + x)
assert integrate(f, [x, -1, 1]) == - pi / 8
@slow
def test_issue_14782_slow():
f = sqrt(-x**2 + 1)*(-x**2 + x)
assert integrate(f, [x, 0, 1]) == S.One / 3 - pi / 16
def test_issue_12081():
f = x**(Rational(-3, 2))*exp(-x)
assert integrate(f, [x, 0, oo]) is oo
def test_issue_15285():
y = 1/x - 1
f = 4*y*exp(-2*y)/x**2
assert integrate(f, [x, 0, 1]) == 1
def test_issue_15432():
assert integrate(x**n * exp(-x) * log(x), (x, 0, oo)).gammasimp() == Piecewise(
(gamma(n + 1)*polygamma(0, n) + gamma(n + 1)/n, re(n) + 1 > 0),
(Integral(x**n*exp(-x)*log(x), (x, 0, oo)), True))
def test_issue_15124():
omega = IndexedBase('omega')
m, p = symbols('m p', cls=Idx)
assert integrate(exp(x*I*(omega[m] + omega[p])), x, conds='none') == \
-I*exp(I*x*omega[m])*exp(I*x*omega[p])/(omega[m] + omega[p])
def test_issue_15218():
with warns_deprecated_sympy():
Integral(Eq(x, y))
with warns_deprecated_sympy():
assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x))
with warns_deprecated_sympy():
assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*y)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
# The warning is made in the ExprWithLimits superclass. The stacklevel
# is correct for integrate(Eq) but not Eq.integrate
assert Eq(x, y).integrate(x) == Eq(x**2/2, x*y)
# These are not deprecated because they are definite integrals
assert integrate(Eq(x, y), (x, 0, 1)) == Eq(S.Half, y)
assert Eq(x, y).integrate((x, 0, 1)) == Eq(S.Half, y)
def test_issue_15292():
res = integrate(exp(-x**2*cos(2*t)) * cos(x**2*sin(2*t)), (x, 0, oo))
assert isinstance(res, Piecewise)
assert gammasimp((res - sqrt(pi)/2 * cos(t)).subs(t, pi/6)) == 0
def test_issue_4514():
assert integrate(sin(2*x)/sin(x), x) == 2*sin(x)
def test_issue_15457():
x, a, b = symbols('x a b', real=True)
definite = integrate(exp(Abs(x-2)), (x, a, b))
indefinite = integrate(exp(Abs(x-2)), x)
assert definite.subs({a: 1, b: 3}) == -2 + 2*E
assert indefinite.subs(x, 3) - indefinite.subs(x, 1) == -2 + 2*E
assert definite.subs({a: -3, b: -1}) == -exp(3) + exp(5)
assert indefinite.subs(x, -1) - indefinite.subs(x, -3) == -exp(3) + exp(5)
def test_issue_15431():
assert integrate(x*exp(x)*log(x), x) == \
(x*exp(x) - exp(x))*log(x) - exp(x) + Ei(x)
def test_issue_15640_log_substitutions():
f = x/log(x)
F = Ei(2*log(x))
assert integrate(f, x) == F and F.diff(x) == f
f = x**3/log(x)**2
F = -x**4/log(x) + 4*Ei(4*log(x))
assert integrate(f, x) == F and F.diff(x) == f
f = sqrt(log(x))/x**2
F = -sqrt(pi)*erfc(sqrt(log(x)))/2 - sqrt(log(x))/x
assert integrate(f, x) == F and F.diff(x) == f
def test_issue_15509():
from sympy.vector import CoordSys3D
N = CoordSys3D('N')
x = N.x
assert integrate(cos(a*x + b), (x, x_1, x_2), heurisch=True) == Piecewise(
(-sin(a*x_1 + b)/a + sin(a*x_2 + b)/a, (a > -oo) & (a < oo) & Ne(a, 0)), \
(-x_1*cos(b) + x_2*cos(b), True))
def test_issue_4311_fast():
x = symbols('x', real=True)
assert integrate(x*abs(9-x**2), x) == Piecewise(
(x**4/4 - 9*x**2/2, x <= -3),
(-x**4/4 + 9*x**2/2 - Rational(81, 2), x <= 3),
(x**4/4 - 9*x**2/2, True))
def test_integrate_with_complex_constants():
K = Symbol('K', positive=True)
x = Symbol('x', real=True)
m = Symbol('m', real=True)
t = Symbol('t', real=True)
assert integrate(exp(-I*K*x**2+m*x), x) == sqrt(I)*sqrt(pi)*exp(-I*m**2
/(4*K))*erfi((-2*I*K*x + m)/(2*sqrt(K)*sqrt(-I)))/(2*sqrt(K))
assert integrate(1/(1 + I*x**2), x) == (-I*(sqrt(-I)*log(x - I*sqrt(-I))/2
- sqrt(-I)*log(x + I*sqrt(-I))/2))
assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I))
assert integrate((1/(exp(I*t)-2)), t) == -t/2 - I*log(exp(I*t) - 2)/2
assert integrate((1/(exp(I*t)-2)), (t, 0, 2*pi)) == -pi
def test_issue_14241():
x = Symbol('x')
n = Symbol('n', positive=True, integer=True)
assert integrate(n * x ** (n - 1) / (x + 1), x) == \
n**2*x**n*lerchphi(x*exp_polar(I*pi), 1, n)*gamma(n)/gamma(n + 1)
def test_issue_13112():
assert integrate(sin(t)**2 / (5 - 4*cos(t)), [t, 0, 2*pi]) == pi / 4
def test_issue_14709b():
h = Symbol('h', positive=True)
i = integrate(x*acos(1 - 2*x/h), (x, 0, h))
assert i == 5*h**2*pi/16
def test_issue_8614():
x = Symbol('x')
t = Symbol('t')
assert integrate(exp(t)/t, (t, -oo, x)) == Ei(x)
assert integrate((exp(-x) - exp(-2*x))/x, (x, 0, oo)) == log(2)
@slow
def test_issue_15494():
s = symbols('s', positive=True)
integrand = (exp(s/2) - 2*exp(1.6*s) + exp(s))*exp(s)
solution = integrate(integrand, s)
assert solution != S.NaN
# Not sure how to test this properly as it is a symbolic expression with floats
# assert str(solution) == '0.666666666666667*exp(1.5*s) + 0.5*exp(2.0*s) - 0.769230769230769*exp(2.6*s)'
# Maybe
assert abs(solution.subs(s, 1) - (-3.67440080236188)) <= 1e-8
integrand = (exp(s/2) - 2*exp(S(8)/5*s) + exp(s))*exp(s)
assert integrate(integrand, s) == -10*exp(13*s/5)/13 + 2*exp(3*s/2)/3 + exp(2*s)/2
def test_li_integral():
y = Symbol('y')
assert Integral(li(y*x**2), x).doit() == Piecewise((x*li(x**2*y) - \
x*Ei(3*log(x**2*y)/2)/sqrt(x**2*y),
Ne(y, 0)), (0, True))
def test_issue_17473():
x = Symbol('x')
n = Symbol('n')
h = S.Half
ans = x**(n + 1)*gamma(h + h/n)*hyper((h + h/n,),
(3*h, 3*h + h/n), -x**(2*n)/4)/(2*n*gamma(3*h + h/n))
got = integrate(sin(x**n), x)
assert got == ans
_x = Symbol('x', zero=False)
reps = {x: _x}
assert integrate(sin(_x**n), _x) == ans.xreplace(reps).expand()
def test_issue_17671():
assert integrate(log(log(x)) / x**2, [x, 1, oo]) == -EulerGamma
assert integrate(log(log(x)) / x**3, [x, 1, oo]) == -log(2)/2 - EulerGamma/2
assert integrate(log(log(x)) / x**10, [x, 1, oo]) == -log(9)/9 - EulerGamma/9
def test_issue_2975():
w = Symbol('w')
C = Symbol('C')
y = Symbol('y')
assert integrate(1/(y**2+C)**(S(3)/2), (y, -w/2, w/2)) == w/(C**(S(3)/2)*sqrt(1 + w**2/(4*C)))
def test_issue_7827():
x, n, M = symbols('x n M')
N = Symbol('N', integer=True)
assert integrate(summation(x*n, (n, 1, N)), x) == x**2*(N**2/4 + N/4)
assert integrate(summation(x*sin(n), (n,1,N)), x) == \
Sum(x**2*sin(n)/2, (n, 1, N))
assert integrate(summation(sin(n*x), (n,1,N)), x) == \
Sum(Piecewise((-cos(n*x)/n, Ne(n, 0)), (0, True)), (n, 1, N))
assert integrate(integrate(summation(sin(n*x), (n,1,N)), x), x) == \
Piecewise((Sum(Piecewise((-sin(n*x)/n**2, Ne(n, 0)), (-x/n, True)),
(n, 1, N)), (n > -oo) & (n < oo) & Ne(n, 0)), (0, True))
assert integrate(Sum(x, (n, 1, M)), x) == M*x**2/2
raises(ValueError, lambda: integrate(Sum(x, (x, y, n)), y))
raises(ValueError, lambda: integrate(Sum(x, (x, 1, n)), n))
raises(ValueError, lambda: integrate(Sum(x, (x, 1, y)), x))
def test_issue_4231():
f = (1 + 2*x + sqrt(x + log(x))*(1 + 3*x) + x**2)/(x*(x + sqrt(x + log(x)))*sqrt(x + log(x)))
assert integrate(f, x) == 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x)))
def test_issue_17841():
f = diff(1/(x**2+x+I), x)
assert integrate(f, x) == 1/(x**2 + x + I)
def test_issue_21034():
x = Symbol('x', real=True, nonzero=True)
f1 = x*(-x**4/asin(5)**4 - x*sinh(x + log(asin(5))) + 5)
f2 = (x + cosh(cos(4)))/(x*(x + 1/(12*x)))
assert integrate(f1, x) == \
-x**6/(6*asin(5)**4) - x**2*cosh(x + log(asin(5))) + 5*x**2/2 + 2*x*sinh(x + log(asin(5))) - 2*cosh(x + log(asin(5)))
assert integrate(f2, x) == \
log(x**2 + S(1)/12)/2 + 2*sqrt(3)*cosh(cos(4))*atan(2*sqrt(3)*x)
def test_issue_4187():
assert integrate(log(x)*exp(-x), x) == Ei(-x) - exp(-x)*log(x)
assert integrate(log(x)*exp(-x), (x, 0, oo)) == -EulerGamma
def test_issue_5547():
L = Symbol('L')
z = Symbol('z')
r0 = Symbol('r0')
R0 = Symbol('R0')
assert integrate(r0**2*cos(z)**2, (z, -L/2, L/2)) == -r0**2*(-L/4 -
sin(L/2)*cos(L/2)/2) + r0**2*(L/4 + sin(L/2)*cos(L/2)/2)
assert integrate(r0**2*cos(R0*z)**2, (z, -L/2, L/2)) == Piecewise(
(-r0**2*(-L*R0/4 - sin(L*R0/2)*cos(L*R0/2)/2)/R0 +
r0**2*(L*R0/4 + sin(L*R0/2)*cos(L*R0/2)/2)/R0, (R0 > -oo) & (R0 < oo) & Ne(R0, 0)),
(L*r0**2, True))
w = 2*pi*z/L
sol = sqrt(2)*sqrt(L)*r0**2*fresnelc(sqrt(2)*sqrt(L))*gamma(S.One/4)/(16*gamma(S(5)/4)) + L*r0**2/2
assert integrate(r0**2*cos(w*z)**2, (z, -L/2, L/2)) == sol
def test_issue_15810():
assert integrate(1/(2**(2*x/3) + 1), (x, 0, oo)) == Rational(3, 2)
def test_issue_21024():
x = Symbol('x', real=True, nonzero=True)
f = log(x)*log(4*x) + log(3*x + exp(2))
F = x*log(x)**2 + x*(1 - 2*log(2)) + (-2*x + 2*x*log(2))*log(x) + \
(x + exp(2)/6)*log(3*x + exp(2)) + exp(2)*log(3*x + exp(2))/6
assert F == integrate(f, x)
f = (x + exp(3))/x**2
F = log(x) - exp(3)/x
assert F == integrate(f, x)
f = (x**2 + exp(5))/x
F = x**2/2 + exp(5)*log(x)
assert F == integrate(f, x)
f = x/(2*x + tanh(1))
F = x/2 - log(2*x + tanh(1))*tanh(1)/4
assert F == integrate(f, x)
f = x - sinh(4)/x
F = x**2/2 - log(x)*sinh(4)
assert F == integrate(f, x)
f = log(x + exp(5)/x)
F = x*log(x + exp(5)/x) - x + 2*exp(Rational(5, 2))*atan(x*exp(Rational(-5, 2)))
assert F == integrate(f, x)
f = x**5/(x + E)
F = x**5/5 - E*x**4/4 + x**3*exp(2)/3 - x**2*exp(3)/2 + x*exp(4) - exp(5)*log(x + E)
assert F == integrate(f, x)
f = 4*x/(x + sinh(5))
F = 4*x - 4*log(x + sinh(5))*sinh(5)
assert F == integrate(f, x)
f = x**2/(2*x + sinh(2))
F = x**2/4 - x*sinh(2)/4 + log(2*x + sinh(2))*sinh(2)**2/8
assert F == integrate(f, x)
f = -x**2/(x + E)
F = -x**2/2 + E*x - exp(2)*log(x + E)
assert F == integrate(f, x)
f = (2*x + 3)*exp(5)/x
F = 2*x*exp(5) + 3*exp(5)*log(x)
assert F == integrate(f, x)
f = x + 2 + cosh(3)/x
F = x**2/2 + 2*x + log(x)*cosh(3)
assert F == integrate(f, x)
f = x - tanh(1)/x**3
F = x**2/2 + tanh(1)/(2*x**2)
assert F == integrate(f, x)
f = (3*x - exp(6))/x
F = 3*x - exp(6)*log(x)
assert F == integrate(f, x)
f = x**4/(x + exp(5))**2 + x
F = x**3/3 + x**2*(Rational(1, 2) - exp(5)) + 3*x*exp(10) - 4*exp(15)*log(x + exp(5)) - exp(20)/(x + exp(5))
assert F == integrate(f, x)
f = x*(x + exp(10)/x**2) + x
F = x**3/3 + x**2/2 + exp(10)*log(x)
assert F == integrate(f, x)
f = x + x/(5*x + sinh(3))
F = x**2/2 + x/5 - log(5*x + sinh(3))*sinh(3)/25
assert F == integrate(f, x)
f = (x + exp(3))/(2*x**2 + 2*x)
F = exp(3)*log(x)/2 - exp(3)*log(x + 1)/2 + log(x + 1)/2
assert F == integrate(f, x).expand()
f = log(x + 4*sinh(4))
F = x*log(x + 4*sinh(4)) - x + 4*log(x + 4*sinh(4))*sinh(4)
assert F == integrate(f, x)
f = -x + 20*(exp(-5) - atan(4)/x)**3*sin(4)/x
F = (-x**2*exp(15)/2 + 20*log(x)*sin(4) - (-180*x**2*exp(5)*sin(4)*atan(4) + 90*x*exp(10)*sin(4)*atan(4)**2 - \
20*exp(15)*sin(4)*atan(4)**3)/(3*x**3))*exp(-15)
assert F == integrate(f, x)
f = 2*x**2*exp(-4) + 6/x
F_true = (2*x**3/3 + 6*exp(4)*log(x))*exp(-4)
assert F_true == integrate(f, x)
def test_issue_21721():
a = Symbol('a')
assert integrate(1/(pi*(1+(x-a)**2)),(x,-oo,oo)).expand() == \
-Heaviside(im(a) - 1, 0) + Heaviside(im(a) + 1, 0)
def test_issue_21831():
theta = symbols('theta')
assert integrate(cos(3*theta)/(5-4*cos(theta)), (theta, 0, 2*pi)) == pi/12
integrand = cos(2*theta)/(5 - 4*cos(theta))
assert integrate(integrand, (theta, 0, 2*pi)) == pi/6
@slow
def test_issue_22033_integral():
assert integrate((x**2 - Rational(1, 4))**2 * sqrt(1 - x**2), (x, -1, 1)) == pi/32
@slow
def test_issue_21671():
assert integrate(1,(z,x**2+y**2,2-x**2-y**2),(y,-sqrt(1-x**2),sqrt(1-x**2)),(x,-1,1)) == pi
assert integrate(-4*(1 - x**2)**(S(3)/2)/3 + 2*sqrt(1 - x**2)*(2 - 2*x**2), (x, -1, 1)) == pi
def test_issue_18527():
# The manual integrator can not currently solve this. Assert that it does
# not give an incorrect result involving Abs when x has real assumptions.
xr = symbols('xr', real=True)
expr = (cos(x)/(4+(sin(x))**2))
res_real = integrate(expr.subs(x, xr), xr, manual=True).subs(xr, x)
assert integrate(expr, x, manual=True) == res_real == Integral(expr, x)
def test_issue_23718():
f = 1/(b*cos(x) + a*sin(x))
Fpos = (-log(-a/b + tan(x/2) - sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2)
+log(-a/b + tan(x/2) + sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2))
F = Piecewise(
# XXX: The zoo case here is for a=b=0 so it should just be zoo or maybe
# it doesn't really need to be included at all given that the original
# integrand is really undefined in that case anyway.
(zoo*(-log(tan(x/2) - 1) + log(tan(x/2) + 1)), Eq(a, 0) & Eq(b, 0)),
(log(tan(x/2))/a, Eq(b, 0)),
(-I/(-I*b*sin(x) + b*cos(x)), Eq(a, -I*b)),
(I/(I*b*sin(x) + b*cos(x)), Eq(a, I*b)),
(Fpos, True),
)
assert integrate(f, x) == F
ap, bp = symbols('a, b', positive=True)
rep = {a: ap, b: bp}
assert integrate(f.subs(rep), x) == Fpos.subs(rep)
def test_issue_23566():
i = integrate(1/sqrt(x**2-1), (x, -2, -1))
assert i == -log(2 - sqrt(3))
assert math.isclose(i.n(), 1.31695789692482)
def test_pr_23583():
# This result from meijerg is wrong. Check whether new result is correct when this test fail.
assert integrate(1/sqrt((x - I)**2-1)) == Piecewise((acosh(x - I), Abs((x - I)**2) > 1), (-I*asin(x - I), True))
def test_issue_7264():
assert integrate(exp(x)*sqrt(1 + exp(2*x))) == sqrt(exp(2*x) + 1)*exp(x)/2 + asinh(exp(x))/2
def test_issue_11254a():
assert integrate(sech(x), (x, 0, 1)) == 2*atan(tanh(S.Half))
def test_issue_11254b():
assert integrate(csch(x), x) == log(tanh(x/2))
assert integrate(csch(x), (x, 0, 1)) == oo
def test_issue_11254d():
assert integrate((sech(x)**2).rewrite(sinh), x) == 2*tanh(x/2)/(tanh(x/2)**2 + 1)
def test_issue_22863():
i = integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2), (x, 0, 1))
assert i == -101*sqrt(2)/8 - 135*log(3 - 2*sqrt(2))/16
assert math.isclose(i.n(), -2.98126694400554)
def test_issue_9723():
assert integrate(sqrt(x + sqrt(x))) == \
2*sqrt(sqrt(x) + x)*(sqrt(x)/12 + x/3 - S(1)/8) + log(2*sqrt(x) + 2*sqrt(sqrt(x) + x) + 1)/8
assert integrate(sqrt(2*x+3+sqrt(4*x+5))**3) == \
sqrt(2*x + sqrt(4*x + 5) + 3) * \
(9*x/10 + 11*(4*x + 5)**(S(3)/2)/40 + sqrt(4*x + 5)/40 + (4*x + 5)**2/10 + S(11)/10)/2
def test_issue_23704():
# XXX: This is testing that an exception is not raised in risch Ideally
# manualintegrate (manual=True) would be able to compute this but
# manualintegrate is very slow for this example so we don't test that here.
assert (integrate(log(x)/x**2/(c*x**2+b*x+a),x, risch=True)
== NonElementaryIntegral(log(x)/(a*x**2 + b*x**3 + c*x**4), x))
def test_exp_substitution():
assert integrate(1/sqrt(1-exp(2*x))) == log(sqrt(1 - exp(2*x)) - 1)/2 - log(sqrt(1 - exp(2*x)) + 1)/2
def test_hyperbolic():
assert integrate(coth(x)) == x - log(tanh(x) + 1) + log(tanh(x))
assert integrate(sech(x)) == 2*atan(tanh(x/2))
assert integrate(csch(x)) == log(tanh(x/2))
def test_nested_pow():
assert integrate(sqrt(x**2)) == x*sqrt(x**2)/2
def test_sqrt_quadratic():
assert integrate(1/sqrt(3*x**2+4*x+5)) == sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/3
assert integrate(1/sqrt(-3*x**2+4*x+5)) == sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/3
assert integrate(1/sqrt(3*x**2+4*x-5)) == sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/3
assert integrate(1/sqrt(a+b*x+c*x**2), x) == \
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
(2*sqrt(a + b*x)/b, Ne(b, 0)), (x/sqrt(a), True))
assert integrate((7*x+6)/sqrt(3*x**2+4*x+5)) == \
7*sqrt(3*x**2 + 4*x + 5)/3 + 4*sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/9
assert integrate((7*x+6)/sqrt(-3*x**2+4*x+5)) == \
-7*sqrt(-3*x**2 + 4*x + 5)/3 + 32*sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/9
assert integrate((7*x+6)/sqrt(3*x**2+4*x-5)) == \
7*sqrt(3*x**2 + 4*x - 5)/3 + 4*sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/9
assert integrate((d+e*x)/sqrt(a+b*x+c*x**2), x) == \
Piecewise((e*sqrt(a + b*x + c*x**2)/c +
(-b*e/(2*c) + d)*log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
((2*d*sqrt(a + b*x) + 2*e*(-a*sqrt(a + b*x) + (a + b*x)**(S(3)/2)/3)/b)/b, Ne(b, 0)),
((d*x + e*x**2/2)/sqrt(a), True))
assert integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2)) == \
sqrt(x**2 - 3*x + 2)*(x**2 + 13*x/4 + S(101)/8) + 135*log(2*x + 2*sqrt(x**2 - 3*x + 2) - 3)/16
assert integrate(sqrt(53225*x**2-66732*x+23013)) == \
(x/2 - S(16683)/53225)*sqrt(53225*x**2 - 66732*x + 23013) + \
111576969*sqrt(2129)*asinh(53225*x/10563 - S(11122)/3521)/1133160250
assert integrate(sqrt(a+b*x+c*x**2), x) == \
Piecewise(((x/2 + b/(4*c))*sqrt(a + b*x + c*x**2) +
(a/2 - b**2/(8*c))*log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
(2*(a + b*x)**(S(3)/2)/(3*b), Ne(b, 0)),
(sqrt(a)*x, True))
assert integrate(x*sqrt(x**2+2*x+4)) == \
(x**2/3 + x/6 + S(5)/6)*sqrt(x**2 + 2*x + 4) - 3*asinh(sqrt(3)*(x + 1)/3)/2
def test_mul_pow_derivative():
assert integrate(x*sec(x)*tan(x)) == x*sec(x) - log(tan(x) + sec(x))
assert integrate(x*sec(x)**2, x) == x*tan(x) + log(cos(x))
assert integrate(x**3*Derivative(f(x), (x, 4))) == \
x**3*Derivative(f(x), (x, 3)) - 3*x**2*Derivative(f(x), (x, 2)) + 6*x*Derivative(f(x), x) - 6*f(x)
|
1da5a0d099c4addacdccd9957f2cf6673e1702064f555a593ede8c6a9dec439f | """Most of these tests come from the examples in Bronstein's book."""
from sympy.core.function import (Function, Lambda, diff, expand_log)
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.relational import Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (atan, sin, tan)
from sympy.polys.polytools import (Poly, cancel, factor)
from sympy.integrals.risch import (gcdex_diophantine, frac_in, as_poly_1t,
derivation, splitfactor, splitfactor_sqf, canonical_representation,
hermite_reduce, polynomial_reduce, residue_reduce, residue_reduce_to_basic,
integrate_primitive, integrate_hyperexponential_polynomial,
integrate_hyperexponential, integrate_hypertangent_polynomial,
integrate_nonlinear_no_specials, integer_powers, DifferentialExtension,
risch_integrate, DecrementLevel, NonElementaryIntegral, recognize_log_derivative,
recognize_derivative, laurent_series)
from sympy.testing.pytest import raises
from sympy.abc import x, t, nu, z, a, y
t0, t1, t2 = symbols('t:3')
i = Symbol('i')
def test_gcdex_diophantine():
assert gcdex_diophantine(Poly(x**4 - 2*x**3 - 6*x**2 + 12*x + 15),
Poly(x**3 + x**2 - 4*x - 4), Poly(x**2 - 1)) == \
(Poly((-x**2 + 4*x - 3)/5), Poly((x**3 - 7*x**2 + 16*x - 10)/5))
assert gcdex_diophantine(Poly(x**3 + 6*x + 7), Poly(x**2 + 3*x + 2), Poly(x + 1)) == \
(Poly(1/13, x, domain='QQ'), Poly(-1/13*x + 3/13, x, domain='QQ'))
def test_frac_in():
assert frac_in(Poly((x + 1)/x*t, t), x) == \
(Poly(t*x + t, x), Poly(x, x))
assert frac_in((x + 1)/x*t, x) == \
(Poly(t*x + t, x), Poly(x, x))
assert frac_in((Poly((x + 1)/x*t, t), Poly(t + 1, t)), x) == \
(Poly(t*x + t, x), Poly((1 + t)*x, x))
raises(ValueError, lambda: frac_in((x + 1)/log(x)*t, x))
assert frac_in(Poly((2 + 2*x + x*(1 + x))/(1 + x)**2, t), x, cancel=True) == \
(Poly(x + 2, x), Poly(x + 1, x))
def test_as_poly_1t():
assert as_poly_1t(2/t + t, t, z) in [
Poly(t + 2*z, t, z), Poly(t + 2*z, z, t)]
assert as_poly_1t(2/t + 3/t**2, t, z) in [
Poly(2*z + 3*z**2, t, z), Poly(2*z + 3*z**2, z, t)]
assert as_poly_1t(2/((exp(2) + 1)*t), t, z) in [
Poly(2/(exp(2) + 1)*z, t, z), Poly(2/(exp(2) + 1)*z, z, t)]
assert as_poly_1t(2/((exp(2) + 1)*t) + t, t, z) in [
Poly(t + 2/(exp(2) + 1)*z, t, z), Poly(t + 2/(exp(2) + 1)*z, z, t)]
assert as_poly_1t(S.Zero, t, z) == Poly(0, t, z)
def test_derivation():
p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 +
(2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]})
assert derivation(p, DE) == Poly(-20*x**4*t**6 + (2*x**3 + 16*x**4)*t**5 +
(21*x**2 + 12*x**3)*t**4 + (x*Rational(7, 2) - 25*x**2 - 12*x**3)*t**3 +
(-5 - x*Rational(15, 2) + 7*x**2)*t**2 - (3 - 8*x - 10*x**2 - 4*x**3)/(2*x)*t +
(1 - 4*x**2)/(2*x), t)
assert derivation(Poly(1, t), DE) == Poly(0, t)
assert derivation(Poly(t, t), DE) == DE.d
assert derivation(Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t), DE) == \
Poly(-2*t**3 - 4/x*t**2 - (5 - 2*x)/(2*x**2)*t - (1 - 2*x)/(2*x**3), t, domain='ZZ(x)')
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t, t)]})
assert derivation(Poly(x*t*t1, t), DE) == Poly(t*t1 + x*t*t1 + t, t)
assert derivation(Poly(x*t*t1, t), DE, coefficientD=True) == \
Poly((1 + t1)*t, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert derivation(Poly(x, x), DE) == Poly(1, x)
# Test basic option
assert derivation((x + 1)/(x - 1), DE, basic=True) == -2/(1 - 2*x + x**2)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert derivation((t + 1)/(t - 1), DE, basic=True) == -2*t/(1 - 2*t + t**2)
assert derivation(t + 1, DE, basic=True) == t
def test_splitfactor():
p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 +
(2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t, field=True)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]})
assert splitfactor(p, DE) == (Poly(4*x**4*t**3 + (-8*x**3 - 4*x**4)*t**2 +
(4*x**2 + 8*x**3)*t - 4*x**2, t, domain='ZZ(x)'),
Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t, domain='ZZ(x)'))
assert splitfactor(Poly(x, t), DE) == (Poly(x, t), Poly(1, t))
r = Poly(-4*x**4*z**2 + 4*x**6*z**2 - z*x**3 - 4*x**5*z**3 + 4*x**3*z**3 + x**4 + z*x**5 - x**6, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
assert splitfactor(r, DE, coefficientD=True) == \
(Poly(x*z - x**2 - z*x**3 + x**4, t), Poly(-x**2 + 4*x**2*z**2, t))
assert splitfactor_sqf(r, DE, coefficientD=True) == \
(((Poly(x*z - x**2 - z*x**3 + x**4, t), 1),), ((Poly(-x**2 + 4*x**2*z**2, t), 1),))
assert splitfactor(Poly(0, t), DE) == (Poly(0, t), Poly(1, t))
assert splitfactor_sqf(Poly(0, t), DE) == (((Poly(0, t), 1),), ())
def test_canonical_representation():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
assert canonical_representation(Poly(x - t, t), Poly(t**2, t), DE) == \
(Poly(0, t, domain='ZZ[x]'), (Poly(0, t, domain='QQ[x]'),
Poly(1, t, domain='ZZ')), (Poly(-t + x, t, domain='QQ[x]'),
Poly(t**2, t)))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert canonical_representation(Poly(t**5 + t**3 + x**2*t + 1, t),
Poly((t**2 + 1)**3, t), DE) == \
(Poly(0, t, domain='ZZ[x]'), (Poly(t**5 + t**3 + x**2*t + 1, t, domain='QQ[x]'),
Poly(t**6 + 3*t**4 + 3*t**2 + 1, t, domain='QQ')),
(Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ')))
def test_hermite_reduce():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert hermite_reduce(Poly(x - t, t), Poly(t**2, t), DE) == \
((Poly(-x, t, domain='QQ[x]'), Poly(t, t, domain='QQ[x]')),
(Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]')),
(Poly(-x, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]')))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]})
assert hermite_reduce(
Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 - nu**2)*t - x**5/4, t),
Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t), DE) == \
((Poly(-x**2 - 4, t, domain='ZZ(x,nu)'), Poly(4*t**2 + 2*x**2 + 4, t, domain='ZZ(x,nu)')),
(Poly((-2*nu**2 - x**4)*t - (2*x**3 + 2*x), t, domain='ZZ(x,nu)'),
Poly(2*x**2*t**2 + x**4 + 2*x**2, t, domain='ZZ(x,nu)')),
(Poly(x*t + 1, t, domain='ZZ(x,nu)'), Poly(x, t, domain='ZZ(x,nu)')))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
a = Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t)
d = Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t)
assert hermite_reduce(a, d, DE) == \
((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'),
Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')),
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')))
assert hermite_reduce(
Poly(-t**2 + 2*t + 2, t, domain='ZZ(x)'),
Poly(-x*t**2 + 2*x*t - x, t, domain='ZZ(x)'), DE) == \
((Poly(3, t, domain='ZZ(x)'), Poly(t - 1, t, domain='ZZ(x)')),
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
(Poly(1, t, domain='ZZ(x)'), Poly(x, t, domain='ZZ(x)')))
assert hermite_reduce(
Poly(-x**2*t**6 + (-1 - 2*x**3 + x**4)*t**3 + (-3 - 3*x**4)*t**2 -
2*x*t - x - 3*x**2, t, domain='ZZ(x)'),
Poly(x**4*t**6 - 2*x**2*t**3 + 1, t, domain='ZZ(x)'), DE) == \
((Poly(x**3*t + x**4 + 1, t, domain='ZZ(x)'), Poly(x**3*t**3 - x, t, domain='ZZ(x)')),
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
(Poly(-1, t, domain='ZZ(x)'), Poly(x**2, t, domain='ZZ(x)')))
assert hermite_reduce(
Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t),
Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t), DE) == \
((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'),
Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')),
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')))
def test_polynomial_reduce():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
assert polynomial_reduce(Poly(1 + x*t + t**2, t), DE) == \
(Poly(t, t), Poly(x*t, t))
assert polynomial_reduce(Poly(0, t), DE) == \
(Poly(0, t), Poly(0, t))
def test_laurent_series():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]})
a = Poly(36, t)
d = Poly((t - 2)*(t**2 - 1)**2, t)
F = Poly(t**2 - 1, t)
n = 2
assert laurent_series(a, d, F, n, DE) == \
(Poly(-3*t**3 + 3*t**2 - 6*t - 8, t), Poly(t**5 + t**4 - 2*t**3 - 2*t**2 + t + 1, t),
[Poly(-3*t**3 - 6*t**2, t, domain='QQ'), Poly(2*t**6 + 6*t**5 - 8*t**3, t, domain='QQ')])
def test_recognize_derivative():
DE = DifferentialExtension(extension={'D': [Poly(1, t)]})
a = Poly(36, t)
d = Poly((t - 2)*(t**2 - 1)**2, t)
assert recognize_derivative(a, d, DE) == False
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
a = Poly(2, t)
d = Poly(t**2 - 1, t)
assert recognize_derivative(a, d, DE) == False
assert recognize_derivative(Poly(x*t, t), Poly(1, t), DE) == True
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert recognize_derivative(Poly(t, t), Poly(1, t), DE) == True
def test_recognize_log_derivative():
a = Poly(2*x**2 + 4*x*t - 2*t - x**2*t, t)
d = Poly((2*x + t)*(t + x**2), t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert recognize_log_derivative(a, d, DE, z) == True
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
assert recognize_log_derivative(Poly(t + 1, t), Poly(t + x, t), DE) == True
assert recognize_log_derivative(Poly(2, t), Poly(t**2 - 1, t), DE) == True
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert recognize_log_derivative(Poly(1, x), Poly(x**2 - 2, x), DE) == False
assert recognize_log_derivative(Poly(1, x), Poly(x**2 + x, x), DE) == True
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert recognize_log_derivative(Poly(1, t), Poly(t**2 - 2, t), DE) == False
assert recognize_log_derivative(Poly(1, t), Poly(t**2 + t, t), DE) == False
def test_residue_reduce():
a = Poly(2*t**2 - t - x**2, t)
d = Poly(t**3 - x**2*t, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)], 'Tfuncs': [log]})
assert residue_reduce(a, d, DE, z, invert=False) == \
([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'),
Poly((1 + 3*x*z - 6*z**2 - 2*x**2 + 4*x**2*z**2)*t - x*z + x**2 +
2*x**2*z**2 - 2*z*x**3, t, domain='ZZ(z, x)'))], False)
assert residue_reduce(a, d, DE, z, invert=True) == \
([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'), Poly(t + 2*x*z, t))], False)
assert residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t,), DE, z, invert=False) == \
([(Poly(z**2 - 1, z, domain='QQ'), Poly(-2*z*t/x - 2/x, t, domain='ZZ(z,x)'))], True)
ans = residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t), DE, z, invert=True)
assert ans == ([(Poly(z**2 - 1, z, domain='QQ'), Poly(t + z, t))], True)
assert residue_reduce_to_basic(ans[0], DE, z) == -log(-1 + log(x)) + log(1 + log(x))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]})
# TODO: Skip or make faster
assert residue_reduce(Poly((-2*nu**2 - x**4)/(2*x**2)*t - (1 + x**2)/x, t),
Poly(t**2 + 1 + x**2/2, t), DE, z) == \
([(Poly(z + S.Half, z, domain='QQ'), Poly(t**2 + 1 + x**2/2, t,
domain='ZZ(x,nu)'))], True)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
assert residue_reduce(Poly(-2*x*t + 1 - x**2, t),
Poly(t**2 + 2*x*t + 1 + x**2, t), DE, z) == \
([(Poly(z**2 + Rational(1, 4), z), Poly(t + x + 2*z, t))], True)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert residue_reduce(Poly(t, t), Poly(t + sqrt(2), t), DE, z) == \
([(Poly(z - 1, z, domain='QQ'), Poly(t + sqrt(2), t))], True)
def test_integrate_hyperexponential():
# TODO: Add tests for integrate_hyperexponential() from the book
a = Poly((1 + 2*t1 + t1**2 + 2*t1**3)*t**2 + (1 + t1**2)*t + 1 + t1**2, t)
d = Poly(1, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t1**2, t1),
Poly(t*(1 + t1**2), t)], 'Tfuncs': [tan, Lambda(i, exp(tan(i)))]})
assert integrate_hyperexponential(a, d, DE) == \
(exp(2*tan(x))*tan(x) + exp(tan(x)), 1 + t1**2, True)
a = Poly((t1**3 + (x + 1)*t1**2 + t1 + x + 2)*t, t)
assert integrate_hyperexponential(a, d, DE) == \
((x + tan(x))*exp(tan(x)), 0, True)
a = Poly(t, t)
d = Poly(1, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*x*t, t)],
'Tfuncs': [Lambda(i, exp(x**2))]})
assert integrate_hyperexponential(a, d, DE) == \
(0, NonElementaryIntegral(exp(x**2), x), False)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]})
assert integrate_hyperexponential(a, d, DE) == (exp(x), 0, True)
a = Poly(25*t**6 - 10*t**5 + 7*t**4 - 8*t**3 + 13*t**2 + 2*t - 1, t)
d = Poly(25*t**6 + 35*t**4 + 11*t**2 + 1, t)
assert integrate_hyperexponential(a, d, DE) == \
(-(11 - 10*exp(x))/(5 + 25*exp(2*x)) + log(1 + exp(2*x)), -1, True)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(t0*t, t)],
'Tfuncs': [exp, Lambda(i, exp(exp(i)))]})
assert integrate_hyperexponential(Poly(2*t0*t**2, t), Poly(1, t), DE) == (exp(2*exp(x)), 0, True)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(-t0*t, t)],
'Tfuncs': [exp, Lambda(i, exp(-exp(i)))]})
assert integrate_hyperexponential(Poly(-27*exp(9) - 162*t0*exp(9) +
27*x*t0*exp(9), t), Poly((36*exp(18) + x**2*exp(18) - 12*x*exp(18))*t, t), DE) == \
(27*exp(exp(x))/(-6*exp(9) + x*exp(9)), 0, True)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]})
assert integrate_hyperexponential(Poly(x**2/2*t, t), Poly(1, t), DE) == \
((2 - 2*x + x**2)*exp(x)/2, 0, True)
assert integrate_hyperexponential(Poly(1 + t, t), Poly(t, t), DE) == \
(-exp(-x), 1, True) # x - exp(-x)
assert integrate_hyperexponential(Poly(x, t), Poly(t + 1, t), DE) == \
(0, NonElementaryIntegral(x/(1 + exp(x)), x), False)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)],
'Tfuncs': [log, Lambda(i, exp(i**2))]})
elem, nonelem, b = integrate_hyperexponential(Poly((8*x**7 - 12*x**5 + 6*x**3 - x)*t1**4 +
(8*t0*x**7 - 8*t0*x**6 - 4*t0*x**5 + 2*t0*x**3 + 2*t0*x**2 - t0*x +
24*x**8 - 36*x**6 - 4*x**5 + 22*x**4 + 4*x**3 - 7*x**2 - x + 1)*t1**3
+ (8*t0*x**8 - 4*t0*x**6 - 16*t0*x**5 - 2*t0*x**4 + 12*t0*x**3 +
t0*x**2 - 2*t0*x + 24*x**9 - 36*x**7 - 8*x**6 + 22*x**5 + 12*x**4 -
7*x**3 - 6*x**2 + x + 1)*t1**2 + (8*t0*x**8 - 8*t0*x**6 - 16*t0*x**5 +
6*t0*x**4 + 10*t0*x**3 - 2*t0*x**2 - t0*x + 8*x**10 - 12*x**8 - 4*x**7
+ 2*x**6 + 12*x**5 + 3*x**4 - 9*x**3 - x**2 + 2*x)*t1 + 8*t0*x**7 -
12*t0*x**6 - 4*t0*x**5 + 8*t0*x**4 - t0*x**2 - 4*x**7 + 4*x**6 +
4*x**5 - 4*x**4 - x**3 + x**2, t1), Poly((8*x**7 - 12*x**5 + 6*x**3 -
x)*t1**4 + (24*x**8 + 8*x**7 - 36*x**6 - 12*x**5 + 18*x**4 + 6*x**3 -
3*x**2 - x)*t1**3 + (24*x**9 + 24*x**8 - 36*x**7 - 36*x**6 + 18*x**5 +
18*x**4 - 3*x**3 - 3*x**2)*t1**2 + (8*x**10 + 24*x**9 - 12*x**8 -
36*x**7 + 6*x**6 + 18*x**5 - x**4 - 3*x**3)*t1 + 8*x**10 - 12*x**8 +
6*x**6 - x**4, t1), DE)
assert factor(elem) == -((x - 1)*log(x)/((x + exp(x**2))*(2*x**2 - 1)))
assert (nonelem, b) == (NonElementaryIntegral(exp(x**2)/(exp(x**2) + 1), x), False)
def test_integrate_hyperexponential_polynomial():
# Without proper cancellation within integrate_hyperexponential_polynomial(),
# this will take a long time to complete, and will return a complicated
# expression
p = Poly((-28*x**11*t0 - 6*x**8*t0 + 6*x**9*t0 - 15*x**8*t0**2 +
15*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 20*x**6*t0**3 +
20*x**7*t0**3 - 15*x**6*t0**4 + 15*x**5*t0**4 + 140*x**8*t0**4 -
84*x**7*t0**5 - 6*x**4*t0**5 + 6*x**5*t0**5 + x**3*t0**6 - x**4*t0**6 +
28*x**6*t0**6 - 4*x**5*t0**7 + x**9 - x**10 + 4*x**12)/(-8*x**11*t0 +
28*x**10*t0**2 - 56*x**9*t0**3 + 70*x**8*t0**4 - 56*x**7*t0**5 +
28*x**6*t0**6 - 8*x**5*t0**7 + x**4*t0**8 + x**12)*t1**2 +
(-28*x**11*t0 - 12*x**8*t0 + 12*x**9*t0 - 30*x**8*t0**2 +
30*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 40*x**6*t0**3 +
40*x**7*t0**3 - 30*x**6*t0**4 + 30*x**5*t0**4 + 140*x**8*t0**4 -
84*x**7*t0**5 - 12*x**4*t0**5 + 12*x**5*t0**5 - 2*x**4*t0**6 +
2*x**3*t0**6 + 28*x**6*t0**6 - 4*x**5*t0**7 + 2*x**9 - 2*x**10 +
4*x**12)/(-8*x**11*t0 + 28*x**10*t0**2 - 56*x**9*t0**3 +
70*x**8*t0**4 - 56*x**7*t0**5 + 28*x**6*t0**6 - 8*x**5*t0**7 +
x**4*t0**8 + x**12)*t1 + (-2*x**2*t0 + 2*x**3*t0 + x*t0**2 -
x**2*t0**2 + x**3 - x**4)/(-4*x**5*t0 + 6*x**4*t0**2 - 4*x**3*t0**3 +
x**2*t0**4 + x**6), t1, z, expand=False)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)]})
assert integrate_hyperexponential_polynomial(p, DE, z) == (
Poly((x - t0)*t1**2 + (-2*t0 + 2*x)*t1, t1), Poly(-2*x*t0 + x**2 +
t0**2, t1), True)
DE = DifferentialExtension(extension={'D':[Poly(1, x), Poly(t0, t0)]})
assert integrate_hyperexponential_polynomial(Poly(0, t0), DE, z) == (
Poly(0, t0), Poly(1, t0), True)
def test_integrate_hyperexponential_returns_piecewise():
a, b = symbols('a b')
DE = DifferentialExtension(a**x, x)
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
(exp(x*log(a))/log(a), Ne(log(a), 0)), (x, True)), 0, True)
DE = DifferentialExtension(a**(b*x), x)
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
(exp(b*x*log(a))/(b*log(a)), Ne(b*log(a), 0)), (x, True)), 0, True)
DE = DifferentialExtension(exp(a*x), x)
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
(exp(a*x)/a, Ne(a, 0)), (x, True)), 0, True)
DE = DifferentialExtension(x*exp(a*x), x)
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
((a*x - 1)*exp(a*x)/a**2, Ne(a**2, 0)), (x**2/2, True)), 0, True)
DE = DifferentialExtension(x**2*exp(a*x), x)
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
((x**2*a**2 - 2*a*x + 2)*exp(a*x)/a**3, Ne(a**3, 0)),
(x**3/3, True)), 0, True)
DE = DifferentialExtension(x**y + z, y)
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
(exp(log(x)*y)/log(x), Ne(log(x), 0)), (y, True)), z, True)
DE = DifferentialExtension(x**y + z + x**(2*y), y)
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
((exp(2*log(x)*y)*log(x) +
2*exp(log(x)*y)*log(x))/(2*log(x)**2), Ne(2*log(x)**2, 0)),
(2*y, True),
), z, True)
# TODO: Add a test where two different parts of the extension use a
# Piecewise, like y**x + z**x.
def test_issue_13947():
a, t, s = symbols('a t s')
assert risch_integrate(2**(-pi)/(2**t + 1), t) == \
2**(-pi)*t - 2**(-pi)*log(2**t + 1)/log(2)
assert risch_integrate(a**(t - s)/(a**t + 1), t) == \
exp(-s*log(a))*log(a**t + 1)/log(a)
def test_integrate_primitive():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)],
'Tfuncs': [log]})
assert integrate_primitive(Poly(t, t), Poly(1, t), DE) == (x*log(x), -1, True)
assert integrate_primitive(Poly(x, t), Poly(t, t), DE) == (0, NonElementaryIntegral(x/log(x), x), False)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)],
'Tfuncs': [log, Lambda(i, log(i + 1))]})
assert integrate_primitive(Poly(t1, t2), Poly(t2, t2), DE) == \
(0, NonElementaryIntegral(log(x)/log(1 + x), x), False)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x*t1), t2)],
'Tfuncs': [log, Lambda(i, log(log(i)))]})
assert integrate_primitive(Poly(t2, t2), Poly(t1, t2), DE) == \
(0, NonElementaryIntegral(log(log(x))/log(x), x), False)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0)],
'Tfuncs': [log]})
assert integrate_primitive(Poly(x**2*t0**3 + (3*x**2 + x)*t0**2 + (3*x**2
+ 2*x)*t0 + x**2 + x, t0), Poly(x**2*t0**4 + 4*x**2*t0**3 + 6*x**2*t0**2 +
4*x**2*t0 + x**2, t0), DE) == \
(-1/(log(x) + 1), NonElementaryIntegral(1/(log(x) + 1), x), False)
def test_integrate_hypertangent_polynomial():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert integrate_hypertangent_polynomial(Poly(t**2 + x*t + 1, t), DE) == \
(Poly(t, t), Poly(x/2, t))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(a*(t**2 + 1), t)]})
assert integrate_hypertangent_polynomial(Poly(t**5, t), DE) == \
(Poly(1/(4*a)*t**4 - 1/(2*a)*t**2, t), Poly(1/(2*a), t))
def test_integrate_nonlinear_no_specials():
a, d, = Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 -
nu**2)*t - x**5/4, t), Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t)
# f(x) == phi_nu(x), the logarithmic derivative of J_v, the Bessel function,
# which has no specials (see Chapter 5, note 4 of Bronstein's book).
f = Function('phi_nu')
DE = DifferentialExtension(extension={'D': [Poly(1, x),
Poly(-t**2 - t/x - (1 - nu**2/x**2), t)], 'Tfuncs': [f]})
assert integrate_nonlinear_no_specials(a, d, DE) == \
(-log(1 + f(x)**2 + x**2/2)/2 + (- 4 - x**2)/(4 + 2*x**2 + 4*f(x)**2), True)
assert integrate_nonlinear_no_specials(Poly(t, t), Poly(1, t), DE) == \
(0, False)
def test_integer_powers():
assert integer_powers([x, x/2, x**2 + 1, x*Rational(2, 3)]) == [
(x/6, [(x, 6), (x/2, 3), (x*Rational(2, 3), 4)]),
(1 + x**2, [(1 + x**2, 1)])]
def test_DifferentialExtension_exp():
assert DifferentialExtension(exp(x) + exp(x**2), x)._important_attrs == \
(Poly(t1 + t0, t1), Poly(1, t1), [Poly(1, x,), Poly(t0, t0),
Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
assert DifferentialExtension(exp(x) + exp(2*x), x)._important_attrs == \
(Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0, t0)], [x, t0],
[Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
assert DifferentialExtension(exp(x) + exp(x/2), x)._important_attrs == \
(Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)],
[x, t0], [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2), x)._important_attrs == \
(Poly((1 + t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2 + 1), x)._important_attrs == \
(Poly((1 + S.Exp1*t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x),
Poly(t0, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2), x)._important_attrs == \
(Poly((t0 + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1],
[Lambda(i, exp(i/2)), Lambda(i, exp(i**2))],
[(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'], [None, x/2, x**2])
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2 + 3), x)._important_attrs == \
(Poly((t0*exp(3) + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i/2)),
Lambda(i, exp(i**2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'],
[None, x/2, x**2])
assert DifferentialExtension(sqrt(exp(x)), x)._important_attrs == \
(Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
[Lambda(i, exp(i/2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp'], [None, x/2])
assert DifferentialExtension(exp(x/2), x)._important_attrs == \
(Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
[Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
def test_DifferentialExtension_log():
assert DifferentialExtension(log(x)*log(x + 1)*log(2*x**2 + 2*x), x)._important_attrs == \
(Poly(t0*t1**2 + (t0*log(2) + t0**2)*t1, t1), Poly(1, t1),
[Poly(1, x), Poly(1/x, t0),
Poly(1/(x + 1), t1, expand=False)], [x, t0, t1],
[Lambda(i, log(i)), Lambda(i, log(i + 1))], [], [None, 'log', 'log'],
[None, x, x + 1])
assert DifferentialExtension(x**x*log(x), x)._important_attrs == \
(Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0),
Poly((1 + t0)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)),
Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)], [None, 'log', 'exp'],
[None, x, t0*x])
def test_DifferentialExtension_symlog():
# See comment on test_risch_integrate below
assert DifferentialExtension(log(x**x), x)._important_attrs == \
(Poly(t0*x, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly((t0 +
1)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i*t0))],
[(exp(x*log(x)), x**x)], [None, 'log', 'exp'], [None, x, t0*x])
assert DifferentialExtension(log(x**y), x)._important_attrs == \
(Poly(y*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
[Lambda(i, log(i))], [(y*log(x), log(x**y))], [None, 'log'],
[None, x])
assert DifferentialExtension(log(sqrt(x)), x)._important_attrs == \
(Poly(t0, t0), Poly(2, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
[Lambda(i, log(i))], [(log(x)/2, log(sqrt(x)))], [None, 'log'],
[None, x])
def test_DifferentialExtension_handle_first():
assert DifferentialExtension(exp(x)*log(x), x, handle_first='log')._important_attrs == \
(Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0),
Poly(t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i))],
[], [None, 'log', 'exp'], [None, x, x])
assert DifferentialExtension(exp(x)*log(x), x, handle_first='exp')._important_attrs == \
(Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
Poly(1/x, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, log(i))],
[], [None, 'exp', 'log'], [None, x, x])
# This one must have the log first, regardless of what we set it to
# (because the log is inside of the exponential: x**x == exp(x*log(x)))
assert DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
handle_first='exp')._important_attrs == \
DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
handle_first='log')._important_attrs == \
(Poly((-1 + x - x*t0**2)*t1, t1), Poly(x, t1),
[Poly(1, x), Poly(1/x, t0), Poly((1 + t0)*t1, t1)], [x, t0, t1],
[Lambda(i, log(i)), Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)],
[None, 'log', 'exp'], [None, x, t0*x])
def test_DifferentialExtension_all_attrs():
# Test 'unimportant' attributes
DE = DifferentialExtension(exp(x)*log(x), x, handle_first='exp')
assert DE.f == exp(x)*log(x)
assert DE.newf == t0*t1
assert DE.x == x
assert DE.cases == ['base', 'exp', 'primitive']
assert DE.case == 'primitive'
assert DE.level == -1
assert DE.t == t1 == DE.T[DE.level]
assert DE.d == Poly(1/x, t1) == DE.D[DE.level]
raises(ValueError, lambda: DE.increment_level())
DE.decrement_level()
assert DE.level == -2
assert DE.t == t0 == DE.T[DE.level]
assert DE.d == Poly(t0, t0) == DE.D[DE.level]
assert DE.case == 'exp'
DE.decrement_level()
assert DE.level == -3
assert DE.t == x == DE.T[DE.level] == DE.x
assert DE.d == Poly(1, x) == DE.D[DE.level]
assert DE.case == 'base'
raises(ValueError, lambda: DE.decrement_level())
DE.increment_level()
DE.increment_level()
assert DE.level == -1
assert DE.t == t1 == DE.T[DE.level]
assert DE.d == Poly(1/x, t1) == DE.D[DE.level]
assert DE.case == 'primitive'
# Test methods
assert DE.indices('log') == [2]
assert DE.indices('exp') == [1]
def test_DifferentialExtension_extension_flag():
raises(ValueError, lambda: DifferentialExtension(extension={'T': [x, t]}))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t],
None, None, None, None)
assert DE.d == Poly(t, t)
assert DE.t == t
assert DE.level == -1
assert DE.cases == ['base', 'exp']
assert DE.x == x
assert DE.case == 'exp'
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)],
'exts': [None, 'exp'], 'extargs': [None, x]})
assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t],
None, None, [None, 'exp'], [None, x])
raises(ValueError, lambda: DifferentialExtension())
def test_DifferentialExtension_misc():
# Odd ends
assert DifferentialExtension(sin(y)*exp(x), x)._important_attrs == \
(Poly(sin(y)*t0, t0, domain='ZZ[sin(y)]'), Poly(1, t0, domain='ZZ'),
[Poly(1, x, domain='ZZ'), Poly(t0, t0, domain='ZZ')], [x, t0],
[Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
raises(NotImplementedError, lambda: DifferentialExtension(sin(x), x))
assert DifferentialExtension(10**x, x)._important_attrs == \
(Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(log(10)*t0, t0)], [x, t0],
[Lambda(i, exp(i*log(10)))], [(exp(x*log(10)), 10**x)], [None, 'exp'],
[None, x*log(10)])
assert DifferentialExtension(log(x) + log(x**2), x)._important_attrs in [
(Poly(3*t0, t0), Poly(2, t0), [Poly(1, x), Poly(2/x, t0)], [x, t0],
[Lambda(i, log(i**2))], [], [None, ], [], [1], [x**2]),
(Poly(3*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
[Lambda(i, log(i))], [], [None, 'log'], [None, x])]
assert DifferentialExtension(S.Zero, x)._important_attrs == \
(Poly(0, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
assert DifferentialExtension(tan(atan(x).rewrite(log)), x)._important_attrs == \
(Poly(x, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
def test_DifferentialExtension_Rothstein():
# Rothstein's integral
f = (2581284541*exp(x) + 1757211400)/(39916800*exp(3*x) +
119750400*exp(x)**2 + 119750400*exp(x) + 39916800)*exp(1/(exp(x) + 1) - 10*x)
assert DifferentialExtension(f, x)._important_attrs == \
(Poly((1757211400 + 2581284541*t0)*t1, t1), Poly(39916800 +
119750400*t0 + 119750400*t0**2 + 39916800*t0**3, t1),
[Poly(1, x), Poly(t0, t0), Poly(-(10 + 21*t0 + 10*t0**2)/(1 + 2*t0 +
t0**2)*t1, t1, domain='ZZ(t0)')], [x, t0, t1],
[Lambda(i, exp(i)), Lambda(i, exp(1/(t0 + 1) - 10*i))], [],
[None, 'exp', 'exp'], [None, x, 1/(t0 + 1) - 10*x])
class _TestingException(Exception):
"""Dummy Exception class for testing."""
pass
def test_DecrementLevel():
DE = DifferentialExtension(x*log(exp(x) + 1), x)
assert DE.level == -1
assert DE.t == t1
assert DE.d == Poly(t0/(t0 + 1), t1)
assert DE.case == 'primitive'
with DecrementLevel(DE):
assert DE.level == -2
assert DE.t == t0
assert DE.d == Poly(t0, t0)
assert DE.case == 'exp'
with DecrementLevel(DE):
assert DE.level == -3
assert DE.t == x
assert DE.d == Poly(1, x)
assert DE.case == 'base'
assert DE.level == -2
assert DE.t == t0
assert DE.d == Poly(t0, t0)
assert DE.case == 'exp'
assert DE.level == -1
assert DE.t == t1
assert DE.d == Poly(t0/(t0 + 1), t1)
assert DE.case == 'primitive'
# Test that __exit__ is called after an exception correctly
try:
with DecrementLevel(DE):
raise _TestingException
except _TestingException:
pass
else:
raise AssertionError("Did not raise.")
assert DE.level == -1
assert DE.t == t1
assert DE.d == Poly(t0/(t0 + 1), t1)
assert DE.case == 'primitive'
def test_risch_integrate():
assert risch_integrate(t0*exp(x), x) == t0*exp(x)
assert risch_integrate(sin(x), x, rewrite_complex=True) == -exp(I*x)/2 - exp(-I*x)/2
# From my GSoC writeup
assert risch_integrate((1 + 2*x**2 + x**4 + 2*x**3*exp(2*x**2))/
(x**4*exp(x**2) + 2*x**2*exp(x**2) + exp(x**2)), x) == \
NonElementaryIntegral(exp(-x**2), x) + exp(x**2)/(1 + x**2)
assert risch_integrate(0, x) == 0
# also tests prde_cancel()
e1 = log(x/exp(x) + 1)
ans1 = risch_integrate(e1, x)
assert ans1 == (x*log(x*exp(-x) + 1) + NonElementaryIntegral((x**2 - x)/(x + exp(x)), x))
assert cancel(diff(ans1, x) - e1) == 0
# also tests issue #10798
e2 = (log(-1/y)/2 - log(1/y)/2)/y - (log(1 - 1/y)/2 - log(1 + 1/y)/2)/y
ans2 = risch_integrate(e2, y)
assert ans2 == log(1/y)*log(1 - 1/y)/2 - log(1/y)*log(1 + 1/y)/2 + \
NonElementaryIntegral((I*pi*y**2 - 2*y*log(1/y) - I*pi)/(2*y**3 - 2*y), y)
assert expand_log(cancel(diff(ans2, y) - e2), force=True) == 0
# These are tested here in addition to in test_DifferentialExtension above
# (symlogs) to test that backsubs works correctly. The integrals should be
# written in terms of the original logarithms in the integrands.
# XXX: Unfortunately, making backsubs work on this one is a little
# trickier, because x**x is converted to exp(x*log(x)), and so log(x**x)
# is converted to x*log(x). (x**2*log(x)).subs(x*log(x), log(x**x)) is
# smart enough, the issue is that these splits happen at different places
# in the algorithm. Maybe a heuristic is in order
assert risch_integrate(log(x**x), x) == x**2*log(x)/2 - x**2/4
assert risch_integrate(log(x**y), x) == x*log(x**y) - x*y
assert risch_integrate(log(sqrt(x)), x) == x*log(sqrt(x)) - x/2
def test_risch_integrate_float():
assert risch_integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) == -2.4*exp(8*x) - 12.0*exp(5*x)
def test_NonElementaryIntegral():
assert isinstance(risch_integrate(exp(x**2), x), NonElementaryIntegral)
assert isinstance(risch_integrate(x**x*log(x), x), NonElementaryIntegral)
# Make sure methods of Integral still give back a NonElementaryIntegral
assert isinstance(NonElementaryIntegral(x**x*t0, x).subs(t0, log(x)), NonElementaryIntegral)
def test_xtothex():
a = risch_integrate(x**x, x)
assert a == NonElementaryIntegral(x**x, x)
assert isinstance(a, NonElementaryIntegral)
def test_DifferentialExtension_equality():
DE1 = DE2 = DifferentialExtension(log(x), x)
assert DE1 == DE2
def test_DifferentialExtension_printing():
DE = DifferentialExtension(exp(2*x**2) + log(exp(x**2) + 1), x)
assert repr(DE) == ("DifferentialExtension(dict([('f', exp(2*x**2) + log(exp(x**2) + 1)), "
"('x', x), ('T', [x, t0, t1]), ('D', [Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), "
"Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]), ('fa', Poly(t1 + t0**2, t1, domain='ZZ[t0]')), "
"('fd', Poly(1, t1, domain='ZZ')), ('Tfuncs', [Lambda(i, exp(i**2)), Lambda(i, log(t0 + 1))]), "
"('backsubs', []), ('exts', [None, 'exp', 'log']), ('extargs', [None, x**2, t0 + 1]), "
"('cases', ['base', 'exp', 'primitive']), ('case', 'primitive'), ('t', t1), "
"('d', Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')), ('newf', t0**2 + t1), ('level', -1), "
"('dummy', False)]))")
assert str(DE) == ("DifferentialExtension({fa=Poly(t1 + t0**2, t1, domain='ZZ[t0]'), "
"fd=Poly(1, t1, domain='ZZ'), D=[Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), "
"Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]})")
def test_issue_23948():
f = (
( (-2*x**5 + 28*x**4 - 144*x**3 + 324*x**2 - 270*x)*log(x)**2
+(-4*x**6 + 56*x**5 - 288*x**4 + 648*x**3 - 540*x**2)*log(x)
+(2*x**5 - 28*x**4 + 144*x**3 - 324*x**2 + 270*x)*exp(x)
+(2*x**5 - 28*x**4 + 144*x**3 - 324*x**2 + 270*x)*log(5)
-2*x**7 + 26*x**6 - 116*x**5 + 180*x**4 + 54*x**3 - 270*x**2
)*log(-log(x)**2 - 2*x*log(x) + exp(x) + log(5) - x**2 - x)**2
+( (4*x**5 - 44*x**4 + 168*x**3 - 216*x**2 - 108*x + 324)*log(x)
+(-2*x**5 + 24*x**4 - 108*x**3 + 216*x**2 - 162*x)*exp(x)
+4*x**6 - 42*x**5 + 144*x**4 - 108*x**3 - 324*x**2 + 486*x
)*log(-log(x)**2 - 2*x*log(x) + exp(x) + log(5) - x**2 - x)
)/(x*exp(x)**2*log(x)**2 + 2*x**2*exp(x)**2*log(x) - x*exp(x)**3
+(-x*log(5) + x**3 + x**2)*exp(x)**2)
F = ((x**4 - 12*x**3 + 54*x**2 - 108*x + 81)*exp(-2*x)
*log(-x**2 - 2*x*log(x) - x + exp(x) - log(x)**2 + log(5))**2)
assert risch_integrate(f, x) == F
|
a99dc6ab3876de4b6869daaef6ad37895037e5567f64daf5a7e5c39e521edad7 | from sympy.core.function import expand_func
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.functions.elementary.complexes import Abs, arg, re, unpolarify
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import cosh, acosh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.trigonometric import (cos, sin, sinc, asin)
from sympy.functions.special.error_functions import (erf, erfc)
from sympy.functions.special.gamma_functions import (gamma, polygamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.integrals.integrals import (Integral, integrate)
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.simplify import simplify
from sympy.integrals.meijerint import (_rewrite_single, _rewrite1,
meijerint_indefinite, _inflate_g, _create_lookup_table,
meijerint_definite, meijerint_inversion)
from sympy.testing.pytest import slow
from sympy.core.random import (verify_numerically,
random_complex_number as randcplx)
from sympy.abc import x, y, a, b, c, d, s, t, z
def test_rewrite_single():
def t(expr, c, m):
e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x)
assert e is not None
assert isinstance(e[0][0][2], meijerg)
assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,))
def tn(expr):
assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None
t(x, 1, x)
t(x**2, 1, x**2)
t(x**2 + y*x**2, y + 1, x**2)
tn(x**2 + x)
tn(x**y)
def u(expr, x):
from sympy.core.add import Add
r = _rewrite_single(expr, x)
e = Add(*[res[0]*res[2] for res in r[0]]).replace(
exp_polar, exp) # XXX Hack?
assert verify_numerically(e, expr, x)
u(exp(-x)*sin(x), x)
# The following has stopped working because hyperexpand changed slightly.
# It is probably not worth fixing
#u(exp(-x)*sin(x)*cos(x), x)
# This one cannot be done numerically, since it comes out as a g-function
# of argument 4*pi
# NOTE This also tests a bug in inverse mellin transform (which used to
# turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of
# exp_polar).
#u(exp(x)*sin(x), x)
assert _rewrite_single(exp(x)*sin(x), x) == \
([(-sqrt(2)/(2*sqrt(pi)), 0,
meijerg(((Rational(-1, 2), 0, Rational(1, 4), S.Half, Rational(3, 4)), (1,)),
((), (Rational(-1, 2), 0)), 64*exp_polar(-4*I*pi)/x**4))], True)
def test_rewrite1():
assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \
(5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True)
def test_meijerint_indefinite_numerically():
def t(fac, arg):
g = meijerg([a], [b], [c], [d], arg)*fac
subs = {a: randcplx()/10, b: randcplx()/10 + I,
c: randcplx(), d: randcplx()}
integral = meijerint_indefinite(g, x)
assert integral is not None
assert verify_numerically(g.subs(subs), integral.diff(x).subs(subs), x)
t(1, x)
t(2, x)
t(1, 2*x)
t(1, x**2)
t(5, x**S('3/2'))
t(x**3, x)
t(3*x**S('3/2'), 4*x**S('7/3'))
def test_meijerint_definite():
v, b = meijerint_definite(x, x, 0, 0)
assert v.is_zero and b is True
v, b = meijerint_definite(x, x, oo, oo)
assert v.is_zero and b is True
def test_inflate():
subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(),
d: randcplx(), y: randcplx()/10}
def t(a, b, arg, n):
from sympy.core.mul import Mul
m1 = meijerg(a, b, arg)
m2 = Mul(*_inflate_g(m1, n))
# NOTE: (the random number)**9 must still be on the principal sheet.
# Thus make b&d small to create random numbers of small imaginary part.
return verify_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1)
assert t([[a], [b]], [[c], [d]], x, 3)
assert t([[a, y], [b]], [[c], [d]], x, 3)
assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3)
def test_recursive():
from sympy.core.symbol import symbols
a, b, c = symbols('a b c', positive=True)
r = exp(-(x - a)**2)*exp(-(x - b)**2)
e = integrate(r, (x, 0, oo), meijerg=True)
assert simplify(e.expand()) == (
sqrt(2)*sqrt(pi)*(
(erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4)
e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo), meijerg=True)
assert simplify(e) == (
sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2
+ (2*a + 2*b + c)**2/8)/4)
assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo), meijerg=True)) == \
sqrt(pi)/2*(1 + erf(a + b + c))
assert simplify(integrate(exp(-(x + a + b + c)**2), (x, 0, oo), meijerg=True)) == \
sqrt(pi)/2*(1 - erf(a + b + c))
@slow
def test_meijerint():
from sympy.core.function import expand
from sympy.core.symbol import symbols
s, t, mu = symbols('s t mu', real=True)
assert integrate(meijerg([], [], [0], [], s*t)
*meijerg([], [], [mu/2], [-mu/2], t**2/4),
(t, 0, oo)).is_Piecewise
s = symbols('s', positive=True)
assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \
gamma(s + 1)
assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo),
meijerg=True) == gamma(s + 1)
assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x),
(x, 0, oo), meijerg=False),
Integral)
assert meijerint_indefinite(exp(x), x) == exp(x)
# TODO what simplifications should be done automatically?
# This tests "extra case" for antecedents_1.
a, b = symbols('a b', positive=True)
assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \
b**(a + 1)/(a + 1)
# This tests various conditions and expansions:
assert meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True)
# Again, how about simplifications?
sigma, mu = symbols('sigma mu', positive=True)
i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo)
assert simplify(i) == sqrt(pi)*sigma*(2 - erfc(mu/(2*sigma)))
assert c == True
i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo)
# TODO it would be nice to test the condition
assert simplify(i) == 1/(mu - sigma)
# Test substitutions to change limits
assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True)
# Note: causes a NaN in _check_antecedents
assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1
assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \
1 - exp(-exp(I*arg(x))*abs(x))
# Test -oo to oo
assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True)
assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True)
assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \
(sqrt(pi)/2, True)
assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True)
assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2),
x, -oo, oo) == (1, True)
assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True)
# Test one of the extra conditions for 2 g-functinos
assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S.Half, True)
# Test a bug
def res(n):
return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n
for n in range(6):
assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \
res(n)
# This used to test trigexpand... now it is done by linear substitution
assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True)
) == sqrt(2)*sin(a + pi/4)/2
# Test the condition 14 from prudnikov.
# (This is besselj*besselj in disguise, to stop the product from being
# recognised in the tables.)
a, b, s = symbols('a b s')
assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4)
*meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo
) == (
(4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
/(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
*gamma(a/2 + b/2 - s + 1)),
(re(s) < 1) & (re(s) < S(1)/2) & (re(a)/2 + re(b)/2 + re(s) > 0)))
# test a bug
assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \
Integral(sin(x**a)*sin(x**b), (x, 0, oo))
# test better hyperexpand
assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \
(sqrt(pi)*polygamma(0, S.Half)/4).expand()
# Test hyperexpand bug.
from sympy.functions.special.gamma_functions import lowergamma
n = symbols('n', integer=True)
assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \
lowergamma(n + 1, x)
# Test a bug with argument 1/x
alpha = symbols('alpha', positive=True)
assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \
(sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S.Half,
alpha/2 + 1)), ((0, 0, S.Half), (Rational(-1, 2),)), alpha**2/16)/4, True)
# test a bug related to 3016
a, s = symbols('a s', positive=True)
assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \
a**(-s/2 - S.Half)*((-1)**s + 1)*gamma(s/2 + S.Half)/2
def test_bessel():
from sympy.functions.special.bessel import (besseli, besselj)
assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo),
meijerg=True, conds='none')) == \
2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b))
assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo),
meijerg=True, conds='none')) == 1/(2*a)
# TODO more orthogonality integrals
assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S.Half)),
(x, 1, oo), meijerg=True, conds='none')
*2/((z/2)**y*sqrt(pi)*gamma(S.Half - y))) == \
besselj(y, z)
# Werner Rosenheinrich
# SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS
assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x)
assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x)
# TODO can do higher powers, but come out as high order ... should they be
# reduced to order 0, 1?
assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x)
assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \
-(besselj(0, x)**2 + besselj(1, x)**2)/2
# TODO more besseli when tables are extended or recursive mellin works
assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \
-2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \
+ 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x
assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \
-besselj(0, x)**2/2
assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \
x**2*besselj(1, x)**2/2
assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \
(x*besselj(0, x)**2 + x*besselj(1, x)**2 -
besselj(0, x)*besselj(1, x))
# TODO how does besselj(0, a*x)*besselj(0, b*x) work?
# TODO how does besselj(0, x)**2*besselj(1, x)**2 work?
# TODO sin(x)*besselj(0, x) etc come out a mess
# TODO can x*log(x)*besselj(0, x) be done?
# TODO how does besselj(1, x)*besselj(0, x+a) work?
# TODO more indefinite integrals when struve functions etc are implemented
# test a substitution
assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \
-besselj(0, x**2)/2
def test_inversion():
from sympy.functions.special.bessel import besselj
from sympy.functions.special.delta_functions import Heaviside
def inv(f):
return piecewise_fold(meijerint_inversion(f, s, t))
assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t)
assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t)
assert inv(exp(-s)/s) == Heaviside(t - 1)
assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t)
# Test some antcedents checking.
assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None
assert inv(exp(s**2)) is None
assert meijerint_inversion(exp(-s**2), s, t) is None
def test_inversion_conditional_output():
from sympy.core.symbol import Symbol
from sympy.integrals.transforms import InverseLaplaceTransform
a = Symbol('a', positive=True)
F = sqrt(pi/a)*exp(-2*sqrt(a)*sqrt(s))
f = meijerint_inversion(F, s, t)
assert not f.is_Piecewise
b = Symbol('b', real=True)
F = F.subs(a, b)
f2 = meijerint_inversion(F, s, t)
assert f2.is_Piecewise
# first piece is same as f
assert f2.args[0][0] == f.subs(a, b)
# last piece is an unevaluated transform
assert f2.args[-1][1]
ILT = InverseLaplaceTransform(F, s, t, None)
assert f2.args[-1][0] == ILT or f2.args[-1][0] == ILT.as_integral
def test_inversion_exp_real_nonreal_shift():
from sympy.core.symbol import Symbol
from sympy.functions.special.delta_functions import DiracDelta
r = Symbol('r', real=True)
c = Symbol('c', extended_real=False)
a = 1 + 2*I
z = Symbol('z')
assert not meijerint_inversion(exp(r*s), s, t).is_Piecewise
assert meijerint_inversion(exp(a*s), s, t) is None
assert meijerint_inversion(exp(c*s), s, t) is None
f = meijerint_inversion(exp(z*s), s, t)
assert f.is_Piecewise
assert isinstance(f.args[0][0], DiracDelta)
@slow
def test_lookup_table():
from sympy.core.random import uniform, randrange
from sympy.core.add import Add
from sympy.integrals.meijerint import z as z_dummy
table = {}
_create_lookup_table(table)
for _, l in sorted(table.items()):
for formula, terms, cond, hint in sorted(l, key=default_sort_key):
subs = {}
for ai in list(formula.free_symbols) + [z_dummy]:
if hasattr(ai, 'properties') and ai.properties:
# these Wilds match positive integers
subs[ai] = randrange(1, 10)
else:
subs[ai] = uniform(1.5, 2.0)
if not isinstance(terms, list):
terms = terms(subs)
# First test that hyperexpand can do this.
expanded = [hyperexpand(g) for (_, g) in terms]
assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded)
# Now test that the meijer g-function is indeed as advertised.
expanded = Add(*[f*x for (f, x) in terms])
a, b = formula.n(subs=subs), expanded.n(subs=subs)
r = min(abs(a), abs(b))
if r < 1:
assert abs(a - b).n() <= 1e-10
else:
assert (abs(a - b)/r).n() <= 1e-10
def test_branch_bug():
from sympy.functions.special.gamma_functions import lowergamma
from sympy.simplify.powsimp import powdenest
# TODO gammasimp cannot prove that the factor is unity
assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x),
polar=True) == 2*erf(x**3)*gamma(Rational(2, 3))/3/gamma(Rational(5, 3))
assert integrate(erf(x**3), x, meijerg=True) == \
2*x*erf(x**3)*gamma(Rational(2, 3))/(3*gamma(Rational(5, 3))) \
- 2*gamma(Rational(2, 3))*lowergamma(Rational(2, 3), x**6)/(3*sqrt(pi)*gamma(Rational(5, 3)))
def test_linear_subs():
from sympy.functions.special.bessel import besselj
assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x)
assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x)
@slow
def test_probability():
# various integrals from probability theory
from sympy.core.function import expand_mul
from sympy.core.symbol import (Symbol, symbols)
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.powsimp import powsimp
mu1, mu2 = symbols('mu1 mu2', nonzero=True)
sigma1, sigma2 = symbols('sigma1 sigma2', positive=True)
rate = Symbol('lambda', positive=True)
def normal(x, mu, sigma):
return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
def exponential(x, rate):
return rate*exp(-rate*x)
assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1
assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \
mu1
assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
== mu1**2 + sigma1**2
assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
== mu1**3 + 3*mu1*sigma1**2
assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == 1
assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1
assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2
assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2
assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2
assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == \
-1 + mu1 + mu2
i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True)
assert not i.has(Abs)
assert simplify(i) == mu1**2 + sigma1**2
assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == \
sigma2**2 + mu2**2
assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1
assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \
1/rate
assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \
2/rate**2
def E(expr):
res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
(x, 0, oo), (y, -oo, oo), meijerg=True)
res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
(y, -oo, oo), (x, 0, oo), meijerg=True)
assert expand_mul(res1) == expand_mul(res2)
return res1
assert E(1) == 1
assert E(x*y) == mu1/rate
assert E(x*y**2) == mu1**2/rate + sigma1**2/rate
ans = sigma1**2 + 1/rate**2
assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans
assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans
assert simplify(E((x + y)**2) - E(x + y)**2) == ans
# Beta' distribution
alpha, beta = symbols('alpha beta', positive=True)
betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
/gamma(alpha)/gamma(beta)
assert integrate(betadist, (x, 0, oo), meijerg=True) == 1
i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate')
assert (gammasimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta)
j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate')
assert j[1] == (beta > 2)
assert gammasimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \
/(beta - 2)/(beta - 1)**2
# Beta distribution
# NOTE: this is evaluated using antiderivatives. It also tests that
# meijerint_indefinite returns the simplest possible answer.
a, b = symbols('a b', positive=True)
betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b))
assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1
assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \
a/(a + b)
assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \
a*(a + 1)/(a + b)/(a + b + 1)
assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \
gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y)
# Chi distribution
k = Symbol('k', integer=True, positive=True)
chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2)
assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1
assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \
sqrt(2)*gamma((k + 1)/2)/gamma(k/2)
assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k
# Chi^2 distribution
chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1
assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k
assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \
k*(k + 2)
assert gammasimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo),
meijerg=True)) == 2*sqrt(2)/sqrt(k)
# Dagum distribution
a, b, p = symbols('a b p', positive=True)
# XXX (x/b)**a does not work
dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1)
assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1
# XXX conditions are a mess
arg = x*dagum
assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none')
) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/(
(a*p + 1)*gamma(p))
assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none')
) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/(
(a*p + 2)*gamma(p))
# F-distribution
d1, d2 = symbols('d1 d2', positive=True)
f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
/gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1
# TODO conditions are a mess
assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none')
) == d2/(d2 - 2)
assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none')
) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2)
# TODO gamma, rayleigh
# inverse gaussian
lamda, mu = symbols('lamda mu', positive=True)
dist = sqrt(lamda/2/pi)*x**(Rational(-3, 2))*exp(-lamda*(x - mu)**2/x/2/mu**2)
mysimp = lambda expr: simplify(expr.rewrite(exp))
assert mysimp(integrate(dist, (x, 0, oo))) == 1
assert mysimp(integrate(x*dist, (x, 0, oo))) == mu
assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda
assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2
# Levi
c = Symbol('c', positive=True)
assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'),
(x, mu, oo)) == 1
# higher moments oo
# log-logistic
alpha, beta = symbols('alpha beta', positive=True)
distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \
(1 + x**beta/alpha**beta)**2
# FIXME: If alpha, beta are not declared as finite the line below hangs
# after the changes in:
# https://github.com/sympy/sympy/pull/16603
assert simplify(integrate(distn, (x, 0, oo))) == 1
# NOTE the conditions are a mess, but correctly state beta > 1
assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \
pi*alpha/beta/sin(pi/beta)
# (similar comment for conditions applies)
assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \
pi*alpha**y*y/beta/sin(pi*y/beta)
# weibull
k = Symbol('k', positive=True)
n = Symbol('n', positive=True)
distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k)
assert simplify(integrate(distn, (x, 0, oo))) == 1
assert simplify(integrate(x**n*distn, (x, 0, oo))) == \
lamda**n*gamma(1 + n/k)
# rice distribution
from sympy.functions.special.bessel import besseli
nu, sigma = symbols('nu sigma', positive=True)
rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2)
assert integrate(rice, (x, 0, oo), meijerg=True) == 1
# can someone verify higher moments?
# Laplace distribution
mu = Symbol('mu', real=True)
b = Symbol('b', positive=True)
laplace = exp(-abs(x - mu)/b)/2/b
assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1
assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu
assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \
2*b**2 + mu**2
# TODO are there other distributions supported on (-oo, oo) that we can do?
# misc tests
k = Symbol('k', positive=True)
assert gammasimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k),
(x, 0, oo)))) == polygamma(0, k)
@slow
def test_expint():
""" Test various exponential integrals. """
from sympy.core.symbol import Symbol
from sympy.functions.elementary.hyperbolic import sinh
from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint)
assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo),
meijerg=True, conds='none'
).rewrite(expint).expand(func=True))) == expint(y, z)
assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True,
conds='none').rewrite(expint).expand() == \
expint(1, z)
assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True,
conds='none').rewrite(expint).expand() == \
expint(2, z).rewrite(Ei).rewrite(expint)
assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,
conds='none').rewrite(expint).expand() == \
expint(3, z).rewrite(Ei).rewrite(expint).expand()
t = Symbol('t', positive=True)
assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t)
assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \
Si(t) - pi/2
assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z)
assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z)
assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \
I*pi - expint(1, x)
assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \
== expint(1, x) - exp(-x)/x - I*pi
u = Symbol('u', polar=True)
assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
== Ci(u)
assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
== Chi(u)
assert integrate(expint(1, x), x, meijerg=True
).rewrite(expint).expand() == x*expint(1, x) - exp(-x)
assert integrate(expint(2, x), x, meijerg=True
).rewrite(expint).expand() == \
-x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2
assert simplify(unpolarify(integrate(expint(y, x), x,
meijerg=True).rewrite(expint).expand(func=True))) == \
-expint(y + 1, x)
assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x)
assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u)
assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x)
assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u)
assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4
assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2
def test_messy():
from sympy.functions.elementary.hyperbolic import (acosh, acoth)
from sympy.functions.elementary.trigonometric import (asin, atan)
from sympy.functions.special.bessel import besselj
from sympy.functions.special.error_functions import (Chi, E1, Shi, Si)
from sympy.integrals.transforms import (fourier_transform, laplace_transform)
assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True)
assert laplace_transform(Shi(x), x, s) == (
acoth(s)/s, -oo, s**2 > 1)
# where should the logs be simplified?
assert laplace_transform(Chi(x), x, s) == (
(log(s**(-2)) - log(1 - 1/s**2))/(2*s), -oo, s**2 > 1)
# TODO maybe simplify the inequalities? when the simplification
# allows for generators instead of symbols this will work
assert laplace_transform(besselj(a, x), x, s)[1:] == \
(0, (re(a) > -2) & (re(a) > -1))
# NOTE s < 0 can be done, but argument reduction is not good enough yet
ans = fourier_transform(besselj(1, x)/x, x, s, noconds=False)
assert tuple([ans[0].factor(deep=True).expand(), ans[1]]) == \
(Piecewise((0, (s > 1/(2*pi)) | (s < -1/(2*pi))),
(2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0)
# TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons)
# - folding could be better
assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \
log(1 + sqrt(2))
assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \
log(S.Half + sqrt(2)/2)
assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \
Piecewise((-acosh(1/x), abs(x**(-2)) > 1), (I*asin(1/x), True))
def test_issue_6122():
assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \
-I*sqrt(pi)*exp(I*pi/4)
def test_issue_6252():
expr = 1/x/(a + b*x)**Rational(1, 3)
anti = integrate(expr, x, meijerg=True)
assert not anti.has(hyper)
# XXX the expression is a mess, but actually upon differentiation and
# putting in numerical values seems to work...
def test_issue_6348():
assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \
== pi*exp(-1)
def test_fresnel():
from sympy.functions.special.error_functions import (fresnelc, fresnels)
assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x)
assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x)
def test_issue_6860():
assert meijerint_indefinite(x**x**x, x) is None
def test_issue_7337():
f = meijerint_indefinite(x*sqrt(2*x + 3), x).together()
assert f == sqrt(2*x + 3)*(2*x**2 + x - 3)/5
assert f._eval_interval(x, S.NegativeOne, S.One) == Rational(2, 5)
def test_issue_8368():
assert meijerint_indefinite(cosh(x)*exp(-x*t), x) == (
(-t - 1)*exp(x) + (-t + 1)*exp(-x))*exp(-t*x)/2/(t**2 - 1)
def test_issue_10211():
from sympy.abc import h, w
assert integrate((1/sqrt((y-x)**2 + h**2)**3), (x,0,w), (y,0,w)) == \
2*sqrt(1 + w**2/h**2)/h - 2/h
def test_issue_11806():
from sympy.core.symbol import symbols
y, L = symbols('y L', positive=True)
assert integrate(1/sqrt(x**2 + y**2)**3, (x, -L, L)) == \
2*L/(y**2*sqrt(L**2 + y**2))
def test_issue_10681():
from sympy.polys.domains.realfield import RR
from sympy.abc import R, r
f = integrate(r**2*(R**2-r**2)**0.5, r, meijerg=True)
g = (1.0/3)*R**1.0*r**3*hyper((-0.5, Rational(3, 2)), (Rational(5, 2),),
r**2*exp_polar(2*I*pi)/R**2)
assert RR.almosteq((f/g).n(), 1.0, 1e-12)
def test_issue_13536():
from sympy.core.symbol import Symbol
a = Symbol('a', positive=True)
assert integrate(1/x**2, (x, oo, a)) == -1/a
def test_issue_6462():
from sympy.core.symbol import Symbol
x = Symbol('x')
n = Symbol('n')
# Not the actual issue, still wrong answer for n = 1, but that there is no
# exception
assert integrate(cos(x**n)/x**n, x, meijerg=True).subs(n, 2).equals(
integrate(cos(x**2)/x**2, x, meijerg=True))
def test_indefinite_1_bug():
assert integrate((b + t)**(-a), t, meijerg=True
) == -b**(1 - a)*(1 + t/b)**(1 - a)/(a - 1)
def test_pr_23583():
# This result is wrong. Check whether new result is correct when this test fail.
assert integrate(1/sqrt((x - I)**2-1), meijerg=True) == \
Piecewise((acosh(x - I), Abs((x - I)**2) > 1), (-I*asin(x - I), True))
|
a7784b2e545bce564d9ae362ecf6686a073950f6ace427728e8f307842a200d5 | from sympy.integrals.transforms import (mellin_transform,
inverse_mellin_transform, laplace_transform,
inverse_laplace_transform, fourier_transform, inverse_fourier_transform,
sine_transform, inverse_sine_transform,
cosine_transform, inverse_cosine_transform,
hankel_transform, inverse_hankel_transform,
LaplaceTransform, FourierTransform, SineTransform, CosineTransform,
InverseLaplaceTransform, InverseFourierTransform,
InverseSineTransform, InverseCosineTransform, IntegralTransformError)
from sympy.core.function import (Function, expand_mul)
from sympy.core import EulerGamma, Subs, Derivative, diff
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (Abs, re, unpolarify)
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import (cosh, sinh, coth, asinh)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (atan, atan2, cos, sin, tan)
from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely)
from sympy.functions.special.delta_functions import Heaviside
from sympy.functions.special.error_functions import (erf, erfc, expint, Ei)
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import meijerg
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.trigsimp import trigsimp
from sympy.testing.pytest import XFAIL, slow, skip, raises, warns_deprecated_sympy
from sympy.matrices import Matrix, eye
from sympy.abc import x, s, a, b, c, d
nu, beta, rho = symbols('nu beta rho')
def test_undefined_function():
from sympy.integrals.transforms import MellinTransform
f = Function('f')
assert mellin_transform(f(x), x, s) == MellinTransform(f(x), x, s)
assert mellin_transform(f(x) + exp(-x), x, s) == \
(MellinTransform(f(x), x, s) + gamma(s + 1)/s, (0, oo), True)
def test_free_symbols():
f = Function('f')
assert mellin_transform(f(x), x, s).free_symbols == {s}
assert mellin_transform(f(x)*a, x, s).free_symbols == {s, a}
def test_as_integral():
from sympy.integrals.integrals import Integral
f = Function('f')
assert mellin_transform(f(x), x, s).rewrite('Integral') == \
Integral(x**(s - 1)*f(x), (x, 0, oo))
assert fourier_transform(f(x), x, s).rewrite('Integral') == \
Integral(f(x)*exp(-2*I*pi*s*x), (x, -oo, oo))
assert laplace_transform(f(x), x, s).rewrite('Integral') == \
Integral(f(x)*exp(-s*x), (x, 0, oo))
assert str(2*pi*I*inverse_mellin_transform(f(s), s, x, (a, b)).rewrite('Integral')) \
== "Integral(f(s)/x**s, (s, _c - oo*I, _c + oo*I))"
assert str(2*pi*I*inverse_laplace_transform(f(s), s, x).rewrite('Integral')) == \
"Integral(f(s)*exp(s*x), (s, _c - oo*I, _c + oo*I))"
assert inverse_fourier_transform(f(s), s, x).rewrite('Integral') == \
Integral(f(s)*exp(2*I*pi*s*x), (s, -oo, oo))
# NOTE this is stuck in risch because meijerint cannot handle it
@slow
@XFAIL
def test_mellin_transform_fail():
skip("Risch takes forever.")
MT = mellin_transform
bpos = symbols('b', positive=True)
# bneg = symbols('b', negative=True)
expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
# TODO does not work with bneg, argument wrong. Needs changes to matching.
assert MT(expr.subs(b, -bpos), x, s) == \
((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s)
*gamma(1 - a - 2*s)/gamma(1 - s),
(-re(a), -re(a)/2 + S.Half), True)
expr = (sqrt(x + b**2) + b)**a
assert MT(expr.subs(b, -bpos), x, s) == \
(
2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2*
s)*gamma(a + s)/gamma(-s + 1),
(-re(a), -re(a)/2), True)
# Test exponent 1:
assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \
(-bpos**(2*s + 1)*gamma(s)*gamma(-s - S.Half)/(2*sqrt(pi)),
(-1, Rational(-1, 2)), True)
def test_mellin_transform():
from sympy.functions.elementary.miscellaneous import (Max, Min)
MT = mellin_transform
bpos = symbols('b', positive=True)
# 8.4.2
assert MT(x**nu*Heaviside(x - 1), x, s) == \
(-1/(nu + s), (-oo, -re(nu)), True)
assert MT(x**nu*Heaviside(1 - x), x, s) == \
(1/(nu + s), (-re(nu), oo), True)
assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \
(gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(beta) > 0)
assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \
(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
(-oo, 1 - re(beta)), re(beta) > 0)
assert MT((1 + x)**(-rho), x, s) == \
(gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True)
assert MT(abs(1 - x)**(-rho), x, s) == (
2*sin(pi*rho/2)*gamma(1 - rho)*
cos(pi*(s - rho/2))*gamma(s)*gamma(rho-s)/pi,
(0, re(rho)), re(rho) < 1)
mt = MT((1 - x)**(beta - 1)*Heaviside(1 - x)
+ a*(x - 1)**(beta - 1)*Heaviside(x - 1), x, s)
assert mt[1], mt[2] == ((0, -re(beta) + 1), re(beta) > 0)
assert MT((x**a - b**a)/(x - b), x, s)[0] == \
pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s)))
assert MT((x**a - bpos**a)/(x - bpos), x, s) == \
(pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))),
(Max(0, -re(a)), Min(1, 1 - re(a))), True)
expr = (sqrt(x + b**2) + b)**a
assert MT(expr.subs(b, bpos), x, s) == \
(-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1),
(0, -re(a)/2), True)
expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
assert MT(expr.subs(b, bpos), x, s) == \
(2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s)
*gamma(1 - a - 2*s)/gamma(1 - a - s),
(0, -re(a)/2 + S.Half), True)
# 8.4.2
assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True)
assert MT(exp(-1/x), x, s) == (gamma(-s), (-oo, 0), True)
# 8.4.5
assert MT(log(x)**4*Heaviside(1 - x), x, s) == (24/s**5, (0, oo), True)
assert MT(log(x)**3*Heaviside(x - 1), x, s) == (6/s**4, (-oo, 0), True)
assert MT(log(x + 1), x, s) == (pi/(s*sin(pi*s)), (-1, 0), True)
assert MT(log(1/x + 1), x, s) == (pi/(s*sin(pi*s)), (0, 1), True)
assert MT(log(abs(1 - x)), x, s) == (pi/(s*tan(pi*s)), (-1, 0), True)
assert MT(log(abs(1 - 1/x)), x, s) == (pi/(s*tan(pi*s)), (0, 1), True)
# 8.4.14
assert MT(erf(sqrt(x)), x, s) == \
(-gamma(s + S.Half)/(sqrt(pi)*s), (Rational(-1, 2), 0), True)
def test_mellin_transform2():
MT = mellin_transform
# TODO we cannot currently do these (needs summation of 3F2(-1))
# this also implies that they cannot be written as a single g-function
# (although this is possible)
mt = MT(log(x)/(x + 1), x, s)
assert mt[1:] == ((0, 1), True)
assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
mt = MT(log(x)**2/(x + 1), x, s)
assert mt[1:] == ((0, 1), True)
assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
mt = MT(log(x)/(x + 1)**2, x, s)
assert mt[1:] == ((0, 2), True)
assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
@slow
def test_mellin_transform_bessel():
from sympy.functions.elementary.miscellaneous import Max
MT = mellin_transform
# 8.4.19
assert MT(besselj(a, 2*sqrt(x)), x, s) == \
(gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, Rational(3, 4)), True)
assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
(2**a*gamma(-2*s + S.Half)*gamma(a/2 + s + S.Half)/(
gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), (
-re(a)/2 - S.Half, Rational(1, 4)), True)
assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
(2**a*gamma(a/2 + s)*gamma(-2*s + S.Half)/(
gamma(-a/2 - s + S.Half)*gamma(a - 2*s + 1)), (
-re(a)/2, Rational(1, 4)), True)
assert MT(besselj(a, sqrt(x))**2, x, s) == \
(gamma(a + s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
(-re(a), S.Half), True)
assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \
(gamma(s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)),
(0, S.Half), True)
# NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as
# I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large)
assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \
(gamma(1 - s)*gamma(a + s - S.Half)
/ (sqrt(pi)*gamma(Rational(3, 2) - s)*gamma(a - s + S.Half)),
(S.Half - re(a), S.Half), True)
assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \
(4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s)
/ (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2)
*gamma( 1 - s + (a + b)/2)),
(-(re(a) + re(b))/2, S.Half), True)
assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \
((Max(re(a), -re(a)), S.Half), True)
# Section 8.4.20
assert MT(bessely(a, 2*sqrt(x)), x, s) == \
(-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi,
(Max(-re(a)/2, re(a)/2), Rational(3, 4)), True)
assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
(-4**s*sin(pi*(a/2 - s))*gamma(S.Half - 2*s)
* gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s)
/ (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)),
(Max(-(re(a) + 1)/2, (re(a) - 1)/2), Rational(1, 4)), True)
assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
(-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S.Half - 2*s)
/ (sqrt(pi)*gamma(S.Half - s - a/2)*gamma(S.Half - s + a/2)),
(Max(-re(a)/2, re(a)/2), Rational(1, 4)), True)
assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \
(-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S.Half - s)
/ (pi**S('3/2')*gamma(1 + a - s)),
(Max(-re(a), 0), S.Half), True)
assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \
(-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s)
* gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s)
/ (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
(Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S.Half), True)
# NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x))
# are a mess (no matter what way you look at it ...)
assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \
((Max(-re(a), 0, re(a)), S.Half), True)
# Section 8.4.22
# TODO we can't do any of these (delicate cancellation)
# Section 8.4.23
assert MT(besselk(a, 2*sqrt(x)), x, s) == \
(gamma(
s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True)
assert MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(
a, 2*sqrt(2*sqrt(x))), x, s) == (4**(-s)*gamma(2*s)*
gamma(a/2 + s)/(2*gamma(a/2 - s + 1)), (Max(0, -re(a)/2), oo), True)
# TODO bessely(a, x)*besselk(a, x) is a mess
assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
(gamma(s)*gamma(
a + s)*gamma(-s + S.Half)/(2*sqrt(pi)*gamma(a - s + 1)),
(Max(-re(a), 0), S.Half), True)
assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
(2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \
gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \
gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \
re(a)/2 - re(b)/2), S.Half), True)
# TODO products of besselk are a mess
mt = MT(exp(-x/2)*besselk(a, x/2), x, s)
mt0 = gammasimp(trigsimp(gammasimp(mt[0].expand(func=True))))
assert mt0 == 2*pi**Rational(3, 2)*cos(pi*s)*gamma(S.Half - s)/(
(cos(2*pi*a) - cos(2*pi*s))*gamma(-a - s + 1)*gamma(a - s + 1))
assert mt[1:] == ((Max(-re(a), re(a)), oo), True)
# TODO exp(x/2)*besselk(a, x/2) [etc] cannot currently be done
# TODO various strange products of special orders
@slow
def test_expint():
from sympy.functions.elementary.miscellaneous import Max
from sympy.functions.special.error_functions import (Ci, E1, Ei, Si)
from sympy.functions.special.zeta_functions import lerchphi
from sympy.simplify.simplify import simplify
aneg = Symbol('a', negative=True)
u = Symbol('u', polar=True)
assert mellin_transform(E1(x), x, s) == (gamma(s)/s, (0, oo), True)
assert inverse_mellin_transform(gamma(s)/s, s, x,
(0, oo)).rewrite(expint).expand() == E1(x)
assert mellin_transform(expint(a, x), x, s) == \
(gamma(s)/(a + s - 1), (Max(1 - re(a), 0), oo), True)
# XXX IMT has hickups with complicated strips ...
assert simplify(unpolarify(
inverse_mellin_transform(gamma(s)/(aneg + s - 1), s, x,
(1 - aneg, oo)).rewrite(expint).expand(func=True))) == \
expint(aneg, x)
assert mellin_transform(Si(x), x, s) == \
(-2**s*sqrt(pi)*gamma(s/2 + S.Half)/(
2*s*gamma(-s/2 + 1)), (-1, 0), True)
assert inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)
/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0)) \
== Si(x)
assert mellin_transform(Ci(sqrt(x)), x, s) == \
(-2**(2*s - 1)*sqrt(pi)*gamma(s)/(s*gamma(-s + S.Half)), (0, 1), True)
assert inverse_mellin_transform(
-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S.Half)),
s, u, (0, 1)).expand() == Ci(sqrt(u))
# TODO LT of Si, Shi, Chi is a mess ...
assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True)
assert laplace_transform(expint(a, x), x, s) == \
(lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero)
assert laplace_transform(expint(1, x), x, s) == (log(s + 1)/s, 0, True)
assert laplace_transform(expint(2, x), x, s) == \
((s - log(s + 1))/s**2, 0, True)
assert inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() == \
Heaviside(u)*Ci(u)
assert inverse_laplace_transform(log(s + 1)/s, s, x).rewrite(expint) == \
Heaviside(x)*E1(x)
assert inverse_laplace_transform((s - log(s + 1))/s**2, s,
x).rewrite(expint).expand() == \
(expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand()
@slow
def test_inverse_mellin_transform():
from sympy.core.function import expand
from sympy.functions.elementary.miscellaneous import (Max, Min)
from sympy.functions.elementary.trigonometric import cot
from sympy.simplify.powsimp import powsimp
from sympy.simplify.simplify import simplify
IMT = inverse_mellin_transform
assert IMT(gamma(s), s, x, (0, oo)) == exp(-x)
assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1/x)
assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \
(x**2 + 1)*Heaviside(1 - x)/(4*x)
# test passing "None"
assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \
-x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \
-x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
# test expansion of sums
assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1)*exp(-x)/x
# test factorisation of polys
r = symbols('r', real=True)
assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo)
).subs(x, r).rewrite(sin).simplify() \
== sin(r)*Heaviside(1 - exp(-r))
# test multiplicative substitution
_a, _b = symbols('a b', positive=True)
assert IMT(_b**(-s/_a)*factorial(s/_a)/s, s, x, (0, oo)) == exp(-_b*x**_a)
assert IMT(factorial(_a/_b + s/_b)/(_a + s), s, x, (-_a, oo)) == x**_a*exp(-x**_b)
def simp_pows(expr):
return simplify(powsimp(expand_mul(expr, deep=False), force=True)).replace(exp_polar, exp)
# Now test the inverses of all direct transforms tested above
# Section 8.4.2
nu = symbols('nu', real=True)
assert IMT(-1/(nu + s), s, x, (-oo, None)) == x**nu*Heaviside(x - 1)
assert IMT(1/(nu + s), s, x, (None, oo)) == x**nu*Heaviside(1 - x)
assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \
== (1 - x)**(beta - 1)*Heaviside(1 - x)
assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
s, x, (-oo, None))) \
== (x - 1)**(beta - 1)*Heaviside(x - 1)
assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \
== (1/(x + 1))**rho
assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c)
*gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi,
s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \
== (x**c - d**c)/(x - d)
assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s)
*gamma(-c/2 - s)/gamma(1 - c - s),
s, x, (0, -re(c)/2))) == \
(1 + sqrt(x + 1))**c
assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s)
/gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \
b**(a - 1)*(b**2*(sqrt(1 + x/b**2) + 1)**a + x*(sqrt(1 + x/b**2) + 1
)**(a - 1))/(b**2 + x)
assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s)
/ gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \
b**c*(sqrt(1 + x/b**2) + 1)**c
# Section 8.4.5
assert IMT(24/s**5, s, x, (0, oo)) == log(x)**4*Heaviside(1 - x)
assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \
log(x)**3*Heaviside(x - 1)
assert IMT(pi/(s*sin(pi*s)), s, x, (-1, 0)) == log(x + 1)
assert IMT(pi/(s*sin(pi*s/2)), s, x, (-2, 0)) == log(x**2 + 1)
assert IMT(pi/(s*sin(2*pi*s)), s, x, (Rational(-1, 2), 0)) == log(sqrt(x) + 1)
assert IMT(pi/(s*sin(pi*s)), s, x, (0, 1)) == log(1 + 1/x)
# TODO
def mysimp(expr):
from sympy.core.function import expand
from sympy.simplify.powsimp import powsimp
from sympy.simplify.simplify import logcombine
return expand(
powsimp(logcombine(expr, force=True), force=True, deep=True),
force=True).replace(exp_polar, exp)
assert mysimp(mysimp(IMT(pi/(s*tan(pi*s)), s, x, (-1, 0)))) in [
log(1 - x)*Heaviside(1 - x) + log(x - 1)*Heaviside(x - 1),
log(x)*Heaviside(x - 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
1)*Heaviside(-x + 1)]
# test passing cot
assert mysimp(IMT(pi*cot(pi*s)/s, s, x, (0, 1))) in [
log(1/x - 1)*Heaviside(1 - x) + log(1 - 1/x)*Heaviside(x - 1),
-log(x)*Heaviside(-x + 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
1)*Heaviside(-x + 1), ]
# 8.4.14
assert IMT(-gamma(s + S.Half)/(sqrt(pi)*s), s, x, (Rational(-1, 2), 0)) == \
erf(sqrt(x))
# 8.4.19
assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, Rational(3, 4)))) \
== besselj(a, 2*sqrt(x))
assert simplify(IMT(2**a*gamma(S.Half - 2*s)*gamma(s + (a + 1)/2)
/ (gamma(1 - s - a/2)*gamma(1 - 2*s + a)),
s, x, (-(re(a) + 1)/2, Rational(1, 4)))) == \
sin(sqrt(x))*besselj(a, sqrt(x))
assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S.Half - 2*s)
/ (gamma(S.Half - s - a/2)*gamma(1 - 2*s + a)),
s, x, (-re(a)/2, Rational(1, 4)))) == \
cos(sqrt(x))*besselj(a, sqrt(x))
# TODO this comes out as an amazing mess, but simplifies nicely
assert simplify(IMT(gamma(a + s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
s, x, (-re(a), S.Half))) == \
besselj(a, sqrt(x))**2
assert simplify(IMT(gamma(s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)),
s, x, (0, S.Half))) == \
besselj(-a, sqrt(x))*besselj(a, sqrt(x))
assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
/ (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
*gamma(a/2 + b/2 - s + 1)),
s, x, (-(re(a) + re(b))/2, S.Half))) == \
besselj(a, sqrt(x))*besselj(b, sqrt(x))
# Section 8.4.20
# TODO this can be further simplified!
assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) *
gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) /
(pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
s, x,
(Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S.Half))) == \
besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) -
besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b)
# TODO more
# for coverage
assert IMT(pi/cos(pi*s), s, x, (0, S.Half)) == sqrt(x)/(x + 1)
@slow
def test_laplace_transform():
from sympy import lowergamma
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import (fresnelc, fresnels)
LT = laplace_transform
a, b, c, = symbols('a, b, c', positive=True)
t, w, x = symbols('t, w, x')
f = Function("f")
g = Function("g")
# Test rule-base evaluation according to
# http://eqworld.ipmnet.ru/en/auxiliary/inttrans/
# Power-law functions (laplace2.pdf)
assert LT(a*t+t**2+t**(S(5)/2), t, s) ==\
(a/s**2 + 2/s**3 + 15*sqrt(pi)/(8*s**(S(7)/2)), 0, True)
assert LT(b/(t+a), t, s) == (-b*exp(-a*s)*Ei(-a*s), 0, True)
assert LT(1/sqrt(t+a), t, s) ==\
(sqrt(pi)*sqrt(1/s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True)
assert LT(sqrt(t)/(t+a), t, s) ==\
(-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
0, True)
assert LT((t+a)**(-S(3)/2), t, s) ==\
(-2*sqrt(pi)*sqrt(s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + 2/sqrt(a),
0, True)
assert LT(t**(S(1)/2)*(t+a)**(-1), t, s) ==\
(-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
0, True)
assert LT(1/(a*sqrt(t) + t**(3/2)), t, s) ==\
(pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True)
assert LT((t+a)**b, t, s) ==\
(s**(-b - 1)*exp(-a*s)*lowergamma(b + 1, a*s), 0, True)
assert LT(t**5/(t+a), t, s) == (120*a**5*lowergamma(-5, a*s), 0, True)
# Exponential functions (laplace3.pdf)
assert LT(exp(t), t, s) == (1/(s - 1), 1, True)
assert LT(exp(2*t), t, s) == (1/(s - 2), 2, True)
assert LT(exp(a*t), t, s) == (1/(s - a), a, True)
assert LT(exp(a*(t-b)), t, s) == (exp(-a*b)/(-a + s), a, True)
assert LT(t*exp(-a*(t)), t, s) == ((a + s)**(-2), -a, True)
assert LT(t*exp(-a*(t-b)), t, s) == (exp(a*b)/(a + s)**2, -a, True)
assert LT(b*t*exp(-a*t), t, s) == (b/(a + s)**2, -a, True)
assert LT(t**(S(7)/4)*exp(-8*t)/gamma(S(11)/4), t, s) ==\
((s + 8)**(-S(11)/4), -8, True)
assert LT(t**(S(3)/2)*exp(-8*t), t, s) ==\
(3*sqrt(pi)/(4*(s + 8)**(S(5)/2)), -8, True)
assert LT(t**a*exp(-a*t), t, s) == ((a+s)**(-a-1)*gamma(a+1), -a, True)
assert LT(b*exp(-a*t**2), t, s) ==\
(sqrt(pi)*b*exp(s**2/(4*a))*erfc(s/(2*sqrt(a)))/(2*sqrt(a)), 0, True)
assert LT(exp(-2*t**2), t, s) ==\
(sqrt(2)*sqrt(pi)*exp(s**2/8)*erfc(sqrt(2)*s/4)/4, 0, True)
assert LT(b*exp(2*t**2), t, s) == b*LaplaceTransform(exp(2*t**2), t, s)
assert LT(t*exp(-a*t**2), t, s) ==\
(1/(2*a) - s*erfc(s/(2*sqrt(a)))/(4*sqrt(pi)*a**(S(3)/2)), 0, True)
assert LT(exp(-a/t), t, s) ==\
(2*sqrt(a)*sqrt(1/s)*besselk(1, 2*sqrt(a)*sqrt(s)), 0, True)
assert LT(sqrt(t)*exp(-a/t), t, s) ==\
(sqrt(pi)*(2*sqrt(a)*sqrt(s) + 1)*sqrt(s**(-3))*exp(-2*sqrt(a)*\
sqrt(s))/2, 0, True)
assert LT(exp(-a/t)/sqrt(t), t, s) ==\
(sqrt(pi)*sqrt(1/s)*exp(-2*sqrt(a)*sqrt(s)), 0, True)
assert LT( exp(-a/t)/(t*sqrt(t)), t, s) ==\
(sqrt(pi)*sqrt(1/a)*exp(-2*sqrt(a)*sqrt(s)), 0, True)
assert LT(exp(-2*sqrt(a*t)), t, s) ==\
( 1/s -sqrt(pi)*sqrt(a) * exp(a/s)*erfc(sqrt(a)*sqrt(1/s))/\
s**(S(3)/2), 0, True)
assert LT(exp(-2*sqrt(a*t))/sqrt(t), t, s) == (exp(a/s)*erfc(sqrt(a)*\
sqrt(1/s))*(sqrt(pi)*sqrt(1/s)), 0, True)
assert LT(t**4*exp(-2/t), t, s) ==\
(8*sqrt(2)*(1/s)**(S(5)/2)*besselk(5, 2*sqrt(2)*sqrt(s)), 0, True)
# Hyperbolic functions (laplace4.pdf)
assert LT(sinh(a*t), t, s) == (a/(-a**2 + s**2), a, True)
assert LT(b*sinh(a*t)**2, t, s) == (2*a**2*b/(-4*a**2*s**2 + s**3),
2*a, True)
# The following line confirms that issue #21202 is solved
assert LT(cosh(2*t), t, s) == (s/(-4 + s**2), 2, True)
assert LT(cosh(a*t), t, s) == (s/(-a**2 + s**2), a, True)
assert LT(cosh(a*t)**2, t, s) == ((-2*a**2 + s**2)/(-4*a**2*s**2 + s**3),
2*a, True)
assert LT(sinh(x + 3), x, s) == (
(-s + (s + 1)*exp(6) + 1)*exp(-3)/(s - 1)/(s + 1)/2, 0, Abs(s) > 1)
# The following line replaces the old test test_issue_7173()
assert LT(sinh(a*t)*cosh(a*t), t, s) == (a/(-4*a**2 + s**2), 2*a, True)
assert LT(sinh(a*t)/t, t, s) == (log((a + s)/(-a + s))/2, a, True)
assert LT(t**(-S(3)/2)*sinh(a*t), t, s) ==\
(-sqrt(pi)*(sqrt(-a + s) - sqrt(a + s)), a, True)
assert LT(sinh(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*sqrt(a)*exp(a/s)/s**(S(3)/2), 0, True)
assert LT(sqrt(t)*sinh(2*sqrt(a*t)), t, s) ==\
(-sqrt(a)/s**2 + sqrt(pi)*(a + s/2)*exp(a/s)*erf(sqrt(a)*\
sqrt(1/s))/s**(S(5)/2), 0, True)
assert LT(sinh(2*sqrt(a*t))/sqrt(t), t, s) ==\
(sqrt(pi)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/sqrt(s), 0, True)
assert LT(sinh(sqrt(a*t))**2/sqrt(t), t, s) ==\
(sqrt(pi)*(exp(a/s) - 1)/(2*sqrt(s)), 0, True)
assert LT(t**(S(3)/7)*cosh(a*t), t, s) ==\
(((a + s)**(-S(10)/7) + (-a+s)**(-S(10)/7))*gamma(S(10)/7)/2, a, True)
assert LT(cosh(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*sqrt(a)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/s**(S(3)/2) + 1/s,
0, True)
assert LT(sqrt(t)*cosh(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*(a + s/2)*exp(a/s)/s**(S(5)/2), 0, True)
assert LT(cosh(2*sqrt(a*t))/sqrt(t), t, s) ==\
(sqrt(pi)*exp(a/s)/sqrt(s), 0, True)
assert LT(cosh(sqrt(a*t))**2/sqrt(t), t, s) ==\
(sqrt(pi)*(exp(a/s) + 1)/(2*sqrt(s)), 0, True)
# logarithmic functions (laplace5.pdf)
assert LT(log(t), t, s) == (-log(s+S.EulerGamma)/s, 0, True)
assert LT(log(t/a), t, s) == (-log(a*s + S.EulerGamma)/s, 0, True)
assert LT(log(1+a*t), t, s) == (-exp(s/a)*Ei(-s/a)/s, 0, True)
assert LT(log(t+a), t, s) == ((log(a) - exp(s/a)*Ei(-s/a)/s)/s, 0, True)
assert LT(log(t)/sqrt(t), t, s) ==\
(sqrt(pi)*(-log(s) - 2*log(2) - S.EulerGamma)/sqrt(s), 0, True)
assert LT(t**(S(5)/2)*log(t), t, s) ==\
(15*sqrt(pi)*(-log(s)-2*log(2)-S.EulerGamma+S(46)/15)/(8*s**(S(7)/2)),
0, True)
assert (LT(t**3*log(t), t, s, noconds=True)-6*(-log(s) - S.EulerGamma\
+ S(11)/6)/s**4).simplify() == S.Zero
assert LT(log(t)**2, t, s) ==\
(((log(s) + EulerGamma)**2 + pi**2/6)/s, 0, True)
assert LT(exp(-a*t)*log(t), t, s) ==\
((-log(a + s) - S.EulerGamma)/(a + s), -a, True)
# Trigonometric functions (laplace6.pdf)
assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True)
assert LT(Abs(sin(a*t)), t, s) ==\
(a*coth(pi*s/(2*a))/(a**2 + s**2), 0, True)
assert LT(sin(a*t)/t, t, s) == (atan(a/s), 0, True)
assert LT(sin(a*t)**2/t, t, s) == (log(4*a**2/s**2 + 1)/4, 0, True)
assert LT(sin(a*t)**2/t**2, t, s) ==\
(a*atan(2*a/s) - s*log(4*a**2/s**2 + 1)/4, 0, True)
assert LT(sin(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*sqrt(a)*exp(-a/s)/s**(S(3)/2), 0, True)
assert LT(sin(2*sqrt(a*t))/t, t, s) == (pi*erf(sqrt(a)*sqrt(1/s)), 0, True)
assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True)
assert LT(cos(a*t)**2, t, s) ==\
((2*a**2 + s**2)/(s*(4*a**2 + s**2)), 0, True)
assert LT(sqrt(t)*cos(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*(-2*a + s)*exp(-a/s)/(2*s**(S(5)/2)), 0, True)
assert LT(cos(2*sqrt(a*t))/sqrt(t), t, s) ==\
(sqrt(pi)*sqrt(1/s)*exp(-a/s), 0, True)
assert LT(sin(a*t)*sin(b*t), t, s) ==\
(2*a*b*s/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True)
assert LT(cos(a*t)*sin(b*t), t, s) ==\
(b*(-a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
0, True)
assert LT(cos(a*t)*cos(b*t), t, s) ==\
(s*(a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
0, True)
assert LT(c*exp(-b*t)*sin(a*t), t, s) == (a*c/(a**2 + (b + s)**2),
-b, True)
assert LT(c*exp(-b*t)*cos(a*t), t, s) == ((b + s)*c/(a**2 + (b + s)**2),
-b, True)
assert LT(cos(x + 3), x, s) == ((s*cos(3) - sin(3))/(s**2 + 1), 0, True)
# Error functions (laplace7.pdf)
assert LT(erf(a*t), t, s) == (exp(s**2/(4*a**2))*erfc(s/(2*a))/s, 0, True)
assert LT(erf(sqrt(a*t)), t, s) == (sqrt(a)/(s*sqrt(a + s)), 0, True)
assert LT(exp(a*t)*erf(sqrt(a*t)), t, s) ==\
(sqrt(a)/(sqrt(s)*(-a + s)), a, True)
assert LT(erf(sqrt(a/t)/2), t, s) == ((1-exp(-sqrt(a)*sqrt(s)))/s, 0, True)
assert LT(erfc(sqrt(a*t)), t, s) ==\
((-sqrt(a) + sqrt(a + s))/(s*sqrt(a + s)), 0, True)
assert LT(exp(a*t)*erfc(sqrt(a*t)), t, s) ==\
(1/(sqrt(a)*sqrt(s) + s), 0, True)
assert LT(erfc(sqrt(a/t)/2), t, s) == (exp(-sqrt(a)*sqrt(s))/s, 0, True)
# Bessel functions (laplace8.pdf)
assert LT(besselj(0, a*t), t, s) == (1/sqrt(a**2 + s**2), 0, True)
assert LT(besselj(1, a*t), t, s) ==\
(a/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))), 0, True)
assert LT(besselj(2, a*t), t, s) ==\
(a**2/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))**2), 0, True)
assert LT(t*besselj(0, a*t), t, s) ==\
(s/(a**2 + s**2)**(S(3)/2), 0, True)
assert LT(t*besselj(1, a*t), t, s) ==\
(a/(a**2 + s**2)**(S(3)/2), 0, True)
assert LT(t**2*besselj(2, a*t), t, s) ==\
(3*a**2/(a**2 + s**2)**(S(5)/2), 0, True)
assert LT(besselj(0, 2*sqrt(a*t)), t, s) == (exp(-a/s)/s, 0, True)
assert LT(t**(S(3)/2)*besselj(3, 2*sqrt(a*t)), t, s) ==\
(a**(S(3)/2)*exp(-a/s)/s**4, 0, True)
assert LT(besselj(0, a*sqrt(t**2+b*t)), t, s) ==\
(exp(b*s - b*sqrt(a**2 + s**2))/sqrt(a**2 + s**2), 0, True)
assert LT(besseli(0, a*t), t, s) == (1/sqrt(-a**2 + s**2), a, True)
assert LT(besseli(1, a*t), t, s) ==\
(a/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))), a, True)
assert LT(besseli(2, a*t), t, s) ==\
(a**2/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))**2), a, True)
assert LT(t*besseli(0, a*t), t, s) == (s/(-a**2 + s**2)**(S(3)/2), a, True)
assert LT(t*besseli(1, a*t), t, s) == (a/(-a**2 + s**2)**(S(3)/2), a, True)
assert LT(t**2*besseli(2, a*t), t, s) ==\
(3*a**2/(-a**2 + s**2)**(S(5)/2), a, True)
assert LT(t**(S(3)/2)*besseli(3, 2*sqrt(a*t)), t, s) ==\
(a**(S(3)/2)*exp(a/s)/s**4, 0, True)
assert LT(bessely(0, a*t), t, s) ==\
(-2*asinh(s/a)/(pi*sqrt(a**2 + s**2)), 0, True)
assert LT(besselk(0, a*t), t, s) ==\
(log(s + sqrt(-a**2 + s**2))/sqrt(-a**2 + s**2), a, True)
assert LT(sin(a*t)**8, t, s) ==\
(40320*a**8/(s*(147456*a**8 + 52480*a**6*s**2 + 4368*a**4*s**4 +\
120*a**2*s**6 + s**8)), 0, True)
# Test general rules and unevaluated forms
# These all also test whether issue #7219 is solved.
assert LT(Heaviside(t-1)*cos(t-1), t, s) == (s*exp(-s)/(s**2 + 1), 0, True)
assert LT(a*f(t), t, w) == a*LaplaceTransform(f(t), t, w)
assert LT(a*Heaviside(t+1)*f(t+1), t, s) ==\
a*LaplaceTransform(f(t + 1)*Heaviside(t + 1), t, s)
assert LT(a*Heaviside(t-1)*f(t-1), t, s) ==\
a*LaplaceTransform(f(t), t, s)*exp(-s)
assert LT(b*f(t/a), t, s) == a*b*LaplaceTransform(f(t), t, a*s)
assert LT(exp(-f(x)*t), t, s) == (1/(s + f(x)), -f(x), True)
assert LT(exp(-a*t)*f(t), t, s) == LaplaceTransform(f(t), t, a + s)
assert LT(exp(-a*t)*erfc(sqrt(b/t)/2), t, s) ==\
(exp(-sqrt(b)*sqrt(a + s))/(a + s), -a, True)
assert LT(sinh(a*t)*f(t), t, s) ==\
LaplaceTransform(f(t), t, -a+s)/2 - LaplaceTransform(f(t), t, a+s)/2
assert LT(sinh(a*t)*t, t, s) ==\
(-1/(2*(a + s)**2) + 1/(2*(-a + s)**2), a, True)
assert LT(cosh(a*t)*f(t), t, s) ==\
LaplaceTransform(f(t), t, -a+s)/2 + LaplaceTransform(f(t), t, a+s)/2
assert LT(cosh(a*t)*t, t, s) ==\
(1/(2*(a + s)**2) + 1/(2*(-a + s)**2), a, True)
assert LT(sin(a*t)*f(t), t, s) ==\
I*(-LaplaceTransform(f(t), t, -I*a + s) +\
LaplaceTransform(f(t), t, I*a + s))/2
assert LT(sin(a*t)*t, t, s) ==\
(2*a*s/(a**4 + 2*a**2*s**2 + s**4), 0, True)
assert LT(cos(a*t)*f(t), t, s) ==\
LaplaceTransform(f(t), t, -I*a + s)/2 +\
LaplaceTransform(f(t), t, I*a + s)/2
assert LT(cos(a*t)*t, t, s) ==\
((-a**2 + s**2)/(a**4 + 2*a**2*s**2 + s**4), 0, True)
# The following two lines test whether issues #5813 and #7176 are solved.
assert LT(diff(f(t), (t, 1)), t, s) == s*LaplaceTransform(f(t), t, s)\
- f(0)
assert LT(diff(f(t), (t, 3)), t, s) == s**3*LaplaceTransform(f(t), t, s)\
- s**2*f(0) - s*Subs(Derivative(f(t), t), t, 0)\
- Subs(Derivative(f(t), (t, 2)), t, 0)
# Issue #23307
assert LT(10*diff(f(t), (t, 1)), t, s) == 10*s*LaplaceTransform(f(t), t, s)\
- 10*f(0)
assert LT(a*f(b*t)+g(c*t), t, s) == a*LaplaceTransform(f(t), t, s/b)/b +\
LaplaceTransform(g(t), t, s/c)/c
assert inverse_laplace_transform(
f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0)
assert LT(f(t)*g(t), t, s) == LaplaceTransform(f(t)*g(t), t, s)
# additional basic tests from wikipedia
assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \
((s + c)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True)
assert LT((exp(2*t) - 1)*exp(-b - t)*Heaviside(t)/2, t, s, noconds=True) \
== exp(-b)/(s**2 - 1)
# DiracDelta function: standard cases
assert LT(DiracDelta(t), t, s) == (1, 0, True)
assert LT(DiracDelta(a*t), t, s) == (1/a, 0, True)
assert LT(DiracDelta(t/42), t, s) == (42, 0, True)
assert LT(DiracDelta(t+42), t, s) == (0, 0, True)
assert LT(DiracDelta(t)+DiracDelta(t-42), t, s) == \
(1 + exp(-42*s), 0, True)
assert LT(DiracDelta(t)-a*exp(-a*t), t, s) == (s/(a + s), 0, True)
assert LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s) == \
(exp(-42*s - 42) + 1, -oo, True)
# Collection of cases that cannot be fully evaluated and/or would catch
# some common implementation errors
assert LT(DiracDelta(t**2), t, s) == LaplaceTransform(DiracDelta(t**2), t, s)
assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True)
assert LT(DiracDelta(t*(1 - t)), t, s) == \
LaplaceTransform(DiracDelta(-t**2 + t), t, s)
assert LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) == \
(LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) + \
1 + exp(-s) + 1/s, 0, True)
assert LT(DiracDelta(2*t-2*exp(a)), t, s) == (exp(-s*exp(a))/2, 0, True)
assert LT(DiracDelta(-2*t+2*exp(a)), t, s) == (exp(-s*exp(a))/2, 0, True)
# Heaviside tests
assert LT(Heaviside(t), t, s) == (1/s, 0, True)
assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True)
assert LT(Heaviside(t-1), t, s) == (exp(-s)/s, 0, True)
assert LT(Heaviside(2*t-4), t, s) == (exp(-2*s)/s, 0, True)
assert LT(Heaviside(-2*t+4), t, s) == ((1 - exp(-2*s))/s, 0, True)
assert LT(Heaviside(2*t+4), t, s) == (1/s, 0, True)
assert LT(Heaviside(-2*t+4), t, s) == ((1 - exp(-2*s))/s, 0, True)
# Fresnel functions
assert laplace_transform(fresnels(t), t, s) == \
((-sin(s**2/(2*pi))*fresnels(s/pi) + sin(s**2/(2*pi))/2 -
cos(s**2/(2*pi))*fresnelc(s/pi) + cos(s**2/(2*pi))/2)/s, 0, True)
assert laplace_transform(fresnelc(t), t, s) == (
((2*sin(s**2/(2*pi))*fresnelc(s/pi) - 2*cos(s**2/(2*pi))*fresnels(s/pi)
+ sqrt(2)*cos(s**2/(2*pi) + pi/4))/(2*s), 0, True))
# Matrix tests
Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]])
Ms = Matrix([[ 1/(s - 1), (s + 1)**(-2)],
[(s + 1)**(-2), 1/(s - 1)]])
# The default behaviour for Laplace tranform of a Matrix returns a Matrix
# of Tuples and is deprecated:
with warns_deprecated_sympy():
Ms_conds = Matrix([[(1/(s - 1), 1, True), ((s + 1)**(-2),
-1, True)], [((s + 1)**(-2), -1, True), (1/(s - 1), 1, True)]])
with warns_deprecated_sympy():
assert LT(Mt, t, s) == Ms_conds
# The new behavior is to return a tuple of a Matrix and the convergence
# conditions for the matrix as a whole:
assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, True)
# With noconds=True the transformed matrix is returned without conditions
# either way:
assert LT(Mt, t, s, noconds=True) == Ms
assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms
@slow
def test_inverse_laplace_transform():
from sympy.core.exprtools import factor_terms
from sympy.functions.special.delta_functions import DiracDelta
from sympy.simplify.simplify import simplify
ILT = inverse_laplace_transform
a, b, c, = symbols('a b c', positive=True)
t = symbols('t')
def simp_hyp(expr):
return factor_terms(expand_mul(expr)).rewrite(sin)
assert ILT(1, s, t) == DiracDelta(t)
assert ILT(1/s, s, t) == Heaviside(t)
assert ILT(a/(a + s), s, t) == a*exp(-a*t)*Heaviside(t)
assert ILT(s/(a + s), s, t) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t)
assert ILT((a + s)**(-2), s, t) == t*exp(-a*t)*Heaviside(t)
assert ILT((a + s)**(-5), s, t) == t**4*exp(-a*t)*Heaviside(t)/24
assert ILT(a/(a**2 + s**2), s, t) == sin(a*t)*Heaviside(t)
assert ILT(s/(s**2 + a**2), s, t) == cos(a*t)*Heaviside(t)
assert ILT(b/(b**2 + (a + s)**2), s, t) == exp(-a*t)*sin(b*t)*Heaviside(t)
assert ILT(b*s/(b**2 + (a + s)**2), s, t) +\
(a*sin(b*t) - b*cos(b*t))*exp(-a*t)*Heaviside(t) == 0
assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t)
assert ILT(exp(-a*s)/(b + s), s, t) == exp(b*(a - t))*Heaviside(-a + t)
assert ILT((b + s)/(a**2 + (b + s)**2), s, t) == \
exp(-b*t)*cos(a*t)*Heaviside(t)
assert ILT(exp(-a*s)/s**b, s, t) == \
(-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b)
assert ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) == \
Heaviside(-a + t)*besselj(0, a - t)
assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
assert ILT(1/(s**2*(s**2 + 1)), s, t) == (t - sin(t))*Heaviside(t)
assert ILT(s**2/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t)
assert ILT(1 - 1/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t)
assert ILT(1/s**2, s, t) == t*Heaviside(t)
assert ILT(1/s**5, s, t) == t**4*Heaviside(t)/24
assert simp_hyp(ILT(a/(s**2 - a**2), s, t)) == sinh(a*t)*Heaviside(t)
assert simp_hyp(ILT(s/(s**2 - a**2), s, t)) == cosh(a*t)*Heaviside(t)
# TODO sinh/cosh shifted come out a mess. also delayed trig is a mess
# TODO should this simplify further?
assert ILT(exp(-a*s)/s**b, s, t) == \
(t - a)**(b - 1)*Heaviside(t - a)/gamma(b)
assert ILT(exp(-a*s)/sqrt(1 + s**2), s, t) == \
Heaviside(t - a)*besselj(0, a - t) # note: besselj(0, x) is even
# XXX ILT turns these branch factor into trig functions ...
assert simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2),
s, t).rewrite(exp)) == \
Heaviside(t)*besseli(b, a*t)
assert ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2),
s, t).rewrite(exp) == \
Heaviside(t)*besselj(b, a*t)
assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
# TODO can we make erf(t) work?
assert ILT(1/(s**2*(s**2 + 1)),s,t) == (t - sin(t))*Heaviside(t)
assert ILT( (s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==\
Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]])
def test_inverse_laplace_transform_delta():
from sympy.functions.special.delta_functions import DiracDelta
ILT = inverse_laplace_transform
t = symbols('t')
assert ILT(2, s, t) == 2*DiracDelta(t)
assert ILT(2*exp(3*s) - 5*exp(-7*s), s, t) == \
2*DiracDelta(t + 3) - 5*DiracDelta(t - 7)
a = cos(sin(7)/2)
assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3)
assert ILT(exp(2*s), s, t) == DiracDelta(t + 2)
r = Symbol('r', real=True)
assert ILT(exp(r*s), s, t) == DiracDelta(t + r)
def test_inverse_laplace_transform_delta_cond():
from sympy.functions.elementary.complexes import im
from sympy.functions.special.delta_functions import DiracDelta
ILT = inverse_laplace_transform
t = symbols('t')
r = Symbol('r', real=True)
assert ILT(exp(r*s), s, t, noconds=False) == (DiracDelta(t + r), True)
z = Symbol('z')
assert ILT(exp(z*s), s, t, noconds=False) == \
(DiracDelta(t + z), Eq(im(z), 0))
# inversion does not exist: verify it doesn't evaluate to DiracDelta
for z in (Symbol('z', extended_real=False),
Symbol('z', imaginary=True, zero=False)):
f = ILT(exp(z*s), s, t, noconds=False)
f = f[0] if isinstance(f, tuple) else f
assert f.func != DiracDelta
# issue 15043
assert ILT(1/s + exp(r*s)/s, s, t, noconds=False) == (
Heaviside(t) + Heaviside(r + t), True)
def test_fourier_transform():
from sympy.core.function import (expand, expand_complex, expand_trig)
from sympy.polys.polytools import factor
from sympy.simplify.simplify import simplify
FT = fourier_transform
IFT = inverse_fourier_transform
def simp(x):
return simplify(expand_trig(expand_complex(expand(x))))
def sinc(x):
return sin(pi*x)/(pi*x)
k = symbols('k', real=True)
f = Function("f")
# TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x)
a = symbols('a', positive=True)
b = symbols('b', positive=True)
posk = symbols('posk', positive=True)
# Test unevaluated form
assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k)
assert inverse_fourier_transform(
f(k), k, x) == InverseFourierTransform(f(k), k, x)
# basic examples from wikipedia
assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a
# TODO IFT is a *mess*
assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a
# TODO IFT
assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \
1/(a + 2*pi*I*k)
# NOTE: the ift comes out in pieces
assert IFT(1/(a + 2*pi*I*x), x, posk,
noconds=False) == (exp(-a*posk), True)
assert IFT(1/(a + 2*pi*I*x), x, -posk,
noconds=False) == (0, True)
assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True),
noconds=False) == (0, True)
# TODO IFT without factoring comes out as meijer g
assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \
1/(a + 2*pi*I*k)**2
assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \
b/(b**2 + (a + 2*I*pi*k)**2)
assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a)
assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2)
assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2)
# TODO IFT (comes out as meijer G)
# TODO besselj(n, x), n an integer > 0 actually can be done...
# TODO are there other common transforms (no distributions!)?
def test_sine_transform():
t = symbols("t")
w = symbols("w")
a = symbols("a")
f = Function("f")
# Test unevaluated form
assert sine_transform(f(t), t, w) == SineTransform(f(t), t, w)
assert inverse_sine_transform(
f(w), w, t) == InverseSineTransform(f(w), w, t)
assert sine_transform(1/sqrt(t), t, w) == 1/sqrt(w)
assert inverse_sine_transform(1/sqrt(w), w, t) == 1/sqrt(t)
assert sine_transform((1/sqrt(t))**3, t, w) == 2*sqrt(w)
assert sine_transform(t**(-a), t, w) == 2**(
-a + S.Half)*w**(a - 1)*gamma(-a/2 + 1)/gamma((a + 1)/2)
assert inverse_sine_transform(2**(-a + S(
1)/2)*w**(a - 1)*gamma(-a/2 + 1)/gamma(a/2 + S.Half), w, t) == t**(-a)
assert sine_transform(
exp(-a*t), t, w) == sqrt(2)*w/(sqrt(pi)*(a**2 + w**2))
assert inverse_sine_transform(
sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t)
assert sine_transform(
log(t)/t, t, w) == sqrt(2)*sqrt(pi)*-(log(w**2) + 2*EulerGamma)/4
assert sine_transform(
t*exp(-a*t**2), t, w) == sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2))
assert inverse_sine_transform(
sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)), w, t) == t*exp(-a*t**2)
def test_cosine_transform():
from sympy.functions.special.error_functions import (Ci, Si)
t = symbols("t")
w = symbols("w")
a = symbols("a")
f = Function("f")
# Test unevaluated form
assert cosine_transform(f(t), t, w) == CosineTransform(f(t), t, w)
assert inverse_cosine_transform(
f(w), w, t) == InverseCosineTransform(f(w), w, t)
assert cosine_transform(1/sqrt(t), t, w) == 1/sqrt(w)
assert inverse_cosine_transform(1/sqrt(w), w, t) == 1/sqrt(t)
assert cosine_transform(1/(
a**2 + t**2), t, w) == sqrt(2)*sqrt(pi)*exp(-a*w)/(2*a)
assert cosine_transform(t**(
-a), t, w) == 2**(-a + S.Half)*w**(a - 1)*gamma((-a + 1)/2)/gamma(a/2)
assert inverse_cosine_transform(2**(-a + S(
1)/2)*w**(a - 1)*gamma(-a/2 + S.Half)/gamma(a/2), w, t) == t**(-a)
assert cosine_transform(
exp(-a*t), t, w) == sqrt(2)*a/(sqrt(pi)*(a**2 + w**2))
assert inverse_cosine_transform(
sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t)
assert cosine_transform(exp(-a*sqrt(t))*cos(a*sqrt(
t)), t, w) == a*exp(-a**2/(2*w))/(2*w**Rational(3, 2))
assert cosine_transform(1/(a + t), t, w) == sqrt(2)*(
(-2*Si(a*w) + pi)*sin(a*w)/2 - cos(a*w)*Ci(a*w))/sqrt(pi)
assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half, 0), ()), (
(S.Half, 0, 0), (S.Half,)), a**2*w**2/4)/(2*pi), w, t) == 1/(a + t)
assert cosine_transform(1/sqrt(a**2 + t**2), t, w) == sqrt(2)*meijerg(
((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi))
assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)), w, t) == 1/(t*sqrt(a**2/t**2 + 1))
def test_hankel_transform():
r = Symbol("r")
k = Symbol("k")
nu = Symbol("nu")
m = Symbol("m")
a = symbols("a")
assert hankel_transform(1/r, r, k, 0) == 1/k
assert inverse_hankel_transform(1/k, k, r, 0) == 1/r
assert hankel_transform(
1/r**m, r, k, 0) == 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2)
assert inverse_hankel_transform(
2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2), k, r, 0) == r**(-m)
assert hankel_transform(1/r**m, r, k, nu) == (
2*2**(-m)*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2))
assert inverse_hankel_transform(2**(-m + 1)*k**(
m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2), k, r, nu) == r**(-m)
assert hankel_transform(r**nu*exp(-a*r), r, k, nu) == \
2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S(
3)/2)*gamma(nu + Rational(3, 2))/sqrt(pi)
assert inverse_hankel_transform(
2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - Rational(3, 2))*gamma(
nu + Rational(3, 2))/sqrt(pi), k, r, nu) == r**nu*exp(-a*r)
def test_issue_7181():
assert mellin_transform(1/(1 - x), x, s) != None
def test_issue_8882():
# This is the original test.
# from sympy import diff, Integral, integrate
# r = Symbol('r')
# psi = 1/r*sin(r)*exp(-(a0*r))
# h = -1/2*diff(psi, r, r) - 1/r*psi
# f = 4*pi*psi*h*r**2
# assert integrate(f, (r, -oo, 3), meijerg=True).has(Integral) == True
# To save time, only the critical part is included.
F = -a**(-s + 1)*(4 + 1/a**2)**(-s/2)*sqrt(1/a**2)*exp(-s*I*pi)* \
sin(s*atan(sqrt(1/a**2)/2))*gamma(s)
raises(IntegralTransformError, lambda:
inverse_mellin_transform(F, s, x, (-1, oo),
**{'as_meijerg': True, 'needeval': True}))
def test_issue_8514():
from sympy.simplify.simplify import simplify
a, b, c, = symbols('a b c', positive=True)
t = symbols('t', positive=True)
ft = simplify(inverse_laplace_transform(1/(a*s**2+b*s+c),s, t))
assert ft == (I*exp(t*cos(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c -
b**2))/a)*sin(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(
4*a*c - b**2))/(2*a)) + exp(t*cos(atan2(0, -4*a*c + b**2)
/2)*sqrt(Abs(4*a*c - b**2))/a)*cos(t*sin(atan2(0, -4*a*c
+ b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)) + I*sin(t*sin(
atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a))
- cos(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c -
b**2))/(2*a)))*exp(-t*(b + cos(atan2(0, -4*a*c + b**2)/2)
*sqrt(Abs(4*a*c - b**2)))/(2*a))/sqrt(-4*a*c + b**2)
def test_issue_12591():
x, y = symbols("x y", real=True)
assert fourier_transform(exp(x), x, y) == FourierTransform(exp(x), x, y)
def test_issue_14692():
b = Symbol('b', negative=True)
assert laplace_transform(1/(I*x - b), x, s) == \
(-I*exp(I*b*s)*expint(1, b*s*exp_polar(I*pi/2)), 0, True)
|
b6c4fc5e0633fc8941c4e62906450dfa299af19a42a860cfe41b2f80c2f80c85 | from sympy.assumptions.refine import refine
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import (ExprBuilder, unchanged, Expr,
UnevaluatedExpr)
from sympy.core.function import (Function, expand, WildFunction,
AppliedUndef, Derivative, diff, Subs)
from sympy.core.mul import Mul
from sympy.core.numbers import (NumberSymbol, E, zoo, oo, Float, I,
Rational, nan, Integer, Number, pi, _illegal)
from sympy.core.power import Pow
from sympy.core.relational import Ge, Lt, Gt, Le
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol, symbols, Dummy, Wild
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.exponential import exp_polar, exp, log
from sympy.functions.elementary.miscellaneous import sqrt, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import tan, sin, cos
from sympy.functions.special.delta_functions import (Heaviside,
DiracDelta)
from sympy.functions.special.error_functions import Si
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import integrate, Integral
from sympy.physics.secondquant import FockState
from sympy.polys.partfrac import apart
from sympy.polys.polytools import factor, cancel, Poly
from sympy.polys.rationaltools import together
from sympy.series.order import O
from sympy.sets.sets import FiniteSet
from sympy.simplify.combsimp import combsimp
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import collect, radsimp
from sympy.simplify.ratsimp import ratsimp
from sympy.simplify.simplify import simplify, nsimplify
from sympy.simplify.trigsimp import trigsimp
from sympy.tensor.indexed import Indexed
from sympy.physics.units import meter
from sympy.testing.pytest import raises, XFAIL
from sympy.abc import a, b, c, n, t, u, x, y, z
f, g, h = symbols('f,g,h', cls=Function)
class DummyNumber:
"""
Minimal implementation of a number that works with SymPy.
If one has a Number class (e.g. Sage Integer, or some other custom class)
that one wants to work well with SymPy, one has to implement at least the
methods of this class DummyNumber, resp. its subclasses I5 and F1_1.
Basically, one just needs to implement either __int__() or __float__() and
then one needs to make sure that the class works with Python integers and
with itself.
"""
def __radd__(self, a):
if isinstance(a, (int, float)):
return a + self.number
return NotImplemented
def __add__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number + a
return NotImplemented
def __rsub__(self, a):
if isinstance(a, (int, float)):
return a - self.number
return NotImplemented
def __sub__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number - a
return NotImplemented
def __rmul__(self, a):
if isinstance(a, (int, float)):
return a * self.number
return NotImplemented
def __mul__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number * a
return NotImplemented
def __rtruediv__(self, a):
if isinstance(a, (int, float)):
return a / self.number
return NotImplemented
def __truediv__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number / a
return NotImplemented
def __rpow__(self, a):
if isinstance(a, (int, float)):
return a ** self.number
return NotImplemented
def __pow__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number ** a
return NotImplemented
def __pos__(self):
return self.number
def __neg__(self):
return - self.number
class I5(DummyNumber):
number = 5
def __int__(self):
return self.number
class F1_1(DummyNumber):
number = 1.1
def __float__(self):
return self.number
i5 = I5()
f1_1 = F1_1()
# basic SymPy objects
basic_objs = [
Rational(2),
Float("1.3"),
x,
y,
pow(x, y)*y,
]
# all supported objects
all_objs = basic_objs + [
5,
5.5,
i5,
f1_1
]
def dotest(s):
for xo in all_objs:
for yo in all_objs:
s(xo, yo)
return True
def test_basic():
def j(a, b):
x = a
x = +a
x = -a
x = a + b
x = a - b
x = a*b
x = a/b
x = a**b
del x
assert dotest(j)
def test_ibasic():
def s(a, b):
x = a
x += b
x = a
x -= b
x = a
x *= b
x = a
x /= b
assert dotest(s)
class NonBasic:
'''This class represents an object that knows how to implement binary
operations like +, -, etc with Expr but is not a subclass of Basic itself.
The NonExpr subclass below does subclass Basic but not Expr.
For both NonBasic and NonExpr it should be possible for them to override
Expr.__add__ etc because Expr.__add__ should be returning NotImplemented
for non Expr classes. Otherwise Expr.__add__ would create meaningless
objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for
other classes to override these operations when interacting with Expr.
'''
def __add__(self, other):
return SpecialOp('+', self, other)
def __radd__(self, other):
return SpecialOp('+', other, self)
def __sub__(self, other):
return SpecialOp('-', self, other)
def __rsub__(self, other):
return SpecialOp('-', other, self)
def __mul__(self, other):
return SpecialOp('*', self, other)
def __rmul__(self, other):
return SpecialOp('*', other, self)
def __truediv__(self, other):
return SpecialOp('/', self, other)
def __rtruediv__(self, other):
return SpecialOp('/', other, self)
def __floordiv__(self, other):
return SpecialOp('//', self, other)
def __rfloordiv__(self, other):
return SpecialOp('//', other, self)
def __mod__(self, other):
return SpecialOp('%', self, other)
def __rmod__(self, other):
return SpecialOp('%', other, self)
def __divmod__(self, other):
return SpecialOp('divmod', self, other)
def __rdivmod__(self, other):
return SpecialOp('divmod', other, self)
def __pow__(self, other):
return SpecialOp('**', self, other)
def __rpow__(self, other):
return SpecialOp('**', other, self)
def __lt__(self, other):
return SpecialOp('<', self, other)
def __gt__(self, other):
return SpecialOp('>', self, other)
def __le__(self, other):
return SpecialOp('<=', self, other)
def __ge__(self, other):
return SpecialOp('>=', self, other)
class NonExpr(Basic, NonBasic):
'''Like NonBasic above except this is a subclass of Basic but not Expr'''
pass
class SpecialOp():
'''Represents the results of operations with NonBasic and NonExpr'''
def __new__(cls, op, arg1, arg2):
obj = object.__new__(cls)
obj.args = (op, arg1, arg2)
return obj
class NonArithmetic(Basic):
'''Represents a Basic subclass that does not support arithmetic operations'''
pass
def test_cooperative_operations():
'''Tests that Expr uses binary operations cooperatively.
In particular it should be possible for non-Expr classes to override
binary operators like +, - etc when used with Expr instances. This should
work for non-Expr classes whether they are Basic subclasses or not. Also
non-Expr classes that do not define binary operators with Expr should give
TypeError.
'''
# A bunch of instances of Expr subclasses
exprs = [
Expr(),
S.Zero,
S.One,
S.Infinity,
S.NegativeInfinity,
S.ComplexInfinity,
S.Half,
Float(0.5),
Integer(2),
Symbol('x'),
Mul(2, Symbol('x')),
Add(2, Symbol('x')),
Pow(2, Symbol('x')),
]
for e in exprs:
# Test that these classes can override arithmetic operations in
# combination with various Expr types.
for ne in [NonBasic(), NonExpr()]:
results = [
(ne + e, ('+', ne, e)),
(e + ne, ('+', e, ne)),
(ne - e, ('-', ne, e)),
(e - ne, ('-', e, ne)),
(ne * e, ('*', ne, e)),
(e * ne, ('*', e, ne)),
(ne / e, ('/', ne, e)),
(e / ne, ('/', e, ne)),
(ne // e, ('//', ne, e)),
(e // ne, ('//', e, ne)),
(ne % e, ('%', ne, e)),
(e % ne, ('%', e, ne)),
(divmod(ne, e), ('divmod', ne, e)),
(divmod(e, ne), ('divmod', e, ne)),
(ne ** e, ('**', ne, e)),
(e ** ne, ('**', e, ne)),
(e < ne, ('>', ne, e)),
(ne < e, ('<', ne, e)),
(e > ne, ('<', ne, e)),
(ne > e, ('>', ne, e)),
(e <= ne, ('>=', ne, e)),
(ne <= e, ('<=', ne, e)),
(e >= ne, ('<=', ne, e)),
(ne >= e, ('>=', ne, e)),
]
for res, args in results:
assert type(res) is SpecialOp and res.args == args
# These classes do not support binary operators with Expr. Every
# operation should raise in combination with any of the Expr types.
for na in [NonArithmetic(), object()]:
raises(TypeError, lambda : e + na)
raises(TypeError, lambda : na + e)
raises(TypeError, lambda : e - na)
raises(TypeError, lambda : na - e)
raises(TypeError, lambda : e * na)
raises(TypeError, lambda : na * e)
raises(TypeError, lambda : e / na)
raises(TypeError, lambda : na / e)
raises(TypeError, lambda : e // na)
raises(TypeError, lambda : na // e)
raises(TypeError, lambda : e % na)
raises(TypeError, lambda : na % e)
raises(TypeError, lambda : divmod(e, na))
raises(TypeError, lambda : divmod(na, e))
raises(TypeError, lambda : e ** na)
raises(TypeError, lambda : na ** e)
raises(TypeError, lambda : e > na)
raises(TypeError, lambda : na > e)
raises(TypeError, lambda : e < na)
raises(TypeError, lambda : na < e)
raises(TypeError, lambda : e >= na)
raises(TypeError, lambda : na >= e)
raises(TypeError, lambda : e <= na)
raises(TypeError, lambda : na <= e)
def test_relational():
from sympy.core.relational import Lt
assert (pi < 3) is S.false
assert (pi <= 3) is S.false
assert (pi > 3) is S.true
assert (pi >= 3) is S.true
assert (-pi < 3) is S.true
assert (-pi <= 3) is S.true
assert (-pi > 3) is S.false
assert (-pi >= 3) is S.false
r = Symbol('r', real=True)
assert (r - 2 < r - 3) is S.false
assert Lt(x + I, x + I + 2).func == Lt # issue 8288
def test_relational_assumptions():
m1 = Symbol("m1", nonnegative=False)
m2 = Symbol("m2", positive=False)
m3 = Symbol("m3", nonpositive=False)
m4 = Symbol("m4", negative=False)
assert (m1 < 0) == Lt(m1, 0)
assert (m2 <= 0) == Le(m2, 0)
assert (m3 > 0) == Gt(m3, 0)
assert (m4 >= 0) == Ge(m4, 0)
m1 = Symbol("m1", nonnegative=False, real=True)
m2 = Symbol("m2", positive=False, real=True)
m3 = Symbol("m3", nonpositive=False, real=True)
m4 = Symbol("m4", negative=False, real=True)
assert (m1 < 0) is S.true
assert (m2 <= 0) is S.true
assert (m3 > 0) is S.true
assert (m4 >= 0) is S.true
m1 = Symbol("m1", negative=True)
m2 = Symbol("m2", nonpositive=True)
m3 = Symbol("m3", positive=True)
m4 = Symbol("m4", nonnegative=True)
assert (m1 < 0) is S.true
assert (m2 <= 0) is S.true
assert (m3 > 0) is S.true
assert (m4 >= 0) is S.true
m1 = Symbol("m1", negative=False, real=True)
m2 = Symbol("m2", nonpositive=False, real=True)
m3 = Symbol("m3", positive=False, real=True)
m4 = Symbol("m4", nonnegative=False, real=True)
assert (m1 < 0) is S.false
assert (m2 <= 0) is S.false
assert (m3 > 0) is S.false
assert (m4 >= 0) is S.false
# See https://github.com/sympy/sympy/issues/17708
#def test_relational_noncommutative():
# from sympy import Lt, Gt, Le, Ge
# A, B = symbols('A,B', commutative=False)
# assert (A < B) == Lt(A, B)
# assert (A <= B) == Le(A, B)
# assert (A > B) == Gt(A, B)
# assert (A >= B) == Ge(A, B)
def test_basic_nostr():
for obj in basic_objs:
raises(TypeError, lambda: obj + '1')
raises(TypeError, lambda: obj - '1')
if obj == 2:
assert obj * '1' == '11'
else:
raises(TypeError, lambda: obj * '1')
raises(TypeError, lambda: obj / '1')
raises(TypeError, lambda: obj ** '1')
def test_series_expansion_for_uniform_order():
assert (1/x + y + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + x).series(x, 0, 1) == 1/x + y + O(x)
assert (1/x + 1 + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + 1 + x).series(x, 0, 1) == 1/x + 1 + O(x)
assert (1/x + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + y*x + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + y*x + x).series(x, 0, 1) == 1/x + y + O(x)
def test_leadterm():
assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
assert (1/x**2 + 1 + x + x**2).leadterm(x)[1] == -2
assert (1/x + 1 + x + x**2).leadterm(x)[1] == -1
assert (x**2 + 1/x).leadterm(x)[1] == -1
assert (1 + x**2).leadterm(x)[1] == 0
assert (x + 1).leadterm(x)[1] == 0
assert (x + x**2).leadterm(x)[1] == 1
assert (x**2).leadterm(x)[1] == 2
def test_as_leading_term():
assert (3 + 2*x**(log(3)/log(2) - 1)).as_leading_term(x) == 3
assert (1/x**2 + 1 + x + x**2).as_leading_term(x) == 1/x**2
assert (1/x + 1 + x + x**2).as_leading_term(x) == 1/x
assert (x**2 + 1/x).as_leading_term(x) == 1/x
assert (1 + x**2).as_leading_term(x) == 1
assert (x + 1).as_leading_term(x) == 1
assert (x + x**2).as_leading_term(x) == x
assert (x**2).as_leading_term(x) == x**2
assert (x + oo).as_leading_term(x) is oo
raises(ValueError, lambda: (x + 1).as_leading_term(1))
# https://github.com/sympy/sympy/issues/21177
e = -3*x + (x + Rational(3, 2) - sqrt(3)*S.ImaginaryUnit/2)**2\
- Rational(3, 2) + 3*sqrt(3)*S.ImaginaryUnit/2
assert e.as_leading_term(x) == \
(12*sqrt(3)*x - 12*S.ImaginaryUnit*x)/(4*sqrt(3) + 12*S.ImaginaryUnit)
# https://github.com/sympy/sympy/issues/21245
e = 1 - x - x**2
d = (1 + sqrt(5))/2
assert e.subs(x, y + 1/d).as_leading_term(y) == \
(-576*sqrt(5)*y - 1280*y)/(256*sqrt(5) + 576)
def test_leadterm2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \
(sin(1 + sin(1)), 0)
def test_leadterm3():
assert (y + z + x).leadterm(x) == (y + z, 0)
def test_as_leading_term2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \
sin(1 + sin(1))
def test_as_leading_term3():
assert (2 + pi + x).as_leading_term(x) == 2 + pi
assert (2*x + pi*x + x**2).as_leading_term(x) == 2*x + pi*x
def test_as_leading_term4():
# see issue 6843
n = Symbol('n', integer=True, positive=True)
r = -n**3/(2*n**2 + 4*n + 2) - n**2/(n**2 + 2*n + 1) + \
n**2/(n + 1) - n/(2*n**2 + 4*n + 2) + n/(n*x + x) + 2*n/(n + 1) - \
1 + 1/(n*x + x) + 1/(n + 1) - 1/x
assert r.as_leading_term(x).cancel() == n/2
def test_as_leading_term_stub():
class foo(Function):
pass
assert foo(1/x).as_leading_term(x) == foo(1/x)
assert foo(1).as_leading_term(x) == foo(1)
raises(NotImplementedError, lambda: foo(x).as_leading_term(x))
def test_as_leading_term_deriv_integral():
# related to issue 11313
assert Derivative(x ** 3, x).as_leading_term(x) == 3*x**2
assert Derivative(x ** 3, y).as_leading_term(x) == 0
assert Integral(x ** 3, x).as_leading_term(x) == x**4/4
assert Integral(x ** 3, y).as_leading_term(x) == y*x**3
assert Derivative(exp(x), x).as_leading_term(x) == 1
assert Derivative(log(x), x).as_leading_term(x) == (1/x).as_leading_term(x)
def test_atoms():
assert x.atoms() == {x}
assert (1 + x).atoms() == {x, S.One}
assert (1 + 2*cos(x)).atoms(Symbol) == {x}
assert (1 + 2*cos(x)).atoms(Symbol, Number) == {S.One, S(2), x}
assert (2*(x**(y**x))).atoms() == {S(2), x, y}
assert S.Half.atoms() == {S.Half}
assert S.Half.atoms(Symbol) == set()
assert sin(oo).atoms(oo) == set()
assert Poly(0, x).atoms() == {S.Zero, x}
assert Poly(1, x).atoms() == {S.One, x}
assert Poly(x, x).atoms() == {x}
assert Poly(x, x, y).atoms() == {x, y}
assert Poly(x + y, x, y).atoms() == {x, y}
assert Poly(x + y, x, y, z).atoms() == {x, y, z}
assert Poly(x + y*t, x, y, z).atoms() == {t, x, y, z}
assert (I*pi).atoms(NumberSymbol) == {pi}
assert (I*pi).atoms(NumberSymbol, I) == \
(I*pi).atoms(I, NumberSymbol) == {pi, I}
assert exp(exp(x)).atoms(exp) == {exp(exp(x)), exp(x)}
assert (1 + x*(2 + y) + exp(3 + z)).atoms(Add) == \
{1 + x*(2 + y) + exp(3 + z), 2 + y, 3 + z}
# issue 6132
e = (f(x) + sin(x) + 2)
assert e.atoms(AppliedUndef) == \
{f(x)}
assert e.atoms(AppliedUndef, Function) == \
{f(x), sin(x)}
assert e.atoms(Function) == \
{f(x), sin(x)}
assert e.atoms(AppliedUndef, Number) == \
{f(x), S(2)}
assert e.atoms(Function, Number) == \
{S(2), sin(x), f(x)}
def test_is_polynomial():
k = Symbol('k', nonnegative=True, integer=True)
assert Rational(2).is_polynomial(x, y, z) is True
assert (S.Pi).is_polynomial(x, y, z) is True
assert x.is_polynomial(x) is True
assert x.is_polynomial(y) is True
assert (x**2).is_polynomial(x) is True
assert (x**2).is_polynomial(y) is True
assert (x**(-2)).is_polynomial(x) is False
assert (x**(-2)).is_polynomial(y) is True
assert (2**x).is_polynomial(x) is False
assert (2**x).is_polynomial(y) is True
assert (x**k).is_polynomial(x) is False
assert (x**k).is_polynomial(k) is False
assert (x**x).is_polynomial(x) is False
assert (k**k).is_polynomial(k) is False
assert (k**x).is_polynomial(k) is False
assert (x**(-k)).is_polynomial(x) is False
assert ((2*x)**k).is_polynomial(x) is False
assert (x**2 + 3*x - 8).is_polynomial(x) is True
assert (x**2 + 3*x - 8).is_polynomial(y) is True
assert (x**2 + 3*x - 8).is_polynomial() is True
assert sqrt(x).is_polynomial(x) is False
assert (sqrt(x)**3).is_polynomial(x) is False
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) is True
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) is False
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() is True
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() is False
assert (
(x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) is True
assert (
(x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) is False
assert (1/f(x) + 1).is_polynomial(f(x)) is False
def test_is_rational_function():
assert Integer(1).is_rational_function() is True
assert Integer(1).is_rational_function(x) is True
assert Rational(17, 54).is_rational_function() is True
assert Rational(17, 54).is_rational_function(x) is True
assert (12/x).is_rational_function() is True
assert (12/x).is_rational_function(x) is True
assert (x/y).is_rational_function() is True
assert (x/y).is_rational_function(x) is True
assert (x/y).is_rational_function(x, y) is True
assert (x**2 + 1/x/y).is_rational_function() is True
assert (x**2 + 1/x/y).is_rational_function(x) is True
assert (x**2 + 1/x/y).is_rational_function(x, y) is True
assert (sin(y)/x).is_rational_function() is False
assert (sin(y)/x).is_rational_function(y) is False
assert (sin(y)/x).is_rational_function(x) is True
assert (sin(y)/x).is_rational_function(x, y) is False
for i in _illegal:
assert not i.is_rational_function()
for d in (1, x):
assert not (i/d).is_rational_function()
def test_is_meromorphic():
f = a/x**2 + b + x + c*x**2
assert f.is_meromorphic(x, 0) is True
assert f.is_meromorphic(x, 1) is True
assert f.is_meromorphic(x, zoo) is True
g = 3 + 2*x**(log(3)/log(2) - 1)
assert g.is_meromorphic(x, 0) is False
assert g.is_meromorphic(x, 1) is True
assert g.is_meromorphic(x, zoo) is False
n = Symbol('n', integer=True)
e = sin(1/x)**n*x
assert e.is_meromorphic(x, 0) is False
assert e.is_meromorphic(x, 1) is True
assert e.is_meromorphic(x, zoo) is False
e = log(x)**pi
assert e.is_meromorphic(x, 0) is False
assert e.is_meromorphic(x, 1) is False
assert e.is_meromorphic(x, 2) is True
assert e.is_meromorphic(x, zoo) is False
assert (log(x)**a).is_meromorphic(x, 0) is False
assert (log(x)**a).is_meromorphic(x, 1) is False
assert (a**log(x)).is_meromorphic(x, 0) is None
assert (3**log(x)).is_meromorphic(x, 0) is False
assert (3**log(x)).is_meromorphic(x, 1) is True
def test_is_algebraic_expr():
assert sqrt(3).is_algebraic_expr(x) is True
assert sqrt(3).is_algebraic_expr() is True
eq = ((1 + x**2)/(1 - y**2))**(S.One/3)
assert eq.is_algebraic_expr(x) is True
assert eq.is_algebraic_expr(y) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(x) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(y) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr() is True
assert (cos(y)/sqrt(x)).is_algebraic_expr() is False
assert (cos(y)/sqrt(x)).is_algebraic_expr(x) is True
assert (cos(y)/sqrt(x)).is_algebraic_expr(y) is False
assert (cos(y)/sqrt(x)).is_algebraic_expr(x, y) is False
def test_SAGE1():
#see https://github.com/sympy/sympy/issues/3346
class MyInt:
def _sympy_(self):
return Integer(5)
m = MyInt()
e = Rational(2)*m
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE2():
class MyInt:
def __int__(self):
return 5
assert sympify(MyInt()) == 5
e = Rational(2)*MyInt()
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE3():
class MySymbol:
def __rmul__(self, other):
return ('mys', other, self)
o = MySymbol()
e = x*o
assert e == ('mys', x, o)
def test_len():
e = x*y
assert len(e.args) == 2
e = x + y + z
assert len(e.args) == 3
def test_doit():
a = Integral(x**2, x)
assert isinstance(a.doit(), Integral) is False
assert isinstance(a.doit(integrals=True), Integral) is False
assert isinstance(a.doit(integrals=False), Integral) is True
assert (2*Integral(x, x)).doit() == x**2
def test_attribute_error():
raises(AttributeError, lambda: x.cos())
raises(AttributeError, lambda: x.sin())
raises(AttributeError, lambda: x.exp())
def test_args():
assert (x*y).args in ((x, y), (y, x))
assert (x + y).args in ((x, y), (y, x))
assert (x*y + 1).args in ((x*y, 1), (1, x*y))
assert sin(x*y).args == (x*y,)
assert sin(x*y).args[0] == x*y
assert (x**y).args == (x, y)
assert (x**y).args[0] == x
assert (x**y).args[1] == y
def test_noncommutative_expand_issue_3757():
A, B, C = symbols('A,B,C', commutative=False)
assert A*B - B*A != 0
assert (A*(A + B)*B).expand() == A**2*B + A*B**2
assert (A*(A + B + C)*B).expand() == A**2*B + A*B**2 + A*C*B
def test_as_numer_denom():
a, b, c = symbols('a, b, c')
assert nan.as_numer_denom() == (nan, 1)
assert oo.as_numer_denom() == (oo, 1)
assert (-oo).as_numer_denom() == (-oo, 1)
assert zoo.as_numer_denom() == (zoo, 1)
assert (-zoo).as_numer_denom() == (zoo, 1)
assert x.as_numer_denom() == (x, 1)
assert (1/x).as_numer_denom() == (1, x)
assert (x/y).as_numer_denom() == (x, y)
assert (x/2).as_numer_denom() == (x, 2)
assert (x*y/z).as_numer_denom() == (x*y, z)
assert (x/(y*z)).as_numer_denom() == (x, y*z)
assert S.Half.as_numer_denom() == (1, 2)
assert (1/y**2).as_numer_denom() == (1, y**2)
assert (x/y**2).as_numer_denom() == (x, y**2)
assert ((x**2 + 1)/y).as_numer_denom() == (x**2 + 1, y)
assert (x*(y + 1)/y**7).as_numer_denom() == (x*(y + 1), y**7)
assert (x**-2).as_numer_denom() == (1, x**2)
assert (a/x + b/2/x + c/3/x).as_numer_denom() == \
(6*a + 3*b + 2*c, 6*x)
assert (a/x + b/2/x + c/3/y).as_numer_denom() == \
(2*c*x + y*(6*a + 3*b), 6*x*y)
assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \
(2*a + b + 4.0*c, 2*x)
# this should take no more than a few seconds
assert int(log(Add(*[Dummy()/i/x for i in range(1, 705)]
).as_numer_denom()[1]/x).n(4)) == 705
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).as_numer_denom() == \
(x + i, 3)
assert (S.Infinity + x/3 + y/4).as_numer_denom() == \
(4*x + 3*y + S.Infinity, 12)
assert (oo*x + zoo*y).as_numer_denom() == \
(zoo*y + oo*x, 1)
A, B, C = symbols('A,B,C', commutative=False)
assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1)
assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x)
assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1)
assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x)
assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1)
assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x)
# the following morphs from Add to Mul during processing
assert Add(0, (x + y)/z/-2, evaluate=False).as_numer_denom(
) == (-x - y, 2*z)
def test_trunc():
import math
x, y = symbols('x y')
assert math.trunc(2) == 2
assert math.trunc(4.57) == 4
assert math.trunc(-5.79) == -5
assert math.trunc(pi) == 3
assert math.trunc(log(7)) == 1
assert math.trunc(exp(5)) == 148
assert math.trunc(cos(pi)) == -1
assert math.trunc(sin(5)) == 0
raises(TypeError, lambda: math.trunc(x))
raises(TypeError, lambda: math.trunc(x + y**2))
raises(TypeError, lambda: math.trunc(oo))
def test_as_independent():
assert S.Zero.as_independent(x, as_Add=True) == (0, 0)
assert S.Zero.as_independent(x, as_Add=False) == (0, 0)
assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x))
assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y)
assert (2*x*sin(x) + y + x).as_independent(x, y) == (0, y + x + 2*x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y))
assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y))
assert (sin(x)).as_independent(x) == (1, sin(x))
assert (sin(x)).as_independent(y) == (sin(x), 1)
assert (2*sin(x)).as_independent(x) == (2, sin(x))
assert (2*sin(x)).as_independent(y) == (2*sin(x), 1)
# issue 4903 = 1766b
n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2)
assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1)
assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1)
assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1)
assert (3*x).as_independent(x, as_Add=True) == (0, 3*x)
assert (3*x).as_independent(x, as_Add=False) == (3, x)
assert (3 + x).as_independent(x, as_Add=True) == (3, x)
assert (3 + x).as_independent(x, as_Add=False) == (1, 3 + x)
# issue 5479
assert (3*x).as_independent(Symbol) == (3, x)
# issue 5648
assert (n1*x*y).as_independent(x) == (n1*y, x)
assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y))
assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y)
assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) \
== (1, DiracDelta(x - n1)*DiracDelta(x - y))
assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3)
assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3)
assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3)
assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \
(DiracDelta(x - n1)*DiracDelta(x - n2), DiracDelta(y - n1))
# issue 5784
assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \
(Integral(x, (x, 1, 2)), x)
eq = Add(x, -x, 2, -3, evaluate=False)
assert eq.as_independent(x) == (-1, Add(x, -x, evaluate=False))
eq = Mul(x, 1/x, 2, -3, evaluate=False)
assert eq.as_independent(x) == (-6, Mul(x, 1/x, evaluate=False))
assert (x*y).as_independent(z, as_Add=True) == (x*y, 0)
@XFAIL
def test_call_2():
# TODO UndefinedFunction does not subclass Expr
assert (2*f)(x) == 2*f(x)
def test_replace():
e = log(sin(x)) + tan(sin(x**2))
assert e.replace(sin, cos) == log(cos(x)) + tan(cos(x**2))
assert e.replace(
sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
a = Wild('a')
b = Wild('b')
assert e.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2))
assert e.replace(
sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
# test exact
assert (2*x).replace(a*x + b, b - a, exact=True) == 2*x
assert (2*x).replace(a*x + b, b - a) == 2*x
assert (2*x).replace(a*x + b, b - a, exact=False) == 2/x
assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=True) == 2*x
assert (2*x).replace(a*x + b, lambda a, b: b - a) == 2*x
assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=False) == 2/x
g = 2*sin(x**3)
assert g.replace(
lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9)
assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)})
assert sin(x).replace(cos, sin) == sin(x)
cond, func = lambda x: x.is_Mul, lambda x: 2*x
assert (x*y).replace(cond, func, map=True) == (2*x*y, {x*y: 2*x*y})
assert (x*(1 + x*y)).replace(cond, func, map=True) == \
(2*x*(2*x*y + 1), {x*(2*x*y + 1): 2*x*(2*x*y + 1), x*y: 2*x*y})
assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, map=True) == \
(sin(x), {sin(x): sin(x)/y})
# if not simultaneous then y*sin(x) -> y*sin(x)/y = sin(x) -> sin(x)/y
assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y,
simultaneous=False) == sin(x)/y
assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e
) == x**2/2 + O(x**3)
assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e,
simultaneous=False) == x**2/2 + O(x**3)
assert (x*(x*y + 3)).replace(lambda x: x.is_Mul, lambda x: 2 + x) == \
x*(x*y + 5) + 2
e = (x*y + 1)*(2*x*y + 1) + 1
assert e.replace(cond, func, map=True) == (
2*((2*x*y + 1)*(4*x*y + 1)) + 1,
{2*x*y: 4*x*y, x*y: 2*x*y, (2*x*y + 1)*(4*x*y + 1):
2*((2*x*y + 1)*(4*x*y + 1))})
assert x.replace(x, y) == y
assert (x + 1).replace(1, 2) == x + 2
# https://groups.google.com/forum/#!topic/sympy/8wCgeC95tz0
n1, n2, n3 = symbols('n1:4', commutative=False)
assert (n1*f(n2)).replace(f, lambda x: x) == n1*n2
assert (n3*f(n2)).replace(f, lambda x: x) == n3*n2
# issue 16725
assert S.Zero.replace(Wild('x'), 1) == 1
# let the user override the default decision of False
assert S.Zero.replace(Wild('x'), 1, exact=True) == 0
def test_find():
expr = (x + y + 2 + sin(3*x))
assert expr.find(lambda u: u.is_Integer) == {S(2), S(3)}
assert expr.find(lambda u: u.is_Symbol) == {x, y}
assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1}
assert expr.find(Integer) == {S(2), S(3)}
assert expr.find(Symbol) == {x, y}
assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(Symbol, group=True) == {x: 2, y: 1}
a = Wild('a')
expr = sin(sin(x)) + sin(x) + cos(x) + x
assert expr.find(lambda u: type(u) is sin) == {sin(x), sin(sin(x))}
assert expr.find(
lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin(a)) == {sin(x), sin(sin(x))}
assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin) == {sin(x), sin(sin(x))}
assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
def test_count():
expr = (x + y + 2 + sin(3*x))
assert expr.count(lambda u: u.is_Integer) == 2
assert expr.count(lambda u: u.is_Symbol) == 3
assert expr.count(Integer) == 2
assert expr.count(Symbol) == 3
assert expr.count(2) == 1
a = Wild('a')
assert expr.count(sin) == 1
assert expr.count(sin(a)) == 1
assert expr.count(lambda u: type(u) is sin) == 1
assert f(x).count(f(x)) == 1
assert f(x).diff(x).count(f(x)) == 1
assert f(x).diff(x).count(x) == 2
def test_has_basics():
p = Wild('p')
assert sin(x).has(x)
assert sin(x).has(sin)
assert not sin(x).has(y)
assert not sin(x).has(cos)
assert f(x).has(x)
assert f(x).has(f)
assert not f(x).has(y)
assert not f(x).has(g)
assert f(x).diff(x).has(x)
assert f(x).diff(x).has(f)
assert f(x).diff(x).has(Derivative)
assert not f(x).diff(x).has(y)
assert not f(x).diff(x).has(g)
assert not f(x).diff(x).has(sin)
assert (x**2).has(Symbol)
assert not (x**2).has(Wild)
assert (2*p).has(Wild)
assert not x.has()
def test_has_multiple():
f = x**2*y + sin(2**t + log(z))
assert f.has(x)
assert f.has(y)
assert f.has(z)
assert f.has(t)
assert not f.has(u)
assert f.has(x, y, z, t)
assert f.has(x, y, z, t, u)
i = Integer(4400)
assert not i.has(x)
assert (i*x**i).has(x)
assert not (i*y**i).has(x)
assert (i*y**i).has(x, y)
assert not (i*y**i).has(x, z)
def test_has_piecewise():
f = (x*y + 3/y)**(3 + 2)
p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True))
assert p.has(x)
assert p.has(y)
assert not p.has(z)
assert p.has(1)
assert p.has(3)
assert not p.has(4)
assert p.has(f)
assert p.has(g)
assert not p.has(h)
def test_has_iterative():
A, B, C = symbols('A,B,C', commutative=False)
f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B)
assert f.has(x)
assert f.has(x*y)
assert f.has(x*sin(x))
assert not f.has(x*sin(y))
assert f.has(x*A)
assert f.has(x*A*B)
assert not f.has(x*A*C)
assert f.has(x*A*B*C)
assert not f.has(x*A*C*B)
assert f.has(x*sin(x)*A*B*C)
assert not f.has(x*sin(x)*A*C*B)
assert not f.has(x*sin(y)*A*B*C)
assert f.has(x*gamma(x))
assert not f.has(x + sin(x))
assert (x & y & z).has(x & z)
def test_has_integrals():
f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z))
assert f.has(x + y)
assert f.has(x + z)
assert f.has(y + z)
assert f.has(x*y)
assert f.has(x*z)
assert f.has(y*z)
assert not f.has(2*x + y)
assert not f.has(2*x*y)
def test_has_tuple():
assert Tuple(x, y).has(x)
assert not Tuple(x, y).has(z)
assert Tuple(f(x), g(x)).has(x)
assert not Tuple(f(x), g(x)).has(y)
assert Tuple(f(x), g(x)).has(f)
assert Tuple(f(x), g(x)).has(f(x))
# XXX to be deprecated
#assert not Tuple(f, g).has(x)
#assert Tuple(f, g).has(f)
#assert not Tuple(f, g).has(h)
assert Tuple(True).has(True)
assert Tuple(True).has(S.true)
assert not Tuple(True).has(1)
def test_has_units():
from sympy.physics.units import m, s
assert (x*m/s).has(x)
assert (x*m/s).has(y, z) is False
def test_has_polys():
poly = Poly(x**2 + x*y*sin(z), x, y, t)
assert poly.has(x)
assert poly.has(x, y, z)
assert poly.has(x, y, z, t)
def test_has_physics():
assert FockState((x, y)).has(x)
def test_as_poly_as_expr():
f = x**2 + 2*x*y
assert f.as_poly().as_expr() == f
assert f.as_poly(x, y).as_expr() == f
assert (f + sin(x)).as_poly(x, y) is None
p = Poly(f, x, y)
assert p.as_poly() == p
# https://github.com/sympy/sympy/issues/20610
assert S(2).as_poly() is None
assert sqrt(2).as_poly(extension=True) is None
raises(AttributeError, lambda: Tuple(x, x).as_poly(x))
raises(AttributeError, lambda: Tuple(x ** 2, x, y).as_poly(x))
def test_nonzero():
assert bool(S.Zero) is False
assert bool(S.One) is True
assert bool(x) is True
assert bool(x + y) is True
assert bool(x - x) is False
assert bool(x*y) is True
assert bool(x*1) is True
assert bool(x*0) is False
def test_is_number():
assert Float(3.14).is_number is True
assert Integer(737).is_number is True
assert Rational(3, 2).is_number is True
assert Rational(8).is_number is True
assert x.is_number is False
assert (2*x).is_number is False
assert (x + y).is_number is False
assert log(2).is_number is True
assert log(x).is_number is False
assert (2 + log(2)).is_number is True
assert (8 + log(2)).is_number is True
assert (2 + log(x)).is_number is False
assert (8 + log(2) + x).is_number is False
assert (1 + x**2/x - x).is_number is True
assert Tuple(Integer(1)).is_number is False
assert Add(2, x).is_number is False
assert Mul(3, 4).is_number is True
assert Pow(log(2), 2).is_number is True
assert oo.is_number is True
g = WildFunction('g')
assert g.is_number is False
assert (2*g).is_number is False
assert (x**2).subs(x, 3).is_number is True
# test extensibility of .is_number
# on subinstances of Basic
class A(Basic):
pass
a = A()
assert a.is_number is False
def test_as_coeff_add():
assert S(2).as_coeff_add() == (2, ())
assert S(3.0).as_coeff_add() == (0, (S(3.0),))
assert S(-3.0).as_coeff_add() == (0, (S(-3.0),))
assert x.as_coeff_add() == (0, (x,))
assert (x - 1).as_coeff_add() == (-1, (x,))
assert (x + 1).as_coeff_add() == (1, (x,))
assert (x + 2).as_coeff_add() == (2, (x,))
assert (x + y).as_coeff_add(y) == (x, (y,))
assert (3*x).as_coeff_add(y) == (3*x, ())
# don't do expansion
e = (x + y)**2
assert e.as_coeff_add(y) == (0, (e,))
def test_as_coeff_mul():
assert S(2).as_coeff_mul() == (2, ())
assert S(3.0).as_coeff_mul() == (1, (S(3.0),))
assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),))
assert S(-3.0).as_coeff_mul(rational=False) == (-S(3.0), ())
assert x.as_coeff_mul() == (1, (x,))
assert (-x).as_coeff_mul() == (-1, (x,))
assert (2*x).as_coeff_mul() == (2, (x,))
assert (x*y).as_coeff_mul(y) == (x, (y,))
assert (3 + x).as_coeff_mul() == (1, (3 + x,))
assert (3 + x).as_coeff_mul(y) == (3 + x, ())
# don't do expansion
e = exp(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
e = 2**(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
assert (1.1*x).as_coeff_mul(rational=False) == (1.1, (x,))
assert (1.1*x).as_coeff_mul() == (1, (1.1, x))
assert (-oo*x).as_coeff_mul(rational=True) == (-1, (oo, x))
def test_as_coeff_exponent():
assert (3*x**4).as_coeff_exponent(x) == (3, 4)
assert (2*x**3).as_coeff_exponent(x) == (2, 3)
assert (4*x**2).as_coeff_exponent(x) == (4, 2)
assert (6*x**1).as_coeff_exponent(x) == (6, 1)
assert (3*x**0).as_coeff_exponent(x) == (3, 0)
assert (2*x**0).as_coeff_exponent(x) == (2, 0)
assert (1*x**0).as_coeff_exponent(x) == (1, 0)
assert (0*x**0).as_coeff_exponent(x) == (0, 0)
assert (-1*x**0).as_coeff_exponent(x) == (-1, 0)
assert (-2*x**0).as_coeff_exponent(x) == (-2, 0)
assert (2*x**3 + pi*x**3).as_coeff_exponent(x) == (2 + pi, 3)
assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \
(log(2)/(2 + pi), 0)
# issue 4784
D = Derivative
fx = D(f(x), x)
assert fx.as_coeff_exponent(f(x)) == (fx, 0)
def test_extractions():
for base in (2, S.Exp1):
assert Pow(base**x, 3, evaluate=False
).extract_multiplicatively(base**x) == base**(2*x)
assert (base**(5*x)).extract_multiplicatively(
base**(3*x)) == base**(2*x)
assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2
assert ((x*y)**3).extract_multiplicatively(x**4 * y) is None
assert (2*x).extract_multiplicatively(2) == x
assert (2*x).extract_multiplicatively(3) is None
assert (2*x).extract_multiplicatively(-1) is None
assert (S.Half*x).extract_multiplicatively(3) == x/6
assert (sqrt(x)).extract_multiplicatively(x) is None
assert (sqrt(x)).extract_multiplicatively(1/x) is None
assert x.extract_multiplicatively(-x) is None
assert (-2 - 4*I).extract_multiplicatively(-2) == 1 + 2*I
assert (-2 - 4*I).extract_multiplicatively(3) is None
assert (-2*x - 4*y - 8).extract_multiplicatively(-2) == x + 2*y + 4
assert (-2*x*y - 4*x**2*y).extract_multiplicatively(-2*y) == 2*x**2 + x
assert (2*x*y + 4*x**2*y).extract_multiplicatively(2*y) == 2*x**2 + x
assert (-4*y**2*x).extract_multiplicatively(-3*y) is None
assert (2*x).extract_multiplicatively(1) == 2*x
assert (-oo).extract_multiplicatively(5) is -oo
assert (oo).extract_multiplicatively(5) is oo
assert ((x*y)**3).extract_additively(1) is None
assert (x + 1).extract_additively(x) == 1
assert (x + 1).extract_additively(2*x) is None
assert (x + 1).extract_additively(-x) is None
assert (-x + 1).extract_additively(2*x) is None
assert (2*x + 3).extract_additively(x) == x + 3
assert (2*x + 3).extract_additively(2) == 2*x + 1
assert (2*x + 3).extract_additively(3) == 2*x
assert (2*x + 3).extract_additively(-2) is None
assert (2*x + 3).extract_additively(3*x) is None
assert (2*x + 3).extract_additively(2*x) == 3
assert x.extract_additively(0) == x
assert S(2).extract_additively(x) is None
assert S(2.).extract_additively(2) is S.Zero
assert S(2*x + 3).extract_additively(x + 1) == x + 2
assert S(2*x + 3).extract_additively(y + 1) is None
assert S(2*x - 3).extract_additively(x + 1) is None
assert S(2*x - 3).extract_additively(y + z) is None
assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \
4*a*x + 3*x + y
assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \
4*a*x + 3*x + y
assert (y*(x + 1)).extract_additively(x + 1) is None
assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \
y*(x + 1) + 3
assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \
x*(x + y) + 3
assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \
x + y + (x + 1)*(x + y) + 3
assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \
(x + 2*y)*(y + 1) + 3
assert (-x - x*I).extract_additively(-x) == -I*x
# extraction does not leave artificats, now
assert (4*x*(y + 1) + y).extract_additively(x) == x*(4*y + 3) + y
n = Symbol("n", integer=True)
assert (Integer(-3)).could_extract_minus_sign() is True
assert (-n*x + x).could_extract_minus_sign() != \
(n*x - x).could_extract_minus_sign()
assert (x - y).could_extract_minus_sign() != \
(-x + y).could_extract_minus_sign()
assert (1 - x - y).could_extract_minus_sign() is True
assert (1 - x + y).could_extract_minus_sign() is False
assert ((-x - x*y)/y).could_extract_minus_sign() is False
assert ((x + x*y)/(-y)).could_extract_minus_sign() is True
assert ((x + x*y)/y).could_extract_minus_sign() is False
assert ((-x - y)/(x + y)).could_extract_minus_sign() is False
class sign_invariant(Function, Expr):
nargs = 1
def __neg__(self):
return self
foo = sign_invariant(x)
assert foo == -foo
assert foo.could_extract_minus_sign() is False
assert (x - y).could_extract_minus_sign() is False
assert (-x + y).could_extract_minus_sign() is True
assert (x - 1).could_extract_minus_sign() is False
assert (1 - x).could_extract_minus_sign() is True
assert (sqrt(2) - 1).could_extract_minus_sign() is True
assert (1 - sqrt(2)).could_extract_minus_sign() is False
# check that result is canonical
eq = (3*x + 15*y).extract_multiplicatively(3)
assert eq.args == eq.func(*eq.args).args
def test_nan_extractions():
for r in (1, 0, I, nan):
assert nan.extract_additively(r) is None
assert nan.extract_multiplicatively(r) is None
def test_coeff():
assert (x + 1).coeff(x + 1) == 1
assert (3*x).coeff(0) == 0
assert (z*(1 + x)*x**2).coeff(1 + x) == z*x**2
assert (1 + 2*x*x**(1 + x)).coeff(x*x**(1 + x)) == 2
assert (1 + 2*x**(y + z)).coeff(x**(y + z)) == 2
assert (3 + 2*x + 4*x**2).coeff(1) == 0
assert (3 + 2*x + 4*x**2).coeff(-1) == 0
assert (3 + 2*x + 4*x**2).coeff(x) == 2
assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
assert (-x/8 + x*y).coeff(x) == Rational(-1, 8) + y
assert (-x/8 + x*y).coeff(-x) == S.One/8
assert (4*x).coeff(2*x) == 0
assert (2*x).coeff(2*x) == 1
assert (-oo*x).coeff(x*oo) == -1
assert (10*x).coeff(x, 0) == 0
assert (10*x).coeff(10*x, 0) == 0
n1, n2 = symbols('n1 n2', commutative=False)
assert (n1*n2).coeff(n1) == 1
assert (n1*n2).coeff(n2) == n1
assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x)
assert (n2*n1 + x*n1).coeff(n1) == n2 + x
assert (n2*n1 + x*n1**2).coeff(n1) == n2
assert (n1**x).coeff(n1) == 0
assert (n1*n2 + n2*n1).coeff(n1) == 0
assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=1) == n2
assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=0) == 2
assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2
expr = z*(x + y)**2
expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x + y)**2
assert expr.coeff(x + y) == 0
assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
assert (x + y + 3*z).coeff(1) == x + y
assert (-x + 2*y).coeff(-1) == x
assert (x - 2*y).coeff(-1) == 2*y
assert (3 + 2*x + 4*x**2).coeff(1) == 0
assert (-x - 2*y).coeff(2) == -y
assert (x + sqrt(2)*x).coeff(sqrt(2)) == x
assert (3 + 2*x + 4*x**2).coeff(x) == 2
assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
assert (z*(x + y)**2).coeff((x + y)**2) == z
assert (z*(x + y)**2).coeff(x + y) == 0
assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y
assert (x + 2*y + 3).coeff(1) == x
assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3
assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x
assert x.coeff(0, 0) == 0
assert x.coeff(x, 0) == 0
n, m, o, l = symbols('n m o l', commutative=False)
assert n.coeff(n) == 1
assert y.coeff(n) == 0
assert (3*n).coeff(n) == 3
assert (2 + n).coeff(x*m) == 0
assert (2*x*n*m).coeff(x) == 2*n*m
assert (2 + n).coeff(x*m*n + y) == 0
assert (2*x*n*m).coeff(3*n) == 0
assert (n*m + m*n*m).coeff(n) == 1 + m
assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m
assert (n*m + m*n).coeff(n) == 0
assert (n*m + o*m*n).coeff(m*n) == o
assert (n*m + o*m*n).coeff(m*n, right=True) == 1
assert (n*m + n*m*n).coeff(n*m, right=True) == 1 + n # = n*m*(n + 1)
assert (x*y).coeff(z, 0) == x*y
assert (x*n + y*n + z*m).coeff(n) == x + y
assert (n*m + n*o + o*l).coeff(n, right=True) == m + o
assert (x*n*m*n + y*n*m*o + z*l).coeff(m, right=True) == x*n + y*o
assert (x*n*m*n + x*n*m*o + z*l).coeff(m, right=True) == n + o
assert (x*n*m*n + x*n*m*o + z*l).coeff(m) == x*n
def test_coeff2():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff(psi(r).diff(r)) == 2/r
def test_coeff2_0():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff(psi(r).diff(r, 2)) == 1
def test_coeff_expand():
expr = z*(x + y)**2
expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x + y)**2
assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
def test_integrate():
assert x.integrate(x) == x**2/2
assert x.integrate((x, 0, 1)) == S.Half
def test_as_base_exp():
assert x.as_base_exp() == (x, S.One)
assert (x*y*z).as_base_exp() == (x*y*z, S.One)
assert (x + y + z).as_base_exp() == (x + y + z, S.One)
assert ((x + y)**z).as_base_exp() == (x + y, z)
def test_issue_4963():
assert hasattr(Mul(x, y), "is_commutative")
assert hasattr(Mul(x, y, evaluate=False), "is_commutative")
assert hasattr(Pow(x, y), "is_commutative")
assert hasattr(Pow(x, y, evaluate=False), "is_commutative")
expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1
assert hasattr(expr, "is_commutative")
def test_action_verbs():
assert nsimplify(1/(exp(3*pi*x/5) + 1)) == \
(1/(exp(3*pi*x/5) + 1)).nsimplify()
assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep=True)
assert radsimp(1/(2 + sqrt(2))) == (1/(2 + sqrt(2))).radsimp()
assert radsimp(1/(a + b*sqrt(c)), symbolic=False) == \
(1/(a + b*sqrt(c))).radsimp(symbolic=False)
assert powsimp(x**y*x**z*y**z, combine='all') == \
(x**y*x**z*y**z).powsimp(combine='all')
assert (x**t*y**t).powsimp(force=True) == (x*y)**t
assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
assert together(1/x + 1/y) == (1/x + 1/y).together()
assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == \
(a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
assert apart(y/(y + 2)/(y + 1), y) == (y/(y + 2)/(y + 1)).apart(y)
assert combsimp(y/(x + 2)/(x + 1)) == (y/(x + 2)/(x + 1)).combsimp()
assert gammasimp(gamma(x)/gamma(x-5)) == (gamma(x)/gamma(x-5)).gammasimp()
assert factor(x**2 + 5*x + 6) == (x**2 + 5*x + 6).factor()
assert refine(sqrt(x**2)) == sqrt(x**2).refine()
assert cancel((x**2 + 5*x + 6)/(x + 2)) == ((x**2 + 5*x + 6)/(x + 2)).cancel()
def test_as_powers_dict():
assert x.as_powers_dict() == {x: 1}
assert (x**y*z).as_powers_dict() == {x: y, z: 1}
assert Mul(2, 2, evaluate=False).as_powers_dict() == {S(2): S(2)}
assert (x*y).as_powers_dict()[z] == 0
assert (x + y).as_powers_dict()[z] == 0
def test_as_coefficients_dict():
check = [S.One, x, y, x*y, 1]
assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \
[3, 5, 1, 0, 3]
assert [Add(3*x, 2*x, y, 3, evaluate=False).as_coefficients_dict()[i]
for i in check] == [3, 5, 1, 0, 3]
assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \
[0, 0, 0, 3, 0]
assert [(3.0*x*y).as_coefficients_dict()[i] for i in check] == \
[0, 0, 0, 3.0, 0]
assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0
eq = x*(x + 1)*a + x*b + c/x
assert eq.as_coefficients_dict(x) == {x: b, 1/x: c,
x*(x + 1): a}
assert eq.expand().as_coefficients_dict(x) == {x**2: a, x: a + b, 1/x: c}
assert x.as_coefficients_dict() == {x: S.One}
def test_args_cnc():
A = symbols('A', commutative=False)
assert (x + A).args_cnc() == \
[[], [x + A]]
assert (x + a).args_cnc() == \
[[a + x], []]
assert (x*a).args_cnc() == \
[[a, x], []]
assert (x*y*A*(A + 1)).args_cnc(cset=True) == \
[{x, y}, [A, 1 + A]]
assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \
[{x}, []]
assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \
[{x, x**2}, []]
raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True))
assert Mul(x, y, x, evaluate=False).args_cnc() == \
[[x, y, x], []]
# always split -1 from leading number
assert (-1.*x).args_cnc() == [[-1, 1.0, x], []]
def test_new_rawargs():
n = Symbol('n', commutative=False)
a = x + n
assert a.is_commutative is False
assert a._new_rawargs(x).is_commutative
assert a._new_rawargs(x, y).is_commutative
assert a._new_rawargs(x, n).is_commutative is False
assert a._new_rawargs(x, y, n).is_commutative is False
m = x*n
assert m.is_commutative is False
assert m._new_rawargs(x).is_commutative
assert m._new_rawargs(n).is_commutative is False
assert m._new_rawargs(x, y).is_commutative
assert m._new_rawargs(x, n).is_commutative is False
assert m._new_rawargs(x, y, n).is_commutative is False
assert m._new_rawargs(x, n, reeval=False).is_commutative is False
assert m._new_rawargs(S.One) is S.One
def test_issue_5226():
assert Add(evaluate=False) == 0
assert Mul(evaluate=False) == 1
assert Mul(x + y, evaluate=False).is_Add
def test_free_symbols():
# free_symbols should return the free symbols of an object
assert S.One.free_symbols == set()
assert x.free_symbols == {x}
assert Integral(x, (x, 1, y)).free_symbols == {y}
assert (-Integral(x, (x, 1, y))).free_symbols == {y}
assert meter.free_symbols == set()
assert (meter**x).free_symbols == {x}
def test_has_free():
assert x.has_free(x)
assert not x.has_free(y)
assert (x + y).has_free(x)
assert (x + y).has_free(*(x, z))
assert f(x).has_free(x)
assert f(x).has_free(f(x))
assert Integral(f(x), (f(x), 1, y)).has_free(y)
assert not Integral(f(x), (f(x), 1, y)).has_free(x)
assert not Integral(f(x), (f(x), 1, y)).has_free(f(x))
# simple extraction
assert (x + 1 + y).has_free(x + 1)
assert not (x + 2 + y).has_free(x + 1)
assert (2 + 3*x*y).has_free(3*x)
raises(TypeError, lambda: x.has_free({x, y}))
s = FiniteSet(1, 2)
assert Piecewise((s, x > 3), (4, True)).has_free(s)
assert not Piecewise((1, x > 3), (4, True)).has_free(s)
# can't make set of these, but fallback will handle
raises(TypeError, lambda: x.has_free(y, []))
def test_has_xfree():
assert (x + 1).has_xfree({x})
assert ((x + 1)**2).has_xfree({x + 1})
assert not (x + y + 1).has_xfree({x + 1})
raises(TypeError, lambda: x.has_xfree(x))
raises(TypeError, lambda: x.has_xfree([x]))
def test_issue_5300():
x = Symbol('x', commutative=False)
assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3
def test_floordiv():
from sympy.functions.elementary.integers import floor
assert x // y == floor(x / y)
def test_as_coeff_Mul():
assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1))
assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1))
assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1))
assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x)
assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x)
assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x)
assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y)
assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y)
assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y)
assert (x).as_coeff_Mul() == (S.One, x)
assert (x*y).as_coeff_Mul() == (S.One, x*y)
assert (-oo*x).as_coeff_Mul(rational=True) == (-1, oo*x)
def test_as_coeff_Add():
assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0))
assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0))
assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0))
assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x)
assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x)
assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x)
assert (Float(5.0) + x).as_coeff_Add(rational=True) == (0, Float(5.0) + x)
assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y)
assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y)
assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y)
assert (x).as_coeff_Add() == (S.Zero, x)
assert (x*y).as_coeff_Add() == (S.Zero, x*y)
def test_expr_sorting():
exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n,
sin(x**2), cos(x), cos(x**2), tan(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[3], [1, 2]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [1, 2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [{x: -y}, {x: y}]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [{1}, {1, 2}]
assert sorted(exprs, key=default_sort_key) == exprs
a, b = exprs = [Dummy('x'), Dummy('x')]
assert sorted([b, a], key=default_sort_key) == exprs
def test_as_ordered_factors():
assert x.as_ordered_factors() == [x]
assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() \
== [Integer(2), x, x**n, sin(x), cos(x)]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Mul(*args)
assert expr.as_ordered_factors() == args
A, B = symbols('A,B', commutative=False)
assert (A*B).as_ordered_factors() == [A, B]
assert (B*A).as_ordered_factors() == [B, A]
def test_as_ordered_terms():
assert x.as_ordered_terms() == [x]
assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() \
== [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Add(*args)
assert expr.as_ordered_terms() == args
assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1]
assert ( 2 + 3*I).as_ordered_terms() == [2, 3*I]
assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I]
assert ( 2 - 3*I).as_ordered_terms() == [2, -3*I]
assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I]
assert ( 4 + 3*I).as_ordered_terms() == [4, 3*I]
assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I]
assert ( 4 - 3*I).as_ordered_terms() == [4, -3*I]
assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I]
e = x**2*y**2 + x*y**4 + y + 2
assert e.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2]
assert e.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2]
assert e.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2]
assert e.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4]
k = symbols('k')
assert k.as_ordered_terms(data=True) == ([(k, ((1.0, 0.0), (1,), ()))], [k])
def test_sort_key_atomic_expr():
from sympy.physics.units import m, s
assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s]
def test_eval_interval():
assert exp(x)._eval_interval(*Tuple(x, 0, 1)) == exp(1) - exp(0)
# issue 4199
a = x/y
raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero))
raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo))
a = x - y
raises(NotImplementedError, lambda: a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One))
raises(ValueError, lambda: x._eval_interval(x, None, None))
a = -y*Heaviside(x - y)
assert a._eval_interval(x, -oo, oo) == -y
assert a._eval_interval(x, oo, -oo) == y
def test_eval_interval_zoo():
# Test that limit is used when zoo is returned
assert Si(1/x)._eval_interval(x, S.Zero, S.One) == -pi/2 + Si(1)
def test_primitive():
assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2)
assert (6*x + 2).primitive() == (2, 3*x + 1)
assert (x/2 + 3).primitive() == (S.Half, x + 6)
eq = (6*x + 2)*(x/2 + 3)
assert eq.primitive()[0] == 1
eq = (2 + 2*x)**2
assert eq.primitive()[0] == 1
assert (4.0*x).primitive() == (1, 4.0*x)
assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y)
assert (-2*x).primitive() == (2, -x)
assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \
(S.One/14, 7.0*x + 21*y + 10*z)
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).primitive() == \
(S.One/3, i + x)
assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \
(S.One/21, 14*x + 12*y + oo)
assert S.Zero.primitive() == (S.One, S.Zero)
def test_issue_5843():
a = 1 + x
assert (2*a).extract_multiplicatively(a) == 2
assert (4*a).extract_multiplicatively(2*a) == 2
assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a
def test_is_constant():
from sympy.solvers.solvers import checksol
assert Sum(x, (x, 1, 10)).is_constant() is True
assert Sum(x, (x, 1, n)).is_constant() is False
assert Sum(x, (x, 1, n)).is_constant(y) is True
assert Sum(x, (x, 1, n)).is_constant(n) is False
assert Sum(x, (x, 1, n)).is_constant(x) is True
eq = a*cos(x)**2 + a*sin(x)**2 - a
assert eq.is_constant() is True
assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
assert x.is_constant() is False
assert x.is_constant(y) is True
assert log(x/y).is_constant() is False
assert checksol(x, x, Sum(x, (x, 1, n))) is False
assert checksol(x, x, Sum(x, (x, 1, n))) is False
assert f(1).is_constant
assert checksol(x, x, f(x)) is False
assert Pow(x, S.Zero, evaluate=False).is_constant() is True # == 1
assert Pow(S.Zero, x, evaluate=False).is_constant() is False # == 0 or 1
assert (2**x).is_constant() is False
assert Pow(S(2), S(3), evaluate=False).is_constant() is True
z1, z2 = symbols('z1 z2', zero=True)
assert (z1 + 2*z2).is_constant() is True
assert meter.is_constant() is True
assert (3*meter).is_constant() is True
assert (x*meter).is_constant() is False
def test_equals():
assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0)
assert (x**2 - 1).equals((x + 1)*(x - 1))
assert (cos(x)**2 + sin(x)**2).equals(1)
assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
r = sqrt(2)
assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
assert factorial(x + 1).equals((x + 1)*factorial(x))
assert sqrt(3).equals(2*sqrt(3)) is False
assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False
assert (sqrt(5) + sqrt(3)).equals(0) is False
assert (sqrt(5) + pi).equals(0) is False
assert meter.equals(0) is False
assert (3*meter**2).equals(0) is False
eq = -(-1)**(S(3)/4)*6**(S.One/4) + (-6)**(S.One/4)*I
if eq != 0: # if canonicalization makes this zero, skip the test
assert eq.equals(0)
assert sqrt(x).equals(0) is False
# from integrate(x*sqrt(1 + 2*x), x);
# diff is zero only when assumptions allow
i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \
2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x)
ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15
diff = i - ans
assert diff.equals(0) is None # should be False, but previously this was False due to wrong intermediate result
assert diff.subs(x, Rational(-1, 2)/2) == 7*sqrt(2)/120
# there are regions for x for which the expression is True, for
# example, when x < -1/2 or x > 0 the expression is zero
p = Symbol('p', positive=True)
assert diff.subs(x, p).equals(0) is True
assert diff.subs(x, -1).equals(0) is True
# prove via minimal_polynomial or self-consistency
eq = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
assert eq.equals(0)
q = 3**Rational(1, 3) + 3
p = expand(q**3)**Rational(1, 3)
assert (p - q).equals(0)
# issue 6829
# eq = q*x + q/4 + x**4 + x**3 + 2*x**2 - S.One/3
# z = eq.subs(x, solve(eq, x)[0])
q = symbols('q')
z = (q*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4) + q/4 + (-sqrt(-2*(-(q
- S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q
- S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**3 + 2*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**2 - Rational(1, 3))
assert z.equals(0)
def test_random():
from sympy.functions.combinatorial.numbers import lucas
from sympy.simplify.simplify import posify
assert posify(x)[0]._random() is not None
assert lucas(n)._random(2, -2, 0, -1, 1) is None
# issue 8662
assert Piecewise((Max(x, y), z))._random() is None
def test_round():
assert str(Float('0.1249999').round(2)) == '0.12'
d20 = 12345678901234567890
ans = S(d20).round(2)
assert ans.is_Integer and ans == d20
ans = S(d20).round(-2)
assert ans.is_Integer and ans == 12345678901234567900
assert str(S('1/7').round(4)) == '0.1429'
assert str(S('.[12345]').round(4)) == '0.1235'
assert str(S('.1349').round(2)) == '0.13'
n = S(12345)
ans = n.round()
assert ans.is_Integer
assert ans == n
ans = n.round(1)
assert ans.is_Integer
assert ans == n
ans = n.round(4)
assert ans.is_Integer
assert ans == n
assert n.round(-1) == 12340
r = Float(str(n)).round(-4)
assert r == 10000
assert n.round(-5) == 0
assert str((pi + sqrt(2)).round(2)) == '4.56'
assert (10*(pi + sqrt(2))).round(-1) == 50
raises(TypeError, lambda: round(x + 2, 2))
assert str(S(2.3).round(1)) == '2.3'
# rounding in SymPy (as in Decimal) should be
# exact for the given precision; we check here
# that when a 5 follows the last digit that
# the rounded digit will be even.
for i in range(-99, 100):
# construct a decimal that ends in 5, e.g. 123 -> 0.1235
s = str(abs(i))
p = len(s) # we are going to round to the last digit of i
n = '0.%s5' % s # put a 5 after i's digits
j = p + 2 # 2 for '0.'
if i < 0: # 1 for '-'
j += 1
n = '-' + n
v = str(Float(n).round(p))[:j] # pertinent digits
if v.endswith('.'):
continue # it ends with 0 which is even
L = int(v[-1]) # last digit
assert L % 2 == 0, (n, '->', v)
assert (Float(.3, 3) + 2*pi).round() == 7
assert (Float(.3, 3) + 2*pi*100).round() == 629
assert (pi + 2*E*I).round() == 3 + 5*I
# don't let request for extra precision give more than
# what is known (in this case, only 3 digits)
assert str((Float(.03, 3) + 2*pi/100).round(5)) == '0.0928'
assert str((Float(.03, 3) + 2*pi/100).round(4)) == '0.0928'
assert S.Zero.round() == 0
a = (Add(1, Float('1.' + '9'*27, ''), evaluate=0))
assert a.round(10) == Float('3.0000000000', '')
assert a.round(25) == Float('3.0000000000000000000000000', '')
assert a.round(26) == Float('3.00000000000000000000000000', '')
assert a.round(27) == Float('2.999999999999999999999999999', '')
assert a.round(30) == Float('2.999999999999999999999999999', '')
raises(TypeError, lambda: x.round())
raises(TypeError, lambda: f(1).round())
# exact magnitude of 10
assert str(S.One.round()) == '1'
assert str(S(100).round()) == '100'
# applied to real and imaginary portions
assert (2*pi + E*I).round() == 6 + 3*I
assert (2*pi + I/10).round() == 6
assert (pi/10 + 2*I).round() == 2*I
# the lhs re and im parts are Float with dps of 2
# and those on the right have dps of 15 so they won't compare
# equal unless we use string or compare components (which will
# then coerce the floats to the same precision) or re-create
# the floats
assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
assert str((pi/10 + E*I).round(2).as_real_imag()) == '(0.31, 2.72)'
assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
# issue 6914
assert (I**(I + 3)).round(3) == Float('-0.208', '')*I
# issue 8720
assert S(-123.6).round() == -124
assert S(-1.5).round() == -2
assert S(-100.5).round() == -100
assert S(-1.5 - 10.5*I).round() == -2 - 10*I
# issue 7961
assert str(S(0.006).round(2)) == '0.01'
assert str(S(0.00106).round(4)) == '0.0011'
# issue 8147
assert S.NaN.round() is S.NaN
assert S.Infinity.round() is S.Infinity
assert S.NegativeInfinity.round() is S.NegativeInfinity
assert S.ComplexInfinity.round() is S.ComplexInfinity
# check that types match
for i in range(2):
fi = float(i)
# 2 args
assert all(type(round(i, p)) is int for p in (-1, 0, 1))
assert all(S(i).round(p).is_Integer for p in (-1, 0, 1))
assert all(type(round(fi, p)) is float for p in (-1, 0, 1))
assert all(S(fi).round(p).is_Float for p in (-1, 0, 1))
# 1 arg (p is None)
assert type(round(i)) is int
assert S(i).round().is_Integer
assert type(round(fi)) is int
assert S(fi).round().is_Integer
def test_held_expression_UnevaluatedExpr():
x = symbols("x")
he = UnevaluatedExpr(1/x)
e1 = x*he
assert isinstance(e1, Mul)
assert e1.args == (x, he)
assert e1.doit() == 1
assert UnevaluatedExpr(Derivative(x, x)).doit(deep=False
) == Derivative(x, x)
assert UnevaluatedExpr(Derivative(x, x)).doit() == 1
xx = Mul(x, x, evaluate=False)
assert xx != x**2
ue2 = UnevaluatedExpr(xx)
assert isinstance(ue2, UnevaluatedExpr)
assert ue2.args == (xx,)
assert ue2.doit() == x**2
assert ue2.doit(deep=False) == xx
x2 = UnevaluatedExpr(2)*2
assert type(x2) is Mul
assert x2.args == (2, UnevaluatedExpr(2))
def test_round_exception_nostr():
# Don't use the string form of the expression in the round exception, as
# it's too slow
s = Symbol('bad')
try:
s.round()
except TypeError as e:
assert 'bad' not in str(e)
else:
# Did not raise
raise AssertionError("Did not raise")
def test_extract_branch_factor():
assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1)
def test_identity_removal():
assert Add.make_args(x + 0) == (x,)
assert Mul.make_args(x*1) == (x,)
def test_float_0():
assert Float(0.0) + 1 == Float(1.0)
@XFAIL
def test_float_0_fail():
assert Float(0.0)*x == Float(0.0)
assert (x + Float(0.0)).is_Add
def test_issue_6325():
ans = (b**2 + z**2 - (b*(a + b*t) + z*(c + t*z))**2/(
(a + b*t)**2 + (c + t*z)**2))/sqrt((a + b*t)**2 + (c + t*z)**2)
e = sqrt((a + b*t)**2 + (c + z*t)**2)
assert diff(e, t, 2) == ans
assert e.diff(t, 2) == ans
assert diff(e, t, 2, simplify=False) != ans
def test_issue_7426():
f1 = a % c
f2 = x % z
assert f1.equals(f2) is None
def test_issue_11122():
x = Symbol('x', extended_positive=False)
assert unchanged(Gt, x, 0) # (x > 0)
# (x > 0) should remain unevaluated after PR #16956
x = Symbol('x', positive=False, real=True)
assert (x > 0) is S.false
def test_issue_10651():
x = Symbol('x', real=True)
e1 = (-1 + x)/(1 - x)
e3 = (4*x**2 - 4)/((1 - x)*(1 + x))
e4 = 1/(cos(x)**2) - (tan(x))**2
x = Symbol('x', positive=True)
e5 = (1 + x)/x
assert e1.is_constant() is None
assert e3.is_constant() is None
assert e4.is_constant() is None
assert e5.is_constant() is False
def test_issue_10161():
x = symbols('x', real=True)
assert x*abs(x)*abs(x) == x**3
def test_issue_10755():
x = symbols('x')
raises(TypeError, lambda: int(log(x)))
raises(TypeError, lambda: log(x).round(2))
def test_issue_11877():
x = symbols('x')
assert integrate(log(S.Half - x), (x, 0, S.Half)) == Rational(-1, 2) -log(2)/2
def test_normal():
x = symbols('x')
e = Mul(S.Half, 1 + x, evaluate=False)
assert e.normal() == e
def test_expr():
x = symbols('x')
raises(TypeError, lambda: tan(x).series(x, 2, oo, "+"))
def test_ExprBuilder():
eb = ExprBuilder(Mul)
eb.args.extend([x, x])
assert eb.build() == x**2
def test_issue_22020():
from sympy.parsing.sympy_parser import parse_expr
x = parse_expr("log((2*V/3-V)/C)/-(R+r)*C")
y = parse_expr("log((2*V/3-V)/C)/-(R+r)*2")
assert x.equals(y) is False
def test_non_string_equality():
# Expressions should not compare equal to strings
x = symbols('x')
one = sympify(1)
assert (x == 'x') is False
assert (x != 'x') is True
assert (one == '1') is False
assert (one != '1') is True
assert (x + 1 == 'x + 1') is False
assert (x + 1 != 'x + 1') is True
# Make sure == doesn't try to convert the resulting expression to a string
# (e.g., by calling sympify() instead of _sympify())
class BadRepr:
def __repr__(self):
raise RuntimeError
assert (x == BadRepr()) is False
assert (x != BadRepr()) is True
def test_21494():
from sympy.testing.pytest import warns_deprecated_sympy
with warns_deprecated_sympy():
assert x.expr_free_symbols == {x}
with warns_deprecated_sympy():
assert Basic().expr_free_symbols == set()
with warns_deprecated_sympy():
assert S(2).expr_free_symbols == {S(2)}
with warns_deprecated_sympy():
assert Indexed("A", x).expr_free_symbols == {Indexed("A", x)}
with warns_deprecated_sympy():
assert Subs(x, x, 0).expr_free_symbols == set()
def test_Expr__eq__iterable_handling():
assert x != range(3)
def test_format():
assert '{:1.2f}'.format(S.Zero) == '0.00'
assert '{:+3.0f}'.format(S(3)) == ' +3'
assert '{:23.20f}'.format(pi) == ' 3.14159265358979323846'
assert '{:50.48f}'.format(exp(sin(1))) == '2.319776824715853173956590377503266813254904772376'
|
121e3252cf2a74131aeb0363404193d665e7af7e7ec94bdc8c280ff16ffcdf3d | """Test whether all elements of cls.args are instances of Basic. """
# NOTE: keep tests sorted by (module, class name) key. If a class can't
# be instantiated, add it here anyway with @SKIP("abstract class) (see
# e.g. Function).
import os
import re
from sympy.assumptions.ask import Q
from sympy.core.basic import Basic
from sympy.core.function import (Function, Lambda)
from sympy.core.numbers import (Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.testing.pytest import SKIP
a, b, c, x, y, z = symbols('a,b,c,x,y,z')
whitelist = [
"sympy.assumptions.predicates", # tested by test_predicates()
"sympy.assumptions.relation.equality", # tested by test_predicates()
]
def test_all_classes_are_tested():
this = os.path.split(__file__)[0]
path = os.path.join(this, os.pardir, os.pardir)
sympy_path = os.path.abspath(path)
prefix = os.path.split(sympy_path)[0] + os.sep
re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE)
modules = {}
for root, dirs, files in os.walk(sympy_path):
module = root.replace(prefix, "").replace(os.sep, ".")
for file in files:
if file.startswith(("_", "test_", "bench_")):
continue
if not file.endswith(".py"):
continue
with open(os.path.join(root, file), encoding='utf-8') as f:
text = f.read()
submodule = module + '.' + file[:-3]
if any(submodule.startswith(wpath) for wpath in whitelist):
continue
names = re_cls.findall(text)
if not names:
continue
try:
mod = __import__(submodule, fromlist=names)
except ImportError:
continue
def is_Basic(name):
cls = getattr(mod, name)
if hasattr(cls, '_sympy_deprecated_func'):
cls = cls._sympy_deprecated_func
if not isinstance(cls, type):
# check instance of singleton class with same name
cls = type(cls)
return issubclass(cls, Basic)
names = list(filter(is_Basic, names))
if names:
modules[submodule] = names
ns = globals()
failed = []
for module, names in modules.items():
mod = module.replace('.', '__')
for name in names:
test = 'test_' + mod + '__' + name
if test not in ns:
failed.append(module + '.' + name)
assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed)
def _test_args(obj):
all_basic = all(isinstance(arg, Basic) for arg in obj.args)
# Ideally obj.func(*obj.args) would always recreate the object, but for
# now, we only require it for objects with non-empty .args
recreatable = not obj.args or obj.func(*obj.args) == obj
return all_basic and recreatable
def test_sympy__algebras__quaternion__Quaternion():
from sympy.algebras.quaternion import Quaternion
assert _test_args(Quaternion(x, 1, 2, 3))
def test_sympy__assumptions__assume__AppliedPredicate():
from sympy.assumptions.assume import AppliedPredicate, Predicate
assert _test_args(AppliedPredicate(Predicate("test"), 2))
assert _test_args(Q.is_true(True))
@SKIP("abstract class")
def test_sympy__assumptions__assume__Predicate():
pass
def test_predicates():
predicates = [
getattr(Q, attr)
for attr in Q.__class__.__dict__
if not attr.startswith('__')]
for p in predicates:
assert _test_args(p)
def test_sympy__assumptions__assume__UndefinedPredicate():
from sympy.assumptions.assume import Predicate
assert _test_args(Predicate("test"))
@SKIP('abstract class')
def test_sympy__assumptions__relation__binrel__BinaryRelation():
pass
def test_sympy__assumptions__relation__binrel__AppliedBinaryRelation():
assert _test_args(Q.eq(1, 2))
def test_sympy__assumptions__wrapper__AssumptionsWrapper():
from sympy.assumptions.wrapper import AssumptionsWrapper
assert _test_args(AssumptionsWrapper(x, Q.positive(x)))
@SKIP("abstract Class")
def test_sympy__codegen__ast__CodegenAST():
from sympy.codegen.ast import CodegenAST
assert _test_args(CodegenAST())
@SKIP("abstract Class")
def test_sympy__codegen__ast__AssignmentBase():
from sympy.codegen.ast import AssignmentBase
assert _test_args(AssignmentBase(x, 1))
@SKIP("abstract Class")
def test_sympy__codegen__ast__AugmentedAssignment():
from sympy.codegen.ast import AugmentedAssignment
assert _test_args(AugmentedAssignment(x, 1))
def test_sympy__codegen__ast__AddAugmentedAssignment():
from sympy.codegen.ast import AddAugmentedAssignment
assert _test_args(AddAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__SubAugmentedAssignment():
from sympy.codegen.ast import SubAugmentedAssignment
assert _test_args(SubAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__MulAugmentedAssignment():
from sympy.codegen.ast import MulAugmentedAssignment
assert _test_args(MulAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__DivAugmentedAssignment():
from sympy.codegen.ast import DivAugmentedAssignment
assert _test_args(DivAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__ModAugmentedAssignment():
from sympy.codegen.ast import ModAugmentedAssignment
assert _test_args(ModAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__CodeBlock():
from sympy.codegen.ast import CodeBlock, Assignment
assert _test_args(CodeBlock(Assignment(x, 1), Assignment(y, 2)))
def test_sympy__codegen__ast__For():
from sympy.codegen.ast import For, CodeBlock, AddAugmentedAssignment
from sympy.sets import Range
assert _test_args(For(x, Range(10), CodeBlock(AddAugmentedAssignment(y, 1))))
def test_sympy__codegen__ast__Token():
from sympy.codegen.ast import Token
assert _test_args(Token())
def test_sympy__codegen__ast__ContinueToken():
from sympy.codegen.ast import ContinueToken
assert _test_args(ContinueToken())
def test_sympy__codegen__ast__BreakToken():
from sympy.codegen.ast import BreakToken
assert _test_args(BreakToken())
def test_sympy__codegen__ast__NoneToken():
from sympy.codegen.ast import NoneToken
assert _test_args(NoneToken())
def test_sympy__codegen__ast__String():
from sympy.codegen.ast import String
assert _test_args(String('foobar'))
def test_sympy__codegen__ast__QuotedString():
from sympy.codegen.ast import QuotedString
assert _test_args(QuotedString('foobar'))
def test_sympy__codegen__ast__Comment():
from sympy.codegen.ast import Comment
assert _test_args(Comment('this is a comment'))
def test_sympy__codegen__ast__Node():
from sympy.codegen.ast import Node
assert _test_args(Node())
assert _test_args(Node(attrs={1, 2, 3}))
def test_sympy__codegen__ast__Type():
from sympy.codegen.ast import Type
assert _test_args(Type('float128'))
def test_sympy__codegen__ast__IntBaseType():
from sympy.codegen.ast import IntBaseType
assert _test_args(IntBaseType('bigint'))
def test_sympy__codegen__ast___SizedIntType():
from sympy.codegen.ast import _SizedIntType
assert _test_args(_SizedIntType('int128', 128))
def test_sympy__codegen__ast__SignedIntType():
from sympy.codegen.ast import SignedIntType
assert _test_args(SignedIntType('int128_with_sign', 128))
def test_sympy__codegen__ast__UnsignedIntType():
from sympy.codegen.ast import UnsignedIntType
assert _test_args(UnsignedIntType('unt128', 128))
def test_sympy__codegen__ast__FloatBaseType():
from sympy.codegen.ast import FloatBaseType
assert _test_args(FloatBaseType('positive_real'))
def test_sympy__codegen__ast__FloatType():
from sympy.codegen.ast import FloatType
assert _test_args(FloatType('float242', 242, nmant=142, nexp=99))
def test_sympy__codegen__ast__ComplexBaseType():
from sympy.codegen.ast import ComplexBaseType
assert _test_args(ComplexBaseType('positive_cmplx'))
def test_sympy__codegen__ast__ComplexType():
from sympy.codegen.ast import ComplexType
assert _test_args(ComplexType('complex42', 42, nmant=15, nexp=5))
def test_sympy__codegen__ast__Attribute():
from sympy.codegen.ast import Attribute
assert _test_args(Attribute('noexcept'))
def test_sympy__codegen__ast__Variable():
from sympy.codegen.ast import Variable, Type, value_const
assert _test_args(Variable(x))
assert _test_args(Variable(y, Type('float32'), {value_const}))
assert _test_args(Variable(z, type=Type('float64')))
def test_sympy__codegen__ast__Pointer():
from sympy.codegen.ast import Pointer, Type, pointer_const
assert _test_args(Pointer(x))
assert _test_args(Pointer(y, type=Type('float32')))
assert _test_args(Pointer(z, Type('float64'), {pointer_const}))
def test_sympy__codegen__ast__Declaration():
from sympy.codegen.ast import Declaration, Variable, Type
vx = Variable(x, type=Type('float'))
assert _test_args(Declaration(vx))
def test_sympy__codegen__ast__While():
from sympy.codegen.ast import While, AddAugmentedAssignment
assert _test_args(While(abs(x) < 1, [AddAugmentedAssignment(x, -1)]))
def test_sympy__codegen__ast__Scope():
from sympy.codegen.ast import Scope, AddAugmentedAssignment
assert _test_args(Scope([AddAugmentedAssignment(x, -1)]))
def test_sympy__codegen__ast__Stream():
from sympy.codegen.ast import Stream
assert _test_args(Stream('stdin'))
def test_sympy__codegen__ast__Print():
from sympy.codegen.ast import Print
assert _test_args(Print([x, y]))
assert _test_args(Print([x, y], "%d %d"))
def test_sympy__codegen__ast__FunctionPrototype():
from sympy.codegen.ast import FunctionPrototype, real, Declaration, Variable
inp_x = Declaration(Variable(x, type=real))
assert _test_args(FunctionPrototype(real, 'pwer', [inp_x]))
def test_sympy__codegen__ast__FunctionDefinition():
from sympy.codegen.ast import FunctionDefinition, real, Declaration, Variable, Assignment
inp_x = Declaration(Variable(x, type=real))
assert _test_args(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)]))
def test_sympy__codegen__ast__Return():
from sympy.codegen.ast import Return
assert _test_args(Return(x))
def test_sympy__codegen__ast__FunctionCall():
from sympy.codegen.ast import FunctionCall
assert _test_args(FunctionCall('pwer', [x]))
def test_sympy__codegen__ast__Element():
from sympy.codegen.ast import Element
assert _test_args(Element('x', range(3)))
def test_sympy__codegen__cnodes__CommaOperator():
from sympy.codegen.cnodes import CommaOperator
assert _test_args(CommaOperator(1, 2))
def test_sympy__codegen__cnodes__goto():
from sympy.codegen.cnodes import goto
assert _test_args(goto('early_exit'))
def test_sympy__codegen__cnodes__Label():
from sympy.codegen.cnodes import Label
assert _test_args(Label('early_exit'))
def test_sympy__codegen__cnodes__PreDecrement():
from sympy.codegen.cnodes import PreDecrement
assert _test_args(PreDecrement(x))
def test_sympy__codegen__cnodes__PostDecrement():
from sympy.codegen.cnodes import PostDecrement
assert _test_args(PostDecrement(x))
def test_sympy__codegen__cnodes__PreIncrement():
from sympy.codegen.cnodes import PreIncrement
assert _test_args(PreIncrement(x))
def test_sympy__codegen__cnodes__PostIncrement():
from sympy.codegen.cnodes import PostIncrement
assert _test_args(PostIncrement(x))
def test_sympy__codegen__cnodes__struct():
from sympy.codegen.ast import real, Variable
from sympy.codegen.cnodes import struct
assert _test_args(struct(declarations=[
Variable(x, type=real),
Variable(y, type=real)
]))
def test_sympy__codegen__cnodes__union():
from sympy.codegen.ast import float32, int32, Variable
from sympy.codegen.cnodes import union
assert _test_args(union(declarations=[
Variable(x, type=float32),
Variable(y, type=int32)
]))
def test_sympy__codegen__cxxnodes__using():
from sympy.codegen.cxxnodes import using
assert _test_args(using('std::vector'))
assert _test_args(using('std::vector', 'vec'))
def test_sympy__codegen__fnodes__Program():
from sympy.codegen.fnodes import Program
assert _test_args(Program('foobar', []))
def test_sympy__codegen__fnodes__Module():
from sympy.codegen.fnodes import Module
assert _test_args(Module('foobar', [], []))
def test_sympy__codegen__fnodes__Subroutine():
from sympy.codegen.fnodes import Subroutine
x = symbols('x', real=True)
assert _test_args(Subroutine('foo', [x], []))
def test_sympy__codegen__fnodes__GoTo():
from sympy.codegen.fnodes import GoTo
assert _test_args(GoTo([10]))
assert _test_args(GoTo([10, 20], x > 1))
def test_sympy__codegen__fnodes__FortranReturn():
from sympy.codegen.fnodes import FortranReturn
assert _test_args(FortranReturn(10))
def test_sympy__codegen__fnodes__Extent():
from sympy.codegen.fnodes import Extent
assert _test_args(Extent())
assert _test_args(Extent(None))
assert _test_args(Extent(':'))
assert _test_args(Extent(-3, 4))
assert _test_args(Extent(x, y))
def test_sympy__codegen__fnodes__use_rename():
from sympy.codegen.fnodes import use_rename
assert _test_args(use_rename('loc', 'glob'))
def test_sympy__codegen__fnodes__use():
from sympy.codegen.fnodes import use
assert _test_args(use('modfoo', only='bar'))
def test_sympy__codegen__fnodes__SubroutineCall():
from sympy.codegen.fnodes import SubroutineCall
assert _test_args(SubroutineCall('foo', ['bar', 'baz']))
def test_sympy__codegen__fnodes__Do():
from sympy.codegen.fnodes import Do
assert _test_args(Do([], 'i', 1, 42))
def test_sympy__codegen__fnodes__ImpliedDoLoop():
from sympy.codegen.fnodes import ImpliedDoLoop
assert _test_args(ImpliedDoLoop('i', 'i', 1, 42))
def test_sympy__codegen__fnodes__ArrayConstructor():
from sympy.codegen.fnodes import ArrayConstructor
assert _test_args(ArrayConstructor([1, 2, 3]))
from sympy.codegen.fnodes import ImpliedDoLoop
idl = ImpliedDoLoop('i', 'i', 1, 42)
assert _test_args(ArrayConstructor([1, idl, 3]))
def test_sympy__codegen__fnodes__sum_():
from sympy.codegen.fnodes import sum_
assert _test_args(sum_('arr'))
def test_sympy__codegen__fnodes__product_():
from sympy.codegen.fnodes import product_
assert _test_args(product_('arr'))
def test_sympy__codegen__numpy_nodes__logaddexp():
from sympy.codegen.numpy_nodes import logaddexp
assert _test_args(logaddexp(x, y))
def test_sympy__codegen__numpy_nodes__logaddexp2():
from sympy.codegen.numpy_nodes import logaddexp2
assert _test_args(logaddexp2(x, y))
def test_sympy__codegen__pynodes__List():
from sympy.codegen.pynodes import List
assert _test_args(List(1, 2, 3))
def test_sympy__codegen__pynodes__NumExprEvaluate():
from sympy.codegen.pynodes import NumExprEvaluate
assert _test_args(NumExprEvaluate(x))
def test_sympy__codegen__scipy_nodes__cosm1():
from sympy.codegen.scipy_nodes import cosm1
assert _test_args(cosm1(x))
def test_sympy__codegen__abstract_nodes__List():
from sympy.codegen.abstract_nodes import List
assert _test_args(List(1, 2, 3))
def test_sympy__combinatorics__graycode__GrayCode():
from sympy.combinatorics.graycode import GrayCode
# an integer is given and returned from GrayCode as the arg
assert _test_args(GrayCode(3, start='100'))
assert _test_args(GrayCode(3, rank=1))
def test_sympy__combinatorics__permutations__Permutation():
from sympy.combinatorics.permutations import Permutation
assert _test_args(Permutation([0, 1, 2, 3]))
def test_sympy__combinatorics__permutations__AppliedPermutation():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.permutations import AppliedPermutation
p = Permutation([0, 1, 2, 3])
assert _test_args(AppliedPermutation(p, x))
def test_sympy__combinatorics__perm_groups__PermutationGroup():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup
assert _test_args(PermutationGroup([Permutation([0, 1])]))
def test_sympy__combinatorics__polyhedron__Polyhedron():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.polyhedron import Polyhedron
from sympy.abc import w, x, y, z
pgroup = [Permutation([[0, 1, 2], [3]]),
Permutation([[0, 1, 3], [2]]),
Permutation([[0, 2, 3], [1]]),
Permutation([[1, 2, 3], [0]]),
Permutation([[0, 1], [2, 3]]),
Permutation([[0, 2], [1, 3]]),
Permutation([[0, 3], [1, 2]]),
Permutation([[0, 1, 2, 3]])]
corners = [w, x, y, z]
faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)]
assert _test_args(Polyhedron(corners, faces, pgroup))
def test_sympy__combinatorics__prufer__Prufer():
from sympy.combinatorics.prufer import Prufer
assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4))
def test_sympy__combinatorics__partitions__Partition():
from sympy.combinatorics.partitions import Partition
assert _test_args(Partition([1]))
def test_sympy__combinatorics__partitions__IntegerPartition():
from sympy.combinatorics.partitions import IntegerPartition
assert _test_args(IntegerPartition([1]))
def test_sympy__concrete__products__Product():
from sympy.concrete.products import Product
assert _test_args(Product(x, (x, 0, 10)))
assert _test_args(Product(x, (x, 0, y), (y, 0, 10)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__ExprWithLimits():
from sympy.concrete.expr_with_limits import ExprWithLimits
assert _test_args(ExprWithLimits(x, (x, 0, 10)))
assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__AddWithLimits():
from sympy.concrete.expr_with_limits import AddWithLimits
assert _test_args(AddWithLimits(x, (x, 0, 10)))
assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits():
from sympy.concrete.expr_with_intlimits import ExprWithIntLimits
assert _test_args(ExprWithIntLimits(x, (x, 0, 10)))
assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3)))
def test_sympy__concrete__summations__Sum():
from sympy.concrete.summations import Sum
assert _test_args(Sum(x, (x, 0, 10)))
assert _test_args(Sum(x, (x, 0, y), (y, 0, 10)))
def test_sympy__core__add__Add():
from sympy.core.add import Add
assert _test_args(Add(x, y, z, 2))
def test_sympy__core__basic__Atom():
from sympy.core.basic import Atom
assert _test_args(Atom())
def test_sympy__core__basic__Basic():
from sympy.core.basic import Basic
assert _test_args(Basic())
def test_sympy__core__containers__Dict():
from sympy.core.containers import Dict
assert _test_args(Dict({x: y, y: z}))
def test_sympy__core__containers__Tuple():
from sympy.core.containers import Tuple
assert _test_args(Tuple(x, y, z, 2))
def test_sympy__core__expr__AtomicExpr():
from sympy.core.expr import AtomicExpr
assert _test_args(AtomicExpr())
def test_sympy__core__expr__Expr():
from sympy.core.expr import Expr
assert _test_args(Expr())
def test_sympy__core__expr__UnevaluatedExpr():
from sympy.core.expr import UnevaluatedExpr
from sympy.abc import x
assert _test_args(UnevaluatedExpr(x))
def test_sympy__core__function__Application():
from sympy.core.function import Application
assert _test_args(Application(1, 2, 3))
def test_sympy__core__function__AppliedUndef():
from sympy.core.function import AppliedUndef
assert _test_args(AppliedUndef(1, 2, 3))
def test_sympy__core__function__Derivative():
from sympy.core.function import Derivative
assert _test_args(Derivative(2, x, y, 3))
@SKIP("abstract class")
def test_sympy__core__function__Function():
pass
def test_sympy__core__function__Lambda():
assert _test_args(Lambda((x, y), x + y + z))
def test_sympy__core__function__Subs():
from sympy.core.function import Subs
assert _test_args(Subs(x + y, x, 2))
def test_sympy__core__function__WildFunction():
from sympy.core.function import WildFunction
assert _test_args(WildFunction('f'))
def test_sympy__core__mod__Mod():
from sympy.core.mod import Mod
assert _test_args(Mod(x, 2))
def test_sympy__core__mul__Mul():
from sympy.core.mul import Mul
assert _test_args(Mul(2, x, y, z))
def test_sympy__core__numbers__Catalan():
from sympy.core.numbers import Catalan
assert _test_args(Catalan())
def test_sympy__core__numbers__ComplexInfinity():
from sympy.core.numbers import ComplexInfinity
assert _test_args(ComplexInfinity())
def test_sympy__core__numbers__EulerGamma():
from sympy.core.numbers import EulerGamma
assert _test_args(EulerGamma())
def test_sympy__core__numbers__Exp1():
from sympy.core.numbers import Exp1
assert _test_args(Exp1())
def test_sympy__core__numbers__Float():
from sympy.core.numbers import Float
assert _test_args(Float(1.23))
def test_sympy__core__numbers__GoldenRatio():
from sympy.core.numbers import GoldenRatio
assert _test_args(GoldenRatio())
def test_sympy__core__numbers__TribonacciConstant():
from sympy.core.numbers import TribonacciConstant
assert _test_args(TribonacciConstant())
def test_sympy__core__numbers__Half():
from sympy.core.numbers import Half
assert _test_args(Half())
def test_sympy__core__numbers__ImaginaryUnit():
from sympy.core.numbers import ImaginaryUnit
assert _test_args(ImaginaryUnit())
def test_sympy__core__numbers__Infinity():
from sympy.core.numbers import Infinity
assert _test_args(Infinity())
def test_sympy__core__numbers__Integer():
from sympy.core.numbers import Integer
assert _test_args(Integer(7))
@SKIP("abstract class")
def test_sympy__core__numbers__IntegerConstant():
pass
def test_sympy__core__numbers__NaN():
from sympy.core.numbers import NaN
assert _test_args(NaN())
def test_sympy__core__numbers__NegativeInfinity():
from sympy.core.numbers import NegativeInfinity
assert _test_args(NegativeInfinity())
def test_sympy__core__numbers__NegativeOne():
from sympy.core.numbers import NegativeOne
assert _test_args(NegativeOne())
def test_sympy__core__numbers__Number():
from sympy.core.numbers import Number
assert _test_args(Number(1, 7))
def test_sympy__core__numbers__NumberSymbol():
from sympy.core.numbers import NumberSymbol
assert _test_args(NumberSymbol())
def test_sympy__core__numbers__One():
from sympy.core.numbers import One
assert _test_args(One())
def test_sympy__core__numbers__Pi():
from sympy.core.numbers import Pi
assert _test_args(Pi())
def test_sympy__core__numbers__Rational():
from sympy.core.numbers import Rational
assert _test_args(Rational(1, 7))
@SKIP("abstract class")
def test_sympy__core__numbers__RationalConstant():
pass
def test_sympy__core__numbers__Zero():
from sympy.core.numbers import Zero
assert _test_args(Zero())
@SKIP("abstract class")
def test_sympy__core__operations__AssocOp():
pass
@SKIP("abstract class")
def test_sympy__core__operations__LatticeOp():
pass
def test_sympy__core__power__Pow():
from sympy.core.power import Pow
assert _test_args(Pow(x, 2))
def test_sympy__core__relational__Equality():
from sympy.core.relational import Equality
assert _test_args(Equality(x, 2))
def test_sympy__core__relational__GreaterThan():
from sympy.core.relational import GreaterThan
assert _test_args(GreaterThan(x, 2))
def test_sympy__core__relational__LessThan():
from sympy.core.relational import LessThan
assert _test_args(LessThan(x, 2))
@SKIP("abstract class")
def test_sympy__core__relational__Relational():
pass
def test_sympy__core__relational__StrictGreaterThan():
from sympy.core.relational import StrictGreaterThan
assert _test_args(StrictGreaterThan(x, 2))
def test_sympy__core__relational__StrictLessThan():
from sympy.core.relational import StrictLessThan
assert _test_args(StrictLessThan(x, 2))
def test_sympy__core__relational__Unequality():
from sympy.core.relational import Unequality
assert _test_args(Unequality(x, 2))
def test_sympy__sandbox__indexed_integrals__IndexedIntegral():
from sympy.tensor import IndexedBase, Idx
from sympy.sandbox.indexed_integrals import IndexedIntegral
A = IndexedBase('A')
i, j = symbols('i j', integer=True)
a1, a2 = symbols('a1:3', cls=Idx)
assert _test_args(IndexedIntegral(A[a1], A[a2]))
assert _test_args(IndexedIntegral(A[i], A[j]))
def test_sympy__calculus__accumulationbounds__AccumulationBounds():
from sympy.calculus.accumulationbounds import AccumulationBounds
assert _test_args(AccumulationBounds(0, 1))
def test_sympy__sets__ordinals__OmegaPower():
from sympy.sets.ordinals import OmegaPower
assert _test_args(OmegaPower(1, 1))
def test_sympy__sets__ordinals__Ordinal():
from sympy.sets.ordinals import Ordinal, OmegaPower
assert _test_args(Ordinal(OmegaPower(2, 1)))
def test_sympy__sets__ordinals__OrdinalOmega():
from sympy.sets.ordinals import OrdinalOmega
assert _test_args(OrdinalOmega())
def test_sympy__sets__ordinals__OrdinalZero():
from sympy.sets.ordinals import OrdinalZero
assert _test_args(OrdinalZero())
def test_sympy__sets__powerset__PowerSet():
from sympy.sets.powerset import PowerSet
from sympy.core.singleton import S
assert _test_args(PowerSet(S.EmptySet))
def test_sympy__sets__sets__EmptySet():
from sympy.sets.sets import EmptySet
assert _test_args(EmptySet())
def test_sympy__sets__sets__UniversalSet():
from sympy.sets.sets import UniversalSet
assert _test_args(UniversalSet())
def test_sympy__sets__sets__FiniteSet():
from sympy.sets.sets import FiniteSet
assert _test_args(FiniteSet(x, y, z))
def test_sympy__sets__sets__Interval():
from sympy.sets.sets import Interval
assert _test_args(Interval(0, 1))
def test_sympy__sets__sets__ProductSet():
from sympy.sets.sets import ProductSet, Interval
assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1)))
@SKIP("does it make sense to test this?")
def test_sympy__sets__sets__Set():
from sympy.sets.sets import Set
assert _test_args(Set())
def test_sympy__sets__sets__Intersection():
from sympy.sets.sets import Intersection, Interval
from sympy.core.symbol import Symbol
x = Symbol('x')
y = Symbol('y')
S = Intersection(Interval(0, x), Interval(y, 1))
assert isinstance(S, Intersection)
assert _test_args(S)
def test_sympy__sets__sets__Union():
from sympy.sets.sets import Union, Interval
assert _test_args(Union(Interval(0, 1), Interval(2, 3)))
def test_sympy__sets__sets__Complement():
from sympy.sets.sets import Complement, Interval
assert _test_args(Complement(Interval(0, 2), Interval(0, 1)))
def test_sympy__sets__sets__SymmetricDifference():
from sympy.sets.sets import FiniteSet, SymmetricDifference
assert _test_args(SymmetricDifference(FiniteSet(1, 2, 3), \
FiniteSet(2, 3, 4)))
def test_sympy__sets__sets__DisjointUnion():
from sympy.sets.sets import FiniteSet, DisjointUnion
assert _test_args(DisjointUnion(FiniteSet(1, 2, 3), \
FiniteSet(2, 3, 4)))
def test_sympy__physics__quantum__trace__Tr():
from sympy.physics.quantum.trace import Tr
a, b = symbols('a b', commutative=False)
assert _test_args(Tr(a + b))
def test_sympy__sets__setexpr__SetExpr():
from sympy.sets.setexpr import SetExpr
from sympy.sets.sets import Interval
assert _test_args(SetExpr(Interval(0, 1)))
def test_sympy__sets__fancysets__Rationals():
from sympy.sets.fancysets import Rationals
assert _test_args(Rationals())
def test_sympy__sets__fancysets__Naturals():
from sympy.sets.fancysets import Naturals
assert _test_args(Naturals())
def test_sympy__sets__fancysets__Naturals0():
from sympy.sets.fancysets import Naturals0
assert _test_args(Naturals0())
def test_sympy__sets__fancysets__Integers():
from sympy.sets.fancysets import Integers
assert _test_args(Integers())
def test_sympy__sets__fancysets__Reals():
from sympy.sets.fancysets import Reals
assert _test_args(Reals())
def test_sympy__sets__fancysets__Complexes():
from sympy.sets.fancysets import Complexes
assert _test_args(Complexes())
def test_sympy__sets__fancysets__ComplexRegion():
from sympy.sets.fancysets import ComplexRegion
from sympy.core.singleton import S
from sympy.sets import Interval
a = Interval(0, 1)
b = Interval(2, 3)
theta = Interval(0, 2*S.Pi)
assert _test_args(ComplexRegion(a*b))
assert _test_args(ComplexRegion(a*theta, polar=True))
def test_sympy__sets__fancysets__CartesianComplexRegion():
from sympy.sets.fancysets import CartesianComplexRegion
from sympy.sets import Interval
a = Interval(0, 1)
b = Interval(2, 3)
assert _test_args(CartesianComplexRegion(a*b))
def test_sympy__sets__fancysets__PolarComplexRegion():
from sympy.sets.fancysets import PolarComplexRegion
from sympy.core.singleton import S
from sympy.sets import Interval
a = Interval(0, 1)
theta = Interval(0, 2*S.Pi)
assert _test_args(PolarComplexRegion(a*theta))
def test_sympy__sets__fancysets__ImageSet():
from sympy.sets.fancysets import ImageSet
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
x = Symbol('x')
assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals))
def test_sympy__sets__fancysets__Range():
from sympy.sets.fancysets import Range
assert _test_args(Range(1, 5, 1))
def test_sympy__sets__conditionset__ConditionSet():
from sympy.sets.conditionset import ConditionSet
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
x = Symbol('x')
assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals))
def test_sympy__sets__contains__Contains():
from sympy.sets.fancysets import Range
from sympy.sets.contains import Contains
assert _test_args(Contains(x, Range(0, 10, 2)))
# STATS
from sympy.stats.crv_types import NormalDistribution
nd = NormalDistribution(0, 1)
from sympy.stats.frv_types import DieDistribution
die = DieDistribution(6)
def test_sympy__stats__crv__ContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import ContinuousDomain
assert _test_args(ContinuousDomain({x}, Interval(-oo, oo)))
def test_sympy__stats__crv__SingleContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import SingleContinuousDomain
assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo)))
def test_sympy__stats__crv__ProductContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
E = SingleContinuousDomain(y, Interval(0, oo))
assert _test_args(ProductContinuousDomain(D, E))
def test_sympy__stats__crv__ConditionalContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import (SingleContinuousDomain,
ConditionalContinuousDomain)
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ConditionalContinuousDomain(D, x > 0))
def test_sympy__stats__crv__ContinuousPSpace():
from sympy.sets.sets import Interval
from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ContinuousPSpace(D, nd))
def test_sympy__stats__crv__SingleContinuousPSpace():
from sympy.stats.crv import SingleContinuousPSpace
assert _test_args(SingleContinuousPSpace(x, nd))
@SKIP("abstract class")
def test_sympy__stats__rv__Distribution():
pass
@SKIP("abstract class")
def test_sympy__stats__crv__SingleContinuousDistribution():
pass
def test_sympy__stats__drv__SingleDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain
assert _test_args(SingleDiscreteDomain(x, S.Naturals))
def test_sympy__stats__drv__ProductDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain, ProductDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals)
Y = SingleDiscreteDomain(y, S.Integers)
assert _test_args(ProductDiscreteDomain(X, Y))
def test_sympy__stats__drv__SingleDiscretePSpace():
from sympy.stats.drv import SingleDiscretePSpace
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1)))
def test_sympy__stats__drv__DiscretePSpace():
from sympy.stats.drv import DiscretePSpace, SingleDiscreteDomain
density = Lambda(x, 2**(-x))
domain = SingleDiscreteDomain(x, S.Naturals)
assert _test_args(DiscretePSpace(domain, density))
def test_sympy__stats__drv__ConditionalDiscreteDomain():
from sympy.stats.drv import ConditionalDiscreteDomain, SingleDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals0)
assert _test_args(ConditionalDiscreteDomain(X, x > 2))
def test_sympy__stats__joint_rv__JointPSpace():
from sympy.stats.joint_rv import JointPSpace, JointDistribution
assert _test_args(JointPSpace('X', JointDistribution(1)))
def test_sympy__stats__joint_rv__JointRandomSymbol():
from sympy.stats.joint_rv import JointRandomSymbol
assert _test_args(JointRandomSymbol(x))
def test_sympy__stats__joint_rv_types__JointDistributionHandmade():
from sympy.tensor.indexed import Indexed
from sympy.stats.joint_rv_types import JointDistributionHandmade
x1, x2 = (Indexed('x', i) for i in (1, 2))
assert _test_args(JointDistributionHandmade(x1 + x2, S.Reals**2))
def test_sympy__stats__joint_rv__MarginalDistribution():
from sympy.stats.rv import RandomSymbol
from sympy.stats.joint_rv import MarginalDistribution
r = RandomSymbol(S('r'))
assert _test_args(MarginalDistribution(r, (r,)))
def test_sympy__stats__compound_rv__CompoundDistribution():
from sympy.stats.compound_rv import CompoundDistribution
from sympy.stats.drv_types import PoissonDistribution, Poisson
r = Poisson('r', 10)
assert _test_args(CompoundDistribution(PoissonDistribution(r)))
def test_sympy__stats__compound_rv__CompoundPSpace():
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
from sympy.stats.drv_types import PoissonDistribution, Poisson
r = Poisson('r', 5)
C = CompoundDistribution(PoissonDistribution(r))
assert _test_args(CompoundPSpace('C', C))
@SKIP("abstract class")
def test_sympy__stats__drv__SingleDiscreteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__drv__DiscreteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__drv__DiscreteDomain():
pass
def test_sympy__stats__rv__RandomDomain():
from sympy.stats.rv import RandomDomain
from sympy.sets.sets import FiniteSet
assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__SingleDomain():
from sympy.stats.rv import SingleDomain
from sympy.sets.sets import FiniteSet
assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__ConditionalDomain():
from sympy.stats.rv import ConditionalDomain, RandomDomain
from sympy.sets.sets import FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2))
assert _test_args(ConditionalDomain(D, x > 1))
def test_sympy__stats__rv__MatrixDomain():
from sympy.stats.rv import MatrixDomain
from sympy.matrices import MatrixSet
from sympy.core.singleton import S
assert _test_args(MatrixDomain(x, MatrixSet(2, 2, S.Reals)))
def test_sympy__stats__rv__PSpace():
from sympy.stats.rv import PSpace, RandomDomain
from sympy.sets.sets import FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6))
assert _test_args(PSpace(D, die))
@SKIP("abstract Class")
def test_sympy__stats__rv__SinglePSpace():
pass
def test_sympy__stats__rv__RandomSymbol():
from sympy.stats.rv import RandomSymbol
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
assert _test_args(RandomSymbol(x, A))
@SKIP("abstract Class")
def test_sympy__stats__rv__ProductPSpace():
pass
def test_sympy__stats__rv__IndependentProductPSpace():
from sympy.stats.rv import IndependentProductPSpace
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
B = SingleContinuousPSpace(y, nd)
assert _test_args(IndependentProductPSpace(A, B))
def test_sympy__stats__rv__ProductDomain():
from sympy.sets.sets import Interval
from sympy.stats.rv import ProductDomain, SingleDomain
D = SingleDomain(x, Interval(-oo, oo))
E = SingleDomain(y, Interval(0, oo))
assert _test_args(ProductDomain(D, E))
def test_sympy__stats__symbolic_probability__Probability():
from sympy.stats.symbolic_probability import Probability
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Probability(X > 0))
def test_sympy__stats__symbolic_probability__Expectation():
from sympy.stats.symbolic_probability import Expectation
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Expectation(X > 0))
def test_sympy__stats__symbolic_probability__Covariance():
from sympy.stats.symbolic_probability import Covariance
from sympy.stats import Normal
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 3)
assert _test_args(Covariance(X, Y))
def test_sympy__stats__symbolic_probability__Variance():
from sympy.stats.symbolic_probability import Variance
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Variance(X))
def test_sympy__stats__symbolic_probability__Moment():
from sympy.stats.symbolic_probability import Moment
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Moment(X, 3, 2, X > 3))
def test_sympy__stats__symbolic_probability__CentralMoment():
from sympy.stats.symbolic_probability import CentralMoment
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(CentralMoment(X, 2, X > 1))
def test_sympy__stats__frv_types__DiscreteUniformDistribution():
from sympy.stats.frv_types import DiscreteUniformDistribution
from sympy.core.containers import Tuple
assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6)))))
def test_sympy__stats__frv_types__DieDistribution():
assert _test_args(die)
def test_sympy__stats__frv_types__BernoulliDistribution():
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(BernoulliDistribution(S.Half, 0, 1))
def test_sympy__stats__frv_types__BinomialDistribution():
from sympy.stats.frv_types import BinomialDistribution
assert _test_args(BinomialDistribution(5, S.Half, 1, 0))
def test_sympy__stats__frv_types__BetaBinomialDistribution():
from sympy.stats.frv_types import BetaBinomialDistribution
assert _test_args(BetaBinomialDistribution(5, 1, 1))
def test_sympy__stats__frv_types__HypergeometricDistribution():
from sympy.stats.frv_types import HypergeometricDistribution
assert _test_args(HypergeometricDistribution(10, 5, 3))
def test_sympy__stats__frv_types__RademacherDistribution():
from sympy.stats.frv_types import RademacherDistribution
assert _test_args(RademacherDistribution())
def test_sympy__stats__frv_types__IdealSolitonDistribution():
from sympy.stats.frv_types import IdealSolitonDistribution
assert _test_args(IdealSolitonDistribution(10))
def test_sympy__stats__frv_types__RobustSolitonDistribution():
from sympy.stats.frv_types import RobustSolitonDistribution
assert _test_args(RobustSolitonDistribution(1000, 0.5, 0.1))
def test_sympy__stats__frv__FiniteDomain():
from sympy.stats.frv import FiniteDomain
assert _test_args(FiniteDomain({(x, 1), (x, 2)})) # x can be 1 or 2
def test_sympy__stats__frv__SingleFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain
assert _test_args(SingleFiniteDomain(x, {1, 2})) # x can be 1 or 2
def test_sympy__stats__frv__ProductFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomain
xd = SingleFiniteDomain(x, {1, 2})
yd = SingleFiniteDomain(y, {1, 2})
assert _test_args(ProductFiniteDomain(xd, yd))
def test_sympy__stats__frv__ConditionalFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomain
xd = SingleFiniteDomain(x, {1, 2})
assert _test_args(ConditionalFiniteDomain(xd, x > 1))
def test_sympy__stats__frv__FinitePSpace():
from sympy.stats.frv import FinitePSpace, SingleFiniteDomain
xd = SingleFiniteDomain(x, {1, 2, 3, 4, 5, 6})
assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))
xd = SingleFiniteDomain(x, {1, 2})
assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))
def test_sympy__stats__frv__SingleFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace
from sympy.core.symbol import Symbol
assert _test_args(SingleFinitePSpace(Symbol('x'), die))
def test_sympy__stats__frv__ProductFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpace
from sympy.core.symbol import Symbol
xp = SingleFinitePSpace(Symbol('x'), die)
yp = SingleFinitePSpace(Symbol('y'), die)
assert _test_args(ProductFinitePSpace(xp, yp))
@SKIP("abstract class")
def test_sympy__stats__frv__SingleFiniteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__crv__ContinuousDistribution():
pass
def test_sympy__stats__frv_types__FiniteDistributionHandmade():
from sympy.stats.frv_types import FiniteDistributionHandmade
from sympy.core.containers import Dict
assert _test_args(FiniteDistributionHandmade(Dict({1: 1})))
def test_sympy__stats__crv_types__ContinuousDistributionHandmade():
from sympy.stats.crv_types import ContinuousDistributionHandmade
from sympy.core.function import Lambda
from sympy.sets.sets import Interval
from sympy.abc import x
assert _test_args(ContinuousDistributionHandmade(Lambda(x, 2*x),
Interval(0, 1)))
def test_sympy__stats__drv_types__DiscreteDistributionHandmade():
from sympy.stats.drv_types import DiscreteDistributionHandmade
from sympy.core.function import Lambda
from sympy.sets.sets import FiniteSet
from sympy.abc import x
assert _test_args(DiscreteDistributionHandmade(Lambda(x, Rational(1, 10)),
FiniteSet(*range(10))))
def test_sympy__stats__rv__Density():
from sympy.stats.rv import Density
from sympy.stats.crv_types import Normal
assert _test_args(Density(Normal('x', 0, 1)))
def test_sympy__stats__crv_types__ArcsinDistribution():
from sympy.stats.crv_types import ArcsinDistribution
assert _test_args(ArcsinDistribution(0, 1))
def test_sympy__stats__crv_types__BeniniDistribution():
from sympy.stats.crv_types import BeniniDistribution
assert _test_args(BeniniDistribution(1, 1, 1))
def test_sympy__stats__crv_types__BetaDistribution():
from sympy.stats.crv_types import BetaDistribution
assert _test_args(BetaDistribution(1, 1))
def test_sympy__stats__crv_types__BetaNoncentralDistribution():
from sympy.stats.crv_types import BetaNoncentralDistribution
assert _test_args(BetaNoncentralDistribution(1, 1, 1))
def test_sympy__stats__crv_types__BetaPrimeDistribution():
from sympy.stats.crv_types import BetaPrimeDistribution
assert _test_args(BetaPrimeDistribution(1, 1))
def test_sympy__stats__crv_types__BoundedParetoDistribution():
from sympy.stats.crv_types import BoundedParetoDistribution
assert _test_args(BoundedParetoDistribution(1, 1, 2))
def test_sympy__stats__crv_types__CauchyDistribution():
from sympy.stats.crv_types import CauchyDistribution
assert _test_args(CauchyDistribution(0, 1))
def test_sympy__stats__crv_types__ChiDistribution():
from sympy.stats.crv_types import ChiDistribution
assert _test_args(ChiDistribution(1))
def test_sympy__stats__crv_types__ChiNoncentralDistribution():
from sympy.stats.crv_types import ChiNoncentralDistribution
assert _test_args(ChiNoncentralDistribution(1,1))
def test_sympy__stats__crv_types__ChiSquaredDistribution():
from sympy.stats.crv_types import ChiSquaredDistribution
assert _test_args(ChiSquaredDistribution(1))
def test_sympy__stats__crv_types__DagumDistribution():
from sympy.stats.crv_types import DagumDistribution
assert _test_args(DagumDistribution(1, 1, 1))
def test_sympy__stats__crv_types__ExGaussianDistribution():
from sympy.stats.crv_types import ExGaussianDistribution
assert _test_args(ExGaussianDistribution(1, 1, 1))
def test_sympy__stats__crv_types__ExponentialDistribution():
from sympy.stats.crv_types import ExponentialDistribution
assert _test_args(ExponentialDistribution(1))
def test_sympy__stats__crv_types__ExponentialPowerDistribution():
from sympy.stats.crv_types import ExponentialPowerDistribution
assert _test_args(ExponentialPowerDistribution(0, 1, 1))
def test_sympy__stats__crv_types__FDistributionDistribution():
from sympy.stats.crv_types import FDistributionDistribution
assert _test_args(FDistributionDistribution(1, 1))
def test_sympy__stats__crv_types__FisherZDistribution():
from sympy.stats.crv_types import FisherZDistribution
assert _test_args(FisherZDistribution(1, 1))
def test_sympy__stats__crv_types__FrechetDistribution():
from sympy.stats.crv_types import FrechetDistribution
assert _test_args(FrechetDistribution(1, 1, 1))
def test_sympy__stats__crv_types__GammaInverseDistribution():
from sympy.stats.crv_types import GammaInverseDistribution
assert _test_args(GammaInverseDistribution(1, 1))
def test_sympy__stats__crv_types__GammaDistribution():
from sympy.stats.crv_types import GammaDistribution
assert _test_args(GammaDistribution(1, 1))
def test_sympy__stats__crv_types__GumbelDistribution():
from sympy.stats.crv_types import GumbelDistribution
assert _test_args(GumbelDistribution(1, 1, False))
def test_sympy__stats__crv_types__GompertzDistribution():
from sympy.stats.crv_types import GompertzDistribution
assert _test_args(GompertzDistribution(1, 1))
def test_sympy__stats__crv_types__KumaraswamyDistribution():
from sympy.stats.crv_types import KumaraswamyDistribution
assert _test_args(KumaraswamyDistribution(1, 1))
def test_sympy__stats__crv_types__LaplaceDistribution():
from sympy.stats.crv_types import LaplaceDistribution
assert _test_args(LaplaceDistribution(0, 1))
def test_sympy__stats__crv_types__LevyDistribution():
from sympy.stats.crv_types import LevyDistribution
assert _test_args(LevyDistribution(0, 1))
def test_sympy__stats__crv_types__LogCauchyDistribution():
from sympy.stats.crv_types import LogCauchyDistribution
assert _test_args(LogCauchyDistribution(0, 1))
def test_sympy__stats__crv_types__LogisticDistribution():
from sympy.stats.crv_types import LogisticDistribution
assert _test_args(LogisticDistribution(0, 1))
def test_sympy__stats__crv_types__LogLogisticDistribution():
from sympy.stats.crv_types import LogLogisticDistribution
assert _test_args(LogLogisticDistribution(1, 1))
def test_sympy__stats__crv_types__LogitNormalDistribution():
from sympy.stats.crv_types import LogitNormalDistribution
assert _test_args(LogitNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LogNormalDistribution():
from sympy.stats.crv_types import LogNormalDistribution
assert _test_args(LogNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LomaxDistribution():
from sympy.stats.crv_types import LomaxDistribution
assert _test_args(LomaxDistribution(1, 2))
def test_sympy__stats__crv_types__MaxwellDistribution():
from sympy.stats.crv_types import MaxwellDistribution
assert _test_args(MaxwellDistribution(1))
def test_sympy__stats__crv_types__MoyalDistribution():
from sympy.stats.crv_types import MoyalDistribution
assert _test_args(MoyalDistribution(1,2))
def test_sympy__stats__crv_types__NakagamiDistribution():
from sympy.stats.crv_types import NakagamiDistribution
assert _test_args(NakagamiDistribution(1, 1))
def test_sympy__stats__crv_types__NormalDistribution():
from sympy.stats.crv_types import NormalDistribution
assert _test_args(NormalDistribution(0, 1))
def test_sympy__stats__crv_types__GaussianInverseDistribution():
from sympy.stats.crv_types import GaussianInverseDistribution
assert _test_args(GaussianInverseDistribution(1, 1))
def test_sympy__stats__crv_types__ParetoDistribution():
from sympy.stats.crv_types import ParetoDistribution
assert _test_args(ParetoDistribution(1, 1))
def test_sympy__stats__crv_types__PowerFunctionDistribution():
from sympy.stats.crv_types import PowerFunctionDistribution
assert _test_args(PowerFunctionDistribution(2,0,1))
def test_sympy__stats__crv_types__QuadraticUDistribution():
from sympy.stats.crv_types import QuadraticUDistribution
assert _test_args(QuadraticUDistribution(1, 2))
def test_sympy__stats__crv_types__RaisedCosineDistribution():
from sympy.stats.crv_types import RaisedCosineDistribution
assert _test_args(RaisedCosineDistribution(1, 1))
def test_sympy__stats__crv_types__RayleighDistribution():
from sympy.stats.crv_types import RayleighDistribution
assert _test_args(RayleighDistribution(1))
def test_sympy__stats__crv_types__ReciprocalDistribution():
from sympy.stats.crv_types import ReciprocalDistribution
assert _test_args(ReciprocalDistribution(5, 30))
def test_sympy__stats__crv_types__ShiftedGompertzDistribution():
from sympy.stats.crv_types import ShiftedGompertzDistribution
assert _test_args(ShiftedGompertzDistribution(1, 1))
def test_sympy__stats__crv_types__StudentTDistribution():
from sympy.stats.crv_types import StudentTDistribution
assert _test_args(StudentTDistribution(1))
def test_sympy__stats__crv_types__TrapezoidalDistribution():
from sympy.stats.crv_types import TrapezoidalDistribution
assert _test_args(TrapezoidalDistribution(1, 2, 3, 4))
def test_sympy__stats__crv_types__TriangularDistribution():
from sympy.stats.crv_types import TriangularDistribution
assert _test_args(TriangularDistribution(-1, 0, 1))
def test_sympy__stats__crv_types__UniformDistribution():
from sympy.stats.crv_types import UniformDistribution
assert _test_args(UniformDistribution(0, 1))
def test_sympy__stats__crv_types__UniformSumDistribution():
from sympy.stats.crv_types import UniformSumDistribution
assert _test_args(UniformSumDistribution(1))
def test_sympy__stats__crv_types__VonMisesDistribution():
from sympy.stats.crv_types import VonMisesDistribution
assert _test_args(VonMisesDistribution(1, 1))
def test_sympy__stats__crv_types__WeibullDistribution():
from sympy.stats.crv_types import WeibullDistribution
assert _test_args(WeibullDistribution(1, 1))
def test_sympy__stats__crv_types__WignerSemicircleDistribution():
from sympy.stats.crv_types import WignerSemicircleDistribution
assert _test_args(WignerSemicircleDistribution(1))
def test_sympy__stats__drv_types__GeometricDistribution():
from sympy.stats.drv_types import GeometricDistribution
assert _test_args(GeometricDistribution(.5))
def test_sympy__stats__drv_types__HermiteDistribution():
from sympy.stats.drv_types import HermiteDistribution
assert _test_args(HermiteDistribution(1, 2))
def test_sympy__stats__drv_types__LogarithmicDistribution():
from sympy.stats.drv_types import LogarithmicDistribution
assert _test_args(LogarithmicDistribution(.5))
def test_sympy__stats__drv_types__NegativeBinomialDistribution():
from sympy.stats.drv_types import NegativeBinomialDistribution
assert _test_args(NegativeBinomialDistribution(.5, .5))
def test_sympy__stats__drv_types__FlorySchulzDistribution():
from sympy.stats.drv_types import FlorySchulzDistribution
assert _test_args(FlorySchulzDistribution(.5))
def test_sympy__stats__drv_types__PoissonDistribution():
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(PoissonDistribution(1))
def test_sympy__stats__drv_types__SkellamDistribution():
from sympy.stats.drv_types import SkellamDistribution
assert _test_args(SkellamDistribution(1, 1))
def test_sympy__stats__drv_types__YuleSimonDistribution():
from sympy.stats.drv_types import YuleSimonDistribution
assert _test_args(YuleSimonDistribution(.5))
def test_sympy__stats__drv_types__ZetaDistribution():
from sympy.stats.drv_types import ZetaDistribution
assert _test_args(ZetaDistribution(1.5))
def test_sympy__stats__joint_rv__JointDistribution():
from sympy.stats.joint_rv import JointDistribution
assert _test_args(JointDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__MultivariateNormalDistribution():
from sympy.stats.joint_rv_types import MultivariateNormalDistribution
assert _test_args(
MultivariateNormalDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateLaplaceDistribution():
from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution
assert _test_args(MultivariateLaplaceDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateTDistribution():
from sympy.stats.joint_rv_types import MultivariateTDistribution
assert _test_args(MultivariateTDistribution([0, 1], [[1, 0],[0, 1]], 1))
def test_sympy__stats__joint_rv_types__NormalGammaDistribution():
from sympy.stats.joint_rv_types import NormalGammaDistribution
assert _test_args(NormalGammaDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__GeneralizedMultivariateLogGammaDistribution():
from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaDistribution
v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4])
assert _test_args(GeneralizedMultivariateLogGammaDistribution(S.Half, v, l, mu))
def test_sympy__stats__joint_rv_types__MultivariateBetaDistribution():
from sympy.stats.joint_rv_types import MultivariateBetaDistribution
assert _test_args(MultivariateBetaDistribution([1, 2, 3]))
def test_sympy__stats__joint_rv_types__MultivariateEwensDistribution():
from sympy.stats.joint_rv_types import MultivariateEwensDistribution
assert _test_args(MultivariateEwensDistribution(5, 1))
def test_sympy__stats__joint_rv_types__MultinomialDistribution():
from sympy.stats.joint_rv_types import MultinomialDistribution
assert _test_args(MultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__joint_rv_types__NegativeMultinomialDistribution():
from sympy.stats.joint_rv_types import NegativeMultinomialDistribution
assert _test_args(NegativeMultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__rv__RandomIndexedSymbol():
from sympy.stats.rv import RandomIndexedSymbol, pspace
from sympy.stats.stochastic_process_types import DiscreteMarkovChain
X = DiscreteMarkovChain("X")
assert _test_args(RandomIndexedSymbol(X[0].symbol, pspace(X[0])))
def test_sympy__stats__rv__RandomMatrixSymbol():
from sympy.stats.rv import RandomMatrixSymbol
from sympy.stats.random_matrix import RandomMatrixPSpace
pspace = RandomMatrixPSpace('P')
assert _test_args(RandomMatrixSymbol('M', 3, 3, pspace))
def test_sympy__stats__stochastic_process__StochasticPSpace():
from sympy.stats.stochastic_process import StochasticPSpace
from sympy.stats.stochastic_process_types import StochasticProcess
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(StochasticPSpace("Y", StochasticProcess("Y", [1, 2, 3]), BernoulliDistribution(S.Half, 1, 0)))
def test_sympy__stats__stochastic_process_types__StochasticProcess():
from sympy.stats.stochastic_process_types import StochasticProcess
assert _test_args(StochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__MarkovProcess():
from sympy.stats.stochastic_process_types import MarkovProcess
assert _test_args(MarkovProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__DiscreteTimeStochasticProcess():
from sympy.stats.stochastic_process_types import DiscreteTimeStochasticProcess
assert _test_args(DiscreteTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__ContinuousTimeStochasticProcess():
from sympy.stats.stochastic_process_types import ContinuousTimeStochasticProcess
assert _test_args(ContinuousTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__TransitionMatrixOf():
from sympy.stats.stochastic_process_types import TransitionMatrixOf, DiscreteMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
DMC = DiscreteMarkovChain("Y")
assert _test_args(TransitionMatrixOf(DMC, MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__GeneratorMatrixOf():
from sympy.stats.stochastic_process_types import GeneratorMatrixOf, ContinuousMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
DMC = ContinuousMarkovChain("Y")
assert _test_args(GeneratorMatrixOf(DMC, MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__StochasticStateSpaceOf():
from sympy.stats.stochastic_process_types import StochasticStateSpaceOf, DiscreteMarkovChain
DMC = DiscreteMarkovChain("Y")
assert _test_args(StochasticStateSpaceOf(DMC, [0, 1, 2]))
def test_sympy__stats__stochastic_process_types__DiscreteMarkovChain():
from sympy.stats.stochastic_process_types import DiscreteMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(DiscreteMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__ContinuousMarkovChain():
from sympy.stats.stochastic_process_types import ContinuousMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(ContinuousMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__BernoulliProcess():
from sympy.stats.stochastic_process_types import BernoulliProcess
assert _test_args(BernoulliProcess("B", 0.5, 1, 0))
def test_sympy__stats__stochastic_process_types__CountingProcess():
from sympy.stats.stochastic_process_types import CountingProcess
assert _test_args(CountingProcess("C"))
def test_sympy__stats__stochastic_process_types__PoissonProcess():
from sympy.stats.stochastic_process_types import PoissonProcess
assert _test_args(PoissonProcess("X", 2))
def test_sympy__stats__stochastic_process_types__WienerProcess():
from sympy.stats.stochastic_process_types import WienerProcess
assert _test_args(WienerProcess("X"))
def test_sympy__stats__stochastic_process_types__GammaProcess():
from sympy.stats.stochastic_process_types import GammaProcess
assert _test_args(GammaProcess("X", 1, 2))
def test_sympy__stats__random_matrix__RandomMatrixPSpace():
from sympy.stats.random_matrix import RandomMatrixPSpace
from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel
model = RandomMatrixEnsembleModel('R', 3)
assert _test_args(RandomMatrixPSpace('P', model=model))
def test_sympy__stats__random_matrix_models__RandomMatrixEnsembleModel():
from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel
assert _test_args(RandomMatrixEnsembleModel('R', 3))
def test_sympy__stats__random_matrix_models__GaussianEnsembleModel():
from sympy.stats.random_matrix_models import GaussianEnsembleModel
assert _test_args(GaussianEnsembleModel('G', 3))
def test_sympy__stats__random_matrix_models__GaussianUnitaryEnsembleModel():
from sympy.stats.random_matrix_models import GaussianUnitaryEnsembleModel
assert _test_args(GaussianUnitaryEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__GaussianOrthogonalEnsembleModel():
from sympy.stats.random_matrix_models import GaussianOrthogonalEnsembleModel
assert _test_args(GaussianOrthogonalEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__GaussianSymplecticEnsembleModel():
from sympy.stats.random_matrix_models import GaussianSymplecticEnsembleModel
assert _test_args(GaussianSymplecticEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__CircularEnsembleModel():
from sympy.stats.random_matrix_models import CircularEnsembleModel
assert _test_args(CircularEnsembleModel('C', 3))
def test_sympy__stats__random_matrix_models__CircularUnitaryEnsembleModel():
from sympy.stats.random_matrix_models import CircularUnitaryEnsembleModel
assert _test_args(CircularUnitaryEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__CircularOrthogonalEnsembleModel():
from sympy.stats.random_matrix_models import CircularOrthogonalEnsembleModel
assert _test_args(CircularOrthogonalEnsembleModel('O', 3))
def test_sympy__stats__random_matrix_models__CircularSymplecticEnsembleModel():
from sympy.stats.random_matrix_models import CircularSymplecticEnsembleModel
assert _test_args(CircularSymplecticEnsembleModel('S', 3))
def test_sympy__stats__symbolic_multivariate_probability__ExpectationMatrix():
from sympy.stats import ExpectationMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(ExpectationMatrix(RandomMatrixSymbol('R', 2, 1)))
def test_sympy__stats__symbolic_multivariate_probability__VarianceMatrix():
from sympy.stats import VarianceMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(VarianceMatrix(RandomMatrixSymbol('R', 3, 1)))
def test_sympy__stats__symbolic_multivariate_probability__CrossCovarianceMatrix():
from sympy.stats import CrossCovarianceMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(CrossCovarianceMatrix(RandomMatrixSymbol('R', 3, 1),
RandomMatrixSymbol('X', 3, 1)))
def test_sympy__stats__matrix_distributions__MatrixPSpace():
from sympy.stats.matrix_distributions import MatrixDistribution, MatrixPSpace
from sympy.matrices.dense import Matrix
M = MatrixDistribution(1, Matrix([[1, 0], [0, 1]]))
assert _test_args(MatrixPSpace('M', M, 2, 2))
def test_sympy__stats__matrix_distributions__MatrixDistribution():
from sympy.stats.matrix_distributions import MatrixDistribution
from sympy.matrices.dense import Matrix
assert _test_args(MatrixDistribution(1, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__MatrixGammaDistribution():
from sympy.stats.matrix_distributions import MatrixGammaDistribution
from sympy.matrices.dense import Matrix
assert _test_args(MatrixGammaDistribution(3, 4, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__WishartDistribution():
from sympy.stats.matrix_distributions import WishartDistribution
from sympy.matrices.dense import Matrix
assert _test_args(WishartDistribution(3, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__MatrixNormalDistribution():
from sympy.stats.matrix_distributions import MatrixNormalDistribution
from sympy.matrices.expressions.matexpr import MatrixSymbol
L = MatrixSymbol('L', 1, 2)
S1 = MatrixSymbol('S1', 1, 1)
S2 = MatrixSymbol('S2', 2, 2)
assert _test_args(MatrixNormalDistribution(L, S1, S2))
def test_sympy__stats__matrix_distributions__MatrixStudentTDistribution():
from sympy.stats.matrix_distributions import MatrixStudentTDistribution
from sympy.matrices.expressions.matexpr import MatrixSymbol
v = symbols('v', positive=True)
Omega = MatrixSymbol('Omega', 3, 3)
Sigma = MatrixSymbol('Sigma', 1, 1)
Location = MatrixSymbol('Location', 1, 3)
assert _test_args(MatrixStudentTDistribution(v, Location, Omega, Sigma))
def test_sympy__utilities__matchpy_connector__WildDot():
from sympy.utilities.matchpy_connector import WildDot
assert _test_args(WildDot("w_"))
def test_sympy__utilities__matchpy_connector__WildPlus():
from sympy.utilities.matchpy_connector import WildPlus
assert _test_args(WildPlus("w__"))
def test_sympy__utilities__matchpy_connector__WildStar():
from sympy.utilities.matchpy_connector import WildStar
assert _test_args(WildStar("w___"))
def test_sympy__core__symbol__Str():
from sympy.core.symbol import Str
assert _test_args(Str('t'))
def test_sympy__core__symbol__Dummy():
from sympy.core.symbol import Dummy
assert _test_args(Dummy('t'))
def test_sympy__core__symbol__Symbol():
from sympy.core.symbol import Symbol
assert _test_args(Symbol('t'))
def test_sympy__core__symbol__Wild():
from sympy.core.symbol import Wild
assert _test_args(Wild('x', exclude=[x]))
@SKIP("abstract class")
def test_sympy__functions__combinatorial__factorials__CombinatorialFunction():
pass
def test_sympy__functions__combinatorial__factorials__FallingFactorial():
from sympy.functions.combinatorial.factorials import FallingFactorial
assert _test_args(FallingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__MultiFactorial():
from sympy.functions.combinatorial.factorials import MultiFactorial
assert _test_args(MultiFactorial(x))
def test_sympy__functions__combinatorial__factorials__RisingFactorial():
from sympy.functions.combinatorial.factorials import RisingFactorial
assert _test_args(RisingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__binomial():
from sympy.functions.combinatorial.factorials import binomial
assert _test_args(binomial(2, x))
def test_sympy__functions__combinatorial__factorials__subfactorial():
from sympy.functions.combinatorial.factorials import subfactorial
assert _test_args(subfactorial(x))
def test_sympy__functions__combinatorial__factorials__factorial():
from sympy.functions.combinatorial.factorials import factorial
assert _test_args(factorial(x))
def test_sympy__functions__combinatorial__factorials__factorial2():
from sympy.functions.combinatorial.factorials import factorial2
assert _test_args(factorial2(x))
def test_sympy__functions__combinatorial__numbers__bell():
from sympy.functions.combinatorial.numbers import bell
assert _test_args(bell(x, y))
def test_sympy__functions__combinatorial__numbers__bernoulli():
from sympy.functions.combinatorial.numbers import bernoulli
assert _test_args(bernoulli(x))
def test_sympy__functions__combinatorial__numbers__catalan():
from sympy.functions.combinatorial.numbers import catalan
assert _test_args(catalan(x))
def test_sympy__functions__combinatorial__numbers__genocchi():
from sympy.functions.combinatorial.numbers import genocchi
assert _test_args(genocchi(x))
def test_sympy__functions__combinatorial__numbers__euler():
from sympy.functions.combinatorial.numbers import euler
assert _test_args(euler(x))
def test_sympy__functions__combinatorial__numbers__andre():
from sympy.functions.combinatorial.numbers import andre
assert _test_args(andre(x))
def test_sympy__functions__combinatorial__numbers__carmichael():
from sympy.functions.combinatorial.numbers import carmichael
assert _test_args(carmichael(x))
def test_sympy__functions__combinatorial__numbers__motzkin():
from sympy.functions.combinatorial.numbers import motzkin
assert _test_args(motzkin(5))
def test_sympy__functions__combinatorial__numbers__fibonacci():
from sympy.functions.combinatorial.numbers import fibonacci
assert _test_args(fibonacci(x))
def test_sympy__functions__combinatorial__numbers__tribonacci():
from sympy.functions.combinatorial.numbers import tribonacci
assert _test_args(tribonacci(x))
def test_sympy__functions__combinatorial__numbers__harmonic():
from sympy.functions.combinatorial.numbers import harmonic
assert _test_args(harmonic(x, 2))
def test_sympy__functions__combinatorial__numbers__lucas():
from sympy.functions.combinatorial.numbers import lucas
assert _test_args(lucas(x))
def test_sympy__functions__combinatorial__numbers__partition():
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.numbers import partition
assert _test_args(partition(Symbol('a', integer=True)))
def test_sympy__functions__elementary__complexes__Abs():
from sympy.functions.elementary.complexes import Abs
assert _test_args(Abs(x))
def test_sympy__functions__elementary__complexes__adjoint():
from sympy.functions.elementary.complexes import adjoint
assert _test_args(adjoint(x))
def test_sympy__functions__elementary__complexes__arg():
from sympy.functions.elementary.complexes import arg
assert _test_args(arg(x))
def test_sympy__functions__elementary__complexes__conjugate():
from sympy.functions.elementary.complexes import conjugate
assert _test_args(conjugate(x))
def test_sympy__functions__elementary__complexes__im():
from sympy.functions.elementary.complexes import im
assert _test_args(im(x))
def test_sympy__functions__elementary__complexes__re():
from sympy.functions.elementary.complexes import re
assert _test_args(re(x))
def test_sympy__functions__elementary__complexes__sign():
from sympy.functions.elementary.complexes import sign
assert _test_args(sign(x))
def test_sympy__functions__elementary__complexes__polar_lift():
from sympy.functions.elementary.complexes import polar_lift
assert _test_args(polar_lift(x))
def test_sympy__functions__elementary__complexes__periodic_argument():
from sympy.functions.elementary.complexes import periodic_argument
assert _test_args(periodic_argument(x, y))
def test_sympy__functions__elementary__complexes__principal_branch():
from sympy.functions.elementary.complexes import principal_branch
assert _test_args(principal_branch(x, y))
def test_sympy__functions__elementary__complexes__transpose():
from sympy.functions.elementary.complexes import transpose
assert _test_args(transpose(x))
def test_sympy__functions__elementary__exponential__LambertW():
from sympy.functions.elementary.exponential import LambertW
assert _test_args(LambertW(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__exponential__ExpBase():
pass
def test_sympy__functions__elementary__exponential__exp():
from sympy.functions.elementary.exponential import exp
assert _test_args(exp(2))
def test_sympy__functions__elementary__exponential__exp_polar():
from sympy.functions.elementary.exponential import exp_polar
assert _test_args(exp_polar(2))
def test_sympy__functions__elementary__exponential__log():
from sympy.functions.elementary.exponential import log
assert _test_args(log(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction():
pass
def test_sympy__functions__elementary__hyperbolic__acosh():
from sympy.functions.elementary.hyperbolic import acosh
assert _test_args(acosh(2))
def test_sympy__functions__elementary__hyperbolic__acoth():
from sympy.functions.elementary.hyperbolic import acoth
assert _test_args(acoth(2))
def test_sympy__functions__elementary__hyperbolic__asinh():
from sympy.functions.elementary.hyperbolic import asinh
assert _test_args(asinh(2))
def test_sympy__functions__elementary__hyperbolic__atanh():
from sympy.functions.elementary.hyperbolic import atanh
assert _test_args(atanh(2))
def test_sympy__functions__elementary__hyperbolic__asech():
from sympy.functions.elementary.hyperbolic import asech
assert _test_args(asech(x))
def test_sympy__functions__elementary__hyperbolic__acsch():
from sympy.functions.elementary.hyperbolic import acsch
assert _test_args(acsch(x))
def test_sympy__functions__elementary__hyperbolic__cosh():
from sympy.functions.elementary.hyperbolic import cosh
assert _test_args(cosh(2))
def test_sympy__functions__elementary__hyperbolic__coth():
from sympy.functions.elementary.hyperbolic import coth
assert _test_args(coth(2))
def test_sympy__functions__elementary__hyperbolic__csch():
from sympy.functions.elementary.hyperbolic import csch
assert _test_args(csch(2))
def test_sympy__functions__elementary__hyperbolic__sech():
from sympy.functions.elementary.hyperbolic import sech
assert _test_args(sech(2))
def test_sympy__functions__elementary__hyperbolic__sinh():
from sympy.functions.elementary.hyperbolic import sinh
assert _test_args(sinh(2))
def test_sympy__functions__elementary__hyperbolic__tanh():
from sympy.functions.elementary.hyperbolic import tanh
assert _test_args(tanh(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__integers__RoundFunction():
pass
def test_sympy__functions__elementary__integers__ceiling():
from sympy.functions.elementary.integers import ceiling
assert _test_args(ceiling(x))
def test_sympy__functions__elementary__integers__floor():
from sympy.functions.elementary.integers import floor
assert _test_args(floor(x))
def test_sympy__functions__elementary__integers__frac():
from sympy.functions.elementary.integers import frac
assert _test_args(frac(x))
def test_sympy__functions__elementary__miscellaneous__IdentityFunction():
from sympy.functions.elementary.miscellaneous import IdentityFunction
assert _test_args(IdentityFunction())
def test_sympy__functions__elementary__miscellaneous__Max():
from sympy.functions.elementary.miscellaneous import Max
assert _test_args(Max(x, 2))
def test_sympy__functions__elementary__miscellaneous__Min():
from sympy.functions.elementary.miscellaneous import Min
assert _test_args(Min(x, 2))
@SKIP("abstract class")
def test_sympy__functions__elementary__miscellaneous__MinMaxBase():
pass
def test_sympy__functions__elementary__miscellaneous__Rem():
from sympy.functions.elementary.miscellaneous import Rem
assert _test_args(Rem(x, 2))
def test_sympy__functions__elementary__piecewise__ExprCondPair():
from sympy.functions.elementary.piecewise import ExprCondPair
assert _test_args(ExprCondPair(1, True))
def test_sympy__functions__elementary__piecewise__Piecewise():
from sympy.functions.elementary.piecewise import Piecewise
assert _test_args(Piecewise((1, x >= 0), (0, True)))
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__TrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction():
pass
def test_sympy__functions__elementary__trigonometric__acos():
from sympy.functions.elementary.trigonometric import acos
assert _test_args(acos(2))
def test_sympy__functions__elementary__trigonometric__acot():
from sympy.functions.elementary.trigonometric import acot
assert _test_args(acot(2))
def test_sympy__functions__elementary__trigonometric__asin():
from sympy.functions.elementary.trigonometric import asin
assert _test_args(asin(2))
def test_sympy__functions__elementary__trigonometric__asec():
from sympy.functions.elementary.trigonometric import asec
assert _test_args(asec(x))
def test_sympy__functions__elementary__trigonometric__acsc():
from sympy.functions.elementary.trigonometric import acsc
assert _test_args(acsc(x))
def test_sympy__functions__elementary__trigonometric__atan():
from sympy.functions.elementary.trigonometric import atan
assert _test_args(atan(2))
def test_sympy__functions__elementary__trigonometric__atan2():
from sympy.functions.elementary.trigonometric import atan2
assert _test_args(atan2(2, 3))
def test_sympy__functions__elementary__trigonometric__cos():
from sympy.functions.elementary.trigonometric import cos
assert _test_args(cos(2))
def test_sympy__functions__elementary__trigonometric__csc():
from sympy.functions.elementary.trigonometric import csc
assert _test_args(csc(2))
def test_sympy__functions__elementary__trigonometric__cot():
from sympy.functions.elementary.trigonometric import cot
assert _test_args(cot(2))
def test_sympy__functions__elementary__trigonometric__sin():
assert _test_args(sin(2))
def test_sympy__functions__elementary__trigonometric__sinc():
from sympy.functions.elementary.trigonometric import sinc
assert _test_args(sinc(2))
def test_sympy__functions__elementary__trigonometric__sec():
from sympy.functions.elementary.trigonometric import sec
assert _test_args(sec(2))
def test_sympy__functions__elementary__trigonometric__tan():
from sympy.functions.elementary.trigonometric import tan
assert _test_args(tan(2))
@SKIP("abstract class")
def test_sympy__functions__special__bessel__BesselBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__bessel__SphericalBesselBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__bessel__SphericalHankelBase():
pass
def test_sympy__functions__special__bessel__besseli():
from sympy.functions.special.bessel import besseli
assert _test_args(besseli(x, 1))
def test_sympy__functions__special__bessel__besselj():
from sympy.functions.special.bessel import besselj
assert _test_args(besselj(x, 1))
def test_sympy__functions__special__bessel__besselk():
from sympy.functions.special.bessel import besselk
assert _test_args(besselk(x, 1))
def test_sympy__functions__special__bessel__bessely():
from sympy.functions.special.bessel import bessely
assert _test_args(bessely(x, 1))
def test_sympy__functions__special__bessel__hankel1():
from sympy.functions.special.bessel import hankel1
assert _test_args(hankel1(x, 1))
def test_sympy__functions__special__bessel__hankel2():
from sympy.functions.special.bessel import hankel2
assert _test_args(hankel2(x, 1))
def test_sympy__functions__special__bessel__jn():
from sympy.functions.special.bessel import jn
assert _test_args(jn(0, x))
def test_sympy__functions__special__bessel__yn():
from sympy.functions.special.bessel import yn
assert _test_args(yn(0, x))
def test_sympy__functions__special__bessel__hn1():
from sympy.functions.special.bessel import hn1
assert _test_args(hn1(0, x))
def test_sympy__functions__special__bessel__hn2():
from sympy.functions.special.bessel import hn2
assert _test_args(hn2(0, x))
def test_sympy__functions__special__bessel__AiryBase():
pass
def test_sympy__functions__special__bessel__airyai():
from sympy.functions.special.bessel import airyai
assert _test_args(airyai(2))
def test_sympy__functions__special__bessel__airybi():
from sympy.functions.special.bessel import airybi
assert _test_args(airybi(2))
def test_sympy__functions__special__bessel__airyaiprime():
from sympy.functions.special.bessel import airyaiprime
assert _test_args(airyaiprime(2))
def test_sympy__functions__special__bessel__airybiprime():
from sympy.functions.special.bessel import airybiprime
assert _test_args(airybiprime(2))
def test_sympy__functions__special__bessel__marcumq():
from sympy.functions.special.bessel import marcumq
assert _test_args(marcumq(x, y, z))
def test_sympy__functions__special__elliptic_integrals__elliptic_k():
from sympy.functions.special.elliptic_integrals import elliptic_k as K
assert _test_args(K(x))
def test_sympy__functions__special__elliptic_integrals__elliptic_f():
from sympy.functions.special.elliptic_integrals import elliptic_f as F
assert _test_args(F(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_e():
from sympy.functions.special.elliptic_integrals import elliptic_e as E
assert _test_args(E(x))
assert _test_args(E(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_pi():
from sympy.functions.special.elliptic_integrals import elliptic_pi as P
assert _test_args(P(x, y))
assert _test_args(P(x, y, z))
def test_sympy__functions__special__delta_functions__DiracDelta():
from sympy.functions.special.delta_functions import DiracDelta
assert _test_args(DiracDelta(x, 1))
def test_sympy__functions__special__singularity_functions__SingularityFunction():
from sympy.functions.special.singularity_functions import SingularityFunction
assert _test_args(SingularityFunction(x, y, z))
def test_sympy__functions__special__delta_functions__Heaviside():
from sympy.functions.special.delta_functions import Heaviside
assert _test_args(Heaviside(x))
def test_sympy__functions__special__error_functions__erf():
from sympy.functions.special.error_functions import erf
assert _test_args(erf(2))
def test_sympy__functions__special__error_functions__erfc():
from sympy.functions.special.error_functions import erfc
assert _test_args(erfc(2))
def test_sympy__functions__special__error_functions__erfi():
from sympy.functions.special.error_functions import erfi
assert _test_args(erfi(2))
def test_sympy__functions__special__error_functions__erf2():
from sympy.functions.special.error_functions import erf2
assert _test_args(erf2(2, 3))
def test_sympy__functions__special__error_functions__erfinv():
from sympy.functions.special.error_functions import erfinv
assert _test_args(erfinv(2))
def test_sympy__functions__special__error_functions__erfcinv():
from sympy.functions.special.error_functions import erfcinv
assert _test_args(erfcinv(2))
def test_sympy__functions__special__error_functions__erf2inv():
from sympy.functions.special.error_functions import erf2inv
assert _test_args(erf2inv(2, 3))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__FresnelIntegral():
pass
def test_sympy__functions__special__error_functions__fresnels():
from sympy.functions.special.error_functions import fresnels
assert _test_args(fresnels(2))
def test_sympy__functions__special__error_functions__fresnelc():
from sympy.functions.special.error_functions import fresnelc
assert _test_args(fresnelc(2))
def test_sympy__functions__special__error_functions__erfs():
from sympy.functions.special.error_functions import _erfs
assert _test_args(_erfs(2))
def test_sympy__functions__special__error_functions__Ei():
from sympy.functions.special.error_functions import Ei
assert _test_args(Ei(2))
def test_sympy__functions__special__error_functions__li():
from sympy.functions.special.error_functions import li
assert _test_args(li(2))
def test_sympy__functions__special__error_functions__Li():
from sympy.functions.special.error_functions import Li
assert _test_args(Li(5))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__TrigonometricIntegral():
pass
def test_sympy__functions__special__error_functions__Si():
from sympy.functions.special.error_functions import Si
assert _test_args(Si(2))
def test_sympy__functions__special__error_functions__Ci():
from sympy.functions.special.error_functions import Ci
assert _test_args(Ci(2))
def test_sympy__functions__special__error_functions__Shi():
from sympy.functions.special.error_functions import Shi
assert _test_args(Shi(2))
def test_sympy__functions__special__error_functions__Chi():
from sympy.functions.special.error_functions import Chi
assert _test_args(Chi(2))
def test_sympy__functions__special__error_functions__expint():
from sympy.functions.special.error_functions import expint
assert _test_args(expint(y, x))
def test_sympy__functions__special__gamma_functions__gamma():
from sympy.functions.special.gamma_functions import gamma
assert _test_args(gamma(x))
def test_sympy__functions__special__gamma_functions__loggamma():
from sympy.functions.special.gamma_functions import loggamma
assert _test_args(loggamma(x))
def test_sympy__functions__special__gamma_functions__lowergamma():
from sympy.functions.special.gamma_functions import lowergamma
assert _test_args(lowergamma(x, 2))
def test_sympy__functions__special__gamma_functions__polygamma():
from sympy.functions.special.gamma_functions import polygamma
assert _test_args(polygamma(x, 2))
def test_sympy__functions__special__gamma_functions__digamma():
from sympy.functions.special.gamma_functions import digamma
assert _test_args(digamma(x))
def test_sympy__functions__special__gamma_functions__trigamma():
from sympy.functions.special.gamma_functions import trigamma
assert _test_args(trigamma(x))
def test_sympy__functions__special__gamma_functions__uppergamma():
from sympy.functions.special.gamma_functions import uppergamma
assert _test_args(uppergamma(x, 2))
def test_sympy__functions__special__gamma_functions__multigamma():
from sympy.functions.special.gamma_functions import multigamma
assert _test_args(multigamma(x, 1))
def test_sympy__functions__special__beta_functions__beta():
from sympy.functions.special.beta_functions import beta
assert _test_args(beta(x))
assert _test_args(beta(x, x))
def test_sympy__functions__special__beta_functions__betainc():
from sympy.functions.special.beta_functions import betainc
assert _test_args(betainc(a, b, x, y))
def test_sympy__functions__special__beta_functions__betainc_regularized():
from sympy.functions.special.beta_functions import betainc_regularized
assert _test_args(betainc_regularized(a, b, x, y))
def test_sympy__functions__special__mathieu_functions__MathieuBase():
pass
def test_sympy__functions__special__mathieu_functions__mathieus():
from sympy.functions.special.mathieu_functions import mathieus
assert _test_args(mathieus(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieuc():
from sympy.functions.special.mathieu_functions import mathieuc
assert _test_args(mathieuc(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieusprime():
from sympy.functions.special.mathieu_functions import mathieusprime
assert _test_args(mathieusprime(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieucprime():
from sympy.functions.special.mathieu_functions import mathieucprime
assert _test_args(mathieucprime(1, 1, 1))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleParametersBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleArg():
pass
def test_sympy__functions__special__hyper__hyper():
from sympy.functions.special.hyper import hyper
assert _test_args(hyper([1, 2, 3], [4, 5], x))
def test_sympy__functions__special__hyper__meijerg():
from sympy.functions.special.hyper import meijerg
assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__HyperRep():
pass
def test_sympy__functions__special__hyper__HyperRep_power1():
from sympy.functions.special.hyper import HyperRep_power1
assert _test_args(HyperRep_power1(x, y))
def test_sympy__functions__special__hyper__HyperRep_power2():
from sympy.functions.special.hyper import HyperRep_power2
assert _test_args(HyperRep_power2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log1():
from sympy.functions.special.hyper import HyperRep_log1
assert _test_args(HyperRep_log1(x))
def test_sympy__functions__special__hyper__HyperRep_atanh():
from sympy.functions.special.hyper import HyperRep_atanh
assert _test_args(HyperRep_atanh(x))
def test_sympy__functions__special__hyper__HyperRep_asin1():
from sympy.functions.special.hyper import HyperRep_asin1
assert _test_args(HyperRep_asin1(x))
def test_sympy__functions__special__hyper__HyperRep_asin2():
from sympy.functions.special.hyper import HyperRep_asin2
assert _test_args(HyperRep_asin2(x))
def test_sympy__functions__special__hyper__HyperRep_sqrts1():
from sympy.functions.special.hyper import HyperRep_sqrts1
assert _test_args(HyperRep_sqrts1(x, y))
def test_sympy__functions__special__hyper__HyperRep_sqrts2():
from sympy.functions.special.hyper import HyperRep_sqrts2
assert _test_args(HyperRep_sqrts2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log2():
from sympy.functions.special.hyper import HyperRep_log2
assert _test_args(HyperRep_log2(x))
def test_sympy__functions__special__hyper__HyperRep_cosasin():
from sympy.functions.special.hyper import HyperRep_cosasin
assert _test_args(HyperRep_cosasin(x, y))
def test_sympy__functions__special__hyper__HyperRep_sinasin():
from sympy.functions.special.hyper import HyperRep_sinasin
assert _test_args(HyperRep_sinasin(x, y))
def test_sympy__functions__special__hyper__appellf1():
from sympy.functions.special.hyper import appellf1
a, b1, b2, c, x, y = symbols('a b1 b2 c x y')
assert _test_args(appellf1(a, b1, b2, c, x, y))
@SKIP("abstract class")
def test_sympy__functions__special__polynomials__OrthogonalPolynomial():
pass
def test_sympy__functions__special__polynomials__jacobi():
from sympy.functions.special.polynomials import jacobi
assert _test_args(jacobi(x, y, 2, 2))
def test_sympy__functions__special__polynomials__gegenbauer():
from sympy.functions.special.polynomials import gegenbauer
assert _test_args(gegenbauer(x, 2, 2))
def test_sympy__functions__special__polynomials__chebyshevt():
from sympy.functions.special.polynomials import chebyshevt
assert _test_args(chebyshevt(x, 2))
def test_sympy__functions__special__polynomials__chebyshevt_root():
from sympy.functions.special.polynomials import chebyshevt_root
assert _test_args(chebyshevt_root(3, 2))
def test_sympy__functions__special__polynomials__chebyshevu():
from sympy.functions.special.polynomials import chebyshevu
assert _test_args(chebyshevu(x, 2))
def test_sympy__functions__special__polynomials__chebyshevu_root():
from sympy.functions.special.polynomials import chebyshevu_root
assert _test_args(chebyshevu_root(3, 2))
def test_sympy__functions__special__polynomials__hermite():
from sympy.functions.special.polynomials import hermite
assert _test_args(hermite(x, 2))
def test_sympy__functions__special__polynomials__hermite_prob():
from sympy.functions.special.polynomials import hermite_prob
assert _test_args(hermite_prob(x, 2))
def test_sympy__functions__special__polynomials__legendre():
from sympy.functions.special.polynomials import legendre
assert _test_args(legendre(x, 2))
def test_sympy__functions__special__polynomials__assoc_legendre():
from sympy.functions.special.polynomials import assoc_legendre
assert _test_args(assoc_legendre(x, 0, y))
def test_sympy__functions__special__polynomials__laguerre():
from sympy.functions.special.polynomials import laguerre
assert _test_args(laguerre(x, 2))
def test_sympy__functions__special__polynomials__assoc_laguerre():
from sympy.functions.special.polynomials import assoc_laguerre
assert _test_args(assoc_laguerre(x, 0, y))
def test_sympy__functions__special__spherical_harmonics__Ynm():
from sympy.functions.special.spherical_harmonics import Ynm
assert _test_args(Ynm(1, 1, x, y))
def test_sympy__functions__special__spherical_harmonics__Znm():
from sympy.functions.special.spherical_harmonics import Znm
assert _test_args(Znm(x, y, 1, 1))
def test_sympy__functions__special__tensor_functions__LeviCivita():
from sympy.functions.special.tensor_functions import LeviCivita
assert _test_args(LeviCivita(x, y, 2))
def test_sympy__functions__special__tensor_functions__KroneckerDelta():
from sympy.functions.special.tensor_functions import KroneckerDelta
assert _test_args(KroneckerDelta(x, y))
def test_sympy__functions__special__zeta_functions__dirichlet_eta():
from sympy.functions.special.zeta_functions import dirichlet_eta
assert _test_args(dirichlet_eta(x))
def test_sympy__functions__special__zeta_functions__riemann_xi():
from sympy.functions.special.zeta_functions import riemann_xi
assert _test_args(riemann_xi(x))
def test_sympy__functions__special__zeta_functions__zeta():
from sympy.functions.special.zeta_functions import zeta
assert _test_args(zeta(101))
def test_sympy__functions__special__zeta_functions__lerchphi():
from sympy.functions.special.zeta_functions import lerchphi
assert _test_args(lerchphi(x, y, z))
def test_sympy__functions__special__zeta_functions__polylog():
from sympy.functions.special.zeta_functions import polylog
assert _test_args(polylog(x, y))
def test_sympy__functions__special__zeta_functions__stieltjes():
from sympy.functions.special.zeta_functions import stieltjes
assert _test_args(stieltjes(x, y))
def test_sympy__integrals__integrals__Integral():
from sympy.integrals.integrals import Integral
assert _test_args(Integral(2, (x, 0, 1)))
def test_sympy__integrals__risch__NonElementaryIntegral():
from sympy.integrals.risch import NonElementaryIntegral
assert _test_args(NonElementaryIntegral(exp(-x**2), x))
@SKIP("abstract class")
def test_sympy__integrals__transforms__IntegralTransform():
pass
def test_sympy__integrals__transforms__MellinTransform():
from sympy.integrals.transforms import MellinTransform
assert _test_args(MellinTransform(2, x, y))
def test_sympy__integrals__transforms__InverseMellinTransform():
from sympy.integrals.transforms import InverseMellinTransform
assert _test_args(InverseMellinTransform(2, x, y, 0, 1))
def test_sympy__integrals__transforms__LaplaceTransform():
from sympy.integrals.transforms import LaplaceTransform
assert _test_args(LaplaceTransform(2, x, y))
def test_sympy__integrals__transforms__InverseLaplaceTransform():
from sympy.integrals.transforms import InverseLaplaceTransform
assert _test_args(InverseLaplaceTransform(2, x, y, 0))
@SKIP("abstract class")
def test_sympy__integrals__transforms__FourierTypeTransform():
pass
def test_sympy__integrals__transforms__InverseFourierTransform():
from sympy.integrals.transforms import InverseFourierTransform
assert _test_args(InverseFourierTransform(2, x, y))
def test_sympy__integrals__transforms__FourierTransform():
from sympy.integrals.transforms import FourierTransform
assert _test_args(FourierTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__SineCosineTypeTransform():
pass
def test_sympy__integrals__transforms__InverseSineTransform():
from sympy.integrals.transforms import InverseSineTransform
assert _test_args(InverseSineTransform(2, x, y))
def test_sympy__integrals__transforms__SineTransform():
from sympy.integrals.transforms import SineTransform
assert _test_args(SineTransform(2, x, y))
def test_sympy__integrals__transforms__InverseCosineTransform():
from sympy.integrals.transforms import InverseCosineTransform
assert _test_args(InverseCosineTransform(2, x, y))
def test_sympy__integrals__transforms__CosineTransform():
from sympy.integrals.transforms import CosineTransform
assert _test_args(CosineTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__HankelTypeTransform():
pass
def test_sympy__integrals__transforms__InverseHankelTransform():
from sympy.integrals.transforms import InverseHankelTransform
assert _test_args(InverseHankelTransform(2, x, y, 0))
def test_sympy__integrals__transforms__HankelTransform():
from sympy.integrals.transforms import HankelTransform
assert _test_args(HankelTransform(2, x, y, 0))
def test_sympy__liealgebras__cartan_type__Standard_Cartan():
from sympy.liealgebras.cartan_type import Standard_Cartan
assert _test_args(Standard_Cartan("A", 2))
def test_sympy__liealgebras__weyl_group__WeylGroup():
from sympy.liealgebras.weyl_group import WeylGroup
assert _test_args(WeylGroup("B4"))
def test_sympy__liealgebras__root_system__RootSystem():
from sympy.liealgebras.root_system import RootSystem
assert _test_args(RootSystem("A2"))
def test_sympy__liealgebras__type_a__TypeA():
from sympy.liealgebras.type_a import TypeA
assert _test_args(TypeA(2))
def test_sympy__liealgebras__type_b__TypeB():
from sympy.liealgebras.type_b import TypeB
assert _test_args(TypeB(4))
def test_sympy__liealgebras__type_c__TypeC():
from sympy.liealgebras.type_c import TypeC
assert _test_args(TypeC(4))
def test_sympy__liealgebras__type_d__TypeD():
from sympy.liealgebras.type_d import TypeD
assert _test_args(TypeD(4))
def test_sympy__liealgebras__type_e__TypeE():
from sympy.liealgebras.type_e import TypeE
assert _test_args(TypeE(6))
def test_sympy__liealgebras__type_f__TypeF():
from sympy.liealgebras.type_f import TypeF
assert _test_args(TypeF(4))
def test_sympy__liealgebras__type_g__TypeG():
from sympy.liealgebras.type_g import TypeG
assert _test_args(TypeG(2))
def test_sympy__logic__boolalg__And():
from sympy.logic.boolalg import And
assert _test_args(And(x, y, 1))
@SKIP("abstract class")
def test_sympy__logic__boolalg__Boolean():
pass
def test_sympy__logic__boolalg__BooleanFunction():
from sympy.logic.boolalg import BooleanFunction
assert _test_args(BooleanFunction(1, 2, 3))
@SKIP("abstract class")
def test_sympy__logic__boolalg__BooleanAtom():
pass
def test_sympy__logic__boolalg__BooleanTrue():
from sympy.logic.boolalg import true
assert _test_args(true)
def test_sympy__logic__boolalg__BooleanFalse():
from sympy.logic.boolalg import false
assert _test_args(false)
def test_sympy__logic__boolalg__Equivalent():
from sympy.logic.boolalg import Equivalent
assert _test_args(Equivalent(x, 2))
def test_sympy__logic__boolalg__ITE():
from sympy.logic.boolalg import ITE
assert _test_args(ITE(x, y, 1))
def test_sympy__logic__boolalg__Implies():
from sympy.logic.boolalg import Implies
assert _test_args(Implies(x, y))
def test_sympy__logic__boolalg__Nand():
from sympy.logic.boolalg import Nand
assert _test_args(Nand(x, y, 1))
def test_sympy__logic__boolalg__Nor():
from sympy.logic.boolalg import Nor
assert _test_args(Nor(x, y))
def test_sympy__logic__boolalg__Not():
from sympy.logic.boolalg import Not
assert _test_args(Not(x))
def test_sympy__logic__boolalg__Or():
from sympy.logic.boolalg import Or
assert _test_args(Or(x, y))
def test_sympy__logic__boolalg__Xor():
from sympy.logic.boolalg import Xor
assert _test_args(Xor(x, y, 2))
def test_sympy__logic__boolalg__Xnor():
from sympy.logic.boolalg import Xnor
assert _test_args(Xnor(x, y, 2))
def test_sympy__logic__boolalg__Exclusive():
from sympy.logic.boolalg import Exclusive
assert _test_args(Exclusive(x, y, z))
def test_sympy__matrices__matrices__DeferredVector():
from sympy.matrices.matrices import DeferredVector
assert _test_args(DeferredVector("X"))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixBase():
pass
@SKIP("abstract class")
def test_sympy__matrices__immutable__ImmutableRepMatrix():
pass
def test_sympy__matrices__immutable__ImmutableDenseMatrix():
from sympy.matrices.immutable import ImmutableDenseMatrix
m = ImmutableDenseMatrix([[1, 2], [3, 4]])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableDenseMatrix(1, 1, [1])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableDenseMatrix(2, 2, lambda i, j: 1)
assert m[0, 0] is S.One
m = ImmutableDenseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))
assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified
assert _test_args(m)
assert _test_args(Basic(*list(m)))
def test_sympy__matrices__immutable__ImmutableSparseMatrix():
from sympy.matrices.immutable import ImmutableSparseMatrix
m = ImmutableSparseMatrix([[1, 2], [3, 4]])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(1, 1, {(0, 0): 1})
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(1, 1, [1])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(2, 2, lambda i, j: 1)
assert m[0, 0] is S.One
m = ImmutableSparseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))
assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified
assert _test_args(m)
assert _test_args(Basic(*list(m)))
def test_sympy__matrices__expressions__slice__MatrixSlice():
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 4, 4)
assert _test_args(MatrixSlice(X, (0, 2), (0, 2)))
def test_sympy__matrices__expressions__applyfunc__ElementwiseApplyFunction():
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol("X", x, x)
func = Lambda(x, x**2)
assert _test_args(ElementwiseApplyFunction(func, X))
def test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix():
from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
assert _test_args(BlockDiagMatrix(X, Y))
def test_sympy__matrices__expressions__blockmatrix__BlockMatrix():
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
Z = MatrixSymbol('Z', x, y)
O = ZeroMatrix(y, x)
assert _test_args(BlockMatrix([[X, Z], [O, Y]]))
def test_sympy__matrices__expressions__inverse__Inverse():
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Inverse(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__matadd__MatAdd():
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(MatAdd(X, Y))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixExpr():
pass
def test_sympy__matrices__expressions__matexpr__MatrixElement():
from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElement
from sympy.core.singleton import S
assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3)))
def test_sympy__matrices__expressions__matexpr__MatrixSymbol():
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(MatrixSymbol('A', 3, 5))
def test_sympy__matrices__expressions__special__OneMatrix():
from sympy.matrices.expressions.special import OneMatrix
assert _test_args(OneMatrix(3, 5))
def test_sympy__matrices__expressions__special__ZeroMatrix():
from sympy.matrices.expressions.special import ZeroMatrix
assert _test_args(ZeroMatrix(3, 5))
def test_sympy__matrices__expressions__special__GenericZeroMatrix():
from sympy.matrices.expressions.special import GenericZeroMatrix
assert _test_args(GenericZeroMatrix())
def test_sympy__matrices__expressions__special__Identity():
from sympy.matrices.expressions.special import Identity
assert _test_args(Identity(3))
def test_sympy__matrices__expressions__special__GenericIdentity():
from sympy.matrices.expressions.special import GenericIdentity
assert _test_args(GenericIdentity())
def test_sympy__matrices__expressions__sets__MatrixSet():
from sympy.matrices.expressions.sets import MatrixSet
from sympy.core.singleton import S
assert _test_args(MatrixSet(2, 2, S.Reals))
def test_sympy__matrices__expressions__matmul__MatMul():
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', y, x)
assert _test_args(MatMul(X, Y))
def test_sympy__matrices__expressions__dotproduct__DotProduct():
from sympy.matrices.expressions.dotproduct import DotProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, 1)
Y = MatrixSymbol('Y', x, 1)
assert _test_args(DotProduct(X, Y))
def test_sympy__matrices__expressions__diagonal__DiagonalMatrix():
from sympy.matrices.expressions.diagonal import DiagonalMatrix
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagonalMatrix(x))
def test_sympy__matrices__expressions__diagonal__DiagonalOf():
from sympy.matrices.expressions.diagonal import DiagonalOf
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('x', 10, 10)
assert _test_args(DiagonalOf(X))
def test_sympy__matrices__expressions__diagonal__DiagMatrix():
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagMatrix(x))
def test_sympy__matrices__expressions__hadamard__HadamardProduct():
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(HadamardProduct(X, Y))
def test_sympy__matrices__expressions__hadamard__HadamardPower():
from sympy.matrices.expressions.hadamard import HadamardPower
from sympy.matrices.expressions import MatrixSymbol
from sympy.core.symbol import Symbol
X = MatrixSymbol('X', x, y)
n = Symbol("n")
assert _test_args(HadamardPower(X, n))
def test_sympy__matrices__expressions__kronecker__KroneckerProduct():
from sympy.matrices.expressions.kronecker import KroneckerProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(KroneckerProduct(X, Y))
def test_sympy__matrices__expressions__matpow__MatPow():
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
assert _test_args(MatPow(X, 2))
def test_sympy__matrices__expressions__transpose__Transpose():
from sympy.matrices.expressions.transpose import Transpose
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Transpose(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__adjoint__Adjoint():
from sympy.matrices.expressions.adjoint import Adjoint
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Adjoint(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__trace__Trace():
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Trace(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__determinant__Determinant():
from sympy.matrices.expressions.determinant import Determinant
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Determinant(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__determinant__Permanent():
from sympy.matrices.expressions.determinant import Permanent
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Permanent(MatrixSymbol('A', 3, 4)))
def test_sympy__matrices__expressions__funcmatrix__FunctionMatrix():
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
from sympy.core.symbol import symbols
i, j = symbols('i,j')
assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) ))
def test_sympy__matrices__expressions__fourier__DFT():
from sympy.matrices.expressions.fourier import DFT
from sympy.core.singleton import S
assert _test_args(DFT(S(2)))
def test_sympy__matrices__expressions__fourier__IDFT():
from sympy.matrices.expressions.fourier import IDFT
from sympy.core.singleton import S
assert _test_args(IDFT(S(2)))
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 10, 10)
def test_sympy__matrices__expressions__factorizations__LofLU():
from sympy.matrices.expressions.factorizations import LofLU
assert _test_args(LofLU(X))
def test_sympy__matrices__expressions__factorizations__UofLU():
from sympy.matrices.expressions.factorizations import UofLU
assert _test_args(UofLU(X))
def test_sympy__matrices__expressions__factorizations__QofQR():
from sympy.matrices.expressions.factorizations import QofQR
assert _test_args(QofQR(X))
def test_sympy__matrices__expressions__factorizations__RofQR():
from sympy.matrices.expressions.factorizations import RofQR
assert _test_args(RofQR(X))
def test_sympy__matrices__expressions__factorizations__LofCholesky():
from sympy.matrices.expressions.factorizations import LofCholesky
assert _test_args(LofCholesky(X))
def test_sympy__matrices__expressions__factorizations__UofCholesky():
from sympy.matrices.expressions.factorizations import UofCholesky
assert _test_args(UofCholesky(X))
def test_sympy__matrices__expressions__factorizations__EigenVectors():
from sympy.matrices.expressions.factorizations import EigenVectors
assert _test_args(EigenVectors(X))
def test_sympy__matrices__expressions__factorizations__EigenValues():
from sympy.matrices.expressions.factorizations import EigenValues
assert _test_args(EigenValues(X))
def test_sympy__matrices__expressions__factorizations__UofSVD():
from sympy.matrices.expressions.factorizations import UofSVD
assert _test_args(UofSVD(X))
def test_sympy__matrices__expressions__factorizations__VofSVD():
from sympy.matrices.expressions.factorizations import VofSVD
assert _test_args(VofSVD(X))
def test_sympy__matrices__expressions__factorizations__SofSVD():
from sympy.matrices.expressions.factorizations import SofSVD
assert _test_args(SofSVD(X))
@SKIP("abstract class")
def test_sympy__matrices__expressions__factorizations__Factorization():
pass
def test_sympy__matrices__expressions__permutation__PermutationMatrix():
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.permutation import PermutationMatrix
assert _test_args(PermutationMatrix(Permutation([2, 0, 1])))
def test_sympy__matrices__expressions__permutation__MatrixPermute():
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.permutation import MatrixPermute
A = MatrixSymbol('A', 3, 3)
assert _test_args(MatrixPermute(A, Permutation([2, 0, 1])))
def test_sympy__matrices__expressions__companion__CompanionMatrix():
from sympy.core.symbol import Symbol
from sympy.matrices.expressions.companion import CompanionMatrix
from sympy.polys.polytools import Poly
x = Symbol('x')
p = Poly([1, 2, 3], x)
assert _test_args(CompanionMatrix(p))
def test_sympy__physics__vector__frame__CoordinateSym():
from sympy.physics.vector import CoordinateSym
from sympy.physics.vector import ReferenceFrame
assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0))
def test_sympy__physics__paulialgebra__Pauli():
from sympy.physics.paulialgebra import Pauli
assert _test_args(Pauli(1))
def test_sympy__physics__quantum__anticommutator__AntiCommutator():
from sympy.physics.quantum.anticommutator import AntiCommutator
assert _test_args(AntiCommutator(x, y))
def test_sympy__physics__quantum__cartesian__PositionBra3D():
from sympy.physics.quantum.cartesian import PositionBra3D
assert _test_args(PositionBra3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionKet3D():
from sympy.physics.quantum.cartesian import PositionKet3D
assert _test_args(PositionKet3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionState3D():
from sympy.physics.quantum.cartesian import PositionState3D
assert _test_args(PositionState3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PxBra():
from sympy.physics.quantum.cartesian import PxBra
assert _test_args(PxBra(x, y, z))
def test_sympy__physics__quantum__cartesian__PxKet():
from sympy.physics.quantum.cartesian import PxKet
assert _test_args(PxKet(x, y, z))
def test_sympy__physics__quantum__cartesian__PxOp():
from sympy.physics.quantum.cartesian import PxOp
assert _test_args(PxOp(x, y, z))
def test_sympy__physics__quantum__cartesian__XBra():
from sympy.physics.quantum.cartesian import XBra
assert _test_args(XBra(x))
def test_sympy__physics__quantum__cartesian__XKet():
from sympy.physics.quantum.cartesian import XKet
assert _test_args(XKet(x))
def test_sympy__physics__quantum__cartesian__XOp():
from sympy.physics.quantum.cartesian import XOp
assert _test_args(XOp(x))
def test_sympy__physics__quantum__cartesian__YOp():
from sympy.physics.quantum.cartesian import YOp
assert _test_args(YOp(x))
def test_sympy__physics__quantum__cartesian__ZOp():
from sympy.physics.quantum.cartesian import ZOp
assert _test_args(ZOp(x))
def test_sympy__physics__quantum__cg__CG():
from sympy.physics.quantum.cg import CG
from sympy.core.singleton import S
assert _test_args(CG(Rational(3, 2), Rational(3, 2), S.Half, Rational(-1, 2), 1, 1))
def test_sympy__physics__quantum__cg__Wigner3j():
from sympy.physics.quantum.cg import Wigner3j
assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0))
def test_sympy__physics__quantum__cg__Wigner6j():
from sympy.physics.quantum.cg import Wigner6j
assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2))
def test_sympy__physics__quantum__cg__Wigner9j():
from sympy.physics.quantum.cg import Wigner9j
assert _test_args(Wigner9j(2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0))
def test_sympy__physics__quantum__circuitplot__Mz():
from sympy.physics.quantum.circuitplot import Mz
assert _test_args(Mz(0))
def test_sympy__physics__quantum__circuitplot__Mx():
from sympy.physics.quantum.circuitplot import Mx
assert _test_args(Mx(0))
def test_sympy__physics__quantum__commutator__Commutator():
from sympy.physics.quantum.commutator import Commutator
A, B = symbols('A,B', commutative=False)
assert _test_args(Commutator(A, B))
def test_sympy__physics__quantum__constants__HBar():
from sympy.physics.quantum.constants import HBar
assert _test_args(HBar())
def test_sympy__physics__quantum__dagger__Dagger():
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Ket
assert _test_args(Dagger(Dagger(Ket('psi'))))
def test_sympy__physics__quantum__gate__CGate():
from sympy.physics.quantum.gate import CGate, Gate
assert _test_args(CGate((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CGateS():
from sympy.physics.quantum.gate import CGateS, Gate
assert _test_args(CGateS((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CNotGate():
from sympy.physics.quantum.gate import CNotGate
assert _test_args(CNotGate(0, 1))
def test_sympy__physics__quantum__gate__Gate():
from sympy.physics.quantum.gate import Gate
assert _test_args(Gate(0))
def test_sympy__physics__quantum__gate__HadamardGate():
from sympy.physics.quantum.gate import HadamardGate
assert _test_args(HadamardGate(0))
def test_sympy__physics__quantum__gate__IdentityGate():
from sympy.physics.quantum.gate import IdentityGate
assert _test_args(IdentityGate(0))
def test_sympy__physics__quantum__gate__OneQubitGate():
from sympy.physics.quantum.gate import OneQubitGate
assert _test_args(OneQubitGate(0))
def test_sympy__physics__quantum__gate__PhaseGate():
from sympy.physics.quantum.gate import PhaseGate
assert _test_args(PhaseGate(0))
def test_sympy__physics__quantum__gate__SwapGate():
from sympy.physics.quantum.gate import SwapGate
assert _test_args(SwapGate(0, 1))
def test_sympy__physics__quantum__gate__TGate():
from sympy.physics.quantum.gate import TGate
assert _test_args(TGate(0))
def test_sympy__physics__quantum__gate__TwoQubitGate():
from sympy.physics.quantum.gate import TwoQubitGate
assert _test_args(TwoQubitGate(0))
def test_sympy__physics__quantum__gate__UGate():
from sympy.physics.quantum.gate import UGate
from sympy.matrices.immutable import ImmutableDenseMatrix
from sympy.core.containers import Tuple
from sympy.core.numbers import Integer
assert _test_args(
UGate(Tuple(Integer(1)), ImmutableDenseMatrix([[1, 0], [0, 2]])))
def test_sympy__physics__quantum__gate__XGate():
from sympy.physics.quantum.gate import XGate
assert _test_args(XGate(0))
def test_sympy__physics__quantum__gate__YGate():
from sympy.physics.quantum.gate import YGate
assert _test_args(YGate(0))
def test_sympy__physics__quantum__gate__ZGate():
from sympy.physics.quantum.gate import ZGate
assert _test_args(ZGate(0))
def test_sympy__physics__quantum__grover__OracleGateFunction():
from sympy.physics.quantum.grover import OracleGateFunction
@OracleGateFunction
def f(qubit):
return
assert _test_args(f)
def test_sympy__physics__quantum__grover__OracleGate():
from sympy.physics.quantum.grover import OracleGate
def f(qubit):
return
assert _test_args(OracleGate(1,f))
def test_sympy__physics__quantum__grover__WGate():
from sympy.physics.quantum.grover import WGate
assert _test_args(WGate(1))
def test_sympy__physics__quantum__hilbert__ComplexSpace():
from sympy.physics.quantum.hilbert import ComplexSpace
assert _test_args(ComplexSpace(x))
def test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace():
from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(DirectSumHilbertSpace(c, f))
def test_sympy__physics__quantum__hilbert__FockSpace():
from sympy.physics.quantum.hilbert import FockSpace
assert _test_args(FockSpace())
def test_sympy__physics__quantum__hilbert__HilbertSpace():
from sympy.physics.quantum.hilbert import HilbertSpace
assert _test_args(HilbertSpace())
def test_sympy__physics__quantum__hilbert__L2():
from sympy.physics.quantum.hilbert import L2
from sympy.core.numbers import oo
from sympy.sets.sets import Interval
assert _test_args(L2(Interval(0, oo)))
def test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace():
from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpace
f = FockSpace()
assert _test_args(TensorPowerHilbertSpace(f, 2))
def test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace():
from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(TensorProductHilbertSpace(f, c))
def test_sympy__physics__quantum__innerproduct__InnerProduct():
from sympy.physics.quantum import Bra, Ket, InnerProduct
b = Bra('b')
k = Ket('k')
assert _test_args(InnerProduct(b, k))
def test_sympy__physics__quantum__operator__DifferentialOperator():
from sympy.physics.quantum.operator import DifferentialOperator
from sympy.core.function import (Derivative, Function)
f = Function('f')
assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x)))
def test_sympy__physics__quantum__operator__HermitianOperator():
from sympy.physics.quantum.operator import HermitianOperator
assert _test_args(HermitianOperator('H'))
def test_sympy__physics__quantum__operator__IdentityOperator():
from sympy.physics.quantum.operator import IdentityOperator
assert _test_args(IdentityOperator(5))
def test_sympy__physics__quantum__operator__Operator():
from sympy.physics.quantum.operator import Operator
assert _test_args(Operator('A'))
def test_sympy__physics__quantum__operator__OuterProduct():
from sympy.physics.quantum.operator import OuterProduct
from sympy.physics.quantum import Ket, Bra
b = Bra('b')
k = Ket('k')
assert _test_args(OuterProduct(k, b))
def test_sympy__physics__quantum__operator__UnitaryOperator():
from sympy.physics.quantum.operator import UnitaryOperator
assert _test_args(UnitaryOperator('U'))
def test_sympy__physics__quantum__piab__PIABBra():
from sympy.physics.quantum.piab import PIABBra
assert _test_args(PIABBra('B'))
def test_sympy__physics__quantum__boson__BosonOp():
from sympy.physics.quantum.boson import BosonOp
assert _test_args(BosonOp('a'))
assert _test_args(BosonOp('a', False))
def test_sympy__physics__quantum__boson__BosonFockKet():
from sympy.physics.quantum.boson import BosonFockKet
assert _test_args(BosonFockKet(1))
def test_sympy__physics__quantum__boson__BosonFockBra():
from sympy.physics.quantum.boson import BosonFockBra
assert _test_args(BosonFockBra(1))
def test_sympy__physics__quantum__boson__BosonCoherentKet():
from sympy.physics.quantum.boson import BosonCoherentKet
assert _test_args(BosonCoherentKet(1))
def test_sympy__physics__quantum__boson__BosonCoherentBra():
from sympy.physics.quantum.boson import BosonCoherentBra
assert _test_args(BosonCoherentBra(1))
def test_sympy__physics__quantum__fermion__FermionOp():
from sympy.physics.quantum.fermion import FermionOp
assert _test_args(FermionOp('c'))
assert _test_args(FermionOp('c', False))
def test_sympy__physics__quantum__fermion__FermionFockKet():
from sympy.physics.quantum.fermion import FermionFockKet
assert _test_args(FermionFockKet(1))
def test_sympy__physics__quantum__fermion__FermionFockBra():
from sympy.physics.quantum.fermion import FermionFockBra
assert _test_args(FermionFockBra(1))
def test_sympy__physics__quantum__pauli__SigmaOpBase():
from sympy.physics.quantum.pauli import SigmaOpBase
assert _test_args(SigmaOpBase())
def test_sympy__physics__quantum__pauli__SigmaX():
from sympy.physics.quantum.pauli import SigmaX
assert _test_args(SigmaX())
def test_sympy__physics__quantum__pauli__SigmaY():
from sympy.physics.quantum.pauli import SigmaY
assert _test_args(SigmaY())
def test_sympy__physics__quantum__pauli__SigmaZ():
from sympy.physics.quantum.pauli import SigmaZ
assert _test_args(SigmaZ())
def test_sympy__physics__quantum__pauli__SigmaMinus():
from sympy.physics.quantum.pauli import SigmaMinus
assert _test_args(SigmaMinus())
def test_sympy__physics__quantum__pauli__SigmaPlus():
from sympy.physics.quantum.pauli import SigmaPlus
assert _test_args(SigmaPlus())
def test_sympy__physics__quantum__pauli__SigmaZKet():
from sympy.physics.quantum.pauli import SigmaZKet
assert _test_args(SigmaZKet(0))
def test_sympy__physics__quantum__pauli__SigmaZBra():
from sympy.physics.quantum.pauli import SigmaZBra
assert _test_args(SigmaZBra(0))
def test_sympy__physics__quantum__piab__PIABHamiltonian():
from sympy.physics.quantum.piab import PIABHamiltonian
assert _test_args(PIABHamiltonian('P'))
def test_sympy__physics__quantum__piab__PIABKet():
from sympy.physics.quantum.piab import PIABKet
assert _test_args(PIABKet('K'))
def test_sympy__physics__quantum__qexpr__QExpr():
from sympy.physics.quantum.qexpr import QExpr
assert _test_args(QExpr(0))
def test_sympy__physics__quantum__qft__Fourier():
from sympy.physics.quantum.qft import Fourier
assert _test_args(Fourier(0, 1))
def test_sympy__physics__quantum__qft__IQFT():
from sympy.physics.quantum.qft import IQFT
assert _test_args(IQFT(0, 1))
def test_sympy__physics__quantum__qft__QFT():
from sympy.physics.quantum.qft import QFT
assert _test_args(QFT(0, 1))
def test_sympy__physics__quantum__qft__RkGate():
from sympy.physics.quantum.qft import RkGate
assert _test_args(RkGate(0, 1))
def test_sympy__physics__quantum__qubit__IntQubit():
from sympy.physics.quantum.qubit import IntQubit
assert _test_args(IntQubit(0))
def test_sympy__physics__quantum__qubit__IntQubitBra():
from sympy.physics.quantum.qubit import IntQubitBra
assert _test_args(IntQubitBra(0))
def test_sympy__physics__quantum__qubit__IntQubitState():
from sympy.physics.quantum.qubit import IntQubitState, QubitState
assert _test_args(IntQubitState(QubitState(0, 1)))
def test_sympy__physics__quantum__qubit__Qubit():
from sympy.physics.quantum.qubit import Qubit
assert _test_args(Qubit(0, 0, 0))
def test_sympy__physics__quantum__qubit__QubitBra():
from sympy.physics.quantum.qubit import QubitBra
assert _test_args(QubitBra('1', 0))
def test_sympy__physics__quantum__qubit__QubitState():
from sympy.physics.quantum.qubit import QubitState
assert _test_args(QubitState(0, 1))
def test_sympy__physics__quantum__density__Density():
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.state import Ket
assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5]))
@SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented")
def test_sympy__physics__quantum__shor__CMod():
from sympy.physics.quantum.shor import CMod
assert _test_args(CMod())
def test_sympy__physics__quantum__spin__CoupledSpinState():
from sympy.physics.quantum.spin import CoupledSpinState
assert _test_args(CoupledSpinState(1, 0, (1, 1)))
assert _test_args(CoupledSpinState(1, 0, (1, S.Half, S.Half)))
assert _test_args(CoupledSpinState(
1, 0, (1, S.Half, S.Half), ((2, 3, S.Half), (1, 2, 1)) ))
j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x')
assert CoupledSpinState(
j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3))
assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \
CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) )
def test_sympy__physics__quantum__spin__J2Op():
from sympy.physics.quantum.spin import J2Op
assert _test_args(J2Op('J'))
def test_sympy__physics__quantum__spin__JminusOp():
from sympy.physics.quantum.spin import JminusOp
assert _test_args(JminusOp('J'))
def test_sympy__physics__quantum__spin__JplusOp():
from sympy.physics.quantum.spin import JplusOp
assert _test_args(JplusOp('J'))
def test_sympy__physics__quantum__spin__JxBra():
from sympy.physics.quantum.spin import JxBra
assert _test_args(JxBra(1, 0))
def test_sympy__physics__quantum__spin__JxBraCoupled():
from sympy.physics.quantum.spin import JxBraCoupled
assert _test_args(JxBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxKet():
from sympy.physics.quantum.spin import JxKet
assert _test_args(JxKet(1, 0))
def test_sympy__physics__quantum__spin__JxKetCoupled():
from sympy.physics.quantum.spin import JxKetCoupled
assert _test_args(JxKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxOp():
from sympy.physics.quantum.spin import JxOp
assert _test_args(JxOp('J'))
def test_sympy__physics__quantum__spin__JyBra():
from sympy.physics.quantum.spin import JyBra
assert _test_args(JyBra(1, 0))
def test_sympy__physics__quantum__spin__JyBraCoupled():
from sympy.physics.quantum.spin import JyBraCoupled
assert _test_args(JyBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyKet():
from sympy.physics.quantum.spin import JyKet
assert _test_args(JyKet(1, 0))
def test_sympy__physics__quantum__spin__JyKetCoupled():
from sympy.physics.quantum.spin import JyKetCoupled
assert _test_args(JyKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyOp():
from sympy.physics.quantum.spin import JyOp
assert _test_args(JyOp('J'))
def test_sympy__physics__quantum__spin__JzBra():
from sympy.physics.quantum.spin import JzBra
assert _test_args(JzBra(1, 0))
def test_sympy__physics__quantum__spin__JzBraCoupled():
from sympy.physics.quantum.spin import JzBraCoupled
assert _test_args(JzBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzKet():
from sympy.physics.quantum.spin import JzKet
assert _test_args(JzKet(1, 0))
def test_sympy__physics__quantum__spin__JzKetCoupled():
from sympy.physics.quantum.spin import JzKetCoupled
assert _test_args(JzKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzOp():
from sympy.physics.quantum.spin import JzOp
assert _test_args(JzOp('J'))
def test_sympy__physics__quantum__spin__Rotation():
from sympy.physics.quantum.spin import Rotation
assert _test_args(Rotation(pi, 0, pi/2))
def test_sympy__physics__quantum__spin__SpinState():
from sympy.physics.quantum.spin import SpinState
assert _test_args(SpinState(1, 0))
def test_sympy__physics__quantum__spin__WignerD():
from sympy.physics.quantum.spin import WignerD
assert _test_args(WignerD(0, 1, 2, 3, 4, 5))
def test_sympy__physics__quantum__state__Bra():
from sympy.physics.quantum.state import Bra
assert _test_args(Bra(0))
def test_sympy__physics__quantum__state__BraBase():
from sympy.physics.quantum.state import BraBase
assert _test_args(BraBase(0))
def test_sympy__physics__quantum__state__Ket():
from sympy.physics.quantum.state import Ket
assert _test_args(Ket(0))
def test_sympy__physics__quantum__state__KetBase():
from sympy.physics.quantum.state import KetBase
assert _test_args(KetBase(0))
def test_sympy__physics__quantum__state__State():
from sympy.physics.quantum.state import State
assert _test_args(State(0))
def test_sympy__physics__quantum__state__StateBase():
from sympy.physics.quantum.state import StateBase
assert _test_args(StateBase(0))
def test_sympy__physics__quantum__state__OrthogonalBra():
from sympy.physics.quantum.state import OrthogonalBra
assert _test_args(OrthogonalBra(0))
def test_sympy__physics__quantum__state__OrthogonalKet():
from sympy.physics.quantum.state import OrthogonalKet
assert _test_args(OrthogonalKet(0))
def test_sympy__physics__quantum__state__OrthogonalState():
from sympy.physics.quantum.state import OrthogonalState
assert _test_args(OrthogonalState(0))
def test_sympy__physics__quantum__state__TimeDepBra():
from sympy.physics.quantum.state import TimeDepBra
assert _test_args(TimeDepBra('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepKet():
from sympy.physics.quantum.state import TimeDepKet
assert _test_args(TimeDepKet('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepState():
from sympy.physics.quantum.state import TimeDepState
assert _test_args(TimeDepState('psi', 't'))
def test_sympy__physics__quantum__state__Wavefunction():
from sympy.physics.quantum.state import Wavefunction
from sympy.functions import sin
from sympy.functions.elementary.piecewise import Piecewise
n = 1
L = 1
g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
assert _test_args(Wavefunction(g, x))
def test_sympy__physics__quantum__tensorproduct__TensorProduct():
from sympy.physics.quantum.tensorproduct import TensorProduct
x, y = symbols("x y", commutative=False)
assert _test_args(TensorProduct(x, y))
def test_sympy__physics__quantum__identitysearch__GateIdentity():
from sympy.physics.quantum.gate import X
from sympy.physics.quantum.identitysearch import GateIdentity
assert _test_args(GateIdentity(X(0), X(0)))
def test_sympy__physics__quantum__sho1d__SHOOp():
from sympy.physics.quantum.sho1d import SHOOp
assert _test_args(SHOOp('a'))
def test_sympy__physics__quantum__sho1d__RaisingOp():
from sympy.physics.quantum.sho1d import RaisingOp
assert _test_args(RaisingOp('a'))
def test_sympy__physics__quantum__sho1d__LoweringOp():
from sympy.physics.quantum.sho1d import LoweringOp
assert _test_args(LoweringOp('a'))
def test_sympy__physics__quantum__sho1d__NumberOp():
from sympy.physics.quantum.sho1d import NumberOp
assert _test_args(NumberOp('N'))
def test_sympy__physics__quantum__sho1d__Hamiltonian():
from sympy.physics.quantum.sho1d import Hamiltonian
assert _test_args(Hamiltonian('H'))
def test_sympy__physics__quantum__sho1d__SHOState():
from sympy.physics.quantum.sho1d import SHOState
assert _test_args(SHOState(0))
def test_sympy__physics__quantum__sho1d__SHOKet():
from sympy.physics.quantum.sho1d import SHOKet
assert _test_args(SHOKet(0))
def test_sympy__physics__quantum__sho1d__SHOBra():
from sympy.physics.quantum.sho1d import SHOBra
assert _test_args(SHOBra(0))
def test_sympy__physics__secondquant__AnnihilateBoson():
from sympy.physics.secondquant import AnnihilateBoson
assert _test_args(AnnihilateBoson(0))
def test_sympy__physics__secondquant__AnnihilateFermion():
from sympy.physics.secondquant import AnnihilateFermion
assert _test_args(AnnihilateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Annihilator():
pass
def test_sympy__physics__secondquant__AntiSymmetricTensor():
from sympy.physics.secondquant import AntiSymmetricTensor
i, j = symbols('i j', below_fermi=True)
a, b = symbols('a b', above_fermi=True)
assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j)))
def test_sympy__physics__secondquant__BosonState():
from sympy.physics.secondquant import BosonState
assert _test_args(BosonState((0, 1)))
@SKIP("abstract class")
def test_sympy__physics__secondquant__BosonicOperator():
pass
def test_sympy__physics__secondquant__Commutator():
from sympy.physics.secondquant import Commutator
x, y = symbols('x y', commutative=False)
assert _test_args(Commutator(x, y))
def test_sympy__physics__secondquant__CreateBoson():
from sympy.physics.secondquant import CreateBoson
assert _test_args(CreateBoson(0))
def test_sympy__physics__secondquant__CreateFermion():
from sympy.physics.secondquant import CreateFermion
assert _test_args(CreateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Creator():
pass
def test_sympy__physics__secondquant__Dagger():
from sympy.physics.secondquant import Dagger
assert _test_args(Dagger(x))
def test_sympy__physics__secondquant__FermionState():
from sympy.physics.secondquant import FermionState
assert _test_args(FermionState((0, 1)))
def test_sympy__physics__secondquant__FermionicOperator():
from sympy.physics.secondquant import FermionicOperator
assert _test_args(FermionicOperator(0))
def test_sympy__physics__secondquant__FockState():
from sympy.physics.secondquant import FockState
assert _test_args(FockState((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonBra():
from sympy.physics.secondquant import FockStateBosonBra
assert _test_args(FockStateBosonBra((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonKet():
from sympy.physics.secondquant import FockStateBosonKet
assert _test_args(FockStateBosonKet((0, 1)))
def test_sympy__physics__secondquant__FockStateBra():
from sympy.physics.secondquant import FockStateBra
assert _test_args(FockStateBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionBra():
from sympy.physics.secondquant import FockStateFermionBra
assert _test_args(FockStateFermionBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionKet():
from sympy.physics.secondquant import FockStateFermionKet
assert _test_args(FockStateFermionKet((0, 1)))
def test_sympy__physics__secondquant__FockStateKet():
from sympy.physics.secondquant import FockStateKet
assert _test_args(FockStateKet((0, 1)))
def test_sympy__physics__secondquant__InnerProduct():
from sympy.physics.secondquant import InnerProduct
from sympy.physics.secondquant import FockStateKet, FockStateBra
assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1))))
def test_sympy__physics__secondquant__NO():
from sympy.physics.secondquant import NO, F, Fd
assert _test_args(NO(Fd(x)*F(y)))
def test_sympy__physics__secondquant__PermutationOperator():
from sympy.physics.secondquant import PermutationOperator
assert _test_args(PermutationOperator(0, 1))
def test_sympy__physics__secondquant__SqOperator():
from sympy.physics.secondquant import SqOperator
assert _test_args(SqOperator(0))
def test_sympy__physics__secondquant__TensorSymbol():
from sympy.physics.secondquant import TensorSymbol
assert _test_args(TensorSymbol(x))
def test_sympy__physics__control__lti__LinearTimeInvariant():
# Direct instances of LinearTimeInvariant class are not allowed.
# func(*args) tests for its derived classes (TransferFunction,
# Series, Parallel and TransferFunctionMatrix) should pass.
pass
def test_sympy__physics__control__lti__SISOLinearTimeInvariant():
# Direct instances of SISOLinearTimeInvariant class are not allowed.
pass
def test_sympy__physics__control__lti__MIMOLinearTimeInvariant():
# Direct instances of MIMOLinearTimeInvariant class are not allowed.
pass
def test_sympy__physics__control__lti__TransferFunction():
from sympy.physics.control.lti import TransferFunction
assert _test_args(TransferFunction(2, 3, x))
def test_sympy__physics__control__lti__Series():
from sympy.physics.control import Series, TransferFunction
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Series(tf1, tf2))
def test_sympy__physics__control__lti__MIMOSeries():
from sympy.physics.control import MIMOSeries, TransferFunction, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
tfm_1 = TransferFunctionMatrix([[tf2, tf1]])
tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
tfm_3 = TransferFunctionMatrix([[tf1], [tf2]])
assert _test_args(MIMOSeries(tfm_3, tfm_2, tfm_1))
def test_sympy__physics__control__lti__Parallel():
from sympy.physics.control import Parallel, TransferFunction
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Parallel(tf1, tf2))
def test_sympy__physics__control__lti__MIMOParallel():
from sympy.physics.control import MIMOParallel, TransferFunction, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
assert _test_args(MIMOParallel(tfm_1, tfm_2))
def test_sympy__physics__control__lti__Feedback():
from sympy.physics.control import TransferFunction, Feedback
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Feedback(tf1, tf2))
assert _test_args(Feedback(tf1, tf2, 1))
def test_sympy__physics__control__lti__MIMOFeedback():
from sympy.physics.control import TransferFunction, MIMOFeedback, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
assert _test_args(MIMOFeedback(tfm_1, tfm_2))
assert _test_args(MIMOFeedback(tfm_1, tfm_2, 1))
def test_sympy__physics__control__lti__TransferFunctionMatrix():
from sympy.physics.control import TransferFunction, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(TransferFunctionMatrix([[tf1, tf2]]))
def test_sympy__physics__units__dimensions__Dimension():
from sympy.physics.units.dimensions import Dimension
assert _test_args(Dimension("length", "L"))
def test_sympy__physics__units__dimensions__DimensionSystem():
from sympy.physics.units.dimensions import DimensionSystem
from sympy.physics.units.definitions.dimension_definitions import length, time, velocity
assert _test_args(DimensionSystem((length, time), (velocity,)))
def test_sympy__physics__units__quantities__Quantity():
from sympy.physics.units.quantities import Quantity
assert _test_args(Quantity("dam"))
def test_sympy__physics__units__quantities__PhysicalConstant():
from sympy.physics.units.quantities import PhysicalConstant
assert _test_args(PhysicalConstant("foo"))
def test_sympy__physics__units__prefixes__Prefix():
from sympy.physics.units.prefixes import Prefix
assert _test_args(Prefix('kilo', 'k', 3))
def test_sympy__core__numbers__AlgebraicNumber():
from sympy.core.numbers import AlgebraicNumber
assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3]))
def test_sympy__polys__polytools__GroebnerBasis():
from sympy.polys.polytools import GroebnerBasis
assert _test_args(GroebnerBasis([x, y, z], x, y, z))
def test_sympy__polys__polytools__Poly():
from sympy.polys.polytools import Poly
assert _test_args(Poly(2, x, y))
def test_sympy__polys__polytools__PurePoly():
from sympy.polys.polytools import PurePoly
assert _test_args(PurePoly(2, x, y))
@SKIP('abstract class')
def test_sympy__polys__rootoftools__RootOf():
pass
def test_sympy__polys__rootoftools__ComplexRootOf():
from sympy.polys.rootoftools import ComplexRootOf
assert _test_args(ComplexRootOf(x**3 + x + 1, 0))
def test_sympy__polys__rootoftools__RootSum():
from sympy.polys.rootoftools import RootSum
assert _test_args(RootSum(x**3 + x + 1, sin))
def test_sympy__series__limits__Limit():
from sympy.series.limits import Limit
assert _test_args(Limit(x, x, 0, dir='-'))
def test_sympy__series__order__Order():
from sympy.series.order import Order
assert _test_args(Order(1, x, y))
@SKIP('Abstract Class')
def test_sympy__series__sequences__SeqBase():
pass
def test_sympy__series__sequences__EmptySequence():
# Need to imort the instance from series not the class from
# series.sequence
from sympy.series import EmptySequence
assert _test_args(EmptySequence)
@SKIP('Abstract Class')
def test_sympy__series__sequences__SeqExpr():
pass
def test_sympy__series__sequences__SeqPer():
from sympy.series.sequences import SeqPer
assert _test_args(SeqPer((1, 2, 3), (0, 10)))
def test_sympy__series__sequences__SeqFormula():
from sympy.series.sequences import SeqFormula
assert _test_args(SeqFormula(x**2, (0, 10)))
def test_sympy__series__sequences__RecursiveSeq():
from sympy.series.sequences import RecursiveSeq
y = Function("y")
n = symbols("n")
assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, (0, 1)))
assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n))
def test_sympy__series__sequences__SeqExprOp():
from sympy.series.sequences import SeqExprOp, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqExprOp(s1, s2))
def test_sympy__series__sequences__SeqAdd():
from sympy.series.sequences import SeqAdd, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqAdd(s1, s2))
def test_sympy__series__sequences__SeqMul():
from sympy.series.sequences import SeqMul, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqMul(s1, s2))
@SKIP('Abstract Class')
def test_sympy__series__series_class__SeriesBase():
pass
def test_sympy__series__fourier__FourierSeries():
from sympy.series.fourier import fourier_series
assert _test_args(fourier_series(x, (x, -pi, pi)))
def test_sympy__series__fourier__FiniteFourierSeries():
from sympy.series.fourier import fourier_series
assert _test_args(fourier_series(sin(pi*x), (x, -1, 1)))
def test_sympy__series__formal__FormalPowerSeries():
from sympy.series.formal import fps
assert _test_args(fps(log(1 + x), x))
def test_sympy__series__formal__Coeff():
from sympy.series.formal import fps
assert _test_args(fps(x**2 + x + 1, x))
@SKIP('Abstract Class')
def test_sympy__series__formal__FiniteFormalPowerSeries():
pass
def test_sympy__series__formal__FormalPowerSeriesProduct():
from sympy.series.formal import fps
f1, f2 = fps(sin(x)), fps(exp(x))
assert _test_args(f1.product(f2, x))
def test_sympy__series__formal__FormalPowerSeriesCompose():
from sympy.series.formal import fps
f1, f2 = fps(exp(x)), fps(sin(x))
assert _test_args(f1.compose(f2, x))
def test_sympy__series__formal__FormalPowerSeriesInverse():
from sympy.series.formal import fps
f1 = fps(exp(x))
assert _test_args(f1.inverse(x))
def test_sympy__simplify__hyperexpand__Hyper_Function():
from sympy.simplify.hyperexpand import Hyper_Function
assert _test_args(Hyper_Function([2], [1]))
def test_sympy__simplify__hyperexpand__G_Function():
from sympy.simplify.hyperexpand import G_Function
assert _test_args(G_Function([2], [1], [], []))
@SKIP("abstract class")
def test_sympy__tensor__array__ndim_array__ImmutableNDimArray():
pass
def test_sympy__tensor__array__dense_ndim_array__ImmutableDenseNDimArray():
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert _test_args(densarr)
def test_sympy__tensor__array__sparse_ndim_array__ImmutableSparseNDimArray():
from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray
sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert _test_args(sparr)
def test_sympy__tensor__array__array_comprehension__ArrayComprehension():
from sympy.tensor.array.array_comprehension import ArrayComprehension
arrcom = ArrayComprehension(x, (x, 1, 5))
assert _test_args(arrcom)
def test_sympy__tensor__array__array_comprehension__ArrayComprehensionMap():
from sympy.tensor.array.array_comprehension import ArrayComprehensionMap
arrcomma = ArrayComprehensionMap(lambda: 0, (x, 1, 5))
assert _test_args(arrcomma)
def test_sympy__tensor__array__array_derivatives__ArrayDerivative():
from sympy.tensor.array.array_derivatives import ArrayDerivative
A = MatrixSymbol("A", 2, 2)
arrder = ArrayDerivative(A, A, evaluate=False)
assert _test_args(arrder)
def test_sympy__tensor__array__expressions__array_expressions__ArraySymbol():
from sympy.tensor.array.expressions.array_expressions import ArraySymbol
m, n, k = symbols("m n k")
array = ArraySymbol("A", (m, n, k, 2))
assert _test_args(array)
def test_sympy__tensor__array__expressions__array_expressions__ArrayElement():
from sympy.tensor.array.expressions.array_expressions import ArrayElement
m, n, k = symbols("m n k")
ae = ArrayElement("A", (m, n, k, 2))
assert _test_args(ae)
def test_sympy__tensor__array__expressions__array_expressions__ZeroArray():
from sympy.tensor.array.expressions.array_expressions import ZeroArray
m, n, k = symbols("m n k")
za = ZeroArray(m, n, k, 2)
assert _test_args(za)
def test_sympy__tensor__array__expressions__array_expressions__OneArray():
from sympy.tensor.array.expressions.array_expressions import OneArray
m, n, k = symbols("m n k")
za = OneArray(m, n, k, 2)
assert _test_args(za)
def test_sympy__tensor__functions__TensorProduct():
from sympy.tensor.functions import TensorProduct
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 3, 3)
tp = TensorProduct(A, B)
assert _test_args(tp)
def test_sympy__tensor__indexed__Idx():
from sympy.tensor.indexed import Idx
assert _test_args(Idx('test'))
assert _test_args(Idx('test', (0, 10)))
assert _test_args(Idx('test', 2))
assert _test_args(Idx('test', x))
def test_sympy__tensor__indexed__Indexed():
from sympy.tensor.indexed import Indexed, Idx
assert _test_args(Indexed('A', Idx('i'), Idx('j')))
def test_sympy__tensor__indexed__IndexedBase():
from sympy.tensor.indexed import IndexedBase
assert _test_args(IndexedBase('A', shape=(x, y)))
assert _test_args(IndexedBase('A', 1))
assert _test_args(IndexedBase('A')[0, 1])
def test_sympy__tensor__tensor__TensorIndexType():
from sympy.tensor.tensor import TensorIndexType
assert _test_args(TensorIndexType('Lorentz'))
@SKIP("deprecated class")
def test_sympy__tensor__tensor__TensorType():
pass
def test_sympy__tensor__tensor__TensorSymmetry():
from sympy.tensor.tensor import TensorSymmetry, get_symmetric_group_sgs
assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2)))
def test_sympy__tensor__tensor__TensorHead():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
sym = TensorSymmetry(get_symmetric_group_sgs(1))
assert _test_args(TensorHead('p', [Lorentz], sym, 0))
def test_sympy__tensor__tensor__TensorIndex():
from sympy.tensor.tensor import TensorIndexType, TensorIndex
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
assert _test_args(TensorIndex('i', Lorentz))
@SKIP("abstract class")
def test_sympy__tensor__tensor__TensExpr():
pass
def test_sympy__tensor__tensor__TensAdd():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensAdd, tensor_heads
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p, q = tensor_heads('p,q', [Lorentz], sym)
t1 = p(a)
t2 = q(a)
assert _test_args(TensAdd(t1, t2))
def test_sympy__tensor__tensor__Tensor():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensorHead
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p = TensorHead('p', [Lorentz], sym)
assert _test_args(p(a))
def test_sympy__tensor__tensor__TensMul():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, tensor_heads
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p, q = tensor_heads('p, q', [Lorentz], sym)
assert _test_args(3*p(a)*q(b))
def test_sympy__tensor__tensor__TensorElement():
from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorElement
L = TensorIndexType("L")
A = TensorHead("A", [L, L])
telem = TensorElement(A(x, y), {x: 1})
assert _test_args(telem)
def test_sympy__tensor__toperators__PartialDerivative():
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
from sympy.tensor.toperators import PartialDerivative
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
A = TensorHead("A", [Lorentz])
assert _test_args(PartialDerivative(A(a), A(b)))
def test_as_coeff_add():
assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add()
def test_sympy__geometry__curve__Curve():
from sympy.geometry.curve import Curve
assert _test_args(Curve((x, 1), (x, 0, 1)))
def test_sympy__geometry__point__Point():
from sympy.geometry.point import Point
assert _test_args(Point(0, 1))
def test_sympy__geometry__point__Point2D():
from sympy.geometry.point import Point2D
assert _test_args(Point2D(0, 1))
def test_sympy__geometry__point__Point3D():
from sympy.geometry.point import Point3D
assert _test_args(Point3D(0, 1, 2))
def test_sympy__geometry__ellipse__Ellipse():
from sympy.geometry.ellipse import Ellipse
assert _test_args(Ellipse((0, 1), 2, 3))
def test_sympy__geometry__ellipse__Circle():
from sympy.geometry.ellipse import Circle
assert _test_args(Circle((0, 1), 2))
def test_sympy__geometry__parabola__Parabola():
from sympy.geometry.parabola import Parabola
from sympy.geometry.line import Line
assert _test_args(Parabola((0, 0), Line((2, 3), (4, 3))))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity():
pass
def test_sympy__geometry__line__Line():
from sympy.geometry.line import Line
assert _test_args(Line((0, 1), (2, 3)))
def test_sympy__geometry__line__Ray():
from sympy.geometry.line import Ray
assert _test_args(Ray((0, 1), (2, 3)))
def test_sympy__geometry__line__Segment():
from sympy.geometry.line import Segment
assert _test_args(Segment((0, 1), (2, 3)))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity2D():
pass
def test_sympy__geometry__line__Line2D():
from sympy.geometry.line import Line2D
assert _test_args(Line2D((0, 1), (2, 3)))
def test_sympy__geometry__line__Ray2D():
from sympy.geometry.line import Ray2D
assert _test_args(Ray2D((0, 1), (2, 3)))
def test_sympy__geometry__line__Segment2D():
from sympy.geometry.line import Segment2D
assert _test_args(Segment2D((0, 1), (2, 3)))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity3D():
pass
def test_sympy__geometry__line__Line3D():
from sympy.geometry.line import Line3D
assert _test_args(Line3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line__Segment3D():
from sympy.geometry.line import Segment3D
assert _test_args(Segment3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line__Ray3D():
from sympy.geometry.line import Ray3D
assert _test_args(Ray3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__plane__Plane():
from sympy.geometry.plane import Plane
assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3)))
def test_sympy__geometry__polygon__Polygon():
from sympy.geometry.polygon import Polygon
assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7)))
def test_sympy__geometry__polygon__RegularPolygon():
from sympy.geometry.polygon import RegularPolygon
assert _test_args(RegularPolygon((0, 1), 2, 3, 4))
def test_sympy__geometry__polygon__Triangle():
from sympy.geometry.polygon import Triangle
assert _test_args(Triangle((0, 1), (2, 3), (4, 5)))
def test_sympy__geometry__entity__GeometryEntity():
from sympy.geometry.entity import GeometryEntity
from sympy.geometry.point import Point
assert _test_args(GeometryEntity(Point(1, 0), 1, [1, 2]))
@SKIP("abstract class")
def test_sympy__geometry__entity__GeometrySet():
pass
def test_sympy__diffgeom__diffgeom__Manifold():
from sympy.diffgeom import Manifold
assert _test_args(Manifold('name', 3))
def test_sympy__diffgeom__diffgeom__Patch():
from sympy.diffgeom import Manifold, Patch
assert _test_args(Patch('name', Manifold('name', 3)))
def test_sympy__diffgeom__diffgeom__CoordSystem():
from sympy.diffgeom import Manifold, Patch, CoordSystem
assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3))))
assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]))
def test_sympy__diffgeom__diffgeom__CoordinateSymbol():
from sympy.diffgeom import Manifold, Patch, CoordSystem, CoordinateSymbol
assert _test_args(CoordinateSymbol(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), 0))
def test_sympy__diffgeom__diffgeom__Point():
from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
assert _test_args(Point(
CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), [x, y]))
def test_sympy__diffgeom__diffgeom__BaseScalarField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseScalarField(cs, 0))
def test_sympy__diffgeom__diffgeom__BaseVectorField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseVectorField(cs, 0))
def test_sympy__diffgeom__diffgeom__Differential():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(Differential(BaseScalarField(cs, 0)))
def test_sympy__diffgeom__diffgeom__Commutator():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, Commutator
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)), [a, b, c])
v = BaseVectorField(cs, 0)
v1 = BaseVectorField(cs1, 0)
assert _test_args(Commutator(v, v1))
def test_sympy__diffgeom__diffgeom__TensorProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
assert _test_args(TensorProduct(d, d))
def test_sympy__diffgeom__diffgeom__WedgeProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
d1 = Differential(BaseScalarField(cs, 1))
assert _test_args(WedgeProduct(d, d1))
def test_sympy__diffgeom__diffgeom__LieDerivative():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivative
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
v = BaseVectorField(cs, 0)
assert _test_args(LieDerivative(v, d))
def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3))
def test_sympy__diffgeom__diffgeom__CovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
v = BaseVectorField(cs, 0)
_test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3))
def test_sympy__categories__baseclasses__Class():
from sympy.categories.baseclasses import Class
assert _test_args(Class())
def test_sympy__categories__baseclasses__Object():
from sympy.categories import Object
assert _test_args(Object("A"))
@SKIP("abstract class")
def test_sympy__categories__baseclasses__Morphism():
pass
def test_sympy__categories__baseclasses__IdentityMorphism():
from sympy.categories import Object, IdentityMorphism
assert _test_args(IdentityMorphism(Object("A")))
def test_sympy__categories__baseclasses__NamedMorphism():
from sympy.categories import Object, NamedMorphism
assert _test_args(NamedMorphism(Object("A"), Object("B"), "f"))
def test_sympy__categories__baseclasses__CompositeMorphism():
from sympy.categories import Object, NamedMorphism, CompositeMorphism
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
assert _test_args(CompositeMorphism(f, g))
def test_sympy__categories__baseclasses__Diagram():
from sympy.categories import Object, NamedMorphism, Diagram
A = Object("A")
B = Object("B")
f = NamedMorphism(A, B, "f")
d = Diagram([f])
assert _test_args(d)
def test_sympy__categories__baseclasses__Category():
from sympy.categories import Object, NamedMorphism, Diagram, Category
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
d1 = Diagram([f, g])
d2 = Diagram([f])
K = Category("K", commutative_diagrams=[d1, d2])
assert _test_args(K)
def test_sympy__ntheory__factor___totient():
from sympy.ntheory.factor_ import totient
k = symbols('k', integer=True)
t = totient(k)
assert _test_args(t)
def test_sympy__ntheory__factor___reduced_totient():
from sympy.ntheory.factor_ import reduced_totient
k = symbols('k', integer=True)
t = reduced_totient(k)
assert _test_args(t)
def test_sympy__ntheory__factor___divisor_sigma():
from sympy.ntheory.factor_ import divisor_sigma
k = symbols('k', integer=True)
n = symbols('n', integer=True)
t = divisor_sigma(n, k)
assert _test_args(t)
def test_sympy__ntheory__factor___udivisor_sigma():
from sympy.ntheory.factor_ import udivisor_sigma
k = symbols('k', integer=True)
n = symbols('n', integer=True)
t = udivisor_sigma(n, k)
assert _test_args(t)
def test_sympy__ntheory__factor___primenu():
from sympy.ntheory.factor_ import primenu
n = symbols('n', integer=True)
t = primenu(n)
assert _test_args(t)
def test_sympy__ntheory__factor___primeomega():
from sympy.ntheory.factor_ import primeomega
n = symbols('n', integer=True)
t = primeomega(n)
assert _test_args(t)
def test_sympy__ntheory__residue_ntheory__mobius():
from sympy.ntheory import mobius
assert _test_args(mobius(2))
def test_sympy__ntheory__generate__primepi():
from sympy.ntheory import primepi
n = symbols('n')
t = primepi(n)
assert _test_args(t)
def test_sympy__physics__optics__waves__TWave():
from sympy.physics.optics import TWave
A, f, phi = symbols('A, f, phi')
assert _test_args(TWave(A, f, phi))
def test_sympy__physics__optics__gaussopt__BeamParameter():
from sympy.physics.optics import BeamParameter
assert _test_args(BeamParameter(530e-9, 1, w=1e-3, n=1))
def test_sympy__physics__optics__medium__Medium():
from sympy.physics.optics import Medium
assert _test_args(Medium('m'))
def test_sympy__physics__optics__medium__MediumN():
from sympy.physics.optics.medium import Medium
assert _test_args(Medium('m', n=2))
def test_sympy__physics__optics__medium__MediumPP():
from sympy.physics.optics.medium import Medium
assert _test_args(Medium('m', permittivity=2, permeability=2))
def test_sympy__tensor__array__expressions__array_expressions__ArrayContraction():
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
from sympy.tensor.indexed import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(ArrayContraction(A, (0, 1)))
def test_sympy__tensor__array__expressions__array_expressions__ArrayDiagonal():
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
from sympy.tensor.indexed import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(ArrayDiagonal(A, (0, 1)))
def test_sympy__tensor__array__expressions__array_expressions__ArrayTensorProduct():
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
from sympy.tensor.indexed import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(ArrayTensorProduct(A, B))
def test_sympy__tensor__array__expressions__array_expressions__ArrayAdd():
from sympy.tensor.array.expressions.array_expressions import ArrayAdd
from sympy.tensor.indexed import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(ArrayAdd(A, B))
def test_sympy__tensor__array__expressions__array_expressions__PermuteDims():
from sympy.tensor.array.expressions.array_expressions import PermuteDims
A = MatrixSymbol("A", 4, 4)
assert _test_args(PermuteDims(A, (1, 0)))
def test_sympy__tensor__array__expressions__array_expressions__ArrayElementwiseApplyFunc():
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElementwiseApplyFunc
A = ArraySymbol("A", (4,))
assert _test_args(ArrayElementwiseApplyFunc(exp, A))
def test_sympy__tensor__array__expressions__array_expressions__Reshape():
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, Reshape
A = ArraySymbol("A", (4,))
assert _test_args(Reshape(A, (2, 2)))
def test_sympy__codegen__ast__Assignment():
from sympy.codegen.ast import Assignment
assert _test_args(Assignment(x, y))
def test_sympy__codegen__cfunctions__expm1():
from sympy.codegen.cfunctions import expm1
assert _test_args(expm1(x))
def test_sympy__codegen__cfunctions__log1p():
from sympy.codegen.cfunctions import log1p
assert _test_args(log1p(x))
def test_sympy__codegen__cfunctions__exp2():
from sympy.codegen.cfunctions import exp2
assert _test_args(exp2(x))
def test_sympy__codegen__cfunctions__log2():
from sympy.codegen.cfunctions import log2
assert _test_args(log2(x))
def test_sympy__codegen__cfunctions__fma():
from sympy.codegen.cfunctions import fma
assert _test_args(fma(x, y, z))
def test_sympy__codegen__cfunctions__log10():
from sympy.codegen.cfunctions import log10
assert _test_args(log10(x))
def test_sympy__codegen__cfunctions__Sqrt():
from sympy.codegen.cfunctions import Sqrt
assert _test_args(Sqrt(x))
def test_sympy__codegen__cfunctions__Cbrt():
from sympy.codegen.cfunctions import Cbrt
assert _test_args(Cbrt(x))
def test_sympy__codegen__cfunctions__hypot():
from sympy.codegen.cfunctions import hypot
assert _test_args(hypot(x, y))
def test_sympy__codegen__fnodes__FFunction():
from sympy.codegen.fnodes import FFunction
assert _test_args(FFunction('f'))
def test_sympy__codegen__fnodes__F95Function():
from sympy.codegen.fnodes import F95Function
assert _test_args(F95Function('f'))
def test_sympy__codegen__fnodes__isign():
from sympy.codegen.fnodes import isign
assert _test_args(isign(1, x))
def test_sympy__codegen__fnodes__dsign():
from sympy.codegen.fnodes import dsign
assert _test_args(dsign(1, x))
def test_sympy__codegen__fnodes__cmplx():
from sympy.codegen.fnodes import cmplx
assert _test_args(cmplx(x, y))
def test_sympy__codegen__fnodes__kind():
from sympy.codegen.fnodes import kind
assert _test_args(kind(x))
def test_sympy__codegen__fnodes__merge():
from sympy.codegen.fnodes import merge
assert _test_args(merge(1, 2, Eq(x, 0)))
def test_sympy__codegen__fnodes___literal():
from sympy.codegen.fnodes import _literal
assert _test_args(_literal(1))
def test_sympy__codegen__fnodes__literal_sp():
from sympy.codegen.fnodes import literal_sp
assert _test_args(literal_sp(1))
def test_sympy__codegen__fnodes__literal_dp():
from sympy.codegen.fnodes import literal_dp
assert _test_args(literal_dp(1))
def test_sympy__codegen__matrix_nodes__MatrixSolve():
from sympy.matrices import MatrixSymbol
from sympy.codegen.matrix_nodes import MatrixSolve
A = MatrixSymbol('A', 3, 3)
v = MatrixSymbol('x', 3, 1)
assert _test_args(MatrixSolve(A, v))
def test_sympy__vector__coordsysrect__CoordSys3D():
from sympy.vector.coordsysrect import CoordSys3D
assert _test_args(CoordSys3D('C'))
def test_sympy__vector__point__Point():
from sympy.vector.point import Point
assert _test_args(Point('P'))
def test_sympy__vector__basisdependent__BasisDependent():
#from sympy.vector.basisdependent import BasisDependent
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentMul():
#from sympy.vector.basisdependent import BasisDependentMul
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentAdd():
#from sympy.vector.basisdependent import BasisDependentAdd
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentZero():
#from sympy.vector.basisdependent import BasisDependentZero
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__vector__BaseVector():
from sympy.vector.vector import BaseVector
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseVector(0, C, ' ', ' '))
def test_sympy__vector__vector__VectorAdd():
from sympy.vector.vector import VectorAdd, VectorMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
from sympy.abc import a, b, c, x, y, z
v1 = a*C.i + b*C.j + c*C.k
v2 = x*C.i + y*C.j + z*C.k
assert _test_args(VectorAdd(v1, v2))
assert _test_args(VectorMul(x, v1))
def test_sympy__vector__vector__VectorMul():
from sympy.vector.vector import VectorMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
from sympy.abc import a
assert _test_args(VectorMul(a, C.i))
def test_sympy__vector__vector__VectorZero():
from sympy.vector.vector import VectorZero
assert _test_args(VectorZero())
def test_sympy__vector__vector__Vector():
#from sympy.vector.vector import Vector
#Vector is never to be initialized using args
pass
def test_sympy__vector__vector__Cross():
from sympy.vector.vector import Cross
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
_test_args(Cross(C.i, C.j))
def test_sympy__vector__vector__Dot():
from sympy.vector.vector import Dot
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
_test_args(Dot(C.i, C.j))
def test_sympy__vector__dyadic__Dyadic():
#from sympy.vector.dyadic import Dyadic
#Dyadic is never to be initialized using args
pass
def test_sympy__vector__dyadic__BaseDyadic():
from sympy.vector.dyadic import BaseDyadic
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseDyadic(C.i, C.j))
def test_sympy__vector__dyadic__DyadicMul():
from sympy.vector.dyadic import BaseDyadic, DyadicMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicAdd():
from sympy.vector.dyadic import BaseDyadic, DyadicAdd
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i),
BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicZero():
from sympy.vector.dyadic import DyadicZero
assert _test_args(DyadicZero())
def test_sympy__vector__deloperator__Del():
from sympy.vector.deloperator import Del
assert _test_args(Del())
def test_sympy__vector__implicitregion__ImplicitRegion():
from sympy.vector.implicitregion import ImplicitRegion
from sympy.abc import x, y
assert _test_args(ImplicitRegion((x, y), y**3 - 4*x))
def test_sympy__vector__integrals__ParametricIntegral():
from sympy.vector.integrals import ParametricIntegral
from sympy.vector.parametricregion import ParametricRegion
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(ParametricIntegral(C.y*C.i - 10*C.j,\
ParametricRegion((x, y), (x, 1, 3), (y, -2, 2))))
def test_sympy__vector__operators__Curl():
from sympy.vector.operators import Curl
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Curl(C.i))
def test_sympy__vector__operators__Laplacian():
from sympy.vector.operators import Laplacian
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Laplacian(C.i))
def test_sympy__vector__operators__Divergence():
from sympy.vector.operators import Divergence
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Divergence(C.i))
def test_sympy__vector__operators__Gradient():
from sympy.vector.operators import Gradient
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Gradient(C.x))
def test_sympy__vector__orienters__Orienter():
#from sympy.vector.orienters import Orienter
#Not to be initialized
pass
def test_sympy__vector__orienters__ThreeAngleOrienter():
#from sympy.vector.orienters import ThreeAngleOrienter
#Not to be initialized
pass
def test_sympy__vector__orienters__AxisOrienter():
from sympy.vector.orienters import AxisOrienter
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(AxisOrienter(x, C.i))
def test_sympy__vector__orienters__BodyOrienter():
from sympy.vector.orienters import BodyOrienter
assert _test_args(BodyOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__SpaceOrienter():
from sympy.vector.orienters import SpaceOrienter
assert _test_args(SpaceOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__QuaternionOrienter():
from sympy.vector.orienters import QuaternionOrienter
a, b, c, d = symbols('a b c d')
assert _test_args(QuaternionOrienter(a, b, c, d))
def test_sympy__vector__parametricregion__ParametricRegion():
from sympy.abc import t
from sympy.vector.parametricregion import ParametricRegion
assert _test_args(ParametricRegion((t, t**3), (t, 0, 2)))
def test_sympy__vector__scalar__BaseScalar():
from sympy.vector.scalar import BaseScalar
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseScalar(0, C, ' ', ' '))
def test_sympy__physics__wigner__Wigner3j():
from sympy.physics.wigner import Wigner3j
assert _test_args(Wigner3j(0, 0, 0, 0, 0, 0))
def test_sympy__integrals__rubi__symbol__matchpyWC():
from sympy.integrals.rubi.symbol import matchpyWC
assert _test_args(matchpyWC(1, True, 'a'))
def test_sympy__integrals__rubi__utility_function__rubi_unevaluated_expr():
from sympy.integrals.rubi.utility_function import rubi_unevaluated_expr
a = symbols('a')
assert _test_args(rubi_unevaluated_expr(a))
def test_sympy__integrals__rubi__utility_function__rubi_exp():
from sympy.integrals.rubi.utility_function import rubi_exp
assert _test_args(rubi_exp(5))
def test_sympy__integrals__rubi__utility_function__rubi_log():
from sympy.integrals.rubi.utility_function import rubi_log
assert _test_args(rubi_log(5))
def test_sympy__integrals__rubi__utility_function__Int():
from sympy.integrals.rubi.utility_function import Int
assert _test_args(Int(5, x))
def test_sympy__integrals__rubi__utility_function__Util_Coefficient():
from sympy.integrals.rubi.utility_function import Util_Coefficient
a, x = symbols('a x')
assert _test_args(Util_Coefficient(a, x))
def test_sympy__integrals__rubi__utility_function__Gamma():
from sympy.integrals.rubi.utility_function import Gamma
assert _test_args(Gamma(x))
def test_sympy__integrals__rubi__utility_function__Util_Part():
from sympy.integrals.rubi.utility_function import Util_Part
a, b = symbols('a b')
assert _test_args(Util_Part(a + b, 0))
def test_sympy__integrals__rubi__utility_function__PolyGamma():
from sympy.integrals.rubi.utility_function import PolyGamma
assert _test_args(PolyGamma(1, x))
def test_sympy__integrals__rubi__utility_function__ProductLog():
from sympy.integrals.rubi.utility_function import ProductLog
assert _test_args(ProductLog(1))
def test_sympy__combinatorics__schur_number__SchurNumber():
from sympy.combinatorics.schur_number import SchurNumber
assert _test_args(SchurNumber(x))
def test_sympy__combinatorics__perm_groups__SymmetricPermutationGroup():
from sympy.combinatorics.perm_groups import SymmetricPermutationGroup
assert _test_args(SymmetricPermutationGroup(5))
def test_sympy__combinatorics__perm_groups__Coset():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup, Coset
a = Permutation(1, 2)
b = Permutation(0, 1)
G = PermutationGroup([a, b])
assert _test_args(Coset(a, G))
|
c0999faedac017ff82b3a4e0d3ac69893b6923259aae175a820c32eb13d1191e | import numbers as nums
import decimal
from sympy.concrete.summations import Sum
from sympy.core import (EulerGamma, Catalan, TribonacciConstant,
GoldenRatio)
from sympy.core.containers import Tuple
from sympy.core.expr import unchanged
from sympy.core.logic import fuzzy_not
from sympy.core.mul import Mul
from sympy.core.numbers import (mpf_norm, mod_inverse, igcd, seterr,
igcd_lehmer, Integer, I, pi, comp, ilcm, Rational, E, nan, igcd2,
oo, AlgebraicNumber, igcdex, Number, Float, zoo)
from sympy.core.power import Pow
from sympy.core.relational import Ge, Gt, Le, Lt
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.combinatorial.numbers import fibonacci
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.miscellaneous import sqrt, cbrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.polys.domains.realfield import RealField
from sympy.printing.latex import latex
from sympy.printing.repr import srepr
from sympy.simplify import simplify
from sympy.core.power import integer_nthroot, isqrt, integer_log
from sympy.polys.domains.groundtypes import PythonRational
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.utilities.iterables import permutations
from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
from mpmath import mpf
from mpmath.rational import mpq
import mpmath
from sympy.core import numbers
t = Symbol('t', real=False)
_ninf = float(-oo)
_inf = float(oo)
def same_and_same_prec(a, b):
# stricter matching for Floats
return a == b and a._prec == b._prec
def test_seterr():
seterr(divide=True)
raises(ValueError, lambda: S.Zero/S.Zero)
seterr(divide=False)
assert S.Zero / S.Zero is S.NaN
def test_mod():
x = S.Half
y = Rational(3, 4)
z = Rational(5, 18043)
assert x % x == 0
assert x % y == S.Half
assert x % z == Rational(3, 36086)
assert y % x == Rational(1, 4)
assert y % y == 0
assert y % z == Rational(9, 72172)
assert z % x == Rational(5, 18043)
assert z % y == Rational(5, 18043)
assert z % z == 0
a = Float(2.6)
assert (a % .2) == 0.0
assert (a % 2).round(15) == 0.6
assert (a % 0.5).round(15) == 0.1
p = Symbol('p', infinite=True)
assert oo % oo is nan
assert zoo % oo is nan
assert 5 % oo is nan
assert p % 5 is nan
# In these two tests, if the precision of m does
# not match the precision of the ans, then it is
# likely that the change made now gives an answer
# with degraded accuracy.
r = Rational(500, 41)
f = Float('.36', 3)
m = r % f
ans = Float(r % Rational(f), 3)
assert m == ans and m._prec == ans._prec
f = Float('8.36', 3)
m = f % r
ans = Float(Rational(f) % r, 3)
assert m == ans and m._prec == ans._prec
s = S.Zero
assert s % float(1) == 0.0
# No rounding required since these numbers can be represented
# exactly.
assert Rational(3, 4) % Float(1.1) == 0.75
assert Float(1.5) % Rational(5, 4) == 0.25
assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25
assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25')
assert 2.75 % Float('1.5') == Float('1.25')
a = Integer(7)
b = Integer(4)
assert type(a % b) == Integer
assert a % b == Integer(3)
assert Integer(1) % Rational(2, 3) == Rational(1, 3)
assert Rational(7, 5) % Integer(1) == Rational(2, 5)
assert Integer(2) % 1.5 == 0.5
assert Integer(3).__rmod__(Integer(10)) == Integer(1)
assert Integer(10) % 4 == Integer(2)
assert 15 % Integer(4) == Integer(3)
def test_divmod():
assert divmod(S(12), S(8)) == Tuple(1, 4)
assert divmod(-S(12), S(8)) == Tuple(-2, 4)
assert divmod(S.Zero, S.One) == Tuple(0, 0)
raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero))
raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero))
assert divmod(S(12), 8) == Tuple(1, 4)
assert divmod(12, S(8)) == Tuple(1, 4)
assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2"))
assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2"))
assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2"))
assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5"))
assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0"))
assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3"))
assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0"))
assert divmod(S("2"), S(".1"))[0] == 19
assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1"))
assert divmod(S("2"), 2) == Tuple(S("1"), S("0"))
assert divmod(2, S("2")) == Tuple(S("1"), S("0"))
assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5"))
assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5"))
assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3"))
assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2"))
assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5"))
assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6"))
assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3"))
assert divmod(S("3/2"), S("0.1"))[0] == 14
assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1"))
assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2"))
assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2"))
assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0"))
assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0"))
assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0"))
assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3"))
assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3"))
assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0"))
assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1"))
assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5"))
assert divmod(2, S("3.5")) == Tuple(S("0"), S("2"))
assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5"))
assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5"))
assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3"))
assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1"))
assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3"))
assert divmod(2, S("1/3")) == Tuple(S("6"), S("0"))
assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3"))
assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3"))
assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1"))
assert divmod(2, S("0.1"))[0] == 19
assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1"))
assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0"))
assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1"))
assert str(divmod(S("2"), 0.3)) == '(6, 0.2)'
assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)'
assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)'
assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)'
assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)'
assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)'
assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)'
assert divmod(-3, S(2)) == (-2, 1)
assert divmod(S(-3), S(2)) == (-2, 1)
assert divmod(S(-3), 2) == (-2, 1)
assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2)
assert divmod(S(4), S(-2.1)) == divmod(4, -2.1)
assert divmod(S(-8), S(-2.5) ) == Tuple(3, -0.5)
assert divmod(oo, 1) == (S.NaN, S.NaN)
assert divmod(S.NaN, 1) == (S.NaN, S.NaN)
assert divmod(1, S.NaN) == (S.NaN, S.NaN)
ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)]
OO = float('inf')
ANS = [tuple(map(float, i)) for i in ans]
assert [divmod(i, oo) for i in range(-2, 3)] == ans
ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)]
ANS = [tuple(map(float, i)) for i in ans]
assert [divmod(i, -oo) for i in range(-2, 3)] == ans
assert [divmod(i, -OO) for i in range(-2, 3)] == ANS
assert divmod(S(3.5), S(-2)) == divmod(3.5, -2)
assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2)
assert divmod(S(0.0), S(9)) == divmod(0.0, 9)
assert divmod(S(0), S(9.0)) == divmod(0, 9.0)
def test_igcd():
assert igcd(0, 0) == 0
assert igcd(0, 1) == 1
assert igcd(1, 0) == 1
assert igcd(0, 7) == 7
assert igcd(7, 0) == 7
assert igcd(7, 1) == 1
assert igcd(1, 7) == 1
assert igcd(-1, 0) == 1
assert igcd(0, -1) == 1
assert igcd(-1, -1) == 1
assert igcd(-1, 7) == 1
assert igcd(7, -1) == 1
assert igcd(8, 2) == 2
assert igcd(4, 8) == 4
assert igcd(8, 16) == 8
assert igcd(7, -3) == 1
assert igcd(-7, 3) == 1
assert igcd(-7, -3) == 1
assert igcd(*[10, 20, 30]) == 10
raises(TypeError, lambda: igcd())
raises(TypeError, lambda: igcd(2))
raises(ValueError, lambda: igcd(0, None))
raises(ValueError, lambda: igcd(1, 2.2))
for args in permutations((45.1, 1, 30)):
raises(ValueError, lambda: igcd(*args))
for args in permutations((1, 2, None)):
raises(ValueError, lambda: igcd(*args))
def test_igcd_lehmer():
a, b = fibonacci(10001), fibonacci(10000)
# len(str(a)) == 2090
# small divisors, long Euclidean sequence
assert igcd_lehmer(a, b) == 1
c = fibonacci(100)
assert igcd_lehmer(a*c, b*c) == c
# big divisor
assert igcd_lehmer(a, 10**1000) == 1
# swapping argmument
assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1)
def test_igcd2():
# short loop
assert igcd2(2**100 - 1, 2**99 - 1) == 1
# Lehmer's algorithm
a, b = int(fibonacci(10001)), int(fibonacci(10000))
assert igcd2(a, b) == 1
def test_ilcm():
assert ilcm(0, 0) == 0
assert ilcm(1, 0) == 0
assert ilcm(0, 1) == 0
assert ilcm(1, 1) == 1
assert ilcm(2, 1) == 2
assert ilcm(8, 2) == 8
assert ilcm(8, 6) == 24
assert ilcm(8, 7) == 56
assert ilcm(*[10, 20, 30]) == 60
raises(ValueError, lambda: ilcm(8.1, 7))
raises(ValueError, lambda: ilcm(8, 7.1))
raises(TypeError, lambda: ilcm(8))
def test_igcdex():
assert igcdex(2, 3) == (-1, 1, 1)
assert igcdex(10, 12) == (-1, 1, 2)
assert igcdex(100, 2004) == (-20, 1, 4)
assert igcdex(0, 0) == (0, 1, 0)
assert igcdex(1, 0) == (1, 0, 1)
def _strictly_equal(a, b):
return (a.p, a.q, type(a.p), type(a.q)) == \
(b.p, b.q, type(b.p), type(b.q))
def _test_rational_new(cls):
"""
Tests that are common between Integer and Rational.
"""
assert cls(0) is S.Zero
assert cls(1) is S.One
assert cls(-1) is S.NegativeOne
# These look odd, but are similar to int():
assert cls('1') is S.One
assert cls('-1') is S.NegativeOne
i = Integer(10)
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls(int(10)))
assert _strictly_equal(i, cls(i))
raises(TypeError, lambda: cls(Symbol('x')))
def test_Integer_new():
"""
Test for Integer constructor
"""
_test_rational_new(Integer)
assert _strictly_equal(Integer(0.9), S.Zero)
assert _strictly_equal(Integer(10.5), Integer(10))
raises(ValueError, lambda: Integer("10.5"))
assert Integer(Rational('1.' + '9'*20)) == 1
def test_Rational_new():
""""
Test for Rational constructor
"""
_test_rational_new(Rational)
n1 = S.Half
assert n1 == Rational(Integer(1), 2)
assert n1 == Rational(Integer(1), Integer(2))
assert n1 == Rational(1, Integer(2))
assert n1 == Rational(S.Half)
assert 1 == Rational(n1, n1)
assert Rational(3, 2) == Rational(S.Half, Rational(1, 3))
assert Rational(3, 1) == Rational(1, Rational(1, 3))
n3_4 = Rational(3, 4)
assert Rational('3/4') == n3_4
assert -Rational('-3/4') == n3_4
assert Rational('.76').limit_denominator(4) == n3_4
assert Rational(19, 25).limit_denominator(4) == n3_4
assert Rational('19/25').limit_denominator(4) == n3_4
assert Rational(1.0, 3) == Rational(1, 3)
assert Rational(1, 3.0) == Rational(1, 3)
assert Rational(Float(0.5)) == S.Half
assert Rational('1e2/1e-2') == Rational(10000)
assert Rational('1 234') == Rational(1234)
assert Rational('1/1 234') == Rational(1, 1234)
assert Rational(-1, 0) is S.ComplexInfinity
assert Rational(1, 0) is S.ComplexInfinity
# Make sure Rational doesn't lose precision on Floats
assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100)
raises(TypeError, lambda: Rational('3**3'))
raises(TypeError, lambda: Rational('1/2 + 2/3'))
# handle fractions.Fraction instances
try:
import fractions
assert Rational(fractions.Fraction(1, 2)) == S.Half
except ImportError:
pass
assert Rational(mpq(2, 6)) == Rational(1, 3)
assert Rational(PythonRational(2, 6)) == Rational(1, 3)
assert Rational(2, 4, gcd=1).q == 4
n = Rational(2, -4, gcd=1)
assert n.q == 4
assert n.p == -2
def test_Number_new():
""""
Test for Number constructor
"""
# Expected behavior on numbers and strings
assert Number(1) is S.One
assert Number(2).__class__ is Integer
assert Number(-622).__class__ is Integer
assert Number(5, 3).__class__ is Rational
assert Number(5.3).__class__ is Float
assert Number('1') is S.One
assert Number('2').__class__ is Integer
assert Number('-622').__class__ is Integer
assert Number('5/3').__class__ is Rational
assert Number('5.3').__class__ is Float
raises(ValueError, lambda: Number('cos'))
raises(TypeError, lambda: Number(cos))
a = Rational(3, 5)
assert Number(a) is a # Check idempotence on Numbers
u = ['inf', '-inf', 'nan', 'iNF', '+inf']
v = [oo, -oo, nan, oo, oo]
for i, a in zip(u, v):
assert Number(i) is a, (i, Number(i), a)
def test_Number_cmp():
n1 = Number(1)
n2 = Number(2)
n3 = Number(-3)
assert n1 < n2
assert n1 <= n2
assert n3 < n1
assert n2 > n3
assert n2 >= n3
raises(TypeError, lambda: n1 < S.NaN)
raises(TypeError, lambda: n1 <= S.NaN)
raises(TypeError, lambda: n1 > S.NaN)
raises(TypeError, lambda: n1 >= S.NaN)
def test_Rational_cmp():
n1 = Rational(1, 4)
n2 = Rational(1, 3)
n3 = Rational(2, 4)
n4 = Rational(2, -4)
n5 = Rational(0)
n6 = Rational(1)
n7 = Rational(3)
n8 = Rational(-3)
assert n8 < n5
assert n5 < n6
assert n6 < n7
assert n8 < n7
assert n7 > n8
assert (n1 + 1)**n2 < 2
assert ((n1 + n6)/n7) < 1
assert n4 < n3
assert n2 < n3
assert n1 < n2
assert n3 > n1
assert not n3 < n1
assert not (Rational(-1) > 0)
assert Rational(-1) < 0
raises(TypeError, lambda: n1 < S.NaN)
raises(TypeError, lambda: n1 <= S.NaN)
raises(TypeError, lambda: n1 > S.NaN)
raises(TypeError, lambda: n1 >= S.NaN)
def test_Float():
def eq(a, b):
t = Float("1.0E-15")
return (-t < a - b < t)
zeros = (0, S.Zero, 0., Float(0))
for i, j in permutations(zeros, 2):
assert i == j
for z in zeros:
assert z in zeros
assert S.Zero.is_zero
a = Float(2) ** Float(3)
assert eq(a.evalf(), Float(8))
assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
a = Float(2) ** Float(4)
assert eq(a.evalf(), Float(16))
assert (S(.3) == S(.5)) is False
mpf = (0, 5404319552844595, -52, 53)
x_str = Float((0, '13333333333333', -52, 53))
x_0xstr = Float((0, '0x13333333333333', -52, 53))
x2_str = Float((0, '26666666666666', -53, 54))
x_hex = Float((0, int(0x13333333333333), -52, 53))
x_dec = Float(mpf)
assert x_str == x_0xstr == x_hex == x_dec == Float(1.2)
# x2_str was entered slightly malformed in that the mantissa
# was even -- it should be odd and the even part should be
# included with the exponent, but this is resolved by normalization
# ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must
# be exact: double the mantissa ==> increase bc by 1
assert Float(1.2)._mpf_ == mpf
assert x2_str._mpf_ == mpf
assert Float((0, int(0), -123, -1)) is S.NaN
assert Float((0, int(0), -456, -2)) is S.Infinity
assert Float((1, int(0), -789, -3)) is S.NegativeInfinity
# if you don't give the full signature, it's not special
assert Float((0, int(0), -123)) == Float(0)
assert Float((0, int(0), -456)) == Float(0)
assert Float((1, int(0), -789)) == Float(0)
raises(ValueError, lambda: Float((0, 7, 1, 3), ''))
assert Float('0.0').is_finite is True
assert Float('0.0').is_negative is False
assert Float('0.0').is_positive is False
assert Float('0.0').is_infinite is False
assert Float('0.0').is_zero is True
# rationality properties
# if the integer test fails then the use of intlike
# should be removed from gamma_functions.py
assert Float(1).is_integer is False
assert Float(1).is_rational is None
assert Float(1).is_irrational is None
assert sqrt(2).n(15).is_rational is None
assert sqrt(2).n(15).is_irrational is None
# do not automatically evalf
def teq(a):
assert (a.evalf() == a) is False
assert (a.evalf() != a) is True
assert (a == a.evalf()) is False
assert (a != a.evalf()) is True
teq(pi)
teq(2*pi)
teq(cos(0.1, evaluate=False))
# long integer
i = 12345678901234567890
assert same_and_same_prec(Float(12, ''), Float('12', ''))
assert same_and_same_prec(Float(Integer(i), ''), Float(i, ''))
assert same_and_same_prec(Float(i, ''), Float(str(i), 20))
assert same_and_same_prec(Float(str(i)), Float(i, ''))
assert same_and_same_prec(Float(i), Float(i, ''))
# inexact floats (repeating binary = denom not multiple of 2)
# cannot have precision greater than 15
assert Float(.125, 22) == .125
assert Float(2.0, 22) == 2
assert float(Float('.12500000000000001', '')) == .125
raises(ValueError, lambda: Float(.12500000000000001, ''))
# allow spaces
assert Float('123 456.123 456') == Float('123456.123456')
assert Integer('123 456') == Integer('123456')
assert Rational('123 456.123 456') == Rational('123456.123456')
assert Float(' .3e2') == Float('0.3e2')
# allow underscore
assert Float('1_23.4_56') == Float('123.456')
assert Float('1_') == Float('1.0')
assert Float('1_.') == Float('1.0')
assert Float('1._') == Float('1.0')
assert Float('1__2') == Float('12.0')
# assert Float('1_23.4_5_6', 12) == Float('123.456', 12)
# ...but not in all cases (per Py 3.6)
raises(ValueError, lambda: Float('_1'))
raises(ValueError, lambda: Float('_inf'))
# allow auto precision detection
assert Float('.1', '') == Float(.1, 1)
assert Float('.125', '') == Float(.125, 3)
assert Float('.100', '') == Float(.1, 3)
assert Float('2.0', '') == Float('2', 2)
raises(ValueError, lambda: Float("12.3d-4", ""))
raises(ValueError, lambda: Float(12.3, ""))
raises(ValueError, lambda: Float('.'))
raises(ValueError, lambda: Float('-.'))
zero = Float('0.0')
assert Float('-0') == zero
assert Float('.0') == zero
assert Float('-.0') == zero
assert Float('-0.0') == zero
assert Float(0.0) == zero
assert Float(0) == zero
assert Float(0, '') == Float('0', '')
assert Float(1) == Float(1.0)
assert Float(S.Zero) == zero
assert Float(S.One) == Float(1.0)
assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3)
assert Float(decimal.Decimal('nan')) is S.NaN
assert Float(decimal.Decimal('Infinity')) is S.Infinity
assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity
assert '{:.3f}'.format(Float(4.236622)) == '4.237'
assert '{:.35f}'.format(Float(pi.n(40), 40)) == \
'3.14159265358979323846264338327950288'
# unicode
assert Float('0.73908513321516064100000000') == \
Float('0.73908513321516064100000000')
assert Float('0.73908513321516064100000000', 28) == \
Float('0.73908513321516064100000000', 28)
# binary precision
# Decimal value 0.1 cannot be expressed precisely as a base 2 fraction
a = Float(S.One/10, dps=15)
b = Float(S.One/10, dps=16)
p = Float(S.One/10, precision=53)
q = Float(S.One/10, precision=54)
assert a._mpf_ == p._mpf_
assert not a._mpf_ == q._mpf_
assert not b._mpf_ == q._mpf_
# Precision specifying errors
raises(ValueError, lambda: Float("1.23", dps=3, precision=10))
raises(ValueError, lambda: Float("1.23", dps="", precision=10))
raises(ValueError, lambda: Float("1.23", dps=3, precision=""))
raises(ValueError, lambda: Float("1.23", dps="", precision=""))
# from NumberSymbol
assert same_and_same_prec(Float(pi, 32), pi.evalf(32))
assert same_and_same_prec(Float(Catalan), Catalan.evalf())
# oo and nan
u = ['inf', '-inf', 'nan', 'iNF', '+inf']
v = [oo, -oo, nan, oo, oo]
for i, a in zip(u, v):
assert Float(i) is a
def test_zero_not_false():
# https://github.com/sympy/sympy/issues/20796
assert (S(0.0) == S.false) is False
assert (S.false == S(0.0)) is False
assert (S(0) == S.false) is False
assert (S.false == S(0)) is False
@conserve_mpmath_dps
def test_float_mpf():
import mpmath
mpmath.mp.dps = 100
mp_pi = mpmath.pi()
assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
mpmath.mp.dps = 15
assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
def test_Float_RealElement():
repi = RealField(dps=100)(pi.evalf(100))
# We still have to pass the precision because Float doesn't know what
# RealElement is, but make sure it keeps full precision from the result.
assert Float(repi, 100) == pi.evalf(100)
def test_Float_default_to_highprec_from_str():
s = str(pi.evalf(128))
assert same_and_same_prec(Float(s), Float(s, ''))
def test_Float_eval():
a = Float(3.2)
assert (a**2).is_Float
def test_Float_issue_2107():
a = Float(0.1, 10)
b = Float("0.1", 10)
assert a - a == 0
assert a + (-a) == 0
assert S.Zero + a - a == 0
assert S.Zero + a + (-a) == 0
assert b - b == 0
assert b + (-b) == 0
assert S.Zero + b - b == 0
assert S.Zero + b + (-b) == 0
def test_issue_14289():
from sympy.polys.numberfields import to_number_field
a = 1 - sqrt(2)
b = to_number_field(a)
assert b.as_expr() == a
assert b.minpoly(a).expand() == 0
def test_Float_from_tuple():
a = Float((0, '1L', 0, 1))
b = Float((0, '1', 0, 1))
assert a == b
def test_Infinity():
assert oo != 1
assert 1*oo is oo
assert 1 != oo
assert oo != -oo
assert oo != Symbol("x")**3
assert oo + 1 is oo
assert 2 + oo is oo
assert 3*oo + 2 is oo
assert S.Half**oo == 0
assert S.Half**(-oo) is oo
assert -oo*3 is -oo
assert oo + oo is oo
assert -oo + oo*(-5) is -oo
assert 1/oo == 0
assert 1/(-oo) == 0
assert 8/oo == 0
assert oo % 2 is nan
assert 2 % oo is nan
assert oo/oo is nan
assert oo/-oo is nan
assert -oo/oo is nan
assert -oo/-oo is nan
assert oo - oo is nan
assert oo - -oo is oo
assert -oo - oo is -oo
assert -oo - -oo is nan
assert oo + -oo is nan
assert -oo + oo is nan
assert oo + oo is oo
assert -oo + oo is nan
assert oo + -oo is nan
assert -oo + -oo is -oo
assert oo*oo is oo
assert -oo*oo is -oo
assert oo*-oo is -oo
assert -oo*-oo is oo
assert oo/0 is oo
assert -oo/0 is -oo
assert 0/oo == 0
assert 0/-oo == 0
assert oo*0 is nan
assert -oo*0 is nan
assert 0*oo is nan
assert 0*-oo is nan
assert oo + 0 is oo
assert -oo + 0 is -oo
assert 0 + oo is oo
assert 0 + -oo is -oo
assert oo - 0 is oo
assert -oo - 0 is -oo
assert 0 - oo is -oo
assert 0 - -oo is oo
assert oo/2 is oo
assert -oo/2 is -oo
assert oo/-2 is -oo
assert -oo/-2 is oo
assert oo*2 is oo
assert -oo*2 is -oo
assert oo*-2 is -oo
assert 2/oo == 0
assert 2/-oo == 0
assert -2/oo == 0
assert -2/-oo == 0
assert 2*oo is oo
assert 2*-oo is -oo
assert -2*oo is -oo
assert -2*-oo is oo
assert 2 + oo is oo
assert 2 - oo is -oo
assert -2 + oo is oo
assert -2 - oo is -oo
assert 2 + -oo is -oo
assert 2 - -oo is oo
assert -2 + -oo is -oo
assert -2 - -oo is oo
assert S(2) + oo is oo
assert S(2) - oo is -oo
assert oo/I == -oo*I
assert -oo/I == oo*I
assert oo*float(1) == _inf and (oo*float(1)) is oo
assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo
assert oo/float(1) == _inf and (oo/float(1)) is oo
assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo
assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo
assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo
assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo
assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo
assert oo + float(1) == _inf and (oo + float(1)) is oo
assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo
assert oo - float(1) == _inf and (oo - float(1)) is oo
assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo
assert float(1)*oo == _inf and (float(1)*oo) is oo
assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo
assert float(1)/oo == 0
assert float(1)/-oo == 0
assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo
assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo
assert float(-1)/oo == 0
assert float(-1)/-oo == 0
assert float(1) + oo is oo
assert float(1) + -oo is -oo
assert float(1) - oo is -oo
assert float(1) - -oo is oo
assert oo == float(oo)
assert (oo != float(oo)) is False
assert type(float(oo)) is float
assert -oo == float(-oo)
assert (-oo != float(-oo)) is False
assert type(float(-oo)) is float
assert Float('nan') is nan
assert nan*1.0 is nan
assert -1.0*nan is nan
assert nan*oo is nan
assert nan*-oo is nan
assert nan/oo is nan
assert nan/-oo is nan
assert nan + oo is nan
assert nan + -oo is nan
assert nan - oo is nan
assert nan - -oo is nan
assert -oo * S.Zero is nan
assert oo*nan is nan
assert -oo*nan is nan
assert oo/nan is nan
assert -oo/nan is nan
assert oo + nan is nan
assert -oo + nan is nan
assert oo - nan is nan
assert -oo - nan is nan
assert S.Zero * oo is nan
assert oo.is_Rational is False
assert isinstance(oo, Rational) is False
assert S.One/oo == 0
assert -S.One/oo == 0
assert S.One/-oo == 0
assert -S.One/-oo == 0
assert S.One*oo is oo
assert -S.One*oo is -oo
assert S.One*-oo is -oo
assert -S.One*-oo is oo
assert S.One/nan is nan
assert S.One - -oo is oo
assert S.One + nan is nan
assert S.One - nan is nan
assert nan - S.One is nan
assert nan/S.One is nan
assert -oo - S.One is -oo
def test_Infinity_2():
x = Symbol('x')
assert oo*x != oo
assert oo*(pi - 1) is oo
assert oo*(1 - pi) is -oo
assert (-oo)*x != -oo
assert (-oo)*(pi - 1) is -oo
assert (-oo)*(1 - pi) is oo
assert (-1)**S.NaN is S.NaN
assert oo - _inf is S.NaN
assert oo + _ninf is S.NaN
assert oo*0 is S.NaN
assert oo/_inf is S.NaN
assert oo/_ninf is S.NaN
assert oo**S.NaN is S.NaN
assert -oo + _inf is S.NaN
assert -oo - _ninf is S.NaN
assert -oo*S.NaN is S.NaN
assert -oo*0 is S.NaN
assert -oo/_inf is S.NaN
assert -oo/_ninf is S.NaN
assert -oo/S.NaN is S.NaN
assert abs(-oo) is oo
assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN))
assert (-oo)**3 is -oo
assert (-oo)**2 is oo
assert abs(S.ComplexInfinity) is oo
def test_Mul_Infinity_Zero():
assert Float(0)*_inf is nan
assert Float(0)*_ninf is nan
assert Float(0)*_inf is nan
assert Float(0)*_ninf is nan
assert _inf*Float(0) is nan
assert _ninf*Float(0) is nan
assert _inf*Float(0) is nan
assert _ninf*Float(0) is nan
def test_Div_By_Zero():
assert 1/S.Zero is zoo
assert 1/Float(0) is zoo
assert 0/S.Zero is nan
assert 0/Float(0) is nan
assert S.Zero/0 is nan
assert Float(0)/0 is nan
assert -1/S.Zero is zoo
assert -1/Float(0) is zoo
@_both_exp_pow
def test_Infinity_inequations():
assert oo > pi
assert not (oo < pi)
assert exp(-3) < oo
assert _inf > pi
assert not (_inf < pi)
assert exp(-3) < _inf
raises(TypeError, lambda: oo < I)
raises(TypeError, lambda: oo <= I)
raises(TypeError, lambda: oo > I)
raises(TypeError, lambda: oo >= I)
raises(TypeError, lambda: -oo < I)
raises(TypeError, lambda: -oo <= I)
raises(TypeError, lambda: -oo > I)
raises(TypeError, lambda: -oo >= I)
raises(TypeError, lambda: I < oo)
raises(TypeError, lambda: I <= oo)
raises(TypeError, lambda: I > oo)
raises(TypeError, lambda: I >= oo)
raises(TypeError, lambda: I < -oo)
raises(TypeError, lambda: I <= -oo)
raises(TypeError, lambda: I > -oo)
raises(TypeError, lambda: I >= -oo)
assert oo > -oo and oo >= -oo
assert (oo < -oo) == False and (oo <= -oo) == False
assert -oo < oo and -oo <= oo
assert (-oo > oo) == False and (-oo >= oo) == False
assert (oo < oo) == False # issue 7775
assert (oo > oo) == False
assert (-oo > -oo) == False and (-oo < -oo) == False
assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo
assert (-oo < -_inf) == False
assert (oo > _inf) == False
assert -oo >= -_inf
assert oo <= _inf
x = Symbol('x')
b = Symbol('b', finite=True, real=True)
assert (x < oo) == Lt(x, oo) # issue 7775
assert b < oo and b > -oo and b <= oo and b >= -oo
assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False
assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b
assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x)
assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x)
assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x)
assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x)
def test_NaN():
assert nan is nan
assert nan != 1
assert 1*nan is nan
assert 1 != nan
assert -nan is nan
assert oo != Symbol("x")**3
assert 2 + nan is nan
assert 3*nan + 2 is nan
assert -nan*3 is nan
assert nan + nan is nan
assert -nan + nan*(-5) is nan
assert 8/nan is nan
raises(TypeError, lambda: nan > 0)
raises(TypeError, lambda: nan < 0)
raises(TypeError, lambda: nan >= 0)
raises(TypeError, lambda: nan <= 0)
raises(TypeError, lambda: 0 < nan)
raises(TypeError, lambda: 0 > nan)
raises(TypeError, lambda: 0 <= nan)
raises(TypeError, lambda: 0 >= nan)
assert nan**0 == 1 # as per IEEE 754
assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work
# test Pow._eval_power's handling of NaN
assert Pow(nan, 0, evaluate=False)**2 == 1
for n in (1, 1., S.One, S.NegativeOne, Float(1)):
assert n + nan is nan
assert n - nan is nan
assert nan + n is nan
assert nan - n is nan
assert n/nan is nan
assert nan/n is nan
def test_special_numbers():
assert isinstance(S.NaN, Number) is True
assert isinstance(S.Infinity, Number) is True
assert isinstance(S.NegativeInfinity, Number) is True
assert S.NaN.is_number is True
assert S.Infinity.is_number is True
assert S.NegativeInfinity.is_number is True
assert S.ComplexInfinity.is_number is True
assert isinstance(S.NaN, Rational) is False
assert isinstance(S.Infinity, Rational) is False
assert isinstance(S.NegativeInfinity, Rational) is False
assert S.NaN.is_rational is not True
assert S.Infinity.is_rational is not True
assert S.NegativeInfinity.is_rational is not True
def test_powers():
assert integer_nthroot(1, 2) == (1, True)
assert integer_nthroot(1, 5) == (1, True)
assert integer_nthroot(2, 1) == (2, True)
assert integer_nthroot(2, 2) == (1, False)
assert integer_nthroot(2, 5) == (1, False)
assert integer_nthroot(4, 2) == (2, True)
assert integer_nthroot(123**25, 25) == (123, True)
assert integer_nthroot(123**25 + 1, 25) == (123, False)
assert integer_nthroot(123**25 - 1, 25) == (122, False)
assert integer_nthroot(1, 1) == (1, True)
assert integer_nthroot(0, 1) == (0, True)
assert integer_nthroot(0, 3) == (0, True)
assert integer_nthroot(10000, 1) == (10000, True)
assert integer_nthroot(4, 2) == (2, True)
assert integer_nthroot(16, 2) == (4, True)
assert integer_nthroot(26, 2) == (5, False)
assert integer_nthroot(1234567**7, 7) == (1234567, True)
assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False)
assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False)
b = 25**1000
assert integer_nthroot(b, 1000) == (25, True)
assert integer_nthroot(b + 1, 1000) == (25, False)
assert integer_nthroot(b - 1, 1000) == (24, False)
c = 10**400
c2 = c**2
assert integer_nthroot(c2, 2) == (c, True)
assert integer_nthroot(c2 + 1, 2) == (c, False)
assert integer_nthroot(c2 - 1, 2) == (c - 1, False)
assert integer_nthroot(2, 10**10) == (1, False)
p, r = integer_nthroot(int(factorial(10000)), 100)
assert p % (10**10) == 5322420655
assert not r
# Test that this is fast
assert integer_nthroot(2, 10**10) == (1, False)
# output should be int if possible
assert type(integer_nthroot(2**61, 2)[0]) is int
def test_integer_nthroot_overflow():
assert integer_nthroot(10**(50*50), 50) == (10**50, True)
assert integer_nthroot(10**100000, 10000) == (10**10, True)
def test_integer_log():
raises(ValueError, lambda: integer_log(2, 1))
raises(ValueError, lambda: integer_log(0, 2))
raises(ValueError, lambda: integer_log(1.1, 2))
raises(ValueError, lambda: integer_log(1, 2.2))
assert integer_log(1, 2) == (0, True)
assert integer_log(1, 3) == (0, True)
assert integer_log(2, 3) == (0, False)
assert integer_log(3, 3) == (1, True)
assert integer_log(3*2, 3) == (1, False)
assert integer_log(3**2, 3) == (2, True)
assert integer_log(3*4, 3) == (2, False)
assert integer_log(3**3, 3) == (3, True)
assert integer_log(27, 5) == (2, False)
assert integer_log(2, 3) == (0, False)
assert integer_log(-4, -2) == (2, False)
assert integer_log(27, -3) == (3, False)
assert integer_log(-49, 7) == (0, False)
assert integer_log(-49, -7) == (2, False)
def test_isqrt():
from math import sqrt as _sqrt
limit = 4503599761588223
assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0]
assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0]
assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0]
# Regression tests for https://github.com/sympy/sympy/issues/17034
assert isqrt(4503599761588224) == 67108864
assert isqrt(9999999999999999) == 99999999
# Other corner cases, especially involving non-integers.
raises(ValueError, lambda: isqrt(-1))
raises(ValueError, lambda: isqrt(-10**1000))
raises(ValueError, lambda: isqrt(Rational(-1, 2)))
tiny = Rational(1, 10**1000)
raises(ValueError, lambda: isqrt(-tiny))
assert isqrt(1-tiny) == 0
assert isqrt(4503599761588224-tiny) == 67108864
assert isqrt(10**100 - tiny) == 10**50 - 1
# Check that using an inaccurate math.sqrt doesn't affect the results.
from sympy.core import power
old_sqrt = power._sqrt
power._sqrt = lambda x: 2.999999999
try:
assert isqrt(9) == 3
assert isqrt(10000) == 100
finally:
power._sqrt = old_sqrt
def test_powers_Integer():
"""Test Integer._eval_power"""
# check infinity
assert S.One ** S.Infinity is S.NaN
assert S.NegativeOne** S.Infinity is S.NaN
assert S(2) ** S.Infinity is S.Infinity
assert S(-2)** S.Infinity == zoo
assert S(0) ** S.Infinity is S.Zero
# check Nan
assert S.One ** S.NaN is S.NaN
assert S.NegativeOne ** S.NaN is S.NaN
# check for exact roots
assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5)
assert sqrt(S(4)) == 2
assert sqrt(S(-4)) == I * 2
assert S(16) ** Rational(1, 4) == 2
assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4)
assert S(9) ** Rational(3, 2) == 27
assert S(-9) ** Rational(3, 2) == -27*I
assert S(27) ** Rational(2, 3) == 9
assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3))
assert (-2) ** Rational(-2, 1) == Rational(1, 4)
# not exact roots
assert sqrt(-3) == I*sqrt(3)
assert (3) ** (Rational(3, 2)) == 3 * sqrt(3)
assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3)
assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3)
assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3)
assert (2) ** (Rational(3, 2)) == 2 * sqrt(2)
assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4
assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3)))
assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3)))
assert (-3) ** Rational(-7, 3) == \
-(-1)**Rational(2, 3)*3**Rational(2, 3)/27
assert (-3) ** Rational(-2, 3) == \
-(-1)**Rational(1, 3)*3**Rational(1, 3)/3
# join roots
assert sqrt(6) + sqrt(24) == 3*sqrt(6)
assert sqrt(2) * sqrt(3) == sqrt(6)
# separate symbols & constansts
x = Symbol("x")
assert sqrt(49 * x) == 7 * sqrt(x)
assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi)
# check that it is fast for big numbers
assert (2**64 + 1) ** Rational(4, 3)
assert (2**64 + 1) ** Rational(17, 25)
# negative rational power and negative base
assert (-3) ** Rational(-7, 3) == \
-(-1)**Rational(2, 3)*3**Rational(2, 3)/27
assert (-3) ** Rational(-2, 3) == \
-(-1)**Rational(1, 3)*3**Rational(1, 3)/3
assert (-2) ** Rational(-10, 3) == \
(-1)**Rational(2, 3)*2**Rational(2, 3)/16
assert abs(Pow(-2, Rational(-10, 3)).n() -
Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16
# negative base and rational power with some simplification
assert (-8) ** Rational(2, 5) == \
2*(-1)**Rational(2, 5)*2**Rational(1, 5)
assert (-4) ** Rational(9, 5) == \
-8*(-1)**Rational(4, 5)*2**Rational(3, 5)
assert S(1234).factors() == {617: 1, 2: 1}
assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1}
# test that eval_power factors numbers bigger than
# the current limit in factor_trial_division (2**15)
from sympy.ntheory.generate import nextprime
n = nextprime(2**15)
assert sqrt(n**2) == n
assert sqrt(n**3) == n*sqrt(n)
assert sqrt(4*n) == 2*sqrt(n)
# check that factors of base with powers sharing gcd with power are removed
assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6)
assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6)
# check that bases sharing a gcd are exptracted
assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \
2**Rational(8, 15)*3**Rational(9, 20)
assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \
4*2**Rational(7, 10)*3**Rational(8, 15)
assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \
4*(-3)**Rational(8, 15)*2**Rational(7, 10)
assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9)
assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3)
assert 2**Rational(2, 3)*6**Rational(8, 9) == \
2*2**Rational(5, 9)*3**Rational(8, 9)
assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3)
assert 3*Pow(3, 2, evaluate=False) == 3**3
assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3)
assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \
-(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \
5**Rational(5, 6)
assert Integer(-2)**Symbol('', even=True) == \
Integer(2)**Symbol('', even=True)
assert (-1)**Float(.5) == 1.0*I
def test_powers_Rational():
"""Test Rational._eval_power"""
# check infinity
assert S.Half ** S.Infinity == 0
assert Rational(3, 2) ** S.Infinity is S.Infinity
assert Rational(-1, 2) ** S.Infinity == 0
assert Rational(-3, 2) ** S.Infinity == zoo
# check Nan
assert Rational(3, 4) ** S.NaN is S.NaN
assert Rational(-2, 3) ** S.NaN is S.NaN
# exact roots on numerator
assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3
assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9
assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3
assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9
assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2
assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4)
# exact root on denominator
assert sqrt(Rational(1, 4)) == S.Half
assert sqrt(Rational(1, -4)) == I * S.Half
assert sqrt(Rational(3, 4)) == sqrt(3) / 2
assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2
assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3
# not exact roots
assert sqrt(S.Half) == sqrt(2) / 2
assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7))
assert Rational(-3, 2)**Rational(-7, 3) == \
-4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27
assert Rational(-3, 2)**Rational(-2, 3) == \
-(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3
assert Rational(-3, 2)**Rational(-10, 3) == \
8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81
assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() -
Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16
# negative integer power and negative rational base
assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4)
a = Rational(1, 10)
assert a**Float(a, 2) == Float(a, 2)**Float(a, 2)
assert Rational(-2, 3)**Symbol('', even=True) == \
Rational(2, 3)**Symbol('', even=True)
def test_powers_Float():
assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3))
def test_lshift_Integer():
assert Integer(0) << Integer(2) == Integer(0)
assert Integer(0) << 2 == Integer(0)
assert 0 << Integer(2) == Integer(0)
assert Integer(0b11) << Integer(0) == Integer(0b11)
assert Integer(0b11) << 0 == Integer(0b11)
assert 0b11 << Integer(0) == Integer(0b11)
assert Integer(0b11) << Integer(2) == Integer(0b11 << 2)
assert Integer(0b11) << 2 == Integer(0b11 << 2)
assert 0b11 << Integer(2) == Integer(0b11 << 2)
assert Integer(-0b11) << Integer(2) == Integer(-0b11 << 2)
assert Integer(-0b11) << 2 == Integer(-0b11 << 2)
assert -0b11 << Integer(2) == Integer(-0b11 << 2)
raises(TypeError, lambda: Integer(2) << 0.0)
raises(TypeError, lambda: 0.0 << Integer(2))
raises(ValueError, lambda: Integer(1) << Integer(-1))
def test_rshift_Integer():
assert Integer(0) >> Integer(2) == Integer(0)
assert Integer(0) >> 2 == Integer(0)
assert 0 >> Integer(2) == Integer(0)
assert Integer(0b11) >> Integer(0) == Integer(0b11)
assert Integer(0b11) >> 0 == Integer(0b11)
assert 0b11 >> Integer(0) == Integer(0b11)
assert Integer(0b11) >> Integer(2) == Integer(0)
assert Integer(0b11) >> 2 == Integer(0)
assert 0b11 >> Integer(2) == Integer(0)
assert Integer(-0b11) >> Integer(2) == Integer(-1)
assert Integer(-0b11) >> 2 == Integer(-1)
assert -0b11 >> Integer(2) == Integer(-1)
assert Integer(0b1100) >> Integer(2) == Integer(0b1100 >> 2)
assert Integer(0b1100) >> 2 == Integer(0b1100 >> 2)
assert 0b1100 >> Integer(2) == Integer(0b1100 >> 2)
assert Integer(-0b1100) >> Integer(2) == Integer(-0b1100 >> 2)
assert Integer(-0b1100) >> 2 == Integer(-0b1100 >> 2)
assert -0b1100 >> Integer(2) == Integer(-0b1100 >> 2)
raises(TypeError, lambda: Integer(0b10) >> 0.0)
raises(TypeError, lambda: 0.0 >> Integer(2))
raises(ValueError, lambda: Integer(1) >> Integer(-1))
def test_and_Integer():
assert Integer(0b01010101) & Integer(0b10101010) == Integer(0)
assert Integer(0b01010101) & 0b10101010 == Integer(0)
assert 0b01010101 & Integer(0b10101010) == Integer(0)
assert Integer(0b01010101) & Integer(0b11011011) == Integer(0b01010001)
assert Integer(0b01010101) & 0b11011011 == Integer(0b01010001)
assert 0b01010101 & Integer(0b11011011) == Integer(0b01010001)
assert -Integer(0b01010101) & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
assert Integer(-0b01010101) & 0b11011011 == Integer(-0b01010101 & 0b11011011)
assert -0b01010101 & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
assert Integer(0b01010101) & -Integer(0b11011011) == Integer(0b01010101 & -0b11011011)
assert Integer(0b01010101) & -0b11011011 == Integer(0b01010101 & -0b11011011)
assert 0b01010101 & Integer(-0b11011011) == Integer(0b01010101 & -0b11011011)
raises(TypeError, lambda: Integer(2) & 0.0)
raises(TypeError, lambda: 0.0 & Integer(2))
def test_xor_Integer():
assert Integer(0b01010101) ^ Integer(0b11111111) == Integer(0b10101010)
assert Integer(0b01010101) ^ 0b11111111 == Integer(0b10101010)
assert 0b01010101 ^ Integer(0b11111111) == Integer(0b10101010)
assert Integer(0b01010101) ^ Integer(0b11011011) == Integer(0b10001110)
assert Integer(0b01010101) ^ 0b11011011 == Integer(0b10001110)
assert 0b01010101 ^ Integer(0b11011011) == Integer(0b10001110)
assert -Integer(0b01010101) ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
assert Integer(-0b01010101) ^ 0b11011011 == Integer(-0b01010101 ^ 0b11011011)
assert -0b01010101 ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
assert Integer(0b01010101) ^ -Integer(0b11011011) == Integer(0b01010101 ^ -0b11011011)
assert Integer(0b01010101) ^ -0b11011011 == Integer(0b01010101 ^ -0b11011011)
assert 0b01010101 ^ Integer(-0b11011011) == Integer(0b01010101 ^ -0b11011011)
raises(TypeError, lambda: Integer(2) ^ 0.0)
raises(TypeError, lambda: 0.0 ^ Integer(2))
def test_or_Integer():
assert Integer(0b01010101) | Integer(0b10101010) == Integer(0b11111111)
assert Integer(0b01010101) | 0b10101010 == Integer(0b11111111)
assert 0b01010101 | Integer(0b10101010) == Integer(0b11111111)
assert Integer(0b01010101) | Integer(0b11011011) == Integer(0b11011111)
assert Integer(0b01010101) | 0b11011011 == Integer(0b11011111)
assert 0b01010101 | Integer(0b11011011) == Integer(0b11011111)
assert -Integer(0b01010101) | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
assert Integer(-0b01010101) | 0b11011011 == Integer(-0b01010101 | 0b11011011)
assert -0b01010101 | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
assert Integer(0b01010101) | -Integer(0b11011011) == Integer(0b01010101 | -0b11011011)
assert Integer(0b01010101) | -0b11011011 == Integer(0b01010101 | -0b11011011)
assert 0b01010101 | Integer(-0b11011011) == Integer(0b01010101 | -0b11011011)
raises(TypeError, lambda: Integer(2) | 0.0)
raises(TypeError, lambda: 0.0 | Integer(2))
def test_invert_Integer():
assert ~Integer(0b01010101) == Integer(-0b01010110)
assert ~Integer(0b01010101) == Integer(~0b01010101)
assert ~(~Integer(0b01010101)) == Integer(0b01010101)
def test_abs1():
assert Rational(1, 6) != Rational(-1, 6)
assert abs(Rational(1, 6)) == abs(Rational(-1, 6))
def test_accept_int():
assert Float(4) == 4
def test_dont_accept_str():
assert Float("0.2") != "0.2"
assert not (Float("0.2") == "0.2")
def test_int():
a = Rational(5)
assert int(a) == 5
a = Rational(9, 10)
assert int(a) == int(-a) == 0
assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3)
# issue 10368
a = Rational(32442016954, 78058255275)
assert type(int(a)) is type(int(-a)) is int
def test_int_NumberSymbols():
assert int(Catalan) == 0
assert int(EulerGamma) == 0
assert int(pi) == 3
assert int(E) == 2
assert int(GoldenRatio) == 1
assert int(TribonacciConstant) == 1
for i in [Catalan, E, EulerGamma, GoldenRatio, TribonacciConstant, pi]:
a, b = i.approximation_interval(Integer)
ia = int(i)
assert ia == a
assert isinstance(ia, int)
assert b == a + 1
assert a.is_Integer and b.is_Integer
def test_real_bug():
x = Symbol("x")
assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"]
assert str(2.1*x*x) != "(2.0*x)*x"
def test_bug_sqrt():
assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1
def test_pi_Pi():
"Test that pi (instance) is imported, but Pi (class) is not"
from sympy import pi # noqa
with raises(ImportError):
from sympy import Pi # noqa
def test_no_len():
# there should be no len for numbers
raises(TypeError, lambda: len(Rational(2)))
raises(TypeError, lambda: len(Rational(2, 3)))
raises(TypeError, lambda: len(Integer(2)))
def test_issue_3321():
assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half
assert 5 * sqrt(Rational(1, 5)) == sqrt(5)
def test_issue_3692():
assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2
assert ((-5)**Rational(1, 6)).expand(complex=True) == \
5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2
assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3)
def test_issue_3423():
x = Symbol("x")
assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half)
assert sqrt(x - 1) != I*sqrt(1 - x)
def test_issue_3449():
x = Symbol("x")
assert sqrt(x - 1).subs(x, 5) == 2
def test_issue_13890():
x = Symbol("x")
e = (-x/4 - S.One/12)**x - 1
f = simplify(e)
a = Rational(9, 5)
assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15
def test_Integer_factors():
def F(i):
return Integer(i).factors()
assert F(1) == {}
assert F(2) == {2: 1}
assert F(3) == {3: 1}
assert F(4) == {2: 2}
assert F(5) == {5: 1}
assert F(6) == {2: 1, 3: 1}
assert F(7) == {7: 1}
assert F(8) == {2: 3}
assert F(9) == {3: 2}
assert F(10) == {2: 1, 5: 1}
assert F(11) == {11: 1}
assert F(12) == {2: 2, 3: 1}
assert F(13) == {13: 1}
assert F(14) == {2: 1, 7: 1}
assert F(15) == {3: 1, 5: 1}
assert F(16) == {2: 4}
assert F(17) == {17: 1}
assert F(18) == {2: 1, 3: 2}
assert F(19) == {19: 1}
assert F(20) == {2: 2, 5: 1}
assert F(21) == {3: 1, 7: 1}
assert F(22) == {2: 1, 11: 1}
assert F(23) == {23: 1}
assert F(24) == {2: 3, 3: 1}
assert F(25) == {5: 2}
assert F(26) == {2: 1, 13: 1}
assert F(27) == {3: 3}
assert F(28) == {2: 2, 7: 1}
assert F(29) == {29: 1}
assert F(30) == {2: 1, 3: 1, 5: 1}
assert F(31) == {31: 1}
assert F(32) == {2: 5}
assert F(33) == {3: 1, 11: 1}
assert F(34) == {2: 1, 17: 1}
assert F(35) == {5: 1, 7: 1}
assert F(36) == {2: 2, 3: 2}
assert F(37) == {37: 1}
assert F(38) == {2: 1, 19: 1}
assert F(39) == {3: 1, 13: 1}
assert F(40) == {2: 3, 5: 1}
assert F(41) == {41: 1}
assert F(42) == {2: 1, 3: 1, 7: 1}
assert F(43) == {43: 1}
assert F(44) == {2: 2, 11: 1}
assert F(45) == {3: 2, 5: 1}
assert F(46) == {2: 1, 23: 1}
assert F(47) == {47: 1}
assert F(48) == {2: 4, 3: 1}
assert F(49) == {7: 2}
assert F(50) == {2: 1, 5: 2}
assert F(51) == {3: 1, 17: 1}
def test_Rational_factors():
def F(p, q, visual=None):
return Rational(p, q).factors(visual=visual)
assert F(2, 3) == {2: 1, 3: -1}
assert F(2, 9) == {2: 1, 3: -2}
assert F(2, 15) == {2: 1, 3: -1, 5: -1}
assert F(6, 10) == {3: 1, 5: -1}
def test_issue_4107():
assert pi*(E + 10) + pi*(-E - 10) != 0
assert pi*(E + 10**10) + pi*(-E - 10**10) != 0
assert pi*(E + 10**20) + pi*(-E - 10**20) != 0
assert pi*(E + 10**80) + pi*(-E - 10**80) != 0
assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0
assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0
assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0
assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0
def test_IntegerInteger():
a = Integer(4)
b = Integer(a)
assert a == b
def test_Rational_gcd_lcm_cofactors():
assert Integer(4).gcd(2) == Integer(2)
assert Integer(4).lcm(2) == Integer(4)
assert Integer(4).gcd(Integer(2)) == Integer(2)
assert Integer(4).lcm(Integer(2)) == Integer(4)
a, b = 720**99911, 480**12342
assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b)
assert Integer(4).gcd(3) == Integer(1)
assert Integer(4).lcm(3) == Integer(12)
assert Integer(4).gcd(Integer(3)) == Integer(1)
assert Integer(4).lcm(Integer(3)) == Integer(12)
assert Rational(4, 3).gcd(2) == Rational(2, 3)
assert Rational(4, 3).lcm(2) == Integer(4)
assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3)
assert Rational(4, 3).lcm(Integer(2)) == Integer(4)
assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9)
assert Integer(4).lcm(Rational(2, 9)) == Integer(4)
assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9)
assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3)
assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45)
assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4)
assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7))
assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1))
assert Integer(4).cofactors(Integer(2)) == \
(Integer(2), Integer(2), Integer(1))
assert Integer(4).gcd(Float(2.0)) == S.One
assert Integer(4).lcm(Float(2.0)) == Float(8.0)
assert Integer(4).cofactors(Float(2.0)) == (S.One, Integer(4), Float(2.0))
assert S.Half.gcd(Float(2.0)) == S.One
assert S.Half.lcm(Float(2.0)) == Float(1.0)
assert S.Half.cofactors(Float(2.0)) == \
(S.One, S.Half, Float(2.0))
def test_Float_gcd_lcm_cofactors():
assert Float(2.0).gcd(Integer(4)) == S.One
assert Float(2.0).lcm(Integer(4)) == Float(8.0)
assert Float(2.0).cofactors(Integer(4)) == (S.One, Float(2.0), Integer(4))
assert Float(2.0).gcd(S.Half) == S.One
assert Float(2.0).lcm(S.Half) == Float(1.0)
assert Float(2.0).cofactors(S.Half) == \
(S.One, Float(2.0), S.Half)
def test_issue_4611():
assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10
assert abs(E._evalf(50) - 2.71828182845905) < 1e-10
assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10
assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10
assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10
assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10
x = Symbol("x")
assert (pi + x).evalf() == pi.evalf() + x
assert (E + x).evalf() == E.evalf() + x
assert (Catalan + x).evalf() == Catalan.evalf() + x
assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x
assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x
assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x
@conserve_mpmath_dps
def test_conversion_to_mpmath():
assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1)
assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5)
assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23')
assert mpmath.mpmathify(I) == mpmath.mpc(1j)
assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j)
assert mpmath.mpmathify(2*I) == mpmath.mpc(2j)
assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j)
assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j)
mpmath.mp.dps = 100
assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j
assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j
def test_relational():
# real
x = S(.1)
assert (x != cos) is True
assert (x == cos) is False
# rational
x = Rational(1, 3)
assert (x != cos) is True
assert (x == cos) is False
# integer defers to rational so these tests are omitted
# number symbol
x = pi
assert (x != cos) is True
assert (x == cos) is False
def test_Integer_as_index():
assert 'hello'[Integer(2):] == 'llo'
def test_Rational_int():
assert int( Rational(7, 5)) == 1
assert int( S.Half) == 0
assert int(Rational(-1, 2)) == 0
assert int(-Rational(7, 5)) == -1
def test_zoo():
b = Symbol('b', finite=True)
nz = Symbol('nz', nonzero=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
im = Symbol('i', imaginary=True)
c = Symbol('c', complex=True)
pb = Symbol('pb', positive=True)
nb = Symbol('nb', negative=True)
imb = Symbol('ib', imaginary=True, finite=True)
for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3),
b, nz, p, n, im, pb, nb, imb, c]:
if i.is_finite and (i.is_real or i.is_imaginary):
assert i + zoo is zoo
assert i - zoo is zoo
assert zoo + i is zoo
assert zoo - i is zoo
elif i.is_finite is not False:
assert (i + zoo).is_Add
assert (i - zoo).is_Add
assert (zoo + i).is_Add
assert (zoo - i).is_Add
else:
assert (i + zoo) is S.NaN
assert (i - zoo) is S.NaN
assert (zoo + i) is S.NaN
assert (zoo - i) is S.NaN
if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary):
assert i*zoo is zoo
assert zoo*i is zoo
elif i.is_zero:
assert i*zoo is S.NaN
assert zoo*i is S.NaN
else:
assert (i*zoo).is_Mul
assert (zoo*i).is_Mul
if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary):
assert zoo/i is zoo
elif (1/i).is_zero:
assert zoo/i is S.NaN
elif i.is_zero:
assert zoo/i is zoo
else:
assert (zoo/i).is_Mul
assert (I*oo).is_Mul # allow directed infinity
assert zoo + zoo is S.NaN
assert zoo * zoo is zoo
assert zoo - zoo is S.NaN
assert zoo/zoo is S.NaN
assert zoo**zoo is S.NaN
assert zoo**0 is S.One
assert zoo**2 is zoo
assert 1/zoo is S.Zero
assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None)
def test_issue_4122():
x = Symbol('x', nonpositive=True)
assert oo + x is oo
x = Symbol('x', extended_nonpositive=True)
assert (oo + x).is_Add
x = Symbol('x', finite=True)
assert (oo + x).is_Add # x could be imaginary
x = Symbol('x', nonnegative=True)
assert oo + x is oo
x = Symbol('x', extended_nonnegative=True)
assert oo + x is oo
x = Symbol('x', finite=True, real=True)
assert oo + x is oo
# similarly for negative infinity
x = Symbol('x', nonnegative=True)
assert -oo + x is -oo
x = Symbol('x', extended_nonnegative=True)
assert (-oo + x).is_Add
x = Symbol('x', finite=True)
assert (-oo + x).is_Add
x = Symbol('x', nonpositive=True)
assert -oo + x is -oo
x = Symbol('x', extended_nonpositive=True)
assert -oo + x is -oo
x = Symbol('x', finite=True, real=True)
assert -oo + x is -oo
def test_GoldenRatio_expand():
assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2
def test_TribonacciConstant_expand():
assert TribonacciConstant.expand(func=True) == \
(1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def test_as_content_primitive():
assert S.Zero.as_content_primitive() == (1, 0)
assert S.Half.as_content_primitive() == (S.Half, 1)
assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1)
assert S(3).as_content_primitive() == (3, 1)
assert S(3.1).as_content_primitive() == (1, 3.1)
def test_hashing_sympy_integers():
# Test for issue 5072
assert {Integer(3)} == {int(3)}
assert hash(Integer(4)) == hash(int(4))
def test_rounding_issue_4172():
assert int((E**100).round()) == \
26881171418161354484126255515800135873611119
assert int((pi**100).round()) == \
51878483143196131920862615246303013562686760680406
assert int((Rational(1)/EulerGamma**100).round()) == \
734833795660954410469466
@XFAIL
def test_mpmath_issues():
from mpmath.libmp.libmpf import _normalize
import mpmath.libmp as mlib
rnd = mlib.round_nearest
mpf = (0, int(0), -123, -1, 53, rnd) # nan
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
mpf = (0, int(0), -456, -2, 53, rnd) # +inf
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
mpf = (1, int(0), -789, -3, 53, rnd) # -inf
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
from mpmath.libmp.libmpf import fnan
assert mlib.mpf_eq(fnan, fnan)
def test_Catalan_EulerGamma_prec():
n = GoldenRatio
f = Float(n.n(), 5)
assert f._mpf_ == (0, int(212079), -17, 18)
assert f._prec == 20
assert n._as_mpf_val(20) == f._mpf_
n = EulerGamma
f = Float(n.n(), 5)
assert f._mpf_ == (0, int(302627), -19, 19)
assert f._prec == 20
assert n._as_mpf_val(20) == f._mpf_
def test_Catalan_rewrite():
k = Dummy('k', integer=True, nonnegative=True)
assert Catalan.rewrite(Sum).dummy_eq(
Sum((-1)**k/(2*k + 1)**2, (k, 0, oo)))
assert Catalan.rewrite() == Catalan
def test_bool_eq():
assert 0 == False
assert S(0) == False
assert S(0) != S.false
assert 1 == True
assert S.One == True
assert S.One != S.true
def test_Float_eq():
# all .5 values are the same
assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1)
# but floats that aren't exact in base-2 still
# don't compare the same because they have different
# underlying mpf values
assert Float(.12, 3) != Float(.12, 4)
assert Float(.12, 3) != .12
assert 0.12 != Float(.12, 3)
assert Float('.12', 22) != .12
# issue 11707
# but Float/Rational -- except for 0 --
# are exact so Rational(x) = Float(y) only if
# Rational(x) == Rational(Float(y))
assert Float('1.1') != Rational(11, 10)
assert Rational(11, 10) != Float('1.1')
# coverage
assert not Float(3) == 2
assert not Float(2**2) == S.Half
assert Float(2**2) == 4
assert not Float(2**-2) == 1
assert Float(2**-1) == S.Half
assert not Float(2*3) == 3
assert not Float(2*3) == S.Half
assert Float(2*3) == 6
assert not Float(2*3) == 8
assert Float(.75) == Rational(3, 4)
assert Float(5/18) == 5/18
# 4473
assert Float(2.) != 3
assert Float((0,1,-3)) == S.One/8
assert Float((0,1,-3)) != S.One/9
# 16196
assert 2 == Float(2) # as per Python
# but in a computation...
assert t**2 != t**2.0
def test_issue_6640():
from mpmath.libmp.libmpf import finf, fninf
# fnan is not included because Float no longer returns fnan,
# but otherwise, the same sort of test could apply
assert Float(finf).is_zero is False
assert Float(fninf).is_zero is False
assert bool(Float(0)) is False
def test_issue_6349():
assert Float('23.e3', '')._prec == 10
assert Float('23e3', '')._prec == 20
assert Float('23000', '')._prec == 20
assert Float('-23000', '')._prec == 20
def test_mpf_norm():
assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_
assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_
def test_latex():
assert latex(pi) == r"\pi"
assert latex(E) == r"e"
assert latex(GoldenRatio) == r"\phi"
assert latex(TribonacciConstant) == r"\text{TribonacciConstant}"
assert latex(EulerGamma) == r"\gamma"
assert latex(oo) == r"\infty"
assert latex(-oo) == r"-\infty"
assert latex(zoo) == r"\tilde{\infty}"
assert latex(nan) == r"\text{NaN}"
assert latex(I) == r"i"
def test_issue_7742():
assert -oo % 1 is nan
def test_simplify_AlgebraicNumber():
A = AlgebraicNumber
e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3)
assert simplify(A(e)) == A(12) # wester test_C20
e = (41 + 29*sqrt(2))**(S.One/5)
assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21
e = (3 + 4*I)**Rational(3, 2)
assert simplify(A(e)) == A(2 + 11*I) # issue 4401
def test_Float_idempotence():
x = Float('1.23', '')
y = Float(x)
z = Float(x, 15)
assert same_and_same_prec(y, x)
assert not same_and_same_prec(z, x)
x = Float(10**20)
y = Float(x)
z = Float(x, 15)
assert same_and_same_prec(y, x)
assert not same_and_same_prec(z, x)
def test_comp1():
# sqrt(2) = 1.414213 5623730950...
a = sqrt(2).n(7)
assert comp(a, 1.4142129) is False
assert comp(a, 1.4142130)
# ...
assert comp(a, 1.4142141)
assert comp(a, 1.4142142) is False
assert comp(sqrt(2).n(2), '1.4')
assert comp(sqrt(2).n(2), Float(1.4, 2), '')
assert comp(sqrt(2).n(2), 1.4, '')
assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False
assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1)
assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1)
assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1)
assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1)
assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1)
assert [(i, j)
for i in range(130, 150)
for j in range(170, 180)
if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [
(141, 173), (142, 173)]
raises(ValueError, lambda: comp(t, '1'))
raises(ValueError, lambda: comp(t, 1))
assert comp(0, 0.0)
assert comp(.5, S.Half)
assert comp(2 + sqrt(2), 2.0 + sqrt(2))
assert not comp(0, 1)
assert not comp(2, sqrt(2))
assert not comp(2 + I, 2.0 + sqrt(2))
assert not comp(2.0 + sqrt(2), 2 + I)
assert not comp(2.0 + sqrt(2), sqrt(3))
assert comp(1/pi.n(4), 0.3183, 1e-5)
assert not comp(1/pi.n(4), 0.3183, 8e-6)
def test_issue_9491():
assert oo**zoo is nan
def test_issue_10063():
assert 2**Float(3) == Float(8)
def test_issue_10020():
assert oo**I is S.NaN
assert oo**(1 + I) is S.ComplexInfinity
assert oo**(-1 + I) is S.Zero
assert (-oo)**I is S.NaN
assert (-oo)**(-1 + I) is S.Zero
assert oo**t == Pow(oo, t, evaluate=False)
assert (-oo)**t == Pow(-oo, t, evaluate=False)
def test_invert_numbers():
assert S(2).invert(5) == 3
assert S(2).invert(Rational(5, 2)) == S.Half
assert S(2).invert(5.) == 0.5
assert S(2).invert(S(5)) == 3
assert S(2.).invert(5) == 0.5
assert S(sqrt(2)).invert(5) == 1/sqrt(2)
assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2)
def test_mod_inverse():
assert mod_inverse(3, 11) == 4
assert mod_inverse(5, 11) == 9
assert mod_inverse(21124921, 521512) == 7713
assert mod_inverse(124215421, 5125) == 2981
assert mod_inverse(214, 12515) == 1579
assert mod_inverse(5823991, 3299) == 1442
assert mod_inverse(123, 44) == 39
assert mod_inverse(2, 5) == 3
assert mod_inverse(-2, 5) == 2
assert mod_inverse(2, -5) == -2
assert mod_inverse(-2, -5) == -3
assert mod_inverse(-3, -7) == -5
x = Symbol('x')
assert S(2).invert(x) == S.Half
raises(TypeError, lambda: mod_inverse(2, x))
raises(ValueError, lambda: mod_inverse(2, S.Half))
raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2))
def test_golden_ratio_rewrite_as_sqrt():
assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half
def test_tribonacci_constant_rewrite_as_sqrt():
assert TribonacciConstant.rewrite(sqrt) == \
(1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def test_comparisons_with_unknown_type():
class Foo:
"""
Class that is unaware of Basic, and relies on both classes returning
the NotImplemented singleton for equivalence to evaluate to False.
"""
ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3)
foo = Foo()
for n in ni, nf, nr, oo, -oo, zoo, nan:
assert n != foo
assert foo != n
assert not n == foo
assert not foo == n
raises(TypeError, lambda: n < foo)
raises(TypeError, lambda: foo > n)
raises(TypeError, lambda: n > foo)
raises(TypeError, lambda: foo < n)
raises(TypeError, lambda: n <= foo)
raises(TypeError, lambda: foo >= n)
raises(TypeError, lambda: n >= foo)
raises(TypeError, lambda: foo <= n)
class Bar:
"""
Class that considers itself equal to any instance of Number except
infinities and nans, and relies on SymPy types returning the
NotImplemented singleton for symmetric equality relations.
"""
def __eq__(self, other):
if other in (oo, -oo, zoo, nan):
return False
if isinstance(other, Number):
return True
return NotImplemented
def __ne__(self, other):
return not self == other
bar = Bar()
for n in ni, nf, nr:
assert n == bar
assert bar == n
assert not n != bar
assert not bar != n
for n in oo, -oo, zoo, nan:
assert n != bar
assert bar != n
assert not n == bar
assert not bar == n
for n in ni, nf, nr, oo, -oo, zoo, nan:
raises(TypeError, lambda: n < bar)
raises(TypeError, lambda: bar > n)
raises(TypeError, lambda: n > bar)
raises(TypeError, lambda: bar < n)
raises(TypeError, lambda: n <= bar)
raises(TypeError, lambda: bar >= n)
raises(TypeError, lambda: n >= bar)
raises(TypeError, lambda: bar <= n)
def test_NumberSymbol_comparison():
from sympy.core.tests.test_relational import rel_check
rpi = Rational('905502432259640373/288230376151711744')
fpi = Float(float(pi))
assert rel_check(rpi, fpi)
def test_Integer_precision():
# Make sure Integer inputs for keyword args work
assert Float('1.0', dps=Integer(15))._prec == 53
assert Float('1.0', precision=Integer(15))._prec == 15
assert type(Float('1.0', precision=Integer(15))._prec) == int
assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15)
def test_numpy_to_float():
from sympy.testing.pytest import skip
from sympy.external import import_module
np = import_module('numpy')
if not np:
skip('numpy not installed. Abort numpy tests.')
def check_prec_and_relerr(npval, ratval):
prec = np.finfo(npval).nmant + 1
x = Float(npval)
assert x._prec == prec
y = Float(ratval, precision=prec)
assert abs((x - y)/y) < 2**(-(prec + 1))
check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3))
check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3))
check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3))
# extended precision, on some arch/compilers:
x = np.longdouble(2)/3
check_prec_and_relerr(x, Rational(2, 3))
y = Float(x, precision=10)
assert same_and_same_prec(y, Float(Rational(2, 3), precision=10))
raises(TypeError, lambda: Float(np.complex64(1+2j)))
raises(TypeError, lambda: Float(np.complex128(1+2j)))
def test_Integer_ceiling_floor():
a = Integer(4)
assert a.floor() == a
assert a.ceiling() == a
def test_ComplexInfinity():
assert zoo.floor() is zoo
assert zoo.ceiling() is zoo
assert zoo**zoo is S.NaN
def test_Infinity_floor_ceiling_power():
assert oo.floor() is oo
assert oo.ceiling() is oo
assert oo**S.NaN is S.NaN
assert oo**zoo is S.NaN
def test_One_power():
assert S.One**12 is S.One
assert S.NegativeOne**S.NaN is S.NaN
def test_NegativeInfinity():
assert (-oo).floor() is -oo
assert (-oo).ceiling() is -oo
assert (-oo)**11 is -oo
assert (-oo)**12 is oo
def test_issue_6133():
raises(TypeError, lambda: (-oo < None))
raises(TypeError, lambda: (S(-2) < None))
raises(TypeError, lambda: (oo < None))
raises(TypeError, lambda: (oo > None))
raises(TypeError, lambda: (S(2) < None))
def test_abc():
x = numbers.Float(5)
assert(isinstance(x, nums.Number))
assert(isinstance(x, numbers.Number))
assert(isinstance(x, nums.Real))
y = numbers.Rational(1, 3)
assert(isinstance(y, nums.Number))
assert(y.numerator == 1)
assert(y.denominator == 3)
assert(isinstance(y, nums.Rational))
z = numbers.Integer(3)
assert(isinstance(z, nums.Number))
assert(isinstance(z, numbers.Number))
assert(isinstance(z, nums.Rational))
assert(isinstance(z, numbers.Rational))
assert(isinstance(z, nums.Integral))
def test_floordiv():
assert S(2)//S.Half == 4
def test_negation():
assert -S.Zero is S.Zero
assert -Float(0) is not S.Zero and -Float(0) == 0
def test_exponentiation_of_0():
x = Symbol('x')
assert 0**-x == zoo**x
assert unchanged(Pow, 0, x)
x = Symbol('x', zero=True)
assert 0**-x == S.One
assert 0**x == S.One
|
a7a0a2ef96bf4fe6c15c4ff91d5c512a56badae49acbfd15b9fe7b814b87eac2 | import sys
from sympy.core.cache import cacheit, cached_property, lazy_function
from sympy.testing.pytest import raises
def test_cacheit_doc():
@cacheit
def testfn():
"test docstring"
pass
assert testfn.__doc__ == "test docstring"
assert testfn.__name__ == "testfn"
def test_cacheit_unhashable():
@cacheit
def testit(x):
return x
assert testit(1) == 1
assert testit(1) == 1
a = {}
assert testit(a) == {}
a[1] = 2
assert testit(a) == {1: 2}
def test_cachit_exception():
# Make sure the cache doesn't call functions multiple times when they
# raise TypeError
a = []
@cacheit
def testf(x):
a.append(0)
raise TypeError
raises(TypeError, lambda: testf(1))
assert len(a) == 1
a.clear()
# Unhashable type
raises(TypeError, lambda: testf([]))
assert len(a) == 1
@cacheit
def testf2(x):
a.append(0)
raise TypeError("Error")
a.clear()
raises(TypeError, lambda: testf2(1))
assert len(a) == 1
a.clear()
# Unhashable type
raises(TypeError, lambda: testf2([]))
assert len(a) == 1
def test_cached_property():
class A:
def __init__(self, value):
self.value = value
self.calls = 0
@cached_property
def prop(self):
self.calls = self.calls + 1
return self.value
a = A(2)
assert a.calls == 0
assert a.prop == 2
assert a.calls == 1
assert a.prop == 2
assert a.calls == 1
b = A(None)
assert b.prop == None
def test_lazy_function():
module_name='xmlrpc.client'
function_name = 'gzip_decode'
lazy = lazy_function(module_name, function_name)
assert lazy(b'') == b''
assert module_name in sys.modules
assert function_name in str(lazy)
repr_lazy = repr(lazy)
assert 'LazyFunction' in repr_lazy
assert function_name in repr_lazy
lazy = lazy_function('sympy.core.cache', 'cheap')
|
f9197bb1141ebef54131c9378d203c920ea382f59e236cb187d71b4aecb47ce0 | from sympy.core.expr import unchanged
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational as R, pi)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.series.order import O
from sympy.simplify.radsimp import expand_numer
from sympy.core.function import expand, expand_multinomial, expand_power_base
from sympy.testing.pytest import raises
from sympy.core.random import verify_numerically
from sympy.abc import x, y, z
def test_expand_no_log():
assert (
(1 + log(x**4))**2).expand(log=False) == 1 + 2*log(x**4) + log(x**4)**2
assert ((1 + log(x**4))*(1 + log(x**3))).expand(
log=False) == 1 + log(x**4) + log(x**3) + log(x**4)*log(x**3)
def test_expand_no_multinomial():
assert ((1 + x)*(1 + (1 + x)**4)).expand(multinomial=False) == \
1 + x + (1 + x)**4 + x*(1 + x)**4
def test_expand_negative_integer_powers():
expr = (x + y)**(-2)
assert expr.expand() == 1 / (2*x*y + x**2 + y**2)
assert expr.expand(multinomial=False) == (x + y)**(-2)
expr = (x + y)**(-3)
assert expr.expand() == 1 / (3*x*x*y + 3*x*y*y + x**3 + y**3)
assert expr.expand(multinomial=False) == (x + y)**(-3)
expr = (x + y)**(2) * (x + y)**(-4)
assert expr.expand() == 1 / (2*x*y + x**2 + y**2)
assert expr.expand(multinomial=False) == (x + y)**(-2)
def test_expand_non_commutative():
A = Symbol('A', commutative=False)
B = Symbol('B', commutative=False)
C = Symbol('C', commutative=False)
a = Symbol('a')
b = Symbol('b')
i = Symbol('i', integer=True)
n = Symbol('n', negative=True)
m = Symbol('m', negative=True)
p = Symbol('p', polar=True)
np = Symbol('p', polar=False)
assert (C*(A + B)).expand() == C*A + C*B
assert (C*(A + B)).expand() != A*C + B*C
assert ((A + B)**2).expand() == A**2 + A*B + B*A + B**2
assert ((A + B)**3).expand() == (A**2*B + B**2*A + A*B**2 + B*A**2 +
A**3 + B**3 + A*B*A + B*A*B)
# issue 6219
assert ((a*A*B*A**-1)**2).expand() == a**2*A*B**2/A
# Note that (a*A*B*A**-1)**2 is automatically converted to a**2*(A*B*A**-1)**2
assert ((a*A*B*A**-1)**2).expand(deep=False) == a**2*(A*B*A**-1)**2
assert ((a*A*B*A**-1)**2).expand() == a**2*(A*B**2*A**-1)
assert ((a*A*B*A**-1)**2).expand(force=True) == a**2*A*B**2*A**(-1)
assert ((a*A*B)**2).expand() == a**2*A*B*A*B
assert ((a*A)**2).expand() == a**2*A**2
assert ((a*A*B)**i).expand() == a**i*(A*B)**i
assert ((a*A*(B*(A*B/A)**2))**i).expand() == a**i*(A*B*A*B**2/A)**i
# issue 6558
assert (A*B*(A*B)**-1).expand() == 1
assert ((a*A)**i).expand() == a**i*A**i
assert ((a*A*B*A**-1)**3).expand() == a**3*A*B**3/A
assert ((a*A*B*A*B/A)**3).expand() == \
a**3*A*B*(A*B**2)*(A*B**2)*A*B*A**(-1)
assert ((a*A*B*A*B/A)**-2).expand() == \
A*B**-1*A**-1*B**-2*A**-1*B**-1*A**-1/a**2
assert ((a*b*A*B*A**-1)**i).expand() == a**i*b**i*(A*B/A)**i
assert ((a*(a*b)**i)**i).expand() == a**i*a**(i**2)*b**(i**2)
e = Pow(Mul(a, 1/a, A, B, evaluate=False), S(2), evaluate=False)
assert e.expand() == A*B*A*B
assert sqrt(a*(A*b)**i).expand() == sqrt(a*b**i*A**i)
assert (sqrt(-a)**a).expand() == sqrt(-a)**a
assert expand((-2*n)**(i/3)) == 2**(i/3)*(-n)**(i/3)
assert expand((-2*n*m)**(i/a)) == (-2)**(i/a)*(-n)**(i/a)*(-m)**(i/a)
assert expand((-2*a*p)**b) == 2**b*p**b*(-a)**b
assert expand((-2*a*np)**b) == 2**b*(-a*np)**b
assert expand(sqrt(A*B)) == sqrt(A*B)
assert expand(sqrt(-2*a*b)) == sqrt(2)*sqrt(-a*b)
def test_expand_radicals():
a = (x + y)**R(1, 2)
assert (a**1).expand() == a
assert (a**3).expand() == x*a + y*a
assert (a**5).expand() == x**2*a + 2*x*y*a + y**2*a
assert (1/a**1).expand() == 1/a
assert (1/a**3).expand() == 1/(x*a + y*a)
assert (1/a**5).expand() == 1/(x**2*a + 2*x*y*a + y**2*a)
a = (x + y)**R(1, 3)
assert (a**1).expand() == a
assert (a**2).expand() == a**2
assert (a**4).expand() == x*a + y*a
assert (a**5).expand() == x*a**2 + y*a**2
assert (a**7).expand() == x**2*a + 2*x*y*a + y**2*a
def test_expand_modulus():
assert ((x + y)**11).expand(modulus=11) == x**11 + y**11
assert ((x + sqrt(2)*y)**11).expand(modulus=11) == x**11 + 10*sqrt(2)*y**11
assert (x + y/2).expand(modulus=1) == y/2
raises(ValueError, lambda: ((x + y)**11).expand(modulus=0))
raises(ValueError, lambda: ((x + y)**11).expand(modulus=x))
def test_issue_5743():
assert (x*sqrt(
x + y)*(1 + sqrt(x + y))).expand() == x**2 + x*y + x*sqrt(x + y)
assert (x*sqrt(
x + y)*(1 + x*sqrt(x + y))).expand() == x**3 + x**2*y + x*sqrt(x + y)
def test_expand_frac():
assert expand((x + y)*y/x/(x + 1), frac=True) == \
(x*y + y**2)/(x**2 + x)
assert expand((x + y)*y/x/(x + 1), numer=True) == \
(x*y + y**2)/(x*(x + 1))
assert expand((x + y)*y/x/(x + 1), denom=True) == \
y*(x + y)/(x**2 + x)
eq = (x + 1)**2/y
assert expand_numer(eq, multinomial=False) == eq
def test_issue_6121():
eq = -I*exp(-3*I*pi/4)/(4*pi**(S(3)/2)*sqrt(x))
assert eq.expand(complex=True) # does not give oo recursion
eq = -I*exp(-3*I*pi/4)/(4*pi**(R(3, 2))*sqrt(x))
assert eq.expand(complex=True) # does not give oo recursion
def test_expand_power_base():
assert expand_power_base((x*y*z)**4) == x**4*y**4*z**4
assert expand_power_base((x*y*z)**x).is_Pow
assert expand_power_base((x*y*z)**x, force=True) == x**x*y**x*z**x
assert expand_power_base((x*(y*z)**2)**3) == x**3*y**6*z**6
assert expand_power_base((sin((x*y)**2)*y)**z).is_Pow
assert expand_power_base(
(sin((x*y)**2)*y)**z, force=True) == sin((x*y)**2)**z*y**z
assert expand_power_base(
(sin((x*y)**2)*y)**z, deep=True) == (sin(x**2*y**2)*y)**z
assert expand_power_base(exp(x)**2) == exp(2*x)
assert expand_power_base((exp(x)*exp(y))**2) == exp(2*x)*exp(2*y)
assert expand_power_base(
(exp((x*y)**z)*exp(y))**2) == exp(2*(x*y)**z)*exp(2*y)
assert expand_power_base((exp((x*y)**z)*exp(
y))**2, deep=True, force=True) == exp(2*x**z*y**z)*exp(2*y)
assert expand_power_base((exp(x)*exp(y))**z).is_Pow
assert expand_power_base(
(exp(x)*exp(y))**z, force=True) == exp(x)**z*exp(y)**z
def test_expand_arit():
a = Symbol("a")
b = Symbol("b", positive=True)
c = Symbol("c")
p = R(5)
e = (a + b)*c
assert e == c*(a + b)
assert (e.expand() - a*c - b*c) == R(0)
e = (a + b)*(a + b)
assert e == (a + b)**2
assert e.expand() == 2*a*b + a**2 + b**2
e = (a + b)*(a + b)**R(2)
assert e == (a + b)**3
assert e.expand() == 3*b*a**2 + 3*a*b**2 + a**3 + b**3
assert e.expand() == 3*b*a**2 + 3*a*b**2 + a**3 + b**3
e = (a + b)*(a + c)*(b + c)
assert e == (a + c)*(a + b)*(b + c)
assert e.expand() == 2*a*b*c + b*a**2 + c*a**2 + b*c**2 + a*c**2 + c*b**2 + a*b**2
e = (a + R(1))**p
assert e == (1 + a)**5
assert e.expand() == 1 + 5*a + 10*a**2 + 10*a**3 + 5*a**4 + a**5
e = (a + b + c)*(a + c + p)
assert e == (5 + a + c)*(a + b + c)
assert e.expand() == 5*a + 5*b + 5*c + 2*a*c + b*c + a*b + a**2 + c**2
x = Symbol("x")
s = exp(x*x) - 1
e = s.nseries(x, 0, 6)/x**2
assert e.expand() == 1 + x**2/2 + O(x**4)
e = (x*(y + z))**(x*(y + z))*(x + y)
assert e.expand(power_exp=False, power_base=False) == x*(x*y + x*
z)**(x*y + x*z) + y*(x*y + x*z)**(x*y + x*z)
assert e.expand(power_exp=False, power_base=False, deep=False) == x* \
(x*(y + z))**(x*(y + z)) + y*(x*(y + z))**(x*(y + z))
e = x * (x + (y + 1)**2)
assert e.expand(deep=False) == x**2 + x*(y + 1)**2
e = (x*(y + z))**z
assert e.expand(power_base=True, mul=True, deep=True) in [x**z*(y +
z)**z, (x*y + x*z)**z]
assert ((2*y)**z).expand() == 2**z*y**z
p = Symbol('p', positive=True)
assert sqrt(-x).expand().is_Pow
assert sqrt(-x).expand(force=True) == I*sqrt(x)
assert ((2*y*p)**z).expand() == 2**z*p**z*y**z
assert ((2*y*p*x)**z).expand() == 2**z*p**z*(x*y)**z
assert ((2*y*p*x)**z).expand(force=True) == 2**z*p**z*x**z*y**z
assert ((2*y*p*-pi)**z).expand() == 2**z*pi**z*p**z*(-y)**z
assert ((2*y*p*-pi*x)**z).expand() == 2**z*pi**z*p**z*(-x*y)**z
n = Symbol('n', negative=True)
m = Symbol('m', negative=True)
assert ((-2*x*y*n)**z).expand() == 2**z*(-n)**z*(x*y)**z
assert ((-2*x*y*n*m)**z).expand() == 2**z*(-m)**z*(-n)**z*(-x*y)**z
# issue 5482
assert sqrt(-2*x*n) == sqrt(2)*sqrt(-n)*sqrt(x)
# issue 5605 (2)
assert (cos(x + y)**2).expand(trig=True) in [
(-sin(x)*sin(y) + cos(x)*cos(y))**2,
sin(x)**2*sin(y)**2 - 2*sin(x)*sin(y)*cos(x)*cos(y) + cos(x)**2*cos(y)**2
]
# Check that this isn't too slow
x = Symbol('x')
W = 1
for i in range(1, 21):
W = W * (x - i)
W = W.expand()
assert W.has(-1672280820*x**15)
def test_expand_mul():
# part of issue 20597
e = Mul(2, 3, evaluate=False)
assert e.expand() == 6
e = Mul(2, 3, 1/x, evaluate = False)
assert e.expand() == 6/x
e = Mul(2, R(1, 3), evaluate=False)
assert e.expand() == R(2, 3)
def test_power_expand():
"""Test for Pow.expand()"""
a = Symbol('a')
b = Symbol('b')
p = (a + b)**2
assert p.expand() == a**2 + b**2 + 2*a*b
p = (1 + 2*(1 + a))**2
assert p.expand() == 9 + 4*(a**2) + 12*a
p = 2**(a + b)
assert p.expand() == 2**a*2**b
A = Symbol('A', commutative=False)
B = Symbol('B', commutative=False)
assert (2**(A + B)).expand() == 2**(A + B)
assert (A**(a + b)).expand() != A**(a + b)
def test_issues_5919_6830():
# issue 5919
n = -1 + 1/x
z = n/x/(-n)**2 - 1/n/x
assert expand(z) == 1/(x**2 - 2*x + 1) - 1/(x - 2 + 1/x) - 1/(-x + 1)
# issue 6830
p = (1 + x)**2
assert expand_multinomial((1 + x*p)**2) == (
x**2*(x**4 + 4*x**3 + 6*x**2 + 4*x + 1) + 2*x*(x**2 + 2*x + 1) + 1)
assert expand_multinomial((1 + (y + x)*p)**2) == (
2*((x + y)*(x**2 + 2*x + 1)) + (x**2 + 2*x*y + y**2)*
(x**4 + 4*x**3 + 6*x**2 + 4*x + 1) + 1)
A = Symbol('A', commutative=False)
p = (1 + A)**2
assert expand_multinomial((1 + x*p)**2) == (
x**2*(1 + 4*A + 6*A**2 + 4*A**3 + A**4) + 2*x*(1 + 2*A + A**2) + 1)
assert expand_multinomial((1 + (y + x)*p)**2) == (
(x + y)*(1 + 2*A + A**2)*2 + (x**2 + 2*x*y + y**2)*
(1 + 4*A + 6*A**2 + 4*A**3 + A**4) + 1)
assert expand_multinomial((1 + (y + x)*p)**3) == (
(x + y)*(1 + 2*A + A**2)*3 + (x**2 + 2*x*y + y**2)*(1 + 4*A +
6*A**2 + 4*A**3 + A**4)*3 + (x**3 + 3*x**2*y + 3*x*y**2 + y**3)*(1 + 6*A
+ 15*A**2 + 20*A**3 + 15*A**4 + 6*A**5 + A**6) + 1)
# unevaluate powers
eq = (Pow((x + 1)*((A + 1)**2), 2, evaluate=False))
# - in this case the base is not an Add so no further
# expansion is done
assert expand_multinomial(eq) == \
(x**2 + 2*x + 1)*(1 + 4*A + 6*A**2 + 4*A**3 + A**4)
# - but here, the expanded base *is* an Add so it gets expanded
eq = (Pow(((A + 1)**2), 2, evaluate=False))
assert expand_multinomial(eq) == 1 + 4*A + 6*A**2 + 4*A**3 + A**4
# coverage
def ok(a, b, n):
e = (a + I*b)**n
return verify_numerically(e, expand_multinomial(e))
for a in [2, S.Half]:
for b in [3, R(1, 3)]:
for n in range(2, 6):
assert ok(a, b, n)
assert expand_multinomial((x + 1 + O(z))**2) == \
1 + 2*x + x**2 + O(z)
assert expand_multinomial((x + 1 + O(z))**3) == \
1 + 3*x + 3*x**2 + x**3 + O(z)
assert expand_multinomial(3**(x + y + 3)) == 27*3**(x + y)
def test_expand_log():
t = Symbol('t', positive=True)
# after first expansion, -2*log(2) + log(4); then 0 after second
assert expand(log(t**2) - log(t**2/4) - 2*log(2)) == 0
def test_issue_23952():
assert (x**(y + z)).expand(force=True) == x**y*x**z
one = Symbol('1', integer=True, prime=True, odd=True, positive=True)
two = Symbol('2', integer=True, prime=True, even=True)
e = two - one
for b in (0, x):
# 0**e = 0, 0**-e = zoo; but if expanded then nan
assert unchanged(Pow, b, e) # power_exp
assert unchanged(Pow, b, -e) # power_exp
assert unchanged(Pow, b, y - x) # power_exp
assert unchanged(Pow, b, 3 - x) # multinomial
assert (b**e).expand().is_Pow # power_exp
assert (b**-e).expand().is_Pow # power_exp
assert (b**(y - x)).expand().is_Pow # power_exp
assert (b**(3 - x)).expand().is_Pow # multinomial
nn1 = Symbol('nn1', nonnegative=True)
nn2 = Symbol('nn2', nonnegative=True)
nn3 = Symbol('nn3', nonnegative=True)
assert (x**(nn1 + nn2)).expand() == x**nn1*x**nn2
assert (x**(-nn1 - nn2)).expand() == x**-nn1*x**-nn2
assert unchanged(Pow, x, nn1 + nn2 - nn3)
assert unchanged(Pow, x, 1 + nn2 - nn3)
assert unchanged(Pow, x, nn1 - nn2)
assert unchanged(Pow, x, 1 - nn2)
assert unchanged(Pow, x, -1 + nn2)
|
2fb7e2df5f73d447856a0ea91fc9b2a83418437d87d7ddd02ca31daa5c400ac6 | """Tests for tools for manipulating of large commutative expressions. """
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.function import Function
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational, oo)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import (root, sqrt)
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.integrals.integrals import Integral
from sympy.series.order import O
from sympy.sets.sets import Interval
from sympy.simplify.radsimp import collect
from sympy.simplify.simplify import simplify
from sympy.core.exprtools import (decompose_power, Factors, Term, _gcd_terms,
gcd_terms, factor_terms, factor_nc, _mask_nc,
_monotonic_sign)
from sympy.core.mul import _keep_coeff as _keep_coeff
from sympy.simplify.cse_opts import sub_pre
from sympy.testing.pytest import raises
from sympy.abc import a, b, t, x, y, z
def test_decompose_power():
assert decompose_power(x) == (x, 1)
assert decompose_power(x**2) == (x, 2)
assert decompose_power(x**(2*y)) == (x**y, 2)
assert decompose_power(x**(2*y/3)) == (x**(y/3), 2)
assert decompose_power(x**(y*Rational(2, 3))) == (x**(y/3), 2)
def test_Factors():
assert Factors() == Factors({}) == Factors(S.One)
assert Factors().as_expr() is S.One
assert Factors({x: 2, y: 3, sin(x): 4}).as_expr() == x**2*y**3*sin(x)**4
assert Factors(S.Infinity) == Factors({oo: 1})
assert Factors(S.NegativeInfinity) == Factors({oo: 1, -1: 1})
# issue #18059:
assert Factors((x**2)**S.Half).as_expr() == (x**2)**S.Half
a = Factors({x: 5, y: 3, z: 7})
b = Factors({ y: 4, z: 3, t: 10})
assert a.mul(b) == a*b == Factors({x: 5, y: 7, z: 10, t: 10})
assert a.div(b) == divmod(a, b) == \
(Factors({x: 5, z: 4}), Factors({y: 1, t: 10}))
assert a.quo(b) == a/b == Factors({x: 5, z: 4})
assert a.rem(b) == a % b == Factors({y: 1, t: 10})
assert a.pow(3) == a**3 == Factors({x: 15, y: 9, z: 21})
assert b.pow(3) == b**3 == Factors({y: 12, z: 9, t: 30})
assert a.gcd(b) == Factors({y: 3, z: 3})
assert a.lcm(b) == Factors({x: 5, y: 4, z: 7, t: 10})
a = Factors({x: 4, y: 7, t: 7})
b = Factors({z: 1, t: 3})
assert a.normal(b) == (Factors({x: 4, y: 7, t: 4}), Factors({z: 1}))
assert Factors(sqrt(2)*x).as_expr() == sqrt(2)*x
assert Factors(-I)*I == Factors()
assert Factors({S.NegativeOne: S(3)})*Factors({S.NegativeOne: S.One, I: S(5)}) == \
Factors(I)
assert Factors(sqrt(I)*I) == Factors(I**(S(3)/2)) == Factors({I: S(3)/2})
assert Factors({I: S(3)/2}).as_expr() == I**(S(3)/2)
assert Factors(S(2)**x).div(S(3)**x) == \
(Factors({S(2): x}), Factors({S(3): x}))
assert Factors(2**(2*x + 2)).div(S(8)) == \
(Factors({S(2): 2*x + 2}), Factors({S(8): S.One}))
# coverage
# /!\ things break if this is not True
assert Factors({S.NegativeOne: Rational(3, 2)}) == Factors({I: S.One, S.NegativeOne: S.One})
assert Factors({I: S.One, S.NegativeOne: Rational(1, 3)}).as_expr() == I*(-1)**Rational(1, 3)
assert Factors(-1.) == Factors({S.NegativeOne: S.One, S(1.): 1})
assert Factors(-2.) == Factors({S.NegativeOne: S.One, S(2.): 1})
assert Factors((-2.)**x) == Factors({S(-2.): x})
assert Factors(S(-2)) == Factors({S.NegativeOne: S.One, S(2): 1})
assert Factors(S.Half) == Factors({S(2): -S.One})
assert Factors(Rational(3, 2)) == Factors({S(3): S.One, S(2): S.NegativeOne})
assert Factors({I: S.One}) == Factors(I)
assert Factors({-1.0: 2, I: 1}) == Factors({S(1.0): 1, I: 1})
assert Factors({S.NegativeOne: Rational(-3, 2)}).as_expr() == I
A = symbols('A', commutative=False)
assert Factors(2*A**2) == Factors({S(2): 1, A**2: 1})
assert Factors(I) == Factors({I: S.One})
assert Factors(x).normal(S(2)) == (Factors(x), Factors(S(2)))
assert Factors(x).normal(S.Zero) == (Factors(), Factors(S.Zero))
raises(ZeroDivisionError, lambda: Factors(x).div(S.Zero))
assert Factors(x).mul(S(2)) == Factors(2*x)
assert Factors(x).mul(S.Zero).is_zero
assert Factors(x).mul(1/x).is_one
assert Factors(x**sqrt(2)**3).as_expr() == x**(2*sqrt(2))
assert Factors(x)**Factors(S(2)) == Factors(x**2)
assert Factors(x).gcd(S.Zero) == Factors(x)
assert Factors(x).lcm(S.Zero).is_zero
assert Factors(S.Zero).div(x) == (Factors(S.Zero), Factors())
assert Factors(x).div(x) == (Factors(), Factors())
assert Factors({x: .2})/Factors({x: .2}) == Factors()
assert Factors(x) != Factors()
assert Factors(S.Zero).normal(x) == (Factors(S.Zero), Factors())
n, d = x**(2 + y), x**2
f = Factors(n)
assert f.div(d) == f.normal(d) == (Factors(x**y), Factors())
assert f.gcd(d) == Factors()
d = x**y
assert f.div(d) == f.normal(d) == (Factors(x**2), Factors())
assert f.gcd(d) == Factors(d)
n = d = 2**x
f = Factors(n)
assert f.div(d) == f.normal(d) == (Factors(), Factors())
assert f.gcd(d) == Factors(d)
n, d = 2**x, 2**y
f = Factors(n)
assert f.div(d) == f.normal(d) == (Factors({S(2): x}), Factors({S(2): y}))
assert f.gcd(d) == Factors()
# extraction of constant only
n = x**(x + 3)
assert Factors(n).normal(x**-3) == (Factors({x: x + 6}), Factors({}))
assert Factors(n).normal(x**3) == (Factors({x: x}), Factors({}))
assert Factors(n).normal(x**4) == (Factors({x: x}), Factors({x: 1}))
assert Factors(n).normal(x**(y - 3)) == \
(Factors({x: x + 6}), Factors({x: y}))
assert Factors(n).normal(x**(y + 3)) == (Factors({x: x}), Factors({x: y}))
assert Factors(n).normal(x**(y + 4)) == \
(Factors({x: x}), Factors({x: y + 1}))
assert Factors(n).div(x**-3) == (Factors({x: x + 6}), Factors({}))
assert Factors(n).div(x**3) == (Factors({x: x}), Factors({}))
assert Factors(n).div(x**4) == (Factors({x: x}), Factors({x: 1}))
assert Factors(n).div(x**(y - 3)) == \
(Factors({x: x + 6}), Factors({x: y}))
assert Factors(n).div(x**(y + 3)) == (Factors({x: x}), Factors({x: y}))
assert Factors(n).div(x**(y + 4)) == \
(Factors({x: x}), Factors({x: y + 1}))
assert Factors(3 * x / 2) == Factors({3: 1, 2: -1, x: 1})
assert Factors(x * x / y) == Factors({x: 2, y: -1})
assert Factors(27 * x / y**9) == Factors({27: 1, x: 1, y: -9})
def test_Term():
a = Term(4*x*y**2/z/t**3)
b = Term(2*x**3*y**5/t**3)
assert a == Term(4, Factors({x: 1, y: 2}), Factors({z: 1, t: 3}))
assert b == Term(2, Factors({x: 3, y: 5}), Factors({t: 3}))
assert a.as_expr() == 4*x*y**2/z/t**3
assert b.as_expr() == 2*x**3*y**5/t**3
assert a.inv() == \
Term(S.One/4, Factors({z: 1, t: 3}), Factors({x: 1, y: 2}))
assert b.inv() == Term(S.Half, Factors({t: 3}), Factors({x: 3, y: 5}))
assert a.mul(b) == a*b == \
Term(8, Factors({x: 4, y: 7}), Factors({z: 1, t: 6}))
assert a.quo(b) == a/b == Term(2, Factors({}), Factors({x: 2, y: 3, z: 1}))
assert a.pow(3) == a**3 == \
Term(64, Factors({x: 3, y: 6}), Factors({z: 3, t: 9}))
assert b.pow(3) == b**3 == Term(8, Factors({x: 9, y: 15}), Factors({t: 9}))
assert a.pow(-3) == a**(-3) == \
Term(S.One/64, Factors({z: 3, t: 9}), Factors({x: 3, y: 6}))
assert b.pow(-3) == b**(-3) == \
Term(S.One/8, Factors({t: 9}), Factors({x: 9, y: 15}))
assert a.gcd(b) == Term(2, Factors({x: 1, y: 2}), Factors({t: 3}))
assert a.lcm(b) == Term(4, Factors({x: 3, y: 5}), Factors({z: 1, t: 3}))
a = Term(4*x*y**2/z/t**3)
b = Term(2*x**3*y**5*t**7)
assert a.mul(b) == Term(8, Factors({x: 4, y: 7, t: 4}), Factors({z: 1}))
assert Term((2*x + 2)**3) == Term(8, Factors({x + 1: 3}), Factors({}))
assert Term((2*x + 2)*(3*x + 6)**2) == \
Term(18, Factors({x + 1: 1, x + 2: 2}), Factors({}))
def test_gcd_terms():
f = 2*(x + 1)*(x + 4)/(5*x**2 + 5) + (2*x + 2)*(x + 5)/(x**2 + 1)/5 + \
(2*x + 2)*(x + 6)/(5*x**2 + 5)
assert _gcd_terms(f) == ((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1)
assert _gcd_terms(Add.make_args(f)) == \
((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1)
newf = (Rational(6, 5))*((1 + x)*(5 + x)/(1 + x**2))
assert gcd_terms(f) == newf
args = Add.make_args(f)
# non-Basic sequences of terms treated as terms of Add
assert gcd_terms(list(args)) == newf
assert gcd_terms(tuple(args)) == newf
assert gcd_terms(set(args)) == newf
# but a Basic sequence is treated as a container
assert gcd_terms(Tuple(*args)) != newf
assert gcd_terms(Basic(Tuple(S(1), 3*y + 3*x*y), Tuple(S(1), S(3)))) == \
Basic(Tuple(S(1), 3*y*(x + 1)), Tuple(S(1), S(3)))
# but we shouldn't change keys of a dictionary or some may be lost
assert gcd_terms(Dict((x*(1 + y), S(2)), (x + x*y, y + x*y))) == \
Dict({x*(y + 1): S(2), x + x*y: y*(1 + x)})
assert gcd_terms((2*x + 2)**3 + (2*x + 2)**2) == 4*(x + 1)**2*(2*x + 3)
assert gcd_terms(0) == 0
assert gcd_terms(1) == 1
assert gcd_terms(x) == x
assert gcd_terms(2 + 2*x) == Mul(2, 1 + x, evaluate=False)
arg = x*(2*x + 4*y)
garg = 2*x*(x + 2*y)
assert gcd_terms(arg) == garg
assert gcd_terms(sin(arg)) == sin(garg)
# issue 6139-like
alpha, alpha1, alpha2, alpha3 = symbols('alpha:4')
a = alpha**2 - alpha*x**2 + alpha + x**3 - x*(alpha + 1)
rep = (alpha, (1 + sqrt(5))/2 + alpha1*x + alpha2*x**2 + alpha3*x**3)
s = (a/(x - alpha)).subs(*rep).series(x, 0, 1)
assert simplify(collect(s, x)) == -sqrt(5)/2 - Rational(3, 2) + O(x)
# issue 5917
assert _gcd_terms([S.Zero, S.Zero]) == (0, 0, 1)
assert _gcd_terms([2*x + 4]) == (2, x + 2, 1)
eq = x/(x + 1/x)
assert gcd_terms(eq, fraction=False) == eq
eq = x/2/y + 1/x/y
assert gcd_terms(eq, fraction=True, clear=True) == \
(x**2 + 2)/(2*x*y)
assert gcd_terms(eq, fraction=True, clear=False) == \
(x**2/2 + 1)/(x*y)
assert gcd_terms(eq, fraction=False, clear=True) == \
(x + 2/x)/(2*y)
assert gcd_terms(eq, fraction=False, clear=False) == \
(x/2 + 1/x)/y
def test_factor_terms():
A = Symbol('A', commutative=False)
assert factor_terms(9*(x + x*y + 1) + (3*x + 3)**(2 + 2*x)) == \
9*x*y + 9*x + _keep_coeff(S(3), x + 1)**_keep_coeff(S(2), x + 1) + 9
assert factor_terms(9*(x + x*y + 1) + (3)**(2 + 2*x)) == \
_keep_coeff(S(9), 3**(2*x) + x*y + x + 1)
assert factor_terms(3**(2 + 2*x) + a*3**(2 + 2*x)) == \
9*3**(2*x)*(a + 1)
assert factor_terms(x + x*A) == \
x*(1 + A)
assert factor_terms(sin(x + x*A)) == \
sin(x*(1 + A))
assert factor_terms((3*x + 3)**((2 + 2*x)/3)) == \
_keep_coeff(S(3), x + 1)**_keep_coeff(Rational(2, 3), x + 1)
assert factor_terms(x + (x*y + x)**(3*x + 3)) == \
x + (x*(y + 1))**_keep_coeff(S(3), x + 1)
assert factor_terms(a*(x + x*y) + b*(x*2 + y*x*2)) == \
x*(a + 2*b)*(y + 1)
i = Integral(x, (x, 0, oo))
assert factor_terms(i) == i
assert factor_terms(x/2 + y) == x/2 + y
# fraction doesn't apply to integer denominators
assert factor_terms(x/2 + y, fraction=True) == x/2 + y
# clear *does* apply to the integer denominators
assert factor_terms(x/2 + y, clear=True) == Mul(S.Half, x + 2*y, evaluate=False)
# check radical extraction
eq = sqrt(2) + sqrt(10)
assert factor_terms(eq) == eq
assert factor_terms(eq, radical=True) == sqrt(2)*(1 + sqrt(5))
eq = root(-6, 3) + root(6, 3)
assert factor_terms(eq, radical=True) == 6**(S.One/3)*(1 + (-1)**(S.One/3))
eq = [x + x*y]
ans = [x*(y + 1)]
for c in [list, tuple, set]:
assert factor_terms(c(eq)) == c(ans)
assert factor_terms(Tuple(x + x*y)) == Tuple(x*(y + 1))
assert factor_terms(Interval(0, 1)) == Interval(0, 1)
e = 1/sqrt(a/2 + 1)
assert factor_terms(e, clear=False) == 1/sqrt(a/2 + 1)
assert factor_terms(e, clear=True) == sqrt(2)/sqrt(a + 2)
eq = x/(x + 1/x) + 1/(x**2 + 1)
assert factor_terms(eq, fraction=False) == eq
assert factor_terms(eq, fraction=True) == 1
assert factor_terms((1/(x**3 + x**2) + 2/x**2)*y) == \
y*(2 + 1/(x + 1))/x**2
# if not True, then processesing for this in factor_terms is not necessary
assert gcd_terms(-x - y) == -x - y
assert factor_terms(-x - y) == Mul(-1, x + y, evaluate=False)
# if not True, then "special" processesing in factor_terms is not necessary
assert gcd_terms(exp(Mul(-1, x + 1))) == exp(-x - 1)
e = exp(-x - 2) + x
assert factor_terms(e) == exp(Mul(-1, x + 2, evaluate=False)) + x
assert factor_terms(e, sign=False) == e
assert factor_terms(exp(-4*x - 2) - x) == -x + exp(Mul(-2, 2*x + 1, evaluate=False))
# sum/integral tests
for F in (Sum, Integral):
assert factor_terms(F(x, (y, 1, 10))) == x * F(1, (y, 1, 10))
assert factor_terms(F(x, (y, 1, 10)) + x) == x * (1 + F(1, (y, 1, 10)))
assert factor_terms(F(x*y + x*y**2, (y, 1, 10))) == x*F(y*(y + 1), (y, 1, 10))
# expressions involving Pow terms with base 0
assert factor_terms(0**(x - 2) - 1) == 0**(x - 2) - 1
assert factor_terms(0**(x + 2) - 1) == 0**(x + 2) - 1
assert factor_terms((0**(x + 2) - 1).subs(x,-2)) == 0
def test_xreplace():
e = Mul(2, 1 + x, evaluate=False)
assert e.xreplace({}) == e
assert e.xreplace({y: x}) == e
def test_factor_nc():
x, y = symbols('x,y')
k = symbols('k', integer=True)
n, m, o = symbols('n,m,o', commutative=False)
# mul and multinomial expansion is needed
from sympy.core.function import _mexpand
e = x*(1 + y)**2
assert _mexpand(e) == x + x*2*y + x*y**2
def factor_nc_test(e):
ex = _mexpand(e)
assert ex.is_Add
f = factor_nc(ex)
assert not f.is_Add and _mexpand(f) == ex
factor_nc_test(x*(1 + y))
factor_nc_test(n*(x + 1))
factor_nc_test(n*(x + m))
factor_nc_test((x + m)*n)
factor_nc_test(n*m*(x*o + n*o*m)*n)
s = Sum(x, (x, 1, 2))
factor_nc_test(x*(1 + s))
factor_nc_test(x*(1 + s)*s)
factor_nc_test(x*(1 + sin(s)))
factor_nc_test((1 + n)**2)
factor_nc_test((x + n)*(x + m)*(x + y))
factor_nc_test(x*(n*m + 1))
factor_nc_test(x*(n*m + x))
factor_nc_test(x*(x*n*m + 1))
factor_nc_test(n*(m/x + o))
factor_nc_test(m*(n + o/2))
factor_nc_test(x*n*(x*m + 1))
factor_nc_test(x*(m*n + x*n*m))
factor_nc_test(n*(1 - m)*n**2)
factor_nc_test((n + m)**2)
factor_nc_test((n - m)*(n + m)**2)
factor_nc_test((n + m)**2*(n - m))
factor_nc_test((m - n)*(n + m)**2*(n - m))
assert factor_nc(n*(n + n*m)) == n**2*(1 + m)
assert factor_nc(m*(m*n + n*m*n**2)) == m*(m + n*m*n)*n
eq = m*sin(n) - sin(n)*m
assert factor_nc(eq) == eq
# for coverage:
from sympy.physics.secondquant import Commutator
from sympy.polys.polytools import factor
eq = 1 + x*Commutator(m, n)
assert factor_nc(eq) == eq
eq = x*Commutator(m, n) + x*Commutator(m, o)*Commutator(m, n)
assert factor(eq) == x*(1 + Commutator(m, o))*Commutator(m, n)
# issue 6534
assert (2*n + 2*m).factor() == 2*(n + m)
# issue 6701
_n = symbols('nz', zero=False, commutative=False)
assert factor_nc(_n**k + _n**(k + 1)) == _n**k*(1 + _n)
assert factor_nc((m*n)**k + (m*n)**(k + 1)) == (1 + m*n)*(m*n)**k
# issue 6918
assert factor_nc(-n*(2*x**2 + 2*x)) == -2*n*x*(x + 1)
def test_issue_6360():
a, b = symbols("a b")
apb = a + b
eq = apb + apb**2*(-2*a - 2*b)
assert factor_terms(sub_pre(eq)) == a + b - 2*(a + b)**3
def test_issue_7903():
a = symbols(r'a', real=True)
t = exp(I*cos(a)) + exp(-I*sin(a))
assert t.simplify()
def test_issue_8263():
F, G = symbols('F, G', commutative=False, cls=Function)
x, y = symbols('x, y')
expr, dummies, _ = _mask_nc(F(x)*G(y) - G(y)*F(x))
for v in dummies.values():
assert not v.is_commutative
assert not expr.is_zero
def test_monotonic_sign():
F = _monotonic_sign
x = symbols('x')
assert F(x) is None
assert F(-x) is None
assert F(Dummy(prime=True)) == 2
assert F(Dummy(prime=True, odd=True)) == 3
assert F(Dummy(composite=True)) == 4
assert F(Dummy(composite=True, odd=True)) == 9
assert F(Dummy(positive=True, integer=True)) == 1
assert F(Dummy(positive=True, even=True)) == 2
assert F(Dummy(positive=True, even=True, prime=False)) == 4
assert F(Dummy(negative=True, integer=True)) == -1
assert F(Dummy(negative=True, even=True)) == -2
assert F(Dummy(zero=True)) == 0
assert F(Dummy(nonnegative=True)) == 0
assert F(Dummy(nonpositive=True)) == 0
assert F(Dummy(positive=True) + 1).is_positive
assert F(Dummy(positive=True, integer=True) - 1).is_nonnegative
assert F(Dummy(positive=True) - 1) is None
assert F(Dummy(negative=True) + 1) is None
assert F(Dummy(negative=True, integer=True) - 1).is_nonpositive
assert F(Dummy(negative=True) - 1).is_negative
assert F(-Dummy(positive=True) + 1) is None
assert F(-Dummy(positive=True, integer=True) - 1).is_negative
assert F(-Dummy(positive=True) - 1).is_negative
assert F(-Dummy(negative=True) + 1).is_positive
assert F(-Dummy(negative=True, integer=True) - 1).is_nonnegative
assert F(-Dummy(negative=True) - 1) is None
x = Dummy(negative=True)
assert F(x**3).is_nonpositive
assert F(x**3 + log(2)*x - 1).is_negative
x = Dummy(positive=True)
assert F(-x**3).is_nonpositive
p = Dummy(positive=True)
assert F(1/p).is_positive
assert F(p/(p + 1)).is_positive
p = Dummy(nonnegative=True)
assert F(p/(p + 1)).is_nonnegative
p = Dummy(positive=True)
assert F(-1/p).is_negative
p = Dummy(nonpositive=True)
assert F(p/(-p + 1)).is_nonpositive
p = Dummy(positive=True, integer=True)
q = Dummy(positive=True, integer=True)
assert F(-2/p/q).is_negative
assert F(-2/(p - 1)/q) is None
assert F((p - 1)*q + 1).is_positive
assert F(-(p - 1)*q - 1).is_negative
def test_issue_17256():
from sympy.sets.fancysets import Range
x = Symbol('x')
s1 = Sum(x + 1, (x, 1, 9))
s2 = Sum(x + 1, (x, Range(1, 10)))
a = Symbol('a')
r1 = s1.xreplace({x:a})
r2 = s2.xreplace({x:a})
assert r1.doit() == r2.doit()
s1 = Sum(x + 1, (x, 0, 9))
s2 = Sum(x + 1, (x, Range(10)))
a = Symbol('a')
r1 = s1.xreplace({x:a})
r2 = s2.xreplace({x:a})
assert r1 == r2
def test_issue_21623():
from sympy.matrices.expressions.matexpr import MatrixSymbol
M = MatrixSymbol('X', 2, 2)
assert gcd_terms(M[0,0], 1) == M[0,0]
|
bd4866c0356b5ee3d973ffae248357f2b74709e14f8645eabcde94e3f7d8091c | from sympy.core.mod import Mod
from sympy.core.numbers import (I, oo, pi)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (asin, sin)
from sympy.simplify.simplify import simplify
from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow
from sympy.core.assumptions import (assumptions, check_assumptions,
failing_assumptions, common_assumptions, _generate_assumption_rules,
_load_pre_generated_assumption_rules)
from sympy.core.facts import InconsistentAssumptions
from sympy.testing.pytest import raises, XFAIL
def test_symbol_unset():
x = Symbol('x', real=True, integer=True)
assert x.is_real is True
assert x.is_integer is True
assert x.is_imaginary is False
assert x.is_noninteger is False
assert x.is_number is False
def test_zero():
z = Integer(0)
assert z.is_commutative is True
assert z.is_integer is True
assert z.is_rational is True
assert z.is_algebraic is True
assert z.is_transcendental is False
assert z.is_real is True
assert z.is_complex is True
assert z.is_noninteger is False
assert z.is_irrational is False
assert z.is_imaginary is False
assert z.is_positive is False
assert z.is_negative is False
assert z.is_nonpositive is True
assert z.is_nonnegative is True
assert z.is_even is True
assert z.is_odd is False
assert z.is_finite is True
assert z.is_infinite is False
assert z.is_comparable is True
assert z.is_prime is False
assert z.is_composite is False
assert z.is_number is True
def test_one():
z = Integer(1)
assert z.is_commutative is True
assert z.is_integer is True
assert z.is_rational is True
assert z.is_algebraic is True
assert z.is_transcendental is False
assert z.is_real is True
assert z.is_complex is True
assert z.is_noninteger is False
assert z.is_irrational is False
assert z.is_imaginary is False
assert z.is_positive is True
assert z.is_negative is False
assert z.is_nonpositive is False
assert z.is_nonnegative is True
assert z.is_even is False
assert z.is_odd is True
assert z.is_finite is True
assert z.is_infinite is False
assert z.is_comparable is True
assert z.is_prime is False
assert z.is_number is True
assert z.is_composite is False # issue 8807
def test_negativeone():
z = Integer(-1)
assert z.is_commutative is True
assert z.is_integer is True
assert z.is_rational is True
assert z.is_algebraic is True
assert z.is_transcendental is False
assert z.is_real is True
assert z.is_complex is True
assert z.is_noninteger is False
assert z.is_irrational is False
assert z.is_imaginary is False
assert z.is_positive is False
assert z.is_negative is True
assert z.is_nonpositive is True
assert z.is_nonnegative is False
assert z.is_even is False
assert z.is_odd is True
assert z.is_finite is True
assert z.is_infinite is False
assert z.is_comparable is True
assert z.is_prime is False
assert z.is_composite is False
assert z.is_number is True
def test_infinity():
oo = S.Infinity
assert oo.is_commutative is True
assert oo.is_integer is False
assert oo.is_rational is False
assert oo.is_algebraic is False
assert oo.is_transcendental is False
assert oo.is_extended_real is True
assert oo.is_real is False
assert oo.is_complex is False
assert oo.is_noninteger is True
assert oo.is_irrational is False
assert oo.is_imaginary is False
assert oo.is_nonzero is False
assert oo.is_positive is False
assert oo.is_negative is False
assert oo.is_nonpositive is False
assert oo.is_nonnegative is False
assert oo.is_extended_nonzero is True
assert oo.is_extended_positive is True
assert oo.is_extended_negative is False
assert oo.is_extended_nonpositive is False
assert oo.is_extended_nonnegative is True
assert oo.is_even is False
assert oo.is_odd is False
assert oo.is_finite is False
assert oo.is_infinite is True
assert oo.is_comparable is True
assert oo.is_prime is False
assert oo.is_composite is False
assert oo.is_number is True
def test_neg_infinity():
mm = S.NegativeInfinity
assert mm.is_commutative is True
assert mm.is_integer is False
assert mm.is_rational is False
assert mm.is_algebraic is False
assert mm.is_transcendental is False
assert mm.is_extended_real is True
assert mm.is_real is False
assert mm.is_complex is False
assert mm.is_noninteger is True
assert mm.is_irrational is False
assert mm.is_imaginary is False
assert mm.is_nonzero is False
assert mm.is_positive is False
assert mm.is_negative is False
assert mm.is_nonpositive is False
assert mm.is_nonnegative is False
assert mm.is_extended_nonzero is True
assert mm.is_extended_positive is False
assert mm.is_extended_negative is True
assert mm.is_extended_nonpositive is True
assert mm.is_extended_nonnegative is False
assert mm.is_even is False
assert mm.is_odd is False
assert mm.is_finite is False
assert mm.is_infinite is True
assert mm.is_comparable is True
assert mm.is_prime is False
assert mm.is_composite is False
assert mm.is_number is True
def test_zoo():
zoo = S.ComplexInfinity
assert zoo.is_complex is False
assert zoo.is_real is False
assert zoo.is_prime is False
def test_nan():
nan = S.NaN
assert nan.is_commutative is True
assert nan.is_integer is None
assert nan.is_rational is None
assert nan.is_algebraic is None
assert nan.is_transcendental is None
assert nan.is_real is None
assert nan.is_complex is None
assert nan.is_noninteger is None
assert nan.is_irrational is None
assert nan.is_imaginary is None
assert nan.is_positive is None
assert nan.is_negative is None
assert nan.is_nonpositive is None
assert nan.is_nonnegative is None
assert nan.is_even is None
assert nan.is_odd is None
assert nan.is_finite is None
assert nan.is_infinite is None
assert nan.is_comparable is False
assert nan.is_prime is None
assert nan.is_composite is None
assert nan.is_number is True
def test_pos_rational():
r = Rational(3, 4)
assert r.is_commutative is True
assert r.is_integer is False
assert r.is_rational is True
assert r.is_algebraic is True
assert r.is_transcendental is False
assert r.is_real is True
assert r.is_complex is True
assert r.is_noninteger is True
assert r.is_irrational is False
assert r.is_imaginary is False
assert r.is_positive is True
assert r.is_negative is False
assert r.is_nonpositive is False
assert r.is_nonnegative is True
assert r.is_even is False
assert r.is_odd is False
assert r.is_finite is True
assert r.is_infinite is False
assert r.is_comparable is True
assert r.is_prime is False
assert r.is_composite is False
r = Rational(1, 4)
assert r.is_nonpositive is False
assert r.is_positive is True
assert r.is_negative is False
assert r.is_nonnegative is True
r = Rational(5, 4)
assert r.is_negative is False
assert r.is_positive is True
assert r.is_nonpositive is False
assert r.is_nonnegative is True
r = Rational(5, 3)
assert r.is_nonnegative is True
assert r.is_positive is True
assert r.is_negative is False
assert r.is_nonpositive is False
def test_neg_rational():
r = Rational(-3, 4)
assert r.is_positive is False
assert r.is_nonpositive is True
assert r.is_negative is True
assert r.is_nonnegative is False
r = Rational(-1, 4)
assert r.is_nonpositive is True
assert r.is_positive is False
assert r.is_negative is True
assert r.is_nonnegative is False
r = Rational(-5, 4)
assert r.is_negative is True
assert r.is_positive is False
assert r.is_nonpositive is True
assert r.is_nonnegative is False
r = Rational(-5, 3)
assert r.is_nonnegative is False
assert r.is_positive is False
assert r.is_negative is True
assert r.is_nonpositive is True
def test_pi():
z = S.Pi
assert z.is_commutative is True
assert z.is_integer is False
assert z.is_rational is False
assert z.is_algebraic is False
assert z.is_transcendental is True
assert z.is_real is True
assert z.is_complex is True
assert z.is_noninteger is True
assert z.is_irrational is True
assert z.is_imaginary is False
assert z.is_positive is True
assert z.is_negative is False
assert z.is_nonpositive is False
assert z.is_nonnegative is True
assert z.is_even is False
assert z.is_odd is False
assert z.is_finite is True
assert z.is_infinite is False
assert z.is_comparable is True
assert z.is_prime is False
assert z.is_composite is False
def test_E():
z = S.Exp1
assert z.is_commutative is True
assert z.is_integer is False
assert z.is_rational is False
assert z.is_algebraic is False
assert z.is_transcendental is True
assert z.is_real is True
assert z.is_complex is True
assert z.is_noninteger is True
assert z.is_irrational is True
assert z.is_imaginary is False
assert z.is_positive is True
assert z.is_negative is False
assert z.is_nonpositive is False
assert z.is_nonnegative is True
assert z.is_even is False
assert z.is_odd is False
assert z.is_finite is True
assert z.is_infinite is False
assert z.is_comparable is True
assert z.is_prime is False
assert z.is_composite is False
def test_I():
z = S.ImaginaryUnit
assert z.is_commutative is True
assert z.is_integer is False
assert z.is_rational is False
assert z.is_algebraic is True
assert z.is_transcendental is False
assert z.is_real is False
assert z.is_complex is True
assert z.is_noninteger is False
assert z.is_irrational is False
assert z.is_imaginary is True
assert z.is_positive is False
assert z.is_negative is False
assert z.is_nonpositive is False
assert z.is_nonnegative is False
assert z.is_even is False
assert z.is_odd is False
assert z.is_finite is True
assert z.is_infinite is False
assert z.is_comparable is False
assert z.is_prime is False
assert z.is_composite is False
def test_symbol_real_false():
# issue 3848
a = Symbol('a', real=False)
assert a.is_real is False
assert a.is_integer is False
assert a.is_zero is False
assert a.is_negative is False
assert a.is_positive is False
assert a.is_nonnegative is False
assert a.is_nonpositive is False
assert a.is_nonzero is False
assert a.is_extended_negative is None
assert a.is_extended_positive is None
assert a.is_extended_nonnegative is None
assert a.is_extended_nonpositive is None
assert a.is_extended_nonzero is None
def test_symbol_extended_real_false():
# issue 3848
a = Symbol('a', extended_real=False)
assert a.is_real is False
assert a.is_integer is False
assert a.is_zero is False
assert a.is_negative is False
assert a.is_positive is False
assert a.is_nonnegative is False
assert a.is_nonpositive is False
assert a.is_nonzero is False
assert a.is_extended_negative is False
assert a.is_extended_positive is False
assert a.is_extended_nonnegative is False
assert a.is_extended_nonpositive is False
assert a.is_extended_nonzero is False
def test_symbol_imaginary():
a = Symbol('a', imaginary=True)
assert a.is_real is False
assert a.is_integer is False
assert a.is_negative is False
assert a.is_positive is False
assert a.is_nonnegative is False
assert a.is_nonpositive is False
assert a.is_zero is False
assert a.is_nonzero is False # since nonzero -> real
def test_symbol_zero():
x = Symbol('x', zero=True)
assert x.is_positive is False
assert x.is_nonpositive
assert x.is_negative is False
assert x.is_nonnegative
assert x.is_zero is True
# TODO Change to x.is_nonzero is None
# See https://github.com/sympy/sympy/pull/9583
assert x.is_nonzero is False
assert x.is_finite is True
def test_symbol_positive():
x = Symbol('x', positive=True)
assert x.is_positive is True
assert x.is_nonpositive is False
assert x.is_negative is False
assert x.is_nonnegative is True
assert x.is_zero is False
assert x.is_nonzero is True
def test_neg_symbol_positive():
x = -Symbol('x', positive=True)
assert x.is_positive is False
assert x.is_nonpositive is True
assert x.is_negative is True
assert x.is_nonnegative is False
assert x.is_zero is False
assert x.is_nonzero is True
def test_symbol_nonpositive():
x = Symbol('x', nonpositive=True)
assert x.is_positive is False
assert x.is_nonpositive is True
assert x.is_negative is None
assert x.is_nonnegative is None
assert x.is_zero is None
assert x.is_nonzero is None
def test_neg_symbol_nonpositive():
x = -Symbol('x', nonpositive=True)
assert x.is_positive is None
assert x.is_nonpositive is None
assert x.is_negative is False
assert x.is_nonnegative is True
assert x.is_zero is None
assert x.is_nonzero is None
def test_symbol_falsepositive():
x = Symbol('x', positive=False)
assert x.is_positive is False
assert x.is_nonpositive is None
assert x.is_negative is None
assert x.is_nonnegative is None
assert x.is_zero is None
assert x.is_nonzero is None
def test_symbol_falsepositive_mul():
# To test pull request 9379
# Explicit handling of arg.is_positive=False was added to Mul._eval_is_positive
x = 2*Symbol('x', positive=False)
assert x.is_positive is False # This was None before
assert x.is_nonpositive is None
assert x.is_negative is None
assert x.is_nonnegative is None
assert x.is_zero is None
assert x.is_nonzero is None
@XFAIL
def test_symbol_infinitereal_mul():
ix = Symbol('ix', infinite=True, extended_real=True)
assert (-ix).is_extended_positive is None
def test_neg_symbol_falsepositive():
x = -Symbol('x', positive=False)
assert x.is_positive is None
assert x.is_nonpositive is None
assert x.is_negative is False
assert x.is_nonnegative is None
assert x.is_zero is None
assert x.is_nonzero is None
def test_neg_symbol_falsenegative():
# To test pull request 9379
# Explicit handling of arg.is_negative=False was added to Mul._eval_is_positive
x = -Symbol('x', negative=False)
assert x.is_positive is False # This was None before
assert x.is_nonpositive is None
assert x.is_negative is None
assert x.is_nonnegative is None
assert x.is_zero is None
assert x.is_nonzero is None
def test_symbol_falsepositive_real():
x = Symbol('x', positive=False, real=True)
assert x.is_positive is False
assert x.is_nonpositive is True
assert x.is_negative is None
assert x.is_nonnegative is None
assert x.is_zero is None
assert x.is_nonzero is None
def test_neg_symbol_falsepositive_real():
x = -Symbol('x', positive=False, real=True)
assert x.is_positive is None
assert x.is_nonpositive is None
assert x.is_negative is False
assert x.is_nonnegative is True
assert x.is_zero is None
assert x.is_nonzero is None
def test_symbol_falsenonnegative():
x = Symbol('x', nonnegative=False)
assert x.is_positive is False
assert x.is_nonpositive is None
assert x.is_negative is None
assert x.is_nonnegative is False
assert x.is_zero is False
assert x.is_nonzero is None
@XFAIL
def test_neg_symbol_falsenonnegative():
x = -Symbol('x', nonnegative=False)
assert x.is_positive is None
assert x.is_nonpositive is False # this currently returns None
assert x.is_negative is False # this currently returns None
assert x.is_nonnegative is None
assert x.is_zero is False # this currently returns None
assert x.is_nonzero is True # this currently returns None
def test_symbol_falsenonnegative_real():
x = Symbol('x', nonnegative=False, real=True)
assert x.is_positive is False
assert x.is_nonpositive is True
assert x.is_negative is True
assert x.is_nonnegative is False
assert x.is_zero is False
assert x.is_nonzero is True
def test_neg_symbol_falsenonnegative_real():
x = -Symbol('x', nonnegative=False, real=True)
assert x.is_positive is True
assert x.is_nonpositive is False
assert x.is_negative is False
assert x.is_nonnegative is True
assert x.is_zero is False
assert x.is_nonzero is True
def test_prime():
assert S.NegativeOne.is_prime is False
assert S(-2).is_prime is False
assert S(-4).is_prime is False
assert S.Zero.is_prime is False
assert S.One.is_prime is False
assert S(2).is_prime is True
assert S(17).is_prime is True
assert S(4).is_prime is False
def test_composite():
assert S.NegativeOne.is_composite is False
assert S(-2).is_composite is False
assert S(-4).is_composite is False
assert S.Zero.is_composite is False
assert S(2).is_composite is False
assert S(17).is_composite is False
assert S(4).is_composite is True
x = Dummy(integer=True, positive=True, prime=False)
assert x.is_composite is None # x could be 1
assert (x + 1).is_composite is None
x = Dummy(positive=True, even=True, prime=False)
assert x.is_integer is True
assert x.is_composite is True
def test_prime_symbol():
x = Symbol('x', prime=True)
assert x.is_prime is True
assert x.is_integer is True
assert x.is_positive is True
assert x.is_negative is False
assert x.is_nonpositive is False
assert x.is_nonnegative is True
x = Symbol('x', prime=False)
assert x.is_prime is False
assert x.is_integer is None
assert x.is_positive is None
assert x.is_negative is None
assert x.is_nonpositive is None
assert x.is_nonnegative is None
def test_symbol_noncommutative():
x = Symbol('x', commutative=True)
assert x.is_complex is None
x = Symbol('x', commutative=False)
assert x.is_integer is False
assert x.is_rational is False
assert x.is_algebraic is False
assert x.is_irrational is False
assert x.is_real is False
assert x.is_complex is False
def test_other_symbol():
x = Symbol('x', integer=True)
assert x.is_integer is True
assert x.is_real is True
assert x.is_finite 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
assert x.is_finite is True
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
assert x.is_finite is True
x = Symbol('x', odd=True)
assert x.is_odd is True
assert x.is_even is False
assert x.is_integer is True
assert x.is_finite 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
assert x.is_finite 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
assert x.is_finite 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
assert x.is_finite is None
x = Symbol('x', integer=True, nonnegative=True)
assert x.is_integer is True
assert x.is_nonnegative is True
assert x.is_finite is True
x = Symbol('x', integer=True, nonpositive=True)
assert x.is_integer is True
assert x.is_nonpositive is True
assert x.is_finite is True
x = Symbol('x', rational=True)
assert x.is_real is True
assert x.is_finite is True
x = Symbol('x', rational=False)
assert x.is_real is None
assert x.is_finite is None
x = Symbol('x', irrational=True)
assert x.is_real is True
assert x.is_finite is True
x = Symbol('x', irrational=False)
assert x.is_real is None
assert x.is_finite is None
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
def test_issue_3825():
"""catch: hash instability"""
x = Symbol("x")
y = Symbol("y")
a1 = x + y
a2 = y + x
a2.is_comparable
h1 = hash(a1)
h2 = hash(a2)
assert h1 == h2
def test_issue_4822():
z = (-1)**Rational(1, 3)*(1 - I*sqrt(3))
assert z.is_real in [True, None]
def test_hash_vs_typeinfo():
"""seemingly different typeinfo, but in fact equal"""
# the following two are semantically equal
x1 = Symbol('x', even=True)
x2 = Symbol('x', integer=True, odd=False)
assert hash(x1) == hash(x2)
assert x1 == x2
def test_hash_vs_typeinfo_2():
"""different typeinfo should mean !eq"""
# the following two are semantically different
x = Symbol('x')
x1 = Symbol('x', even=True)
assert x != x1
assert hash(x) != hash(x1) # This might fail with very low probability
def test_hash_vs_eq():
"""catch: different hash for equal objects"""
a = 1 + S.Pi # important: do not fold it into a Number instance
ha = hash(a) # it should be Add/Mul/... to trigger the bug
a.is_positive # this uses .evalf() and deduces it is positive
assert a.is_positive is True
# be sure that hash stayed the same
assert ha == hash(a)
# now b should be the same expression
b = a.expand(trig=True)
hb = hash(b)
assert a == b
assert ha == hb
def test_Add_is_pos_neg():
# these cover lines not covered by the rest of tests in core
n = Symbol('n', extended_negative=True, infinite=True)
nn = Symbol('n', extended_nonnegative=True, infinite=True)
np = Symbol('n', extended_nonpositive=True, infinite=True)
p = Symbol('p', extended_positive=True, infinite=True)
r = Dummy(extended_real=True, finite=False)
x = Symbol('x')
xf = Symbol('xf', finite=True)
assert (n + p).is_extended_positive is None
assert (n + x).is_extended_positive is None
assert (p + x).is_extended_positive is None
assert (n + p).is_extended_negative is None
assert (n + x).is_extended_negative is None
assert (p + x).is_extended_negative is None
assert (n + xf).is_extended_positive is False
assert (p + xf).is_extended_positive is True
assert (n + xf).is_extended_negative is True
assert (p + xf).is_extended_negative is False
assert (x - S.Infinity).is_extended_negative is None # issue 7798
# issue 8046, 16.2
assert (p + nn).is_extended_positive
assert (n + np).is_extended_negative
assert (p + r).is_extended_positive is None
def test_Add_is_imaginary():
nn = Dummy(nonnegative=True)
assert (I*nn + I).is_imaginary # issue 8046, 17
def test_Add_is_algebraic():
a = Symbol('a', algebraic=True)
b = Symbol('a', algebraic=True)
na = Symbol('na', algebraic=False)
nb = Symbol('nb', algebraic=False)
x = Symbol('x')
assert (a + b).is_algebraic
assert (na + nb).is_algebraic is None
assert (a + na).is_algebraic is False
assert (a + x).is_algebraic is None
assert (na + x).is_algebraic is None
def test_Mul_is_algebraic():
a = Symbol('a', algebraic=True)
b = Symbol('b', algebraic=True)
na = Symbol('na', algebraic=False)
an = Symbol('an', algebraic=True, nonzero=True)
nb = Symbol('nb', algebraic=False)
x = Symbol('x')
assert (a*b).is_algebraic is True
assert (na*nb).is_algebraic is None
assert (a*na).is_algebraic is None
assert (an*na).is_algebraic is False
assert (a*x).is_algebraic is None
assert (na*x).is_algebraic is None
def test_Pow_is_algebraic():
e = Symbol('e', algebraic=True)
assert Pow(1, e, evaluate=False).is_algebraic
assert Pow(0, e, evaluate=False).is_algebraic
a = Symbol('a', algebraic=True)
azf = Symbol('azf', algebraic=True, zero=False)
na = Symbol('na', algebraic=False)
ia = Symbol('ia', algebraic=True, irrational=True)
ib = Symbol('ib', algebraic=True, irrational=True)
r = Symbol('r', rational=True)
x = Symbol('x')
assert (a**2).is_algebraic is True
assert (a**r).is_algebraic is None
assert (azf**r).is_algebraic is True
assert (a**x).is_algebraic is None
assert (na**r).is_algebraic is None
assert (ia**r).is_algebraic is True
assert (ia**ib).is_algebraic is False
assert (a**e).is_algebraic is None
# Gelfond-Schneider constant:
assert Pow(2, sqrt(2), evaluate=False).is_algebraic is False
assert Pow(S.GoldenRatio, sqrt(3), evaluate=False).is_algebraic is False
# issue 8649
t = Symbol('t', real=True, transcendental=True)
n = Symbol('n', integer=True)
assert (t**n).is_algebraic is None
assert (t**n).is_integer is None
assert (pi**3).is_algebraic is False
r = Symbol('r', zero=True)
assert (pi**r).is_algebraic is True
def test_Mul_is_prime_composite():
x = Symbol('x', positive=True, integer=True)
y = Symbol('y', positive=True, integer=True)
assert (x*y).is_prime is None
assert ( (x+1)*(y+1) ).is_prime is False
assert ( (x+1)*(y+1) ).is_composite is True
x = Symbol('x', positive=True)
assert ( (x+1)*(y+1) ).is_prime is None
assert ( (x+1)*(y+1) ).is_composite is None
def test_Pow_is_pos_neg():
z = Symbol('z', real=True)
w = Symbol('w', nonpositive=True)
assert (S.NegativeOne**S(2)).is_positive is True
assert (S.One**z).is_positive is True
assert (S.NegativeOne**S(3)).is_positive is False
assert (S.Zero**S.Zero).is_positive is True # 0**0 is 1
assert (w**S(3)).is_positive is False
assert (w**S(2)).is_positive is None
assert (I**2).is_positive is False
assert (I**4).is_positive is True
# tests emerging from #16332 issue
p = Symbol('p', zero=True)
q = Symbol('q', zero=False, real=True)
j = Symbol('j', zero=False, even=True)
x = Symbol('x', zero=True)
y = Symbol('y', zero=True)
assert (p**q).is_positive is False
assert (p**q).is_negative is False
assert (p**j).is_positive is False
assert (x**y).is_positive is True # 0**0
assert (x**y).is_negative is False
def test_Pow_is_prime_composite():
x = Symbol('x', positive=True, integer=True)
y = Symbol('y', positive=True, integer=True)
assert (x**y).is_prime is None
assert ( x**(y+1) ).is_prime is False
assert ( x**(y+1) ).is_composite is None
assert ( (x+1)**(y+1) ).is_composite is True
assert ( (-x-1)**(2*y) ).is_composite is True
x = Symbol('x', positive=True)
assert (x**y).is_prime is None
def test_Mul_is_infinite():
x = Symbol('x')
f = Symbol('f', finite=True)
i = Symbol('i', infinite=True)
z = Dummy(zero=True)
nzf = Dummy(finite=True, zero=False)
from sympy.core.mul import Mul
assert (x*f).is_finite is None
assert (x*i).is_finite is None
assert (f*i).is_finite is None
assert (x*f*i).is_finite is None
assert (z*i).is_finite is None
assert (nzf*i).is_finite is False
assert (z*f).is_finite is True
assert Mul(0, f, evaluate=False).is_finite is True
assert Mul(0, i, evaluate=False).is_finite is None
assert (x*f).is_infinite is None
assert (x*i).is_infinite is None
assert (f*i).is_infinite is None
assert (x*f*i).is_infinite is None
assert (z*i).is_infinite is S.NaN.is_infinite
assert (nzf*i).is_infinite is True
assert (z*f).is_infinite is False
assert Mul(0, f, evaluate=False).is_infinite is False
assert Mul(0, i, evaluate=False).is_infinite is S.NaN.is_infinite
def test_Add_is_infinite():
x = Symbol('x')
f = Symbol('f', finite=True)
i = Symbol('i', infinite=True)
i2 = Symbol('i2', infinite=True)
z = Dummy(zero=True)
nzf = Dummy(finite=True, zero=False)
from sympy.core.add import Add
assert (x+f).is_finite is None
assert (x+i).is_finite is None
assert (f+i).is_finite is False
assert (x+f+i).is_finite is None
assert (z+i).is_finite is False
assert (nzf+i).is_finite is False
assert (z+f).is_finite is True
assert (i+i2).is_finite is None
assert Add(0, f, evaluate=False).is_finite is True
assert Add(0, i, evaluate=False).is_finite is False
assert (x+f).is_infinite is None
assert (x+i).is_infinite is None
assert (f+i).is_infinite is True
assert (x+f+i).is_infinite is None
assert (z+i).is_infinite is True
assert (nzf+i).is_infinite is True
assert (z+f).is_infinite is False
assert (i+i2).is_infinite is None
assert Add(0, f, evaluate=False).is_infinite is False
assert Add(0, i, evaluate=False).is_infinite is True
def test_special_is_rational():
i = Symbol('i', integer=True)
i2 = Symbol('i2', integer=True)
ni = Symbol('ni', integer=True, nonzero=True)
r = Symbol('r', rational=True)
rn = Symbol('r', rational=True, nonzero=True)
nr = Symbol('nr', irrational=True)
x = Symbol('x')
assert sqrt(3).is_rational is False
assert (3 + sqrt(3)).is_rational is False
assert (3*sqrt(3)).is_rational is False
assert exp(3).is_rational is False
assert exp(ni).is_rational is False
assert exp(rn).is_rational is False
assert exp(x).is_rational is None
assert exp(log(3), evaluate=False).is_rational is True
assert log(exp(3), evaluate=False).is_rational is True
assert log(3).is_rational is False
assert log(ni + 1).is_rational is False
assert log(rn + 1).is_rational is False
assert log(x).is_rational is None
assert (sqrt(3) + sqrt(5)).is_rational is None
assert (sqrt(3) + S.Pi).is_rational is False
assert (x**i).is_rational is None
assert (i**i).is_rational is True
assert (i**i2).is_rational is None
assert (r**i).is_rational is None
assert (r**r).is_rational is None
assert (r**x).is_rational is None
assert (nr**i).is_rational is None # issue 8598
assert (nr**Symbol('z', zero=True)).is_rational
assert sin(1).is_rational is False
assert sin(ni).is_rational is False
assert sin(rn).is_rational is False
assert sin(x).is_rational is None
assert asin(r).is_rational is False
assert sin(asin(3), evaluate=False).is_rational is True
@XFAIL
def test_issue_6275():
x = Symbol('x')
# both zero or both Muls...but neither "change would be very appreciated.
# This is similar to x/x => 1 even though if x = 0, it is really nan.
assert isinstance(x*0, type(0*S.Infinity))
if 0*S.Infinity is S.NaN:
b = Symbol('b', finite=None)
assert (b*0).is_zero is None
def test_sanitize_assumptions():
# issue 6666
for cls in (Symbol, Dummy, Wild):
x = cls('x', real=1, positive=0)
assert x.is_real is True
assert x.is_positive is False
assert cls('', real=True, positive=None).is_positive is None
raises(ValueError, lambda: cls('', commutative=None))
raises(ValueError, lambda: Symbol._sanitize(dict(commutative=None)))
def test_special_assumptions():
e = -3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2
assert simplify(e < 0) is S.false
assert simplify(e > 0) is S.false
assert (e == 0) is False # it's not a literal 0
assert e.equals(0) is True
def test_inconsistent():
# cf. issues 5795 and 5545
raises(InconsistentAssumptions, lambda: Symbol('x', real=True,
commutative=False))
def test_issue_6631():
assert ((-1)**(I)).is_real is True
assert ((-1)**(I*2)).is_real is True
assert ((-1)**(I/2)).is_real is True
assert ((-1)**(I*S.Pi)).is_real is True
assert (I**(I + 2)).is_real is True
def test_issue_2730():
assert (1/(1 + I)).is_real is False
def test_issue_4149():
assert (3 + I).is_complex
assert (3 + I).is_imaginary is False
assert (3*I + S.Pi*I).is_imaginary
# as Zero.is_imaginary is False, see issue 7649
y = Symbol('y', real=True)
assert (3*I + S.Pi*I + y*I).is_imaginary is None
p = Symbol('p', positive=True)
assert (3*I + S.Pi*I + p*I).is_imaginary
n = Symbol('n', negative=True)
assert (-3*I - S.Pi*I + n*I).is_imaginary
i = Symbol('i', imaginary=True)
assert ([(i**a).is_imaginary for a in range(4)] ==
[False, True, False, True])
# tests from the PR #7887:
e = S("-sqrt(3)*I/2 + 0.866025403784439*I")
assert e.is_real is False
assert e.is_imaginary
def test_issue_2920():
n = Symbol('n', negative=True)
assert sqrt(n).is_imaginary
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
@XFAIL
def test_issue_7993():
x = Dummy(integer=True)
y = Dummy(noninteger=True)
assert (x - y).is_zero is False
def test_issue_8075():
raises(InconsistentAssumptions, lambda: Dummy(zero=True, finite=False))
raises(InconsistentAssumptions, lambda: Dummy(zero=True, infinite=True))
def test_issue_8642():
x = Symbol('x', real=True, integer=False)
assert (x*2).is_integer is None, (x*2).is_integer
def test_issues_8632_8633_8638_8675_8992():
p = Dummy(integer=True, positive=True)
nn = Dummy(integer=True, nonnegative=True)
assert (p - S.Half).is_positive
assert (p - 1).is_nonnegative
assert (nn + 1).is_positive
assert (-p + 1).is_nonpositive
assert (-nn - 1).is_negative
prime = Dummy(prime=True)
assert (prime - 2).is_nonnegative
assert (prime - 3).is_nonnegative is None
even = Dummy(positive=True, even=True)
assert (even - 2).is_nonnegative
p = Dummy(positive=True)
assert (p/(p + 1) - 1).is_negative
assert ((p + 2)**3 - S.Half).is_positive
n = Dummy(negative=True)
assert (n - 3).is_nonpositive
def test_issue_9115_9150():
n = Dummy('n', integer=True, nonnegative=True)
assert (factorial(n) >= 1) == True
assert (factorial(n) < 1) == False
assert factorial(n + 1).is_even is None
assert factorial(n + 2).is_even is True
assert factorial(n + 2) >= 2
def test_issue_9165():
z = Symbol('z', zero=True)
f = Symbol('f', finite=False)
assert 0/z is S.NaN
assert 0*(1/z) is S.NaN
assert 0*f is S.NaN
def test_issue_10024():
x = Dummy('x')
assert Mod(x, 2*pi).is_zero is None
def test_issue_10302():
x = Symbol('x')
r = Symbol('r', real=True)
u = -(3*2**pi)**(1/pi) + 2*3**(1/pi)
i = u + u*I
assert i.is_real is None # w/o simplification this should fail
assert (u + i).is_zero is None
assert (1 + i).is_zero is False
a = Dummy('a', zero=True)
assert (a + I).is_zero is False
assert (a + r*I).is_zero is None
assert (a + I).is_imaginary
assert (a + x + I).is_imaginary is None
assert (a + r*I + I).is_imaginary is None
def test_complex_reciprocal_imaginary():
assert (1 / (4 + 3*I)).is_imaginary is False
def test_issue_16313():
x = Symbol('x', extended_real=False)
k = Symbol('k', real=True)
l = Symbol('l', real=True, zero=False)
assert (-x).is_real is False
assert (k*x).is_real is None # k can be zero also
assert (l*x).is_real is False
assert (l*x*x).is_real is None # since x*x can be a real number
assert (-x).is_positive is False
def test_issue_16579():
# extended_real -> finite | infinite
x = Symbol('x', extended_real=True, infinite=False)
y = Symbol('y', extended_real=True, finite=False)
assert x.is_finite is True
assert y.is_infinite is True
# With PR 16978, complex now implies finite
c = Symbol('c', complex=True)
assert c.is_finite is True
raises(InconsistentAssumptions, lambda: Dummy(complex=True, finite=False))
# Now infinite == !finite
nf = Symbol('nf', finite=False)
assert nf.is_infinite is True
def test_issue_17556():
z = I*oo
assert z.is_imaginary is False
assert z.is_finite is False
def test_issue_21651():
k = Symbol('k', positive=True, integer=True)
exp = 2*2**(-k)
assert exp.is_integer is None
def test_assumptions_copy():
assert assumptions(Symbol('x'), dict(commutative=True)
) == {'commutative': True}
assert assumptions(Symbol('x'), ['integer']) == {}
assert assumptions(Symbol('x'), ['commutative']
) == {'commutative': True}
assert assumptions(Symbol('x')) == {'commutative': True}
assert assumptions(1)['positive']
assert assumptions(3 + I) == {
'algebraic': True,
'commutative': True,
'complex': True,
'composite': False,
'even': False,
'extended_negative': False,
'extended_nonnegative': False,
'extended_nonpositive': False,
'extended_nonzero': False,
'extended_positive': False,
'extended_real': False,
'finite': True,
'imaginary': False,
'infinite': False,
'integer': False,
'irrational': False,
'negative': False,
'noninteger': False,
'nonnegative': False,
'nonpositive': False,
'nonzero': False,
'odd': False,
'positive': False,
'prime': False,
'rational': False,
'real': False,
'transcendental': False,
'zero': False}
def test_check_assumptions():
assert check_assumptions(1, 0) is False
x = Symbol('x', positive=True)
assert check_assumptions(1, x) is True
assert check_assumptions(1, 1) is True
assert check_assumptions(-1, 1) is False
i = Symbol('i', integer=True)
# don't know if i is positive (or prime, etc...)
assert check_assumptions(i, 1) is None
assert check_assumptions(Dummy(integer=None), integer=True) is None
assert check_assumptions(Dummy(integer=None), integer=False) is None
assert check_assumptions(Dummy(integer=False), integer=True) is False
assert check_assumptions(Dummy(integer=True), integer=False) is False
# no T/F assumptions to check
assert check_assumptions(Dummy(integer=False), integer=None) is True
raises(ValueError, lambda: check_assumptions(2*x, x, positive=True))
def test_failing_assumptions():
x = Symbol('x', positive=True)
y = Symbol('y')
assert failing_assumptions(6*x + y, **x.assumptions0) == \
{'real': None, 'imaginary': None, 'complex': None, 'hermitian': None,
'positive': None, 'nonpositive': None, 'nonnegative': None, 'nonzero': None,
'negative': None, 'zero': None, 'extended_real': None, 'finite': None,
'infinite': None, 'extended_negative': None, 'extended_nonnegative': None,
'extended_nonpositive': None, 'extended_nonzero': None,
'extended_positive': None }
def test_common_assumptions():
assert common_assumptions([0, 1, 2]
) == {'algebraic': True, 'irrational': False, 'hermitian':
True, 'extended_real': True, 'real': True, 'extended_negative':
False, 'extended_nonnegative': True, 'integer': True,
'rational': True, 'imaginary': False, 'complex': True,
'commutative': True,'noninteger': False, 'composite': False,
'infinite': False, 'nonnegative': True, 'finite': True,
'transcendental': False,'negative': False}
assert common_assumptions([0, 1, 2], 'positive integer'.split()
) == {'integer': True}
assert common_assumptions([0, 1, 2], []) == {}
assert common_assumptions([], ['integer']) == {}
assert common_assumptions([0], ['integer']) == {'integer': True}
def test_pre_generated_assumption_rules_are_valid():
# check the pre-generated assumptions match freshly generated assumptions
# if this check fails, consider updating the assumptions
# see sympy.core.assumptions._generate_assumption_rules
pre_generated_assumptions =_load_pre_generated_assumption_rules()
generated_assumptions =_generate_assumption_rules()
assert pre_generated_assumptions._to_python() == generated_assumptions._to_python(), "pre-generated assumptions are invalid, see sympy.core.assumptions._generate_assumption_rules"
|
fb3f251a1c8c4666e2bdf4396ffcaecd1d59e3bfe616dcf162309d49181d959e | from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.mod import Mod
from sympy.core.mul import Mul
from sympy.core.numbers import (Float, I, Integer, Rational, comp, nan,
oo, pi, zoo)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (im, re, sign)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import (Max, sqrt)
from sympy.functions.elementary.trigonometric import (atan, cos, sin)
from sympy.polys.polytools import Poly
from sympy.sets.sets import FiniteSet
from sympy.core.parameters import distribute
from sympy.core.expr import unchanged
from sympy.utilities.iterables import permutations
from sympy.testing.pytest import XFAIL, raises, warns
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.core.random import verify_numerically
from sympy.functions.elementary.trigonometric import asin
from itertools import product
a, c, x, y, z = symbols('a,c,x,y,z')
b = Symbol("b", positive=True)
def same_and_same_prec(a, b):
# stricter matching for Floats
return a == b and a._prec == b._prec
def test_bug1():
assert re(x) != x
x.series(x, 0, 1)
assert re(x) != x
def test_Symbol():
e = a*b
assert e == a*b
assert a*b*b == a*b**2
assert a*b*b + c == c + a*b**2
assert a*b*b - c == -c + a*b**2
x = Symbol('x', complex=True, real=False)
assert x.is_imaginary is None # could be I or 1 + I
x = Symbol('x', complex=True, imaginary=False)
assert x.is_real is None # could be 1 or 1 + I
x = Symbol('x', real=True)
assert x.is_complex
x = Symbol('x', imaginary=True)
assert x.is_complex
x = Symbol('x', real=False, imaginary=False)
assert x.is_complex is None # might be a non-number
def test_arit0():
p = Rational(5)
e = a*b
assert e == a*b
e = a*b + b*a
assert e == 2*a*b
e = a*b + b*a + a*b + p*b*a
assert e == 8*a*b
e = a*b + b*a + a*b + p*b*a + a
assert e == a + 8*a*b
e = a + a
assert e == 2*a
e = a + b + a
assert e == b + 2*a
e = a + b*b + a + b*b
assert e == 2*a + 2*b**2
e = a + Rational(2) + b*b + a + b*b + p
assert e == 7 + 2*a + 2*b**2
e = (a + b*b + a + b*b)*p
assert e == 5*(2*a + 2*b**2)
e = (a*b*c + c*b*a + b*a*c)*p
assert e == 15*a*b*c
e = (a*b*c + c*b*a + b*a*c)*p - Rational(15)*a*b*c
assert e == Rational(0)
e = Rational(50)*(a - a)
assert e == Rational(0)
e = b*a - b - a*b + b
assert e == Rational(0)
e = a*b + c**p
assert e == a*b + c**5
e = a/b
assert e == a*b**(-1)
e = a*2*2
assert e == 4*a
e = 2 + a*2/2
assert e == 2 + a
e = 2 - a - 2
assert e == -a
e = 2*a*2
assert e == 4*a
e = 2/a/2
assert e == a**(-1)
e = 2**a**2
assert e == 2**(a**2)
e = -(1 + a)
assert e == -1 - a
e = S.Half*(1 + a)
assert e == S.Half + a/2
def test_div():
e = a/b
assert e == a*b**(-1)
e = a/b + c/2
assert e == a*b**(-1) + Rational(1)/2*c
e = (1 - b)/(b - 1)
assert e == (1 + -b)*((-1) + b)**(-1)
def test_pow_arit():
n1 = Rational(1)
n2 = Rational(2)
n5 = Rational(5)
e = a*a
assert e == a**2
e = a*a*a
assert e == a**3
e = a*a*a*a**Rational(6)
assert e == a**9
e = a*a*a*a**Rational(6) - a**Rational(9)
assert e == Rational(0)
e = a**(b - b)
assert e == Rational(1)
e = (a + Rational(1) - a)**b
assert e == Rational(1)
e = (a + b + c)**n2
assert e == (a + b + c)**2
assert e.expand() == 2*b*c + 2*a*c + 2*a*b + a**2 + c**2 + b**2
e = (a + b)**n2
assert e == (a + b)**2
assert e.expand() == 2*a*b + a**2 + b**2
e = (a + b)**(n1/n2)
assert e == sqrt(a + b)
assert e.expand() == sqrt(a + b)
n = n5**(n1/n2)
assert n == sqrt(5)
e = n*a*b - n*b*a
assert e == Rational(0)
e = n*a*b + n*b*a
assert e == 2*a*b*sqrt(5)
assert e.diff(a) == 2*b*sqrt(5)
assert e.diff(a) == 2*b*sqrt(5)
e = a/b**2
assert e == a*b**(-2)
assert sqrt(2*(1 + sqrt(2))) == (2*(1 + 2**S.Half))**S.Half
x = Symbol('x')
y = Symbol('y')
assert ((x*y)**3).expand() == y**3 * x**3
assert ((x*y)**-3).expand() == y**-3 * x**-3
assert (x**5*(3*x)**(3)).expand() == 27 * x**8
assert (x**5*(-3*x)**(3)).expand() == -27 * x**8
assert (x**5*(3*x)**(-3)).expand() == x**2 * Rational(1, 27)
assert (x**5*(-3*x)**(-3)).expand() == x**2 * Rational(-1, 27)
# expand_power_exp
_x = Symbol('x', zero=False)
_y = Symbol('y', zero=False)
assert (_x**(y**(x + exp(x + y)) + z)).expand(deep=False) == \
_x**z*_x**(y**(x + exp(x + y)))
assert (_x**(_y**(x + exp(x + y)) + z)).expand() == \
_x**z*_x**(_y**x*_y**(exp(x)*exp(y)))
n = Symbol('n', even=False)
k = Symbol('k', even=True)
o = Symbol('o', odd=True)
assert unchanged(Pow, -1, x)
assert unchanged(Pow, -1, n)
assert (-2)**k == 2**k
assert (-1)**k == 1
assert (-1)**o == -1
def test_pow2():
# x**(2*y) is always (x**y)**2 but is only (x**2)**y if
# x.is_positive or y.is_integer
# let x = 1 to see why the following are not true.
assert (-x)**Rational(2, 3) != x**Rational(2, 3)
assert (-x)**Rational(5, 7) != -x**Rational(5, 7)
assert ((-x)**2)**Rational(1, 3) != ((-x)**Rational(1, 3))**2
assert sqrt(x**2) != x
def test_pow3():
assert sqrt(2)**3 == 2 * sqrt(2)
assert sqrt(2)**3 == sqrt(8)
def test_mod_pow():
for s, t, u, v in [(4, 13, 497, 445), (4, -3, 497, 365),
(3.2, 2.1, 1.9, 0.1031015682350942), (S(3)/2, 5, S(5)/6, S(3)/32)]:
assert pow(S(s), t, u) == v
assert pow(S(s), S(t), u) == v
assert pow(S(s), t, S(u)) == v
assert pow(S(s), S(t), S(u)) == v
assert pow(S(2), S(10000000000), S(3)) == 1
assert pow(x, y, z) == x**y%z
raises(TypeError, lambda: pow(S(4), "13", 497))
raises(TypeError, lambda: pow(S(4), 13, "497"))
def test_pow_E():
assert 2**(y/log(2)) == S.Exp1**y
assert 2**(y/log(2)/3) == S.Exp1**(y/3)
assert 3**(1/log(-3)) != S.Exp1
assert (3 + 2*I)**(1/(log(-3 - 2*I) + I*pi)) == S.Exp1
assert (4 + 2*I)**(1/(log(-4 - 2*I) + I*pi)) == S.Exp1
assert (3 + 2*I)**(1/(log(-3 - 2*I, 3)/2 + I*pi/log(3)/2)) == 9
assert (3 + 2*I)**(1/(log(3 + 2*I, 3)/2)) == 9
# every time tests are run they will affirm with a different random
# value that this identity holds
while 1:
b = x._random()
r, i = b.as_real_imag()
if i:
break
assert verify_numerically(b**(1/(log(-b) + sign(i)*I*pi).n()), S.Exp1)
def test_pow_issue_3516():
assert 4**Rational(1, 4) == sqrt(2)
def test_pow_im():
for m in (-2, -1, 2):
for d in (3, 4, 5):
b = m*I
for i in range(1, 4*d + 1):
e = Rational(i, d)
assert (b**e - b.n()**e.n()).n(2, chop=1e-10) == 0
e = Rational(7, 3)
assert (2*x*I)**e == 4*2**Rational(1, 3)*(I*x)**e # same as Wolfram Alpha
im = symbols('im', imaginary=True)
assert (2*im*I)**e == 4*2**Rational(1, 3)*(I*im)**e
args = [I, I, I, I, 2]
e = Rational(1, 3)
ans = 2**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args = [I, I, I, 2]
e = Rational(1, 3)
ans = 2**e*(-I)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-3)
ans = (6*I)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-1)
ans = (-6*I)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args = [I, I, 2]
e = Rational(1, 3)
ans = (-2)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-3)
ans = (6)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
args.append(-1)
ans = (-6)**e
assert Mul(*args, evaluate=False)**e == ans
assert Mul(*args)**e == ans
assert Mul(Pow(-1, Rational(3, 2), evaluate=False), I, I) == I
assert Mul(I*Pow(I, S.Half, evaluate=False)) == sqrt(I)*I
def test_real_mul():
assert Float(0) * pi * x == 0
assert set((Float(1) * pi * x).args) == {Float(1), pi, x}
def test_ncmul():
A = Symbol("A", commutative=False)
B = Symbol("B", commutative=False)
C = Symbol("C", commutative=False)
assert A*B != B*A
assert A*B*C != C*B*A
assert A*b*B*3*C == 3*b*A*B*C
assert A*b*B*3*C != 3*b*B*A*C
assert A*b*B*3*C == 3*A*B*C*b
assert A + B == B + A
assert (A + B)*C != C*(A + B)
assert C*(A + B)*C != C*C*(A + B)
assert A*A == A**2
assert (A + B)*(A + B) == (A + B)**2
assert A**-1 * A == 1
assert A/A == 1
assert A/(A**2) == 1/A
assert A/(1 + A) == A/(1 + A)
assert set((A + B + 2*(A + B)).args) == \
{A, B, 2*(A + B)}
def test_mul_add_identity():
m = Mul(1, 2)
assert isinstance(m, Rational) and m.p == 2 and m.q == 1
m = Mul(1, 2, evaluate=False)
assert isinstance(m, Mul) and m.args == (1, 2)
m = Mul(0, 1)
assert m is S.Zero
m = Mul(0, 1, evaluate=False)
assert isinstance(m, Mul) and m.args == (0, 1)
m = Add(0, 1)
assert m is S.One
m = Add(0, 1, evaluate=False)
assert isinstance(m, Add) and m.args == (0, 1)
def test_ncpow():
x = Symbol('x', commutative=False)
y = Symbol('y', commutative=False)
z = Symbol('z', commutative=False)
a = Symbol('a')
b = Symbol('b')
c = Symbol('c')
assert (x**2)*(y**2) != (y**2)*(x**2)
assert (x**-2)*y != y*(x**2)
assert 2**x*2**y != 2**(x + y)
assert 2**x*2**y*2**z != 2**(x + y + z)
assert 2**x*2**(2*x) == 2**(3*x)
assert 2**x*2**(2*x)*2**x == 2**(4*x)
assert exp(x)*exp(y) != exp(y)*exp(x)
assert exp(x)*exp(y)*exp(z) != exp(y)*exp(x)*exp(z)
assert exp(x)*exp(y)*exp(z) != exp(x + y + z)
assert x**a*x**b != x**(a + b)
assert x**a*x**b*x**c != x**(a + b + c)
assert x**3*x**4 == x**7
assert x**3*x**4*x**2 == x**9
assert x**a*x**(4*a) == x**(5*a)
assert x**a*x**(4*a)*x**a == x**(6*a)
def test_powerbug():
x = Symbol("x")
assert x**1 != (-x)**1
assert x**2 == (-x)**2
assert x**3 != (-x)**3
assert x**4 == (-x)**4
assert x**5 != (-x)**5
assert x**6 == (-x)**6
assert x**128 == (-x)**128
assert x**129 != (-x)**129
assert (2*x)**2 == (-2*x)**2
def test_Mul_doesnt_expand_exp():
x = Symbol('x')
y = Symbol('y')
assert unchanged(Mul, exp(x), exp(y))
assert unchanged(Mul, 2**x, 2**y)
assert x**2*x**3 == x**5
assert 2**x*3**x == 6**x
assert x**(y)*x**(2*y) == x**(3*y)
assert sqrt(2)*sqrt(2) == 2
assert 2**x*2**(2*x) == 2**(3*x)
assert sqrt(2)*2**Rational(1, 4)*5**Rational(3, 4) == 10**Rational(3, 4)
assert (x**(-log(5)/log(3))*x)/(x*x**( - log(5)/log(3))) == sympify(1)
def test_Mul_is_integer():
k = Symbol('k', integer=True)
n = Symbol('n', integer=True)
nr = Symbol('nr', rational=False)
ir = Symbol('ir', irrational=True)
nz = Symbol('nz', integer=True, zero=False)
e = Symbol('e', even=True)
o = Symbol('o', odd=True)
i2 = Symbol('2', prime=True, even=True)
assert (k/3).is_integer is None
assert (nz/3).is_integer is None
assert (nr/3).is_integer is False
assert (ir/3).is_integer is False
assert (x*k*n).is_integer is None
assert (e/2).is_integer is True
assert (e**2/2).is_integer is True
assert (2/k).is_integer is None
assert (2/k**2).is_integer is None
assert ((-1)**k*n).is_integer is True
assert (3*k*e/2).is_integer is True
assert (2*k*e/3).is_integer is None
assert (e/o).is_integer is None
assert (o/e).is_integer is False
assert (o/i2).is_integer is False
assert Mul(k, 1/k, evaluate=False).is_integer is None
assert Mul(2., S.Half, evaluate=False).is_integer is None
assert (2*sqrt(k)).is_integer is None
assert (2*k**n).is_integer is None
s = 2**2**2**Pow(2, 1000, evaluate=False)
m = Mul(s, s, evaluate=False)
assert m.is_integer
# broken in 1.6 and before, see #20161
xq = Symbol('xq', rational=True)
yq = Symbol('yq', rational=True)
assert (xq*yq).is_integer is None
e_20161 = Mul(-1,Mul(1,Pow(2,-1,evaluate=False),evaluate=False),evaluate=False)
assert e_20161.is_integer is not True # expand(e_20161) -> -1/2, but no need to see that in the assumption without evaluation
def test_Add_Mul_is_integer():
x = Symbol('x')
k = Symbol('k', integer=True)
n = Symbol('n', integer=True)
nk = Symbol('nk', integer=False)
nr = Symbol('nr', rational=False)
nz = Symbol('nz', integer=True, zero=False)
assert (-nk).is_integer is None
assert (-nr).is_integer is False
assert (2*k).is_integer is True
assert (-k).is_integer is True
assert (k + nk).is_integer is False
assert (k + n).is_integer is True
assert (k + x).is_integer is None
assert (k + n*x).is_integer is None
assert (k + n/3).is_integer is None
assert (k + nz/3).is_integer is None
assert (k + nr/3).is_integer is False
assert ((1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False
assert (1 + (1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False
def test_Add_Mul_is_finite():
x = Symbol('x', extended_real=True, finite=False)
assert sin(x).is_finite is True
assert (x*sin(x)).is_finite is None
assert (x*atan(x)).is_finite is False
assert (1024*sin(x)).is_finite is True
assert (sin(x)*exp(x)).is_finite is None
assert (sin(x)*cos(x)).is_finite is True
assert (x*sin(x)*exp(x)).is_finite is None
assert (sin(x) - 67).is_finite is True
assert (sin(x) + exp(x)).is_finite is not True
assert (1 + x).is_finite is False
assert (1 + x**2 + (1 + x)*(1 - x)).is_finite is None
assert (sqrt(2)*(1 + x)).is_finite is False
assert (sqrt(2)*(1 + x)*(1 - x)).is_finite is False
def test_Mul_is_even_odd():
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
k = Symbol('k', odd=True)
n = Symbol('n', odd=True)
m = Symbol('m', even=True)
assert (2*x).is_even is True
assert (2*x).is_odd is False
assert (3*x).is_even is None
assert (3*x).is_odd is None
assert (k/3).is_integer is None
assert (k/3).is_even is None
assert (k/3).is_odd is None
assert (2*n).is_even is True
assert (2*n).is_odd is False
assert (2*m).is_even is True
assert (2*m).is_odd is False
assert (-n).is_even is False
assert (-n).is_odd is True
assert (k*n).is_even is False
assert (k*n).is_odd is True
assert (k*m).is_even is True
assert (k*m).is_odd is False
assert (k*n*m).is_even is True
assert (k*n*m).is_odd is False
assert (k*m*x).is_even is True
assert (k*m*x).is_odd is False
# issue 6791:
assert (x/2).is_integer is None
assert (k/2).is_integer is False
assert (m/2).is_integer is True
assert (x*y).is_even is None
assert (x*x).is_even is None
assert (x*(x + k)).is_even is True
assert (x*(x + m)).is_even is None
assert (x*y).is_odd is None
assert (x*x).is_odd is None
assert (x*(x + k)).is_odd is False
assert (x*(x + m)).is_odd is None
# issue 8648
assert (m**2/2).is_even
assert (m**2/3).is_even is False
assert (2/m**2).is_odd is False
assert (2/m).is_odd is None
@XFAIL
def test_evenness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
k = Symbol('k', odd=True)
assert (x*y*(y + k)).is_even is True
assert (y*x*(x + k)).is_even is True
def test_evenness_in_ternary_integer_product_with_even():
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
m = Symbol('m', even=True)
assert (x*y*(y + m)).is_even is None
@XFAIL
def test_oddness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
k = Symbol('k', odd=True)
assert (x*y*(y + k)).is_odd is False
assert (y*x*(x + k)).is_odd is False
def test_oddness_in_ternary_integer_product_with_even():
x = Symbol('x', integer=True)
y = Symbol('y', integer=True)
m = Symbol('m', even=True)
assert (x*y*(y + m)).is_odd is None
def test_Mul_is_rational():
x = Symbol('x')
n = Symbol('n', integer=True)
m = Symbol('m', integer=True, nonzero=True)
assert (n/m).is_rational is True
assert (x/pi).is_rational is None
assert (x/n).is_rational is None
assert (m/pi).is_rational is False
r = Symbol('r', rational=True)
assert (pi*r).is_rational is None
# issue 8008
z = Symbol('z', zero=True)
i = Symbol('i', imaginary=True)
assert (z*i).is_rational is True
bi = Symbol('i', imaginary=True, finite=True)
assert (z*bi).is_zero is True
def test_Add_is_rational():
x = Symbol('x')
n = Symbol('n', rational=True)
m = Symbol('m', rational=True)
assert (n + m).is_rational is True
assert (x + pi).is_rational is None
assert (x + n).is_rational is None
assert (n + pi).is_rational is False
def test_Add_is_even_odd():
x = Symbol('x', integer=True)
k = Symbol('k', odd=True)
n = Symbol('n', odd=True)
m = Symbol('m', even=True)
assert (k + 7).is_even is True
assert (k + 7).is_odd is False
assert (-k + 7).is_even is True
assert (-k + 7).is_odd is False
assert (k - 12).is_even is False
assert (k - 12).is_odd is True
assert (-k - 12).is_even is False
assert (-k - 12).is_odd is True
assert (k + n).is_even is True
assert (k + n).is_odd is False
assert (k + m).is_even is False
assert (k + m).is_odd is True
assert (k + n + m).is_even is True
assert (k + n + m).is_odd is False
assert (k + n + x + m).is_even is None
assert (k + n + x + m).is_odd is None
def test_Mul_is_negative_positive():
x = Symbol('x', real=True)
y = Symbol('y', extended_real=False, complex=True)
z = Symbol('z', zero=True)
e = 2*z
assert e.is_Mul and e.is_positive is False and e.is_negative is False
neg = Symbol('neg', negative=True)
pos = Symbol('pos', positive=True)
nneg = Symbol('nneg', nonnegative=True)
npos = Symbol('npos', nonpositive=True)
assert neg.is_negative is True
assert (-neg).is_negative is False
assert (2*neg).is_negative is True
assert (2*pos)._eval_is_extended_negative() is False
assert (2*pos).is_negative is False
assert pos.is_negative is False
assert (-pos).is_negative is True
assert (2*pos).is_negative is False
assert (pos*neg).is_negative is True
assert (2*pos*neg).is_negative is True
assert (-pos*neg).is_negative is False
assert (pos*neg*y).is_negative is False # y.is_real=F; !real -> !neg
assert nneg.is_negative is False
assert (-nneg).is_negative is None
assert (2*nneg).is_negative is False
assert npos.is_negative is None
assert (-npos).is_negative is False
assert (2*npos).is_negative is None
assert (nneg*npos).is_negative is None
assert (neg*nneg).is_negative is None
assert (neg*npos).is_negative is False
assert (pos*nneg).is_negative is False
assert (pos*npos).is_negative is None
assert (npos*neg*nneg).is_negative is False
assert (npos*pos*nneg).is_negative is None
assert (-npos*neg*nneg).is_negative is None
assert (-npos*pos*nneg).is_negative is False
assert (17*npos*neg*nneg).is_negative is False
assert (17*npos*pos*nneg).is_negative is None
assert (neg*npos*pos*nneg).is_negative is False
assert (x*neg).is_negative is None
assert (nneg*npos*pos*x*neg).is_negative is None
assert neg.is_positive is False
assert (-neg).is_positive is True
assert (2*neg).is_positive is False
assert pos.is_positive is True
assert (-pos).is_positive is False
assert (2*pos).is_positive is True
assert (pos*neg).is_positive is False
assert (2*pos*neg).is_positive is False
assert (-pos*neg).is_positive is True
assert (-pos*neg*y).is_positive is False # y.is_real=F; !real -> !neg
assert nneg.is_positive is None
assert (-nneg).is_positive is False
assert (2*nneg).is_positive is None
assert npos.is_positive is False
assert (-npos).is_positive is None
assert (2*npos).is_positive is False
assert (nneg*npos).is_positive is False
assert (neg*nneg).is_positive is False
assert (neg*npos).is_positive is None
assert (pos*nneg).is_positive is None
assert (pos*npos).is_positive is False
assert (npos*neg*nneg).is_positive is None
assert (npos*pos*nneg).is_positive is False
assert (-npos*neg*nneg).is_positive is False
assert (-npos*pos*nneg).is_positive is None
assert (17*npos*neg*nneg).is_positive is None
assert (17*npos*pos*nneg).is_positive is False
assert (neg*npos*pos*nneg).is_positive is None
assert (x*neg).is_positive is None
assert (nneg*npos*pos*x*neg).is_positive is None
def test_Mul_is_negative_positive_2():
a = Symbol('a', nonnegative=True)
b = Symbol('b', nonnegative=True)
c = Symbol('c', nonpositive=True)
d = Symbol('d', nonpositive=True)
assert (a*b).is_nonnegative is True
assert (a*b).is_negative is False
assert (a*b).is_zero is None
assert (a*b).is_positive is None
assert (c*d).is_nonnegative is True
assert (c*d).is_negative is False
assert (c*d).is_zero is None
assert (c*d).is_positive is None
assert (a*c).is_nonpositive is True
assert (a*c).is_positive is False
assert (a*c).is_zero is None
assert (a*c).is_negative is None
def test_Mul_is_nonpositive_nonnegative():
x = Symbol('x', real=True)
k = Symbol('k', negative=True)
n = Symbol('n', positive=True)
u = Symbol('u', nonnegative=True)
v = Symbol('v', nonpositive=True)
assert k.is_nonpositive is True
assert (-k).is_nonpositive is False
assert (2*k).is_nonpositive is True
assert n.is_nonpositive is False
assert (-n).is_nonpositive is True
assert (2*n).is_nonpositive is False
assert (n*k).is_nonpositive is True
assert (2*n*k).is_nonpositive is True
assert (-n*k).is_nonpositive is False
assert u.is_nonpositive is None
assert (-u).is_nonpositive is True
assert (2*u).is_nonpositive is None
assert v.is_nonpositive is True
assert (-v).is_nonpositive is None
assert (2*v).is_nonpositive is True
assert (u*v).is_nonpositive is True
assert (k*u).is_nonpositive is True
assert (k*v).is_nonpositive is None
assert (n*u).is_nonpositive is None
assert (n*v).is_nonpositive is True
assert (v*k*u).is_nonpositive is None
assert (v*n*u).is_nonpositive is True
assert (-v*k*u).is_nonpositive is True
assert (-v*n*u).is_nonpositive is None
assert (17*v*k*u).is_nonpositive is None
assert (17*v*n*u).is_nonpositive is True
assert (k*v*n*u).is_nonpositive is None
assert (x*k).is_nonpositive is None
assert (u*v*n*x*k).is_nonpositive is None
assert k.is_nonnegative is False
assert (-k).is_nonnegative is True
assert (2*k).is_nonnegative is False
assert n.is_nonnegative is True
assert (-n).is_nonnegative is False
assert (2*n).is_nonnegative is True
assert (n*k).is_nonnegative is False
assert (2*n*k).is_nonnegative is False
assert (-n*k).is_nonnegative is True
assert u.is_nonnegative is True
assert (-u).is_nonnegative is None
assert (2*u).is_nonnegative is True
assert v.is_nonnegative is None
assert (-v).is_nonnegative is True
assert (2*v).is_nonnegative is None
assert (u*v).is_nonnegative is None
assert (k*u).is_nonnegative is None
assert (k*v).is_nonnegative is True
assert (n*u).is_nonnegative is True
assert (n*v).is_nonnegative is None
assert (v*k*u).is_nonnegative is True
assert (v*n*u).is_nonnegative is None
assert (-v*k*u).is_nonnegative is None
assert (-v*n*u).is_nonnegative is True
assert (17*v*k*u).is_nonnegative is True
assert (17*v*n*u).is_nonnegative is None
assert (k*v*n*u).is_nonnegative is True
assert (x*k).is_nonnegative is None
assert (u*v*n*x*k).is_nonnegative is None
def test_Add_is_negative_positive():
x = Symbol('x', real=True)
k = Symbol('k', negative=True)
n = Symbol('n', positive=True)
u = Symbol('u', nonnegative=True)
v = Symbol('v', nonpositive=True)
assert (k - 2).is_negative is True
assert (k + 17).is_negative is None
assert (-k - 5).is_negative is None
assert (-k + 123).is_negative is False
assert (k - n).is_negative is True
assert (k + n).is_negative is None
assert (-k - n).is_negative is None
assert (-k + n).is_negative is False
assert (k - n - 2).is_negative is True
assert (k + n + 17).is_negative is None
assert (-k - n - 5).is_negative is None
assert (-k + n + 123).is_negative is False
assert (-2*k + 123*n + 17).is_negative is False
assert (k + u).is_negative is None
assert (k + v).is_negative is True
assert (n + u).is_negative is False
assert (n + v).is_negative is None
assert (u - v).is_negative is False
assert (u + v).is_negative is None
assert (-u - v).is_negative is None
assert (-u + v).is_negative is None
assert (u - v + n + 2).is_negative is False
assert (u + v + n + 2).is_negative is None
assert (-u - v + n + 2).is_negative is None
assert (-u + v + n + 2).is_negative is None
assert (k + x).is_negative is None
assert (k + x - n).is_negative is None
assert (k - 2).is_positive is False
assert (k + 17).is_positive is None
assert (-k - 5).is_positive is None
assert (-k + 123).is_positive is True
assert (k - n).is_positive is False
assert (k + n).is_positive is None
assert (-k - n).is_positive is None
assert (-k + n).is_positive is True
assert (k - n - 2).is_positive is False
assert (k + n + 17).is_positive is None
assert (-k - n - 5).is_positive is None
assert (-k + n + 123).is_positive is True
assert (-2*k + 123*n + 17).is_positive is True
assert (k + u).is_positive is None
assert (k + v).is_positive is False
assert (n + u).is_positive is True
assert (n + v).is_positive is None
assert (u - v).is_positive is None
assert (u + v).is_positive is None
assert (-u - v).is_positive is None
assert (-u + v).is_positive is False
assert (u - v - n - 2).is_positive is None
assert (u + v - n - 2).is_positive is None
assert (-u - v - n - 2).is_positive is None
assert (-u + v - n - 2).is_positive is False
assert (n + x).is_positive is None
assert (n + x - k).is_positive is None
z = (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2)
assert z.is_zero
z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
assert z.is_zero
def test_Add_is_nonpositive_nonnegative():
x = Symbol('x', real=True)
k = Symbol('k', negative=True)
n = Symbol('n', positive=True)
u = Symbol('u', nonnegative=True)
v = Symbol('v', nonpositive=True)
assert (u - 2).is_nonpositive is None
assert (u + 17).is_nonpositive is False
assert (-u - 5).is_nonpositive is True
assert (-u + 123).is_nonpositive is None
assert (u - v).is_nonpositive is None
assert (u + v).is_nonpositive is None
assert (-u - v).is_nonpositive is None
assert (-u + v).is_nonpositive is True
assert (u - v - 2).is_nonpositive is None
assert (u + v + 17).is_nonpositive is None
assert (-u - v - 5).is_nonpositive is None
assert (-u + v - 123).is_nonpositive is True
assert (-2*u + 123*v - 17).is_nonpositive is True
assert (k + u).is_nonpositive is None
assert (k + v).is_nonpositive is True
assert (n + u).is_nonpositive is False
assert (n + v).is_nonpositive is None
assert (k - n).is_nonpositive is True
assert (k + n).is_nonpositive is None
assert (-k - n).is_nonpositive is None
assert (-k + n).is_nonpositive is False
assert (k - n + u + 2).is_nonpositive is None
assert (k + n + u + 2).is_nonpositive is None
assert (-k - n + u + 2).is_nonpositive is None
assert (-k + n + u + 2).is_nonpositive is False
assert (u + x).is_nonpositive is None
assert (v - x - n).is_nonpositive is None
assert (u - 2).is_nonnegative is None
assert (u + 17).is_nonnegative is True
assert (-u - 5).is_nonnegative is False
assert (-u + 123).is_nonnegative is None
assert (u - v).is_nonnegative is True
assert (u + v).is_nonnegative is None
assert (-u - v).is_nonnegative is None
assert (-u + v).is_nonnegative is None
assert (u - v + 2).is_nonnegative is True
assert (u + v + 17).is_nonnegative is None
assert (-u - v - 5).is_nonnegative is None
assert (-u + v - 123).is_nonnegative is False
assert (2*u - 123*v + 17).is_nonnegative is True
assert (k + u).is_nonnegative is None
assert (k + v).is_nonnegative is False
assert (n + u).is_nonnegative is True
assert (n + v).is_nonnegative is None
assert (k - n).is_nonnegative is False
assert (k + n).is_nonnegative is None
assert (-k - n).is_nonnegative is None
assert (-k + n).is_nonnegative is True
assert (k - n - u - 2).is_nonnegative is False
assert (k + n - u - 2).is_nonnegative is None
assert (-k - n - u - 2).is_nonnegative is None
assert (-k + n - u - 2).is_nonnegative is None
assert (u - x).is_nonnegative is None
assert (v + x + n).is_nonnegative is None
def test_Pow_is_integer():
x = Symbol('x')
k = Symbol('k', integer=True)
n = Symbol('n', integer=True, nonnegative=True)
m = Symbol('m', integer=True, positive=True)
assert (k**2).is_integer is True
assert (k**(-2)).is_integer is None
assert ((m + 1)**(-2)).is_integer is False
assert (m**(-1)).is_integer is None # issue 8580
assert (2**k).is_integer is None
assert (2**(-k)).is_integer is None
assert (2**n).is_integer is True
assert (2**(-n)).is_integer is None
assert (2**m).is_integer is True
assert (2**(-m)).is_integer is False
assert (x**2).is_integer is None
assert (2**x).is_integer is None
assert (k**n).is_integer is True
assert (k**(-n)).is_integer is None
assert (k**x).is_integer is None
assert (x**k).is_integer is None
assert (k**(n*m)).is_integer is True
assert (k**(-n*m)).is_integer is None
assert sqrt(3).is_integer is False
assert sqrt(.3).is_integer is False
assert Pow(3, 2, evaluate=False).is_integer is True
assert Pow(3, 0, evaluate=False).is_integer is True
assert Pow(3, -2, evaluate=False).is_integer is False
assert Pow(S.Half, 3, evaluate=False).is_integer is False
# decided by re-evaluating
assert Pow(3, S.Half, evaluate=False).is_integer is False
assert Pow(3, S.Half, evaluate=False).is_integer is False
assert Pow(4, S.Half, evaluate=False).is_integer is True
assert Pow(S.Half, -2, evaluate=False).is_integer is True
assert ((-1)**k).is_integer
# issue 8641
x = Symbol('x', real=True, integer=False)
assert (x**2).is_integer is None
# issue 10458
x = Symbol('x', positive=True)
assert (1/(x + 1)).is_integer is False
assert (1/(-x - 1)).is_integer is False
assert (-1/(x + 1)).is_integer is False
# issue 23287
assert (x**2/2).is_integer is None
# issue 8648-like
k = Symbol('k', even=True)
assert (k**3/2).is_integer
assert (k**3/8).is_integer
assert (k**3/16).is_integer is None
assert (2/k).is_integer is None
assert (2/k**2).is_integer is False
o = Symbol('o', odd=True)
assert (k/o).is_integer is None
o = Symbol('o', odd=True, prime=True)
assert (k/o).is_integer is False
def test_Pow_is_real():
x = Symbol('x', real=True)
y = Symbol('y', positive=True)
assert (x**2).is_real is True
assert (x**3).is_real is True
assert (x**x).is_real is None
assert (y**x).is_real is True
assert (x**Rational(1, 3)).is_real is None
assert (y**Rational(1, 3)).is_real is True
assert sqrt(-1 - sqrt(2)).is_real is False
i = Symbol('i', imaginary=True)
assert (i**i).is_real is None
assert (I**i).is_extended_real is True
assert ((-I)**i).is_extended_real is True
assert (2**i).is_real is None # (2**(pi/log(2) * I)) is real, 2**I is not
assert (2**I).is_real is False
assert (2**-I).is_real is False
assert (i**2).is_extended_real is True
assert (i**3).is_extended_real is False
assert (i**x).is_real is None # could be (-I)**(2/3)
e = Symbol('e', even=True)
o = Symbol('o', odd=True)
k = Symbol('k', integer=True)
assert (i**e).is_extended_real is True
assert (i**o).is_extended_real is False
assert (i**k).is_real is None
assert (i**(4*k)).is_extended_real is True
x = Symbol("x", nonnegative=True)
y = Symbol("y", nonnegative=True)
assert im(x**y).expand(complex=True) is S.Zero
assert (x**y).is_real is True
i = Symbol('i', imaginary=True)
assert (exp(i)**I).is_extended_real is True
assert log(exp(i)).is_imaginary is None # i could be 2*pi*I
c = Symbol('c', complex=True)
assert log(c).is_real is None # c could be 0 or 2, too
assert log(exp(c)).is_real is None # log(0), log(E), ...
n = Symbol('n', negative=False)
assert log(n).is_real is None
n = Symbol('n', nonnegative=True)
assert log(n).is_real is None
assert sqrt(-I).is_real is False # issue 7843
i = Symbol('i', integer=True)
assert (1/(i-1)).is_real is None
assert (1/(i-1)).is_extended_real is None
# test issue 20715
from sympy.core.parameters import evaluate
x = S(-1)
with evaluate(False):
assert x.is_negative is True
f = Pow(x, -1)
with evaluate(False):
assert f.is_imaginary is False
def test_real_Pow():
k = Symbol('k', integer=True, nonzero=True)
assert (k**(I*pi/log(k))).is_real
def test_Pow_is_finite():
xe = Symbol('xe', extended_real=True)
xr = Symbol('xr', real=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
i = Symbol('i', integer=True)
assert (xe**2).is_finite is None # xe could be oo
assert (xr**2).is_finite is True
assert (xe**xe).is_finite is None
assert (xr**xe).is_finite is None
assert (xe**xr).is_finite is None
# FIXME: The line below should be True rather than None
# assert (xr**xr).is_finite is True
assert (xr**xr).is_finite is None
assert (p**xe).is_finite is None
assert (p**xr).is_finite is True
assert (n**xe).is_finite is None
assert (n**xr).is_finite is True
assert (sin(xe)**2).is_finite is True
assert (sin(xr)**2).is_finite is True
assert (sin(xe)**xe).is_finite is None # xe, xr could be -pi
assert (sin(xr)**xr).is_finite is None
# FIXME: Should the line below be True rather than None?
assert (sin(xe)**exp(xe)).is_finite is None
assert (sin(xr)**exp(xr)).is_finite is True
assert (1/sin(xe)).is_finite is None # if zero, no, otherwise yes
assert (1/sin(xr)).is_finite is None
assert (1/exp(xe)).is_finite is None # xe could be -oo
assert (1/exp(xr)).is_finite is True
assert (1/S.Pi).is_finite is True
assert (1/(i-1)).is_finite is None
def test_Pow_is_even_odd():
x = Symbol('x')
k = Symbol('k', even=True)
n = Symbol('n', odd=True)
m = Symbol('m', integer=True, nonnegative=True)
p = Symbol('p', integer=True, positive=True)
assert ((-1)**n).is_odd
assert ((-1)**k).is_odd
assert ((-1)**(m - p)).is_odd
assert (k**2).is_even is True
assert (n**2).is_even is False
assert (2**k).is_even is None
assert (x**2).is_even is None
assert (k**m).is_even is None
assert (n**m).is_even is False
assert (k**p).is_even is True
assert (n**p).is_even is False
assert (m**k).is_even is None
assert (p**k).is_even is None
assert (m**n).is_even is None
assert (p**n).is_even is None
assert (k**x).is_even is None
assert (n**x).is_even is None
assert (k**2).is_odd is False
assert (n**2).is_odd is True
assert (3**k).is_odd is None
assert (k**m).is_odd is None
assert (n**m).is_odd is True
assert (k**p).is_odd is False
assert (n**p).is_odd is True
assert (m**k).is_odd is None
assert (p**k).is_odd is None
assert (m**n).is_odd is None
assert (p**n).is_odd is None
assert (k**x).is_odd is None
assert (n**x).is_odd is None
def test_Pow_is_negative_positive():
r = Symbol('r', real=True)
k = Symbol('k', integer=True, positive=True)
n = Symbol('n', even=True)
m = Symbol('m', odd=True)
x = Symbol('x')
assert (2**r).is_positive is True
assert ((-2)**r).is_positive is None
assert ((-2)**n).is_positive is True
assert ((-2)**m).is_positive is False
assert (k**2).is_positive is True
assert (k**(-2)).is_positive is True
assert (k**r).is_positive is True
assert ((-k)**r).is_positive is None
assert ((-k)**n).is_positive is True
assert ((-k)**m).is_positive is False
assert (2**r).is_negative is False
assert ((-2)**r).is_negative is None
assert ((-2)**n).is_negative is False
assert ((-2)**m).is_negative is True
assert (k**2).is_negative is False
assert (k**(-2)).is_negative is False
assert (k**r).is_negative is False
assert ((-k)**r).is_negative is None
assert ((-k)**n).is_negative is False
assert ((-k)**m).is_negative is True
assert (2**x).is_positive is None
assert (2**x).is_negative is None
def test_Pow_is_zero():
z = Symbol('z', zero=True)
e = z**2
assert e.is_zero
assert e.is_positive is False
assert e.is_negative is False
assert Pow(0, 0, evaluate=False).is_zero is False
assert Pow(0, 3, evaluate=False).is_zero
assert Pow(0, oo, evaluate=False).is_zero
assert Pow(0, -3, evaluate=False).is_zero is False
assert Pow(0, -oo, evaluate=False).is_zero is False
assert Pow(2, 2, evaluate=False).is_zero is False
a = Symbol('a', zero=False)
assert Pow(a, 3).is_zero is False # issue 7965
assert Pow(2, oo, evaluate=False).is_zero is False
assert Pow(2, -oo, evaluate=False).is_zero
assert Pow(S.Half, oo, evaluate=False).is_zero
assert Pow(S.Half, -oo, evaluate=False).is_zero is False
# All combinations of real/complex base/exponent
h = S.Half
T = True
F = False
N = None
pow_iszero = [
['**', 0, h, 1, 2, -h, -1,-2,-2*I,-I/2,I/2,1+I,oo,-oo,zoo],
[ 0, F, T, T, T, F, F, F, F, F, F, N, T, F, N],
[ h, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ 1, F, F, F, F, F, F, F, F, F, F, F, F, F, N],
[ 2, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[ -h, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ -1, F, F, F, F, F, F, F, F, F, F, F, F, F, N],
[ -2, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[-2*I, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[-I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
[ 1+I, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
[ oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N],
[ -oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N],
[ zoo, F, F, F, F, T, T, T, N, N, N, N, F, T, N]
]
def test_table(table):
n = len(table[0])
for row in range(1, n):
base = table[row][0]
for col in range(1, n):
exp = table[0][col]
is_zero = table[row][col]
# The actual test here:
assert Pow(base, exp, evaluate=False).is_zero is is_zero
test_table(pow_iszero)
# A zero symbol...
zo, zo2 = symbols('zo, zo2', zero=True)
# All combinations of finite symbols
zf, zf2 = symbols('zf, zf2', finite=True)
wf, wf2 = symbols('wf, wf2', nonzero=True)
xf, xf2 = symbols('xf, xf2', real=True)
yf, yf2 = symbols('yf, yf2', nonzero=True)
af, af2 = symbols('af, af2', positive=True)
bf, bf2 = symbols('bf, bf2', nonnegative=True)
cf, cf2 = symbols('cf, cf2', negative=True)
df, df2 = symbols('df, df2', nonpositive=True)
# Without finiteness:
zi, zi2 = symbols('zi, zi2')
wi, wi2 = symbols('wi, wi2', zero=False)
xi, xi2 = symbols('xi, xi2', extended_real=True)
yi, yi2 = symbols('yi, yi2', zero=False, extended_real=True)
ai, ai2 = symbols('ai, ai2', extended_positive=True)
bi, bi2 = symbols('bi, bi2', extended_nonnegative=True)
ci, ci2 = symbols('ci, ci2', extended_negative=True)
di, di2 = symbols('di, di2', extended_nonpositive=True)
pow_iszero_sym = [
['**',zo,wf,yf,af,cf,zf,xf,bf,df,zi,wi,xi,yi,ai,bi,ci,di],
[ zo2, F, N, N, T, F, N, N, N, F, N, N, N, N, T, N, F, F],
[ wf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ yf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ af2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ cf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
[ zf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ xf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ bf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ df2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
[ zi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
[ wi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ xi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
[ yi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ ai2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ bi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
[ ci2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
[ di2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N]
]
test_table(pow_iszero_sym)
# In some cases (x**x).is_zero is different from (x**y).is_zero even if y
# has the same assumptions as x.
assert (zo ** zo).is_zero is False
assert (wf ** wf).is_zero is False
assert (yf ** yf).is_zero is False
assert (af ** af).is_zero is False
assert (cf ** cf).is_zero is False
assert (zf ** zf).is_zero is None
assert (xf ** xf).is_zero is None
assert (bf ** bf).is_zero is False # None in table
assert (df ** df).is_zero is None
assert (zi ** zi).is_zero is None
assert (wi ** wi).is_zero is None
assert (xi ** xi).is_zero is None
assert (yi ** yi).is_zero is None
assert (ai ** ai).is_zero is False # None in table
assert (bi ** bi).is_zero is False # None in table
assert (ci ** ci).is_zero is None
assert (di ** di).is_zero is None
def test_Pow_is_nonpositive_nonnegative():
x = Symbol('x', real=True)
k = Symbol('k', integer=True, nonnegative=True)
l = Symbol('l', integer=True, positive=True)
n = Symbol('n', even=True)
m = Symbol('m', odd=True)
assert (x**(4*k)).is_nonnegative is True
assert (2**x).is_nonnegative is True
assert ((-2)**x).is_nonnegative is None
assert ((-2)**n).is_nonnegative is True
assert ((-2)**m).is_nonnegative is False
assert (k**2).is_nonnegative is True
assert (k**(-2)).is_nonnegative is None
assert (k**k).is_nonnegative is True
assert (k**x).is_nonnegative is None # NOTE (0**x).is_real = U
assert (l**x).is_nonnegative is True
assert (l**x).is_positive is True
assert ((-k)**x).is_nonnegative is None
assert ((-k)**m).is_nonnegative is None
assert (2**x).is_nonpositive is False
assert ((-2)**x).is_nonpositive is None
assert ((-2)**n).is_nonpositive is False
assert ((-2)**m).is_nonpositive is True
assert (k**2).is_nonpositive is None
assert (k**(-2)).is_nonpositive is None
assert (k**x).is_nonpositive is None
assert ((-k)**x).is_nonpositive is None
assert ((-k)**n).is_nonpositive is None
assert (x**2).is_nonnegative is True
i = symbols('i', imaginary=True)
assert (i**2).is_nonpositive is True
assert (i**4).is_nonpositive is False
assert (i**3).is_nonpositive is False
assert (I**i).is_nonnegative is True
assert (exp(I)**i).is_nonnegative is True
assert ((-l)**n).is_nonnegative is True
assert ((-l)**m).is_nonpositive is True
assert ((-k)**n).is_nonnegative is None
assert ((-k)**m).is_nonpositive is None
def test_Mul_is_imaginary_real():
r = Symbol('r', real=True)
p = Symbol('p', positive=True)
i1 = Symbol('i1', imaginary=True)
i2 = Symbol('i2', imaginary=True)
x = Symbol('x')
assert I.is_imaginary is True
assert I.is_real is False
assert (-I).is_imaginary is True
assert (-I).is_real is False
assert (3*I).is_imaginary is True
assert (3*I).is_real is False
assert (I*I).is_imaginary is False
assert (I*I).is_real is True
e = (p + p*I)
j = Symbol('j', integer=True, zero=False)
assert (e**j).is_real is None
assert (e**(2*j)).is_real is None
assert (e**j).is_imaginary is None
assert (e**(2*j)).is_imaginary is None
assert (e**-1).is_imaginary is False
assert (e**2).is_imaginary
assert (e**3).is_imaginary is False
assert (e**4).is_imaginary is False
assert (e**5).is_imaginary is False
assert (e**-1).is_real is False
assert (e**2).is_real is False
assert (e**3).is_real is False
assert (e**4).is_real is True
assert (e**5).is_real is False
assert (e**3).is_complex
assert (r*i1).is_imaginary is None
assert (r*i1).is_real is None
assert (x*i1).is_imaginary is None
assert (x*i1).is_real is None
assert (i1*i2).is_imaginary is False
assert (i1*i2).is_real is True
assert (r*i1*i2).is_imaginary is False
assert (r*i1*i2).is_real is True
# Github's issue 5874:
nr = Symbol('nr', real=False, complex=True) # e.g. I or 1 + I
a = Symbol('a', real=True, nonzero=True)
b = Symbol('b', real=True)
assert (i1*nr).is_real is None
assert (a*nr).is_real is False
assert (b*nr).is_real is None
ni = Symbol('ni', imaginary=False, complex=True) # e.g. 2 or 1 + I
a = Symbol('a', real=True, nonzero=True)
b = Symbol('b', real=True)
assert (i1*ni).is_real is False
assert (a*ni).is_real is None
assert (b*ni).is_real is None
def test_Mul_hermitian_antihermitian():
xz, yz = symbols('xz, yz', zero=True, antihermitian=True)
xf, yf = symbols('xf, yf', hermitian=False, antihermitian=False, finite=True)
xh, yh = symbols('xh, yh', hermitian=True, antihermitian=False, nonzero=True)
xa, ya = symbols('xa, ya', hermitian=False, antihermitian=True, zero=False, finite=True)
assert (xz*xh).is_hermitian is True
assert (xz*xh).is_antihermitian is True
assert (xz*xa).is_hermitian is True
assert (xz*xa).is_antihermitian is True
assert (xf*yf).is_hermitian is None
assert (xf*yf).is_antihermitian is None
assert (xh*yh).is_hermitian is True
assert (xh*yh).is_antihermitian is False
assert (xh*ya).is_hermitian is False
assert (xh*ya).is_antihermitian is True
assert (xa*ya).is_hermitian is True
assert (xa*ya).is_antihermitian is False
a = Symbol('a', hermitian=True, zero=False)
b = Symbol('b', hermitian=True)
c = Symbol('c', hermitian=False)
d = Symbol('d', antihermitian=True)
e1 = Mul(a, b, c, evaluate=False)
e2 = Mul(b, a, c, evaluate=False)
e3 = Mul(a, b, c, d, evaluate=False)
e4 = Mul(b, a, c, d, evaluate=False)
e5 = Mul(a, c, evaluate=False)
e6 = Mul(a, c, d, evaluate=False)
assert e1.is_hermitian is None
assert e2.is_hermitian is None
assert e1.is_antihermitian is None
assert e2.is_antihermitian is None
assert e3.is_antihermitian is None
assert e4.is_antihermitian is None
assert e5.is_antihermitian is None
assert e6.is_antihermitian is None
def test_Add_is_comparable():
assert (x + y).is_comparable is False
assert (x + 1).is_comparable is False
assert (Rational(1, 3) - sqrt(8)).is_comparable is True
def test_Mul_is_comparable():
assert (x*y).is_comparable is False
assert (x*2).is_comparable is False
assert (sqrt(2)*Rational(1, 3)).is_comparable is True
def test_Pow_is_comparable():
assert (x**y).is_comparable is False
assert (x**2).is_comparable is False
assert (sqrt(Rational(1, 3))).is_comparable is True
def test_Add_is_positive_2():
e = Rational(1, 3) - sqrt(8)
assert e.is_positive is False
assert e.is_negative is True
e = pi - 1
assert e.is_positive is True
assert e.is_negative is False
def test_Add_is_irrational():
i = Symbol('i', irrational=True)
assert i.is_irrational is True
assert i.is_rational is False
assert (i + 1).is_irrational is True
assert (i + 1).is_rational is False
def test_Mul_is_irrational():
expr = Mul(1, 2, 3, evaluate=False)
assert expr.is_irrational is False
expr = Mul(1, I, I, evaluate=False)
assert expr.is_rational is None # I * I = -1 but *no evaluation allowed*
# sqrt(2) * I * I = -sqrt(2) is irrational but
# this can't be determined without evaluating the
# expression and the eval_is routines shouldn't do that
expr = Mul(sqrt(2), I, I, evaluate=False)
assert expr.is_irrational is None
def test_issue_3531():
# https://github.com/sympy/sympy/issues/3531
# https://github.com/sympy/sympy/pull/18116
class MightyNumeric(tuple):
def __rtruediv__(self, other):
return "something"
assert sympify(1)/MightyNumeric((1, 2)) == "something"
def test_issue_3531b():
class Foo:
def __init__(self):
self.field = 1.0
def __mul__(self, other):
self.field = self.field * other
def __rmul__(self, other):
self.field = other * self.field
f = Foo()
x = Symbol("x")
assert f*x == x*f
def test_bug3():
a = Symbol("a")
b = Symbol("b", positive=True)
e = 2*a + b
f = b + 2*a
assert e == f
def test_suppressed_evaluation():
a = Add(0, 3, 2, evaluate=False)
b = Mul(1, 3, 2, evaluate=False)
c = Pow(3, 2, evaluate=False)
assert a != 6
assert a.func is Add
assert a.args == (0, 3, 2)
assert b != 6
assert b.func is Mul
assert b.args == (1, 3, 2)
assert c != 9
assert c.func is Pow
assert c.args == (3, 2)
def test_AssocOp_doit():
a = Add(x,x, evaluate=False)
b = Mul(y,y, evaluate=False)
c = Add(b,b, evaluate=False)
d = Mul(a,a, evaluate=False)
assert c.doit(deep=False).func == Mul
assert c.doit(deep=False).args == (2,y,y)
assert c.doit().func == Mul
assert c.doit().args == (2, Pow(y,2))
assert d.doit(deep=False).func == Pow
assert d.doit(deep=False).args == (a, 2*S.One)
assert d.doit().func == Mul
assert d.doit().args == (4*S.One, Pow(x,2))
def test_Add_Mul_Expr_args():
nonexpr = [Basic(), Poly(x, x), FiniteSet(x)]
for typ in [Add, Mul]:
for obj in nonexpr:
# The cache can mess with the stacklevel check
with warns(SymPyDeprecationWarning, test_stacklevel=False):
typ(obj, 1)
def test_Add_as_coeff_mul():
# issue 5524. These should all be (1, self)
assert (x + 1).as_coeff_mul() == (1, (x + 1,))
assert (x + 2).as_coeff_mul() == (1, (x + 2,))
assert (x + 3).as_coeff_mul() == (1, (x + 3,))
assert (x - 1).as_coeff_mul() == (1, (x - 1,))
assert (x - 2).as_coeff_mul() == (1, (x - 2,))
assert (x - 3).as_coeff_mul() == (1, (x - 3,))
n = Symbol('n', integer=True)
assert (n + 1).as_coeff_mul() == (1, (n + 1,))
assert (n + 2).as_coeff_mul() == (1, (n + 2,))
assert (n + 3).as_coeff_mul() == (1, (n + 3,))
assert (n - 1).as_coeff_mul() == (1, (n - 1,))
assert (n - 2).as_coeff_mul() == (1, (n - 2,))
assert (n - 3).as_coeff_mul() == (1, (n - 3,))
def test_Pow_as_coeff_mul_doesnt_expand():
assert exp(x + y).as_coeff_mul() == (1, (exp(x + y),))
assert exp(x + exp(x + y)) != exp(x + exp(x)*exp(y))
def test_issue_3514_18626():
assert sqrt(S.Half) * sqrt(6) == 2 * sqrt(3)/2
assert S.Half*sqrt(6)*sqrt(2) == sqrt(3)
assert sqrt(6)/2*sqrt(2) == sqrt(3)
assert sqrt(6)*sqrt(2)/2 == sqrt(3)
assert sqrt(8)**Rational(2, 3) == 2
def test_make_args():
assert Add.make_args(x) == (x,)
assert Mul.make_args(x) == (x,)
assert Add.make_args(x*y*z) == (x*y*z,)
assert Mul.make_args(x*y*z) == (x*y*z).args
assert Add.make_args(x + y + z) == (x + y + z).args
assert Mul.make_args(x + y + z) == (x + y + z,)
assert Add.make_args((x + y)**z) == ((x + y)**z,)
assert Mul.make_args((x + y)**z) == ((x + y)**z,)
def test_issue_5126():
assert (-2)**x*(-3)**x != 6**x
i = Symbol('i', integer=1)
assert (-2)**i*(-3)**i == 6**i
def test_Rational_as_content_primitive():
c, p = S.One, S.Zero
assert (c*p).as_content_primitive() == (c, p)
c, p = S.Half, S.One
assert (c*p).as_content_primitive() == (c, p)
def test_Add_as_content_primitive():
assert (x + 2).as_content_primitive() == (1, x + 2)
assert (3*x + 2).as_content_primitive() == (1, 3*x + 2)
assert (3*x + 3).as_content_primitive() == (3, x + 1)
assert (3*x + 6).as_content_primitive() == (3, x + 2)
assert (3*x + 2*y).as_content_primitive() == (1, 3*x + 2*y)
assert (3*x + 3*y).as_content_primitive() == (3, x + y)
assert (3*x + 6*y).as_content_primitive() == (3, x + 2*y)
assert (3/x + 2*x*y*z**2).as_content_primitive() == (1, 3/x + 2*x*y*z**2)
assert (3/x + 3*x*y*z**2).as_content_primitive() == (3, 1/x + x*y*z**2)
assert (3/x + 6*x*y*z**2).as_content_primitive() == (3, 1/x + 2*x*y*z**2)
assert (2*x/3 + 4*y/9).as_content_primitive() == \
(Rational(2, 9), 3*x + 2*y)
assert (2*x/3 + 2.5*y).as_content_primitive() == \
(Rational(1, 3), 2*x + 7.5*y)
# the coefficient may sort to a position other than 0
p = 3 + x + y
assert (2*p).expand().as_content_primitive() == (2, p)
assert (2.0*p).expand().as_content_primitive() == (1, 2.*p)
p *= -1
assert (2*p).expand().as_content_primitive() == (2, p)
def test_Mul_as_content_primitive():
assert (2*x).as_content_primitive() == (2, x)
assert (x*(2 + 2*x)).as_content_primitive() == (2, x*(1 + x))
assert (x*(2 + 2*y)*(3*x + 3)**2).as_content_primitive() == \
(18, x*(1 + y)*(x + 1)**2)
assert ((2 + 2*x)**2*(3 + 6*x) + S.Half).as_content_primitive() == \
(S.Half, 24*(x + 1)**2*(2*x + 1) + 1)
def test_Pow_as_content_primitive():
assert (x**y).as_content_primitive() == (1, x**y)
assert ((2*x + 2)**y).as_content_primitive() == \
(1, (Mul(2, (x + 1), evaluate=False))**y)
assert ((2*x + 2)**3).as_content_primitive() == (8, (x + 1)**3)
def test_issue_5460():
u = Mul(2, (1 + x), evaluate=False)
assert (2 + u).args == (2, u)
def test_product_irrational():
assert (I*pi).is_irrational is False
# The following used to be deduced from the above bug:
assert (I*pi).is_positive is False
def test_issue_5919():
assert (x/(y*(1 + y))).expand() == x/(y**2 + y)
def test_Mod():
assert Mod(x, 1).func is Mod
assert pi % pi is S.Zero
assert Mod(5, 3) == 2
assert Mod(-5, 3) == 1
assert Mod(5, -3) == -1
assert Mod(-5, -3) == -2
assert type(Mod(3.2, 2, evaluate=False)) == Mod
assert 5 % x == Mod(5, x)
assert x % 5 == Mod(x, 5)
assert x % y == Mod(x, y)
assert (x % y).subs({x: 5, y: 3}) == 2
assert Mod(nan, 1) is nan
assert Mod(1, nan) is nan
assert Mod(nan, nan) is nan
assert Mod(0, x) == 0
with raises(ZeroDivisionError):
Mod(x, 0)
k = Symbol('k', integer=True)
m = Symbol('m', integer=True, positive=True)
assert (x**m % x).func is Mod
assert (k**(-m) % k).func is Mod
assert k**m % k == 0
assert (-2*k)**m % k == 0
# Float handling
point3 = Float(3.3) % 1
assert (x - 3.3) % 1 == Mod(1.*x + 1 - point3, 1)
assert Mod(-3.3, 1) == 1 - point3
assert Mod(0.7, 1) == Float(0.7)
e = Mod(1.3, 1)
assert comp(e, .3) and e.is_Float
e = Mod(1.3, .7)
assert comp(e, .6) and e.is_Float
e = Mod(1.3, Rational(7, 10))
assert comp(e, .6) and e.is_Float
e = Mod(Rational(13, 10), 0.7)
assert comp(e, .6) and e.is_Float
e = Mod(Rational(13, 10), Rational(7, 10))
assert comp(e, .6) and e.is_Rational
# check that sign is right
r2 = sqrt(2)
r3 = sqrt(3)
for i in [-r3, -r2, r2, r3]:
for j in [-r3, -r2, r2, r3]:
assert verify_numerically(i % j, i.n() % j.n())
for _x in range(4):
for _y in range(9):
reps = [(x, _x), (y, _y)]
assert Mod(3*x + y, 9).subs(reps) == (3*_x + _y) % 9
# denesting
t = Symbol('t', real=True)
assert Mod(Mod(x, t), t) == Mod(x, t)
assert Mod(-Mod(x, t), t) == Mod(-x, t)
assert Mod(Mod(x, 2*t), t) == Mod(x, t)
assert Mod(-Mod(x, 2*t), t) == Mod(-x, t)
assert Mod(Mod(x, t), 2*t) == Mod(x, t)
assert Mod(-Mod(x, t), -2*t) == -Mod(x, t)
for i in [-4, -2, 2, 4]:
for j in [-4, -2, 2, 4]:
for k in range(4):
assert Mod(Mod(x, i), j).subs({x: k}) == (k % i) % j
assert Mod(-Mod(x, i), j).subs({x: k}) == -(k % i) % j
# known difference
assert Mod(5*sqrt(2), sqrt(5)) == 5*sqrt(2) - 3*sqrt(5)
p = symbols('p', positive=True)
assert Mod(2, p + 3) == 2
assert Mod(-2, p + 3) == p + 1
assert Mod(2, -p - 3) == -p - 1
assert Mod(-2, -p - 3) == -2
assert Mod(p + 5, p + 3) == 2
assert Mod(-p - 5, p + 3) == p + 1
assert Mod(p + 5, -p - 3) == -p - 1
assert Mod(-p - 5, -p - 3) == -2
assert Mod(p + 1, p - 1).func is Mod
# handling sums
assert (x + 3) % 1 == Mod(x, 1)
assert (x + 3.0) % 1 == Mod(1.*x, 1)
assert (x - S(33)/10) % 1 == Mod(x + S(7)/10, 1)
a = Mod(.6*x + y, .3*y)
b = Mod(0.1*y + 0.6*x, 0.3*y)
# Test that a, b are equal, with 1e-14 accuracy in coefficients
eps = 1e-14
assert abs((a.args[0] - b.args[0]).subs({x: 1, y: 1})) < eps
assert abs((a.args[1] - b.args[1]).subs({x: 1, y: 1})) < eps
assert (x + 1) % x == 1 % x
assert (x + y) % x == y % x
assert (x + y + 2) % x == (y + 2) % x
assert (a + 3*x + 1) % (2*x) == Mod(a + x + 1, 2*x)
assert (12*x + 18*y) % (3*x) == 3*Mod(6*y, x)
# gcd extraction
assert (-3*x) % (-2*y) == -Mod(3*x, 2*y)
assert (.6*pi) % (.3*x*pi) == 0.3*pi*Mod(2, x)
assert (.6*pi) % (.31*x*pi) == pi*Mod(0.6, 0.31*x)
assert (6*pi) % (.3*x*pi) == 0.3*pi*Mod(20, x)
assert (6*pi) % (.31*x*pi) == pi*Mod(6, 0.31*x)
assert (6*pi) % (.42*x*pi) == pi*Mod(6, 0.42*x)
assert (12*x) % (2*y) == 2*Mod(6*x, y)
assert (12*x) % (3*5*y) == 3*Mod(4*x, 5*y)
assert (12*x) % (15*x*y) == 3*x*Mod(4, 5*y)
assert (-2*pi) % (3*pi) == pi
assert (2*x + 2) % (x + 1) == 0
assert (x*(x + 1)) % (x + 1) == (x + 1)*Mod(x, 1)
assert Mod(5.0*x, 0.1*y) == 0.1*Mod(50*x, y)
i = Symbol('i', integer=True)
assert (3*i*x) % (2*i*y) == i*Mod(3*x, 2*y)
assert Mod(4*i, 4) == 0
# issue 8677
n = Symbol('n', integer=True, positive=True)
assert factorial(n) % n == 0
assert factorial(n + 2) % n == 0
assert (factorial(n + 4) % (n + 5)).func is Mod
# Wilson's theorem
assert factorial(18042, evaluate=False) % 18043 == 18042
p = Symbol('n', prime=True)
assert factorial(p - 1) % p == p - 1
assert factorial(p - 1) % -p == -1
assert (factorial(3, evaluate=False) % 4).doit() == 2
n = Symbol('n', composite=True, odd=True)
assert factorial(n - 1) % n == 0
# symbolic with known parity
n = Symbol('n', even=True)
assert Mod(n, 2) == 0
n = Symbol('n', odd=True)
assert Mod(n, 2) == 1
# issue 10963
assert (x**6000%400).args[1] == 400
#issue 13543
assert Mod(Mod(x + 1, 2) + 1, 2) == Mod(x, 2)
assert Mod(Mod(x + 2, 4)*(x + 4), 4) == Mod(x*(x + 2), 4)
assert Mod(Mod(x + 2, 4)*4, 4) == 0
# issue 15493
i, j = symbols('i j', integer=True, positive=True)
assert Mod(3*i, 2) == Mod(i, 2)
assert Mod(8*i/j, 4) == 4*Mod(2*i/j, 1)
assert Mod(8*i, 4) == 0
# rewrite
assert Mod(x, y).rewrite(floor) == x - y*floor(x/y)
assert ((x - Mod(x, y))/y).rewrite(floor) == floor(x/y)
# issue 21373
from sympy.functions.elementary.hyperbolic import sinh
from sympy.functions.elementary.piecewise import Piecewise
x_r, y_r = symbols('x_r y_r', real=True)
assert (Piecewise((x_r, y_r > x_r), (y_r, True)) / z) % 1
expr = exp(sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) / z))
expr.subs({1: 1.0})
sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) * z ** -1.0).is_zero
def test_Mod_Pow():
# modular exponentiation
assert isinstance(Mod(Pow(2, 2, evaluate=False), 3), Integer)
assert Mod(Pow(4, 13, evaluate=False), 497) == Mod(Pow(4, 13), 497)
assert Mod(Pow(2, 10000000000, evaluate=False), 3) == 1
assert Mod(Pow(32131231232, 9**10**6, evaluate=False),10**12) == \
pow(32131231232,9**10**6,10**12)
assert Mod(Pow(33284959323, 123**999, evaluate=False),11**13) == \
pow(33284959323,123**999,11**13)
assert Mod(Pow(78789849597, 333**555, evaluate=False),12**9) == \
pow(78789849597,333**555,12**9)
# modular nested exponentiation
expr = Pow(2, 2, evaluate=False)
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 16
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 6487
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 32191
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 18016
expr = Pow(2, expr, evaluate=False)
assert Mod(expr, 3**10) == 5137
expr = Pow(2, 2, evaluate=False)
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 16
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 256
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 6487
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 38281
expr = Pow(expr, 2, evaluate=False)
assert Mod(expr, 3**10) == 15928
expr = Pow(2, 2, evaluate=False)
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 256
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 9229
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 25708
expr = Pow(expr, expr, evaluate=False)
assert Mod(expr, 3**10) == 26608
expr = Pow(expr, expr, evaluate=False)
# XXX This used to fail in a nondeterministic way because of overflow
# error.
assert Mod(expr, 3**10) == 1966
def test_Mod_is_integer():
p = Symbol('p', integer=True)
q1 = Symbol('q1', integer=True)
q2 = Symbol('q2', integer=True, nonzero=True)
assert Mod(x, y).is_integer is None
assert Mod(p, q1).is_integer is None
assert Mod(x, q2).is_integer is None
assert Mod(p, q2).is_integer
def test_Mod_is_nonposneg():
n = Symbol('n', integer=True)
k = Symbol('k', integer=True, positive=True)
assert (n%3).is_nonnegative
assert Mod(n, -3).is_nonpositive
assert Mod(n, k).is_nonnegative
assert Mod(n, -k).is_nonpositive
assert Mod(k, n).is_nonnegative is None
def test_issue_6001():
A = Symbol("A", commutative=False)
eq = A + A**2
# it doesn't matter whether it's True or False; they should
# just all be the same
assert (
eq.is_commutative ==
(eq + 1).is_commutative ==
(A + 1).is_commutative)
B = Symbol("B", commutative=False)
# Although commutative terms could cancel we return True
# meaning "there are non-commutative symbols; aftersubstitution
# that definition can change, e.g. (A*B).subs(B,A**-1) -> 1
assert (sqrt(2)*A).is_commutative is False
assert (sqrt(2)*A*B).is_commutative is False
def test_polar():
from sympy.functions.elementary.complexes import polar_lift
p = Symbol('p', polar=True)
x = Symbol('x')
assert p.is_polar
assert x.is_polar is None
assert S.One.is_polar is None
assert (p**x).is_polar is True
assert (x**p).is_polar is None
assert ((2*p)**x).is_polar is True
assert (2*p).is_polar is True
assert (-2*p).is_polar is not True
assert (polar_lift(-2)*p).is_polar is True
q = Symbol('q', polar=True)
assert (p*q)**2 == p**2 * q**2
assert (2*q)**2 == 4 * q**2
assert ((p*q)**x).expand() == p**x * q**x
def test_issue_6040():
a, b = Pow(1, 2, evaluate=False), S.One
assert a != b
assert b != a
assert not (a == b)
assert not (b == a)
def test_issue_6082():
# Comparison is symmetric
assert Basic.compare(Max(x, 1), Max(x, 2)) == \
- Basic.compare(Max(x, 2), Max(x, 1))
# Equal expressions compare equal
assert Basic.compare(Max(x, 1), Max(x, 1)) == 0
# Basic subtypes (such as Max) compare different than standard types
assert Basic.compare(Max(1, x), frozenset((1, x))) != 0
def test_issue_6077():
assert x**2.0/x == x**1.0
assert x/x**2.0 == x**-1.0
assert x*x**2.0 == x**3.0
assert x**1.5*x**2.5 == x**4.0
assert 2**(2.0*x)/2**x == 2**(1.0*x)
assert 2**x/2**(2.0*x) == 2**(-1.0*x)
assert 2**x*2**(2.0*x) == 2**(3.0*x)
assert 2**(1.5*x)*2**(2.5*x) == 2**(4.0*x)
def test_mul_flatten_oo():
p = symbols('p', positive=True)
n, m = symbols('n,m', negative=True)
x_im = symbols('x_im', imaginary=True)
assert n*oo is -oo
assert n*m*oo is oo
assert p*oo is oo
assert x_im*oo != I*oo # i could be +/- 3*I -> +/-oo
def test_add_flatten():
# see https://github.com/sympy/sympy/issues/2633#issuecomment-29545524
a = oo + I*oo
b = oo - I*oo
assert a + b is nan
assert a - b is nan
# FIXME: This evaluates as:
# >>> 1/a
# 0*(oo + oo*I)
# which should not simplify to 0. Should be fixed in Pow.eval
#assert (1/a).simplify() == (1/b).simplify() == 0
a = Pow(2, 3, evaluate=False)
assert a + a == 16
def test_issue_5160_6087_6089_6090():
# issue 6087
assert ((-2*x*y**y)**3.2).n(2) == (2**3.2*(-x*y**y)**3.2).n(2)
# issue 6089
A, B, C = symbols('A,B,C', commutative=False)
assert (2.*B*C)**3 == 8.0*(B*C)**3
assert (-2.*B*C)**3 == -8.0*(B*C)**3
assert (-2*B*C)**2 == 4*(B*C)**2
# issue 5160
assert sqrt(-1.0*x) == 1.0*sqrt(-x)
assert sqrt(1.0*x) == 1.0*sqrt(x)
# issue 6090
assert (-2*x*y*A*B)**2 == 4*x**2*y**2*(A*B)**2
def test_float_int_round():
assert int(float(sqrt(10))) == int(sqrt(10))
assert int(pi**1000) % 10 == 2
assert int(Float('1.123456789012345678901234567890e20', '')) == \
int(112345678901234567890)
assert int(Float('1.123456789012345678901234567890e25', '')) == \
int(11234567890123456789012345)
# decimal forces float so it's not an exact integer ending in 000000
assert int(Float('1.123456789012345678901234567890e35', '')) == \
112345678901234567890123456789000192
assert int(Float('123456789012345678901234567890e5', '')) == \
12345678901234567890123456789000000
assert Integer(Float('1.123456789012345678901234567890e20', '')) == \
112345678901234567890
assert Integer(Float('1.123456789012345678901234567890e25', '')) == \
11234567890123456789012345
# decimal forces float so it's not an exact integer ending in 000000
assert Integer(Float('1.123456789012345678901234567890e35', '')) == \
112345678901234567890123456789000192
assert Integer(Float('123456789012345678901234567890e5', '')) == \
12345678901234567890123456789000000
assert same_and_same_prec(Float('123000e-2',''), Float('1230.00', ''))
assert same_and_same_prec(Float('123000e2',''), Float('12300000', ''))
assert int(1 + Rational('.9999999999999999999999999')) == 1
assert int(pi/1e20) == 0
assert int(1 + pi/1e20) == 1
assert int(Add(1.2, -2, evaluate=False)) == int(1.2 - 2)
assert int(Add(1.2, +2, evaluate=False)) == int(1.2 + 2)
assert int(Add(1 + Float('.99999999999999999', ''), evaluate=False)) == 1
raises(TypeError, lambda: float(x))
raises(TypeError, lambda: float(sqrt(-1)))
assert int(12345678901234567890 + cos(1)**2 + sin(1)**2) == \
12345678901234567891
def test_issue_6611a():
assert Mul.flatten([3**Rational(1, 3),
Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \
([Rational(1, 3), (-1)**Rational(2, 3)], [], None)
def test_denest_add_mul():
# when working with evaluated expressions make sure they denest
eq = x + 1
eq = Add(eq, 2, evaluate=False)
eq = Add(eq, 2, evaluate=False)
assert Add(*eq.args) == x + 5
eq = x*2
eq = Mul(eq, 2, evaluate=False)
eq = Mul(eq, 2, evaluate=False)
assert Mul(*eq.args) == 8*x
# but don't let them denest unecessarily
eq = Mul(-2, x - 2, evaluate=False)
assert 2*eq == Mul(-4, x - 2, evaluate=False)
assert -eq == Mul(2, x - 2, evaluate=False)
def test_mul_coeff():
# It is important that all Numbers be removed from the seq;
# This can be tricky when powers combine to produce those numbers
p = exp(I*pi/3)
assert p**2*x*p*y*p*x*p**2 == x**2*y
def test_mul_zero_detection():
nz = Dummy(real=True, zero=False)
r = Dummy(extended_real=True)
c = Dummy(real=False, complex=True)
c2 = Dummy(real=False, complex=True)
i = Dummy(imaginary=True)
e = nz*r*c
assert e.is_imaginary is None
assert e.is_extended_real is None
e = nz*c
assert e.is_imaginary is None
assert e.is_extended_real is False
e = nz*i*c
assert e.is_imaginary is False
assert e.is_extended_real is None
# check for more than one complex; it is important to use
# uniquely named Symbols to ensure that two factors appear
# e.g. if the symbols have the same name they just become
# a single factor, a power.
e = nz*i*c*c2
assert e.is_imaginary is None
assert e.is_extended_real is None
# _eval_is_extended_real and _eval_is_zero both employ trapping of the
# zero value so args should be tested in both directions and
# TO AVOID GETTING THE CACHED RESULT, Dummy MUST BE USED
# real is unknown
def test(z, b, e):
if z.is_zero and b.is_finite:
assert e.is_extended_real and e.is_zero
else:
assert e.is_extended_real is None
if b.is_finite:
if z.is_zero:
assert e.is_zero
else:
assert e.is_zero is None
elif b.is_finite is False:
if z.is_zero is None:
assert e.is_zero is None
else:
assert e.is_zero is False
for iz, ib in product(*[[True, False, None]]*2):
z = Dummy('z', nonzero=iz)
b = Dummy('f', finite=ib)
e = Mul(z, b, evaluate=False)
test(z, b, e)
z = Dummy('nz', nonzero=iz)
b = Dummy('f', finite=ib)
e = Mul(b, z, evaluate=False)
test(z, b, e)
# real is True
def test(z, b, e):
if z.is_zero and not b.is_finite:
assert e.is_extended_real is None
else:
assert e.is_extended_real is True
for iz, ib in product(*[[True, False, None]]*2):
z = Dummy('z', nonzero=iz, extended_real=True)
b = Dummy('b', finite=ib, extended_real=True)
e = Mul(z, b, evaluate=False)
test(z, b, e)
z = Dummy('z', nonzero=iz, extended_real=True)
b = Dummy('b', finite=ib, extended_real=True)
e = Mul(b, z, evaluate=False)
test(z, b, e)
def test_Mul_with_zero_infinite():
zer = Dummy(zero=True)
inf = Dummy(finite=False)
e = Mul(zer, inf, evaluate=False)
assert e.is_extended_positive is None
assert e.is_hermitian is None
e = Mul(inf, zer, evaluate=False)
assert e.is_extended_positive is None
assert e.is_hermitian is None
def test_Mul_does_not_cancel_infinities():
a, b = symbols('a b')
assert ((zoo + 3*a)/(3*a + zoo)) is nan
assert ((b - oo)/(b - oo)) is nan
# issue 13904
expr = (1/(a+b) + 1/(a-b))/(1/(a+b) - 1/(a-b))
assert expr.subs(b, a) is nan
def test_Mul_does_not_distribute_infinity():
a, b = symbols('a b')
assert ((1 + I)*oo).is_Mul
assert ((a + b)*(-oo)).is_Mul
assert ((a + 1)*zoo).is_Mul
assert ((1 + I)*oo).is_finite is False
z = (1 + I)*oo
assert ((1 - I)*z).expand() is oo
def test_issue_8247_8354():
from sympy.functions.elementary.trigonometric import tan
z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
assert z.is_positive is False # it's 0
z = S('''-2**(1/3)*(3*sqrt(93) + 29)**2 - 4*(3*sqrt(93) + 29)**(4/3) +
12*sqrt(93)*(3*sqrt(93) + 29)**(1/3) + 116*(3*sqrt(93) + 29)**(1/3) +
174*2**(1/3)*sqrt(93) + 1678*2**(1/3)''')
assert z.is_positive is False # it's 0
z = 2*(-3*tan(19*pi/90) + sqrt(3))*cos(11*pi/90)*cos(19*pi/90) - \
sqrt(3)*(-3 + 4*cos(19*pi/90)**2)
assert z.is_positive is not True # it's zero and it shouldn't hang
z = S('''9*(3*sqrt(93) + 29)**(2/3)*((3*sqrt(93) +
29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**3 +
72*(3*sqrt(93) + 29)**(2/3)*(81*sqrt(93) + 783) + (162*sqrt(93) +
1566)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) -
2) - 2*2**(1/3))**2''')
assert z.is_positive is False # it's 0 (and a single _mexpand isn't enough)
def test_Add_is_zero():
x, y = symbols('x y', zero=True)
assert (x + y).is_zero
# Issue 15873
e = -2*I + (1 + I)**2
assert e.is_zero is None
def test_issue_14392():
assert (sin(zoo)**2).as_real_imag() == (nan, nan)
def test_divmod():
assert divmod(x, y) == (x//y, x % y)
assert divmod(x, 3) == (x//3, x % 3)
assert divmod(3, x) == (3//x, 3 % x)
def test__neg__():
assert -(x*y) == -x*y
assert -(-x*y) == x*y
assert -(1.*x) == -1.*x
assert -(-1.*x) == 1.*x
assert -(2.*x) == -2.*x
assert -(-2.*x) == 2.*x
with distribute(False):
eq = -(x + y)
assert eq.is_Mul and eq.args == (-1, x + y)
def test_issue_18507():
assert Mul(zoo, zoo, 0) is nan
def test_issue_17130():
e = Add(b, -b, I, -I, evaluate=False)
assert e.is_zero is None # ideally this would be True
def test_issue_21034():
e = -I*log((re(asin(5)) + I*im(asin(5)))/sqrt(re(asin(5))**2 + im(asin(5))**2))/pi
assert e.round(2)
def test_issue_22021():
from sympy.calculus.accumulationbounds import AccumBounds
# these objects are special cases in Mul
from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
L = TensorIndexType("L")
i = tensor_indices("i", L)
A, B = tensor_heads("A B", [L])
e = A(i) + B(i)
assert -e == -1*e
e = zoo + x
assert -e == -1*e
a = AccumBounds(1, 2)
e = a + x
assert -e == -1*e
for args in permutations((zoo, a, x)):
e = Add(*args, evaluate=False)
assert -e == -1*e
assert 2*Add(1, x, x, evaluate=False) == 4*x + 2
def test_issue_22244():
assert -(zoo*x) == zoo*x
def test_issue_22453():
from sympy.utilities.iterables import cartes
e = Symbol('e', extended_positive=True)
for a, b in cartes(*[[oo, -oo, 3]]*2):
if a == b == 3:
continue
i = a + I*b
assert i**(1 + e) is S.ComplexInfinity
assert i**-e is S.Zero
assert unchanged(Pow, i, e)
assert 1/(oo + I*oo) is S.Zero
r, i = [Dummy(infinite=True, extended_real=True) for _ in range(2)]
assert 1/(r + I*i) is S.Zero
assert 1/(3 + I*i) is S.Zero
assert 1/(r + I*3) is S.Zero
def test_issue_22613():
assert (0**(x - 2)).as_content_primitive() == (1, 0**(x - 2))
assert (0**(x + 2)).as_content_primitive() == (1, 0**(x + 2))
|
613111b91af7d10b5fc584747ab5ef246f03f8835ef5168c14017464cf87e0ab | """Tests for efficient functions for generating Appell sequences."""
from sympy.core.numbers import Rational as Q
from sympy.polys.polytools import Poly
from sympy.testing.pytest import raises
from sympy.polys.appellseqs import (bernoulli_poly, bernoulli_c_poly,
euler_poly, genocchi_poly, andre_poly)
from sympy.abc import x
def test_bernoulli_poly():
raises(ValueError, lambda: bernoulli_poly(-1, x))
assert bernoulli_poly(1, x, polys=True) == Poly(x - Q(1,2))
assert bernoulli_poly(0, x) == 1
assert bernoulli_poly(1, x) == x - Q(1,2)
assert bernoulli_poly(2, x) == x**2 - x + Q(1,6)
assert bernoulli_poly(3, x) == x**3 - Q(3,2)*x**2 + Q(1,2)*x
assert bernoulli_poly(4, x) == x**4 - 2*x**3 + x**2 - Q(1,30)
assert bernoulli_poly(5, x) == x**5 - Q(5,2)*x**4 + Q(5,3)*x**3 - Q(1,6)*x
assert bernoulli_poly(6, x) == x**6 - 3*x**5 + Q(5,2)*x**4 - Q(1,2)*x**2 + Q(1,42)
assert bernoulli_poly(1).dummy_eq(x - Q(1,2))
assert bernoulli_poly(1, polys=True) == Poly(x - Q(1,2))
def test_bernoulli_c_poly():
raises(ValueError, lambda: bernoulli_c_poly(-1, x))
assert bernoulli_c_poly(1, x, polys=True) == Poly(x, domain='QQ')
assert bernoulli_c_poly(0, x) == 1
assert bernoulli_c_poly(1, x) == x
assert bernoulli_c_poly(2, x) == x**2 - Q(1,3)
assert bernoulli_c_poly(3, x) == x**3 - x
assert bernoulli_c_poly(4, x) == x**4 - 2*x**2 + Q(7,15)
assert bernoulli_c_poly(5, x) == x**5 - Q(10,3)*x**3 + Q(7,3)*x
assert bernoulli_c_poly(6, x) == x**6 - 5*x**4 + 7*x**2 - Q(31,21)
assert bernoulli_c_poly(1).dummy_eq(x)
assert bernoulli_c_poly(1, polys=True) == Poly(x, domain='QQ')
assert 2**8 * bernoulli_poly(8, (x+1)/2).expand() == bernoulli_c_poly(8, x)
assert 2**9 * bernoulli_poly(9, (x+1)/2).expand() == bernoulli_c_poly(9, x)
def test_genocchi_poly():
raises(ValueError, lambda: genocchi_poly(-1, x))
assert genocchi_poly(2, x, polys=True) == Poly(-2*x + 1)
assert genocchi_poly(0, x) == 0
assert genocchi_poly(1, x) == -1
assert genocchi_poly(2, x) == 1 - 2*x
assert genocchi_poly(3, x) == 3*x - 3*x**2
assert genocchi_poly(4, x) == -1 + 6*x**2 - 4*x**3
assert genocchi_poly(5, x) == -5*x + 10*x**3 - 5*x**4
assert genocchi_poly(6, x) == 3 - 15*x**2 + 15*x**4 - 6*x**5
assert genocchi_poly(2).dummy_eq(-2*x + 1)
assert genocchi_poly(2, polys=True) == Poly(-2*x + 1)
assert 2 * (bernoulli_poly(8, x) - bernoulli_c_poly(8, x)) == genocchi_poly(8, x)
assert 2 * (bernoulli_poly(9, x) - bernoulli_c_poly(9, x)) == genocchi_poly(9, x)
def test_euler_poly():
raises(ValueError, lambda: euler_poly(-1, x))
assert euler_poly(1, x, polys=True) == Poly(x - Q(1,2))
assert euler_poly(0, x) == 1
assert euler_poly(1, x) == x - Q(1,2)
assert euler_poly(2, x) == x**2 - x
assert euler_poly(3, x) == x**3 - Q(3,2)*x**2 + Q(1,4)
assert euler_poly(4, x) == x**4 - 2*x**3 + x
assert euler_poly(5, x) == x**5 - Q(5,2)*x**4 + Q(5,2)*x**2 - Q(1,2)
assert euler_poly(6, x) == x**6 - 3*x**5 + 5*x**3 - 3*x
assert euler_poly(1).dummy_eq(x - Q(1,2))
assert euler_poly(1, polys=True) == Poly(x - Q(1,2))
assert genocchi_poly(9, x) == euler_poly(8, x) * -9
assert genocchi_poly(10, x) == euler_poly(9, x) * -10
def test_andre_poly():
raises(ValueError, lambda: andre_poly(-1, x))
assert andre_poly(1, x, polys=True) == Poly(x)
assert andre_poly(0, x) == 1
assert andre_poly(1, x) == x
assert andre_poly(2, x) == x**2 - 1
assert andre_poly(3, x) == x**3 - 3*x
assert andre_poly(4, x) == x**4 - 6*x**2 + 5
assert andre_poly(5, x) == x**5 - 10*x**3 + 25*x
assert andre_poly(6, x) == x**6 - 15*x**4 + 75*x**2 - 61
assert andre_poly(1).dummy_eq(x)
assert andre_poly(1, polys=True) == Poly(x)
|
5292703e59aa677219b5685a2dc7e14791322a3e3dfd5a6bb91948d9d2bf0309 | """Tests for efficient functions for generating orthogonal polynomials. """
from sympy.core.numbers import Rational as Q
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.polys.polytools import Poly
from sympy.testing.pytest import raises
from sympy.polys.orthopolys import (
jacobi_poly,
gegenbauer_poly,
chebyshevt_poly,
chebyshevu_poly,
hermite_poly,
hermite_prob_poly,
legendre_poly,
laguerre_poly,
spherical_bessel_fn,
)
from sympy.abc import x, a, b
def test_jacobi_poly():
raises(ValueError, lambda: jacobi_poly(-1, a, b, x))
assert jacobi_poly(1, a, b, x, polys=True) == Poly(
(a/2 + b/2 + 1)*x + a/2 - b/2, x, domain='ZZ(a,b)')
assert jacobi_poly(0, a, b, x) == 1
assert jacobi_poly(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1)
assert jacobi_poly(2, a, b, x) == (a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 +
x**2*(a**2/8 + a*b/4 + a*Q(7, 8) + b**2/8 +
b*Q(7, 8) + Q(3, 2)) + x*(a**2/4 +
a*Q(3, 4) - b**2/4 - b*Q(3, 4)) - S.Half)
assert jacobi_poly(1, a, b, polys=True) == Poly(
(a/2 + b/2 + 1)*x + a/2 - b/2, x, domain='ZZ(a,b)')
def test_gegenbauer_poly():
raises(ValueError, lambda: gegenbauer_poly(-1, a, x))
assert gegenbauer_poly(
1, a, x, polys=True) == Poly(2*a*x, x, domain='ZZ(a)')
assert gegenbauer_poly(0, a, x) == 1
assert gegenbauer_poly(1, a, x) == 2*a*x
assert gegenbauer_poly(2, a, x) == -a + x**2*(2*a**2 + 2*a)
assert gegenbauer_poly(
3, a, x) == x**3*(4*a**3/3 + 4*a**2 + a*Q(8, 3)) + x*(-2*a**2 - 2*a)
assert gegenbauer_poly(1, S.Half).dummy_eq(x)
assert gegenbauer_poly(1, a, polys=True) == Poly(2*a*x, x, domain='ZZ(a)')
def test_chebyshevt_poly():
raises(ValueError, lambda: chebyshevt_poly(-1, x))
assert chebyshevt_poly(1, x, polys=True) == Poly(x)
assert chebyshevt_poly(0, x) == 1
assert chebyshevt_poly(1, x) == x
assert chebyshevt_poly(2, x) == 2*x**2 - 1
assert chebyshevt_poly(3, x) == 4*x**3 - 3*x
assert chebyshevt_poly(4, x) == 8*x**4 - 8*x**2 + 1
assert chebyshevt_poly(5, x) == 16*x**5 - 20*x**3 + 5*x
assert chebyshevt_poly(6, x) == 32*x**6 - 48*x**4 + 18*x**2 - 1
assert chebyshevt_poly(1).dummy_eq(x)
assert chebyshevt_poly(1, polys=True) == Poly(x)
def test_chebyshevu_poly():
raises(ValueError, lambda: chebyshevu_poly(-1, x))
assert chebyshevu_poly(1, x, polys=True) == Poly(2*x)
assert chebyshevu_poly(0, x) == 1
assert chebyshevu_poly(1, x) == 2*x
assert chebyshevu_poly(2, x) == 4*x**2 - 1
assert chebyshevu_poly(3, x) == 8*x**3 - 4*x
assert chebyshevu_poly(4, x) == 16*x**4 - 12*x**2 + 1
assert chebyshevu_poly(5, x) == 32*x**5 - 32*x**3 + 6*x
assert chebyshevu_poly(6, x) == 64*x**6 - 80*x**4 + 24*x**2 - 1
assert chebyshevu_poly(1).dummy_eq(2*x)
assert chebyshevu_poly(1, polys=True) == Poly(2*x)
def test_hermite_poly():
raises(ValueError, lambda: hermite_poly(-1, x))
assert hermite_poly(1, x, polys=True) == Poly(2*x)
assert hermite_poly(0, x) == 1
assert hermite_poly(1, x) == 2*x
assert hermite_poly(2, x) == 4*x**2 - 2
assert hermite_poly(3, x) == 8*x**3 - 12*x
assert hermite_poly(4, x) == 16*x**4 - 48*x**2 + 12
assert hermite_poly(5, x) == 32*x**5 - 160*x**3 + 120*x
assert hermite_poly(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
assert hermite_poly(1).dummy_eq(2*x)
assert hermite_poly(1, polys=True) == Poly(2*x)
def test_hermite_prob_poly():
raises(ValueError, lambda: hermite_prob_poly(-1, x))
assert hermite_prob_poly(1, x, polys=True) == Poly(x)
assert hermite_prob_poly(0, x) == 1
assert hermite_prob_poly(1, x) == x
assert hermite_prob_poly(2, x) == x**2 - 1
assert hermite_prob_poly(3, x) == x**3 - 3*x
assert hermite_prob_poly(4, x) == x**4 - 6*x**2 + 3
assert hermite_prob_poly(5, x) == x**5 - 10*x**3 + 15*x
assert hermite_prob_poly(6, x) == x**6 - 15*x**4 + 45*x**2 - 15
assert hermite_prob_poly(1).dummy_eq(x)
assert hermite_prob_poly(1, polys=True) == Poly(x)
def test_legendre_poly():
raises(ValueError, lambda: legendre_poly(-1, x))
assert legendre_poly(1, x, polys=True) == Poly(x, domain='QQ')
assert legendre_poly(0, x) == 1
assert legendre_poly(1, x) == x
assert legendre_poly(2, x) == Q(3, 2)*x**2 - Q(1, 2)
assert legendre_poly(3, x) == Q(5, 2)*x**3 - Q(3, 2)*x
assert legendre_poly(4, x) == Q(35, 8)*x**4 - Q(30, 8)*x**2 + Q(3, 8)
assert legendre_poly(5, x) == Q(63, 8)*x**5 - Q(70, 8)*x**3 + Q(15, 8)*x
assert legendre_poly(6, x) == Q(
231, 16)*x**6 - Q(315, 16)*x**4 + Q(105, 16)*x**2 - Q(5, 16)
assert legendre_poly(1).dummy_eq(x)
assert legendre_poly(1, polys=True) == Poly(x)
def test_laguerre_poly():
raises(ValueError, lambda: laguerre_poly(-1, x))
assert laguerre_poly(1, x, polys=True) == Poly(-x + 1, domain='QQ')
assert laguerre_poly(0, x) == 1
assert laguerre_poly(1, x) == -x + 1
assert laguerre_poly(2, x) == Q(1, 2)*x**2 - Q(4, 2)*x + 1
assert laguerre_poly(3, x) == -Q(1, 6)*x**3 + Q(9, 6)*x**2 - Q(18, 6)*x + 1
assert laguerre_poly(4, x) == Q(
1, 24)*x**4 - Q(16, 24)*x**3 + Q(72, 24)*x**2 - Q(96, 24)*x + 1
assert laguerre_poly(5, x) == -Q(1, 120)*x**5 + Q(25, 120)*x**4 - Q(
200, 120)*x**3 + Q(600, 120)*x**2 - Q(600, 120)*x + 1
assert laguerre_poly(6, x) == Q(1, 720)*x**6 - Q(36, 720)*x**5 + Q(450, 720)*x**4 - Q(2400, 720)*x**3 + Q(5400, 720)*x**2 - Q(4320, 720)*x + 1
assert laguerre_poly(0, x, a) == 1
assert laguerre_poly(1, x, a) == -x + a + 1
assert laguerre_poly(2, x, a) == x**2/2 + (-a - 2)*x + a**2/2 + a*Q(3, 2) + 1
assert laguerre_poly(3, x, a) == -x**3/6 + (a/2 + Q(
3)/2)*x**2 + (-a**2/2 - a*Q(5, 2) - 3)*x + a**3/6 + a**2 + a*Q(11, 6) + 1
assert laguerre_poly(1).dummy_eq(-x + 1)
assert laguerre_poly(1, polys=True) == Poly(-x + 1)
def test_spherical_bessel_fn():
x, z = symbols("x z")
assert spherical_bessel_fn(1, z) == 1/z**2
assert spherical_bessel_fn(2, z) == -1/z + 3/z**3
assert spherical_bessel_fn(3, z) == -6/z**2 + 15/z**4
assert spherical_bessel_fn(4, z) == 1/z - 45/z**3 + 105/z**5
|
8442e25b032ffde5379c7bc123efdac5ed6ada2beb6508048c248b1ddbe0f876 | from sympy.core.backend import Symbol
from sympy.physics.vector import Point, Vector, ReferenceFrame, Dyadic
from sympy.physics.mechanics import RigidBody, Particle, inertia
__all__ = ['Body']
# XXX: We use type:ignore because the classes RigidBody and Particle have
# inconsistent parallel axis methods that take different numbers of arguments.
class Body(RigidBody, Particle): # type: ignore
"""
Body is a common representation of either a RigidBody or a Particle SymPy
object depending on what is passed in during initialization. If a mass is
passed in and central_inertia is left as None, the Particle object is
created. Otherwise a RigidBody object will be created.
Explanation
===========
The attributes that Body possesses will be the same as a Particle instance
or a Rigid Body instance depending on which was created. Additional
attributes are listed below.
Attributes
==========
name : string
The body's name
masscenter : Point
The point which represents the center of mass of the rigid body
frame : ReferenceFrame
The reference frame which the body is fixed in
mass : Sympifyable
The body's mass
inertia : (Dyadic, Point)
The body's inertia around its center of mass. This attribute is specific
to the rigid body form of Body and is left undefined for the Particle
form
loads : iterable
This list contains information on the different loads acting on the
Body. Forces are listed as a (point, vector) tuple and torques are
listed as (reference frame, vector) tuples.
Parameters
==========
name : String
Defines the name of the body. It is used as the base for defining
body specific properties.
masscenter : Point, optional
A point that represents the center of mass of the body or particle.
If no point is given, a point is generated.
mass : Sympifyable, optional
A Sympifyable object which represents the mass of the body. If no
mass is passed, one is generated.
frame : ReferenceFrame, optional
The ReferenceFrame that represents the reference frame of the body.
If no frame is given, a frame is generated.
central_inertia : Dyadic, optional
Central inertia dyadic of the body. If none is passed while creating
RigidBody, a default inertia is generated.
Examples
========
Default behaviour. This results in the creation of a RigidBody object for
which the mass, mass center, frame and inertia attributes are given default
values. ::
>>> from sympy.physics.mechanics import Body
>>> body = Body('name_of_body')
This next example demonstrates the code required to specify all of the
values of the Body object. Note this will also create a RigidBody version of
the Body object. ::
>>> from sympy import Symbol
>>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia
>>> from sympy.physics.mechanics import Body
>>> mass = Symbol('mass')
>>> masscenter = Point('masscenter')
>>> frame = ReferenceFrame('frame')
>>> ixx = Symbol('ixx')
>>> body_inertia = inertia(frame, ixx, 0, 0)
>>> body = Body('name_of_body', masscenter, mass, frame, body_inertia)
The minimal code required to create a Particle version of the Body object
involves simply passing in a name and a mass. ::
>>> from sympy import Symbol
>>> from sympy.physics.mechanics import Body
>>> mass = Symbol('mass')
>>> body = Body('name_of_body', mass=mass)
The Particle version of the Body object can also receive a masscenter point
and a reference frame, just not an inertia.
"""
def __init__(self, name, masscenter=None, mass=None, frame=None,
central_inertia=None):
self.name = name
self._loads = []
if frame is None:
frame = ReferenceFrame(name + '_frame')
if masscenter is None:
masscenter = Point(name + '_masscenter')
if central_inertia is None and mass is None:
ixx = Symbol(name + '_ixx')
iyy = Symbol(name + '_iyy')
izz = Symbol(name + '_izz')
izx = Symbol(name + '_izx')
ixy = Symbol(name + '_ixy')
iyz = Symbol(name + '_iyz')
_inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx),
masscenter)
else:
_inertia = (central_inertia, masscenter)
if mass is None:
_mass = Symbol(name + '_mass')
else:
_mass = mass
masscenter.set_vel(frame, 0)
# If user passes masscenter and mass then a particle is created
# otherwise a rigidbody. As a result a body may or may not have inertia.
if central_inertia is None and mass is not None:
self.frame = frame
self.masscenter = masscenter
Particle.__init__(self, name, masscenter, _mass)
self._central_inertia = Dyadic(0)
else:
RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia)
@property
def loads(self):
return self._loads
@property
def x(self):
"""The basis Vector for the Body, in the x direction. """
return self.frame.x
@property
def y(self):
"""The basis Vector for the Body, in the y direction. """
return self.frame.y
@property
def z(self):
"""The basis Vector for the Body, in the z direction. """
return self.frame.z
@property
def inertia(self):
"""The body's inertia about a point; stored as (Dyadic, Point)."""
if self.is_rigidbody:
return RigidBody.inertia.fget(self)
return (self.central_inertia, self.masscenter)
@inertia.setter
def inertia(self, I):
RigidBody.inertia.fset(self, I)
@property
def is_rigidbody(self):
if hasattr(self, '_inertia'):
return True
return False
def kinetic_energy(self, frame):
"""Kinetic energy of the body.
Parameters
==========
frame : ReferenceFrame or Body
The Body's angular velocity and the velocity of it's mass
center are typically defined with respect to an inertial frame but
any relevant frame in which the velocities are known can be supplied.
Examples
========
>>> from sympy.physics.mechanics import Body, ReferenceFrame, Point
>>> from sympy import symbols
>>> m, v, r, omega = symbols('m v r omega')
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> P = Body('P', masscenter=O, mass=m)
>>> P.masscenter.set_vel(N, v * N.y)
>>> P.kinetic_energy(N)
m*v**2/2
>>> N = ReferenceFrame('N')
>>> b = ReferenceFrame('b')
>>> b.set_ang_vel(N, omega * b.x)
>>> P = Point('P')
>>> P.set_vel(N, v * N.x)
>>> B = Body('B', masscenter=P, frame=b)
>>> B.kinetic_energy(N)
B_ixx*omega**2/2 + B_mass*v**2/2
See Also
========
sympy.physics.mechanics : Particle, RigidBody
"""
if isinstance(frame, Body):
frame = Body.frame
if self.is_rigidbody:
return RigidBody(self.name, self.masscenter, self.frame, self.mass,
(self.central_inertia, self.masscenter)).kinetic_energy(frame)
return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame)
def apply_force(self, force, point=None, reaction_body=None, reaction_point=None):
"""Add force to the body(s).
Explanation
===========
Applies the force on self or equal and oppposite forces on
self and other body if both are given on the desried point on the bodies.
The force applied on other body is taken opposite of self, i.e, -force.
Parameters
==========
force: Vector
The force to be applied.
point: Point, optional
The point on self on which force is applied.
By default self's masscenter.
reaction_body: Body, optional
Second body on which equal and opposite force
is to be applied.
reaction_point : Point, optional
The point on other body on which equal and opposite
force is applied. By default masscenter of other body.
Example
=======
>>> from sympy import symbols
>>> from sympy.physics.mechanics import Body, Point, dynamicsymbols
>>> m, g = symbols('m g')
>>> B = Body('B')
>>> force1 = m*g*B.z
>>> B.apply_force(force1) #Applying force on B's masscenter
>>> B.loads
[(B_masscenter, g*m*B_frame.z)]
We can also remove some part of force from any point on the body by
adding the opposite force to the body on that point.
>>> f1, f2 = dynamicsymbols('f1 f2')
>>> P = Point('P') #Considering point P on body B
>>> B.apply_force(f1*B.x + f2*B.y, P)
>>> B.loads
[(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)]
Let's remove f1 from point P on body B.
>>> B.apply_force(-f1*B.x, P)
>>> B.loads
[(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)]
To further demonstrate the use of ``apply_force`` attribute,
consider two bodies connected through a spring.
>>> from sympy.physics.mechanics import Body, dynamicsymbols
>>> N = Body('N') #Newtonion Frame
>>> x = dynamicsymbols('x')
>>> B1 = Body('B1')
>>> B2 = Body('B2')
>>> spring_force = x*N.x
Now let's apply equal and opposite spring force to the bodies.
>>> P1 = Point('P1')
>>> P2 = Point('P2')
>>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2)
We can check the loads(forces) applied to bodies now.
>>> B1.loads
[(P1, x(t)*N_frame.x)]
>>> B2.loads
[(P2, - x(t)*N_frame.x)]
Notes
=====
If a new force is applied to a body on a point which already has some
force applied on it, then the new force is added to the already applied
force on that point.
"""
if not isinstance(point, Point):
if point is None:
point = self.masscenter # masscenter
else:
raise TypeError("Force must be applied to a point on the body.")
if not isinstance(force, Vector):
raise TypeError("Force must be a vector.")
if reaction_body is not None:
reaction_body.apply_force(-force, point=reaction_point)
for load in self._loads:
if point in load:
force += load[1]
self._loads.remove(load)
break
self._loads.append((point, force))
def apply_torque(self, torque, reaction_body=None):
"""Add torque to the body(s).
Explanation
===========
Applies the torque on self or equal and oppposite torquess on
self and other body if both are given.
The torque applied on other body is taken opposite of self,
i.e, -torque.
Parameters
==========
torque: Vector
The torque to be applied.
reaction_body: Body, optional
Second body on which equal and opposite torque
is to be applied.
Example
=======
>>> from sympy import symbols
>>> from sympy.physics.mechanics import Body, dynamicsymbols
>>> t = symbols('t')
>>> B = Body('B')
>>> torque1 = t*B.z
>>> B.apply_torque(torque1)
>>> B.loads
[(B_frame, t*B_frame.z)]
We can also remove some part of torque from the body by
adding the opposite torque to the body.
>>> t1, t2 = dynamicsymbols('t1 t2')
>>> B.apply_torque(t1*B.x + t2*B.y)
>>> B.loads
[(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)]
Let's remove t1 from Body B.
>>> B.apply_torque(-t1*B.x)
>>> B.loads
[(B_frame, t2(t)*B_frame.y + t*B_frame.z)]
To further demonstrate the use, let us consider two bodies such that
a torque `T` is acting on one body, and `-T` on the other.
>>> from sympy.physics.mechanics import Body, dynamicsymbols
>>> N = Body('N') #Newtonion frame
>>> B1 = Body('B1')
>>> B2 = Body('B2')
>>> v = dynamicsymbols('v')
>>> T = v*N.y #Torque
Now let's apply equal and opposite torque to the bodies.
>>> B1.apply_torque(T, B2)
We can check the loads (torques) applied to bodies now.
>>> B1.loads
[(B1_frame, v(t)*N_frame.y)]
>>> B2.loads
[(B2_frame, - v(t)*N_frame.y)]
Notes
=====
If a new torque is applied on body which already has some torque applied on it,
then the new torque is added to the previous torque about the body's frame.
"""
if not isinstance(torque, Vector):
raise TypeError("A Vector must be supplied to add torque.")
if reaction_body is not None:
reaction_body.apply_torque(-torque)
for load in self._loads:
if self.frame in load:
torque += load[1]
self._loads.remove(load)
break
self._loads.append((self.frame, torque))
def clear_loads(self):
"""
Clears the Body's loads list.
Example
=======
>>> from sympy.physics.mechanics import Body
>>> B = Body('B')
>>> force = B.x + B.y
>>> B.apply_force(force)
>>> B.loads
[(B_masscenter, B_frame.x + B_frame.y)]
>>> B.clear_loads()
>>> B.loads
[]
"""
self._loads = []
def remove_load(self, about=None):
"""
Remove load about a point or frame.
Parameters
==========
about : Point or ReferenceFrame, optional
The point about which force is applied,
and is to be removed.
If about is None, then the torque about
self's frame is removed.
Example
=======
>>> from sympy.physics.mechanics import Body, Point
>>> B = Body('B')
>>> P = Point('P')
>>> f1 = B.x
>>> f2 = B.y
>>> B.apply_force(f1)
>>> B.apply_force(f2, P)
>>> B.loads
[(B_masscenter, B_frame.x), (P, B_frame.y)]
>>> B.remove_load(P)
>>> B.loads
[(B_masscenter, B_frame.x)]
"""
if about is not None:
if not isinstance(about, Point):
raise TypeError('Load is applied about Point or ReferenceFrame.')
else:
about = self.frame
for load in self._loads:
if about in load:
self._loads.remove(load)
break
def masscenter_vel(self, body):
"""
Returns the velocity of the mass center with respect to the provided
rigid body or reference frame.
Parameters
==========
body: Body or ReferenceFrame
The rigid body or reference frame to calculate the velocity in.
Example
=======
>>> from sympy.physics.mechanics import Body
>>> A = Body('A')
>>> B = Body('B')
>>> A.masscenter.set_vel(B.frame, 5*B.frame.x)
>>> A.masscenter_vel(B)
5*B_frame.x
>>> A.masscenter_vel(B.frame)
5*B_frame.x
"""
if isinstance(body, ReferenceFrame):
frame=body
elif isinstance(body, Body):
frame = body.frame
return self.masscenter.vel(frame)
def ang_vel_in(self, body):
"""
Returns this body's angular velocity with respect to the provided
rigid body or reference frame.
Parameters
==========
body: Body or ReferenceFrame
The rigid body or reference frame to calculate the angular velocity in.
Example
=======
>>> from sympy.physics.mechanics import Body, ReferenceFrame
>>> A = Body('A')
>>> N = ReferenceFrame('N')
>>> B = Body('B', frame=N)
>>> A.frame.set_ang_vel(N, 5*N.x)
>>> A.ang_vel_in(B)
5*N.x
>>> A.ang_vel_in(N)
5*N.x
"""
if isinstance(body, ReferenceFrame):
frame=body
elif isinstance(body, Body):
frame = body.frame
return self.frame.ang_vel_in(frame)
def dcm(self, body):
"""
Returns the direction cosine matrix of this body relative to the
provided rigid body or reference frame.
Parameters
==========
body: Body or ReferenceFrame
The rigid body or reference frame to calculate the dcm.
Example
=======
>>> from sympy.physics.mechanics import Body
>>> A = Body('A')
>>> B = Body('B')
>>> A.frame.orient_axis(B.frame, B.frame.x, 5)
>>> A.dcm(B)
Matrix([
[1, 0, 0],
[0, cos(5), sin(5)],
[0, -sin(5), cos(5)]])
>>> A.dcm(B.frame)
Matrix([
[1, 0, 0],
[0, cos(5), sin(5)],
[0, -sin(5), cos(5)]])
"""
if isinstance(body, ReferenceFrame):
frame=body
elif isinstance(body, Body):
frame = body.frame
return self.frame.dcm(frame)
def parallel_axis(self, point, frame=None):
"""Returns the inertia dyadic of the body with respect to another
point.
Parameters
==========
point : sympy.physics.vector.Point
The point to express the inertia dyadic about.
frame : sympy.physics.vector.ReferenceFrame
The reference frame used to construct the dyadic.
Returns
=======
inertia : sympy.physics.vector.Dyadic
The inertia dyadic of the rigid body expressed about the provided
point.
Example
=======
>>> from sympy.physics.mechanics import Body
>>> A = Body('A')
>>> P = A.masscenter.locatenew('point', 3 * A.x + 5 * A.y)
>>> A.parallel_axis(P).to_matrix(A.frame)
Matrix([
[A_ixx + 25*A_mass, A_ixy - 15*A_mass, A_izx],
[A_ixy - 15*A_mass, A_iyy + 9*A_mass, A_iyz],
[ A_izx, A_iyz, A_izz + 34*A_mass]])
"""
if self.is_rigidbody:
return RigidBody.parallel_axis(self, point, frame)
return Particle.parallel_axis(self, point, frame)
|
d7fe15f06a087e77e9a2973649726063ee732a3b7f190822aba2cc2cacad82ae | __all__ = [
'vector',
'CoordinateSym', 'ReferenceFrame', 'Dyadic', 'Vector', 'Point', 'cross',
'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations',
'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint',
'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting', 'curl',
'divergence', 'gradient', 'is_conservative', 'is_solenoidal',
'scalar_potential', 'scalar_potential_difference',
'KanesMethod',
'RigidBody',
'inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum',
'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing',
'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols',
'Particle',
'LagrangesMethod',
'Linearizer',
'Body',
'SymbolicSystem',
'PinJoint', 'PrismaticJoint', 'CylindricalJoint',
'JointsMethod'
]
from sympy.physics import vector
from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point,
cross, dot, express, time_derivative, outer, kinematic_equations,
get_motion_params, partial_velocity, dynamicsymbols, vprint,
vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence,
gradient, is_conservative, is_solenoidal, scalar_potential,
scalar_potential_difference)
from .kane import KanesMethod
from .rigidbody import RigidBody
from .functions import (inertia, inertia_of_point_mass, linear_momentum,
angular_momentum, kinetic_energy, potential_energy, Lagrangian,
mechanics_printing, mprint, msprint, mpprint, mlatex, msubs,
find_dynamicsymbols)
from .particle import Particle
from .lagrange import LagrangesMethod
from .linearize import Linearizer
from .body import Body
from .system import SymbolicSystem
from .jointsmethod import JointsMethod
from .joint import PinJoint, PrismaticJoint, CylindricalJoint
|
0148f41489709438c2642d24f0386c3467f970ddb8e690a4c7bbaa6b24a8e190 | from sympy.core.backend import sympify
from sympy.physics.vector import Point, ReferenceFrame, Dyadic
from sympy.utilities.exceptions import sympy_deprecation_warning
__all__ = ['RigidBody']
class RigidBody:
"""An idealized rigid body.
Explanation
===========
This is essentially a container which holds the various components which
describe a rigid body: a name, mass, center of mass, reference frame, and
inertia.
All of these need to be supplied on creation, but can be changed
afterwards.
Attributes
==========
name : string
The body's name.
masscenter : Point
The point which represents the center of mass of the rigid body.
frame : ReferenceFrame
The ReferenceFrame which the rigid body is fixed in.
mass : Sympifyable
The body's mass.
inertia : (Dyadic, Point)
The body's inertia about a point; stored in a tuple as shown above.
Examples
========
>>> from sympy import Symbol
>>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody
>>> from sympy.physics.mechanics import outer
>>> m = Symbol('m')
>>> A = ReferenceFrame('A')
>>> P = Point('P')
>>> I = outer (A.x, A.x)
>>> inertia_tuple = (I, P)
>>> B = RigidBody('B', P, A, m, inertia_tuple)
>>> # Or you could change them afterwards
>>> m2 = Symbol('m2')
>>> B.mass = m2
"""
def __init__(self, name, masscenter, frame, mass, inertia):
if not isinstance(name, str):
raise TypeError('Supply a valid name.')
self._name = name
self.masscenter = masscenter
self.mass = mass
self.frame = frame
self.inertia = inertia
self.potential_energy = 0
def __str__(self):
return self._name
def __repr__(self):
return self.__str__()
@property
def frame(self):
"""The ReferenceFrame fixed to the body."""
return self._frame
@frame.setter
def frame(self, F):
if not isinstance(F, ReferenceFrame):
raise TypeError("RigdBody frame must be a ReferenceFrame object.")
self._frame = F
@property
def masscenter(self):
"""The body's center of mass."""
return self._masscenter
@masscenter.setter
def masscenter(self, p):
if not isinstance(p, Point):
raise TypeError("RigidBody center of mass must be a Point object.")
self._masscenter = p
@property
def mass(self):
"""The body's mass."""
return self._mass
@mass.setter
def mass(self, m):
self._mass = sympify(m)
@property
def inertia(self):
"""The body's inertia about a point; stored as (Dyadic, Point)."""
return (self._inertia, self._inertia_point)
@inertia.setter
def inertia(self, I):
if not isinstance(I[0], Dyadic):
raise TypeError("RigidBody inertia must be a Dyadic object.")
if not isinstance(I[1], Point):
raise TypeError("RigidBody inertia must be about a Point.")
self._inertia = I[0]
self._inertia_point = I[1]
# have I S/O, want I S/S*
# I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O
# I_S/S* = I_S/O - I_S*/O
from sympy.physics.mechanics.functions import inertia_of_point_mass
I_Ss_O = inertia_of_point_mass(self.mass,
self.masscenter.pos_from(I[1]),
self.frame)
self._central_inertia = I[0] - I_Ss_O
@property
def central_inertia(self):
"""The body's central inertia dyadic."""
return self._central_inertia
@central_inertia.setter
def central_inertia(self, I):
if not isinstance(I, Dyadic):
raise TypeError("RigidBody inertia must be a Dyadic object.")
self.inertia = (I, self.masscenter)
def linear_momentum(self, frame):
""" Linear momentum of the rigid body.
Explanation
===========
The linear momentum L, of a rigid body B, with respect to frame N is
given by
L = M * v*
where M is the mass of the rigid body and v* is the velocity of
the mass center of B in the frame, N.
Parameters
==========
frame : ReferenceFrame
The frame in which linear momentum is desired.
Examples
========
>>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
>>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> M, v = dynamicsymbols('M v')
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, v * N.x)
>>> I = outer (N.x, N.x)
>>> Inertia_tuple = (I, P)
>>> B = RigidBody('B', P, N, M, Inertia_tuple)
>>> B.linear_momentum(N)
M*v*N.x
"""
return self.mass * self.masscenter.vel(frame)
def angular_momentum(self, point, frame):
"""Returns the angular momentum of the rigid body about a point in the
given frame.
Explanation
===========
The angular momentum H of a rigid body B about some point O in a frame
N is given by:
H = I . w + r x Mv
where I is the central inertia dyadic of B, w is the angular velocity
of body B in the frame, N, r is the position vector from point O to the
mass center of B, and v is the velocity of the mass center in the
frame, N.
Parameters
==========
point : Point
The point about which angular momentum is desired.
frame : ReferenceFrame
The frame in which angular momentum is desired.
Examples
========
>>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
>>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> M, v, r, omega = dynamicsymbols('M v r omega')
>>> N = ReferenceFrame('N')
>>> b = ReferenceFrame('b')
>>> b.set_ang_vel(N, omega * b.x)
>>> P = Point('P')
>>> P.set_vel(N, 1 * N.x)
>>> I = outer(b.x, b.x)
>>> B = RigidBody('B', P, b, M, (I, P))
>>> B.angular_momentum(P, N)
omega*b.x
"""
I = self.central_inertia
w = self.frame.ang_vel_in(frame)
m = self.mass
r = self.masscenter.pos_from(point)
v = self.masscenter.vel(frame)
return I.dot(w) + r.cross(m * v)
def kinetic_energy(self, frame):
"""Kinetic energy of the rigid body.
Explanation
===========
The kinetic energy, T, of a rigid body, B, is given by
'T = 1/2 (I omega^2 + m v^2)'
where I and m are the central inertia dyadic and mass of rigid body B,
respectively, omega is the body's angular velocity and v is the
velocity of the body's mass center in the supplied ReferenceFrame.
Parameters
==========
frame : ReferenceFrame
The RigidBody's angular velocity and the velocity of it's mass
center are typically defined with respect to an inertial frame but
any relevant frame in which the velocities are known can be supplied.
Examples
========
>>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
>>> from sympy.physics.mechanics import RigidBody
>>> from sympy import symbols
>>> M, v, r, omega = symbols('M v r omega')
>>> N = ReferenceFrame('N')
>>> b = ReferenceFrame('b')
>>> b.set_ang_vel(N, omega * b.x)
>>> P = Point('P')
>>> P.set_vel(N, v * N.x)
>>> I = outer (b.x, b.x)
>>> inertia_tuple = (I, P)
>>> B = RigidBody('B', P, b, M, inertia_tuple)
>>> B.kinetic_energy(N)
M*v**2/2 + omega**2/2
"""
rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia &
self.frame.ang_vel_in(frame)) / sympify(2))
translational_KE = (self.mass * (self.masscenter.vel(frame) &
self.masscenter.vel(frame)) / sympify(2))
return rotational_KE + translational_KE
@property
def potential_energy(self):
"""The potential energy of the RigidBody.
Examples
========
>>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame
>>> from sympy import symbols
>>> M, g, h = symbols('M g h')
>>> b = ReferenceFrame('b')
>>> P = Point('P')
>>> I = outer (b.x, b.x)
>>> Inertia_tuple = (I, P)
>>> B = RigidBody('B', P, b, M, Inertia_tuple)
>>> B.potential_energy = M * g * h
>>> B.potential_energy
M*g*h
"""
return self._pe
@potential_energy.setter
def potential_energy(self, scalar):
"""Used to set the potential energy of this RigidBody.
Parameters
==========
scalar: Sympifyable
The potential energy (a scalar) of the RigidBody.
Examples
========
>>> from sympy.physics.mechanics import Point, outer
>>> from sympy.physics.mechanics import RigidBody, ReferenceFrame
>>> from sympy import symbols
>>> b = ReferenceFrame('b')
>>> M, g, h = symbols('M g h')
>>> P = Point('P')
>>> I = outer (b.x, b.x)
>>> Inertia_tuple = (I, P)
>>> B = RigidBody('B', P, b, M, Inertia_tuple)
>>> B.potential_energy = M * g * h
"""
self._pe = sympify(scalar)
def set_potential_energy(self, scalar):
sympy_deprecation_warning(
"""
The sympy.physics.mechanics.RigidBody.set_potential_energy()
method is deprecated. Instead use
B.potential_energy = scalar
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-set-potential-energy",
)
self.potential_energy = scalar
def parallel_axis(self, point, frame=None):
"""Returns the inertia dyadic of the body with respect to another
point.
Parameters
==========
point : sympy.physics.vector.Point
The point to express the inertia dyadic about.
frame : sympy.physics.vector.ReferenceFrame
The reference frame used to construct the dyadic.
Returns
=======
inertia : sympy.physics.vector.Dyadic
The inertia dyadic of the rigid body expressed about the provided
point.
"""
# circular import issue
from sympy.physics.mechanics.functions import inertia_of_point_mass
if frame is None:
frame = self.frame
return self.central_inertia + inertia_of_point_mass(
self.mass, self.masscenter.pos_from(point), frame)
|
d10acd3b010950c6b001ecc57caced809a52013fdf9679b01c5ab830d3df05f3 | # coding=utf-8
from abc import ABC, abstractmethod
from sympy.core.backend import pi, AppliedUndef, Derivative, Matrix
from sympy.physics.mechanics.body import Body
from sympy.physics.vector import (Vector, dynamicsymbols, cross, Point,
ReferenceFrame)
from sympy.utilities.exceptions import sympy_deprecation_warning
__all__ = ['Joint', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint']
class Joint(ABC):
"""Abstract base class for all specific joints.
Explanation
===========
A joint subtracts degrees of freedom from a body. This is the base class
for all specific joints and holds all common methods acting as an interface
for all joints. Custom joint can be created by inheriting Joint class and
defining all abstract functions.
The abstract methods are:
- ``_generate_coordinates``
- ``_generate_speeds``
- ``_orient_frames``
- ``_set_angular_velocity``
- ``_set_linear_velocity``
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: iterable of dynamicsymbols, optional
Generalized coordinates of the joint.
speeds : iterable of dynamicsymbols, optional
Generalized speeds of joint.
parent_point : Point or Vector, optional
Attachment point where the joint is fixed to the parent body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the parent's mass
center.
child_point : Point or Vector, optional
Attachment point where the joint is fixed to the child body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the child's mass
center.
parent_axis : Vector, optional
.. deprecated:: 1.12
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is the x axis of parent's reference frame.
For more information on this deprecation, see
:ref:`deprecated-mechanics-joint-axis`.
child_axis : Vector, optional
.. deprecated:: 1.12
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is the x axis of child's reference frame.
For more information on this deprecation, see
:ref:`deprecated-mechanics-joint-axis`.
parent_interframe : ReferenceFrame, optional
Intermediate frame of the parent body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the parent's own frame.
child_interframe : ReferenceFrame, optional
Intermediate frame of the child body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the child's own frame.
parent_joint_pos : Point or Vector, optional
.. deprecated:: 1.12
This argument is replaced by parent_point and will be removed in a
future version.
See :ref:`deprecated-mechanics-joint-pos` for more information.
child_joint_pos : Point or Vector, optional
.. deprecated:: 1.12
This argument is replaced by child_point and will be removed in a
future version.
See :ref:`deprecated-mechanics-joint-pos` for more information.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : Matrix
Matrix of the joint's generalized coordinates.
speeds : Matrix
Matrix of the joint's generalized speeds.
parent_point : Point
Attachment point where the joint is fixed to the parent body.
child_point : Point
Attachment point where the joint is fixed to the child body.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
parent_interframe : ReferenceFrame
Intermediate frame of the parent body with respect to which the joint
transformation is formulated.
child_interframe : ReferenceFrame
Intermediate frame of the child body with respect to which the joint
transformation is formulated.
kdes : Matrix
Kinematical differential equations of the joint.
Notes
=====
When providing a vector as the intermediate frame, a new intermediate frame
is created which aligns its X axis with the provided vector. This is done
with a single fixed rotation about a rotation axis. This rotation axis is
determined by taking the cross product of the ``body.x`` axis with the
provided vector. In the case where the provided vector is in the ``-body.x``
direction, the rotation is done about the ``body.y`` axis.
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None,
parent_point=None, child_point=None, parent_axis=None,
child_axis=None, parent_interframe=None, child_interframe=None,
parent_joint_pos=None, child_joint_pos=None):
if not isinstance(name, str):
raise TypeError('Supply a valid name.')
self._name = name
if not isinstance(parent, Body):
raise TypeError('Parent must be an instance of Body.')
self._parent = parent
if not isinstance(child, Body):
raise TypeError('Parent must be an instance of Body.')
self._child = child
self._coordinates = self._generate_coordinates(coordinates)
self._speeds = self._generate_speeds(speeds)
self._kdes = self._generate_kdes()
self._parent_axis = self._axis(parent_axis, parent.frame)
self._child_axis = self._axis(child_axis, child.frame)
if parent_joint_pos is not None or child_joint_pos is not None:
sympy_deprecation_warning(
"""
The parent_joint_pos and child_joint_pos arguments for the Joint
classes are deprecated. Instead use parent_point and child_point.
""",
deprecated_since_version="1.12",
active_deprecations_target="deprecated-mechanics-joint-pos",
stacklevel=4
)
if parent_point is None:
parent_point = parent_joint_pos
if child_point is None:
child_point = child_joint_pos
self._parent_point = self._locate_joint_pos(parent, parent_point)
self._child_point = self._locate_joint_pos(child, child_point)
if parent_axis is not None or child_axis is not None:
sympy_deprecation_warning(
"""
The parent_axis and child_axis arguments for the Joint classes
are deprecated. Instead use parent_interframe, child_interframe.
""",
deprecated_since_version="1.12",
active_deprecations_target="deprecated-mechanics-joint-axis",
stacklevel=4
)
if parent_interframe is None:
parent_interframe = parent_axis
if child_interframe is None:
child_interframe = child_axis
self._parent_interframe = self._locate_joint_frame(parent,
parent_interframe)
self._child_interframe = self._locate_joint_frame(child,
child_interframe)
self._orient_frames()
self._set_angular_velocity()
self._set_linear_velocity()
def __str__(self):
return self.name
def __repr__(self):
return self.__str__()
@property
def name(self):
"""Name of the joint."""
return self._name
@property
def parent(self):
"""Parent body of Joint."""
return self._parent
@property
def child(self):
"""Child body of Joint."""
return self._child
@property
def coordinates(self):
"""Matrix of the joint's generalized coordinates."""
return self._coordinates
@property
def speeds(self):
"""Matrix of the joint's generalized speeds."""
return self._speeds
@property
def kdes(self):
"""Kinematical differential equations of the joint."""
return self._kdes
@property
def parent_axis(self):
"""The axis of parent frame."""
# Will be removed with `deprecated-mechanics-joint-axis`
return self._parent_axis
@property
def child_axis(self):
"""The axis of child frame."""
# Will be removed with `deprecated-mechanics-joint-axis`
return self._child_axis
@property
def parent_point(self):
"""Attachment point where the joint is fixed to the parent body."""
return self._parent_point
@property
def child_point(self):
"""Attachment point where the joint is fixed to the child body."""
return self._child_point
@property
def parent_interframe(self):
return self._parent_interframe
@property
def child_interframe(self):
return self._child_interframe
@abstractmethod
def _generate_coordinates(self, coordinates):
"""Generate Matrix of the joint's generalized coordinates."""
pass
@abstractmethod
def _generate_speeds(self, speeds):
"""Generate Matrix of the joint's generalized speeds."""
pass
@abstractmethod
def _orient_frames(self):
"""Orient frames as per the joint."""
pass
@abstractmethod
def _set_angular_velocity(self):
"""Set angular velocity of the joint related frames."""
pass
@abstractmethod
def _set_linear_velocity(self):
"""Set velocity of related points to the joint."""
pass
@staticmethod
def _to_vector(matrix, frame):
"""Converts a matrix to a vector in the given frame."""
return Vector([(matrix, frame)])
@staticmethod
def _axis(ax, *frames):
"""Check whether an axis is fixed in one of the frames."""
if ax is None:
ax = frames[0].x
return ax
if not isinstance(ax, Vector):
raise TypeError("Axis must be a Vector.")
ref_frame = None # Find a body in which the axis can be expressed
for frame in frames:
try:
ax.to_matrix(frame)
except ValueError:
pass
else:
ref_frame = frame
break
if ref_frame is None:
raise ValueError("Axis cannot be expressed in one of the body's "
"frames.")
if not ax.dt(ref_frame) == 0:
raise ValueError('Axis cannot be time-varying when viewed from the '
'associated body.')
return ax
@staticmethod
def _choose_rotation_axis(frame, axis):
components = axis.to_matrix(frame)
x, y, z = components[0], components[1], components[2]
if x != 0:
if y != 0:
if z != 0:
return cross(axis, frame.x)
if z != 0:
return frame.y
return frame.z
else:
if y != 0:
return frame.x
return frame.y
@staticmethod
def _create_aligned_interframe(frame, align_axis, frame_axis=None,
frame_name=None):
"""
Returns an intermediate frame, where the ``frame_axis`` defined in
``frame`` is aligned with ``axis``. By default this means that the X
axis will be aligned with ``axis``.
Parameters
==========
frame: Body or ReferenceFrame
The body or reference frame with respect to which the intermediate
frame is oriented.
align_axis: Vector
The vector with respect to which the intermediate frame will be
aligned.
frame_axis: Vector
The vector of the frame which should get aligned with ``axis``. The
default is the X axis of the frame.
frame_name: string
Name of the to be created intermediate frame. The default adds
"_int_frame" to the name of ``frame``.
Example
=======
An intermediate frame, where the X axis of the parent becomes aligned
with ``parent.y + parent.z`` can be created as follows:
>>> from sympy.physics.mechanics.joint import Joint
>>> from sympy.physics.mechanics import Body
>>> parent = Body('parent')
>>> parent_interframe = Joint._create_aligned_interframe(
... parent, parent.y + parent.z)
>>> parent_interframe
parent_int_frame
>>> parent.dcm(parent_interframe)
Matrix([
[ 0, -sqrt(2)/2, -sqrt(2)/2],
[sqrt(2)/2, 1/2, -1/2],
[sqrt(2)/2, -1/2, 1/2]])
>>> (parent.y + parent.z).express(parent_interframe)
sqrt(2)*parent_int_frame.x
Notes
=====
The direction cosine matrix between the given frame and intermediate
frame is formed using a simple rotation about an axis that is normal to
both ``align_axis`` and ``frame_axis``. In general, the normal axis is
formed by crossing the ``frame_axis`` with the ``align_axis``. The
exception is if the axes are parallel with opposite directions, in which
case the rotation vector is chosen using the rules in the following
table with the vectors expressed in the given frame:
.. list-table::
:header-rows: 1
* - ``align_axis``
- ``frame_axis``
- ``rotation_axis``
* - ``-x``
- ``x``
- ``z``
* - ``-y``
- ``y``
- ``x``
* - ``-z``
- ``z``
- ``y``
* - ``-x-y``
- ``x+y``
- ``z``
* - ``-y-z``
- ``y+z``
- ``x``
* - ``-x-z``
- ``x+z``
- ``y``
* - ``-x-y-z``
- ``x+y+z``
- ``(x+y+z) × x``
"""
if isinstance(frame, Body):
frame = frame.frame
if frame_axis is None:
frame_axis = frame.x
if frame_name is None:
if frame.name[-6:] == '_frame':
frame_name = f'{frame.name[:-6]}_int_frame'
else:
frame_name = f'{frame.name}_int_frame'
angle = frame_axis.angle_between(align_axis)
rotation_axis = cross(frame_axis, align_axis)
if rotation_axis == Vector(0) and angle == 0:
return frame
if angle == pi:
rotation_axis = Joint._choose_rotation_axis(frame, align_axis)
int_frame = ReferenceFrame(frame_name)
int_frame.orient_axis(frame, rotation_axis, angle)
int_frame.set_ang_vel(frame, 0 * rotation_axis)
return int_frame
def _generate_kdes(self):
"""Generate kinematical differential equations."""
kdes = []
t = dynamicsymbols._t
for i in range(len(self.coordinates)):
kdes.append(-self.coordinates[i].diff(t) + self.speeds[i])
return Matrix(kdes)
def _locate_joint_pos(self, body, joint_pos):
"""Returns the attachment point of a body."""
if joint_pos is None:
return body.masscenter
if not isinstance(joint_pos, (Point, Vector)):
raise TypeError('Attachment point must be a Point or Vector.')
if isinstance(joint_pos, Vector):
point_name = f'{self.name}_{body.name}_joint'
joint_pos = body.masscenter.locatenew(point_name, joint_pos)
if not joint_pos.pos_from(body.masscenter).dt(body.frame) == 0:
raise ValueError('Attachment point must be fixed to the associated '
'body.')
return joint_pos
def _locate_joint_frame(self, body, interframe):
"""Returns the attachment frame of a body."""
if interframe is None:
return body.frame
if isinstance(interframe, Vector):
interframe = Joint._create_aligned_interframe(
body, interframe,
frame_name=f'{self.name}_{body.name}_int_frame')
elif not isinstance(interframe, ReferenceFrame):
raise TypeError('Interframe must be a ReferenceFrame.')
if not interframe.ang_vel_in(body.frame) == 0:
raise ValueError(f'Interframe {interframe} is not fixed to body '
f'{body}.')
body.masscenter.set_vel(interframe, 0) # Fixate interframe to body
return interframe
def _fill_coordinate_list(self, coordinates, n_coords, label='q', offset=0,
number_single=False):
"""Helper method for _generate_coordinates and _generate_speeds.
Parameters
==========
coordinates : iterable
Iterable of coordinates or speeds that have been provided.
n_coords : Integer
Number of coordinates that should be returned.
label : String, optional
Coordinate type either 'q' (coordinates) or 'u' (speeds). The
Default is 'q'.
offset : Integer
Count offset when creating new dynamicsymbols. The default is 0.
number_single : Boolean
Boolean whether if n_coords == 1, number should still be used. The
default is False.
"""
def create_symbol(number):
if n_coords == 1 and not number_single:
return dynamicsymbols(f'{label}_{self.name}')
return dynamicsymbols(f'{label}{number}_{self.name}')
name = 'generalized coordinate' if label == 'q' else 'generalized speed'
generated_coordinates = []
if coordinates is None:
coordinates = []
elif isinstance(coordinates, (AppliedUndef, Derivative)):
coordinates = [coordinates]
# Supports more iterables, also Matrix
for i, coord in enumerate(coordinates):
if coord is None:
generated_coordinates.append(create_symbol(i + offset))
elif isinstance(coord, (AppliedUndef, Derivative)):
generated_coordinates.append(coord)
else:
raise TypeError(f'The {name} {coord} should have been a '
f'dynamicsymbol.')
for i in range(len(coordinates) + offset, n_coords + offset):
generated_coordinates.append(create_symbol(i))
if len(generated_coordinates) != n_coords:
raise ValueError(f'{len(coordinates)} {name}s have been provided. '
f'The maximum number of {name}s is {n_coords}.')
return Matrix(generated_coordinates)
class _JointAxisMixin:
"""Mixin class, which provides joint axis support methods.
This class is strictly only to be inherited by joint types that have a joint
axis. This is because the methods of this class assume that the object has
a joint_axis attribute.
"""
__slots__ = ()
def _express_joint_axis(self, frame):
"""Helper method to express the joint axis in a specified frame."""
try:
ax_mat = self.joint_axis.to_matrix(self.parent_interframe)
except ValueError:
ax_mat = self.joint_axis.to_matrix(self.child_interframe)
try:
self.parent_interframe.dcm(frame) # Check if connected
except ValueError:
self.child_interframe.dcm(frame) # Should be connected
int_frame = self.child_interframe
else:
int_frame = self.parent_interframe
return self._to_vector(ax_mat, int_frame).express(frame)
class PinJoint(Joint, _JointAxisMixin):
"""Pin (Revolute) Joint.
.. image:: PinJoint.svg
Explanation
===========
A pin joint is defined such that the joint rotation axis is fixed in both
the child and parent and the location of the joint is relative to the mass
center of each body. The child rotates an angle, θ, from the parent about
the rotation axis and has a simple angular speed, ω, relative to the
parent. The direction cosine matrix between the child interframe and
parent interframe is formed using a simple rotation about the joint axis.
The page on the joints framework gives a more detailed explanation of the
intermediate frames.
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: dynamicsymbol, optional
Generalized coordinates of the joint.
speeds : dynamicsymbol, optional
Generalized speeds of joint.
parent_point : Point or Vector, optional
Attachment point where the joint is fixed to the parent body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the parent's mass
center.
child_point : Point or Vector, optional
Attachment point where the joint is fixed to the child body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the child's mass
center.
parent_axis : Vector, optional
.. deprecated:: 1.12
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is the x axis of parent's reference frame.
For more information on this deprecation, see
:ref:`deprecated-mechanics-joint-axis`.
child_axis : Vector, optional
.. deprecated:: 1.12
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is the x axis of child's reference frame.
For more information on this deprecation, see
:ref:`deprecated-mechanics-joint-axis`.
parent_interframe : ReferenceFrame, optional
Intermediate frame of the parent body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the parent's own frame.
child_interframe : ReferenceFrame, optional
Intermediate frame of the child body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the child's own frame.
joint_axis : Vector
The axis about which the rotation occurs. Note that the components
of this axis are the same in the parent_interframe and child_interframe.
parent_joint_pos : Point or Vector, optional
.. deprecated:: 1.12
This argument is replaced by parent_point and will be removed in a
future version.
See :ref:`deprecated-mechanics-joint-pos` for more information.
child_joint_pos : Point or Vector, optional
.. deprecated:: 1.12
This argument is replaced by child_point and will be removed in a
future version.
See :ref:`deprecated-mechanics-joint-pos` for more information.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : Matrix
Matrix of the joint's generalized coordinates. The default value is
``dynamicsymbols(f'q_{joint.name}')``.
speeds : Matrix
Matrix of the joint's generalized speeds. The default value is
``dynamicsymbols(f'u_{joint.name}')``.
parent_point : Point
Attachment point where the joint is fixed to the parent body.
child_point : Point
Attachment point where the joint is fixed to the child body.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
parent_interframe : ReferenceFrame
Intermediate frame of the parent body with respect to which the joint
transformation is formulated.
child_interframe : ReferenceFrame
Intermediate frame of the child body with respect to which the joint
transformation is formulated.
joint_axis : Vector
The axis about which the rotation occurs. Note that the components of
this axis are the same in the parent_interframe and child_interframe.
kdes : Matrix
Kinematical differential equations of the joint.
Examples
=========
A single pin joint is created from two bodies and has the following basic
attributes:
>>> from sympy.physics.mechanics import Body, PinJoint
>>> parent = Body('P')
>>> parent
P
>>> child = Body('C')
>>> child
C
>>> joint = PinJoint('PC', parent, child)
>>> joint
PinJoint: PC parent: P child: C
>>> joint.name
'PC'
>>> joint.parent
P
>>> joint.child
C
>>> joint.parent_point
P_masscenter
>>> joint.child_point
C_masscenter
>>> joint.parent_axis
P_frame.x
>>> joint.child_axis
C_frame.x
>>> joint.coordinates
Matrix([[q_PC(t)]])
>>> joint.speeds
Matrix([[u_PC(t)]])
>>> joint.child.frame.ang_vel_in(joint.parent.frame)
u_PC(t)*P_frame.x
>>> joint.child.frame.dcm(joint.parent.frame)
Matrix([
[1, 0, 0],
[0, cos(q_PC(t)), sin(q_PC(t))],
[0, -sin(q_PC(t)), cos(q_PC(t))]])
>>> joint.child_point.pos_from(joint.parent_point)
0
To further demonstrate the use of the pin joint, the kinematics of simple
double pendulum that rotates about the Z axis of each connected body can be
created as follows.
>>> from sympy import symbols, trigsimp
>>> from sympy.physics.mechanics import Body, PinJoint
>>> l1, l2 = symbols('l1 l2')
First create bodies to represent the fixed ceiling and one to represent
each pendulum bob.
>>> ceiling = Body('C')
>>> upper_bob = Body('U')
>>> lower_bob = Body('L')
The first joint will connect the upper bob to the ceiling by a distance of
``l1`` and the joint axis will be about the Z axis for each body.
>>> ceiling_joint = PinJoint('P1', ceiling, upper_bob,
... child_point=-l1*upper_bob.frame.x,
... joint_axis=ceiling.frame.z)
The second joint will connect the lower bob to the upper bob by a distance
of ``l2`` and the joint axis will also be about the Z axis for each body.
>>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob,
... child_point=-l2*lower_bob.frame.x,
... joint_axis=upper_bob.frame.z)
Once the joints are established the kinematics of the connected bodies can
be accessed. First the direction cosine matrices of pendulum link relative
to the ceiling are found:
>>> upper_bob.frame.dcm(ceiling.frame)
Matrix([
[ cos(q_P1(t)), sin(q_P1(t)), 0],
[-sin(q_P1(t)), cos(q_P1(t)), 0],
[ 0, 0, 1]])
>>> trigsimp(lower_bob.frame.dcm(ceiling.frame))
Matrix([
[ cos(q_P1(t) + q_P2(t)), sin(q_P1(t) + q_P2(t)), 0],
[-sin(q_P1(t) + q_P2(t)), cos(q_P1(t) + q_P2(t)), 0],
[ 0, 0, 1]])
The position of the lower bob's masscenter is found with:
>>> lower_bob.masscenter.pos_from(ceiling.masscenter)
l1*U_frame.x + l2*L_frame.x
The angular velocities of the two pendulum links can be computed with
respect to the ceiling.
>>> upper_bob.frame.ang_vel_in(ceiling.frame)
u_P1(t)*C_frame.z
>>> lower_bob.frame.ang_vel_in(ceiling.frame)
u_P1(t)*C_frame.z + u_P2(t)*U_frame.z
And finally, the linear velocities of the two pendulum bobs can be computed
with respect to the ceiling.
>>> upper_bob.masscenter.vel(ceiling.frame)
l1*u_P1(t)*U_frame.y
>>> lower_bob.masscenter.vel(ceiling.frame)
l1*u_P1(t)*U_frame.y + l2*(u_P1(t) + u_P2(t))*L_frame.y
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None,
parent_point=None, child_point=None, parent_axis=None,
child_axis=None, parent_interframe=None, child_interframe=None,
joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
self._joint_axis = joint_axis
super().__init__(name, parent, child, coordinates, speeds, parent_point,
child_point, parent_axis, child_axis,
parent_interframe, child_interframe, parent_joint_pos,
child_joint_pos)
def __str__(self):
return (f'PinJoint: {self.name} parent: {self.parent} '
f'child: {self.child}')
@property
def joint_axis(self):
"""Axis about which the child rotates with respect to the parent."""
return self._joint_axis
def _generate_coordinates(self, coordinate):
return self._fill_coordinate_list(coordinate, 1, 'q')
def _generate_speeds(self, speed):
return self._fill_coordinate_list(speed, 1, 'u')
def _orient_frames(self):
self._joint_axis = self._axis(
self.joint_axis, self.parent_interframe, self.child_interframe)
axis = self._express_joint_axis(self.parent_interframe)
self.child_interframe.orient_axis(
self.parent_interframe, axis, self.coordinates[0])
def _set_angular_velocity(self):
self.child_interframe.set_ang_vel(self.parent_interframe, self.speeds[
0] * self.joint_axis.normalize())
def _set_linear_velocity(self):
self.child_point.set_pos(self.parent_point, 0)
self.parent_point.set_vel(self.parent.frame, 0)
self.child_point.set_vel(self.child.frame, 0)
self.child.masscenter.v2pt_theory(self.parent_point,
self.parent.frame, self.child.frame)
class PrismaticJoint(Joint, _JointAxisMixin):
"""Prismatic (Sliding) Joint.
.. image:: PrismaticJoint.svg
Explanation
===========
It is defined such that the child body translates with respect to the parent
body along the body-fixed joint axis. The location of the joint is defined
by two points, one in each body, which coincide when the generalized
coordinate is zero. The direction cosine matrix between the
parent_interframe and child_interframe is the identity matrix. Therefore,
the direction cosine matrix between the parent and child frames is fully
defined by the definition of the intermediate frames. The page on the joints
framework gives a more detailed explanation of the intermediate frames.
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: dynamicsymbol, optional
Generalized coordinates of the joint. The default value is
``dynamicsymbols(f'q_{joint.name}')``.
speeds : dynamicsymbol, optional
Generalized speeds of joint. The default value is
``dynamicsymbols(f'u_{joint.name}')``.
parent_point : Point or Vector, optional
Attachment point where the joint is fixed to the parent body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the parent's mass
center.
child_point : Point or Vector, optional
Attachment point where the joint is fixed to the child body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the child's mass
center.
parent_axis : Vector, optional
.. deprecated:: 1.12
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is the x axis of parent's reference frame.
For more information on this deprecation, see
:ref:`deprecated-mechanics-joint-axis`.
child_axis : Vector, optional
.. deprecated:: 1.12
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is the x axis of child's reference frame.
For more information on this deprecation, see
:ref:`deprecated-mechanics-joint-axis`.
parent_interframe : ReferenceFrame, optional
Intermediate frame of the parent body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the parent's own frame.
child_interframe : ReferenceFrame, optional
Intermediate frame of the child body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the child's own frame.
joint_axis : Vector
The axis along which the translation occurs. Note that the components
of this axis are the same in the parent_interframe and child_interframe.
parent_joint_pos : Point or Vector, optional
.. deprecated:: 1.12
This argument is replaced by parent_point and will be removed in a
future version.
See :ref:`deprecated-mechanics-joint-pos` for more information.
child_joint_pos : Point or Vector, optional
.. deprecated:: 1.12
This argument is replaced by child_point and will be removed in a
future version.
See :ref:`deprecated-mechanics-joint-pos` for more information.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : Matrix
Matrix of the joint's generalized coordinates.
speeds : Matrix
Matrix of the joint's generalized speeds.
parent_point : Point
Attachment point where the joint is fixed to the parent body.
child_point : Point
Attachment point where the joint is fixed to the child body.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
parent_interframe : ReferenceFrame
Intermediate frame of the parent body with respect to which the joint
transformation is formulated.
child_interframe : ReferenceFrame
Intermediate frame of the child body with respect to which the joint
transformation is formulated.
kdes : Matrix
Kinematical differential equations of the joint.
Examples
=========
A single prismatic joint is created from two bodies and has the following
basic attributes:
>>> from sympy.physics.mechanics import Body, PrismaticJoint
>>> parent = Body('P')
>>> parent
P
>>> child = Body('C')
>>> child
C
>>> joint = PrismaticJoint('PC', parent, child)
>>> joint
PrismaticJoint: PC parent: P child: C
>>> joint.name
'PC'
>>> joint.parent
P
>>> joint.child
C
>>> joint.parent_point
P_masscenter
>>> joint.child_point
C_masscenter
>>> joint.parent_axis
P_frame.x
>>> joint.child_axis
C_frame.x
>>> joint.coordinates
Matrix([[q_PC(t)]])
>>> joint.speeds
Matrix([[u_PC(t)]])
>>> joint.child.frame.ang_vel_in(joint.parent.frame)
0
>>> joint.child.frame.dcm(joint.parent.frame)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> joint.child_point.pos_from(joint.parent_point)
q_PC(t)*P_frame.x
To further demonstrate the use of the prismatic joint, the kinematics of two
masses sliding, one moving relative to a fixed body and the other relative
to the moving body. about the X axis of each connected body can be created
as follows.
>>> from sympy.physics.mechanics import PrismaticJoint, Body
First create bodies to represent the fixed ceiling and one to represent
a particle.
>>> wall = Body('W')
>>> Part1 = Body('P1')
>>> Part2 = Body('P2')
The first joint will connect the particle to the ceiling and the
joint axis will be about the X axis for each body.
>>> J1 = PrismaticJoint('J1', wall, Part1)
The second joint will connect the second particle to the first particle
and the joint axis will also be about the X axis for each body.
>>> J2 = PrismaticJoint('J2', Part1, Part2)
Once the joint is established the kinematics of the connected bodies can
be accessed. First the direction cosine matrices of Part relative
to the ceiling are found:
>>> Part1.dcm(wall)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> Part2.dcm(wall)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
The position of the particles' masscenter is found with:
>>> Part1.masscenter.pos_from(wall.masscenter)
q_J1(t)*W_frame.x
>>> Part2.masscenter.pos_from(wall.masscenter)
q_J1(t)*W_frame.x + q_J2(t)*P1_frame.x
The angular velocities of the two particle links can be computed with
respect to the ceiling.
>>> Part1.ang_vel_in(wall)
0
>>> Part2.ang_vel_in(wall)
0
And finally, the linear velocities of the two particles can be computed
with respect to the ceiling.
>>> Part1.masscenter_vel(wall)
u_J1(t)*W_frame.x
>>> Part2.masscenter.vel(wall.frame)
u_J1(t)*W_frame.x + Derivative(q_J2(t), t)*P1_frame.x
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None,
parent_point=None, child_point=None, parent_axis=None,
child_axis=None, parent_interframe=None, child_interframe=None,
joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
self._joint_axis = joint_axis
super().__init__(name, parent, child, coordinates, speeds, parent_point,
child_point, parent_axis, child_axis,
parent_interframe, child_interframe, parent_joint_pos,
child_joint_pos)
def __str__(self):
return (f'PrismaticJoint: {self.name} parent: {self.parent} '
f'child: {self.child}')
@property
def joint_axis(self):
"""Axis along which the child translates with respect to the parent."""
return self._joint_axis
def _generate_coordinates(self, coordinate):
return self._fill_coordinate_list(coordinate, 1, 'q')
def _generate_speeds(self, speed):
return self._fill_coordinate_list(speed, 1, 'u')
def _orient_frames(self):
self._joint_axis = self._axis(
self.joint_axis, self.parent_interframe, self.child_interframe)
axis = self._express_joint_axis(self.parent_interframe)
self.child_interframe.orient_axis(self.parent_interframe, axis, 0)
def _set_angular_velocity(self):
self.child_interframe.set_ang_vel(self.parent_interframe, 0)
def _set_linear_velocity(self):
axis = self.joint_axis.normalize()
self.child_point.set_pos(self.parent_point, self.coordinates[0] * axis)
self.parent_point.set_vel(self.parent.frame, 0)
self.child_point.set_vel(self.child.frame, 0)
self.child_point.set_vel(self.parent.frame, self.speeds[0] * axis)
self.child.masscenter.set_vel(self.parent.frame, self.speeds[0] * axis)
class CylindricalJoint(_JointAxisMixin, Joint):
"""Cylindrical Joint.
.. image:: CylindricalJoint.svg
:align: center
:width: 600
Explanation
===========
A cylindrical joint is defined such that the child body both rotates about
and translates along the body-fixed joint axis with respect to the parent
body. The joint axis is both the rotation axis and translation axis. The
location of the joint is defined by two points, one in each body, which
coincide when the generalized coordinate corresponding to the translation is
zero. The direction cosine matrix between the child interframe and parent
interframe is formed using a simple rotation about the joint axis. The page
on the joints framework gives a more detailed explanation of the
intermediate frames.
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
rotation_coordinate : dynamicsymbol, optional
Generalized coordinate corresponding to the rotation angle. The default
value is ``dynamicsymbols(f'q0_{joint.name}')``.
translation_coordinate : dynamicsymbol, optional
Generalized coordinate corresponding to the translation distance. The
default value is ``dynamicsymbols(f'q1_{joint.name}')``.
rotation_speed : dynamicsymbol, optional
Generalized speed corresponding to the angular velocity. The default
value is ``dynamicsymbols(f'u0_{joint.name}')``.
translation_speed : dynamicsymbol, optional
Generalized speed corresponding to the translation velocity. The default
value is ``dynamicsymbols(f'u1_{joint.name}')``.
parent_point : Point or Vector, optional
Attachment point where the joint is fixed to the parent body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the parent's mass
center.
child_point : Point or Vector, optional
Attachment point where the joint is fixed to the child body. If a
vector is provided, then the attachment point is computed by adding the
vector to the body's mass center. The default value is the child's mass
center.
parent_interframe : ReferenceFrame, optional
Intermediate frame of the parent body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the parent's own frame.
child_interframe : ReferenceFrame, optional
Intermediate frame of the child body with respect to which the joint
transformation is formulated. If a Vector is provided then an interframe
is created which aligns its X axis with the given vector. The default
value is the child's own frame.
joint_axis : Vector, optional
The rotation as well as translation axis. Note that the components of
this axis are the same in the parent_interframe and child_interframe.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
rotation_coordinate : dynamicsymbol
Generalized coordinate corresponding to the rotation angle.
translation_coordinate : dynamicsymbol
Generalized coordinate corresponding to the translation distance.
rotation_speed : dynamicsymbol
Generalized speed corresponding to the angular velocity.
translation_speed : dynamicsymbol
Generalized speed corresponding to the translation velocity.
coordinates : Matrix
Matrix of the joint's generalized coordinates.
speeds : Matrix
Matrix of the joint's generalized speeds.
parent_point : Point
Attachment point where the joint is fixed to the parent body.
child_point : Point
Attachment point where the joint is fixed to the child body.
parent_interframe : ReferenceFrame
Intermediate frame of the parent body with respect to which the joint
transformation is formulated.
child_interframe : ReferenceFrame
Intermediate frame of the child body with respect to which the joint
transformation is formulated.
kdes : Matrix
Kinematical differential equations of the joint.
joint_axis : Vector
The axis of rotation and translation.
Examples
=========
A single cylindrical joint is created between two bodies and has the
following basic attributes:
>>> from sympy.physics.mechanics import Body, CylindricalJoint
>>> parent = Body('P')
>>> parent
P
>>> child = Body('C')
>>> child
C
>>> joint = CylindricalJoint('PC', parent, child)
>>> joint
CylindricalJoint: PC parent: P child: C
>>> joint.name
'PC'
>>> joint.parent
P
>>> joint.child
C
>>> joint.parent_point
P_masscenter
>>> joint.child_point
C_masscenter
>>> joint.parent_axis
P_frame.x
>>> joint.child_axis
C_frame.x
>>> joint.coordinates
Matrix([
[q0_PC(t)],
[q1_PC(t)]])
>>> joint.speeds
Matrix([
[u0_PC(t)],
[u1_PC(t)]])
>>> joint.child.frame.ang_vel_in(joint.parent.frame)
u0_PC(t)*P_frame.x
>>> joint.child.frame.dcm(joint.parent.frame)
Matrix([
[1, 0, 0],
[0, cos(q0_PC(t)), sin(q0_PC(t))],
[0, -sin(q0_PC(t)), cos(q0_PC(t))]])
>>> joint.child_point.pos_from(joint.parent_point)
q1_PC(t)*P_frame.x
>>> child.masscenter.vel(parent.frame)
u1_PC(t)*P_frame.x
To further demonstrate the use of the cylindrical joint, the kinematics of
two cylindral joints perpendicular to each other can be created as follows.
>>> from sympy import symbols
>>> from sympy.physics.mechanics import Body, CylindricalJoint
>>> r, l, w = symbols('r l w')
First create bodies to represent the fixed floor with a fixed pole on it.
The second body represents a freely moving tube around that pole. The third
body represents a solid flag freely translating along and rotating around
the Y axis of the tube.
>>> floor = Body('floor')
>>> tube = Body('tube')
>>> flag = Body('flag')
The first joint will connect the first tube to the floor with it translating
along and rotating around the Z axis of both bodies.
>>> floor_joint = CylindricalJoint('C1', floor, tube, joint_axis=floor.z)
The second joint will connect the tube perpendicular to the flag along the Y
axis of both the tube and the flag, with the joint located at a distance
``r`` from the tube's center of mass and a combination of the distances
``l`` and ``w`` from the flag's center of mass.
>>> flag_joint = CylindricalJoint('C2', tube, flag,
... parent_point=r * tube.y,
... child_point=-w * flag.y + l * flag.z,
... joint_axis=tube.y)
Once the joints are established the kinematics of the connected bodies can
be accessed. First the direction cosine matrices of both the body and the
flag relative to the floor are found:
>>> tube.dcm(floor)
Matrix([
[ cos(q0_C1(t)), sin(q0_C1(t)), 0],
[-sin(q0_C1(t)), cos(q0_C1(t)), 0],
[ 0, 0, 1]])
>>> flag.dcm(floor)
Matrix([
[cos(q0_C1(t))*cos(q0_C2(t)), sin(q0_C1(t))*cos(q0_C2(t)), -sin(q0_C2(t))],
[ -sin(q0_C1(t)), cos(q0_C1(t)), 0],
[sin(q0_C2(t))*cos(q0_C1(t)), sin(q0_C1(t))*sin(q0_C2(t)), cos(q0_C2(t))]])
The position of the flag's center of mass is found with:
>>> flag.masscenter.pos_from(floor.masscenter)
q1_C1(t)*floor_frame.z + (r + q1_C2(t))*tube_frame.y + w*flag_frame.y - l*flag_frame.z
The angular velocities of the two tubes can be computed with respect to the
floor.
>>> tube.ang_vel_in(floor)
u0_C1(t)*floor_frame.z
>>> flag.ang_vel_in(floor)
u0_C1(t)*floor_frame.z + u0_C2(t)*tube_frame.y
Finally, the linear velocities of the two tube centers of mass can be
computed with respect to the floor, while expressed in the tube's frame.
>>> tube.masscenter.vel(floor.frame).to_matrix(tube.frame)
Matrix([
[ 0],
[ 0],
[u1_C1(t)]])
>>> flag.masscenter.vel(floor.frame).to_matrix(tube.frame).simplify()
Matrix([
[-l*u0_C2(t)*cos(q0_C2(t)) - r*u0_C1(t) - w*u0_C1(t) - q1_C2(t)*u0_C1(t)],
[ -l*u0_C1(t)*sin(q0_C2(t)) + Derivative(q1_C2(t), t)],
[ l*u0_C2(t)*sin(q0_C2(t)) + u1_C1(t)]])
"""
def __init__(self, name, parent, child, rotation_coordinate=None,
translation_coordinate=None, rotation_speed=None,
translation_speed=None, parent_point=None, child_point=None,
parent_interframe=None, child_interframe=None,
joint_axis=None):
self._joint_axis = joint_axis
coordinates = (rotation_coordinate, translation_coordinate)
speeds = (rotation_speed, translation_speed)
super().__init__(name, parent, child, coordinates, speeds,
parent_point, child_point,
parent_interframe=parent_interframe,
child_interframe=child_interframe)
def __str__(self):
return (f'CylindricalJoint: {self.name} parent: {self.parent} '
f'child: {self.child}')
@property
def joint_axis(self):
"""Axis about and along which the rotation and translation occurs."""
return self._joint_axis
@property
def rotation_coordinate(self):
"""Generalized coordinate corresponding to the rotation angle."""
return self.coordinates[0]
@property
def translation_coordinate(self):
"""Generalized coordinate corresponding to the translation distance."""
return self.coordinates[1]
@property
def rotation_speed(self):
"""Generalized speed corresponding to the angular velocity."""
return self.speeds[0]
@property
def translation_speed(self):
"""Generalized speed corresponding to the translation velocity."""
return self.speeds[1]
def _generate_coordinates(self, coordinates):
return self._fill_coordinate_list(coordinates, 2, 'q')
def _generate_speeds(self, speeds):
return self._fill_coordinate_list(speeds, 2, 'u')
def _orient_frames(self):
self._joint_axis = self._axis(
self.joint_axis, self.parent_interframe, self.child_interframe)
axis = self._express_joint_axis(self.parent_interframe)
self.child_interframe.orient_axis(
self.parent_interframe, axis, self.rotation_coordinate)
def _set_angular_velocity(self):
self.child_interframe.set_ang_vel(
self.parent_interframe,
self.rotation_speed * self.joint_axis.normalize())
def _set_linear_velocity(self):
self.child_point.set_pos(
self.parent_point,
self.translation_coordinate * self.joint_axis.normalize())
self.parent_point.set_vel(self.parent.frame, 0)
self.child_point.set_vel(self.child.frame, 0)
self.child_point.set_vel(
self.parent.frame,
self.translation_speed * self.joint_axis.normalize())
self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame,
self.child_interframe)
|
d8a02398ebbf245637b068f718351adbc490ed3d63cd00c62f6150ab05cac4ad | from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod,
RigidBody, Particle)
from sympy.physics.mechanics.method import _Methods
from sympy.core.backend import Matrix
__all__ = ['JointsMethod']
class JointsMethod(_Methods):
"""Method for formulating the equations of motion using a set of interconnected bodies with joints.
Parameters
==========
newtonion : Body or ReferenceFrame
The newtonion(inertial) frame.
*joints : Joint
The joints in the system
Attributes
==========
q, u : iterable
Iterable of the generalized coordinates and speeds
bodies : iterable
Iterable of Body objects in the system.
loads : iterable
Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
describing the forces on the system.
mass_matrix : Matrix, shape(n, n)
The system's mass matrix
forcing : Matrix, shape(n, 1)
The system's forcing vector
mass_matrix_full : Matrix, shape(2*n, 2*n)
The "mass matrix" for the u's and q's
forcing_full : Matrix, shape(2*n, 1)
The "forcing vector" for the u's and q's
method : KanesMethod or Lagrange's method
Method's object.
kdes : iterable
Iterable of kde in they system.
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
>>> from sympy import symbols
>>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint
>>> from sympy.physics.vector import dynamicsymbols
>>> c, k = symbols('c k')
>>> x, v = dynamicsymbols('x v')
>>> wall = Body('W')
>>> body = Body('B')
>>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v)
>>> wall.apply_force(c*v*wall.x, reaction_body=body)
>>> wall.apply_force(k*x*wall.x, reaction_body=body)
>>> method = JointsMethod(wall, J)
>>> method.form_eoms()
Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]])
>>> M = method.mass_matrix_full
>>> F = method.forcing_full
>>> rhs = M.LUsolve(F)
>>> rhs
Matrix([
[ v(t)],
[(-c*v(t) - k*x(t))/B_mass]])
Notes
=====
``JointsMethod`` currently only works with systems that do not have any
configuration or motion constraints.
"""
def __init__(self, newtonion, *joints):
if isinstance(newtonion, Body):
self.frame = newtonion.frame
else:
self.frame = newtonion
self._joints = joints
self._bodies = self._generate_bodylist()
self._loads = self._generate_loadlist()
self._q = self._generate_q()
self._u = self._generate_u()
self._kdes = self._generate_kdes()
self._method = None
@property
def bodies(self):
"""List of bodies in they system."""
return self._bodies
@property
def loads(self):
"""List of loads on the system."""
return self._loads
@property
def q(self):
"""List of the generalized coordinates."""
return self._q
@property
def u(self):
"""List of the generalized speeds."""
return self._u
@property
def kdes(self):
"""List of the generalized coordinates."""
return self._kdes
@property
def forcing_full(self):
"""The "forcing vector" for the u's and q's."""
return self.method.forcing_full
@property
def mass_matrix_full(self):
"""The "mass matrix" for the u's and q's."""
return self.method.mass_matrix_full
@property
def mass_matrix(self):
"""The system's mass matrix."""
return self.method.mass_matrix
@property
def forcing(self):
"""The system's forcing vector."""
return self.method.forcing
@property
def method(self):
"""Object of method used to form equations of systems."""
return self._method
def _generate_bodylist(self):
bodies = []
for joint in self._joints:
if joint.child not in bodies:
bodies.append(joint.child)
if joint.parent not in bodies:
bodies.append(joint.parent)
return bodies
def _generate_loadlist(self):
load_list = []
for body in self.bodies:
load_list.extend(body.loads)
return load_list
def _generate_q(self):
q_ind = []
for joint in self._joints:
for coordinate in joint.coordinates:
if coordinate in q_ind:
raise ValueError('Coordinates of joints should be unique.')
q_ind.append(coordinate)
return Matrix(q_ind)
def _generate_u(self):
u_ind = []
for joint in self._joints:
for speed in joint.speeds:
if speed in u_ind:
raise ValueError('Speeds of joints should be unique.')
u_ind.append(speed)
return Matrix(u_ind)
def _generate_kdes(self):
kd_ind = Matrix(1, 0, []).T
for joint in self._joints:
kd_ind = kd_ind.col_join(joint.kdes)
return kd_ind
def _convert_bodies(self):
# Convert `Body` to `Particle` and `RigidBody`
bodylist = []
for body in self.bodies:
if body.is_rigidbody:
rb = RigidBody(body.name, body.masscenter, body.frame, body.mass,
(body.central_inertia, body.masscenter))
rb.potential_energy = body.potential_energy
bodylist.append(rb)
else:
part = Particle(body.name, body.masscenter, body.mass)
part.potential_energy = body.potential_energy
bodylist.append(part)
return bodylist
def form_eoms(self, method=KanesMethod):
"""Method to form system's equation of motions.
Parameters
==========
method : Class
Class name of method.
Returns
========
Matrix
Vector of equations of motions.
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
>>> from sympy import S, symbols
>>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body
>>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod
>>> q = dynamicsymbols('q')
>>> qd = dynamicsymbols('q', 1)
>>> m, k, b = symbols('m k b')
>>> wall = Body('W')
>>> part = Body('P', mass=m)
>>> part.potential_energy = k * q**2 / S(2)
>>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd)
>>> wall.apply_force(b * qd * wall.x, reaction_body=part)
>>> method = JointsMethod(wall, J)
>>> method.form_eoms(LagrangesMethod)
Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
We can also solve for the states using the 'rhs' method.
>>> method.rhs()
Matrix([
[ Derivative(q(t), t)],
[(-b*Derivative(q(t), t) - k*q(t))/m]])
"""
bodylist = self._convert_bodies()
if issubclass(method, LagrangesMethod): #LagrangesMethod or similar
L = Lagrangian(self.frame, *bodylist)
self._method = method(L, self.q, self.loads, bodylist, self.frame)
else: #KanesMethod or similar
self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes,
forcelist=self.loads, bodies=bodylist)
soln = self.method._form_eoms()
return soln
def rhs(self, inv_method=None):
"""Returns equations that can be solved numerically.
Parameters
==========
inv_method : str
The specific sympy inverse matrix calculation method to use. For a
list of valid methods, see
:meth:`~sympy.matrices.matrices.MatrixBase.inv`
Returns
========
Matrix
Numerically solveable equations.
See Also
========
sympy.physics.mechanics.kane.KanesMethod.rhs():
KanesMethod's rhs function.
sympy.physics.mechanics.lagrange.LagrangesMethod.rhs():
LagrangesMethod's rhs function.
"""
return self.method.rhs(inv_method=inv_method)
|
1dd9a98d51d9d496a776866b1b015bed8b2192612472fb778cb2d5c59d7752f0 | from sympy.core.numbers import (I, pi, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.spherical_harmonics import Ynm
from sympy.matrices.dense import Matrix
from sympy.physics.wigner import (clebsch_gordan, wigner_9j, wigner_6j, gaunt,
real_gaunt, racah, dot_rot_grad_Ynm, wigner_3j, wigner_d_small, wigner_d)
from sympy.testing.pytest import raises
# for test cases, refer : https://en.wikipedia.org/wiki/Table_of_Clebsch%E2%80%93Gordan_coefficients
def test_clebsch_gordan_docs():
assert clebsch_gordan(Rational(3, 2), S.Half, 2, Rational(3, 2), S.Half, 2) == 1
assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(3, 2), Rational(-1, 2), 1) == sqrt(3)/2
assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(-1, 2), S.Half, 0) == -sqrt(2)/2
def test_clebsch_gordan():
# Argument order: (j_1, j_2, j, m_1, m_2, m)
h = S.One
k = S.Half
l = Rational(3, 2)
i = Rational(-1, 2)
n = Rational(7, 2)
p = Rational(5, 2)
assert clebsch_gordan(k, k, 1, k, k, 1) == 1
assert clebsch_gordan(k, k, 1, k, k, 0) == 0
assert clebsch_gordan(k, k, 1, i, i, -1) == 1
assert clebsch_gordan(k, k, 1, k, i, 0) == sqrt(2)/2
assert clebsch_gordan(k, k, 0, k, i, 0) == sqrt(2)/2
assert clebsch_gordan(k, k, 1, i, k, 0) == sqrt(2)/2
assert clebsch_gordan(k, k, 0, i, k, 0) == -sqrt(2)/2
assert clebsch_gordan(h, k, l, 1, k, l) == 1
assert clebsch_gordan(h, k, l, 1, i, k) == 1/sqrt(3)
assert clebsch_gordan(h, k, k, 1, i, k) == sqrt(2)/sqrt(3)
assert clebsch_gordan(h, k, k, 0, k, k) == -1/sqrt(3)
assert clebsch_gordan(h, k, l, 0, k, k) == sqrt(2)/sqrt(3)
assert clebsch_gordan(h, h, S(2), 1, 1, S(2)) == 1
assert clebsch_gordan(h, h, S(2), 1, 0, 1) == 1/sqrt(2)
assert clebsch_gordan(h, h, S(2), 0, 1, 1) == 1/sqrt(2)
assert clebsch_gordan(h, h, 1, 1, 0, 1) == 1/sqrt(2)
assert clebsch_gordan(h, h, 1, 0, 1, 1) == -1/sqrt(2)
assert clebsch_gordan(l, l, S(3), l, l, S(3)) == 1
assert clebsch_gordan(l, l, S(2), l, k, S(2)) == 1/sqrt(2)
assert clebsch_gordan(l, l, S(3), l, k, S(2)) == 1/sqrt(2)
assert clebsch_gordan(S(2), S(2), S(4), S(2), S(2), S(4)) == 1
assert clebsch_gordan(S(2), S(2), S(3), S(2), 1, S(3)) == 1/sqrt(2)
assert clebsch_gordan(S(2), S(2), S(3), 1, 1, S(2)) == 0
assert clebsch_gordan(p, h, n, p, 1, n) == 1
assert clebsch_gordan(p, h, p, p, 0, p) == sqrt(5)/sqrt(7)
assert clebsch_gordan(p, h, l, k, 1, l) == 1/sqrt(15)
def test_wigner():
def tn(a, b):
return (a - b).n(64) < S('1e-64')
assert tn(wigner_9j(1, 1, 1, 1, 1, 1, 1, 1, 0, prec=64), Rational(1, 18))
assert wigner_9j(3, 3, 2, 3, 3, 2, 3, 3, 2) == 3221*sqrt(
70)/(246960*sqrt(105)) - 365/(3528*sqrt(70)*sqrt(105))
assert wigner_6j(5, 5, 5, 5, 5, 5) == Rational(1, 52)
assert tn(wigner_6j(8, 8, 8, 8, 8, 8, prec=64), Rational(-12219, 965770))
# regression test for #8747
half = S.Half
assert wigner_9j(0, 0, 0, 0, half, half, 0, half, half) == half
assert (wigner_9j(3, 5, 4,
7 * half, 5 * half, 4,
9 * half, 9 * half, 0)
== -sqrt(Rational(361, 205821000)))
assert (wigner_9j(1, 4, 3,
5 * half, 4, 5 * half,
5 * half, 2, 7 * half)
== -sqrt(Rational(3971, 373403520)))
assert (wigner_9j(4, 9 * half, 5 * half,
2, 4, 4,
5, 7 * half, 7 * half)
== -sqrt(Rational(3481, 5042614500)))
def test_gaunt():
def tn(a, b):
return (a - b).n(64) < S('1e-64')
assert gaunt(1, 0, 1, 1, 0, -1) == -1/(2*sqrt(pi))
assert isinstance(gaunt(1, 1, 0, -1, 1, 0).args[0], Rational)
assert isinstance(gaunt(0, 1, 1, 0, -1, 1).args[0], Rational)
assert tn(gaunt(
10, 10, 12, 9, 3, -12, prec=64), (Rational(-98, 62031)) * sqrt(6279)/sqrt(pi))
def gaunt_ref(l1, l2, l3, m1, m2, m3):
return (
sqrt((2 * l1 + 1) * (2 * l2 + 1) * (2 * l3 + 1) / (4 * pi)) *
wigner_3j(l1, l2, l3, 0, 0, 0) *
wigner_3j(l1, l2, l3, m1, m2, m3)
)
threshold = 1e-10
l_max = 3
l3_max = 24
for l1 in range(l_max + 1):
for l2 in range(l_max + 1):
for l3 in range(l3_max + 1):
for m1 in range(-l1, l1 + 1):
for m2 in range(-l2, l2 + 1):
for m3 in range(-l3, l3 + 1):
args = l1, l2, l3, m1, m2, m3
g = gaunt(*args)
g0 = gaunt_ref(*args)
assert abs(g - g0) < threshold
if m1 + m2 + m3 != 0:
assert abs(g) < threshold
if (l1 + l2 + l3) % 2:
assert abs(g) < threshold
assert gaunt(1, 1, 0, 0, 2, -2) is S.Zero
def test_realgaunt():
# All non-zero values corresponding to l values from 0 to 2
for l in range(3):
for m in range(-l, l+1):
assert real_gaunt(0, l, l, 0, m, m) == 1/(2*sqrt(pi))
assert real_gaunt(1, 1, 2, 0, 0, 0) == sqrt(5)/(5*sqrt(pi))
assert real_gaunt(1, 1, 2, 1, 1, 0) == -sqrt(5)/(10*sqrt(pi))
assert real_gaunt(2, 2, 2, 0, 0, 0) == sqrt(5)/(7*sqrt(pi))
assert real_gaunt(2, 2, 2, 0, 2, 2) == -sqrt(5)/(7*sqrt(pi))
assert real_gaunt(2, 2, 2, -2, -2, 0) == -sqrt(5)/(7*sqrt(pi))
assert real_gaunt(1, 1, 2, -1, 0, -1) == sqrt(15)/(10*sqrt(pi))
assert real_gaunt(1, 1, 2, 0, 1, 1) == sqrt(15)/(10*sqrt(pi))
assert real_gaunt(1, 1, 2, 1, 1, 2) == sqrt(15)/(10*sqrt(pi))
assert real_gaunt(1, 1, 2, -1, 1, -2) == -sqrt(15)/(10*sqrt(pi))
assert real_gaunt(1, 1, 2, -1, -1, 2) == -sqrt(15)/(10*sqrt(pi))
assert real_gaunt(2, 2, 2, 0, 1, 1) == sqrt(5)/(14*sqrt(pi))
assert real_gaunt(2, 2, 2, 1, 1, 2) == sqrt(15)/(14*sqrt(pi))
assert real_gaunt(2, 2, 2, -1, -1, 2) == -sqrt(15)/(14*sqrt(pi))
assert real_gaunt(-2, -2, -2, -2, -2, 0) is S.Zero # m test
assert real_gaunt(-2, 1, 0, 1, 1, 1) is S.Zero # l test
assert real_gaunt(-2, -1, -2, -1, -1, 0) is S.Zero # m and l test
assert real_gaunt(-2, -2, -2, -2, -2, -2) is S.Zero # m and k test
assert real_gaunt(-2, -1, -2, -1, -1, -1) is S.Zero # m, l and k test
x = symbols('x', integer=True)
v = [0]*6
for i in range(len(v)):
v[i] = x # non literal ints fail
raises(ValueError, lambda: real_gaunt(*v))
v[i] = 0
def test_racah():
assert racah(3,3,3,3,3,3) == Rational(-1,14)
assert racah(2,2,2,2,2,2) == Rational(-3,70)
assert racah(7,8,7,1,7,7, prec=4).is_Float
assert racah(5.5,7.5,9.5,6.5,8,9) == -719*sqrt(598)/1158924
assert abs(racah(5.5,7.5,9.5,6.5,8,9, prec=4) - (-0.01517)) < S('1e-4')
def test_dot_rota_grad_SH():
theta, phi = symbols("theta phi")
assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0) != \
sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0).doit() == \
sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2) != \
0
assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2).doit() == \
0
assert dot_rot_grad_Ynm(3, 3, 3, 3, theta, phi).doit() == \
15*sqrt(3003)*Ynm(6, 6, theta, phi)/(143*sqrt(pi))
assert dot_rot_grad_Ynm(3, 3, 1, 1, theta, phi).doit() == \
sqrt(3)*Ynm(4, 4, theta, phi)/sqrt(pi)
assert dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit() == \
3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi))
assert dot_rot_grad_Ynm(3, 2, 3, 2, theta, phi).doit().expand() == \
-sqrt(70)*Ynm(4, 4, theta, phi)/(11*sqrt(pi)) + \
45*sqrt(182)*Ynm(6, 4, theta, phi)/(143*sqrt(pi))
def test_wigner_d():
half = S(1)/2
alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
d = wigner_d_small(half, beta).subs({beta: pi/2})
d_ = Matrix([[1, 1], [-1, 1]])/sqrt(2)
assert d == d_
D = wigner_d(half, alpha, beta, gamma)
assert D[0, 0] == exp(I*alpha/2)*exp(I*gamma/2)*cos(beta/2)
assert D[0, 1] == exp(I*alpha/2)*exp(-I*gamma/2)*sin(beta/2)
assert D[1, 0] == -exp(-I*alpha/2)*exp(I*gamma/2)*sin(beta/2)
assert D[1, 1] == exp(-I*alpha/2)*exp(-I*gamma/2)*cos(beta/2)
|
Subsets and Splits