hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
c442f15753e427dcacc7d422c0f0d183a46a5ada73f3eb1d8f81c75aef6ae8f9 | """ Riemann zeta and related function. """
from __future__ import print_function, division
from sympy.core import Function, S, sympify, pi, I
from sympy.core.compatibility import range
from sympy.core.function import ArgumentIndexError
from sympy.functions.combinatorial.numbers import bernoulli, factorial, harmonic
from sympy.functions.elementary.exponential import log, exp_polar
from sympy.functions.elementary.miscellaneous import sqrt
###############################################################################
###################### LERCH TRANSCENDENT #####################################
###############################################################################
class lerchphi(Function):
r"""
Lerch transcendent (Lerch phi function).
For :math:`\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 :math:`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 :math:`\mathbb{C} - [1, \infty)`.
Finally, for :math:`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 :math:`\log{x}` and
:math:`\log{\log{x}}` (a branch of :math:`\log{\log{x}}` is needed to
evaluate :math:`\log{x}^{s-1}`).
This concludes the analytic continuation. The Lerch transcendent is thus
branched at :math:`z \in \{0, 1, \infty\}` and
:math:`a \in \mathbb{Z}_{\le 0}`. For fixed :math:`z, a` outside these
branch points, it is an entire function of :math:`s`.
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
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 :math:`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 :math:`z` is a root of unity, the Lerch transcendent
reduces to a sum of Hurwitz zeta functions:
>>> expand_func(lerchphi(-1, s, a))
2**(-s)*zeta(s, a/2) - 2**(-s)*zeta(s, a/2 + 1/2)
If :math:`a=1`, the Lerch transcendent reduces to the polylogarithm:
>>> expand_func(lerchphi(z, s, 1))
polylog(s, z)/z
More generally, if :math:`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 :math:`z` and :math:`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)
"""
def _eval_expand_func(self, **hints):
from sympy import exp, I, floor, Add, Poly, Dummy, exp_polar, unpolarify
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.
For :math:`|z| < 1` and :math:`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 :math:`n`. It admits
an analytic continuation which is branched at :math:`z=1` (notably not on the
sheet of initial definition), :math:`z=0` and :math:`z=\infty`.
The name polylogarithm comes from the fact that for :math:`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)
See Also
========
zeta, lerchphi
Examples
========
For :math:`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 :math:`s` is a negative integer, :math:`0` or :math:`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 :math:`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)
"""
@classmethod
def eval(cls, s, z):
s, z = sympify((s, z))
if z == 1:
return zeta(s)
elif z == -1:
return -dirichlet_eta(s)
elif z == 0:
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
# 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
elif s == 0:
return z/(1 - z)
elif s == -1:
return z/(1 - z)**2
# polylog is branched, but not over the unit disk
from sympy.functions.elementary.complexes import (Abs, unpolarify,
polar_lift)
if z.has(exp_polar, polar_lift) and (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):
from sympy import log, expand_mul, Dummy
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)
###############################################################################
###################### HURWITZ GENERALIZED ZETA FUNCTION ######################
###############################################################################
class zeta(Function):
r"""
Hurwitz zeta function (or Riemann zeta function).
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 :math:`n + a` is used. For fixed
:math:`a` with `\operatorname{Re}(a) > 0` the Hurwitz zeta function admits a
meromorphic continuation to all of :math:`\mathbb{C}`, it is an unbranched
function with a simple pole at :math:`s = 1`.
Analytic continuation to other :math:`a` is possible under some circumstances,
but this is not typically done.
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
:math:`s` and :math:`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 :math:`a`, by this function assumes a default value
of :math:`a = 1`, yielding the Riemann zeta function.
See Also
========
dirichlet_eta, lerchphi, polylog
References
==========
.. [1] http://dlmf.nist.gov/25.11
.. [2] https://en.wikipedia.org/wiki/Hurwitz_zeta_function
Examples
========
For :math:`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 positive even integer and negative odd integer
values is related to the Bernoulli numbers:
>>> zeta(2)
pi**2/6
>>> zeta(4)
pi**4/90
>>> zeta(-1)
-1/12
The specific formulae are:
.. math:: \zeta(2n) = (-1)^{n+1} \frac{B_{2n} (2\pi)^{2n}}{2(2n)!}
.. math:: \zeta(-n) = -\frac{B_{n+1}}{n+1}
At negative even integers the Riemann zeta function is zero:
>>> zeta(-4)
0
No closed-form expressions are known at positive odd integers, but
numerical evaluation is possible:
>>> zeta(3).n()
1.20205690315959
The derivative of :math:`\zeta(s, a)` with respect to :math:`a` is easily
computed:
>>> from sympy.abc import a
>>> zeta(s, a).diff(a)
-s*zeta(s + 1, a)
However the derivative with respect to :math:`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:`sympy.functions.special.lerchphi`:
>>> from sympy import lerchphi
>>> zeta(s, a).rewrite(lerchphi)
lerchphi(1, s, a)
"""
@classmethod
def eval(cls, z, a_=None):
if a_ is None:
z, a = list(map(sympify, (z, 1)))
else:
z, a = list(map(sympify, (z, a_)))
if a.is_Number:
if a is S.NaN:
return S.NaN
elif a is S.One and a_ is not None:
return cls(z)
# TODO Should a == 0 return S.NaN as well?
if z.is_Number:
if z is S.NaN:
return S.NaN
elif z is S.Infinity:
return S.One
elif z.is_zero:
return S.Half - a
elif z is S.One:
return S.ComplexInfinity
if z.is_integer:
if a.is_Integer:
if z.is_negative:
zeta = (-1)**z * bernoulli(-z + 1)/(-z + 1)
elif z.is_even and z.is_positive:
B, F = bernoulli(z), factorial(z)
zeta = ((-1)**(z/2+1) * 2**(z - 1) * B * pi**z) / F
else:
return
if a.is_negative:
return zeta + harmonic(abs(a), z)
else:
return zeta - harmonic(a - 1, z)
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 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
class dirichlet_eta(Function):
r"""
Dirichlet eta function.
For `\operatorname{Re}(s) > 0`, this function is defined as
.. math:: \eta(s) = \sum_{n=1}^\infty \frac{(-1)^{n-1}}{n^s}.
It admits a unique analytic continuation to all of :math:`\mathbb{C}`.
It is an entire, unbranched function.
See Also
========
zeta
References
==========
.. [1] https://en.wikipedia.org/wiki/Dirichlet_eta_function
Examples
========
The Dirichlet eta function is closely related to the Riemann zeta function:
>>> from sympy import dirichlet_eta, zeta
>>> from sympy.abc import s
>>> dirichlet_eta(s).rewrite(zeta)
(1 - 2**(1 - s))*zeta(s)
"""
@classmethod
def eval(cls, s):
if s == 1:
return log(2)
z = zeta(s)
if not z.has(zeta):
return (1 - 2**(1 - s))*z
def _eval_rewrite_as_zeta(self, s, **kwargs):
return (1 - 2**(1 - s)) * zeta(s)
class stieltjes(Function):
r"""Represents Stieltjes constants, :math:`\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)
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):
n = sympify(n)
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 == 0 and a in [None, 1]:
return S.EulerGamma
|
518beab8787a16608775d3b3d887872641c9995ea6b01ce1b25aba32e6df130e | """ This module contains the Mathieu functions.
"""
from __future__ import print_function, division
from sympy.core import S
from sympy.core.function import Function, ArgumentIndexError
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin, cos
class MathieuBase(Function):
"""
Abstract base class for Mathieu functions.
This class is meant to reduce code duplication.
"""
unbranched = True
def _eval_conjugate(self):
a, q, z = self.args
return self.func(a.conjugate(), q.conjugate(), z.conjugate())
class mathieus(MathieuBase):
r"""
The Mathieu Sine function `S(a,q,z)`. This function is one solution
of the Mathieu differential equation:
.. math ::
y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
The other solution is the Mathieu Cosine function.
Examples
========
>>> from sympy import diff, mathieus
>>> from sympy.abc import a, q, z
>>> mathieus(a, q, z)
mathieus(a, q, z)
>>> mathieus(a, 0, z)
sin(sqrt(a)*z)
>>> diff(mathieus(a, q, z), z)
mathieusprime(a, q, z)
See Also
========
mathieuc: Mathieu cosine function.
mathieusprime: Derivative of Mathieu sine function.
mathieucprime: Derivative of Mathieu cosine function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Mathieu_function
.. [2] http://dlmf.nist.gov/28
.. [3] http://mathworld.wolfram.com/MathieuBase.html
.. [4] http://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuS/
"""
def fdiff(self, argindex=1):
if argindex == 3:
a, q, z = self.args
return mathieusprime(a, q, z)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, a, q, z):
if q.is_Number and q.is_zero:
return sin(sqrt(a)*z)
# Try to pull out factors of -1
if z.could_extract_minus_sign():
return -cls(a, q, -z)
class mathieuc(MathieuBase):
r"""
The Mathieu Cosine function `C(a,q,z)`. This function is one solution
of the Mathieu differential equation:
.. math ::
y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
The other solution is the Mathieu Sine function.
Examples
========
>>> from sympy import diff, mathieuc
>>> from sympy.abc import a, q, z
>>> mathieuc(a, q, z)
mathieuc(a, q, z)
>>> mathieuc(a, 0, z)
cos(sqrt(a)*z)
>>> diff(mathieuc(a, q, z), z)
mathieucprime(a, q, z)
See Also
========
mathieus: Mathieu sine function
mathieusprime: Derivative of Mathieu sine function
mathieucprime: Derivative of Mathieu cosine function
References
==========
.. [1] https://en.wikipedia.org/wiki/Mathieu_function
.. [2] http://dlmf.nist.gov/28
.. [3] http://mathworld.wolfram.com/MathieuBase.html
.. [4] http://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuC/
"""
def fdiff(self, argindex=1):
if argindex == 3:
a, q, z = self.args
return mathieucprime(a, q, z)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, a, q, z):
if q.is_Number and q.is_zero:
return cos(sqrt(a)*z)
# Try to pull out factors of -1
if z.could_extract_minus_sign():
return cls(a, q, -z)
class mathieusprime(MathieuBase):
r"""
The derivative `S^{\prime}(a,q,z)` of the Mathieu Sine function.
This function is one solution of the Mathieu differential equation:
.. math ::
y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
The other solution is the Mathieu Cosine function.
Examples
========
>>> from sympy import diff, mathieusprime
>>> from sympy.abc import a, q, z
>>> mathieusprime(a, q, z)
mathieusprime(a, q, z)
>>> mathieusprime(a, 0, z)
sqrt(a)*cos(sqrt(a)*z)
>>> diff(mathieusprime(a, q, z), z)
(-a + 2*q*cos(2*z))*mathieus(a, q, z)
See Also
========
mathieus: Mathieu sine function
mathieuc: Mathieu cosine function
mathieucprime: Derivative of Mathieu cosine function
References
==========
.. [1] https://en.wikipedia.org/wiki/Mathieu_function
.. [2] http://dlmf.nist.gov/28
.. [3] http://mathworld.wolfram.com/MathieuBase.html
.. [4] http://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuSPrime/
"""
def fdiff(self, argindex=1):
if argindex == 3:
a, q, z = self.args
return (2*q*cos(2*z) - a)*mathieus(a, q, z)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, a, q, z):
if q.is_Number and q.is_zero:
return sqrt(a)*cos(sqrt(a)*z)
# Try to pull out factors of -1
if z.could_extract_minus_sign():
return cls(a, q, -z)
class mathieucprime(MathieuBase):
r"""
The derivative `C^{\prime}(a,q,z)` of the Mathieu Cosine function.
This function is one solution of the Mathieu differential equation:
.. math ::
y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
The other solution is the Mathieu Sine function.
Examples
========
>>> from sympy import diff, mathieucprime
>>> from sympy.abc import a, q, z
>>> mathieucprime(a, q, z)
mathieucprime(a, q, z)
>>> mathieucprime(a, 0, z)
-sqrt(a)*sin(sqrt(a)*z)
>>> diff(mathieucprime(a, q, z), z)
(-a + 2*q*cos(2*z))*mathieuc(a, q, z)
See Also
========
mathieus: Mathieu sine function
mathieuc: Mathieu cosine function
mathieusprime: Derivative of Mathieu sine function
References
==========
.. [1] https://en.wikipedia.org/wiki/Mathieu_function
.. [2] http://dlmf.nist.gov/28
.. [3] http://mathworld.wolfram.com/MathieuBase.html
.. [4] http://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuCPrime/
"""
def fdiff(self, argindex=1):
if argindex == 3:
a, q, z = self.args
return (2*q*cos(2*z) - a)*mathieuc(a, q, z)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, a, q, z):
if q.is_Number and q.is_zero:
return -sqrt(a)*sin(sqrt(a)*z)
# Try to pull out factors of -1
if z.could_extract_minus_sign():
return -cls(a, q, -z)
|
48edd119ab9f83b0144465029a97f070c33e4566203fdffdf09f0bd798516489 | from __future__ import print_function, division
from functools import wraps
from sympy import S, pi, I, Rational, Wild, cacheit, sympify
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.power import Pow
from sympy.core.compatibility import range
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.trigonometric import sin, cos, csc, cot
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.miscellaneous import sqrt, root
from sympy.functions.elementary.complexes import re, im
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import hyper
from sympy.polys.orthopolys import spherical_bessel_fn as fn
# 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 Series Expansions for functions of the second kind about zero
# 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, and 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_expand_func(self, **hints):
nu, z, f = self.order, self.argument, self.__class__
if nu.is_extended_real:
if (nu - 1).is_extended_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_extended_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.
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 is S.Infinity or (z is 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:
from sympy import unpolarify, exp
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):
from sympy import polar_lift, exp
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_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_extended_real:
return True
def _sage_(self):
import sage.all as sage
return sage.bessel_J(self.args[0]._sage_(), self.args[1]._sage_())
class bessely(BesselBase):
r"""
Bessel function of the second kind.
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 is S.Infinity or z is S.NegativeInfinity:
return S.Zero
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_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_positive:
return True
def _sage_(self):
import sage.all as sage
return sage.bessel_Y(self.args[0]._sage_(), self.args[1]._sage_())
class besseli(BesselBase):
r"""
Modified Bessel function of the first kind.
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 z.is_imaginary:
if im(z) is S.Infinity or im(z) is S.NegativeInfinity:
return S.Zero
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:
from sympy import unpolarify, exp
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):
from sympy import polar_lift, exp
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 _sage_(self):
import sage.all as sage
return sage.bessel_I(self.args[0]._sage_(), self.args[1]._sage_())
class besselk(BesselBase):
r"""
Modified Bessel function of the second kind.
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.is_imaginary:
if im(z) is S.Infinity or im(z) is 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 _sage_(self):
import sage.all as sage
return sage.bessel_K(self.args[0]._sage_(), self.args[1]._sage_())
class hankel1(BesselBase):
r"""
Hankel function of the first kind.
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.
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 ``_rewrite`` and ``_expand`` methods.
"""
def _expand(self, **hints):
""" Expand self into a polynomial. Nu is guaranteed to be Integer. """
raise NotImplementedError('expansion')
def _rewrite(self):
""" Rewrite self in terms of ordinary Bessel functions. """
raise NotImplementedError('rewriting')
def _eval_expand_func(self, **hints):
if self.order.is_Integer:
return self._expand(**hints)
return self
def _eval_evalf(self, prec):
if self.order.is_Integer:
return self._rewrite()._eval_evalf(prec)
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 fn(n, z)*sin(z) + (-1)**(n + 1)*fn(-n - 1, z)*cos(z)
def _yn(n, z):
# (-1)**(n + 1) * _jn(-n - 1, z)
return (-1)**(n + 1) * fn(-n - 1, z)*sin(z) - fn(n, z)*cos(z)
class jn(SphericalBesselBase):
r"""
Spherical Bessel function of the first kind.
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:`polys.orthopolys.spherical_bessel_fn`.
Examples
========
>>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely
>>> from sympy import simplify
>>> 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
"""
def _rewrite(self):
return self._eval_rewrite_as_besselj(self.order, self.argument)
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 (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
return (-1)**(nu) * yn(-nu - 1, z)
def _expand(self, **hints):
return _jn(self.order, self.argument)
class yn(SphericalBesselBase):
r"""
Spherical Bessel function of the second kind.
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
"""
def _rewrite(self):
return self._eval_rewrite_as_bessely(self.order, self.argument)
@assume_integer_order
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
return (-1)**(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 (-1)**(nu + 1) * jn(-nu - 1, z)
def _expand(self, **hints):
return _yn(self.order, self.argument)
class SphericalHankelBase(SphericalBesselBase):
def _rewrite(self):
return self._eval_rewrite_as_besselj(self.order, self.argument)
@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*(-1)**(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))*((-1)**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()
class hn1(SphericalHankelBase):
r"""
Spherical Hankel function of the first kind.
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.
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.
This returns an array of zeros of jn up to the k-th zero.
* method = "sympy": uses :func:`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
"""
from math import pi
if method == "sympy":
from mpmath import besseljzero
from mpmath.libmp.libmpf import dps_to_prec
from sympy import Expr
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 + 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 + 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):
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:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
return (re, im)
def as_real_imag(self, deep=True, **hints):
x, y = self._as_real_imag(deep=deep, **hints)
sq = -y**2/x**2
re = S.Half*(self.func(x+x*sqrt(sq))+self.func(x-x*sqrt(sq)))
im = x/(2*y) * sqrt(sq) * (self.func(x-x*sqrt(sq)) - self.func(x+x*sqrt(sq)))
return (re, im)
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.
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 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)))
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 ((3**Rational(1, 3)*x)**(-n)*(3**Rational(1, 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(2*pi*(n+S.One)/S(3)) /
factorial(n) * (root(3, 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.
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 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)))
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 (3**Rational(1, 3)*x * Abs(sin(2*pi*(n + S.One)/S(3))) * factorial((n - S.One)/S(3)) /
((n + S.One) * Abs(cos(2*pi*(n + S.Half)/S(3))) * factorial((n - 2)/S(3))) * p)
else:
return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(2*pi*(n + S.One)/S(3))) /
factorial(n) * (root(3, 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.
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 Ai'(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
elif arg.is_zero:
return -S.One / (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):
from mpmath import mp, workprec
from sympy import Expr
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.
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 Bi'(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))
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):
from mpmath import mp, workprec
from sympy import Expr
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
It 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, x
>>> 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):
from sympy import exp, uppergamma
if a == 0:
if m == 0 and b == 0:
return S.Zero
return uppergamma(m, b**2 / 2) / gamma(m)
if m == 0 and b == 0:
return 1 - 1 / exp(a**2 / 2)
if a == b:
if m == 1:
return (1 + exp(-a**2) * besseli(0, a**2)) / 2
if m == 2:
return S.Half + S.Half * exp(-a**2) * besseli(0, a**2) + exp(-a**2) * besseli(1, a**2)
def fdiff(self, argindex=2):
from sympy import exp
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 import Integral, exp, Dummy, oo
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, oo])
def _eval_rewrite_as_Sum(self, m, a, b, **kwargs):
from sympy import Sum, exp, Dummy, oo
k = kwargs.get('k', Dummy('k'))
return exp(-(a**2 + b**2) / 2) * Sum((a/b)**k * besseli(k, a*b), [k, 1-m, oo])
def _eval_rewrite_as_besseli(self, m, a, b, **kwargs):
if a == b:
from sympy import exp
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
|
79cf9dc13fe2e27f03e2edcaaf8114eb40ab474314c2e6bbbe20a0819a08732a | """ Elliptic integrals. """
from __future__ import print_function, division
from sympy.core import S, pi, I, Rational
from sympy.core.function import Function, ArgumentIndexError
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.hyperbolic import atanh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin, tan
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import hyper, meijerg
class elliptic_k(Function):
r"""
The complete elliptic integral of the first kind, defined by
.. math:: K(m) = F\left(\tfrac{\pi}{2}\middle| m\right)
where `F\left(z\middle| m\right)` is the Legendre incomplete
elliptic integral of the first kind.
The function `K(m)` is a single-valued function on the complex
plane with branch cut along the interval `(1, \infty)`.
Note that our notation defines the incomplete elliptic integral
in terms of the parameter `m` instead of the elliptic modulus
(eccentricity) `k`.
In this case, the parameter `m` is defined as `m=k^2`.
Examples
========
>>> from sympy import elliptic_k, I, pi
>>> from sympy.abc import m
>>> elliptic_k(0)
pi/2
>>> elliptic_k(1.0 + I)
1.50923695405127 + 0.625146415202697*I
>>> elliptic_k(m).series(n=3)
pi/2 + pi*m/8 + 9*pi*m**2/128 + O(m**3)
See Also
========
elliptic_f
References
==========
.. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
.. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticK
"""
@classmethod
def eval(cls, m):
if m.is_zero:
return pi/2
elif m is S.Half:
return 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2
elif m is S.One:
return S.ComplexInfinity
elif m is S.NegativeOne:
return gamma(Rational(1, 4))**2/(4*sqrt(2*pi))
elif m in (S.Infinity, S.NegativeInfinity, I*S.Infinity,
I*S.NegativeInfinity, S.ComplexInfinity):
return S.Zero
def fdiff(self, argindex=1):
m = self.args[0]
return (elliptic_e(m) - (1 - m)*elliptic_k(m))/(2*m*(1 - m))
def _eval_conjugate(self):
m = self.args[0]
if (m.is_real and (m - 1).is_positive) is False:
return self.func(m.conjugate())
def _eval_nseries(self, x, n, logx):
from sympy.simplify import hyperexpand
return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx))
def _eval_rewrite_as_hyper(self, m, **kwargs):
return (pi/2)*hyper((S.Half, S.Half), (S.One,), m)
def _eval_rewrite_as_meijerg(self, m, **kwargs):
return meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -m)/2
def _sage_(self):
import sage.all as sage
return sage.elliptic_kc(self.args[0]._sage_())
class elliptic_f(Function):
r"""
The Legendre incomplete elliptic integral of the first
kind, defined by
.. math:: F\left(z\middle| m\right) =
\int_0^z \frac{dt}{\sqrt{1 - m \sin^2 t}}
This function reduces to a complete elliptic integral of
the first kind, `K(m)`, when `z = \pi/2`.
Note that our notation defines the incomplete elliptic integral
in terms of the parameter `m` instead of the elliptic modulus
(eccentricity) `k`.
In this case, the parameter `m` is defined as `m=k^2`.
Examples
========
>>> from sympy import elliptic_f, I, O
>>> from sympy.abc import z, m
>>> elliptic_f(z, m).series(z)
z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6)
>>> elliptic_f(3.0 + I/2, 1.0 + I)
2.909449841483 + 1.74720545502474*I
See Also
========
elliptic_k
References
==========
.. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
.. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticF
"""
@classmethod
def eval(cls, z, m):
k = 2*z/pi
if m.is_zero:
return z
elif z.is_zero:
return S.Zero
elif k.is_integer:
return k*elliptic_k(m)
elif m in (S.Infinity, S.NegativeInfinity):
return S.Zero
elif z.could_extract_minus_sign():
return -elliptic_f(-z, m)
def fdiff(self, argindex=1):
z, m = self.args
fm = sqrt(1 - m*sin(z)**2)
if argindex == 1:
return 1/fm
elif argindex == 2:
return (elliptic_e(z, m)/(2*m*(1 - m)) - elliptic_f(z, m)/(2*m) -
sin(2*z)/(4*(1 - m)*fm))
raise ArgumentIndexError(self, argindex)
def _eval_conjugate(self):
z, m = self.args
if (m.is_real and (m - 1).is_positive) is False:
return self.func(z.conjugate(), m.conjugate())
class elliptic_e(Function):
r"""
Called with two arguments `z` and `m`, evaluates the
incomplete elliptic integral of the second kind, defined by
.. math:: E\left(z\middle| m\right) = \int_0^z \sqrt{1 - m \sin^2 t} dt
Called with a single argument `m`, evaluates the Legendre complete
elliptic integral of the second kind
.. math:: E(m) = E\left(\tfrac{\pi}{2}\middle| m\right)
The function `E(m)` is a single-valued function on the complex
plane with branch cut along the interval `(1, \infty)`.
Note that our notation defines the incomplete elliptic integral
in terms of the parameter `m` instead of the elliptic modulus
(eccentricity) `k`.
In this case, the parameter `m` is defined as `m=k^2`.
Examples
========
>>> from sympy import elliptic_e, I, pi, O
>>> from sympy.abc import z, m
>>> elliptic_e(z, m).series(z)
z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6)
>>> elliptic_e(m).series(n=4)
pi/2 - pi*m/8 - 3*pi*m**2/128 - 5*pi*m**3/512 + O(m**4)
>>> elliptic_e(1 + I, 2 - I/2).n()
1.55203744279187 + 0.290764986058437*I
>>> elliptic_e(0)
pi/2
>>> elliptic_e(2.0 - I)
0.991052601328069 + 0.81879421395609*I
References
==========
.. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
.. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticE2
.. [3] http://functions.wolfram.com/EllipticIntegrals/EllipticE
"""
@classmethod
def eval(cls, m, z=None):
if z is not None:
z, m = m, z
k = 2*z/pi
if m.is_zero:
return z
if z.is_zero:
return S.Zero
elif k.is_integer:
return k*elliptic_e(m)
elif m in (S.Infinity, S.NegativeInfinity):
return S.ComplexInfinity
elif z.could_extract_minus_sign():
return -elliptic_e(-z, m)
else:
if m.is_zero:
return pi/2
elif m is S.One:
return S.One
elif m is S.Infinity:
return I*S.Infinity
elif m is S.NegativeInfinity:
return S.Infinity
elif m is S.ComplexInfinity:
return S.ComplexInfinity
def fdiff(self, argindex=1):
if len(self.args) == 2:
z, m = self.args
if argindex == 1:
return sqrt(1 - m*sin(z)**2)
elif argindex == 2:
return (elliptic_e(z, m) - elliptic_f(z, m))/(2*m)
else:
m = self.args[0]
if argindex == 1:
return (elliptic_e(m) - elliptic_k(m))/(2*m)
raise ArgumentIndexError(self, argindex)
def _eval_conjugate(self):
if len(self.args) == 2:
z, m = self.args
if (m.is_real and (m - 1).is_positive) is False:
return self.func(z.conjugate(), m.conjugate())
else:
m = self.args[0]
if (m.is_real and (m - 1).is_positive) is False:
return self.func(m.conjugate())
def _eval_nseries(self, x, n, logx):
from sympy.simplify import hyperexpand
if len(self.args) == 1:
return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx))
return super(elliptic_e, self)._eval_nseries(x, n=n, logx=logx)
def _eval_rewrite_as_hyper(self, *args, **kwargs):
if len(args) == 1:
m = args[0]
return (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), m)
def _eval_rewrite_as_meijerg(self, *args, **kwargs):
if len(args) == 1:
m = args[0]
return -meijerg(((S.Half, Rational(3, 2)), []), \
((S.Zero,), (S.Zero,)), -m)/4
class elliptic_pi(Function):
r"""
Called with three arguments `n`, `z` and `m`, evaluates the
Legendre incomplete elliptic integral of the third kind, defined by
.. math:: \Pi\left(n; z\middle| m\right) = \int_0^z \frac{dt}
{\left(1 - n \sin^2 t\right) \sqrt{1 - m \sin^2 t}}
Called with two arguments `n` and `m`, evaluates the complete
elliptic integral of the third kind:
.. math:: \Pi\left(n\middle| m\right) =
\Pi\left(n; \tfrac{\pi}{2}\middle| m\right)
Note that our notation defines the incomplete elliptic integral
in terms of the parameter `m` instead of the elliptic modulus
(eccentricity) `k`.
In this case, the parameter `m` is defined as `m=k^2`.
Examples
========
>>> from sympy import elliptic_pi, I, pi, O, S
>>> from sympy.abc import z, n, m
>>> elliptic_pi(n, z, m).series(z, n=4)
z + z**3*(m/6 + n/3) + O(z**4)
>>> elliptic_pi(0.5 + I, 1.0 - I, 1.2)
2.50232379629182 - 0.760939574180767*I
>>> elliptic_pi(0, 0)
pi/2
>>> elliptic_pi(1.0 - I/3, 2.0 + I)
3.29136443417283 + 0.32555634906645*I
References
==========
.. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
.. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticPi3
.. [3] http://functions.wolfram.com/EllipticIntegrals/EllipticPi
"""
@classmethod
def eval(cls, n, m, z=None):
if z is not None:
n, z, m = n, m, z
k = 2*z/pi
if n.is_zero:
return elliptic_f(z, m)
elif n == S.One:
return (elliptic_f(z, m) +
(sqrt(1 - m*sin(z)**2)*tan(z) -
elliptic_e(z, m))/(1 - m))
elif k.is_integer:
return k*elliptic_pi(n, m)
elif m.is_zero:
return atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1)
elif n == m:
return (elliptic_f(z, n) - elliptic_pi(1, z, n) +
tan(z)/sqrt(1 - n*sin(z)**2))
elif n in (S.Infinity, S.NegativeInfinity):
return S.Zero
elif m in (S.Infinity, S.NegativeInfinity):
return S.Zero
elif z.could_extract_minus_sign():
return -elliptic_pi(n, -z, m)
else:
if n.is_zero:
return elliptic_k(m)
elif n == S.One:
return S.ComplexInfinity
elif m.is_zero:
return pi/(2*sqrt(1 - n))
elif m == S.One:
return S.NegativeInfinity/sign(n - 1)
elif n == m:
return elliptic_e(n)/(1 - n)
elif n in (S.Infinity, S.NegativeInfinity):
return S.Zero
elif m in (S.Infinity, S.NegativeInfinity):
return S.Zero
def _eval_conjugate(self):
if len(self.args) == 3:
n, z, m = self.args
if (n.is_real and (n - 1).is_positive) is False and \
(m.is_real and (m - 1).is_positive) is False:
return self.func(n.conjugate(), z.conjugate(), m.conjugate())
else:
n, m = self.args
return self.func(n.conjugate(), m.conjugate())
def fdiff(self, argindex=1):
if len(self.args) == 3:
n, z, m = self.args
fm, fn = sqrt(1 - m*sin(z)**2), 1 - n*sin(z)**2
if argindex == 1:
return (elliptic_e(z, m) + (m - n)*elliptic_f(z, m)/n +
(n**2 - m)*elliptic_pi(n, z, m)/n -
n*fm*sin(2*z)/(2*fn))/(2*(m - n)*(n - 1))
elif argindex == 2:
return 1/(fm*fn)
elif argindex == 3:
return (elliptic_e(z, m)/(m - 1) +
elliptic_pi(n, z, m) -
m*sin(2*z)/(2*(m - 1)*fm))/(2*(n - m))
else:
n, m = self.args
if argindex == 1:
return (elliptic_e(m) + (m - n)*elliptic_k(m)/n +
(n**2 - m)*elliptic_pi(n, m)/n)/(2*(m - n)*(n - 1))
elif argindex == 2:
return (elliptic_e(m)/(m - 1) + elliptic_pi(n, m))/(2*(n - m))
raise ArgumentIndexError(self, argindex)
|
8eeda59cca6953ac0ee537b378b36fb76b07571ed6b0d0b9f56338400a4c15ca | """ This module contains various functions that are special cases
of incomplete gamma functions. It should probably be renamed. """
from __future__ import print_function, division
from sympy.core import Add, S, sympify, cacheit, pi, I, Rational
from sympy.core.compatibility import range
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt, root
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.complexes import polar_lift
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. 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]
# 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 is S.Infinity or t is 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*(-1)**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_rewrite_as_uppergamma(self, z, **kwargs):
from sympy 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, **kwargs):
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):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return 2*x/sqrt(pi)
else:
return self.func(arg)
as_real_imag = real_to_real_as_real_imag
class erfc(Function):
r"""
Complementary Error Function. 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]
# Try to pull out factors of I
t = arg.extract_multiplicatively(S.ImaginaryUnit)
if t is S.Infinity or t is S.NegativeInfinity:
return -arg
# Try to pull out factors of -1
if arg.could_extract_minus_sign():
return S(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*(-1)**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, **kwargs):
return self.rewrite(erf).rewrite("tractable", deep=True)
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 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):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return S.One
else:
return self.func(arg)
as_real_imag = real_to_real_as_real_imag
class erfi(Function):
r"""
Imaginary error function. 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
# 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_rewrite_as_tractable(self, z, **kwargs):
return self.rewrite(erf).rewrite("tractable", deep=True)
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 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
class erf2(Function):
r"""
Two-argument error function. 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 I, 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):
I = S.Infinity
N = S.NegativeInfinity
O = S.Zero
if x is S.NaN or y is S.NaN:
return S.NaN
elif x == y:
return S.Zero
elif (x is I or x is N or x is O) or (y is I or y is N or y is O):
return erf(y) - erf(x)
if isinstance(y, erf2inv) and y.args[0] == x:
return y.args[1]
#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 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)
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 I, oo, 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]
# 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)
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 I, oo, 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
def _eval_rewrite_as_erfinv(self, z, **kwargs):
return erfinv(1-z)
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 I, oo, erf2inv, erfinv, erfcinv
>>> 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)
###############################################################################
#################### EXPONENTIAL INTEGRALS ####################################
###############################################################################
class Ei(Function):
r"""
The classical exponential integral.
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 uppergamma, 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.
sympy.functions.special.gamma_functions.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
nz, n = z.extract_branch_factor()
if n:
return Ei(nz) + 2*I*pi*n
def fdiff(self, argindex=1):
from sympy import unpolarify
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 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):
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, **kwargs):
return exp(z) * _eis(z)
def _eval_nseries(self, x, n, logx):
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(Ei, self)._eval_nseries(x, n, logx)
class expint(Function):
r"""
Generalized exponential integral.
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 :math:`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 :math:`\operatorname{E}_\nu(z)`. If :math:`\nu` is a
non-positive integer the exponential integral is thus an unbranched
function of :math:`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 explains
further 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.
sympy.functions.special.gamma_functions.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 import (unpolarify, expand_mul, uppergamma, exp, gamma,
factorial)
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 == 0:
return
if nu.is_integer:
if not nu > 0:
return
return expint(nu, z) \
- 2*pi*I*n*(-1)**(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):
from sympy import meijerg
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 import uppergamma
return z**(nu - 1)*uppergamma(1 - nu, z)
def _eval_rewrite_as_Ei(self, nu, z, **kwargs):
from sympy import exp_polar, unpolarify, exp, factorial
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):
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(expint, self)._eval_nseries(x, n, logx)
def _sage_(self):
import sage.all as sage
return sage.exp_integral_e(self.args[0]._sage_(), self.args[1]._sage_())
def E1(z):
"""
Classical case of the generalized exponential integral.
This is equivalent to ``expint(1, z)``.
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.
For the 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:
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
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 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, **kwargs):
return z * _eis(log(z))
class Li(Function):
r"""
The offset logarithmic integral.
For the use in SymPy, this function is defined as
.. math:: \operatorname{Li}(x) = \operatorname{li}(x) - \operatorname{li}(2)
Examples
========
>>> from sympy import I, oo, 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 is 2*S.One:
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, **kwargs):
return self.rewrite(li).rewrite("tractable", deep=True)
###############################################################################
#################### TRIGONOMETRIC INTEGRALS ##################################
###############################################################################
class TrigonometricIntegral(Function):
""" Base class for trigonometric integrals. """
@classmethod
def eval(cls, z):
if z == 0:
return cls._atzero
elif z is S.Infinity:
return cls._atinf()
elif z is S.NegativeInfinity:
return cls._atneginf()
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):
from sympy import unpolarify
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 import uppergamma
return self._eval_rewrite_as_expint(z).rewrite(uppergamma)
def _eval_nseries(self, x, n, logx):
# NOTE this is fairly inefficient
from sympy import log, EulerGamma, Pow
n += 1
if self.args[0].subs(x, 0) != 0:
return super(TrigonometricIntegral, self)._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.
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 import Integral
t = Symbol('t', Dummy=True)
return Integral(sinc(t), (t, 0, z))
def _sage_(self):
import sage.all as sage
return sage.sin_integral(self.args[0]._sage_())
class Ci(TrigonometricIntegral):
r"""
Cosine integral.
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 _sage_(self):
import sage.all as sage
return sage.cos_integral(self.args[0]._sage_())
class Shi(TrigonometricIntegral):
r"""
Sinh integral.
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):
from sympy import exp_polar
# XXX should we polarify z?
return (E1(z) - E1(exp_polar(I*pi)*z))/2 - I*pi/2
def _sage_(self):
import sage.all as sage
return sage.sinh_integral(self.args[0]._sage_())
class Chi(TrigonometricIntegral):
r"""
Cosh integral.
This function is defined for positive :math:`x` by
.. math:: \operatorname{Chi}(x) = \gamma + \log{x}
+ \int_0^x \frac{\cosh{t} - 1}{t} \mathrm{d}t,
where :math:`\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 :math:`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):
from sympy import exp_polar
return -I*pi/2 - (E1(z) + E1(exp_polar(I*pi)*z))/2
def _sage_(self):
import sage.all as sage
return sage.cosh_integral(self.args[0]._sage_())
###############################################################################
#################### FRESNEL INTEGRALS ########################################
###############################################################################
class FresnelIntegral(Function):
""" Base class for the Fresnel integrals."""
unbranched = True
@classmethod
def eval(cls, z):
# 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)
# Values at positive infinities signs
# if any were extracted automatically
if z is S.Infinity:
return S.Half
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_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.
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, gamma, 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_aseries(self, n, args0, x, logx):
from sympy 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 = [(-1)**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)] + [(-1)**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(fresnels, self)._eval_aseries(n, args0, x, logx)
class fresnelc(FresnelIntegral):
r"""
Fresnel integral C.
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, gamma, 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_aseries(self, n, args0, x, logx):
from sympy 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 = [(-1)**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)] + [(-1)**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(fresnelc, self)._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.
"""
def _eval_aseries(self, n, args0, x, logx):
from sympy 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(0, 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(0, 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(_erfs, self)._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 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(0, 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_nseries(self, x, n, logx):
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(_eis, self)._eval_nseries(x, n, logx)
|
bc511bb73d35ad637d3a62a8ab2e31733030e181eaf437e4c5471fddb03faf05 | """
This module mainly implements special orthogonal polynomials.
See also functions.combinatorial.numbers which contains some
combinatorial polynomials.
"""
from __future__ import print_function, division
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 (
jacobi_poly,
gegenbauer_poly,
chebyshevt_poly,
chebyshevu_poly,
laguerre_poly,
hermite_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 :math:`P_n^{\left(\alpha, \beta\right)}(x)`
jacobi(n, alpha, beta, x) gives the nth Jacobi polynomial
in x, :math:`P_n^{\left(\alpha, \beta\right)}(x)`.
The Jacobi polynomials are orthogonal on :math:`[-1, 1]` with respect
to the weight :math:`\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)
2**(-n)*gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(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,
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 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_polynomial(self, n, a, b, x, **kwargs):
from sympy 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_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 :math:`P_n^{\left(\alpha, \beta\right)}(x)`
jacobi_normalized(n, alpha, beta, x) gives the nth Jacobi polynomial
in x, :math:`P_n^{\left(\alpha, \beta\right)}(x)`.
The Jacobi polynomials are orthogonal on :math:`[-1, 1]` with respect
to the weight :math:`\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)))
See Also
========
gegenbauer,
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.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 :math:`C_n^{\left(\alpha\right)}(x)`
gegenbauer(n, alpha, x) gives the nth Gegenbauer polynomial
in x, :math:`C_n^{\left(\alpha\right)}(x)`.
The Gegenbauer polynomials are orthogonal on :math:`[-1, 1]` with
respect to the weight :math:`\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,
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/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 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_polynomial(self, n, a, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = ((-1)**k * RisingFactorial(a, n - k) * (2*x)**(n - 2*k) /
(factorial(k) * factorial(n - 2*k)))
return Sum(kern, (k, 0, floor(n/2)))
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, :math:`T_n(x)`
chebyshevt(n, x) gives the nth Chebyshev polynomial (of the first
kind) in x, :math:`T_n(x)`.
The Chebyshev polynomials of the first kind are orthogonal on
:math:`[-1, 1]` with respect to the weight :math:`\frac{1}{\sqrt{1-x^2}}`.
Examples
========
>>> from sympy import chebyshevt, chebyshevu, 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,
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/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_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = binomial(n, 2*k) * (x**2 - 1)**k * x**(n - 2*k)
return Sum(kern, (k, 0, floor(n/2)))
class chebyshevu(OrthogonalPolynomial):
r"""
Chebyshev polynomial of the second kind, :math:`U_n(x)`
chebyshevu(n, x) gives the nth Chebyshev polynomial of the second
kind in x, :math:`U_n(x)`.
The Chebyshev polynomials of the second kind are orthogonal on
:math:`[-1, 1]` with respect to the weight :math:`\sqrt{1-x^2}`.
Examples
========
>>> from sympy import chebyshevt, 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,
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/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_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = S.NegativeOne**k * factorial(
n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k))
return Sum(kern, (k, 0, floor(n/2)))
class chebyshevt_root(Function):
r"""
chebyshev_root(n, k) returns the kth root (indexed from zero) of
the nth Chebyshev polynomial of the first kind; that is, if
0 <= 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,
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
"""
@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 kth root (indexed from zero) of the
nth Chebyshev polynomial of the second kind; that is, if 0 <= 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,
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
"""
@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 nth Legendre polynomial of x, :math:`P_n(x)`
The Legendre polynomials are orthogonal on [-1, 1] with respect to
the constant weight 1. They satisfy :math:`P_n(1) = 1` for all n; further,
:math:`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,
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/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_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = (-1)**k*binomial(n, k)**2*((1 + x)/2)**(n - k)*((1 - x)/2)**k
return Sum(kern, (k, 0, n))
class assoc_legendre(Function):
r"""
assoc_legendre(n,m, x) gives :math:`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, :math:`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}
Associated Legendre polynomial are orthogonal on [-1, 1] with:
- weight = 1 for the same m, and different n.
- weight = 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,
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/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 (-1)**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_polynomial(self, n, m, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = factorial(2*n - 2*k)/(2**n*factorial(n - k)*factorial(
k)*factorial(n - 2*k - m))*(-1)**k*x**(n - m - 2*k)
return (1 - x**2)**(m/2) * Sum(kern, (k, 0, floor((n - m)*S.Half)))
def _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 nth Hermite polynomial in x, :math:`H_n(x)`
The Hermite polynomials are orthogonal on :math:`(-\infty, \infty)`
with respect to the weight :math:`\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,
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/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_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = (-1)**k / (factorial(k)*factorial(n - 2*k)) * (2*x)**(n - 2*k)
return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
#----------------------------------------------------------------------------
# Laguerre polynomials
#
class laguerre(OrthogonalPolynomial):
r"""
Returns the nth Laguerre polynomial in x, :math:`L_n(x)`.
Parameters
==========
n : int
Degree of Laguerre polynomial. Must be ``n >= 0``.
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)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
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/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_polynomial(self, n, x, **kwargs):
from sympy import Sum
# Make sure n \in N_0
if n.is_negative:
return exp(x) * self._eval_rewrite_as_polynomial(-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))
class assoc_laguerre(OrthogonalPolynomial):
r"""
Returns the nth generalized Laguerre polynomial in x, :math:`L_n(x)`.
Parameters
==========
n : int
Degree of Laguerre polynomial. Must be ``n >= 0``.
alpha : Expr
Arbitrary expression. For ``alpha=0`` regular Laguerre
polynomials will be generated.
Examples
========
>>> from sympy import laguerre, 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))
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
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/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 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_polynomial(self, n, alpha, x, **kwargs):
from sympy 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_conjugate(self):
n, alpha, x = self.args
return self.func(n, alpha.conjugate(), x.conjugate())
|
7c23e6cad14f76ee46a19c6b60d1a8e7db8d4f2bc10f316785ec8b81419c296b | from sympy import (S, Symbol, symbols, factorial, factorial2, Float, binomial,
rf, ff, gamma, polygamma, EulerGamma, O, pi, nan,
oo, zoo, simplify, expand_func, Product, Mul, Piecewise,
Mod, Eq, sqrt, Poly, Dummy, I, Rational)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.functions.combinatorial.factorials import subfactorial
from sympy.functions.special.gamma_functions import uppergamma
from sympy.utilities.pytest import XFAIL, raises, slow
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
def test_rf_eval_apply():
x, y = symbols('x,y')
n, k = symbols('n k', integer=True)
m = Symbol('m', integer=True, nonnegative=True)
assert rf(nan, y) is nan
assert rf(x, nan) is nan
assert unchanged(rf, x, y)
assert rf(oo, 0) == 1
assert rf(-oo, 0) == 1
assert rf(oo, 6) is oo
assert rf(-oo, 7) is -oo
assert rf(-oo, 6) is oo
assert rf(oo, -6) is oo
assert rf(-oo, -7) is oo
assert rf(-1, pi) == 0
assert rf(-5, 1 + I) == 0
assert unchanged(rf, -3, k)
assert unchanged(rf, x, Symbol('k', integer=False))
assert rf(-3, Symbol('k', integer=False)) == 0
assert rf(Symbol('x', negative=True, integer=True), Symbol('k', integer=False)) == 0
assert rf(x, 0) == 1
assert rf(x, 1) == x
assert rf(x, 2) == x*(x + 1)
assert rf(x, 3) == x*(x + 1)*(x + 2)
assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4)
assert rf(x, -1) == 1/(x - 1)
assert rf(x, -2) == 1/((x - 1)*(x - 2))
assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3))
assert rf(1, 100) == factorial(100)
assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1)
assert isinstance(rf(x**2 + 3*x, 2), Mul)
assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2))
assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x)
assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly)
raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2))
assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20)
raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2))
assert rf(x, m).is_integer is None
assert rf(n, k).is_integer is None
assert rf(n, m).is_integer is True
assert rf(n, k + pi).is_integer is False
assert rf(n, m + pi).is_integer is False
assert rf(pi, m).is_integer is False
assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k)
assert rf(n, k).rewrite(factorial) == \
factorial(n + k - 1) / factorial(n - 1)
assert rf(x, y).rewrite(factorial) == rf(x, y)
assert rf(x, y).rewrite(binomial) == rf(x, y)
import random
from mpmath import rf as mpmath_rf
for i in range(100):
x = -500 + 500 * random.random()
k = -500 + 500 * random.random()
assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15))
def test_ff_eval_apply():
x, y = symbols('x,y')
n, k = symbols('n k', integer=True)
m = Symbol('m', integer=True, nonnegative=True)
assert ff(nan, y) is nan
assert ff(x, nan) is nan
assert unchanged(ff, x, y)
assert ff(oo, 0) == 1
assert ff(-oo, 0) == 1
assert ff(oo, 6) is oo
assert ff(-oo, 7) is -oo
assert ff(-oo, 6) is oo
assert ff(oo, -6) is oo
assert ff(-oo, -7) is oo
assert ff(x, 0) == 1
assert ff(x, 1) == x
assert ff(x, 2) == x*(x - 1)
assert ff(x, 3) == x*(x - 1)*(x - 2)
assert ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
assert ff(x, -1) == 1/(x + 1)
assert ff(x, -2) == 1/((x + 1)*(x + 2))
assert ff(x, -3) == 1/((x + 1)*(x + 2)*(x + 3))
assert ff(100, 100) == factorial(100)
assert ff(2*x**2 - 5*x, 2) == (2*x**2 - 5*x)*(2*x**2 - 5*x - 1)
assert isinstance(ff(2*x**2 - 5*x, 2), Mul)
assert ff(x**2 + 3*x, -2) == 1/((x**2 + 3*x + 1)*(x**2 + 3*x + 2))
assert ff(Poly(2*x**2 - 5*x, x), 2) == Poly(4*x**4 - 28*x**3 + 59*x**2 - 35*x, x)
assert isinstance(ff(Poly(2*x**2 - 5*x, x), 2), Poly)
raises(ValueError, lambda: ff(Poly(2*x**2 - 5*x, x, y), 2))
assert ff(Poly(x**2 + 3*x, x), -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40)
raises(ValueError, lambda: ff(Poly(x**2 + 3*x, x, y), -2))
assert ff(x, m).is_integer is None
assert ff(n, k).is_integer is None
assert ff(n, m).is_integer is True
assert ff(n, k + pi).is_integer is False
assert ff(n, m + pi).is_integer is False
assert ff(pi, m).is_integer is False
assert isinstance(ff(x, x), ff)
assert ff(n, n) == factorial(n)
assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
assert ff(x, k).rewrite(gamma) == (-1)**k*gamma(k - x) / gamma(-x)
assert ff(n, k).rewrite(factorial) == factorial(n) / factorial(n - k)
assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
assert ff(x, y).rewrite(factorial) == ff(x, y)
assert ff(x, y).rewrite(binomial) == ff(x, y)
import random
from mpmath import ff as mpmath_ff
for i in range(100):
x = -500 + 500 * random.random()
k = -500 + 500 * random.random()
assert (abs(mpmath_ff(x, k) - ff(x, k)) < 10**(-15))
def test_rf_ff_eval_hiprec():
maple = Float('6.9109401292234329956525265438452')
us = ff(18, Rational(2, 3)).evalf(32)
assert abs(us - maple)/us < 1e-31
maple = Float('6.8261540131125511557924466355367')
us = rf(18, Rational(2, 3)).evalf(32)
assert abs(us - maple)/us < 1e-31
maple = Float('34.007346127440197150854651814225')
us = rf(Float('4.4', 32), Float('2.2', 32));
assert abs(us - maple)/us < 1e-31
def test_rf_lambdify_mpmath():
from sympy import lambdify
x, y = symbols('x,y')
f = lambdify((x,y), rf(x, y), 'mpmath')
maple = Float('34.007346127440197')
us = f(4.4, 2.2)
assert abs(us - maple)/us < 1e-15
def test_factorial():
x = Symbol('x')
n = Symbol('n', integer=True)
k = Symbol('k', integer=True, nonnegative=True)
r = Symbol('r', integer=False)
s = Symbol('s', integer=False, negative=True)
t = Symbol('t', nonnegative=True)
u = Symbol('u', noninteger=True)
assert factorial(-2) is zoo
assert factorial(0) == 1
assert factorial(7) == 5040
assert factorial(19) == 121645100408832000
assert factorial(31) == 8222838654177922817725562880000000
assert factorial(n).func == factorial
assert factorial(2*n).func == factorial
assert factorial(x).is_integer is None
assert factorial(n).is_integer is None
assert factorial(k).is_integer
assert factorial(r).is_integer is None
assert factorial(n).is_positive is None
assert factorial(k).is_positive
assert factorial(x).is_real is None
assert factorial(n).is_real is None
assert factorial(k).is_real is True
assert factorial(r).is_real is None
assert factorial(s).is_real is True
assert factorial(t).is_real is True
assert factorial(u).is_real is True
assert factorial(x).is_composite is None
assert factorial(n).is_composite is None
assert factorial(k).is_composite is None
assert factorial(k + 3).is_composite is True
assert factorial(r).is_composite is None
assert factorial(s).is_composite is None
assert factorial(t).is_composite is None
assert factorial(u).is_composite is None
assert factorial(oo) is oo
def test_factorial_Mod():
pr = Symbol('pr', prime=True)
p, q = 10**9 + 9, 10**9 + 33 # prime modulo
r, s = 10**7 + 5, 33333333 # composite modulo
assert Mod(factorial(pr - 1), pr) == pr - 1
assert Mod(factorial(pr - 1), -pr) == -1
assert Mod(factorial(r - 1, evaluate=False), r) == 0
assert Mod(factorial(s - 1, evaluate=False), s) == 0
assert Mod(factorial(p - 1, evaluate=False), p) == p - 1
assert Mod(factorial(q - 1, evaluate=False), q) == q - 1
assert Mod(factorial(p - 50, evaluate=False), p) == 854928834
assert Mod(factorial(q - 1800, evaluate=False), q) == 905504050
assert Mod(factorial(153, evaluate=False), r) == Mod(factorial(153), r)
assert Mod(factorial(255, evaluate=False), s) == Mod(factorial(255), s)
def test_factorial_diff():
n = Symbol('n', integer=True)
assert factorial(n).diff(n) == \
gamma(1 + n)*polygamma(0, 1 + n)
assert factorial(n**2).diff(n) == \
2*n*gamma(1 + n**2)*polygamma(0, 1 + n**2)
raises(ArgumentIndexError, lambda: factorial(n**2).fdiff(2))
def test_factorial_series():
n = Symbol('n', integer=True)
assert factorial(n).series(n, 0, 3) == \
1 - n*EulerGamma + n**2*(EulerGamma**2/2 + pi**2/12) + O(n**3)
def test_factorial_rewrite():
n = Symbol('n', integer=True)
k = Symbol('k', integer=True, nonnegative=True)
assert factorial(n).rewrite(gamma) == gamma(n + 1)
_i = Dummy('i')
assert factorial(k).rewrite(Product).dummy_eq(Product(_i, (_i, 1, k)))
assert factorial(n).rewrite(Product) == factorial(n)
def test_factorial2():
n = Symbol('n', integer=True)
assert factorial2(-1) == 1
assert factorial2(0) == 1
assert factorial2(7) == 105
assert factorial2(8) == 384
# The following is exhaustive
tt = Symbol('tt', integer=True, nonnegative=True)
tte = Symbol('tte', even=True, nonnegative=True)
tpe = Symbol('tpe', even=True, positive=True)
tto = Symbol('tto', odd=True, nonnegative=True)
tf = Symbol('tf', integer=True, nonnegative=False)
tfe = Symbol('tfe', even=True, nonnegative=False)
tfo = Symbol('tfo', odd=True, nonnegative=False)
ft = Symbol('ft', integer=False, nonnegative=True)
ff = Symbol('ff', integer=False, nonnegative=False)
fn = Symbol('fn', integer=False)
nt = Symbol('nt', nonnegative=True)
nf = Symbol('nf', nonnegative=False)
nn = Symbol('nn')
z = Symbol('z', zero=True)
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
raises(ValueError, lambda: factorial2(oo))
raises(ValueError, lambda: factorial2(Rational(5, 2)))
raises(ValueError, lambda: factorial2(-4))
assert factorial2(n).is_integer is None
assert factorial2(tt - 1).is_integer
assert factorial2(tte - 1).is_integer
assert factorial2(tpe - 3).is_integer
assert factorial2(tto - 4).is_integer
assert factorial2(tto - 2).is_integer
assert factorial2(tf).is_integer is None
assert factorial2(tfe).is_integer is None
assert factorial2(tfo).is_integer is None
assert factorial2(ft).is_integer is None
assert factorial2(ff).is_integer is None
assert factorial2(fn).is_integer is None
assert factorial2(nt).is_integer is None
assert factorial2(nf).is_integer is None
assert factorial2(nn).is_integer is None
assert factorial2(n).is_positive is None
assert factorial2(tt - 1).is_positive is True
assert factorial2(tte - 1).is_positive is True
assert factorial2(tpe - 3).is_positive is True
assert factorial2(tpe - 1).is_positive is True
assert factorial2(tto - 2).is_positive is True
assert factorial2(tto - 1).is_positive is True
assert factorial2(tf).is_positive is None
assert factorial2(tfe).is_positive is None
assert factorial2(tfo).is_positive is None
assert factorial2(ft).is_positive is None
assert factorial2(ff).is_positive is None
assert factorial2(fn).is_positive is None
assert factorial2(nt).is_positive is None
assert factorial2(nf).is_positive is None
assert factorial2(nn).is_positive is None
assert factorial2(tt).is_even is None
assert factorial2(tt).is_odd is None
assert factorial2(tte).is_even is None
assert factorial2(tte).is_odd is None
assert factorial2(tte + 2).is_even is True
assert factorial2(tpe).is_even is True
assert factorial2(tpe).is_odd is False
assert factorial2(tto).is_odd is True
assert factorial2(tf).is_even is None
assert factorial2(tf).is_odd is None
assert factorial2(tfe).is_even is None
assert factorial2(tfe).is_odd is None
assert factorial2(tfo).is_even is False
assert factorial2(tfo).is_odd is None
assert factorial2(z).is_even is False
assert factorial2(z).is_odd is True
def test_factorial2_rewrite():
n = Symbol('n', integer=True)
assert factorial2(n).rewrite(gamma) == \
2**(n/2)*Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2)/sqrt(pi), Eq(Mod(n, 2), 1)))*gamma(n/2 + 1)
assert factorial2(2*n).rewrite(gamma) == 2**n*gamma(n + 1)
assert factorial2(2*n + 1).rewrite(gamma) == \
sqrt(2)*2**(n + S.Half)*gamma(n + Rational(3, 2))/sqrt(pi)
def test_binomial():
x = Symbol('x')
n = Symbol('n', integer=True)
nz = Symbol('nz', integer=True, nonzero=True)
k = Symbol('k', integer=True)
kp = Symbol('kp', integer=True, positive=True)
kn = Symbol('kn', integer=True, negative=True)
u = Symbol('u', negative=True)
v = Symbol('v', nonnegative=True)
p = Symbol('p', positive=True)
z = Symbol('z', zero=True)
nt = Symbol('nt', integer=False)
kt = Symbol('kt', integer=False)
a = Symbol('a', integer=True, nonnegative=True)
b = Symbol('b', integer=True, nonnegative=True)
assert binomial(0, 0) == 1
assert binomial(1, 1) == 1
assert binomial(10, 10) == 1
assert binomial(n, z) == 1
assert binomial(1, 2) == 0
assert binomial(-1, 2) == 1
assert binomial(1, -1) == 0
assert binomial(-1, 1) == -1
assert binomial(-1, -1) == 0
assert binomial(S.Half, S.Half) == 1
assert binomial(-10, 1) == -10
assert binomial(-10, 7) == -11440
assert binomial(n, -1) == 0 # holds for all integers (negative, zero, positive)
assert binomial(kp, -1) == 0
assert binomial(nz, 0) == 1
assert expand_func(binomial(n, 1)) == n
assert expand_func(binomial(n, 2)) == n*(n - 1)/2
assert expand_func(binomial(n, n - 2)) == n*(n - 1)/2
assert expand_func(binomial(n, n - 1)) == n
assert binomial(n, 3).func == binomial
assert binomial(n, 3).expand(func=True) == n**3/6 - n**2/2 + n/3
assert expand_func(binomial(n, 3)) == n*(n - 2)*(n - 1)/6
assert binomial(n, n).func == binomial # e.g. (-1, -1) == 0, (2, 2) == 1
assert binomial(n, n + 1).func == binomial # e.g. (-1, 0) == 1
assert binomial(kp, kp + 1) == 0
assert binomial(kn, kn) == 0 # issue #14529
assert binomial(n, u).func == binomial
assert binomial(kp, u).func == binomial
assert binomial(n, p).func == binomial
assert binomial(n, k).func == binomial
assert binomial(n, n + p).func == binomial
assert binomial(kp, kp + p).func == binomial
assert expand_func(binomial(n, n - 3)) == n*(n - 2)*(n - 1)/6
assert binomial(n, k).is_integer
assert binomial(nt, k).is_integer is None
assert binomial(x, nt).is_integer is False
assert binomial(gamma(25), 6) == 79232165267303928292058750056084441948572511312165380965440075720159859792344339983120618959044048198214221915637090855535036339620413440000
assert binomial(1324, 47) == 906266255662694632984994480774946083064699457235920708992926525848438478406790323869952
assert binomial(1735, 43) == 190910140420204130794758005450919715396159959034348676124678207874195064798202216379800
assert binomial(2512, 53) == 213894469313832631145798303740098720367984955243020898718979538096223399813295457822575338958939834177325304000
assert binomial(3383, 52) == 27922807788818096863529701501764372757272890613101645521813434902890007725667814813832027795881839396839287659777235
assert binomial(4321, 51) == 124595639629264868916081001263541480185227731958274383287107643816863897851139048158022599533438936036467601690983780576
assert binomial(a, b).is_nonnegative is True
assert binomial(-1, 2, evaluate=False).is_nonnegative is True
assert binomial(10, 5, evaluate=False).is_nonnegative is True
assert binomial(10, -3, evaluate=False).is_nonnegative is True
assert binomial(-10, -3, evaluate=False).is_nonnegative is True
assert binomial(-10, 2, evaluate=False).is_nonnegative is True
assert binomial(-10, 1, evaluate=False).is_nonnegative is False
assert binomial(-10, 7, evaluate=False).is_nonnegative is False
# issue #14625
for _ in (pi, -pi, nt, v, a):
assert binomial(_, _) == 1
assert binomial(_, _ - 1) == _
assert isinstance(binomial(u, u), binomial)
assert isinstance(binomial(u, u - 1), binomial)
assert isinstance(binomial(x, x), binomial)
assert isinstance(binomial(x, x - 1), binomial)
# issue #13980 and #13981
assert binomial(-7, -5) == 0
assert binomial(-23, -12) == 0
assert binomial(Rational(13, 2), -10) == 0
assert binomial(-49, -51) == 0
assert binomial(19, Rational(-7, 2)) == S(-68719476736)/(911337863661225*pi)
assert binomial(0, Rational(3, 2)) == S(-2)/(3*pi)
assert binomial(-3, Rational(-7, 2)) is zoo
assert binomial(kn, kt) is zoo
assert binomial(nt, kt).func == binomial
assert binomial(nt, Rational(15, 6)) == 8*gamma(nt + 1)/(15*sqrt(pi)*gamma(nt - Rational(3, 2)))
assert binomial(Rational(20, 3), Rational(-10, 8)) == gamma(Rational(23, 3))/(gamma(Rational(-1, 4))*gamma(Rational(107, 12)))
assert binomial(Rational(19, 2), Rational(-7, 2)) == Rational(-1615, 8388608)
assert binomial(Rational(-13, 5), Rational(-7, 8)) == gamma(Rational(-8, 5))/(gamma(Rational(-29, 40))*gamma(Rational(1, 8)))
assert binomial(Rational(-19, 8), Rational(-13, 5)) == gamma(Rational(-11, 8))/(gamma(Rational(-8, 5))*gamma(Rational(49, 40)))
# binomial for complexes
from sympy import I
assert binomial(I, Rational(-89, 8)) == gamma(1 + I)/(gamma(Rational(-81, 8))*gamma(Rational(97, 8) + I))
assert binomial(I, 2*I) == gamma(1 + I)/(gamma(1 - I)*gamma(1 + 2*I))
assert binomial(-7, I) is zoo
assert binomial(Rational(-7, 6), I) == gamma(Rational(-1, 6))/(gamma(Rational(-1, 6) - I)*gamma(1 + I))
assert binomial((1+2*I), (1+3*I)) == gamma(2 + 2*I)/(gamma(1 - I)*gamma(2 + 3*I))
assert binomial(I, 5) == Rational(1, 3) - I/S(12)
assert binomial((2*I + 3), 7) == -13*I/S(63)
assert isinstance(binomial(I, n), binomial)
assert expand_func(binomial(3, 2, evaluate=False)) == 3
assert expand_func(binomial(n, 0, evaluate=False)) == 1
assert expand_func(binomial(n, -2, evaluate=False)) == 0
assert expand_func(binomial(n, k)) == binomial(n, k)
def test_binomial_Mod():
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
r = 10**7 + 5 # composite modulo
# A few tests to get coverage
# Lucas Theorem
assert Mod(binomial(156675, 4433, evaluate=False), p) == Mod(binomial(156675, 4433), p)
# factorial Mod
assert Mod(binomial(1234, 432, evaluate=False), q) == Mod(binomial(1234, 432), q)
# binomial factorize
assert Mod(binomial(253, 113, evaluate=False), r) == Mod(binomial(253, 113), r)
@slow
def test_binomial_Mod_slow():
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
r, s = 10**7 + 5, 33333333 # composite modulo
n, k, m = symbols('n k m')
assert (binomial(n, k) % q).subs({n: s, k: p}) == Mod(binomial(s, p), q)
assert (binomial(n, k) % m).subs({n: 8, k: 5, m: 13}) == 4
assert (binomial(9, k) % 7).subs(k, 2) == 1
# Lucas Theorem
assert Mod(binomial(123456, 43253, evaluate=False), p) == Mod(binomial(123456, 43253), p)
assert Mod(binomial(-178911, 237, evaluate=False), p) == Mod(-binomial(178911 + 237 - 1, 237), p)
assert Mod(binomial(-178911, 238, evaluate=False), p) == Mod(binomial(178911 + 238 - 1, 238), p)
# factorial Mod
assert Mod(binomial(9734, 451, evaluate=False), q) == Mod(binomial(9734, 451), q)
assert Mod(binomial(-10733, 4459, evaluate=False), q) == Mod(binomial(-10733, 4459), q)
assert Mod(binomial(-15733, 4458, evaluate=False), q) == Mod(binomial(-15733, 4458), q)
# binomial factorize
assert Mod(binomial(753, 119, evaluate=False), r) == Mod(binomial(753, 119), r)
assert Mod(binomial(3781, 948, evaluate=False), s) == Mod(binomial(3781, 948), s)
assert Mod(binomial(25773, 1793, evaluate=False), s) == Mod(binomial(25773, 1793), s)
assert Mod(binomial(-753, 118, evaluate=False), r) == Mod(binomial(-753, 118), r)
assert Mod(binomial(-25773, 1793, evaluate=False), s) == Mod(binomial(-25773, 1793), s)
def test_binomial_diff():
n = Symbol('n', integer=True)
k = Symbol('k', integer=True)
assert binomial(n, k).diff(n) == \
(-polygamma(0, 1 + n - k) + polygamma(0, 1 + n))*binomial(n, k)
assert binomial(n**2, k**3).diff(n) == \
2*n*(-polygamma(
0, 1 + n**2 - k**3) + polygamma(0, 1 + n**2))*binomial(n**2, k**3)
assert binomial(n, k).diff(k) == \
(-polygamma(0, 1 + k) + polygamma(0, 1 + n - k))*binomial(n, k)
assert binomial(n**2, k**3).diff(k) == \
3*k**2*(-polygamma(
0, 1 + k**3) + polygamma(0, 1 + n**2 - k**3))*binomial(n**2, k**3)
raises(ArgumentIndexError, lambda: binomial(n, k).fdiff(3))
def test_binomial_rewrite():
n = Symbol('n', integer=True)
k = Symbol('k', integer=True)
x = Symbol('x')
assert binomial(n, k).rewrite(
factorial) == factorial(n)/(factorial(k)*factorial(n - k))
assert binomial(
n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
assert binomial(n, x).rewrite(ff) == binomial(n, x)
@XFAIL
def test_factorial_simplify_fail():
# simplify(factorial(x + 1).diff(x) - ((x + 1)*factorial(x)).diff(x))) == 0
from sympy.abc import x
assert simplify(x*polygamma(0, x + 1) - x*polygamma(0, x + 2) +
polygamma(0, x + 1) - polygamma(0, x + 2) + 1) == 0
def test_subfactorial():
assert all(subfactorial(i) == ans for i, ans in enumerate(
[1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496]))
assert subfactorial(oo) is oo
assert subfactorial(nan) is nan
assert unchanged(subfactorial, 2.2)
x = Symbol('x')
assert subfactorial(x).rewrite(uppergamma) == uppergamma(x + 1, -1)/S.Exp1
tt = Symbol('tt', integer=True, nonnegative=True)
tf = Symbol('tf', integer=True, nonnegative=False)
tn = Symbol('tf', integer=True)
ft = Symbol('ft', integer=False, nonnegative=True)
ff = Symbol('ff', integer=False, nonnegative=False)
fn = Symbol('ff', integer=False)
nt = Symbol('nt', nonnegative=True)
nf = Symbol('nf', nonnegative=False)
nn = Symbol('nf')
te = Symbol('te', even=True, nonnegative=True)
to = Symbol('to', odd=True, nonnegative=True)
assert subfactorial(tt).is_integer
assert subfactorial(tf).is_integer is None
assert subfactorial(tn).is_integer is None
assert subfactorial(ft).is_integer is None
assert subfactorial(ff).is_integer is None
assert subfactorial(fn).is_integer is None
assert subfactorial(nt).is_integer is None
assert subfactorial(nf).is_integer is None
assert subfactorial(nn).is_integer is None
assert subfactorial(tt).is_nonnegative
assert subfactorial(tf).is_nonnegative is None
assert subfactorial(tn).is_nonnegative is None
assert subfactorial(ft).is_nonnegative is None
assert subfactorial(ff).is_nonnegative is None
assert subfactorial(fn).is_nonnegative is None
assert subfactorial(nt).is_nonnegative is None
assert subfactorial(nf).is_nonnegative is None
assert subfactorial(nn).is_nonnegative is None
assert subfactorial(tt).is_even is None
assert subfactorial(tt).is_odd is None
assert subfactorial(te).is_odd is True
assert subfactorial(to).is_even is True
|
ae10e625bb5ade485fcb43792ef2add350b07cc42de3d7bb551c3c3851d4c6c3 | import string
from sympy import (
Symbol, symbols, Dummy, S, Sum, Rational, oo, pi, I, floor, limit,
expand_func, diff, EulerGamma, cancel, re, im, Product, carmichael,
TribonacciConstant)
from sympy.functions import (
bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan,
genocchi, partition, binomial, gamma, sqrt, cbrt, hyper, log, digamma,
trigamma, polygamma, factorial, sin, cos, cot, zeta)
from sympy.functions.combinatorial.numbers import _nT
from sympy.core.compatibility import range
from sympy.core.expr import unchanged
from sympy.core.numbers import GoldenRatio
from sympy.utilities.pytest import XFAIL, raises
x = Symbol('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]
assert carmichael.is_prime(2821) == False
assert carmichael.is_prime(2465) == False
assert carmichael.is_prime(1729) == False
assert carmichael.is_prime(1105) == False
assert carmichael.is_prime(561) == False
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))
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
raises(ValueError, lambda: bernoulli(-2))
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))
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]:
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(0, m) == 0
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
def test_harmonic_rewrite():
n = Symbol("n")
m = Symbol("m")
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 harmonic(n,m).rewrite(polygamma) == (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1)
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)
_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)))
@XFAIL
def test_harmonic_limit_fail():
n = Symbol("n")
m = Symbol("m")
# For m > 1:
assert limit(harmonic(n, m), n, oo) == zeta(m)
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
raises(ValueError, lambda: euler(-2))
raises(ValueError, lambda: euler(-3))
raises(ValueError, lambda: euler(2.3))
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 import Float
A = Float('-0.46237208575048694923364757452876131e8') # from Maple
B = euler(19, S.Pi.evalf(32))
assert abs((A - B)/A) < 1e-31 # expect low relative error
C = euler(19, S.Pi, evaluate=False).evalf(32)
assert abs((A - C)/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 = [1, -1, 0, 1, 0, -3, 0, 17]
for n, g in enumerate(genocchis):
assert genocchi(n + 1) == g
m = Symbol('m', integer=True)
n = Symbol('n', integer=True, positive=True)
assert unchanged(genocchi, m)
assert genocchi(2*n + 1) == 0
assert genocchi(n).rewrite(bernoulli) == (1 - 2 ** n) * bernoulli(n) * 2
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
raises(ValueError, lambda: genocchi(Rational(5, 4)))
raises(ValueError, lambda: genocchi(-2))
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, _multiset_histogram, _AOP_product)
from sympy.combinatorics.permutations import Permutation
from sympy.core.numbers import oo
from 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))
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'
|
76a686eddf777ec106604f07171e487ae3041b27f3b8419a79cd0c141c012b92 | from sympy import (
symbols, log, ln, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
LambertW, sqrt, Rational, expand_log, S, sign, conjugate, refine,
sin, cos, sinh, cosh, tanh, exp_polar, re, simplify,
AccumBounds, MatrixSymbol, Pow, gcd, Sum, Product)
from sympy.functions.elementary.exponential import match_real_imag
from sympy.abc import x, y, z
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.utilities.pytest import raises, XFAIL
def test_exp_values():
k = Symbol('k', integer=True)
assert exp(nan) is nan
assert exp(oo) is oo
assert exp(-oo) == 0
assert exp(0) == 1
assert exp(1) == E
assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1)
assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1)
assert exp(pi*I/2) == I
assert exp(pi*I) == -1
assert exp(pi*I*Rational(3, 2)) == -I
assert exp(2*pi*I) == 1
assert refine(exp(pi*I*2*k)) == 1
assert refine(exp(pi*I*2*(k + S.Half))) == -1
assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I
assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I
assert exp(log(x)) == x
assert exp(2*log(x)) == x**2
assert exp(pi*log(x)) == x**pi
assert exp(17*log(x) + E*log(y)) == x**17 * y**E
assert exp(x*log(x)) != x**x
assert exp(sin(x)*log(x)) != x
assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3
assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y))
assert exp(-oo, evaluate=False).is_finite is True
assert exp(oo, evaluate=False).is_finite is False
def test_exp_period():
assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4)
assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9))
assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7))
assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3)
assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0
assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1
assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5))
assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9))
n = Symbol('n', integer=True)
e = Symbol('e', even=True)
assert exp(e*I*pi) == 1
assert exp((e + 1)*I*pi) == -1
assert exp((1 + 4*n)*I*pi/2) == I
assert exp((-1 + 4*n)*I*pi/2) == -I
def test_exp_log():
x = Symbol("x", real=True)
assert log(exp(x)) == x
assert exp(log(x)) == x
assert log(x).inverse() == exp
assert exp(x).inverse() == log
y = Symbol("y", polar=True)
assert log(exp_polar(z)) == z
assert exp(log(y)) == y
def test_exp_expand():
e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x)
assert e.expand() == 2
assert exp(x + y) != exp(x)*exp(y)
assert exp(x + y).expand() == exp(x)*exp(y)
def test_exp__as_base_exp():
assert exp(x).as_base_exp() == (E, x)
assert exp(2*x).as_base_exp() == (E, 2*x)
assert exp(x*y).as_base_exp() == (E, x*y)
assert exp(-x).as_base_exp() == (E, -x)
# Pow( *expr.as_base_exp() ) == expr invariant should hold
assert E**x == exp(x)
assert E**(2*x) == exp(2*x)
assert E**(x*y) == exp(x*y)
assert exp(x).base is S.Exp1
assert exp(x).exp == x
def test_exp_infinity():
assert exp(I*y) != nan
assert refine(exp(I*oo)) is nan
assert refine(exp(-I*oo)) is nan
assert exp(y*I*oo) != nan
assert exp(zoo) is nan
def test_exp_subs():
x = Symbol('x')
e = (exp(3*log(x), evaluate=False)) # evaluates to x**3
assert e.subs(x**3, y**3) == e
assert e.subs(x**2, 5) == e
assert (x**3).subs(x**2, y) != y**Rational(3, 2)
assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2))
assert exp(x).subs(E, y) == y**x
x = symbols('x', real=True)
assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7)
assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7)
x = symbols('x', positive=True)
assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2)
# differentiate between E and exp
assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E))
assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3))
assert exp(3).subs(E, sin) == sin(3)
def test_exp_conjugate():
assert conjugate(exp(x)) == exp(conjugate(x))
def test_exp_rewrite():
from sympy.concrete.summations import Sum
assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x)
assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2))
assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2
assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2
assert exp(x*log(y)).rewrite(Pow) == y**x
assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y
n = Symbol('n', integer=True)
assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*Rational(2, 5)
assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
assert Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(Rational(3, 4) - sqrt(3)*I/4)
def test_exp_leading_term():
assert exp(x).as_leading_term(x) == 1
assert exp(2 + x).as_leading_term(x) == exp(2)
assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3)
# The following tests are commented, since now SymPy returns the
# original function when the leading term in the series expansion does
# not exist.
# raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x))
# raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x))
# raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x))
def test_exp_taylor_term():
x = symbols('x')
assert exp(x).taylor_term(1, x) == x
assert exp(x).taylor_term(3, x) == x**3/6
assert exp(x).taylor_term(4, x) == x**4/24
assert exp(x).taylor_term(-1, x) is S.Zero
def test_exp_MatrixSymbol():
A = MatrixSymbol("A", 2, 2)
assert exp(A).has(exp)
def test_exp_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: exp(x).fdiff(2))
def test_log_values():
assert log(nan) is nan
assert log(oo) is oo
assert log(-oo) is oo
assert log(zoo) is zoo
assert log(-zoo) is zoo
assert log(0) is zoo
assert log(1) == 0
assert log(-1) == I*pi
assert log(E) == 1
assert log(-E).expand() == 1 + I*pi
assert unchanged(log, pi)
assert log(-pi).expand() == log(pi) + I*pi
assert unchanged(log, 17)
assert log(-17) == log(17) + I*pi
assert log(I) == I*pi/2
assert log(-I) == -I*pi/2
assert log(17*I) == I*pi/2 + log(17)
assert log(-17*I).expand() == -I*pi/2 + log(17)
assert log(oo*I) is oo
assert log(-oo*I) is oo
assert log(0, 2) is zoo
assert log(0, 5) is zoo
assert exp(-log(3))**(-1) == 3
assert log(S.Half) == -log(2)
assert log(2*3).func is log
assert log(2*3**2).func is log
def test_match_real_imag():
x, y = symbols('x,y', real=True)
i = Symbol('i', imaginary=True)
assert match_real_imag(S.One) == (1, 0)
assert match_real_imag(I) == (0, 1)
assert match_real_imag(3 - 5*I) == (3, -5)
assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half)
assert match_real_imag(x + y*I) == (x, y)
assert match_real_imag(x*I + y*I) == (0, x + y)
assert match_real_imag((x + y)*I) == (0, x + y)
assert match_real_imag(Rational(-2, 3)*i*I) == (None, None)
assert match_real_imag(1 - 2*i) == (None, None)
assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None)
def test_log_exact():
# check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
for n in range(-23, 24):
if gcd(n, 24) != 1:
assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24
for n in range(-9, 10):
assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10
assert log(S.Half - I*sqrt(3)/2) == -I*pi/3
assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3)
assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4)
assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6)
assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5)
assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10)
assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8)
assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12)
assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3)
assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4
assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2
assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12)
assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8)
assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8
assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12)
assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5)
assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4
assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12)
assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3)
assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8
zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2)
assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2
assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo
# bail quickly if no obvious simplification is possible:
assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000)
# beware of non-real coefficients
assert unchanged(log, sqrt(2-sqrt(5))*(1 + I))
def test_log_base():
assert log(1, 2) == 0
assert log(2, 2) == 1
assert log(3, 2) == log(3)/log(2)
assert log(6, 2) == 1 + log(3)/log(2)
assert log(6, 3) == 1 + log(2)/log(3)
assert log(2**3, 2) == 3
assert log(3**3, 3) == 3
assert log(5, 1) is zoo
assert log(1, 1) is nan
assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10)
assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1
assert log(Rational(2, 3), Rational(2, 5)) == \
log(Rational(2, 3))/log(Rational(2, 5))
# issue 17148
assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3
def test_log_symbolic():
assert log(x, exp(1)) == log(x)
assert log(exp(x)) != x
assert log(x, exp(1)) == log(x)
assert log(x*y) != log(x) + log(y)
assert log(x/y).expand() != log(x) - log(y)
assert log(x/y).expand(force=True) == log(x) - log(y)
assert log(x**y).expand() != y*log(x)
assert log(x**y).expand(force=True) == y*log(x)
assert log(x, 2) == log(x)/log(2)
assert log(E, 2) == 1/log(2)
p, q = symbols('p,q', positive=True)
r = Symbol('r', real=True)
assert log(p**2) != 2*log(p)
assert log(p**2).expand() == 2*log(p)
assert log(x**2).expand() != 2*log(x)
assert log(p**q) != q*log(p)
assert log(exp(p)) == p
assert log(p*q) != log(p) + log(q)
assert log(p*q).expand() == log(p) + log(q)
assert log(-sqrt(3)) == log(sqrt(3)) + I*pi
assert log(-exp(p)) != p + I*pi
assert log(-exp(x)).expand() != x + I*pi
assert log(-exp(r)).expand() == r + I*pi
assert log(x**y) != y*log(x)
assert (log(x**-5)**-1).expand() != -1/log(x)/5
assert (log(p**-5)**-1).expand() == -1/log(p)/5
assert log(-x).func is log and log(-x).args[0] == -x
assert log(-p).func is log and log(-p).args[0] == -p
def test_log_exp():
assert log(exp(4*I*pi)) == 0 # exp evaluates
assert log(exp(-5*I*pi)) == I*pi # exp evaluates
assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4)
assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7)
assert log(exp(-5*I)) == -5*I + 2*I*pi
def test_exp_assumptions():
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
for e in exp, exp_polar:
assert e(x).is_real is None
assert e(x).is_imaginary is None
assert e(i).is_real is None
assert e(i).is_imaginary is None
assert e(r).is_real is True
assert e(r).is_imaginary is False
assert e(re(x)).is_extended_real is True
assert e(re(x)).is_imaginary is False
assert exp(0, evaluate=False).is_algebraic
a = Symbol('a', algebraic=True)
an = Symbol('an', algebraic=True, nonzero=True)
r = Symbol('r', rational=True)
rn = Symbol('rn', rational=True, nonzero=True)
assert exp(a).is_algebraic is None
assert exp(an).is_algebraic is False
assert exp(pi*r).is_algebraic is None
assert exp(pi*rn).is_algebraic is False
def test_exp_AccumBounds():
assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2)
def test_log_assumptions():
p = symbols('p', positive=True)
n = symbols('n', negative=True)
z = symbols('z', zero=True)
x = symbols('x', infinite=True, extended_positive=True)
assert log(z).is_positive is False
assert log(x).is_extended_positive is True
assert log(2) > 0
assert log(1, evaluate=False).is_zero
assert log(1 + z).is_zero
assert log(p).is_zero is None
assert log(n).is_zero is False
assert log(0.5).is_negative is True
assert log(exp(p) + 1).is_positive
assert log(1, evaluate=False).is_algebraic
assert log(42, evaluate=False).is_algebraic is False
assert log(1 + z).is_rational
def test_log_hashing():
assert x != log(log(x))
assert hash(x) != hash(log(log(x)))
assert log(x) != log(log(log(x)))
e = 1/log(log(x) + log(log(x)))
assert e.base.func is log
e = 1/log(log(x) + log(log(log(x))))
assert e.base.func is log
e = log(log(x))
assert e.func is log
assert not x.func is log
assert hash(log(log(x))) != hash(x)
assert e != x
def test_log_sign():
assert sign(log(2)) == 1
def test_log_expand_complex():
assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4
assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi
def test_log_apply_evalf():
value = (log(3)/log(2) - 1).evalf()
assert value.epsilon_eq(Float("0.58496250072115618145373"))
def test_log_expand():
w = Symbol("w", positive=True)
e = log(w**(log(5)/log(3)))
assert e.expand() == log(5)/log(3) * log(w)
x, y, z = symbols('x,y,z', positive=True)
assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z)
assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) +
2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2),
log((log(y) + log(z))*log(x)) + log(2)]
assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2)
assert log(x**log(x**2)).expand() == 2*log(x)**2
x, y = symbols('x,y')
assert log(x*y).expand(force=True) == log(x) + log(y)
assert log(x**y).expand(force=True) == y*log(x)
assert log(exp(x)).expand(force=True) == x
# there's generally no need to expand out logs since this requires
# factoring and if simplification is sought, it's cheaper to put
# logs together than it is to take them apart.
assert log(2*3**2).expand() != 2*log(3) + log(2)
@XFAIL
def test_log_expand_fail():
x, y, z = symbols('x,y,z', positive=True)
assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log(
x) + y*log(y + z) + z*log(x) + z*log(y + z)
def test_log_simplify():
x = Symbol("x", positive=True)
assert log(x**2).expand() == 2*log(x)
assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x)
z = Symbol('z')
assert log(sqrt(z)).expand() == log(z)/2
assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z)
assert log(z**(-1)).expand() != -log(z)
assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1)
def test_log_AccumBounds():
assert log(AccumBounds(1, E)) == AccumBounds(0, 1)
def test_lambertw():
k = Symbol('k')
assert LambertW(x, 0) == LambertW(x)
assert LambertW(x, 0, evaluate=False) != LambertW(x)
assert LambertW(0) == 0
assert LambertW(E) == 1
assert LambertW(-1/E) == -1
assert LambertW(-log(2)/2) == -log(2)
assert LambertW(oo) is oo
assert LambertW(0, 1) is -oo
assert LambertW(0, 42) is -oo
assert LambertW(-pi/2, -1) == -I*pi/2
assert LambertW(-1/E, -1) == -1
assert LambertW(-2*exp(-2), -1) == -2
assert LambertW(2*log(2)) == log(2)
assert LambertW(-pi/2) == I*pi/2
assert LambertW(exp(1 + E)) == E
assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2))
assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k))
assert LambertW(sqrt(2)).evalf(30).epsilon_eq(
Float("0.701338383413663009202120278965", 30), 1e-29)
assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110"))
assert LambertW(-1).is_real is False # issue 5215
assert LambertW(2, evaluate=False).is_real
p = Symbol('p', positive=True)
assert LambertW(p, evaluate=False).is_real
assert LambertW(p - 1, evaluate=False).is_real is None
assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False
assert LambertW(S.Half, -1, evaluate=False).is_real is False
assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real
assert LambertW(-10, -1, evaluate=False).is_real is False
assert LambertW(-2, 2, evaluate=False).is_real is False
assert LambertW(0, evaluate=False).is_algebraic
na = Symbol('na', nonzero=True, algebraic=True)
assert LambertW(na).is_algebraic is False
def test_issue_5673():
e = LambertW(-1)
assert e.is_comparable is False
assert e.is_positive is not True
e2 = 1 - 1/(1 - exp(-1000))
assert e2.is_positive is not True
e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2)))
assert e3.is_nonzero is not True
def test_log_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: log(x).fdiff(2))
def test_log_taylor_term():
x = symbols('x')
assert log(x).taylor_term(0, x) == x
assert log(x).taylor_term(1, x) == -x**2/2
assert log(x).taylor_term(4, x) == x**5/5
assert log(x).taylor_term(-1, x) is S.Zero
def test_exp_expand_NC():
A, B, C = symbols('A,B,C', commutative=False)
assert exp(A + B).expand() == exp(A + B)
assert exp(A + B + C).expand() == exp(A + B + C)
assert exp(x + y).expand() == exp(x)*exp(y)
assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z)
def test_as_numer_denom():
n = symbols('n', negative=True)
assert exp(x).as_numer_denom() == (exp(x), 1)
assert exp(-x).as_numer_denom() == (1, exp(x))
assert exp(-2*x).as_numer_denom() == (1, exp(2*x))
assert exp(-2).as_numer_denom() == (1, exp(2))
assert exp(n).as_numer_denom() == (1, exp(-n))
assert exp(-n).as_numer_denom() == (exp(-n), 1)
assert exp(-I*x).as_numer_denom() == (1, exp(I*x))
assert exp(-I*n).as_numer_denom() == (1, exp(I*n))
assert exp(-n).as_numer_denom() == (exp(-n), 1)
def test_polar():
x, y = symbols('x y', polar=True)
assert abs(exp_polar(I*4)) == 1
assert abs(exp_polar(0)) == 1
assert abs(exp_polar(2 + 3*I)) == exp(2)
assert exp_polar(I*10).n() == exp_polar(I*10)
assert log(exp_polar(z)) == z
assert log(x*y).expand() == log(x) + log(y)
assert log(x**z).expand() == z*log(x)
assert exp_polar(3).exp == 3
# Compare exp(1.0*pi*I).
assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0
assert exp_polar(0).is_rational is True # issue 8008
def test_exp_summation():
w = symbols("w")
m, n, i, j = symbols("m n i j")
expr = exp(Sum(w*i, (i, 0, n), (j, 0, m)))
assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m))
def test_log_product():
from sympy.abc import n, m
from sympy.concrete import Product
i, j = symbols('i,j', positive=True, integer=True)
x, y = symbols('x,y', positive=True)
z = symbols('z', real=True)
w = symbols('w')
expr = log(Product(x**i, (i, 1, n)))
assert simplify(expr) == expr
assert expr.expand() == Sum(i*log(x), (i, 1, n))
expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))
assert simplify(expr) == expr
assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
expr = log(Product(-2, (n, 0, 4)))
assert simplify(expr) == expr
assert expr.expand() == expr
assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))
expr = log(Product(exp(z*i), (i, 0, n)))
assert expr.expand() == Sum(z*i, (i, 0, n))
expr = log(Product(exp(w*i), (i, 0, n)))
assert expr.expand() == expr
assert expr.expand(force=True) == Sum(w*i, (i, 0, n))
expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m)))
assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m))
@XFAIL
def test_log_product_simplify_to_sum():
from sympy.abc import n, m
i, j = symbols('i,j', positive=True, integer=True)
x, y = symbols('x,y', positive=True)
from sympy.concrete import Product, Sum
assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n))
assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
def test_issue_8866():
assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10))
y = Symbol('y', positive=True)
l1 = log(exp(y), exp(10))
b1 = log(exp(y), exp(5))
l2 = log(exp(y), exp(10), evaluate=False)
b2 = log(exp(y), exp(5), evaluate=False)
assert simplify(log(l1, b1)) == simplify(log(l2, b2))
assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
def test_issue_9116():
n = Symbol('n', positive=True, integer=True)
assert ln(n).is_nonnegative is True
assert log(n).is_nonnegative is True
|
0b04127a9e886357b96f84f933a63b3d1e33aa560b548a9b890de2959daf38e8 | from sympy import AccumBounds, Symbol, floor, nan, oo, zoo, E, symbols, \
ceiling, pi, Rational, Float, I, sin, exp, log, factorial, frac, Eq, \
Le, Ge, Gt, Lt, Ne, sqrt, S
from sympy.core.expr import unchanged
from sympy.utilities.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', real=True, positive=True)
n_r = Symbol('n_r', real=True, 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
@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_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)
|
d1d37bbdb6a21cbb2336f9aecd7603180e291cbc0c71b017f0a11d8467b4e2b9 | from sympy import (symbols, Symbol, nan, oo, zoo, I, sinh, sin, pi, atan,
acos, Rational, sqrt, asin, acot, coth, E, S, tan, tanh, cos,
cosh, atan2, exp, log, asinh, acoth, atanh, O, cancel, Matrix, re, im,
Float, Pow, gcd, sec, csc, cot, diff, simplify, Heaviside, arg,
conjugate, series, FiniteSet, asec, acsc, Mul, sinc, jn,
AccumBounds, Interval, ImageSet, Lambda, besselj)
from sympy.core.compatibility import range
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.core.relational import Ne, Eq
from sympy.functions.elementary.piecewise import Piecewise
from sympy.sets.setexpr import SetExpr
from sympy.utilities.pytest import XFAIL, slow, raises
x, y, z = symbols('x y z')
r = Symbol('r', real=True)
k = Symbol('k', integer=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
np = Symbol('p', nonpositive=True)
nn = Symbol('n', nonnegative=True)
nz = Symbol('nz', nonzero=True)
ep = Symbol('ep', extended_positive=True)
en = Symbol('en', extended_negative=True)
enp = Symbol('ep', extended_nonpositive=True)
enn = Symbol('en', extended_nonnegative=True)
enz = Symbol('enz', extended_nonzero=True)
a = Symbol('a', algebraic=True)
na = Symbol('na', nonzero=True, algebraic=True)
def test_sin():
x, y = symbols('x y')
assert sin.nargs == FiniteSet(1)
assert sin(nan) is nan
assert sin(zoo) is nan
assert sin(oo) == AccumBounds(-1, 1)
assert sin(oo) - sin(oo) == AccumBounds(-2, 2)
assert sin(oo*I) == oo*I
assert sin(-oo*I) == -oo*I
assert 0*sin(oo) is S.Zero
assert 0/sin(oo) is S.Zero
assert 0 + sin(oo) == AccumBounds(-1, 1)
assert 5 + sin(oo) == AccumBounds(4, 6)
assert sin(0) == 0
assert sin(asin(x)) == x
assert sin(atan(x)) == x / sqrt(1 + x**2)
assert sin(acos(x)) == sqrt(1 - x**2)
assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x)
assert sin(acsc(x)) == 1 / x
assert sin(asec(x)) == sqrt(1 - 1 / x**2)
assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2)
assert sin(pi*I) == sinh(pi)*I
assert sin(-pi*I) == -sinh(pi)*I
assert sin(-2*I) == -sinh(2)*I
assert sin(pi) == 0
assert sin(-pi) == 0
assert sin(2*pi) == 0
assert sin(-2*pi) == 0
assert sin(-3*10**73*pi) == 0
assert sin(7*10**103*pi) == 0
assert sin(pi/2) == 1
assert sin(-pi/2) == -1
assert sin(pi*Rational(5, 2)) == 1
assert sin(pi*Rational(7, 2)) == -1
ne = symbols('ne', integer=True, even=False)
e = symbols('e', even=True)
assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half)
assert sin(pi*k/2).func == sin
assert sin(pi*e/2) == 0
assert sin(pi*k) == 0
assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298
assert sin(pi/3) == S.Half*sqrt(3)
assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)
assert sin(pi/4) == S.Half*sqrt(2)
assert sin(-pi/4) == Rational(-1, 2)*sqrt(2)
assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2)
assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
assert sin(pi/6) == S.Half
assert sin(-pi/6) == Rational(-1, 2)
assert sin(pi*Rational(7, 6)) == Rational(-1, 2)
assert sin(pi*Rational(-5, 6)) == Rational(-1, 2)
assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8)
assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8)
assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5))
assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5))
assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5))
assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5))
assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5))
assert sin(pi/8) == sqrt((2 - sqrt(2))/4)
assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4
assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4
assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4
assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4
assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4
assert sin(pi*Rational(104, 105)) == sin(pi/105)
assert sin(pi*Rational(106, 105)) == -sin(pi/105)
assert sin(pi*Rational(-104, 105)) == -sin(pi/105)
assert sin(pi*Rational(-106, 105)) == sin(pi/105)
assert sin(x*I) == sinh(x)*I
assert sin(k*pi) == 0
assert sin(17*k*pi) == 0
assert sin(k*pi*I) == sinh(k*pi)*I
assert sin(r).is_real is True
assert sin(0, evaluate=False).is_algebraic
assert sin(a).is_algebraic is None
assert sin(na).is_algebraic is False
q = Symbol('q', rational=True)
assert sin(pi*q).is_algebraic
qn = Symbol('qn', rational=True, nonzero=True)
assert sin(qn).is_rational is False
assert sin(q).is_rational is None # issue 8653
assert isinstance(sin( re(x) - im(y)), sin) is True
assert isinstance(sin(-re(x) + im(y)), sin) is False
assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)),
Interval(0, 1)))
for d in list(range(1, 22)) + [60, 85]:
for n in range(0, d*2 + 1):
x = n*pi/d
e = abs( float(sin(x)) - sin(float(x)) )
assert e < 1e-12
def test_sin_cos():
for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive...
for n in range(-2*d, d*2):
x = n*pi/d
assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d)
assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d)
assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d)
assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d)
def test_sin_series():
assert sin(x).series(x, 0, 9) == \
x - x**3/6 + x**5/120 - x**7/5040 + O(x**9)
def test_sin_rewrite():
assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2
assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2)
assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2)
assert sin(sinh(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n()
assert sin(cosh(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n()
assert sin(tanh(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n()
assert sin(coth(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n()
assert sin(sin(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n()
assert sin(cos(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n()
assert sin(tan(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n()
assert sin(cot(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n()
assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2
assert sin(x).rewrite(csc) == 1/csc(x)
assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False)
assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False)
assert sin(cos(x)).rewrite(Pow) == sin(cos(x))
def test_sin_expansion():
# Note: these formulas are not unique. The ones here come from the
# Chebyshev formulas.
assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y)
assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y)
assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y)
assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x)
assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x)
assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x)
assert sin(2).expand(trig=True) == 2*sin(1)*cos(1)
assert sin(3).expand(trig=True) == -4*sin(1)**3 + 3*sin(1)
def test_sin_AccumBounds():
assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1)
assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1)
assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4)))
assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3))
assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 6))) == AccumBounds(sin(S.Pi*Rational(5, 6)), sin(S.Pi*Rational(3, 4)))
def test_sin_fdiff():
assert sin(x).fdiff() == cos(x)
raises(ArgumentIndexError, lambda: sin(x).fdiff(2))
def test_trig_symmetry():
assert sin(-x) == -sin(x)
assert cos(-x) == cos(x)
assert tan(-x) == -tan(x)
assert cot(-x) == -cot(x)
assert sin(x + pi) == -sin(x)
assert sin(x + 2*pi) == sin(x)
assert sin(x + 3*pi) == -sin(x)
assert sin(x + 4*pi) == sin(x)
assert sin(x - 5*pi) == -sin(x)
assert cos(x + pi) == -cos(x)
assert cos(x + 2*pi) == cos(x)
assert cos(x + 3*pi) == -cos(x)
assert cos(x + 4*pi) == cos(x)
assert cos(x - 5*pi) == -cos(x)
assert tan(x + pi) == tan(x)
assert tan(x - 3*pi) == tan(x)
assert cot(x + pi) == cot(x)
assert cot(x - 3*pi) == cot(x)
assert sin(pi/2 - x) == cos(x)
assert sin(pi*Rational(3, 2) - x) == -cos(x)
assert sin(pi*Rational(5, 2) - x) == cos(x)
assert cos(pi/2 - x) == sin(x)
assert cos(pi*Rational(3, 2) - x) == -sin(x)
assert cos(pi*Rational(5, 2) - x) == sin(x)
assert tan(pi/2 - x) == cot(x)
assert tan(pi*Rational(3, 2) - x) == cot(x)
assert tan(pi*Rational(5, 2) - x) == cot(x)
assert cot(pi/2 - x) == tan(x)
assert cot(pi*Rational(3, 2) - x) == tan(x)
assert cot(pi*Rational(5, 2) - x) == tan(x)
assert sin(pi/2 + x) == cos(x)
assert cos(pi/2 + x) == -sin(x)
assert tan(pi/2 + x) == -cot(x)
assert cot(pi/2 + x) == -tan(x)
def test_cos():
x, y = symbols('x y')
assert cos.nargs == FiniteSet(1)
assert cos(nan) is nan
assert cos(oo) == AccumBounds(-1, 1)
assert cos(oo) - cos(oo) == AccumBounds(-2, 2)
assert cos(oo*I) is oo
assert cos(-oo*I) is oo
assert cos(zoo) is nan
assert cos(0) == 1
assert cos(acos(x)) == x
assert cos(atan(x)) == 1 / sqrt(1 + x**2)
assert cos(asin(x)) == sqrt(1 - x**2)
assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2)
assert cos(acsc(x)) == sqrt(1 - 1 / x**2)
assert cos(asec(x)) == 1 / x
assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2)
assert cos(pi*I) == cosh(pi)
assert cos(-pi*I) == cosh(pi)
assert cos(-2*I) == cosh(2)
assert cos(pi/2) == 0
assert cos(-pi/2) == 0
assert cos(pi/2) == 0
assert cos(-pi/2) == 0
assert cos((-3*10**73 + 1)*pi/2) == 0
assert cos((7*10**103 + 1)*pi/2) == 0
n = symbols('n', integer=True, even=False)
e = symbols('e', even=True)
assert cos(pi*n/2) == 0
assert cos(pi*e/2) == (-1)**(e/2)
assert cos(pi) == -1
assert cos(-pi) == -1
assert cos(2*pi) == 1
assert cos(5*pi) == -1
assert cos(8*pi) == 1
assert cos(pi/3) == S.Half
assert cos(pi*Rational(-2, 3)) == Rational(-1, 2)
assert cos(pi/4) == S.Half*sqrt(2)
assert cos(-pi/4) == S.Half*sqrt(2)
assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
assert cos(pi/6) == S.Half*sqrt(3)
assert cos(-pi/6) == S.Half*sqrt(3)
assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4
assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4
assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5))
assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5))
assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5))
assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5))
assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5))
assert cos(pi/8) == sqrt((2 + sqrt(2))/4)
assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4
assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4
assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4
assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4
assert cos(pi*Rational(104, 105)) == -cos(pi/105)
assert cos(pi*Rational(106, 105)) == -cos(pi/105)
assert cos(pi*Rational(-104, 105)) == -cos(pi/105)
assert cos(pi*Rational(-106, 105)) == -cos(pi/105)
assert cos(x*I) == cosh(x)
assert cos(k*pi*I) == cosh(k*pi)
assert cos(r).is_real is True
assert cos(0, evaluate=False).is_algebraic
assert cos(a).is_algebraic is None
assert cos(na).is_algebraic is False
q = Symbol('q', rational=True)
assert cos(pi*q).is_algebraic
assert cos(pi*Rational(2, 7)).is_algebraic
assert cos(k*pi) == (-1)**k
assert cos(2*k*pi) == 1
for d in list(range(1, 22)) + [60, 85]:
for n in range(0, 2*d + 1):
x = n*pi/d
e = abs( float(cos(x)) - cos(float(x)) )
assert e < 1e-12
def test_issue_6190():
c = Float('123456789012345678901234567890.25', '')
for cls in [sin, cos, tan, cot]:
assert cls(c*pi) == cls(pi/4)
assert cls(4.125*pi) == cls(pi/8)
assert cls(4.7*pi) == cls((4.7 % 2)*pi)
def test_cos_series():
assert cos(x).series(x, 0, 9) == \
1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9)
def test_cos_rewrite():
assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2
assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2)
assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2)
assert cos(sinh(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n()
assert cos(cosh(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n()
assert cos(tanh(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n()
assert cos(coth(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n()
assert cos(sin(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n()
assert cos(cos(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n()
assert cos(tan(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n()
assert cos(cot(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n()
assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2
assert cos(x).rewrite(sec) == 1/sec(x)
assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False)
assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False)
assert cos(sin(x)).rewrite(Pow) == cos(sin(x))
def test_cos_expansion():
assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y)
assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1
assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x)
assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1
assert cos(2).expand(trig=True) == 2*cos(1)**2 - 1
assert cos(3).expand(trig=True) == 4*cos(1)**3 - 3*cos(1)
def test_cos_AccumBounds():
assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1)
assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1)
assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4)))
assert cos(AccumBounds(S.Pi*Rational(5, 4), S.Pi*Rational(4, 3))) == AccumBounds(cos(S.Pi*Rational(5, 4)), cos(S.Pi*Rational(4, 3)))
assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4))
def test_cos_fdiff():
assert cos(x).fdiff() == -sin(x)
raises(ArgumentIndexError, lambda: cos(x).fdiff(2))
def test_tan():
assert tan(nan) is nan
assert tan(zoo) is nan
assert tan(oo) == AccumBounds(-oo, oo)
assert tan(oo) - tan(oo) == AccumBounds(-oo, oo)
assert tan.nargs == FiniteSet(1)
assert tan(oo*I) == I
assert tan(-oo*I) == -I
assert tan(0) == 0
assert tan(atan(x)) == x
assert tan(asin(x)) == x / sqrt(1 - x**2)
assert tan(acos(x)) == sqrt(1 - x**2) / x
assert tan(acot(x)) == 1 / x
assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x
assert tan(atan2(y, x)) == y/x
assert tan(pi*I) == tanh(pi)*I
assert tan(-pi*I) == -tanh(pi)*I
assert tan(-2*I) == -tanh(2)*I
assert tan(pi) == 0
assert tan(-pi) == 0
assert tan(2*pi) == 0
assert tan(-2*pi) == 0
assert tan(-3*10**73*pi) == 0
assert tan(pi/2) is zoo
assert tan(pi*Rational(3, 2)) is zoo
assert tan(pi/3) == sqrt(3)
assert tan(pi*Rational(-2, 3)) == sqrt(3)
assert tan(pi/4) is S.One
assert tan(-pi/4) is S.NegativeOne
assert tan(pi*Rational(17, 4)) is S.One
assert tan(pi*Rational(-3, 4)) is S.One
assert tan(pi/5) == sqrt(5 - 2*sqrt(5))
assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5))
assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5))
assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5))
assert tan(pi/6) == 1/sqrt(3)
assert tan(-pi/6) == -1/sqrt(3)
assert tan(pi*Rational(7, 6)) == 1/sqrt(3)
assert tan(pi*Rational(-5, 6)) == 1/sqrt(3)
assert tan(pi/8) == -1 + sqrt(2)
assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959
assert tan(pi*Rational(5, 8)) == -1 - sqrt(2)
assert tan(pi*Rational(7, 8)) == 1 - sqrt(2)
assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5)
assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5)
assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5)
assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5)
assert tan(pi/12) == -sqrt(3) + 2
assert tan(pi*Rational(5, 12)) == sqrt(3) + 2
assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2
assert tan(pi*Rational(11, 12)) == sqrt(3) - 2
assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6)
assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6)
assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6)
assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6)
assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6)
assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6)
assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6)
assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6)
assert tan(x*I) == tanh(x)*I
assert tan(k*pi) == 0
assert tan(17*k*pi) == 0
assert tan(k*pi*I) == tanh(k*pi)*I
assert tan(r).is_real is None
assert tan(r).is_extended_real is True
assert tan(0, evaluate=False).is_algebraic
assert tan(a).is_algebraic is None
assert tan(na).is_algebraic is False
assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7))
assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7))
assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7))
assert tan(pi*Rational(15, 14)) == tan(pi/14)
assert tan(pi*Rational(-15, 14)) == -tan(pi/14)
assert tan(r).is_finite is None
assert tan(I*r).is_finite is True
def test_tan_series():
assert tan(x).series(x, 0, 9) == \
x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9)
def test_tan_rewrite():
neg_exp, pos_exp = exp(-x*I), exp(x*I)
assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp)
assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x)
assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x)
assert tan(x).rewrite(cot) == 1/cot(x)
assert tan(sinh(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n()
assert tan(cosh(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n()
assert tan(tanh(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n()
assert tan(coth(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n()
assert tan(sin(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n()
assert tan(cos(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n()
assert tan(tan(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n()
assert tan(cot(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n()
assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I)
assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow)
assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow)
assert tan(pi/19).rewrite(pow) == tan(pi/19)
assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19))
assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False)
assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x)
assert tan(sin(x)).rewrite(Pow) == tan(sin(x))
assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 +
Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4)
def test_tan_subs():
assert tan(x).subs(tan(x), y) == y
assert tan(x).subs(x, y) == tan(y)
assert tan(x).subs(x, S.Pi/2) is zoo
assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo
def test_tan_expansion():
assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand()
assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand()
assert tan(x + y + z).expand(trig=True) == (
(tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/
(1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand()
assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7
assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37
assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1
def test_tan_AccumBounds():
assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo)
assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3))
def test_tan_fdiff():
assert tan(x).fdiff() == tan(x)**2 + 1
raises(ArgumentIndexError, lambda: tan(x).fdiff(2))
def test_cot():
assert cot(nan) is nan
assert cot.nargs == FiniteSet(1)
assert cot(oo*I) == -I
assert cot(-oo*I) == I
assert cot(zoo) is nan
assert cot(0) is zoo
assert cot(2*pi) is zoo
assert cot(acot(x)) == x
assert cot(atan(x)) == 1 / x
assert cot(asin(x)) == sqrt(1 - x**2) / x
assert cot(acos(x)) == x / sqrt(1 - x**2)
assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x
assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
assert cot(atan2(y, x)) == x/y
assert cot(pi*I) == -coth(pi)*I
assert cot(-pi*I) == coth(pi)*I
assert cot(-2*I) == coth(2)*I
assert cot(pi) == cot(2*pi) == cot(3*pi)
assert cot(-pi) == cot(-2*pi) == cot(-3*pi)
assert cot(pi/2) == 0
assert cot(-pi/2) == 0
assert cot(pi*Rational(5, 2)) == 0
assert cot(pi*Rational(7, 2)) == 0
assert cot(pi/3) == 1/sqrt(3)
assert cot(pi*Rational(-2, 3)) == 1/sqrt(3)
assert cot(pi/4) is S.One
assert cot(-pi/4) is S.NegativeOne
assert cot(pi*Rational(17, 4)) is S.One
assert cot(pi*Rational(-3, 4)) is S.One
assert cot(pi/6) == sqrt(3)
assert cot(-pi/6) == -sqrt(3)
assert cot(pi*Rational(7, 6)) == sqrt(3)
assert cot(pi*Rational(-5, 6)) == sqrt(3)
assert cot(pi/8) == 1 + sqrt(2)
assert cot(pi*Rational(3, 8)) == -1 + sqrt(2)
assert cot(pi*Rational(5, 8)) == 1 - sqrt(2)
assert cot(pi*Rational(7, 8)) == -1 - sqrt(2)
assert cot(pi/12) == sqrt(3) + 2
assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2
assert cot(pi*Rational(7, 12)) == sqrt(3) - 2
assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2
assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6)
assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6)
assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6)
assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6)
assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6)
assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6)
assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6)
assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6)
assert cot(x*I) == -coth(x)*I
assert cot(k*pi*I) == -coth(k*pi)*I
assert cot(r).is_real is None
assert cot(r).is_extended_real is True
assert cot(a).is_algebraic is None
assert cot(na).is_algebraic is False
assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7))
assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7))
assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7))
assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34))
assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34))
assert cot(x).is_finite is None
assert cot(r).is_finite is None
i = Symbol('i', imaginary=True)
assert cot(i).is_finite is True
assert cot(x).subs(x, 3*pi) is zoo
def test_tan_cot_sin_cos_evalf():
assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14
assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14
@XFAIL
def test_tan_cot_sin_cos_ratsimp():
assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp()
assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp()
def test_cot_series():
assert cot(x).series(x, 0, 9) == \
1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9)
# issue 6210
assert cot(x**4 + x**5).series(x, 0, 1) == \
x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x)
assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3)
assert cot(x).taylor_term(0, x) == 1/x
assert cot(x).taylor_term(2, x) is S.Zero
assert cot(x).taylor_term(3, x) == -x**3/45
def test_cot_rewrite():
neg_exp, pos_exp = exp(-x*I), exp(x*I)
assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp)
assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2))
assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False)
assert cot(x).rewrite(tan) == 1/tan(x)
assert cot(sinh(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, sinh(3)).n()
assert cot(cosh(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, cosh(3)).n()
assert cot(tanh(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, tanh(3)).n()
assert cot(coth(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, coth(3)).n()
assert cot(sin(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, sin(3)).n()
assert cot(tan(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, tan(3)).n()
assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I)
assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == (cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp()
assert cot(pi*Rational(4, 17)).rewrite(pow) == (cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow)
assert cot(pi/19).rewrite(pow) == cot(pi/19)
assert cot(pi/19).rewrite(sqrt) == cot(pi/19)
assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x)
assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False)
assert cot(sin(x)).rewrite(Pow) == cot(sin(x))
assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == (Rational(-1, 4) + sqrt(5)/4)/\
sqrt(sqrt(5)/8 + Rational(5, 8))
def test_cot_subs():
assert cot(x).subs(cot(x), y) == y
assert cot(x).subs(x, y) == cot(y)
assert cot(x).subs(x, 0) is zoo
assert cot(x).subs(x, S.Pi) is zoo
def test_cot_expansion():
assert cot(x + y).expand(trig=True) == ((cot(x)*cot(y) - 1)/(cot(x) + cot(y))).expand()
assert cot(x - y).expand(trig=True) == (-(cot(x)*cot(y) + 1)/(cot(x) - cot(y))).expand()
assert cot(x + y + z).expand(trig=True) == (
(cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/
(-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z))).expand()
assert cot(3*x).expand(trig=True) == ((cot(x)**3 - 3*cot(x))/(3*cot(x)**2 - 1)).expand()
assert 0 == cot(2*x).expand(trig=True).rewrite(cot).subs([(cot(x), Rational(1, 3))])*3 + 4
assert 0 == cot(3*x).expand(trig=True).rewrite(cot).subs([(cot(x), Rational(1, 5))])*55 - 37
assert 0 == cot(4*x - pi/4).expand(trig=True).rewrite(cot).subs([(cot(x), Rational(1, 7))])*863 + 191
def test_cot_AccumBounds():
assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo)
assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6))
def test_cot_fdiff():
assert cot(x).fdiff() == -cot(x)**2 - 1
raises(ArgumentIndexError, lambda: cot(x).fdiff(2))
def test_sinc():
assert isinstance(sinc(x), sinc)
s = Symbol('s', zero=True)
assert sinc(s) is S.One
assert sinc(S.Infinity) is S.Zero
assert sinc(S.NegativeInfinity) is S.Zero
assert sinc(S.NaN) is S.NaN
assert sinc(S.ComplexInfinity) is S.NaN
n = Symbol('n', integer=True, nonzero=True)
assert sinc(n*pi) is S.Zero
assert sinc(-n*pi) is S.Zero
assert sinc(pi/2) == 2 / pi
assert sinc(-pi/2) == 2 / pi
assert sinc(pi*Rational(5, 2)) == 2 / (5*pi)
assert sinc(pi*Rational(7, 2)) == -2 / (7*pi)
assert sinc(-x) == sinc(x)
assert sinc(x).diff() == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True))
assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x))
assert sinc(x).diff().subs(x, 0) is S.Zero
assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6)
assert sinc(x).rewrite(jn) == jn(0, x)
assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True))
def test_asin():
assert asin(nan) is nan
assert asin.nargs == FiniteSet(1)
assert asin(oo) == -I*oo
assert asin(-oo) == I*oo
assert asin(zoo) is zoo
# Note: asin(-x) = - asin(x)
assert asin(0) == 0
assert asin(1) == pi/2
assert asin(-1) == -pi/2
assert asin(sqrt(3)/2) == pi/3
assert asin(-sqrt(3)/2) == -pi/3
assert asin(sqrt(2)/2) == pi/4
assert asin(-sqrt(2)/2) == -pi/4
assert asin(sqrt((5 - sqrt(5))/8)) == pi/5
assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5
assert asin(S.Half) == pi/6
assert asin(Rational(-1, 2)) == -pi/6
assert asin((sqrt(2 - sqrt(2)))/2) == pi/8
assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8
assert asin((sqrt(5) - 1)/4) == pi/10
assert asin(-(sqrt(5) - 1)/4) == -pi/10
assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12
assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12
# check round-trip for exact values:
for d in [5, 6, 8, 10, 12]:
for n in range(-(d//2), d//2 + 1):
if gcd(n, d) == 1:
assert asin(sin(n*pi/d)) == n*pi/d
assert asin(x).diff(x) == 1/sqrt(1 - x**2)
assert asin(0.2).is_real is True
assert asin(-2).is_real is False
assert asin(r).is_real is None
assert asin(-2*I) == -I*asinh(2)
assert asin(Rational(1, 7), evaluate=False).is_positive is True
assert asin(Rational(-1, 7), evaluate=False).is_positive is False
assert asin(p).is_positive is None
assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi
assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi
assert unchanged(asin, cos(x))
def test_asin_series():
assert asin(x).series(x, 0, 9) == \
x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9)
t5 = asin(x).taylor_term(5, x)
assert t5 == 3*x**5/40
assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112
def test_asin_rewrite():
assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2))
assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2)))
assert asin(x).rewrite(acos) == S.Pi/2 - acos(x)
assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x)
assert asin(x).rewrite(asec) == -asec(1/x) + pi/2
assert asin(x).rewrite(acsc) == acsc(1/x)
def test_asin_fdiff():
assert asin(x).fdiff() == 1/sqrt(1 - x**2)
raises(ArgumentIndexError, lambda: asin(x).fdiff(2))
def test_acos():
assert acos(nan) is nan
assert acos(zoo) is zoo
assert acos.nargs == FiniteSet(1)
assert acos(oo) == I*oo
assert acos(-oo) == -I*oo
# Note: acos(-x) = pi - acos(x)
assert acos(0) == pi/2
assert acos(S.Half) == pi/3
assert acos(Rational(-1, 2)) == pi*Rational(2, 3)
assert acos(1) == 0
assert acos(-1) == pi
assert acos(sqrt(2)/2) == pi/4
assert acos(-sqrt(2)/2) == pi*Rational(3, 4)
# check round-trip for exact values:
for d in [5, 6, 8, 10, 12]:
for num in range(d):
if gcd(num, d) == 1:
assert acos(cos(num*pi/d)) == num*pi/d
assert acos(2*I) == pi/2 - asin(2*I)
assert acos(x).diff(x) == -1/sqrt(1 - x**2)
assert acos(0.2).is_real is True
assert acos(-2).is_real is False
assert acos(r).is_real is None
assert acos(Rational(1, 7), evaluate=False).is_positive is True
assert acos(Rational(-1, 7), evaluate=False).is_positive is True
assert acos(Rational(3, 2), evaluate=False).is_positive is False
assert acos(p).is_positive is None
assert acos(2 + p).conjugate() != acos(10 + p)
assert acos(-3 + n).conjugate() != acos(-3 + n)
assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3))
assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3))
assert acos(p + n*I).conjugate() == acos(p - n*I)
assert acos(z).conjugate() != acos(conjugate(z))
def test_acos_series():
assert acos(x).series(x, 0, 8) == \
pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8)
assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8)
t5 = acos(x).taylor_term(5, x)
assert t5 == -3*x**5/40
assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112
assert acos(x).taylor_term(0, x) == pi/2
assert acos(x).taylor_term(2, x) is S.Zero
def test_acos_rewrite():
assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2))
assert acos(x).rewrite(atan) == \
atan(sqrt(1 - x**2)/x) + (pi/2)*(1 - x*sqrt(1/x**2))
assert acos(0).rewrite(atan) == S.Pi/2
assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log)
assert acos(x).rewrite(asin) == S.Pi/2 - asin(x)
assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2
assert acos(x).rewrite(asec) == asec(1/x)
assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2
def test_acos_fdiff():
assert acos(x).fdiff() == -1/sqrt(1 - x**2)
raises(ArgumentIndexError, lambda: acos(x).fdiff(2))
def test_atan():
assert atan(nan) is nan
assert atan.nargs == FiniteSet(1)
assert atan(oo) == pi/2
assert atan(-oo) == -pi/2
assert atan(zoo) == AccumBounds(-pi/2, pi/2)
assert atan(0) == 0
assert atan(1) == pi/4
assert atan(sqrt(3)) == pi/3
assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8)
assert atan(sqrt((5 - 2 * sqrt(5)))) == pi/5
assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10
assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10)
assert atan(-2 + sqrt(3)) == -pi/12
assert atan(2 + sqrt(3)) == pi*Rational(5, 12)
assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12)
# check round-trip for exact values:
for d in [5, 6, 8, 10, 12]:
for num in range(-(d//2), d//2 + 1):
if gcd(num, d) == 1:
assert atan(tan(num*pi/d)) == num*pi/d
assert atan(oo) == pi/2
assert atan(x).diff(x) == 1/(1 + x**2)
assert atan(r).is_real is True
assert atan(-2*I) == -I*atanh(2)
assert unchanged(atan, cot(x))
assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2
assert acot(Rational(1, 4)).is_rational is False
for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz):
if s.is_real or s.is_extended_real is None:
assert s.is_nonzero is atan(s).is_nonzero
assert s.is_positive is atan(s).is_positive
assert s.is_negative is atan(s).is_negative
assert s.is_nonpositive is atan(s).is_nonpositive
assert s.is_nonnegative is atan(s).is_nonnegative
else:
assert s.is_extended_nonzero is atan(s).is_nonzero
assert s.is_extended_positive is atan(s).is_positive
assert s.is_extended_negative is atan(s).is_negative
assert s.is_extended_nonpositive is atan(s).is_nonpositive
assert s.is_extended_nonnegative is atan(s).is_nonnegative
assert s.is_extended_nonzero is atan(s).is_extended_nonzero
assert s.is_extended_positive is atan(s).is_extended_positive
assert s.is_extended_negative is atan(s).is_extended_negative
assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive
assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative
def test_atan_rewrite():
assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2
assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x
assert atan(x).rewrite(acot) == acot(1/x)
assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x
assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I})
assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I})
def test_atan_fdiff():
assert atan(x).fdiff() == 1/(x**2 + 1)
raises(ArgumentIndexError, lambda: atan(x).fdiff(2))
def test_atan2():
assert atan2.nargs == FiniteSet(2)
assert atan2(0, 0) is S.NaN
assert atan2(0, 1) == 0
assert atan2(1, 1) == pi/4
assert atan2(1, 0) == pi/2
assert atan2(1, -1) == pi*Rational(3, 4)
assert atan2(0, -1) == pi
assert atan2(-1, -1) == pi*Rational(-3, 4)
assert atan2(-1, 0) == -pi/2
assert atan2(-1, 1) == -pi/4
i = symbols('i', imaginary=True)
r = symbols('r', real=True)
eq = atan2(r, i)
ans = -I*log((i + I*r)/sqrt(i**2 + r**2))
reps = ((r, 2), (i, I))
assert eq.subs(reps) == ans.subs(reps)
x = Symbol('x', negative=True)
y = Symbol('y', negative=True)
assert atan2(y, x) == atan(y/x) - pi
y = Symbol('y', nonnegative=True)
assert atan2(y, x) == atan(y/x) + pi
y = Symbol('y')
assert atan2(y, x) == atan2(y, x, evaluate=False)
u = Symbol("u", positive=True)
assert atan2(0, u) == 0
u = Symbol("u", negative=True)
assert atan2(0, u) == pi
assert atan2(y, oo) == 0
assert atan2(y, -oo)== 2*pi*Heaviside(re(y)) - pi
assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
assert atan2(0, 0) is S.NaN
ex = atan2(y, x) - arg(x + I*y)
assert ex.subs({x:2, y:3}).rewrite(arg) == 0
assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5)
assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I)
assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2))
i = symbols('i', imaginary=True)
r = symbols('r', real=True)
e = atan2(i, r)
rewrite = e.rewrite(arg)
reps = {i: I, r: -2}
assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2))
assert (e - rewrite).subs(reps).equals(0)
assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0),
(0, Ne(x, 0)),
(nan, True))
assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True))
assert atan2(0, i),rewrite(atan) == 0
assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True))
assert atan2(y, x).rewrite(atan) == Piecewise(
(2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)),
(pi, re(x) < 0),
(0, (re(x) > 0) | Ne(im(x), 0)),
(nan, True))
assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y))
assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
assert diff(atan2(y, x), y) == x/(x**2 + y**2)
assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2)
assert str(atan2(1, 2).evalf(5)) == '0.46365'
raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3))
def test_issue_17461():
class A(Symbol):
is_extended_real = True
def _eval_evalf(self, prec):
return Float(5.0)
x = A('X')
y = A('Y')
assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10
def test_acot():
assert acot(nan) is nan
assert acot.nargs == FiniteSet(1)
assert acot(-oo) == 0
assert acot(oo) == 0
assert acot(zoo) == 0
assert acot(1) == pi/4
assert acot(0) == pi/2
assert acot(sqrt(3)/3) == pi/3
assert acot(1/sqrt(3)) == pi/3
assert acot(-1/sqrt(3)) == -pi/3
assert acot(x).diff(x) == -1/(1 + x**2)
assert acot(r).is_extended_real is True
assert acot(I*pi) == -I*acoth(pi)
assert acot(-2*I) == I*acoth(2)
assert acot(x).is_positive is None
assert acot(n).is_positive is False
assert acot(p).is_positive is True
assert acot(I).is_positive is False
assert acot(Rational(1, 4)).is_rational is False
assert unchanged(acot, cot(x))
assert unchanged(acot, tan(x))
assert acot(cot(Rational(1, 4))) == Rational(1, 4)
assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2
def test_acot_rewrite():
assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2
assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2))
assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1))
assert acot(x).rewrite(atan) == atan(1/x)
assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2))
assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2))
assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5})
assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5})
def test_acot_fdiff():
assert acot(x).fdiff() == -1/(x**2 + 1)
raises(ArgumentIndexError, lambda: acot(x).fdiff(2))
def test_attributes():
assert sin(x).args == (x,)
def test_sincos_rewrite():
assert sin(pi/2 - x) == cos(x)
assert sin(pi - x) == sin(x)
assert cos(pi/2 - x) == sin(x)
assert cos(pi - x) == -cos(x)
def _check_even_rewrite(func, arg):
"""Checks that the expr has been rewritten using f(-x) -> f(x)
arg : -x
"""
return func(arg).args[0] == -arg
def _check_odd_rewrite(func, arg):
"""Checks that the expr has been rewritten using f(-x) -> -f(x)
arg : -x
"""
return func(arg).func.is_Mul
def _check_no_rewrite(func, arg):
"""Checks that the expr is not rewritten"""
return func(arg).args[0] == arg
def test_evenodd_rewrite():
a = cos(2) # negative
b = sin(1) # positive
even = [cos]
odd = [sin, tan, cot, asin, atan, acot]
with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y]
for func in even:
for expr in with_minus:
assert _check_even_rewrite(func, expr)
assert _check_no_rewrite(func, a*b)
assert func(
x - y) == func(y - x) # it doesn't matter which form is canonical
for func in odd:
for expr in with_minus:
assert _check_odd_rewrite(func, expr)
assert _check_no_rewrite(func, a*b)
assert func(
x - y) == -func(y - x) # it doesn't matter which form is canonical
def test_issue_4547():
assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2)
assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2)
assert tan(x).rewrite(cot) == 1/cot(x)
assert cot(x).fdiff() == -1 - cot(x)**2
def test_as_leading_term_issue_5272():
assert sin(x).as_leading_term(x) == x
assert cos(x).as_leading_term(x) == 1
assert tan(x).as_leading_term(x) == x
assert cot(x).as_leading_term(x) == 1/x
assert asin(x).as_leading_term(x) == x
assert acos(x).as_leading_term(x) == x
assert atan(x).as_leading_term(x) == x
assert acot(x).as_leading_term(x) == x
def test_leading_terms():
for func in [sin, cos, tan, cot, asin, acos, atan, acot]:
for arg in (1/x, S.Half):
eq = func(arg)
assert eq.as_leading_term(x) == eq
def test_atan2_expansion():
assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0
assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5)
+ atan2(0, x) - atan(0)) == O(y**5)
assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4)
+ atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1))
assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3)
+ atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1))
assert Matrix([atan2(y, x)]).jacobian([y, x]) == \
Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]])
def test_aseries():
def t(n, v, d, e):
assert abs(
n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e
t(atan, 0.1, '+', 1e-5)
t(atan, -0.1, '-', 1e-5)
t(acot, 0.1, '+', 1e-5)
t(acot, -0.1, '-', 1e-5)
def test_issue_4420():
i = Symbol('i', integer=True)
e = Symbol('e', even=True)
o = Symbol('o', odd=True)
# unknown parity for variable
assert cos(4*i*pi) == 1
assert sin(4*i*pi) == 0
assert tan(4*i*pi) == 0
assert cot(4*i*pi) is zoo
assert cos(3*i*pi) == cos(pi*i) # +/-1
assert sin(3*i*pi) == 0
assert tan(3*i*pi) == 0
assert cot(3*i*pi) is zoo
assert cos(4.0*i*pi) == 1
assert sin(4.0*i*pi) == 0
assert tan(4.0*i*pi) == 0
assert cot(4.0*i*pi) is zoo
assert cos(3.0*i*pi) == cos(pi*i) # +/-1
assert sin(3.0*i*pi) == 0
assert tan(3.0*i*pi) == 0
assert cot(3.0*i*pi) is zoo
assert cos(4.5*i*pi) == cos(0.5*pi*i)
assert sin(4.5*i*pi) == sin(0.5*pi*i)
assert tan(4.5*i*pi) == tan(0.5*pi*i)
assert cot(4.5*i*pi) == cot(0.5*pi*i)
# parity of variable is known
assert cos(4*e*pi) == 1
assert sin(4*e*pi) == 0
assert tan(4*e*pi) == 0
assert cot(4*e*pi) is zoo
assert cos(3*e*pi) == 1
assert sin(3*e*pi) == 0
assert tan(3*e*pi) == 0
assert cot(3*e*pi) is zoo
assert cos(4.0*e*pi) == 1
assert sin(4.0*e*pi) == 0
assert tan(4.0*e*pi) == 0
assert cot(4.0*e*pi) is zoo
assert cos(3.0*e*pi) == 1
assert sin(3.0*e*pi) == 0
assert tan(3.0*e*pi) == 0
assert cot(3.0*e*pi) is zoo
assert cos(4.5*e*pi) == cos(0.5*pi*e)
assert sin(4.5*e*pi) == sin(0.5*pi*e)
assert tan(4.5*e*pi) == tan(0.5*pi*e)
assert cot(4.5*e*pi) == cot(0.5*pi*e)
assert cos(4*o*pi) == 1
assert sin(4*o*pi) == 0
assert tan(4*o*pi) == 0
assert cot(4*o*pi) is zoo
assert cos(3*o*pi) == -1
assert sin(3*o*pi) == 0
assert tan(3*o*pi) == 0
assert cot(3*o*pi) is zoo
assert cos(4.0*o*pi) == 1
assert sin(4.0*o*pi) == 0
assert tan(4.0*o*pi) == 0
assert cot(4.0*o*pi) is zoo
assert cos(3.0*o*pi) == -1
assert sin(3.0*o*pi) == 0
assert tan(3.0*o*pi) == 0
assert cot(3.0*o*pi) is zoo
assert cos(4.5*o*pi) == cos(0.5*pi*o)
assert sin(4.5*o*pi) == sin(0.5*pi*o)
assert tan(4.5*o*pi) == tan(0.5*pi*o)
assert cot(4.5*o*pi) == cot(0.5*pi*o)
# x could be imaginary
assert cos(4*x*pi) == cos(4*pi*x)
assert sin(4*x*pi) == sin(4*pi*x)
assert tan(4*x*pi) == tan(4*pi*x)
assert cot(4*x*pi) == cot(4*pi*x)
assert cos(3*x*pi) == cos(3*pi*x)
assert sin(3*x*pi) == sin(3*pi*x)
assert tan(3*x*pi) == tan(3*pi*x)
assert cot(3*x*pi) == cot(3*pi*x)
assert cos(4.0*x*pi) == cos(4.0*pi*x)
assert sin(4.0*x*pi) == sin(4.0*pi*x)
assert tan(4.0*x*pi) == tan(4.0*pi*x)
assert cot(4.0*x*pi) == cot(4.0*pi*x)
assert cos(3.0*x*pi) == cos(3.0*pi*x)
assert sin(3.0*x*pi) == sin(3.0*pi*x)
assert tan(3.0*x*pi) == tan(3.0*pi*x)
assert cot(3.0*x*pi) == cot(3.0*pi*x)
assert cos(4.5*x*pi) == cos(4.5*pi*x)
assert sin(4.5*x*pi) == sin(4.5*pi*x)
assert tan(4.5*x*pi) == tan(4.5*pi*x)
assert cot(4.5*x*pi) == cot(4.5*pi*x)
def test_inverses():
raises(AttributeError, lambda: sin(x).inverse())
raises(AttributeError, lambda: cos(x).inverse())
assert tan(x).inverse() == atan
assert cot(x).inverse() == acot
raises(AttributeError, lambda: csc(x).inverse())
raises(AttributeError, lambda: sec(x).inverse())
assert asin(x).inverse() == sin
assert acos(x).inverse() == cos
assert atan(x).inverse() == tan
assert acot(x).inverse() == cot
def test_real_imag():
a, b = symbols('a b', real=True)
z = a + b*I
for deep in [True, False]:
assert sin(
z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b))
assert cos(
z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b))
assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) +
cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b)))
assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) -
cosh(2*b)), -sinh(2*b)/(cos(2*a) - cosh(2*b)))
assert sin(a).as_real_imag(deep=deep) == (sin(a), 0)
assert cos(a).as_real_imag(deep=deep) == (cos(a), 0)
assert tan(a).as_real_imag(deep=deep) == (tan(a), 0)
assert cot(a).as_real_imag(deep=deep) == (cot(a), 0)
@XFAIL
def test_sin_cos_with_infinity():
# Test for issue 5196
# https://github.com/sympy/sympy/issues/5196
assert sin(oo) is S.NaN
assert cos(oo) is S.NaN
@slow
def test_sincos_rewrite_sqrt():
# equivalent to testing rewrite(pow)
for p in [1, 3, 5, 17]:
for t in [1, 8]:
n = t*p
# The vertices `exp(i*pi/n)` of a regular `n`-gon can
# be expressed by means of nested square roots if and
# only if `n` is a product of Fermat primes, `p`, and
# powers of 2, `t'. The code aims to check all vertices
# not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`).
# For large `n` this makes the test too slow, therefore
# the vertices are limited to those of index `i < 10`.
for i in range(1, min((n + 1)//2 + 1, 10)):
if 1 == gcd(i, n):
x = i*pi/n
s1 = sin(x).rewrite(sqrt)
c1 = cos(x).rewrite(sqrt)
assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64)
assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite(
sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half)
assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite(
sqrt) == -1
e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation
a = (
-3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 -
3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) +
17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
+ sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17)
+ 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128
+ 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) +
17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
+ sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32
+ sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 +
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 -
5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 -
3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32
+ sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 +
S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) +
17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
Rational(15, 32))/32)/2)
assert e.rewrite(sqrt) == a
assert e.n() == a.n()
# coverage of fermatCoords: multiplicity > 1; the following could be
# different but that portion of the code should be tested in some way
assert cos(pi/9/17).rewrite(sqrt) == \
sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17))
@slow
def test_tancot_rewrite_sqrt():
# equivalent to testing rewrite(pow)
for p in [1, 3, 5, 17]:
for t in [1, 8]:
n = t*p
for i in range(1, min((n + 1)//2 + 1, 10)):
if 1 == gcd(i, n):
x = i*pi/n
if 2*i != n and 3*i != 2*n:
t1 = tan(x).rewrite(sqrt)
assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
if i != 0 and i != n:
c1 = cot(x).rewrite(sqrt)
assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
def test_sec():
x = symbols('x', real=True)
z = symbols('z')
assert sec.nargs == FiniteSet(1)
assert sec(zoo) is nan
assert sec(0) == 1
assert sec(pi) == -1
assert sec(pi/2) is zoo
assert sec(-pi/2) is zoo
assert sec(pi/6) == 2*sqrt(3)/3
assert sec(pi/3) == 2
assert sec(pi*Rational(5, 2)) is zoo
assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7))
assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421
assert sec(I) == 1/cosh(1)
assert sec(x*I) == 1/cosh(x)
assert sec(-x) == sec(x)
assert sec(asec(x)) == x
assert sec(z).conjugate() == sec(conjugate(z))
assert (sec(z).as_real_imag() ==
(cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
cos(re(z))**2*cosh(im(z))**2),
sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
cos(re(z))**2*cosh(im(z))**2)))
assert sec(x).expand(trig=True) == 1/cos(x)
assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1)
assert sec(x).is_extended_real == True
assert sec(z).is_real == None
assert sec(a).is_algebraic is None
assert sec(na).is_algebraic is False
assert sec(x).as_leading_term() == sec(x)
assert sec(0).is_finite == True
assert sec(x).is_finite == None
assert sec(pi/2).is_finite == False
assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6)
# https://github.com/sympy/sympy/issues/7166
assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6)
# https://github.com/sympy/sympy/issues/7167
assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) ==
1/sqrt(x - pi*Rational(3, 2)) + (x - pi*Rational(3, 2))**Rational(3, 2)/12 +
(x - pi*Rational(3, 2))**Rational(7, 2)/160 + O((x - pi*Rational(3, 2))**4, (x, pi*Rational(3, 2))))
assert sec(x).diff(x) == tan(x)*sec(x)
# Taylor Term checks
assert sec(z).taylor_term(4, z) == 5*z**4/24
assert sec(z).taylor_term(6, z) == 61*z**6/720
assert sec(z).taylor_term(5, z) == 0
def test_sec_rewrite():
assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2)
assert sec(x).rewrite(cos) == 1/cos(x)
assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1)
assert sec(x).rewrite(pow) == sec(x)
assert sec(x).rewrite(sqrt) == sec(x)
assert sec(z).rewrite(cot) == (cot(z/2)**2 + 1)/(cot(z/2)**2 - 1)
assert sec(x).rewrite(sin) == 1 / sin(x + pi / 2, evaluate=False)
assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1)
assert sec(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)
def test_sec_fdiff():
assert sec(x).fdiff() == tan(x)*sec(x)
raises(ArgumentIndexError, lambda: sec(x).fdiff(2))
def test_csc():
x = symbols('x', real=True)
z = symbols('z')
# https://github.com/sympy/sympy/issues/6707
cosecant = csc('x')
alternate = 1/sin('x')
assert cosecant.equals(alternate) == True
assert alternate.equals(cosecant) == True
assert csc.nargs == FiniteSet(1)
assert csc(0) is zoo
assert csc(pi) is zoo
assert csc(zoo) is nan
assert csc(pi/2) == 1
assert csc(-pi/2) == -1
assert csc(pi/6) == 2
assert csc(pi/3) == 2*sqrt(3)/3
assert csc(pi*Rational(5, 2)) == 1
assert csc(pi*Rational(9, 7)) == -csc(pi*Rational(2, 7))
assert csc(pi*Rational(3, 4)) == sqrt(2) # issue 8421
assert csc(I) == -I/sinh(1)
assert csc(x*I) == -I/sinh(x)
assert csc(-x) == -csc(x)
assert csc(acsc(x)) == x
assert csc(z).conjugate() == csc(conjugate(z))
assert (csc(z).as_real_imag() ==
(sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
cos(re(z))**2*sinh(im(z))**2),
-cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
cos(re(z))**2*sinh(im(z))**2)))
assert csc(x).expand(trig=True) == 1/sin(x)
assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x))
assert csc(x).is_extended_real == True
assert csc(z).is_real == None
assert csc(a).is_algebraic is None
assert csc(na).is_algebraic is False
assert csc(x).as_leading_term() == csc(x)
assert csc(0).is_finite == False
assert csc(x).is_finite == None
assert csc(pi/2).is_finite == True
assert series(csc(x), x, x0=pi/2, n=6) == \
1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2))
assert series(csc(x), x, x0=0, n=6) == \
1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6)
assert csc(x).diff(x) == -cot(x)*csc(x)
assert csc(x).taylor_term(2, x) == 0
assert csc(x).taylor_term(3, x) == 7*x**3/360
assert csc(x).taylor_term(5, x) == 31*x**5/15120
raises(ArgumentIndexError, lambda: csc(x).fdiff(2))
def test_asec():
z = Symbol('z', zero=True)
assert asec(z) is zoo
assert asec(nan) is nan
assert asec(1) == 0
assert asec(-1) == pi
assert asec(oo) == pi/2
assert asec(-oo) == pi/2
assert asec(zoo) == pi/2
assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4)
assert asec(1 + sqrt(5)) == pi*Rational(2, 5)
assert asec(2/sqrt(3)) == pi/6
assert asec(sqrt(4 - 2*sqrt(2))) == pi/8
assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8)
assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10)
assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10)
assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12)
assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2))
assert asec(x).as_leading_term(x) == log(x)
assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2
assert asec(x).rewrite(asin) == -asin(1/x) + pi/2
assert asec(x).rewrite(acos) == acos(1/x)
assert asec(x).rewrite(atan) == (2*atan(x + sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x
assert asec(x).rewrite(acot) == (2*acot(x - sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x
assert asec(x).rewrite(acsc) == -acsc(x) + pi/2
raises(ArgumentIndexError, lambda: asec(x).fdiff(2))
def test_asec_is_real():
assert asec(S.Half).is_real is False
n = Symbol('n', positive=True, integer=True)
assert asec(n).is_extended_real is True
assert asec(x).is_real is None
assert asec(r).is_real is None
t = Symbol('t', real=False, finite=True)
assert asec(t).is_real is False
def test_acsc():
assert acsc(nan) is nan
assert acsc(1) == pi/2
assert acsc(-1) == -pi/2
assert acsc(oo) == 0
assert acsc(-oo) == 0
assert acsc(zoo) == 0
assert acsc(0) is zoo
assert acsc(csc(3)) == -3 + pi
assert acsc(csc(4)) == -4 + pi
assert acsc(csc(6)) == 6 - 2*pi
assert unchanged(acsc, csc(x))
assert unchanged(acsc, sec(x))
assert acsc(2/sqrt(3)) == pi/3
assert acsc(csc(pi*Rational(13, 4))) == -pi/4
assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5
assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5
assert acsc(-2) == -pi/6
assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8
assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8)
assert acsc(1 + sqrt(5)) == pi/10
assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12)
assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2))
assert acsc(x).as_leading_term(x) == log(x)
assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x)
assert acsc(x).rewrite(asin) == asin(1/x)
assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2
assert acsc(x).rewrite(atan) == (-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
assert acsc(x).rewrite(asec) == -asec(x) + pi/2
raises(ArgumentIndexError, lambda: acsc(x).fdiff(2))
def test_csc_rewrite():
assert csc(x).rewrite(pow) == csc(x)
assert csc(x).rewrite(sqrt) == csc(x)
assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x))
assert csc(x).rewrite(sin) == 1/sin(x)
assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2))
assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2))
assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False)
assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False)
# issue 17349
assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \
-1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) +
I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False)
def test_issue_8653():
n = Symbol('n', integer=True)
assert sin(n).is_irrational is None
assert cos(n).is_irrational is None
assert tan(n).is_irrational is None
def test_issue_9157():
n = Symbol('n', integer=True, positive=True)
assert atan(n - 1).is_nonnegative is True
def test_trig_period():
x, y = symbols('x, y')
assert sin(x).period() == 2*pi
assert cos(x).period() == 2*pi
assert tan(x).period() == pi
assert cot(x).period() == pi
assert sec(x).period() == 2*pi
assert csc(x).period() == 2*pi
assert sin(2*x).period() == pi
assert cot(4*x - 6).period() == pi/4
assert cos((-3)*x).period() == pi*Rational(2, 3)
assert cos(x*y).period(x) == 2*pi/abs(y)
assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x)
assert tan(3*x).period(y) is S.Zero
raises(NotImplementedError, lambda: sin(x**2).period(x))
def test_issue_7171():
assert sin(x).rewrite(sqrt) == sin(x)
assert sin(x).rewrite(pow) == sin(x)
def test_issue_11864():
w, k = symbols('w, k', real=True)
F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True))
soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True))
assert F.rewrite(sinc) == soln
def test_real_assumptions():
z = Symbol('z', real=False, finite=True)
assert sin(z).is_real is None
assert cos(z).is_real is None
assert tan(z).is_real is False
assert sec(z).is_real is None
assert csc(z).is_real is None
assert cot(z).is_real is False
assert asin(p).is_real is None
assert asin(n).is_real is None
assert asec(p).is_real is None
assert asec(n).is_real is None
assert acos(p).is_real is None
assert acos(n).is_real is None
assert acsc(p).is_real is None
assert acsc(n).is_real is None
assert atan(p).is_positive is True
assert atan(n).is_negative is True
assert acot(p).is_positive is True
assert acot(n).is_negative is True
def test_issue_14320():
assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi)
assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2)
assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2)
assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20)
assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi)
assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17)
assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15)
assert atan(cot(12)) == -12 + pi*Rational(7, 2) and (-pi/2 < -12 + pi*Rational(7, 2) < pi/2) and cot(12) == tan(-12 + pi*Rational(7, 2))
assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15)
assert acot(tan(19)) == -19 + pi*Rational(13, 2) and (-pi/2 < -19 + pi*Rational(13, 2) <= pi/2) and tan(19) == cot(-19 + pi*Rational(13, 2))
assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi)
assert asec(csc(13)) == -13 + pi*Rational(9, 2) and (0 <= -13 + pi*Rational(9, 2) <= pi) and sin(13) == cos(-13 + pi*Rational(9, 2))
assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14)
assert acsc(sec(10)) == pi*Rational(-7, 2) + 10 and (-pi/2 <= pi*Rational(-7, 2) + 10 <= pi/2) and cos(10) == sin(pi*Rational(-7, 2) + 10)
def test_issue_14543():
assert sec(2*pi + 11) == sec(11)
assert sec(2*pi - 11) == sec(11)
assert sec(pi + 11) == -sec(11)
assert sec(pi - 11) == -sec(11)
assert csc(2*pi + 17) == csc(17)
assert csc(2*pi - 17) == -csc(17)
assert csc(pi + 17) == -csc(17)
assert csc(pi - 17) == csc(17)
x = Symbol('x')
assert csc(pi/2 + x) == sec(x)
assert csc(pi/2 - x) == sec(x)
assert csc(pi*Rational(3, 2) + x) == -sec(x)
assert csc(pi*Rational(3, 2) - x) == -sec(x)
assert sec(pi/2 - x) == csc(x)
assert sec(pi/2 + x) == -csc(x)
assert sec(pi*Rational(3, 2) + x) == csc(x)
assert sec(pi*Rational(3, 2) - x) == -csc(x)
|
3cbfd2f2f04075dc3b1b36d12e3867935663d0c9fe4104e99de98813e1ec4cb2 | from sympy import (
Abs, acos, adjoint, arg, atan, atan2, conjugate, cos, DiracDelta,
E, exp, expand, Expr, Function, Heaviside, I, im, log, nan, oo,
pi, Rational, re, S, sign, sin, sqrt, Symbol, symbols, transpose,
zoo, exp_polar, Piecewise, Interval, comp, Integral, Matrix,
ImmutableMatrix, SparseMatrix, ImmutableSparseMatrix, MatrixSymbol,
FunctionMatrix, Lambda, Derivative)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.utilities.pytest import XFAIL, raises
def N_equals(a, b):
"""Check whether two complex numbers are numerically close"""
return comp(a.n(), b.n(), 1.e-6)
def test_re():
x, y = symbols('x,y')
a, b = symbols('a,b', real=True)
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
assert re(nan) is nan
assert re(oo) is oo
assert re(-oo) is -oo
assert re(0) == 0
assert re(1) == 1
assert re(-1) == -1
assert re(E) == E
assert re(-E) == -E
assert unchanged(re, x)
assert re(x*I) == -im(x)
assert re(r*I) == 0
assert re(r) == r
assert re(i*I) == I * i
assert re(i) == 0
assert re(x + y) == re(x) + re(y)
assert re(x + r) == re(x) + r
assert re(re(x)) == re(x)
assert re(2 + I) == 2
assert re(x + I) == re(x)
assert re(x + y*I) == re(x) - im(y)
assert re(x + r*I) == re(x)
assert re(log(2*I)) == log(2)
assert re((2 + I)**2).expand(complex=True) == 3
assert re(conjugate(x)) == re(x)
assert conjugate(re(x)) == re(x)
assert re(x).as_real_imag() == (re(x), 0)
assert re(i*r*x).diff(r) == re(i*x)
assert re(i*r*x).diff(i) == I*r*im(x)
assert re(
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)
assert re(a * (2 + b*I)) == 2*a
assert re((1 + sqrt(a + b*I))/2) == \
(a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + S.Half
assert re(x).rewrite(im) == x - S.ImaginaryUnit*im(x)
assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit*im(y)
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
x = Symbol('x')
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
assert re(S.ComplexInfinity) is S.NaN
n, m, l = symbols('n m l')
A = MatrixSymbol('A',n,m)
assert re(A) == (S.Half) * (A + conjugate(A))
A = Matrix([[1 + 4*I,2],[0, -3*I]])
assert re(A) == Matrix([[1, 2],[0, 0]])
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
assert re(A) == ImmutableMatrix([[1, 3],[0, 0]])
X = SparseMatrix([[2*j + i*I for i in range(5)] for j in range(5)])
assert re(X) - Matrix([[0, 0, 0, 0, 0],
[2, 2, 2, 2, 2],
[4, 4, 4, 4, 4],
[6, 6, 6, 6, 6],
[8, 8, 8, 8, 8]]) == Matrix.zeros(5)
assert im(X) - Matrix([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]) == Matrix.zeros(5)
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
def test_im():
x, y = symbols('x,y')
a, b = symbols('a,b', real=True)
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
assert im(nan) is nan
assert im(oo*I) is oo
assert im(-oo*I) is -oo
assert im(0) == 0
assert im(1) == 0
assert im(-1) == 0
assert im(E*I) == E
assert im(-E*I) == -E
assert unchanged(im, x)
assert im(x*I) == re(x)
assert im(r*I) == r
assert im(r) == 0
assert im(i*I) == 0
assert im(i) == -I * i
assert im(x + y) == im(x) + im(y)
assert im(x + r) == im(x)
assert im(x + r*I) == im(x) + r
assert im(im(x)*I) == im(x)
assert im(2 + I) == 1
assert im(x + I) == im(x) + 1
assert im(x + y*I) == im(x) + re(y)
assert im(x + r*I) == im(x) + r
assert im(log(2*I)) == pi/2
assert im((2 + I)**2).expand(complex=True) == 4
assert im(conjugate(x)) == -im(x)
assert conjugate(im(x)) == im(x)
assert im(x).as_real_imag() == (im(x), 0)
assert im(i*r*x).diff(r) == im(i*x)
assert im(i*r*x).diff(i) == -I * re(r*x)
assert im(
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)
assert im(a * (2 + b*I)) == a*b
assert im((1 + sqrt(a + b*I))/2) == \
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2
assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
x = Symbol('x')
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
assert im(S.ComplexInfinity) is S.NaN
n, m, l = symbols('n m l')
A = MatrixSymbol('A',n,m)
assert im(A) == (S.One/(2*I)) * (A - conjugate(A))
A = Matrix([[1 + 4*I, 2],[0, -3*I]])
assert im(A) == Matrix([[4, 0],[0, -3]])
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
assert im(A) == ImmutableMatrix([[3, -2],[0, 2]])
X = ImmutableSparseMatrix(
[[i*I + i for i in range(5)] for i in range(5)])
Y = SparseMatrix([[i for i in range(5)] for i in range(5)])
assert im(X).as_immutable() == Y
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
def test_sign():
assert sign(1.2) == 1
assert sign(-1.2) == -1
assert sign(3*I) == I
assert sign(-3*I) == -I
assert sign(0) == 0
assert sign(nan) is nan
assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4
assert sign(2 + 3*I).simplify() == sign(2 + 3*I)
assert sign(2 + 2*I).simplify() == sign(1 + I)
assert sign(im(sqrt(1 - sqrt(3)))) == 1
assert sign(sqrt(1 - sqrt(3))) == I
x = Symbol('x')
assert sign(x).is_finite is True
assert sign(x).is_complex is True
assert sign(x).is_imaginary is None
assert sign(x).is_integer is None
assert sign(x).is_real is None
assert sign(x).is_zero is None
assert sign(x).doit() == sign(x)
assert sign(1.2*x) == sign(x)
assert sign(2*x) == sign(x)
assert sign(I*x) == I*sign(x)
assert sign(-2*I*x) == -I*sign(x)
assert sign(conjugate(x)) == conjugate(sign(x))
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
m = Symbol('m', negative=True)
assert sign(2*p*x) == sign(x)
assert sign(n*x) == -sign(x)
assert sign(n*m*x) == sign(x)
x = Symbol('x', imaginary=True)
assert sign(x).is_imaginary is True
assert sign(x).is_integer is False
assert sign(x).is_real is False
assert sign(x).is_zero is False
assert sign(x).diff(x) == 2*DiracDelta(-I*x)
assert sign(x).doit() == x / Abs(x)
assert conjugate(sign(x)) == -sign(x)
x = Symbol('x', real=True)
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is None
assert sign(x).diff(x) == 2*DiracDelta(x)
assert sign(x).doit() == sign(x)
assert conjugate(sign(x)) == sign(x)
x = Symbol('x', nonzero=True)
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is False
assert sign(x).doit() == x / Abs(x)
assert sign(Abs(x)) == 1
assert Abs(sign(x)) == 1
x = Symbol('x', positive=True)
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is False
assert sign(x).doit() == x / Abs(x)
assert sign(Abs(x)) == 1
assert Abs(sign(x)) == 1
x = 0
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is True
assert sign(x).doit() == 0
assert sign(Abs(x)) == 0
assert Abs(sign(x)) == 0
nz = Symbol('nz', nonzero=True, integer=True)
assert sign(nz).is_imaginary is False
assert sign(nz).is_integer is True
assert sign(nz).is_real is True
assert sign(nz).is_zero is False
assert sign(nz)**2 == 1
assert (sign(nz)**3).args == (sign(nz), 3)
assert sign(Symbol('x', nonnegative=True)).is_nonnegative
assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
assert sign(Symbol('x', nonpositive=True)).is_nonpositive
assert sign(Symbol('x', real=True)).is_nonnegative is None
assert sign(Symbol('x', real=True)).is_nonpositive is None
assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None
x, y = Symbol('x', real=True), Symbol('y')
assert sign(x).rewrite(Piecewise) == \
Piecewise((1, x > 0), (-1, x < 0), (0, True))
assert sign(y).rewrite(Piecewise) == sign(y)
assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1
assert sign(y).rewrite(Heaviside) == sign(y)
# evaluate what can be evaluated
assert sign(exp_polar(I*pi)*pi) is S.NegativeOne
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
# if there is a fast way to know when and when you cannot prove an
# expression like this is zero then the equality to zero is ok
assert sign(eq).func is sign or sign(eq) == 0
# but sometimes it's hard to do this so it's better not to load
# abs down with tests that will be very slow
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
p = expand(q**3)**Rational(1, 3)
d = p - q
assert sign(d).func is sign or sign(d) == 0
def test_as_real_imag():
n = pi**1000
# the special code for working out the real
# and complex parts of a power with Integer exponent
# should not run if there is no imaginary part, hence
# this should not hang
assert n.as_real_imag() == (n, 0)
# issue 6261
x = Symbol('x')
assert sqrt(x).as_real_imag() == \
((re(x)**2 + im(x)**2)**Rational(1, 4)*cos(atan2(im(x), re(x))/2),
(re(x)**2 + im(x)**2)**Rational(1, 4)*sin(atan2(im(x), re(x))/2))
# issue 3853
a, b = symbols('a,b', real=True)
assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
(
(a**2 + b**2)**Rational(
1, 4)*cos(atan2(b, a)/2)/2 + S.Half,
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)
assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
i = symbols('i', imaginary=True)
assert sqrt(i**2).as_real_imag() == (0, abs(i))
assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
assert ((1 + I)**3/(1 - I)).as_real_imag() == (-2, 0)
@XFAIL
def test_sign_issue_3068():
n = pi**1000
i = int(n)
x = Symbol('x')
assert (n - i).round() == 1 # doesn't hang
assert sign(n - i) == 1
# perhaps it's not possible to get the sign right when
# only 1 digit is being requested for this situation;
# 2 digits works
assert (n - x).n(1, subs={x: i}) > 0
assert (n - x).n(2, subs={x: i}) > 0
def test_Abs():
raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717
x, y = symbols('x,y')
assert sign(sign(x)) == sign(x)
assert sign(x*y).func is sign
assert Abs(0) == 0
assert Abs(1) == 1
assert Abs(-1) == 1
assert Abs(I) == 1
assert Abs(-I) == 1
assert Abs(nan) is nan
assert Abs(zoo) is oo
assert Abs(I * pi) == pi
assert Abs(-I * pi) == pi
assert Abs(I * x) == Abs(x)
assert Abs(-I * x) == Abs(x)
assert Abs(-2*x) == 2*Abs(x)
assert Abs(-2.0*x) == 2.0*Abs(x)
assert Abs(2*pi*x*y) == 2*pi*Abs(x*y)
assert Abs(conjugate(x)) == Abs(x)
assert conjugate(Abs(x)) == Abs(x)
assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)
a = Symbol('a', positive=True)
assert Abs(2*pi*x*a) == 2*pi*a*Abs(x)
assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x)
x = Symbol('x', real=True)
n = Symbol('n', integer=True)
assert Abs((-1)**n) == 1
assert x**(2*n) == Abs(x)**(2*n)
assert Abs(x).diff(x) == sign(x)
assert abs(x) == Abs(x) # Python built-in
assert Abs(x)**3 == x**2*Abs(x)
assert Abs(x)**4 == x**4
assert (
Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged
assert (1/Abs(x)).args == (Abs(x), -1)
assert 1/Abs(x)**3 == 1/(x**2*Abs(x))
assert Abs(x)**-3 == Abs(x)/(x**4)
assert Abs(x**3) == x**2*Abs(x)
assert Abs(I**I) == exp(-pi/2)
assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4)))
y = Symbol('y', real=True)
assert Abs(I**y) == 1
y = Symbol('y')
assert Abs(I**y) == exp(-pi*im(y)/2)
x = Symbol('x', imaginary=True)
assert Abs(x).diff(x) == -sign(x)
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
# if there is a fast way to know when you can and when you cannot prove an
# expression like this is zero then the equality to zero is ok
assert abs(eq).func is Abs or abs(eq) == 0
# but sometimes it's hard to do this so it's better not to load
# abs down with tests that will be very slow
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
p = expand(q**3)**Rational(1, 3)
d = p - q
assert abs(d).func is Abs or abs(d) == 0
assert Abs(4*exp(pi*I/4)) == 4
assert Abs(3**(2 + I)) == 9
assert Abs((-3)**(1 - I)) == 3*exp(pi)
assert Abs(oo) is oo
assert Abs(-oo) is oo
assert Abs(oo + I) is oo
assert Abs(oo + I*oo) is oo
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
x = Symbol('x')
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
assert Abs(x).fdiff() == sign(x)
raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))
# doesn't have recursion error
arg = sqrt(acos(1 - I)*acos(1 + I))
assert abs(arg) == arg
# special handling to put Abs in denom
assert abs(1/x) == 1/Abs(x)
e = abs(2/x**2)
assert e.is_Mul and e == 2/Abs(x**2)
assert unchanged(Abs, y/x)
assert unchanged(Abs, x/(x + 1))
assert unchanged(Abs, x*y)
p = Symbol('p', positive=True)
assert abs(x/p) == abs(x)/p
# coverage
assert unchanged(Abs, Symbol('x', real=True)**y)
def test_Abs_rewrite():
x = Symbol('x', real=True)
a = Abs(x).rewrite(Heaviside).expand()
assert a == x*Heaviside(x) - x*Heaviside(-x)
for i in [-2, -1, 0, 1, 2]:
assert a.subs(x, i) == abs(i)
y = Symbol('y')
assert Abs(y).rewrite(Heaviside) == Abs(y)
x, y = Symbol('x', real=True), Symbol('y')
assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True))
assert Abs(y).rewrite(Piecewise) == Abs(y)
assert Abs(y).rewrite(sign) == y/sign(y)
i = Symbol('i', imaginary=True)
assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True))
assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y))
assert Abs(i).rewrite(conjugate) == sqrt(-i**2) # == -I*i
y = Symbol('y', extended_real=True)
assert (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \
-exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y)
def test_Abs_real():
# test some properties of abs that only apply
# to real numbers
x = Symbol('x', complex=True)
assert sqrt(x**2) != Abs(x)
assert Abs(x**2) != x**2
x = Symbol('x', real=True)
assert sqrt(x**2) == Abs(x)
assert Abs(x**2) == x**2
# if the symbol is zero, the following will still apply
nn = Symbol('nn', nonnegative=True, real=True)
np = Symbol('np', nonpositive=True, real=True)
assert Abs(nn) == nn
assert Abs(np) == -np
def test_Abs_properties():
x = Symbol('x')
assert Abs(x).is_real is None
assert Abs(x).is_extended_real is True
assert Abs(x).is_rational is None
assert Abs(x).is_positive is None
assert Abs(x).is_nonnegative is None
assert Abs(x).is_extended_positive is None
assert Abs(x).is_extended_nonnegative is True
f = Symbol('x', finite=True)
assert Abs(f).is_real is True
assert Abs(f).is_extended_real is True
assert Abs(f).is_rational is None
assert Abs(f).is_positive is None
assert Abs(f).is_nonnegative is True
assert Abs(f).is_extended_positive is None
assert Abs(f).is_extended_nonnegative is True
z = Symbol('z', complex=True, zero=False)
assert Abs(z).is_real is None
assert Abs(z).is_extended_real is True
assert Abs(z).is_rational is None
assert Abs(z).is_positive is None
assert Abs(z).is_extended_positive is True
assert Abs(z).is_zero is False
p = Symbol('p', positive=True)
assert Abs(p).is_real is True
assert Abs(p).is_extended_real is True
assert Abs(p).is_rational is None
assert Abs(p).is_positive is True
assert Abs(p).is_zero is False
q = Symbol('q', rational=True)
assert Abs(q).is_real is True
assert Abs(q).is_rational is True
assert Abs(q).is_integer is None
assert Abs(q).is_positive is None
assert Abs(q).is_nonnegative is True
i = Symbol('i', integer=True)
assert Abs(i).is_real is True
assert Abs(i).is_integer is True
assert Abs(i).is_positive is None
assert Abs(i).is_nonnegative is True
e = Symbol('n', even=True)
ne = Symbol('ne', real=True, even=False)
assert Abs(e).is_even is True
assert Abs(ne).is_even is False
assert Abs(i).is_even is None
o = Symbol('n', odd=True)
no = Symbol('no', real=True, odd=False)
assert Abs(o).is_odd is True
assert Abs(no).is_odd is False
assert Abs(i).is_odd is None
def test_abs():
# this tests that abs calls Abs; don't rename to
# test_Abs since that test is already above
a = Symbol('a', positive=True)
assert abs(I*(1 + a)**2) == (1 + a)**2
def test_arg():
assert arg(0) is nan
assert arg(1) == 0
assert arg(-1) == pi
assert arg(I) == pi/2
assert arg(-I) == -pi/2
assert arg(1 + I) == pi/4
assert arg(-1 + I) == pi*Rational(3, 4)
assert arg(1 - I) == -pi/4
assert arg(exp_polar(4*pi*I)) == 4*pi
assert arg(exp_polar(-7*pi*I)) == -7*pi
assert arg(exp_polar(5 - 3*pi*I/4)) == pi*Rational(-3, 4)
f = Function('f')
assert not arg(f(0) + I*f(1)).atoms(re)
p = Symbol('p', positive=True)
assert arg(p) == 0
n = Symbol('n', negative=True)
assert arg(n) == pi
x = Symbol('x')
assert conjugate(arg(x)) == arg(x)
e = p + I*p**2
assert arg(e) == arg(1 + p*I)
# make sure sign doesn't swap
e = -2*p + 4*I*p**2
assert arg(e) == arg(-1 + 2*p*I)
# make sure sign isn't lost
x = symbols('x', real=True) # could be zero
e = x + I*x
assert arg(e) == arg(x*(1 + I))
assert arg(e/p) == arg(x*(1 + I))
e = p*cos(p) + I*log(p)*exp(p)
assert arg(e).args[0] == e
# keep it simple -- let the user do more advanced cancellation
e = (p + 1) + I*(p**2 - 1)
assert arg(e).args[0] == e
f = Function('f')
e = 2*x*(f(0) - 1) - 2*x*f(0)
assert arg(e) == arg(-2*x)
assert arg(f(0)).func == arg and arg(f(0)).args == (f(0),)
def test_arg_rewrite():
assert arg(1 + I) == atan2(1, 1)
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert arg(x + I*y).rewrite(atan2) == atan2(y, x)
def test_adjoint():
a = Symbol('a', antihermitian=True)
b = Symbol('b', hermitian=True)
assert adjoint(a) == -a
assert adjoint(I*a) == I*a
assert adjoint(b) == b
assert adjoint(I*b) == -I*b
assert adjoint(a*b) == -b*a
assert adjoint(I*a*b) == I*b*a
x, y = symbols('x y')
assert adjoint(adjoint(x)) == x
assert adjoint(x + y) == adjoint(x) + adjoint(y)
assert adjoint(x - y) == adjoint(x) - adjoint(y)
assert adjoint(x * y) == adjoint(x) * adjoint(y)
assert adjoint(x / y) == adjoint(x) / adjoint(y)
assert adjoint(-x) == -adjoint(x)
x, y = symbols('x y', commutative=False)
assert adjoint(adjoint(x)) == x
assert adjoint(x + y) == adjoint(x) + adjoint(y)
assert adjoint(x - y) == adjoint(x) - adjoint(y)
assert adjoint(x * y) == adjoint(y) * adjoint(x)
assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x)
assert adjoint(-x) == -adjoint(x)
def test_conjugate():
a = Symbol('a', real=True)
b = Symbol('b', imaginary=True)
assert conjugate(a) == a
assert conjugate(I*a) == -I*a
assert conjugate(b) == -b
assert conjugate(I*b) == I*b
assert conjugate(a*b) == -a*b
assert conjugate(I*a*b) == I*a*b
x, y = symbols('x y')
assert conjugate(conjugate(x)) == x
assert conjugate(x + y) == conjugate(x) + conjugate(y)
assert conjugate(x - y) == conjugate(x) - conjugate(y)
assert conjugate(x * y) == conjugate(x) * conjugate(y)
assert conjugate(x / y) == conjugate(x) / conjugate(y)
assert conjugate(-x) == -conjugate(x)
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
def test_conjugate_transpose():
x = Symbol('x')
assert conjugate(transpose(x)) == adjoint(x)
assert transpose(conjugate(x)) == adjoint(x)
assert adjoint(transpose(x)) == conjugate(x)
assert transpose(adjoint(x)) == conjugate(x)
assert adjoint(conjugate(x)) == transpose(x)
assert conjugate(adjoint(x)) == transpose(x)
class Symmetric(Expr):
def _eval_adjoint(self):
return None
def _eval_conjugate(self):
return None
def _eval_transpose(self):
return self
x = Symmetric()
assert conjugate(x) == adjoint(x)
assert transpose(x) == x
def test_transpose():
a = Symbol('a', complex=True)
assert transpose(a) == a
assert transpose(I*a) == I*a
x, y = symbols('x y')
assert transpose(transpose(x)) == x
assert transpose(x + y) == transpose(x) + transpose(y)
assert transpose(x - y) == transpose(x) - transpose(y)
assert transpose(x * y) == transpose(x) * transpose(y)
assert transpose(x / y) == transpose(x) / transpose(y)
assert transpose(-x) == -transpose(x)
x, y = symbols('x y', commutative=False)
assert transpose(transpose(x)) == x
assert transpose(x + y) == transpose(x) + transpose(y)
assert transpose(x - y) == transpose(x) - transpose(y)
assert transpose(x * y) == transpose(y) * transpose(x)
assert transpose(x / y) == 1 / transpose(y) * transpose(x)
assert transpose(-x) == -transpose(x)
def test_polarify():
from sympy import polar_lift, polarify
x = Symbol('x')
z = Symbol('z', polar=True)
f = Function('f')
ES = {}
assert polarify(-1) == (polar_lift(-1), ES)
assert polarify(1 + I) == (polar_lift(1 + I), ES)
assert polarify(exp(x), subs=False) == exp(x)
assert polarify(1 + x, subs=False) == 1 + x
assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x
assert polarify(x, lift=True) == polar_lift(x)
assert polarify(z, lift=True) == z
assert polarify(f(x), lift=True) == f(polar_lift(x))
assert polarify(1 + x, lift=True) == polar_lift(1 + x)
assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x)))
newex, subs = polarify(f(x) + z)
assert newex.subs(subs) == f(x) + z
mu = Symbol("mu")
sigma = Symbol("sigma", positive=True)
# Make sure polarify(lift=True) doesn't try to lift the integration
# variable
assert polarify(
Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma),
(x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)*
exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)**
(2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo))
def test_unpolarify():
from sympy import (exp_polar, polar_lift, exp, unpolarify,
principal_branch)
from sympy import gamma, erf, sin, tanh, uppergamma, Eq, Ne
from sympy.abc import x
p = exp_polar(7*I) + 1
u = exp(7*I) + 1
assert unpolarify(1) == 1
assert unpolarify(p) == u
assert unpolarify(p**2) == u**2
assert unpolarify(p**x) == p**x
assert unpolarify(p*x) == u*x
assert unpolarify(p + x) == u + x
assert unpolarify(sqrt(sin(p))) == sqrt(sin(u))
# Test reduction to principal branch 2*pi.
t = principal_branch(x, 2*pi)
assert unpolarify(t) == x
assert unpolarify(sqrt(t)) == sqrt(t)
# Test exponents_only.
assert unpolarify(p**p, exponents_only=True) == p**u
assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u)
# Test functions.
assert unpolarify(sin(p)) == sin(u)
assert unpolarify(tanh(p)) == tanh(u)
assert unpolarify(gamma(p)) == gamma(u)
assert unpolarify(erf(p)) == erf(u)
assert unpolarify(uppergamma(x, p)) == uppergamma(x, p)
assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \
uppergamma(sin(u), sin(u + 1))
assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \
uppergamma(0, 2)
assert unpolarify(Eq(p, 0)) == Eq(u, 0)
assert unpolarify(Ne(p, 0)) == Ne(u, 0)
assert unpolarify(polar_lift(x) > 0) == (x > 0)
# Test bools
assert unpolarify(True) is True
def test_issue_4035():
x = Symbol('x')
assert Abs(x).expand(trig=True) == Abs(x)
assert sign(x).expand(trig=True) == sign(x)
assert arg(x).expand(trig=True) == arg(x)
def test_issue_3206():
x = Symbol('x')
assert Abs(Abs(x)) == Abs(x)
def test_issue_4754_derivative_conjugate():
x = Symbol('x', real=True)
y = Symbol('y', imaginary=True)
f = Function('f')
assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate()
assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate()
def test_derivatives_issue_4757():
x = Symbol('x', real=True)
y = Symbol('y', imaginary=True)
f = Function('f')
assert re(f(x)).diff(x) == re(f(x).diff(x))
assert im(f(x)).diff(x) == im(f(x).diff(x))
assert re(f(y)).diff(y) == -I*im(f(y).diff(y))
assert im(f(y)).diff(y) == -I*re(f(y).diff(y))
assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2)
assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4)
assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2)
assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4)
def test_issue_11413():
from sympy import Matrix, simplify
v0 = Symbol('v0')
v1 = Symbol('v1')
v2 = Symbol('v2')
V = Matrix([[v0],[v1],[v2]])
U = V.normalized()
assert U == Matrix([
[v0/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
[v1/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
[v2/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]])
U.norm = sqrt(v0**2/(v0**2 + v1**2 + v2**2) + v1**2/(v0**2 + v1**2 + v2**2) + v2**2/(v0**2 + v1**2 + v2**2))
assert simplify(U.norm) == 1
def test_periodic_argument():
from sympy import (periodic_argument, unbranched_argument, oo,
principal_branch, polar_lift, pi)
x = Symbol('x')
p = Symbol('p', positive=True)
assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo)
assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo)
assert N_equals(unbranched_argument((1 + I)**2), pi/2)
assert N_equals(unbranched_argument((1 - I)**2), -pi/2)
assert N_equals(periodic_argument((1 + I)**2, 3*pi), pi/2)
assert N_equals(periodic_argument((1 - I)**2, 3*pi), -pi/2)
assert unbranched_argument(principal_branch(x, pi)) == \
periodic_argument(x, pi)
assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I)
assert periodic_argument(polar_lift(2 + I), 2*pi) == \
periodic_argument(2 + I, 2*pi)
assert periodic_argument(polar_lift(2 + I), 3*pi) == \
periodic_argument(2 + I, 3*pi)
assert periodic_argument(polar_lift(2 + I), pi) == \
periodic_argument(polar_lift(2 + I), pi)
assert unbranched_argument(polar_lift(1 + I)) == pi/4
assert periodic_argument(2*p, p) == periodic_argument(p, p)
assert periodic_argument(pi*p, p) == periodic_argument(p, p)
assert Abs(polar_lift(1 + I)) == Abs(1 + I)
@XFAIL
def test_principal_branch_fail():
# TODO XXX why does abs(x)._eval_evalf() not fall back to global evalf?
from sympy import principal_branch
assert N_equals(principal_branch((1 + I)**2, pi/2), 0)
def test_principal_branch():
from sympy import principal_branch, polar_lift, exp_polar
p = Symbol('p', positive=True)
x = Symbol('x')
neg = Symbol('x', negative=True)
assert principal_branch(polar_lift(x), p) == principal_branch(x, p)
assert principal_branch(polar_lift(2 + I), p) == principal_branch(2 + I, p)
assert principal_branch(2*x, p) == 2*principal_branch(x, p)
assert principal_branch(1, pi) == exp_polar(0)
assert principal_branch(-1, 2*pi) == exp_polar(I*pi)
assert principal_branch(-1, pi) == exp_polar(0)
assert principal_branch(exp_polar(3*pi*I)*x, 2*pi) == \
principal_branch(exp_polar(I*pi)*x, 2*pi)
assert principal_branch(neg*exp_polar(pi*I), 2*pi) == neg*exp_polar(-I*pi)
# related to issue #14692
assert principal_branch(exp_polar(-I*pi/2)/polar_lift(neg), 2*pi) == \
exp_polar(-I*pi/2)/neg
assert N_equals(principal_branch((1 + I)**2, 2*pi), 2*I)
assert N_equals(principal_branch((1 + I)**2, 3*pi), 2*I)
assert N_equals(principal_branch((1 + I)**2, 1*pi), 2*I)
# test argument sanitization
assert principal_branch(x, I).func is principal_branch
assert principal_branch(x, -4).func is principal_branch
assert principal_branch(x, -oo).func is principal_branch
assert principal_branch(x, zoo).func is principal_branch
@XFAIL
def test_issue_6167_6151():
n = pi**1000
i = int(n)
assert sign(n - i) == 1
assert abs(n - i) == n - i
x = Symbol('x')
eps = pi**-1500
big = pi**1000
one = cos(x)**2 + sin(x)**2
e = big*one - big + eps
from sympy import simplify
assert sign(simplify(e)) == 1
for xi in (111, 11, 1, Rational(1, 10)):
assert sign(e.subs(x, xi)) == 1
def test_issue_14216():
from sympy.functions.elementary.complexes import unpolarify
A = MatrixSymbol("A", 2, 2)
assert unpolarify(A[0, 0]) == A[0, 0]
assert unpolarify(A[0, 0]*A[1, 0]) == A[0, 0]*A[1, 0]
def test_issue_14238():
# doesn't cause recursion error
r = Symbol('r', real=True)
assert Abs(r + Piecewise((0, r > 0), (1 - r, True)))
def test_zero_assumptions():
nr = Symbol('nonreal', real=False, finite=True)
ni = Symbol('nonimaginary', imaginary=False)
# imaginary implies not zero
nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)
assert re(nr).is_zero is None
assert im(nr).is_zero is False
assert re(ni).is_zero is None
assert im(ni).is_zero is None
assert re(nzni).is_zero is False
assert im(nzni).is_zero is None
def test_issue_15893():
f = Function('f', real=True)
x = Symbol('x', real=True)
eq = Derivative(Abs(f(x)), f(x))
assert eq.doit() == sign(f(x))
|
482e95a16a76b6d367eda5339a85169a25abee33c105ca82e6694f09ab6d0bfe | from sympy import (
adjoint, And, Basic, conjugate, diff, expand, Eq, Function, I, ITE,
Integral, integrate, Interval, KroneckerDelta, lambdify, log, Max, Min,
oo, Or, pi, Piecewise, piecewise_fold, Rational, solve, symbols, transpose,
cos, sin, exp, Abs, Ne, Not, Symbol, S, sqrt, Sum, Tuple, zoo,
DiracDelta, Heaviside, Add, Mul, factorial, Ge, Contains, Le)
from sympy.core.expr import unchanged
from sympy.functions.elementary.piecewise import Undefined, ExprCondPair
from sympy.printing import srepr
from sympy.utilities.pytest import raises, slow
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))
# 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() == p
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, finite=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)
# XXX Make test pass without simplify
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2).simplify()
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2).simplify()
assert piecewise_fold(gy1.rewrite(Piecewise)) == \
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)) == \
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)
# XXX Make test pass without simplify
assert gy1.simplify() == 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.simplify() == 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)) == \
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)) == \
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, finite=True)
b = Symbol('b', real=True, finite=True)
x = Symbol('x', real=True, finite=True)
y = Symbol('y', real=True, finite=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_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))
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))
assert p2 == Piecewise((1 - x, (x >= 0) & (x < 1)), (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_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 import sin, cos, 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
p = Piecewise((x, True), evaluate=False)
assert p != x
assert p.is_Piecewise
assert all(isinstance(i, Basic) for i in p.args)
assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),)
assert Piecewise((1, Eq(1, x)), evaluate=False).args == (
(1, Eq(1, 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 - 1, 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, finite=True)
b = Symbol('b', real=True, finite=True)
x = Symbol('x', real=True, finite=True)
y = Symbol('y', real=True, finite=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) == []
assert Piecewise(
(1, x > x + 1),
(Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
(1, True))._intervals(x) == [(-oo, oo, 1, 1)]
assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == [
(-oo, oo, 1, 0)]
assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
)._intervals(x) == [(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) == [(-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():
from sympy import im, re, Gt
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)
|
1d18887bcdaafca6d4cf0c437a38c6a8b37d6a2aaec309c261a7f0d369cb4967 | import itertools as it
from sympy.core.expr import unchanged
from sympy.core.function import Function
from sympy.core.numbers import I, oo, Rational
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.external import import_module
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor, ceiling
from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min,
Max, real_root)
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.functions.special.delta_functions import Heaviside
from sympy.utilities.lambdify import lambdify
from sympy.utilities.pytest import raises, skip, ignore_warnings
def test_Min():
from sympy.abc import x, y, z
n = Symbol('n', negative=True)
n_ = Symbol('n_', negative=True)
nn = Symbol('nn', nonnegative=True)
nn_ = Symbol('nn_', nonnegative=True)
p = Symbol('p', positive=True)
p_ = Symbol('p_', positive=True)
np = Symbol('np', nonpositive=True)
np_ = Symbol('np_', nonpositive=True)
r = Symbol('r', real=True)
assert Min(5, 4) == 4
assert Min(-oo, -oo) is -oo
assert Min(-oo, n) is -oo
assert Min(n, -oo) is -oo
assert Min(-oo, np) is -oo
assert Min(np, -oo) is -oo
assert Min(-oo, 0) is -oo
assert Min(0, -oo) is -oo
assert Min(-oo, nn) is -oo
assert Min(nn, -oo) is -oo
assert Min(-oo, p) is -oo
assert Min(p, -oo) is -oo
assert Min(-oo, oo) is -oo
assert Min(oo, -oo) is -oo
assert Min(n, n) == n
assert unchanged(Min, n, np)
assert Min(np, n) == Min(n, np)
assert Min(n, 0) == n
assert Min(0, n) == n
assert Min(n, nn) == n
assert Min(nn, n) == n
assert Min(n, p) == n
assert Min(p, n) == n
assert Min(n, oo) == n
assert Min(oo, n) == n
assert Min(np, np) == np
assert Min(np, 0) == np
assert Min(0, np) == np
assert Min(np, nn) == np
assert Min(nn, np) == np
assert Min(np, p) == np
assert Min(p, np) == np
assert Min(np, oo) == np
assert Min(oo, np) == np
assert Min(0, 0) == 0
assert Min(0, nn) == 0
assert Min(nn, 0) == 0
assert Min(0, p) == 0
assert Min(p, 0) == 0
assert Min(0, oo) == 0
assert Min(oo, 0) == 0
assert Min(nn, nn) == nn
assert unchanged(Min, nn, p)
assert Min(p, nn) == Min(nn, p)
assert Min(nn, oo) == nn
assert Min(oo, nn) == nn
assert Min(p, p) == p
assert Min(p, oo) == p
assert Min(oo, p) == p
assert Min(oo, oo) is oo
assert Min(n, n_).func is Min
assert Min(nn, nn_).func is Min
assert Min(np, np_).func is Min
assert Min(p, p_).func is Min
# lists
assert Min() is S.Infinity
assert Min(x) == x
assert Min(x, y) == Min(y, x)
assert Min(x, y, z) == Min(z, y, x)
assert Min(x, Min(y, z)) == Min(z, y, x)
assert Min(x, Max(y, -oo)) == Min(x, y)
assert Min(p, oo, n, p, p, p_) == n
assert Min(p_, n_, p) == n_
assert Min(n, oo, -7, p, p, 2) == Min(n, -7)
assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_)
assert Min(0, x, 1, y) == Min(0, x, y)
assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100)
assert unchanged(Min, sin(x), cos(x))
assert Min(sin(x), cos(x)) == Min(cos(x), sin(x))
assert Min(cos(x), sin(x)).subs(x, 1) == cos(1)
assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half)
raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I))
raises(ValueError, lambda: Min(I))
raises(ValueError, lambda: Min(I, x))
raises(ValueError, lambda: Min(S.ComplexInfinity, x))
assert Min(1, x).diff(x) == Heaviside(1 - x)
assert Min(x, 1).diff(x) == Heaviside(1 - x)
assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \
- 2*Heaviside(2*x + Min(0, -x) - 1)
# issue 7619
f = Function('f')
assert Min(1, 2*Min(f(1), 2)) # doesn't fail
# issue 7233
e = Min(0, x)
assert e.evalf == e.n
assert e.n().args == (0, x)
# issue 8643
m = Min(n, p_, n_, r)
assert m.is_positive is False
assert m.is_nonnegative is False
assert m.is_negative is True
m = Min(p, p_)
assert m.is_positive is True
assert m.is_nonnegative is True
assert m.is_negative is False
m = Min(p, nn_, p_)
assert m.is_positive is None
assert m.is_nonnegative is True
assert m.is_negative is False
m = Min(nn, p, r)
assert m.is_positive is None
assert m.is_nonnegative is None
assert m.is_negative is None
def test_Max():
from sympy.abc import x, y, z
n = Symbol('n', negative=True)
n_ = Symbol('n_', negative=True)
nn = Symbol('nn', nonnegative=True)
p = Symbol('p', positive=True)
p_ = Symbol('p_', positive=True)
r = Symbol('r', real=True)
assert Max(5, 4) == 5
# lists
assert Max() is S.NegativeInfinity
assert Max(x) == x
assert Max(x, y) == Max(y, x)
assert Max(x, y, z) == Max(z, y, x)
assert Max(x, Max(y, z)) == Max(z, y, x)
assert Max(x, Min(y, oo)) == Max(x, y)
assert Max(n, -oo, n_, p, 2) == Max(p, 2)
assert Max(n, -oo, n_, p) == p
assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p)
assert Max(0, x, 1, y) == Max(1, x, y)
assert Max(r, r + 1, r - 1) == 1 + r
assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000)
assert Max(cos(x), sin(x)) == Max(sin(x), cos(x))
assert Max(cos(x), sin(x)).subs(x, 1) == sin(1)
assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half)
raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I))
raises(ValueError, lambda: Max(I))
raises(ValueError, lambda: Max(I, x))
raises(ValueError, lambda: Max(S.ComplexInfinity, 1))
assert Max(n, -oo, n_, p, 2) == Max(p, 2)
assert Max(n, -oo, n_, p, 1000) == Max(p, 1000)
assert Max(1, x).diff(x) == Heaviside(x - 1)
assert Max(x, 1).diff(x) == Heaviside(x - 1)
assert Max(x**2, 1 + x, 1).diff(x) == \
2*x*Heaviside(x**2 - Max(1, x + 1)) \
+ Heaviside(x - Max(1, x**2) + 1)
e = Max(0, x)
assert e.evalf == e.n
assert e.n().args == (0, x)
# issue 8643
m = Max(p, p_, n, r)
assert m.is_positive is True
assert m.is_nonnegative is True
assert m.is_negative is False
m = Max(n, n_)
assert m.is_positive is False
assert m.is_nonnegative is False
assert m.is_negative is True
m = Max(n, n_, r)
assert m.is_positive is None
assert m.is_nonnegative is None
assert m.is_negative is None
m = Max(n, nn, r)
assert m.is_positive is None
assert m.is_nonnegative is True
assert m.is_negative is False
def test_minmax_assumptions():
r = Symbol('r', real=True)
a = Symbol('a', real=True, algebraic=True)
t = Symbol('t', real=True, transcendental=True)
q = Symbol('q', rational=True)
p = Symbol('p', irrational=True)
n = Symbol('n', rational=True, integer=False)
i = Symbol('i', integer=True)
o = Symbol('o', odd=True)
e = Symbol('e', even=True)
k = Symbol('k', prime=True)
reals = [r, a, t, q, p, n, i, o, e, k]
for ext in (Max, Min):
for x, y in it.product(reals, repeat=2):
# Must be real
assert ext(x, y).is_real
# Algebraic?
if x.is_algebraic and y.is_algebraic:
assert ext(x, y).is_algebraic
elif x.is_transcendental and y.is_transcendental:
assert ext(x, y).is_transcendental
else:
assert ext(x, y).is_algebraic is None
# Rational?
if x.is_rational and y.is_rational:
assert ext(x, y).is_rational
elif x.is_irrational and y.is_irrational:
assert ext(x, y).is_irrational
else:
assert ext(x, y).is_rational is None
# Integer?
if x.is_integer and y.is_integer:
assert ext(x, y).is_integer
elif x.is_noninteger and y.is_noninteger:
assert ext(x, y).is_noninteger
else:
assert ext(x, y).is_integer is None
# Odd?
if x.is_odd and y.is_odd:
assert ext(x, y).is_odd
elif x.is_odd is False and y.is_odd is False:
assert ext(x, y).is_odd is False
else:
assert ext(x, y).is_odd is None
# Even?
if x.is_even and y.is_even:
assert ext(x, y).is_even
elif x.is_even is False and y.is_even is False:
assert ext(x, y).is_even is False
else:
assert ext(x, y).is_even is None
# Prime?
if x.is_prime and y.is_prime:
assert ext(x, y).is_prime
elif x.is_prime is False and y.is_prime is False:
assert ext(x, y).is_prime is False
else:
assert ext(x, y).is_prime is None
def test_issue_8413():
x = Symbol('x', real=True)
# we can't evaluate in general because non-reals are not
# comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError
assert Min(floor(x), x) == floor(x)
assert Min(ceiling(x), x) == x
assert Max(floor(x), x) == x
assert Max(ceiling(x), x) == ceiling(x)
def test_root():
from sympy.abc import x
n = Symbol('n', integer=True)
k = Symbol('k', integer=True)
assert root(2, 2) == sqrt(2)
assert root(2, 1) == 2
assert root(2, 3) == 2**Rational(1, 3)
assert root(2, 3) == cbrt(2)
assert root(2, -5) == 2**Rational(4, 5)/2
assert root(-2, 1) == -2
assert root(-2, 2) == sqrt(2)*I
assert root(-2, 1) == -2
assert root(x, 2) == sqrt(x)
assert root(x, 1) == x
assert root(x, 3) == x**Rational(1, 3)
assert root(x, 3) == cbrt(x)
assert root(x, -5) == x**Rational(-1, 5)
assert root(x, n) == x**(1/n)
assert root(x, -n) == x**(-1/n)
assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n)
def test_real_root():
assert real_root(-8, 3) == -2
assert real_root(-16, 4) == root(-16, 4)
r = root(-7, 4)
assert real_root(r) == r
r1 = root(-1, 3)
r2 = r1**2
r3 = root(-1, 4)
assert real_root(r1 + r2 + r3) == -1 + r2 + r3
assert real_root(root(-2, 3)) == -root(2, 3)
assert real_root(-8., 3) == -2
x = Symbol('x')
n = Symbol('n')
g = real_root(x, n)
assert g.subs(dict(x=-8, n=3)) == -2
assert g.subs(dict(x=8, n=3)) == 2
# give principle root if there is no real root -- if this is not desired
# then maybe a Root class is needed to raise an error instead
assert g.subs(dict(x=I, n=3)) == cbrt(I)
assert g.subs(dict(x=-8, n=2)) == sqrt(-8)
assert g.subs(dict(x=I, n=2)) == sqrt(I)
def test_issue_11463():
numpy = import_module('numpy')
if not numpy:
skip("numpy not installed.")
x = Symbol('x')
f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy')
# numpy.select evaluates all options before considering conditions,
# so it raises a warning about root of negative number which does
# not affect the outcome. This warning is suppressed here
with ignore_warnings(RuntimeWarning):
assert f(numpy.array(-1)) < -1
def test_rewrite_MaxMin_as_Heaviside():
from sympy.abc import x
assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x)
assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \
3*Heaviside(-x + 3)
assert Max(0, x+2, 2*x).rewrite(Heaviside) == \
2*x*Heaviside(2*x)*Heaviside(x - 2) + \
(x + 2)*Heaviside(-x + 2)*Heaviside(x + 2)
assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x)
assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \
3*Heaviside(x - 3)
assert Min(x, -x, -2).rewrite(Heaviside) == \
x*Heaviside(-2*x)*Heaviside(-x - 2) - \
x*Heaviside(2*x)*Heaviside(x - 2) \
- 2*Heaviside(-x + 2)*Heaviside(x + 2)
def test_rewrite_MaxMin_as_Piecewise():
from sympy import symbols, Piecewise
x, y, z, a, b = symbols('x y z a b', real=True)
vx, vy, va = symbols('vx vy va')
assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True))
assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True))
assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)),
(b, (b >= x) & (b >= y)), (x, x >= y), (y, True))
assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True))
assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True))
assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)),
(b, (b <= x) & (b <= y)), (x, x <= y), (y, True))
# Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments
assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True))
assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True))
def test_issue_11099():
from sympy.abc import x, y
# some fixed value tests
fixed_test_data = {x: -2, y: 3}
assert Min(x, y).evalf(subs=fixed_test_data) == \
Min(x, y).subs(fixed_test_data).evalf()
assert Max(x, y).evalf(subs=fixed_test_data) == \
Max(x, y).subs(fixed_test_data).evalf()
# randomly generate some test data
from random import randint
for i in range(20):
random_test_data = {x: randint(-100, 100), y: randint(-100, 100)}
assert Min(x, y).evalf(subs=random_test_data) == \
Min(x, y).subs(random_test_data).evalf()
assert Max(x, y).evalf(subs=random_test_data) == \
Max(x, y).subs(random_test_data).evalf()
def test_issue_12638():
from sympy.abc import a, b, c
assert Min(a, b, c, Max(a, b)) == Min(a, b, c)
assert Min(a, b, Max(a, b, c)) == Min(a, b)
assert Min(a, b, Max(a, c)) == Min(a, b)
def test_instantiation_evaluation():
from sympy.abc import v, w, x, y, z
assert Min(1, Max(2, x)) == 1
assert Max(3, Min(2, x)) == 3
assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z))
assert set(Min(Max(w, x), Max(y, z)).args) == set(
[Max(w, x), Max(y, z)])
assert Min(Max(x, y), Max(x, z), w) == Min(
w, Max(x, Min(y, z)))
A, B = Min, Max
for i in range(2):
assert A(x, B(x, y)) == x
assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z)))
A, B = B, A
assert Min(w, Max(x, y), Max(v, x, z)) == Min(
w, Max(x, Min(y, Max(v, z))))
def test_rewrite_as_Abs():
from itertools import permutations
from sympy.functions.elementary.complexes import Abs
from sympy.abc import x, y, z, w
def test(e):
free = e.free_symbols
a = e.rewrite(Abs)
assert not a.has(Min, Max)
for i in permutations(range(len(free))):
reps = dict(zip(free, i))
assert a.xreplace(reps) == e.xreplace(reps)
test(Min(x, y))
test(Max(x, y))
test(Min(x, y, z))
test(Min(Max(w, x), Max(y, z)))
def test_issue_14000():
assert isinstance(sqrt(4, evaluate=False), Pow) == True
assert isinstance(cbrt(3.5, evaluate=False), Pow) == True
assert isinstance(root(16, 4, evaluate=False), Pow) == True
assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False)
assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False)
assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False)
assert root(16, 4, 2, evaluate=False).has(Pow) == True
assert real_root(-8, 3, evaluate=False).has(Pow) == True
|
036b9a94bbeb5a4321ed0659ca93e22e5716f82c279af1f9705b55304f83243d | from sympy import (symbols, Symbol, sinh, nan, oo, zoo, pi, asinh, acosh, log,
sqrt, coth, I, cot, E, tanh, tan, cosh, cos, S, sin, Rational, atanh, acoth,
Integer, O, exp, sech, sec, csch, asech, acsch, acos, asin, expand_mul,
AccumBounds, im, re)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.utilities.pytest import raises
def test_sinh():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert sinh(nan) is nan
assert sinh(zoo) is nan
assert sinh(oo) is oo
assert sinh(-oo) is -oo
assert sinh(0) == 0
assert unchanged(sinh, 1)
assert sinh(-1) == -sinh(1)
assert unchanged(sinh, x)
assert sinh(-x) == -sinh(x)
assert unchanged(sinh, pi)
assert sinh(-pi) == -sinh(pi)
assert unchanged(sinh, 2**1024 * E)
assert sinh(-2**1024 * E) == -sinh(2**1024 * E)
assert sinh(pi*I) == 0
assert sinh(-pi*I) == 0
assert sinh(2*pi*I) == 0
assert sinh(-2*pi*I) == 0
assert sinh(-3*10**73*pi*I) == 0
assert sinh(7*10**103*pi*I) == 0
assert sinh(pi*I/2) == I
assert sinh(-pi*I/2) == -I
assert sinh(pi*I*Rational(5, 2)) == I
assert sinh(pi*I*Rational(7, 2)) == -I
assert sinh(pi*I/3) == S.Half*sqrt(3)*I
assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I
assert sinh(pi*I/4) == S.Half*sqrt(2)*I
assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I
assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I
assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I
assert sinh(pi*I/6) == S.Half*I
assert sinh(-pi*I/6) == Rational(-1, 2)*I
assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I
assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I
assert sinh(pi*I/105) == sin(pi/105)*I
assert sinh(-pi*I/105) == -sin(pi/105)*I
assert unchanged(sinh, 2 + 3*I)
assert sinh(x*I) == sin(x)*I
assert sinh(k*pi*I) == 0
assert sinh(17*k*pi*I) == 0
assert sinh(k*pi*I/2) == sin(k*pi/2)*I
assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)),
sin(im(x))*cosh(re(x)))
x = Symbol('x', extended_real=True)
assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0)
x = Symbol('x', real=True)
assert sinh(I*x).is_finite is True
def test_sinh_series():
x = Symbol('x')
assert sinh(x).series(x, 0, 10) == \
x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10)
def test_sinh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: sinh(x).fdiff(2))
def test_cosh():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert cosh(nan) is nan
assert cosh(zoo) is nan
assert cosh(oo) is oo
assert cosh(-oo) is oo
assert cosh(0) == 1
assert unchanged(cosh, 1)
assert cosh(-1) == cosh(1)
assert unchanged(cosh, x)
assert cosh(-x) == cosh(x)
assert cosh(pi*I) == cos(pi)
assert cosh(-pi*I) == cos(pi)
assert unchanged(cosh, 2**1024 * E)
assert cosh(-2**1024 * E) == cosh(2**1024 * E)
assert cosh(pi*I/2) == 0
assert cosh(-pi*I/2) == 0
assert cosh((-3*10**73 + 1)*pi*I/2) == 0
assert cosh((7*10**103 + 1)*pi*I/2) == 0
assert cosh(pi*I) == -1
assert cosh(-pi*I) == -1
assert cosh(5*pi*I) == -1
assert cosh(8*pi*I) == 1
assert cosh(pi*I/3) == S.Half
assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2)
assert cosh(pi*I/4) == S.Half*sqrt(2)
assert cosh(-pi*I/4) == S.Half*sqrt(2)
assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
assert cosh(pi*I/6) == S.Half*sqrt(3)
assert cosh(-pi*I/6) == S.Half*sqrt(3)
assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
assert cosh(pi*I/105) == cos(pi/105)
assert cosh(-pi*I/105) == cos(pi/105)
assert unchanged(cosh, 2 + 3*I)
assert cosh(x*I) == cos(x)
assert cosh(k*pi*I) == cos(k*pi)
assert cosh(17*k*pi*I) == cos(17*k*pi)
assert unchanged(cosh, k*pi)
assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)),
sin(im(x))*sinh(re(x)))
x = Symbol('x', extended_real=True)
assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)
x = Symbol('x', real=True)
assert cosh(I*x).is_finite is True
def test_cosh_series():
x = Symbol('x')
assert cosh(x).series(x, 0, 10) == \
1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10)
def test_cosh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: cosh(x).fdiff(2))
def test_tanh():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert tanh(nan) is nan
assert tanh(zoo) is nan
assert tanh(oo) == 1
assert tanh(-oo) == -1
assert tanh(0) == 0
assert unchanged(tanh, 1)
assert tanh(-1) == -tanh(1)
assert unchanged(tanh, x)
assert tanh(-x) == -tanh(x)
assert unchanged(tanh, pi)
assert tanh(-pi) == -tanh(pi)
assert unchanged(tanh, 2**1024 * E)
assert tanh(-2**1024 * E) == -tanh(2**1024 * E)
assert tanh(pi*I) == 0
assert tanh(-pi*I) == 0
assert tanh(2*pi*I) == 0
assert tanh(-2*pi*I) == 0
assert tanh(-3*10**73*pi*I) == 0
assert tanh(7*10**103*pi*I) == 0
assert tanh(pi*I/2) is zoo
assert tanh(-pi*I/2) is zoo
assert tanh(pi*I*Rational(5, 2)) is zoo
assert tanh(pi*I*Rational(7, 2)) is zoo
assert tanh(pi*I/3) == sqrt(3)*I
assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I
assert tanh(pi*I/4) == I
assert tanh(-pi*I/4) == -I
assert tanh(pi*I*Rational(17, 4)) == I
assert tanh(pi*I*Rational(-3, 4)) == I
assert tanh(pi*I/6) == I/sqrt(3)
assert tanh(-pi*I/6) == -I/sqrt(3)
assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3)
assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3)
assert tanh(pi*I/105) == tan(pi/105)*I
assert tanh(-pi*I/105) == -tan(pi/105)*I
assert unchanged(tanh, 2 + 3*I)
assert tanh(x*I) == tan(x)*I
assert tanh(k*pi*I) == 0
assert tanh(17*k*pi*I) == 0
assert tanh(k*pi*I/2) == tan(k*pi/2)*I
assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2
+ sinh(re(x))**2),
sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2))
x = Symbol('x', extended_real=True)
assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0)
def test_tanh_series():
x = Symbol('x')
assert tanh(x).series(x, 0, 10) == \
x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10)
def test_tanh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: tanh(x).fdiff(2))
def test_coth():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert coth(nan) is nan
assert coth(zoo) is nan
assert coth(oo) == 1
assert coth(-oo) == -1
assert coth(0) is zoo
assert unchanged(coth, 1)
assert coth(-1) == -coth(1)
assert unchanged(coth, x)
assert coth(-x) == -coth(x)
assert coth(pi*I) == -I*cot(pi)
assert coth(-pi*I) == cot(pi)*I
assert unchanged(coth, 2**1024 * E)
assert coth(-2**1024 * E) == -coth(2**1024 * E)
assert coth(pi*I) == -I*cot(pi)
assert coth(-pi*I) == I*cot(pi)
assert coth(2*pi*I) == -I*cot(2*pi)
assert coth(-2*pi*I) == I*cot(2*pi)
assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi)
assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi)
assert coth(pi*I/2) == 0
assert coth(-pi*I/2) == 0
assert coth(pi*I*Rational(5, 2)) == 0
assert coth(pi*I*Rational(7, 2)) == 0
assert coth(pi*I/3) == -I/sqrt(3)
assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3)
assert coth(pi*I/4) == -I
assert coth(-pi*I/4) == I
assert coth(pi*I*Rational(17, 4)) == -I
assert coth(pi*I*Rational(-3, 4)) == -I
assert coth(pi*I/6) == -sqrt(3)*I
assert coth(-pi*I/6) == sqrt(3)*I
assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I
assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I
assert coth(pi*I/105) == -cot(pi/105)*I
assert coth(-pi*I/105) == cot(pi/105)*I
assert unchanged(coth, 2 + 3*I)
assert coth(x*I) == -cot(x)*I
assert coth(k*pi*I) == -cot(k*pi)*I
assert coth(17*k*pi*I) == -cot(17*k*pi)*I
assert coth(k*pi*I) == -cot(k*pi)*I
assert coth(log(tan(2))) == coth(log(-tan(2)))
assert coth(1 + I*pi/2) == tanh(1)
assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2
+ sinh(re(x))**2),
-sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2))
x = Symbol('x', extended_real=True)
assert coth(x).as_real_imag(deep=False) == (coth(x), 0)
def test_coth_series():
x = Symbol('x')
assert coth(x).series(x, 0, 8) == \
1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8)
def test_coth_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: coth(x).fdiff(2))
def test_csch():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
n = Symbol('n', positive=True)
assert csch(nan) is nan
assert csch(zoo) is nan
assert csch(oo) == 0
assert csch(-oo) == 0
assert csch(0) is zoo
assert csch(-1) == -csch(1)
assert csch(-x) == -csch(x)
assert csch(-pi) == -csch(pi)
assert csch(-2**1024 * E) == -csch(2**1024 * E)
assert csch(pi*I) is zoo
assert csch(-pi*I) is zoo
assert csch(2*pi*I) is zoo
assert csch(-2*pi*I) is zoo
assert csch(-3*10**73*pi*I) is zoo
assert csch(7*10**103*pi*I) is zoo
assert csch(pi*I/2) == -I
assert csch(-pi*I/2) == I
assert csch(pi*I*Rational(5, 2)) == -I
assert csch(pi*I*Rational(7, 2)) == I
assert csch(pi*I/3) == -2/sqrt(3)*I
assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I
assert csch(pi*I/4) == -sqrt(2)*I
assert csch(-pi*I/4) == sqrt(2)*I
assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I
assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I
assert csch(pi*I/6) == -2*I
assert csch(-pi*I/6) == 2*I
assert csch(pi*I*Rational(7, 6)) == 2*I
assert csch(pi*I*Rational(-7, 6)) == -2*I
assert csch(pi*I*Rational(-5, 6)) == 2*I
assert csch(pi*I/105) == -1/sin(pi/105)*I
assert csch(-pi*I/105) == 1/sin(pi/105)*I
assert csch(x*I) == -1/sin(x)*I
assert csch(k*pi*I) is zoo
assert csch(17*k*pi*I) is zoo
assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I
assert csch(n).is_real is True
def test_csch_series():
x = Symbol('x')
assert csch(x).series(x, 0, 10) == \
1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \
- 73*x**9/3421440 + O(x**10)
def test_csch_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: csch(x).fdiff(2))
def test_sech():
x, y = symbols('x, y')
k = Symbol('k', integer=True)
n = Symbol('n', positive=True)
assert sech(nan) is nan
assert sech(zoo) is nan
assert sech(oo) == 0
assert sech(-oo) == 0
assert sech(0) == 1
assert sech(-1) == sech(1)
assert sech(-x) == sech(x)
assert sech(pi*I) == sec(pi)
assert sech(-pi*I) == sec(pi)
assert sech(-2**1024 * E) == sech(2**1024 * E)
assert sech(pi*I/2) is zoo
assert sech(-pi*I/2) is zoo
assert sech((-3*10**73 + 1)*pi*I/2) is zoo
assert sech((7*10**103 + 1)*pi*I/2) is zoo
assert sech(pi*I) == -1
assert sech(-pi*I) == -1
assert sech(5*pi*I) == -1
assert sech(8*pi*I) == 1
assert sech(pi*I/3) == 2
assert sech(pi*I*Rational(-2, 3)) == -2
assert sech(pi*I/4) == sqrt(2)
assert sech(-pi*I/4) == sqrt(2)
assert sech(pi*I*Rational(5, 4)) == -sqrt(2)
assert sech(pi*I*Rational(-5, 4)) == -sqrt(2)
assert sech(pi*I/6) == 2/sqrt(3)
assert sech(-pi*I/6) == 2/sqrt(3)
assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3)
assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3)
assert sech(pi*I/105) == 1/cos(pi/105)
assert sech(-pi*I/105) == 1/cos(pi/105)
assert sech(x*I) == 1/cos(x)
assert sech(k*pi*I) == 1/cos(k*pi)
assert sech(17*k*pi*I) == 1/cos(17*k*pi)
assert sech(n).is_real is True
def test_sech_series():
x = Symbol('x')
assert sech(x).series(x, 0, 10) == \
1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10)
def test_sech_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: sech(x).fdiff(2))
def test_asinh():
x, y = symbols('x,y')
assert unchanged(asinh, x)
assert asinh(-x) == -asinh(x)
#at specific points
assert asinh(nan) is nan
assert asinh( 0) == 0
assert asinh(+1) == log(sqrt(2) + 1)
assert asinh(-1) == log(sqrt(2) - 1)
assert asinh(I) == pi*I/2
assert asinh(-I) == -pi*I/2
assert asinh(I/2) == pi*I/6
assert asinh(-I/2) == -pi*I/6
# at infinites
assert asinh(oo) is oo
assert asinh(-oo) is -oo
assert asinh(I*oo) is oo
assert asinh(-I *oo) is -oo
assert asinh(zoo) is zoo
#properties
assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12
assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12
assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10
assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10
assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10)
assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10)
# Symmetry
assert asinh(Rational(-1, 2)) == -asinh(S.Half)
# inverse composition
assert unchanged(asinh, sinh(Symbol('v1')))
assert asinh(sinh(0, evaluate=False)) == 0
assert asinh(sinh(-3, evaluate=False)) == -3
assert asinh(sinh(2, evaluate=False)) == 2
assert asinh(sinh(I, evaluate=False)) == I
assert asinh(sinh(-I, evaluate=False)) == -I
assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I
assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I
assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi
assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I
assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I
def test_asinh_rewrite():
x = Symbol('x')
assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1))
def test_asinh_series():
x = Symbol('x')
assert asinh(x).series(x, 0, 8) == \
x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8)
t5 = asinh(x).taylor_term(5, x)
assert t5 == 3*x**5/40
assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112
def test_asinh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: asinh(x).fdiff(2))
def test_acosh():
x = Symbol('x')
assert unchanged(acosh, -x)
#at specific points
assert acosh(1) == 0
assert acosh(-1) == pi*I
assert acosh(0) == I*pi/2
assert acosh(S.Half) == I*pi/3
assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3)
assert acosh(nan) is nan
# at infinites
assert acosh(oo) is oo
assert acosh(-oo) is oo
assert acosh(I*oo) == oo + I*pi/2
assert acosh(-I*oo) == oo - I*pi/2
assert acosh(zoo) is zoo
assert acosh(I) == log(I*(1 + sqrt(2)))
assert acosh(-I) == log(-I*(1 + sqrt(2)))
assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12)
assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12)
assert acosh(sqrt(2)/2) == I*pi/4
assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4)
assert acosh(sqrt(3)/2) == I*pi/6
assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6)
assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8
assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8)
assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8)
assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8)
assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12
assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12)
assert acosh((sqrt(5) + 1)/4) == I*pi/5
assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5)
assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I'
assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I'
# inverse composition
assert unchanged(acosh, Symbol('v1'))
assert acosh(cosh(-3, evaluate=False)) == 3
assert acosh(cosh(3, evaluate=False)) == 3
assert acosh(cosh(0, evaluate=False)) == 0
assert acosh(cosh(I, evaluate=False)) == I
assert acosh(cosh(-I, evaluate=False)) == I
assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I
assert acosh(cosh(1 + I)) == 1 + I
assert acosh(cosh(3 - 3*I)) == 3 - 3*I
assert acosh(cosh(-3 + 2*I)) == 3 - 2*I
assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I
assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi
assert acosh(cosh(cosh(1) + I)) == cosh(1) + I
def test_acosh_rewrite():
x = Symbol('x')
assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1))
def test_acosh_series():
x = Symbol('x')
assert acosh(x).series(x, 0, 8) == \
-I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8)
t5 = acosh(x).taylor_term(5, x)
assert t5 == - 3*I*x**5/40
assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112
def test_acosh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: acosh(x).fdiff(2))
def test_asech():
x = Symbol('x')
assert unchanged(asech, -x)
# values at fixed points
assert asech(1) == 0
assert asech(-1) == pi*I
assert asech(0) is oo
assert asech(2) == I*pi/3
assert asech(-2) == 2*I*pi / 3
assert asech(nan) is nan
# at infinites
assert asech(oo) == I*pi/2
assert asech(-oo) == I*pi/2
assert asech(zoo) == I*AccumBounds(-pi/2, pi/2)
assert asech(I) == log(1 + sqrt(2)) - I*pi/2
assert asech(-I) == log(1 + sqrt(2)) + I*pi/2
assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12
assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10
assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10
assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8
assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8
assert asech(sqrt(5) - 1) == I*pi / 5
assert asech(1 - sqrt(5)) == 4*I*pi / 5
assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8
# properties
# asech(x) == acosh(1/x)
assert asech(sqrt(2)) == acosh(1/sqrt(2))
assert asech(2/sqrt(3)) == acosh(sqrt(3)/2)
assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2)
assert asech(2) == acosh(S.Half)
# asech(x) == I*acos(1/x)
# (Note: the exact formula is asech(x) == +/- I*acos(1/x))
assert asech(-sqrt(2)) == I*acos(-1/sqrt(2))
assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2)
assert asech(-S(2)) == I*acos(Rational(-1, 2))
assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2)
# sech(asech(x)) / x == 1
assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1
assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1
assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1
assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1
assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1
assert expand_mul(sech(asech((1 + sqrt(5)))) / ((1 + sqrt(5)))) == 1
assert expand_mul(sech(asech((-1 - sqrt(5)))) / ((-1 - sqrt(5)))) == 1
assert expand_mul(sech(asech((-sqrt(6) - sqrt(2)))) / ((-sqrt(6) - sqrt(2)))) == 1
# numerical evaluation
assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I'
assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I'
def test_asech_series():
x = Symbol('x')
t6 = asech(x).expansion_term(6, x)
assert t6 == -5*x**6/96
assert asech(x).expansion_term(8, x, t6, 0) == -35*x**8/1024
def test_asech_rewrite():
x = Symbol('x')
assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1))
def test_asech_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: asech(x).fdiff(2))
def test_acsch():
x = Symbol('x')
assert unchanged(acsch, x)
assert acsch(-x) == -acsch(x)
# values at fixed points
assert acsch(1) == log(1 + sqrt(2))
assert acsch(-1) == - log(1 + sqrt(2))
assert acsch(0) is zoo
assert acsch(2) == log((1+sqrt(5))/2)
assert acsch(-2) == - log((1+sqrt(5))/2)
assert acsch(I) == - I*pi/2
assert acsch(-I) == I*pi/2
assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12
assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12
assert acsch(-I*(1 + sqrt(5))) == I*pi / 10
assert acsch(I*(1 + sqrt(5))) == -I*pi / 10
assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8
assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8
assert acsch(-I*2) == I*pi / 6
assert acsch(I*2) == -I*pi / 6
assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5
assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5
assert acsch(-I*sqrt(2)) == I*pi / 4
assert acsch(I*sqrt(2)) == -I*pi / 4
assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10
assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10
assert acsch(-I*2 / sqrt(3)) == I*pi / 3
assert acsch(I*2 / sqrt(3)) == -I*pi / 3
assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8
assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8
assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5
assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5
assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12
assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12
assert acsch(nan) is nan
# properties
# acsch(x) == asinh(1/x)
assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2))
assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2)
# acsch(x) == -I*asin(I/x)
assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2))
assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2)
# csch(acsch(x)) / x == 1
assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1
assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / ((I*(1 + sqrt(5))))) == 1
assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
# numerical evaluation
assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I'
assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I'
def test_acsch_infinities():
assert acsch(oo) == 0
assert acsch(-oo) == 0
assert acsch(zoo) == 0
def test_acsch_rewrite():
x = Symbol('x')
assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1))
def test_acsch_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: acsch(x).fdiff(2))
def test_atanh():
x = Symbol('x')
#at specific points
assert atanh(0) == 0
assert atanh(I) == I*pi/4
assert atanh(-I) == -I*pi/4
assert atanh(1) is oo
assert atanh(-1) is -oo
assert atanh(nan) is nan
# at infinites
assert atanh(oo) == -I*pi/2
assert atanh(-oo) == I*pi/2
assert atanh(I*oo) == I*pi/2
assert atanh(-I*oo) == -I*pi/2
assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2)
#properties
assert atanh(-x) == -atanh(x)
assert atanh(I/sqrt(3)) == I*pi/6
assert atanh(-I/sqrt(3)) == -I*pi/6
assert atanh(I*sqrt(3)) == I*pi/3
assert atanh(-I*sqrt(3)) == -I*pi/3
assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8)
assert atanh(I*(sqrt(2) - 1)) == pi*I/8
assert atanh(I*(1 - sqrt(2))) == -pi*I/8
assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8)
assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5)
assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5)
assert atanh(I*(2 - sqrt(3))) == pi*I/12
assert atanh(I*(sqrt(3) - 2)) == -pi*I/12
assert atanh(oo) == -I*pi/2
# Symmetry
assert atanh(Rational(-1, 2)) == -atanh(S.Half)
# inverse composition
assert unchanged(atanh, tanh(Symbol('v1')))
assert atanh(tanh(-5, evaluate=False)) == -5
assert atanh(tanh(0, evaluate=False)) == 0
assert atanh(tanh(7, evaluate=False)) == 7
assert atanh(tanh(I, evaluate=False)) == I
assert atanh(tanh(-I, evaluate=False)) == -I
assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi
assert atanh(tanh(3 + I)) == 3 + I
assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I
assert atanh(tanh(pi/2)) == pi/2
assert atanh(tanh(pi)) == pi
assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I
assert atanh(tanh(9 - I*Rational(2, 3))) == 9 - I*Rational(2, 3)
assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi
def test_atanh_rewrite():
x = Symbol('x')
assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2
def test_atanh_series():
x = Symbol('x')
assert atanh(x).series(x, 0, 10) == \
x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
def test_atanh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: atanh(x).fdiff(2))
def test_acoth():
x = Symbol('x')
#at specific points
assert acoth(0) == I*pi/2
assert acoth(I) == -I*pi/4
assert acoth(-I) == I*pi/4
assert acoth(1) is oo
assert acoth(-1) is -oo
assert acoth(nan) is nan
# at infinites
assert acoth(oo) == 0
assert acoth(-oo) == 0
assert acoth(I*oo) == 0
assert acoth(-I*oo) == 0
assert acoth(zoo) == 0
#properties
assert acoth(-x) == -acoth(x)
assert acoth(I/sqrt(3)) == -I*pi/3
assert acoth(-I/sqrt(3)) == I*pi/3
assert acoth(I*sqrt(3)) == -I*pi/6
assert acoth(-I*sqrt(3)) == I*pi/6
assert acoth(I*(1 + sqrt(2))) == -pi*I/8
assert acoth(-I*(sqrt(2) + 1)) == pi*I/8
assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8)
assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8)
assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10
assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10
assert acoth(I*(2 + sqrt(3))) == -pi*I/12
assert acoth(-I*(2 + sqrt(3))) == pi*I/12
assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12)
assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12)
# Symmetry
assert acoth(Rational(-1, 2)) == -acoth(S.Half)
def test_acoth_rewrite():
x = Symbol('x')
assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2
def test_acoth_series():
x = Symbol('x')
assert acoth(x).series(x, 0, 10) == \
I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
def test_acoth_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: acoth(x).fdiff(2))
def test_inverses():
x = Symbol('x')
assert sinh(x).inverse() == asinh
raises(AttributeError, lambda: cosh(x).inverse())
assert tanh(x).inverse() == atanh
assert coth(x).inverse() == acoth
assert asinh(x).inverse() == sinh
assert acosh(x).inverse() == cosh
assert atanh(x).inverse() == tanh
assert acoth(x).inverse() == coth
assert asech(x).inverse() == sech
assert acsch(x).inverse() == csch
def test_leading_term():
x = Symbol('x')
assert cosh(x).as_leading_term(x) == 1
assert coth(x).as_leading_term(x) == 1/x
assert acosh(x).as_leading_term(x) == I*pi/2
assert acoth(x).as_leading_term(x) == I*pi/2
for func in [sinh, tanh, asinh, atanh]:
assert func(x).as_leading_term(x) == x
for func in [sinh, cosh, tanh, coth, asinh, acosh, atanh, acoth]:
for arg in (1/x, S.Half):
eq = func(arg)
assert eq.as_leading_term(x) == eq
for func in [csch, sech]:
eq = func(S.Half)
assert eq.as_leading_term(x) == eq
def test_complex():
a, b = symbols('a,b', real=True)
z = a + b*I
for func in [sinh, cosh, tanh, coth, sech, csch]:
assert func(z).conjugate() == func(a - b*I)
for deep in [True, False]:
assert sinh(z).expand(
complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b)
assert cosh(z).expand(
complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b)
assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2)
assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2)
assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\
*cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\
*cosh(a)**2 + cos(b)**2 * sinh(a)**2)
assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\
*sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\
*sinh(a)**2 + cos(b)**2 * cosh(a)**2)
def test_complex_2899():
a, b = symbols('a,b', real=True)
for deep in [True, False]:
for func in [sinh, cosh, tanh, coth]:
assert func(a).expand(complex=True, deep=deep) == func(a)
def test_simplifications():
x = Symbol('x')
assert sinh(asinh(x)) == x
assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1)
assert sinh(atanh(x)) == x/sqrt(1 - x**2)
assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
assert cosh(asinh(x)) == sqrt(1 + x**2)
assert cosh(acosh(x)) == x
assert cosh(atanh(x)) == 1/sqrt(1 - x**2)
assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
assert tanh(asinh(x)) == x/sqrt(1 + x**2)
assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x
assert tanh(atanh(x)) == x
assert tanh(acoth(x)) == 1/x
assert coth(asinh(x)) == sqrt(1 + x**2)/x
assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
assert coth(atanh(x)) == 1/x
assert coth(acoth(x)) == x
assert csch(asinh(x)) == 1/x
assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
assert csch(atanh(x)) == sqrt(1 - x**2)/x
assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)
assert sech(asinh(x)) == 1/sqrt(1 + x**2)
assert sech(acosh(x)) == 1/x
assert sech(atanh(x)) == sqrt(1 - x**2)
assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x
def test_issue_4136():
assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4)
def test_sinh_rewrite():
x = Symbol('x')
assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \
== sinh(x).rewrite('tractable')
assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2)
tanh_half = tanh(S.Half*x)
assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2)
coth_half = coth(S.Half*x)
assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1)
def test_cosh_rewrite():
x = Symbol('x')
assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \
== cosh(x).rewrite('tractable')
assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2)
tanh_half = tanh(S.Half*x)**2
assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half)
coth_half = coth(S.Half*x)**2
assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1)
def test_tanh_rewrite():
x = Symbol('x')
assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \
== tanh(x).rewrite('tractable')
assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x)
assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x)/cosh(x)
assert tanh(x).rewrite(coth) == 1/coth(x)
def test_coth_rewrite():
x = Symbol('x')
assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \
== coth(x).rewrite('tractable')
assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x)/sinh(x)
assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x)
assert coth(x).rewrite(tanh) == 1/tanh(x)
def test_csch_rewrite():
x = Symbol('x')
assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \
== csch(x).rewrite('tractable')
assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2)
tanh_half = tanh(S.Half*x)
assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half)
coth_half = coth(S.Half*x)
assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half)
def test_sech_rewrite():
x = Symbol('x')
assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \
== sech(x).rewrite('tractable')
assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2)
tanh_half = tanh(S.Half*x)**2
assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half)
coth_half = coth(S.Half*x)**2
assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1)
def test_derivs():
x = Symbol('x')
assert coth(x).diff(x) == -sinh(x)**(-2)
assert sinh(x).diff(x) == cosh(x)
assert cosh(x).diff(x) == sinh(x)
assert tanh(x).diff(x) == -tanh(x)**2 + 1
assert csch(x).diff(x) == -coth(x)*csch(x)
assert sech(x).diff(x) == -tanh(x)*sech(x)
assert acoth(x).diff(x) == 1/(-x**2 + 1)
assert asinh(x).diff(x) == 1/sqrt(x**2 + 1)
assert acosh(x).diff(x) == 1/sqrt(x**2 - 1)
assert atanh(x).diff(x) == 1/(-x**2 + 1)
assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2))
assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2)))
def test_sinh_expansion():
x, y = symbols('x,y')
assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y)
assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x)
assert sinh(3*x).expand(trig=True).expand() == \
sinh(x)**3 + 3*sinh(x)*cosh(x)**2
def test_cosh_expansion():
x, y = symbols('x,y')
assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y)
assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2
assert cosh(3*x).expand(trig=True).expand() == \
3*sinh(x)**2*cosh(x) + cosh(x)**3
def test_real_assumptions():
z = Symbol('z', real=False)
assert sinh(z).is_real is None
assert cosh(z).is_real is None
assert tanh(z).is_real is None
assert sech(z).is_real is None
assert csch(z).is_real is None
assert coth(z).is_real is None
def test_sign_assumptions():
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
assert sinh(n).is_negative is True
assert sinh(p).is_positive is True
assert cosh(n).is_positive is True
assert cosh(p).is_positive is True
assert tanh(n).is_negative is True
assert tanh(p).is_positive is True
assert csch(n).is_negative is True
assert csch(p).is_positive is True
assert sech(n).is_positive is True
assert sech(p).is_positive is True
assert coth(n).is_negative is True
assert coth(p).is_positive is True
|
bf863d57c2904e5988ea4aee124cb8d9d78bd587463ef2cd42567e1f5a4f269d | from sympy.functions import bspline_basis_set, interpolating_spline
from sympy.core.compatibility import range
from sympy import Piecewise, Interval, And
from sympy import symbols, Rational, S
from sympy.utilities.pytest import slow
x, y = symbols('x,y')
def test_basic_degree_0():
d = 0
knots = range(5)
splines = bspline_basis_set(d, knots, x)
for i in range(len(splines)):
assert splines[i] == Piecewise((1, Interval(i, i + 1).contains(x)),
(0, True))
def test_basic_degree_1():
d = 1
knots = range(5)
splines = bspline_basis_set(d, knots, x)
assert splines[0] == Piecewise((x, Interval(0, 1).contains(x)),
(2 - x, Interval(1, 2).contains(x)),
(0, True))
assert splines[1] == Piecewise((-1 + x, Interval(1, 2).contains(x)),
(3 - x, Interval(2, 3).contains(x)),
(0, True))
assert splines[2] == Piecewise((-2 + x, Interval(2, 3).contains(x)),
(4 - x, Interval(3, 4).contains(x)),
(0, True))
def test_basic_degree_2():
d = 2
knots = range(5)
splines = bspline_basis_set(d, knots, x)
b0 = Piecewise((x**2/2, Interval(0, 1).contains(x)),
(Rational(-3, 2) + 3*x - x**2, Interval(1, 2).contains(x)),
(Rational(9, 2) - 3*x + x**2/2, Interval(2, 3).contains(x)),
(0, True))
b1 = Piecewise((S.Half - x + x**2/2, Interval(1, 2).contains(x)),
(Rational(-11, 2) + 5*x - x**2, Interval(2, 3).contains(x)),
(8 - 4*x + x**2/2, Interval(3, 4).contains(x)),
(0, True))
assert splines[0] == b0
assert splines[1] == b1
def test_basic_degree_3():
d = 3
knots = range(5)
splines = bspline_basis_set(d, knots, x)
b0 = Piecewise(
(x**3/6, Interval(0, 1).contains(x)),
(Rational(2, 3) - 2*x + 2*x**2 - x**3/2, Interval(1, 2).contains(x)),
(Rational(-22, 3) + 10*x - 4*x**2 + x**3/2, Interval(2, 3).contains(x)),
(Rational(32, 3) - 8*x + 2*x**2 - x**3/6, Interval(3, 4).contains(x)),
(0, True)
)
assert splines[0] == b0
def test_repeated_degree_1():
d = 1
knots = [0, 0, 1, 2, 2, 3, 4, 4]
splines = bspline_basis_set(d, knots, x)
assert splines[0] == Piecewise((1 - x, Interval(0, 1).contains(x)),
(0, True))
assert splines[1] == Piecewise((x, Interval(0, 1).contains(x)),
(2 - x, Interval(1, 2).contains(x)),
(0, True))
assert splines[2] == Piecewise((-1 + x, Interval(1, 2).contains(x)),
(0, True))
assert splines[3] == Piecewise((3 - x, Interval(2, 3).contains(x)),
(0, True))
assert splines[4] == Piecewise((-2 + x, Interval(2, 3).contains(x)),
(4 - x, Interval(3, 4).contains(x)),
(0, True))
assert splines[5] == Piecewise((-3 + x, Interval(3, 4).contains(x)),
(0, True))
def test_repeated_degree_2():
d = 2
knots = [0, 0, 1, 2, 2, 3, 4, 4]
splines = bspline_basis_set(d, knots, x)
assert splines[0] == Piecewise(((-3*x**2/2 + 2*x), And(x <= 1, x >= 0)),
(x**2/2 - 2*x + 2, And(x <= 2, x >= 1)),
(0, True))
assert splines[1] == Piecewise((x**2/2, And(x <= 1, x >= 0)),
(-3*x**2/2 + 4*x - 2, And(x <= 2, x >= 1)),
(0, True))
assert splines[2] == Piecewise((x**2 - 2*x + 1, And(x <= 2, x >= 1)),
(x**2 - 6*x + 9, And(x <= 3, x >= 2)),
(0, True))
assert splines[3] == Piecewise((-3*x**2/2 + 8*x - 10, And(x <= 3, x >= 2)),
(x**2/2 - 4*x + 8, And(x <= 4, x >= 3)),
(0, True))
assert splines[4] == Piecewise((x**2/2 - 2*x + 2, And(x <= 3, x >= 2)),
(-3*x**2/2 + 10*x - 16, And(x <= 4, x >= 3)),
(0, True))
# Tests for interpolating_spline
def test_10_points_degree_1():
d = 1
X = [-5, 2, 3, 4, 7, 9, 10, 30, 31, 34]
Y = [-10, -2, 2, 4, 7, 6, 20, 45, 19, 25]
spline = interpolating_spline(d, x, X, Y)
assert spline == Piecewise((x*Rational(8, 7) - Rational(30, 7), (x >= -5) & (x <= 2)), (4*x - 10, (x >= 2) & (x <= 3)),
(2*x - 4, (x >= 3) & (x <= 4)), (x, (x >= 4) & (x <= 7)),
(-x/2 + Rational(21, 2), (x >= 7) & (x <= 9)), (14*x - 120, (x >= 9) & (x <= 10)),
(x*Rational(5, 4) + Rational(15, 2), (x >= 10) & (x <= 30)), (-26*x + 825, (x >= 30) & (x <= 31)),
(2*x - 43, (x >= 31) & (x <= 34)))
def test_3_points_degree_2():
d = 2
X = [-3, 10, 19]
Y = [3, -4, 30]
spline = interpolating_spline(d, x, X, Y)
assert spline == Piecewise((505*x**2/2574 - x*Rational(4921, 2574) - Rational(1931, 429), (x >= -3) & (x <= 19)))
def test_5_points_degree_2():
d = 2
X = [-3, 2, 4, 5, 10]
Y = [-1, 2, 5, 10, 14]
spline = interpolating_spline(d, x, X, Y)
assert spline == Piecewise((4*x**2/329 + x*Rational(1007, 1645) + Rational(1196, 1645), (x >= -3) & (x <= 3)),
(2701*x**2/1645 - x*Rational(15079, 1645) + Rational(5065, 329), (x >= 3) & (x <= Rational(9, 2))),
(-1319*x**2/1645 + x*Rational(21101, 1645) - Rational(11216, 329), (x >= Rational(9, 2)) & (x <= 10)))
@slow
def test_6_points_degree_3():
d = 3
X = [-1, 0, 2, 3, 9, 12]
Y = [-4, 3, 3, 7, 9, 20]
spline = interpolating_spline(d, x, X, Y)
assert spline == Piecewise((6058*x**3/5301 - 18427*x**2/5301 + x*Rational(12622, 5301) + 3, (x >= -1) & (x <= 2)),
(-8327*x**3/5301 + 67883*x**2/5301 - x*Rational(159998, 5301) + Rational(43661, 1767), (x >= 2) & (x <= 3)),
(5414*x**3/47709 - 1386*x**2/589 + x*Rational(4267, 279) - Rational(12232, 589), (x >= 3) & (x <= 12)))
|
0089a9263dfc4724f5874c87af5fa6799004ef497f767d08252808f56234aea4 | from sympy import (hyper, meijerg, S, Tuple, pi, I, exp, log, Rational,
cos, sqrt, symbols, oo, Derivative, gamma, O, appellf1)
from sympy.series.limits import limit
from sympy.abc import x, z, k
from sympy.utilities.pytest import raises, slow
from sympy.utilities.randtest 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 import polar_lift
assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \
hyper([z], [k], polar_lift(x))
def test_expand_func():
# evaluation at 1 of Gauss' hypergeometric function:
from sympy.abc import a, b, c
from sympy import gamma, 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 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 import RisingFactorial, factorial, Dummy, Sum
_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 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 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 import Piecewise, exp_polar
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 import besseli, exp_polar
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) == \
hyper((1,), (Rational(4, 3), Rational(5, 3)), 0) + \
9*k**2*hyper((2,), (Rational(7, 3), Rational(8, 3)), 0)/20 + \
81*k**4*hyper((3,), (Rational(10, 3), Rational(11, 3)), 0)/1120 + \
O(k**6) # issue 6350
assert limit(meijerg((), (), (1,), (0,), -x), x, 0) == \
meijerg(((), ()), ((1,), (0,)), 0) # issue 6052
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
def test_derivative_appellf1():
from sympy 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)
|
ecd3dbdde4746822022c2633011070044181a30d49964567dbfa11dc6397fce0 | from sympy import (
adjoint, conjugate, DiracDelta, Heaviside, nan, pi, sign, sqrt,
symbols, transpose, Symbol, Piecewise, I, S, Eq, Ne, oo,
SingularityFunction, signsimp
)
from sympy.utilities.pytest import raises, warns_deprecated_sympy
from sympy.core.function import ArgumentIndexError
x, y = symbols('x y')
i = symbols('t', nonzero=True)
j = symbols('j', positive=True)
k = symbols('k', negative=True)
def test_DiracDelta():
assert DiracDelta(1) == 0
assert DiracDelta(5.1) == 0
assert DiracDelta(-pi) == 0
assert DiracDelta(5, 7) == 0
assert DiracDelta(i) == 0
assert DiracDelta(j) == 0
assert DiracDelta(k) == 0
assert DiracDelta(nan) is nan
assert DiracDelta(0).func is DiracDelta
assert DiracDelta(x).func is DiracDelta
# FIXME: this is generally undefined @ x=0
# But then limit(Delta(c)*Heaviside(x),x,-oo)
# need's to be implemented.
# assert 0*DiracDelta(x) == 0
assert adjoint(DiracDelta(x)) == DiracDelta(x)
assert adjoint(DiracDelta(x - y)) == DiracDelta(x - y)
assert conjugate(DiracDelta(x)) == DiracDelta(x)
assert conjugate(DiracDelta(x - y)) == DiracDelta(x - y)
assert transpose(DiracDelta(x)) == DiracDelta(x)
assert transpose(DiracDelta(x - y)) == DiracDelta(x - y)
assert DiracDelta(x).diff(x) == DiracDelta(x, 1)
assert DiracDelta(x, 1).diff(x) == DiracDelta(x, 2)
assert DiracDelta(x).is_simple(x) is True
assert DiracDelta(3*x).is_simple(x) is True
assert DiracDelta(x**2).is_simple(x) is False
assert DiracDelta(sqrt(x)).is_simple(x) is False
assert DiracDelta(x).is_simple(y) is False
assert DiracDelta(x*y).expand(diracdelta=True, wrt=x) == DiracDelta(x)/abs(y)
assert DiracDelta(x*y).expand(diracdelta=True, wrt=y) == DiracDelta(y)/abs(x)
assert DiracDelta(x**2*y).expand(diracdelta=True, wrt=x) == DiracDelta(x**2*y)
assert DiracDelta(y).expand(diracdelta=True, wrt=x) == DiracDelta(y)
assert DiracDelta((x - 1)*(x - 2)*(x - 3)).expand(diracdelta=True, wrt=x) == (
DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2)
assert DiracDelta(2*x) != DiracDelta(x) # scaling property
assert DiracDelta(x) == DiracDelta(-x) # even function
assert DiracDelta(-x, 2) == DiracDelta(x, 2)
assert DiracDelta(-x, 1) == -DiracDelta(x, 1) # odd deriv is odd
assert DiracDelta(-oo*x) == DiracDelta(oo*x)
assert DiracDelta(x - y) != DiracDelta(y - x)
assert signsimp(DiracDelta(x - y) - DiracDelta(y - x)) == 0
with warns_deprecated_sympy():
assert DiracDelta(x*y).simplify(x) == DiracDelta(x)/abs(y)
with warns_deprecated_sympy():
assert DiracDelta(x*y).simplify(y) == DiracDelta(y)/abs(x)
with warns_deprecated_sympy():
assert DiracDelta(x**2*y).simplify(x) == DiracDelta(x**2*y)
with warns_deprecated_sympy():
assert DiracDelta(y).simplify(x) == DiracDelta(y)
with warns_deprecated_sympy():
assert DiracDelta((x - 1)*(x - 2)*(x - 3)).simplify(x) == (
DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2)
raises(ArgumentIndexError, lambda: DiracDelta(x).fdiff(2))
raises(ValueError, lambda: DiracDelta(x, -1))
raises(ValueError, lambda: DiracDelta(I))
raises(ValueError, lambda: DiracDelta(2 + 3*I))
def test_heaviside():
assert Heaviside(0).func == Heaviside
assert Heaviside(-5) == 0
assert Heaviside(1) == 1
assert Heaviside(nan) is nan
assert Heaviside(0, x) == x
assert Heaviside(0, nan) is nan
assert Heaviside(x, None) == Heaviside(x)
assert Heaviside(0, None) == Heaviside(0)
# we do not want None and Heaviside(0) in the args:
assert Heaviside(x, H0=None).args == (x,)
assert Heaviside(x, H0=Heaviside(0)).args == (x,)
assert adjoint(Heaviside(x)) == Heaviside(x)
assert adjoint(Heaviside(x - y)) == Heaviside(x - y)
assert conjugate(Heaviside(x)) == Heaviside(x)
assert conjugate(Heaviside(x - y)) == Heaviside(x - y)
assert transpose(Heaviside(x)) == Heaviside(x)
assert transpose(Heaviside(x - y)) == Heaviside(x - y)
assert Heaviside(x).diff(x) == DiracDelta(x)
assert Heaviside(x + I).is_Function is True
assert Heaviside(I*x).is_Function is True
raises(ArgumentIndexError, lambda: Heaviside(x).fdiff(2))
raises(ValueError, lambda: Heaviside(I))
raises(ValueError, lambda: Heaviside(2 + 3*I))
def test_rewrite():
x, y = Symbol('x', real=True), Symbol('y')
assert Heaviside(x).rewrite(Piecewise) == (
Piecewise((0, x < 0), (Heaviside(0), Eq(x, 0)), (1, x > 0)))
assert Heaviside(y).rewrite(Piecewise) == (
Piecewise((0, y < 0), (Heaviside(0), Eq(y, 0)), (1, y > 0)))
assert Heaviside(x, y).rewrite(Piecewise) == (
Piecewise((0, x < 0), (y, Eq(x, 0)), (1, x > 0)))
assert Heaviside(x, 0).rewrite(Piecewise) == (
Piecewise((0, x <= 0), (1, x > 0)))
assert Heaviside(x, 1).rewrite(Piecewise) == (
Piecewise((0, x < 0), (1, x >= 0)))
assert Heaviside(x).rewrite(sign) == \
Heaviside(x, H0=Heaviside(0)).rewrite(sign) == \
Piecewise(
(sign(x)/2 + S(1)/2, Eq(Heaviside(0), S(1)/2)),
(Piecewise(
(sign(x)/2 + S(1)/2, Ne(x, 0)), (Heaviside(0), True)), True)
)
assert Heaviside(y).rewrite(sign) == Heaviside(y)
assert Heaviside(x, S.Half).rewrite(sign) == (sign(x)+1)/2
assert Heaviside(x, y).rewrite(sign) == \
Piecewise(
(sign(x)/2 + S(1)/2, Eq(y, S(1)/2)),
(Piecewise(
(sign(x)/2 + S(1)/2, Ne(x, 0)), (y, True)), True)
)
assert DiracDelta(y).rewrite(Piecewise) == Piecewise((DiracDelta(0), Eq(y, 0)), (0, True))
assert DiracDelta(y, 1).rewrite(Piecewise) == DiracDelta(y, 1)
assert DiracDelta(x - 5).rewrite(Piecewise) == (
Piecewise((DiracDelta(0), Eq(x - 5, 0)), (0, True)))
assert (x*DiracDelta(x - 10)).rewrite(SingularityFunction) == x*SingularityFunction(x, 10, -1)
assert 5*x*y*DiracDelta(y, 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, 0, -2)
assert DiracDelta(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, -1)
assert DiracDelta(0, 1).rewrite(SingularityFunction) == SingularityFunction(0, 0, -2)
assert Heaviside(x).rewrite(SingularityFunction) == SingularityFunction(x, 0, 0)
assert 5*x*y*Heaviside(y + 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, -1, 0)
assert ((x - 3)**3*Heaviside(x - 3)).rewrite(SingularityFunction) == (x - 3)**3*SingularityFunction(x, 3, 0)
assert Heaviside(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, 0)
def test_issue_15923():
x = Symbol('x', real=True)
assert Heaviside(x).rewrite(Piecewise, H0=0) == (
Piecewise((0, x <= 0), (1, True)))
assert Heaviside(x).rewrite(Piecewise, H0=1) == (
Piecewise((0, x < 0), (1, True)))
assert Heaviside(x).rewrite(Piecewise, H0=S.Half) == (
Piecewise((0, x < 0), (S.Half, Eq(x, 0)), (1, x > 0)))
|
2692f5843c0786252641c0258bc9fd82041325f1fed270ac437aa3942903b15d | from sympy import (Symbol, zeta, nan, Rational, Float, pi, dirichlet_eta, log,
zoo, expand_func, polylog, lerchphi, S, exp, sqrt, I,
exp_polar, polar_lift, O, stieltjes, Abs, Sum, oo)
from sympy.core.function import ArgumentIndexError
from sympy.functions.combinatorial.numbers import bernoulli, factorial
from sympy.utilities.pytest import raises
from sympy.utilities.randtest import (test_derivative_numerically as td,
random_complex_number as randcplx, verify_numerically as tn)
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(2) == pi**2/6
assert zeta(4) == pi**4/90
assert zeta(6) == pi**6/945
assert zeta(2, 2) == pi**2/6 - 1
assert zeta(4, 3) == pi**4/90 - Rational(17, 16)
assert zeta(6, 4) == pi**6/945 - Rational(47449, 46656)
assert zeta(2, -2) == pi**2/6 + Rational(5, 4)
assert zeta(4, -3) == pi**4/90 + Rational(1393, 1296)
assert zeta(6, -4) == pi**6/945 + Rational(3037465, 2985984)
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(119, 12)
assert zeta(-1, -9) == Rational(539, 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, 0, 2) == \
zeta(x, 0) - x*a*zeta(x + 1, 0) + O(a**2)
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(2) == pi**2/12
assert dirichlet_eta(4) == pi**4*Rational(7, 720)
def test_rewriting():
assert dirichlet_eta(x).rewrite(zeta) == (1 - 2**(1 - x))*zeta(x)
assert zeta(x).rewrite(dirichlet_eta) == dirichlet_eta(x)/(1 - 2**(1 - x))
assert zeta(x).rewrite(dirichlet_eta, a=2) == zeta(x)
assert tn(dirichlet_eta(x), dirichlet_eta(x).rewrite(zeta), x)
assert tn(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 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():
from sympy import log
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_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():
from sympy.utilities.randtest import verify_numerically as tn
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 tn(polylog(s, z), polylog(s, z, evaluate=False), z,
a=-3, b=-2, c=S.Half, d=2)
assert tn(polylog(s, z), polylog(s, z, evaluate=False), z,
a=2, b=-2, c=5, d=2)
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', real=True)
b = Symbol('b', 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', positive=True, integer=True)
assert zeta(2*n) == (-1)**(n + 1)*2**(2*n - 1)*pi**(2*n)*bernoulli(2*n)/factorial(2*n)
assert zeta(-n) == (-1)**(-n)*bernoulli(n + 1)/(n + 1)
n = Symbol('n')
assert zeta(2*n) == zeta(2*n) # As sign of z (= 2*n) is not determined
|
fe8536cb9cd142df9ac8b1e2fc6a0ead1ddcb35f5a402359da01f9f2fa49337f | from itertools import product
from sympy import (jn, yn, symbols, Symbol, sin, cos, pi, S, jn_zeros, besselj,
bessely, besseli, besselk, hankel1, hankel2, hn1, hn2,
expand_func, sqrt, sinh, cosh, diff, series, gamma, hyper,
Abs, I, O, oo, conjugate, uppergamma, exp, Integral, Sum,
Rational)
from sympy.functions.special.bessel import fn
from sympy.functions.special.bessel import (airyai, airybi,
airyaiprime, airybiprime, marcumq)
from sympy.utilities.randtest import (random_complex_number as randcplx,
verify_numerically as tn,
test_derivative_numerically as td,
_randint)
from sympy.utilities.pytest import raises
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_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():
from sympy import polar_lift, exp, I
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():
from sympy import besselsimp, Symbol, exp, exp_polar, I
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))
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)
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
def test_fn():
x, z = symbols("x z")
assert fn(1, z) == 1/z**2
assert fn(2, z) == -1/z + 3/z**3
assert fn(3, z) == -6/z**2 + 15/z**4
assert fn(4, z) == 1/z - 45/z**3 + 105/z**5
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 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 x, y in zip(a, b):
if not (abs(x - y) < 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():
from sympy import I, Symbol
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_conjugate():
from sympy import conjugate, I, Symbol
n = Symbol('n')
z = Symbol('z', extended_real=False)
x = Symbol('x', extended_real=True)
y = Symbol('y', real=True, 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():
from sympy import exp_polar, polar_lift, Symbol, I, exp
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 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*x*Abs(y)/Abs(x))/2 + airyai(x + I*x*Abs(y)/Abs(x))/2,
I*x*(airyai(x - I*x*Abs(y)/Abs(x)) -
airyai(x + I*x*Abs(y)/Abs(x)))*Abs(y)/(2*y*Abs(x)))
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)
|
a87491bf3096f0e215fc71041c3d66e09a2ff7248cbd9fa699e94a3eeff71d25 | from sympy import (
nan, pi, symbols, DiracDelta, Symbol, diff,
Piecewise, I, Eq, Derivative, oo, SingularityFunction, Heaviside,
Float
)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.utilities.pytest import raises
x, y, a, n = symbols('x y a n')
def test_fdiff():
assert SingularityFunction(x, 4, 5).fdiff() == 5*SingularityFunction(x, 4, 4)
assert SingularityFunction(x, 4, -1).fdiff() == SingularityFunction(x, 4, -2)
assert SingularityFunction(x, 4, 0).fdiff() == SingularityFunction(x, 4, -1)
assert SingularityFunction(y, 6, 2).diff(y) == 2*SingularityFunction(y, 6, 1)
assert SingularityFunction(y, -4, -1).diff(y) == SingularityFunction(y, -4, -2)
assert SingularityFunction(y, 4, 0).diff(y) == SingularityFunction(y, 4, -1)
assert SingularityFunction(y, 4, 0).diff(y, 2) == SingularityFunction(y, 4, -2)
n = Symbol('n', positive=True)
assert SingularityFunction(x, a, n).fdiff() == n*SingularityFunction(x, a, n - 1)
assert SingularityFunction(y, a, n).diff(y) == n*SingularityFunction(y, a, n - 1)
expr_in = 4*SingularityFunction(x, a, n) + 3*SingularityFunction(x, a, -1) + -10*SingularityFunction(x, a, 0)
expr_out = n*4*SingularityFunction(x, a, n - 1) + 3*SingularityFunction(x, a, -2) - 10*SingularityFunction(x, a, -1)
assert diff(expr_in, x) == expr_out
assert SingularityFunction(x, -10, 5).diff(evaluate=False) == (
Derivative(SingularityFunction(x, -10, 5), x))
raises(ArgumentIndexError, lambda: SingularityFunction(x, 4, 5).fdiff(2))
def test_eval():
assert SingularityFunction(x, a, n).func == SingularityFunction
assert unchanged(SingularityFunction, x, 5, n)
assert SingularityFunction(5, 3, 2) == 4
assert SingularityFunction(3, 5, 1) == 0
assert SingularityFunction(3, 3, 0) == 1
assert SingularityFunction(4, 4, -1) is oo
assert SingularityFunction(4, 2, -1) == 0
assert SingularityFunction(4, 7, -1) == 0
assert SingularityFunction(5, 6, -2) == 0
assert SingularityFunction(4, 2, -2) == 0
assert SingularityFunction(4, 4, -2) is oo
assert (SingularityFunction(6.1, 4, 5)).evalf(5) == Float('40.841', '5')
assert SingularityFunction(6.1, pi, 2) == (-pi + 6.1)**2
assert SingularityFunction(x, a, nan) is nan
assert SingularityFunction(x, nan, 1) is nan
assert SingularityFunction(nan, a, n) is nan
raises(ValueError, lambda: SingularityFunction(x, a, I))
raises(ValueError, lambda: SingularityFunction(2*I, I, n))
raises(ValueError, lambda: SingularityFunction(x, a, -3))
def test_rewrite():
assert SingularityFunction(x, 4, 5).rewrite(Piecewise) == (
Piecewise(((x - 4)**5, x - 4 > 0), (0, True)))
assert SingularityFunction(x, -10, 0).rewrite(Piecewise) == (
Piecewise((1, x + 10 > 0), (0, True)))
assert SingularityFunction(x, 2, -1).rewrite(Piecewise) == (
Piecewise((oo, Eq(x - 2, 0)), (0, True)))
assert SingularityFunction(x, 0, -2).rewrite(Piecewise) == (
Piecewise((oo, Eq(x, 0)), (0, True)))
n = Symbol('n', nonnegative=True)
assert SingularityFunction(x, a, n).rewrite(Piecewise) == (
Piecewise(((x - a)**n, x - a > 0), (0, True)))
expr_in = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2)
expr_out = (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1)
assert expr_in.rewrite(Heaviside) == expr_out
assert expr_in.rewrite(DiracDelta) == expr_out
assert expr_in.rewrite('HeavisideDiracDelta') == expr_out
expr_in = SingularityFunction(x, a, n) + SingularityFunction(x, a, -1) - SingularityFunction(x, a, -2)
expr_out = (x - a)**n*Heaviside(x - a) + DiracDelta(x - a) + DiracDelta(a - x, 1)
assert expr_in.rewrite(Heaviside) == expr_out
assert expr_in.rewrite(DiracDelta) == expr_out
assert expr_in.rewrite('HeavisideDiracDelta') == expr_out
|
32cdc3dc243347fe0c956667aaba3f645714b801de56c037cddbf1ee9ef75805 | from sympy import (S, Symbol, pi, I, oo, zoo, sin, sqrt, tan, gamma,
atanh, hyper, meijerg, O, Rational)
from sympy.functions.special.elliptic_integrals import (elliptic_k as K,
elliptic_f as F, elliptic_e as E, elliptic_pi as P)
from sympy.utilities.randtest import (test_derivative_numerically as td,
random_complex_number as randcplx,
verify_numerically as tn)
from sympy.abc import z, m, n
i = Symbol('i', integer=True)
j = Symbol('k', integer=True, positive=True)
def test_K():
assert K(0) == pi/2
assert K(S.Half) == 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2
assert K(1) is zoo
assert K(-1) == gamma(Rational(1, 4))**2/(4*sqrt(2*pi))
assert K(oo) == 0
assert K(-oo) == 0
assert K(I*oo) == 0
assert K(-I*oo) == 0
assert K(zoo) == 0
assert K(z).diff(z) == (E(z) - (1 - z)*K(z))/(2*z*(1 - z))
assert td(K(z), z)
zi = Symbol('z', real=False)
assert K(zi).conjugate() == K(zi.conjugate())
zr = Symbol('z', real=True, negative=True)
assert K(zr).conjugate() == K(zr)
assert K(z).rewrite(hyper) == \
(pi/2)*hyper((S.Half, S.Half), (S.One,), z)
assert tn(K(z), (pi/2)*hyper((S.Half, S.Half), (S.One,), z))
assert K(z).rewrite(meijerg) == \
meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2
assert tn(K(z), meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2)
assert K(z).series(z) == pi/2 + pi*z/8 + 9*pi*z**2/128 + \
25*pi*z**3/512 + 1225*pi*z**4/32768 + 3969*pi*z**5/131072 + O(z**6)
def test_F():
assert F(z, 0) == z
assert F(0, m) == 0
assert F(pi*i/2, m) == i*K(m)
assert F(z, oo) == 0
assert F(z, -oo) == 0
assert F(-z, m) == -F(z, m)
assert F(z, m).diff(z) == 1/sqrt(1 - m*sin(z)**2)
assert F(z, m).diff(m) == E(z, m)/(2*m*(1 - m)) - F(z, m)/(2*m) - \
sin(2*z)/(4*(1 - m)*sqrt(1 - m*sin(z)**2))
r = randcplx()
assert td(F(z, r), z)
assert td(F(r, m), m)
mi = Symbol('m', real=False)
assert F(z, mi).conjugate() == F(z.conjugate(), mi.conjugate())
mr = Symbol('m', real=True, negative=True)
assert F(z, mr).conjugate() == F(z.conjugate(), mr)
assert F(z, m).series(z) == \
z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6)
def test_E():
assert E(z, 0) == z
assert E(0, m) == 0
assert E(i*pi/2, m) == i*E(m)
assert E(z, oo) is zoo
assert E(z, -oo) is zoo
assert E(0) == pi/2
assert E(1) == 1
assert E(oo) == I*oo
assert E(-oo) is oo
assert E(zoo) is zoo
assert E(-z, m) == -E(z, m)
assert E(z, m).diff(z) == sqrt(1 - m*sin(z)**2)
assert E(z, m).diff(m) == (E(z, m) - F(z, m))/(2*m)
assert E(z).diff(z) == (E(z) - K(z))/(2*z)
r = randcplx()
assert td(E(r, m), m)
assert td(E(z, r), z)
assert td(E(z), z)
mi = Symbol('m', real=False)
assert E(z, mi).conjugate() == E(z.conjugate(), mi.conjugate())
assert E(mi).conjugate() == E(mi.conjugate())
mr = Symbol('m', real=True, negative=True)
assert E(z, mr).conjugate() == E(z.conjugate(), mr)
assert E(mr).conjugate() == E(mr)
assert E(z).rewrite(hyper) == (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z)
assert tn(E(z), (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z))
assert E(z).rewrite(meijerg) == \
-meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4
assert tn(E(z), -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4)
assert E(z, m).series(z) == \
z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6)
assert E(z).series(z) == pi/2 - pi*z/8 - 3*pi*z**2/128 - \
5*pi*z**3/512 - 175*pi*z**4/32768 - 441*pi*z**5/131072 + O(z**6)
def test_P():
assert P(0, z, m) == F(z, m)
assert P(1, z, m) == F(z, m) + \
(sqrt(1 - m*sin(z)**2)*tan(z) - E(z, m))/(1 - m)
assert P(n, i*pi/2, m) == i*P(n, m)
assert P(n, z, 0) == atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1)
assert P(n, z, n) == F(z, n) - P(1, z, n) + tan(z)/sqrt(1 - n*sin(z)**2)
assert P(oo, z, m) == 0
assert P(-oo, z, m) == 0
assert P(n, z, oo) == 0
assert P(n, z, -oo) == 0
assert P(0, m) == K(m)
assert P(1, m) is zoo
assert P(n, 0) == pi/(2*sqrt(1 - n))
assert P(2, 1) is -oo
assert P(-1, 1) is oo
assert P(n, n) == E(n)/(1 - n)
assert P(n, -z, m) == -P(n, z, m)
ni, mi = Symbol('n', real=False), Symbol('m', real=False)
assert P(ni, z, mi).conjugate() == \
P(ni.conjugate(), z.conjugate(), mi.conjugate())
nr, mr = Symbol('n', real=True, negative=True), \
Symbol('m', real=True, negative=True)
assert P(nr, z, mr).conjugate() == P(nr, z.conjugate(), mr)
assert P(n, m).conjugate() == P(n.conjugate(), m.conjugate())
assert P(n, z, m).diff(n) == (E(z, m) + (m - n)*F(z, m)/n +
(n**2 - m)*P(n, z, m)/n - n*sqrt(1 -
m*sin(z)**2)*sin(2*z)/(2*(1 - n*sin(z)**2)))/(2*(m - n)*(n - 1))
assert P(n, z, m).diff(z) == 1/(sqrt(1 - m*sin(z)**2)*(1 - n*sin(z)**2))
assert P(n, z, m).diff(m) == (E(z, m)/(m - 1) + P(n, z, m) -
m*sin(2*z)/(2*(m - 1)*sqrt(1 - m*sin(z)**2)))/(2*(n - m))
assert P(n, m).diff(n) == (E(m) + (m - n)*K(m)/n +
(n**2 - m)*P(n, m)/n)/(2*(m - n)*(n - 1))
assert P(n, m).diff(m) == (E(m)/(m - 1) + P(n, m))/(2*(n - m))
rx, ry = randcplx(), randcplx()
assert td(P(n, rx, ry), n)
assert td(P(rx, z, ry), z)
assert td(P(rx, ry, m), m)
assert P(n, z, m).series(z) == z + z**3*(m/6 + n/3) + \
z**5*(3*m**2/40 + m*n/10 - m/30 + n**2/5 - n/15) + O(z**6)
|
a3e2ed97be58312c2701acf4d6fa0f69ec02a488ed301c50f2ddc21ec9c500ac | from sympy import (
Symbol, Dummy, diff, Derivative, Rational, roots, S, sqrt, hyper,
cos, gamma, conjugate, factorial, pi, oo, zoo, binomial, RisingFactorial,
legendre, assoc_legendre, chebyshevu, chebyshevt, chebyshevt_root,
chebyshevu_root, laguerre, assoc_laguerre, laguerre_poly, hermite,
gegenbauer, jacobi, jacobi_normalized, Sum, floor, exp)
from sympy.core.compatibility import range
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.utilities.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("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('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("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("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("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("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("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))
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("polynomial").dummy_eq(
Sum(x**_k*RisingFactorial(-n, _k)/factorial(_k)**2, (_k, 0, n)))
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('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))
|
e52e50d8cbd204dbd7f7bfca1016ca5cd08e1bf512879d0c03d8511d5291fe72 | from sympy import (
Symbol, Dummy, gamma, I, oo, nan, zoo, factorial, sqrt, Rational,
multigamma, log, polygamma, EulerGamma, pi, uppergamma, S, expand_func,
loggamma, sin, cos, O, lowergamma, exp, erf, erfc, exp_polar, harmonic,
zeta, conjugate, Ei, im, re, tanh, Abs)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.utilities.pytest import raises
from sympy.utilities.randtest 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 import I, pi, exp_polar
from 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 import meijerg, exp_polar, I, expint
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)*polygamma(0, 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(
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 import meijerg, exp_polar, I, expint
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():
from sympy import I
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(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
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:
from sympy import exp_polar
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)
# 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 None
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 None
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 polygamma(pi, 3).evalf() == polygamma(pi, 3)
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*sqrt(re(polygamma(I, 4))**2 + im(polygamma(I, 4))**2)\
/((re(polygamma(I, 4)) + I*im(polygamma(I, 4)))*Abs(polygamma(I, 4)))
assert unchanged(polygamma, 2.3, 1.0)
# 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
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
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))
from sympy import I
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)
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)
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, 3)
tN(3, 3)
tN(4, 5)
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**4)
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_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 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
|
24ed1de60117768d4e4a042fd762b4542f5628ab9709afc1ba8f0f6a0bdbe622 | from sympy import (
symbols, expand, expand_func, nan, oo, Float, conjugate, diff,
re, im, O, exp_polar, polar_lift, gruntz, limit,
Symbol, I, integrate, Integral, S,
sqrt, sin, cos, sinc, sinh, cosh, exp, log, pi, EulerGamma,
erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv,
gamma, uppergamma,
Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
fresnels, fresnelc,
hyper, meijerg, E, Rational)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.functions.special.error_functions import _erfs, _eis
from sympy.utilities.pytest import raises, slow
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) == 0
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).is_real is True
assert conjugate(erf(z)) == erf(conjugate(z))
assert erf(x).as_leading_term(x) == 2*x/sqrt(pi)
assert erf(1/x).as_leading_term(x) == erf(1/x)
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 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)
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) == 0
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).is_real is True
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) == erfc(1/x)
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)
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).is_real is True
assert conjugate(erfi(z)) == erfi(conjugate(z))
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)
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).is_real is True
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) == 0
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) == 0
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.utilities.randtest 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.utilities.randtest 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 import I, pi, exp_polar
from 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 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) - z**4/24 + \
z**5/240 + O(z**6)
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))
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 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) == 0
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) == 0
raises(ArgumentIndexError, lambda: li(z).fdiff(2))
def test_Li():
assert Li(2) == 0
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) == 0
assert Li(z).rewrite(li) == li(z) - li(2)
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))
t = Symbol('t', Dummy=True)
assert Si(x).rewrite(sinc) == Integral(sinc(t), (t, 0, x))
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) == 0
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)
from sympy import O, EulerGamma, log, limit
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 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) == 0
assert fresnels(oo) == 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) == 0
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.utilities.randtest 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
@slow
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
|
4aa97ca6b0f9630c6f7dbf910134dc675ceb58edfe8e2bd2976a5933773cb67a | from sympy.core.containers import Tuple
from sympy.core.function import (Function, Lambda, nfloat)
from sympy.core.mod import Mod
from sympy.core.numbers import (E, I, Rational, oo, pi)
from sympy.core.relational import (Eq, Gt,
Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (HyperbolicFunction,
atanh, sinh, tanh)
from sympy.functions.elementary.miscellaneous import sqrt, Min, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (
TrigonometricFunction, acos, acot, acsc, asec, asin, atan, atan2,
cos, cot, csc, sec, sin, tan)
from sympy.functions.special.error_functions import (erf, erfc,
erfcinv, erfinv)
from sympy.logic.boolalg import And
from sympy.matrices.dense import MutableDenseMatrix as Matrix
from sympy.polys.polytools import Poly
from sympy.polys.rootoftools import CRootOf
from sympy.sets.contains import Contains
from sympy.sets.conditionset import ConditionSet
from sympy.sets.fancysets import ImageSet
from sympy.sets.sets import (Complement, EmptySet, FiniteSet,
Intersection, Interval, Union, imageset)
from sympy.tensor.indexed import Indexed
from sympy.utilities.iterables import numbered_symbols
from sympy.utilities.pytest import XFAIL, raises, skip, slow, SKIP
from sympy.utilities.randtest import verify_numerically as tn
from sympy.physics.units import cm
from sympy.solvers.solveset import (
solveset_real, domain_check, solveset_complex, linear_eq_to_matrix,
linsolve, _is_function_class_equation, invert_real, invert_complex,
solveset, solve_decomposition, substitution, nonlinsolve, solvify,
_is_finite_with_finite_vars, _transolve, _is_exponential,
_solve_exponential, _is_logarithmic,
_solve_logarithm, _term_factors, _is_modular)
a = Symbol('a', real=True)
b = Symbol('b', real=True)
c = Symbol('c', real=True)
x = Symbol('x', real=True)
y = Symbol('y', real=True)
z = Symbol('z', real=True)
q = Symbol('q', real=True)
m = Symbol('m', real=True)
n = Symbol('n', real=True)
def test_invert_real():
x = Symbol('x', real=True)
y = Symbol('y')
n = Symbol('n')
def ireal(x, s=S.Reals):
return Intersection(s, x)
# issue 14223
assert invert_real(x, 0, x, Interval(1, 2)) == (x, S.EmptySet)
assert invert_real(exp(x), y, x) == (x, ireal(FiniteSet(log(y))))
y = Symbol('y', positive=True)
n = Symbol('n', real=True)
assert invert_real(x + 3, y, x) == (x, FiniteSet(y - 3))
assert invert_real(x*3, y, x) == (x, FiniteSet(y / 3))
assert invert_real(exp(x), y, x) == (x, FiniteSet(log(y)))
assert invert_real(exp(3*x), y, x) == (x, FiniteSet(log(y) / 3))
assert invert_real(exp(x + 3), y, x) == (x, FiniteSet(log(y) - 3))
assert invert_real(exp(x) + 3, y, x) == (x, ireal(FiniteSet(log(y - 3))))
assert invert_real(exp(x)*3, y, x) == (x, FiniteSet(log(y / 3)))
assert invert_real(log(x), y, x) == (x, FiniteSet(exp(y)))
assert invert_real(log(3*x), y, x) == (x, FiniteSet(exp(y) / 3))
assert invert_real(log(x + 3), y, x) == (x, FiniteSet(exp(y) - 3))
assert invert_real(Abs(x), y, x) == (x, FiniteSet(y, -y))
assert invert_real(2**x, y, x) == (x, FiniteSet(log(y)/log(2)))
assert invert_real(2**exp(x), y, x) == (x, ireal(FiniteSet(log(log(y)/log(2)))))
assert invert_real(x**2, y, x) == (x, FiniteSet(sqrt(y), -sqrt(y)))
assert invert_real(x**S.Half, y, x) == (x, FiniteSet(y**2))
raises(ValueError, lambda: invert_real(x, x, x))
raises(ValueError, lambda: invert_real(x**pi, y, x))
raises(ValueError, lambda: invert_real(S.One, y, x))
assert invert_real(x**31 + x, y, x) == (x**31 + x, FiniteSet(y))
lhs = x**31 + x
base_values = FiniteSet(y - 1, -y - 1)
assert invert_real(Abs(x**31 + x + 1), y, x) == (lhs, base_values)
assert invert_real(sin(x), y, x) == \
(x, imageset(Lambda(n, n*pi + (-1)**n*asin(y)), S.Integers))
assert invert_real(sin(exp(x)), y, x) == \
(x, imageset(Lambda(n, log((-1)**n*asin(y) + n*pi)), S.Integers))
assert invert_real(csc(x), y, x) == \
(x, imageset(Lambda(n, n*pi + (-1)**n*acsc(y)), S.Integers))
assert invert_real(csc(exp(x)), y, x) == \
(x, imageset(Lambda(n, log((-1)**n*acsc(y) + n*pi)), S.Integers))
assert invert_real(cos(x), y, x) == \
(x, Union(imageset(Lambda(n, 2*n*pi + acos(y)), S.Integers), \
imageset(Lambda(n, 2*n*pi - acos(y)), S.Integers)))
assert invert_real(cos(exp(x)), y, x) == \
(x, Union(imageset(Lambda(n, log(2*n*pi + acos(y))), S.Integers), \
imageset(Lambda(n, log(2*n*pi - acos(y))), S.Integers)))
assert invert_real(sec(x), y, x) == \
(x, Union(imageset(Lambda(n, 2*n*pi + asec(y)), S.Integers), \
imageset(Lambda(n, 2*n*pi - asec(y)), S.Integers)))
assert invert_real(sec(exp(x)), y, x) == \
(x, Union(imageset(Lambda(n, log(2*n*pi + asec(y))), S.Integers), \
imageset(Lambda(n, log(2*n*pi - asec(y))), S.Integers)))
assert invert_real(tan(x), y, x) == \
(x, imageset(Lambda(n, n*pi + atan(y)), S.Integers))
assert invert_real(tan(exp(x)), y, x) == \
(x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers))
assert invert_real(cot(x), y, x) == \
(x, imageset(Lambda(n, n*pi + acot(y)), S.Integers))
assert invert_real(cot(exp(x)), y, x) == \
(x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers))
assert invert_real(tan(tan(x)), y, x) == \
(tan(x), imageset(Lambda(n, n*pi + atan(y)), S.Integers))
x = Symbol('x', positive=True)
assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi)))
def test_invert_complex():
assert invert_complex(x + 3, y, x) == (x, FiniteSet(y - 3))
assert invert_complex(x*3, y, x) == (x, FiniteSet(y / 3))
assert invert_complex(exp(x), y, x) == \
(x, imageset(Lambda(n, I*(2*pi*n + arg(y)) + log(Abs(y))), S.Integers))
assert invert_complex(log(x), y, x) == (x, FiniteSet(exp(y)))
raises(ValueError, lambda: invert_real(1, y, x))
raises(ValueError, lambda: invert_complex(x, x, x))
raises(ValueError, lambda: invert_complex(x, x, 1))
# https://github.com/skirpichev/omg/issues/16
assert invert_complex(sinh(x), 0, x) != (x, FiniteSet(0))
def test_domain_check():
assert domain_check(1/(1 + (1/(x+1))**2), x, -1) is False
assert domain_check(x**2, x, 0) is True
assert domain_check(x, x, oo) is False
assert domain_check(0, x, oo) is False
def test_issue_11536():
assert solveset(0**x - 100, x, S.Reals) == S.EmptySet
assert solveset(0**x - 1, x, S.Reals) == FiniteSet(0)
def test_issue_17479():
import sympy as sb
from sympy.solvers.solveset import nonlinsolve
x, y, z = sb.symbols("x, y, z")
f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2)
fx = sb.diff(f, x)
fy = sb.diff(f, y)
fz = sb.diff(f, z)
sol = nonlinsolve([fx, fy, fz], [x, y, z])
# FIXME: This previously gave 18 solutions and now gives 20 due to fixes
# in the handling of intersection of FiniteSets or possibly a small change
# to ImageSet._contains. However Using expand I can turn this into 16
# solutions either way:
#
# >>> len(FiniteSet(*(Tuple(*(expand(w) for w in s)) for s in sol)))
# 16
#
assert len(sol) == 20
def test_is_function_class_equation():
from sympy.abc import x, a
assert _is_function_class_equation(TrigonometricFunction,
tan(x), x) is True
assert _is_function_class_equation(TrigonometricFunction,
tan(x) - 1, x) is True
assert _is_function_class_equation(TrigonometricFunction,
tan(x) + sin(x), x) is True
assert _is_function_class_equation(TrigonometricFunction,
tan(x) + sin(x) - a, x) is True
assert _is_function_class_equation(TrigonometricFunction,
sin(x)*tan(x) + sin(x), x) is True
assert _is_function_class_equation(TrigonometricFunction,
sin(x)*tan(x + a) + sin(x), x) is True
assert _is_function_class_equation(TrigonometricFunction,
sin(x)*tan(x*a) + sin(x), x) is True
assert _is_function_class_equation(TrigonometricFunction,
a*tan(x) - 1, x) is True
assert _is_function_class_equation(TrigonometricFunction,
tan(x)**2 + sin(x) - 1, x) is True
assert _is_function_class_equation(TrigonometricFunction,
tan(x) + x, x) is False
assert _is_function_class_equation(TrigonometricFunction,
tan(x**2), x) is False
assert _is_function_class_equation(TrigonometricFunction,
tan(x**2) + sin(x), x) is False
assert _is_function_class_equation(TrigonometricFunction,
tan(x)**sin(x), x) is False
assert _is_function_class_equation(TrigonometricFunction,
tan(sin(x)) + sin(x), x) is False
assert _is_function_class_equation(HyperbolicFunction,
tanh(x), x) is True
assert _is_function_class_equation(HyperbolicFunction,
tanh(x) - 1, x) is True
assert _is_function_class_equation(HyperbolicFunction,
tanh(x) + sinh(x), x) is True
assert _is_function_class_equation(HyperbolicFunction,
tanh(x) + sinh(x) - a, x) is True
assert _is_function_class_equation(HyperbolicFunction,
sinh(x)*tanh(x) + sinh(x), x) is True
assert _is_function_class_equation(HyperbolicFunction,
sinh(x)*tanh(x + a) + sinh(x), x) is True
assert _is_function_class_equation(HyperbolicFunction,
sinh(x)*tanh(x*a) + sinh(x), x) is True
assert _is_function_class_equation(HyperbolicFunction,
a*tanh(x) - 1, x) is True
assert _is_function_class_equation(HyperbolicFunction,
tanh(x)**2 + sinh(x) - 1, x) is True
assert _is_function_class_equation(HyperbolicFunction,
tanh(x) + x, x) is False
assert _is_function_class_equation(HyperbolicFunction,
tanh(x**2), x) is False
assert _is_function_class_equation(HyperbolicFunction,
tanh(x**2) + sinh(x), x) is False
assert _is_function_class_equation(HyperbolicFunction,
tanh(x)**sinh(x), x) is False
assert _is_function_class_equation(HyperbolicFunction,
tanh(sinh(x)) + sinh(x), x) is False
def test_garbage_input():
raises(ValueError, lambda: solveset_real([x], x))
assert solveset_real(x, 1) == S.EmptySet
assert solveset_real(x - 1, 1) == FiniteSet(x)
assert solveset_real(x, pi) == S.EmptySet
assert solveset_real(x, x**2) == S.EmptySet
raises(ValueError, lambda: solveset_complex([x], x))
assert solveset_complex(x, pi) == S.EmptySet
raises(ValueError, lambda: solveset((x, y), x))
raises(ValueError, lambda: solveset(x + 1, S.Reals))
raises(ValueError, lambda: solveset(x + 1, x, 2))
def test_solve_mul():
assert solveset_real((a*x + b)*(exp(x) - 3), x) == \
FiniteSet(-b/a, log(3))
assert solveset_real((2*x + 8)*(8 + exp(x)), x) == FiniteSet(S(-4))
assert solveset_real(x/log(x), x) == EmptySet()
def test_solve_invert():
assert solveset_real(exp(x) - 3, x) == FiniteSet(log(3))
assert solveset_real(log(x) - 3, x) == FiniteSet(exp(3))
assert solveset_real(3**(x + 2), x) == FiniteSet()
assert solveset_real(3**(2 - x), x) == FiniteSet()
assert solveset_real(y - b*exp(a/x), x) == Intersection(
S.Reals, FiniteSet(a/log(y/b)))
# issue 4504
assert solveset_real(2**x - 10, x) == FiniteSet(1 + log(5)/log(2))
def test_errorinverses():
assert solveset_real(erf(x) - S.Half, x) == \
FiniteSet(erfinv(S.Half))
assert solveset_real(erfinv(x) - 2, x) == \
FiniteSet(erf(2))
assert solveset_real(erfc(x) - S.One, x) == \
FiniteSet(erfcinv(S.One))
assert solveset_real(erfcinv(x) - 2, x) == FiniteSet(erfc(2))
def test_solve_polynomial():
assert solveset_real(3*x - 2, x) == FiniteSet(Rational(2, 3))
assert solveset_real(x**2 - 1, x) == FiniteSet(-S.One, S.One)
assert solveset_real(x - y**3, x) == FiniteSet(y ** 3)
a11, a12, a21, a22, b1, b2 = symbols('a11, a12, a21, a22, b1, b2')
assert solveset_real(x**3 - 15*x - 4, x) == FiniteSet(
-2 + 3 ** S.Half,
S(4),
-2 - 3 ** S.Half)
assert solveset_real(sqrt(x) - 1, x) == FiniteSet(1)
assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4)
assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16)
assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27)
assert len(solveset_real(x**5 + x**3 + 1, x)) == 1
assert len(solveset_real(-2*x**3 + 4*x**2 - 2*x + 6, x)) > 0
assert solveset_real(x**6 + x**4 + I, x) == ConditionSet(x,
Eq(x**6 + x**4 + I, 0), S.Reals)
def test_return_root_of():
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = list(solveset_complex(f, x))
for root in s:
assert root.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 CRootOf 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(list(solveset_complex(x**5 + 3*x**3 + 7, x))[0],
exponent=False) == CRootOf(x**5 + 3*x**3 + 7, 0).n()
sol = list(solveset_complex(x**6 - 2*x + 2, x))
assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = list(solveset_complex(f, x))
for root in s:
assert root.func == CRootOf
s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4)
assert solveset_complex(s, x) == \
FiniteSet(*Poly(s*4, domain='ZZ').all_roots())
# Refer issue #7876
eq = x*(x - 1)**2*(x + 1)*(x**6 - x + 1)
assert solveset_complex(eq, x) == \
FiniteSet(-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__has_rational_power():
from sympy.solvers.solveset import _has_rational_power
assert _has_rational_power(sqrt(2), x)[0] is False
assert _has_rational_power(x*sqrt(2), x)[0] is False
assert _has_rational_power(x**2*sqrt(x), x) == (True, 2)
assert _has_rational_power(sqrt(2)*x**Rational(1, 3), x) == (True, 3)
assert _has_rational_power(sqrt(x)*x**Rational(1, 3), x) == (True, 6)
def test_solveset_sqrt_1():
assert solveset_real(sqrt(5*x + 6) - 2 - x, x) == \
FiniteSet(-S.One, S(2))
assert solveset_real(sqrt(x - 1) - x + 7, x) == FiniteSet(10)
assert solveset_real(sqrt(x - 2) - 5, x) == FiniteSet(27)
assert solveset_real(sqrt(x) - 2 - 5, x) == FiniteSet(49)
assert solveset_real(sqrt(x**3), x) == FiniteSet(0)
assert solveset_real(sqrt(x - 1), x) == FiniteSet(1)
def test_solveset_sqrt_2():
# http://tutorial.math.lamar.edu/Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
assert solveset_real(sqrt(2*x - 1) - sqrt(x - 4) - 2, x) == \
FiniteSet(S(5), S(13))
assert solveset_real(sqrt(x + 7) + 2 - sqrt(3 - x), x) == \
FiniteSet(-6)
# http://www.purplemath.com/modules/solverad.htm
assert solveset_real(sqrt(17*x - sqrt(x**2 - 5)) - 7, x) == \
FiniteSet(3)
eq = x + 1 - (x**4 + 4*x**3 - x)**Rational(1, 4)
assert solveset_real(eq, x) == FiniteSet(Rational(-1, 2), Rational(-1, 3))
eq = sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)
assert solveset_real(eq, x) == FiniteSet(0)
eq = sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)
assert solveset_real(eq, x) == FiniteSet(5)
eq = sqrt(x)*sqrt(x - 7) - 12
assert solveset_real(eq, x) == FiniteSet(16)
eq = sqrt(x - 3) + sqrt(x) - 3
assert solveset_real(eq, x) == FiniteSet(4)
eq = sqrt(2*x**2 - 7) - (3 - x)
assert solveset_real(eq, x) == FiniteSet(-S(8), S(2))
# others
eq = sqrt(9*x**2 + 4) - (3*x + 2)
assert solveset_real(eq, x) == FiniteSet(0)
assert solveset_real(sqrt(x - 3) - sqrt(x) - 3, x) == FiniteSet()
eq = (2*x - 5)**Rational(1, 3) - 3
assert solveset_real(eq, x) == FiniteSet(16)
assert solveset_real(sqrt(x) + sqrt(sqrt(x)) - 4, x) == \
FiniteSet((Rational(-1, 2) + sqrt(17)/2)**4)
eq = sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))
assert solveset_real(eq, x) == FiniteSet()
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
ans = solveset_real(eq, x)
ra = S('''-1484/375 - 4*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 +
114*sqrt(12657)/78125)**(1/3) - 172564/(140625*(-1/2 +
sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3))''')
rb = Rational(4, 5)
assert all(abs(eq.subs(x, i).n()) < 1e-10 for i in (ra, rb)) and \
len(ans) == 2 and \
set([i.n(chop=True) for i in ans]) == \
set([i.n(chop=True) for i in (ra, rb)])
assert solveset_real(sqrt(x) + x**Rational(1, 3) +
x**Rational(1, 4), x) == FiniteSet(0)
assert solveset_real(x/sqrt(x**2 + 1), x) == FiniteSet(0)
eq = (x - y**3)/((y**2)*sqrt(1 - y**2))
assert solveset_real(eq, x) == FiniteSet(y**3)
# issue 4497
assert solveset_real(1/(5 + x)**Rational(1, 5) - 9, x) == \
FiniteSet(Rational(-295244, 59049))
@XFAIL
def test_solve_sqrt_fail():
# this only works if we check real_root(eq.subs(x, Rational(1, 3)))
# but checksol doesn't work like that
eq = (x**3 - 3*x**2)**Rational(1, 3) + 1 - x
assert solveset_real(eq, x) == FiniteSet(Rational(1, 3))
@slow
def test_solve_sqrt_3():
R = Symbol('R')
eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1)
sol = solveset_complex(eq, R)
fset = [Rational(5, 3) + 4*sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3,
-sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 +
40*re(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 +
sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 + Rational(5, 3) +
I*(-sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3 -
sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 +
40*im(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9)]
cset = [40*re(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 -
sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 - sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 +
Rational(5, 3) +
I*(40*im(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 -
sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 +
sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3)]
assert sol._args[0] == FiniteSet(*fset)
assert sol._args[1] == ConditionSet(
R,
Eq(sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1), 0),
FiniteSet(*cset))
# the number of real roots will depend on the value of m: for m=1 there are 4
# and for m=-1 there are none.
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)
unsolved_object = ConditionSet(q, 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), 0), S.Reals)
assert solveset_real(eq, q) == unsolved_object
def test_solve_polynomial_symbolic_param():
assert solveset_complex((x**2 - 1)**2 - a, x) == \
FiniteSet(sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)),
sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a)))
# issue 4507
assert solveset_complex(y - b/(1 + a*x), x) == \
FiniteSet((b/y - 1)/a) - FiniteSet(-1/a)
# issue 4508
assert solveset_complex(y - b*x/(a + x), x) == \
FiniteSet(-a*y/(y - b)) - FiniteSet(-a)
def test_solve_rational():
assert solveset_real(1/x + 1, x) == FiniteSet(-S.One)
assert solveset_real(1/exp(x) - 1, x) == FiniteSet(0)
assert solveset_real(x*(1 - 5/x), x) == FiniteSet(5)
assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2)
assert solveset_real((x**2/(7 - x)).diff(x), x) == \
FiniteSet(S.Zero, S(14))
def test_solveset_real_gen_is_pow():
assert solveset_real(sqrt(1) + 1, x) == EmptySet()
def test_no_sol():
assert solveset(1 - oo*x) == EmptySet()
assert solveset(oo*x, x) == EmptySet()
assert solveset(oo*x - oo, x) == EmptySet()
assert solveset_real(4, x) == EmptySet()
assert solveset_real(exp(x), x) == EmptySet()
assert solveset_real(x**2 + 1, x) == EmptySet()
assert solveset_real(-3*a/sqrt(x), x) == EmptySet()
assert solveset_real(1/x, x) == EmptySet()
assert solveset_real(-(1 + x)/(2 + x)**2 + 1/(2 + x), x) == \
EmptySet()
def test_sol_zero_real():
assert solveset_real(0, x) == S.Reals
assert solveset(0, x, Interval(1, 2)) == Interval(1, 2)
assert solveset_real(-x**2 - 2*x + (x + 1)**2 - 1, x) == S.Reals
def test_no_sol_rational_extragenous():
assert solveset_real((x/(x + 1) + 3)**(-2), x) == EmptySet()
assert solveset_real((x - 1)/(1 + 1/(x - 1)), x) == EmptySet()
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 solveset_real(sqrt(x) - 1, x) == FiniteSet(1)
assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4)
assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16)
assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27)
assert solveset_real(x*(x**(S.One / 3) - 3), x) == \
FiniteSet(S.Zero, S(27))
def test_solveset_real_rational():
"""Test solveset_real for rational functions"""
assert solveset_real((x - y**3) / ((y**2)*sqrt(1 - y**2)), x) \
== FiniteSet(y**3)
# issue 4486
assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2)
def test_solveset_real_log():
assert solveset_real(log((x-1)*(x+1)), x) == \
FiniteSet(sqrt(2), -sqrt(2))
def test_poly_gens():
assert solveset_real(4**(2*(x**2) + 2*x) - 8, x) == \
FiniteSet(Rational(-3, 2), S.Half)
def test_solve_abs():
x = Symbol('x')
n = Dummy('n')
raises(ValueError, lambda: solveset(Abs(x) - 1, x))
assert solveset(Abs(x) - n, x, S.Reals) == ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n})
assert solveset_real(Abs(x) - 2, x) == FiniteSet(-2, 2)
assert solveset_real(Abs(x) + 2, x) is S.EmptySet
assert solveset_real(Abs(x + 3) - 2*Abs(x - 3), x) == \
FiniteSet(1, 9)
assert solveset_real(2*Abs(x) - Abs(x - 1), x) == \
FiniteSet(-1, Rational(1, 3))
sol = ConditionSet(
x,
And(
Contains(b, Interval(0, oo)),
Contains(a + b, Interval(0, oo)),
Contains(a - b, Interval(0, oo))),
FiniteSet(-a - b - 3, -a + b - 3, a - b - 3, a + b - 3))
eq = Abs(Abs(x + 3) - a) - b
assert invert_real(eq, 0, x)[1] == sol
reps = {a: 3, b: 1}
eqab = eq.subs(reps)
for i in sol.subs(reps):
assert not eqab.subs(x, i)
assert solveset(Eq(sin(Abs(x)), 1), x, domain=S.Reals) == Union(
Intersection(Interval(0, oo),
ImageSet(Lambda(n, (-1)**n*pi/2 + n*pi), S.Integers)),
Intersection(Interval(-oo, 0),
ImageSet(Lambda(n, n*pi - (-1)**(-n)*pi/2), S.Integers)))
def test_issue_9565():
assert solveset_real(Abs((x - 1)/(x - 5)) <= Rational(1, 3), x) == Interval(-1, 2)
def test_issue_10069():
eq = abs(1/(x - 1)) - 1 > 0
u = Union(Interval.open(0, 1), Interval.open(1, 2))
assert solveset_real(eq, x) == u
@XFAIL
def test_rewrite_trigh():
# if this import passes then the test below should also pass
from sympy import sech
assert solveset_real(sinh(x) + sech(x), x) == FiniteSet(
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_real_imag_splitting():
a, b = symbols('a b', real=True)
assert solveset_real(sqrt(a**2 - b**2) - 3, a) == \
FiniteSet(-sqrt(b**2 + 9), sqrt(b**2 + 9))
assert solveset_real(sqrt(a**2 + b**2) - 3, a) != \
S.EmptySet
def test_units():
assert solveset_real(1/x - 1/(2*cm), x) == FiniteSet(2*cm)
def test_solve_only_exp_1():
y = Symbol('y', positive=True)
assert solveset_real(exp(x) - y, x) == FiniteSet(log(y))
assert solveset_real(exp(x) + exp(-x) - 4, x) == \
FiniteSet(log(-sqrt(3) + 2), log(sqrt(3) + 2))
assert solveset_real(exp(x) + exp(-x) - y, x) != S.EmptySet
def test_atan2():
# The .inverse() method on atan2 works only if x.is_real is True and the
# second argument is a real constant
assert solveset_real(atan2(x, 2) - pi/3, x) == FiniteSet(2*sqrt(3))
def test_piecewise_solveset():
eq = Piecewise((x - 2, Gt(x, 2)), (2 - x, True)) - 3
assert set(solveset_real(eq, x)) == set(FiniteSet(-1, 5))
absxm3 = Piecewise(
(x - 3, 0 <= x - 3),
(3 - x, 0 > x - 3))
y = Symbol('y', positive=True)
assert solveset_real(absxm3 - y, x) == FiniteSet(-y + 3, y + 3)
f = Piecewise(((x - 2)**2, x >= 0), (0, True))
assert solveset(f, x, domain=S.Reals) == Union(FiniteSet(2), Interval(-oo, 0, True, True))
assert solveset(
Piecewise((x + 1, x > 0), (I, True)) - I, x, S.Reals
) == Interval(-oo, 0)
assert solveset(Piecewise((x - 1, Ne(x, I)), (x, True)), x) == FiniteSet(1)
def test_solveset_complex_polynomial():
from sympy.abc import x, a, b, c
assert solveset_complex(a*x**2 + b*x + c, x) == \
FiniteSet(-b/(2*a) - sqrt(-4*a*c + b**2)/(2*a),
-b/(2*a) + sqrt(-4*a*c + b**2)/(2*a))
assert solveset_complex(x - y**3, y) == FiniteSet(
(-x**Rational(1, 3))/2 + I*sqrt(3)*x**Rational(1, 3)/2,
x**Rational(1, 3),
(-x**Rational(1, 3))/2 - I*sqrt(3)*x**Rational(1, 3)/2)
assert solveset_complex(x + 1/x - 1, x) == \
FiniteSet(S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2)
def test_sol_zero_complex():
assert solveset_complex(0, x) == S.Complexes
def test_solveset_complex_rational():
assert solveset_complex((x - 1)*(x - I)/(x - 3), x) == \
FiniteSet(1, I)
assert solveset_complex((x - y**3)/((y**2)*sqrt(1 - y**2)), x) == \
FiniteSet(y**3)
assert solveset_complex(-x**2 - I, x) == \
FiniteSet(-sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2)
def test_solve_quintics():
skip("This test is too slow")
f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979
s = solveset_complex(f, x)
for root in s:
res = f.subs(x, root.n()).n()
assert tn(res, 0)
f = x**5 + 15*x + 12
s = solveset_complex(f, x)
for root in s:
res = f.subs(x, root.n()).n()
assert tn(res, 0)
def test_solveset_complex_exp():
from sympy.abc import x, n
assert solveset_complex(exp(x) - 1, x) == \
imageset(Lambda(n, I*2*n*pi), S.Integers)
assert solveset_complex(exp(x) - I, x) == \
imageset(Lambda(n, I*(2*n*pi + pi/2)), S.Integers)
assert solveset_complex(1/exp(x), x) == S.EmptySet
assert solveset_complex(sinh(x).rewrite(exp), x) == \
imageset(Lambda(n, n*pi*I), S.Integers)
def test_solveset_real_exp():
from sympy.abc import x, y
assert solveset(Eq((-2)**x, 4), x, S.Reals) == FiniteSet(2)
assert solveset(Eq(-2**x, 4), x, S.Reals) == S.EmptySet
assert solveset(Eq((-3)**x, 27), x, S.Reals) == S.EmptySet
assert solveset(Eq((-5)**(x+1), 625), x, S.Reals) == FiniteSet(3)
assert solveset(Eq(2**(x-3), -16), x, S.Reals) == S.EmptySet
assert solveset(Eq((-3)**(x - 3), -3**39), x, S.Reals) == FiniteSet(42)
assert solveset(Eq(2**x, y), x, S.Reals) == Intersection(S.Reals, FiniteSet(log(y)/log(2)))
assert invert_real((-2)**(2*x) - 16, 0, x) == (x, FiniteSet(2))
def test_solve_complex_log():
assert solveset_complex(log(x), x) == FiniteSet(1)
assert solveset_complex(1 - log(a + 4*x**2), x) == \
FiniteSet(-sqrt(-a + E)/2, sqrt(-a + E)/2)
def test_solve_complex_sqrt():
assert solveset_complex(sqrt(5*x + 6) - 2 - x, x) == \
FiniteSet(-S.One, S(2))
assert solveset_complex(sqrt(5*x + 6) - (2 + 2*I) - x, x) == \
FiniteSet(-S(2), 3 - 4*I)
assert solveset_complex(4*x*(1 - a * sqrt(x)), x) == \
FiniteSet(S.Zero, 1 / a ** 2)
def test_solveset_complex_tan():
s = solveset_complex(tan(x).rewrite(exp), x)
assert s == imageset(Lambda(n, pi*n), S.Integers) - \
imageset(Lambda(n, pi*n + pi/2), S.Integers)
def test_solve_trig():
from sympy.abc import n
assert solveset_real(sin(x), x) == \
Union(imageset(Lambda(n, 2*pi*n), S.Integers),
imageset(Lambda(n, 2*pi*n + pi), S.Integers))
assert solveset_real(sin(x) - 1, x) == \
imageset(Lambda(n, 2*pi*n + pi/2), S.Integers)
assert solveset_real(cos(x), x) == \
Union(imageset(Lambda(n, 2*pi*n + pi/2), S.Integers),
imageset(Lambda(n, 2*pi*n + pi*Rational(3, 2)), S.Integers))
assert solveset_real(sin(x) + cos(x), x) == \
Union(imageset(Lambda(n, 2*n*pi + pi*Rational(3, 4)), S.Integers),
imageset(Lambda(n, 2*n*pi + pi*Rational(7, 4)), S.Integers))
assert solveset_real(sin(x)**2 + cos(x)**2, x) == S.EmptySet
assert solveset_complex(cos(x) - S.Half, x) == \
Union(imageset(Lambda(n, 2*n*pi + pi*Rational(5, 3)), S.Integers),
imageset(Lambda(n, 2*n*pi + pi/3), S.Integers))
y, a = symbols('y,a')
assert solveset(sin(y + a) - sin(y), a, domain=S.Reals) == \
Union(ImageSet(Lambda(n, 2*n*pi), S.Integers),
Intersection(ImageSet(Lambda(n, -I*(I*(
2*n*pi + arg(-exp(-2*I*y))) +
2*im(y))), S.Integers), S.Reals))
assert solveset_real(sin(2*x)*cos(x) + cos(2*x)*sin(x)-1, x) == \
ImageSet(Lambda(n, n*pi*Rational(2, 3) + pi/6), S.Integers)
# Tests for _solve_trig2() function
assert solveset_real(2*cos(x)*cos(2*x) - 1, x) == \
Union(ImageSet(Lambda(n, 2*n*pi + 2*atan(sqrt(-2*2**Rational(1, 3)*(67 +
9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 +
9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6)))), S.Integers),
ImageSet(Lambda(n, 2*n*pi - 2*atan(sqrt(-2*2**Rational(1, 3)*(67 +
9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 +
9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6))) +
2*pi), S.Integers))
assert solveset_real(2*tan(x)*sin(x) + 1, x) == Union(
ImageSet(Lambda(n, 2*n*pi + atan(sqrt(2)*sqrt(-1 +sqrt(17))/
(1 - sqrt(17))) + pi), S.Integers),
ImageSet(Lambda(n, 2*n*pi - atan(sqrt(2)*sqrt(-1 + sqrt(17))/
(1 - sqrt(17))) + pi), S.Integers))
assert solveset_real(cos(2*x)*cos(4*x) - 1, x) == \
ImageSet(Lambda(n, n*pi), S.Integers)
def test_solve_invalid_sol():
assert 0 not in solveset_real(sin(x)/x, x)
assert 0 not in solveset_complex((exp(x) - 1)/x, x)
@XFAIL
def test_solve_trig_simplified():
from sympy.abc import n
assert solveset_real(sin(x), x) == \
imageset(Lambda(n, n*pi), S.Integers)
assert solveset_real(cos(x), x) == \
imageset(Lambda(n, n*pi + pi/2), S.Integers)
assert solveset_real(cos(x) + sin(x), x) == \
imageset(Lambda(n, n*pi - pi/4), S.Integers)
@XFAIL
def test_solve_lambert():
assert solveset_real(x*exp(x) - 1, x) == FiniteSet(LambertW(1))
assert solveset_real(exp(x) + x, x) == FiniteSet(-LambertW(1))
assert solveset_real(x + 2**x, x) == \
FiniteSet(-LambertW(log(2))/log(2))
# issue 4739
ans = solveset_real(3*x + 5 + 2**(-5*x + 3), x)
assert ans == FiniteSet(Rational(-5, 3) +
LambertW(-10240*2**Rational(1, 3)*log(2)/3)/(5*log(2)))
eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9)
result = solveset_real(eq, x)
ans = FiniteSet((log(2401) +
5*LambertW(-log(7**(7*3**Rational(1, 5)/5))))/(3*log(7))/-1)
assert result == ans
assert solveset_real(eq.expand(), x) == result
assert solveset_real(5*x - 1 + 3*exp(2 - 7*x), x) == \
FiniteSet(Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7)
assert solveset_real(2*x + 5 + log(3*x - 2), x) == \
FiniteSet(Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2)
assert solveset_real(3*x + log(4*x), x) == \
FiniteSet(LambertW(Rational(3, 4))/3)
assert solveset_real(x**x - 2) == FiniteSet(exp(LambertW(log(2))))
a = Symbol('a')
assert solveset_real(-a*x + 2*x*log(x), x) == FiniteSet(exp(a/2))
a = Symbol('a', real=True)
assert solveset_real(a/x + exp(x/2), x) == \
FiniteSet(2*LambertW(-a/2))
assert solveset_real((a/x + exp(x/2)).diff(x), x) == \
FiniteSet(4*LambertW(sqrt(2)*sqrt(a)/4))
# coverage test
assert solveset_real(tanh(x + 3)*tanh(x - 3) - 1, x) == EmptySet()
assert solveset_real((x**2 - 2*x + 1).subs(x, log(x) + 3*x), x) == \
FiniteSet(LambertW(3*S.Exp1)/3)
assert solveset_real((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) == \
FiniteSet(LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3)
assert solveset_real((x**2 - 2*x - 2).subs(x, log(x) + 3*x), x) == \
FiniteSet(LambertW(3*exp(1 + sqrt(3)))/3, LambertW(3*exp(-sqrt(3) + 1))/3)
assert solveset_real(x*log(x) + 3*x + 1, x) == \
FiniteSet(exp(-3 + LambertW(-exp(3))))
eq = (x*exp(x) - 3).subs(x, x*exp(x))
assert solveset_real(eq, x) == \
FiniteSet(LambertW(3*exp(-LambertW(3))))
assert solveset_real(3*log(a**(3*x + 5)) + a**(3*x + 5), x) == \
FiniteSet(-((log(a**5) + LambertW(Rational(1, 3)))/(3*log(a))))
p = symbols('p', positive=True)
assert solveset_real(3*log(p**(3*x + 5)) + p**(3*x + 5), x) == \
FiniteSet(
log((-3**Rational(1, 3) - 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p),
log((-3**Rational(1, 3) + 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p),
log((3*LambertW(Rational(1, 3))/p**5)**(1/(3*log(p)))),) # checked numerically
# check collection
b = Symbol('b')
eq = 3*log(a**(3*x + 5)) + b*log(a**(3*x + 5)) + a**(3*x + 5)
assert solveset_real(eq, x) == FiniteSet(
-((log(a**5) + LambertW(1/(b + 3)))/(3*log(a))))
# issue 4271
assert solveset_real((a/x + exp(x/2)).diff(x, 2), x) == FiniteSet(
6*LambertW((-1)**Rational(1, 3)*a**Rational(1, 3)/3))
assert solveset_real(x**3 - 3**x, x) == \
FiniteSet(-3/log(3)*LambertW(-log(3)/3))
assert solveset_real(3**cos(x) - cos(x)**3) == FiniteSet(
acos(-3*LambertW(-log(3)/3)/log(3)))
assert solveset_real(x**2 - 2**x, x) == \
solveset_real(-x**2 + 2**x, x)
assert solveset_real(3*log(x) - x*log(3)) == FiniteSet(
-3*LambertW(-log(3)/3)/log(3),
-3*LambertW(-log(3)/3, -1)/log(3))
assert solveset_real(LambertW(2*x) - y) == FiniteSet(
y*exp(y)/2)
@XFAIL
def test_other_lambert():
a = Rational(6, 5)
assert solveset_real(x**a - a**x, x) == FiniteSet(
a, -a*LambertW(-log(a)/a)/log(a))
def test_solveset():
x = Symbol('x')
f = Function('f')
raises(ValueError, lambda: solveset(x + y))
assert solveset(x, 1) == S.EmptySet
assert solveset(f(1)**2 + y + 1, f(1)
) == FiniteSet(-sqrt(-y - 1), sqrt(-y - 1))
assert solveset(f(1)**2 - 1, f(1), S.Reals) == FiniteSet(-1, 1)
assert solveset(f(1)**2 + 1, f(1)) == FiniteSet(-I, I)
assert solveset(x - 1, 1) == FiniteSet(x)
assert solveset(sin(x) - cos(x), sin(x)) == FiniteSet(cos(x))
assert solveset(0, domain=S.Reals) == S.Reals
assert solveset(1) == S.EmptySet
assert solveset(True, domain=S.Reals) == S.Reals # issue 10197
assert solveset(False, domain=S.Reals) == S.EmptySet
assert solveset(exp(x) - 1, domain=S.Reals) == FiniteSet(0)
assert solveset(exp(x) - 1, x, S.Reals) == FiniteSet(0)
assert solveset(Eq(exp(x), 1), x, S.Reals) == FiniteSet(0)
assert solveset(exp(x) - 1, exp(x), S.Reals) == FiniteSet(1)
A = Indexed('A', x)
assert solveset(A - 1, A, S.Reals) == FiniteSet(1)
assert solveset(x - 1 >= 0, x, S.Reals) == Interval(1, oo)
assert solveset(exp(x) - 1 >= 0, x, S.Reals) == Interval(0, oo)
assert solveset(exp(x) - 1, x) == imageset(Lambda(n, 2*I*pi*n), S.Integers)
assert solveset(Eq(exp(x), 1), x) == imageset(Lambda(n, 2*I*pi*n),
S.Integers)
# issue 13825
assert solveset(x**2 + f(0) + 1, x) == {-sqrt(-f(0) - 1), sqrt(-f(0) - 1)}
def test_conditionset():
assert solveset(Eq(sin(x)**2 + cos(x)**2, 1), x, domain=S.Reals) == \
ConditionSet(x, True, S.Reals)
assert solveset(Eq(x**2 + x*sin(x), 1), x, domain=S.Reals
) == ConditionSet(x, Eq(x**2 + x*sin(x) - 1, 0), S.Reals)
assert solveset(Eq(-I*(exp(I*x) - exp(-I*x))/2, 1), x
) == imageset(Lambda(n, 2*n*pi + pi/2), S.Integers)
assert solveset(x + sin(x) > 1, x, domain=S.Reals
) == ConditionSet(x, x + sin(x) > 1, S.Reals)
assert solveset(Eq(sin(Abs(x)), x), x, domain=S.Reals
) == ConditionSet(x, Eq(-x + sin(Abs(x)), 0), S.Reals)
assert solveset(y**x-z, x, S.Reals) == \
ConditionSet(x, Eq(y**x - z, 0), S.Reals)
@XFAIL
def test_conditionset_equality():
''' Checking equality of different representations of ConditionSet'''
assert solveset(Eq(tan(x), y), x) == ConditionSet(x, Eq(tan(x), y), S.Complexes)
def test_solveset_domain():
x = Symbol('x')
assert solveset(x**2 - x - 6, x, Interval(0, oo)) == FiniteSet(3)
assert solveset(x**2 - 1, x, Interval(0, oo)) == FiniteSet(1)
assert solveset(x**4 - 16, x, Interval(0, 10)) == FiniteSet(2)
def test_improve_coverage():
from sympy.solvers.solveset import _has_rational_power
x = Symbol('x')
solution = solveset(exp(x) + sin(x), x, S.Reals)
unsolved_object = ConditionSet(x, Eq(exp(x) + sin(x), 0), S.Reals)
assert solution == unsolved_object
assert _has_rational_power(sin(x)*exp(x) + 1, x) == (False, S.One)
assert _has_rational_power((sin(x)**2)*(exp(x) + 1)**3, x) == (False, S.One)
def test_issue_9522():
x = Symbol('x')
expr1 = Eq(1/(x**2 - 4) + x, 1/(x**2 - 4) + 2)
expr2 = Eq(1/x + x, 1/x)
assert solveset(expr1, x, S.Reals) == EmptySet()
assert solveset(expr2, x, S.Reals) == EmptySet()
def test_solvify():
x = Symbol('x')
assert solvify(x**2 + 10, x, S.Reals) == []
assert solvify(x**3 + 1, x, S.Complexes) == [-1, S.Half - sqrt(3)*I/2,
S.Half + sqrt(3)*I/2]
assert solvify(log(x), x, S.Reals) == [1]
assert solvify(cos(x), x, S.Reals) == [pi/2, pi*Rational(3, 2)]
assert solvify(sin(x) + 1, x, S.Reals) == [pi*Rational(3, 2)]
raises(NotImplementedError, lambda: solvify(sin(exp(x)), x, S.Complexes))
def test_abs_invert_solvify():
assert solvify(sin(Abs(x)), x, S.Reals) is None
def test_linear_eq_to_matrix():
x, y, z = symbols('x, y, z')
a, b, c, d, e, f, g, h, i, j, k, l = symbols('a:l')
eqns1 = [2*x + y - 2*z - 3, x - y - z, x + y + 3*z - 12]
eqns2 = [Eq(3*x + 2*y - z, 1), Eq(2*x - 2*y + 4*z, -2), -2*x + y - 2*z]
A, B = linear_eq_to_matrix(eqns1, x, y, z)
assert A == Matrix([[2, 1, -2], [1, -1, -1], [1, 1, 3]])
assert B == Matrix([[3], [0], [12]])
A, B = linear_eq_to_matrix(eqns2, x, y, z)
assert A == Matrix([[3, 2, -1], [2, -2, 4], [-2, 1, -2]])
assert B == Matrix([[1], [-2], [0]])
# Pure symbolic coefficients
eqns3 = [a*b*x + b*y + c*z - d, e*x + d*x + f*y + g*z - h, i*x + j*y + k*z - l]
A, B = linear_eq_to_matrix(eqns3, x, y, z)
assert A == Matrix([[a*b, b, c], [d + e, f, g], [i, j, k]])
assert B == Matrix([[d], [h], [l]])
# raise ValueError if
# 1) no symbols are given
raises(ValueError, lambda: linear_eq_to_matrix(eqns3))
# 2) there are duplicates
raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, x, y]))
# 3) there are non-symbols
raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, 1/a, y]))
# 4) a nonlinear term is detected in the original expression
raises(ValueError, lambda: linear_eq_to_matrix(Eq(1/x + x, 1/x)))
assert linear_eq_to_matrix(1, x) == (Matrix([[0]]), Matrix([[-1]]))
# issue 15195
assert linear_eq_to_matrix(x + y*(z*(3*x + 2) + 3), x) == (
Matrix([[3*y*z + 1]]), Matrix([[-y*(2*z + 3)]]))
assert linear_eq_to_matrix(Matrix(
[[a*x + b*y - 7], [5*x + 6*y - c]]), x, y) == (
Matrix([[a, b], [5, 6]]), Matrix([[7], [c]]))
# issue 15312
assert linear_eq_to_matrix(Eq(x + 2, 1), x) == (
Matrix([[1]]), Matrix([[-1]]))
def test_issue_16577():
assert linear_eq_to_matrix(Eq(a*(2*x + 3*y) + 4*y, 5), x, y) == (
Matrix([[2*a, 3*a + 4]]), Matrix([[5]]))
def test_linsolve():
x, y, z, u, v, w = symbols("x, y, z, u, v, w")
x1, x2, x3, x4 = symbols('x1, x2, x3, x4')
# Test for different input forms
M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
system1 = A, b = M[:, :-1], M[:, -1]
Eqns = [x1 + 2*x2 + x3 + x4 - 7, x1 + 2*x2 + 2*x3 - x4 - 12,
2*x1 + 4*x2 + 6*x4 - 4]
sol = FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4))
assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
assert linsolve(Eqns, *(x1, x2, x3, x4)) == sol
assert linsolve(system1, (x1, x2, x3, x4)) == sol
assert linsolve(system1, *(x1, x2, x3, x4)) == sol
# issue 9667 - symbols can be Dummy symbols
x1, x2, x3, x4 = symbols('x:4', cls=Dummy)
assert linsolve(system1, x1, x2, x3, x4) == FiniteSet(
(-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4))
# raise ValueError for garbage value
raises(ValueError, lambda: linsolve(Eqns))
raises(ValueError, lambda: linsolve(x1))
raises(ValueError, lambda: linsolve(x1, x2))
raises(ValueError, lambda: linsolve((A,), x1, x2))
raises(ValueError, lambda: linsolve(A, b, x1, x2))
#raise ValueError if equations are non-linear in given variables
raises(ValueError, lambda: linsolve([x + y - 1, x ** 2 + y - 3], [x, y]))
raises(ValueError, lambda: linsolve([cos(x) + y, x + y], [x, y]))
assert linsolve([x + z - 1, x ** 2 + y - 3], [z, y]) == {(-x + 1, -x**2 + 3)}
# Fully symbolic test
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
A = Matrix([[a, b], [c, d]])
B = Matrix([[e], [f]])
system2 = (A, B)
sol = FiniteSet(((-b*f + d*e)/(a*d - b*c), (a*f - c*e)/(a*d - b*c)))
assert linsolve(system2, [x, y]) == sol
# No solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 1])
assert linsolve((A, b), (x, y, z)) == EmptySet()
# Issue #10056
A, B, J1, J2 = symbols('A B J1 J2')
Augmatrix = Matrix([
[2*I*J1, 2*I*J2, -2/J1],
[-2*I*J2, -2*I*J1, 2/J2],
[0, 2, 2*I/(J1*J2)],
[2, 0, 0],
])
assert linsolve(Augmatrix, A, B) == FiniteSet((0, I/(J1*J2)))
# Issue #10121 - Assignment of free variables
a, b, c, d, e = symbols('a, b, c, d, e')
Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
raises(IndexError, lambda: linsolve(Augmatrix, a, b, c))
x0, x1, x2, _x0 = symbols('tau0 tau1 tau2 _tau0')
assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]])
) == FiniteSet((x0, 0, x1, _x0, x2))
x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau0')
assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]])
) == FiniteSet((x0, 0, x1, _x0, x2))
x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau1')
assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]])
) == FiniteSet((x0, 0, x1, _x0, x2))
# symbols can be given as generators
x0, x2, x4 = symbols('x0, x2, x4')
assert linsolve(Augmatrix, numbered_symbols('x')
) == FiniteSet((x0, 0, x2, 0, x4))
Augmatrix[-1, -1] = x0
# use Dummy to avoid clash; the names may clash but the symbols
# will not
Augmatrix[-1, -1] = symbols('_x0')
assert len(linsolve(
Augmatrix, numbered_symbols('x', cls=Dummy)).free_symbols) == 4
# Issue #12604
f = Function('f')
assert linsolve([f(x) - 5], f(x)) == FiniteSet((5,))
# Issue #14860
from sympy.physics.units import meter, newton, kilo
Eqns = [8*kilo*newton + x + y, 28*kilo*newton*meter + 3*x*meter]
assert linsolve(Eqns, x, y) == {(newton*Rational(-28000, 3), newton*Rational(4000, 3))}
# linsolve fully expands expressions, so removable singularities
# and other nonlinearity does not raise an error
assert linsolve([Eq(x, x + y)], [x, y]) == {(x, 0)}
assert linsolve([Eq(1/x, 1/x + y)], [x, y]) == {(x, 0)}
assert linsolve([Eq(y/x, y/x + y)], [x, y]) == {(x, 0)}
assert linsolve([Eq(x*(x + 1), x**2 + y)], [x, y]) == {(y, y)}
def test_solve_decomposition():
x = Symbol('x')
n = Dummy('n')
f1 = exp(3*x) - 6*exp(2*x) + 11*exp(x) - 6
f2 = sin(x)**2 - 2*sin(x) + 1
f3 = sin(x)**2 - sin(x)
f4 = sin(x + 1)
f5 = exp(x + 2) - 1
f6 = 1/log(x)
f7 = 1/x
s1 = ImageSet(Lambda(n, 2*n*pi), S.Integers)
s2 = ImageSet(Lambda(n, 2*n*pi + pi), S.Integers)
s3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers)
s4 = ImageSet(Lambda(n, 2*n*pi - 1), S.Integers)
s5 = ImageSet(Lambda(n, 2*n*pi - 1 + pi), S.Integers)
assert solve_decomposition(f1, x, S.Reals) == FiniteSet(0, log(2), log(3))
assert solve_decomposition(f2, x, S.Reals) == s3
assert solve_decomposition(f3, x, S.Reals) == Union(s1, s2, s3)
assert solve_decomposition(f4, x, S.Reals) == Union(s4, s5)
assert solve_decomposition(f5, x, S.Reals) == FiniteSet(-2)
assert solve_decomposition(f6, x, S.Reals) == S.EmptySet
assert solve_decomposition(f7, x, S.Reals) == S.EmptySet
assert solve_decomposition(x, x, Interval(1, 2)) == S.EmptySet
# nonlinsolve testcases
def test_nonlinsolve_basic():
assert nonlinsolve([],[]) == S.EmptySet
assert nonlinsolve([],[x, y]) == S.EmptySet
system = [x, y - x - 5]
assert nonlinsolve([x],[x, y]) == FiniteSet((0, y))
assert nonlinsolve(system, [y]) == FiniteSet((x + 5,))
soln = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),)
assert nonlinsolve([sin(x) - 1], [x]) == FiniteSet(tuple(soln))
assert nonlinsolve([x**2 - 1], [x]) == FiniteSet((-1,), (1,))
soln = FiniteSet((y, y))
assert nonlinsolve([x - y, 0], x, y) == soln
assert nonlinsolve([0, x - y], x, y) == soln
assert nonlinsolve([x - y, x - y], x, y) == soln
assert nonlinsolve([x, 0], x, y) == FiniteSet((0, y))
f = Function('f')
assert nonlinsolve([f(x), 0], f(x), y) == FiniteSet((0, y))
assert nonlinsolve([f(x), 0], f(x), f(y)) == FiniteSet((0, f(y)))
A = Indexed('A', x)
assert nonlinsolve([A, 0], A, y) == FiniteSet((0, y))
assert nonlinsolve([x**2 -1], [sin(x)]) == FiniteSet((S.EmptySet,))
assert nonlinsolve([x**2 -1], sin(x)) == FiniteSet((S.EmptySet,))
assert nonlinsolve([x**2 -1], 1) == FiniteSet((x**2,))
assert nonlinsolve([x**2 -1], x + y) == FiniteSet((S.EmptySet,))
def test_nonlinsolve_abs():
soln = FiniteSet((x, Abs(x)))
assert nonlinsolve([Abs(x) - y], x, y) == soln
def test_raise_exception_nonlinsolve():
raises(IndexError, lambda: nonlinsolve([x**2 -1], []))
raises(ValueError, lambda: nonlinsolve([x**2 -1]))
raises(NotImplementedError, lambda: nonlinsolve([(x+y)**2 - 9, x**2 - y**2 - 0.75], (x, y)))
def test_trig_system():
# TODO: add more simple testcases when solveset returns
# simplified soln for Trig eq
assert nonlinsolve([sin(x) - 1, cos(x) -1 ], x) == S.EmptySet
soln1 = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),)
soln = FiniteSet(soln1)
assert nonlinsolve([sin(x) - 1, cos(x)], x) == soln
@XFAIL
def test_trig_system_fail():
# fails because solveset trig solver is not much smart.
sys = [x + y - pi/2, sin(x) + sin(y) - 1]
# solveset returns conditionset for sin(x) + sin(y) - 1
soln_1 = (ImageSet(Lambda(n, n*pi + pi/2), S.Integers),
ImageSet(Lambda(n, n*pi)), S.Integers)
soln_1 = FiniteSet(soln_1)
soln_2 = (ImageSet(Lambda(n, n*pi), S.Integers),
ImageSet(Lambda(n, n*pi+ pi/2), S.Integers))
soln_2 = FiniteSet(soln_2)
soln = soln_1 + soln_2
assert nonlinsolve(sys, [x, y]) == soln
# Add more cases from here
# http://www.vitutor.com/geometry/trigonometry/equations_systems.html#uno
sys = [sin(x) + sin(y) - (sqrt(3)+1)/2, sin(x) - sin(y) - (sqrt(3) - 1)/2]
soln_x = Union(ImageSet(Lambda(n, 2*n*pi + pi/3), S.Integers),
ImageSet(Lambda(n, 2*n*pi + pi*Rational(2, 3)), S.Integers))
soln_y = Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers),
ImageSet(Lambda(n, 2*n*pi + pi*Rational(5, 6)), S.Integers))
assert nonlinsolve(sys, [x, y]) ==FiniteSet((soln_x, soln_y))
def test_nonlinsolve_positive_dimensional():
x, y, z, a, b, c, d = symbols('x, y, z, a, b, c, d', extended_real = True)
assert nonlinsolve([x*y, x*y - x], [x, y]) == FiniteSet((0, y))
system = [a**2 + a*c, a - b]
assert nonlinsolve(system, [a, b]) == FiniteSet((0, 0), (-c, -c))
# here (a= 0, b = 0) is independent soln so both is printed.
# if symbols = [a, b, c] then only {a : -c ,b : -c}
eq1 = a + b + c + d
eq2 = a*b + b*c + c*d + d*a
eq3 = a*b*c + b*c*d + c*d*a + d*a*b
eq4 = a*b*c*d - 1
system = [eq1, eq2, eq3, eq4]
sol1 = (-1/d, -d, 1/d, FiniteSet(d) - FiniteSet(0))
sol2 = (1/d, -d, -1/d, FiniteSet(d) - FiniteSet(0))
soln = FiniteSet(sol1, sol2)
assert nonlinsolve(system, [a, b, c, d]) == soln
def test_nonlinsolve_polysys():
x, y, z = symbols('x, y, z', real = True)
assert nonlinsolve([x**2 + y - 2, x**2 + y], [x, y]) == S.EmptySet
s = (-y + 2, y)
assert nonlinsolve([(x + y)**2 - 4, x + y - 2], [x, y]) == FiniteSet(s)
system = [x**2 - y**2]
soln_real = FiniteSet((-y, y), (y, y))
soln_complex = FiniteSet((-Abs(y), y), (Abs(y), y))
soln =soln_real + soln_complex
assert nonlinsolve(system, [x, y]) == soln
system = [x**2 - y**2]
soln_real= FiniteSet((y, -y), (y, y))
soln_complex = FiniteSet((y, -Abs(y)), (y, Abs(y)))
soln = soln_real + soln_complex
assert nonlinsolve(system, [y, x]) == soln
system = [x**2 + y - 3, x - y - 4]
assert nonlinsolve(system, (x, y)) != nonlinsolve(system, (y, x))
def test_nonlinsolve_using_substitution():
x, y, z, n = symbols('x, y, z, n', real = True)
system = [(x + y)*n - y**2 + 2]
s_x = (n*y - y**2 + 2)/n
soln = (-s_x, y)
assert nonlinsolve(system, [x, y]) == FiniteSet(soln)
system = [z**2*x**2 - z**2*y**2/exp(x)]
soln_real_1 = (y, x, 0)
soln_real_2 = (-exp(x/2)*Abs(x), x, z)
soln_real_3 = (exp(x/2)*Abs(x), x, z)
soln_complex_1 = (-x*exp(x/2), x, z)
soln_complex_2 = (x*exp(x/2), x, z)
syms = [y, x, z]
soln = FiniteSet(soln_real_1, soln_complex_1, soln_complex_2,\
soln_real_2, soln_real_3)
assert nonlinsolve(system,syms) == soln
def test_nonlinsolve_complex():
x, y, z = symbols('x, y, z')
n = Dummy('n')
assert nonlinsolve([exp(x) - sin(y), 1/y - 3], [x, y]) == {
(ImageSet(Lambda(n, 2*n*I*pi + log(sin(Rational(1, 3)))), S.Integers), Rational(1, 3))}
system = [exp(x) - sin(y), 1/exp(y) - 3]
assert nonlinsolve(system, [x, y]) == {
(ImageSet(Lambda(n, I*(2*n*pi + pi)
+ log(sin(log(3)))), S.Integers), -log(3)),
(ImageSet(Lambda(n, I*(2*n*pi + arg(sin(2*n*I*pi - log(3))))
+ log(Abs(sin(2*n*I*pi - log(3))))), S.Integers),
ImageSet(Lambda(n, 2*n*I*pi - log(3)), S.Integers))}
system = [exp(x) - sin(y), y**2 - 4]
assert nonlinsolve(system, [x, y]) == {
(ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sin(2))), S.Integers), -2),
(ImageSet(Lambda(n, 2*n*I*pi + log(sin(2))), S.Integers), 2)}
@XFAIL
def test_solve_nonlinear_trans():
# After the transcendental equation solver these will work
x, y, z = symbols('x, y, z', real=True)
soln1 = FiniteSet((2*LambertW(y/2), y))
soln2 = FiniteSet((-x*sqrt(exp(x)), y), (x*sqrt(exp(x)), y))
soln3 = FiniteSet((x*exp(x/2), x))
soln4 = FiniteSet(2*LambertW(y/2), y)
assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln1
assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln2
assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln3
assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln4
def test_issue_5132_1():
system = [sqrt(x**2 + y**2) - sqrt(10), x + y - 4]
assert nonlinsolve(system, [x, y]) == FiniteSet((1, 3), (3, 1))
n = Dummy('n')
eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3]
s_real_y = -log(3)
s_real_z = sqrt(-exp(2*x) - sin(log(3)))
soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z))
lam = Lambda(n, 2*n*I*pi + -log(3))
s_complex_y = ImageSet(lam, S.Integers)
lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3))))
s_complex_z_1 = ImageSet(lam, S.Integers)
lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3))))
s_complex_z_2 = ImageSet(lam, S.Integers)
soln_complex = FiniteSet(
(s_complex_y, s_complex_z_1),
(s_complex_y, s_complex_z_2)
)
soln = soln_real + soln_complex
assert nonlinsolve(eqs, [y, z]) == soln
def test_issue_5132_2():
x, y = symbols('x, y', real=True)
eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3]
n = Dummy('n')
soln_real = (log(-z**2 + sin(y))/2, z)
lam = Lambda( n, I*(2*n*pi + arg(-z**2 + sin(y)))/2 + log(Abs(z**2 - sin(y)))/2)
img = ImageSet(lam, S.Integers)
# not sure about the complex soln. But it looks correct.
soln_complex = (img, z)
soln = FiniteSet(soln_real, soln_complex)
assert nonlinsolve(eqs, [x, z]) == soln
r, t = symbols('r, t')
system = [r - x**2 - y**2, tan(t) - y/x]
s_x = sqrt(r/(tan(t)**2 + 1))
s_y = sqrt(r/(tan(t)**2 + 1))*tan(t)
soln = FiniteSet((s_x, s_y), (-s_x, -s_y))
assert nonlinsolve(system, [x, y]) == soln
def test_issue_6752():
a,b,c,d = symbols('a, b, c, d', real=True)
assert nonlinsolve([a**2 + a, a - b], [a, b]) == {(-1, -1), (0, 0)}
@SKIP("slow")
def test_issue_5114_solveset():
# slow testcase
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(nonlinsolve(eqs, syms)) == 1
@SKIP("Hangs")
def _test_issue_5335():
# Not able to check zero dimensional system.
# is_zero_dimensional Hangs
lam, a0, conc = symbols('lam a0 conc')
eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x,
a0*(1 - x/2)*x - 1*y - 0.743436700916726*y,
x + y - conc]
sym = [x, y, a0]
# there are 4 solutions but only two are valid
assert len(nonlinsolve(eqs, sym)) == 2
# float
lam, a0, conc = symbols('lam a0 conc')
eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x,
a0*(1 - x/2)*x - 1*y - 0.743436700916726*y,
x + y - conc]
sym = [x, y, a0]
assert len(nonlinsolve(eqs, sym)) == 2
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 nonlinsolve((e1, e2), (x, y)) == ans
assert nonlinsolve((e1, e2/(x - a)), (x, y)) == S.EmptySet
# make the 2nd circle's radius be -3
e2 += 6
assert nonlinsolve((e1, e2), (x, y)) == S.EmptySet
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 = (x2 - x)**2 + (y2 - y)**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]
# both soln same
A = nonlinsolve(F, v)
B = nonlinsolve(G, v)
assert A == B
def test_nonlinsolve_conditionset():
# when solveset failed to solve all the eq
# return conditionset
f = Function('f')
f1 = f(x) - pi/2
f2 = f(y) - pi*Rational(3, 2)
intermediate_system = FiniteSet(2*f(x) - pi, 2*f(y) - 3*pi)
symbols = Tuple(x, y)
soln = ConditionSet(
symbols,
intermediate_system,
S.Complexes)
assert nonlinsolve([f1, f2], [x, y]) == soln
def test_substitution_basic():
assert substitution([], [x, y]) == S.EmptySet
assert substitution([], []) == S.EmptySet
system = [2*x**2 + 3*y**2 - 30, 3*x**2 - 2*y**2 - 19]
soln = FiniteSet((-3, -2), (-3, 2), (3, -2), (3, 2))
assert substitution(system, [x, y]) == soln
soln = FiniteSet((-1, 1))
assert substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) == soln
assert substitution(
[x + y], [x], [{y: 1}], [y],
set([x + 1]), [y, x]) == S.EmptySet
def test_issue_5132_substitution():
x, y, z, r, t = symbols('x, y, z, r, t', real=True)
system = [r - x**2 - y**2, tan(t) - y/x]
s_x_1 = Complement(FiniteSet(-sqrt(r/(tan(t)**2 + 1))), FiniteSet(0))
s_x_2 = Complement(FiniteSet(sqrt(r/(tan(t)**2 + 1))), FiniteSet(0))
s_y = sqrt(r/(tan(t)**2 + 1))*tan(t)
soln = FiniteSet((s_x_2, s_y)) + FiniteSet((s_x_1, -s_y))
assert substitution(system, [x, y]) == soln
n = Dummy('n')
eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3]
s_real_y = -log(3)
s_real_z = sqrt(-exp(2*x) - sin(log(3)))
soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z))
lam = Lambda(n, 2*n*I*pi + -log(3))
s_complex_y = ImageSet(lam, S.Integers)
lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3))))
s_complex_z_1 = ImageSet(lam, S.Integers)
lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3))))
s_complex_z_2 = ImageSet(lam, S.Integers)
soln_complex = FiniteSet(
(s_complex_y, s_complex_z_1),
(s_complex_y, s_complex_z_2))
soln = soln_real + soln_complex
assert substitution(eqs, [y, z]) == soln
def test_raises_substitution():
raises(ValueError, lambda: substitution([x**2 -1], []))
raises(TypeError, lambda: substitution([x**2 -1]))
raises(ValueError, lambda: substitution([x**2 -1], [sin(x)]))
raises(TypeError, lambda: substitution([x**2 -1], x))
raises(TypeError, lambda: substitution([x**2 -1], 1))
# end of tests for nonlinsolve
def test_issue_9556():
x = Symbol('x')
b = Symbol('b', positive=True)
assert solveset(Abs(x) + 1, x, S.Reals) == EmptySet()
assert solveset(Abs(x) + b, x, S.Reals) == EmptySet()
assert solveset(Eq(b, -1), b, S.Reals) == EmptySet()
def test_issue_9611():
x = Symbol('x')
a = Symbol('a')
y = Symbol('y')
assert solveset(Eq(x - x + a, a), x, S.Reals) == S.Reals
assert solveset(Eq(y - y + a, a), y) == S.Complexes
def test_issue_9557():
x = Symbol('x')
a = Symbol('a')
assert solveset(x**2 + a, x, S.Reals) == Intersection(S.Reals,
FiniteSet(-sqrt(-a), sqrt(-a)))
def test_issue_9778():
assert solveset(x**3 + 1, x, S.Reals) == FiniteSet(-1)
assert solveset(x**Rational(3, 5) + 1, x, S.Reals) == S.EmptySet
assert solveset(x**3 + y, x, S.Reals) == \
FiniteSet(-Abs(y)**Rational(1, 3)*sign(y))
def test_issue_10214():
assert solveset(x**Rational(3, 2) + 4, x, S.Reals) == S.EmptySet
assert solveset(x**(Rational(-3, 2)) + 4, x, S.Reals) == S.EmptySet
ans = FiniteSet(-2**Rational(2, 3))
assert solveset(x**(S(3)) + 4, x, S.Reals) == ans
assert (x**(S(3)) + 4).subs(x,list(ans)[0]) == 0 # substituting ans and verifying the result.
assert (x**(S(3)) + 4).subs(x,-(-2)**Rational(2, 3)) == 0
def test_issue_9849():
assert solveset(Abs(sin(x)) + 1, x, S.Reals) == S.EmptySet
def test_issue_9953():
assert linsolve([ ], x) == S.EmptySet
def test_issue_9913():
assert solveset(2*x + 1/(x - 10)**2, x, S.Reals) == \
FiniteSet(-(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)/3 - 100/
(3*(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)) + Rational(20, 3))
def test_issue_10397():
assert solveset(sqrt(x), x, S.Complexes) == FiniteSet(0)
def test_issue_14987():
raises(ValueError, lambda: linear_eq_to_matrix(
[x**2], x))
raises(ValueError, lambda: linear_eq_to_matrix(
[x*(-3/x + 1) + 2*y - a], [x, y]))
raises(ValueError, lambda: linear_eq_to_matrix(
[(x**2 - 3*x)/(x - 3) - 3], x))
raises(ValueError, lambda: linear_eq_to_matrix(
[(x + 1)**3 - x**3 - 3*x**2 + 7], x))
raises(ValueError, lambda: linear_eq_to_matrix(
[x*(1/x + 1) + y], [x, y]))
raises(ValueError, lambda: linear_eq_to_matrix(
[(x + 1)*y], [x, y]))
raises(ValueError, lambda: linear_eq_to_matrix(
[Eq(1/x, 1/x + y)], [x, y]))
raises(ValueError, lambda: linear_eq_to_matrix(
[Eq(y/x, y/x + y)], [x, y]))
raises(ValueError, lambda: linear_eq_to_matrix(
[Eq(x*(x + 1), x**2 + y)], [x, y]))
def test_simplification():
eq = x + (a - b)/(-2*a + 2*b)
assert solveset(eq, x) == FiniteSet(S.Half)
assert solveset(eq, x, S.Reals) == FiniteSet(S.Half)
def test_issue_10555():
f = Function('f')
g = Function('g')
assert solveset(f(x) - pi/2, x, S.Reals) == \
ConditionSet(x, Eq(f(x) - pi/2, 0), S.Reals)
assert solveset(f(g(x)) - pi/2, g(x), S.Reals) == \
ConditionSet(g(x), Eq(f(g(x)) - pi/2, 0), S.Reals)
def test_issue_8715():
eq = x + 1/x > -2 + 1/x
assert solveset(eq, x, S.Reals) == \
(Interval.open(-2, oo) - FiniteSet(0))
assert solveset(eq.subs(x,log(x)), x, S.Reals) == \
Interval.open(exp(-2), oo) - FiniteSet(1)
def test_issue_11174():
r, t = symbols('r t')
eq = z**2 + exp(2*x) - sin(y)
soln = Intersection(S.Reals, FiniteSet(log(-z**2 + sin(y))/2))
assert solveset(eq, x, S.Reals) == soln
eq = sqrt(r)*Abs(tan(t))/sqrt(tan(t)**2 + 1) + x*tan(t)
s = -sqrt(r)*Abs(tan(t))/(sqrt(tan(t)**2 + 1)*tan(t))
soln = Intersection(S.Reals, FiniteSet(s))
assert solveset(eq, x, S.Reals) == soln
def test_issue_11534():
# eq and eq2 should give the same solution as a Complement
eq = -y + x/sqrt(-x**2 + 1)
eq2 = -y**2 + x**2/(-x**2 + 1)
soln = Complement(FiniteSet(-y/sqrt(y**2 + 1), y/sqrt(y**2 + 1)), FiniteSet(-1, 1))
assert solveset(eq, x, S.Reals) == soln
assert solveset(eq2, x, S.Reals) == soln
def test_issue_10477():
assert solveset((x**2 + 4*x - 3)/x < 2, x, S.Reals) == \
Union(Interval.open(-oo, -3), Interval.open(0, 1))
def test_issue_10671():
assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi)
i = Interval(1, 10)
assert solveset((1/x).diff(x) < 0, x, i) == i
def test_issue_11064():
eq = x + sqrt(x**2 - 5)
assert solveset(eq > 0, x, S.Reals) == \
Interval(sqrt(5), oo)
assert solveset(eq < 0, x, S.Reals) == \
Interval(-oo, -sqrt(5))
assert solveset(eq > sqrt(5), x, S.Reals) == \
Interval.Lopen(sqrt(5), oo)
def test_issue_12478():
eq = sqrt(x - 2) + 2
soln = solveset_real(eq, x)
assert soln is S.EmptySet
assert solveset(eq < 0, x, S.Reals) is S.EmptySet
assert solveset(eq > 0, x, S.Reals) == Interval(2, oo)
def test_issue_12429():
eq = solveset(log(x)/x <= 0, x, S.Reals)
sol = Interval.Lopen(0, 1)
assert eq == sol
def test_solveset_arg():
assert solveset(arg(x), x, S.Reals) == Interval.open(0, oo)
assert solveset(arg(4*x -3), x) == Interval.open(Rational(3, 4), oo)
def test__is_finite_with_finite_vars():
f = _is_finite_with_finite_vars
# issue 12482
assert all(f(1/x) is None for x in (
Dummy(), Dummy(real=True), Dummy(complex=True)))
assert f(1/Dummy(real=False)) is True # b/c it's finite but not 0
def test_issue_13550():
assert solveset(x**2 - 2*x - 15, symbol = x, domain = Interval(-oo, 0)) == FiniteSet(-3)
def test_issue_13849():
t = symbols('t')
assert nonlinsolve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) == EmptySet()
def test_issue_14223():
x = Symbol('x')
assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x,
S.Reals) == FiniteSet(-1, 1)
assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x,
Interval(0, 2)) == FiniteSet(1)
def test_issue_10158():
x = Symbol('x')
dom = S.Reals
assert solveset(x*Max(x, 15) - 10, x, dom) == FiniteSet(Rational(2, 3))
assert solveset(x*Min(x, 15) - 10, x, dom) == FiniteSet(-sqrt(10), sqrt(10))
assert solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom) == FiniteSet(-1, 1)
assert solveset(Abs(x - 1) - Abs(y), x, dom) == FiniteSet(-Abs(y) + 1, Abs(y) + 1)
assert solveset(Abs(x + 4*Abs(x + 1)), x, dom) == FiniteSet(Rational(-4, 3), Rational(-4, 5))
assert solveset(2*Abs(x + Abs(x + Max(3, x))) - 2, x, S.Reals) == FiniteSet(-1, -2)
dom = S.Complexes
raises(ValueError, lambda: solveset(x*Max(x, 15) - 10, x, dom))
raises(ValueError, lambda: solveset(x*Min(x, 15) - 10, x, dom))
raises(ValueError, lambda: solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom))
raises(ValueError, lambda: solveset(Abs(x - 1) - Abs(y), x, dom))
raises(ValueError, lambda: solveset(Abs(x + 4*Abs(x + 1)), x, dom))
def test_issue_14300():
x, y, n = symbols('x y n')
f = 1 - exp(-18000000*x) - y
a1 = FiniteSet(-log(-y + 1)/18000000)
assert solveset(f, x, S.Reals) == \
Intersection(S.Reals, a1)
assert solveset(f, x) == \
ImageSet(Lambda(n, -I*(2*n*pi + arg(-y + 1))/18000000 -
log(Abs(y - 1))/18000000), S.Integers)
def test_issue_14454():
x = Symbol('x')
number = CRootOf(x**4 + x - 1, 2)
raises(ValueError, lambda: invert_real(number, 0, x, S.Reals))
assert invert_real(x**2, number, x, S.Reals) # no error
def test_term_factors():
assert list(_term_factors(3**x - 2)) == [-2, 3**x]
expr = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3)
assert set(_term_factors(expr)) == set([
3**(x + 2), 4**(x + 2), 3**(x + 3), 4**(x - 1), -1, 4**(x + 1)])
#################### tests for transolve and its helpers ###############
def test_transolve():
assert _transolve(3**x, x, S.Reals) == S.EmptySet
assert _transolve(3**x - 9**(x + 5), x, S.Reals) == FiniteSet(-10)
# exponential tests
def test_exponential_real():
from sympy.abc import x, y, z
e1 = 3**(2*x) - 2**(x + 3)
e2 = 4**(5 - 9*x) - 8**(2 - x)
e3 = 2**x + 4**x
e4 = exp(log(5)*x) - 2**x
e5 = exp(x/y)*exp(-z/y) - 2
e6 = 5**(x/2) - 2**(x/3)
e7 = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3)
e8 = -9*exp(-2*x + 5) + 4*exp(3*x + 1)
e9 = 2**x + 4**x + 8**x - 84
assert solveset(e1, x, S.Reals) == FiniteSet(
-3*log(2)/(-2*log(3) + log(2)))
assert solveset(e2, x, S.Reals) == FiniteSet(Rational(4, 15))
assert solveset(e3, x, S.Reals) == S.EmptySet
assert solveset(e4, x, S.Reals) == FiniteSet(0)
assert solveset(e5, x, S.Reals) == Intersection(
S.Reals, FiniteSet(y*log(2*exp(z/y))))
assert solveset(e6, x, S.Reals) == FiniteSet(0)
assert solveset(e7, x, S.Reals) == FiniteSet(2)
assert solveset(e8, x, S.Reals) == FiniteSet(-2*log(2)/5 + 2*log(3)/5 + Rational(4, 5))
assert solveset(e9, x, S.Reals) == FiniteSet(2)
assert solveset_real(-9*exp(-2*x + 5) + 2**(x + 1), x) == FiniteSet(
-((-5 - 2*log(3) + log(2))/(log(2) + 2)))
assert solveset_real(4**(x/2) - 2**(x/3), x) == FiniteSet(0)
b = sqrt(6)*sqrt(log(2))/sqrt(log(5))
assert solveset_real(5**(x/2) - 2**(3/x), x) == FiniteSet(-b, b)
# coverage test
C1, C2 = symbols('C1 C2')
f = Function('f')
assert solveset_real(C1 + C2/x**2 - exp(-f(x)), f(x)) == Intersection(
S.Reals, FiniteSet(-log(C1 + C2/x**2)))
y = symbols('y', positive=True)
assert solveset_real(x**2 - y**2/exp(x), y) == Intersection(
S.Reals, FiniteSet(-sqrt(x**2*exp(x)), sqrt(x**2*exp(x))))
p = Symbol('p', positive=True)
assert solveset_real((1/p + 1)**(p + 1), p) == EmptySet()
@XFAIL
def test_exponential_complex():
from sympy.abc import x
from sympy import Dummy
n = Dummy('n')
assert solveset_complex(2**x + 4**x, x) == imageset(
Lambda(n, I*(2*n*pi + pi)/log(2)), S.Integers)
assert solveset_complex(x**z*y**z - 2, z) == FiniteSet(
log(2)/(log(x) + log(y)))
assert solveset_complex(4**(x/2) - 2**(x/3), x) == imageset(
Lambda(n, 3*n*I*pi/log(2)), S.Integers)
assert solveset(2**x + 32, x) == imageset(
Lambda(n, (I*(2*n*pi + pi) + 5*log(2))/log(2)), S.Integers)
eq = (2**exp(y**2/x) + 2)/(x**2 + 15)
a = sqrt(x)*sqrt(-log(log(2)) + log(log(2) + 2*n*I*pi))
assert solveset_complex(eq, y) == FiniteSet(-a, a)
union1 = imageset(Lambda(n, I*(2*n*pi - pi*Rational(2, 3))/log(2)), S.Integers)
union2 = imageset(Lambda(n, I*(2*n*pi + pi*Rational(2, 3))/log(2)), S.Integers)
assert solveset(2**x + 4**x + 8**x, x) == Union(union1, union2)
eq = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3)
res = solveset(eq, x)
num = 2*n*I*pi - 4*log(2) + 2*log(3)
den = -2*log(2) + log(3)
ans = imageset(Lambda(n, num/den), S.Integers)
assert res == ans
def test_expo_conditionset():
from sympy.abc import x, y
f1 = (exp(x) + 1)**x - 2
f2 = (x + 2)**y*x - 3
f3 = 2**x - exp(x) - 3
f4 = log(x) - exp(x)
f5 = 2**x + 3**x - 5**x
assert solveset(f1, x, S.Reals) == ConditionSet(
x, Eq((exp(x) + 1)**x - 2, 0), S.Reals)
assert solveset(f2, x, S.Reals) == ConditionSet(
x, Eq(x*(x + 2)**y - 3, 0), S.Reals)
assert solveset(f3, x, S.Reals) == ConditionSet(
x, Eq(2**x - exp(x) - 3, 0), S.Reals)
assert solveset(f4, x, S.Reals) == ConditionSet(
x, Eq(-exp(x) + log(x), 0), S.Reals)
assert solveset(f5, x, S.Reals) == ConditionSet(
x, Eq(2**x + 3**x - 5**x, 0), S.Reals)
def test_exponential_symbols():
x, y, z = symbols('x y z', positive=True)
assert solveset(z**x - y, x, S.Reals) == Intersection(
S.Reals, FiniteSet(log(y)/log(z)))
w = symbols('w')
f1 = 2*x**w - 4*y**w
f2 = (x/y)**w - 2
ans1 = solveset(f1, w, S.Reals)
ans2 = solveset(f2, w, S.Reals)
assert len(ans1) == len(ans2) == 1
a1, a2 = [list(i)[0] for i in (ans1, ans2)]
assert a1.equals(a2)
assert solveset(x**x, x, S.Reals) == S.EmptySet
assert solveset(x**y - 1, y, S.Reals) == FiniteSet(0)
assert solveset(exp(x/y)*exp(-z/y) - 2, y, S.Reals) == FiniteSet(
(x - z)/log(2)) - FiniteSet(0)
a, b, x, y = symbols('a b x y')
assert solveset_real(a**x - b**x, x) == ConditionSet(
x, (a > 0) & (b > 0), FiniteSet(0))
assert solveset(a**x - b**x, x) == ConditionSet(
x, Ne(a, 0) & Ne(b, 0), FiniteSet(0))
@XFAIL
def test_issue_10864():
assert solveset(x**(y*z) - x, x, S.Reals) == FiniteSet(1)
@XFAIL
def test_solve_only_exp_2():
assert solveset_real(sqrt(exp(x)) + sqrt(exp(-x)) - 4, x) == \
FiniteSet(2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2))
def test_is_exponential():
x, y, z = symbols('x y z')
assert _is_exponential(y, x) is False
assert _is_exponential(3**x - 2, x) is True
assert _is_exponential(5**x - 7**(2 - x), x) is True
assert _is_exponential(sin(2**x) - 4*x, x) is False
assert _is_exponential(x**y - z, y) is True
assert _is_exponential(x**y - z, x) is False
assert _is_exponential(2**x + 4**x - 1, x) is True
assert _is_exponential(x**(y*z) - x, x) is False
assert _is_exponential(x**(2*x) - 3**x, x) is False
assert _is_exponential(x**y - y*z, y) is False
assert _is_exponential(x**y - x*z, y) is True
def test_solve_exponential():
assert _solve_exponential(3**(2*x) - 2**(x + 3), 0, x, S.Reals) == \
FiniteSet(-3*log(2)/(-2*log(3) + log(2)))
assert _solve_exponential(2**y + 4**y, 1, y, S.Reals) == \
FiniteSet(log(Rational(-1, 2) + sqrt(5)/2)/log(2))
assert _solve_exponential(2**y + 4**y, 0, y, S.Reals) == \
S.EmptySet
assert _solve_exponential(2**x + 3**x - 5**x, 0, x, S.Reals) == \
ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), S.Reals)
# end of exponential tests
# logarithmic tests
def test_logarithmic():
assert solveset_real(log(x - 3) + log(x + 3), x) == FiniteSet(
-sqrt(10), sqrt(10))
assert solveset_real(log(x + 1) - log(2*x - 1), x) == FiniteSet(2)
assert solveset_real(log(x + 3) + log(1 + 3/x) - 3, x) == FiniteSet(
-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)
eq = z - log(x) + log(y/(x*(-1 + y**2/x**2)))
assert solveset_real(eq, x) == \
Intersection(S.Reals, FiniteSet(-sqrt(y**2 - y*exp(z)),
sqrt(y**2 - y*exp(z)))) - \
Intersection(S.Reals, FiniteSet(-sqrt(y**2), sqrt(y**2)))
assert solveset_real(
log(3*x) - log(-x + 1) - log(4*x + 1), x) == FiniteSet(Rational(-1, 2), S.Half)
assert solveset(log(x**y) - y*log(x), x, S.Reals) == S.Reals
@XFAIL
def test_uselogcombine_2():
eq = log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2)
assert solveset_real(eq, x) == EmptySet()
eq = log(8*x) - log(sqrt(x) + 1) - 2
assert solveset_real(eq, x) == EmptySet()
def test_is_logarithmic():
assert _is_logarithmic(y, x) is False
assert _is_logarithmic(log(x), x) is True
assert _is_logarithmic(log(x) - 3, x) is True
assert _is_logarithmic(log(x)*log(y), x) is True
assert _is_logarithmic(log(x)**2, x) is False
assert _is_logarithmic(log(x - 3) + log(x + 3), x) is True
assert _is_logarithmic(log(x**y) - y*log(x), x) is True
assert _is_logarithmic(sin(log(x)), x) is False
assert _is_logarithmic(x + y, x) is False
assert _is_logarithmic(log(3*x) - log(1 - x) + 4, x) is True
assert _is_logarithmic(log(x) + log(y) + x, x) is False
assert _is_logarithmic(log(log(x - 3)) + log(x - 3), x) is True
assert _is_logarithmic(log(log(3) + x) + log(x), x) is True
assert _is_logarithmic(log(x)*(y + 3) + log(x), y) is False
def test_solve_logarithm():
y = Symbol('y')
assert _solve_logarithm(log(x**y) - y*log(x), 0, x, S.Reals) == S.Reals
y = Symbol('y', positive=True)
assert _solve_logarithm(log(x)*log(y), 0, x, S.Reals) == FiniteSet(1)
# end of logarithmic tests
def test_linear_coeffs():
from sympy.solvers.solveset import linear_coeffs
assert linear_coeffs(0, x) == [0, 0]
assert all(i is S.Zero for i in linear_coeffs(0, x))
assert linear_coeffs(x + 2*y + 3, x, y) == [1, 2, 3]
assert linear_coeffs(x + 2*y + 3, y, x) == [2, 1, 3]
assert linear_coeffs(x + 2*x**2 + 3, x, x**2) == [1, 2, 3]
raises(ValueError, lambda:
linear_coeffs(x + 2*x**2 + x**3, x, x**2))
raises(ValueError, lambda:
linear_coeffs(1/x*(x - 1) + 1/x, x))
assert linear_coeffs(a*(x + y), x, y) == [a, a, 0]
# modular tests
def test_is_modular():
x, y = symbols('x y')
assert _is_modular(y, x) is False
assert _is_modular(Mod(x, 3) - 1, x) is True
assert _is_modular(Mod(x**3 - 3*x**2 - x + 1, 3) - 1, x) is True
assert _is_modular(Mod(exp(x + y), 3) - 2, x) is True
assert _is_modular(Mod(exp(x + y), 3) - log(x), x) is True
assert _is_modular(Mod(x, 3) - 1, y) is False
assert _is_modular(Mod(x, 3)**2 - 5, x) is False
assert _is_modular(Mod(x, 3)**2 - y, x) is False
assert _is_modular(exp(Mod(x, 3)) - 1, x) is False
assert _is_modular(Mod(3, y) - 1, y) is False
def test_invert_modular():
x, y = symbols('x y')
n = Dummy('n', integer=True)
from sympy.solvers.solveset import _invert_modular as invert_modular
# non invertible cases
assert invert_modular(Mod(sin(x), 7), S(5), n, x) == (Mod(sin(x), 7), 5)
assert invert_modular(Mod(exp(x), 7), S(5), n, x) == (Mod(exp(x), 7), 5)
assert invert_modular(Mod(log(x), 7), S(5), n, x) == (Mod(log(x), 7), 5)
# a is symbol
assert invert_modular(Mod(x, 7), S(5), n, x) == \
(x, ImageSet(Lambda(n, 7*n + 5), S.Integers))
# a.is_Add
assert invert_modular(Mod(x + 8, 7), S(5), n, x) == \
(x, ImageSet(Lambda(n, 7*n + 4), S.Integers))
assert invert_modular(Mod(x**2 + x, 7), S(5), n, x) == \
(Mod(x**2 + x, 7), 5)
# a.is_Mul
assert invert_modular(Mod(3*x, 7), S(5), n, x) == \
(x, ImageSet(Lambda(n, 7*n + 4), S.Integers))
assert invert_modular(Mod((x + 1)*(x + 2), 7), S(5), n, x) == \
(Mod((x + 1)*(x + 2), 7), 5)
# a.is_Pow
assert invert_modular(Mod(x**4, 7), S(5), n, x) == \
(x, EmptySet())
assert invert_modular(Mod(3**x, 4), S(3), n, x) == \
(x, ImageSet(Lambda(n, 2*n + 1), S.Naturals0))
assert invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x) == \
(x**2 + x + 1, ImageSet(Lambda(n, 3*n + 1), S.Naturals0))
def test_solve_modular():
x = Symbol('x')
n = Dummy('n', integer=True)
# if rhs has symbol (need to be implemented in future).
assert solveset(Mod(x, 4) - x, x, S.Integers) == \
ConditionSet(x, Eq(-x + Mod(x, 4), 0), \
S.Integers)
# when _invert_modular fails to invert
assert solveset(3 - Mod(sin(x), 7), x, S.Integers) == \
ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), S.Integers)
assert solveset(3 - Mod(log(x), 7), x, S.Integers) == \
ConditionSet(x, Eq(Mod(log(x), 7) - 3, 0), S.Integers)
assert solveset(3 - Mod(exp(x), 7), x, S.Integers) == \
ConditionSet(x, Eq(Mod(exp(x), 7) - 3, 0), S.Integers)
# EmptySet solution definitely
assert solveset(7 - Mod(x, 5), x, S.Integers) == EmptySet()
assert solveset(5 - Mod(x, 5), x, S.Integers) == EmptySet()
# Negative m
assert solveset(2 + Mod(x, -3), x, S.Integers) == \
ImageSet(Lambda(n, -3*n - 2), S.Integers)
assert solveset(4 + Mod(x, -3), x, S.Integers) == EmptySet()
# linear expression in Mod
assert solveset(3 - Mod(x, 5), x, S.Integers) == ImageSet(Lambda(n, 5*n + 3), S.Integers)
assert solveset(3 - Mod(5*x - 8, 7), x, S.Integers) == \
ImageSet(Lambda(n, 7*n + 5), S.Integers)
assert solveset(3 - Mod(5*x, 7), x, S.Integers) == \
ImageSet(Lambda(n, 7*n + 2), S.Integers)
# higher degree expression in Mod
assert solveset(Mod(x**2, 160) - 9, x, S.Integers) == \
Union(ImageSet(Lambda(n, 160*n + 3), S.Integers),
ImageSet(Lambda(n, 160*n + 13), S.Integers),
ImageSet(Lambda(n, 160*n + 67), S.Integers),
ImageSet(Lambda(n, 160*n + 77), S.Integers),
ImageSet(Lambda(n, 160*n + 83), S.Integers),
ImageSet(Lambda(n, 160*n + 93), S.Integers),
ImageSet(Lambda(n, 160*n + 147), S.Integers),
ImageSet(Lambda(n, 160*n + 157), S.Integers))
assert solveset(3 - Mod(x**4, 7), x, S.Integers) == EmptySet()
assert solveset(Mod(x**4, 17) - 13, x, S.Integers) == \
Union(ImageSet(Lambda(n, 17*n + 3), S.Integers),
ImageSet(Lambda(n, 17*n + 5), S.Integers),
ImageSet(Lambda(n, 17*n + 12), S.Integers),
ImageSet(Lambda(n, 17*n + 14), S.Integers))
# a.is_Pow tests
assert solveset(Mod(7**x, 41) - 15, x, S.Integers) == \
ImageSet(Lambda(n, 40*n + 3), S.Naturals0)
assert solveset(Mod(12**x, 21) - 18, x, S.Integers) == \
ImageSet(Lambda(n, 6*n + 2), S.Naturals0)
assert solveset(Mod(3**x, 4) - 3, x, S.Integers) == \
ImageSet(Lambda(n, 2*n + 1), S.Naturals0)
assert solveset(Mod(2**x, 7) - 2 , x, S.Integers) == \
ImageSet(Lambda(n, 3*n + 1), S.Naturals0)
assert solveset(Mod(3**(3**x), 4) - 3, x, S.Integers) == \
Intersection(ImageSet(Lambda(n, Intersection({log(2*n + 1)/log(3)},
S.Integers)), S.Naturals0), S.Integers)
# Not Implemented for m without primitive root
assert solveset(Mod(x**3, 8) - 1, x, S.Integers) == \
ConditionSet(x, Eq(Mod(x**3, 8) - 1, 0), S.Integers)
assert solveset(Mod(x**4, 9) - 4, x, S.Integers) == \
ConditionSet(x, Eq(Mod(x**4, 9) - 4, 0), S.Integers)
# domain intersection
assert solveset(3 - Mod(5*x - 8, 7), x, S.Naturals0) == \
Intersection(ImageSet(Lambda(n, 7*n + 5), S.Integers), S.Naturals0)
# Complex args
assert solveset(Mod(x, 3) - I, x, S.Integers) == \
EmptySet()
assert solveset(Mod(I*x, 3) - 2, x, S.Integers) == \
ConditionSet(x, Eq(Mod(I*x, 3) - 2, 0), S.Integers)
assert solveset(Mod(I + x, 3) - 2, x, S.Integers) == \
ConditionSet(x, Eq(Mod(x + I, 3) - 2, 0), S.Integers)
# issue 13178
n = symbols('n', integer=True)
a = 742938285
z = 1898888478
m = 2**31 - 1
x = 20170816
assert solveset(x - Mod(a**n*z, m), n, S.Integers) == \
ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0)
assert solveset(x - Mod(a**n*z, m), n, S.Naturals0) == \
Intersection(ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0),
S.Naturals0)
assert solveset(x - Mod(a**(2*n)*z, m), n, S.Integers) == \
Intersection(ImageSet(Lambda(n, 1073741823*n + 50), S.Naturals0),
S.Integers)
assert solveset(x - Mod(a**(2*n + 7)*z, m), n, S.Integers) == EmptySet()
assert solveset(x - Mod(a**(n - 4)*z, m), n, S.Integers) == \
Intersection(ImageSet(Lambda(n, 2147483646*n + 104), S.Naturals0),
S.Integers)
@XFAIL
def test_solve_modular_fail():
# issue 17373 (https://github.com/sympy/sympy/issues/17373)
assert solveset(Mod(x**4, 14) - 11, x, S.Integers) == \
Union(ImageSet(Lambda(n, 14*n + 3), S.Integers),
ImageSet(Lambda(n, 14*n + 11), S.Integers))
assert solveset(Mod(x**31, 74) - 43, x, S.Integers) == \
ImageSet(Lambda(n, 74*n + 31), S.Integers)
# end of modular tests
|
7d92610eaefbd0db7f1270b905171f1ebab70c3d8d21d6618214a53b821eef3c | from sympy import (
Abs, And, Derivative, Dummy, Eq, Float, Function, Gt, I, Integral,
LambertW, Lt, Matrix, Or, Poly, Q, Rational, S, Symbol, Ne,
Wild, acos, asin, atan, atanh, cos, cosh, diff, erf, erfinv, erfc,
erfcinv, exp, im, log, pi, re, sec, sin,
sinh, solve, solve_linear, sqrt, sstr, symbols, sympify, tan, tanh,
root, atan2, arg, Mul, SparseMatrix, ask, Tuple, nsolve, oo,
E, cbrt, denom, Add, Piecewise)
from sympy.core.compatibility import range
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, check_assumptions, denoms, \
failing_assumptions
from sympy.physics.units import cm
from sympy.polys.rootoftools import CRootOf
from sympy.utilities.pytest import slow, XFAIL, SKIP, raises
from sympy.utilities.randtest import verify_numerically as tn
from sympy.abc import a, b, c, d, k, h, p, x, y, z, t, q, m
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)[0] == {fx: 2, gx: 0}
assert solve(fx + gx**2*x - y, [fx, gx], dict=True) == [{fx: y - gx**2*x}]
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)) == set([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]) == []
# duplicate symbols removed
assert solve((x - 3, y + 2), x, y, x) == {x: 3, y: -2}
# unordered symbols
# only 1
assert solve(y - 3, set([y])) == [3]
# more than 1
assert solve(y - 3, set([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}
args = (a + b)*x - b**2 + 2, a, b
assert solve(*args) == \
[(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))]
assert solve(*args, set=True) == \
([a, b], set([(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))]))
assert solve(*args, dict=True) == \
[{b: sqrt(2), a: -sqrt(2)}, {b: -sqrt(2), a: sqrt(2)}]
eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p
flags = dict(dict=True)
assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \
[{k: c - b**2/(4*a), h: -b/(2*a), p: 1/(4*a)}]
flags.update(dict(simplify=False))
assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \
[{k: (4*a*c - b**2)/(4*a), h: -b/(2*a), p: 1/(4*a)}]
# failing undetermined system
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
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]) == []
# 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([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())
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)) == set([-S.One, S.One])
assert set(solve(Eq(x**2, 1), x)) == set([-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 = {y: S.Zero, x: 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)) == set([
-2 + 3**S.Half,
S(4),
-2 - 3**S.Half
])
assert set(solve((x**2 - 1)**2 - a, x)) == \
set([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)) == set([S.Zero, 1/a**2])
assert set(solve(x*(root(x, 3) - 3), x)) == set([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_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_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
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_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_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 - t/n, z: -t - t/n, y: 0}
assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t}
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_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)) == set([-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*Rational(-3, 4), pi/4]
assert set(solve(exp(x) + exp(-x) - y, x)) in [set([
log(y/2 - sqrt(y**2 - 4)/2),
log(y/2 + sqrt(y**2 - 4)/2),
]), set([
log(y - sqrt(y**2 - 4)) - log(2),
log(y + sqrt(y**2 - 4)) - log(2)]),
set([
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)) == set([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)
ans = [(log(2401) + 5*LambertW((-1 + sqrt(5) + sqrt(2)*I*sqrt(sqrt(5) + \
5))*log(7**(7*3**Rational(1, 5)/20))* -1))/(-3*log(7)), \
(log(2401) + 5*LambertW((1 + sqrt(5) - sqrt(2)*I*sqrt(5 - \
sqrt(5)))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \
(log(2401) + 5*LambertW((1 + sqrt(5) + sqrt(2)*I*sqrt(5 - \
sqrt(5)))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \
(log(2401) + 5*LambertW((-sqrt(5) + 1 + sqrt(2)*I*sqrt(sqrt(5) + \
5))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \
(log(2401) + 5*LambertW(-log(7**(7*3**Rational(1, 5)/5))))/(-3*log(7))]
assert result == ans
# 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) == [log(10)/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 = set((3*x - 1, 2*y - 4))
assert solve(eqns, set((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) }
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}
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(True, x)) == True
assert solve(Eq(False, ~x)) == True
assert solve(Eq(True, ~x)) == False
assert solve(Ne(True, x)) == False
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))) == set([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 \
[
set([log((-sqrt(3) + 2)**2), log((sqrt(3) + 2)**2)]),
set([2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)]),
set([log(-4*sqrt(3) + 7), log(4*sqrt(3) + 7)]),
]
assert set(solve(Poly(exp(x) + exp(-x) - 4))) == \
set([log(-sqrt(3) + 2), log(sqrt(3) + 2)])
assert set(solve(x**y + x**(2*y) - 1, x)) == \
set([(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)*n - y**2 + 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)) == set([sqrt(y), S.Zero, -sqrt(y)])
assert set(solve(x*(x - y/x), x, check=True)) == set([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 set(solve((
a**2 + 1) * (sin(a*x) + cos(a*x)), x)) == set([-pi/(4*a), 3*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)) == \
set([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])) == \
set([(
-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])) == \
set([(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) == \
([x, y], set([
(log(-sqrt(-z**2 - sin(log(3)))), -log(3)),
(log(-z**2 - sin(log(3)))/2, -log(3))]))
assert solve(eqs, x, z, set=True) == (
[x, z],
{(log(-z**2 + sin(y))/2, z), (log(-sqrt(-z**2 + sin(y))), z)})
assert set(solve(eqs, x, y)) == \
set([
(log(-sqrt(-z**2 - sin(log(3)))), -log(3)),
(log(-z**2 - sin(log(3)))/2, -log(3))])
assert set(solve(eqs, y, z)) == \
set([
(-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) == ([x, y], set(
[
(log(-sqrt(-z - sin(log(3)))), -log(3)),
(log(-z - sin(log(3)))/2, -log(3))]))
assert solve(eqs, x, z, set=True) == (
[x, z],
{(log(-sqrt(-z + sin(y))), z), (log(-z + sin(y))/2, z)})
assert set(solve(eqs, x, y)) == set(
[
(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], set([(S.One, S(3)), (S(3), S.One)]))
assert set(solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), x, y)) == \
set([(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])) == \
set([(-sqrt(-y - 4),), (sqrt(-y - 4),)])
def test_polysys():
assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \
set([(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 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)) == set([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)))) == \
set([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))) == set([-S.One, S(2)])
assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == set([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))) == \
set([Rational(-1, 2), Rational(-1, 3)])
assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == set([-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]))
# is this needed?
#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, [])
raises(NotImplementedError, lambda:
unrad(sqrt(cosh(x)/x) + root(x + 1,3)*sqrt(x) - 1))
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]))
# 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) == [
4*2**Rational(2, 3)*(27*x + 27*sqrt(x**2))**Rational(1, 3)/21 - (Rational(-1, 2) -
sqrt(3)*I/2)*(x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) - Rational(13824, 343))**2)/2 -
Rational(6912, 343))**Rational(1, 3)/3, 4*2**Rational(2, 3)*(27*x + 27*sqrt(x**2))**Rational(1, 3)/21 -
(Rational(-1, 2) + sqrt(3)*I/2)*(x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) -
Rational(13824, 343))**2)/2 - Rational(6912, 343))**Rational(1, 3)/3, 4*2**Rational(2, 3)*(27*x +
27*sqrt(x**2))**Rational(1, 3)/21 - (x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) -
Rational(13824, 343))**2)/2 - Rational(6912, 343))**Rational(1, 3)/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)),
(4096*s**13 + 960*s**12 + 48*s**11 - s**10 - 1728*s**4,
[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)))
@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
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():
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 = [{
dQ4: I3 - I5,
dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24,
I4: I3 - I5,
dQ2: I2,
Q2: 2*I3 + 2*I5 + 3*I6,
I1: I2 + I3,
Q4: -I3/2 + 3*I5/2 - dI4/2}]
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) == []
# 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_2750 but solved with the matrix solver.'''
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) == {
dI4: -I3 + 3*I5 - 2*Q4,
dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24,
dQ2: I2,
I1: I2 + I3,
Q2: 2*I3 + 2*I5 + 3*I6,
dQ4: I3 - I5,
I4: I3 - I5}
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) == \
[{f(x): 3*D, y: 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) == \
([g(a)], set([
(-sqrt(h(a)**2*f(a)**2 + G)/f(a),),
(sqrt(h(a)**2*f(a)**2+ G)/f(a),)]))
args = [f(x).diff(x, 2)*(f(x) + g(x)) - g(x)**2 + 2, f(x), g(x)]
assert set(solve(*args)) == \
set([(-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)], set([
(-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))) == \
set([-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)) == \
set([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]
assert check_assumptions(1, x) == True
raises(AssertionError, lambda: check_assumptions(2*x, x, positive=True))
raises(TypeError, lambda: check_assumptions(1, 1))
def test_failing_assumptions():
x = Symbol('x', real=True, 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_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():
def count(dic):
return len([x for x in dic.values() if x == 0])
assert count(solve([x + y + z, y + z + a + t], particular=True, quick=True)) \
== 3
assert count(solve([x + y + z, y + z + a + t], particular=True, quick=False)) \
== 3
assert count(solve([x + y + z, y + z + a], particular=True, quick=True)) == 1
assert count(solve([x + y + z, y + z + a], particular=True, quick=False)) == 2
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,), (2,)]
assert set(solve(abs(x - 7) - 8)) == set([-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) == set([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) == set(
[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)) == set(
[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)))]
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) == [-2*atan(2 - sqrt(5)),
-2*atan(2 + sqrt(5))]
@XFAIL
def test_rewrite_trigh():
# if this import passes then the test below should also pass
from sympy 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 == set([(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()]) <= 2617
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]) == set([x**y])
assert _simple_dens(1/root(x, 3), [x]) == set([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 = (x2 - x)**2 + (y2 - y)**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 = [set([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]
s = solve(terms, [a, b, c, d, e, f, g], dict=True)
assert s == [{a: -sqrt(-f**2 - 1), b: -sqrt(-f**2 - 1),
c: -sqrt(-f**2 - 1), d: f, e: f, g: -1},
{a: sqrt(-f**2 - 1), b: sqrt(-f**2 - 1),
c: sqrt(-f**2 - 1), d: f, e: f, g: -1},
{a: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2,
b: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2),
d: -f/2 + sqrt(-3*f**2 + 6)/2,
e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/2, g: 2},
{a: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2,
b: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2),
d: -f/2 - sqrt(-3*f**2 + 6)/2,
e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2},
{a: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2,
b: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2),
d: -f/2 - sqrt(-3*f**2 + 6)/2,
e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2},
{a: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2,
b: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2),
d: -f/2 + sqrt(-3*f**2 + 6)/2,
e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/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) == set([2, y])
assert denoms(x/2 + 1/y, y) == set([y])
assert denoms(x/2 + 1/y, [y]) == set([y])
assert denoms(1/x + 1/y + 1/z, [x, y]) == set([x, y])
assert denoms(1/x + 1/y + 1/z, x, y) == set([x, y])
assert denoms(1/x + 1/y + 1/z, set([x, y])) == set([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))]
|
d742f20efb0a9af0b03c3e4f8285a47dfc278bc989983ba64cb59bd4efbc1cd9 | """Tests for solvers of systems of polynomial equations. """
from sympy import (flatten, I, Integer, Poly, QQ, Rational, S, sqrt,
solve, symbols)
from sympy.abc import x, y, z
from sympy.polys import PolynomialError
from sympy.solvers.polysys import (solve_poly_system,
solve_triangulated, solve_biquadratic, SolveFailed)
from sympy.polys.polytools import parallel_poly_from_expr
from sympy.utilities.pytest import raises
def test_solve_poly_system():
assert solve_poly_system([x - 1], x) == [(S.One,)]
assert solve_poly_system([y - x, y - x - 1], x, y) is None
assert solve_poly_system([y - x**2, y + x**2], x, y) == [(S.Zero, S.Zero)]
assert solve_poly_system([2*x - 3, y*Rational(3, 2) - 2*x, z - 5*y], x, y, z) == \
[(Rational(3, 2), Integer(2), Integer(10))]
assert solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) == \
[(0, 0), (2, -sqrt(2)), (2, sqrt(2))]
assert solve_poly_system([y - x**2, y + x**2 + 1], x, y) == \
[(-I*sqrt(S.Half), Rational(-1, 2)), (I*sqrt(S.Half), Rational(-1, 2))]
f_1 = x**2 + y + z - 1
f_2 = x + y**2 + z - 1
f_3 = x + y + z**2 - 1
a, b = sqrt(2) - 1, -sqrt(2) - 1
assert solve_poly_system([f_1, f_2, f_3], x, y, z) == \
[(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
solution = [(1, -1), (1, 1)]
assert solve_poly_system([Poly(x**2 - y**2), Poly(x - 1)]) == solution
assert solve_poly_system([x**2 - y**2, x - 1], x, y) == solution
assert solve_poly_system([x**2 - y**2, x - 1]) == solution
assert solve_poly_system(
[x + x*y - 3, y + x*y - 4], x, y) == [(-3, -2), (1, 2)]
raises(NotImplementedError, lambda: solve_poly_system([x**3 - y**3], x, y))
raises(NotImplementedError, lambda: solve_poly_system(
[z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2]))
raises(PolynomialError, lambda: solve_poly_system([1/x], x))
def test_solve_biquadratic():
x0, y0, x1, y1, r = symbols('x0 y0 x1 y1 r')
f_1 = (x - 1)**2 + (y - 1)**2 - r**2
f_2 = (x - 2)**2 + (y - 2)**2 - r**2
s = sqrt(2*r**2 - 1)
a = (3 - s)/2
b = (3 + s)/2
assert solve_poly_system([f_1, f_2], x, y) == [(a, b), (b, a)]
f_1 = (x - 1)**2 + (y - 2)**2 - r**2
f_2 = (x - 1)**2 + (y - 1)**2 - r**2
assert solve_poly_system([f_1, f_2], x, y) == \
[(1 - sqrt(((2*r - 1)*(2*r + 1)))/2, Rational(3, 2)),
(1 + sqrt(((2*r - 1)*(2*r + 1)))/2, Rational(3, 2))]
query = lambda expr: expr.is_Pow and expr.exp is S.Half
f_1 = (x - 1 )**2 + (y - 2)**2 - r**2
f_2 = (x - x1)**2 + (y - 1)**2 - r**2
result = solve_poly_system([f_1, f_2], x, y)
assert len(result) == 2 and all(len(r) == 2 for r in result)
assert all(r.count(query) == 1 for r in flatten(result))
f_1 = (x - x0)**2 + (y - y0)**2 - r**2
f_2 = (x - x1)**2 + (y - y1)**2 - r**2
result = solve_poly_system([f_1, f_2], x, y)
assert len(result) == 2 and all(len(r) == 2 for r in result)
assert all(len(r.find(query)) == 1 for r in flatten(result))
s1 = (x*y - y, x**2 - x)
assert solve(s1) == [{x: 1}, {x: 0, y: 0}]
s2 = (x*y - x, y**2 - y)
assert solve(s2) == [{y: 1}, {x: 0, y: 0}]
gens = (x, y)
for seq in (s1, s2):
(f, g), opt = parallel_poly_from_expr(seq, *gens)
raises(SolveFailed, lambda: solve_biquadratic(f, g, opt))
seq = (x**2 + y**2 - 2, y**2 - 1)
(f, g), opt = parallel_poly_from_expr(seq, *gens)
assert solve_biquadratic(f, g, opt) == [
(-1, -1), (-1, 1), (1, -1), (1, 1)]
ans = [(0, -1), (0, 1)]
seq = (x**2 + y**2 - 1, y**2 - 1)
(f, g), opt = parallel_poly_from_expr(seq, *gens)
assert solve_biquadratic(f, g, opt) == ans
seq = (x**2 + y**2 - 1, x**2 - x + y**2 - 1)
(f, g), opt = parallel_poly_from_expr(seq, *gens)
assert solve_biquadratic(f, g, opt) == ans
def test_solve_triangulated():
f_1 = x**2 + y + z - 1
f_2 = x + y**2 + z - 1
f_3 = x + y + z**2 - 1
a, b = sqrt(2) - 1, -sqrt(2) - 1
assert solve_triangulated([f_1, f_2, f_3], x, y, z) == \
[(0, 0, 1), (0, 1, 0), (1, 0, 0)]
dom = QQ.algebraic_field(sqrt(2))
assert solve_triangulated([f_1, f_2, f_3], x, y, z, domain=dom) == \
[(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
def test_solve_issue_3686():
roots = solve_poly_system([((x - 5)**2/250000 + (y - Rational(5, 10))**2/250000) - 1, x], x, y)
assert roots == [(0, S.Half - 15*sqrt(1111)), (0, S.Half + 15*sqrt(1111))]
roots = solve_poly_system([((x - 5)**2/250000 + (y - 5.0/10)**2/250000) - 1, x], x, y)
# TODO: does this really have to be so complicated?!
assert len(roots) == 2
assert roots[0][0] == 0
assert roots[0][1].epsilon_eq(-499.474999374969, 1e12)
assert roots[1][0] == 0
assert roots[1][1].epsilon_eq(500.474999374969, 1e12)
|
9a223e54844e964732090652dd222eacf354ef6ce0eb5e0225cd8924b8e496aa | from sympy import (Add, Matrix, Mul, S, symbols, Eq, pi, factorint, oo,
powsimp, Rational)
from sympy.core.function import _mexpand
from sympy.core.compatibility import range, ordered
from sympy.functions.elementary.trigonometric import sin
from sympy.solvers.diophantine import (descent, diop_bf_DN, diop_DN,
diop_solve, diophantine, divisible, equivalent, find_DN, ldescent, length,
reconstruct, partition, power_representation,
prime_as_sum_of_two_squares, square_factor, sum_of_four_squares,
sum_of_three_squares, transformation_to_DN, transformation_to_normal,
classify_diop, base_solution_linear, cornacchia, sqf_normal,
diop_ternary_quadratic_normal, _diop_ternary_quadratic_normal,
gaussian_reduce, holzer,diop_general_pythagorean,
_diop_general_sum_of_squares, _nint_or_floor, _odd, _even,
_remove_gcd, check_param, parametrize_ternary_quadratic,
diop_ternary_quadratic, diop_linear, diop_quadratic,
diop_general_sum_of_squares, sum_of_powers, sum_of_squares,
diop_general_sum_of_even_powers, _can_do_sum_of_squares)
from sympy.utilities import default_sort_key
from sympy.utilities.pytest import slow, raises, XFAIL
from sympy.utilities.iterables import (
signed_permutations)
a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols(
"a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True)
t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True)
m1, m2, m3 = symbols('m1:4', integer=True)
n1 = symbols('n1', integer=True)
def diop_simplify(eq):
return _mexpand(powsimp(_mexpand(eq)))
def test_input_format():
raises(TypeError, lambda: diophantine(sin(x)))
raises(TypeError, lambda: diophantine(3))
raises(TypeError, lambda: diophantine(x/pi - 3))
def test_univariate():
assert diop_solve((x - 1)*(x - 2)**2) == set([(1,), (2,)])
assert diop_solve((x - 1)*(x - 2)) == set([(1,), (2,)])
def test_classify_diop():
raises(TypeError, lambda: classify_diop(x**2/3 - 1))
raises(ValueError, lambda: classify_diop(1))
raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1))
raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90))
assert classify_diop(14*x**2 + 15*x - 42) == (
[x], {1: -42, x: 15, x**2: 14}, 'univariate')
assert classify_diop(x*y + z) == (
[x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic')
assert classify_diop(x*y + z + w + x**2) == (
[w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic')
assert classify_diop(x*y + x*z + x**2 + 1) == (
[x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic')
assert classify_diop(x*y + z + w + 42) == (
[w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic')
assert classify_diop(x*y + z*w) == (
[w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic')
assert classify_diop(x*y**2 + 1) == (
[x, y], {x*y**2: 1, 1: 1}, 'cubic_thue')
assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == (
[x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers')
def test_linear():
assert diop_solve(x) == (0,)
assert diop_solve(1*x) == (0,)
assert diop_solve(3*x) == (0,)
assert diop_solve(x + 1) == (-1,)
assert diop_solve(2*x + 1) == (None,)
assert diop_solve(2*x + 4) == (-2,)
assert diop_solve(y + x) == (t_0, -t_0)
assert diop_solve(y + x + 0) == (t_0, -t_0)
assert diop_solve(y + x - 0) == (t_0, -t_0)
assert diop_solve(0*x - y - 5) == (-5,)
assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5)
assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5)
assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5)
assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0)
assert diop_solve(2*x + 4*y) == (2*t_0, -t_0)
assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2)
assert diop_solve(4*x + 6*y - 3) == (None, None)
assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5)
assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5)
assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None)
assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18)
assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1)
assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2)
# to ignore constant factors, use diophantine
raises(TypeError, lambda: diop_solve(x/2))
def test_quadratic_simple_hyperbolic_case():
# Simple Hyperbolic case: A = C = 0 and B != 0
assert diop_solve(3*x*y + 34*x - 12*y + 1) == \
set([(-133, -11), (5, -57)])
assert diop_solve(6*x*y + 2*x + 3*y + 1) == set([])
assert diop_solve(-13*x*y + 2*x - 4*y - 54) == set([(27, 0)])
assert diop_solve(-27*x*y - 30*x - 12*y - 54) == set([(-14, -1)])
assert diop_solve(2*x*y + 5*x + 56*y + 7) == set([(-161, -3),\
(-47,-6), (-35, -12), (-29, -69),\
(-27, 64), (-21, 7),(-9, 1),\
(105, -2)])
assert diop_solve(6*x*y + 9*x + 2*y + 3) == set([])
assert diop_solve(x*y + x + y + 1) == set([(-1, t), (t, -1)])
assert diophantine(48*x*y)
def test_quadratic_elliptical_case():
# Elliptical case: B**2 - 4AC < 0
# Two test cases highlighted require lot of memory due to quadratic_congruence() method.
# This above method should be replaced by Pernici's square_mod() method when his PR gets merged.
#assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == set([(-11, -1)])
assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set([])
assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == set([(-1, -1)])
#assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == set([(-15, 6)])
assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \
set([(-1, -1), (-1, 2), (1, -2), (1, 1)])
def test_quadratic_parabolic_case():
# Parabolic case: B**2 - 4AC = 0
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16)
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6)
assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7)
assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3)
assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1)
assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1)
assert check_solutions(y**2 - 41*x + 40)
def test_quadratic_perfect_square():
# B**2 - 4*A*C > 0
# B**2 - 4*A*C is a perfect square
assert check_solutions(48*x*y)
assert check_solutions(4*x**2 - 5*x*y + y**2 + 2)
assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25)
assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12)
assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23)
assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3)
assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10)
assert check_solutions(x**2 - y**2 - 2*x - 2*y)
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3)
def test_quadratic_non_perfect_square():
# B**2 - 4*A*C is not a perfect square
# Used check_solutions() since the solutions are complex expressions involving
# square roots and exponents
assert check_solutions(x**2 - 2*x - 5*y**2)
assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y)
assert check_solutions(x**2 - x*y - y**2 - 3*y)
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
def test_issue_9106():
eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1)
v = (x, y)
for sol in diophantine(eq):
assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
@slow
def test_quadratic_non_perfect_slow():
assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23)
# This leads to very large numbers.
# assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15)
assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7)
assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2)
assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2)
def test_DN():
# Most of the test cases were adapted from,
# Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004.
# http://www.jpr2718.org/pell.pdf
# others are verified using Wolfram Alpha.
# Covers cases where D <= 0 or D > 0 and D is a square or N = 0
# Solutions are straightforward in these cases.
assert diop_DN(3, 0) == [(0, 0)]
assert diop_DN(-17, -5) == []
assert diop_DN(-19, 23) == [(2, 1)]
assert diop_DN(-13, 17) == [(2, 1)]
assert diop_DN(-15, 13) == []
assert diop_DN(0, 5) == []
assert diop_DN(0, 9) == [(3, t)]
assert diop_DN(9, 0) == [(3*t, t)]
assert diop_DN(16, 24) == []
assert diop_DN(9, 180) == [(18, 4)]
assert diop_DN(9, -180) == [(12, 6)]
assert diop_DN(7, 0) == [(0, 0)]
# When equation is x**2 + y**2 = N
# Solutions are interchangeable
assert diop_DN(-1, 5) == [(2, 1), (1, 2)]
assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)]
# D > 0 and D is not a square
# N = 1
assert diop_DN(13, 1) == [(649, 180)]
assert diop_DN(980, 1) == [(51841, 1656)]
assert diop_DN(981, 1) == [(158070671986249, 5046808151700)]
assert diop_DN(986, 1) == [(49299, 1570)]
assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)]
assert diop_DN(17, 1) == [(33, 8)]
assert diop_DN(19, 1) == [(170, 39)]
# N = -1
assert diop_DN(13, -1) == [(18, 5)]
assert diop_DN(991, -1) == []
assert diop_DN(41, -1) == [(32, 5)]
assert diop_DN(290, -1) == [(17, 1)]
assert diop_DN(21257, -1) == [(13913102721304, 95427381109)]
assert diop_DN(32, -1) == []
# |N| > 1
# Some tests were created using calculator at
# http://www.numbertheory.org/php/patz.html
assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)]
# Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions
# So (-3, 1) and (393, 109) should be in the same equivalent class
assert equivalent(-3, 1, 393, 109, 13, -4) == True
assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)]
assert set(diop_DN(157, 12)) == \
set([(13, 1), (10663, 851), (579160, 46222), \
(483790960,38610722), (26277068347, 2097138361), (21950079635497, 1751807067011)])
assert diop_DN(13, 25) == [(3245, 900)]
assert diop_DN(192, 18) == []
assert diop_DN(23, 13) == [(-6, 1), (6, 1)]
assert diop_DN(167, 2) == [(13, 1)]
assert diop_DN(167, -2) == []
assert diop_DN(123, -2) == [(11, 1)]
# One calculator returned [(11, 1), (-11, 1)] but both of these are in
# the same equivalence class
assert equivalent(11, 1, -11, 1, 123, -2)
assert diop_DN(123, -23) == [(-10, 1), (10, 1)]
assert diop_DN(0, 0, t) == [(0, t)]
assert diop_DN(0, -1, t) == []
def test_bf_pell():
assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)]
assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)]
assert diop_bf_DN(167, -2) == []
assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)]
assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)]
assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)]
assert diop_bf_DN(340, -4) == [(756, 41)]
assert diop_bf_DN(-1, 0, t) == [(0, 0)]
assert diop_bf_DN(0, 0, t) == [(0, t)]
assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)]
assert diop_bf_DN(3, 0, t) == [(0, 0)]
assert diop_bf_DN(1, -2, t) == []
def test_length():
assert length(2, 1, 0) == 1
assert length(-2, 4, 5) == 3
assert length(-5, 4, 17) == 4
assert length(0, 4, 13) == 6
assert length(7, 13, 11) == 23
assert length(1, 6, 4) == 2
def is_pell_transformation_ok(eq):
"""
Test whether X*Y, X, or Y terms are present in the equation
after transforming the equation using the transformation returned
by transformation_to_pell(). If they are not present we are good.
Moreover, coefficient of X**2 should be a divisor of coefficient of
Y**2 and the constant term.
"""
A, B = transformation_to_DN(eq)
u = (A*Matrix([X, Y]) + B)[0]
v = (A*Matrix([X, Y]) + B)[1]
simplified = diop_simplify(eq.subs(zip((x, y), (u, v))))
coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args])
for term in [X*Y, X, Y]:
if term in coeff.keys():
return False
for term in [X**2, Y**2, 1]:
if term not in coeff.keys():
coeff[term] = 0
if coeff[X**2] != 0:
return divisible(coeff[Y**2], coeff[X**2]) and \
divisible(coeff[1], coeff[X**2])
return True
def test_transformation_to_pell():
assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14)
assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23)
assert is_pell_transformation_ok(x**2 - y**2 + 17)
assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23)
assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5)
assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130)
assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89)
assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950)
def test_find_DN():
assert find_DN(x**2 - 2*x - y**2) == (1, 1)
assert find_DN(x**2 - 3*y**2 - 5) == (3, 5)
assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7)
assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36)
assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84)
assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0)
assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480)
def test_ldescent():
# Equations which have solutions
u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1),
(4, 32), (17, 13), (123689, 1), (19, -570)])
for a, b in u:
w, x, y = ldescent(a, b)
assert a*x**2 + b*y**2 == w**2
assert ldescent(-1, -1) is None
def test_diop_ternary_quadratic_normal():
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
assert check_solutions(23*x**2 + 616*y**2 - z**2)
assert check_solutions(5*x**2 + 4*y**2 - z**2)
assert check_solutions(3*x**2 + 6*y**2 - 3*z**2)
assert check_solutions(x**2 + 3*y**2 - z**2)
assert check_solutions(4*x**2 + 5*y**2 - z**2)
assert check_solutions(x**2 + y**2 - z**2)
assert check_solutions(16*x**2 + y**2 - 25*z**2)
assert check_solutions(6*x**2 - y**2 + 10*z**2)
assert check_solutions(213*x**2 + 12*y**2 - 9*z**2)
assert check_solutions(34*x**2 - 3*y**2 - 301*z**2)
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
def is_normal_transformation_ok(eq):
A = transformation_to_normal(eq)
X, Y, Z = A*Matrix([x, y, z])
simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z))))
coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
for term in [X*Y, Y*Z, X*Z]:
if term in coeff.keys():
return False
return True
def test_transformation_to_normal():
assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2)
assert is_normal_transformation_ok(x**2 + 23*y*z)
assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y)
assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z)
assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z)
assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z)
assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2)
assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z)
assert is_normal_transformation_ok(2*x*z + 3*y*z)
def test_diop_ternary_quadratic():
assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y)
assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z)
assert check_solutions(3*x**2 - x*y - y*z - x*z)
assert check_solutions(x**2 - y*z - x*z)
assert check_solutions(5*x**2 - 3*x*y - x*z)
assert check_solutions(4*x**2 - 5*y**2 - x*z)
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
assert check_solutions(8*x**2 - 12*y*z)
assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2)
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z)
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z)
assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
assert check_solutions(x*y - 7*y*z + 13*x*z)
assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None)
assert diop_ternary_quadratic_normal(x**2 + y**2) is None
raises(ValueError, lambda:
_diop_ternary_quadratic_normal((x, y, z),
{x*y: 1, x**2: 2, y**2: 3, z**2: 0}))
eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2
assert diop_ternary_quadratic(eq) == (7, 2, 0)
assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \
(1, 0, 2)
assert diop_ternary_quadratic(x*y + 2*y*z) == \
(-2, 0, n1)
eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2
assert parametrize_ternary_quadratic(eq) == \
(8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q)
# this cannot be tested with diophantine because it will
# factor into a product
assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q)
def test_square_factor():
assert square_factor(1) == square_factor(-1) == 1
assert square_factor(0) == 1
assert square_factor(5) == square_factor(-5) == 1
assert square_factor(4) == square_factor(-4) == 2
assert square_factor(12) == square_factor(-12) == 2
assert square_factor(6) == 1
assert square_factor(18) == 3
assert square_factor(52) == 2
assert square_factor(49) == 7
assert square_factor(392) == 14
assert square_factor(factorint(-12)) == 2
def test_parametrize_ternary_quadratic():
assert check_solutions(x**2 + y**2 - z**2)
assert check_solutions(x**2 + 2*x*y + z**2)
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
assert check_solutions(x**2 - y**2 - z**2)
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y)
assert check_solutions(8*x*y + z**2)
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z)
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
def test_no_square_ternary_quadratic():
assert check_solutions(2*x*y + y*z - 3*x*z)
assert check_solutions(189*x*y - 345*y*z - 12*x*z)
assert check_solutions(23*x*y + 34*y*z)
assert check_solutions(x*y + y*z + z*x)
assert check_solutions(23*x*y + 23*y*z + 23*x*z)
def test_descent():
u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)])
for a, b in u:
w, x, y = descent(a, b)
assert a*x**2 + b*y**2 == w**2
# the docstring warns against bad input, so these are expected results
# - can't both be negative
raises(TypeError, lambda: descent(-1, -3))
# A can't be zero unless B != 1
raises(ZeroDivisionError, lambda: descent(0, 3))
# supposed to be square-free
raises(TypeError, lambda: descent(4, 3))
def test_diophantine():
assert check_solutions((x - y)*(y - z)*(z - x))
assert check_solutions((x - y)*(x**2 + y**2 - z**2))
assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2))
assert check_solutions((x**2 - 3*y**2 - 1))
assert check_solutions(y**2 + 7*x*y)
assert check_solutions(x**2 - 3*x*y + y**2)
assert check_solutions(z*(x**2 - y**2 - 15))
assert check_solutions(x*(2*y - 2*z + 5))
assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15))
assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z))
assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w))
# Following test case caused problems in parametric representation
# But this can be solved by factroing out y.
# No need to use methods for ternary quadratic equations.
assert check_solutions(y**2 - 7*x*y + 4*y*z)
assert check_solutions(x**2 - 2*x + 1)
assert diophantine(x - y) == diophantine(Eq(x, y))
assert diophantine(3*x*pi - 2*y*pi) == set([(2*t_0, 3*t_0)])
eq = x**2 + y**2 + z**2 - 14
base_sol = set([(1, 2, 3)])
assert diophantine(eq) == base_sol
complete_soln = set(signed_permutations(base_sol.pop()))
assert diophantine(eq, permute=True) == complete_soln
assert diophantine(x**2 + x*Rational(15, 14) - 3) == set()
# test issue 11049
eq = 92*x**2 - 99*y**2 - z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
(9, 7, 51)
assert diophantine(eq) == set([(
891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2,
5049*p**2 - 1386*p*q - 51*q**2)])
eq = 2*x**2 + 2*y**2 - z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
(1, 1, 2)
assert diophantine(eq) == set([(
2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
4*p**2 - 4*p*q + 2*q**2)])
eq = 411*x**2+57*y**2-221*z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
(2021, 2645, 3066)
assert diophantine(eq) == \
set([(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q -
584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)])
eq = 573*x**2+267*y**2-984*z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
(49, 233, 127)
assert diophantine(eq) == \
set([(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2,
11303*p**2 - 41474*p*q + 41656*q**2)])
# this produces factors during reconstruction
eq = x**2 + 3*y**2 - 12*z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
(0, 2, 1)
assert diophantine(eq) == \
set([(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)])
# solvers have not been written for every type
raises(NotImplementedError, lambda: diophantine(x*y**2 + 1))
# rational expressions
assert diophantine(1/x) == set()
assert diophantine(1/x + 1/y - S.Half)
set([(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)])
assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \
set([(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)])
def test_general_pythagorean():
from sympy.abc import a, b, c, d, e
assert check_solutions(a**2 + b**2 + c**2 - d**2)
assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2)
assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2)
assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 )
assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2)
assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2)
assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2)
def test_diop_general_sum_of_squares_quick():
for i in range(3, 10):
assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i)
raises(ValueError, lambda: _diop_general_sum_of_squares((x, y), 2))
assert _diop_general_sum_of_squares((x, y, z), -2) == set()
eq = x**2 + y**2 + z**2 - (1 + 4 + 9)
assert diop_general_sum_of_squares(eq) == \
set([(1, 2, 3)])
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313
assert len(diop_general_sum_of_squares(eq, 3)) == 3
# issue 11016
var = symbols(':5') + (symbols('6', negative=True),)
eq = Add(*[i**2 for i in var]) - 112
base_soln = set(
[(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7),
(0, 1, 1, 1, 3, -10), (0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8),
(0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6), (1, 1, 3, 4, 6, -7),
(0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9),
(0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6),
(0, 2, 2, 2, 6, -8), (0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7),
(0, 1, 5, 5, 5, -6)])
assert diophantine(eq) == base_soln
assert len(diophantine(eq, permute=True)) == 196800
# handle negated squares with signsimp
assert diophantine(12 - x**2 - y**2 - z**2) == set([(2, 2, 2)])
# diophantine handles simplification, so classify_diop should
# not have to look for additional patterns that are removed
# by diophantine
eq = a**2 + b**2 + c**2 + d**2 - 4
raises(NotImplementedError, lambda: classify_diop(-eq))
def test_diop_partition():
for n in [8, 10]:
for k in range(1, 8):
for p in partition(n, k):
assert len(p) == k
assert [p for p in partition(3, 5)] == []
assert [list(p) for p in partition(3, 5, 1)] == [
[0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]]
assert list(partition(0)) == [()]
assert list(partition(1, 0)) == [()]
assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]]
def test_prime_as_sum_of_two_squares():
for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]:
a, b = prime_as_sum_of_two_squares(i)
assert a**2 + b**2 == i
assert prime_as_sum_of_two_squares(7) is None
ans = prime_as_sum_of_two_squares(800029)
assert ans == (450, 773) and type(ans[0]) is int
def test_sum_of_three_squares():
for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344,
800, 801, 802, 803, 804, 805, 806]:
a, b, c = sum_of_three_squares(i)
assert a**2 + b**2 + c**2 == i
assert sum_of_three_squares(7) is None
assert sum_of_three_squares((4**5)*15) is None
assert sum_of_three_squares(25) == (5, 0, 0)
assert sum_of_three_squares(4) == (0, 0, 2)
def test_sum_of_four_squares():
from random import randint
# this should never fail
n = randint(1, 100000000000000)
assert sum(i**2 for i in sum_of_four_squares(n)) == n
assert sum_of_four_squares(0) == (0, 0, 0, 0)
assert sum_of_four_squares(14) == (0, 1, 2, 3)
assert sum_of_four_squares(15) == (1, 1, 2, 3)
assert sum_of_four_squares(18) == (1, 2, 2, 3)
assert sum_of_four_squares(19) == (0, 1, 3, 3)
assert sum_of_four_squares(48) == (0, 4, 4, 4)
def test_power_representation():
tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4),
(32760, 2, 3)]
for test in tests:
n, p, k = test
f = power_representation(n, p, k)
while True:
try:
l = next(f)
assert len(l) == k
chk_sum = 0
for l_i in l:
chk_sum = chk_sum + l_i**p
assert chk_sum == n
except StopIteration:
break
assert list(power_representation(20, 2, 4, True)) == \
[(1, 1, 3, 3), (0, 0, 2, 4)]
raises(ValueError, lambda: list(power_representation(1.2, 2, 2)))
raises(ValueError, lambda: list(power_representation(2, 0, 2)))
raises(ValueError, lambda: list(power_representation(2, 2, 0)))
assert list(power_representation(-1, 2, 2)) == []
assert list(power_representation(1, 1, 1)) == [(1,)]
assert list(power_representation(3, 2, 1)) == []
assert list(power_representation(4, 2, 1)) == [(2,)]
assert list(power_representation(3**4, 4, 6, zeros=True)) == \
[(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)]
assert list(power_representation(3**4, 4, 5, zeros=False)) == []
assert list(power_representation(-2, 3, 2)) == [(-1, -1)]
assert list(power_representation(-2, 4, 2)) == []
assert list(power_representation(0, 3, 2, True)) == [(0, 0)]
assert list(power_representation(0, 3, 2, False)) == []
# when we are dealing with squares, do feasibility checks
assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0
# there will be a recursion error if these aren't recognized
big = 2**30
for i in [13, 10, 7, 5, 4, 2, 1]:
assert list(sum_of_powers(big, 2, big - i)) == []
def test_assumptions():
"""
Test whether diophantine respects the assumptions.
"""
#Test case taken from the below so question regarding assumptions in diophantine module
#https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy
m, n = symbols('m n', integer=True, positive=True)
diof = diophantine(n ** 2 + m * n - 500)
assert diof == set([(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)])
a, b = symbols('a b', integer=True, positive=False)
diof = diophantine(a*b + 2*a + 3*b - 6)
assert diof == set([(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)])
def check_solutions(eq):
"""
Determines whether solutions returned by diophantine() satisfy the original
equation. Hope to generalize this so we can remove functions like check_ternay_quadratic,
check_solutions_normal, check_solutions()
"""
s = diophantine(eq)
factors = Mul.make_args(eq)
var = list(eq.free_symbols)
var.sort(key=default_sort_key)
while s:
solution = s.pop()
for f in factors:
if diop_simplify(f.subs(zip(var, solution))) == 0:
break
else:
return False
return True
def test_diopcoverage():
eq = (2*x + y + 1)**2
assert diop_solve(eq) == set([(t_0, -2*t_0 - 1)])
eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18
assert diop_solve(eq) == set([(t_0, -t_0 - 3), (2*t_0 - 3, -t_0)])
assert diop_quadratic(x + y**2 - 3) == set([(-t**2 + 3, -t)])
assert diop_linear(x + y - 3) == (t_0, 3 - t_0)
assert base_solution_linear(0, 1, 2, t=None) == (0, 0)
ans = (3*t - 1, -2*t + 1)
assert base_solution_linear(4, 8, 12, t) == ans
assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans)
assert cornacchia(1, 1, 20) is None
assert cornacchia(1, 1, 5) == set([(2, 1)])
assert cornacchia(1, 2, 17) == set([(3, 2)])
raises(ValueError, lambda: reconstruct(4, 20, 1))
assert gaussian_reduce(4, 1, 3) == (1, 1)
eq = -w**2 - x**2 - y**2 + z**2
assert diop_general_pythagorean(eq) == \
diop_general_pythagorean(-eq) == \
(m1**2 + m2**2 - m3**2, 2*m1*m3,
2*m2*m3, m1**2 + m2**2 + m3**2)
assert check_param(S(3) + x/3, S(4) + x/2, S(2), x) == (None, None)
assert check_param(Rational(3, 2), S(4) + x, S(2), x) == (None, None)
assert check_param(S(4) + x, Rational(3, 2), S(2), x) == (None, None)
assert _nint_or_floor(16, 10) == 2
assert _odd(1) == (not _even(1)) == True
assert _odd(0) == (not _even(0)) == False
assert _remove_gcd(2, 4, 6) == (1, 2, 3)
raises(TypeError, lambda: _remove_gcd((2, 4, 6)))
assert sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11) == \
(11, 1, 5)
# it's ok if these pass some day when the solvers are implemented
raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12))
raises(NotImplementedError, lambda: diophantine(x**3 + y**2))
assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \
set([(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)])
def test_holzer():
# if the input is good, don't let it diverge in holzer()
# (but see test_fail_holzer below)
assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13)
# None in uv condition met; solution is not Holzer reduced
# so this will hopefully change but is here for coverage
assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2)
raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23))
@XFAIL
def test_fail_holzer():
eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2
a, b, c = 4, 79, 23
x, y, z = xyz = 26, 1, 11
X, Y, Z = ans = 2, 7, 13
assert eq(*xyz) == 0
assert eq(*ans) == 0
assert max(a*x**2, b*y**2, c*z**2) <= a*b*c
assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c
h = holzer(x, y, z, a, b, c)
assert h == ans # it would be nice to get the smaller soln
def test_issue_9539():
assert diophantine(6*w + 9*y + 20*x - z) == \
set([(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)])
def test_issue_8943():
assert diophantine(
(3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x))) == \
set([(0, 0, 0)])
def test_diop_sum_of_even_powers():
eq = x**4 + y**4 + z**4 - 2673
assert diop_solve(eq) == set([(3, 6, 6), (2, 4, 7)])
assert diop_general_sum_of_even_powers(eq, 2) == set(
[(3, 6, 6), (2, 4, 7)])
raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2))
neg = symbols('neg', negative=True)
eq = x**4 + y**4 + neg**4 - 2673
assert diop_general_sum_of_even_powers(eq) == set([(-3, 6, 6)])
assert diophantine(x**4 + y**4 + 2) == set()
assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set()
def test_sum_of_squares_powers():
tru = set([
(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9),
(0, 3, 4, 7, 7), (0, 3, 5, 5, 8), (1, 1, 2, 6, 9), (1, 1, 6, 6, 7),
(1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9),
(2, 3, 5, 6, 7), (3, 3, 4, 5, 8)])
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123
ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used
assert len(ans) == 14
assert ans == tru
raises(ValueError, lambda: list(sum_of_squares(10, -1)))
assert list(sum_of_squares(-10, 2)) == []
assert list(sum_of_squares(2, 3)) == []
assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)]
assert list(sum_of_squares(0, 3)) == []
assert list(sum_of_squares(4, 1)) == [(2,)]
assert list(sum_of_squares(5, 1)) == []
assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)]
assert list(sum_of_squares(11, 5, True)) == [
(1, 1, 1, 2, 2), (0, 0, 1, 1, 3)]
assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)]
assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [
1, 1, 1, 1, 2,
2, 1, 1, 2, 2,
2, 2, 2, 3, 2,
1, 3, 3, 3, 3,
4, 3, 3, 2, 2,
4, 4, 4, 4, 5]
assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [
0, 0, 0, 0, 0,
1, 0, 0, 1, 0,
0, 1, 0, 1, 1,
0, 1, 1, 0, 1,
2, 1, 1, 1, 1,
1, 1, 1, 1, 3]
for i in range(30):
s1 = set(sum_of_squares(i, 5, True))
assert not s1 or all(sum(j**2 for j in t) == i for t in s1)
s2 = set(sum_of_squares(i, 5))
assert all(sum(j**2 for j in t) == i for t in s2)
raises(ValueError, lambda: list(sum_of_powers(2, -1, 1)))
raises(ValueError, lambda: list(sum_of_powers(2, 1, -1)))
assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)]
assert list(sum_of_powers(-2, 4, 2)) == []
assert list(sum_of_powers(2, 1, 1)) == [(2,)]
assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)]
assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)]
assert list(sum_of_powers(6, 2, 2)) == []
assert list(sum_of_powers(3**5, 3, 1)) == []
assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6)
assert list(sum_of_powers(2**1000, 5, 2)) == []
def test__can_do_sum_of_squares():
assert _can_do_sum_of_squares(3, -1) is False
assert _can_do_sum_of_squares(-3, 1) is False
assert _can_do_sum_of_squares(0, 1)
assert _can_do_sum_of_squares(4, 1)
assert _can_do_sum_of_squares(1, 2)
assert _can_do_sum_of_squares(2, 2)
assert _can_do_sum_of_squares(3, 2) is False
def test_diophantine_permute_sign():
from sympy.abc import a, b, c, d, e
eq = a**4 + b**4 - (2**4 + 3**4)
base_sol = set([(2, 3)])
assert diophantine(eq) == base_sol
complete_soln = set(signed_permutations(base_sol.pop()))
assert diophantine(eq, permute=True) == complete_soln
eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234
assert len(diophantine(eq)) == 35
assert len(diophantine(eq, permute=True)) == 62000
soln = set([(-1, -1), (-1, 2), (1, -2), (1, 1)])
assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln
@XFAIL
def test_not_implemented():
eq = x**2 + y**4 - 1**2 - 3**4
assert diophantine(eq, syms=[x, y]) == set([(9, 1), (1, 3)])
def test_issue_9538():
eq = x - 3*y + 2
assert diophantine(eq, syms=[y,x]) == set([(t_0, 3*t_0 - 2)])
raises(TypeError, lambda: diophantine(eq, syms=set([y,x])))
def test_ternary_quadratic():
# solution with 3 parameters
s = diophantine(2*x**2 + y**2 - 2*z**2)
p, q, r = ordered(S(s).free_symbols)
assert s == {(
p**2 - 2*q**2,
-2*p**2 + 4*p*q - 4*p*r - 4*q**2,
p**2 - 4*p*q + 2*q**2 - 4*q*r)}
# solution with Mul in solution
s = diophantine(x**2 + 2*y**2 - 2*z**2)
assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)}
# solution with no Mul in solution
s = diophantine(2*x**2 + 2*y**2 - z**2)
assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
4*p**2 - 4*p*q + 2*q**2)}
# reduced form when parametrized
s = diophantine(3*x**2 + 72*y**2 - 27*z**2)
assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)}
assert parametrize_ternary_quadratic(
3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == (
2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 -
2*p*q + 3*q**2)
assert parametrize_ternary_quadratic(
124*x**2 - 30*y**2 - 7729*z**2) == (
-1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q -
695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
|
777642500d24900f906426ff3ccdcffca42f7090e6757e74b6fa23c07cf22045 | """Tests for tools for solving inequalities and systems of inequalities. """
from sympy import (And, Eq, FiniteSet, Ge, Gt, Interval, Le, Lt, Ne, oo, I,
Or, S, sin, cos, tan, sqrt, Symbol, Union, Integral, Sum,
Function, Poly, PurePoly, pi, root, log, exp, Dummy, Abs,
Piecewise, Rational)
from sympy.solvers.inequalities import (reduce_inequalities,
solve_poly_inequality as psolve,
reduce_rational_inequalities,
solve_univariate_inequality as isolve,
reduce_abs_inequality,
_solve_inequality)
from sympy.polys.rootoftools import rootof
from sympy.solvers.solvers import solve
from sympy.solvers.solveset import solveset
from sympy.abc import x, y
from sympy.utilities.pytest import raises, XFAIL
inf = oo.evalf()
def test_solve_poly_inequality():
assert psolve(Poly(0, x), '==') == [S.Reals]
assert psolve(Poly(1, x), '==') == [S.EmptySet]
assert psolve(PurePoly(x + 1, x), ">") == [Interval(-1, oo, True, False)]
def test_reduce_poly_inequalities_real_interval():
assert reduce_rational_inequalities(
[[Eq(x**2, 0)]], x, relational=False) == FiniteSet(0)
assert reduce_rational_inequalities(
[[Le(x**2, 0)]], x, relational=False) == FiniteSet(0)
assert reduce_rational_inequalities(
[[Lt(x**2, 0)]], x, relational=False) == S.EmptySet
assert reduce_rational_inequalities(
[[Ge(x**2, 0)]], x, relational=False) == \
S.Reals if x.is_real else Interval(-oo, oo)
assert reduce_rational_inequalities(
[[Gt(x**2, 0)]], x, relational=False) == \
FiniteSet(0).complement(S.Reals)
assert reduce_rational_inequalities(
[[Ne(x**2, 0)]], x, relational=False) == \
FiniteSet(0).complement(S.Reals)
assert reduce_rational_inequalities(
[[Eq(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1)
assert reduce_rational_inequalities(
[[Le(x**2, 1)]], x, relational=False) == Interval(-1, 1)
assert reduce_rational_inequalities(
[[Lt(x**2, 1)]], x, relational=False) == Interval(-1, 1, True, True)
assert reduce_rational_inequalities(
[[Ge(x**2, 1)]], x, relational=False) == \
Union(Interval(-oo, -1), Interval(1, oo))
assert reduce_rational_inequalities(
[[Gt(x**2, 1)]], x, relational=False) == \
Interval(-1, 1).complement(S.Reals)
assert reduce_rational_inequalities(
[[Ne(x**2, 1)]], x, relational=False) == \
FiniteSet(-1, 1).complement(S.Reals)
assert reduce_rational_inequalities([[Eq(
x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).evalf()
assert reduce_rational_inequalities(
[[Le(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0)
assert reduce_rational_inequalities([[Lt(
x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0, True, True)
assert reduce_rational_inequalities(
[[Ge(x**2, 1.0)]], x, relational=False) == \
Union(Interval(-inf, -1.0), Interval(1.0, inf))
assert reduce_rational_inequalities(
[[Gt(x**2, 1.0)]], x, relational=False) == \
Union(Interval(-inf, -1.0, right_open=True),
Interval(1.0, inf, left_open=True))
assert reduce_rational_inequalities([[Ne(
x**2, 1.0)]], x, relational=False) == \
FiniteSet(-1.0, 1.0).complement(S.Reals)
s = sqrt(2)
assert reduce_rational_inequalities([[Lt(
x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == S.EmptySet
assert reduce_rational_inequalities([[Le(x**2 - 1, 0), Ge(
x**2 - 1, 0)]], x, relational=False) == FiniteSet(-1, 1)
assert reduce_rational_inequalities(
[[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False))
assert reduce_rational_inequalities(
[[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False))
assert reduce_rational_inequalities(
[[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True))
assert reduce_rational_inequalities(
[[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, True, True), Interval(1, s, True, True))
assert reduce_rational_inequalities(
[[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, True, True), Interval(-1, 1, True, True),
Interval(1, s, True, True))
assert reduce_rational_inequalities([[Lt(x**2, -1.)]], x) is S.false
def test_reduce_poly_inequalities_complex_relational():
assert reduce_rational_inequalities(
[[Eq(x**2, 0)]], x, relational=True) == Eq(x, 0)
assert reduce_rational_inequalities(
[[Le(x**2, 0)]], x, relational=True) == Eq(x, 0)
assert reduce_rational_inequalities(
[[Lt(x**2, 0)]], x, relational=True) == False
assert reduce_rational_inequalities(
[[Ge(x**2, 0)]], x, relational=True) == And(Lt(-oo, x), Lt(x, oo))
assert reduce_rational_inequalities(
[[Gt(x**2, 0)]], x, relational=True) == \
And(Gt(x, -oo), Lt(x, oo), Ne(x, 0))
assert reduce_rational_inequalities(
[[Ne(x**2, 0)]], x, relational=True) == \
And(Gt(x, -oo), Lt(x, oo), Ne(x, 0))
for one in (S.One, S(1.0)):
inf = one*oo
assert reduce_rational_inequalities(
[[Eq(x**2, one)]], x, relational=True) == \
Or(Eq(x, -one), Eq(x, one))
assert reduce_rational_inequalities(
[[Le(x**2, one)]], x, relational=True) == \
And(And(Le(-one, x), Le(x, one)))
assert reduce_rational_inequalities(
[[Lt(x**2, one)]], x, relational=True) == \
And(And(Lt(-one, x), Lt(x, one)))
assert reduce_rational_inequalities(
[[Ge(x**2, one)]], x, relational=True) == \
And(Or(And(Le(one, x), Lt(x, inf)), And(Le(x, -one), Lt(-inf, x))))
assert reduce_rational_inequalities(
[[Gt(x**2, one)]], x, relational=True) == \
And(Or(And(Lt(-inf, x), Lt(x, -one)), And(Lt(one, x), Lt(x, inf))))
assert reduce_rational_inequalities(
[[Ne(x**2, one)]], x, relational=True) == \
Or(And(Lt(-inf, x), Lt(x, -one)),
And(Lt(-one, x), Lt(x, one)),
And(Lt(one, x), Lt(x, inf)))
def test_reduce_rational_inequalities_real_relational():
assert reduce_rational_inequalities([], x) == False
assert reduce_rational_inequalities(
[[(x**2 + 3*x + 2)/(x**2 - 16) >= 0]], x, relational=False) == \
Union(Interval.open(-oo, -4), Interval(-2, -1), Interval.open(4, oo))
assert reduce_rational_inequalities(
[[((-2*x - 10)*(3 - x))/((x**2 + 5)*(x - 2)**2) < 0]], x,
relational=False) == \
Union(Interval.open(-5, 2), Interval.open(2, 3))
assert reduce_rational_inequalities([[(x + 1)/(x - 5) <= 0]], x,
relational=False) == \
Interval.Ropen(-1, 5)
assert reduce_rational_inequalities([[(x**2 + 4*x + 3)/(x - 1) > 0]], x,
relational=False) == \
Union(Interval.open(-3, -1), Interval.open(1, oo))
assert reduce_rational_inequalities([[(x**2 - 16)/(x - 1)**2 < 0]], x,
relational=False) == \
Union(Interval.open(-4, 1), Interval.open(1, 4))
assert reduce_rational_inequalities([[(3*x + 1)/(x + 4) >= 1]], x,
relational=False) == \
Union(Interval.open(-oo, -4), Interval.Ropen(Rational(3, 2), oo))
assert reduce_rational_inequalities([[(x - 8)/x <= 3 - x]], x,
relational=False) == \
Union(Interval.Lopen(-oo, -2), Interval.Lopen(0, 4))
# issue sympy/sympy#10237
assert reduce_rational_inequalities(
[[x < oo, x >= 0, -oo < x]], x, relational=False) == Interval(0, oo)
def test_reduce_abs_inequalities():
e = abs(x - 5) < 3
ans = And(Lt(2, x), Lt(x, 8))
assert reduce_inequalities(e) == ans
assert reduce_inequalities(e, x) == ans
assert reduce_inequalities(abs(x - 5)) == Eq(x, 5)
assert reduce_inequalities(
abs(2*x + 3) >= 8) == Or(And(Le(Rational(5, 2), x), Lt(x, oo)),
And(Le(x, Rational(-11, 2)), Lt(-oo, x)))
assert reduce_inequalities(abs(x - 4) + abs(
3*x - 5) < 7) == And(Lt(S.Half, x), Lt(x, 4))
assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7) == \
Or(And(S(-2) < x, x < -1), And(S.Half < x, x < 4))
nr = Symbol('nr', extended_real=False)
raises(TypeError, lambda: reduce_inequalities(abs(nr - 5) < 3))
assert reduce_inequalities(x < 3, symbols=[x, nr]) == And(-oo < x, x < 3)
def test_reduce_inequalities_general():
assert reduce_inequalities(Ge(sqrt(2)*x, 1)) == And(sqrt(2)/2 <= x, x < oo)
assert reduce_inequalities(PurePoly(x + 1, x) > 0) == And(S.NegativeOne < x, x < oo)
def test_reduce_inequalities_boolean():
assert reduce_inequalities(
[Eq(x**2, 0), True]) == Eq(x, 0)
assert reduce_inequalities([Eq(x**2, 0), False]) == False
assert reduce_inequalities(x**2 >= 0) is S.true # issue 10196
def test_reduce_inequalities_multivariate():
assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == And(
Or(And(Le(S.One, x), Lt(x, oo)), And(Le(x, -1), Lt(-oo, x))),
Or(And(Le(S.One, y), Lt(y, oo)), And(Le(y, -1), Lt(-oo, y))))
def test_reduce_inequalities_errors():
raises(NotImplementedError, lambda: reduce_inequalities(Ge(sin(x) + x, 1)))
raises(NotImplementedError, lambda: reduce_inequalities(Ge(x**2*y + y, 1)))
def test__solve_inequalities():
assert reduce_inequalities(x + y < 1, symbols=[x]) == (x < 1 - y)
assert reduce_inequalities(x + y >= 1, symbols=[x]) == (x < oo) & (x >= -y + 1)
assert reduce_inequalities(Eq(0, x - y), symbols=[x]) == Eq(x, y)
assert reduce_inequalities(Ne(0, x - y), symbols=[x]) == Ne(x, y)
def test_issue_6343():
eq = -3*x**2/2 - x*Rational(45, 4) + Rational(33, 2) > 0
assert reduce_inequalities(eq) == \
And(x < Rational(-15, 4) + sqrt(401)/4, -sqrt(401)/4 - Rational(15, 4) < x)
def test_issue_8235():
assert reduce_inequalities(x**2 - 1 < 0) == \
And(S.NegativeOne < x, x < 1)
assert reduce_inequalities(x**2 - 1 <= 0) == \
And(S.NegativeOne <= x, x <= 1)
assert reduce_inequalities(x**2 - 1 > 0) == \
Or(And(-oo < x, x < -1), And(x < oo, S.One < x))
assert reduce_inequalities(x**2 - 1 >= 0) == \
Or(And(-oo < x, x <= -1), And(S.One <= x, x < oo))
eq = x**8 + x - 9 # we want CRootOf solns here
sol = solve(eq >= 0)
tru = Or(And(rootof(eq, 1) <= x, x < oo), And(-oo < x, x <= rootof(eq, 0)))
assert sol == tru
# recast vanilla as real
assert solve(sqrt((-x + 1)**2) < 1) == And(S.Zero < x, x < 2)
def test_issue_5526():
assert reduce_inequalities(0 <=
x + Integral(y**2, (y, 1, 3)) - 1, [x]) == \
(x >= -Integral(y**2, (y, 1, 3)) + 1)
f = Function('f')
e = Sum(f(x), (x, 1, 3))
assert reduce_inequalities(0 <= x + e + y**2, [x]) == \
(x >= -y**2 - Sum(f(x), (x, 1, 3)))
def test_solve_univariate_inequality():
assert isolve(x**2 >= 4, x, relational=False) == Union(Interval(-oo, -2),
Interval(2, oo))
assert isolve(x**2 >= 4, x) == Or(And(Le(2, x), Lt(x, oo)), And(Le(x, -2),
Lt(-oo, x)))
assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x, relational=False) == \
Union(Interval(1, 2), Interval(3, oo))
assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x) == \
Or(And(Le(1, x), Le(x, 2)), And(Le(3, x), Lt(x, oo)))
assert isolve((x - 1)*(x - 2)*(x - 4) < 0, x, domain = FiniteSet(0, 3)) == \
Or(Eq(x, 0), Eq(x, 3))
# issue 2785:
assert isolve(x**3 - 2*x - 1 > 0, x, relational=False) == \
Union(Interval(-1, -sqrt(5)/2 + S.Half, True, True),
Interval(S.Half + sqrt(5)/2, oo, True, True))
# issue 2794:
assert isolve(x**3 - x**2 + x - 1 > 0, x, relational=False) == \
Interval(1, oo, True)
#issue 13105
assert isolve((x + I)*(x + 2*I) < 0, x) == Eq(x, 0)
assert isolve(((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I) < 0, x) == Or(Eq(x, 1), Eq(x, 2))
assert isolve((((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I))/(x - 2) > 0, x) == Eq(x, 1)
raises (ValueError, lambda: isolve((x**2 - 3*x*I + 2)/x < 0, x))
# numerical testing in valid() is needed
assert isolve(x**7 - x - 2 > 0, x) == \
And(rootof(x**7 - x - 2, 0) < x, x < oo)
# handle numerator and denominator; although these would be handled as
# rational inequalities, these test confirm that the right thing is done
# when the domain is EX (e.g. when 2 is replaced with sqrt(2))
assert isolve(1/(x - 2) > 0, x) == And(S(2) < x, x < oo)
den = ((x - 1)*(x - 2)).expand()
assert isolve((x - 1)/den <= 0, x) == \
Or(And(-oo < x, x < 1), And(S.One < x, x < 2))
n = Dummy('n')
raises(NotImplementedError, lambda: isolve(Abs(x) <= n, x, relational=False))
c1 = Dummy("c1", positive=True)
raises(NotImplementedError, lambda: isolve(n/c1 < 0, c1))
n = Dummy('n', negative=True)
assert isolve(n/c1 > -2, c1) == (-n/2 < c1)
assert isolve(n/c1 < 0, c1) == True
assert isolve(n/c1 > 0, c1) == False
zero = cos(1)**2 + sin(1)**2 - 1
raises(NotImplementedError, lambda: isolve(x**2 < zero, x))
raises(NotImplementedError, lambda: isolve(
x**2 < zero*I, x))
raises(NotImplementedError, lambda: isolve(1/(x - y) < 2, x))
raises(NotImplementedError, lambda: isolve(1/(x - y) < 0, x))
raises(ValueError, lambda: isolve(x - I < 0, x))
zero = x**2 + x - x*(x + 1)
assert isolve(zero < 0, x, relational=False) is S.EmptySet
assert isolve(zero <= 0, x, relational=False) is S.Reals
# make sure iter_solutions gets a default value
raises(NotImplementedError, lambda: isolve(
Eq(cos(x)**2 + sin(x)**2, 1), x))
def test_trig_inequalities():
# all the inequalities are solved in a periodic interval.
assert isolve(sin(x) < S.Half, x, relational=False) == \
Union(Interval(0, pi/6, False, True), Interval(pi*Rational(5, 6), 2*pi, True, False))
assert isolve(sin(x) > S.Half, x, relational=False) == \
Interval(pi/6, pi*Rational(5, 6), True, True)
assert isolve(cos(x) < S.Zero, x, relational=False) == \
Interval(pi/2, pi*Rational(3, 2), True, True)
assert isolve(cos(x) >= S.Zero, x, relational=False) == \
Union(Interval(0, pi/2), Interval(pi*Rational(3, 2), 2*pi))
assert isolve(tan(x) < S.One, x, relational=False) == \
Union(Interval.Ropen(0, pi/4), Interval.Lopen(pi/2, pi))
assert isolve(sin(x) <= S.Zero, x, relational=False) == \
Union(FiniteSet(S.Zero), Interval(pi, 2*pi))
assert isolve(sin(x) <= S.One, x, relational=False) == S.Reals
assert isolve(cos(x) < S(-2), x, relational=False) == S.EmptySet
assert isolve(sin(x) >= S.NegativeOne, x, relational=False) == S.Reals
assert isolve(cos(x) > S.One, x, relational=False) == S.EmptySet
def test_issue_9954():
assert isolve(x**2 >= 0, x, relational=False) == S.Reals
assert isolve(x**2 >= 0, x, relational=True) == S.Reals.as_relational(x)
assert isolve(x**2 < 0, x, relational=False) == S.EmptySet
assert isolve(x**2 < 0, x, relational=True) == S.EmptySet.as_relational(x)
@XFAIL
def test_slow_general_univariate():
r = rootof(x**5 - x**2 + 1, 0)
assert solve(sqrt(x) + 1/root(x, 3) > 1) == \
Or(And(0 < x, x < r**6), And(r**6 < x, x < oo))
def test_issue_8545():
eq = 1 - x - abs(1 - x)
ans = And(Lt(1, x), Lt(x, oo))
assert reduce_abs_inequality(eq, '<', x) == ans
eq = 1 - x - sqrt((1 - x)**2)
assert reduce_inequalities(eq < 0) == ans
def test_issue_8974():
assert isolve(-oo < x, x) == And(-oo < x, x < oo)
assert isolve(oo > x, x) == And(-oo < x, x < oo)
def test_issue_10198():
assert reduce_inequalities(
-1 + 1/abs(1/x - 1) < 0) == Or(
And(-oo < x, x < 0), And(S.Zero < x, x < S.Half)
)
assert reduce_inequalities(abs(1/sqrt(x)) - 1, x) == Eq(x, 1)
assert reduce_abs_inequality(-3 + 1/abs(1 - 1/x), '<', x) == \
Or(And(-oo < x, x < 0),
And(S.Zero < x, x < Rational(3, 4)), And(Rational(3, 2) < x, x < oo))
raises(ValueError,lambda: reduce_abs_inequality(-3 + 1/abs(
1 - 1/sqrt(x)), '<', x))
def test_issue_10047():
# issue 10047: this must remain an inequality, not True, since if x
# is not real the inequality is invalid
# assert solve(sin(x) < 2) == (x <= oo)
# with PR 16956, (x <= oo) autoevaluates when x is extended_real
assert solve(sin(x) < 2) == True
def test_issue_10268():
assert solve(log(x) < 1000) == And(S.Zero < x, x < exp(1000))
@XFAIL
def test_isolve_Sets():
n = Dummy('n')
assert isolve(Abs(x) <= n, x, relational=False) == \
Piecewise((S.EmptySet, n < 0), (Interval(-n, n), True))
def test_issue_10671_12466():
assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi)
i = Interval(1, 10)
assert solveset((1/x).diff(x) < 0, x, i) == i
assert solveset((log(x - 6)/x) <= 0, x, S.Reals) == \
Interval.Lopen(6, 7)
def test__solve_inequality():
for op in (Gt, Lt, Le, Ge, Eq, Ne):
assert _solve_inequality(op(x, 1), x).lhs == x
assert _solve_inequality(op(S.One, x), x).lhs == x
# don't get tricked by symbol on right: solve it
assert _solve_inequality(Eq(2*x - 1, x), x) == Eq(x, 1)
ie = Eq(S.One, y)
assert _solve_inequality(ie, x) == ie
for fx in (x**2, exp(x), sin(x) + cos(x), x*(1 + x)):
for c in (0, 1):
e = 2*fx - c > 0
assert _solve_inequality(e, x, linear=True) == (
fx > c/S(2))
assert _solve_inequality(2*x**2 + 2*x - 1 < 0, x, linear=True) == (
x*(x + 1) < S.Half)
assert _solve_inequality(Eq(x*y, 1), x) == Eq(x*y, 1)
nz = Symbol('nz', nonzero=True)
assert _solve_inequality(Eq(x*nz, 1), x) == Eq(x, 1/nz)
assert _solve_inequality(x*nz < 1, x) == (x*nz < 1)
a = Symbol('a', positive=True)
assert _solve_inequality(a/x > 1, x) == (S.Zero < x) & (x < a)
assert _solve_inequality(a/x > 1, x, linear=True) == (1/x > 1/a)
# make sure to include conditions under which solution is valid
e = Eq(1 - x, x*(1/x - 1))
assert _solve_inequality(e, x) == Ne(x, 0)
assert _solve_inequality(x < x*(1/x - 1), x) == (x < S.Half) & Ne(x, 0)
def test__pt():
from sympy.solvers.inequalities import _pt
assert _pt(-oo, oo) == 0
assert _pt(S.One, S(3)) == 2
assert _pt(S.One, oo) == _pt(oo, S.One) == 2
assert _pt(S.One, -oo) == _pt(-oo, S.One) == S.Half
assert _pt(S.NegativeOne, oo) == _pt(oo, S.NegativeOne) == Rational(-1, 2)
assert _pt(S.NegativeOne, -oo) == _pt(-oo, S.NegativeOne) == -2
assert _pt(x, oo) == _pt(oo, x) == x + 1
assert _pt(x, -oo) == _pt(-oo, x) == x - 1
raises(ValueError, lambda: _pt(Dummy('i', infinite=True), S.One))
|
bd09efecd2118b703dc03601f3c3eadaedc12d39dadbef823d28ddf14ec0a7e7 | from sympy import (acos, acosh, asinh, atan, cos, Derivative, diff,
Dummy, Eq, Ne, erf, erfi, exp, Function, I, Integral, LambertW, log, O, pi,
Rational, rootof, S, sin, sqrt, Subs, Symbol, tan, asin, sinh,
Piecewise, symbols, Poly, sec, Ei, re, im, atan2, collect)
from sympy.solvers.ode import (_undetermined_coefficients_match,
checkodesol, classify_ode, classify_sysode, constant_renumber,
constantsimp, homogeneous_order, infinitesimals, checkinfsol,
checksysodesol, solve_ics, dsolve, get_numbered_constants)
from sympy.functions import airyai, airybi, besselj, bessely
from sympy.solvers.deutils import ode_order
from sympy.utilities.pytest import XFAIL, skip, raises, slow, ON_TRAVIS, SKIP
from sympy.utilities.misc import filldedent
C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11')
u, x, y, z = symbols('u,x:z', real=True)
f = Function('f')
g = Function('g')
h = Function('h')
# Note: the tests below may fail (but still be correct) if ODE solver,
# the integral engine, solve(), or even simplify() changes. Also, in
# differently formatted solutions, the arbitrary constants might not be
# equal. Using specific hints in tests can help to avoid this.
# Tests of order higher than 1 should run the solutions through
# constant_renumber because it will normalize it (constant_renumber causes
# dsolve() to return different results on different machines)
def test_linear_2eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
k, l, m, n = symbols('k, l, m, n', Integer=True)
t = Symbol('t')
x0, y0 = symbols('x0, y0', cls=Function)
eq1 = (Eq(diff(x(t),t), 9*y(t)), Eq(diff(y(t),t), 12*x(t)))
sol1 = [Eq(x(t), 9*C1*exp(6*sqrt(3)*t) + 9*C2*exp(-6*sqrt(3)*t)), \
Eq(y(t), 6*sqrt(3)*C1*exp(6*sqrt(3)*t) - 6*sqrt(3)*C2*exp(-6*sqrt(3)*t))]
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = (Eq(diff(x(t),t), 2*x(t) + 4*y(t)), Eq(diff(y(t),t), 12*x(t) + 41*y(t)))
sol2 = [Eq(x(t), 4*C1*exp(t*(sqrt(1713)/2 + Rational(43, 2))) + 4*C2*exp(t*(-sqrt(1713)/2 + Rational(43, 2)))), \
Eq(y(t), C1*(Rational(39, 2) + sqrt(1713)/2)*exp(t*(sqrt(1713)/2 + Rational(43, 2))) + \
C2*(-sqrt(1713)/2 + Rational(39, 2))*exp(t*(-sqrt(1713)/2 + Rational(43, 2))))]
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = (Eq(diff(x(t),t), x(t) + y(t)), Eq(diff(y(t),t), -2*x(t) + 2*y(t)))
sol3 = [Eq(x(t), (C1*cos(sqrt(7)*t/2) + C2*sin(sqrt(7)*t/2))*exp(t*Rational(3, 2))), \
Eq(y(t), (C1*(-sqrt(7)*sin(sqrt(7)*t/2)/2 + cos(sqrt(7)*t/2)/2) + \
C2*(sin(sqrt(7)*t/2)/2 + sqrt(7)*cos(sqrt(7)*t/2)/2))*exp(t*Rational(3, 2)))]
assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23))
sol4 = [Eq(x(t), C1*exp(t*(sqrt(6) + 3)) + C2*exp(t*(-sqrt(6) + 3)) - Rational(22, 3)), \
Eq(y(t), C1*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) + C2*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) - Rational(5, 3))]
assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23))
sol5 = [Eq(x(t), (C1*cos(sqrt(2)*t) + C2*sin(sqrt(2)*t))*exp(t) - Rational(58, 3)), \
Eq(y(t), (-sqrt(2)*C1*sin(sqrt(2)*t) + sqrt(2)*C2*cos(sqrt(2)*t))*exp(t) - Rational(185, 3))]
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t)))
sol6 = [Eq(x(t), (C1*exp(2*t) + C2*exp(-2*t))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (C1*exp(2*t) - C2*exp(-2*t))*exp(Rational(5, 2)*t**2))]
s = dsolve(eq6)
assert checksysodesol(eq6, sol6) == (True, [0, 0])
eq7 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
sol7 = [Eq(x(t), (C1*cos((t**3)/3) + C2*sin((t**3)/3))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (-C1*sin((t**3)/3) + C2*cos((t**3)/3))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq7, sol7) == (True, [0, 0])
eq8 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t)))
sol8 = [Eq(x(t), (C1*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \
C2*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2)), \
Eq(y(t), (C1*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \
C2*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2))]
assert checksysodesol(eq8, sol8) == (True, [0, 0])
eq10 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t)))
sol10 = [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), \
Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + \
exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))]
s = dsolve(eq10)
assert s == sol10 # too complicated to test with subs and simplify
# assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this one fails
def test_linear_2eq_order1_nonhomog_linear():
e = [Eq(diff(f(x), x), f(x) + g(x) + 5*x),
Eq(diff(g(x), x), f(x) - g(x))]
raises(NotImplementedError, lambda: dsolve(e))
def test_linear_2eq_order1_nonhomog():
# Note: once implemented, add some tests esp. with resonance
e = [Eq(diff(f(x), x), f(x) + exp(x)),
Eq(diff(g(x), x), f(x) + g(x) + x*exp(x))]
raises(NotImplementedError, lambda: dsolve(e))
def test_linear_2eq_order1_type2_degen():
e = [Eq(diff(f(x), x), f(x) + 5),
Eq(diff(g(x), x), f(x) + 7)]
s1 = [Eq(f(x), C1*exp(x) - 5), Eq(g(x), C1*exp(x) - C2 + 2*x - 5)]
assert checksysodesol(e, s1) == (True, [0, 0])
def test_dsolve_linear_2eq_order1_diag_triangular():
e = [Eq(diff(f(x), x), f(x)),
Eq(diff(g(x), x), g(x))]
s1 = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x))]
assert checksysodesol(e, s1) == (True, [0, 0])
e = [Eq(diff(f(x), x), 2*f(x)),
Eq(diff(g(x), x), 3*f(x) + 7*g(x))]
s1 = [Eq(f(x), -5*C2*exp(2*x)),
Eq(g(x), 5*C1*exp(7*x) + 3*C2*exp(2*x))]
assert checksysodesol(e, s1) == (True, [0, 0])
def test_sysode_linear_2eq_order1_type1_D_lt_0():
e = [Eq(diff(f(x), x), -9*I*f(x) - 4*g(x)),
Eq(diff(g(x), x), -4*I*g(x))]
s1 = [Eq(f(x), -4*C1*exp(-4*I*x) - 4*C2*exp(-9*I*x)), \
Eq(g(x), 5*I*C1*exp(-4*I*x))]
assert checksysodesol(e, s1) == (True, [0, 0])
def test_sysode_linear_2eq_order1_type1_D_lt_0_b_eq_0():
e = [Eq(diff(f(x), x), -9*I*f(x)),
Eq(diff(g(x), x), -4*I*g(x))]
s1 = [Eq(f(x), -5*I*C2*exp(-9*I*x)), Eq(g(x), 5*I*C1*exp(-4*I*x))]
assert checksysodesol(e, s1) == (True, [0, 0])
def test_sysode_linear_2eq_order1_many_zeros():
t = Symbol('t')
corner_cases = [(0, 0, 0, 0), (1, 0, 0, 0), (0, 1, 0, 0),
(0, 0, 1, 0), (0, 0, 0, 1), (1, 0, 0, I),
(I, 0, 0, -I), (0, I, 0, 0), (0, I, I, 0)]
s1 = [[Eq(f(t), C1), Eq(g(t), C2)],
[Eq(f(t), C1*exp(t)), Eq(g(t), -C2)],
[Eq(f(t), C1 + C2*t), Eq(g(t), C2)],
[Eq(f(t), C2), Eq(g(t), C1 + C2*t)],
[Eq(f(t), -C2), Eq(g(t), C1*exp(t))],
[Eq(f(t), C1*(1 - I)*exp(t)), Eq(g(t), C2*(-1 + I)*exp(I*t))],
[Eq(f(t), 2*I*C1*exp(I*t)), Eq(g(t), -2*I*C2*exp(-I*t))],
[Eq(f(t), I*C1 + I*C2*t), Eq(g(t), C2)],
[Eq(f(t), I*C1*exp(I*t) + I*C2*exp(-I*t)), \
Eq(g(t), I*C1*exp(I*t) - I*C2*exp(-I*t))]
]
for r, sol in zip(corner_cases, s1):
eq = [Eq(diff(f(t), t), r[0]*f(t) + r[1]*g(t)),
Eq(diff(g(t), t), r[2]*f(t) + r[3]*g(t))]
assert checksysodesol(eq, sol) == (True, [0, 0])
def test_dsolve_linsystem_symbol_piecewise():
u = Symbol('u') # XXX it's more complicated with real u
eq = (Eq(diff(f(x), x), 2*f(x) + g(x)),
Eq(diff(g(x), x), u*f(x)))
s1 = [Eq(f(x), Piecewise((C1*exp(x*(sqrt(4*u + 4)/2 + 1)) +
C2*exp(x*(-sqrt(4*u + 4)/2 + 1)), Ne(4*u + 4, 0)), ((C1 + C2*(x +
Piecewise((0, Eq(sqrt(4*u + 4)/2 + 1, 2)), (1/(-sqrt(4*u + 4)/2 + 1),
True))))*exp(x*(sqrt(4*u + 4)/2 + 1)), True))), Eq(g(x),
Piecewise((C1*(sqrt(4*u + 4)/2 - 1)*exp(x*(sqrt(4*u + 4)/2 + 1)) +
C2*(-sqrt(4*u + 4)/2 - 1)*exp(x*(-sqrt(4*u + 4)/2 + 1)), Ne(4*u + 4,
0)), ((C1*(sqrt(4*u + 4)/2 - 1) + C2*(x*(sqrt(4*u + 4)/2 - 1) +
Piecewise((1, Eq(sqrt(4*u + 4)/2 + 1, 2)), (0,
True))))*exp(x*(sqrt(4*u + 4)/2 + 1)), True)))]
assert dsolve(eq) == s1
# FIXME: assert checksysodesol(eq, s) == (True, [0, 0])
# Remove lines below when checksysodesol works
s = [(l.lhs, l.rhs) for l in s1]
for v in [0, 7, -42, 5*I, 3 + 4*I]:
assert eq[0].subs(s).subs(u, v).doit().simplify()
assert eq[1].subs(s).subs(u, v).doit().simplify()
# example from https://groups.google.com/d/msg/sympy/xmzoqW6tWaE/sf0bgQrlCgAJ
i, r1, c1, r2, c2, t = symbols('i, r1, c1, r2, c2, t')
x1 = Function('x1')
x2 = Function('x2')
eq1 = r1*c1*Derivative(x1(t), t) + x1(t) - x2(t) - r1*i
eq2 = r2*c1*Derivative(x1(t), t) + r2*c2*Derivative(x2(t), t) + x2(t) - r2*i
sol = dsolve((eq1, eq2))
# FIXME: assert checksysodesol(eq, sol) == (True, [0, 0])
# Remove line below when checksysodesol works
assert all(s.has(Piecewise) for s in sol)
@slow
def test_linear_2eq_order2():
x, y, z = symbols('x, y, z', cls=Function)
k, l, m, n = symbols('k, l, m, n', Integer=True)
t, l = symbols('t, l')
x0, y0 = symbols('x0, y0', cls=Function)
eq1 = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t)))
sol1 = [Eq(x(t), 43*C1*exp(t*rootof(l**4 - 14*l**2 + 2, 0)) + 43*C2*exp(t*rootof(l**4 - 14*l**2 + 2, 1)) + \
43*C3*exp(t*rootof(l**4 - 14*l**2 + 2, 2)) + 43*C4*exp(t*rootof(l**4 - 14*l**2 + 2, 3))), \
Eq(y(t), C1*(rootof(l**4 - 14*l**2 + 2, 0)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 0)) + \
C2*(rootof(l**4 - 14*l**2 + 2, 1)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 1)) + \
C3*(rootof(l**4 - 14*l**2 + 2, 2)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 2)) + \
C4*(rootof(l**4 - 14*l**2 + 2, 3)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 3)))]
assert dsolve(eq1) == sol1
# FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0]) # this one fails
eq2 = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12))
sol2 = [Eq(x(t), 3*C1*exp(t*rootof(l**4 - 15*l**2 + 29, 0)) + 3*C2*exp(t*rootof(l**4 - 15*l**2 + 29, 1)) + \
3*C3*exp(t*rootof(l**4 - 15*l**2 + 29, 2)) + 3*C4*exp(t*rootof(l**4 - 15*l**2 + 29, 3)) - Rational(181, 29)), \
Eq(y(t), C1*(rootof(l**4 - 15*l**2 + 29, 0)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 0)) + \
C2*(rootof(l**4 - 15*l**2 + 29, 1)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 1)) + \
C3*(rootof(l**4 - 15*l**2 + 29, 2)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 2)) + \
C4*(rootof(l**4 - 15*l**2 + 29, 3)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 3)) + Rational(183, 29))]
assert dsolve(eq2) == sol2
# FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0]) # this one fails
eq3 = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0))
sol3 = [Eq(x(t), C1*cos(t*(Rational(9, 2) + sqrt(109)/2)) + C2*sin(t*(Rational(9, 2) + sqrt(109)/2)) + C3*cos(t*(-sqrt(109)/2 + Rational(9, 2))) + \
C4*sin(t*(-sqrt(109)/2 + Rational(9, 2)))), Eq(y(t), -C1*sin(t*(Rational(9, 2) + sqrt(109)/2)) + C2*cos(t*(Rational(9, 2) + sqrt(109)/2)) - \
C3*sin(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*cos(t*(-sqrt(109)/2 + Rational(9, 2))))]
assert dsolve(eq3) == sol3
assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t)))
sol4 = [Eq(x(t), C3*t + t*Integral((9*C1*exp(3*sqrt(7)*t**2/2) + 9*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t)), \
Eq(y(t), C4*t + t*Integral((3*sqrt(7)*C1*exp(3*sqrt(7)*t**2/2) - 3*sqrt(7)*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t))]
assert dsolve(eq4) == sol4
assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(diff(x(t),t,t), (log(t)+t**2)*diff(x(t),t)+(log(t)+t**2)*3*diff(y(t),t)), Eq(diff(y(t),t,t), \
(log(t)+t**2)*2*diff(x(t),t)+(log(t)+t**2)*9*diff(y(t),t)))
sol5 = [Eq(x(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2 - \
C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4 - \
(sqrt(22) + 5)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2) + \
(-sqrt(22) + 5)*(C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C4))/88), \
Eq(y(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + \
C2 - C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4)/44)]
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t,t), log(t)*t*diff(y(t),t) - log(t)*y(t)), Eq(diff(y(t),t,t), log(t)*t*diff(x(t),t) - log(t)*x(t)))
sol6 = [Eq(x(t), C3*t + t*Integral((C1*exp(Integral(t*log(t), t)) + \
C2*exp(-Integral(t*log(t), t)))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*exp(Integral(t*log(t), t)) - \
C2*exp(-Integral(t*log(t), t)))/t**2, t))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0])
eq7 = (Eq(diff(x(t),t,t), log(t)*(t*diff(x(t),t) - x(t)) + exp(t)*(t*diff(y(t),t) - y(t))), \
Eq(diff(y(t),t,t), (t**2)*(t*diff(x(t),t) - x(t)) + (t)*(t*diff(y(t),t) - y(t))))
sol7 = [Eq(x(t), C3*t + t*Integral((C1*x0(t) + C2*x0(t)*Integral(t*exp(t)*exp(Integral(t**2, t))*\
exp(Integral(t*log(t), t))/x0(t)**2, t))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*y0(t) + \
C2*(y0(t)*Integral(t*exp(t)*exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0(t)**2, t) + \
exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0(t)))/t**2, t))]
assert dsolve(eq7) == sol7
# FIXME: assert checksysodesol(eq7, sol7) == (True, [0, 0])
eq8 = (Eq(diff(x(t),t,t), t*(4*x(t) + 9*y(t))), Eq(diff(y(t),t,t), t*(12*x(t) - 6*y(t))))
sol8 = [Eq(x(t), -sqrt(133)*(-4*C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + 4*C1*airyai(-t*(1 + \
sqrt(133))**(S(1)/3)) - 4*C2*airybi(t*(-1 + sqrt(133))**(S(1)/3)) + 4*C2*airybi(-t*(1 + sqrt(133))**(S(1)/3)) +\
(-sqrt(133) - 1)*(C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + C2*airybi(t*(-1 + sqrt(133))**(S(1)/3))) - (-1 +\
sqrt(133))*(C1*airyai(-t*(1 + sqrt(133))**(S(1)/3)) + C2*airybi(-t*(1 + sqrt(133))**(S(1)/3))))/3192), \
Eq(y(t), -sqrt(133)*(-C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + C1*airyai(-t*(1 + sqrt(133))**(S(1)/3)) -\
C2*airybi(t*(-1 + sqrt(133))**(S(1)/3)) + C2*airybi(-t*(1 + sqrt(133))**(S(1)/3)))/266)]
assert dsolve(eq8) == sol8
assert checksysodesol(eq8, sol8) == (True, [0, 0])
assert filldedent(dsolve(eq8)) == filldedent('''
[Eq(x(t), -sqrt(133)*(-4*C1*airyai(t*(-1 + sqrt(133))**(1/3)) +
4*C1*airyai(-t*(1 + sqrt(133))**(1/3)) - 4*C2*airybi(t*(-1 +
sqrt(133))**(1/3)) + 4*C2*airybi(-t*(1 + sqrt(133))**(1/3)) +
(-sqrt(133) - 1)*(C1*airyai(t*(-1 + sqrt(133))**(1/3)) +
C2*airybi(t*(-1 + sqrt(133))**(1/3))) - (-1 +
sqrt(133))*(C1*airyai(-t*(1 + sqrt(133))**(1/3)) + C2*airybi(-t*(1 +
sqrt(133))**(1/3))))/3192), Eq(y(t), -sqrt(133)*(-C1*airyai(t*(-1 +
sqrt(133))**(1/3)) + C1*airyai(-t*(1 + sqrt(133))**(1/3)) -
C2*airybi(t*(-1 + sqrt(133))**(1/3)) + C2*airybi(-t*(1 +
sqrt(133))**(1/3)))/266)]''')
assert checksysodesol(eq8, sol8) == (True, [0, 0])
eq9 = (Eq(diff(x(t),t,t), t*(4*diff(x(t),t) + 9*diff(y(t),t))), Eq(diff(y(t),t,t), t*(12*diff(x(t),t) - 6*diff(y(t),t))))
sol9 = [Eq(x(t), -sqrt(133)*(4*C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + 4*C2 - \
4*C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - 4*C4 - (-1 + sqrt(133))*(C1*Integral(exp((-sqrt(133) - \
1)*Integral(t, t)), t) + C2) + (-sqrt(133) - 1)*(C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) + \
C4))/3192), Eq(y(t), -sqrt(133)*(C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + C2 - \
C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - C4)/266)]
assert dsolve(eq9) == sol9
assert checksysodesol(eq9, sol9) == (True, [0, 0])
eq10 = (t**2*diff(x(t),t,t) + 3*t*diff(x(t),t) + 4*t*diff(y(t),t) + 12*x(t) + 9*y(t), \
t**2*diff(y(t),t,t) + 2*t*diff(x(t),t) - 5*t*diff(y(t),t) + 15*x(t) + 8*y(t))
sol10 = [Eq(x(t), -C1*(-2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 13 + 2*sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \
346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) - \
C2*(-2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
13 - 2*sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) - C3*t**(1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*(2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 13 + 2*sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))) - C4*t**(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2)*(-2*sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))) + 2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 13)), Eq(y(t), C1*(-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14 + (-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) + C2*(-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))) + (-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2)*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) + C3*t**(1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \
2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)*(sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))) + 14 + (1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2) + C4*t**(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \
346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2)*(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + \
8 + 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))) + (-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \
346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \
4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2)**2 + sqrt(-346/(3*(Rational(4333, 4) + \
5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14))]
assert dsolve(eq10) == sol10
# FIXME: assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this hangs or at least takes a while...
def test_linear_3eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
t = Symbol('t')
eq1 = (Eq(diff(x(t),t), 21*x(t)), Eq(diff(y(t),t), 17*x(t)+3*y(t)), Eq(diff(z(t),t), 5*x(t)+7*y(t)+9*z(t)))
sol1 = [Eq(x(t), C1*exp(21*t)), Eq(y(t), 17*C1*exp(21*t)/18 + C2*exp(3*t)), \
Eq(z(t), 209*C1*exp(21*t)/216 - 7*C2*exp(3*t)/6 + C3*exp(9*t))]
assert checksysodesol(eq1, sol1) == (True, [0, 0, 0])
eq2 = (Eq(diff(x(t),t),3*y(t)-11*z(t)),Eq(diff(y(t),t),7*z(t)-3*x(t)),Eq(diff(z(t),t),11*x(t)-7*y(t)))
sol2 = [Eq(x(t), 7*C0 + sqrt(179)*C1*cos(sqrt(179)*t) + (77*C1/3 + 130*C2/3)*sin(sqrt(179)*t)), \
Eq(y(t), 11*C0 + sqrt(179)*C2*cos(sqrt(179)*t) + (-58*C1/3 - 77*C2/3)*sin(sqrt(179)*t)), \
Eq(z(t), 3*C0 + sqrt(179)*(-7*C1/3 - 11*C2/3)*cos(sqrt(179)*t) + (11*C1 - 7*C2)*sin(sqrt(179)*t))]
assert checksysodesol(eq2, sol2) == (True, [0, 0, 0])
eq3 = (Eq(3*diff(x(t),t),4*5*(y(t)-z(t))),Eq(4*diff(y(t),t),3*5*(z(t)-x(t))),Eq(5*diff(z(t),t),3*4*(x(t)-y(t))))
sol3 = [Eq(x(t), C0 + 5*sqrt(2)*C1*cos(5*sqrt(2)*t) + (12*C1/5 + 164*C2/15)*sin(5*sqrt(2)*t)), \
Eq(y(t), C0 + 5*sqrt(2)*C2*cos(5*sqrt(2)*t) + (-51*C1/10 - 12*C2/5)*sin(5*sqrt(2)*t)), \
Eq(z(t), C0 + 5*sqrt(2)*(-9*C1/25 - 16*C2/25)*cos(5*sqrt(2)*t) + (12*C1/5 - 12*C2/5)*sin(5*sqrt(2)*t))]
assert checksysodesol(eq3, sol3) == (True, [0, 0, 0])
f = t**3 + log(t)
g = t**2 + sin(t)
eq4 = (Eq(diff(x(t),t),(4*f+g)*x(t)-f*y(t)-2*f*z(t)), Eq(diff(y(t),t),2*f*x(t)+(f+g)*y(t)-2*f*z(t)), Eq(diff(z(t),t),5*f*x(t)+f*y(t)+(-3*f+g)*z(t)))
sol4 = [Eq(x(t), (C1*exp(-2*Integral(t**3 + log(t), t)) + C2*(sqrt(3)*sin(sqrt(3)*Integral(t**3 + log(t), t))/6 \
+ cos(sqrt(3)*Integral(t**3 + log(t), t))/2) + C3*(sin(sqrt(3)*Integral(t**3 + log(t), t))/2 - \
sqrt(3)*cos(sqrt(3)*Integral(t**3 + log(t), t))/6))*exp(Integral(-t**2 - sin(t), t))), Eq(y(t), \
(C2*(sqrt(3)*sin(sqrt(3)*Integral(t**3 + log(t), t))/6 + cos(sqrt(3)*Integral(t**3 + log(t), t))/2) + \
C3*(sin(sqrt(3)*Integral(t**3 + log(t), t))/2 - sqrt(3)*cos(sqrt(3)*Integral(t**3 + log(t), t))/6))*\
exp(Integral(-t**2 - sin(t), t))), Eq(z(t), (C1*exp(-2*Integral(t**3 + log(t), t)) + C2*cos(sqrt(3)*\
Integral(t**3 + log(t), t)) + C3*sin(sqrt(3)*Integral(t**3 + log(t), t)))*exp(Integral(-t**2 - sin(t), t)))]
assert dsolve(eq4) == sol4
# FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0, 0]) # this one fails
eq5 = (Eq(diff(x(t),t),4*x(t) - z(t)),Eq(diff(y(t),t),2*x(t)+2*y(t)-z(t)),Eq(diff(z(t),t),3*x(t)+y(t)))
sol5 = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t) + C3*exp(2*t)), \
Eq(y(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t)), \
Eq(z(t), 2*C1*exp(2*t) + 2*C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t) + C3*t*exp(2*t) + C3*exp(2*t))]
assert checksysodesol(eq5, sol5) == (True, [0, 0, 0])
eq6 = (Eq(diff(x(t),t),4*x(t) - y(t) - 2*z(t)),Eq(diff(y(t),t),2*x(t) + y(t)- 2*z(t)),Eq(diff(z(t),t),5*x(t)-3*z(t)))
sol6 = [Eq(x(t), C1*exp(2*t) + C2*(-sin(t)/5 + 3*cos(t)/5) + C3*(3*sin(t)/5 + cos(t)/5)),
Eq(y(t), C2*(-sin(t)/5 + 3*cos(t)/5) + C3*(3*sin(t)/5 + cos(t)/5)),
Eq(z(t), C1*exp(2*t) + C2*cos(t) + C3*sin(t))]
assert checksysodesol(eq6, sol6) == (True, [0, 0, 0])
def test_linear_3eq_order1_nonhomog():
e = [Eq(diff(f(x), x), -9*f(x) - 4*g(x)),
Eq(diff(g(x), x), -4*g(x)),
Eq(diff(h(x), x), h(x) + exp(x))]
raises(NotImplementedError, lambda: dsolve(e))
@XFAIL
def test_linear_3eq_order1_diagonal():
# code makes assumptions about coefficients being nonzero, breaks when assumptions are not true
e = [Eq(diff(f(x), x), f(x)),
Eq(diff(g(x), x), g(x)),
Eq(diff(h(x), x), h(x))]
s1 = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x)), Eq(h(x), C3*exp(x))]
s = dsolve(e)
assert s == s1
assert checksysodesol(e, s1) == (True, [0, 0, 0])
def test_nonlinear_2eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
t = Symbol('t')
eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5))
sol1 = [
Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq1) == sol1
assert checksysodesol(eq1, sol1) == (True, [0, 0])
eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5))
sol2 = [
Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq2) == sol2
assert checksysodesol(eq2, sol2) == (True, [0, 0])
eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3))
tt = Rational(2, 3)
sol3 = [
Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)),
Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)]
assert dsolve(eq3) == sol3
# FIXME: assert checksysodesol(eq3, sol3) == (True, [0, 0])
eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2))
sol4 = set([Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))])
assert dsolve(eq4) == sol4
# FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0])
eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2))
sol5 = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)])
assert dsolve(eq5) == sol5
assert checksysodesol(eq5, sol5) == (True, [0, 0])
eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5))
sol6 = [
Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(Rational(-1, 4)))),
Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)),
Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**Rational(1, 4))),
Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert dsolve(eq6) == sol6
assert checksysodesol(eq6, sol6) == (True, [0, 0])
def test_checksysodesol():
x, y, z = symbols('x, y, z', cls=Function)
t = Symbol('t')
eq = (Eq(diff(x(t),t), 9*y(t)), Eq(diff(y(t),t), 12*x(t)))
sol = [Eq(x(t), 9*C1*exp(-6*sqrt(3)*t) + 9*C2*exp(6*sqrt(3)*t)), \
Eq(y(t), -6*sqrt(3)*C1*exp(-6*sqrt(3)*t) + 6*sqrt(3)*C2*exp(6*sqrt(3)*t))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), 2*x(t) + 4*y(t)), Eq(diff(y(t),t), 12*x(t) + 41*y(t)))
sol = [Eq(x(t), 4*C1*exp(t*(-sqrt(1713)/2 + Rational(43, 2))) + 4*C2*exp(t*(sqrt(1713)/2 + \
Rational(43, 2)))), Eq(y(t), C1*(-sqrt(1713)/2 + Rational(39, 2))*exp(t*(-sqrt(1713)/2 + \
Rational(43, 2))) + C2*(Rational(39, 2) + sqrt(1713)/2)*exp(t*(sqrt(1713)/2 + Rational(43, 2))))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), x(t) + y(t)), Eq(diff(y(t),t), -2*x(t) + 2*y(t)))
sol = [Eq(x(t), (C1*sin(sqrt(7)*t/2) + C2*cos(sqrt(7)*t/2))*exp(t*Rational(3, 2))), \
Eq(y(t), ((C1/2 - sqrt(7)*C2/2)*sin(sqrt(7)*t/2) + (sqrt(7)*C1/2 + \
C2/2)*cos(sqrt(7)*t/2))*exp(t*Rational(3, 2)))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23))
sol = [Eq(x(t), C1*exp(t*(-sqrt(6) + 3)) + C2*exp(t*(sqrt(6) + 3)) - \
Rational(22, 3)), Eq(y(t), C1*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) + C2*(2 + \
sqrt(6))*exp(t*(sqrt(6) + 3)) - Rational(5, 3))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23))
sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - Rational(58, 3)), \
Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - Rational(185, 3))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t)))
sol = [Eq(x(t), (C1*exp((Integral(2, t).doit())) + C2*exp(-(Integral(2, t)).doit()))*\
exp((Integral(5*t, t)).doit())), Eq(y(t), (C1*exp((Integral(2, t)).doit()) - \
C2*exp(-(Integral(2, t)).doit()))*exp((Integral(5*t, t)).doit()))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
sol = [Eq(x(t), (C1*cos((Integral(t**2, t)).doit()) + C2*sin((Integral(t**2, t)).doit()))*\
exp((Integral(5*t, t)).doit())), Eq(y(t), (-C1*sin((Integral(t**2, t)).doit()) + \
C2*cos((Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t)))
sol = [Eq(x(t), (C1*exp((-sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()) + \
C2*exp((sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit())), \
Eq(y(t), (C1*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()) + \
C2*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t)))
root0 = -sqrt(-sqrt(47) + 7)
root1 = sqrt(-sqrt(47) + 7)
root2 = -sqrt(sqrt(47) + 7)
root3 = sqrt(sqrt(47) + 7)
sol = [Eq(x(t), 43*C1*exp(t*root0) + 43*C2*exp(t*root1) + 43*C3*exp(t*root2) + 43*C4*exp(t*root3)), \
Eq(y(t), C1*(root0**2 - 5)*exp(t*root0) + C2*(root1**2 - 5)*exp(t*root1) + \
C3*(root2**2 - 5)*exp(t*root2) + C4*(root3**2 - 5)*exp(t*root3))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12))
root0 = -sqrt(-sqrt(109)/2 + Rational(15, 2))
root1 = sqrt(-sqrt(109)/2 + Rational(15, 2))
root2 = -sqrt(sqrt(109)/2 + Rational(15, 2))
root3 = sqrt(sqrt(109)/2 + Rational(15, 2))
sol = [Eq(x(t), 3*C1*exp(t*root0) + 3*C2*exp(t*root1) + 3*C3*exp(t*root2) + 3*C4*exp(t*root3) - Rational(181, 29)), \
Eq(y(t), C1*(root0**2 - 8)*exp(t*root0) + C2*(root1**2 - 8)*exp(t*root1) + \
C3*(root2**2 - 8)*exp(t*root2) + C4*(root3**2 - 8)*exp(t*root3) + Rational(183, 29))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0))
sol = [Eq(x(t), C1*cos(t*(Rational(9, 2) + sqrt(109)/2)) + C2*sin(t*(Rational(9, 2) + sqrt(109)/2)) + \
C3*cos(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*sin(t*(-sqrt(109)/2 + Rational(9, 2)))), Eq(y(t), -C1*sin(t*(Rational(9, 2) + sqrt(109)/2)) \
+ C2*cos(t*(Rational(9, 2) + sqrt(109)/2)) - C3*sin(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*cos(t*(-sqrt(109)/2 + Rational(9, 2))))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t)))
I1 = sqrt(6)*7**Rational(1, 4)*sqrt(pi)*erfi(sqrt(6)*7**Rational(1, 4)*t/2)/2 - exp(3*sqrt(7)*t**2/2)/t
I2 = -sqrt(6)*7**Rational(1, 4)*sqrt(pi)*erf(sqrt(6)*7**Rational(1, 4)*t/2)/2 - exp(-3*sqrt(7)*t**2/2)/t
sol = [Eq(x(t), C3*t + t*(9*C1*I1 + 9*C2*I2)), Eq(y(t), C4*t + t*(3*sqrt(7)*C1*I1 - 3*sqrt(7)*C2*I2))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), 21*x(t)), Eq(diff(y(t),t), 17*x(t)+3*y(t)), Eq(diff(z(t),t), 5*x(t)+7*y(t)+9*z(t)))
sol = [Eq(x(t), C1*exp(21*t)), Eq(y(t), 17*C1*exp(21*t)/18 + C2*exp(3*t)), \
Eq(z(t), 209*C1*exp(21*t)/216 - 7*C2*exp(3*t)/6 + C3*exp(9*t))]
assert checksysodesol(eq, sol) == (True, [0, 0, 0])
eq = (Eq(diff(x(t),t),3*y(t)-11*z(t)),Eq(diff(y(t),t),7*z(t)-3*x(t)),Eq(diff(z(t),t),11*x(t)-7*y(t)))
sol = [Eq(x(t), 7*C0 + sqrt(179)*C1*cos(sqrt(179)*t) + (77*C1/3 + 130*C2/3)*sin(sqrt(179)*t)), \
Eq(y(t), 11*C0 + sqrt(179)*C2*cos(sqrt(179)*t) + (-58*C1/3 - 77*C2/3)*sin(sqrt(179)*t)), \
Eq(z(t), 3*C0 + sqrt(179)*(-7*C1/3 - 11*C2/3)*cos(sqrt(179)*t) + (11*C1 - 7*C2)*sin(sqrt(179)*t))]
assert checksysodesol(eq, sol) == (True, [0, 0, 0])
eq = (Eq(3*diff(x(t),t),4*5*(y(t)-z(t))),Eq(4*diff(y(t),t),3*5*(z(t)-x(t))),Eq(5*diff(z(t),t),3*4*(x(t)-y(t))))
sol = [Eq(x(t), C0 + 5*sqrt(2)*C1*cos(5*sqrt(2)*t) + (12*C1/5 + 164*C2/15)*sin(5*sqrt(2)*t)), \
Eq(y(t), C0 + 5*sqrt(2)*C2*cos(5*sqrt(2)*t) + (-51*C1/10 - 12*C2/5)*sin(5*sqrt(2)*t)), \
Eq(z(t), C0 + 5*sqrt(2)*(-9*C1/25 - 16*C2/25)*cos(5*sqrt(2)*t) + (12*C1/5 - 12*C2/5)*sin(5*sqrt(2)*t))]
assert checksysodesol(eq, sol) == (True, [0, 0, 0])
eq = (Eq(diff(x(t),t),4*x(t) - z(t)),Eq(diff(y(t),t),2*x(t)+2*y(t)-z(t)),Eq(diff(z(t),t),3*x(t)+y(t)))
sol = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t) + C3*exp(2*t)), \
Eq(y(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t)), \
Eq(z(t), 2*C1*exp(2*t) + 2*C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t) + C3*t*exp(2*t) + C3*exp(2*t))]
assert checksysodesol(eq, sol) == (True, [0, 0, 0])
eq = (Eq(diff(x(t),t),4*x(t) - y(t) - 2*z(t)),Eq(diff(y(t),t),2*x(t) + y(t)- 2*z(t)),Eq(diff(z(t),t),5*x(t)-3*z(t)))
sol = [Eq(x(t), C1*exp(2*t) + C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), \
Eq(y(t), C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), Eq(z(t), C1*exp(2*t) + 5*C2*cos(t) + 5*C3*sin(t))]
assert checksysodesol(eq, sol) == (True, [0, 0, 0])
eq = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5))
sol = [Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), \
Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), \
Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), \
Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5))
sol = [Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), \
Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), \
Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), \
Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))]
assert checksysodesol(eq, sol) == (True, [0, 0])
eq = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2))
sol = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)])
assert checksysodesol(eq, sol) == (True, [0, 0])
@slow
def test_nonlinear_3eq_order1():
x, y, z = symbols('x, y, z', cls=Function)
t, u = symbols('t u')
eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t))
sol1 = [Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, x(t))),
C3 - sqrt(15)*t/15), Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)),
(u, y(t))), C3 + sqrt(5)*t/10), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)*
sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*t/6)]
assert [i.dummy_eq(j) for i, j in zip(dsolve(eq1), sol1)]
# FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0, 0])
eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t))
sol2 = [Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, x(t))), C3 +
sqrt(5)*cos(t)/10), Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)),
(u, y(t))), C3 - sqrt(15)*cos(t)/15), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)*
sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*cos(t)/6)]
assert [i.dummy_eq(j) for i, j in zip(dsolve(eq2), sol2)]
# FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0, 0])
@slow
def test_checkodesol():
from sympy import Ei
# For the most part, checkodesol is well tested in the tests below.
# These tests only handle cases not checked below.
raises(ValueError, lambda: checkodesol(f(x, y).diff(x), Eq(f(x, y), x)))
raises(ValueError, lambda: checkodesol(f(x).diff(x), Eq(f(x, y),
x), f(x, y)))
assert checkodesol(f(x).diff(x), Eq(f(x, y), x)) == \
(False, -f(x).diff(x) + f(x, y).diff(x) - 1)
assert checkodesol(f(x).diff(x), Eq(f(x), x)) is not True
assert checkodesol(f(x).diff(x), Eq(f(x), x)) == (False, 1)
sol1 = Eq(f(x)**5 + 11*f(x) - 2*f(x) + x, 0)
assert checkodesol(diff(sol1.lhs, x), sol1) == (True, 0)
assert checkodesol(diff(sol1.lhs, x)*exp(f(x)), sol1) == (True, 0)
assert checkodesol(diff(sol1.lhs, x, 2), sol1) == (True, 0)
assert checkodesol(diff(sol1.lhs, x, 2)*exp(f(x)), sol1) == (True, 0)
assert checkodesol(diff(sol1.lhs, x, 3), sol1) == (True, 0)
assert checkodesol(diff(sol1.lhs, x, 3)*exp(f(x)), sol1) == (True, 0)
assert checkodesol(diff(sol1.lhs, x, 3), Eq(f(x), x*log(x))) == \
(False, 60*x**4*((log(x) + 1)**2 + log(x))*(
log(x) + 1)*log(x)**2 - 5*x**4*log(x)**4 - 9)
assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x, 0)) == \
(True, 0)
assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x, 0),
solve_for_func=False) == (True, 0)
assert checkodesol(f(x).diff(x, 2), [Eq(f(x), C1 + C2*x),
Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)]) == \
[(True, 0), (True, 0), (False, C2)]
assert checkodesol(f(x).diff(x, 2), set([Eq(f(x), C1 + C2*x),
Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)])) == \
set([(True, 0), (True, 0), (False, C2)])
assert checkodesol(f(x).diff(x) - 1/f(x)/2, Eq(f(x)**2, x)) == \
[(True, 0), (True, 0)]
assert checkodesol(f(x).diff(x) - f(x), Eq(C1*exp(x), f(x))) == (True, 0)
# Based on test_1st_homogeneous_coeff_ode2_eq3sol. Make sure that
# checkodesol tries back substituting f(x) when it can.
eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x)
sol3 = Eq(f(x), log(log(C1/x)**(-x)))
assert not checkodesol(eq3, sol3)[1].has(f(x))
# This case was failing intermittently depending on hash-seed:
eqn = Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x))
sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))
assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0]
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (2*x**2 +25)*f(x)
sol = Eq(f(x), C1*besselj(5*I, sqrt(2)*x) + C2*bessely(5*I, sqrt(2)*x))
assert checkodesol(eq, sol) == (True, 0)
@slow
def test_dsolve_options():
eq = x*f(x).diff(x) + f(x)
a = dsolve(eq, hint='all')
b = dsolve(eq, hint='all', simplify=False)
c = dsolve(eq, hint='all_Integral')
keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear',
'1st_linear_Integral', 'almost_linear', 'almost_linear_Integral',
'best', 'best_hint', 'default', 'lie_group',
'nth_linear_euler_eq_homogeneous', 'order',
'separable', 'separable_Integral']
Integral_keys = ['1st_exact_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral',
'almost_linear_Integral', 'best', 'best_hint', 'default',
'nth_linear_euler_eq_homogeneous',
'order', 'separable_Integral']
assert sorted(a.keys()) == keys
assert a['order'] == ode_order(eq, f(x))
assert a['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best') == Eq(f(x), C1/x)
assert a['default'] == 'separable'
assert a['best_hint'] == 'separable'
assert not a['1st_exact'].has(Integral)
assert not a['separable'].has(Integral)
assert not a['1st_homogeneous_coeff_best'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not a['1st_linear'].has(Integral)
assert a['1st_linear_Integral'].has(Integral)
assert a['1st_exact_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert a['separable_Integral'].has(Integral)
assert sorted(b.keys()) == keys
assert b['order'] == ode_order(eq, f(x))
assert b['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x)
assert b['default'] == 'separable'
assert b['best_hint'] == '1st_linear'
assert a['separable'] != b['separable']
assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \
b['1st_homogeneous_coeff_subs_dep_div_indep']
assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \
b['1st_homogeneous_coeff_subs_indep_div_dep']
assert not b['1st_exact'].has(Integral)
assert not b['separable'].has(Integral)
assert not b['1st_homogeneous_coeff_best'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not b['1st_linear'].has(Integral)
assert b['1st_linear_Integral'].has(Integral)
assert b['1st_exact_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert b['separable_Integral'].has(Integral)
assert sorted(c.keys()) == Integral_keys
raises(ValueError, lambda: dsolve(eq, hint='notarealhint'))
raises(ValueError, lambda: dsolve(eq, hint='Liouville'))
assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \
dsolve(f(x).diff(x) - 1/f(x)**2, hint='best')
assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x),
hint="1st_linear_Integral") == \
Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)*
exp(Integral(1, x)), x))*exp(-Integral(1, x)))
def test_classify_ode():
assert classify_ode(f(x).diff(x, 2), f(x)) == \
(
'nth_algebraic',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'Liouville',
'2nd_power_series_ordinary',
'nth_algebraic_Integral',
'Liouville_Integral',
)
assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral')
assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == (
'nth_algebraic',
'separable',
'1st_linear', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral',
'separable_Integral',
'1st_linear_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
assert classify_ode(f(x).diff(x)**2, f(x)) == ('nth_algebraic',
'separable',
'1st_linear',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral',
'separable_Integral',
'1st_linear_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
# issue 4749: f(x) should be cleared from highest derivative before classifying
a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x))
b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x))
c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x))
assert a == ('1st_linear',
'Bernoulli',
'almost_linear',
'1st_power_series', "lie_group",
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert b == ('factorable',
'1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert c == ('1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert classify_ode(
2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x)
) == ('Bernoulli', 'almost_linear', 'lie_group',
'Bernoulli_Integral', 'almost_linear_Integral')
assert 'Riccati_special_minus2' in \
classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x))
raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff(
y), f(x, y)))
# issue 5176
k = Symbol('k')
assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) +
k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \
('separable', '1st_exact', '1st_power_series', 'lie_group',
'separable_Integral', '1st_exact_Integral')
# preprocessing
ans = ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'nth_algebraic_Integral',
'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral')
# w/o f(x) given
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans
# w/ f(x) and prep=True
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x),
prep=True) == ans
assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_linear', '1st_power_series',
'lie_group', 'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral', 'separable_Integral',
'1st_linear_Integral')
assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_power_series', 'lie_group',
'nth_algebraic_Integral', 'separable_Integral')
# test issue 13864
assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \
('1st_power_series', 'lie_group')
assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict)
def test_classify_ode_ics():
# Dummy
eq = f(x).diff(x, x) - f(x)
# Not f(0) or f'(0)
ics = {x: 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
############################
# f(0) type (AppliedUndef) #
############################
# Wrong function
ics = {g(0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(0, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(0): f(1)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(0): 1}
classify_ode(eq, f(x), ics=ics)
#####################
# f'(0) type (Subs) #
#####################
# Wrong function
ics = {g(x).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Wrong variable
ics = {f(y).diff(y).subs(y, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, y).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, 0): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, 0): 1}
classify_ode(eq, f(x), ics=ics)
###########################
# f'(y) type (Derivative) #
###########################
# Wrong function
ics = {g(x).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, z).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, y): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, y): 1}
classify_ode(eq, f(x), ics=ics)
def test_classify_sysode():
# Here x is assumed to be x(t) and y as y(t) for simplicity.
# Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively.
k, l, m, n = symbols('k, l, m, n', Integer=True)
k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True)
P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function)
P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function)
x, y, z = symbols('x, y, z', cls=Function)
t = symbols('t')
x1 = diff(x(t),t) ; y1 = diff(y(t),t) ; z1 = diff(z(t),t)
x2 = diff(x(t),t,t) ; y2 = diff(y(t),t,t)
eq1 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t)))
sol1 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -5*t, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): -5*t, (1, x(t), 0): -2, (0, y(t), 1): 0, (0, y(t), 0): -2, (1, y(t), 1): 1}, \
'type_of_equation': 'type3', 'func': [x(t), y(t)], 'is_linear': True, 'eq': [-5*t*x(t) - 2*y(t) + \
Derivative(x(t), t), -5*t*y(t) - 2*x(t) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq1) == sol1
eq2 = (Eq(x2, k*x(t) - l*y1), Eq(y2, l*x1 + k*y(t)))
sol2 = {'order': {y(t): 2, x(t): 2}, 'type_of_equation': 'type3', 'is_linear': True, 'eq': \
[-k*x(t) + l*Derivative(y(t), t) + Derivative(x(t), t, t), -k*y(t) - l*Derivative(x(t), t) + \
Derivative(y(t), t, t)], 'no_of_equation': 2, 'func_coeff': {(0, y(t), 0): 0, (0, x(t), 2): 1, \
(1, y(t), 1): 0, (1, y(t), 2): 1, (1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -k, (1, x(t), 1): \
-l, (0, x(t), 1): 0, (0, y(t), 1): l, (1, x(t), 0): 0, (1, y(t), 0): -k}, 'func': [x(t), y(t)]}
assert classify_sysode(eq2) == sol2
eq3 = (Eq(x2+4*x1+3*y1+9*x(t)+7*y(t), 11*exp(I*t)), Eq(y2+5*x1+8*y1+3*x(t)+12*y(t), 2*exp(I*t)))
sol3 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): 9, \
(1, x(t), 1): 5, (0, x(t), 1): 4, (0, y(t), 1): 3, (1, x(t), 0): 3, (1, y(t), 0): 12, (0, y(t), 0): 7, \
(0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): 8}, 'type_of_equation': 'type4', 'func': [x(t), y(t)], \
'is_linear': True, 'eq': [9*x(t) + 7*y(t) - 11*exp(I*t) + 4*Derivative(x(t), t) + 3*Derivative(y(t), t) + \
Derivative(x(t), t, t), 3*x(t) + 12*y(t) - 2*exp(I*t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + \
Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}}
assert classify_sysode(eq3) == sol3
eq4 = (Eq((4*t**2 + 7*t + 1)**2*x2, 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*y2, x(t) + 9*y(t)))
sol4 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -5, \
(1, x(t), 1): 0, (0, x(t), 1): 0, (0, y(t), 1): 0, (1, x(t), 0): -1, (1, y(t), 0): -9, (0, y(t), 0): -35, \
(0, x(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, (1, y(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, \
(1, y(t), 1): 0}, 'type_of_equation': 'type10', 'func': [x(t), y(t)], 'is_linear': True, \
'eq': [(4*t**2 + 7*t + 1)**2*Derivative(x(t), t, t) - 5*x(t) - 35*y(t), (4*t**2 + 7*t + 1)**2*Derivative(y(t), t, t)\
- x(t) - 9*y(t)], 'order': {y(t): 2, x(t): 2}}
assert classify_sysode(eq4) == sol4
eq5 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23))
sol5 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -1, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): -5, \
(1, x(t), 0): -2, (0, y(t), 1): 0, (0, y(t), 0): -1, (1, y(t), 1): 1}, 'type_of_equation': 'type2', \
'func': [x(t), y(t)], 'is_linear': True, 'eq': [-x(t) - y(t) + Derivative(x(t), t) - 9, -2*x(t) - 5*y(t) + \
Derivative(y(t), t) - 23], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq5) == sol5
eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t))))
sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \
[x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \
y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq6) == sol6
eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t)))
sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \
'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \
Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq7) == sol7
eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)))
sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \
[-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \
Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \
(1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2}
assert classify_sysode(eq8) == sol8
eq9 = (Eq(x1,3*y(t)-11*z(t)),Eq(y1,7*z(t)-3*x(t)),Eq(z1,11*x(t)-7*y(t)))
sol9 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): 0, (2, y(t), 1): 0, (2, z(t), 1): 1, \
(0, x(t), 0): 0, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): 7, (0, x(t), 1): 1, (1, z(t), 1): 0, \
(0, y(t), 1): 0, (1, x(t), 0): 3, (0, z(t), 0): 11, (0, y(t), 0): -3, (1, z(t), 0): -7, (0, z(t), 1): 0, \
(2, x(t), 0): -11, (2, z(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': [x(t), y(t), z(t)], \
'is_linear': True, 'eq': [-3*y(t) + 11*z(t) + Derivative(x(t), t), 3*x(t) - 7*z(t) + Derivative(y(t), t), \
-11*x(t) + 7*y(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}}
assert classify_sysode(eq9) == sol9
eq10 = (x2 + log(t)*(t*x1 - x(t)) + exp(t)*(t*y1 - y(t)), y2 + (t**2)*(t*x1 - x(t)) + (t)*(t*y1 - y(t)))
sol10 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -log(t), \
(1, x(t), 1): t**3, (0, x(t), 1): t*log(t), (0, y(t), 1): t*exp(t), (1, x(t), 0): -t**2, (1, y(t), 0): -t, \
(0, y(t), 0): -exp(t), (0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): t**2}, 'type_of_equation': 'type11', \
'func': [x(t), y(t)], 'is_linear': True, 'eq': [(t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - \
y(t))*exp(t) + Derivative(x(t), t, t), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) \
+ Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}}
assert classify_sysode(eq10) == sol10
eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5))
sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \
'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \
-y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq11) == sol11
eq12 = (Eq(x1, y(t)), Eq(y1, x(t)))
sol12 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): -1, (0, y(t), 1): 0, (0, y(t), 0): -1, (1, y(t), 1): 1}, 'type_of_equation': 'type1', 'func': \
[x(t), y(t)], 'is_linear': True, 'eq': [-y(t) + Derivative(x(t), t), -x(t) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq12) == sol12
eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2))
sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \
'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \
Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq13) == sol13
eq14 = (Eq(x1, 21*x(t)), Eq(y1, 17*x(t)+3*y(t)), Eq(z1, 5*x(t)+7*y(t)+9*z(t)))
sol14 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): -3, (2, y(t), 1): 0, (2, z(t), 1): 1, \
(0, x(t), 0): -21, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): -7, (0, x(t), 1): 1, (1, z(t), 1): 0, \
(0, y(t), 1): 0, (1, x(t), 0): -17, (0, z(t), 0): 0, (0, y(t), 0): 0, (1, z(t), 0): 0, (0, z(t), 1): 0, \
(2, x(t), 0): -5, (2, z(t), 0): -9, (1, y(t), 1): 1}, 'type_of_equation': 'type1', 'func': [x(t), y(t), z(t)], \
'is_linear': True, 'eq': [-21*x(t) + Derivative(x(t), t), -17*x(t) - 3*y(t) + Derivative(y(t), t), -5*x(t) - \
7*y(t) - 9*z(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}}
assert classify_sysode(eq14) == sol14
eq15 = (Eq(x1,4*x(t)+5*y(t)+2*z(t)),Eq(y1,x(t)+13*y(t)+9*z(t)),Eq(z1,32*x(t)+41*y(t)+11*z(t)))
sol15 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): -13, (2, y(t), 1): 0, (2, z(t), 1): 1, \
(0, x(t), 0): -4, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): -41, (0, x(t), 1): 1, (1, z(t), 1): 0, \
(0, y(t), 1): 0, (1, x(t), 0): -1, (0, z(t), 0): -2, (0, y(t), 0): -5, (1, z(t), 0): -9, (0, z(t), 1): 0, \
(2, x(t), 0): -32, (2, z(t), 0): -11, (1, y(t), 1): 1}, 'type_of_equation': 'type6', 'func': \
[x(t), y(t), z(t)], 'is_linear': True, 'eq': [-4*x(t) - 5*y(t) - 2*z(t) + Derivative(x(t), t), -x(t) - 13*y(t) - \
9*z(t) + Derivative(y(t), t), -32*x(t) - 41*y(t) - 11*z(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}}
assert classify_sysode(eq15) == sol15
eq16 = (Eq(3*x1,4*5*(y(t)-z(t))),Eq(4*y1,3*5*(z(t)-x(t))),Eq(5*z1,3*4*(x(t)-y(t))))
sol16 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): 0, (2, y(t), 1): 0, (2, z(t), 1): 5, \
(0, x(t), 0): 0, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): 12, (0, x(t), 1): 3, (1, z(t), 1): 0, \
(0, y(t), 1): 0, (1, x(t), 0): 15, (0, z(t), 0): 20, (0, y(t), 0): -20, (1, z(t), 0): -15, (0, z(t), 1): 0, \
(2, x(t), 0): -12, (2, z(t), 0): 0, (1, y(t), 1): 4}, 'type_of_equation': 'type3', 'func': [x(t), y(t), z(t)], \
'is_linear': True, 'eq': [-20*y(t) + 20*z(t) + 3*Derivative(x(t), t), 15*x(t) - 15*z(t) + 4*Derivative(y(t), t), \
-12*x(t) + 12*y(t) + 5*Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}}
assert classify_sysode(eq16) == sol16
# issue 8193: funcs parameter for classify_sysode has to actually work
assert classify_sysode(eq1, funcs=[x(t), y(t)]) == sol1
def test_solve_ics():
# Basic tests that things work from dsolve.
assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \
Eq(f(x), sqrt(2 * x + 2))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1,
f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x))
assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)],
[f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)),
Eq(g(x), exp(x)*sin(x))]
# Test cases where dsolve returns two solutions.
eq = (x**2*f(x)**2 - x).diff(x)
assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x),
-sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)]
assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x),
-sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)]
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \
{C2: 1}
# Some more complicated tests Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)}
K, r, f0 = symbols('K r f0')
sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1)))
assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol
#Order dependent issues Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
# XXX: Ought to be ValueError
raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1}))
# Degenerate case. f'(0) is identically 0.
raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0}))
EI, q, L = symbols('EI q L')
# eq = Eq(EI*diff(f(x), x, 4), q)
sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))]
funcs = [f(x)]
constants = [C1, C2, C3, C4]
# Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)),
# and Subs
ics1 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
f(L).diff(L, 2): 0,
f(L).diff(L, 3): 0}
ics2 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
Subs(f(x).diff(x, 2), x, L): 0,
Subs(f(x).diff(x, 3), x, L): 0}
solved_constants1 = solve_ics(sols, funcs, constants, ics1)
solved_constants2 = solve_ics(sols, funcs, constants, ics2)
assert solved_constants1 == solved_constants2 == {
C1: 0,
C2: 0,
C3: L**2*q/(4*EI),
C4: -L*q/(6*EI)}
def test_ode_order():
f = Function('f')
g = Function('g')
x = Symbol('x')
assert ode_order(3*x*exp(f(x)), f(x)) == 0
assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1
assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2
assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3
assert ode_order(diff(f(x), x, x), g(x)) == 0
assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2
assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0
# issue 5835: ode_order has to also work for unevaluated derivatives
# (ie, without using doit()).
assert ode_order(Derivative(x*f(x), x), f(x)) == 1
assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2
assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0
assert ode_order(Derivative(f(x), x, x), g(x)) == 0
assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1
assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3
assert ode_order(
x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3
# In all tests below, checkodesol has the order option set to prevent
# superfluous calls to ode_order(), and the solve_for_func flag set to False
# because dsolve() already tries to solve for the function, unless the
# simplify=False option is set.
def test_old_ode_tests():
# These are simple tests from the old ode module
eq1 = Eq(f(x).diff(x), 0)
eq2 = Eq(3*f(x).diff(x) - 5, 0)
eq3 = Eq(3*f(x).diff(x), 5)
eq4 = Eq(9*f(x).diff(x, x) + f(x), 0)
eq5 = Eq(9*f(x).diff(x, x), f(x))
# Type: a(x)f'(x)+b(x)*f(x)+c(x)=0
eq6 = Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0)
eq7 = Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0)
# Type: 2nd order, constant coefficients (two real different roots)
eq8 = Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0)
# Type: 2nd order, constant coefficients (two real equal roots)
eq9 = Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0)
# Type: 2nd order, constant coefficients (two complex roots)
eq10 = Eq(3*f(x).diff(x) - 1, 0)
eq11 = Eq(x*f(x).diff(x) - 1, 0)
sol1 = Eq(f(x), C1)
sol2 = Eq(f(x), C1 + x*Rational(5, 3))
sol3 = Eq(f(x), C1 + x*Rational(5, 3))
sol4 = Eq(f(x), C1*sin(x/3) + C2*cos(x/3))
sol5 = Eq(f(x), C1*exp(-x/3) + C2*exp(x/3))
sol6 = Eq(f(x), (C1 - cos(x))/x**3)
sol7 = Eq(f(x), (C1 + C2*exp(x))*exp(x))
sol8 = Eq(f(x), (C1 + C2*x)*exp(2*x))
sol9 = Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x))
sol10 = Eq(f(x), C1 + x/3)
sol11 = Eq(f(x), C1 + log(x))
assert dsolve(eq1) == sol1
assert dsolve(eq1.lhs) == sol1
assert dsolve(eq2) == sol2
assert dsolve(eq3) == sol3
assert dsolve(eq4) == sol4
assert dsolve(eq5) == sol5
assert dsolve(eq6) == sol6
assert dsolve(eq7) == sol7
assert dsolve(eq8) == sol8
assert dsolve(eq9) == sol9
assert dsolve(eq10) == sol10
assert dsolve(eq11) == sol11
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0]
assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0]
def test_1st_linear():
# Type: first order linear form f'(x)+p(x)f(x)=q(x)
eq = Eq(f(x).diff(x) + x*f(x), x**2)
sol = Eq(f(x), (C1 + x*exp(x**2/2)
- sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)/2)*exp(-x**2/2))
assert dsolve(eq, hint='1st_linear') == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_Bernoulli():
# Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n
eq = Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0)
sol = dsolve(eq, f(x), hint='Bernoulli')
assert sol == Eq(f(x), 1/(x*(C1 + 1/x)))
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_Riccati_special_minus2():
# Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2
eq = 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2)
sol = dsolve(eq, f(x), hint='Riccati_special_minus2')
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
@slow
def test_1st_exact1():
# Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0,
# where dp/df == dq/dx
eq1 = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
eq2 = (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x)
eq3 = 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x)
eq4 = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
eq5 = 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x)
sol1 = [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
sol2 = Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2))))
sol2b = Eq(log(f(x)) + x/f(x) + x**2, C1)
sol3 = Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1)
sol4 = Eq(x*cos(f(x)) + f(x)**3/3, C1)
sol5 = Eq(x**2*f(x) + f(x)**3/3, C1)
assert dsolve(eq1, f(x), hint='1st_exact') == sol1
assert dsolve(eq2, f(x), hint='1st_exact') == sol2
assert dsolve(eq3, f(x), hint='1st_exact') == sol3
assert dsolve(eq4, hint='1st_exact') == sol4
assert dsolve(eq5, hint='1st_exact', simplify=False) == sol5
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
# issue 5080 blocks the testing of this solution
# FIXME: assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2b, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0]
@slow
@XFAIL
def test_1st_exact2():
"""
This is an exact equation that fails under the exact engine. It is caught
by first order homogeneous albeit with a much contorted solution. The
exact engine fails because of a poorly simplified integral of q(0,y)dy,
where q is the function multiplying f'. The solutions should be
Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is
equivalent, but it is so complex that checkodesol fails, and takes a long
time to do so.
"""
if ON_TRAVIS:
skip("Too slow for travis.")
eq = (x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) -
sqrt(x**2 + f(x)**2)))*f(x).diff(x))
sol = dsolve(eq)
assert sol == Eq(log(x),
C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x +
27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)*
log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) +
9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) +
9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))))
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_separable1():
# test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and
# Pollard, pg. 55
eq1 = f(x).diff(x) - f(x)
eq2 = x*f(x).diff(x) - f(x)
eq3 = f(x).diff(x) + sin(x)
eq4 = f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x)
eq5 = f(x).diff(x)/tan(x) - f(x) - 2
eq6 = f(x).diff(x) * (1 - sin(f(x))) - 1
sol1 = Eq(f(x), C1*exp(x))
sol2 = Eq(f(x), C1*x)
sol3 = Eq(f(x), C1 + cos(x))
sol4 = Eq(f(x), tan(C1 + atan(x)))
sol5 = Eq(f(x), C1/cos(x) - 2)
sol6 = Eq(-x + f(x) + cos(f(x)), C1)
assert dsolve(eq1, hint='separable') == sol1
assert dsolve(eq2, hint='separable') == sol2
assert dsolve(eq3, hint='separable') == sol3
assert dsolve(eq4, hint='separable') == sol4
assert dsolve(eq5, hint='separable') == sol5
assert dsolve(eq6, hint='separable') == sol6
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
@slow
def test_separable2():
a = Symbol('a')
eq6 = f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x)
eq7 = f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x)
eq8 = x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2)
eq9 = exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x)
eq10 = (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) -
a**2*sin(f(x))*f(x).diff(x))
sol6 = Eq(Integral((u - 2)/u**3, (u, f(x))),
C1 + Integral(x**(-2), x))
sol7 = Eq(-log(-1 + f(x)**2)/2, C1 - log(2 + x))
sol8 = Eq(asinh(f(x)), C1 - log(log(x)))
# integrate cannot handle the integral on the lhs (cos/tan)
sol9 = Eq(Integral(cos(u)/tan(u), (u, f(x))),
C1 + Integral(-exp(1)*exp(x), x))
sol10 = Eq(-log(cos(f(x))), C1 - log(- a**2 + x**2)/2)
assert dsolve(eq6, hint='separable_Integral').dummy_eq(sol6)
assert dsolve(eq7, hint='separable', simplify=False) == sol7
assert dsolve(eq8, hint='separable', simplify=False) == sol8
assert dsolve(eq9, hint='separable_Integral').dummy_eq(sol9)
assert dsolve(eq10, hint='separable', simplify=False) == sol10
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=1, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0]
def test_separable3():
eq11 = f(x).diff(x) - f(x)*tan(x)
eq12 = (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x))
eq13 = f(x).diff(x) - f(x)*log(f(x))/tan(x)
sol11 = Eq(f(x), C1/cos(x))
sol12 = Eq(log(sin(f(x))), C1 + 2*x + 2*log(x - 1))
sol13 = Eq(log(log(f(x))), C1 + log(sin(x)))
assert dsolve(eq11, hint='separable') == sol11
assert dsolve(eq12, hint='separable', simplify=False) == sol12
assert dsolve(eq13, hint='separable', simplify=False) == sol13
assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0]
assert checkodesol(eq12, sol12, order=1, solve_for_func=False)[0]
assert checkodesol(eq13, sol13, order=1, solve_for_func=False)[0]
def test_separable4():
# This has a slow integral (1/((1 + y**2)*atan(y))), so we isolate it.
eq14 = x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x))
sol14 = Eq(log(atan(f(x))), C1 - log(x))
assert dsolve(eq14, hint='separable', simplify=False) == sol14
assert checkodesol(eq14, sol14, order=1, solve_for_func=False)[0]
def test_separable5():
eq15 = f(x).diff(x) + x*(f(x) + 1)
eq16 = exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x)
eq17 = f(x).diff(x) + f(x)
eq18 = sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x)
eq19 = (1 - x)*f(x).diff(x) - x*(f(x) + 1)
eq20 = f(x)*diff(f(x), x) + x - 3*x*f(x)**2
eq21 = f(x).diff(x) - exp(x + f(x))
sol15 = Eq(f(x), -1 + C1*exp(-x**2/2))
sol16 = Eq(-exp(-f(x)**2)/2, C1 - x - x**2/2)
sol17 = Eq(f(x), C1*exp(-x))
sol18 = Eq(-log(cos(2*f(x)))/2, C1 + log(cos(x)))
sol19 = Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1))
sol20 = Eq(log(-1 + 3*f(x)**2)/6, C1 + x**2/2)
sol21 = Eq(-exp(-f(x)), C1 + exp(x))
assert dsolve(eq15, hint='separable') == sol15
assert dsolve(eq16, hint='separable', simplify=False) == sol16
assert dsolve(eq17, hint='separable') == sol17
assert dsolve(eq18, hint='separable', simplify=False) == sol18
assert dsolve(eq19, hint='separable') == sol19
assert dsolve(eq20, hint='separable', simplify=False) == sol20
assert dsolve(eq21, hint='separable', simplify=False) == sol21
assert checkodesol(eq15, sol15, order=1, solve_for_func=False)[0]
assert checkodesol(eq16, sol16, order=1, solve_for_func=False)[0]
assert checkodesol(eq17, sol17, order=1, solve_for_func=False)[0]
assert checkodesol(eq18, sol18, order=1, solve_for_func=False)[0]
assert checkodesol(eq19, sol19, order=1, solve_for_func=False)[0]
assert checkodesol(eq20, sol20, order=1, solve_for_func=False)[0]
assert checkodesol(eq21, sol21, order=1, solve_for_func=False)[0]
def test_separable_1_5_checkodesol():
eq12 = (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x))
sol12 = Eq(-log(1 - cos(f(x))**2)/2, C1 - 2*x - 2*log(1 - x))
assert checkodesol(eq12, sol12, order=1, solve_for_func=False)[0]
def test_homogeneous_order():
assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0
assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None
assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1
assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/
(pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6)
assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0
assert homogeneous_order(f(x), x, f(x)) == 1
assert homogeneous_order(f(x)**2, x, f(x)) == 2
assert homogeneous_order(x*y*z, x, y) == 2
assert homogeneous_order(x*y*z, x, y, z) == 3
assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2
assert homogeneous_order(f(x, y)**2, x, f(x), y) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None
assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None
assert homogeneous_order(f(y), f(x), x) is None
assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0
assert homogeneous_order(log(1/y) + log(x**2), x, y) is None
assert homogeneous_order(log(1/y) + log(x), x, y) == 0
assert homogeneous_order(log(x/y), x, y) == 0
assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0
a = Symbol('a')
assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0
assert homogeneous_order(f(x).diff(x), x, y) is None
assert homogeneous_order(-f(x).diff(x) + x, x, y) is None
assert homogeneous_order(O(x), x, y) is None
assert homogeneous_order(x + O(x**2), x, y) is None
assert homogeneous_order(x**pi, x) == pi
assert homogeneous_order(x**x, x) is None
raises(ValueError, lambda: homogeneous_order(x*y))
@slow
def test_1st_homogeneous_coeff_ode():
# Type: First order homogeneous, y'=f(y/x)
eq1 = f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x)
eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x)
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
eq4 = 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x)
eq5 = 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x)
eq6 = x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x)
eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x)
eq8 = x + f(x) - (x - f(x))*f(x).diff(x)
sol1 = Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x))
sol2 = Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2)
sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1)))
sol4 = Eq(log(f(x)), C1 - 2*exp(x/f(x)))
sol5 = Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x)
sol6 = Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2)
sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))
sol8 = Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x))
# indep_div_dep actually has a simpler solution for eq2,
# but it runs too slow
assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1
assert dsolve(eq2, hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False) == sol2
assert dsolve(eq3, hint='1st_homogeneous_coeff_best') == sol3
assert dsolve(eq4, hint='1st_homogeneous_coeff_best') == sol4
assert dsolve(eq5, hint='1st_homogeneous_coeff_best') == sol5
assert dsolve(eq6, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol6
assert dsolve(eq7, hint='1st_homogeneous_coeff_best') == sol7
assert dsolve(eq8, hint='1st_homogeneous_coeff_best') == sol8
# FIXME: sol3 and sol5 don't work with checkodesol (because of LambertW?)
# previous code was testing with these other solutions:
sol3b = Eq(-f(x)/(1 + log(x/f(x))), C1)
sol5b = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0]
assert checkodesol(eq5, sol5b, order=1, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check2():
eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x)
sol2 = Eq(x/tan(f(x)/(2*x)), C1)
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
@XFAIL
def test_1st_homogeneous_coeff_ode_check3():
skip('This is a known issue.')
# checker cannot determine that the following expression is zero:
# (False,
# x*(log(exp(-LambertW(C1*x))) +
# LambertW(C1*x))*exp(-LambertW(C1*x) + 1))
# This is blocked by issue 5080.
eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x)
sol3a = Eq(f(x), x*exp(1 - LambertW(C1*x)))
assert checkodesol(eq3, sol3a, solve_for_func=True)[0]
# Checker can't verify this form either
# (False,
# C1*(log(C1*LambertW(C2*x)/x) + LambertW(C2*x) - 1)*LambertW(C2*x))
# It is because a = W(a)*exp(W(a)), so log(a) == log(W(a)) + W(a) and C2 =
# -E/C1 (which can be verified by solving with simplify=False).
sol3b = Eq(f(x), C1*LambertW(C2*x))
assert checkodesol(eq3, sol3b, solve_for_func=True)[0]
def test_1st_homogeneous_coeff_ode_check7():
eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x)
sol7 = Eq(log(C1*f(x)) + 2*sqrt(1 - x/f(x)), 0)
assert checkodesol(eq7, sol7, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode2():
eq1 = f(x).diff(x) - f(x)/x + 1/sin(f(x)/x)
eq2 = x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x)
eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x)
sol1 = [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))]
sol2 = Eq(log(f(x)), log(C1) + log(x/f(x)) - log(x**2/f(x)**2 - 1))
sol3 = Eq(f(x), log((1/(C1 - log(x)))**x))
# specific hints are applied for speed reasons
assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1
assert dsolve(eq2, hint='1st_homogeneous_coeff_best', simplify=False) == sol2
assert dsolve(eq3, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol3
# FIXME: sol3 doesn't work with checkodesol (because of **x?)
# previous code was testing with this other solution:
sol3b = Eq(f(x), log(log(C1/x)**(-x)))
assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0]
assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode_check9():
_u2 = Dummy('u2')
__a = Dummy('a')
eq9 = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x)
sol9 = Eq(-Integral(-1/(-(1 - sqrt(1 - _u2**2))*_u2 + _u2), (_u2, __a,
x/f(x))) + log(C1*f(x)), 0)
assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0]
def test_1st_homogeneous_coeff_ode3():
# The standard integration engine cannot handle one of the integrals
# involved (see issue 4551). meijerg code comes up with an answer, but in
# unconventional form.
# checkodesol fails for this equation, so its test is in
# test_1st_homogeneous_coeff_ode_check9 above. It has to compare string
# expressions because u2 is a dummy variable.
eq = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x)
sol = Eq(log(f(x)), C1 + Piecewise(
(acosh(f(x)/x), abs(f(x)**2)/x**2 > 1),
(-I*asin(f(x)/x), True)))
assert dsolve(eq, hint='1st_homogeneous_coeff_subs_indep_div_dep') == sol
def test_1st_homogeneous_coeff_corner_case():
eq1 = f(x).diff(x) - f(x)/x
c1 = classify_ode(eq1, f(x))
eq2 = x*f(x).diff(x) - f(x)
c2 = classify_ode(eq2, f(x))
sdi = "1st_homogeneous_coeff_subs_dep_div_indep"
sid = "1st_homogeneous_coeff_subs_indep_div_dep"
assert sid not in c1 and sdi not in c1
assert sid not in c2 and sdi not in c2
@slow
def test_nth_linear_constant_coeff_homogeneous():
# From Exercise 20, in Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 220
a = Symbol('a', positive=True)
k = Symbol('k', real=True)
eq1 = f(x).diff(x, 2) + 2*f(x).diff(x)
eq2 = f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x)
eq3 = f(x).diff(x, 2) - f(x)
eq4 = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x)
eq5 = 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x)
eq6 = Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0)
eq7 = diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x)
eq8 = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \
4*f(x).diff(x)
eq9 = f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \
4*f(x).diff(x) - 2*f(x)
eq10 = f(x).diff(x, 4) - a**2*f(x)
eq11 = f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x)
eq12 = f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x)
eq13 = f(x).diff(x, 4)
eq14 = f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x)
eq15 = 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x)
eq16 = f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x)
eq17 = f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x)
eq18 = f(x).diff(x, 4) + 3*f(x).diff(x, 3)
eq19 = f(x).diff(x, 4) - 2*f(x).diff(x, 2)
eq20 = f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \
12*f(x).diff(x) + 36*f(x)
eq21 = 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x)
eq22 = f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x)
eq23 = f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x)
eq24 = f(x).diff(x, 2) - f(x).diff(x) + f(x)
eq25 = f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x)
eq26 = f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x)
eq27 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x)
eq28 = f(x).diff(x, 3) + 8*f(x)
eq29 = f(x).diff(x, 4) + 4*f(x).diff(x, 2)
eq30 = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x)
eq31 = f(x).diff(x, 4) + f(x).diff(x, 2) + f(x)
eq32 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x)
sol1 = Eq(f(x), C1 + C2*exp(-2*x))
sol2 = Eq(f(x), (C1 + C2*exp(x))*exp(x))
sol3 = Eq(f(x), C1*exp(x) + C2*exp(-x))
sol4 = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))
sol5 = Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3)))
sol6 = Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(x*(-sqrt(2) - 1)))
sol7 = Eq(f(x),
C1*exp(3*x) + C2*exp(x*(-2 - sqrt(2))) + C3*exp(x*(-2 + sqrt(2))))
sol8 = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x))
sol9 = Eq(f(x),
C1*exp(x) + C2*exp(-x) + C3*exp(x*(-2 + sqrt(2))) +
C4*exp(x*(-2 - sqrt(2))))
sol10 = Eq(f(x),
C1*sin(x*sqrt(a)) + C2*cos(x*sqrt(a)) + C3*exp(x*sqrt(a)) +
C4*exp(-x*sqrt(a)))
sol11 = Eq(f(x),
C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2))))
sol12 = Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x))
sol13 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3)
sol14 = Eq(f(x), (C1 + C2*x)*exp(-2*x))
sol15 = Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3))
sol16 = Eq(f(x), (C1 + C2*x + C3*x**2)*exp(2*x))
sol17 = Eq(f(x), (C1 + C2*x)*exp(a*x))
sol18 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))
sol19 = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2)))
sol20 = Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x))
sol21 = Eq(f(x), C1*exp(x/2) + C2*exp(-x) + C3*exp(-x/3) + C4*exp(x*Rational(5, 6)))
sol22 = Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x))
sol23 = Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x))
sol24 = Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2))
sol25 = Eq(f(x),
C1*cos(x*sqrt(3)) + C2*sin(x*sqrt(3)) + C3*sin(x*sqrt(2)) +
C4*cos(x*sqrt(2)))
sol26 = Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x))
sol27 = Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2)))
sol28 = Eq(f(x),
(C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x))
sol29 = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x)
sol30 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))
sol31 = Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))/sqrt(exp(x))
+ (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*sqrt(exp(x)))
sol32 = Eq(f(x), C1*sin(x*sqrt(-sqrt(3) + 2)) + C2*sin(x*sqrt(sqrt(3) + 2))
+ C3*cos(x*sqrt(-sqrt(3) + 2)) + C4*cos(x*sqrt(sqrt(3) + 2)))
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
sol3s = constant_renumber(sol3)
sol4s = constant_renumber(sol4)
sol5s = constant_renumber(sol5)
sol6s = constant_renumber(sol6)
sol7s = constant_renumber(sol7)
sol8s = constant_renumber(sol8)
sol9s = constant_renumber(sol9)
sol10s = constant_renumber(sol10)
sol11s = constant_renumber(sol11)
sol12s = constant_renumber(sol12)
sol13s = constant_renumber(sol13)
sol14s = constant_renumber(sol14)
sol15s = constant_renumber(sol15)
sol16s = constant_renumber(sol16)
sol17s = constant_renumber(sol17)
sol18s = constant_renumber(sol18)
sol19s = constant_renumber(sol19)
sol20s = constant_renumber(sol20)
sol21s = constant_renumber(sol21)
sol22s = constant_renumber(sol22)
sol23s = constant_renumber(sol23)
sol24s = constant_renumber(sol24)
sol25s = constant_renumber(sol25)
sol26s = constant_renumber(sol26)
sol27s = constant_renumber(sol27)
sol28s = constant_renumber(sol28)
sol29s = constant_renumber(sol29)
sol30s = constant_renumber(sol30)
assert dsolve(eq1) in (sol1, sol1s)
assert dsolve(eq2) in (sol2, sol2s)
assert dsolve(eq3) in (sol3, sol3s)
assert dsolve(eq4) in (sol4, sol4s)
assert dsolve(eq5) in (sol5, sol5s)
assert dsolve(eq6) in (sol6, sol6s)
assert dsolve(eq7) in (sol7, sol7s)
assert dsolve(eq8) in (sol8, sol8s)
assert dsolve(eq9) in (sol9, sol9s)
assert dsolve(eq10) in (sol10, sol10s)
assert dsolve(eq11) in (sol11, sol11s)
assert dsolve(eq12) in (sol12, sol12s)
assert dsolve(eq13) in (sol13, sol13s)
assert dsolve(eq14) in (sol14, sol14s)
assert dsolve(eq15) in (sol15, sol15s)
assert dsolve(eq16) in (sol16, sol16s)
assert dsolve(eq17) in (sol17, sol17s)
assert dsolve(eq18) in (sol18, sol18s)
assert dsolve(eq19) in (sol19, sol19s)
assert dsolve(eq20) in (sol20, sol20s)
assert dsolve(eq21) in (sol21, sol21s)
assert dsolve(eq22) in (sol22, sol22s)
assert dsolve(eq23) in (sol23, sol23s)
assert dsolve(eq24) in (sol24, sol24s)
assert dsolve(eq25) in (sol25, sol25s)
assert dsolve(eq26) in (sol26, sol26s)
assert dsolve(eq27) in (sol27, sol27s)
assert dsolve(eq28) in (sol28, sol28s)
assert dsolve(eq29) in (sol29, sol29s)
assert dsolve(eq30) in (sol30, sol30s)
assert dsolve(eq31) in (sol31,)
assert dsolve(eq32) in (sol32,)
assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=3, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=3, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=4, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=4, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=4, solve_for_func=False)[0]
assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0]
assert checkodesol(eq12, sol12, order=2, solve_for_func=False)[0]
assert checkodesol(eq13, sol13, order=4, solve_for_func=False)[0]
assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0]
assert checkodesol(eq15, sol15, order=3, solve_for_func=False)[0]
assert checkodesol(eq16, sol16, order=3, solve_for_func=False)[0]
assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0]
assert checkodesol(eq18, sol18, order=4, solve_for_func=False)[0]
assert checkodesol(eq19, sol19, order=4, solve_for_func=False)[0]
assert checkodesol(eq20, sol20, order=4, solve_for_func=False)[0]
assert checkodesol(eq21, sol21, order=4, solve_for_func=False)[0]
assert checkodesol(eq22, sol22, order=4, solve_for_func=False)[0]
assert checkodesol(eq23, sol23, order=2, solve_for_func=False)[0]
assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0]
assert checkodesol(eq25, sol25, order=4, solve_for_func=False)[0]
assert checkodesol(eq26, sol26, order=2, solve_for_func=False)[0]
assert checkodesol(eq27, sol27, order=4, solve_for_func=False)[0]
assert checkodesol(eq28, sol28, order=3, solve_for_func=False)[0]
assert checkodesol(eq29, sol29, order=4, solve_for_func=False)[0]
assert checkodesol(eq30, sol30, order=5, solve_for_func=False)[0]
assert checkodesol(eq31, sol31, order=4, solve_for_func=False)[0]
assert checkodesol(eq32, sol32, order=4, solve_for_func=False)[0]
# Issue #15237
eqn = Derivative(x*f(x), x, x, x)
hint = 'nth_linear_constant_coeff_homogeneous'
raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=True))
raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=False))
def test_nth_linear_constant_coeff_homogeneous_rootof():
# One real root, two complex conjugate pairs
eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)]
sol = Eq(f(x),
C5*exp(r1*x)
+ exp(re(r2)*x) * (C1*sin(im(r2)*x) + C2*cos(im(r2)*x))
+ exp(re(r4)*x) * (C3*sin(im(r4)*x) + C4*cos(im(r4)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Three real roots, one complex conjugate pair
eq = f(x).diff(x,5) - 3*f(x).diff(x) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - 3*x + 1, n) for n in range(5)]
sol = Eq(f(x),
C3*exp(r1*x) + C4*exp(r2*x) + C5*exp(r3*x)
+ exp(re(r4)*x) * (C1*sin(im(r4)*x) + C2*cos(im(r4)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Five distinct real roots
eq = f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)]
sol = Eq(f(x), C1*exp(r1*x) + C2*exp(r2*x) + C3*exp(r3*x) + C4*exp(r4*x) + C5*exp(r5*x))
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Rational root and unsolvable quintic
eq = f(x).diff(x, 6) - 6*f(x).diff(x, 5) + 5*f(x).diff(x, 4) + 10*f(x).diff(x) - 50 * f(x)
r2, r3, r4, r5, r6 = [rootof(x**5 - x**4 + 10, n) for n in range(5)]
sol = Eq(f(x),
C5*exp(5*x)
+ C6*exp(x*r2)
+ exp(re(r3)*x) * (C1*sin(im(r3)*x) + C2*cos(im(r3)*x))
+ exp(re(r5)*x) * (C3*sin(im(r5)*x) + C4*cos(im(r5)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
# Five double roots (this is (x**5 - x + 1)**2)
eq = f(x).diff(x, 10) - 2*f(x).diff(x, 6) + 2*f(x).diff(x, 5) + f(x).diff(x, 2) - 2*f(x).diff(x, 1) + f(x)
r1, r2, r3, r4, r5 = [rootof(x**5 - x + 1, n) for n in range(5)]
sol = Eq(f(x),
(C1 + C2 *x)*exp(r1*x)
+ exp(re(r2)*x) * ((C3 + C4*x)*sin(im(r2)*x) + (C5 + C6 *x)*cos(im(r2)*x))
+ exp(re(r4)*x) * ((C7 + C8*x)*sin(im(r4)*x) + (C9 + C10*x)*cos(im(r4)*x))
)
assert dsolve(eq) == sol
# FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs...
def test_nth_linear_constant_coeff_homogeneous_irrational():
our_hint='nth_linear_constant_coeff_homogeneous'
eq = Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
E = exp(1)
eq = Eq(E * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(x/sqrt(E)) + C3*cos(x/sqrt(E)))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
eq = Eq(pi * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(x/sqrt(pi)) + C3*cos(x/sqrt(pi)))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
eq = Eq(I * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*exp(-sqrt(I)*x) + C3*exp(sqrt(I)*x))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=3, solve_for_func=False)[0]
@XFAIL
@slow
def test_nth_linear_constant_coeff_homogeneous_rootof_sol():
if ON_TRAVIS:
skip("Too slow for travis.")
eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x)
sol = Eq(f(x),
C1*exp(x*rootof(x**5 + 11*x - 2, 0)) +
C2*exp(x*rootof(x**5 + 11*x - 2, 1)) +
C3*exp(x*rootof(x**5 + 11*x - 2, 2)) +
C4*exp(x*rootof(x**5 + 11*x - 2, 3)) +
C5*exp(x*rootof(x**5 + 11*x - 2, 4)))
assert checkodesol(eq, sol, order=5, solve_for_func=False)[0]
@XFAIL
def test_noncircularized_real_imaginary_parts():
# If this passes, lines numbered 3878-3882 (at the time of this commit)
# of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous
# should be removed.
y = sqrt(1+x)
i, r = im(y), re(y)
assert not (i.has(atan2) and r.has(atan2))
def test_collect_respecting_exponentials():
# If this test passes, lines 1306-1311 (at the time of this commit)
# of sympy/solvers/ode.py should be removed.
sol = 1 + exp(x/2)
assert sol == collect( sol, exp(x/3))
def test_undetermined_coefficients_match():
assert _undetermined_coefficients_match(g(x), x) == {'test': False}
assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \
{'test': True, 'trialset':
set([cos(2*x + sqrt(5)), sin(2*x + sqrt(5))])}
assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \
{'test': False}
s = set([cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)])
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
exp(2*x)*sin(x)*(x**2 + x + 1), x
) == {
'test': True, 'trialset': set([exp(2*x)*sin(x), x**2*exp(2*x)*sin(x),
cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x),
x*exp(2*x)*sin(x)])}
assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False}
assert _undetermined_coefficients_match(log(x), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': set([2**x, x*2**x, x**2*2**x])}
assert _undetermined_coefficients_match(x**y, x) == {'test': False}
assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \
{'test': True, 'trialset': set([exp(1 + 3*x)])}
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': set([x*cos(x), x*sin(x), x**2*cos(x),
x**2*sin(x), cos(x), sin(x)])}
assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \
{'test': False}
assert _undetermined_coefficients_match(
x**2*sin(x)*exp(x) + x*sin(x) + x, x
) == {
'test': True, 'trialset': set([x**2*cos(x)*exp(x), x, cos(x), S.One,
exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x),
x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)])}
assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == {
'trialset': set([x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)]),
'test': True,
}
assert _undetermined_coefficients_match(2**x*x, x) == \
{'test': True, 'trialset': set([2**x, x*2**x])}
assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \
{'test': True, 'trialset': set([2**x*exp(2*x)])}
assert _undetermined_coefficients_match(exp(-x)/x, x) == \
{'test': False}
# Below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
assert _undetermined_coefficients_match(S(4), x) == \
{'test': True, 'trialset': set([S.One])}
assert _undetermined_coefficients_match(12*exp(x), x) == \
{'test': True, 'trialset': set([exp(x)])}
assert _undetermined_coefficients_match(exp(I*x), x) == \
{'test': True, 'trialset': set([exp(I*x)])}
assert _undetermined_coefficients_match(sin(x), x) == \
{'test': True, 'trialset': set([cos(x), sin(x)])}
assert _undetermined_coefficients_match(cos(x), x) == \
{'test': True, 'trialset': set([cos(x), sin(x)])}
assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \
{'test': True, 'trialset': set([S.One, cos(x), sin(x), exp(x)])}
assert _undetermined_coefficients_match(x**2, x) == \
{'test': True, 'trialset': set([S.One, x, x**2])}
assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(x), exp(x), exp(-x)])}
assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \
{'test': True, 'trialset': set([exp(2*x)*sin(x), cos(x)*exp(2*x)])}
assert _undetermined_coefficients_match(x - sin(x), x) == \
{'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])}
assert _undetermined_coefficients_match(x**2 + 2*x, x) == \
{'test': True, 'trialset': set([S.One, x, x**2])}
assert _undetermined_coefficients_match(4*x*sin(x), x) == \
{'test': True, 'trialset': set([x*cos(x), x*sin(x), cos(x), sin(x)])}
assert _undetermined_coefficients_match(x*sin(2*x), x) == \
{'test': True, 'trialset':
set([x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)])}
assert _undetermined_coefficients_match(x**2*exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])}
assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])}
assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \
{'test': True, 'trialset': set([S.One, x, x**2, exp(-2*x)])}
assert _undetermined_coefficients_match(x*exp(-x), x) == \
{'test': True, 'trialset': set([x*exp(-x), exp(-x)])}
assert _undetermined_coefficients_match(x + exp(2*x), x) == \
{'test': True, 'trialset': set([S.One, x, exp(2*x)])}
assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \
{'test': True, 'trialset': set([cos(x), sin(x), exp(-x)])}
assert _undetermined_coefficients_match(exp(x), x) == \
{'test': True, 'trialset': set([exp(x)])}
# converted from sin(x)**2
assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \
{'test': True, 'trialset': set([S.One, cos(2*x), sin(2*x)])}
# converted from exp(2*x)*sin(x)**2
assert _undetermined_coefficients_match(
exp(2*x)*(S.Half + cos(2*x)/2), x
) == {
'test': True, 'trialset': set([exp(2*x)*sin(2*x), cos(2*x)*exp(2*x),
exp(2*x)])}
assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \
{'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])}
# converted from sin(2*x)*sin(x)
assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \
{'test': True, 'trialset': set([cos(x), cos(3*x), sin(x), sin(3*x)])}
assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False}
@slow
def test_nth_linear_constant_coeff_undetermined_coefficients():
hint = 'nth_linear_constant_coeff_undetermined_coefficients'
g = exp(-x)
f2 = f(x).diff(x, 2)
c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x
eq1 = c - x*g
eq2 = c - g
# 3-27 below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
eq3 = f2 + 3*f(x).diff(x) + 2*f(x) - 4
eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x)
eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x)
eq6 = f2 + 3*f(x).diff(x) + 2*f(x) - sin(x)
eq7 = f2 + 3*f(x).diff(x) + 2*f(x) - cos(x)
eq8 = f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x))
eq9 = f2 + f(x).diff(x) + f(x) - x**2
eq10 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x)
eq11 = f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x)
eq12 = f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x)
eq13 = f2 + f(x).diff(x) - x**2 - 2*x
eq14 = f2 + f(x).diff(x) - x - sin(2*x)
eq15 = f2 + f(x) - 4*x*sin(x)
eq16 = f2 + 4*f(x) - x*sin(2*x)
eq17 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x)
eq18 = f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \
x**2*exp(-x)
eq19 = f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2
eq20 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x)
eq21 = f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x)
eq22 = f2 + f(x) - sin(x) - exp(-x)
eq23 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x)
# sin(x)**2
eq24 = f2 + f(x) - S.Half - cos(2*x)/2
# exp(2*x)*sin(x)**2
eq25 = f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S.Half - cos(2*x)/2)
eq26 = (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x -
sin(x) - cos(x))
# sin(2*x)*sin(x), skip 3127 for now, match bug
eq27 = f2 + f(x) - cos(x)/2 + cos(3*x)/2
eq28 = f(x).diff(x) - 1
sol1 = Eq(f(x),
-1 - x + (C1 + C2*x - 3*x**2/32 - x**3/24)*exp(-x) + C3*exp(x/3))
sol2 = Eq(f(x), -1 - x + (C1 + C2*x - x**2/8)*exp(-x) + C3*exp(x/3))
sol3 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x))
sol4 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x))
sol5 = Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(I*x)/10 - 3*I*exp(I*x)/10)
sol6 = Eq(f(x), -3*cos(x)/10 + sin(x)/10 + C1*exp(-x) + C2*exp(-2*x))
sol7 = Eq(f(x), cos(x)/10 + 3*sin(x)/10 + C1*exp(-x) + C2*exp(-2*x))
sol8 = Eq(f(x),
4 - 3*cos(x)/5 + sin(x)/5 + exp(x) + C1*exp(-x) + C2*exp(-2*x))
sol9 = Eq(f(x),
-2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2))
sol10 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))
sol11 = Eq(f(x), C1 + C2*exp(3*x) + (-3*sin(x) - cos(x))*exp(2*x)/5)
sol12 = Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x))
sol13 = Eq(f(x), C1 + x**3/3 + C2*exp(-x))
sol14 = Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x))
sol15 = Eq(f(x), (C1 + x)*sin(x) + (C2 - x**2)*cos(x))
sol16 = Eq(f(x), (C1 + x/16)*sin(2*x) + (C2 - x**2/8)*cos(2*x))
sol17 = Eq(f(x), (C1 + C2*x + x**4/12)*exp(-x))
sol18 = Eq(f(x), (C1 + C2*x + C3*x**2 - x**5/60 + x**3/3)*exp(-x))
sol19 = Eq(f(x), Rational(7, 4) - x*Rational(3, 2) + x**2/2 + C1*exp(-x) + (C2 - x)*exp(-2*x))
sol20 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)
sol21 = Eq(f(x), Rational(-1, 36) - x/6 + C1*exp(-3*x) + (C2 + x/5)*exp(2*x))
sol22 = Eq(f(x), C1*sin(x) + (C2 - x/2)*cos(x) + exp(-x)/2)
sol23 = Eq(f(x), (C1 + C2*x + C3*x**2 + x**3/6)*exp(x))
sol24 = Eq(f(x), S.Half - cos(2*x)/6 + C1*sin(x) + C2*cos(x))
sol25 = Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) +
(-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560)
sol26 = Eq(f(x),
C1 + (C2 + C3*x - x**2/8)*sin(x) + (C4 + C5*x + x**2/8)*cos(x) + x**2)
sol27 = Eq(f(x), cos(3*x)/16 + C1*cos(x) + (C2 + x/4)*sin(x))
sol28 = Eq(f(x), C1 + x)
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
sol3s = constant_renumber(sol3)
sol4s = constant_renumber(sol4)
sol5s = constant_renumber(sol5)
sol6s = constant_renumber(sol6)
sol7s = constant_renumber(sol7)
sol8s = constant_renumber(sol8)
sol9s = constant_renumber(sol9)
sol10s = constant_renumber(sol10)
sol11s = constant_renumber(sol11)
sol12s = constant_renumber(sol12)
sol13s = constant_renumber(sol13)
sol14s = constant_renumber(sol14)
sol15s = constant_renumber(sol15)
sol16s = constant_renumber(sol16)
sol17s = constant_renumber(sol17)
sol18s = constant_renumber(sol18)
sol19s = constant_renumber(sol19)
sol20s = constant_renumber(sol20)
sol21s = constant_renumber(sol21)
sol22s = constant_renumber(sol22)
sol23s = constant_renumber(sol23)
sol24s = constant_renumber(sol24)
sol25s = constant_renumber(sol25)
sol26s = constant_renumber(sol26)
sol27s = constant_renumber(sol27)
assert dsolve(eq1, hint=hint) in (sol1, sol1s)
assert dsolve(eq2, hint=hint) in (sol2, sol2s)
assert dsolve(eq3, hint=hint) in (sol3, sol3s)
assert dsolve(eq4, hint=hint) in (sol4, sol4s)
assert dsolve(eq5, hint=hint) in (sol5, sol5s)
assert dsolve(eq6, hint=hint) in (sol6, sol6s)
assert dsolve(eq7, hint=hint) in (sol7, sol7s)
assert dsolve(eq8, hint=hint) in (sol8, sol8s)
assert dsolve(eq9, hint=hint) in (sol9, sol9s)
assert dsolve(eq10, hint=hint) in (sol10, sol10s)
assert dsolve(eq11, hint=hint) in (sol11, sol11s)
assert dsolve(eq12, hint=hint) in (sol12, sol12s)
assert dsolve(eq13, hint=hint) in (sol13, sol13s)
assert dsolve(eq14, hint=hint) in (sol14, sol14s)
assert dsolve(eq15, hint=hint) in (sol15, sol15s)
assert dsolve(eq16, hint=hint) in (sol16, sol16s)
assert dsolve(eq17, hint=hint) in (sol17, sol17s)
assert dsolve(eq18, hint=hint) in (sol18, sol18s)
assert dsolve(eq19, hint=hint) in (sol19, sol19s)
assert dsolve(eq20, hint=hint) in (sol20, sol20s)
assert dsolve(eq21, hint=hint) in (sol21, sol21s)
assert dsolve(eq22, hint=hint) in (sol22, sol22s)
assert dsolve(eq23, hint=hint) in (sol23, sol23s)
assert dsolve(eq24, hint=hint) in (sol24, sol24s)
assert dsolve(eq25, hint=hint) in (sol25, sol25s)
assert dsolve(eq26, hint=hint) in (sol26, sol26s)
assert dsolve(eq27, hint=hint) in (sol27, sol27s)
assert dsolve(eq28, hint=hint) == sol28
assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0]
assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0]
assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0]
assert checkodesol(eq13, sol13, order=2, solve_for_func=False)[0]
assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0]
assert checkodesol(eq15, sol15, order=2, solve_for_func=False)[0]
assert checkodesol(eq16, sol16, order=2, solve_for_func=False)[0]
assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0]
assert checkodesol(eq18, sol18, order=3, solve_for_func=False)[0]
assert checkodesol(eq19, sol19, order=2, solve_for_func=False)[0]
assert checkodesol(eq20, sol20, order=2, solve_for_func=False)[0]
assert checkodesol(eq21, sol21, order=2, solve_for_func=False)[0]
assert checkodesol(eq22, sol22, order=2, solve_for_func=False)[0]
assert checkodesol(eq23, sol23, order=3, solve_for_func=False)[0]
assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0]
assert checkodesol(eq25, sol25, order=3, solve_for_func=False)[0]
assert checkodesol(eq26, sol26, order=5, solve_for_func=False)[0]
assert checkodesol(eq27, sol27, order=2, solve_for_func=False)[0]
assert checkodesol(eq28, sol28, order=1, solve_for_func=False)[0]
def test_issue_5787():
# This test case is to show the classification of imaginary constants under
# nth_linear_constant_coeff_undetermined_coefficients
eq = Eq(diff(f(x), x), I*f(x) + S.Half - I)
our_hint = 'nth_linear_constant_coeff_undetermined_coefficients'
assert our_hint in classify_ode(eq)
@XFAIL
def test_nth_linear_constant_coeff_undetermined_coefficients_imaginary_exp():
# Equivalent to eq26 in
# test_nth_linear_constant_coeff_undetermined_coefficients above.
# This fails because the algorithm for undetermined coefficients
# doesn't know to multiply exp(I*x) by sufficient x because it is linearly
# dependent on sin(x) and cos(x).
hint = 'nth_linear_constant_coeff_undetermined_coefficients'
eq26a = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x)
sol26 = Eq(f(x),
C1 + (C2 + C3*x - x**2/8)*sin(x) + (C4 + C5*x + x**2/8)*cos(x) + x**2)
assert dsolve(eq26a, hint=hint) == sol26
assert checkodesol(eq26a, sol26, order=5, solve_for_func=False)[0]
@slow
def test_nth_linear_constant_coeff_variation_of_parameters():
hint = 'nth_linear_constant_coeff_variation_of_parameters'
g = exp(-x)
f2 = f(x).diff(x, 2)
c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x
eq1 = c - x*g
eq2 = c - g
eq3 = f(x).diff(x) - 1
eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 4
eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x)
eq6 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x)
eq7 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x)
eq8 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x)
eq9 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x)
eq10 = f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x
eq11 = f2 + f(x) - 1/sin(x)*1/cos(x)
eq12 = f(x).diff(x, 4) - 1/x
sol1 = Eq(f(x),
-1 - x + (C1 + C2*x - 3*x**2/32 - x**3/24)*exp(-x) + C3*exp(x/3))
sol2 = Eq(f(x), -1 - x + (C1 + C2*x - x**2/8)*exp(-x) + C3*exp(x/3))
sol3 = Eq(f(x), C1 + x)
sol4 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x))
sol5 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x))
sol6 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))
sol7 = Eq(f(x), (C1 + C2*x + x**4/12)*exp(-x))
sol8 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)
sol9 = Eq(f(x), (C1 + C2*x + C3*x**2 + x**3/6)*exp(x))
sol10 = Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x))
sol11 = Eq(f(x), (C1 + log(sin(x) - 1)/2 - log(sin(x) + 1)/2
)*cos(x) + (C2 + log(cos(x) - 1)/2 - log(cos(x) + 1)/2)*sin(x))
sol12 = Eq(f(x), C1 + C2*x + x**3*(C3 + log(x)/6) + C4*x**2)
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
sol3s = constant_renumber(sol3)
sol4s = constant_renumber(sol4)
sol5s = constant_renumber(sol5)
sol6s = constant_renumber(sol6)
sol7s = constant_renumber(sol7)
sol8s = constant_renumber(sol8)
sol9s = constant_renumber(sol9)
sol10s = constant_renumber(sol10)
sol11s = constant_renumber(sol11)
sol12s = constant_renumber(sol12)
assert dsolve(eq1, hint=hint) in (sol1, sol1s)
assert dsolve(eq2, hint=hint) in (sol2, sol2s)
assert dsolve(eq3, hint=hint) in (sol3, sol3s)
assert dsolve(eq4, hint=hint) in (sol4, sol4s)
assert dsolve(eq5, hint=hint) in (sol5, sol5s)
assert dsolve(eq6, hint=hint) in (sol6, sol6s)
assert dsolve(eq7, hint=hint) in (sol7, sol7s)
assert dsolve(eq8, hint=hint) in (sol8, sol8s)
assert dsolve(eq9, hint=hint) in (sol9, sol9s)
assert dsolve(eq10, hint=hint) in (sol10, sol10s)
assert dsolve(eq11, hint=hint + '_Integral').doit() in (sol11, sol11s)
assert dsolve(eq12, hint=hint) in (sol12, sol12s)
assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0]
assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0]
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0]
assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0]
assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0]
assert checkodesol(eq9, sol9, order=3, solve_for_func=False)[0]
assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0]
assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0]
@slow
def test_nth_linear_constant_coeff_variation_of_parameters_simplify_False():
# solve_variation_of_parameters shouldn't attempt to simplify the
# Wronskian if simplify=False. If wronskian() ever gets good enough
# to simplify the result itself, this test might fail.
our_hint = 'nth_linear_constant_coeff_variation_of_parameters_Integral'
eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x)
sol_simp = dsolve(eq, f(x), hint=our_hint, simplify=True)
sol_nsimp = dsolve(eq, f(x), hint=our_hint, simplify=False)
assert sol_simp != sol_nsimp
# /----------
# eq.subs(*sol_simp.args) doesn't simplify to zero without help
(t, zero) = checkodesol(eq, sol_simp, order=5, solve_for_func=False)
# if this fails because zero.is_zero, replace this block with
# assert checkodesol(eq, sol_simp, order=5, solve_for_func=False)[0]
assert not zero.is_zero and zero.rewrite(exp).simplify() == 0
# \-----------
(t, zero) = checkodesol(eq, sol_nsimp, order=5, solve_for_func=False)
# if this fails because zero.is_zero, replace this block with
# assert checkodesol(eq, sol_simp, order=5, solve_for_func=False)[0]
assert zero == 0
# \-----------
assert t
def test_Liouville_ODE():
hint = 'Liouville'
# The first part here used to be test_ODE_1() from test_solvers.py
eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2
eq1a = diff(x*exp(-f(x)), x, x)
# compare to test_unexpanded_Liouville_ODE() below
eq2 = (eq1*exp(-f(x))/exp(f(x))).expand()
eq3 = diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x)
eq4 = x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x)
eq5 = Eq((x*exp(f(x))).diff(x, x), 0)
sol1 = Eq(f(x), log(x/(C1 + C2*x)))
sol1a = Eq(C1 + C2/x - exp(-f(x)), 0)
sol2 = sol1
sol3 = set(
[Eq(f(x), -sqrt(C1 + C2*log(x))),
Eq(f(x), sqrt(C1 + C2*log(x)))])
sol4 = set([Eq(f(x), sqrt(C1 + C2*exp(x))*exp(-x/2)),
Eq(f(x), -sqrt(C1 + C2*exp(x))*exp(-x/2))])
sol5 = Eq(f(x), log(C1 + C2/x))
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
sol3s = constant_renumber(sol3)
sol4s = constant_renumber(sol4)
sol5s = constant_renumber(sol5)
assert dsolve(eq1, hint=hint) in (sol1, sol1s)
assert dsolve(eq1a, hint=hint) in (sol1, sol1s)
assert dsolve(eq2, hint=hint) in (sol2, sol2s)
assert set(dsolve(eq3, hint=hint)) in (sol3, sol3s)
assert set(dsolve(eq4, hint=hint)) in (sol4, sol4s)
assert dsolve(eq5, hint=hint) in (sol5, sol5s)
assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0]
assert checkodesol(eq1a, sol1a, order=2, solve_for_func=False)[0]
assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0]
assert checkodesol(eq3, sol3, order=2, solve_for_func=False) == {(True, 0)}
assert checkodesol(eq4, sol4, order=2, solve_for_func=False) == {(True, 0)}
assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0]
not_Liouville1 = classify_ode(diff(f(x), x)/x + f(x)*diff(f(x), x, x)/2 -
diff(f(x), x)**2/2, f(x))
not_Liouville2 = classify_ode(diff(f(x), x)/x + diff(f(x), x, x)/2 -
x*diff(f(x), x)**2/2, f(x))
assert hint not in not_Liouville1
assert hint not in not_Liouville2
assert hint + '_Integral' not in not_Liouville1
assert hint + '_Integral' not in not_Liouville2
def test_unexpanded_Liouville_ODE():
# This is the same as eq1 from test_Liouville_ODE() above.
eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2
eq2 = eq1*exp(-f(x))/exp(f(x))
sol2 = Eq(f(x), log(x/(C1 + C2*x)))
sol2s = constant_renumber(sol2)
assert dsolve(eq2) in (sol2, sol2s)
assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0]
def test_issue_4785():
from sympy.abc import A
eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2
assert classify_ode(eq, f(x)) == ('1st_linear', 'almost_linear',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral', 'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
# issue 4864
eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x)
assert classify_ode(eq, f(x)) == ('1st_exact',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group', '1st_exact_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
def test_issue_4825():
raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x)))
assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
# See also issue 3793, test Z13.
raises(ValueError, lambda: dsolve(f(x).diff(x), f(y)))
assert classify_ode(f(x).diff(x), f(y), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
def test_constant_renumber_order_issue_5308():
from sympy.utilities.iterables import variations
assert constant_renumber(C1*x + C2*y) == \
constant_renumber(C1*y + C2*x) == \
C1*x + C2*y
e = C1*(C2 + x)*(C3 + y)
for a, b, c in variations([C1, C2, C3], 3):
assert constant_renumber(a*(b + x)*(c + y)) == e
def test_issue_5770():
k = Symbol("k", real=True)
t = Symbol('t')
w = Function('w')
sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t))
assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6
assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), set([C1, C2])) == \
C1*cos(x)*exp(x)
assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), set([C1, C2, C3])) == \
C1*cos(x) + C3*sin(x)
assert constantsimp(exp(C1 + x), set([C1])) == C1*exp(x)
assert constantsimp(x + C1 + y, set([C1, y])) == C1 + x
assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), set([C1])) == C1 + x
def test_issue_5112_5430():
assert homogeneous_order(-log(x) + acosh(x), x) is None
assert homogeneous_order(y - log(x), x, y) is None
def test_nth_order_linear_euler_eq_homogeneous():
x, t, a, b, c = symbols('x t a b c')
y = Function('y')
our_hint = "nth_linear_euler_eq_homogeneous"
eq = diff(f(t), t, 4)*t**4 - 13*diff(f(t), t, 2)*t**2 + 36*f(t)
assert our_hint in classify_ode(eq)
eq = a*y(t) + b*t*diff(y(t), t) + c*t**2*diff(y(t), t, 2)
assert our_hint in classify_ode(eq)
eq = Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0)
sol = C1 + C2*x**Rational(5, 2)
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0)
sol = C1*sqrt(x) + C2*x**3
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0)
sol = (C1 + C2*log(x))/x**2
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(6*f(x) - 6*diff(f(x), x)*x + 1*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0)
sol = dsolve(eq, f(x), hint=our_hint)
sol = C1/x**2 + C2*x + C3*x**3
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(-125*f(x) + 61*diff(f(x), x)*x - 12*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0)
sol = x**5*(C1 + C2*log(x) + C3*log(x)**2)
sols = [sol, constant_renumber(sol)]
sols += [sols[-1].expand()]
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs in sols
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = t**2*diff(y(t), t, 2) + t*diff(y(t), t) - 9*y(t)
sol = C1*t**3 + C2*t**-3
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, y(t), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = sin(x)*x**2*f(x).diff(x, 2) + sin(x)*x*f(x).diff(x) + sin(x)*f(x)
sol = C1*sin(log(x)) + C2*cos(log(x))
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
def test_nth_order_linear_euler_eq_nonhomogeneous_undetermined_coefficients():
x, t = symbols('x t')
a, b, c, d = symbols('a b c d', integer=True)
our_hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"
eq = x**4*diff(f(x), x, 4) - 13*x**2*diff(f(x), x, 2) + 36*f(x) + x
assert our_hint in classify_ode(eq, f(x))
eq = a*x**2*diff(f(x), x, 2) + b*x*diff(f(x), x) + c*f(x) + d*log(x)
assert our_hint in classify_ode(eq, f(x))
eq = Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1)
sol = C1 + C2*log(x) + log(x)**2/2
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq, f(x))
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3)
sol = x*(C1 + C2*x + Rational(1, 2)*x**2)
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq, f(x))
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x)
sol = C1/x + C2*x**3 - Rational(1, 16)*log(x)/x - Rational(1, 8)*log(x)**2/x
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq, f(x))
assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x))
sol = C1/x**4 + C2*x**2 - Rational(1,8)*log(x)**3 - Rational(3,32)*log(x)**2 - Rational(1,64)*log(x) - Rational(7, 256)
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(x**3*diff(f(x), x, x, x) - 3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), log(x))
sol = C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36)
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
def test_nth_order_linear_euler_eq_nonhomogeneous_variation_of_parameters():
x, t = symbols('x, t')
a, b, c, d = symbols('a, b, c, d', integer=True)
our_hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"
eq = Eq(x**2*diff(f(x),x,2) - 8*x*diff(f(x),x) + 12*f(x), x**2)
assert our_hint in classify_ode(eq, f(x))
eq = Eq(a*x**3*diff(f(x),x,3) + b*x**2*diff(f(x),x,2) + c*x*diff(f(x),x) + d*f(x), x*log(x))
assert our_hint in classify_ode(eq, f(x))
eq = Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4)
sol = C1*x + C2*x**2 + x**4/6
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x))
sol = C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2)
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x))
sol = C1*x + C2*x**2 + x**2*exp(x) - 2*x*exp(x)
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x)
sol = C1*x + C2*x**2 + log(x)/2 + Rational(3, 4)
sols = constant_renumber(sol)
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
eq = -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x
sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))
assert our_hint in classify_ode(eq)
assert dsolve(eq, f(x), hint=our_hint) == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False)[0]
def test_issue_5095():
f = Function('f')
raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf'))
def test_almost_linear():
from sympy import Ei
A = Symbol('A', positive=True)
our_hint = 'almost_linear'
f = Function('f')
d = f(x).diff(x)
eq = x**2*f(x)**2*d + f(x)**3 + 1
sol = dsolve(eq, f(x), hint = 'almost_linear')
assert sol[0].rhs == (C1*exp(3/x) - 1)**Rational(1, 3)
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = x*f(x)*d + 2*x*f(x)**2 + 1
sol = [
Eq(f(x), -sqrt((C1 - 2*Ei(4*x))*exp(-4*x))),
Eq(f(x), sqrt((C1 - 2*Ei(4*x))*exp(-4*x)))
]
assert set(dsolve(eq, f(x), hint = 'almost_linear')) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = x*d + x*f(x) + 1
sol = dsolve(eq, f(x), hint = 'almost_linear')
assert sol.rhs == (C1 - Ei(x))*exp(-x)
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
assert our_hint in classify_ode(eq, f(x))
eq = x*exp(f(x))*d + exp(f(x)) + 3*x
sol = dsolve(eq, f(x), hint = 'almost_linear')
assert sol.rhs == log(C1/x - x*Rational(3, 2))
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2
sol = dsolve(eq, f(x), hint = 'almost_linear')
assert sol.rhs == (C1 + Piecewise(
(x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x)
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_exact_enhancement():
f = Function('f')(x)
df = Derivative(f, x)
eq = f/x**2 + ((f*x - 1)/x)*df
sol = [Eq(f, (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
eq = (x*f - 1) + df*(x**2 - x*f)
sol = [Eq(f, x - sqrt(C1 + x**2 - 2*log(x))),
Eq(f, x + sqrt(C1 + x**2 - 2*log(x)))]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
eq = (x + 2)*sin(f) + df*x*cos(f)
sol = [Eq(f, -asin(C1*exp(-x)/x**2) + pi),
Eq(f, asin(C1*exp(-x)/x**2))]
assert set(dsolve(eq, f)) == set(sol)
assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)]
@slow
def test_separable_reduced():
f = Function('f')
x = Symbol('x')
df = f(x).diff(x)
eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
eq = x* df + f(x)* (1 / (x**2*f(x) - 1))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
sol = dsolve(eq, hint = 'separable_reduced', simplify=False)
assert sol.lhs == log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6
assert sol.rhs == C1 + log(x)
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = f(x).diff(x) + (f(x) / (x**4*f(x) - x))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
sol = dsolve(eq, hint = 'separable_reduced')
# FIXME: This one hangs
#assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0)] * 4
assert len(sol) == 4
eq = x*df + f(x)*(x**2*f(x))
sol = dsolve(eq, hint = 'separable_reduced', simplify=False)
assert sol == Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x))
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_homogeneous_function():
f = Function('f')
eq1 = tan(x + f(x))
eq2 = sin((3*x)/(4*f(x)))
eq3 = cos(x*f(x)*Rational(3, 4))
eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x))
eq5 = exp((2*x**2)/(3*f(x)**2))
eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2)))
eq7 = sin((3*x)/(5*f(x) + x**2))
assert homogeneous_order(eq1, x, f(x)) == None
assert homogeneous_order(eq2, x, f(x)) == 0
assert homogeneous_order(eq3, x, f(x)) == None
assert homogeneous_order(eq4, x, f(x)) == 0
assert homogeneous_order(eq5, x, f(x)) == 0
assert homogeneous_order(eq6, x, f(x)) == 0
assert homogeneous_order(eq7, x, f(x)) == None
def test_linear_coeff_match():
from sympy.solvers.ode import _linear_coeff_match
n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11)
rat = n/d
eq1 = sin(rat) + cos(rat.expand())
eq2 = rat
eq3 = log(sin(rat))
ans = (4, Rational(-13, 3))
assert _linear_coeff_match(eq1, f(x)) == ans
assert _linear_coeff_match(eq2, f(x)) == ans
assert _linear_coeff_match(eq3, f(x)) == ans
# no c
eq4 = (3*x)/f(x)
# not x and f(x)
eq5 = (3*x + 2)/x
# denom will be zero
eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5)
# not rational coefficient
eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5)
assert _linear_coeff_match(eq4, f(x)) is None
assert _linear_coeff_match(eq5, f(x)) is None
assert _linear_coeff_match(eq6, f(x)) is None
assert _linear_coeff_match(eq7, f(x)) is None
def test_linear_coefficients():
f = Function('f')
sol = Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2))
eq = f(x).diff(x) + (3 + 2*f(x))/(x + 3)
assert dsolve(eq, hint='linear_coefficients') == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_constantsimp_take_problem():
c = exp(C1) + 2
assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2
def test_issue_6879():
f = Function('f')
eq = Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x))
sol = (C1 + C2*x)*exp(x) + cos(x)/2
assert dsolve(eq).rhs == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_issue_6989():
f = Function('f')
k = Symbol('k')
eq = f(x).diff(x) - x*exp(-k*x)
csol = Eq(f(x), C1 + Piecewise(
((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),
(x**2/2, True)
))
sol = dsolve(eq, f(x))
assert sol == csol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
eq = -f(x).diff(x) + x*exp(-k*x)
csol = Eq(f(x), C1 + Piecewise(
((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),
(x**2/2, True)
))
sol = dsolve(eq, f(x))
assert sol == csol
assert checkodesol(eq, sol, order=1, solve_for_func=False)[0]
def test_heuristic1():
y, a, b, c, a4, a3, a2, a1, a0 = symbols("y a b c a4 a3 a2 a1 a0")
f = Function('f')
xi = Function('xi')
eta = Function('eta')
df = f(x).diff(x)
eq = Eq(df, x**2*f(x))
eq1 = f(x).diff(x) + a*f(x) - c*exp(b*x)
eq2 = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2)
eq3 = (1 + 2*x)*df + 2 - 4*exp(-f(x))
eq4 = f(x).diff(x) - (a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**Rational(-1, 2)
eq5 = x**2*df - f(x) + x**2*exp(x - (1/x))
eqlist = [eq, eq1, eq2, eq3, eq4, eq5]
i = infinitesimals(eq, hint='abaco1_simple')
assert i == [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0},
{eta(x, f(x)): f(x), xi(x, f(x)): 0},
{eta(x, f(x)): 0, xi(x, f(x)): x**(-2)}]
i1 = infinitesimals(eq1, hint='abaco1_simple')
assert i1 == [{eta(x, f(x)): exp(-a*x), xi(x, f(x)): 0}]
i2 = infinitesimals(eq2, hint='abaco1_simple')
assert i2 == [{eta(x, f(x)): exp(-x**2), xi(x, f(x)): 0}]
i3 = infinitesimals(eq3, hint='abaco1_simple')
assert i3 == [{eta(x, f(x)): 0, xi(x, f(x)): 2*x + 1},
{eta(x, f(x)): 0, xi(x, f(x)): 1/(exp(f(x)) - 2)}]
i4 = infinitesimals(eq4, hint='abaco1_simple')
assert i4 == [{eta(x, f(x)): 1, xi(x, f(x)): 0},
{eta(x, f(x)): 0,
xi(x, f(x)): sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4)}]
i5 = infinitesimals(eq5, hint='abaco1_simple')
assert i5 == [{xi(x, f(x)): 0, eta(x, f(x)): exp(-1/x)}]
ilist = [i, i1, i2, i3, i4, i5]
for eq, i in (zip(eqlist, ilist)):
check = checkinfsol(eq, i)
assert check[0]
def test_issue_6247():
eq = x**2*f(x)**2 + x*Derivative(f(x), x)
sol = Eq(f(x), 2*C1/(C1*x**2 - 1))
assert dsolve(eq, hint = 'separable_reduced') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x, x) + 4*f(x)
sol = Eq(f(x), C1*sin(2*x) + C2*cos(2*x))
assert dsolve(eq) == sol
assert checkodesol(eq, sol, order=1)[0]
def test_heuristic2():
xi = Function('xi')
eta = Function('eta')
df = f(x).diff(x)
# This ODE can be solved by the Lie Group method, when there are
# better assumptions
eq = df - (f(x)/x)*(x*log(x**2/f(x)) + 2)
i = infinitesimals(eq, hint='abaco1_product')
assert i == [{eta(x, f(x)): f(x)*exp(-x), xi(x, f(x)): 0}]
assert checkinfsol(eq, i)[0]
@slow
def test_heuristic3():
xi = Function('xi')
eta = Function('eta')
a, b = symbols("a b")
df = f(x).diff(x)
eq = x**2*df + x*f(x) + f(x)**2 + x**2
i = infinitesimals(eq, hint='bivariate')
assert i == [{eta(x, f(x)): f(x), xi(x, f(x)): x}]
assert checkinfsol(eq, i)[0]
eq = x**2*(-f(x)**2 + df)- a*x**2*f(x) + 2 - a*x
i = infinitesimals(eq, hint='bivariate')
assert checkinfsol(eq, i)[0]
def test_heuristic_4():
y, a = symbols("y a")
eq = x*(f(x).diff(x)) + 1 - f(x)**2
i = infinitesimals(eq, hint='chi')
assert checkinfsol(eq, i)[0]
def test_heuristic_function_sum():
xi = Function('xi')
eta = Function('eta')
eq = f(x).diff(x) - (3*(1 + x**2/f(x)**2)*atan(f(x)/x) + (1 - 2*f(x))/x +
(1 - 3*f(x))*(x/f(x)**2))
i = infinitesimals(eq, hint='function_sum')
assert i == [{eta(x, f(x)): f(x)**(-2) + x**(-2), xi(x, f(x)): 0}]
assert checkinfsol(eq, i)[0]
def test_heuristic_abaco2_similar():
xi = Function('xi')
eta = Function('eta')
F = Function('F')
a, b = symbols("a b")
eq = f(x).diff(x) - F(a*x + b*f(x))
i = infinitesimals(eq, hint='abaco2_similar')
assert i == [{eta(x, f(x)): -a/b, xi(x, f(x)): 1}]
assert checkinfsol(eq, i)[0]
eq = f(x).diff(x) - (f(x)**2 / (sin(f(x) - x) - x**2 + 2*x*f(x)))
i = infinitesimals(eq, hint='abaco2_similar')
assert i == [{eta(x, f(x)): f(x)**2, xi(x, f(x)): f(x)**2}]
assert checkinfsol(eq, i)[0]
def test_heuristic_abaco2_unique_unknown():
xi = Function('xi')
eta = Function('eta')
F = Function('F')
a, b = symbols("a b")
x = Symbol("x", positive=True)
eq = f(x).diff(x) - x**(a - 1)*(f(x)**(1 - b))*F(x**a/a + f(x)**b/b)
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert i == [{eta(x, f(x)): -f(x)*f(x)**(-b), xi(x, f(x)): x*x**(-a)}]
assert checkinfsol(eq, i)[0]
eq = f(x).diff(x) + tan(F(x**2 + f(x)**2) + atan(x/f(x)))
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert i == [{eta(x, f(x)): x, xi(x, f(x)): -f(x)}]
assert checkinfsol(eq, i)[0]
eq = (x*f(x).diff(x) + f(x) + 2*x)**2 -4*x*f(x) -4*x**2 -4*a
i = infinitesimals(eq, hint='abaco2_unique_unknown')
assert checkinfsol(eq, i)[0]
def test_heuristic_linear():
a, b, m, n = symbols("a b m n")
eq = x**(n*(m + 1) - m)*(f(x).diff(x)) - a*f(x)**n -b*x**(n*(m + 1))
i = infinitesimals(eq, hint='linear')
assert checkinfsol(eq, i)[0]
@XFAIL
def test_kamke():
a, b, alpha, c = symbols("a b alpha c")
eq = x**2*(a*f(x)**2+(f(x).diff(x))) + b*x**alpha + c
i = infinitesimals(eq, hint='sum_function')
assert checkinfsol(eq, i)[0]
def test_series():
# FIXME: Maybe there should be a way to check series solutions
# checkodesol doesn't work with them.
C1 = Symbol("C1")
eq = f(x).diff(x) - f(x)
assert dsolve(eq, hint='1st_power_series') == Eq(f(x),
C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 +
C1*x**5/120 + O(x**6))
eq = f(x).diff(x) - x*f(x)
assert dsolve(eq, hint='1st_power_series') == Eq(f(x),
C1*x**4/8 + C1*x**2/2 + C1 + O(x**6))
eq = f(x).diff(x) - sin(x*f(x))
sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3))
assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol
@XFAIL
@SKIP
def test_lie_group_issue17322():
eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x
sol = dsolve(eq, f(x))
assert checkodesol(eq, sol) == (True, 0)
eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, 0)
eq=Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0)
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, 0)
eq=f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x)
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, 0)
@slow
def test_lie_group():
C1 = Symbol("C1")
x = Symbol("x") # assuming x is real generates an error!
a, b, c = symbols("a b c")
eq = f(x).diff(x)**2
sol = dsolve(eq, f(x), hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = Eq(f(x).diff(x), x**2*f(x))
sol = dsolve(eq, f(x), hint='lie_group')
assert sol == Eq(f(x), C1*exp(x**3)**Rational(1, 3))
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x) + a*f(x) - c*exp(b*x)
sol = dsolve(eq, f(x), hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2)
sol = dsolve(eq, f(x), hint='lie_group')
actual_sol = Eq(f(x), (C1 + x**2/2)*exp(-x**2))
errstr = str(eq)+' : '+str(sol)+' == '+str(actual_sol)
assert sol == actual_sol, errstr
assert checkodesol(eq, sol) == (True, 0)
eq = (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x))
sol = dsolve(eq, f(x), hint='lie_group')
assert sol == Eq(f(x), log(C1/(2*x + 1) + 2))
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x))
sol = dsolve(eq, f(x), hint='lie_group')
assert checkodesol(eq, sol)[0]
eq = x**2*f(x)**2 + x*Derivative(f(x), x)
sol = dsolve(eq, f(x), hint='lie_group')
assert sol == Eq(f(x), 2/(C1 + x**2))
assert checkodesol(eq, sol) == (True, 0)
eq=diff(f(x),x) + 2*x*f(x) - x*exp(-x**2)
sol = Eq(f(x), exp(-x**2)*(C1 + x**2/2))
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = diff(f(x),x) + f(x)*cos(x) - exp(2*x)
sol = Eq(f(x), exp(-sin(x))*(C1 + Integral(exp(2*x)*exp(sin(x)), x)))
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2
sol = Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1)
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = x*diff(f(x),x) + f(x) - x*sin(x)
sol = Eq(f(x), (C1 - x*cos(x) + sin(x))/x)
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = x*diff(f(x),x) - f(x) - x/log(x)
sol = Eq(f(x), x*(C1 + log(log(x))))
assert sol == dsolve(eq, hint='lie_group')
assert checkodesol(eq, sol) == (True, 0)
eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x))
sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol[0]) == (True, 0)
assert checkodesol(eq, sol[1]) == (True, 0)
eq = f(x).diff(x) * (f(x).diff(x) - f(x))
sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1)]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol[0]) == (True, 0)
assert checkodesol(eq, sol[1]) == (True, 0)
@XFAIL
def test_lie_group_issue15219():
eqn = exp(f(x).diff(x)-f(x))
assert 'lie_group' not in classify_ode(eqn, f(x))
def test_user_infinitesimals():
x = Symbol("x") # assuming x is real generates an error
eq = x*(f(x).diff(x)) + 1 - f(x)**2
sol = Eq(f(x), (C1 + x**2)/(C1 - x**2))
infinitesimals = {'xi':sqrt(f(x) - 1)/sqrt(f(x) + 1), 'eta':0}
assert dsolve(eq, hint='lie_group', **infinitesimals) == sol
assert checkodesol(eq, sol) == (True, 0)
def test_issue_7081():
eq = x*(f(x).diff(x)) + 1 - f(x)**2
s = Eq(f(x), -1/(-C1 + x**2)*(C1 + x**2))
assert dsolve(eq) == s
assert checkodesol(eq, s) == (True, 0)
@slow
def test_2nd_power_series_ordinary():
# FIXME: Maybe there should be a way to check series solutions
# checkodesol doesn't work with them.
C1, C2 = symbols("C1 C2")
eq = f(x).diff(x, 2) - x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
assert dsolve(eq, hint='2nd_power_series_ordinary') == Eq(f(x),
C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6))
assert dsolve(eq, x0=-2, hint='2nd_power_series_ordinary') == Eq(f(x),
C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1)
+ C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2))
+ O(x**6))
assert dsolve(eq, n=2, hint='2nd_power_series_ordinary') == Eq(f(x), C2*x + C1 + O(x**2))
eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
assert dsolve(eq) == Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x
+ O(x**6))
eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
assert dsolve(eq) == Eq(f(x), C2*(
x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6))
eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
assert dsolve(eq) == Eq(f(x), C2*(
-x**4/24 + x**3/6 + 1) + C1*x*(x**3/24 + x**2/6 - x/2
+ 1) + O(x**6))
eq = f(x).diff(x, 2) + x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
assert dsolve(eq, n=7, hint='2nd_power_series_ordinary') == Eq(f(x), C2*(
x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7))
def test_Airy_equation():
eq = f(x).diff(x, 2) - x*f(x)
sol = Eq(f(x), C1*airyai(x) + C2*airybi(x))
sols = constant_renumber(sol)
assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary')
assert checkodesol(eq, sol) == (True, 0)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols)
eq = f(x).diff(x, 2) + 2*x*f(x)
sol = Eq(f(x), C1*airyai(-2**(S(1)/3)*x) + C2*airybi(-2**(S(1)/3)*x))
sols = constant_renumber(sol)
assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary')
assert checkodesol(eq, sol) == (True, 0)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols)
def test_2nd_power_series_regular():
# FIXME: Maybe there should be a way to check series solutions
# checkodesol doesn't work with them.
eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x)
assert dsolve(eq, hint='2nd_power_series_regular') == Eq(f(x), C1*x**2*(-16*x**3/9 +
4*x**2 - 4*x + 1) + O(x**6))
eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 +
1)*f(x)
assert dsolve(eq, hint='2nd_power_series_regular') == Eq(f(x), C1*sqrt(x)*(
x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6))
eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + (
x**2 - 2)*f(x)
assert dsolve(eq) == Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 +
x**2/2 + x/2 + 1)/x + C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1)
+ O(x**6))
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x)
assert dsolve(eq) == Eq(f(x), C1*besselj(S.Half, x) + C2*bessely(S.Half, x))
def test_2nd_linear_bessel_equation():
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - 4)*f(x)
sol = Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 +25)*f(x)
sol = Eq(f(x), C1*besselj(5*I, x) + C2*bessely(5*I, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2)*f(x)
sol = Eq(f(x), C1*besselj(0, x) + C2*bessely(0, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (81*x**2 -S(1)/9)*f(x)
sol = Eq(f(x), C1*besselj(S(1)/3, 9*x) + C2*bessely(S(1)/3, 9*x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**4 - 4)*f(x)
sol = Eq(f(x), C1*besselj(1, x**2/2) + C2*bessely(1, x**2/2))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) + (x**4 - 4)*f(x)
sol = Eq(f(x), (C1*besselj(sqrt(17)/4, x**2/2) + C2*bessely(sqrt(17)/4, x**2/2))/sqrt(x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x)
sol = Eq(f(x), C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x)
sol = Eq(f(x), x**2*(C1*besselj(0, 4*sqrt(x)) + C2*bessely(0, 4*sqrt(x))))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x)
sol = Eq(f(x), x*(C1*besselj(S(1)/2, x**2) + C2*bessely(S(1)/2, x**2)))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
eq = (x-2)**2*(f(x).diff(x, 2)) - (x-2)*f(x).diff(x) + 4*(x-2)**2*f(x)
sol = Eq(f(x), (x - 2)*(C1*besselj(1, 2*x - 4) + C2*bessely(1, 2*x - 4)))
sols = constant_renumber(sol)
assert dsolve(eq, f(x)) in (sol, sols)
assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols)
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
def test_issue_7093():
x = Symbol("x") # assuming x is real leads to an error
sol = [Eq(f(x), C1 - 2*x*sqrt(x**3)/5),
Eq(f(x), C1 + 2*x*sqrt(x**3)/5)]
eq = Derivative(f(x), x)**2 - x**3
assert set(dsolve(eq)) == set(sol)
assert checkodesol(eq, sol) == [(True, 0)] * 2
def test_dsolve_linsystem_symbol():
eps = Symbol('epsilon', positive=True)
eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x)))
sol1 = [Eq(f(x), -C1*eps*cos(eps*x) - C2*eps*sin(eps*x)),
Eq(g(x), -C1*eps*sin(eps*x) + C2*eps*cos(eps*x))]
assert checksysodesol(eq1, sol1) == (True, [0, 0])
def test_C1_function_9239():
t = Symbol('t')
C1 = Function('C1')
C2 = Function('C2')
C3 = Symbol('C3')
C4 = Symbol('C4')
eq = (Eq(diff(C1(t), t), 9*C2(t)), Eq(diff(C2(t), t), 12*C1(t)))
sol = [Eq(C1(t), 9*C3*exp(6*sqrt(3)*t) + 9*C4*exp(-6*sqrt(3)*t)),
Eq(C2(t), 6*sqrt(3)*C3*exp(6*sqrt(3)*t) - 6*sqrt(3)*C4*exp(-6*sqrt(3)*t))]
assert checksysodesol(eq, sol) == (True, [0, 0])
def test_issue_15056():
t = Symbol('t')
C3 = Symbol('C3')
assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3
def test_issue_10379():
t,y = symbols('t,y')
eq = f(t).diff(t)-(1-51.05*y*f(t))
sol = Eq(f(t), (0.019588638589618*exp(y*(C1 - 51.05*t)) + 0.019588638589618)/y)
dsolve_sol = dsolve(eq, rational=False)
assert str(dsolve_sol) == str(sol)
assert checkodesol(eq, dsolve_sol)[0]
def test_issue_10867():
x = Symbol('x')
eq = Eq(g(x).diff(x).diff(x), (x-2)**2 + (x-3)**3)
sol = Eq(g(x), C1 + C2*x + x**5/20 - 2*x**4/3 + 23*x**3/6 - 23*x**2/2)
assert dsolve(eq, g(x)) == sol
assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
def test_issue_11290():
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
sol_1 = dsolve(eq, f(x), simplify=False, hint='1st_exact_Integral')
sol_0 = dsolve(eq, f(x), simplify=False, hint='1st_exact')
assert sol_1.dummy_eq(Eq(Subs(
Integral(u**2 - x*sin(u) - Integral(-sin(u), x), u) +
Integral(cos(u), x), u, f(x)), C1))
assert sol_1.doit() == sol_0
assert checkodesol(eq, sol_0, order=1, solve_for_func=False)
assert checkodesol(eq, sol_1, order=1, solve_for_func=False)
def test_issue_4838():
# Issue #15999
eq = f(x).diff(x) - C1*f(x)
sol = Eq(f(x), C2*exp(C1*x))
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0)
# Issue #13691
eq = f(x).diff(x) - C1*g(x).diff(x)
sol = Eq(f(x), C2 + C1*g(x))
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, f(x), order=1, solve_for_func=False) == (True, 0)
# Issue #4838
eq = f(x).diff(x) - 3*C1 - 3*x**2
sol = Eq(f(x), C2 + 3*C1*x + x**3)
assert dsolve(eq, f(x)) == sol
assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0)
@slow
def test_issue_14395():
eq = Derivative(f(x), x, x) + 9*f(x) - sec(x)
sol = Eq(f(x), (C1 - x/3 + sin(2*x)/3)*sin(3*x) + (C2 + log(cos(x))
- 2*log(cos(x)**2)/3 + 2*cos(x)**2/3)*cos(3*x))
assert dsolve(eq, f(x)) == sol
# FIXME: assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0)
def test_sysode_linear_neq_order1():
from sympy.abc import t
Z0 = Function('Z0')
Z1 = Function('Z1')
Z2 = Function('Z2')
Z3 = Function('Z3')
k01, k10, k20, k21, k23, k30 = symbols('k01 k10 k20 k21 k23 k30')
eq = (Eq(Derivative(Z0(t), t), -k01*Z0(t) + k10*Z1(t) + k20*Z2(t) + k30*Z3(t)), Eq(Derivative(Z1(t), t),
k01*Z0(t) - k10*Z1(t) + k21*Z2(t)), Eq(Derivative(Z2(t), t), -(k20 + k21 + k23)*Z2(t)), Eq(Derivative(Z3(t),
t), k23*Z2(t) - k30*Z3(t)))
sols_eq = [Eq(Z0(t), C1*k10/k01 + C2*(-k10 + k30)*exp(-k30*t)/(k01 + k10 - k30) - C3*exp(t*(-
k01 - k10)) + C4*(k10*k20 + k10*k21 - k10*k30 - k20**2 - k20*k21 - k20*k23 + k20*k30 +
k23*k30)*exp(t*(-k20 - k21 - k23))/(k23*(k01 + k10 - k20 - k21 - k23))),
Eq(Z1(t), C1 - C2*k01*exp(-k30*t)/(k01 + k10 - k30) + C3*exp(t*(-k01 - k10)) + C4*(k01*k20 + k01*k21
- k01*k30 - k20*k21 - k21**2 - k21*k23 + k21*k30)*exp(t*(-k20 - k21 - k23))/(k23*(k01 + k10 - k20 -
k21 - k23))),
Eq(Z2(t), C4*(-k20 - k21 - k23 + k30)*exp(t*(-k20 - k21 - k23))/k23),
Eq(Z3(t), C2*exp(-k30*t) + C4*exp(t*(-k20 - k21 - k23)))]
assert dsolve(eq, simplify=False) == sols_eq
assert checksysodesol(eq, sols_eq) == (True, [0, 0, 0, 0])
@slow
def test_nth_order_reducible():
from sympy.solvers.ode import _nth_order_reducible_match
eqn = Eq(x*Derivative(f(x), x)**2 + Derivative(f(x), x, 2), 0)
sol = Eq(f(x),
C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert sol == dsolve(eqn, f(x), hint='nth_order_reducible')
assert sol == dsolve(eqn, f(x))
F = lambda eq: _nth_order_reducible_match(eq, f(x))
D = Derivative
assert F(D(y*f(x), x, y) + D(f(x), x)) is None
assert F(D(y*f(y), y, y) + D(f(y), y)) is None
assert F(f(x)*D(f(x), x) + D(f(x), x, 2)) is None
assert F(D(x*f(y), y, 2) + D(u*y*f(x), x, 3)) is None # no simplification by design
assert F(D(f(y), y, 2) + D(f(y), y, 3) + D(f(x), x, 4)) is None
assert F(D(f(x), x, 2) + D(f(x), x, 3)) == dict(n=2)
eqn = -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x
sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert sol == dsolve(eqn, f(x))
assert sol == dsolve(eqn, f(x), hint='nth_order_reducible')
eqn = Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0)
sol = Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert sol == dsolve(eqn, f(x))
assert sol == dsolve(eqn, f(x), hint='nth_order_reducible')
eqn = f(x).diff(x, 2) + 2*f(x).diff(x)
sol = Eq(f(x), C1 + C2*exp(-2*x))
sols = constant_renumber(sol)
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x)) in (sol, sols)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols)
eqn = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x)
sol = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))
sols = constant_renumber(sol)
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x)) in (sol, sols)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols)
eqn = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \
4*f(x).diff(x)
sol = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x))
sols = constant_renumber(sol)
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x)) in (sol, sols)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols)
eqn = f(x).diff(x, 4) + 3*f(x).diff(x, 3)
sol = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))
sols = constant_renumber(sol)
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x)) in (sol, sols)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols)
eqn = f(x).diff(x, 4) - 2*f(x).diff(x, 2)
sol = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2)))
sols = constant_renumber(sol)
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x)) in (sol, sols)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols)
eqn = f(x).diff(x, 4) + 4*f(x).diff(x, 2)
sol = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x)
sols = constant_renumber(sol)
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x)) in (sol, sols)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols)
eqn = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x)
# These are equivalent:
sol1 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))
sol2 = Eq(f(x), C1 + C2*(x*sin(x) + cos(x)) + C3*(-x*cos(x) + sin(x)) + C4*sin(x) + C5*cos(x))
sol1s = constant_renumber(sol1)
sol2s = constant_renumber(sol2)
assert checkodesol(eqn, sol1, order=2, solve_for_func=False) == (True, 0)
assert checkodesol(eqn, sol2, order=2, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x)) in (sol1, sol1s)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol2, sol2s)
# In this case the reduced ODE has two distinct solutions
eqn = f(x).diff(x, 2) - f(x).diff(x)**3
sol = [Eq(f(x), C2 - sqrt(2)*I*(C1 + x)*sqrt(1/(C1 + x))),
Eq(f(x), C2 + sqrt(2)*I*(C1 + x)*sqrt(1/(C1 + x)))]
sols = constant_renumber(sol)
assert checkodesol(eqn, sol, order=2, solve_for_func=False) == [(True, 0), (True, 0)]
assert dsolve(eqn, f(x)) in (sol, sols)
assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols)
def test_nth_algebraic():
eqn = Eq(Derivative(f(x), x), Derivative(g(x), x))
sol = Eq(f(x), C1 + g(x))
assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), hint='nth_algebraic'), dsolve(eqn, f(x), hint='nth_algebraic')
assert sol == dsolve(eqn, f(x))
eqn = (diff(f(x)) - x)*(diff(f(x)) + x)
sol = [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)]
assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0]
assert set(sol) == set(dsolve(eqn, f(x), hint='nth_algebraic'))
assert set(sol) == set(dsolve(eqn, f(x)))
eqn = (1 - sin(f(x))) * f(x).diff(x)
sol = Eq(f(x), C1)
assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), hint='nth_algebraic')
assert sol == dsolve(eqn, f(x))
M, m, r, t = symbols('M m r t')
phi = Function('phi')
eqn = Eq(-M * phi(t).diff(t),
Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t))
solns = [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))]
assert checkodesol(eqn, solns[0], order=2, solve_for_func=False)[0]
assert checkodesol(eqn, solns[1], order=2, solve_for_func=False)[0]
assert set(solns) == set(dsolve(eqn, phi(t), hint='nth_algebraic'))
assert set(solns) == set(dsolve(eqn, phi(t)))
eqn = f(x) * f(x).diff(x) * f(x).diff(x, x)
sol = Eq(f(x), C1 + C2*x)
assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), hint='nth_algebraic')
assert sol == dsolve(eqn, f(x))
eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1)
sol = Eq(f(x), C1 + C2*x)
assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), hint='nth_algebraic')
assert sol == dsolve(eqn, f(x))
eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x)
solns = [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)]
assert checkodesol(eqn, solns[0], order=2, solve_for_func=False)[0]
assert checkodesol(eqn, solns[1], order=2, solve_for_func=False)[0]
assert set(solns) == set(dsolve(eqn, f(x), hint='nth_algebraic'))
assert set(solns) == set(dsolve(eqn, f(x)))
def test_nth_algebraic_issue15999():
eqn = f(x).diff(x) - C1
sol = Eq(f(x), C1*x + C2) # Correct solution
assert checkodesol(eqn, sol, order=1, solve_for_func=False) == (True, 0)
assert dsolve(eqn, f(x), hint='nth_algebraic') == sol
assert dsolve(eqn, f(x)) == sol
def test_nth_algebraic_redundant_solutions():
# This one has a redundant solution that should be removed
eqn = f(x)*f(x).diff(x)
soln = Eq(f(x), C1)
assert checkodesol(eqn, soln, order=1, solve_for_func=False)[0]
assert soln == dsolve(eqn, f(x), hint='nth_algebraic')
assert soln == dsolve(eqn, f(x))
# This has two integral solutions and no algebraic solutions
eqn = (diff(f(x)) - x)*(diff(f(x)) + x)
sol = [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)]
assert all(c[0] for c in checkodesol(eqn, sol, order=1, solve_for_func=False))
assert set(sol) == set(dsolve(eqn, f(x), hint='nth_algebraic'))
assert set(sol) == set(dsolve(eqn, f(x)))
eqn = f(x) + f(x)*f(x).diff(x)
solns = [Eq(f(x), 0),
Eq(f(x), C1 - x)]
assert all(c[0] for c in checkodesol(eqn, solns, order=1, solve_for_func=False))
assert set(solns) == set(dsolve(eqn, f(x)))
from sympy.solvers.ode import _remove_redundant_solutions
solns = [Eq(f(x), exp(x)),
Eq(f(x), C1*exp(C2*x))]
solns_final = _remove_redundant_solutions(eqn, solns, 2, x)
assert solns_final == [Eq(f(x), C1*exp(C2*x))]
# This one needs a substitution f' = g.
eqn = -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x
sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))
assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x))
#
# These tests can be combined with the above test if they get fixed
# so that dsolve actually works in all these cases.
#
# prep = True breaks this
def test_nth_algebraic_noprep1():
eqn = Derivative(x*f(x), x, x, x)
sol = Eq(f(x), (C1 + C2*x + C3*x**2) / x)
assert checkodesol(eqn, sol, order=3, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), prep=False, hint='nth_algebraic')
@XFAIL
def test_nth_algebraic_prep1():
eqn = Derivative(x*f(x), x, x, x)
sol = Eq(f(x), (C1 + C2*x + C3*x**2) / x)
assert checkodesol(eqn, sol, order=3, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), prep=True, hint='nth_algebraic')
assert sol == dsolve(eqn, f(x))
# prep = True breaks this
def test_nth_algebraic_noprep2():
eqn = Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x))
sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))
assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), prep=False, hint='nth_algebraic')
@XFAIL
def test_nth_algebraic_prep2():
eqn = Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x))
sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))
assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0]
assert sol == dsolve(eqn, f(x), prep=True, hint='nth_algebraic')
assert sol == dsolve(eqn, f(x))
# Needs to be a way to know how to combine derivatives in the expression
def test_factoring_ode():
from sympy import Mul
eqn = Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x)
# 2-arg Mul!
soln = Eq(f(x), C1 + C2*x + C3/Mul(2, (x + 1), evaluate=False))
assert checkodesol(eqn, soln, order=2, solve_for_func=False)[0]
assert soln == dsolve(eqn, f(x))
def test_issue_11542():
m = 96
g = 9.8
k = .2
f1 = g * m
t = Symbol('t')
v = Function('v')
v_equation = dsolve(f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 0)
assert str(v_equation) == \
'Eq(v(t), -68.585712797929/tanh(C1 - 0.142886901662352*t))'
def test_issue_15913():
eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x)
sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x)
assert checkodesol(eq, sol) == (True, 0)
sol = C1 + C2*exp(-x*y)
eq = Derivative(y*f(x), x) + f(x).diff(x, 2)
assert checkodesol(eq, sol, f(x)) == (True, 0)
def test_issue_16146():
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)]))
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)]))
def test_dsolve_remove_redundant_solutions():
eq = (f(x)-2)*f(x).diff(x)
sol = Eq(f(x), C1)
assert dsolve(eq) == sol
eq = (f(x)-sin(x))*(f(x).diff(x, 2))
sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))}
assert set(dsolve(eq)) == sol
eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3)
sol = Eq(f(x), C1 + C2*x + C3*x**2)
assert dsolve(eq) == sol
def test_factorable():
eq = f(x) + f(x)*f(x).diff(x)
sols = [Eq(f(x), C1 - x), Eq(f(x), 0)]
assert set(sols) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sols) == 2*[(True, 0)]
eq = f(x)*(f(x).diff(x)+f(x)*x+2)
sols = [Eq(f(x), (C1 - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2))
*exp(-x**2/2)), Eq(f(x), 0)]
assert set(sols) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sols) == 2*[(True, 0)]
eq = (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + x*f(x))
sols = [Eq(f(x), C1*airyai(-x) + C2*airybi(-x)),
Eq(f(x), C1*exp(-x**3/3))]
assert set(sols) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sols[1]) == (True, 0)
eq = (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + f(x))
sols = [Eq(f(x), C1*exp(-x**3/3)), Eq(f(x), C1*sin(x) + C2*cos(x))]
assert set(sols) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sols) == 2*[(True, 0)]
eq = (f(x).diff(x)**2-1)*(f(x).diff(x)**2-4)
sols = [Eq(f(x), C1 - x), Eq(f(x), C1 + x), Eq(f(x), C1 + 2*x), Eq(f(x), C1 - 2*x)]
assert set(sols) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sols) == 4*[(True, 0)]
eq = (f(x).diff(x, 2)-exp(f(x)))*f(x).diff(x)
sol = Eq(f(x), C1)
assert sol == dsolve(eq, f(x), hint='factorable')
assert checkodesol(eq, sol) == (True, 0)
eq = (f(x).diff(x)**2-1)*(f(x)*f(x).diff(x)-1)
sol = [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),
Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)]
assert set(sol) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sol) == 4*[(True, 0)]
eq = Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1
sol = [Eq(f(x), C1 - x), Eq(f(x), C1 + x)]
assert set(sol) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
eq = f(x)**2*Derivative(f(x), x)**6 - 2*f(x)**2*Derivative(f(x),
x)**4 + f(x)**2*Derivative(f(x), x)**2 - 2*f(x)*Derivative(f(x),
x)**5 + 4*f(x)*Derivative(f(x), x)**3 - 2*f(x)*Derivative(f(x),
x) + Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1
sol = [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),
Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)]
assert set(sol) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sol) == 4*[(True, 0)]
eq = (f(x).diff(x, 2)-exp(f(x)))*(f(x).diff(x, 2)+exp(f(x)))
raises(NotImplementedError, lambda: dsolve(eq, hint = 'factorable'))
eq = x**4*f(x)**2 + 2*x**4*f(x)*Derivative(f(x), (x, 2)) + x**4*Derivative(f(x),
(x, 2))**2 + 2*x**3*f(x)*Derivative(f(x), x) + 2*x**3*Derivative(f(x),
x)*Derivative(f(x), (x, 2)) - 7*x**2*f(x)**2 - 7*x**2*f(x)*Derivative(f(x),
(x, 2)) + x**2*Derivative(f(x), x)**2 - 7*x*f(x)*Derivative(f(x), x) + 12*f(x)**2
sol = [Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)), Eq(f(x), C1*besselj(sqrt(3),
x) + C2*bessely(sqrt(3), x))]
assert set(sol) == set(dsolve(eq, f(x), hint='factorable'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
def test_issue_17322():
eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x))
sol = [Eq(f(x), C1*exp(-x)), Eq(f(x), C1*exp(x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
eq = f(x).diff(x)*(f(x).diff(x)+f(x))
sol = [Eq(f(x), C1), Eq(f(x), C1*exp(-x))]
assert set(sol) == set(dsolve(eq, hint='lie_group'))
assert checkodesol(eq, sol) == 2*[(True, 0)]
|
703b0e4086b2b00782bb3e379e1eec6a50fc93417ce46e6a1cb2ab8c87535299 | from sympy import Eq, factorial, Function, Lambda, rf, S, sqrt, symbols, I, \
expand_func, binomial, gamma, Rational
from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio
from sympy.utilities.pytest import raises, slow
from sympy.core.compatibility import range
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) == C1*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 in [
C1*((-2*n + 3)/(n**2 - 1))/3,
(S.Half)*(C1*(-3 + 2*n)/(-1 + n**2)),
(S.Half)*(C1*( 3 - 2*n)/( 1 - n**2)),
(S.Half)*(C2*(-3 + 2*n)/(-1 + n**2)),
(S.Half)*(C2*( 3 - 2*n)/( 1 - n**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) == None
assert rsolve_hyper([-n - 1, -1, 1], 0, n) == None
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) is 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):
# assert rsolve_hyper(c, q, n) == p
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)**n*b + a)
f = (-16*n**2 + 32*n - 12)*y(n - 1) + (4*n**2 - 12*n + 9)*y(n)
assert expand_func(rsolve(f, y(n), \
{y(1): binomial(2*n + 1, 3)}).rewrite(gamma)).simplify() == \
2**(2*n)*n*(2*n - 1)*(4*n**2 - 1)/12
assert (rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n)) -
(C0*((sqrt(-a**2 + 1) - 1)/a)**n +
C1*((-sqrt(-a**2 + 1) - 1)/a)**n)).simplify() == 0
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)
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}))
def test_issue_6844():
f = y(n + 2) - y(n + 1) + y(n)/4
assert rsolve(f, y(n)) == 2**(-n)*(C0 + C1*n)
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2*2**(-n)*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
|
b541887a12d92c0575b67b7e7eed3073a174067e47eabe9c6a0dbcf4875235a1 | from sympy import sqrt, pi, E, exp, Rational
from sympy.core import S, Symbol, symbols, I
from sympy.core.compatibility import range
from sympy.discrete.convolutions import (
convolution, convolution_fft, convolution_ntt, convolution_fwht,
convolution_subset, covering_product, intersecting_product)
from sympy.utilities.pytest import raises
from sympy.abc import x, y
def test_convolution():
# fft
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
b = [9, 5, 5, 4, 3, 2]
c = [3, 5, 3, 7, 8]
d = [1422, 6572, 3213, 5552]
assert convolution(a, b) == convolution_fft(a, b)
assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9)
assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7)
assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3)
# prime moduli of the form (m*2**k + 1), sequence length
# should be a divisor of 2**k
p = 7*17*2**23 + 1
q = 19*2**10 + 1
# ntt
assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q)
assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p)
assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p)
raises(TypeError, lambda: convolution(b, d, dps=5, prime=q))
raises(TypeError, lambda: convolution(b, d, dps=6, prime=q))
# fwht
assert convolution(a, b, dyadic=True) == convolution_fwht(a, b)
assert convolution(a, b, dyadic=False) == convolution(a, b)
raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True))
raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True))
raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True))
raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True))
# subset
assert convolution(a, b, subset=True) == convolution_subset(a, b) == \
convolution(a, b, subset=True, dyadic=False) == \
convolution(a, b, subset=True)
assert convolution(a, b, subset=False) == convolution(a, b)
raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True))
raises(TypeError, lambda: convolution(c, d, subset=True, dps=6))
raises(TypeError, lambda: convolution(a, c, subset=True, prime=q))
def test_cyclic_convolution():
# fft
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
b = [9, 5, 5, 4, 3, 2]
assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
convolution([1, 2, 3], [4, 5, 6])
assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]
a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)]
b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)]
assert convolution(a, b, cycle=0) == \
convolution(a, b, cycle=len(a) + len(b) - 1)
assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340),
Rational(11125, 4032), Rational(3653, 1080)]
assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24),
Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)]
assert convolution(a, b, cycle=9) == \
convolution(a, b, cycle=0) + [S.Zero]
# ntt
a = [2313, 5323532, S(3232), 42142, 42242421]
b = [S(33456), 56757, 45754, 432423]
assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
convolution(a, b, prime=19*2**10 + 1)
assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
15534, 3517]
assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
15534, 3517, 16314, 13688]
assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
convolution(a, b, prime=19*2**10 + 1) + [0]
# fwht
u, v, w, x, y = symbols('u v w x y')
p, q, r, s, t = symbols('p q r s t')
c = [u, v, w, x, y]
d = [p, q, r, s, t]
assert convolution(a, b, dyadic=True, cycle=3) == \
[2499522285783, 19861417974796, 4702176579021]
assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
2114320852171, 20571217906407, 246166418903, 1413262436976]
assert convolution(c, d, dyadic=True, cycle=4) == \
[p*u + p*y + q*v + r*w + s*x + t*u + t*y,
p*v + q*u + q*y + r*x + s*w + t*v,
p*w + q*x + r*u + r*y + s*v + t*w,
p*x + q*w + r*v + s*u + s*y + t*x]
assert convolution(c, d, dyadic=True, cycle=6) == \
[p*u + q*v + r*w + r*y + s*x + t*w + t*y,
p*v + q*u + r*x + s*w + s*y + t*x,
p*w + q*x + r*u + s*v,
p*x + q*w + r*v + s*u,
p*y + t*u,
q*y + t*v]
# subset
assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
178235365533, 213958794, 246166418903, 1413262436976,
2397553088697, 1932759730434]
assert convolution(a[1:], b, subset=True, cycle=4) == \
[178104086592, 302255835516, 244982785880, 3717819845434]
assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]
assert convolution(c, d, subset=True, cycle=3) == \
[p*u + p*x + q*w + r*v + r*y + s*u + t*w,
p*v + p*y + q*u + s*y + t*u + t*x,
p*w + q*y + r*u + t*v]
assert convolution(c, d, subset=True, cycle=5) == \
[p*u + q*y + t*v,
p*v + q*u + r*y + t*w,
p*w + r*u + s*y + t*x,
p*x + q*w + r*v + s*u,
p*y + t*u]
raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1))
def test_convolution_fft():
assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3))
assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7]
assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I]
assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + Rational(3, 5)*I], [Rational(2, 5) + Rational(4, 7)*I]) == \
[Rational(-26, 35) + I*Rational(48, 35), Rational(-38, 35) + I*Rational(116, 35), Rational(58, 35) + I*Rational(542, 175)]
assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \
[Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)]
assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \
[Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)]
assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \
[sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6),
sqrt(2)/pi + 1, sqrt(2)*exp(-1)]
assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \
[12350041, 190918524, 374911166, 2362431729]
assert convolution_fft([312313, 31278232], [32139631, 319631]) == \
[10037624576503, 1005370659728895, 9997492572392]
raises(TypeError, lambda: convolution_fft(x, y))
raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
def test_convolution_ntt():
# prime moduli of the form (m*2**k + 1), sequence length
# should be a divisor of 2**k
p = 7*17*2**23 + 1
q = 19*2**10 + 1
r = 2*500000003 + 1 # only for sequences of length 1 or 2
s = 2*3*5*7 # composite modulus
assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r))
assert convolution_ntt([2], [3], r) == [6]
assert convolution_ntt([2, 3], [4], r) == [8, 12]
assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619,
459741727, 79180879, 831885249, 381344700, 369993322]
assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \
[8158, 3065, 3682, 7090, 1239, 2232, 3744]
assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \
convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q)
assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \
convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q)
raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r))
raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q))
raises(TypeError, lambda: convolution_ntt(x, y, p))
def test_convolution_fwht():
assert convolution_fwht([], []) == []
assert convolution_fwht([], [1]) == []
assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27]
assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \
[Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)]
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I]
b = [94, 51, 53, 45, 31, 27, 13]
c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8]
assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I,
45*sqrt(3) + Rational(5848, 15) + 135*I,
94*sqrt(3) + Rational(1257, 5) + 65*I,
51*sqrt(3) + Rational(3974, 15),
13*sqrt(3) + 452 + 470*I,
Rational(4513, 15) + 255*I,
31*sqrt(3) + Rational(1314, 5) + 265*I,
27*sqrt(3) + Rational(3676, 15) + 225*I]
assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I,
Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I,
Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I]
assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*Rational(293, 5), -1 + I*Rational(204, 5),
Rational(133, 15) + I*Rational(35, 6), Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0]
u, v, w, x, y, z = symbols('u v w x y z')
assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x]
assert convolution_fwht([u, v, w], [x, y]) == \
[u*x + v*y, u*y + v*x, w*x, w*y]
assert convolution_fwht([u, v, w], [x, y, z]) == \
[u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y]
raises(TypeError, lambda: convolution_fwht(x, y))
raises(TypeError, lambda: convolution_fwht(x*y, u + v))
def test_convolution_subset():
assert convolution_subset([], []) == []
assert convolution_subset([], [Rational(1, 3)]) == []
assert convolution_subset([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)]
a = [1, Rational(5, 3), sqrt(3), 4 + 5*I]
b = [64, 71, 55, 47, 33, 29, 15]
c = [3 + I*Rational(2, 3), 5 + 7*I, 7, Rational(7, 5), 9]
assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3),
71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84,
15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I]
assert convolution_subset(b, c) == [192 + I*Rational(128, 3), 533 + I*Rational(1486, 3),
613 + I*Rational(110, 3), Rational(5013, 5) + I*Rational(1249, 3),
675 + 22*I, 891 + I*Rational(751, 3),
771 + 10*I, Rational(3736, 5) + 105*I]
assert convolution_subset(a, c) == convolution_subset(c, a)
assert convolution_subset(a[:2], b) == \
[64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25]
assert convolution_subset(a[:2], c) == \
[3 + I*Rational(2, 3), 10 + I*Rational(73, 9), 7, Rational(196, 15), 9, 15, 0, 0]
u, v, w, x, y, z = symbols('u v w x y z')
assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y]
assert convolution_subset([u, v, w, x], [y, z]) == \
[u*y, u*z + v*y, w*y, w*z + x*y]
assert convolution_subset([u, v], [x, y, z]) == \
convolution_subset([x, y, z], [u, v])
raises(TypeError, lambda: convolution_subset(x, z))
raises(TypeError, lambda: convolution_subset(Rational(7, 3), u))
def test_covering_product():
assert covering_product([], []) == []
assert covering_product([], [Rational(1, 3)]) == []
assert covering_product([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)]
a = [1, Rational(5, 8), sqrt(7), 4 + 9*I]
b = [66, 81, 95, 49, 37, 89, 17]
c = [3 + I*Rational(2, 3), 51 + 72*I, 7, Rational(7, 15), 91]
assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7),
130*sqrt(7) + 1303 + 2619*I, 37,
Rational(671, 4), 17 + 54*sqrt(7),
89*sqrt(7) + Rational(4661, 8) + 1287*I]
assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I,
1412 + I*Rational(190, 3), Rational(42684, 5) + I*Rational(31202, 3),
9484 + I*Rational(74, 3), 22163 + I*Rational(27394, 3),
10621 + I*Rational(34, 3), Rational(90236, 15) + 1224*I]
assert covering_product(a, c) == covering_product(c, a)
assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I,
1412 + I*Rational(190, 3), Rational(42684, 5) + I*Rational(31202, 3),
111 + I*Rational(74, 3), 6693 + I*Rational(27394, 3),
429 + I*Rational(34, 3), Rational(23351, 15) + 1224*I]
assert covering_product(a, c[:-1]) == [3 + I*Rational(2, 3),
Rational(339, 4) + I*Rational(1409, 12), 7 + 10*sqrt(7) + 2*sqrt(7)*I/3,
-403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*Rational(12658, 15)]
u, v, w, x, y, z = symbols('u v w x y z')
assert covering_product([u, v, w], [x, y]) == \
[u*x, u*y + v*x + v*y, w*x, w*y]
assert covering_product([u, v, w, x], [y, z]) == \
[u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z]
assert covering_product([u, v], [x, y, z]) == \
covering_product([x, y, z], [u, v])
raises(TypeError, lambda: covering_product(x, z))
raises(TypeError, lambda: covering_product(Rational(7, 3), u))
def test_intersecting_product():
assert intersecting_product([], []) == []
assert intersecting_product([], [Rational(1, 3)]) == []
assert intersecting_product([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)]
a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I]
b = [67, 51, 65, 48, 36, 79, 27]
c = [3 + I*Rational(2, 5), 5 + 9*I, 7, Rational(7, 19), 13]
assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I,
178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I,
192 + 336*I, 0, 0, 0, 0]
assert intersecting_product(b, c) == [Rational(128553, 19) + I*Rational(9521, 5),
Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0]
assert intersecting_product(a, c) == intersecting_product(c, a)
assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*Rational(8622, 5),
Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0]
assert intersecting_product(a, c[:-2]) == \
[Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*Rational(3021, 40),
-43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0]
u, v, w, x, y, z = symbols('u v w x y z')
assert intersecting_product([u, v, w], [x, y]) == \
[u*x + u*y + v*x + w*x + w*y, v*y, 0, 0]
assert intersecting_product([u, v, w, x], [y, z]) == \
[u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0]
assert intersecting_product([u, v], [x, y, z]) == \
intersecting_product([x, y, z], [u, v])
raises(TypeError, lambda: intersecting_product(x, z))
raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
|
5755f4ae58f56f91300af2a41bb43863957ac19f3c79a22656b170b65f8a68c0 | from sympy import Rational, fibonacci
from sympy.core import S, symbols
from sympy.core.compatibility import range
from sympy.utilities.pytest import raises
from sympy.discrete.recurrences import linrec
def test_linrec():
assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946
assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040
assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384
assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \
56889923441670659718376223533331214868804815612050381493741233489928913241
assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \
702633573874937994980598979769135096432444135301118916539
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4)
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5)
assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n)
for n in range(95, 115))
assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1)
for n in range(595, 615))
a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)]
b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6]
x, y, z = symbols('x y z')
assert linrec(coeffs=a[:5], init=b[:4], n=80) == \
Rational(1726244235456268979436592226626304376013002142588105090705187189,
1960143456748895967474334873705475211264)
assert linrec(coeffs=a[:4], init=b[:4], n=50) == \
Rational(368949940033050147080268092104304441, 504857282956046106624)
assert linrec(coeffs=a[3:], init=b[:3], n=35) == \
Rational(97409272177295731943657945116791049305244422833125109,
814315512679031689453125)
assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \
Rational(26777668739896791448594650497024, 48084516708184142230517578125)
raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1))
raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000))
raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000))
raises(TypeError, lambda: linrec(x, b, n=10000))
raises(TypeError, lambda: linrec(a, y, n=10000))
assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \
x**2 + x*y + x*z + y + z
assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \
269542*x + 664575*y + 578949*z
assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \
58516436*x + 56372788*y
assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \
11477135884896*x + 25999077948732*y + 41975630244216*z
assert linrec(coeffs=[], init=[1, 1], n=20) == 0
|
a5a8f8b7ba0e3568e59f179997d6e8b7ac1cf0ec79a8702e40a5d896d1d7043c | from sympy import sqrt
from sympy.core import S, Symbol, symbols, I, Rational
from sympy.core.compatibility import range
from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht,
mobius_transform, inverse_mobius_transform)
from sympy.utilities.pytest import raises
def test_fft_ifft():
assert all(tf(ls) == ls for tf in (fft, ifft)
for ls in ([], [Rational(5, 3)]))
ls = list(range(6))
fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I,
-4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3,
-4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I,
2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2]
assert fft(ls) == fls
assert ifft(fls) == ls + [S.Zero]*2
ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4]
assert ifft(ls) == ifls
assert fft(ifls) == ls + [S.Zero]
x = Symbol('x', real=True)
raises(TypeError, lambda: fft(x))
raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3]))
def test_ntt_intt():
# prime moduli of the form (m*2**k + 1), sequence length
# should be a divisor of 2**k
p = 7*17*2**23 + 1
q = 2*500000003 + 1 # only for sequences of length 1 or 2
r = 2*3*5*7 # composite modulus
assert all(tf(ls, p) == ls for tf in (ntt, intt)
for ls in ([], [5]))
ls = list(range(6))
nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224,
259751156, 12232587]
assert ntt(ls, p) == nls
assert intt(nls, p) == ls + [0]*2
ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
x = Symbol('x', integer=True)
raises(TypeError, lambda: ntt(x, p))
raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p))
raises(ValueError, lambda: intt(ls, p))
raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p))
raises(ValueError, lambda: ntt([3, 5, 6], q))
raises(ValueError, lambda: ntt([4, 5, 7], r))
raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p))
def test_fwht_ifwht():
assert all(tf(ls) == ls for tf in (fwht, ifwht) \
for ls in ([], [Rational(7, 4)]))
ls = [213, 321, 43235, 5325, 312, 53]
fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277]
assert fwht(ls) == fls
assert ifwht(fls) == ls + [S.Zero]*2
ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)]
ifls = [Rational(533, 672) + I*Rational(3, 2), Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I,
Rational(155, 672) + I*Rational(3, 2), Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I]
assert ifwht(ls) == ifls
assert fwht(ifls) == ls + [S.Zero]*3
x, y = symbols('x y')
raises(TypeError, lambda: fwht(x))
ls = [x, 2*x, 3*x**2, 4*x**3]
ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4),
-x**3 + 3*x**2/4 - x/4,
-x**3 - 3*x**2/4 + x*Rational(3, 4),
x**3 - 3*x**2/4 - x/4]
assert ifwht(ls) == ifls
assert fwht(ifls) == ls
ls = [x, y, x**2, y**2, x*y]
fls = [x**2 + x*y + x + y**2 + y,
x**2 + x*y + x - y**2 - y,
-x**2 + x*y + x - y**2 + y,
-x**2 + x*y + x + y**2 - y,
x**2 - x*y + x + y**2 + y,
x**2 - x*y + x - y**2 - y,
-x**2 - x*y + x - y**2 + y,
-x**2 - x*y + x + y**2 - y]
assert fwht(ls) == fls
assert ifwht(fls) == ls + [S.Zero]*3
ls = list(range(6))
assert fwht(ls) == [x*8 for x in ifwht(ls)]
def test_mobius_transform():
assert all(tf(ls, subset=subset) == ls
for ls in ([], [Rational(7, 4)]) for subset in (True, False)
for tf in (mobius_transform, inverse_mobius_transform))
w, x, y, z = symbols('w x y z')
assert mobius_transform([x, y]) == [x, x + y]
assert inverse_mobius_transform([x, x + y]) == [x, y]
assert mobius_transform([x, y], subset=False) == [x + y, y]
assert inverse_mobius_transform([x + y, y], subset=False) == [x, y]
assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z]
assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \
[w, x, y, z]
assert mobius_transform([w, x, y, z], subset=False) == \
[w + x + y + z, x + z, y + z, z]
assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \
[w, x, y, z]
ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I]
mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168),
Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I,
Rational(2153, 168) + 7*I]
assert mobius_transform(ls) == mls
assert inverse_mobius_transform(mls) == ls + [S.Zero]*3
mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0]
assert mobius_transform(ls, subset=False) == mls
assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3
ls = ls[:-1]
mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)]
assert mobius_transform(ls) == mls
assert inverse_mobius_transform(mls) == ls
mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9]
assert mobius_transform(ls, subset=False) == mls
assert inverse_mobius_transform(mls, subset=False) == ls
raises(TypeError, lambda: mobius_transform(x, subset=True))
raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
|
27969cfc8234619e807cdfb69747d0c747453186f348408d88a0345b4af7b8b7 | from sympy.liealgebras.cartan_type import CartanType
from sympy.core.compatibility import range
from sympy.matrices import Matrix
from sympy.core.backend import S
def test_type_F():
c = CartanType("F4")
m = Matrix(4, 4, [2, -1, 0, 0, -1, 2, -2, 0, 0, -1, 2, -1, 0, 0, -1, 2])
assert c.cartan_matrix() == m
assert c.dimension() == 4
assert c.simple_root(1) == [1, -1, 0, 0]
assert c.simple_root(2) == [0, 1, -1, 0]
assert c.simple_root(3) == [0, 0, 0, 1]
assert c.simple_root(4) == [-S.Half, -S.Half, -S.Half, -S.Half]
assert c.roots() == 48
assert c.basis() == 52
diag = "0---0=>=0---0\n" + " ".join(str(i) for i in range(1, 5))
assert c.dynkin_diagram() == diag
assert c.positive_roots() == {1: [1, -1, 0, 0], 2: [1, 1, 0, 0], 3: [1, 0, -1, 0],
4: [1, 0, 1, 0], 5: [1, 0, 0, -1], 6: [1, 0, 0, 1], 7: [0, 1, -1, 0],
8: [0, 1, 1, 0], 9: [0, 1, 0, -1], 10: [0, 1, 0, 1], 11: [0, 0, 1, -1],
12: [0, 0, 1, 1], 13: [1, 0, 0, 0], 14: [0, 1, 0, 0], 15: [0, 0, 1, 0],
16: [0, 0, 0, 1], 17: [S.Half, S.Half, S.Half, S.Half], 18: [S.Half, -S.Half, S.Half, S.Half],
19: [S.Half, S.Half, -S.Half, S.Half], 20: [S.Half, S.Half, S.Half, -S.Half], 21: [S.Half, S.Half, -S.Half, -S.Half],
22: [S.Half, -S.Half, S.Half, -S.Half], 23: [S.Half, -S.Half, -S.Half, S.Half], 24: [S.Half, -S.Half, -S.Half, -S.Half]}
|
e430b5fe4e73641ddcb6cd3ff7960af9964caf37529d812c0f183533afd69b97 | from sympy import Symbol, exp, log, oo, S, I, sqrt, Rational
from sympy.calculus.singularities import (
singularities,
is_increasing,
is_strictly_increasing,
is_decreasing,
is_strictly_decreasing,
is_monotonic
)
from sympy.sets import Interval, FiniteSet
from sympy.utilities.pytest import XFAIL, raises
from sympy.abc import x, y
def test_singularities():
x = Symbol('x')
assert singularities(x**2, x) == S.EmptySet
assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1)
assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I)
assert singularities(x/(x**3 + 1), x) == \
FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2)
assert singularities(1/(y**2 + 2*I*y + 1), y) == \
FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I)
x = Symbol('x', real=True)
assert singularities(1/(x**2 + 1), x) == S.EmptySet
@XFAIL
def test_singularities_non_rational():
x = Symbol('x', real=True)
assert singularities(exp(1/x), x) == FiniteSet(0)
assert singularities(log((x - 2)**2), x) == FiniteSet(2)
def test_is_increasing():
"""Test whether is_increasing returns correct value."""
a = Symbol('a', negative=True)
assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
assert is_increasing(-x**2, Interval(-oo, 0))
assert not is_increasing(-x**2, Interval(0, oo))
assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
assert is_increasing(x**2 + y, Interval(1, oo), x)
assert is_increasing(-x**2*a, Interval(1, oo), x)
assert is_increasing(1)
def test_is_strictly_increasing():
"""Test whether is_strictly_increasing returns correct value."""
assert is_strictly_increasing(
4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
assert is_strictly_increasing(
4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
assert not is_strictly_increasing(
4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
assert not is_strictly_increasing(-x**2, Interval(0, oo))
assert not is_strictly_decreasing(1)
def test_is_decreasing():
"""Test whether is_decreasing returns correct value."""
b = Symbol('b', positive=True)
assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
assert not is_decreasing(-x**2, Interval(-oo, 0))
assert not is_decreasing(-x**2*b, Interval(-oo, 0), x)
def test_is_strictly_decreasing():
"""Test whether is_strictly_decreasing returns correct value."""
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
assert not is_strictly_decreasing(
1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
assert not is_strictly_decreasing(-x**2, Interval(-oo, 0))
assert not is_strictly_decreasing(1)
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
def test_is_monotonic():
"""Test whether is_monotonic returns correct value."""
assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
assert not is_monotonic(-x**2, S.Reals)
assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
|
83bf420e3ee1845ccd7ab98c81d2992138e4092fedc3034849bfd8875c364aa1 | from sympy import (Symbol, S, exp, log, sqrt, oo, E, zoo, pi, tan, sin, cos,
cot, sec, csc, Abs, symbols, I, re, simplify,
expint, Rational)
from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,
periodicity, lcim, AccumBounds, is_convex,
stationary_points, minimum, maximum)
from sympy.core import Add, Mul, Pow
from sympy.sets.sets import (Interval, FiniteSet, EmptySet, Complement,
Union)
from sympy.utilities.pytest import raises
from sympy.abc import x
a = Symbol('a', real=True)
def test_function_range():
x, y, a, b = symbols('x y a b')
assert function_range(sin(x), x, Interval(-pi/2, pi/2)
) == Interval(-1, 1)
assert function_range(sin(x), x, Interval(0, pi)
) == Interval(0, 1)
assert function_range(tan(x), x, Interval(0, pi)
) == Interval(-oo, oo)
assert function_range(tan(x), x, Interval(pi/2, pi)
) == Interval(-oo, 0)
assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)
) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))
assert function_range(1/(x**2), x, Interval(-1, 1)
) == Interval(1, oo)
assert function_range(exp(x), x, Interval(-1, 1)
) == Interval(exp(-1), exp(1))
assert function_range(log(x) - x, x, S.Reals
) == Interval(-oo, -1)
assert function_range(sqrt(3*x - 1), x, Interval(0, 2)
) == Interval(0, sqrt(5))
assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals
) == FiniteSet(0)
assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals
) == FiniteSet(y)
assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))
) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))
assert function_range(cos(x), x, Interval(-oo, -4)
) == Interval(-1, 1)
assert function_range(cos(x), x, S.EmptySet) == S.EmptySet
raises(NotImplementedError, lambda : function_range(
exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))
raises(NotImplementedError, lambda : function_range(
sin(x) + x, x, S.Reals)) # issue 13273
raises(NotImplementedError, lambda : function_range(
log(x), x, S.Integers))
raises(NotImplementedError, lambda : function_range(
sin(x)/2, x, S.Naturals))
def test_continuous_domain():
x = Symbol('x')
assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)
assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \
Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),
Interval(pi*Rational(3, 2), 2*pi, True, False))
assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \
Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))
assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \
Interval(Rational(1, 4), oo, True, True)
assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)
assert continuous_domain(1/x - 2, x, S.Reals) == \
Union(Interval.open(-oo, 0), Interval.open(0, oo))
assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \
Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))
def test_not_empty_in():
assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \
Interval(S.Half, 2, True, False)
assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \
Union(Interval(-sqrt(2), -1), Interval(1, 2))
assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \
Union(Interval(-sqrt(17)/2 - S.Half, -2),
Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))
assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
Interval(-oo, oo)
assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
Interval(S(3)/2, 2)
assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(-1, 1))
assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),
Interval(4, 5))), x) == \
Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),
Interval(1, 3, True, True), Interval(4, 5))
assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet
assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \
Union(Interval(-2, -1, True, False), Interval(2, oo))
raises(ValueError, lambda: not_empty_in(x))
raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))
raises(NotImplementedError,
lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))
def test_periodicity():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z', real=True)
assert periodicity(sin(2*x), x) == pi
assert periodicity((-2)*tan(4*x), x) == pi/4
assert periodicity(sin(x)**2, x) == 2*pi
assert periodicity(3**tan(3*x), x) == pi/3
assert periodicity(tan(x)*cos(x), x) == 2*pi
assert periodicity(sin(x)**(tan(x)), x) == 2*pi
assert periodicity(tan(x)*sec(x), x) == 2*pi
assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
assert periodicity(tan(x) + cot(x), x) == pi
assert periodicity(sin(x) - cos(2*x), x) == 2*pi
assert periodicity(sin(x) - 1, x) == 2*pi
assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
assert periodicity(exp(sin(x)), x) == 2*pi
assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
assert periodicity(tan(sin(2*x)), x) == pi
assert periodicity(2*tan(x)**2, x) == pi
assert periodicity(sin(x%4), x) == 4
assert periodicity(sin(x)%4, x) == 2*pi
assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
assert periodicity((x**2+1) % x, x) is None
assert periodicity(sin(re(x)), x) == 2*pi
assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
assert periodicity(tan(x), y) is S.Zero
assert periodicity(sin(x) + I*cos(x), x) == 2*pi
assert periodicity(x - sin(2*y), y) == pi
assert periodicity(exp(x), x) is None
assert periodicity(exp(I*x), x) == 2*pi
assert periodicity(exp(I*z), z) == 2*pi
assert periodicity(exp(z), z) is None
assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi
assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi
assert periodicity(exp(sin(z)), z) == 2*pi
assert periodicity(exp(2*I*z), z) == pi
assert periodicity(exp(z + I*sin(z)), z) is None
assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi
assert periodicity(log(x), x) is None
assert periodicity(exp(x)**sin(x), x) is None
assert periodicity(sin(x)**y, y) is None
assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
assert all(periodicity(Abs(f(x)), x) == pi for f in (
cos, sin, sec, csc, tan, cot))
assert periodicity(Abs(sin(tan(x))), x) == pi
assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
assert periodicity(sin(x) > S.Half, x) is 2*pi
assert periodicity(x > 2, x) is None
assert periodicity(x**3 - x**2 + 1, x) is None
assert periodicity(Abs(x), x) is None
assert periodicity(Abs(x**2 - 1), x) is None
assert periodicity((x**2 + 4)%2, x) is None
assert periodicity((E**x)%3, x) is None
assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
def test_periodicity_check():
x = Symbol('x')
y = Symbol('y')
assert periodicity(tan(x), x, check=True) == pi
assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi
assert periodicity(sec(x), x) == 2*pi
assert periodicity(sin(x*y), x) == 2*pi/abs(y)
assert periodicity(Abs(sec(sec(x))), x) == pi
def test_lcim():
from sympy import pi
assert lcim([S.Half, S(2), S(3)]) == 6
assert lcim([pi/2, pi/4, pi]) == pi
assert lcim([2*pi, pi/2]) == 2*pi
assert lcim([S.One, 2*pi]) is None
assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E
def test_is_convex():
assert is_convex(1/x, x, domain=Interval(0, oo)) == True
assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False
assert is_convex(x**2, x, domain=Interval(0, oo)) == True
assert is_convex(log(x), x) == False
raises(NotImplementedError, lambda: is_convex(log(x), x, a))
def test_stationary_points():
x, y = symbols('x y')
assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
) == {-pi/2, pi/2}
assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
) == EmptySet()
assert stationary_points(tan(x), x,
) == EmptySet()
assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
) == {pi/4, pi*Rational(3, 4)}
assert stationary_points(sec(x), x, Interval(0, pi)
) == {0, pi}
assert stationary_points((x+3)*(x-2), x
) == FiniteSet(Rational(-1, 2))
assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
) == EmptySet()
assert stationary_points((x**2+3)/(x-2), x
) == {2 - sqrt(7), 2 + sqrt(7)}
assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
) == {2 + sqrt(7)}
assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
) == FiniteSet(-2, 0, Rational(5, 4))
assert stationary_points(exp(x), x
) == EmptySet()
assert stationary_points(log(x) - x, x, S.Reals
) == {1}
assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) == {0, -pi, pi}
assert stationary_points(y, x, S.Reals
) == S.Reals
assert stationary_points(y, x, S.EmptySet) == S.EmptySet
def test_maximum():
x, y = symbols('x y')
assert maximum(sin(x), x) is S.One
assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
assert maximum(tan(x), x) is oo
assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
) == sqrt(2)/4
assert maximum((x+3)*(x-2), x) is oo
assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
assert simplify(maximum(-x**4-x**3+x**2+10, x)
) == 41*sqrt(41)/512 + Rational(5419, 512)
assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) is S.One
assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
assert maximum(y, x, S.Reals) == y
raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
raises(ValueError, lambda : maximum(sin(x), sin(x)))
raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
raises(ValueError, lambda : maximum(sin(x), S.One))
def test_minimum():
x, y = symbols('x y')
assert minimum(sin(x), x) is S.NegativeOne
assert minimum(sin(x), x, Interval(1, 4)) == sin(4)
assert minimum(tan(x), x) is -oo
assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne
assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)
assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
) == -sqrt(2)/4
assert minimum((x+3)*(x-2), x) == Rational(-25, 4)
assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)
assert minimum(x**4-x**3+x**2+10, x) == S(10)
assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)
assert minimum(log(x) - x, x, S.Reals) is -oo
assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) is S.NegativeOne
assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)
assert minimum(y, x, S.Reals) == y
raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))
raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))
raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))
raises(ValueError, lambda : minimum(sin(x), sin(x)))
raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))
raises(ValueError, lambda : minimum(sin(x), S.One))
def test_AccumBounds():
assert AccumBounds(1, 2).args == (1, 2)
assert AccumBounds(1, 2).delta is S.One
assert AccumBounds(1, 2).mid == Rational(3, 2)
assert AccumBounds(1, 3).is_real == True
assert AccumBounds(1, 1) is S.One
assert AccumBounds(1, 2) + 1 == AccumBounds(2, 3)
assert 1 + AccumBounds(1, 2) == AccumBounds(2, 3)
assert AccumBounds(1, 2) + AccumBounds(2, 3) == AccumBounds(3, 5)
assert -AccumBounds(1, 2) == AccumBounds(-2, -1)
assert AccumBounds(1, 2) - 1 == AccumBounds(0, 1)
assert 1 - AccumBounds(1, 2) == AccumBounds(-1, 0)
assert AccumBounds(2, 3) - AccumBounds(1, 2) == AccumBounds(0, 2)
assert x + AccumBounds(1, 2) == Add(AccumBounds(1, 2), x)
assert a + AccumBounds(1, 2) == AccumBounds(1 + a, 2 + a)
assert AccumBounds(1, 2) - x == Add(AccumBounds(1, 2), -x)
assert AccumBounds(-oo, 1) + oo == AccumBounds(-oo, oo)
assert AccumBounds(1, oo) + oo is oo
assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo)
assert (-oo - AccumBounds(-1, oo)) is -oo
assert AccumBounds(-oo, 1) - oo is -oo
assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo)
assert AccumBounds(-oo, 1) - (-oo) == AccumBounds(-oo, oo)
assert (oo - AccumBounds(1, oo)) == AccumBounds(-oo, oo)
assert (-oo - AccumBounds(1, oo)) is -oo
assert AccumBounds(1, 2)/2 == AccumBounds(S.Half, 1)
assert 2/AccumBounds(2, 3) == AccumBounds(Rational(2, 3), 1)
assert 1/AccumBounds(-1, 1) == AccumBounds(-oo, oo)
assert abs(AccumBounds(1, 2)) == AccumBounds(1, 2)
assert abs(AccumBounds(-2, -1)) == AccumBounds(1, 2)
assert abs(AccumBounds(-2, 1)) == AccumBounds(0, 2)
assert abs(AccumBounds(-1, 2)) == AccumBounds(0, 2)
c = Symbol('c')
raises(ValueError, lambda: AccumBounds(0, c))
raises(ValueError, lambda: AccumBounds(1, -1))
def test_AccumBounds_mul():
assert AccumBounds(1, 2)*2 == AccumBounds(2, 4)
assert 2*AccumBounds(1, 2) == AccumBounds(2, 4)
assert AccumBounds(1, 2)*AccumBounds(2, 3) == AccumBounds(2, 6)
assert AccumBounds(1, 2)*0 == 0
assert AccumBounds(1, oo)*0 == AccumBounds(0, oo)
assert AccumBounds(-oo, 1)*0 == AccumBounds(-oo, 0)
assert AccumBounds(-oo, oo)*0 == AccumBounds(-oo, oo)
assert AccumBounds(1, 2)*x == Mul(AccumBounds(1, 2), x, evaluate=False)
assert AccumBounds(0, 2)*oo == AccumBounds(0, oo)
assert AccumBounds(-2, 0)*oo == AccumBounds(-oo, 0)
assert AccumBounds(0, 2)*(-oo) == AccumBounds(-oo, 0)
assert AccumBounds(-2, 0)*(-oo) == AccumBounds(0, oo)
assert AccumBounds(-1, 1)*oo == AccumBounds(-oo, oo)
assert AccumBounds(-1, 1)*(-oo) == AccumBounds(-oo, oo)
assert AccumBounds(-oo, oo)*oo == AccumBounds(-oo, oo)
def test_AccumBounds_div():
assert AccumBounds(-1, 3)/AccumBounds(3, 4) == AccumBounds(Rational(-1, 3), 1)
assert AccumBounds(-2, 4)/AccumBounds(-3, 4) == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)/AccumBounds(-4, 0) == AccumBounds(S.Half, oo)
# these two tests can have a better answer
# after Union of AccumBounds is improved
assert AccumBounds(-3, -2)/AccumBounds(-2, 1) == AccumBounds(-oo, oo)
assert AccumBounds(2, 3)/AccumBounds(-2, 2) == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)/AccumBounds(0, 4) == AccumBounds(-oo, Rational(-1, 2))
assert AccumBounds(2, 4)/AccumBounds(-3, 0) == AccumBounds(-oo, Rational(-2, 3))
assert AccumBounds(2, 4)/AccumBounds(0, 3) == AccumBounds(Rational(2, 3), oo)
assert AccumBounds(0, 1)/AccumBounds(0, 1) == AccumBounds(0, oo)
assert AccumBounds(-1, 0)/AccumBounds(0, 1) == AccumBounds(-oo, 0)
assert AccumBounds(-1, 2)/AccumBounds(-2, 2) == AccumBounds(-oo, oo)
assert 1/AccumBounds(-1, 2) == AccumBounds(-oo, oo)
assert 1/AccumBounds(0, 2) == AccumBounds(S.Half, oo)
assert (-1)/AccumBounds(0, 2) == AccumBounds(-oo, Rational(-1, 2))
assert 1/AccumBounds(-oo, 0) == AccumBounds(-oo, 0)
assert 1/AccumBounds(-1, 0) == AccumBounds(-oo, -1)
assert (-2)/AccumBounds(-oo, 0) == AccumBounds(0, oo)
assert 1/AccumBounds(-oo, -1) == AccumBounds(-1, 0)
assert AccumBounds(1, 2)/a == Mul(AccumBounds(1, 2), 1/a, evaluate=False)
assert AccumBounds(1, 2)/0 == AccumBounds(1, 2)*zoo
assert AccumBounds(1, oo)/oo == AccumBounds(0, oo)
assert AccumBounds(1, oo)/(-oo) == AccumBounds(-oo, 0)
assert AccumBounds(-oo, -1)/oo == AccumBounds(-oo, 0)
assert AccumBounds(-oo, -1)/(-oo) == AccumBounds(0, oo)
assert AccumBounds(-oo, oo)/oo == AccumBounds(-oo, oo)
assert AccumBounds(-oo, oo)/(-oo) == AccumBounds(-oo, oo)
assert AccumBounds(-1, oo)/oo == AccumBounds(0, oo)
assert AccumBounds(-1, oo)/(-oo) == AccumBounds(-oo, 0)
assert AccumBounds(-oo, 1)/oo == AccumBounds(-oo, 0)
assert AccumBounds(-oo, 1)/(-oo) == AccumBounds(0, oo)
def test_AccumBounds_func():
assert (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) == AccumBounds(-1, 4)
assert exp(AccumBounds(0, 1)) == AccumBounds(1, E)
assert exp(AccumBounds(-oo, oo)) == AccumBounds(0, oo)
assert log(AccumBounds(3, 6)) == AccumBounds(log(3), log(6))
def test_AccumBounds_pow():
assert AccumBounds(0, 2)**2 == AccumBounds(0, 4)
assert AccumBounds(-1, 1)**2 == AccumBounds(0, 1)
assert AccumBounds(1, 2)**2 == AccumBounds(1, 4)
assert AccumBounds(-1, 2)**3 == AccumBounds(-1, 8)
assert AccumBounds(-1, 1)**0 == 1
assert AccumBounds(1, 2)**Rational(5, 2) == AccumBounds(1, 4*sqrt(2))
assert AccumBounds(-1, 2)**Rational(1, 3) == AccumBounds(-1, 2**Rational(1, 3))
assert AccumBounds(0, 2)**S.Half == AccumBounds(0, sqrt(2))
assert AccumBounds(-4, 2)**Rational(2, 3) == AccumBounds(0, 2*2**Rational(1, 3))
assert AccumBounds(-1, 5)**S.Half == AccumBounds(0, sqrt(5))
assert AccumBounds(-oo, 2)**S.Half == AccumBounds(0, sqrt(2))
assert AccumBounds(-2, 3)**Rational(-1, 4) == AccumBounds(0, oo)
assert AccumBounds(1, 5)**(-2) == AccumBounds(Rational(1, 25), 1)
assert AccumBounds(-1, 3)**(-2) == AccumBounds(0, oo)
assert AccumBounds(0, 2)**(-2) == AccumBounds(Rational(1, 4), oo)
assert AccumBounds(-1, 2)**(-3) == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)**(-3) == AccumBounds(Rational(-1, 8), Rational(-1, 27))
assert AccumBounds(-3, -2)**(-2) == AccumBounds(Rational(1, 9), Rational(1, 4))
assert AccumBounds(0, oo)**S.Half == AccumBounds(0, oo)
assert AccumBounds(-oo, -1)**Rational(1, 3) == AccumBounds(-oo, -1)
assert AccumBounds(-2, 3)**(Rational(-1, 3)) == AccumBounds(-oo, oo)
assert AccumBounds(-oo, 0)**(-2) == AccumBounds(0, oo)
assert AccumBounds(-2, 0)**(-2) == AccumBounds(Rational(1, 4), oo)
assert AccumBounds(Rational(1, 3), S.Half)**oo is S.Zero
assert AccumBounds(0, S.Half)**oo is S.Zero
assert AccumBounds(S.Half, 1)**oo == AccumBounds(0, oo)
assert AccumBounds(0, 1)**oo == AccumBounds(0, oo)
assert AccumBounds(2, 3)**oo is oo
assert AccumBounds(1, 2)**oo == AccumBounds(0, oo)
assert AccumBounds(S.Half, 3)**oo == AccumBounds(0, oo)
assert AccumBounds(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero
assert AccumBounds(-1, Rational(-1, 2))**oo == AccumBounds(-oo, oo)
assert AccumBounds(-3, -2)**oo == FiniteSet(-oo, oo)
assert AccumBounds(-2, -1)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-2, Rational(-1, 2))**oo == AccumBounds(-oo, oo)
assert AccumBounds(Rational(-1, 2), S.Half)**oo is S.Zero
assert AccumBounds(Rational(-1, 2), 1)**oo == AccumBounds(0, oo)
assert AccumBounds(Rational(-2, 3), 2)**oo == AccumBounds(0, oo)
assert AccumBounds(-1, 1)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-1, S.Half)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-1, 2)**oo == AccumBounds(-oo, oo)
assert AccumBounds(-2, S.Half)**oo == AccumBounds(-oo, oo)
assert AccumBounds(1, 2)**x == Pow(AccumBounds(1, 2), x, evaluate=False)
assert AccumBounds(2, 3)**(-oo) is S.Zero
assert AccumBounds(0, 2)**(-oo) == AccumBounds(0, oo)
assert AccumBounds(-1, 2)**(-oo) == AccumBounds(-oo, oo)
assert (tan(x)**sin(2*x)).subs(x, AccumBounds(0, pi/2)) == \
Pow(AccumBounds(-oo, oo), AccumBounds(0, 1), evaluate=False)
def test_comparison_AccumBounds():
assert (AccumBounds(1, 3) < 4) == S.true
assert (AccumBounds(1, 3) < -1) == S.false
assert (AccumBounds(1, 3) < 2).rel_op == '<'
assert (AccumBounds(1, 3) <= 2).rel_op == '<='
assert (AccumBounds(1, 3) > 4) == S.false
assert (AccumBounds(1, 3) > -1) == S.true
assert (AccumBounds(1, 3) > 2).rel_op == '>'
assert (AccumBounds(1, 3) >= 2).rel_op == '>='
assert (AccumBounds(1, 3) < AccumBounds(4, 6)) == S.true
assert (AccumBounds(1, 3) < AccumBounds(2, 4)).rel_op == '<'
assert (AccumBounds(1, 3) < AccumBounds(-2, 0)) == S.false
assert (AccumBounds(1, 3) <= AccumBounds(4, 6)) == S.true
assert (AccumBounds(1, 3) <= AccumBounds(-2, 0)) == S.false
assert (AccumBounds(1, 3) > AccumBounds(4, 6)) == S.false
assert (AccumBounds(1, 3) > AccumBounds(-2, 0)) == S.true
assert (AccumBounds(1, 3) >= AccumBounds(4, 6)) == S.false
assert (AccumBounds(1, 3) >= AccumBounds(-2, 0)) == S.true
# issue 13499
assert (cos(x) > 0).subs(x, oo) == (AccumBounds(-1, 1) > 0)
c = Symbol('c')
raises(TypeError, lambda: (AccumBounds(0, 1) < c))
raises(TypeError, lambda: (AccumBounds(0, 1) <= c))
raises(TypeError, lambda: (AccumBounds(0, 1) > c))
raises(TypeError, lambda: (AccumBounds(0, 1) >= c))
def test_contains_AccumBounds():
assert (1 in AccumBounds(1, 2)) == S.true
raises(TypeError, lambda: a in AccumBounds(1, 2))
assert 0 in AccumBounds(-1, 0)
raises(TypeError, lambda:
(cos(1)**2 + sin(1)**2 - 1) in AccumBounds(-1, 0))
assert (-oo in AccumBounds(1, oo)) == S.true
assert (oo in AccumBounds(-oo, 0)) == S.true
# issue 13159
assert Mul(0, AccumBounds(-1, 1)) == Mul(AccumBounds(-1, 1), 0) == 0
import itertools
for perm in itertools.permutations([0, AccumBounds(-1, 1), x]):
assert Mul(*perm) == 0
def test_intersection_AccumBounds():
assert AccumBounds(0, 3).intersection(AccumBounds(1, 2)) == AccumBounds(1, 2)
assert AccumBounds(0, 3).intersection(AccumBounds(1, 4)) == AccumBounds(1, 3)
assert AccumBounds(0, 3).intersection(AccumBounds(-1, 2)) == AccumBounds(0, 2)
assert AccumBounds(0, 3).intersection(AccumBounds(-1, 4)) == AccumBounds(0, 3)
assert AccumBounds(0, 1).intersection(AccumBounds(2, 3)) == S.EmptySet
raises(TypeError, lambda: AccumBounds(0, 3).intersection(1))
def test_union_AccumBounds():
assert AccumBounds(0, 3).union(AccumBounds(1, 2)) == AccumBounds(0, 3)
assert AccumBounds(0, 3).union(AccumBounds(1, 4)) == AccumBounds(0, 4)
assert AccumBounds(0, 3).union(AccumBounds(-1, 2)) == AccumBounds(-1, 3)
assert AccumBounds(0, 3).union(AccumBounds(-1, 4)) == AccumBounds(-1, 4)
raises(TypeError, lambda: AccumBounds(0, 3).union(1))
def test_issue_16469():
x = Symbol("x", real=True)
f = abs(x)
assert function_range(f, x, S.Reals) == Interval(0, oo, False, True)
|
72980eac61fc469713d0302f681c6898864da6ded35a0c48cda91fc7e22ca2c7 | from itertools import product
from sympy import S, symbols, Function, exp, diff, Rational
from sympy.calculus.finite_diff import (
apply_finite_diff, differentiate_finite, finite_diff_weights,
as_finite_diff
)
from sympy.core.compatibility import range
from sympy.utilities.pytest import raises, warns_deprecated_sympy
def test_apply_finite_diff():
x, h = symbols('x h')
f = Function('f')
assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) -
(f(x+h)-f(x-h))/(2*h)).simplify() == 0
assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) -
(Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0
raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)]))
def test_finite_diff_weights():
d = finite_diff_weights(1, [5, 6, 7], 5)
assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)]
# Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0
# --------------------------------------------------------
xl = [0, 1, -1, 2, -2, 3, -3, 4, -4]
# d holds all coefficients
d = finite_diff_weights(4, xl, S.Zero)
# Zeroeth derivative
for i in range(5):
assert d[0][i] == [S.One] + [S.Zero]*8
# First derivative
assert d[1][0] == [S.Zero]*9
assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6
assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4
assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20),
Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2
assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5),
Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)]
# Second derivative
for i in range(2):
assert d[2][i] == [S.Zero]*9
assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6
assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4
assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20),
Rational(1, 90), Rational(1, 90)] + [S.Zero]*2
assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5),
Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)]
# Third derivative
for i in range(3):
assert d[3][i] == [S.Zero]*9
assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4
assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One,
Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2
assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120),
Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)]
# Fourth derivative
for i in range(4):
assert d[4][i] == [S.Zero]*9
assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4
assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2),
Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2
assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60),
Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)]
# Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0
# --------------------------------------------------------
xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))]
for i in range(1, 5)]
# d holds all coefficients
d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for
i in range(4)]
# Zeroth derivative
assert d[0][0][1] == [S.Half, S.Half]
assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)]
assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128),
Rational(-25, 256), Rational(3, 256)]
assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048),
Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)]
# First derivative
assert d[0][1][1] == [-S.One, S.One]
assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)]
assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64),
Rational(75, 64), Rational(-25, 384), Rational(3, 640)]
assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120),
Rational(245, 3072), Rational(-1225, 1024),
Rational(1225, 1024), Rational(-245, 3072),
Rational(49, 5120), Rational(-5, 7168)]
# Reasonably the rest of the table is also correct... (testing of that
# deemed excessive at the moment)
raises(ValueError, lambda: finite_diff_weights(-1, [1, 2]))
raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2]))
x = symbols('x')
raises(ValueError, lambda: finite_diff_weights(x, [1, 2]))
def test_as_finite_diff():
x = symbols('x')
f = Function('f')
dx = Function('dx')
with warns_deprecated_sympy():
as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2])
# Use of undefined functions in ``points``
df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \
+ f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2)
df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2)
assert (df_test - df_true).simplify() == 0
def test_differentiate_finite():
x, y = symbols('x y')
f = Function('f')
res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True)
xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])]
ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym)
assert (res0 - ref0).simplify() == 0
g = Function('g')
res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True)
ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \
(-g(x - S.Half) + g(x + S.Half))*f(x)
assert (res1 - ref1).simplify() == 0
res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1])
ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2
assert (res2 - ref2).simplify() == 0
raises(ValueError, lambda: differentiate_finite(f(x)*g(x), x,
pints=[x-1, x+1]))
|
8142dfbc055caf418a78eef2d9e9eb90858cb862ac294215f25eeba17bf3925a | from distutils.version import LooseVersion as V
from itertools import product
import math
import inspect
import mpmath
from sympy.utilities.pytest import XFAIL, raises
from sympy import (
symbols, lambdify, sqrt, sin, cos, tan, pi, acos, acosh, Rational,
Float, Matrix, Lambda, Piecewise, exp, E, Integral, oo, I, Abs, Function,
true, false, And, Or, Not, ITE, Min, Max, floor, diff, IndexedBase, Sum,
DotProduct, Eq, Dummy, sinc, erf, erfc, factorial, gamma, loggamma,
digamma, RisingFactorial, besselj, bessely, besseli, besselk, S, beta,
MatrixSymbol, chebyshevt, chebyshevu, legendre, hermite, laguerre,
gegenbauer, assoc_legendre, assoc_laguerre, jacobi, fresnelc, fresnels)
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.pycode import NumPyPrinter
from sympy.utilities.lambdify import implemented_function, lambdastr
from sympy.utilities.pytest import skip
from sympy.utilities.decorator import conserve_mpmath_dps
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')
numexpr = import_module('numexpr')
tensorflow = import_module('tensorflow')
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
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
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_tensorflow_transl():
if not tensorflow:
skip("tensorflow not installed")
from sympy.utilities.lambdify import TENSORFLOW_TRANSLATIONS
for sym, tens in TENSORFLOW_TRANSLATIONS.items():
assert sym in sympy.__dict__
# XXX __dict__ is not supported after tensorflow 1.14.0
assert tens in tensorflow.__all__
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)
#================== Test some functions ============================
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
#================== 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'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.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")
a = tensorflow.constant(0, dtype=tensorflow.float32)
s = tensorflow.Session()
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")
a = tensorflow.placeholder(dtype=tensorflow.float32)
s = tensorflow.Session()
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")
a = tensorflow.Variable(0, dtype=tensorflow.float32)
s = tensorflow.Session()
if V(tensorflow.__version__) < '1.0':
s.run(tensorflow.initialize_all_variables())
else:
s.run(tensorflow.global_variables_initializer())
assert func(a).eval(session=s) == 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")
a = tensorflow.constant(False)
b = tensorflow.constant(True)
s = tensorflow.Session()
assert func(a, b).eval(session=s) == 0
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")
a = tensorflow.placeholder(dtype=tensorflow.float32)
s = tensorflow.Session()
assert func(a).eval(session=s, feed_dict={a: -1}) == -1
assert func(a).eval(session=s, feed_dict={a: 0}) == 0
assert func(a).eval(session=s, feed_dict={a: 1}) == 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")
a = tensorflow.placeholder(dtype=tensorflow.float32)
s = tensorflow.Session()
assert func(a).eval(session=s, feed_dict={a: -2}) == 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")
a = tensorflow.placeholder(dtype=tensorflow.float32)
s = tensorflow.Session()
assert func(a).eval(session=s, feed_dict={a: -2}) == -2
def test_tensorflow_relational():
if not tensorflow:
skip("tensorflow not installed.")
expr = x >= 0
func = lambdify(x, expr, modules="tensorflow")
a = tensorflow.placeholder(dtype=tensorflow.float32)
s = tensorflow.Session()
assert func(a).eval(session=s, feed_dict={a: 1})
def test_integral():
f = Lambda(x, exp(-x**2))
l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
assert l(x) == Integral(exp(-x**2), (x, -oo, oo))
#================== 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).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_namespace_type():
# lambdify had a bug where it would reject modules of type unicode
# on Python 2.
x = sympy.Symbol('x')
lambdify(x, x, modules=u'math')
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.polys.numberfields 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)
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
exp1 = lambdify((x, y), uppergamma(x, y),"mpmath")(1, 2)
exp2 = lambdify((x, y), lowergamma(x, y),"mpmath")(1, 2)
assert exp1 == uppergamma(1, 2).evalf()
assert exp2 == 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_tensorflow_array_arg():
# Test for issue 14655 (tensorflow part)
if not tensorflow:
skip("tensorflow not installed.")
f = lambdify([[x, y]], x*x + y, 'tensorflow')
fcall = f(tensorflow.constant([2.0, 1.0]))
s = tensorflow.Session()
assert s.run(fcall) == 5
def test_scipy_fns():
if not scipy:
skip("scipy not installed")
single_arg_sympy_fns = [erf, erfc, factorial, gamma, loggamma, digamma]
single_arg_scipy_fns = [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.
# SymPy does not think so.
if sympy_fn == factorial and numpy.real(tv) < 0:
tv = tv + 2*numpy.abs(numpy.real(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:
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)
# 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_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_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
|
46d866f9e7b95b864336a3c5f894b67e2ed776d3f139820adeb2393766e0789b | """ 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 import (Rational, symbols, Dummy, factorial, sqrt, log, exp, oo, zoo,
product, binomial, rf, pi, gamma, igcd, factorint, radsimp, combsimp,
npartitions, totient, primerange, factor, simplify, gcd, resultant, expand,
I, trigsimp, tan, sin, cos, cot, diff, nan, limit, EulerGamma, polygamma,
bernoulli, hyper, hyperexpand, besselj, asin, assoc_legendre, Function, re,
im, DiracDelta, chebyshevt, legendre_poly, polylog, series, O,
atan, sinh, cosh, tanh, floor, ceiling, solve, asinh, acot, csc, sec,
LambertW, N, apart, sqrtdenest, factorial2, powdenest, Mul, S, ZZ,
Poly, expand_func, E, Q, And, Or, Ne, Eq, Le, Lt, Min,
ask, refine, AlgebraicNumber, continued_fraction_iterator as cf_i,
continued_fraction_periodic as cf_p, continued_fraction_convergents as cf_c,
continued_fraction_reduce as cf_r, FiniteSet, elliptic_e, elliptic_f,
powsimp, hessian, wronskian, fibonacci, sign, Lambda, Piecewise, Subs,
residue, Derivative, logcombine, Symbol, Intersection, Union,
EmptySet, Interval, Integral, idiff, ImageSet, acos, Max, MatMul, conjugate)
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.integrals.deltafunctions import deltaintegrate
from sympy.utilities.pytest import XFAIL, slow, SKIP, skip, ON_TRAVIS
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.assumptions import assuming
from sympy.polys.rings import vring
from sympy.polys.fields import vfield
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 sympy.core.compatibility import range, PY3
from itertools import islice, takewhile
from sympy.series.formal import fps
from sympy.series.fourier import fourier_series
from sympy.calculus.util import minimum
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():
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():
try:
# This should fail or return nan or something.
diff((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x)
except:
assert True
else:
assert False, "taking the derivative with a fraction equivalent to 0/0 should fail"
# 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)
@XFAIL
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', real=True, positive=True)
assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0
def test_K10():
z = symbols('z', real=True, 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
sol = 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)
assert [s.simplify() for s in sol] == [
1 - sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2,
1 + sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2,
1 - sqrt(-6 + 2*I*sqrt(3 + 4*sqrt(3)))/2,
1 + sqrt(-6 + 2*I*sqrt(3 + 4*sqrt (3)))/2,
1 - sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2,
1 + sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2,
1 - sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2,
1 + sqrt(-6 - 2*sqrt(-3 + 4*sqrt(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():
if PY3:
n = Dummy('n')
assert solveset(sin(x) - S.Half) 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)
with assuming(Q.is_true(sin(cos(1/E**2) + 1) + b > 0)):
# TODO: Replace solve with solveset
solve(log(acos(asin(x**R(2, 3) - b) - 1)) + 2, x) == [-b - sin(1 + cos(1/E**2))**R(3/2), b + sin(1 + cos(1/E**2))**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():
variables = vring("k1:50", vfield("a,b,c", ZZ).to_domain())
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, variables) == 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(Q.is_true(E**pi > pi**E))
@XFAIL
def test_N2():
x = symbols('x', real=True)
assert ask(Q.is_true(x**4 - x + 1 > 0)) is True
assert ask(Q.is_true(x**4 - x + 1 > 1)) is False
@XFAIL
def test_N3():
x = symbols('x', real=True)
assert ask(Q.is_true(And(Lt(-1, x), Lt(x, 1))), Q.is_true(abs(x) < 1 ))
@XFAIL
def test_N4():
x, y = symbols('x y', real=True)
assert ask(Q.is_true(2*x**2 > 2*y**2), Q.is_true((x > y) & (y > 0))) is True
@XFAIL
def test_N5():
x, y, k = symbols('x y k', real=True)
assert ask(Q.is_true(k*x**2 > k*y**2), Q.is_true((x > y) & (y > 0) & (k > 0))) is True
@XFAIL
def test_N6():
x, y, k, n = symbols('x y k n', real=True)
assert ask(Q.is_true(k*x**n > k*y**n), Q.is_true((x > y) & (y > 0) & (k > 0) & (n > 0))) is True
@XFAIL
def test_N7():
x, y = symbols('x y', real=True)
assert ask(Q.is_true(y > 0), Q.is_true((x > 1) & (y >= x - 1))) is True
@XFAIL
def test_N8():
x, y, z = symbols('x y z', real=True)
assert ask(Q.is_true((x == y) & (y == z)),
Q.is_true((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)
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
# The vector module has no way of representing vectors symbolically (without
# respect to a basis)
@XFAIL
def test_O5():
assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0
#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]]
from sympy.utilities.pytest import raises
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', real=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():
M = Matrix([[x, y], [1, x*y]]).inv()
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]]))
assert (Matrix(sorted(MF.eigenvals())) - Matrix(
[-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0,
1019.9019513592784, 1020.0, 1020.0490184299969])).norm() < 1e-13
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/(-1 + I)],
[ 0],
[ 0],
[ 1]])]),
(1 + I, 1, [Matrix([[ 0],
[-1/(-1 - I)],
[ 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]])
#raises ValueError: Matrix det == 0; not invertible
M**S.Half
@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', real=True, 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', real=True, 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)
@XFAIL
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
@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(tan(x/2) + R(3, 4))/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)))
@XFAIL
def test_V12():
r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x)
# Correct result in python2.7.4, wrong result in python3.5
# https://github.com/sympy/sympy/issues/7157
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', real=True, 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
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', real=True, 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', real=True, 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', real=True, positive=True)
r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo))
assert r1.collect(pi) == pi*(-a + b)
def test_W23b():
# like W23 but limits are reversed
a, b = symbols('a b', real=True, 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', real=True, 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', real=True, 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 - t)
def test_Y3():
t = symbols('t', real=True, 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', real=True, positive=True)
s = symbols('s')
F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s)
assert F == (1 - exp(-6*sqrt(s)))/s
@XFAIL
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', real=True, 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)
# Laplace transform for diff() not calculated
# https://github.com/sympy/sympy/issues/7176
assert (F == s**2*LaplaceTransform(y(t), t, s) - s
+ LaplaceTransform(y(t), t, s) - 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', real=True, 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) ==
(-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
assert (rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n),
{r(1): 1, r(2): 2}).simplify()
== 2**(-n)*((1 + sqrt(5))**n*(sqrt(5) + 5) +
(-sqrt(5) + 1)**n*(-sqrt(5) + 5))/10)
@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', real=True, 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
|
42fc6cd1253c2254669e0ba6cb6916d5ed15d383a504a958fedeb2cf6b05301c | from sympy import (
Add, Abs, Chi, Ci, CosineTransform, Dict, Ei, Eq, FallingFactorial,
FiniteSet, Float, FourierTransform, Function, Indexed, IndexedBase, Integral,
Interval, InverseCosineTransform, InverseFourierTransform, Derivative,
InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform,
Lambda, LaplaceTransform, Limit, Matrix, Max, MellinTransform, Min, Mul,
Order, Piecewise, Poly, ring, field, ZZ, Pow, Product, Range, Rational,
RisingFactorial, rootof, RootSum, S, Shi, Si, SineTransform, Subs,
Sum, Symbol, ImageSet, Tuple, Ynm, Znm, arg, asin, acsc, Mod,
assoc_laguerre, assoc_legendre, beta, binomial, catalan, ceiling, Complement,
chebyshevt, chebyshevu, conjugate, cot, coth, diff, dirichlet_eta, euler,
exp, expint, factorial, factorial2, floor, gamma, gegenbauer, hermite,
hyper, im, jacobi, laguerre, legendre, lerchphi, log, frac,
meijerg, oo, polar_lift, polylog, re, root, sin, sqrt, symbols,
uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f,
elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not,
Contains, divisor_sigma, SeqPer, SeqFormula,
SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexRegion, fps,
AccumBounds, reduced_totient, primenu, primeomega, SingularityFunction,
stieltjes, mathieuc, mathieus, mathieucprime, mathieusprime,
UnevaluatedExpr, Quaternion, I, KroneckerProduct, LambertW)
from sympy.ntheory.factor_ import udivisor_sigma
from sympy.abc import mu, tau
from sympy.printing.latex import (latex, translate, greek_letters_set,
tex_greek_dictionary, multiline_latex)
from sympy.tensor.array import (ImmutableDenseNDimArray,
ImmutableSparseNDimArray,
MutableSparseNDimArray,
MutableDenseNDimArray,
tensorproduct)
from sympy.utilities.pytest import XFAIL, raises
from sympy.functions import DiracDelta, Heaviside, KroneckerDelta, LeviCivita
from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \
fibonacci, tribonacci
from sympy.logic import Implies
from sympy.logic.boolalg import And, Or, Xor
from sympy.physics.quantum import Commutator, Operator
from sympy.physics.units import degree, radian, kg, meter, gibibyte, microgram, second
from sympy.core.trace import Tr
from sympy.core.compatibility import range
from sympy.combinatorics.permutations import Cycle, Permutation
from sympy import MatrixSymbol, ln
from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian
from sympy.sets.setexpr import SetExpr
from sympy.sets.sets import \
Union, Intersection, Complement, SymmetricDifference, ProductSet
import sympy as sym
class lowergamma(sym.lowergamma):
pass # testing notation inheritance by a subclass with same name
x, y, z, t, a, b, c = symbols('x y z t a b c')
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)) == "foo(x)"
class R(Abs):
def _latex(self, printer):
return "foo"
assert latex(R(x)) == "foo"
def test_latex_basic():
assert latex(1 + x) == "x + 1"
assert latex(x**2) == "x^{2}"
assert latex(x**(1 + x)) == "x^{x + 1}"
assert latex(x**3 + x + 1 + x**2) == "x^{3} + x^{2} + x + 1"
assert latex(2*x*y) == "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(1/x) == r"\frac{1}{x}"
assert latex(1/x, fold_short_frac=True) == "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) == "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(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) == "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(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"
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}"
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)"
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}"
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((3 \mathbf{{x}_{A}})\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((x)\mathbf{\hat{i}_{A}}\right)'
assert latex(Curl(3*A.x*A.j)) == \
r"\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*A.x*A.j+A.i)) == \
r"\nabla\times \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*x*A.x*A.j)) == \
r"\nabla\times \left((3 \mathbf{{x}_{A}} x)\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Curl(3*A.x*A.j)) == \
r"x \left(\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)"
assert latex(Divergence(3*A.x*A.j+A.i)) == \
r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(Divergence(3*A.x*A.j)) == \
r"\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Divergence(3*A.x*A.j)) == \
r"x \left(\nabla\cdot \left((3 \mathbf{{x}_{A}})\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((3 \mathbf{{x}_{A}})\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((x)\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"\triangle \mathbf{{x}_{A}}"
assert latex(Laplacian(A.x + 3*A.y)) == \
r"\triangle \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
assert latex(x*Laplacian(A.x)) == r"x \left(\triangle \mathbf{{x}_{A}}\right)"
assert latex(Laplacian(x*A.x)) == r"\triangle \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) == "T"
assert latex(TAU) == r"\tau"
assert latex(taU) == r"\tau"
# Check that all capitalized greek letters are handled explicitly
capitalized_letters = set(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^{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}"
def test_latex_functions():
assert latex(exp(x)) == "e^{x}"
assert latex(exp(1) + exp(2)) == "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"
a1 = Function('a_1')
assert latex(a1) == r"\operatorname{a_{1}}"
assert latex(a1(x)) == r"\operatorname{a_{1}}{\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(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(Mod(x, 7)) == r'x\bmod{7}'
assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right)\bmod{7}'
assert latex(Mod(2 * x, 7)) == r'2 x\bmod{7}'
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)'
# 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 import pi
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 == '\\Psi_{0} \\overline{\\Psi_{0}}'
assert indexed_latex == '\\overline{{\\Psi}_{0}} {\\Psi}_{0}'
# Symbol('gamma') gives r'\gamma'
assert latex(Indexed('x1', Symbol('i'))) == '{x_{1}}_{i}'
assert latex(IndexedBase('gamma')) == r'\gamma'
assert latex(IndexedBase('a b')) == 'a b'
assert latex(IndexedBase('a_b')) == '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))
# 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)}'
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"
# 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"
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\}'
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_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)) == \
'\\left\\{a\\right\\} \\cap ' \
'\\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)'
assert latex(Intersection(U1, U2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\cap \\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)'
assert latex(Intersection(C1, C2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(Intersection(D1, D2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \
'\\triangle \\left\\{d\\right\\}\\right)'
assert latex(Intersection(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \
'\\cap \\left(\\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Union(A, I2, evaluate=False)) == \
'\\left\\{a\\right\\} \\cup ' \
'\\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)'
assert latex(Union(I1, I2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cap ''\\left\\{b\\right\\}\\right) ' \
'\\cup \\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)'
assert latex(Union(C1, C2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(Union(D1, D2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \
'\\triangle \\left\\{d\\right\\}\\right)'
assert latex(Union(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \
'\\cup \\left(\\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Complement(A, C2, evaluate=False)) == \
'\\left\\{a\\right\\} \\setminus \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(Complement(U1, U2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\setminus \\left(\\left\\{c\\right\\} \\cup ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Complement(I1, I2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \
'\\setminus \\left(\\left\\{c\\right\\} \\cap ' \
'\\left\\{d\\right\\}\\right)'
assert latex(Complement(D1, D2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\setminus ' \
'\\left(\\left\\{c\\right\\} \\triangle \\left\\{d\\right\\}\\right)'
assert latex(Complement(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) '\
'\\setminus \\left(\\left\\{c\\right\\} \\times '\
'\\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(A, D2, evaluate=False)) == \
'\\left\\{a\\right\\} \\triangle \\left(\\left\\{c\\right\\} ' \
'\\triangle \\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\triangle \\left(\\left\\{c\\right\\} \\cup ' \
'\\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \
'\\triangle \\left(\\left\\{c\\right\\} \\cap ' \
'\\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\triangle ' \
'\\left(\\left\\{c\\right\\} \\setminus \\left\\{d\\right\\}\\right)'
assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \
'\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \
'\\triangle \\left(\\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}\\right)'
# XXX This can be incorrect since cartesian product is not associative
assert latex(ProductSet(A, P2).flatten()) == \
'\\left\\{a\\right\\} \\times \\left\\{c\\right\\} \\times ' \
'\\left\\{d\\right\\}'
assert latex(ProductSet(U1, U2)) == \
'\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \
'\\times \\left(\\left\\{c\\right\\} \\cup ' \
'\\left\\{d\\right\\}\\right)'
assert latex(ProductSet(I1, I2)) == \
'\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \
'\\times \\left(\\left\\{c\\right\\} \\cap ' \
'\\left\\{d\\right\\}\\right)'
assert latex(ProductSet(C1, C2)) == \
'\\left(\\left\\{a\\right\\} \\setminus ' \
'\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \
'\\setminus \\left\\{d\\right\\}\\right)'
assert latex(ProductSet(D1, D2)) == \
'\\left(\\left\\{a\\right\\} \\triangle ' \
'\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \
'\\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}\; |\; 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\; |\; x \in \left\{1, 2, 3\right\}, y \in \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 \mid x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \
r"\left\{x \mid x^{2} = 1 \right\}"
def test_latex_ComplexRegion():
assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \
r"\left\{x + y i\; |\; 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)\; |\; 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(ln(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)) == "8 \\sqrt{2} \\tau^{\\frac{7}{2}}"
assert latex((2*mu)**Rational(7, 2), mode='equation*') == \
"\\begin{equation*}8 \\sqrt{2} \\mu^{\\frac{7}{2}}\\end{equation*}"
assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \
"$$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_rational():
# tests issue 3973
assert latex(-Rational(1, 2)) == "- \\frac{1}{2}"
assert latex(Rational(-1, 2)) == "- \\frac{1}{2}"
assert latex(Rational(1, -2)) == "- \\frac{1}{2}"
assert latex(-Rational(-1, 2)) == "\\frac{1}{2}"
assert latex(-Rational(1, 2)*x) == "- \\frac{x}{2}"
assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \
"- \\frac{x}{2} - \\frac{2 y}{3}"
def test_latex_inverse():
# tests issue 4129
assert latex(1/x) == "\\frac{1}{x}"
assert latex(1/(x + y)) == "\\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) == 'x + y'
assert latex(expr, mode='plain') == 'x + y'
assert latex(expr, mode='inline') == '$x + y$'
assert latex(
expr, mode='equation*') == '\\begin{equation*}x + y\\end{equation*}'
assert latex(
expr, mode='equation') == '\\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) == "\\begin{cases} x & \\text{for}\\: x < 1 \\\\x^{2} &" \
" \\text{otherwise} \\end{cases}"
assert latex(p, itex=True) == \
"\\begin{cases} x & \\text{for}\\: x \\lt 1 \\\\x^{2} &" \
" \\text{otherwise} \\end{cases}"
p = Piecewise((x, x < 0), (0, x >= 0))
assert latex(p) == '\\begin{cases} x & \\text{for}\\: x < 0 \\\\0 &' \
' \\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))) == \
'\\begin{cases} x & ' \
'\\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) == "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) == \
'\\left[\\begin{matrix}\\frac{1}{x} & y\\\\z & w\\end{matrix}\\right]'
assert latex(M1) == \
"\\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') == "4 \\times 4^{x}"
assert latex(4*4**x, mul_symbol='dot') == "4 \\cdot 4^{x}"
assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}"
assert latex(4*x, mul_symbol='times') == "4 \\times x"
assert latex(4*x, mul_symbol='dot') == "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 '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 '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) == "A B C^{-1}"
assert latex(C**-1*A*B) == "C^{-1} A B"
assert latex(A*C**-1*B) == "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') == "x^{3} + x^{2} y + 3 x y^{3} + y^{4}"
assert latex(
expr, order='rev-lex') == "y^{4} + 3 x y^{3} + x^{2} y + x^{3}"
assert latex(expr, order='none') == "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)"
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)) == \
'\\operatorname{Poly}{\\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\
' x + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}'
assert latex(Poly([a, 1, b+c, 2, 3], x)) == \
'\\operatorname{Poly}{\\left( a x^{4} + x^{3} + \\left(b + c\\right) '\
'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))) == \
'\\operatorname{Poly}{\\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\
'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(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) == "x"
assert latex(x, symbol_names={x: "x_i"}) == "x_i"
assert latex(x + y, symbol_names={x: "x_i"}) == "x_i + y"
assert latex(x**2, symbol_names={x: "x_i"}) == "x_i^{2}"
assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == "x_i + y_j"
def test_matAdd():
from sympy import MatrixSymbol
from sympy.printing.latex import LatexPrinter
C = MatrixSymbol('C', 5, 5)
B = MatrixSymbol('B', 5, 5)
l = LatexPrinter()
assert l._print(C - 2*B) in ['- 2 B + C', 'C -2 B']
assert l._print(C + 2*B) in ['2 B + C', 'C + 2 B']
assert l._print(B - 2*C) in ['B - 2 C', '- 2 C + B']
assert l._print(B + 2*C) in ['B + 2 C', '2 C + B']
def test_matMul():
from sympy import MatrixSymbol
from sympy.printing.latex import LatexPrinter
A = MatrixSymbol('A', 5, 5)
B = MatrixSymbol('B', 5, 5)
x = Symbol('x')
lp = LatexPrinter()
assert lp._print_MatMul(2*A) == '2 A'
assert lp._print_MatMul(2*x*A) == '2 x A'
assert lp._print_MatMul(-2*A) == '- 2 A'
assert lp._print_MatMul(1.5*A) == '1.5 A'
assert lp._print_MatMul(sqrt(2)*A) == r'\sqrt{2} A'
assert lp._print_MatMul(-sqrt(2)*A) == r'- \sqrt{2} A'
assert lp._print_MatMul(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A'
assert lp._print_MatMul(-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():
from sympy.matrices.expressions import MatrixSymbol
assert latex(MatrixSymbol('X', 10, 10)[:5, 1:9:2]) == \
r'X\left[:5, 1:9:2\right]'
assert latex(MatrixSymbol('X', 10, 10)[5, :5:2]) == \
r'X\left[5, :5: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\}\text{ 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) == "A_{1}"
assert latex(f1) == "f_{1}:A_{1}\\rightarrow A_{2}"
assert latex(id_A1) == "id:A_{1}\\rightarrow A_{1}"
assert latex(f2*f1) == "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) == "\\begin{array}{cc}\n" \
"A & B \\\\\n" \
" & C \n" \
"\\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_Adjoint():
from sympy.matrices import MatrixSymbol, 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}'
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}'
def test_Hadamard():
from sympy.matrices import MatrixSymbol, 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_ElementwiseApplyFunction():
from sympy.matrices import MatrixSymbol
X = MatrixSymbol('X', 2, 2)
expr = (X.T*X).applyfunc(sin)
assert latex(expr) == r"{\sin}_{\circ}\left({X^{T} X}\right)"
expr = X.applyfunc(Lambda(x, 1/x))
assert latex(expr) == r'{\left( d \mapsto \frac{1}{d} \right)}_{\circ}\left({X}\right)'
def test_ZeroMatrix():
from sympy import ZeroMatrix
assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"\mathbb{0}"
assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}"
def test_OneMatrix():
from sympy import OneMatrix
assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"\mathbb{1}"
assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}"
def test_Identity():
from sympy 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_boolean_args_order():
syms = symbols('a:f')
expr = And(*syms)
assert latex(expr) == 'a \\wedge b \\wedge c \\wedge d \\wedge e \\wedge f'
expr = Or(*syms)
assert latex(expr) == 'a \\vee b \\vee c \\vee d \\vee e \\vee f'
expr = Equivalent(*syms)
assert latex(expr) == \
'a \\Leftrightarrow b \\Leftrightarrow c \\Leftrightarrow d \\Leftrightarrow e \\Leftrightarrow f'
expr = Xor(*syms)
assert latex(expr) == \
'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'A'
assert latex(s(x)) == r'A{\left(x \right)}'
s = Function('Beta')
assert latex(s) == r'B'
s = Function('Eta')
assert latex(s) == r'H'
assert latex(s(x)) == r'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) == 'A'
s = 'Beta'
assert translate(s) == 'B'
s = 'Eta'
assert translate(s) == 'H'
s = 'omicron'
assert translate(s) == '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)) == "\\"+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'A'
assert latex(Symbol('Beta')) == r'B'
assert latex(Symbol('Gamma')) == r'\Gamma'
assert latex(Symbol('Delta')) == r'\Delta'
assert latex(Symbol('Epsilon')) == r'E'
assert latex(Symbol('Zeta')) == r'Z'
assert latex(Symbol('Eta')) == r'H'
assert latex(Symbol('Theta')) == r'\Theta'
assert latex(Symbol('Iota')) == r'I'
assert latex(Symbol('Kappa')) == r'K'
assert latex(Symbol('Lambda')) == r'\Lambda'
assert latex(Symbol('Mu')) == r'M'
assert latex(Symbol('Nu')) == r'N'
assert latex(Symbol('Xi')) == r'\Xi'
assert latex(Symbol('Omicron')) == r'O'
assert latex(Symbol('Pi')) == r'\Pi'
assert latex(Symbol('Rho')) == r'P'
assert latex(Symbol('Sigma')) == r'\Sigma'
assert latex(Symbol('Tau')) == r'T'
assert latex(Symbol('Upsilon')) == r'\Upsilon'
assert latex(Symbol('Phi')) == r'\Phi'
assert latex(Symbol('Chi')) == r'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'
@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_7117():
# See also issue #5031 (hence the evaluate=False in these).
e = Eq(x + 1, 2*x)
q = Mul(2, e, evaluate=False)
assert latex(q) == r"2 \left(x + 1 = 2 x\right)"
q = Add(6, e, evaluate=False)
assert latex(q) == r"6 + \left(x + 1 = 2 x\right)"
q = Pow(e, 2, evaluate=False)
assert latex(q) == r"\left(x + 1 = 2 x\right)^{2}"
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"- x y"
def test_issue_2934():
assert latex(Symbol(r'\frac{a_1}{b_1}')) == '\\frac{a_1}{b_1}'
def test_issue_10489():
latexSymbolWithBrace = '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_Quaternion_latex_printing():
q = Quaternion(x, y, z, t)
assert latex(q) == "x + y i + z j + t k"
q = Quaternion(x, y, z, x*t)
assert latex(q) == "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_14041():
import sympy.physics.mechanics as me
A_frame = me.ReferenceFrame('A')
thetad, phid = me.dynamicsymbols('theta, phi', 1)
L = Symbol('L')
assert latex(L*(phid + thetad)**2*A_frame.x) == \
r"L \left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}"
assert latex((phid + thetad)**2*A_frame.x) == \
r"\left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}"
assert latex((phid*thetad)**a*A_frame.x) == \
r"\left(\dot{\phi} \dot{\theta}\right)^{a}\mathbf{\hat{a}_x}"
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) == "{}^{i}"
assert latex(-i) == "{}_{i}"
expr = A(i)
assert latex(expr) == "A{}^{i}"
expr = A(i0)
assert latex(expr) == "A{}^{i_{0}}"
expr = A(-i)
assert latex(expr) == "A{}_{i}"
expr = -3*A(i)
assert latex(expr) == r"-3A{}^{i}"
expr = K(i, j, -k, -i0)
assert latex(expr) == "K{}^{ij}{}_{ki_{0}}"
expr = K(i, -j, -k, i0)
assert latex(expr) == "K{}^{i}{}_{jk}{}^{i_{0}}"
expr = K(i, -j, k, -i0)
assert latex(expr) == "K{}^{i}{}_{j}{}^{k}{}_{i_{0}}"
expr = H(i, -j)
assert latex(expr) == "H{}^{i}{}_{j}"
expr = H(i, j)
assert latex(expr) == "H{}^{ij}"
expr = H(-i, -j)
assert latex(expr) == "H{}_{ij}"
expr = (1+x)*A(i)
assert latex(expr) == r"\left(x + 1\right)A{}^{i}"
expr = H(i, -i)
assert latex(expr) == "H{}^{L_{0}}{}_{L_{0}}"
expr = H(i, -j)*A(j)*B(k)
assert latex(expr) == "H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}"
expr = A(i) + 3*B(i)
assert latex(expr) == "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) == 'K{}^{i=3,j,k=2,l}'
expr = TensorElement(K(i, j, k, l), {i: 3})
assert latex(expr) == 'K{}^{i=3,jkl}'
expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2})
assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2,l}'
expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2})
assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2})
assert latex(expr) == 'K{}^{i=3,j}{}_{k=2,l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3})
assert latex(expr) == 'K{}^{i=3,j}{}_{kl}'
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():
from sympy import ConditionSet, Tuple, FiniteSet, S, sin, cos
a, x = symbols('a x')
# Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a])
sol = ConditionSet(Tuple(x, a), FiniteSet(sin(a*x), cos(a*x)), S.Complexes)
assert latex(sol) == \
r'\left\{\left( x, \ a\right) \mid \left( x, \ a\right) \in '\
r'\mathbb{C} \wedge \left\{\sin{\left(a x \right)}, \cos{\left(a x '\
r'\right)}\right\} \right\}'
def test_trace():
# Issue 15303
from sympy 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 import Basic, 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'UnimplementedExpr\left(x\right)'
assert latex(unimplemented_expr(x**2)) == \
r'UnimplementedExpr\left(x^{2}\right)'
assert latex(unimplemented_expr_sup_sub(x)) == \
r'UnimplementedExpr^{1}_{x}\left(x\right)'
def test_MatrixSymbol_bold():
# Issue #15871
from sympy 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 = MatrixSymbol("A_k", 3, 3)
assert latex(A, mat_symbol_style='bold') == r"\mathbf{A_{k}}"
def test_imaginary_unit():
assert latex(1 + I) == '1 + i'
assert latex(1 + I, imaginary_unit='i') == '1 + i'
assert latex(1 + I, imaginary_unit='j') == '1 + j'
assert latex(1 + I, imaginary_unit='foo') == '1 + foo'
assert latex(I, imaginary_unit="ti") == '\\text{i}'
assert latex(I, imaginary_unit="tj") == '\\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_DiffGeomMethods():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
from sympy.diffgeom.rn import R2
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)
assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}'
b = BaseScalarField(rect, 0)
assert latex(b) == r'\mathbf{rect_{0}}'
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}}'
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)')
# 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)')
# 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(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{,}8e-07')
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'))
|
7cb5dc38f4331bfed640516231c60218a1997c6802d3c3a018afcec65f5acf55 | from sympy.core import (S, pi, oo, symbols, Rational, Integer,
GoldenRatio, EulerGamma, Catalan, Lambda, Dummy,
Eq, Ne, Le, Lt, Gt, Ge)
from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
sign)
from sympy.logic import ITE
from sympy.utilities.pytest import raises
from sympy.utilities.lambdify import implemented_function
from sympy.tensor import IndexedBase, Idx
from sympy.matrices import MatrixSymbol
from sympy import rust_code
x, y, z = symbols('x,y,z')
def test_Integer():
assert rust_code(Integer(42)) == "42"
assert rust_code(Integer(-56)) == "-56"
def test_Relational():
assert rust_code(Eq(x, y)) == "x == y"
assert rust_code(Ne(x, y)) == "x != y"
assert rust_code(Le(x, y)) == "x <= y"
assert rust_code(Lt(x, y)) == "x < y"
assert rust_code(Gt(x, y)) == "x > y"
assert rust_code(Ge(x, y)) == "x >= y"
def test_Rational():
assert rust_code(Rational(3, 7)) == "3_f64/7.0"
assert rust_code(Rational(18, 9)) == "2"
assert rust_code(Rational(3, -7)) == "-3_f64/7.0"
assert rust_code(Rational(-3, -7)) == "3_f64/7.0"
assert rust_code(x + Rational(3, 7)) == "x + 3_f64/7.0"
assert rust_code(Rational(3, 7)*x) == "(3_f64/7.0)*x"
def test_basic_ops():
assert rust_code(x + y) == "x + y"
assert rust_code(x - y) == "x - y"
assert rust_code(x * y) == "x*y"
assert rust_code(x / y) == "x/y"
assert rust_code(-x) == "-x"
def test_printmethod():
class fabs(Abs):
def _rust_code(self, printer):
return "%s.fabs()" % printer._print(self.args[0])
assert rust_code(fabs(x)) == "x.fabs()"
a = MatrixSymbol("a", 1 ,3)
assert rust_code(a[0,0]) == 'a[0]'
def test_Functions():
assert rust_code(sin(x) ** cos(x)) == "x.sin().powf(x.cos())"
assert rust_code(abs(x)) == "x.abs()"
assert rust_code(ceiling(x)) == "x.ceil()"
def test_Pow():
assert rust_code(1/x) == "x.recip()"
assert rust_code(x**-1) == rust_code(x**-1.0) == "x.recip()"
assert rust_code(sqrt(x)) == "x.sqrt()"
assert rust_code(x**S.Half) == rust_code(x**0.5) == "x.sqrt()"
assert rust_code(1/sqrt(x)) == "x.sqrt().recip()"
assert rust_code(x**-S.Half) == rust_code(x**-0.5) == "x.sqrt().recip()"
assert rust_code(1/pi) == "PI.recip()"
assert rust_code(pi**-1) == rust_code(pi**-1.0) == "PI.recip()"
assert rust_code(pi**-0.5) == "PI.sqrt().recip()"
assert rust_code(x**Rational(1, 3)) == "x.cbrt()"
assert rust_code(2**x) == "x.exp2()"
assert rust_code(exp(x)) == "x.exp()"
assert rust_code(x**3) == "x.powi(3)"
assert rust_code(x**(y**3)) == "x.powf(y.powi(3))"
assert rust_code(x**Rational(2, 3)) == "x.powf(2_f64/3.0)"
g = implemented_function('g', Lambda(x, 2*x))
assert rust_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
"(3.5*2*x).powf(-x + y.powf(x))/(x.powi(2) + y)"
_cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi", 1),
(lambda base, exp: not exp.is_integer, "pow", 1)]
assert rust_code(x**3, user_functions={'Pow': _cond_cfunc}) == 'x.dpowi(3)'
assert rust_code(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'x.pow(3.2)'
def test_constants():
assert rust_code(pi) == "PI"
assert rust_code(oo) == "INFINITY"
assert rust_code(S.Infinity) == "INFINITY"
assert rust_code(-oo) == "NEG_INFINITY"
assert rust_code(S.NegativeInfinity) == "NEG_INFINITY"
assert rust_code(S.NaN) == "NAN"
assert rust_code(exp(1)) == "E"
assert rust_code(S.Exp1) == "E"
def test_constants_other():
assert rust_code(2*GoldenRatio) == "const GoldenRatio: f64 = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17)
assert rust_code(
2*Catalan) == "const Catalan: f64 = %s;\n2*Catalan" % Catalan.evalf(17)
assert rust_code(2*EulerGamma) == "const EulerGamma: f64 = %s;\n2*EulerGamma" % EulerGamma.evalf(17)
def test_boolean():
assert rust_code(True) == "true"
assert rust_code(S.true) == "true"
assert rust_code(False) == "false"
assert rust_code(S.false) == "false"
assert rust_code(x & y) == "x && y"
assert rust_code(x | y) == "x || y"
assert rust_code(~x) == "!x"
assert rust_code(x & y & z) == "x && y && z"
assert rust_code(x | y | z) == "x || y || z"
assert rust_code((x & y) | z) == "z || x && y"
assert rust_code((x | y) & z) == "z && (x || y)"
def test_Piecewise():
expr = Piecewise((x, x < 1), (x + 2, True))
assert rust_code(expr) == (
"if (x < 1) {\n"
" x\n"
"} else {\n"
" x + 2\n"
"}")
assert rust_code(expr, assign_to="r") == (
"r = if (x < 1) {\n"
" x\n"
"} else {\n"
" x + 2\n"
"};")
assert rust_code(expr, assign_to="r", inline=True) == (
"r = if (x < 1) { x } else { x + 2 };")
expr = Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True))
assert rust_code(expr, inline=True) == (
"if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }")
assert rust_code(expr, assign_to="r", inline=True) == (
"r = if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 };")
assert rust_code(expr, assign_to="r") == (
"r = if (x < 1) {\n"
" x\n"
"} else if (x < 5) {\n"
" x + 1\n"
"} else {\n"
" x + 2\n"
"};")
expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True))
assert rust_code(expr, inline=True) == (
"2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }")
expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) - 42
assert rust_code(expr, inline=True) == (
"2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 } - 42")
# 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: rust_code(expr))
def test_dereference_printing():
expr = x + y + sin(z) + z
assert rust_code(expr, dereference=[z]) == "x + y + (*z) + (*z).sin()"
def test_sign():
expr = sign(x) * y
assert rust_code(expr) == "y*x.signum()"
assert rust_code(expr, assign_to='r') == "r = y*x.signum();"
expr = sign(x + y) + 42
assert rust_code(expr) == "(x + y).signum() + 42"
assert rust_code(expr, assign_to='r') == "r = (x + y).signum() + 42;"
expr = sign(cos(x))
assert rust_code(expr) == "x.cos().signum()"
def test_reserved_words():
x, y = symbols("x if")
expr = sin(y)
assert rust_code(expr) == "if_.sin()"
assert rust_code(expr, dereference=[y]) == "(*if_).sin()"
assert rust_code(expr, reserved_word_suffix='_unreserved') == "if_unreserved.sin()"
with raises(ValueError):
rust_code(expr, error_on_reserved=True)
def test_ITE():
expr = ITE(x < 1, y, z)
assert rust_code(expr) == (
"if (x < 1) {\n"
" y\n"
"} else {\n"
" z\n"
"}")
def test_Indexed():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o = symbols('n m o', integer=True)
i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
x = IndexedBase('x')[j]
assert rust_code(x) == "x[j]"
A = IndexedBase('A')[i, j]
assert rust_code(A) == "A[m*i + j]"
B = IndexedBase('B')[i, j, k]
assert rust_code(B) == "B[m*o*i + o*j + k]"
def test_dummy_loops():
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
assert rust_code(x[i], assign_to=y[i]) == (
"for i in 0..m {\n"
" y[i] = x[i];\n"
"}")
def test_loops():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
m, n = symbols('m n', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
z = IndexedBase('z')
i = Idx('i', m)
j = Idx('j', n)
assert rust_code(A[i, j]*x[j], assign_to=y[i]) == (
"for i in 0..m {\n"
" y[i] = 0;\n"
"}\n"
"for i in 0..m {\n"
" for j in 0..n {\n"
" y[i] = A[n*i + j]*x[j] + y[i];\n"
" }\n"
"}")
assert rust_code(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == (
"for i in 0..m {\n"
" y[i] = x[i] + z[i];\n"
"}\n"
"for i in 0..m {\n"
" for j in 0..n {\n"
" y[i] = A[n*i + j]*x[j] + y[i];\n"
" }\n"
"}")
def test_loops_multiple_contractions():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
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)
assert rust_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == (
"for i in 0..m {\n"
" y[i] = 0;\n"
"}\n"
"for i in 0..m {\n"
" for j in 0..n {\n"
" for k in 0..o {\n"
" for l in 0..p {\n"
" y[i] = a[%s]*b[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
" }\n"
" }\n"
" }\n"
"}")
def test_loops_addfactor():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
m, n, o, p = symbols('m n 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)
code = rust_code((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
assert code == (
"for i in 0..m {\n"
" y[i] = 0;\n"
"}\n"
"for i in 0..m {\n"
" for j in 0..n {\n"
" for k in 0..o {\n"
" for l in 0..p {\n"
" y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
" }\n"
" }\n"
" }\n"
"}")
def test_settings():
raises(TypeError, lambda: rust_code(sin(x), method="garbage"))
def test_inline_function():
x = symbols('x')
g = implemented_function('g', Lambda(x, 2*x))
assert rust_code(g(x)) == "2*x"
g = implemented_function('g', Lambda(x, 2*x/Catalan))
assert rust_code(g(x)) == (
"const Catalan: f64 = %s;\n2*x/Catalan" % Catalan.evalf(17))
A = IndexedBase('A')
i = Idx('i', symbols('n', integer=True))
g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
assert rust_code(g(A[i]), assign_to=A[i]) == (
"for i in 0..n {\n"
" A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
"}")
def test_user_functions():
x = symbols('x', integer=False)
n = symbols('n', integer=True)
custom_functions = {
"ceiling": "ceil",
"Abs": [(lambda x: not x.is_integer, "fabs", 4), (lambda x: x.is_integer, "abs", 4)],
}
assert rust_code(ceiling(x), user_functions=custom_functions) == "x.ceil()"
assert rust_code(Abs(x), user_functions=custom_functions) == "fabs(x)"
assert rust_code(Abs(n), user_functions=custom_functions) == "abs(n)"
|
45d4747bd7cfded01981386edc1e4d3a16b99f213214f640fb279ce7150cee05 | from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer,
Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge)
from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow
from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos
from sympy.utilities.pytest import raises
from sympy.utilities.lambdify import implemented_function
from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity,
HadamardProduct, SparseMatrix)
from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli,
besselk, hankel1, hankel2, airyai,
airybi, airyaiprime, airybiprime)
from sympy.utilities.pytest import XFAIL
from sympy import julia_code
x, y, z = symbols('x,y,z')
def test_Integer():
assert julia_code(Integer(67)) == "67"
assert julia_code(Integer(-1)) == "-1"
def test_Rational():
assert julia_code(Rational(3, 7)) == "3/7"
assert julia_code(Rational(18, 9)) == "2"
assert julia_code(Rational(3, -7)) == "-3/7"
assert julia_code(Rational(-3, -7)) == "3/7"
assert julia_code(x + Rational(3, 7)) == "x + 3/7"
assert julia_code(Rational(3, 7)*x) == "3*x/7"
def test_Relational():
assert julia_code(Eq(x, y)) == "x == y"
assert julia_code(Ne(x, y)) == "x != y"
assert julia_code(Le(x, y)) == "x <= y"
assert julia_code(Lt(x, y)) == "x < y"
assert julia_code(Gt(x, y)) == "x > y"
assert julia_code(Ge(x, y)) == "x >= y"
def test_Function():
assert julia_code(sin(x) ** cos(x)) == "sin(x).^cos(x)"
assert julia_code(abs(x)) == "abs(x)"
assert julia_code(ceiling(x)) == "ceil(x)"
def test_Pow():
assert julia_code(x**3) == "x.^3"
assert julia_code(x**(y**3)) == "x.^(y.^3)"
assert julia_code(x**Rational(2, 3)) == 'x.^(2/3)'
g = implemented_function('g', Lambda(x, 2*x))
assert julia_code(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 julia_code(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
evaluate=False)) == '-2*x./(y.*y)'
def test_basic_ops():
assert julia_code(x*y) == "x.*y"
assert julia_code(x + y) == "x + y"
assert julia_code(x - y) == "x - y"
assert julia_code(-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 julia_code(1/x) == '1./x'
assert julia_code(x**-1) == julia_code(x**-1.0) == '1./x'
assert julia_code(1/sqrt(x)) == '1./sqrt(x)'
assert julia_code(x**-S.Half) == julia_code(x**-0.5) == '1./sqrt(x)'
assert julia_code(sqrt(x)) == 'sqrt(x)'
assert julia_code(x**S.Half) == julia_code(x**0.5) == 'sqrt(x)'
assert julia_code(1/pi) == '1/pi'
assert julia_code(pi**-1) == julia_code(pi**-1.0) == '1/pi'
assert julia_code(pi**-0.5) == '1/sqrt(pi)'
def test_mix_number_mult_symbols():
assert julia_code(3*x) == "3*x"
assert julia_code(pi*x) == "pi*x"
assert julia_code(3/x) == "3./x"
assert julia_code(pi/x) == "pi./x"
assert julia_code(x/3) == "x/3"
assert julia_code(x/pi) == "x/pi"
assert julia_code(x*y) == "x.*y"
assert julia_code(3*x*y) == "3*x.*y"
assert julia_code(3*pi*x*y) == "3*pi*x.*y"
assert julia_code(x/y) == "x./y"
assert julia_code(3*x/y) == "3*x./y"
assert julia_code(x*y/z) == "x.*y./z"
assert julia_code(x/y*z) == "x.*z./y"
assert julia_code(1/x/y) == "1./(x.*y)"
assert julia_code(2*pi*x/y/z) == "2*pi*x./(y.*z)"
assert julia_code(3*pi/x) == "3*pi./x"
assert julia_code(S(3)/5) == "3/5"
assert julia_code(S(3)/5*x) == "3*x/5"
assert julia_code(x/y/z) == "x./(y.*z)"
assert julia_code((x+y)/z) == "(x + y)./z"
assert julia_code((x+y)/(z+x)) == "(x + y)./(x + z)"
assert julia_code((x+y)/EulerGamma) == "(x + y)/eulergamma"
assert julia_code(x/3/pi) == "x/(3*pi)"
assert julia_code(S(3)/5*x*y/pi) == "3*x.*y/(5*pi)"
def test_mix_number_pow_symbols():
assert julia_code(pi**3) == 'pi^3'
assert julia_code(x**2) == 'x.^2'
assert julia_code(x**(pi**3)) == 'x.^(pi^3)'
assert julia_code(x**y) == 'x.^y'
assert julia_code(x**(y**z)) == 'x.^(y.^z)'
assert julia_code((x**y)**z) == '(x.^y).^z'
def test_imag():
I = S('I')
assert julia_code(I) == "im"
assert julia_code(5*I) == "5im"
assert julia_code((S(3)/2)*I) == "3*im/2"
assert julia_code(3+4*I) == "3 + 4im"
def test_constants():
assert julia_code(pi) == "pi"
assert julia_code(oo) == "Inf"
assert julia_code(-oo) == "-Inf"
assert julia_code(S.NegativeInfinity) == "-Inf"
assert julia_code(S.NaN) == "NaN"
assert julia_code(S.Exp1) == "e"
assert julia_code(exp(1)) == "e"
def test_constants_other():
assert julia_code(2*GoldenRatio) == "2*golden"
assert julia_code(2*Catalan) == "2*catalan"
assert julia_code(2*EulerGamma) == "2*eulergamma"
def test_boolean():
assert julia_code(x & y) == "x && y"
assert julia_code(x | y) == "x || y"
assert julia_code(~x) == "!x"
assert julia_code(x & y & z) == "x && y && z"
assert julia_code(x | y | z) == "x || y || z"
assert julia_code((x & y) | z) == "z || x && y"
assert julia_code((x | y) & z) == "z && (x || y)"
def test_Matrices():
assert julia_code(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);\n"
"0 1 pi;\n"
"0 e ceil(x)]")
assert julia_code(A) == expected
# row and columns
assert julia_code(A[:,0]) == "[1, 0, 0]"
assert julia_code(A[0,:]) == "[1 sin(x/2) abs(x)]"
# empty matrices
assert julia_code(Matrix(0, 0, [])) == 'zeros(0, 0)'
assert julia_code(Matrix(0, 3, [])) == 'zeros(0, 3)'
# annoying to read but correct
assert julia_code(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 julia_code(A) == "[1 sin(2./x) 3*pi./(5*x)]"
assert julia_code(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 julia_code(A) == expected
def test_MatrixSymbol():
n = Symbol('n', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
assert julia_code(A*B) == "A*B"
assert julia_code(B*A) == "B*A"
assert julia_code(2*A*B) == "2*A*B"
assert julia_code(B*2*A) == "2*B*A"
assert julia_code(A*(B + 3*Identity(n))) == "A*(3*eye(n) + B)"
assert julia_code(A**(x**2)) == "A^(x.^2)"
assert julia_code(A**3) == "A^3"
assert julia_code(A**S.Half) == "A^(1/2)"
def test_special_matrices():
assert julia_code(6*Identity(3)) == "6*eye(3)"
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_julia_noninline():
source = julia_code((x+y)/Catalan, assign_to='me', inline=False)
expected = (
"const Catalan = %s\n"
"me = (x + y)/Catalan"
) % Catalan.evalf(17)
assert source == expected
def test_julia_piecewise():
expr = Piecewise((x, x < 1), (x**2, True))
assert julia_code(expr) == "((x < 1) ? (x) : (x.^2))"
assert julia_code(expr, assign_to="r") == (
"r = ((x < 1) ? (x) : (x.^2))")
assert julia_code(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) :\n"
"(x < 2) ? (x.^3) :\n"
"(x < 3) ? (x.^4) : (x.^5))")
assert julia_code(expr) == expected
assert julia_code(expr, assign_to="r") == "r = " + expected
assert julia_code(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: julia_code(expr))
def test_julia_piecewise_times_const():
pw = Piecewise((x, x < 1), (x**2, True))
assert julia_code(2*pw) == "2*((x < 1) ? (x) : (x.^2))"
assert julia_code(pw/x) == "((x < 1) ? (x) : (x.^2))./x"
assert julia_code(pw/(x*y)) == "((x < 1) ? (x) : (x.^2))./(x.*y)"
assert julia_code(pw/3) == "((x < 1) ? (x) : (x.^2))/3"
def test_julia_matrix_assign_to():
A = Matrix([[1, 2, 3]])
assert julia_code(A, assign_to='a') == "a = [1 2 3]"
A = Matrix([[1, 2], [3, 4]])
assert julia_code(A, assign_to='A') == "A = [1 2;\n3 4]"
def test_julia_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 julia_code(A, assign_to=B) == "B = [1 2 3]"
raises(ValueError, lambda: julia_code(A, assign_to=x))
raises(ValueError, lambda: julia_code(A, assign_to=C))
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]"
# FIXME?
#assert julia_code(A, assign_to=x) == "x = [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_julia_boolean():
assert julia_code(True) == "true"
assert julia_code(S.true) == "true"
assert julia_code(False) == "false"
assert julia_code(S.false) == "false"
def test_julia_not_supported():
assert julia_code(S.ComplexInfinity) == (
"# Not supported in Julia:\n"
"# ComplexInfinity\n"
"zoo"
)
f = Function('f')
assert julia_code(f(x).diff(x)) == (
"# Not supported in Julia:\n"
"# Derivative\n"
"Derivative(f(x), 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 julia_code(pw, inline=False) == (
"if (x < 0)\n"
" endless\n"
"elseif (x <= 1)\n"
" elsewhere\n"
"else\n"
" 1\n"
"end")
def test_haramard():
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 3, 3)
v = MatrixSymbol('v', 3, 1)
h = MatrixSymbol('h', 1, 3)
C = HadamardProduct(A, B)
assert julia_code(C) == "A.*B"
assert julia_code(C*v) == "(A.*B)*v"
assert julia_code(h*C*v) == "h*(A.*B)*v"
assert julia_code(C*A) == "(A.*B)*A"
# mixing Hadamard and scalar strange b/c we vectorize scalars
assert julia_code(C*x*y) == "(x.*y)*(A.*B)"
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 julia_code(M) == (
"sparse([4, 2, 3, 1, 2], [1, 3, 3, 4, 4], [x.*y, 20, 10, 30, 22], 5, 6)"
)
def test_specfun():
n = Symbol('n')
for f in [besselj, bessely, besseli, besselk]:
assert julia_code(f(n, x)) == f.__name__ + '(n, x)'
for f in [airyai, airyaiprime, airybi, airybiprime]:
assert julia_code(f(x)) == f.__name__ + '(x)'
assert julia_code(hankel1(n, x)) == 'hankelh1(n, x)'
assert julia_code(hankel2(n, x)) == 'hankelh2(n, x)'
assert julia_code(jn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*besselj(n + 1/2, x)/2'
assert julia_code(yn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*bessely(n + 1/2, 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(julia_code(A[0, 0]) == "A[1,1]")
assert(julia_code(3 * A[0, 0]) == "3*A[1,1]")
F = C[0, 0].subs(C, A - B)
assert(julia_code(F) == "(A - B)[1,1]")
|
3e9b3b301e6c210d0cc74309a5050907a201fad9db228dfc30ab0b3dde4ffecb |
from sympy import TableForm, S
from sympy.printing.latex import latex
from sympy.abc import x
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.utilities.pytest import raises
from textwrap import dedent
def test_TableForm():
s = str(TableForm([["a", "b"], ["c", "d"], ["e", 0]],
headings="automatic"))
assert s == (
' | 1 2\n'
'-------\n'
'1 | a b\n'
'2 | c d\n'
'3 | e '
)
s = str(TableForm([["a", "b"], ["c", "d"], ["e", 0]],
headings="automatic", wipe_zeros=False))
assert s == dedent('''\
| 1 2
-------
1 | a b
2 | c d
3 | e 0''')
s = str(TableForm([[x**2, "b"], ["c", x**2], ["e", "f"]],
headings=("automatic", None)))
assert s == (
'1 | x**2 b \n'
'2 | c x**2\n'
'3 | e f '
)
s = str(TableForm([["a", "b"], ["c", "d"], ["e", "f"]],
headings=(None, "automatic")))
assert s == dedent('''\
1 2
---
a b
c d
e f''')
s = str(TableForm([[5, 7], [4, 2], [10, 3]],
headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]]))
assert s == (
' | y1 y2\n'
'---------------\n'
'Group A | 5 7 \n'
'Group B | 4 2 \n'
'Group C | 10 3 '
)
raises(
ValueError,
lambda:
TableForm(
[[5, 7], [4, 2], [10, 3]],
headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]],
alignments="middle")
)
s = str(TableForm([[5, 7], [4, 2], [10, 3]],
headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]],
alignments="right"))
assert s == dedent('''\
| y1 y2
---------------
Group A | 5 7
Group B | 4 2
Group C | 10 3''')
# other alignment permutations
d = [[1, 100], [100, 1]]
s = TableForm(d, headings=(('xxx', 'x'), None), alignments='l')
assert str(s) == (
'xxx | 1 100\n'
' x | 100 1 '
)
s = TableForm(d, headings=(('xxx', 'x'), None), alignments='lr')
assert str(s) == dedent('''\
xxx | 1 100
x | 100 1''')
s = TableForm(d, headings=(('xxx', 'x'), None), alignments='clr')
assert str(s) == dedent('''\
xxx | 1 100
x | 100 1''')
s = TableForm(d, headings=(('xxx', 'x'), None))
assert str(s) == (
'xxx | 1 100\n'
' x | 100 1 '
)
raises(ValueError, lambda: TableForm(d, alignments='clr'))
#pad
s = str(TableForm([[None, "-", 2], [1]], pad='?'))
assert s == dedent('''\
? - 2
1 ? ?''')
def test_TableForm_latex():
s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
wipe_zeros=True, headings=("automatic", "automatic")))
assert s == (
'\\begin{tabular}{r l l}\n'
' & 1 & 2 \\\\\n'
'\\hline\n'
'1 & & $x^{3}$ \\\\\n'
'2 & $c$ & $\\frac{1}{4}$ \\\\\n'
'3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
'\\end{tabular}'
)
s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
wipe_zeros=True, headings=("automatic", "automatic"), alignments='l'))
assert s == (
'\\begin{tabular}{r l l}\n'
' & 1 & 2 \\\\\n'
'\\hline\n'
'1 & & $x^{3}$ \\\\\n'
'2 & $c$ & $\\frac{1}{4}$ \\\\\n'
'3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
'\\end{tabular}'
)
s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
wipe_zeros=True, headings=("automatic", "automatic"), alignments='l'*3))
assert s == (
'\\begin{tabular}{l l l}\n'
' & 1 & 2 \\\\\n'
'\\hline\n'
'1 & & $x^{3}$ \\\\\n'
'2 & $c$ & $\\frac{1}{4}$ \\\\\n'
'3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
'\\end{tabular}'
)
s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
headings=("automatic", "automatic")))
assert s == (
'\\begin{tabular}{r l l}\n'
' & 1 & 2 \\\\\n'
'\\hline\n'
'1 & $a$ & $x^{3}$ \\\\\n'
'2 & $c$ & $\\frac{1}{4}$ \\\\\n'
'3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
'\\end{tabular}'
)
s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
formats=['(%s)', None], headings=("automatic", "automatic")))
assert s == (
'\\begin{tabular}{r l l}\n'
' & 1 & 2 \\\\\n'
'\\hline\n'
'1 & (a) & $x^{3}$ \\\\\n'
'2 & (c) & $\\frac{1}{4}$ \\\\\n'
'3 & (sqrt(x)) & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
'\\end{tabular}'
)
def neg_in_paren(x, i, j):
if i % 2:
return ('(%s)' if x < 0 else '%s') % x
else:
pass # use default print
s = latex(TableForm([[-1, 2], [-3, 4]],
formats=[neg_in_paren]*2, headings=("automatic", "automatic")))
assert s == (
'\\begin{tabular}{r l l}\n'
' & 1 & 2 \\\\\n'
'\\hline\n'
'1 & -1 & 2 \\\\\n'
'2 & (-3) & 4 \\\\\n'
'\\end{tabular}'
)
s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]]))
assert s == (
'\\begin{tabular}{l l}\n'
'$a$ & $x^{3}$ \\\\\n'
'$c$ & $\\frac{1}{4}$ \\\\\n'
'$\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
'\\end{tabular}'
)
|
48e61d317963d68567d22e1b938a5635dc688f7c986dde0f80b60ac9ef44c105 | from sympy import diff, Integral, Limit, sin, Symbol, Integer, Rational, cos, \
tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, E, I, oo, \
pi, GoldenRatio, EulerGamma, Sum, Eq, Ne, Ge, Lt, Float, Matrix, Basic, \
S, MatrixSymbol, Function, Derivative, log, true, false, Range, Min, Max, \
Lambda, IndexedBase, symbols, zoo, elliptic_f, elliptic_e, elliptic_pi, Ei, \
expint, jacobi, gegenbauer, chebyshevt, chebyshevu, legendre, assoc_legendre, \
laguerre, assoc_laguerre, hermite, euler, stieltjes, mathieuc, mathieus, \
mathieucprime, mathieusprime, TribonacciConstant, Contains, LambertW, \
cot, coth, acot, acoth, csc, acsc, csch, acsch, sec, asec, sech, asech
from sympy import elliptic_k, totient, reduced_totient, primenu, primeomega, \
fresnelc, fresnels, Heaviside
from sympy.calculus.util import AccumBounds
from sympy.core.containers import Tuple
from sympy.functions.combinatorial.factorials import factorial, factorial2, \
binomial
from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \
fibonacci, tribonacci, catalan
from sympy.functions.elementary.complexes import re, im, Abs, conjugate
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.integers import floor, ceiling
from sympy.functions.special.gamma_functions import gamma, lowergamma, uppergamma
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.zeta_functions import polylog, lerchphi, zeta, dirichlet_eta
from sympy.logic.boolalg import And, Or, Implies, Equivalent, Xor, Not
from sympy.matrices.expressions.determinant import Determinant
from sympy.physics.quantum import ComplexSpace, HilbertSpace, FockSpace, hbar, Dagger
from sympy.printing.mathml import mathml, MathMLContentPrinter, \
MathMLPresentationPrinter, MathMLPrinter
from sympy.sets.sets import FiniteSet, Union, Intersection, Complement, \
SymmetricDifference, Interval, EmptySet
from sympy.stats.rv import RandomSymbol
from sympy.utilities.pytest import raises
from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian
x, y, z, a, b, c, d, e, n = symbols('x:z a:e n')
mp = MathMLContentPrinter()
mpp = MathMLPresentationPrinter()
def test_mathml_printer():
m = MathMLPrinter()
assert m.doprint(1+x) == mp.doprint(1+x)
def test_content_printmethod():
assert mp.doprint(1 + x) == '<apply><plus/><ci>x</ci><cn>1</cn></apply>'
def test_content_mathml_core():
mml_1 = mp._print(1 + x)
assert mml_1.nodeName == 'apply'
nodes = mml_1.childNodes
assert len(nodes) == 3
assert nodes[0].nodeName == 'plus'
assert nodes[0].hasChildNodes() is False
assert nodes[0].nodeValue is None
assert nodes[1].nodeName in ['cn', 'ci']
if nodes[1].nodeName == 'cn':
assert nodes[1].childNodes[0].nodeValue == '1'
assert nodes[2].childNodes[0].nodeValue == 'x'
else:
assert nodes[1].childNodes[0].nodeValue == 'x'
assert nodes[2].childNodes[0].nodeValue == '1'
mml_2 = mp._print(x**2)
assert mml_2.nodeName == 'apply'
nodes = mml_2.childNodes
assert nodes[1].childNodes[0].nodeValue == 'x'
assert nodes[2].childNodes[0].nodeValue == '2'
mml_3 = mp._print(2*x)
assert mml_3.nodeName == 'apply'
nodes = mml_3.childNodes
assert nodes[0].nodeName == 'times'
assert nodes[1].childNodes[0].nodeValue == '2'
assert nodes[2].childNodes[0].nodeValue == 'x'
mml = mp._print(Float(1.0, 2)*x)
assert mml.nodeName == 'apply'
nodes = mml.childNodes
assert nodes[0].nodeName == 'times'
assert nodes[1].childNodes[0].nodeValue == '1.0'
assert nodes[2].childNodes[0].nodeValue == 'x'
def test_content_mathml_functions():
mml_1 = mp._print(sin(x))
assert mml_1.nodeName == 'apply'
assert mml_1.childNodes[0].nodeName == 'sin'
assert mml_1.childNodes[1].nodeName == 'ci'
mml_2 = mp._print(diff(sin(x), x, evaluate=False))
assert mml_2.nodeName == 'apply'
assert mml_2.childNodes[0].nodeName == 'diff'
assert mml_2.childNodes[1].nodeName == 'bvar'
assert mml_2.childNodes[1].childNodes[
0].nodeName == 'ci' # below bvar there's <ci>x/ci>
mml_3 = mp._print(diff(cos(x*y), x, evaluate=False))
assert mml_3.nodeName == 'apply'
assert mml_3.childNodes[0].nodeName == 'partialdiff'
assert mml_3.childNodes[1].nodeName == 'bvar'
assert mml_3.childNodes[1].childNodes[
0].nodeName == 'ci' # below bvar there's <ci>x/ci>
def test_content_mathml_limits():
# XXX No unevaluated limits
lim_fun = sin(x)/x
mml_1 = mp._print(Limit(lim_fun, x, 0))
assert mml_1.childNodes[0].nodeName == 'limit'
assert mml_1.childNodes[1].nodeName == 'bvar'
assert mml_1.childNodes[2].nodeName == 'lowlimit'
assert mml_1.childNodes[3].toxml() == mp._print(lim_fun).toxml()
def test_content_mathml_integrals():
integrand = x
mml_1 = mp._print(Integral(integrand, (x, 0, 1)))
assert mml_1.childNodes[0].nodeName == 'int'
assert mml_1.childNodes[1].nodeName == 'bvar'
assert mml_1.childNodes[2].nodeName == 'lowlimit'
assert mml_1.childNodes[3].nodeName == 'uplimit'
assert mml_1.childNodes[4].toxml() == mp._print(integrand).toxml()
def test_content_mathml_matrices():
A = Matrix([1, 2, 3])
B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]])
mll_1 = mp._print(A)
assert mll_1.childNodes[0].nodeName == 'matrixrow'
assert mll_1.childNodes[0].childNodes[0].nodeName == 'cn'
assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeValue == '1'
assert mll_1.childNodes[1].nodeName == 'matrixrow'
assert mll_1.childNodes[1].childNodes[0].nodeName == 'cn'
assert mll_1.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
assert mll_1.childNodes[2].nodeName == 'matrixrow'
assert mll_1.childNodes[2].childNodes[0].nodeName == 'cn'
assert mll_1.childNodes[2].childNodes[0].childNodes[0].nodeValue == '3'
mll_2 = mp._print(B)
assert mll_2.childNodes[0].nodeName == 'matrixrow'
assert mll_2.childNodes[0].childNodes[0].nodeName == 'cn'
assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeValue == '0'
assert mll_2.childNodes[0].childNodes[1].nodeName == 'cn'
assert mll_2.childNodes[0].childNodes[1].childNodes[0].nodeValue == '5'
assert mll_2.childNodes[0].childNodes[2].nodeName == 'cn'
assert mll_2.childNodes[0].childNodes[2].childNodes[0].nodeValue == '4'
assert mll_2.childNodes[1].nodeName == 'matrixrow'
assert mll_2.childNodes[1].childNodes[0].nodeName == 'cn'
assert mll_2.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
assert mll_2.childNodes[1].childNodes[1].nodeName == 'cn'
assert mll_2.childNodes[1].childNodes[1].childNodes[0].nodeValue == '3'
assert mll_2.childNodes[1].childNodes[2].nodeName == 'cn'
assert mll_2.childNodes[1].childNodes[2].childNodes[0].nodeValue == '1'
assert mll_2.childNodes[2].nodeName == 'matrixrow'
assert mll_2.childNodes[2].childNodes[0].nodeName == 'cn'
assert mll_2.childNodes[2].childNodes[0].childNodes[0].nodeValue == '9'
assert mll_2.childNodes[2].childNodes[1].nodeName == 'cn'
assert mll_2.childNodes[2].childNodes[1].childNodes[0].nodeValue == '7'
assert mll_2.childNodes[2].childNodes[2].nodeName == 'cn'
assert mll_2.childNodes[2].childNodes[2].childNodes[0].nodeValue == '9'
def test_content_mathml_sums():
summand = x
mml_1 = mp._print(Sum(summand, (x, 1, 10)))
assert mml_1.childNodes[0].nodeName == 'sum'
assert mml_1.childNodes[1].nodeName == 'bvar'
assert mml_1.childNodes[2].nodeName == 'lowlimit'
assert mml_1.childNodes[3].nodeName == 'uplimit'
assert mml_1.childNodes[4].toxml() == mp._print(summand).toxml()
def test_content_mathml_tuples():
mml_1 = mp._print([2])
assert mml_1.nodeName == 'list'
assert mml_1.childNodes[0].nodeName == 'cn'
assert len(mml_1.childNodes) == 1
mml_2 = mp._print([2, Integer(1)])
assert mml_2.nodeName == 'list'
assert mml_2.childNodes[0].nodeName == 'cn'
assert mml_2.childNodes[1].nodeName == 'cn'
assert len(mml_2.childNodes) == 2
def test_content_mathml_add():
mml = mp._print(x**5 - x**4 + x)
assert mml.childNodes[0].nodeName == 'plus'
assert mml.childNodes[1].childNodes[0].nodeName == 'minus'
assert mml.childNodes[1].childNodes[1].nodeName == 'apply'
def test_content_mathml_Rational():
mml_1 = mp._print(Rational(1, 1))
"""should just return a number"""
assert mml_1.nodeName == 'cn'
mml_2 = mp._print(Rational(2, 5))
assert mml_2.childNodes[0].nodeName == 'divide'
def test_content_mathml_constants():
mml = mp._print(I)
assert mml.nodeName == 'imaginaryi'
mml = mp._print(E)
assert mml.nodeName == 'exponentiale'
mml = mp._print(oo)
assert mml.nodeName == 'infinity'
mml = mp._print(pi)
assert mml.nodeName == 'pi'
assert mathml(GoldenRatio) == '<cn>φ</cn>'
mml = mathml(EulerGamma)
assert mml == '<eulergamma/>'
mml = mathml(EmptySet())
assert mml == '<emptyset/>'
mml = mathml(S.true)
assert mml == '<true/>'
mml = mathml(S.false)
assert mml == '<false/>'
mml = mathml(S.NaN)
assert mml == '<notanumber/>'
def test_content_mathml_trig():
mml = mp._print(sin(x))
assert mml.childNodes[0].nodeName == 'sin'
mml = mp._print(cos(x))
assert mml.childNodes[0].nodeName == 'cos'
mml = mp._print(tan(x))
assert mml.childNodes[0].nodeName == 'tan'
mml = mp._print(cot(x))
assert mml.childNodes[0].nodeName == 'cot'
mml = mp._print(csc(x))
assert mml.childNodes[0].nodeName == 'csc'
mml = mp._print(sec(x))
assert mml.childNodes[0].nodeName == 'sec'
mml = mp._print(asin(x))
assert mml.childNodes[0].nodeName == 'arcsin'
mml = mp._print(acos(x))
assert mml.childNodes[0].nodeName == 'arccos'
mml = mp._print(atan(x))
assert mml.childNodes[0].nodeName == 'arctan'
mml = mp._print(acot(x))
assert mml.childNodes[0].nodeName == 'arccot'
mml = mp._print(acsc(x))
assert mml.childNodes[0].nodeName == 'arccsc'
mml = mp._print(asec(x))
assert mml.childNodes[0].nodeName == 'arcsec'
mml = mp._print(sinh(x))
assert mml.childNodes[0].nodeName == 'sinh'
mml = mp._print(cosh(x))
assert mml.childNodes[0].nodeName == 'cosh'
mml = mp._print(tanh(x))
assert mml.childNodes[0].nodeName == 'tanh'
mml = mp._print(coth(x))
assert mml.childNodes[0].nodeName == 'coth'
mml = mp._print(csch(x))
assert mml.childNodes[0].nodeName == 'csch'
mml = mp._print(sech(x))
assert mml.childNodes[0].nodeName == 'sech'
mml = mp._print(asinh(x))
assert mml.childNodes[0].nodeName == 'arcsinh'
mml = mp._print(atanh(x))
assert mml.childNodes[0].nodeName == 'arctanh'
mml = mp._print(acosh(x))
assert mml.childNodes[0].nodeName == 'arccosh'
mml = mp._print(acoth(x))
assert mml.childNodes[0].nodeName == 'arccoth'
mml = mp._print(acsch(x))
assert mml.childNodes[0].nodeName == 'arccsch'
mml = mp._print(asech(x))
assert mml.childNodes[0].nodeName == 'arcsech'
def test_content_mathml_relational():
mml_1 = mp._print(Eq(x, 1))
assert mml_1.nodeName == 'apply'
assert mml_1.childNodes[0].nodeName == 'eq'
assert mml_1.childNodes[1].nodeName == 'ci'
assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x'
assert mml_1.childNodes[2].nodeName == 'cn'
assert mml_1.childNodes[2].childNodes[0].nodeValue == '1'
mml_2 = mp._print(Ne(1, x))
assert mml_2.nodeName == 'apply'
assert mml_2.childNodes[0].nodeName == 'neq'
assert mml_2.childNodes[1].nodeName == 'cn'
assert mml_2.childNodes[1].childNodes[0].nodeValue == '1'
assert mml_2.childNodes[2].nodeName == 'ci'
assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x'
mml_3 = mp._print(Ge(1, x))
assert mml_3.nodeName == 'apply'
assert mml_3.childNodes[0].nodeName == 'geq'
assert mml_3.childNodes[1].nodeName == 'cn'
assert mml_3.childNodes[1].childNodes[0].nodeValue == '1'
assert mml_3.childNodes[2].nodeName == 'ci'
assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x'
mml_4 = mp._print(Lt(1, x))
assert mml_4.nodeName == 'apply'
assert mml_4.childNodes[0].nodeName == 'lt'
assert mml_4.childNodes[1].nodeName == 'cn'
assert mml_4.childNodes[1].childNodes[0].nodeValue == '1'
assert mml_4.childNodes[2].nodeName == 'ci'
assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x'
def test_content_symbol():
mml = mp._print(x)
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeValue == 'x'
del mml
mml = mp._print(Symbol("x^2"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msup'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
del mml
mml = mp._print(Symbol("x__2"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msup'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
del mml
mml = mp._print(Symbol("x_2"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msub'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
del mml
mml = mp._print(Symbol("x^3_2"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msubsup'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3'
del mml
mml = mp._print(Symbol("x__3_2"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msubsup'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3'
del mml
mml = mp._print(Symbol("x_2_a"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msub'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[
0].nodeValue == '2'
assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo'
assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[
0].nodeValue == ' '
assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[
0].nodeValue == 'a'
del mml
mml = mp._print(Symbol("x^2^a"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msup'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[
0].nodeValue == '2'
assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo'
assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[
0].nodeValue == ' '
assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[
0].nodeValue == 'a'
del mml
mml = mp._print(Symbol("x__2__a"))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeName == 'mml:msup'
assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[
0].nodeValue == '2'
assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo'
assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[
0].nodeValue == ' '
assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi'
assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[
0].nodeValue == 'a'
del mml
def test_content_mathml_greek():
mml = mp._print(Symbol('alpha'))
assert mml.nodeName == 'ci'
assert mml.childNodes[0].nodeValue == u'\N{GREEK SMALL LETTER ALPHA}'
assert mp.doprint(Symbol('alpha')) == '<ci>α</ci>'
assert mp.doprint(Symbol('beta')) == '<ci>β</ci>'
assert mp.doprint(Symbol('gamma')) == '<ci>γ</ci>'
assert mp.doprint(Symbol('delta')) == '<ci>δ</ci>'
assert mp.doprint(Symbol('epsilon')) == '<ci>ε</ci>'
assert mp.doprint(Symbol('zeta')) == '<ci>ζ</ci>'
assert mp.doprint(Symbol('eta')) == '<ci>η</ci>'
assert mp.doprint(Symbol('theta')) == '<ci>θ</ci>'
assert mp.doprint(Symbol('iota')) == '<ci>ι</ci>'
assert mp.doprint(Symbol('kappa')) == '<ci>κ</ci>'
assert mp.doprint(Symbol('lambda')) == '<ci>λ</ci>'
assert mp.doprint(Symbol('mu')) == '<ci>μ</ci>'
assert mp.doprint(Symbol('nu')) == '<ci>ν</ci>'
assert mp.doprint(Symbol('xi')) == '<ci>ξ</ci>'
assert mp.doprint(Symbol('omicron')) == '<ci>ο</ci>'
assert mp.doprint(Symbol('pi')) == '<ci>π</ci>'
assert mp.doprint(Symbol('rho')) == '<ci>ρ</ci>'
assert mp.doprint(Symbol('varsigma')) == '<ci>ς</ci>'
assert mp.doprint(Symbol('sigma')) == '<ci>σ</ci>'
assert mp.doprint(Symbol('tau')) == '<ci>τ</ci>'
assert mp.doprint(Symbol('upsilon')) == '<ci>υ</ci>'
assert mp.doprint(Symbol('phi')) == '<ci>φ</ci>'
assert mp.doprint(Symbol('chi')) == '<ci>χ</ci>'
assert mp.doprint(Symbol('psi')) == '<ci>ψ</ci>'
assert mp.doprint(Symbol('omega')) == '<ci>ω</ci>'
assert mp.doprint(Symbol('Alpha')) == '<ci>Α</ci>'
assert mp.doprint(Symbol('Beta')) == '<ci>Β</ci>'
assert mp.doprint(Symbol('Gamma')) == '<ci>Γ</ci>'
assert mp.doprint(Symbol('Delta')) == '<ci>Δ</ci>'
assert mp.doprint(Symbol('Epsilon')) == '<ci>Ε</ci>'
assert mp.doprint(Symbol('Zeta')) == '<ci>Ζ</ci>'
assert mp.doprint(Symbol('Eta')) == '<ci>Η</ci>'
assert mp.doprint(Symbol('Theta')) == '<ci>Θ</ci>'
assert mp.doprint(Symbol('Iota')) == '<ci>Ι</ci>'
assert mp.doprint(Symbol('Kappa')) == '<ci>Κ</ci>'
assert mp.doprint(Symbol('Lambda')) == '<ci>Λ</ci>'
assert mp.doprint(Symbol('Mu')) == '<ci>Μ</ci>'
assert mp.doprint(Symbol('Nu')) == '<ci>Ν</ci>'
assert mp.doprint(Symbol('Xi')) == '<ci>Ξ</ci>'
assert mp.doprint(Symbol('Omicron')) == '<ci>Ο</ci>'
assert mp.doprint(Symbol('Pi')) == '<ci>Π</ci>'
assert mp.doprint(Symbol('Rho')) == '<ci>Ρ</ci>'
assert mp.doprint(Symbol('Sigma')) == '<ci>Σ</ci>'
assert mp.doprint(Symbol('Tau')) == '<ci>Τ</ci>'
assert mp.doprint(Symbol('Upsilon')) == '<ci>Υ</ci>'
assert mp.doprint(Symbol('Phi')) == '<ci>Φ</ci>'
assert mp.doprint(Symbol('Chi')) == '<ci>Χ</ci>'
assert mp.doprint(Symbol('Psi')) == '<ci>Ψ</ci>'
assert mp.doprint(Symbol('Omega')) == '<ci>Ω</ci>'
def test_content_mathml_order():
expr = x**3 + x**2*y + 3*x*y**3 + y**4
mp = MathMLContentPrinter({'order': 'lex'})
mml = mp._print(expr)
assert mml.childNodes[1].childNodes[0].nodeName == 'power'
assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'x'
assert mml.childNodes[1].childNodes[2].childNodes[0].data == '3'
assert mml.childNodes[4].childNodes[0].nodeName == 'power'
assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'y'
assert mml.childNodes[4].childNodes[2].childNodes[0].data == '4'
mp = MathMLContentPrinter({'order': 'rev-lex'})
mml = mp._print(expr)
assert mml.childNodes[1].childNodes[0].nodeName == 'power'
assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'y'
assert mml.childNodes[1].childNodes[2].childNodes[0].data == '4'
assert mml.childNodes[4].childNodes[0].nodeName == 'power'
assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'x'
assert mml.childNodes[4].childNodes[2].childNodes[0].data == '3'
def test_content_settings():
raises(TypeError, lambda: mathml(x, method="garbage"))
def test_content_mathml_logic():
assert mathml(And(x, y)) == '<apply><and/><ci>x</ci><ci>y</ci></apply>'
assert mathml(Or(x, y)) == '<apply><or/><ci>x</ci><ci>y</ci></apply>'
assert mathml(Xor(x, y)) == '<apply><xor/><ci>x</ci><ci>y</ci></apply>'
assert mathml(Implies(x, y)) == '<apply><implies/><ci>x</ci><ci>y</ci></apply>'
assert mathml(Not(x)) == '<apply><not/><ci>x</ci></apply>'
def test_presentation_printmethod():
assert mpp.doprint(1 + x) == '<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>'
assert mpp.doprint(x**2) == '<msup><mi>x</mi><mn>2</mn></msup>'
assert mpp.doprint(x**-1) == '<mfrac><mn>1</mn><mi>x</mi></mfrac>'
assert mpp.doprint(x**-2) == \
'<mfrac><mn>1</mn><msup><mi>x</mi><mn>2</mn></msup></mfrac>'
assert mpp.doprint(2*x) == \
'<mrow><mn>2</mn><mo>⁢</mo><mi>x</mi></mrow>'
def test_presentation_mathml_core():
mml_1 = mpp._print(1 + x)
assert mml_1.nodeName == 'mrow'
nodes = mml_1.childNodes
assert len(nodes) == 3
assert nodes[0].nodeName in ['mi', 'mn']
assert nodes[1].nodeName == 'mo'
if nodes[0].nodeName == 'mn':
assert nodes[0].childNodes[0].nodeValue == '1'
assert nodes[2].childNodes[0].nodeValue == 'x'
else:
assert nodes[0].childNodes[0].nodeValue == 'x'
assert nodes[2].childNodes[0].nodeValue == '1'
mml_2 = mpp._print(x**2)
assert mml_2.nodeName == 'msup'
nodes = mml_2.childNodes
assert nodes[0].childNodes[0].nodeValue == 'x'
assert nodes[1].childNodes[0].nodeValue == '2'
mml_3 = mpp._print(2*x)
assert mml_3.nodeName == 'mrow'
nodes = mml_3.childNodes
assert nodes[0].childNodes[0].nodeValue == '2'
assert nodes[1].childNodes[0].nodeValue == '⁢'
assert nodes[2].childNodes[0].nodeValue == 'x'
mml = mpp._print(Float(1.0, 2)*x)
assert mml.nodeName == 'mrow'
nodes = mml.childNodes
assert nodes[0].childNodes[0].nodeValue == '1.0'
assert nodes[1].childNodes[0].nodeValue == '⁢'
assert nodes[2].childNodes[0].nodeValue == 'x'
def test_presentation_mathml_functions():
mml_1 = mpp._print(sin(x))
assert mml_1.childNodes[0].childNodes[0
].nodeValue == 'sin'
assert mml_1.childNodes[1].childNodes[0
].childNodes[0].nodeValue == 'x'
mml_2 = mpp._print(diff(sin(x), x, evaluate=False))
assert mml_2.nodeName == 'mrow'
assert mml_2.childNodes[0].childNodes[0
].childNodes[0].childNodes[0].nodeValue == 'ⅆ'
assert mml_2.childNodes[1].childNodes[1
].nodeName == 'mfenced'
assert mml_2.childNodes[0].childNodes[1
].childNodes[0].childNodes[0].nodeValue == 'ⅆ'
mml_3 = mpp._print(diff(cos(x*y), x, evaluate=False))
assert mml_3.childNodes[0].nodeName == 'mfrac'
assert mml_3.childNodes[0].childNodes[0
].childNodes[0].childNodes[0].nodeValue == '∂'
assert mml_3.childNodes[1].childNodes[0
].childNodes[0].nodeValue == 'cos'
def test_print_derivative():
f = Function('f')
d = Derivative(f(x, y, z), x, z, x, z, z, y)
assert mathml(d) == \
'<apply><partialdiff/><bvar><ci>y</ci><ci>z</ci><degree><cn>2</cn></degree><ci>x</ci><ci>z</ci><ci>x</ci></bvar><apply><f/><ci>x</ci><ci>y</ci><ci>z</ci></apply></apply>'
assert mathml(d, printer='presentation') == \
'<mrow><mfrac><mrow><msup><mo>∂</mo><mn>6</mn></msup></mrow><mrow><mo>∂</mo><mi>y</mi><msup><mo>∂</mo><mn>2</mn></msup><mi>z</mi><mo>∂</mo><mi>x</mi><mo>∂</mo><mi>z</mi><mo>∂</mo><mi>x</mi></mrow></mfrac><mrow><mi>f</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow></mrow>'
def test_presentation_mathml_limits():
lim_fun = sin(x)/x
mml_1 = mpp._print(Limit(lim_fun, x, 0))
assert mml_1.childNodes[0].nodeName == 'munder'
assert mml_1.childNodes[0].childNodes[0
].childNodes[0].nodeValue == 'lim'
assert mml_1.childNodes[0].childNodes[1
].childNodes[0].childNodes[0
].nodeValue == 'x'
assert mml_1.childNodes[0].childNodes[1
].childNodes[1].childNodes[0
].nodeValue == '→'
assert mml_1.childNodes[0].childNodes[1
].childNodes[2].childNodes[0
].nodeValue == '0'
def test_presentation_mathml_integrals():
assert mpp.doprint(Integral(x, (x, 0, 1))) == \
'<mrow><msubsup><mo>∫</mo><mn>0</mn><mn>1</mn></msubsup>'\
'<mi>x</mi><mo>ⅆ</mo><mi>x</mi></mrow>'
assert mpp.doprint(Integral(log(x), x)) == \
'<mrow><mo>∫</mo><mrow><mi>log</mi><mfenced><mi>x</mi>'\
'</mfenced></mrow><mo>ⅆ</mo><mi>x</mi></mrow>'
assert mpp.doprint(Integral(x*y, x, y)) == \
'<mrow><mo>∬</mo><mrow><mi>x</mi><mo>⁢</mo>'\
'<mi>y</mi></mrow><mo>ⅆ</mo><mi>y</mi><mo>ⅆ</mo><mi>x</mi></mrow>'
z, w = symbols('z w')
assert mpp.doprint(Integral(x*y*z, x, y, z)) == \
'<mrow><mo>∭</mo><mrow><mi>x</mi><mo>⁢</mo>'\
'<mi>y</mi><mo>⁢</mo><mi>z</mi></mrow><mo>ⅆ</mo>'\
'<mi>z</mi><mo>ⅆ</mo><mi>y</mi><mo>ⅆ</mo><mi>x</mi></mrow>'
assert mpp.doprint(Integral(x*y*z*w, x, y, z, w)) == \
'<mrow><mo>∫</mo><mo>∫</mo><mo>∫</mo>'\
'<mo>∫</mo><mrow><mi>w</mi><mo>⁢</mo>'\
'<mi>x</mi><mo>⁢</mo><mi>y</mi>'\
'<mo>⁢</mo><mi>z</mi></mrow><mo>ⅆ</mo><mi>w</mi>'\
'<mo>ⅆ</mo><mi>z</mi><mo>ⅆ</mo><mi>y</mi><mo>ⅆ</mo><mi>x</mi></mrow>'
assert mpp.doprint(Integral(x, x, y, (z, 0, 1))) == \
'<mrow><msubsup><mo>∫</mo><mn>0</mn><mn>1</mn></msubsup>'\
'<mo>∫</mo><mo>∫</mo><mi>x</mi><mo>ⅆ</mo><mi>z</mi>'\
'<mo>ⅆ</mo><mi>y</mi><mo>ⅆ</mo><mi>x</mi></mrow>'
assert mpp.doprint(Integral(x, (x, 0))) == \
'<mrow><msup><mo>∫</mo><mn>0</mn></msup><mi>x</mi><mo>ⅆ</mo>'\
'<mi>x</mi></mrow>'
def test_presentation_mathml_matrices():
A = Matrix([1, 2, 3])
B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]])
mll_1 = mpp._print(A)
assert mll_1.childNodes[0].nodeName == 'mtable'
assert mll_1.childNodes[0].childNodes[0].nodeName == 'mtr'
assert len(mll_1.childNodes[0].childNodes) == 3
assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd'
assert len(mll_1.childNodes[0].childNodes[0].childNodes) == 1
assert mll_1.childNodes[0].childNodes[0].childNodes[0
].childNodes[0].childNodes[0].nodeValue == '1'
assert mll_1.childNodes[0].childNodes[1].childNodes[0
].childNodes[0].childNodes[0].nodeValue == '2'
assert mll_1.childNodes[0].childNodes[2].childNodes[0
].childNodes[0].childNodes[0].nodeValue == '3'
mll_2 = mpp._print(B)
assert mll_2.childNodes[0].nodeName == 'mtable'
assert mll_2.childNodes[0].childNodes[0].nodeName == 'mtr'
assert len(mll_2.childNodes[0].childNodes) == 3
assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd'
assert len(mll_2.childNodes[0].childNodes[0].childNodes) == 3
assert mll_2.childNodes[0].childNodes[0].childNodes[0
].childNodes[0].childNodes[0].nodeValue == '0'
assert mll_2.childNodes[0].childNodes[0].childNodes[1
].childNodes[0].childNodes[0].nodeValue == '5'
assert mll_2.childNodes[0].childNodes[0].childNodes[2
].childNodes[0].childNodes[0].nodeValue == '4'
assert mll_2.childNodes[0].childNodes[1].childNodes[0
].childNodes[0].childNodes[0].nodeValue == '2'
assert mll_2.childNodes[0].childNodes[1].childNodes[1
].childNodes[0].childNodes[0].nodeValue == '3'
assert mll_2.childNodes[0].childNodes[1].childNodes[2
].childNodes[0].childNodes[0].nodeValue == '1'
assert mll_2.childNodes[0].childNodes[2].childNodes[0
].childNodes[0].childNodes[0].nodeValue == '9'
assert mll_2.childNodes[0].childNodes[2].childNodes[1
].childNodes[0].childNodes[0].nodeValue == '7'
assert mll_2.childNodes[0].childNodes[2].childNodes[2
].childNodes[0].childNodes[0].nodeValue == '9'
def test_presentation_mathml_sums():
summand = x
mml_1 = mpp._print(Sum(summand, (x, 1, 10)))
assert mml_1.childNodes[0].nodeName == 'munderover'
assert len(mml_1.childNodes[0].childNodes) == 3
assert mml_1.childNodes[0].childNodes[0].childNodes[0
].nodeValue == '∑'
assert len(mml_1.childNodes[0].childNodes[1].childNodes) == 3
assert mml_1.childNodes[0].childNodes[2].childNodes[0
].nodeValue == '10'
assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x'
def test_presentation_mathml_add():
mml = mpp._print(x**5 - x**4 + x)
assert len(mml.childNodes) == 5
assert mml.childNodes[0].childNodes[0].childNodes[0
].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].childNodes[0
].nodeValue == '5'
assert mml.childNodes[1].childNodes[0].nodeValue == '-'
assert mml.childNodes[2].childNodes[0].childNodes[0
].nodeValue == 'x'
assert mml.childNodes[2].childNodes[1].childNodes[0
].nodeValue == '4'
assert mml.childNodes[3].childNodes[0].nodeValue == '+'
assert mml.childNodes[4].childNodes[0].nodeValue == 'x'
def test_presentation_mathml_Rational():
mml_1 = mpp._print(Rational(1, 1))
assert mml_1.nodeName == 'mn'
mml_2 = mpp._print(Rational(2, 5))
assert mml_2.nodeName == 'mfrac'
assert mml_2.childNodes[0].childNodes[0].nodeValue == '2'
assert mml_2.childNodes[1].childNodes[0].nodeValue == '5'
def test_presentation_mathml_constants():
mml = mpp._print(I)
assert mml.childNodes[0].nodeValue == 'ⅈ'
mml = mpp._print(E)
assert mml.childNodes[0].nodeValue == 'ⅇ'
mml = mpp._print(oo)
assert mml.childNodes[0].nodeValue == '∞'
mml = mpp._print(pi)
assert mml.childNodes[0].nodeValue == 'π'
assert mathml(GoldenRatio, printer='presentation') == '<mi>Φ</mi>'
assert mathml(zoo, printer='presentation') == \
'<mover><mo>∞</mo><mo>~</mo></mover>'
assert mathml(S.NaN, printer='presentation') == '<mi>NaN</mi>'
def test_presentation_mathml_trig():
mml = mpp._print(sin(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'sin'
mml = mpp._print(cos(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'cos'
mml = mpp._print(tan(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'tan'
mml = mpp._print(asin(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsin'
mml = mpp._print(acos(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'arccos'
mml = mpp._print(atan(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'arctan'
mml = mpp._print(sinh(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'sinh'
mml = mpp._print(cosh(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'cosh'
mml = mpp._print(tanh(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'tanh'
mml = mpp._print(asinh(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsinh'
mml = mpp._print(atanh(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'arctanh'
mml = mpp._print(acosh(x))
assert mml.childNodes[0].childNodes[0].nodeValue == 'arccosh'
def test_presentation_mathml_relational():
mml_1 = mpp._print(Eq(x, 1))
assert len(mml_1.childNodes) == 3
assert mml_1.childNodes[0].nodeName == 'mi'
assert mml_1.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml_1.childNodes[1].nodeName == 'mo'
assert mml_1.childNodes[1].childNodes[0].nodeValue == '='
assert mml_1.childNodes[2].nodeName == 'mn'
assert mml_1.childNodes[2].childNodes[0].nodeValue == '1'
mml_2 = mpp._print(Ne(1, x))
assert len(mml_2.childNodes) == 3
assert mml_2.childNodes[0].nodeName == 'mn'
assert mml_2.childNodes[0].childNodes[0].nodeValue == '1'
assert mml_2.childNodes[1].nodeName == 'mo'
assert mml_2.childNodes[1].childNodes[0].nodeValue == '≠'
assert mml_2.childNodes[2].nodeName == 'mi'
assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x'
mml_3 = mpp._print(Ge(1, x))
assert len(mml_3.childNodes) == 3
assert mml_3.childNodes[0].nodeName == 'mn'
assert mml_3.childNodes[0].childNodes[0].nodeValue == '1'
assert mml_3.childNodes[1].nodeName == 'mo'
assert mml_3.childNodes[1].childNodes[0].nodeValue == '≥'
assert mml_3.childNodes[2].nodeName == 'mi'
assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x'
mml_4 = mpp._print(Lt(1, x))
assert len(mml_4.childNodes) == 3
assert mml_4.childNodes[0].nodeName == 'mn'
assert mml_4.childNodes[0].childNodes[0].nodeValue == '1'
assert mml_4.childNodes[1].nodeName == 'mo'
assert mml_4.childNodes[1].childNodes[0].nodeValue == '<'
assert mml_4.childNodes[2].nodeName == 'mi'
assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x'
def test_presentation_symbol():
mml = mpp._print(x)
assert mml.nodeName == 'mi'
assert mml.childNodes[0].nodeValue == 'x'
del mml
mml = mpp._print(Symbol("x^2"))
assert mml.nodeName == 'msup'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].nodeValue == '2'
del mml
mml = mpp._print(Symbol("x__2"))
assert mml.nodeName == 'msup'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].nodeValue == '2'
del mml
mml = mpp._print(Symbol("x_2"))
assert mml.nodeName == 'msub'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].nodeValue == '2'
del mml
mml = mpp._print(Symbol("x^3_2"))
assert mml.nodeName == 'msubsup'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].nodeValue == '2'
assert mml.childNodes[2].nodeName == 'mi'
assert mml.childNodes[2].childNodes[0].nodeValue == '3'
del mml
mml = mpp._print(Symbol("x__3_2"))
assert mml.nodeName == 'msubsup'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].nodeValue == '2'
assert mml.childNodes[2].nodeName == 'mi'
assert mml.childNodes[2].childNodes[0].nodeValue == '3'
del mml
mml = mpp._print(Symbol("x_2_a"))
assert mml.nodeName == 'msub'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mrow'
assert mml.childNodes[1].childNodes[0].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
assert mml.childNodes[1].childNodes[1].nodeName == 'mo'
assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' '
assert mml.childNodes[1].childNodes[2].nodeName == 'mi'
assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a'
del mml
mml = mpp._print(Symbol("x^2^a"))
assert mml.nodeName == 'msup'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mrow'
assert mml.childNodes[1].childNodes[0].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
assert mml.childNodes[1].childNodes[1].nodeName == 'mo'
assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' '
assert mml.childNodes[1].childNodes[2].nodeName == 'mi'
assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a'
del mml
mml = mpp._print(Symbol("x__2__a"))
assert mml.nodeName == 'msup'
assert mml.childNodes[0].nodeName == 'mi'
assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[1].nodeName == 'mrow'
assert mml.childNodes[1].childNodes[0].nodeName == 'mi'
assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
assert mml.childNodes[1].childNodes[1].nodeName == 'mo'
assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' '
assert mml.childNodes[1].childNodes[2].nodeName == 'mi'
assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a'
del mml
def test_presentation_mathml_greek():
mml = mpp._print(Symbol('alpha'))
assert mml.nodeName == 'mi'
assert mml.childNodes[0].nodeValue == u'\N{GREEK SMALL LETTER ALPHA}'
assert mpp.doprint(Symbol('alpha')) == '<mi>α</mi>'
assert mpp.doprint(Symbol('beta')) == '<mi>β</mi>'
assert mpp.doprint(Symbol('gamma')) == '<mi>γ</mi>'
assert mpp.doprint(Symbol('delta')) == '<mi>δ</mi>'
assert mpp.doprint(Symbol('epsilon')) == '<mi>ε</mi>'
assert mpp.doprint(Symbol('zeta')) == '<mi>ζ</mi>'
assert mpp.doprint(Symbol('eta')) == '<mi>η</mi>'
assert mpp.doprint(Symbol('theta')) == '<mi>θ</mi>'
assert mpp.doprint(Symbol('iota')) == '<mi>ι</mi>'
assert mpp.doprint(Symbol('kappa')) == '<mi>κ</mi>'
assert mpp.doprint(Symbol('lambda')) == '<mi>λ</mi>'
assert mpp.doprint(Symbol('mu')) == '<mi>μ</mi>'
assert mpp.doprint(Symbol('nu')) == '<mi>ν</mi>'
assert mpp.doprint(Symbol('xi')) == '<mi>ξ</mi>'
assert mpp.doprint(Symbol('omicron')) == '<mi>ο</mi>'
assert mpp.doprint(Symbol('pi')) == '<mi>π</mi>'
assert mpp.doprint(Symbol('rho')) == '<mi>ρ</mi>'
assert mpp.doprint(Symbol('varsigma')) == '<mi>ς</mi>'
assert mpp.doprint(Symbol('sigma')) == '<mi>σ</mi>'
assert mpp.doprint(Symbol('tau')) == '<mi>τ</mi>'
assert mpp.doprint(Symbol('upsilon')) == '<mi>υ</mi>'
assert mpp.doprint(Symbol('phi')) == '<mi>φ</mi>'
assert mpp.doprint(Symbol('chi')) == '<mi>χ</mi>'
assert mpp.doprint(Symbol('psi')) == '<mi>ψ</mi>'
assert mpp.doprint(Symbol('omega')) == '<mi>ω</mi>'
assert mpp.doprint(Symbol('Alpha')) == '<mi>Α</mi>'
assert mpp.doprint(Symbol('Beta')) == '<mi>Β</mi>'
assert mpp.doprint(Symbol('Gamma')) == '<mi>Γ</mi>'
assert mpp.doprint(Symbol('Delta')) == '<mi>Δ</mi>'
assert mpp.doprint(Symbol('Epsilon')) == '<mi>Ε</mi>'
assert mpp.doprint(Symbol('Zeta')) == '<mi>Ζ</mi>'
assert mpp.doprint(Symbol('Eta')) == '<mi>Η</mi>'
assert mpp.doprint(Symbol('Theta')) == '<mi>Θ</mi>'
assert mpp.doprint(Symbol('Iota')) == '<mi>Ι</mi>'
assert mpp.doprint(Symbol('Kappa')) == '<mi>Κ</mi>'
assert mpp.doprint(Symbol('Lambda')) == '<mi>Λ</mi>'
assert mpp.doprint(Symbol('Mu')) == '<mi>Μ</mi>'
assert mpp.doprint(Symbol('Nu')) == '<mi>Ν</mi>'
assert mpp.doprint(Symbol('Xi')) == '<mi>Ξ</mi>'
assert mpp.doprint(Symbol('Omicron')) == '<mi>Ο</mi>'
assert mpp.doprint(Symbol('Pi')) == '<mi>Π</mi>'
assert mpp.doprint(Symbol('Rho')) == '<mi>Ρ</mi>'
assert mpp.doprint(Symbol('Sigma')) == '<mi>Σ</mi>'
assert mpp.doprint(Symbol('Tau')) == '<mi>Τ</mi>'
assert mpp.doprint(Symbol('Upsilon')) == '<mi>Υ</mi>'
assert mpp.doprint(Symbol('Phi')) == '<mi>Φ</mi>'
assert mpp.doprint(Symbol('Chi')) == '<mi>Χ</mi>'
assert mpp.doprint(Symbol('Psi')) == '<mi>Ψ</mi>'
assert mpp.doprint(Symbol('Omega')) == '<mi>Ω</mi>'
def test_presentation_mathml_order():
expr = x**3 + x**2*y + 3*x*y**3 + y**4
mp = MathMLPresentationPrinter({'order': 'lex'})
mml = mp._print(expr)
assert mml.childNodes[0].nodeName == 'msup'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '3'
assert mml.childNodes[6].nodeName == 'msup'
assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'y'
assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '4'
mp = MathMLPresentationPrinter({'order': 'rev-lex'})
mml = mp._print(expr)
assert mml.childNodes[0].nodeName == 'msup'
assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'y'
assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '4'
assert mml.childNodes[6].nodeName == 'msup'
assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'x'
assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '3'
def test_print_intervals():
a = Symbol('a', real=True)
assert mpp.doprint(Interval(0, a)) == \
'<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>'
assert mpp.doprint(Interval(0, a, False, False)) == \
'<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>'
assert mpp.doprint(Interval(0, a, True, False)) == \
'<mrow><mfenced close="]" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>'
assert mpp.doprint(Interval(0, a, False, True)) == \
'<mrow><mfenced close=")" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>'
assert mpp.doprint(Interval(0, a, True, True)) == \
'<mrow><mfenced close=")" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>'
def test_print_tuples():
assert mpp.doprint(Tuple(0,)) == \
'<mrow><mfenced><mn>0</mn></mfenced></mrow>'
assert mpp.doprint(Tuple(0, a)) == \
'<mrow><mfenced><mn>0</mn><mi>a</mi></mfenced></mrow>'
assert mpp.doprint(Tuple(0, a, a)) == \
'<mrow><mfenced><mn>0</mn><mi>a</mi><mi>a</mi></mfenced></mrow>'
assert mpp.doprint(Tuple(0, 1, 2, 3, 4)) == \
'<mrow><mfenced><mn>0</mn><mn>1</mn><mn>2</mn><mn>3</mn><mn>4</mn></mfenced></mrow>'
assert mpp.doprint(Tuple(0, 1, Tuple(2, 3, 4))) == \
'<mrow><mfenced><mn>0</mn><mn>1</mn><mrow><mfenced><mn>2</mn><mn>3'\
'</mn><mn>4</mn></mfenced></mrow></mfenced></mrow>'
def test_print_re_im():
assert mpp.doprint(re(x)) == \
'<mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(im(x)) == \
'<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(re(x + 1)) == \
'<mrow><mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi>'\
'</mfenced></mrow><mo>+</mo><mn>1</mn></mrow>'
assert mpp.doprint(im(x + 1)) == \
'<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_Abs():
assert mpp.doprint(Abs(x)) == \
'<mrow><mfenced close="|" open="|"><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(Abs(x + 1)) == \
'<mrow><mfenced close="|" open="|"><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced></mrow>'
def test_print_Determinant():
assert mpp.doprint(Determinant(Matrix([[1, 2], [3, 4]]))) == \
'<mrow><mfenced close="|" open="|"><mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced></mfenced></mrow>'
def test_presentation_settings():
raises(TypeError, lambda: mathml(x, printer='presentation',
method="garbage"))
def test_toprettyxml_hooking():
# test that the patch doesn't influence the behavior of the standard
# library
import xml.dom.minidom
doc1 = xml.dom.minidom.parseString(
"<apply><plus/><ci>x</ci><cn>1</cn></apply>")
doc2 = xml.dom.minidom.parseString(
"<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>")
prettyxml_old1 = doc1.toprettyxml()
prettyxml_old2 = doc2.toprettyxml()
mp.apply_patch()
mp.restore_patch()
assert prettyxml_old1 == doc1.toprettyxml()
assert prettyxml_old2 == doc2.toprettyxml()
def test_print_domains():
from sympy import Complexes, Integers, Naturals, Naturals0, Reals
assert mpp.doprint(Complexes) == '<mi mathvariant="normal">ℂ</mi>'
assert mpp.doprint(Integers) == '<mi mathvariant="normal">ℤ</mi>'
assert mpp.doprint(Naturals) == '<mi mathvariant="normal">ℕ</mi>'
assert mpp.doprint(Naturals0) == \
'<msub><mi mathvariant="normal">ℕ</mi><mn>0</mn></msub>'
assert mpp.doprint(Reals) == '<mi mathvariant="normal">ℝ</mi>'
def test_print_expression_with_minus():
assert mpp.doprint(-x) == '<mrow><mo>-</mo><mi>x</mi></mrow>'
assert mpp.doprint(-x/y) == \
'<mrow><mo>-</mo><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow>'
assert mpp.doprint(-Rational(1, 2)) == \
'<mrow><mo>-</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow>'
def test_print_AssocOp():
from sympy.core.operations import AssocOp
class TestAssocOp(AssocOp):
identity = 0
expr = TestAssocOp(1, 2)
mpp.doprint(expr) == \
'<mrow><mi>testassocop</mi><mn>2</mn><mn>1</mn></mrow>'
def test_print_basic():
expr = Basic(1, 2)
assert mpp.doprint(expr) == \
'<mrow><mi>basic</mi><mfenced><mn>1</mn><mn>2</mn></mfenced></mrow>'
assert mp.doprint(expr) == '<basic><cn>1</cn><cn>2</cn></basic>'
def test_mat_delim_print():
expr = Matrix([[1, 2], [3, 4]])
assert mathml(expr, printer='presentation', mat_delim='[') == \
'<mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd>'\
'<mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn>'\
'</mtd></mtr></mtable></mfenced>'
assert mathml(expr, printer='presentation', mat_delim='(') == \
'<mfenced><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd>'\
'</mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced>'
assert mathml(expr, printer='presentation', mat_delim='') == \
'<mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr>'\
'<mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable>'
def test_ln_notation_print():
expr = log(x)
assert mathml(expr, printer='presentation') == \
'<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mathml(expr, printer='presentation', ln_notation=False) == \
'<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mathml(expr, printer='presentation', ln_notation=True) == \
'<mrow><mi>ln</mi><mfenced><mi>x</mi></mfenced></mrow>'
def test_mul_symbol_print():
expr = x * y
assert mathml(expr, printer='presentation') == \
'<mrow><mi>x</mi><mo>⁢</mo><mi>y</mi></mrow>'
assert mathml(expr, printer='presentation', mul_symbol=None) == \
'<mrow><mi>x</mi><mo>⁢</mo><mi>y</mi></mrow>'
assert mathml(expr, printer='presentation', mul_symbol='dot') == \
'<mrow><mi>x</mi><mo>·</mo><mi>y</mi></mrow>'
assert mathml(expr, printer='presentation', mul_symbol='ldot') == \
'<mrow><mi>x</mi><mo>․</mo><mi>y</mi></mrow>'
assert mathml(expr, printer='presentation', mul_symbol='times') == \
'<mrow><mi>x</mi><mo>×</mo><mi>y</mi></mrow>'
def test_print_lerchphi():
assert mpp.doprint(lerchphi(1, 2, 3)) == \
'<mrow><mi>Φ</mi><mfenced><mn>1</mn><mn>2</mn><mn>3</mn></mfenced></mrow>'
def test_print_polylog():
assert mp.doprint(polylog(x, y)) == \
'<apply><polylog/><ci>x</ci><ci>y</ci></apply>'
assert mpp.doprint(polylog(x, y)) == \
'<mrow><msub><mi>Li</mi><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>'
def test_print_set_frozenset():
f = frozenset({1, 5, 3})
assert mpp.doprint(f) == \
'<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mn>5</mn></mfenced>'
s = set({1, 2, 3})
assert mpp.doprint(s) == \
'<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>'
def test_print_FiniteSet():
f1 = FiniteSet(x, 1, 3)
assert mpp.doprint(f1) == \
'<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi></mfenced>'
def test_print_LambertW():
assert mpp.doprint(LambertW(x)) == '<mrow><mi>W</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(LambertW(x, y)) == '<mrow><mi>W</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'
def test_print_EmptySet():
assert mpp.doprint(EmptySet()) == '<mo>∅</mo>'
def test_print_UniversalSet():
assert mpp.doprint(S.UniversalSet) == '<mo>𝕌</mo>'
def test_print_spaces():
assert mpp.doprint(HilbertSpace()) == '<mi>ℋ</mi>'
assert mpp.doprint(ComplexSpace(2)) == '<msup>𝒞<mn>2</mn></msup>'
assert mpp.doprint(FockSpace()) == '<mi>ℱ</mi>'
def test_print_constants():
assert mpp.doprint(hbar) == '<mi>ℏ</mi>'
assert mpp.doprint(TribonacciConstant) == '<mi>TribonacciConstant</mi>'
assert mpp.doprint(EulerGamma) == '<mi>γ</mi>'
def test_print_Contains():
assert mpp.doprint(Contains(x, S.Naturals)) == \
'<mrow><mi>x</mi><mo>∈</mo><mi mathvariant="normal">ℕ</mi></mrow>'
def test_print_Dagger():
assert mpp.doprint(Dagger(x)) == '<msup><mi>x</mi>†</msup>'
def test_print_SetOp():
f1 = FiniteSet(x, 1, 3)
f2 = FiniteSet(y, 2, 4)
assert mpp.doprint(Union(f1, f2, evaluate=False)) == \
'<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\
'</mfenced><mo>∪</mo><mfenced close="}" open="{"><mn>2</mn>'\
'<mn>4</mn><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(Intersection(f1, f2, evaluate=False)) == \
'<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\
'</mfenced><mo>∩</mo><mfenced close="}" open="{"><mn>2</mn>'\
'<mn>4</mn><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(Complement(f1, f2, evaluate=False)) == \
'<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\
'</mfenced><mo>∖</mo><mfenced close="}" open="{"><mn>2</mn>'\
'<mn>4</mn><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(SymmetricDifference(f1, f2, evaluate=False)) == \
'<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\
'</mfenced><mo>∆</mo><mfenced close="}" open="{"><mn>2</mn>'\
'<mn>4</mn><mi>y</mi></mfenced></mrow>'
def test_print_logic():
assert mpp.doprint(And(x, y)) == \
'<mrow><mi>x</mi><mo>∧</mo><mi>y</mi></mrow>'
assert mpp.doprint(Or(x, y)) == \
'<mrow><mi>x</mi><mo>∨</mo><mi>y</mi></mrow>'
assert mpp.doprint(Xor(x, y)) == \
'<mrow><mi>x</mi><mo>⊻</mo><mi>y</mi></mrow>'
assert mpp.doprint(Implies(x, y)) == \
'<mrow><mi>x</mi><mo>⇒</mo><mi>y</mi></mrow>'
assert mpp.doprint(Equivalent(x, y)) == \
'<mrow><mi>x</mi><mo>⇔</mo><mi>y</mi></mrow>'
assert mpp.doprint(And(Eq(x, y), x > 4)) == \
'<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>∧</mo>'\
'<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>'
assert mpp.doprint(And(Eq(x, 3), y < 3, x > y + 1)) == \
'<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>∧</mo>'\
'<mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo><mn>1</mn></mrow>'\
'</mrow><mo>∧</mo><mrow><mi>y</mi><mo><</mo><mn>3</mn></mrow></mrow>'
assert mpp.doprint(Or(Eq(x, y), x > 4)) == \
'<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>∨</mo>'\
'<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>'
assert mpp.doprint(And(Eq(x, 3), Or(y < 3, x > y + 1))) == \
'<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>∧</mo>'\
'<mfenced><mrow><mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo>'\
'<mn>1</mn></mrow></mrow><mo>∨</mo><mrow><mi>y</mi><mo><</mo>'\
'<mn>3</mn></mrow></mrow></mfenced></mrow>'
assert mpp.doprint(Not(x)) == '<mrow><mo>¬</mo><mi>x</mi></mrow>'
assert mpp.doprint(Not(And(x, y))) == \
'<mrow><mo>¬</mo><mfenced><mrow><mi>x</mi><mo>∧</mo>'\
'<mi>y</mi></mrow></mfenced></mrow>'
def test_root_notation_print():
assert mathml(x**(S.One/3), printer='presentation') == \
'<mroot><mi>x</mi><mn>3</mn></mroot>'
assert mathml(x**(S.One/3), printer='presentation', root_notation=False) ==\
'<msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup>'
assert mathml(x**(S.One/3), printer='content') == \
'<apply><root/><degree><ci>3</ci></degree><ci>x</ci></apply>'
assert mathml(x**(S.One/3), printer='content', root_notation=False) == \
'<apply><power/><ci>x</ci><apply><divide/><cn>1</cn><cn>3</cn></apply></apply>'
assert mathml(x**(Rational(-1, 3)), printer='presentation') == \
'<mfrac><mn>1</mn><mroot><mi>x</mi><mn>3</mn></mroot></mfrac>'
assert mathml(x**(Rational(-1, 3)), printer='presentation', root_notation=False) \
== '<mfrac><mn>1</mn><msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup></mfrac>'
def test_fold_frac_powers_print():
expr = x ** Rational(5, 2)
assert mathml(expr, printer='presentation') == \
'<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>'
assert mathml(expr, printer='presentation', fold_frac_powers=True) == \
'<msup><mi>x</mi><mfrac bevelled="true"><mn>5</mn><mn>2</mn></mfrac></msup>'
assert mathml(expr, printer='presentation', fold_frac_powers=False) == \
'<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>'
def test_fold_short_frac_print():
expr = Rational(2, 5)
assert mathml(expr, printer='presentation') == \
'<mfrac><mn>2</mn><mn>5</mn></mfrac>'
assert mathml(expr, printer='presentation', fold_short_frac=True) == \
'<mfrac bevelled="true"><mn>2</mn><mn>5</mn></mfrac>'
assert mathml(expr, printer='presentation', fold_short_frac=False) == \
'<mfrac><mn>2</mn><mn>5</mn></mfrac>'
def test_print_factorials():
assert mpp.doprint(factorial(x)) == '<mrow><mi>x</mi><mo>!</mo></mrow>'
assert mpp.doprint(factorial(x + 1)) == \
'<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!</mo></mrow>'
assert mpp.doprint(factorial2(x)) == '<mrow><mi>x</mi><mo>!!</mo></mrow>'
assert mpp.doprint(factorial2(x + 1)) == \
'<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!!</mo></mrow>'
assert mpp.doprint(binomial(x, y)) == \
'<mfenced><mfrac linethickness="0"><mi>x</mi><mi>y</mi></mfrac></mfenced>'
assert mpp.doprint(binomial(4, x + y)) == \
'<mfenced><mfrac linethickness="0"><mn>4</mn><mrow><mi>x</mi>'\
'<mo>+</mo><mi>y</mi></mrow></mfrac></mfenced>'
def test_print_floor():
expr = floor(x)
assert mathml(expr, printer='presentation') == \
'<mrow><mfenced close="⌋" open="⌊"><mi>x</mi></mfenced></mrow>'
def test_print_ceiling():
expr = ceiling(x)
assert mathml(expr, printer='presentation') == \
'<mrow><mfenced close="⌉" open="⌈"><mi>x</mi></mfenced></mrow>'
def test_print_Lambda():
expr = Lambda(x, x+1)
assert mathml(expr, printer='presentation') == \
'<mfenced><mrow><mi>x</mi><mo>↦</mo><mrow><mi>x</mi><mo>+</mo>'\
'<mn>1</mn></mrow></mrow></mfenced>'
expr = Lambda((x, y), x + y)
assert mathml(expr, printer='presentation') == \
'<mfenced><mrow><mrow><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'\
'<mo>↦</mo><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow></mrow></mfenced>'
def test_print_conjugate():
assert mpp.doprint(conjugate(x)) == \
'<menclose notation="top"><mi>x</mi></menclose>'
assert mpp.doprint(conjugate(x + 1)) == \
'<mrow><menclose notation="top"><mi>x</mi></menclose><mo>+</mo><mn>1</mn></mrow>'
def test_print_AccumBounds():
a = Symbol('a', real=True)
assert mpp.doprint(AccumBounds(0, 1)) == '<mfenced close="⟩" open="⟨"><mn>0</mn><mn>1</mn></mfenced>'
assert mpp.doprint(AccumBounds(0, a)) == '<mfenced close="⟩" open="⟨"><mn>0</mn><mi>a</mi></mfenced>'
assert mpp.doprint(AccumBounds(a + 1, a + 2)) == '<mfenced close="⟩" open="⟨"><mrow><mi>a</mi><mo>+</mo><mn>1</mn></mrow><mrow><mi>a</mi><mo>+</mo><mn>2</mn></mrow></mfenced>'
def test_print_Float():
assert mpp.doprint(Float(1e100)) == '<mrow><mn>1.0</mn><mo>·</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>'
assert mpp.doprint(Float(1e-100)) == '<mrow><mn>1.0</mn><mo>·</mo><msup><mn>10</mn><mn>-100</mn></msup></mrow>'
assert mpp.doprint(Float(-1e100)) == '<mrow><mn>-1.0</mn><mo>·</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>'
assert mpp.doprint(Float(1.0*oo)) == '<mi>∞</mi>'
assert mpp.doprint(Float(-1.0*oo)) == '<mrow><mo>-</mo><mi>∞</mi></mrow>'
def test_print_different_functions():
assert mpp.doprint(gamma(x)) == '<mrow><mi>Γ</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(lowergamma(x, y)) == '<mrow><mi>γ</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(uppergamma(x, y)) == '<mrow><mi>Γ</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(zeta(x)) == '<mrow><mi>ζ</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(zeta(x, y)) == '<mrow><mi>ζ</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(dirichlet_eta(x)) == '<mrow><mi>η</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(elliptic_k(x)) == '<mrow><mi>Κ</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(totient(x)) == '<mrow><mi>ϕ</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(reduced_totient(x)) == '<mrow><mi>λ</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(primenu(x)) == '<mrow><mi>ν</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(primeomega(x)) == '<mrow><mi>Ω</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(fresnels(x)) == '<mrow><mi>S</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(fresnelc(x)) == '<mrow><mi>C</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mpp.doprint(Heaviside(x)) == '<mrow><mi>Θ</mi><mfenced><mi>x</mi></mfenced></mrow>'
def test_mathml_builtins():
assert mpp.doprint(None) == '<mi>None</mi>'
assert mpp.doprint(true) == '<mi>True</mi>'
assert mpp.doprint(false) == '<mi>False</mi>'
def test_mathml_Range():
assert mpp.doprint(Range(1, 51)) == \
'<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mi>…</mi><mn>50</mn></mfenced>'
assert mpp.doprint(Range(1, 4)) == \
'<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>'
assert mpp.doprint(Range(0, 3, 1)) == \
'<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mn>2</mn></mfenced>'
assert mpp.doprint(Range(0, 30, 1)) == \
'<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mi>…</mi><mn>29</mn></mfenced>'
assert mpp.doprint(Range(30, 1, -1)) == \
'<mfenced close="}" open="{"><mn>30</mn><mn>29</mn><mi>…</mi>'\
'<mn>2</mn></mfenced>'
assert mpp.doprint(Range(0, oo, 2)) == \
'<mfenced close="}" open="{"><mn>0</mn><mn>2</mn><mi>…</mi></mfenced>'
assert mpp.doprint(Range(oo, -2, -2)) == \
'<mfenced close="}" open="{"><mi>…</mi><mn>2</mn><mn>0</mn></mfenced>'
assert mpp.doprint(Range(-2, -oo, -1)) == \
'<mfenced close="}" open="{"><mn>-2</mn><mn>-3</mn><mi>…</mi></mfenced>'
def test_print_exp():
assert mpp.doprint(exp(x)) == \
'<msup><mi>ⅇ</mi><mi>x</mi></msup>'
assert mpp.doprint(exp(1) + exp(2)) == \
'<mrow><mi>ⅇ</mi><mo>+</mo><msup><mi>ⅇ</mi><mn>2</mn></msup></mrow>'
def test_print_MinMax():
assert mpp.doprint(Min(x, y)) == \
'<mrow><mo>min</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(Min(x, 2, x**3)) == \
'<mrow><mo>min</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\
'<mn>3</mn></msup></mfenced></mrow>'
assert mpp.doprint(Max(x, y)) == \
'<mrow><mo>max</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'
assert mpp.doprint(Max(x, 2, x**3)) == \
'<mrow><mo>max</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\
'<mn>3</mn></msup></mfenced></mrow>'
def test_mathml_presentation_numbers():
n = Symbol('n')
assert mathml(catalan(n), printer='presentation') == \
'<msub><mi>C</mi><mi>n</mi></msub>'
assert mathml(bernoulli(n), printer='presentation') == \
'<msub><mi>B</mi><mi>n</mi></msub>'
assert mathml(bell(n), printer='presentation') == \
'<msub><mi>B</mi><mi>n</mi></msub>'
assert mathml(euler(n), printer='presentation') == \
'<msub><mi>E</mi><mi>n</mi></msub>'
assert mathml(fibonacci(n), printer='presentation') == \
'<msub><mi>F</mi><mi>n</mi></msub>'
assert mathml(lucas(n), printer='presentation') == \
'<msub><mi>L</mi><mi>n</mi></msub>'
assert mathml(tribonacci(n), printer='presentation') == \
'<msub><mi>T</mi><mi>n</mi></msub>'
assert mathml(bernoulli(n, x), printer='presentation') == \
'<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
assert mathml(bell(n, x), printer='presentation') == \
'<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
assert mathml(euler(n, x), printer='presentation') == \
'<mrow><msub><mi>E</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
assert mathml(fibonacci(n, x), printer='presentation') == \
'<mrow><msub><mi>F</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
assert mathml(tribonacci(n, x), printer='presentation') == \
'<mrow><msub><mi>T</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
def test_mathml_presentation_mathieu():
assert mathml(mathieuc(x, y, z), printer='presentation') == \
'<mrow><mi>C</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>'
assert mathml(mathieus(x, y, z), printer='presentation') == \
'<mrow><mi>S</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>'
assert mathml(mathieucprime(x, y, z), printer='presentation') == \
'<mrow><mi>C′</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>'
assert mathml(mathieusprime(x, y, z), printer='presentation') == \
'<mrow><mi>S′</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>'
def test_mathml_presentation_stieltjes():
assert mathml(stieltjes(n), printer='presentation') == \
'<msub><mi>γ</mi><mi>n</mi></msub>'
assert mathml(stieltjes(n, x), printer='presentation') == \
'<mrow><msub><mi>γ</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_matrix_symbol():
A = MatrixSymbol('A', 1, 2)
assert mpp.doprint(A) == '<mi>A</mi>'
assert mp.doprint(A) == '<ci>A</ci>'
assert mathml(A, printer='presentation', mat_symbol_style="bold") == \
'<mi mathvariant="bold">A</mi>'
# No effect in content printer
assert mathml(A, mat_symbol_style="bold") == '<ci>A</ci>'
def test_print_hadamard():
from sympy.matrices.expressions import HadamardProduct
from sympy.matrices.expressions import Transpose
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert mathml(HadamardProduct(X, Y*Y), printer="presentation") == \
'<mrow>' \
'<mi>X</mi>' \
'<mo>∘</mo>' \
'<msup><mi>Y</mi><mn>2</mn></msup>' \
'</mrow>'
assert mathml(HadamardProduct(X, Y)*Y, printer="presentation") == \
'<mrow>' \
'<mfenced>' \
'<mrow><mi>X</mi><mo>∘</mo><mi>Y</mi></mrow>' \
'</mfenced>' \
'<mo>⁢</mo><mi>Y</mi>' \
'</mrow>'
assert mathml(HadamardProduct(X, Y, Y), printer="presentation") == \
'<mrow>' \
'<mi>X</mi><mo>∘</mo>' \
'<mi>Y</mi><mo>∘</mo>' \
'<mi>Y</mi>' \
'</mrow>'
assert mathml(
Transpose(HadamardProduct(X, Y)), printer="presentation") == \
'<msup>' \
'<mfenced>' \
'<mrow><mi>X</mi><mo>∘</mo><mi>Y</mi></mrow>' \
'</mfenced>' \
'<mo>T</mo>' \
'</msup>'
def test_print_random_symbol():
R = RandomSymbol(Symbol('R'))
assert mpp.doprint(R) == '<mi>R</mi>'
assert mp.doprint(R) == '<ci>R</ci>'
def test_print_IndexedBase():
assert mathml(IndexedBase(a)[b], printer='presentation') == \
'<msub><mi>a</mi><mi>b</mi></msub>'
assert mathml(IndexedBase(a)[b, c, d], printer='presentation') == \
'<msub><mi>a</mi><mfenced><mi>b</mi><mi>c</mi><mi>d</mi></mfenced></msub>'
assert mathml(IndexedBase(a)[b]*IndexedBase(c)[d]*IndexedBase(e),
printer='presentation') == \
'<mrow><msub><mi>a</mi><mi>b</mi></msub><mo>⁢'\
'</mo><msub><mi>c</mi><mi>d</mi></msub><mo>⁢</mo><mi>e</mi></mrow>'
def test_print_Indexed():
assert mathml(IndexedBase(a), printer='presentation') == '<mi>a</mi>'
assert mathml(IndexedBase(a/b), printer='presentation') == \
'<mrow><mfrac><mi>a</mi><mi>b</mi></mfrac></mrow>'
assert mathml(IndexedBase((a, b)), printer='presentation') == \
'<mrow><mfenced><mi>a</mi><mi>b</mi></mfenced></mrow>'
def test_print_MatrixElement():
i, j = symbols('i j')
A = MatrixSymbol('A', i, j)
assert mathml(A[0,0],printer = 'presentation') == \
'<msub><mi>A</mi><mfenced close="" open=""><mn>0</mn><mn>0</mn></mfenced></msub>'
assert mathml(A[i,j], printer = 'presentation') == \
'<msub><mi>A</mi><mfenced close="" open=""><mi>i</mi><mi>j</mi></mfenced></msub>'
assert mathml(A[i*j,0], printer = 'presentation') == \
'<msub><mi>A</mi><mfenced close="" open=""><mrow><mi>i</mi><mo>⁢</mo><mi>j</mi></mrow><mn>0</mn></mfenced></msub>'
def test_print_Vector():
ACS = CoordSys3D('A')
assert mathml(Cross(ACS.i, ACS.j*ACS.x*3 + ACS.k), printer='presentation') == \
'<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>×</mo><mfenced><mrow>'\
'<mfenced><mrow><mn>3</mn><mo>⁢</mo><msub>'\
'<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\
'</mrow></mfenced><mo>⁢</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\
'<mi mathvariant="bold">k</mi><mo>^</mo></mover><mi mathvariant="bold">'\
'A</mi></msub></mrow></mfenced></mrow>'
assert mathml(Cross(ACS.i, ACS.j), printer='presentation') == \
'<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>×</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow>'
assert mathml(x*Cross(ACS.i, ACS.j), printer='presentation') == \
'<mrow><mi>x</mi><mo>⁢</mo><mfenced><mrow><msub><mover>'\
'<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>×</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(Cross(x*ACS.i, ACS.j), printer='presentation') == \
'<mrow><mo>-</mo><mrow><msub><mover><mi mathvariant="bold">j</mi>'\
'<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub>'\
'<mo>×</mo><mfenced><mrow><mfenced><mi>x</mi></mfenced>'\
'<mo>⁢</mo><msub><mover><mi mathvariant="bold">i</mi>'\
'<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\
'</mfenced></mrow></mrow>'
assert mathml(Curl(3*ACS.x*ACS.j), printer='presentation') == \
'<mrow><mo>∇</mo><mo>×</mo><mfenced><mrow><mfenced><mrow>'\
'<mn>3</mn><mo>⁢</mo><msub>'\
'<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\
'</mrow></mfenced><mo>⁢</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(Curl(3*x*ACS.x*ACS.j), printer='presentation') == \
'<mrow><mo>∇</mo><mo>×</mo><mfenced><mrow><mfenced><mrow>'\
'<mn>3</mn><mo>⁢</mo><msub><mi mathvariant="bold">x'\
'</mi><mi mathvariant="bold">A</mi></msub><mo>⁢</mo>'\
'<mi>x</mi></mrow></mfenced><mo>⁢</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(x*Curl(3*ACS.x*ACS.j), printer='presentation') == \
'<mrow><mi>x</mi><mo>⁢</mo><mfenced><mrow><mo>∇</mo>'\
'<mo>×</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\
'<mo>⁢</mo><msub><mi mathvariant="bold">x</mi>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\
'<mo>⁢</mo><msub><mover><mi mathvariant="bold">j</mi>'\
'<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\
'</mfenced></mrow></mfenced></mrow>'
assert mathml(Curl(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \
'<mrow><mo>∇</mo><mo>×</mo><mfenced><mrow><msub><mover>'\
'<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\
'<mn>3</mn><mo>⁢</mo><msub><mi mathvariant="bold">x'\
'</mi><mi mathvariant="bold">A</mi></msub><mo>⁢</mo>'\
'<mi>x</mi></mrow></mfenced><mo>⁢</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(Divergence(3*ACS.x*ACS.j), printer='presentation') == \
'<mrow><mo>∇</mo><mo>·</mo><mfenced><mrow><mfenced><mrow>'\
'<mn>3</mn><mo>⁢</mo><msub><mi mathvariant="bold">x'\
'</mi><mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\
'<mo>⁢</mo><msub><mover><mi mathvariant="bold">j</mi>'\
'<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(x*Divergence(3*ACS.x*ACS.j), printer='presentation') == \
'<mrow><mi>x</mi><mo>⁢</mo><mfenced><mrow><mo>∇</mo>'\
'<mo>·</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\
'<mo>⁢</mo><msub><mi mathvariant="bold">x</mi>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\
'<mo>⁢</mo><msub><mover><mi mathvariant="bold">j</mi>'\
'<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\
'</mfenced></mrow></mfenced></mrow>'
assert mathml(Divergence(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \
'<mrow><mo>∇</mo><mo>·</mo><mfenced><mrow><msub><mover>'\
'<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\
'<mn>3</mn><mo>⁢</mo><msub>'\
'<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\
'<mo>⁢</mo><mi>x</mi></mrow></mfenced>'\
'<mo>⁢</mo><msub><mover><mi mathvariant="bold">j</mi>'\
'<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(Dot(ACS.i, ACS.j*ACS.x*3+ACS.k), printer='presentation') == \
'<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>·</mo><mfenced><mrow>'\
'<mfenced><mrow><mn>3</mn><mo>⁢</mo><msub>'\
'<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\
'</mrow></mfenced><mo>⁢</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\
'<mi mathvariant="bold">k</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(Dot(ACS.i, ACS.j), printer='presentation') == \
'<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>·</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow>'
assert mathml(Dot(x*ACS.i, ACS.j), printer='presentation') == \
'<mrow><msub><mover><mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>·</mo><mfenced><mrow>'\
'<mfenced><mi>x</mi></mfenced><mo>⁢</mo><msub><mover>'\
'<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(x*Dot(ACS.i, ACS.j), printer='presentation') == \
'<mrow><mi>x</mi><mo>⁢</mo><mfenced><mrow><msub><mover>'\
'<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub><mo>·</mo><msub><mover>'\
'<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>'
assert mathml(Gradient(ACS.x), printer='presentation') == \
'<mrow><mo>∇</mo><msub><mi mathvariant="bold">x</mi>'\
'<mi mathvariant="bold">A</mi></msub></mrow>'
assert mathml(Gradient(ACS.x + 3*ACS.y), printer='presentation') == \
'<mrow><mo>∇</mo><mfenced><mrow><msub><mi mathvariant="bold">'\
'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\
'<mo>⁢</mo><msub><mi mathvariant="bold">y</mi>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>'
assert mathml(x*Gradient(ACS.x), printer='presentation') == \
'<mrow><mi>x</mi><mo>⁢</mo><mfenced><mrow><mo>∇</mo>'\
'<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\
'</msub></mrow></mfenced></mrow>'
assert mathml(Gradient(x*ACS.x), printer='presentation') == \
'<mrow><mo>∇</mo><mfenced><mrow><msub><mi mathvariant="bold">'\
'x</mi><mi mathvariant="bold">A</mi></msub><mo>⁢</mo>'\
'<mi>x</mi></mrow></mfenced></mrow>'
assert mathml(Cross(ACS.x, ACS.z) + Cross(ACS.z, ACS.x), printer='presentation') == \
'<mover><mi mathvariant="bold">0</mi><mo>^</mo></mover>'
assert mathml(Cross(ACS.z, ACS.x), printer='presentation') == \
'<mrow><mo>-</mo><mrow><msub><mi mathvariant="bold">x</mi>'\
'<mi mathvariant="bold">A</mi></msub><mo>×</mo><msub>'\
'<mi mathvariant="bold">z</mi><mi mathvariant="bold">A</mi></msub></mrow></mrow>'
assert mathml(Laplacian(ACS.x), printer='presentation') == \
'<mrow><mo>∆</mo><msub><mi mathvariant="bold">x</mi>'\
'<mi mathvariant="bold">A</mi></msub></mrow>'
assert mathml(Laplacian(ACS.x + 3*ACS.y), printer='presentation') == \
'<mrow><mo>∆</mo><mfenced><mrow><msub><mi mathvariant="bold">'\
'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\
'<mo>⁢</mo><msub><mi mathvariant="bold">y</mi>'\
'<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>'
assert mathml(x*Laplacian(ACS.x), printer='presentation') == \
'<mrow><mi>x</mi><mo>⁢</mo><mfenced><mrow><mo>∆</mo>'\
'<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\
'</msub></mrow></mfenced></mrow>'
assert mathml(Laplacian(x*ACS.x), printer='presentation') == \
'<mrow><mo>∆</mo><mfenced><mrow><msub><mi mathvariant="bold">'\
'x</mi><mi mathvariant="bold">A</mi></msub><mo>⁢</mo>'\
'<mi>x</mi></mrow></mfenced></mrow>'
def test_print_elliptic_f():
assert mathml(elliptic_f(x, y), printer = 'presentation') == \
'<mrow><mi>𝖥</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>'
assert mathml(elliptic_f(x/y, y), printer = 'presentation') == \
'<mrow><mi>𝖥</mi><mfenced separators="|"><mrow><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow><mi>y</mi></mfenced></mrow>'
def test_print_elliptic_e():
assert mathml(elliptic_e(x), printer = 'presentation') == \
'<mrow><mi>𝖤</mi><mfenced separators="|"><mi>x</mi></mfenced></mrow>'
assert mathml(elliptic_e(x, y), printer = 'presentation') == \
'<mrow><mi>𝖤</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>'
def test_print_elliptic_pi():
assert mathml(elliptic_pi(x, y), printer = 'presentation') == \
'<mrow><mi>𝛱</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>'
assert mathml(elliptic_pi(x, y, z), printer = 'presentation') == \
'<mrow><mi>𝛱</mi><mfenced separators=";|"><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>'
def test_print_Ei():
assert mathml(Ei(x), printer = 'presentation') == \
'<mrow><mi>Ei</mi><mfenced><mi>x</mi></mfenced></mrow>'
assert mathml(Ei(x**y), printer = 'presentation') == \
'<mrow><mi>Ei</mi><mfenced><msup><mi>x</mi><mi>y</mi></msup></mfenced></mrow>'
def test_print_expint():
assert mathml(expint(x, y), printer = 'presentation') == \
'<mrow><msub><mo>E</mo><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>'
assert mathml(expint(IndexedBase(x)[1], IndexedBase(x)[2]), printer = 'presentation') == \
'<mrow><msub><mo>E</mo><msub><mi>x</mi><mn>1</mn></msub></msub><mfenced><msub><mi>x</mi><mn>2</mn></msub></mfenced></mrow>'
def test_print_jacobi():
assert mathml(jacobi(n, a, b, x), printer = 'presentation') == \
'<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi><mi>b</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_gegenbauer():
assert mathml(gegenbauer(n, a, x), printer = 'presentation') == \
'<mrow><msubsup><mo>C</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_chebyshevt():
assert mathml(chebyshevt(n, x), printer = 'presentation') == \
'<mrow><msub><mo>T</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_chebyshevu():
assert mathml(chebyshevu(n, x), printer = 'presentation') == \
'<mrow><msub><mo>U</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_legendre():
assert mathml(legendre(n, x), printer = 'presentation') == \
'<mrow><msub><mo>P</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_assoc_legendre():
assert mathml(assoc_legendre(n, a, x), printer = 'presentation') == \
'<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_laguerre():
assert mathml(laguerre(n, x), printer = 'presentation') == \
'<mrow><msub><mo>L</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_assoc_laguerre():
assert mathml(assoc_laguerre(n, a, x), printer = 'presentation') == \
'<mrow><msubsup><mo>L</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>'
def test_print_hermite():
assert mathml(hermite(n, x), printer = 'presentation') == \
'<mrow><msub><mo>H</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>'
def test_mathml_SingularityFunction():
assert mathml(SingularityFunction(x, 4, 5), printer='presentation') == \
'<msup><mfenced close="⟩" open="⟨"><mrow><mi>x</mi>' \
'<mo>-</mo><mn>4</mn></mrow></mfenced><mn>5</mn></msup>'
assert mathml(SingularityFunction(x, -3, 4), printer='presentation') == \
'<msup><mfenced close="⟩" open="⟨"><mrow><mi>x</mi>' \
'<mo>+</mo><mn>3</mn></mrow></mfenced><mn>4</mn></msup>'
assert mathml(SingularityFunction(x, 0, 4), printer='presentation') == \
'<msup><mfenced close="⟩" open="⟨"><mi>x</mi></mfenced>' \
'<mn>4</mn></msup>'
assert mathml(SingularityFunction(x, a, n), printer='presentation') == \
'<msup><mfenced close="⟩" open="⟨"><mrow><mrow>' \
'<mo>-</mo><mi>a</mi></mrow><mo>+</mo><mi>x</mi></mrow></mfenced>' \
'<mi>n</mi></msup>'
assert mathml(SingularityFunction(x, 4, -2), printer='presentation') == \
'<msup><mfenced close="⟩" open="⟨"><mrow><mi>x</mi>' \
'<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-2</mn></msup>'
assert mathml(SingularityFunction(x, 4, -1), printer='presentation') == \
'<msup><mfenced close="⟩" open="⟨"><mrow><mi>x</mi>' \
'<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-1</mn></msup>'
def test_mathml_matrix_functions():
from sympy.matrices import MatrixSymbol, Adjoint, Inverse, Transpose
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert mathml(Adjoint(X), printer='presentation') == \
'<msup><mi>X</mi><mo>†</mo></msup>'
assert mathml(Adjoint(X + Y), printer='presentation') == \
'<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>†</mo></msup>'
assert mathml(Adjoint(X) + Adjoint(Y), printer='presentation') == \
'<mrow><msup><mi>X</mi><mo>†</mo></msup><mo>+</mo><msup>' \
'<mi>Y</mi><mo>†</mo></msup></mrow>'
assert mathml(Adjoint(X*Y), printer='presentation') == \
'<msup><mfenced><mrow><mi>X</mi><mo>⁢</mo>' \
'<mi>Y</mi></mrow></mfenced><mo>†</mo></msup>'
assert mathml(Adjoint(Y)*Adjoint(X), printer='presentation') == \
'<mrow><msup><mi>Y</mi><mo>†</mo></msup><mo>⁢' \
'</mo><msup><mi>X</mi><mo>†</mo></msup></mrow>'
assert mathml(Adjoint(X**2), printer='presentation') == \
'<msup><mfenced><msup><mi>X</mi><mn>2</mn></msup></mfenced><mo>†</mo></msup>'
assert mathml(Adjoint(X)**2, printer='presentation') == \
'<msup><mfenced><msup><mi>X</mi><mo>†</mo></msup></mfenced><mn>2</mn></msup>'
assert mathml(Adjoint(Inverse(X)), printer='presentation') == \
'<msup><mfenced><msup><mi>X</mi><mn>-1</mn></msup></mfenced><mo>†</mo></msup>'
assert mathml(Inverse(Adjoint(X)), printer='presentation') == \
'<msup><mfenced><msup><mi>X</mi><mo>†</mo></msup></mfenced><mn>-1</mn></msup>'
assert mathml(Adjoint(Transpose(X)), printer='presentation') == \
'<msup><mfenced><msup><mi>X</mi><mo>T</mo></msup></mfenced><mo>†</mo></msup>'
assert mathml(Transpose(Adjoint(X)), printer='presentation') == \
'<msup><mfenced><msup><mi>X</mi><mo>†</mo></msup></mfenced><mo>T</mo></msup>'
assert mathml(Transpose(Adjoint(X) + Y), printer='presentation') == \
'<msup><mfenced><mrow><msup><mi>X</mi><mo>†</mo></msup>' \
'<mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>'
assert mathml(Transpose(X), printer='presentation') == \
'<msup><mi>X</mi><mo>T</mo></msup>'
assert mathml(Transpose(X + Y), printer='presentation') == \
'<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>'
def test_mathml_special_matrices():
from sympy.matrices import Identity, ZeroMatrix, OneMatrix
assert mathml(Identity(4), printer='presentation') == '<mi>𝕀</mi>'
assert mathml(ZeroMatrix(2, 2), printer='presentation') == '<mn>𝟘</mn>'
assert mathml(OneMatrix(2, 2), printer='presentation') == '<mn>𝟙</mn>'
def test_mathml_piecewise():
from sympy import Piecewise
# Content MathML
assert mathml(Piecewise((x, x <= 1), (x**2, True))) == \
'<piecewise><piece><ci>x</ci><apply><leq/><ci>x</ci><cn>1</cn></apply></piece><otherwise><apply><power/><ci>x</ci><cn>2</cn></apply></otherwise></piecewise>'
raises(ValueError, lambda: mathml(Piecewise((x, x <= 1))))
|
4f89f367b6e636e372bd322888bcff015a47a22db7c72127ff8b2ca555b65840 | from sympy.core import (pi, oo, symbols, Rational, Integer, GoldenRatio,
EulerGamma, Catalan, Lambda, Dummy, S, Eq, Ne, Le,
Lt, Gt, Ge)
from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
sinh, cosh, tanh, asin, acos, acosh, Max, Min)
from sympy.utilities.pytest import raises
from sympy.printing.jscode import JavascriptCodePrinter
from sympy.utilities.lambdify import implemented_function
from sympy.tensor import IndexedBase, Idx
from sympy.matrices import Matrix, MatrixSymbol
from sympy import jscode
x, y, z = symbols('x,y,z')
def test_printmethod():
assert jscode(Abs(x)) == "Math.abs(x)"
def test_jscode_sqrt():
assert jscode(sqrt(x)) == "Math.sqrt(x)"
assert jscode(x**0.5) == "Math.sqrt(x)"
assert jscode(x**(S.One/3)) == "Math.cbrt(x)"
def test_jscode_Pow():
g = implemented_function('g', Lambda(x, 2*x))
assert jscode(x**3) == "Math.pow(x, 3)"
assert jscode(x**(y**3)) == "Math.pow(x, Math.pow(y, 3))"
assert jscode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
"Math.pow(3.5*2*x, -x + Math.pow(y, x))/(Math.pow(x, 2) + y)"
assert jscode(x**-1.0) == '1/x'
def test_jscode_constants_mathh():
assert jscode(exp(1)) == "Math.E"
assert jscode(pi) == "Math.PI"
assert jscode(oo) == "Number.POSITIVE_INFINITY"
assert jscode(-oo) == "Number.NEGATIVE_INFINITY"
def test_jscode_constants_other():
assert jscode(
2*GoldenRatio) == "var GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17)
assert jscode(2*Catalan) == "var Catalan = %s;\n2*Catalan" % Catalan.evalf(17)
assert jscode(
2*EulerGamma) == "var EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17)
def test_jscode_Rational():
assert jscode(Rational(3, 7)) == "3/7"
assert jscode(Rational(18, 9)) == "2"
assert jscode(Rational(3, -7)) == "-3/7"
assert jscode(Rational(-3, -7)) == "3/7"
def test_Relational():
assert jscode(Eq(x, y)) == "x == y"
assert jscode(Ne(x, y)) == "x != y"
assert jscode(Le(x, y)) == "x <= y"
assert jscode(Lt(x, y)) == "x < y"
assert jscode(Gt(x, y)) == "x > y"
assert jscode(Ge(x, y)) == "x >= y"
def test_jscode_Integer():
assert jscode(Integer(67)) == "67"
assert jscode(Integer(-1)) == "-1"
def test_jscode_functions():
assert jscode(sin(x) ** cos(x)) == "Math.pow(Math.sin(x), Math.cos(x))"
assert jscode(sinh(x) * cosh(x)) == "Math.sinh(x)*Math.cosh(x)"
assert jscode(Max(x, y) + Min(x, y)) == "Math.max(x, y) + Math.min(x, y)"
assert jscode(tanh(x)*acosh(y)) == "Math.tanh(x)*Math.acosh(y)"
assert jscode(asin(x)-acos(y)) == "-Math.acos(y) + Math.asin(x)"
def test_jscode_inline_function():
x = symbols('x')
g = implemented_function('g', Lambda(x, 2*x))
assert jscode(g(x)) == "2*x"
g = implemented_function('g', Lambda(x, 2*x/Catalan))
assert jscode(g(x)) == "var Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17)
A = IndexedBase('A')
i = Idx('i', symbols('n', integer=True))
g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
assert jscode(g(A[i]), assign_to=A[i]) == (
"for (var i=0; i<n; i++){\n"
" A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
"}"
)
def test_jscode_exceptions():
assert jscode(ceiling(x)) == "Math.ceil(x)"
assert jscode(Abs(x)) == "Math.abs(x)"
def test_jscode_boolean():
assert jscode(x & y) == "x && y"
assert jscode(x | y) == "x || y"
assert jscode(~x) == "!x"
assert jscode(x & y & z) == "x && y && z"
assert jscode(x | y | z) == "x || y || z"
assert jscode((x & y) | z) == "z || x && y"
assert jscode((x | y) & z) == "z && (x || y)"
def test_jscode_Piecewise():
expr = Piecewise((x, x < 1), (x**2, True))
p = jscode(expr)
s = \
"""\
((x < 1) ? (
x
)
: (
Math.pow(x, 2)
))\
"""
assert p == s
assert jscode(expr, assign_to="c") == (
"if (x < 1) {\n"
" c = x;\n"
"}\n"
"else {\n"
" c = Math.pow(x, 2);\n"
"}")
# 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: jscode(expr))
def test_jscode_Piecewise_deep():
p = jscode(2*Piecewise((x, x < 1), (x**2, True)))
s = \
"""\
2*((x < 1) ? (
x
)
: (
Math.pow(x, 2)
))\
"""
assert p == s
def test_jscode_settings():
raises(TypeError, lambda: jscode(sin(x), method="garbage"))
def test_jscode_Indexed():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n, m, o = symbols('n m o', integer=True)
i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
p = JavascriptCodePrinter()
p._not_c = set()
x = IndexedBase('x')[j]
assert p._print_Indexed(x) == 'x[j]'
A = IndexedBase('A')[i, j]
assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
B = IndexedBase('B')[i, j, k]
assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
assert p._not_c == set()
def test_jscode_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 (var i=0; i<m; i++){\n'
' y[i] = 0;\n'
'}\n'
'for (var i=0; i<m; i++){\n'
' for (var j=0; j<n; j++){\n'
' y[i] = A[n*i + j]*x[j] + y[i];\n'
' }\n'
'}'
)
c = jscode(A[i, j]*x[j], assign_to=y[i])
assert c == s
def test_dummy_loops():
i, m = symbols('i m', integer=True, cls=Dummy)
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx(i, m)
expected = (
'for (var i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n'
' y[i_%(icount)i] = x[i_%(icount)i];\n'
'}'
) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
code = jscode(x[i], assign_to=y[i])
assert code == expected
def test_jscode_loops_add():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
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 (var i=0; i<m; i++){\n'
' y[i] = x[i] + z[i];\n'
'}\n'
'for (var i=0; i<m; i++){\n'
' for (var j=0; j<n; j++){\n'
' y[i] = A[n*i + j]*x[j] + y[i];\n'
' }\n'
'}'
)
c = jscode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i])
assert c == s
def test_jscode_loops_multiple_contractions():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
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 (var i=0; i<m; i++){\n'
' y[i] = 0;\n'
'}\n'
'for (var i=0; i<m; i++){\n'
' for (var j=0; j<n; j++){\n'
' for (var k=0; k<o; k++){\n'
' for (var l=0; l<p; l++){\n'
' y[i] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
' }\n'
' }\n'
' }\n'
'}'
)
c = jscode(b[j, k, l]*a[i, j, k, l], assign_to=y[i])
assert c == s
def test_jscode_loops_addfactor():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
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 (var i=0; i<m; i++){\n'
' y[i] = 0;\n'
'}\n'
'for (var i=0; i<m; i++){\n'
' for (var j=0; j<n; j++){\n'
' for (var k=0; k<o; k++){\n'
' for (var l=0; l<p; l++){\n'
' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
' }\n'
' }\n'
' }\n'
'}'
)
c = jscode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
assert c == s
def test_jscode_loops_multiple_terms():
from sympy.tensor import IndexedBase, Idx
from sympy import symbols
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 (var i=0; i<m; i++){\n'
' y[i] = 0;\n'
'}\n'
)
s1 = (
'for (var i=0; i<m; i++){\n'
' for (var j=0; j<n; j++){\n'
' for (var k=0; k<o; k++){\n'
' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i*n*o + j*o + k) +\
' }\n'
' }\n'
'}\n'
)
s2 = (
'for (var i=0; i<m; i++){\n'
' for (var k=0; k<o; k++){\n'
' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\
' }\n'
'}\n'
)
s3 = (
'for (var i=0; i<m; i++){\n'
' for (var j=0; j<n; j++){\n'
' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\
' }\n'
'}\n'
)
c = jscode(
b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i])
assert (c == s0 + s1 + s2 + s3[:-1] or
c == s0 + s1 + s3 + s2[:-1] or
c == s0 + s2 + s1 + s3[:-1] or
c == s0 + s2 + s3 + s1[:-1] or
c == s0 + s3 + s1 + s2[:-1] or
c == s0 + s3 + s2 + s1[:-1])
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)
assert jscode(mat, A) == (
"A[0] = x*y;\n"
"if (y > 0) {\n"
" A[1] = x + 2;\n"
"}\n"
"else {\n"
" A[1] = y;\n"
"}\n"
"A[2] = Math.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 jscode(expr) == (
"((x > 0) ? (\n"
" 2*A[2]\n"
")\n"
": (\n"
" A[2]\n"
")) + Math.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 jscode(m, M) == (
"M[0] = Math.sin(q[1]);\n"
"M[1] = 0;\n"
"M[2] = Math.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] = Math.sqrt(q[0]) + 4;\n"
"M[8] = 0;")
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(jscode(A[0, 0]) == "A[0]")
assert(jscode(3 * A[0, 0]) == "3*A[0]")
F = C[0, 0].subs(C, A - B)
assert(jscode(F) == "(A - B)[0]")
|
61ff243bd24dfd1d2b246a6c691331286306dabf6f76baa3be7cdde9168c55c6 | 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)
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.utilities.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)
from sympy import octave_code
from sympy import 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)"
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 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)'
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)'
|
7d84e87fb3ce1613595204da76fe7e0eb215a5146367b30402cd665e264d1272 | # -*- coding: utf-8 -*-
from sympy import (
Add, And, Basic, Derivative, Dict, Eq, Equivalent, FF,
FiniteSet, Function, Ge, Gt, I, Implies, Integral, SingularityFunction,
Lambda, Le, Limit, Lt, Matrix, Mul, Nand, Ne, Nor, Not, O, Or,
Pow, Product, QQ, RR, Rational, Ray, rootof, RootSum, S,
Segment, Subs, Sum, Symbol, Tuple, Trace, Xor, ZZ, conjugate,
groebner, oo, pi, symbols, ilex, grlex, Range, Contains,
SeqPer, SeqFormula, SeqAdd, SeqMul, fourier_series, fps, ITE,
Complement, Interval, Intersection, Union, EulerGamma, GoldenRatio,
LambertW, airyai, airybi, airyaiprime, airybiprime, fresnelc, fresnels,
Heaviside, dirichlet_eta)
from sympy.codegen.ast import (Assignment, AddAugmentedAssignment,
SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment)
from sympy.core.compatibility import range, u_decode as u, PY3
from sympy.core.expr import UnevaluatedExpr
from sympy.core.trace import Tr
from sympy.functions import (Abs, Chi, Ci, Ei, KroneckerDelta,
Piecewise, Shi, Si, atan2, beta, binomial, catalan, ceiling, cos,
euler, exp, expint, factorial, factorial2, floor, gamma, hyper, log,
meijerg, sin, sqrt, subfactorial, tan, uppergamma, lerchphi,
elliptic_k, elliptic_f, elliptic_e, elliptic_pi, DiracDelta, bell,
bernoulli, fibonacci, tribonacci, lucas, stieltjes, mathieuc, mathieus,
mathieusprime, mathieucprime)
from sympy.matrices import Adjoint, Inverse, MatrixSymbol, Transpose, KroneckerProduct
from sympy.matrices.expressions import hadamard_power
from sympy.physics import mechanics
from sympy.physics.units import joule, degree
from sympy.printing.pretty import pprint, pretty as xpretty
from sympy.printing.pretty.pretty_symbology import center_accent
from sympy.sets import ImageSet
from sympy.sets.setexpr import SetExpr
from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray,
MutableDenseNDimArray, MutableSparseNDimArray, tensorproduct)
from sympy.tensor.functions import TensorProduct
from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead,
TensorElement, tensor_heads)
from sympy.utilities.pytest import raises, XFAIL
from sympy.vector import CoordSys3D, Gradient, Curl, Divergence, Dot, Cross, Laplacian
import sympy as sym
class lowergamma(sym.lowergamma):
pass # testing notation inheritance by a subclass with same name
a, b, c, d, x, y, z, k, n = symbols('a,b,c,d,x,y,z,k,n')
f = Function("f")
th = Symbol('theta')
ph = Symbol('phi')
"""
Expressions whose pretty-printing is tested here:
(A '#' to the right of an expression indicates that its various acceptable
orderings are accounted for by the tests.)
BASIC EXPRESSIONS:
oo
(x**2)
1/x
y*x**-2
x**Rational(-5,2)
(-2)**x
Pow(3, 1, evaluate=False)
(x**2 + x + 1) #
1-x #
1-2*x #
x/y
-x/y
(x+2)/y #
(1+x)*y #3
-5*x/(x+10) # correct placement of negative sign
1 - Rational(3,2)*(x+1)
-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5) # issue 5524
ORDERING:
x**2 + x + 1
1 - x
1 - 2*x
2*x**4 + y**2 - x**2 + y**3
RELATIONAL:
Eq(x, y)
Lt(x, y)
Gt(x, y)
Le(x, y)
Ge(x, y)
Ne(x/(y+1), y**2) #
RATIONAL NUMBERS:
y*x**-2
y**Rational(3,2) * x**Rational(-5,2)
sin(x)**3/tan(x)**2
FUNCTIONS (ABS, CONJ, EXP, FUNCTION BRACES, FACTORIAL, FLOOR, CEILING):
(2*x + exp(x)) #
Abs(x)
Abs(x/(x**2+1)) #
Abs(1 / (y - Abs(x)))
factorial(n)
factorial(2*n)
subfactorial(n)
subfactorial(2*n)
factorial(factorial(factorial(n)))
factorial(n+1) #
conjugate(x)
conjugate(f(x+1)) #
f(x)
f(x, y)
f(x/(y+1), y) #
f(x**x**x**x**x**x)
sin(x)**2
conjugate(a+b*I)
conjugate(exp(a+b*I))
conjugate( f(1 + conjugate(f(x))) ) #
f(x/(y+1), y) # denom of first arg
floor(1 / (y - floor(x)))
ceiling(1 / (y - ceiling(x)))
SQRT:
sqrt(2)
2**Rational(1,3)
2**Rational(1,1000)
sqrt(x**2 + 1)
(1 + sqrt(5))**Rational(1,3)
2**(1/x)
sqrt(2+pi)
(2+(1+x**2)/(2+x))**Rational(1,4)+(1+x**Rational(1,1000))/sqrt(3+x**2)
DERIVATIVES:
Derivative(log(x), x, evaluate=False)
Derivative(log(x), x, evaluate=False) + x #
Derivative(log(x) + x**2, x, y, evaluate=False)
Derivative(2*x*y, y, x, evaluate=False) + x**2 #
beta(alpha).diff(alpha)
INTEGRALS:
Integral(log(x), x)
Integral(x**2, x)
Integral((sin(x))**2 / (tan(x))**2)
Integral(x**(2**x), x)
Integral(x**2, (x,1,2))
Integral(x**2, (x,Rational(1,2),10))
Integral(x**2*y**2, x,y)
Integral(x**2, (x, None, 1))
Integral(x**2, (x, 1, None))
Integral(sin(th)/cos(ph), (th,0,pi), (ph, 0, 2*pi))
MATRICES:
Matrix([[x**2+1, 1], [y, x+y]]) #
Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]])
PIECEWISE:
Piecewise((x,x<1),(x**2,True))
ITE:
ITE(x, y, z)
SEQUENCES (TUPLES, LISTS, DICTIONARIES):
()
[]
{}
(1/x,)
[x**2, 1/x, x, y, sin(th)**2/cos(ph)**2]
(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
{x: sin(x)}
{1/x: 1/y, x: sin(x)**2} #
[x**2]
(x**2,)
{x**2: 1}
LIMITS:
Limit(x, x, oo)
Limit(x**2, x, 0)
Limit(1/x, x, 0)
Limit(sin(x)/x, x, 0)
UNITS:
joule => kg*m**2/s
SUBS:
Subs(f(x), x, ph**2)
Subs(f(x).diff(x), x, 0)
Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2)))
ORDER:
O(1)
O(1/x)
O(x**2 + y**2)
"""
def pretty(expr, order=None):
"""ASCII pretty-printing"""
return xpretty(expr, order=order, use_unicode=False, wrap_line=False)
def upretty(expr, order=None):
"""Unicode pretty-printing"""
return xpretty(expr, order=order, use_unicode=True, wrap_line=False)
def test_pretty_ascii_str():
assert pretty( 'xxx' ) == 'xxx'
assert pretty( "xxx" ) == 'xxx'
assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx'
assert pretty( 'xxx"xxx' ) == 'xxx\"xxx'
assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx'
assert pretty( "xxx'xxx" ) == 'xxx\'xxx'
assert pretty( "xxx\'xxx" ) == 'xxx\'xxx'
assert pretty( "xxx\"xxx" ) == 'xxx\"xxx'
assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx'
assert pretty( "xxx\nxxx" ) == 'xxx\nxxx'
def test_pretty_unicode_str():
assert pretty( u'xxx' ) == u'xxx'
assert pretty( u'xxx' ) == u'xxx'
assert pretty( u'xxx\'xxx' ) == u'xxx\'xxx'
assert pretty( u'xxx"xxx' ) == u'xxx\"xxx'
assert pretty( u'xxx\"xxx' ) == u'xxx\"xxx'
assert pretty( u"xxx'xxx" ) == u'xxx\'xxx'
assert pretty( u"xxx\'xxx" ) == u'xxx\'xxx'
assert pretty( u"xxx\"xxx" ) == u'xxx\"xxx'
assert pretty( u"xxx\"xxx\'xxx" ) == u'xxx"xxx\'xxx'
assert pretty( u"xxx\nxxx" ) == u'xxx\nxxx'
def test_upretty_greek():
assert upretty( oo ) == u'∞'
assert upretty( Symbol('alpha^+_1') ) == u'α⁺₁'
assert upretty( Symbol('beta') ) == u'β'
assert upretty(Symbol('lambda')) == u'λ'
def test_upretty_multiindex():
assert upretty( Symbol('beta12') ) == u'β₁₂'
assert upretty( Symbol('Y00') ) == u'Y₀₀'
assert upretty( Symbol('Y_00') ) == u'Y₀₀'
assert upretty( Symbol('F^+-') ) == u'F⁺⁻'
def test_upretty_sub_super():
assert upretty( Symbol('beta_1_2') ) == u'β₁ ₂'
assert upretty( Symbol('beta^1^2') ) == u'β¹ ²'
assert upretty( Symbol('beta_1^2') ) == u'β²₁'
assert upretty( Symbol('beta_10_20') ) == u'β₁₀ ₂₀'
assert upretty( Symbol('beta_ax_gamma^i') ) == u'βⁱₐₓ ᵧ'
assert upretty( Symbol("F^1^2_3_4") ) == u'F¹ ²₃ ₄'
assert upretty( Symbol("F_1_2^3^4") ) == u'F³ ⁴₁ ₂'
assert upretty( Symbol("F_1_2_3_4") ) == u'F₁ ₂ ₃ ₄'
assert upretty( Symbol("F^1^2^3^4") ) == u'F¹ ² ³ ⁴'
def test_upretty_subs_missing_in_24():
assert upretty( Symbol('F_beta') ) == u'Fᵦ'
assert upretty( Symbol('F_gamma') ) == u'Fᵧ'
assert upretty( Symbol('F_rho') ) == u'Fᵨ'
assert upretty( Symbol('F_phi') ) == u'Fᵩ'
assert upretty( Symbol('F_chi') ) == u'Fᵪ'
assert upretty( Symbol('F_a') ) == u'Fₐ'
assert upretty( Symbol('F_e') ) == u'Fₑ'
assert upretty( Symbol('F_i') ) == u'Fᵢ'
assert upretty( Symbol('F_o') ) == u'Fₒ'
assert upretty( Symbol('F_u') ) == u'Fᵤ'
assert upretty( Symbol('F_r') ) == u'Fᵣ'
assert upretty( Symbol('F_v') ) == u'Fᵥ'
assert upretty( Symbol('F_x') ) == u'Fₓ'
def test_missing_in_2X_issue_9047():
if PY3:
assert upretty( Symbol('F_h') ) == u'Fₕ'
assert upretty( Symbol('F_k') ) == u'Fₖ'
assert upretty( Symbol('F_l') ) == u'Fₗ'
assert upretty( Symbol('F_m') ) == u'Fₘ'
assert upretty( Symbol('F_n') ) == u'Fₙ'
assert upretty( Symbol('F_p') ) == u'Fₚ'
assert upretty( Symbol('F_s') ) == u'Fₛ'
assert upretty( Symbol('F_t') ) == u'Fₜ'
def test_upretty_modifiers():
# Accents
assert upretty( Symbol('Fmathring') ) == u'F̊'
assert upretty( Symbol('Fddddot') ) == u'F⃜'
assert upretty( Symbol('Fdddot') ) == u'F⃛'
assert upretty( Symbol('Fddot') ) == u'F̈'
assert upretty( Symbol('Fdot') ) == u'Ḟ'
assert upretty( Symbol('Fcheck') ) == u'F̌'
assert upretty( Symbol('Fbreve') ) == u'F̆'
assert upretty( Symbol('Facute') ) == u'F́'
assert upretty( Symbol('Fgrave') ) == u'F̀'
assert upretty( Symbol('Ftilde') ) == u'F̃'
assert upretty( Symbol('Fhat') ) == u'F̂'
assert upretty( Symbol('Fbar') ) == u'F̅'
assert upretty( Symbol('Fvec') ) == u'F⃗'
assert upretty( Symbol('Fprime') ) == u'F′'
assert upretty( Symbol('Fprm') ) == u'F′'
# No faces are actually implemented, but test to make sure the modifiers are stripped
assert upretty( Symbol('Fbold') ) == u'Fbold'
assert upretty( Symbol('Fbm') ) == u'Fbm'
assert upretty( Symbol('Fcal') ) == u'Fcal'
assert upretty( Symbol('Fscr') ) == u'Fscr'
assert upretty( Symbol('Ffrak') ) == u'Ffrak'
# Brackets
assert upretty( Symbol('Fnorm') ) == u'‖F‖'
assert upretty( Symbol('Favg') ) == u'⟨F⟩'
assert upretty( Symbol('Fabs') ) == u'|F|'
assert upretty( Symbol('Fmag') ) == u'|F|'
# Combinations
assert upretty( Symbol('xvecdot') ) == u'x⃗̇'
assert upretty( Symbol('xDotVec') ) == u'ẋ⃗'
assert upretty( Symbol('xHATNorm') ) == u'‖x̂‖'
assert upretty( Symbol('xMathring_yCheckPRM__zbreveAbs') ) == u'x̊_y̌′__|z̆|'
assert upretty( Symbol('alphadothat_nVECDOT__tTildePrime') ) == u'α̇̂_n⃗̇__t̃′'
assert upretty( Symbol('x_dot') ) == u'x_dot'
assert upretty( Symbol('x__dot') ) == u'x__dot'
def test_pretty_Cycle():
from sympy.combinatorics.permutations import Cycle
assert pretty(Cycle(1, 2)) == '(1 2)'
assert pretty(Cycle(2)) == '(2)'
assert pretty(Cycle(1, 3)(4, 5)) == '(1 3)(4 5)'
assert pretty(Cycle()) == '()'
def test_pretty_basic():
assert pretty( -Rational(1)/2 ) == '-1/2'
assert pretty( -Rational(13)/22 ) == \
"""\
-13 \n\
----\n\
22 \
"""
expr = oo
ascii_str = \
"""\
oo\
"""
ucode_str = \
u("""\
∞\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2)
ascii_str = \
"""\
2\n\
x \
"""
ucode_str = \
u("""\
2\n\
x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 1/x
ascii_str = \
"""\
1\n\
-\n\
x\
"""
ucode_str = \
u("""\
1\n\
─\n\
x\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# not the same as 1/x
expr = x**-1.0
ascii_str = \
"""\
-1.0\n\
x \
"""
ucode_str = \
("""\
-1.0\n\
x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# see issue #2860
expr = Pow(S(2), -1.0, evaluate=False)
ascii_str = \
"""\
-1.0\n\
2 \
"""
ucode_str = \
("""\
-1.0\n\
2 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = y*x**-2
ascii_str = \
"""\
y \n\
--\n\
2\n\
x \
"""
ucode_str = \
u("""\
y \n\
──\n\
2\n\
x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
#see issue #14033
expr = x**Rational(1, 3)
ascii_str = \
"""\
1/3\n\
x \
"""
ucode_str = \
u("""\
1/3\n\
x \
""")
assert xpretty(expr, use_unicode=False, wrap_line=False,\
root_notation = False) == ascii_str
assert xpretty(expr, use_unicode=True, wrap_line=False,\
root_notation = False) == ucode_str
expr = x**Rational(-5, 2)
ascii_str = \
"""\
1 \n\
----\n\
5/2\n\
x \
"""
ucode_str = \
u("""\
1 \n\
────\n\
5/2\n\
x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (-2)**x
ascii_str = \
"""\
x\n\
(-2) \
"""
ucode_str = \
u("""\
x\n\
(-2) \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# See issue 4923
expr = Pow(3, 1, evaluate=False)
ascii_str = \
"""\
1\n\
3 \
"""
ucode_str = \
u("""\
1\n\
3 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2 + x + 1)
ascii_str_1 = \
"""\
2\n\
1 + x + x \
"""
ascii_str_2 = \
"""\
2 \n\
x + x + 1\
"""
ascii_str_3 = \
"""\
2 \n\
x + 1 + x\
"""
ucode_str_1 = \
u("""\
2\n\
1 + x + x \
""")
ucode_str_2 = \
u("""\
2 \n\
x + x + 1\
""")
ucode_str_3 = \
u("""\
2 \n\
x + 1 + x\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
expr = 1 - x
ascii_str_1 = \
"""\
1 - x\
"""
ascii_str_2 = \
"""\
-x + 1\
"""
ucode_str_1 = \
u("""\
1 - x\
""")
ucode_str_2 = \
u("""\
-x + 1\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = 1 - 2*x
ascii_str_1 = \
"""\
1 - 2*x\
"""
ascii_str_2 = \
"""\
-2*x + 1\
"""
ucode_str_1 = \
u("""\
1 - 2⋅x\
""")
ucode_str_2 = \
u("""\
-2⋅x + 1\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = x/y
ascii_str = \
"""\
x\n\
-\n\
y\
"""
ucode_str = \
u("""\
x\n\
─\n\
y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x/y
ascii_str = \
"""\
-x \n\
---\n\
y \
"""
ucode_str = \
u("""\
-x \n\
───\n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x + 2)/y
ascii_str_1 = \
"""\
2 + x\n\
-----\n\
y \
"""
ascii_str_2 = \
"""\
x + 2\n\
-----\n\
y \
"""
ucode_str_1 = \
u("""\
2 + x\n\
─────\n\
y \
""")
ucode_str_2 = \
u("""\
x + 2\n\
─────\n\
y \
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = (1 + x)*y
ascii_str_1 = \
"""\
y*(1 + x)\
"""
ascii_str_2 = \
"""\
(1 + x)*y\
"""
ascii_str_3 = \
"""\
y*(x + 1)\
"""
ucode_str_1 = \
u("""\
y⋅(1 + x)\
""")
ucode_str_2 = \
u("""\
(1 + x)⋅y\
""")
ucode_str_3 = \
u("""\
y⋅(x + 1)\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
# Test for correct placement of the negative sign
expr = -5*x/(x + 10)
ascii_str_1 = \
"""\
-5*x \n\
------\n\
10 + x\
"""
ascii_str_2 = \
"""\
-5*x \n\
------\n\
x + 10\
"""
ucode_str_1 = \
u("""\
-5⋅x \n\
──────\n\
10 + x\
""")
ucode_str_2 = \
u("""\
-5⋅x \n\
──────\n\
x + 10\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = -S.Half - 3*x
ascii_str = \
"""\
-3*x - 1/2\
"""
ucode_str = \
u("""\
-3⋅x - 1/2\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = S.Half - 3*x
ascii_str = \
"""\
1/2 - 3*x\
"""
ucode_str = \
u("""\
1/2 - 3⋅x\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -S.Half - 3*x/2
ascii_str = \
"""\
3*x 1\n\
- --- - -\n\
2 2\
"""
ucode_str = \
u("""\
3⋅x 1\n\
- ─── - ─\n\
2 2\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = S.Half - 3*x/2
ascii_str = \
"""\
1 3*x\n\
- - ---\n\
2 2 \
"""
ucode_str = \
u("""\
1 3⋅x\n\
─ - ───\n\
2 2 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_negative_fractions():
expr = -x/y
ascii_str =\
"""\
-x \n\
---\n\
y \
"""
ucode_str =\
u("""\
-x \n\
───\n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x*z/y
ascii_str =\
"""\
-x*z \n\
-----\n\
y \
"""
ucode_str =\
u("""\
-x⋅z \n\
─────\n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x**2/y
ascii_str =\
"""\
2\n\
x \n\
--\n\
y \
"""
ucode_str =\
u("""\
2\n\
x \n\
──\n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x**2/y
ascii_str =\
"""\
2 \n\
-x \n\
----\n\
y \
"""
ucode_str =\
u("""\
2 \n\
-x \n\
────\n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -x/(y*z)
ascii_str =\
"""\
-x \n\
---\n\
y*z\
"""
ucode_str =\
u("""\
-x \n\
───\n\
y⋅z\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -a/y**2
ascii_str =\
"""\
-a \n\
---\n\
2\n\
y \
"""
ucode_str =\
u("""\
-a \n\
───\n\
2\n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = y**(-a/b)
ascii_str =\
"""\
-a \n\
---\n\
b \n\
y \
"""
ucode_str =\
u("""\
-a \n\
───\n\
b \n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -1/y**2
ascii_str =\
"""\
-1 \n\
---\n\
2\n\
y \
"""
ucode_str =\
u("""\
-1 \n\
───\n\
2\n\
y \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -10/b**2
ascii_str =\
"""\
-10 \n\
----\n\
2 \n\
b \
"""
ucode_str =\
u("""\
-10 \n\
────\n\
2 \n\
b \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Rational(-200, 37)
ascii_str =\
"""\
-200 \n\
-----\n\
37 \
"""
ucode_str =\
u("""\
-200 \n\
─────\n\
37 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_5524():
assert pretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \
"""\
2 / ___ \\\n\
- (5 - y) + (x - 5)*\\-x - 2*\\/ 2 + 5/\
"""
assert upretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \
u("""\
2 \n\
- (5 - y) + (x - 5)⋅(-x - 2⋅√2 + 5)\
""")
def test_pretty_ordering():
assert pretty(x**2 + x + 1, order='lex') == \
"""\
2 \n\
x + x + 1\
"""
assert pretty(x**2 + x + 1, order='rev-lex') == \
"""\
2\n\
1 + x + x \
"""
assert pretty(1 - x, order='lex') == '-x + 1'
assert pretty(1 - x, order='rev-lex') == '1 - x'
assert pretty(1 - 2*x, order='lex') == '-2*x + 1'
assert pretty(1 - 2*x, order='rev-lex') == '1 - 2*x'
f = 2*x**4 + y**2 - x**2 + y**3
assert pretty(f, order=None) == \
"""\
4 2 3 2\n\
2*x - x + y + y \
"""
assert pretty(f, order='lex') == \
"""\
4 2 3 2\n\
2*x - x + y + y \
"""
assert pretty(f, order='rev-lex') == \
"""\
2 3 2 4\n\
y + y - x + 2*x \
"""
expr = x - x**3/6 + x**5/120 + O(x**6)
ascii_str = \
"""\
3 5 \n\
x x / 6\\\n\
x - -- + --- + O\\x /\n\
6 120 \
"""
ucode_str = \
u("""\
3 5 \n\
x x ⎛ 6⎞\n\
x - ── + ─── + O⎝x ⎠\n\
6 120 \
""")
assert pretty(expr, order=None) == ascii_str
assert upretty(expr, order=None) == ucode_str
assert pretty(expr, order='lex') == ascii_str
assert upretty(expr, order='lex') == ucode_str
assert pretty(expr, order='rev-lex') == ascii_str
assert upretty(expr, order='rev-lex') == ucode_str
def test_EulerGamma():
assert pretty(EulerGamma) == str(EulerGamma) == "EulerGamma"
assert upretty(EulerGamma) == u"γ"
def test_GoldenRatio():
assert pretty(GoldenRatio) == str(GoldenRatio) == "GoldenRatio"
assert upretty(GoldenRatio) == u"φ"
def test_pretty_relational():
expr = Eq(x, y)
ascii_str = \
"""\
x = y\
"""
ucode_str = \
u("""\
x = y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lt(x, y)
ascii_str = \
"""\
x < y\
"""
ucode_str = \
u("""\
x < y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Gt(x, y)
ascii_str = \
"""\
x > y\
"""
ucode_str = \
u("""\
x > y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Le(x, y)
ascii_str = \
"""\
x <= y\
"""
ucode_str = \
u("""\
x ≤ y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Ge(x, y)
ascii_str = \
"""\
x >= y\
"""
ucode_str = \
u("""\
x ≥ y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Ne(x/(y + 1), y**2)
ascii_str_1 = \
"""\
x 2\n\
----- != y \n\
1 + y \
"""
ascii_str_2 = \
"""\
x 2\n\
----- != y \n\
y + 1 \
"""
ucode_str_1 = \
u("""\
x 2\n\
───── ≠ y \n\
1 + y \
""")
ucode_str_2 = \
u("""\
x 2\n\
───── ≠ y \n\
y + 1 \
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
def test_Assignment():
expr = Assignment(x, y)
ascii_str = \
"""\
x := y\
"""
ucode_str = \
u("""\
x := y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_AugmentedAssignment():
expr = AddAugmentedAssignment(x, y)
ascii_str = \
"""\
x += y\
"""
ucode_str = \
u("""\
x += y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = SubAugmentedAssignment(x, y)
ascii_str = \
"""\
x -= y\
"""
ucode_str = \
u("""\
x -= y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = MulAugmentedAssignment(x, y)
ascii_str = \
"""\
x *= y\
"""
ucode_str = \
u("""\
x *= y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = DivAugmentedAssignment(x, y)
ascii_str = \
"""\
x /= y\
"""
ucode_str = \
u("""\
x /= y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = ModAugmentedAssignment(x, y)
ascii_str = \
"""\
x %= y\
"""
ucode_str = \
u("""\
x %= y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_7117():
# See also issue #5031 (hence the evaluate=False in these).
e = Eq(x + 1, x/2)
q = Mul(2, e, evaluate=False)
assert upretty(q) == u("""\
⎛ x⎞\n\
2⋅⎜x + 1 = ─⎟\n\
⎝ 2⎠\
""")
q = Add(e, 6, evaluate=False)
assert upretty(q) == u("""\
⎛ x⎞\n\
6 + ⎜x + 1 = ─⎟\n\
⎝ 2⎠\
""")
q = Pow(e, 2, evaluate=False)
assert upretty(q) == u("""\
2\n\
⎛ x⎞ \n\
⎜x + 1 = ─⎟ \n\
⎝ 2⎠ \
""")
e2 = Eq(x, 2)
q = Mul(e, e2, evaluate=False)
assert upretty(q) == u("""\
⎛ x⎞ \n\
⎜x + 1 = ─⎟⋅(x = 2)\n\
⎝ 2⎠ \
""")
def test_pretty_rational():
expr = y*x**-2
ascii_str = \
"""\
y \n\
--\n\
2\n\
x \
"""
ucode_str = \
u("""\
y \n\
──\n\
2\n\
x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = y**Rational(3, 2) * x**Rational(-5, 2)
ascii_str = \
"""\
3/2\n\
y \n\
----\n\
5/2\n\
x \
"""
ucode_str = \
u("""\
3/2\n\
y \n\
────\n\
5/2\n\
x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sin(x)**3/tan(x)**2
ascii_str = \
"""\
3 \n\
sin (x)\n\
-------\n\
2 \n\
tan (x)\
"""
ucode_str = \
u("""\
3 \n\
sin (x)\n\
───────\n\
2 \n\
tan (x)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_functions():
"""Tests for Abs, conjugate, exp, function braces, and factorial."""
expr = (2*x + exp(x))
ascii_str_1 = \
"""\
x\n\
2*x + e \
"""
ascii_str_2 = \
"""\
x \n\
e + 2*x\
"""
ucode_str_1 = \
u("""\
x\n\
2⋅x + ℯ \
""")
ucode_str_2 = \
u("""\
x \n\
ℯ + 2⋅x\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Abs(x)
ascii_str = \
"""\
|x|\
"""
ucode_str = \
u("""\
│x│\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Abs(x/(x**2 + 1))
ascii_str_1 = \
"""\
| x |\n\
|------|\n\
| 2|\n\
|1 + x |\
"""
ascii_str_2 = \
"""\
| x |\n\
|------|\n\
| 2 |\n\
|x + 1|\
"""
ucode_str_1 = \
u("""\
│ x │\n\
│──────│\n\
│ 2│\n\
│1 + x │\
""")
ucode_str_2 = \
u("""\
│ x │\n\
│──────│\n\
│ 2 │\n\
│x + 1│\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Abs(1 / (y - Abs(x)))
ascii_str = \
"""\
1 \n\
---------\n\
|y - |x||\
"""
ucode_str = \
u("""\
1 \n\
─────────\n\
│y - │x││\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
n = Symbol('n', integer=True)
expr = factorial(n)
ascii_str = \
"""\
n!\
"""
ucode_str = \
u("""\
n!\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial(2*n)
ascii_str = \
"""\
(2*n)!\
"""
ucode_str = \
u("""\
(2⋅n)!\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial(factorial(factorial(n)))
ascii_str = \
"""\
((n!)!)!\
"""
ucode_str = \
u("""\
((n!)!)!\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial(n + 1)
ascii_str_1 = \
"""\
(1 + n)!\
"""
ascii_str_2 = \
"""\
(n + 1)!\
"""
ucode_str_1 = \
u("""\
(1 + n)!\
""")
ucode_str_2 = \
u("""\
(n + 1)!\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = subfactorial(n)
ascii_str = \
"""\
!n\
"""
ucode_str = \
u("""\
!n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = subfactorial(2*n)
ascii_str = \
"""\
!(2*n)\
"""
ucode_str = \
u("""\
!(2⋅n)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
n = Symbol('n', integer=True)
expr = factorial2(n)
ascii_str = \
"""\
n!!\
"""
ucode_str = \
u("""\
n!!\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial2(2*n)
ascii_str = \
"""\
(2*n)!!\
"""
ucode_str = \
u("""\
(2⋅n)!!\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial2(factorial2(factorial2(n)))
ascii_str = \
"""\
((n!!)!!)!!\
"""
ucode_str = \
u("""\
((n!!)!!)!!\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = factorial2(n + 1)
ascii_str_1 = \
"""\
(1 + n)!!\
"""
ascii_str_2 = \
"""\
(n + 1)!!\
"""
ucode_str_1 = \
u("""\
(1 + n)!!\
""")
ucode_str_2 = \
u("""\
(n + 1)!!\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = 2*binomial(n, k)
ascii_str = \
"""\
/n\\\n\
2*| |\n\
\\k/\
"""
ucode_str = \
u("""\
⎛n⎞\n\
2⋅⎜ ⎟\n\
⎝k⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2*binomial(2*n, k)
ascii_str = \
"""\
/2*n\\\n\
2*| |\n\
\\ k /\
"""
ucode_str = \
u("""\
⎛2⋅n⎞\n\
2⋅⎜ ⎟\n\
⎝ k ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2*binomial(n**2, k)
ascii_str = \
"""\
/ 2\\\n\
|n |\n\
2*| |\n\
\\k /\
"""
ucode_str = \
u("""\
⎛ 2⎞\n\
⎜n ⎟\n\
2⋅⎜ ⎟\n\
⎝k ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = catalan(n)
ascii_str = \
"""\
C \n\
n\
"""
ucode_str = \
u("""\
C \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = catalan(n)
ascii_str = \
"""\
C \n\
n\
"""
ucode_str = \
u("""\
C \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = bell(n)
ascii_str = \
"""\
B \n\
n\
"""
ucode_str = \
u("""\
B \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = bernoulli(n)
ascii_str = \
"""\
B \n\
n\
"""
ucode_str = \
u("""\
B \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = bernoulli(n, x)
ascii_str = \
"""\
B (x)\n\
n \
"""
ucode_str = \
u("""\
B (x)\n\
n \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = fibonacci(n)
ascii_str = \
"""\
F \n\
n\
"""
ucode_str = \
u("""\
F \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = lucas(n)
ascii_str = \
"""\
L \n\
n\
"""
ucode_str = \
u("""\
L \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = tribonacci(n)
ascii_str = \
"""\
T \n\
n\
"""
ucode_str = \
u("""\
T \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = stieltjes(n)
ascii_str = \
"""\
stieltjes \n\
n\
"""
ucode_str = \
u("""\
γ \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = stieltjes(n, x)
ascii_str = \
"""\
stieltjes (x)\n\
n \
"""
ucode_str = \
u("""\
γ (x)\n\
n \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieuc(x, y, z)
ascii_str = 'C(x, y, z)'
ucode_str = u('C(x, y, z)')
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieus(x, y, z)
ascii_str = 'S(x, y, z)'
ucode_str = u('S(x, y, z)')
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieucprime(x, y, z)
ascii_str = "C'(x, y, z)"
ucode_str = u("C'(x, y, z)")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = mathieusprime(x, y, z)
ascii_str = "S'(x, y, z)"
ucode_str = u("S'(x, y, z)")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate(x)
ascii_str = \
"""\
_\n\
x\
"""
ucode_str = \
u("""\
_\n\
x\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
f = Function('f')
expr = conjugate(f(x + 1))
ascii_str_1 = \
"""\
________\n\
f(1 + x)\
"""
ascii_str_2 = \
"""\
________\n\
f(x + 1)\
"""
ucode_str_1 = \
u("""\
________\n\
f(1 + x)\
""")
ucode_str_2 = \
u("""\
________\n\
f(x + 1)\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = f(x)
ascii_str = \
"""\
f(x)\
"""
ucode_str = \
u("""\
f(x)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = f(x, y)
ascii_str = \
"""\
f(x, y)\
"""
ucode_str = \
u("""\
f(x, y)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = f(x/(y + 1), y)
ascii_str_1 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\1 + y /\
"""
ascii_str_2 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\y + 1 /\
"""
ucode_str_1 = \
u("""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝1 + y ⎠\
""")
ucode_str_2 = \
u("""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝y + 1 ⎠\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = f(x**x**x**x**x**x)
ascii_str = \
"""\
/ / / / / x\\\\\\\\\\
| | | | \\x /||||
| | | \\x /|||
| | \\x /||
| \\x /|
f\\x /\
"""
ucode_str = \
u("""\
⎛ ⎛ ⎛ ⎛ ⎛ x⎞⎞⎞⎞⎞
⎜ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟⎟
⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟
⎜ ⎜ ⎝x ⎠⎟⎟
⎜ ⎝x ⎠⎟
f⎝x ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sin(x)**2
ascii_str = \
"""\
2 \n\
sin (x)\
"""
ucode_str = \
u("""\
2 \n\
sin (x)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate(a + b*I)
ascii_str = \
"""\
_ _\n\
a - I*b\
"""
ucode_str = \
u("""\
_ _\n\
a - ⅈ⋅b\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate(exp(a + b*I))
ascii_str = \
"""\
_ _\n\
a - I*b\n\
e \
"""
ucode_str = \
u("""\
_ _\n\
a - ⅈ⋅b\n\
ℯ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = conjugate( f(1 + conjugate(f(x))) )
ascii_str_1 = \
"""\
___________\n\
/ ____\\\n\
f\\1 + f(x)/\
"""
ascii_str_2 = \
"""\
___________\n\
/____ \\\n\
f\\f(x) + 1/\
"""
ucode_str_1 = \
u("""\
___________\n\
⎛ ____⎞\n\
f⎝1 + f(x)⎠\
""")
ucode_str_2 = \
u("""\
___________\n\
⎛____ ⎞\n\
f⎝f(x) + 1⎠\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = f(x/(y + 1), y)
ascii_str_1 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\1 + y /\
"""
ascii_str_2 = \
"""\
/ x \\\n\
f|-----, y|\n\
\\y + 1 /\
"""
ucode_str_1 = \
u("""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝1 + y ⎠\
""")
ucode_str_2 = \
u("""\
⎛ x ⎞\n\
f⎜─────, y⎟\n\
⎝y + 1 ⎠\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = floor(1 / (y - floor(x)))
ascii_str = \
"""\
/ 1 \\\n\
floor|------------|\n\
\\y - floor(x)/\
"""
ucode_str = \
u("""\
⎢ 1 ⎥\n\
⎢───────⎥\n\
⎣y - ⌊x⌋⎦\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = ceiling(1 / (y - ceiling(x)))
ascii_str = \
"""\
/ 1 \\\n\
ceiling|--------------|\n\
\\y - ceiling(x)/\
"""
ucode_str = \
u("""\
⎡ 1 ⎤\n\
⎢───────⎥\n\
⎢y - ⌈x⌉⎥\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(n)
ascii_str = \
"""\
E \n\
n\
"""
ucode_str = \
u("""\
E \n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(1/(1 + 1/(1 + 1/n)))
ascii_str = \
"""\
E \n\
1 \n\
---------\n\
1 \n\
1 + -----\n\
1\n\
1 + -\n\
n\
"""
ucode_str = \
u("""\
E \n\
1 \n\
─────────\n\
1 \n\
1 + ─────\n\
1\n\
1 + ─\n\
n\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(n, x)
ascii_str = \
"""\
E (x)\n\
n \
"""
ucode_str = \
u("""\
E (x)\n\
n \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = euler(n, x/2)
ascii_str = \
"""\
/x\\\n\
E |-|\n\
n\\2/\
"""
ucode_str = \
u("""\
⎛x⎞\n\
E ⎜─⎟\n\
n⎝2⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_sqrt():
expr = sqrt(2)
ascii_str = \
"""\
___\n\
\\/ 2 \
"""
ucode_str = \
u"√2"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2**Rational(1, 3)
ascii_str = \
"""\
3 ___\n\
\\/ 2 \
"""
ucode_str = \
u("""\
3 ___\n\
╲╱ 2 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2**Rational(1, 1000)
ascii_str = \
"""\
1000___\n\
\\/ 2 \
"""
ucode_str = \
u("""\
1000___\n\
╲╱ 2 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sqrt(x**2 + 1)
ascii_str = \
"""\
________\n\
/ 2 \n\
\\/ x + 1 \
"""
ucode_str = \
u("""\
________\n\
╱ 2 \n\
╲╱ x + 1 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (1 + sqrt(5))**Rational(1, 3)
ascii_str = \
"""\
___________\n\
3 / ___ \n\
\\/ 1 + \\/ 5 \
"""
ucode_str = \
u("""\
3 ________\n\
╲╱ 1 + √5 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2**(1/x)
ascii_str = \
"""\
x ___\n\
\\/ 2 \
"""
ucode_str = \
u("""\
x ___\n\
╲╱ 2 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = sqrt(2 + pi)
ascii_str = \
"""\
________\n\
\\/ 2 + pi \
"""
ucode_str = \
u("""\
_______\n\
╲╱ 2 + π \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (2 + (
1 + x**2)/(2 + x))**Rational(1, 4) + (1 + x**Rational(1, 1000))/sqrt(3 + x**2)
ascii_str = \
"""\
____________ \n\
/ 2 1000___ \n\
/ x + 1 \\/ x + 1\n\
4 / 2 + ------ + -----------\n\
\\/ x + 2 ________\n\
/ 2 \n\
\\/ x + 3 \
"""
ucode_str = \
u("""\
____________ \n\
╱ 2 1000___ \n\
╱ x + 1 ╲╱ x + 1\n\
4 ╱ 2 + ────── + ───────────\n\
╲╱ x + 2 ________\n\
╱ 2 \n\
╲╱ x + 3 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_sqrt_char_knob():
# See PR #9234.
expr = sqrt(2)
ucode_str1 = \
u("""\
___\n\
╲╱ 2 \
""")
ucode_str2 = \
u"√2"
assert xpretty(expr, use_unicode=True,
use_unicode_sqrt_char=False) == ucode_str1
assert xpretty(expr, use_unicode=True,
use_unicode_sqrt_char=True) == ucode_str2
def test_pretty_sqrt_longsymbol_no_sqrt_char():
# Do not use unicode sqrt char for long symbols (see PR #9234).
expr = sqrt(Symbol('C1'))
ucode_str = \
u("""\
____\n\
╲╱ C₁ \
""")
assert upretty(expr) == ucode_str
def test_pretty_KroneckerDelta():
x, y = symbols("x, y")
expr = KroneckerDelta(x, y)
ascii_str = \
"""\
d \n\
x,y\
"""
ucode_str = \
u("""\
δ \n\
x,y\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_product():
n, m, k, l = symbols('n m k l')
f = symbols('f', cls=Function)
expr = Product(f((n/3)**2), (n, k**2, l))
unicode_str = \
u("""\
l \n\
─┬──────┬─ \n\
│ │ ⎛ 2⎞\n\
│ │ ⎜n ⎟\n\
│ │ f⎜──⎟\n\
│ │ ⎝9 ⎠\n\
│ │ \n\
2 \n\
n = k """)
ascii_str = \
"""\
l \n\
__________ \n\
| | / 2\\\n\
| | |n |\n\
| | f|--|\n\
| | \\9 /\n\
| | \n\
2 \n\
n = k """
expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m))
unicode_str = \
u("""\
m l \n\
─┬──────┬─ ─┬──────┬─ \n\
│ │ │ │ ⎛ 2⎞\n\
│ │ │ │ ⎜n ⎟\n\
│ │ │ │ f⎜──⎟\n\
│ │ │ │ ⎝9 ⎠\n\
│ │ │ │ \n\
l = 1 2 \n\
n = k """)
ascii_str = \
"""\
m l \n\
__________ __________ \n\
| | | | / 2\\\n\
| | | | |n |\n\
| | | | f|--|\n\
| | | | \\9 /\n\
| | | | \n\
l = 1 2 \n\
n = k """
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
def test_pretty_lambda():
# S.IdentityFunction is a special case
expr = Lambda(y, y)
assert pretty(expr) == "x -> x"
assert upretty(expr) == u"x ↦ x"
expr = Lambda(x, x+1)
assert pretty(expr) == "x -> x + 1"
assert upretty(expr) == u"x ↦ x + 1"
expr = Lambda(x, x**2)
ascii_str = \
"""\
2\n\
x -> x \
"""
ucode_str = \
u("""\
2\n\
x ↦ x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lambda(x, x**2)**2
ascii_str = \
"""\
2
/ 2\\ \n\
\\x -> x / \
"""
ucode_str = \
u("""\
2
⎛ 2⎞ \n\
⎝x ↦ x ⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lambda((x, y), x)
ascii_str = "(x, y) -> x"
ucode_str = u"(x, y) ↦ x"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Lambda((x, y), x**2)
ascii_str = \
"""\
2\n\
(x, y) -> x \
"""
ucode_str = \
u("""\
2\n\
(x, y) ↦ x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_order():
expr = O(1)
ascii_str = \
"""\
O(1)\
"""
ucode_str = \
u("""\
O(1)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(1/x)
ascii_str = \
"""\
/1\\\n\
O|-|\n\
\\x/\
"""
ucode_str = \
u("""\
⎛1⎞\n\
O⎜─⎟\n\
⎝x⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(x**2 + y**2)
ascii_str = \
"""\
/ 2 2 \\\n\
O\\x + y ; (x, y) -> (0, 0)/\
"""
ucode_str = \
u("""\
⎛ 2 2 ⎞\n\
O⎝x + y ; (x, y) → (0, 0)⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(1, (x, oo))
ascii_str = \
"""\
O(1; x -> oo)\
"""
ucode_str = \
u("""\
O(1; x → ∞)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(1/x, (x, oo))
ascii_str = \
"""\
/1 \\\n\
O|-; x -> oo|\n\
\\x /\
"""
ucode_str = \
u("""\
⎛1 ⎞\n\
O⎜─; x → ∞⎟\n\
⎝x ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = O(x**2 + y**2, (x, oo), (y, oo))
ascii_str = \
"""\
/ 2 2 \\\n\
O\\x + y ; (x, y) -> (oo, oo)/\
"""
ucode_str = \
u("""\
⎛ 2 2 ⎞\n\
O⎝x + y ; (x, y) → (∞, ∞)⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_derivatives():
# Simple
expr = Derivative(log(x), x, evaluate=False)
ascii_str = \
"""\
d \n\
--(log(x))\n\
dx \
"""
ucode_str = \
u("""\
d \n\
──(log(x))\n\
dx \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(log(x), x, evaluate=False) + x
ascii_str_1 = \
"""\
d \n\
x + --(log(x))\n\
dx \
"""
ascii_str_2 = \
"""\
d \n\
--(log(x)) + x\n\
dx \
"""
ucode_str_1 = \
u("""\
d \n\
x + ──(log(x))\n\
dx \
""")
ucode_str_2 = \
u("""\
d \n\
──(log(x)) + x\n\
dx \
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
# basic partial derivatives
expr = Derivative(log(x + y) + x, x)
ascii_str_1 = \
"""\
d \n\
--(log(x + y) + x)\n\
dx \
"""
ascii_str_2 = \
"""\
d \n\
--(x + log(x + y))\n\
dx \
"""
ucode_str_1 = \
u("""\
∂ \n\
──(log(x + y) + x)\n\
∂x \
""")
ucode_str_2 = \
u("""\
∂ \n\
──(x + log(x + y))\n\
∂x \
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2], upretty(expr)
# Multiple symbols
expr = Derivative(log(x) + x**2, x, y)
ascii_str_1 = \
"""\
2 \n\
d / 2\\\n\
-----\\log(x) + x /\n\
dy dx \
"""
ascii_str_2 = \
"""\
2 \n\
d / 2 \\\n\
-----\\x + log(x)/\n\
dy dx \
"""
ucode_str_1 = \
u("""\
2 \n\
d ⎛ 2⎞\n\
─────⎝log(x) + x ⎠\n\
dy dx \
""")
ucode_str_2 = \
u("""\
2 \n\
d ⎛ 2 ⎞\n\
─────⎝x + log(x)⎠\n\
dy dx \
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Derivative(2*x*y, y, x) + x**2
ascii_str_1 = \
"""\
2 \n\
d 2\n\
-----(2*x*y) + x \n\
dx dy \
"""
ascii_str_2 = \
"""\
2 \n\
2 d \n\
x + -----(2*x*y)\n\
dx dy \
"""
ucode_str_1 = \
u("""\
2 \n\
∂ 2\n\
─────(2⋅x⋅y) + x \n\
∂x ∂y \
""")
ucode_str_2 = \
u("""\
2 \n\
2 ∂ \n\
x + ─────(2⋅x⋅y)\n\
∂x ∂y \
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Derivative(2*x*y, x, x)
ascii_str = \
"""\
2 \n\
d \n\
---(2*x*y)\n\
2 \n\
dx \
"""
ucode_str = \
u("""\
2 \n\
∂ \n\
───(2⋅x⋅y)\n\
2 \n\
∂x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(2*x*y, x, 17)
ascii_str = \
"""\
17 \n\
d \n\
----(2*x*y)\n\
17 \n\
dx \
"""
ucode_str = \
u("""\
17 \n\
∂ \n\
────(2⋅x⋅y)\n\
17 \n\
∂x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(2*x*y, x, x, y)
ascii_str = \
"""\
3 \n\
d \n\
------(2*x*y)\n\
2 \n\
dy dx \
"""
ucode_str = \
u("""\
3 \n\
∂ \n\
──────(2⋅x⋅y)\n\
2 \n\
∂y ∂x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# Greek letters
alpha = Symbol('alpha')
beta = Function('beta')
expr = beta(alpha).diff(alpha)
ascii_str = \
"""\
d \n\
------(beta(alpha))\n\
dalpha \
"""
ucode_str = \
u("""\
d \n\
──(β(α))\n\
dα \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Derivative(f(x), (x, n))
ascii_str = \
"""\
n \n\
d \n\
---(f(x))\n\
n \n\
dx \
"""
ucode_str = \
u("""\
n \n\
d \n\
───(f(x))\n\
n \n\
dx \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_integrals():
expr = Integral(log(x), x)
ascii_str = \
"""\
/ \n\
| \n\
| log(x) dx\n\
| \n\
/ \
"""
ucode_str = \
u("""\
⌠ \n\
⎮ log(x) dx\n\
⌡ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2, x)
ascii_str = \
"""\
/ \n\
| \n\
| 2 \n\
| x dx\n\
| \n\
/ \
"""
ucode_str = \
u("""\
⌠ \n\
⎮ 2 \n\
⎮ x dx\n\
⌡ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral((sin(x))**2 / (tan(x))**2)
ascii_str = \
"""\
/ \n\
| \n\
| 2 \n\
| sin (x) \n\
| ------- dx\n\
| 2 \n\
| tan (x) \n\
| \n\
/ \
"""
ucode_str = \
u("""\
⌠ \n\
⎮ 2 \n\
⎮ sin (x) \n\
⎮ ─────── dx\n\
⎮ 2 \n\
⎮ tan (x) \n\
⌡ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**(2**x), x)
ascii_str = \
"""\
/ \n\
| \n\
| / x\\ \n\
| \\2 / \n\
| x dx\n\
| \n\
/ \
"""
ucode_str = \
u("""\
⌠ \n\
⎮ ⎛ x⎞ \n\
⎮ ⎝2 ⎠ \n\
⎮ x dx\n\
⌡ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2, (x, 1, 2))
ascii_str = \
"""\
2 \n\
/ \n\
| \n\
| 2 \n\
| x dx\n\
| \n\
/ \n\
1 \
"""
ucode_str = \
u("""\
2 \n\
⌠ \n\
⎮ 2 \n\
⎮ x dx\n\
⌡ \n\
1 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2, (x, Rational(1, 2), 10))
ascii_str = \
"""\
10 \n\
/ \n\
| \n\
| 2 \n\
| x dx\n\
| \n\
/ \n\
1/2 \
"""
ucode_str = \
u("""\
10 \n\
⌠ \n\
⎮ 2 \n\
⎮ x dx\n\
⌡ \n\
1/2 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(x**2*y**2, x, y)
ascii_str = \
"""\
/ / \n\
| | \n\
| | 2 2 \n\
| | x *y dx dy\n\
| | \n\
/ / \
"""
ucode_str = \
u("""\
⌠ ⌠ \n\
⎮ ⎮ 2 2 \n\
⎮ ⎮ x ⋅y dx dy\n\
⌡ ⌡ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(sin(th)/cos(ph), (th, 0, pi), (ph, 0, 2*pi))
ascii_str = \
"""\
2*pi pi \n\
/ / \n\
| | \n\
| | sin(theta) \n\
| | ---------- d(theta) d(phi)\n\
| | cos(phi) \n\
| | \n\
/ / \n\
0 0 \
"""
ucode_str = \
u("""\
2⋅π π \n\
⌠ ⌠ \n\
⎮ ⎮ sin(θ) \n\
⎮ ⎮ ────── dθ dφ\n\
⎮ ⎮ cos(φ) \n\
⌡ ⌡ \n\
0 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_matrix():
# Empty Matrix
expr = Matrix()
ascii_str = "[]"
unicode_str = "[]"
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Matrix(2, 0, lambda i, j: 0)
ascii_str = "[]"
unicode_str = "[]"
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Matrix(0, 2, lambda i, j: 0)
ascii_str = "[]"
unicode_str = "[]"
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Matrix([[x**2 + 1, 1], [y, x + y]])
ascii_str_1 = \
"""\
[ 2 ]
[1 + x 1 ]
[ ]
[ y x + y]\
"""
ascii_str_2 = \
"""\
[ 2 ]
[x + 1 1 ]
[ ]
[ y x + y]\
"""
ucode_str_1 = \
u("""\
⎡ 2 ⎤
⎢1 + x 1 ⎥
⎢ ⎥
⎣ y x + y⎦\
""")
ucode_str_2 = \
u("""\
⎡ 2 ⎤
⎢x + 1 1 ⎥
⎢ ⎥
⎣ y x + y⎦\
""")
assert pretty(expr) in [ascii_str_1, ascii_str_2]
assert upretty(expr) in [ucode_str_1, ucode_str_2]
expr = Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]])
ascii_str = \
"""\
[x ]
[- y theta]
[y ]
[ ]
[ I*k*phi ]
[0 e 1 ]\
"""
ucode_str = \
u("""\
⎡x ⎤
⎢─ y θ⎥
⎢y ⎥
⎢ ⎥
⎢ ⅈ⋅k⋅φ ⎥
⎣0 ℯ 1⎦\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_ndim_arrays():
x, y, z, w = symbols("x y z w")
for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray):
# Basic: scalar array
M = ArrayType(x)
assert pretty(M) == "x"
assert upretty(M) == "x"
M = ArrayType([[1/x, y], [z, w]])
M1 = ArrayType([1/x, y, z])
M2 = tensorproduct(M1, M)
M3 = tensorproduct(M, M)
ascii_str = \
"""\
[1 ]\n\
[- y]\n\
[x ]\n\
[ ]\n\
[z w]\
"""
ucode_str = \
u("""\
⎡1 ⎤\n\
⎢─ y⎥\n\
⎢x ⎥\n\
⎢ ⎥\n\
⎣z w⎦\
""")
assert pretty(M) == ascii_str
assert upretty(M) == ucode_str
ascii_str = \
"""\
[1 ]\n\
[- y z]\n\
[x ]\
"""
ucode_str = \
u("""\
⎡1 ⎤\n\
⎢─ y z⎥\n\
⎣x ⎦\
""")
assert pretty(M1) == ascii_str
assert upretty(M1) == ucode_str
ascii_str = \
"""\
[[1 y] ]\n\
[[-- -] [z ]]\n\
[[ 2 x] [ y 2 ] [- y*z]]\n\
[[x ] [ - y ] [x ]]\n\
[[ ] [ x ] [ ]]\n\
[[z w] [ ] [ 2 ]]\n\
[[- -] [y*z w*y] [z w*z]]\n\
[[x x] ]\
"""
ucode_str = \
u("""\
⎡⎡1 y⎤ ⎤\n\
⎢⎢── ─⎥ ⎡z ⎤⎥\n\
⎢⎢ 2 x⎥ ⎡ y 2 ⎤ ⎢─ y⋅z⎥⎥\n\
⎢⎢x ⎥ ⎢ ─ y ⎥ ⎢x ⎥⎥\n\
⎢⎢ ⎥ ⎢ x ⎥ ⎢ ⎥⎥\n\
⎢⎢z w⎥ ⎢ ⎥ ⎢ 2 ⎥⎥\n\
⎢⎢─ ─⎥ ⎣y⋅z w⋅y⎦ ⎣z w⋅z⎦⎥\n\
⎣⎣x x⎦ ⎦\
""")
assert pretty(M2) == ascii_str
assert upretty(M2) == ucode_str
ascii_str = \
"""\
[ [1 y] ]\n\
[ [-- -] ]\n\
[ [ 2 x] [ y 2 ]]\n\
[ [x ] [ - y ]]\n\
[ [ ] [ x ]]\n\
[ [z w] [ ]]\n\
[ [- -] [y*z w*y]]\n\
[ [x x] ]\n\
[ ]\n\
[[z ] [ w ]]\n\
[[- y*z] [ - w*y]]\n\
[[x ] [ x ]]\n\
[[ ] [ ]]\n\
[[ 2 ] [ 2 ]]\n\
[[z w*z] [w*z w ]]\
"""
ucode_str = \
u("""\
⎡ ⎡1 y⎤ ⎤\n\
⎢ ⎢── ─⎥ ⎥\n\
⎢ ⎢ 2 x⎥ ⎡ y 2 ⎤⎥\n\
⎢ ⎢x ⎥ ⎢ ─ y ⎥⎥\n\
⎢ ⎢ ⎥ ⎢ x ⎥⎥\n\
⎢ ⎢z w⎥ ⎢ ⎥⎥\n\
⎢ ⎢─ ─⎥ ⎣y⋅z w⋅y⎦⎥\n\
⎢ ⎣x x⎦ ⎥\n\
⎢ ⎥\n\
⎢⎡z ⎤ ⎡ w ⎤⎥\n\
⎢⎢─ y⋅z⎥ ⎢ ─ w⋅y⎥⎥\n\
⎢⎢x ⎥ ⎢ x ⎥⎥\n\
⎢⎢ ⎥ ⎢ ⎥⎥\n\
⎢⎢ 2 ⎥ ⎢ 2 ⎥⎥\n\
⎣⎣z w⋅z⎦ ⎣w⋅z w ⎦⎦\
""")
assert pretty(M3) == ascii_str
assert upretty(M3) == ucode_str
Mrow = ArrayType([[x, y, 1 / z]])
Mcolumn = ArrayType([[x], [y], [1 / z]])
Mcol2 = ArrayType([Mcolumn.tolist()])
ascii_str = \
"""\
[[ 1]]\n\
[[x y -]]\n\
[[ z]]\
"""
ucode_str = \
u("""\
⎡⎡ 1⎤⎤\n\
⎢⎢x y ─⎥⎥\n\
⎣⎣ z⎦⎦\
""")
assert pretty(Mrow) == ascii_str
assert upretty(Mrow) == ucode_str
ascii_str = \
"""\
[x]\n\
[ ]\n\
[y]\n\
[ ]\n\
[1]\n\
[-]\n\
[z]\
"""
ucode_str = \
u("""\
⎡x⎤\n\
⎢ ⎥\n\
⎢y⎥\n\
⎢ ⎥\n\
⎢1⎥\n\
⎢─⎥\n\
⎣z⎦\
""")
assert pretty(Mcolumn) == ascii_str
assert upretty(Mcolumn) == ucode_str
ascii_str = \
"""\
[[x]]\n\
[[ ]]\n\
[[y]]\n\
[[ ]]\n\
[[1]]\n\
[[-]]\n\
[[z]]\
"""
ucode_str = \
u("""\
⎡⎡x⎤⎤\n\
⎢⎢ ⎥⎥\n\
⎢⎢y⎥⎥\n\
⎢⎢ ⎥⎥\n\
⎢⎢1⎥⎥\n\
⎢⎢─⎥⎥\n\
⎣⎣z⎦⎦\
""")
assert pretty(Mcol2) == ascii_str
assert upretty(Mcol2) == ucode_str
def test_tensor_TensorProduct():
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
assert upretty(TensorProduct(A, B)) == "A\u2297B"
assert upretty(TensorProduct(A, B, A)) == "A\u2297B\u2297A"
def test_diffgeom_print_WedgeProduct():
from sympy.diffgeom.rn import R2
from sympy.diffgeom import WedgeProduct
wp = WedgeProduct(R2.dx, R2.dy)
assert upretty(wp) == u("ⅆ x∧ⅆ y")
def test_Adjoint():
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert pretty(Adjoint(X)) == " +\nX "
assert pretty(Adjoint(X + Y)) == " +\n(X + Y) "
assert pretty(Adjoint(X) + Adjoint(Y)) == " + +\nX + Y "
assert pretty(Adjoint(X*Y)) == " +\n(X*Y) "
assert pretty(Adjoint(Y)*Adjoint(X)) == " + +\nY *X "
assert pretty(Adjoint(X**2)) == " +\n/ 2\\ \n\\X / "
assert pretty(Adjoint(X)**2) == " 2\n/ +\\ \n\\X / "
assert pretty(Adjoint(Inverse(X))) == " +\n/ -1\\ \n\\X / "
assert pretty(Inverse(Adjoint(X))) == " -1\n/ +\\ \n\\X / "
assert pretty(Adjoint(Transpose(X))) == " +\n/ T\\ \n\\X / "
assert pretty(Transpose(Adjoint(X))) == " T\n/ +\\ \n\\X / "
assert upretty(Adjoint(X)) == u" †\nX "
assert upretty(Adjoint(X + Y)) == u" †\n(X + Y) "
assert upretty(Adjoint(X) + Adjoint(Y)) == u" † †\nX + Y "
assert upretty(Adjoint(X*Y)) == u" †\n(X⋅Y) "
assert upretty(Adjoint(Y)*Adjoint(X)) == u" † †\nY ⋅X "
assert upretty(Adjoint(X**2)) == \
u" †\n⎛ 2⎞ \n⎝X ⎠ "
assert upretty(Adjoint(X)**2) == \
u" 2\n⎛ †⎞ \n⎝X ⎠ "
assert upretty(Adjoint(Inverse(X))) == \
u" †\n⎛ -1⎞ \n⎝X ⎠ "
assert upretty(Inverse(Adjoint(X))) == \
u" -1\n⎛ †⎞ \n⎝X ⎠ "
assert upretty(Adjoint(Transpose(X))) == \
u" †\n⎛ T⎞ \n⎝X ⎠ "
assert upretty(Transpose(Adjoint(X))) == \
u" T\n⎛ †⎞ \n⎝X ⎠ "
def test_pretty_Trace_issue_9044():
X = Matrix([[1, 2], [3, 4]])
Y = Matrix([[2, 4], [6, 8]])
ascii_str_1 = \
"""\
/[1 2]\\
tr|[ ]|
\\[3 4]/\
"""
ucode_str_1 = \
u("""\
⎛⎡1 2⎤⎞
tr⎜⎢ ⎥⎟
⎝⎣3 4⎦⎠\
""")
ascii_str_2 = \
"""\
/[1 2]\\ /[2 4]\\
tr|[ ]| + tr|[ ]|
\\[3 4]/ \\[6 8]/\
"""
ucode_str_2 = \
u("""\
⎛⎡1 2⎤⎞ ⎛⎡2 4⎤⎞
tr⎜⎢ ⎥⎟ + tr⎜⎢ ⎥⎟
⎝⎣3 4⎦⎠ ⎝⎣6 8⎦⎠\
""")
assert pretty(Trace(X)) == ascii_str_1
assert upretty(Trace(X)) == ucode_str_1
assert pretty(Trace(X) + Trace(Y)) == ascii_str_2
assert upretty(Trace(X) + Trace(Y)) == ucode_str_2
def test_MatrixExpressions():
n = Symbol('n', integer=True)
X = MatrixSymbol('X', n, n)
assert pretty(X) == upretty(X) == "X"
Y = X[1:2:3, 4:5:6]
ascii_str = ucode_str = "X[1:3, 4:6]"
assert pretty(Y) == ascii_str
assert upretty(Y) == ucode_str
Z = X[1:10:2]
ascii_str = ucode_str = "X[1:10:2, :n]"
assert pretty(Z) == ascii_str
assert upretty(Z) == ucode_str
# Apply function elementwise (`ElementwiseApplyFunc`):
expr = (X.T*X).applyfunc(sin)
ascii_str = """\
/ T \\\n\
sin.\\X *X/\
"""
ucode_str = u("""\
⎛ T ⎞\n\
sin˳⎝X ⋅X⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
lamda = Lambda(x, 1/x)
expr = (n*X).applyfunc(lamda)
ascii_str = """\
/ 1\\ \n\
|d -> -|.(n*X)\n\
\\ d/ \
"""
ucode_str = u("""\
⎛ 1⎞ \n\
⎜d ↦ ─⎟˳(n⋅X)\n\
⎝ d⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_dotproduct():
from sympy.matrices import Matrix, MatrixSymbol
from sympy.matrices.expressions.dotproduct import DotProduct
n = symbols("n", integer=True)
A = MatrixSymbol('A', n, 1)
B = MatrixSymbol('B', n, 1)
C = Matrix(1, 3, [1, 2, 3])
D = Matrix(1, 3, [1, 3, 4])
assert pretty(DotProduct(A, B)) == u"A*B"
assert pretty(DotProduct(C, D)) == u"[1 2 3]*[1 3 4]"
assert upretty(DotProduct(A, B)) == u"A⋅B"
assert upretty(DotProduct(C, D)) == u"[1 2 3]⋅[1 3 4]"
def test_pretty_piecewise():
expr = Piecewise((x, x < 1), (x**2, True))
ascii_str = \
"""\
/x for x < 1\n\
| \n\
< 2 \n\
|x otherwise\n\
\\ \
"""
ucode_str = \
u("""\
⎧x for x < 1\n\
⎪ \n\
⎨ 2 \n\
⎪x otherwise\n\
⎩ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -Piecewise((x, x < 1), (x**2, True))
ascii_str = \
"""\
//x for x < 1\\\n\
|| |\n\
-|< 2 |\n\
||x otherwise|\n\
\\\\ /\
"""
ucode_str = \
u("""\
⎛⎧x for x < 1⎞\n\
⎜⎪ ⎟\n\
-⎜⎨ 2 ⎟\n\
⎜⎪x otherwise⎟\n\
⎝⎩ ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x + Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2),
(y**2, x > 2), (1, True)) + 1
ascii_str = \
"""\
//x \\ \n\
||- for x < 2| \n\
||y | \n\
//x for x > 0\\ || | \n\
x + |< | + |< 2 | + 1\n\
\\\\y otherwise/ ||y for x > 2| \n\
|| | \n\
||1 otherwise| \n\
\\\\ / \
"""
ucode_str = \
u("""\
⎛⎧x ⎞ \n\
⎜⎪─ for x < 2⎟ \n\
⎜⎪y ⎟ \n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\
x + ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\
⎜⎪ ⎟ \n\
⎜⎪1 otherwise⎟ \n\
⎝⎩ ⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x - Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2),
(y**2, x > 2), (1, True)) + 1
ascii_str = \
"""\
//x \\ \n\
||- for x < 2| \n\
||y | \n\
//x for x > 0\\ || | \n\
x - |< | + |< 2 | + 1\n\
\\\\y otherwise/ ||y for x > 2| \n\
|| | \n\
||1 otherwise| \n\
\\\\ / \
"""
ucode_str = \
u("""\
⎛⎧x ⎞ \n\
⎜⎪─ for x < 2⎟ \n\
⎜⎪y ⎟ \n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\
x - ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\
⎜⎪ ⎟ \n\
⎜⎪1 otherwise⎟ \n\
⎝⎩ ⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = x*Piecewise((x, x > 0), (y, True))
ascii_str = \
"""\
//x for x > 0\\\n\
x*|< |\n\
\\\\y otherwise/\
"""
ucode_str = \
u("""\
⎛⎧x for x > 0⎞\n\
x⋅⎜⎨ ⎟\n\
⎝⎩y otherwise⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x >
2), (1, True))
ascii_str = \
"""\
//x \\\n\
||- for x < 2|\n\
||y |\n\
//x for x > 0\\ || |\n\
|< |*|< 2 |\n\
\\\\y otherwise/ ||y for x > 2|\n\
|| |\n\
||1 otherwise|\n\
\\\\ /\
"""
ucode_str = \
u("""\
⎛⎧x ⎞\n\
⎜⎪─ for x < 2⎟\n\
⎜⎪y ⎟\n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\
⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\
⎜⎪ ⎟\n\
⎜⎪1 otherwise⎟\n\
⎝⎩ ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x
> 2), (1, True))
ascii_str = \
"""\
//x \\\n\
||- for x < 2|\n\
||y |\n\
//x for x > 0\\ || |\n\
-|< |*|< 2 |\n\
\\\\y otherwise/ ||y for x > 2|\n\
|| |\n\
||1 otherwise|\n\
\\\\ /\
"""
ucode_str = \
u("""\
⎛⎧x ⎞\n\
⎜⎪─ for x < 2⎟\n\
⎜⎪y ⎟\n\
⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\
-⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\
⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\
⎜⎪ ⎟\n\
⎜⎪1 otherwise⎟\n\
⎝⎩ ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Piecewise((0, Abs(1/y) < 1), (1, Abs(y) < 1), (y*meijerg(((2, 1),
()), ((), (1, 0)), 1/y), True))
ascii_str = \
"""\
/ 1 \n\
| 0 for --- < 1\n\
| |y| \n\
| \n\
< 1 for |y| < 1\n\
| \n\
| __0, 2 /2, 1 | 1\\ \n\
|y*/__ | | -| otherwise \n\
\\ \\_|2, 2 \\ 1, 0 | y/ \
"""
ucode_str = \
u("""\
⎧ 1 \n\
⎪ 0 for ─── < 1\n\
⎪ │y│ \n\
⎪ \n\
⎨ 1 for │y│ < 1\n\
⎪ \n\
⎪ ╭─╮0, 2 ⎛2, 1 │ 1⎞ \n\
⎪y⋅│╶┐ ⎜ │ ─⎟ otherwise \n\
⎩ ╰─╯2, 2 ⎝ 1, 0 │ y⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
# XXX: We have to use evaluate=False here because Piecewise._eval_power
# denests the power.
expr = Pow(Piecewise((x, x > 0), (y, True)), 2, evaluate=False)
ascii_str = \
"""\
2\n\
//x for x > 0\\ \n\
|< | \n\
\\\\y otherwise/ \
"""
ucode_str = \
u("""\
2\n\
⎛⎧x for x > 0⎞ \n\
⎜⎨ ⎟ \n\
⎝⎩y otherwise⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_ITE():
expr = ITE(x, y, z)
assert pretty(expr) == (
'/y for x \n'
'< \n'
'\\z otherwise'
)
assert upretty(expr) == u("""\
⎧y for x \n\
⎨ \n\
⎩z otherwise\
""")
def test_pretty_seq():
expr = ()
ascii_str = \
"""\
()\
"""
ucode_str = \
u("""\
()\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = []
ascii_str = \
"""\
[]\
"""
ucode_str = \
u("""\
[]\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = {}
expr_2 = {}
ascii_str = \
"""\
{}\
"""
ucode_str = \
u("""\
{}\
""")
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
expr = (1/x,)
ascii_str = \
"""\
1 \n\
(-,)\n\
x \
"""
ucode_str = \
u("""\
⎛1 ⎞\n\
⎜─,⎟\n\
⎝x ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2]
ascii_str = \
"""\
2 \n\
2 1 sin (theta) \n\
[x , -, x, y, -----------]\n\
x 2 \n\
cos (phi) \
"""
ucode_str = \
u("""\
⎡ 2 ⎤\n\
⎢ 2 1 sin (θ)⎥\n\
⎢x , ─, x, y, ───────⎥\n\
⎢ x 2 ⎥\n\
⎣ cos (φ)⎦\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
ascii_str = \
"""\
2 \n\
2 1 sin (theta) \n\
(x , -, x, y, -----------)\n\
x 2 \n\
cos (phi) \
"""
ucode_str = \
u("""\
⎛ 2 ⎞\n\
⎜ 2 1 sin (θ)⎟\n\
⎜x , ─, x, y, ───────⎟\n\
⎜ x 2 ⎟\n\
⎝ cos (φ)⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Tuple(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
ascii_str = \
"""\
2 \n\
2 1 sin (theta) \n\
(x , -, x, y, -----------)\n\
x 2 \n\
cos (phi) \
"""
ucode_str = \
u("""\
⎛ 2 ⎞\n\
⎜ 2 1 sin (θ)⎟\n\
⎜x , ─, x, y, ───────⎟\n\
⎜ x 2 ⎟\n\
⎝ cos (φ)⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = {x: sin(x)}
expr_2 = Dict({x: sin(x)})
ascii_str = \
"""\
{x: sin(x)}\
"""
ucode_str = \
u("""\
{x: sin(x)}\
""")
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
expr = {1/x: 1/y, x: sin(x)**2}
expr_2 = Dict({1/x: 1/y, x: sin(x)**2})
ascii_str = \
"""\
1 1 2 \n\
{-: -, x: sin (x)}\n\
x y \
"""
ucode_str = \
u("""\
⎧1 1 2 ⎫\n\
⎨─: ─, x: sin (x)⎬\n\
⎩x y ⎭\
""")
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
# There used to be a bug with pretty-printing sequences of even height.
expr = [x**2]
ascii_str = \
"""\
2 \n\
[x ]\
"""
ucode_str = \
u("""\
⎡ 2⎤\n\
⎣x ⎦\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (x**2,)
ascii_str = \
"""\
2 \n\
(x ,)\
"""
ucode_str = \
u("""\
⎛ 2 ⎞\n\
⎝x ,⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Tuple(x**2)
ascii_str = \
"""\
2 \n\
(x ,)\
"""
ucode_str = \
u("""\
⎛ 2 ⎞\n\
⎝x ,⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = {x**2: 1}
expr_2 = Dict({x**2: 1})
ascii_str = \
"""\
2 \n\
{x : 1}\
"""
ucode_str = \
u("""\
⎧ 2 ⎫\n\
⎨x : 1⎬\n\
⎩ ⎭\
""")
assert pretty(expr) == ascii_str
assert pretty(expr_2) == ascii_str
assert upretty(expr) == ucode_str
assert upretty(expr_2) == ucode_str
def test_any_object_in_sequence():
# Cf. issue 5306
b1 = Basic()
b2 = Basic(Basic())
expr = [b2, b1]
assert pretty(expr) == "[Basic(Basic()), Basic()]"
assert upretty(expr) == u"[Basic(Basic()), Basic()]"
expr = {b2, b1}
assert pretty(expr) == "{Basic(), Basic(Basic())}"
assert upretty(expr) == u"{Basic(), Basic(Basic())}"
expr = {b2: b1, b1: b2}
expr2 = Dict({b2: b1, b1: b2})
assert pretty(expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
assert pretty(
expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
assert upretty(
expr) == u"{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
assert upretty(
expr2) == u"{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
def test_print_builtin_set():
assert pretty(set()) == 'set()'
assert upretty(set()) == u'set()'
assert pretty(frozenset()) == 'frozenset()'
assert upretty(frozenset()) == u'frozenset()'
s1 = {1/x, x}
s2 = frozenset(s1)
assert pretty(s1) == \
"""\
1 \n\
{-, x}
x \
"""
assert upretty(s1) == \
u"""\
⎧1 ⎫
⎨─, x⎬
⎩x ⎭\
"""
assert pretty(s2) == \
"""\
1 \n\
frozenset({-, x})
x \
"""
assert upretty(s2) == \
u"""\
⎛⎧1 ⎫⎞
frozenset⎜⎨─, x⎬⎟
⎝⎩x ⎭⎠\
"""
def test_pretty_sets():
s = FiniteSet
assert pretty(s(*[x*y, x**2])) == \
"""\
2 \n\
{x , x*y}\
"""
assert pretty(s(*range(1, 6))) == "{1, 2, 3, 4, 5}"
assert pretty(s(*range(1, 13))) == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}"
assert pretty(set([x*y, x**2])) == \
"""\
2 \n\
{x , x*y}\
"""
assert pretty(set(range(1, 6))) == "{1, 2, 3, 4, 5}"
assert pretty(set(range(1, 13))) == \
"{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}"
assert pretty(frozenset([x*y, x**2])) == \
"""\
2 \n\
frozenset({x , x*y})\
"""
assert pretty(frozenset(range(1, 6))) == "frozenset({1, 2, 3, 4, 5})"
assert pretty(frozenset(range(1, 13))) == \
"frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})"
assert pretty(Range(0, 3, 1)) == '{0, 1, 2}'
ascii_str = '{0, 1, ..., 29}'
ucode_str = u'{0, 1, …, 29}'
assert pretty(Range(0, 30, 1)) == ascii_str
assert upretty(Range(0, 30, 1)) == ucode_str
ascii_str = '{30, 29, ..., 2}'
ucode_str = u('{30, 29, …, 2}')
assert pretty(Range(30, 1, -1)) == ascii_str
assert upretty(Range(30, 1, -1)) == ucode_str
ascii_str = '{0, 2, ...}'
ucode_str = u'{0, 2, …}'
assert pretty(Range(0, oo, 2)) == ascii_str
assert upretty(Range(0, oo, 2)) == ucode_str
ascii_str = '{..., 2, 0}'
ucode_str = u('{…, 2, 0}')
assert pretty(Range(oo, -2, -2)) == ascii_str
assert upretty(Range(oo, -2, -2)) == ucode_str
ascii_str = '{-2, -3, ...}'
ucode_str = u('{-2, -3, …}')
assert pretty(Range(-2, -oo, -1)) == ascii_str
assert upretty(Range(-2, -oo, -1)) == ucode_str
def test_pretty_SetExpr():
iv = Interval(1, 3)
se = SetExpr(iv)
ascii_str = "SetExpr([1, 3])"
ucode_str = u("SetExpr([1, 3])")
assert pretty(se) == ascii_str
assert upretty(se) == ucode_str
def test_pretty_ImageSet():
imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4})
ascii_str = '{x + y | x in {1, 2, 3} , y in {3, 4}}'
ucode_str = u('{x + y | x ∊ {1, 2, 3} , y ∊ {3, 4}}')
assert pretty(imgset) == ascii_str
assert upretty(imgset) == ucode_str
imgset = ImageSet(Lambda(x, x**2), S.Naturals)
ascii_str = \
' 2 \n'\
'{x | x in Naturals}'
ucode_str = u('''\
⎧ 2 ⎫\n\
⎨x | x ∊ ℕ⎬\n\
⎩ ⎭''')
assert pretty(imgset) == ascii_str
assert upretty(imgset) == ucode_str
def test_pretty_ConditionSet():
from sympy import ConditionSet
ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}'
ucode_str = u'{x | x ∊ ℝ ∧ sin(x) = 0}'
assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str
assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str
assert pretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}'
assert upretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == u'{1}'
assert pretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "EmptySet()"
assert upretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == u"∅"
assert pretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}'
assert upretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == u'{2}'
def test_pretty_ComplexRegion():
from sympy import ComplexRegion
ucode_str = u'{x + y⋅ⅈ | x, y ∊ [3, 5] × [4, 6]}'
assert upretty(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == ucode_str
ucode_str = u'{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}'
assert upretty(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == ucode_str
def test_pretty_Union_issue_10414():
a, b = Interval(2, 3), Interval(4, 7)
ucode_str = u'[2, 3] ∪ [4, 7]'
ascii_str = '[2, 3] U [4, 7]'
assert upretty(Union(a, b)) == ucode_str
assert pretty(Union(a, b)) == ascii_str
def test_pretty_Intersection_issue_10414():
x, y, z, w = symbols('x, y, z, w')
a, b = Interval(x, y), Interval(z, w)
ucode_str = u'[x, y] ∩ [z, w]'
ascii_str = '[x, y] n [z, w]'
assert upretty(Intersection(a, b)) == ucode_str
assert pretty(Intersection(a, b)) == ascii_str
def test_ProductSet_exponent():
ucode_str = ' 1\n[0, 1] '
assert upretty(Interval(0, 1)**1) == ucode_str
ucode_str = ' 2\n[0, 1] '
assert upretty(Interval(0, 1)**2) == ucode_str
def test_ProductSet_parenthesis():
ucode_str = u'([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])'
a, b, c = Interval(2, 3), Interval(4, 7), Interval(1, 9)
assert upretty(Union(a*b, b*FiniteSet(1, 2))) == ucode_str
def test_ProductSet_prod_char_issue_10413():
ascii_str = '[2, 3] x [4, 7]'
ucode_str = u'[2, 3] × [4, 7]'
a, b = Interval(2, 3), Interval(4, 7)
assert pretty(a*b) == ascii_str
assert upretty(a*b) == ucode_str
def test_pretty_sequences():
s1 = SeqFormula(a**2, (0, oo))
s2 = SeqPer((1, 2))
ascii_str = '[0, 1, 4, 9, ...]'
ucode_str = u'[0, 1, 4, 9, …]'
assert pretty(s1) == ascii_str
assert upretty(s1) == ucode_str
ascii_str = '[1, 2, 1, 2, ...]'
ucode_str = u'[1, 2, 1, 2, …]'
assert pretty(s2) == ascii_str
assert upretty(s2) == ucode_str
s3 = SeqFormula(a**2, (0, 2))
s4 = SeqPer((1, 2), (0, 2))
ascii_str = '[0, 1, 4]'
ucode_str = u'[0, 1, 4]'
assert pretty(s3) == ascii_str
assert upretty(s3) == ucode_str
ascii_str = '[1, 2, 1]'
ucode_str = u'[1, 2, 1]'
assert pretty(s4) == ascii_str
assert upretty(s4) == ucode_str
s5 = SeqFormula(a**2, (-oo, 0))
s6 = SeqPer((1, 2), (-oo, 0))
ascii_str = '[..., 9, 4, 1, 0]'
ucode_str = u'[…, 9, 4, 1, 0]'
assert pretty(s5) == ascii_str
assert upretty(s5) == ucode_str
ascii_str = '[..., 2, 1, 2, 1]'
ucode_str = u'[…, 2, 1, 2, 1]'
assert pretty(s6) == ascii_str
assert upretty(s6) == ucode_str
ascii_str = '[1, 3, 5, 11, ...]'
ucode_str = u'[1, 3, 5, 11, …]'
assert pretty(SeqAdd(s1, s2)) == ascii_str
assert upretty(SeqAdd(s1, s2)) == ucode_str
ascii_str = '[1, 3, 5]'
ucode_str = u'[1, 3, 5]'
assert pretty(SeqAdd(s3, s4)) == ascii_str
assert upretty(SeqAdd(s3, s4)) == ucode_str
ascii_str = '[..., 11, 5, 3, 1]'
ucode_str = u'[…, 11, 5, 3, 1]'
assert pretty(SeqAdd(s5, s6)) == ascii_str
assert upretty(SeqAdd(s5, s6)) == ucode_str
ascii_str = '[0, 2, 4, 18, ...]'
ucode_str = u'[0, 2, 4, 18, …]'
assert pretty(SeqMul(s1, s2)) == ascii_str
assert upretty(SeqMul(s1, s2)) == ucode_str
ascii_str = '[0, 2, 4]'
ucode_str = u'[0, 2, 4]'
assert pretty(SeqMul(s3, s4)) == ascii_str
assert upretty(SeqMul(s3, s4)) == ucode_str
ascii_str = '[..., 18, 4, 2, 0]'
ucode_str = u'[…, 18, 4, 2, 0]'
assert pretty(SeqMul(s5, s6)) == ascii_str
assert upretty(SeqMul(s5, s6)) == ucode_str
# Sequences with symbolic limits, issue 12629
s7 = SeqFormula(a**2, (a, 0, x))
raises(NotImplementedError, lambda: pretty(s7))
raises(NotImplementedError, lambda: upretty(s7))
b = Symbol('b')
s8 = SeqFormula(b*a**2, (a, 0, 2))
ascii_str = u'[0, b, 4*b]'
ucode_str = u'[0, b, 4⋅b]'
assert pretty(s8) == ascii_str
assert upretty(s8) == ucode_str
def test_pretty_FourierSeries():
f = fourier_series(x, (x, -pi, pi))
ascii_str = \
"""\
2*sin(3*x) \n\
2*sin(x) - sin(2*x) + ---------- + ...\n\
3 \
"""
ucode_str = \
u("""\
2⋅sin(3⋅x) \n\
2⋅sin(x) - sin(2⋅x) + ────────── + …\n\
3 \
""")
assert pretty(f) == ascii_str
assert upretty(f) == ucode_str
def test_pretty_FormalPowerSeries():
f = fps(log(1 + x))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ -k k \n\
\\ -(-1) *x \n\
/ -----------\n\
/ k \n\
/___, \n\
k = 1 \
"""
ucode_str = \
u("""\
∞ \n\
____ \n\
╲ \n\
╲ -k k \n\
╲ -(-1) ⋅x \n\
╱ ───────────\n\
╱ k \n\
╱ \n\
‾‾‾‾ \n\
k = 1 \
""")
assert pretty(f) == ascii_str
assert upretty(f) == ucode_str
def test_pretty_limits():
expr = Limit(x, x, oo)
ascii_str = \
"""\
lim x\n\
x->oo \
"""
ucode_str = \
u("""\
lim x\n\
x─→∞ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x**2, x, 0)
ascii_str = \
"""\
2\n\
lim x \n\
x->0+ \
"""
ucode_str = \
u("""\
2\n\
lim x \n\
x─→0⁺ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(1/x, x, 0)
ascii_str = \
"""\
1\n\
lim -\n\
x->0+x\
"""
ucode_str = \
u("""\
1\n\
lim ─\n\
x─→0⁺x\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(sin(x)/x, x, 0)
ascii_str = \
"""\
/sin(x)\\\n\
lim |------|\n\
x->0+\\ x /\
"""
ucode_str = \
u("""\
⎛sin(x)⎞\n\
lim ⎜──────⎟\n\
x─→0⁺⎝ x ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(sin(x)/x, x, 0, "-")
ascii_str = \
"""\
/sin(x)\\\n\
lim |------|\n\
x->0-\\ x /\
"""
ucode_str = \
u("""\
⎛sin(x)⎞\n\
lim ⎜──────⎟\n\
x─→0⁻⎝ x ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x + sin(x), x, 0)
ascii_str = \
"""\
lim (x + sin(x))\n\
x->0+ \
"""
ucode_str = \
u("""\
lim (x + sin(x))\n\
x─→0⁺ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x, x, 0)**2
ascii_str = \
"""\
2\n\
/ lim x\\ \n\
\\x->0+ / \
"""
ucode_str = \
u("""\
2\n\
⎛ lim x⎞ \n\
⎝x─→0⁺ ⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(x*Limit(y/2,y,0), x, 0)
ascii_str = \
"""\
/ /y\\\\\n\
lim |x* lim |-||\n\
x->0+\\ y->0+\\2//\
"""
ucode_str = \
u("""\
⎛ ⎛y⎞⎞\n\
lim ⎜x⋅ lim ⎜─⎟⎟\n\
x─→0⁺⎝ y─→0⁺⎝2⎠⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = 2*Limit(x*Limit(y/2,y,0), x, 0)
ascii_str = \
"""\
/ /y\\\\\n\
2* lim |x* lim |-||\n\
x->0+\\ y->0+\\2//\
"""
ucode_str = \
u("""\
⎛ ⎛y⎞⎞\n\
2⋅ lim ⎜x⋅ lim ⎜─⎟⎟\n\
x─→0⁺⎝ y─→0⁺⎝2⎠⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Limit(sin(x), x, 0, dir='+-')
ascii_str = \
"""\
lim sin(x)\n\
x->0 \
"""
ucode_str = \
u("""\
lim sin(x)\n\
x─→0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_ComplexRootOf():
expr = rootof(x**5 + 11*x - 2, 0)
ascii_str = \
"""\
/ 5 \\\n\
CRootOf\\x + 11*x - 2, 0/\
"""
ucode_str = \
u("""\
⎛ 5 ⎞\n\
CRootOf⎝x + 11⋅x - 2, 0⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_RootSum():
expr = RootSum(x**5 + 11*x - 2, auto=False)
ascii_str = \
"""\
/ 5 \\\n\
RootSum\\x + 11*x - 2/\
"""
ucode_str = \
u("""\
⎛ 5 ⎞\n\
RootSum⎝x + 11⋅x - 2⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = RootSum(x**5 + 11*x - 2, Lambda(z, exp(z)))
ascii_str = \
"""\
/ 5 z\\\n\
RootSum\\x + 11*x - 2, z -> e /\
"""
ucode_str = \
u("""\
⎛ 5 z⎞\n\
RootSum⎝x + 11⋅x - 2, z ↦ ℯ ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_GroebnerBasis():
expr = groebner([], x, y)
ascii_str = \
"""\
GroebnerBasis([], x, y, domain=ZZ, order=lex)\
"""
ucode_str = \
u("""\
GroebnerBasis([], x, y, domain=ℤ, order=lex)\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
expr = groebner(F, x, y, order='grlex')
ascii_str = \
"""\
/[ 2 2 ] \\\n\
GroebnerBasis\\[x - x - 3*y + 1, y - 2*x + y - 1], x, y, domain=ZZ, order=grlex/\
"""
ucode_str = \
u("""\
⎛⎡ 2 2 ⎤ ⎞\n\
GroebnerBasis⎝⎣x - x - 3⋅y + 1, y - 2⋅x + y - 1⎦, x, y, domain=ℤ, order=grlex⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = expr.fglm('lex')
ascii_str = \
"""\
/[ 2 4 3 2 ] \\\n\
GroebnerBasis\\[2*x - y - y + 1, y + 2*y - 3*y - 16*y + 7], x, y, domain=ZZ, order=lex/\
"""
ucode_str = \
u("""\
⎛⎡ 2 4 3 2 ⎤ ⎞\n\
GroebnerBasis⎝⎣2⋅x - y - y + 1, y + 2⋅y - 3⋅y - 16⋅y + 7⎦, x, y, domain=ℤ, order=lex⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_UniversalSet():
assert pretty(S.UniversalSet) == "UniversalSet"
assert upretty(S.UniversalSet) == u'𝕌'
def test_pretty_Boolean():
expr = Not(x, evaluate=False)
assert pretty(expr) == "Not(x)"
assert upretty(expr) == u"¬x"
expr = And(x, y)
assert pretty(expr) == "And(x, y)"
assert upretty(expr) == u"x ∧ y"
expr = Or(x, y)
assert pretty(expr) == "Or(x, y)"
assert upretty(expr) == u"x ∨ y"
syms = symbols('a:f')
expr = And(*syms)
assert pretty(expr) == "And(a, b, c, d, e, f)"
assert upretty(expr) == u"a ∧ b ∧ c ∧ d ∧ e ∧ f"
expr = Or(*syms)
assert pretty(expr) == "Or(a, b, c, d, e, f)"
assert upretty(expr) == u"a ∨ b ∨ c ∨ d ∨ e ∨ f"
expr = Xor(x, y, evaluate=False)
assert pretty(expr) == "Xor(x, y)"
assert upretty(expr) == u"x ⊻ y"
expr = Nand(x, y, evaluate=False)
assert pretty(expr) == "Nand(x, y)"
assert upretty(expr) == u"x ⊼ y"
expr = Nor(x, y, evaluate=False)
assert pretty(expr) == "Nor(x, y)"
assert upretty(expr) == u"x ⊽ y"
expr = Implies(x, y, evaluate=False)
assert pretty(expr) == "Implies(x, y)"
assert upretty(expr) == u"x → y"
# don't sort args
expr = Implies(y, x, evaluate=False)
assert pretty(expr) == "Implies(y, x)"
assert upretty(expr) == u"y → x"
expr = Equivalent(x, y, evaluate=False)
assert pretty(expr) == "Equivalent(x, y)"
assert upretty(expr) == u"x ⇔ y"
expr = Equivalent(y, x, evaluate=False)
assert pretty(expr) == "Equivalent(x, y)"
assert upretty(expr) == u"x ⇔ y"
def test_pretty_Domain():
expr = FF(23)
assert pretty(expr) == "GF(23)"
assert upretty(expr) == u"ℤ₂₃"
expr = ZZ
assert pretty(expr) == "ZZ"
assert upretty(expr) == u"ℤ"
expr = QQ
assert pretty(expr) == "QQ"
assert upretty(expr) == u"ℚ"
expr = RR
assert pretty(expr) == "RR"
assert upretty(expr) == u"ℝ"
expr = QQ[x]
assert pretty(expr) == "QQ[x]"
assert upretty(expr) == u"ℚ[x]"
expr = QQ[x, y]
assert pretty(expr) == "QQ[x, y]"
assert upretty(expr) == u"ℚ[x, y]"
expr = ZZ.frac_field(x)
assert pretty(expr) == "ZZ(x)"
assert upretty(expr) == u"ℤ(x)"
expr = ZZ.frac_field(x, y)
assert pretty(expr) == "ZZ(x, y)"
assert upretty(expr) == u"ℤ(x, y)"
expr = QQ.poly_ring(x, y, order=grlex)
assert pretty(expr) == "QQ[x, y, order=grlex]"
assert upretty(expr) == u"ℚ[x, y, order=grlex]"
expr = QQ.poly_ring(x, y, order=ilex)
assert pretty(expr) == "QQ[x, y, order=ilex]"
assert upretty(expr) == u"ℚ[x, y, order=ilex]"
def test_pretty_prec():
assert xpretty(S("0.3"), full_prec=True, wrap_line=False) == "0.300000000000000"
assert xpretty(S("0.3"), full_prec="auto", wrap_line=False) == "0.300000000000000"
assert xpretty(S("0.3"), full_prec=False, wrap_line=False) == "0.3"
assert xpretty(S("0.3")*x, full_prec=True, use_unicode=False, wrap_line=False) in [
"0.300000000000000*x",
"x*0.300000000000000"
]
assert xpretty(S("0.3")*x, full_prec="auto", use_unicode=False, wrap_line=False) in [
"0.3*x",
"x*0.3"
]
assert xpretty(S("0.3")*x, full_prec=False, use_unicode=False, wrap_line=False) in [
"0.3*x",
"x*0.3"
]
def test_pprint():
import sys
from sympy.core.compatibility import StringIO
fd = StringIO()
sso = sys.stdout
sys.stdout = fd
try:
pprint(pi, use_unicode=False, wrap_line=False)
finally:
sys.stdout = sso
assert fd.getvalue() == 'pi\n'
def test_pretty_class():
"""Test that the printer dispatcher correctly handles classes."""
class C:
pass # C has no .__class__ and this was causing problems
class D(object):
pass
assert pretty( C ) == str( C )
assert pretty( D ) == str( D )
def test_pretty_no_wrap_line():
huge_expr = 0
for i in range(20):
huge_expr += i*sin(i + x)
assert xpretty(huge_expr ).find('\n') != -1
assert xpretty(huge_expr, wrap_line=False).find('\n') == -1
def test_settings():
raises(TypeError, lambda: pretty(S(4), method="garbage"))
def test_pretty_sum():
from sympy.abc import x, a, b, k, m, n
expr = Sum(k**k, (k, 0, n))
ascii_str = \
"""\
n \n\
___ \n\
\\ ` \n\
\\ k\n\
/ k \n\
/__, \n\
k = 0 \
"""
ucode_str = \
u("""\
n \n\
___ \n\
╲ \n\
╲ k\n\
╱ k \n\
╱ \n\
‾‾‾ \n\
k = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**k, (k, oo, n))
ascii_str = \
"""\
n \n\
___ \n\
\\ ` \n\
\\ k\n\
/ k \n\
/__, \n\
k = oo \
"""
ucode_str = \
u("""\
n \n\
___ \n\
╲ \n\
╲ k\n\
╱ k \n\
╱ \n\
‾‾‾ \n\
k = ∞ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (k, 0, n**n))
ascii_str = \
"""\
n \n\
n \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
k = 0 \
"""
ucode_str = \
u("""\
n \n\
n \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
k = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(
Integral(x**n, (x, -oo, oo))), (k, 0, Integral(x**x, (x, -oo, oo))))
ascii_str = \
"""\
oo \n\
/ \n\
| \n\
| x \n\
| x dx \n\
| \n\
/ \n\
-oo \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
k = 0 \
"""
ucode_str = \
u("""\
∞ \n\
⌠ \n\
⎮ x \n\
⎮ x dx \n\
⌡ \n\
-∞ \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
k = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (
k, x + n + x**2 + n**2 + (x/n) + (1/x), Integral(x**x, (x, -oo, oo))))
ascii_str = \
"""\
oo \n\
/ \n\
| \n\
| x \n\
| x dx \n\
| \n\
/ \n\
-oo \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
2 2 1 x \n\
k = n + n + x + x + - + - \n\
x n \
"""
ucode_str = \
u("""\
∞ \n\
⌠ \n\
⎮ x \n\
⎮ x dx \n\
⌡ \n\
-∞ \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
2 2 1 x \n\
k = n + n + x + x + ─ + ─ \n\
x n \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(k**(
Integral(x**n, (x, -oo, oo))), (k, 0, x + n + x**2 + n**2 + (x/n) + (1/x)))
ascii_str = \
"""\
2 2 1 x \n\
n + n + x + x + - + - \n\
x n \n\
______ \n\
\\ ` \n\
\\ oo \n\
\\ / \n\
\\ | \n\
\\ | n \n\
) | x dx\n\
/ | \n\
/ / \n\
/ -oo \n\
/ k \n\
/_____, \n\
k = 0 \
"""
ucode_str = \
u("""\
2 2 1 x \n\
n + n + x + x + ─ + ─ \n\
x n \n\
______ \n\
╲ \n\
╲ \n\
╲ ∞ \n\
╲ ⌠ \n\
╲ ⎮ n \n\
╱ ⎮ x dx\n\
╱ ⌡ \n\
╱ -∞ \n\
╱ k \n\
╱ \n\
‾‾‾‾‾‾ \n\
k = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x, (x, 0, oo))
ascii_str = \
"""\
oo \n\
__ \n\
\\ ` \n\
) x\n\
/_, \n\
x = 0 \
"""
ucode_str = \
u("""\
∞ \n\
___ \n\
╲ \n\
╲ \n\
╱ x\n\
╱ \n\
‾‾‾ \n\
x = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x**2, (x, 0, oo))
ascii_str = \
u("""\
oo \n\
___ \n\
\\ ` \n\
\\ 2\n\
/ x \n\
/__, \n\
x = 0 \
""")
ucode_str = \
u("""\
∞ \n\
___ \n\
╲ \n\
╲ 2\n\
╱ x \n\
╱ \n\
‾‾‾ \n\
x = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x/2, (x, 0, oo))
ascii_str = \
"""\
oo \n\
___ \n\
\\ ` \n\
\\ x\n\
) -\n\
/ 2\n\
/__, \n\
x = 0 \
"""
ucode_str = \
u("""\
∞ \n\
____ \n\
╲ \n\
╲ \n\
╲ x\n\
╱ ─\n\
╱ 2\n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(x**3/2, (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ 3\n\
\\ x \n\
/ --\n\
/ 2 \n\
/___, \n\
x = 0 \
"""
ucode_str = \
u("""\
∞ \n\
____ \n\
╲ \n\
╲ 3\n\
╲ x \n\
╱ ──\n\
╱ 2 \n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum((x**3*y**(x/2))**n, (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ n\n\
\\ / x\\ \n\
) | -| \n\
/ | 3 2| \n\
/ \\x *y / \n\
/___, \n\
x = 0 \
"""
ucode_str = \
u("""\
∞ \n\
_____ \n\
╲ \n\
╲ \n\
╲ n\n\
╲ ⎛ x⎞ \n\
╱ ⎜ ─⎟ \n\
╱ ⎜ 3 2⎟ \n\
╱ ⎝x ⋅y ⎠ \n\
╱ \n\
‾‾‾‾‾ \n\
x = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(1/x**2, (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ 1 \n\
\\ --\n\
/ 2\n\
/ x \n\
/___, \n\
x = 0 \
"""
ucode_str = \
u("""\
∞ \n\
____ \n\
╲ \n\
╲ 1 \n\
╲ ──\n\
╱ 2\n\
╱ x \n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(1/y**(a/b), (x, 0, oo))
ascii_str = \
"""\
oo \n\
____ \n\
\\ ` \n\
\\ -a \n\
\\ ---\n\
/ b \n\
/ y \n\
/___, \n\
x = 0 \
"""
ucode_str = \
u("""\
∞ \n\
____ \n\
╲ \n\
╲ -a \n\
╲ ───\n\
╱ b \n\
╱ y \n\
╱ \n\
‾‾‾‾ \n\
x = 0 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Sum(1/y**(a/b), (x, 0, oo), (y, 1, 2))
ascii_str = \
"""\
2 oo \n\
____ ____ \n\
\\ ` \\ ` \n\
\\ \\ -a\n\
\\ \\ --\n\
/ / b \n\
/ / y \n\
/___, /___, \n\
y = 1 x = 0 \
"""
ucode_str = \
u("""\
2 ∞ \n\
____ ____ \n\
╲ ╲ \n\
╲ ╲ -a\n\
╲ ╲ ──\n\
╱ ╱ b \n\
╱ ╱ y \n\
╱ ╱ \n\
‾‾‾‾ ‾‾‾‾ \n\
y = 1 x = 0 \
""")
expr = Sum(1/(1 + 1/(
1 + 1/k)) + 1, (k, 111, 1 + 1/n), (k, 1/(1 + m), oo)) + 1/(1 + 1/k)
ascii_str = \
"""\
1 \n\
1 + - \n\
oo n \n\
_____ _____ \n\
\\ ` \\ ` \n\
\\ \\ / 1 \\ \n\
\\ \\ |1 + ---------| \n\
\\ \\ | 1 | 1 \n\
) ) | 1 + -----| + -----\n\
/ / | 1| 1\n\
/ / | 1 + -| 1 + -\n\
/ / \\ k/ k\n\
/____, /____, \n\
1 k = 111 \n\
k = ----- \n\
m + 1 \
"""
ucode_str = \
u("""\
1 \n\
1 + ─ \n\
∞ n \n\
______ ______ \n\
╲ ╲ \n\
╲ ╲ \n\
╲ ╲ ⎛ 1 ⎞ \n\
╲ ╲ ⎜1 + ─────────⎟ \n\
╲ ╲ ⎜ 1 ⎟ 1 \n\
╱ ╱ ⎜ 1 + ─────⎟ + ─────\n\
╱ ╱ ⎜ 1⎟ 1\n\
╱ ╱ ⎜ 1 + ─⎟ 1 + ─\n\
╱ ╱ ⎝ k⎠ k\n\
╱ ╱ \n\
‾‾‾‾‾‾ ‾‾‾‾‾‾ \n\
1 k = 111 \n\
k = ───── \n\
m + 1 \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_units():
expr = joule
ascii_str1 = \
"""\
2\n\
kilogram*meter \n\
---------------\n\
2 \n\
second \
"""
unicode_str1 = \
u("""\
2\n\
kilogram⋅meter \n\
───────────────\n\
2 \n\
second \
""")
ascii_str2 = \
"""\
2\n\
3*x*y*kilogram*meter \n\
---------------------\n\
2 \n\
second \
"""
unicode_str2 = \
u("""\
2\n\
3⋅x⋅y⋅kilogram⋅meter \n\
─────────────────────\n\
2 \n\
second \
""")
from sympy.physics.units import kg, m, s
assert upretty(expr) == u("joule")
assert pretty(expr) == "joule"
assert upretty(expr.convert_to(kg*m**2/s**2)) == unicode_str1
assert pretty(expr.convert_to(kg*m**2/s**2)) == ascii_str1
assert upretty(3*kg*x*m**2*y/s**2) == unicode_str2
assert pretty(3*kg*x*m**2*y/s**2) == ascii_str2
def test_pretty_Subs():
f = Function('f')
expr = Subs(f(x), x, ph**2)
ascii_str = \
"""\
(f(x))| 2\n\
|x=phi \
"""
unicode_str = \
u("""\
(f(x))│ 2\n\
│x=φ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Subs(f(x).diff(x), x, 0)
ascii_str = \
"""\
/d \\| \n\
|--(f(x))|| \n\
\\dx /|x=0\
"""
unicode_str = \
u("""\
⎛d ⎞│ \n\
⎜──(f(x))⎟│ \n\
⎝dx ⎠│x=0\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
expr = Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2)))
ascii_str = \
"""\
/d \\| \n\
|--(f(x))|| \n\
|dx || \n\
|--------|| \n\
\\ y /|x=0, y=1/2\
"""
unicode_str = \
u("""\
⎛d ⎞│ \n\
⎜──(f(x))⎟│ \n\
⎜dx ⎟│ \n\
⎜────────⎟│ \n\
⎝ y ⎠│x=0, y=1/2\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == unicode_str
def test_gammas():
assert upretty(lowergamma(x, y)) == u"γ(x, y)"
assert upretty(uppergamma(x, y)) == u"Γ(x, y)"
assert xpretty(gamma(x), use_unicode=True) == u'Γ(x)'
assert xpretty(gamma, use_unicode=True) == u'Γ'
assert xpretty(symbols('gamma', cls=Function)(x), use_unicode=True) == u'γ(x)'
assert xpretty(symbols('gamma', cls=Function), use_unicode=True) == u'γ'
def test_beta():
assert xpretty(beta(x,y), use_unicode=True) == u'Β(x, y)'
assert xpretty(beta(x,y), use_unicode=False) == u'B(x, y)'
assert xpretty(beta, use_unicode=True) == u'Β'
assert xpretty(beta, use_unicode=False) == u'B'
mybeta = Function('beta')
assert xpretty(mybeta(x), use_unicode=True) == u'β(x)'
assert xpretty(mybeta(x, y, z), use_unicode=False) == u'beta(x, y, z)'
assert xpretty(mybeta, use_unicode=True) == u'β'
# test that notation passes to subclasses of the same name only
def test_function_subclass_different_name():
class mygamma(gamma):
pass
assert xpretty(mygamma, use_unicode=True) == r"mygamma"
assert xpretty(mygamma(x), use_unicode=True) == r"mygamma(x)"
def test_SingularityFunction():
assert xpretty(SingularityFunction(x, 0, n), use_unicode=True) == (
"""\
n\n\
<x> \
""")
assert xpretty(SingularityFunction(x, 1, n), use_unicode=True) == (
"""\
n\n\
<x - 1> \
""")
assert xpretty(SingularityFunction(x, -1, n), use_unicode=True) == (
"""\
n\n\
<x + 1> \
""")
assert xpretty(SingularityFunction(x, a, n), use_unicode=True) == (
"""\
n\n\
<-a + x> \
""")
assert xpretty(SingularityFunction(x, y, n), use_unicode=True) == (
"""\
n\n\
<x - y> \
""")
assert xpretty(SingularityFunction(x, 0, n), use_unicode=False) == (
"""\
n\n\
<x> \
""")
assert xpretty(SingularityFunction(x, 1, n), use_unicode=False) == (
"""\
n\n\
<x - 1> \
""")
assert xpretty(SingularityFunction(x, -1, n), use_unicode=False) == (
"""\
n\n\
<x + 1> \
""")
assert xpretty(SingularityFunction(x, a, n), use_unicode=False) == (
"""\
n\n\
<-a + x> \
""")
assert xpretty(SingularityFunction(x, y, n), use_unicode=False) == (
"""\
n\n\
<x - y> \
""")
def test_deltas():
assert xpretty(DiracDelta(x), use_unicode=True) == u'δ(x)'
assert xpretty(DiracDelta(x, 1), use_unicode=True) == \
u("""\
(1) \n\
δ (x)\
""")
assert xpretty(x*DiracDelta(x, 1), use_unicode=True) == \
u("""\
(1) \n\
x⋅δ (x)\
""")
def test_hyper():
expr = hyper((), (), z)
ucode_str = \
u("""\
┌─ ⎛ │ ⎞\n\
├─ ⎜ │ z⎟\n\
0╵ 0 ⎝ │ ⎠\
""")
ascii_str = \
"""\
_ \n\
|_ / | \\\n\
| | | z|\n\
0 0 \\ | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper((), (1,), x)
ucode_str = \
u("""\
┌─ ⎛ │ ⎞\n\
├─ ⎜ │ x⎟\n\
0╵ 1 ⎝1 │ ⎠\
""")
ascii_str = \
"""\
_ \n\
|_ / | \\\n\
| | | x|\n\
0 1 \\1 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper([2], [1], x)
ucode_str = \
u("""\
┌─ ⎛2 │ ⎞\n\
├─ ⎜ │ x⎟\n\
1╵ 1 ⎝1 │ ⎠\
""")
ascii_str = \
"""\
_ \n\
|_ /2 | \\\n\
| | | x|\n\
1 1 \\1 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper((pi/3, -2*k), (3, 4, 5, -3), x)
ucode_str = \
u("""\
⎛ π │ ⎞\n\
┌─ ⎜ ─, -2⋅k │ ⎟\n\
├─ ⎜ 3 │ x⎟\n\
2╵ 4 ⎜ │ ⎟\n\
⎝3, 4, 5, -3 │ ⎠\
""")
ascii_str = \
"""\
\n\
_ / pi | \\\n\
|_ | --, -2*k | |\n\
| | 3 | x|\n\
2 4 | | |\n\
\\3, 4, 5, -3 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper((pi, S('2/3'), -2*k), (3, 4, 5, -3), x**2)
ucode_str = \
u("""\
┌─ ⎛π, 2/3, -2⋅k │ 2⎞\n\
├─ ⎜ │ x ⎟\n\
3╵ 4 ⎝3, 4, 5, -3 │ ⎠\
""")
ascii_str = \
"""\
_ \n\
|_ /pi, 2/3, -2*k | 2\\\n\
| | | x |\n\
3 4 \\ 3, 4, 5, -3 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hyper([1, 2], [3, 4], 1/(1/(1/(1/x + 1) + 1) + 1))
ucode_str = \
u("""\
⎛ │ 1 ⎞\n\
⎜ │ ─────────────⎟\n\
⎜ │ 1 ⎟\n\
┌─ ⎜1, 2 │ 1 + ─────────⎟\n\
├─ ⎜ │ 1 ⎟\n\
2╵ 2 ⎜3, 4 │ 1 + ─────⎟\n\
⎜ │ 1⎟\n\
⎜ │ 1 + ─⎟\n\
⎝ │ x⎠\
""")
ascii_str = \
"""\
\n\
/ | 1 \\\n\
| | -------------|\n\
_ | | 1 |\n\
|_ |1, 2 | 1 + ---------|\n\
| | | 1 |\n\
2 2 |3, 4 | 1 + -----|\n\
| | 1|\n\
| | 1 + -|\n\
\\ | x/\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_meijerg():
expr = meijerg([pi, pi, x], [1], [0, 1], [1, 2, 3], z)
ucode_str = \
u("""\
╭─╮2, 3 ⎛π, π, x 1 │ ⎞\n\
│╶┐ ⎜ │ z⎟\n\
╰─╯4, 5 ⎝ 0, 1 1, 2, 3 │ ⎠\
""")
ascii_str = \
"""\
__2, 3 /pi, pi, x 1 | \\\n\
/__ | | z|\n\
\\_|4, 5 \\ 0, 1 1, 2, 3 | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = meijerg([1, pi/7], [2, pi, 5], [], [], z**2)
ucode_str = \
u("""\
⎛ π │ ⎞\n\
╭─╮0, 2 ⎜1, ─ 2, π, 5 │ 2⎟\n\
│╶┐ ⎜ 7 │ z ⎟\n\
╰─╯5, 0 ⎜ │ ⎟\n\
⎝ │ ⎠\
""")
ascii_str = \
"""\
/ pi | \\\n\
__0, 2 |1, -- 2, pi, 5 | 2|\n\
/__ | 7 | z |\n\
\\_|5, 0 | | |\n\
\\ | /\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ucode_str = \
u("""\
╭─╮ 1, 10 ⎛1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 │ ⎞\n\
│╶┐ ⎜ │ z⎟\n\
╰─╯11, 2 ⎝ 1 1 │ ⎠\
""")
ascii_str = \
"""\
__ 1, 10 /1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 | \\\n\
/__ | | z|\n\
\\_|11, 2 \\ 1 1 | /\
"""
expr = meijerg([1]*10, [1], [1], [1], z)
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = meijerg([1, 2, ], [4, 3], [3], [4, 5], 1/(1/(1/(1/x + 1) + 1) + 1))
ucode_str = \
u("""\
⎛ │ 1 ⎞\n\
⎜ │ ─────────────⎟\n\
⎜ │ 1 ⎟\n\
╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟\n\
│╶┐ ⎜ │ 1 ⎟\n\
╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟\n\
⎜ │ 1⎟\n\
⎜ │ 1 + ─⎟\n\
⎝ │ x⎠\
""")
ascii_str = \
"""\
/ | 1 \\\n\
| | -------------|\n\
| | 1 |\n\
__1, 2 |1, 2 4, 3 | 1 + ---------|\n\
/__ | | 1 |\n\
\\_|4, 3 | 3 4, 5 | 1 + -----|\n\
| | 1|\n\
| | 1 + -|\n\
\\ | x/\
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = Integral(expr, x)
ucode_str = \
u("""\
⌠ \n\
⎮ ⎛ │ 1 ⎞ \n\
⎮ ⎜ │ ─────────────⎟ \n\
⎮ ⎜ │ 1 ⎟ \n\
⎮ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟ \n\
⎮ │╶┐ ⎜ │ 1 ⎟ dx\n\
⎮ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟ \n\
⎮ ⎜ │ 1⎟ \n\
⎮ ⎜ │ 1 + ─⎟ \n\
⎮ ⎝ │ x⎠ \n\
⌡ \
""")
ascii_str = \
"""\
/ \n\
| \n\
| / | 1 \\ \n\
| | | -------------| \n\
| | | 1 | \n\
| __1, 2 |1, 2 4, 3 | 1 + ---------| \n\
| /__ | | 1 | dx\n\
| \\_|4, 3 | 3 4, 5 | 1 + -----| \n\
| | | 1| \n\
| | | 1 + -| \n\
| \\ | x/ \n\
| \n\
/ \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_noncommutative():
A, B, C = symbols('A,B,C', commutative=False)
expr = A*B*C**-1
ascii_str = \
"""\
-1\n\
A*B*C \
"""
ucode_str = \
u("""\
-1\n\
A⋅B⋅C \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = C**-1*A*B
ascii_str = \
"""\
-1 \n\
C *A*B\
"""
ucode_str = \
u("""\
-1 \n\
C ⋅A⋅B\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A*C**-1*B
ascii_str = \
"""\
-1 \n\
A*C *B\
"""
ucode_str = \
u("""\
-1 \n\
A⋅C ⋅B\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A*C**-1*B/x
ascii_str = \
"""\
-1 \n\
A*C *B\n\
-------\n\
x \
"""
ucode_str = \
u("""\
-1 \n\
A⋅C ⋅B\n\
───────\n\
x \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_special_functions():
x, y = symbols("x y")
# atan2
expr = atan2(y/sqrt(200), sqrt(x))
ascii_str = \
"""\
/ ___ \\\n\
|\\/ 2 *y ___|\n\
atan2|-------, \\/ x |\n\
\\ 20 /\
"""
ucode_str = \
u("""\
⎛√2⋅y ⎞\n\
atan2⎜────, √x⎟\n\
⎝ 20 ⎠\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_geometry():
e = Segment((0, 1), (0, 2))
assert pretty(e) == 'Segment2D(Point2D(0, 1), Point2D(0, 2))'
e = Ray((1, 1), angle=4.02*pi)
assert pretty(e) == 'Ray2D(Point2D(1, 1), Point2D(2, tan(pi/50) + 1))'
def test_expint():
expr = Ei(x)
string = 'Ei(x)'
assert pretty(expr) == string
assert upretty(expr) == string
expr = expint(1, z)
ucode_str = u"E₁(z)"
ascii_str = "expint(1, z)"
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
assert pretty(Shi(x)) == 'Shi(x)'
assert pretty(Si(x)) == 'Si(x)'
assert pretty(Ci(x)) == 'Ci(x)'
assert pretty(Chi(x)) == 'Chi(x)'
assert upretty(Shi(x)) == 'Shi(x)'
assert upretty(Si(x)) == 'Si(x)'
assert upretty(Ci(x)) == 'Ci(x)'
assert upretty(Chi(x)) == 'Chi(x)'
def test_elliptic_functions():
ascii_str = \
"""\
/ 1 \\\n\
K|-----|\n\
\\z + 1/\
"""
ucode_str = \
u("""\
⎛ 1 ⎞\n\
K⎜─────⎟\n\
⎝z + 1⎠\
""")
expr = elliptic_k(1/(z + 1))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ | 1 \\\n\
F|1|-----|\n\
\\ |z + 1/\
"""
ucode_str = \
u("""\
⎛ │ 1 ⎞\n\
F⎜1│─────⎟\n\
⎝ │z + 1⎠\
""")
expr = elliptic_f(1, 1/(1 + z))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ 1 \\\n\
E|-----|\n\
\\z + 1/\
"""
ucode_str = \
u("""\
⎛ 1 ⎞\n\
E⎜─────⎟\n\
⎝z + 1⎠\
""")
expr = elliptic_e(1/(z + 1))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ | 1 \\\n\
E|1|-----|\n\
\\ |z + 1/\
"""
ucode_str = \
u("""\
⎛ │ 1 ⎞\n\
E⎜1│─────⎟\n\
⎝ │z + 1⎠\
""")
expr = elliptic_e(1, 1/(1 + z))
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ |4\\\n\
Pi|3|-|\n\
\\ |x/\
"""
ucode_str = \
u("""\
⎛ │4⎞\n\
Π⎜3│─⎟\n\
⎝ │x⎠\
""")
expr = elliptic_pi(3, 4/x)
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
ascii_str = \
"""\
/ 4| \\\n\
Pi|3; -|6|\n\
\\ x| /\
"""
ucode_str = \
u("""\
⎛ 4│ ⎞\n\
Π⎜3; ─│6⎟\n\
⎝ x│ ⎠\
""")
expr = elliptic_pi(3, 4/x, 6)
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_RandomDomain():
from sympy.stats import Normal, Die, Exponential, pspace, where
X = Normal('x1', 0, 1)
assert upretty(where(X > 0)) == u"Domain: 0 < x₁ ∧ x₁ < ∞"
D = Die('d1', 6)
assert upretty(where(D > 4)) == u'Domain: d₁ = 5 ∨ d₁ = 6'
A = Exponential('a', 1)
B = Exponential('b', 1)
assert upretty(pspace(Tuple(A, B)).domain) == \
u'Domain: 0 ≤ a ∧ 0 ≤ b ∧ a < ∞ ∧ b < ∞'
def test_PrettyPoly():
F = QQ.frac_field(x, y)
R = QQ.poly_ring(x, y)
expr = F.convert(x/(x + y))
assert pretty(expr) == "x/(x + y)"
assert upretty(expr) == u"x/(x + y)"
expr = R.convert(x + y)
assert pretty(expr) == "x + y"
assert upretty(expr) == u"x + y"
def test_issue_6285():
assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 '
assert pretty(Pow(x, (1/pi))) == 'pi___\n\\/ x '
def test_issue_6359():
assert pretty(Integral(x**2, x)**2) == \
"""\
2
/ / \\ \n\
| | | \n\
| | 2 | \n\
| | x dx| \n\
| | | \n\
\\/ / \
"""
assert upretty(Integral(x**2, x)**2) == \
u("""\
2
⎛⌠ ⎞ \n\
⎜⎮ 2 ⎟ \n\
⎜⎮ x dx⎟ \n\
⎝⌡ ⎠ \
""")
assert pretty(Sum(x**2, (x, 0, 1))**2) == \
"""\
2
/ 1 \\ \n\
| ___ | \n\
| \\ ` | \n\
| \\ 2| \n\
| / x | \n\
| /__, | \n\
\\x = 0 / \
"""
assert upretty(Sum(x**2, (x, 0, 1))**2) == \
u("""\
2
⎛ 1 ⎞ \n\
⎜ ___ ⎟ \n\
⎜ ╲ ⎟ \n\
⎜ ╲ 2⎟ \n\
⎜ ╱ x ⎟ \n\
⎜ ╱ ⎟ \n\
⎜ ‾‾‾ ⎟ \n\
⎝x = 0 ⎠ \
""")
assert pretty(Product(x**2, (x, 1, 2))**2) == \
"""\
2
/ 2 \\ \n\
|______ | \n\
| | | 2| \n\
| | | x | \n\
| | | | \n\
\\x = 1 / \
"""
assert upretty(Product(x**2, (x, 1, 2))**2) == \
u("""\
2
⎛ 2 ⎞ \n\
⎜─┬──┬─ ⎟ \n\
⎜ │ │ 2⎟ \n\
⎜ │ │ x ⎟ \n\
⎜ │ │ ⎟ \n\
⎝x = 1 ⎠ \
""")
f = Function('f')
assert pretty(Derivative(f(x), x)**2) == \
"""\
2
/d \\ \n\
|--(f(x))| \n\
\\dx / \
"""
assert upretty(Derivative(f(x), x)**2) == \
u("""\
2
⎛d ⎞ \n\
⎜──(f(x))⎟ \n\
⎝dx ⎠ \
""")
def test_issue_6739():
ascii_str = \
"""\
1 \n\
-----\n\
___\n\
\\/ x \
"""
ucode_str = \
u("""\
1 \n\
──\n\
√x\
""")
assert pretty(1/sqrt(x)) == ascii_str
assert upretty(1/sqrt(x)) == ucode_str
def test_complicated_symbol_unchanged():
for symb_name in ["dexpr2_d1tau", "dexpr2^d1tau"]:
assert pretty(Symbol(symb_name)) == symb_name
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 pretty(A1) == "A1"
assert upretty(A1) == u"A₁"
assert pretty(f1) == "f1:A1-->A2"
assert upretty(f1) == u"f₁:A₁——▶A₂"
assert pretty(id_A1) == "id:A1-->A1"
assert upretty(id_A1) == u"id:A₁——▶A₁"
assert pretty(f2*f1) == "f2*f1:A1-->A3"
assert upretty(f2*f1) == u"f₂∘f₁:A₁——▶A₃"
assert pretty(K1) == "K1"
assert upretty(K1) == u"K₁"
# Test how diagrams are printed.
d = Diagram()
assert pretty(d) == "EmptySet()"
assert upretty(d) == u"∅"
d = Diagram({f1: "unique", f2: S.EmptySet})
assert pretty(d) == "{f2*f1:A1-->A3: EmptySet(), id:A1-->A1: " \
"EmptySet(), id:A2-->A2: EmptySet(), id:A3-->A3: " \
"EmptySet(), f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet()}"
assert upretty(d) == u("{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, " \
"id:A₂——▶A₂: ∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}")
d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"})
assert pretty(d) == "{f2*f1:A1-->A3: EmptySet(), id:A1-->A1: " \
"EmptySet(), id:A2-->A2: EmptySet(), id:A3-->A3: " \
"EmptySet(), f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet()}" \
" ==> {f2*f1:A1-->A3: {unique}}"
assert upretty(d) == u("{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, id:A₂——▶A₂: " \
"∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" \
" ══▶ {f₂∘f₁:A₁——▶A₃: {unique}}")
grid = DiagramGrid(d)
assert pretty(grid) == "A1 A2\n \nA3 "
assert upretty(grid) == u"A₁ A₂\n \nA₃ "
def test_PrettyModules():
R = QQ.old_poly_ring(x, y)
F = R.free_module(2)
M = F.submodule([x, y], [1, x**2])
ucode_str = \
u("""\
2\n\
ℚ[x, y] \
""")
ascii_str = \
"""\
2\n\
QQ[x, y] \
"""
assert upretty(F) == ucode_str
assert pretty(F) == ascii_str
ucode_str = \
u("""\
╱ ⎡ 2⎤╲\n\
╲[x, y], ⎣1, x ⎦╱\
""")
ascii_str = \
"""\
2 \n\
<[x, y], [1, x ]>\
"""
assert upretty(M) == ucode_str
assert pretty(M) == ascii_str
I = R.ideal(x**2, y)
ucode_str = \
u("""\
╱ 2 ╲\n\
╲x , y╱\
""")
ascii_str = \
"""\
2 \n\
<x , y>\
"""
assert upretty(I) == ucode_str
assert pretty(I) == ascii_str
Q = F / M
ucode_str = \
u("""\
2 \n\
ℚ[x, y] \n\
─────────────────\n\
╱ ⎡ 2⎤╲\n\
╲[x, y], ⎣1, x ⎦╱\
""")
ascii_str = \
"""\
2 \n\
QQ[x, y] \n\
-----------------\n\
2 \n\
<[x, y], [1, x ]>\
"""
assert upretty(Q) == ucode_str
assert pretty(Q) == ascii_str
ucode_str = \
u("""\
╱⎡ 3⎤ ╲\n\
│⎢ x ⎥ ╱ ⎡ 2⎤╲ ╱ ⎡ 2⎤╲│\n\
│⎢1, ──⎥ + ╲[x, y], ⎣1, x ⎦╱, [2, y] + ╲[x, y], ⎣1, x ⎦╱│\n\
╲⎣ 2 ⎦ ╱\
""")
ascii_str = \
"""\
3 \n\
x 2 2 \n\
<[1, --] + <[x, y], [1, x ]>, [2, y] + <[x, y], [1, x ]>>\n\
2 \
"""
def test_QuotientRing():
R = QQ.old_poly_ring(x)/[x**2 + 1]
ucode_str = \
u("""\
ℚ[x] \n\
────────\n\
╱ 2 ╲\n\
╲x + 1╱\
""")
ascii_str = \
"""\
QQ[x] \n\
--------\n\
2 \n\
<x + 1>\
"""
assert upretty(R) == ucode_str
assert pretty(R) == ascii_str
ucode_str = \
u("""\
╱ 2 ╲\n\
1 + ╲x + 1╱\
""")
ascii_str = \
"""\
2 \n\
1 + <x + 1>\
"""
assert upretty(R.one) == ucode_str
assert pretty(R.one) == ascii_str
def test_Homomorphism():
from sympy.polys.agca import homomorphism
R = QQ.old_poly_ring(x)
expr = homomorphism(R.free_module(1), R.free_module(1), [0])
ucode_str = \
u("""\
1 1\n\
[0] : ℚ[x] ──> ℚ[x] \
""")
ascii_str = \
"""\
1 1\n\
[0] : QQ[x] --> QQ[x] \
"""
assert upretty(expr) == ucode_str
assert pretty(expr) == ascii_str
expr = homomorphism(R.free_module(2), R.free_module(2), [0, 0])
ucode_str = \
u("""\
⎡0 0⎤ 2 2\n\
⎢ ⎥ : ℚ[x] ──> ℚ[x] \n\
⎣0 0⎦ \
""")
ascii_str = \
"""\
[0 0] 2 2\n\
[ ] : QQ[x] --> QQ[x] \n\
[0 0] \
"""
assert upretty(expr) == ucode_str
assert pretty(expr) == ascii_str
expr = homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])
ucode_str = \
u("""\
1\n\
1 ℚ[x] \n\
[0] : ℚ[x] ──> ─────\n\
<[x]>\
""")
ascii_str = \
"""\
1\n\
1 QQ[x] \n\
[0] : QQ[x] --> ------\n\
<[x]> \
"""
assert upretty(expr) == ucode_str
assert pretty(expr) == ascii_str
def test_Tr():
A, B = symbols('A B', commutative=False)
t = Tr(A*B)
assert pretty(t) == r'Tr(A*B)'
assert upretty(t) == u'Tr(A⋅B)'
def test_pretty_Add():
eq = Mul(-2, x - 2, evaluate=False) + 5
assert pretty(eq) == '5 - 2*(x - 2)'
def test_issue_7179():
assert upretty(Not(Equivalent(x, y))) == u'x ⇎ y'
assert upretty(Not(Implies(x, y))) == u'x ↛ y'
def test_issue_7180():
assert upretty(Equivalent(x, y)) == u'x ⇔ y'
def test_pretty_Complement():
assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \\ Naturals'
assert upretty(S.Reals - S.Naturals) == u'ℝ \\ ℕ'
assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \\ Naturals0'
assert upretty(S.Reals - S.Naturals0) == u'ℝ \\ ℕ₀'
def test_pretty_SymmetricDifference():
from sympy import SymmetricDifference, Interval
from sympy.utilities.pytest import raises
assert upretty(SymmetricDifference(Interval(2,3), Interval(3,5), \
evaluate = False)) == u'[2, 3] ∆ [3, 5]'
with raises(NotImplementedError):
pretty(SymmetricDifference(Interval(2,3), Interval(3,5), evaluate = False))
def test_pretty_Contains():
assert pretty(Contains(x, S.Integers)) == 'Contains(x, Integers)'
assert upretty(Contains(x, S.Integers)) == u'x ∈ ℤ'
def test_issue_8292():
from sympy.core import sympify
e = sympify('((x+x**4)/(x-1))-(2*(x-1)**4/(x-1)**4)', evaluate=False)
ucode_str = \
u("""\
4 4 \n\
2⋅(x - 1) x + x\n\
- ────────── + ──────\n\
4 x - 1 \n\
(x - 1) \
""")
ascii_str = \
"""\
4 4 \n\
2*(x - 1) x + x\n\
- ---------- + ------\n\
4 x - 1 \n\
(x - 1) \
"""
assert pretty(e) == ascii_str
assert upretty(e) == ucode_str
def test_issue_4335():
y = Function('y')
expr = -y(x).diff(x)
ucode_str = \
u("""\
d \n\
-──(y(x))\n\
dx \
""")
ascii_str = \
"""\
d \n\
- --(y(x))\n\
dx \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_8344():
from sympy.core import sympify
e = sympify('2*x*y**2/1**2 + 1', evaluate=False)
ucode_str = \
u("""\
2 \n\
2⋅x⋅y \n\
────── + 1\n\
2 \n\
1 \
""")
assert upretty(e) == ucode_str
def test_issue_6324():
x = Pow(2, 3, evaluate=False)
y = Pow(10, -2, evaluate=False)
e = Mul(x, y, evaluate=False)
ucode_str = \
u("""\
3\n\
2 \n\
───\n\
2\n\
10 \
""")
assert upretty(e) == ucode_str
def test_issue_7927():
e = sin(x/2)**cos(x/2)
ucode_str = \
u("""\
⎛x⎞\n\
cos⎜─⎟\n\
⎝2⎠\n\
⎛ ⎛x⎞⎞ \n\
⎜sin⎜─⎟⎟ \n\
⎝ ⎝2⎠⎠ \
""")
assert upretty(e) == ucode_str
e = sin(x)**(S(11)/13)
ucode_str = \
u("""\
11\n\
──\n\
13\n\
(sin(x)) \
""")
assert upretty(e) == ucode_str
def test_issue_6134():
from sympy.abc import lamda, t
phi = Function('phi')
e = lamda*x*Integral(phi(t)*pi*sin(pi*t), (t, 0, 1)) + lamda*x**2*Integral(phi(t)*2*pi*sin(2*pi*t), (t, 0, 1))
ucode_str = \
u("""\
1 1 \n\
2 ⌠ ⌠ \n\
λ⋅x ⋅⎮ 2⋅π⋅φ(t)⋅sin(2⋅π⋅t) dt + λ⋅x⋅⎮ π⋅φ(t)⋅sin(π⋅t) dt\n\
⌡ ⌡ \n\
0 0 \
""")
assert upretty(e) == ucode_str
def test_issue_9877():
ucode_str1 = u'(2, 3) ∪ ([1, 2] \\ {x})'
a, b, c = Interval(2, 3, True, True), Interval(1, 2), FiniteSet(x)
assert upretty(Union(a, Complement(b, c))) == ucode_str1
ucode_str2 = u'{x} ∩ {y} ∩ ({z} \\ [1, 2])'
d, e, f, g = FiniteSet(x), FiniteSet(y), FiniteSet(z), Interval(1, 2)
assert upretty(Intersection(d, e, Complement(f, g))) == ucode_str2
def test_issue_13651():
expr1 = c + Mul(-1, a + b, evaluate=False)
assert pretty(expr1) == 'c - (a + b)'
expr2 = c + Mul(-1, a - b + d, evaluate=False)
assert pretty(expr2) == 'c - (a - b + d)'
def test_pretty_primenu():
from sympy.ntheory.factor_ import primenu
ascii_str1 = "nu(n)"
ucode_str1 = u("ν(n)")
n = symbols('n', integer=True)
assert pretty(primenu(n)) == ascii_str1
assert upretty(primenu(n)) == ucode_str1
def test_pretty_primeomega():
from sympy.ntheory.factor_ import primeomega
ascii_str1 = "Omega(n)"
ucode_str1 = u("Ω(n)")
n = symbols('n', integer=True)
assert pretty(primeomega(n)) == ascii_str1
assert upretty(primeomega(n)) == ucode_str1
def test_pretty_Mod():
from sympy.core import Mod
ascii_str1 = "x mod 7"
ucode_str1 = u("x mod 7")
ascii_str2 = "(x + 1) mod 7"
ucode_str2 = u("(x + 1) mod 7")
ascii_str3 = "2*x mod 7"
ucode_str3 = u("2⋅x mod 7")
ascii_str4 = "(x mod 7) + 1"
ucode_str4 = u("(x mod 7) + 1")
ascii_str5 = "2*(x mod 7)"
ucode_str5 = u("2⋅(x mod 7)")
x = symbols('x', integer=True)
assert pretty(Mod(x, 7)) == ascii_str1
assert upretty(Mod(x, 7)) == ucode_str1
assert pretty(Mod(x + 1, 7)) == ascii_str2
assert upretty(Mod(x + 1, 7)) == ucode_str2
assert pretty(Mod(2 * x, 7)) == ascii_str3
assert upretty(Mod(2 * x, 7)) == ucode_str3
assert pretty(Mod(x, 7) + 1) == ascii_str4
assert upretty(Mod(x, 7) + 1) == ucode_str4
assert pretty(2 * Mod(x, 7)) == ascii_str5
assert upretty(2 * Mod(x, 7)) == ucode_str5
def test_issue_11801():
assert pretty(Symbol("")) == ""
assert upretty(Symbol("")) == ""
def test_pretty_UnevaluatedExpr():
x = symbols('x')
he = UnevaluatedExpr(1/x)
ucode_str = \
u("""\
1\n\
─\n\
x\
""")
assert upretty(he) == ucode_str
ucode_str = \
u("""\
2\n\
⎛1⎞ \n\
⎜─⎟ \n\
⎝x⎠ \
""")
assert upretty(he**2) == ucode_str
ucode_str = \
u("""\
1\n\
1 + ─\n\
x\
""")
assert upretty(he + 1) == ucode_str
ucode_str = \
u('''\
1\n\
x⋅─\n\
x\
''')
assert upretty(x*he) == ucode_str
def test_issue_10472():
M = (Matrix([[0, 0], [0, 0]]), Matrix([0, 0]))
ucode_str = \
u("""\
⎛⎡0 0⎤ ⎡0⎤⎞
⎜⎢ ⎥, ⎢ ⎥⎟
⎝⎣0 0⎦ ⎣0⎦⎠\
""")
assert upretty(M) == ucode_str
def test_MatrixElement_printing():
# test cases for issue #11821
A = MatrixSymbol("A", 1, 3)
B = MatrixSymbol("B", 1, 3)
C = MatrixSymbol("C", 1, 3)
ascii_str1 = "A_00"
ucode_str1 = u("A₀₀")
assert pretty(A[0, 0]) == ascii_str1
assert upretty(A[0, 0]) == ucode_str1
ascii_str1 = "3*A_00"
ucode_str1 = u("3⋅A₀₀")
assert pretty(3*A[0, 0]) == ascii_str1
assert upretty(3*A[0, 0]) == ucode_str1
ascii_str1 = "(-B + A)[0, 0]"
ucode_str1 = u("(-B + A)[0, 0]")
F = C[0, 0].subs(C, A - B)
assert pretty(F) == ascii_str1
assert upretty(F) == ucode_str1
def test_issue_12675():
from sympy.vector import CoordSys3D
x, y, t, j = symbols('x y t j')
e = CoordSys3D('e')
ucode_str = \
u("""\
⎛ t⎞ \n\
⎜⎛x⎞ ⎟ j_e\n\
⎜⎜─⎟ ⎟ \n\
⎝⎝y⎠ ⎠ \
""")
assert upretty((x/y)**t*e.j) == ucode_str
ucode_str = \
u("""\
⎛1⎞ \n\
⎜─⎟ j_e\n\
⎝y⎠ \
""")
assert upretty((1/y)*e.j) == ucode_str
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 pretty(-A*B*C) == "-A*B*C"
assert pretty(A - B) == "-B + A"
assert pretty(A*B*C - A*B - B*C) == "-A*B -B*C + A*B*C"
# issue #14814
x = MatrixSymbol('x', n, n)
y = MatrixSymbol('y*', n, n)
assert pretty(x + y) == "x + y*"
ascii_str = \
"""\
2 \n\
-2*y* -a*x\
"""
assert pretty(-a*x + -2*y*y) == ascii_str
def test_degree_printing():
expr1 = 90*degree
assert pretty(expr1) == u'90°'
expr2 = x*degree
assert pretty(expr2) == u'x°'
expr3 = cos(x*degree + 90*degree)
assert pretty(expr3) == u'cos(x° + 90°)'
def test_vector_expr_pretty_printing():
A = CoordSys3D('A')
assert upretty(Cross(A.i, A.x*A.i+3*A.y*A.j)) == u("(i_A)×((x_A) i_A + (3⋅y_A) j_A)")
assert upretty(x*Cross(A.i, A.j)) == u('x⋅(i_A)×(j_A)')
assert upretty(Curl(A.x*A.i + 3*A.y*A.j)) == u("∇×((x_A) i_A + (3⋅y_A) j_A)")
assert upretty(Divergence(A.x*A.i + 3*A.y*A.j)) == u("∇⋅((x_A) i_A + (3⋅y_A) j_A)")
assert upretty(Dot(A.i, A.x*A.i+3*A.y*A.j)) == u("(i_A)⋅((x_A) i_A + (3⋅y_A) j_A)")
assert upretty(Gradient(A.x+3*A.y)) == u("∇(x_A + 3⋅y_A)")
assert upretty(Laplacian(A.x+3*A.y)) == u("∆(x_A + 3⋅y_A)")
# TODO: add support for ASCII pretty.
def test_pretty_print_tensor_expr():
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
i0 = tensor_indices("i_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
expr = -i
ascii_str = \
"""\
-i\
"""
ucode_str = \
u("""\
-i\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i)
ascii_str = \
"""\
i\n\
A \n\
\
"""
ucode_str = \
u("""\
i\n\
A \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i0)
ascii_str = \
"""\
i_0\n\
A \n\
\
"""
ucode_str = \
u("""\
i₀\n\
A \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(-i)
ascii_str = \
"""\
\n\
A \n\
i\
"""
ucode_str = \
u("""\
\n\
A \n\
i\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = -3*A(-i)
ascii_str = \
"""\
\n\
-3*A \n\
i\
"""
ucode_str = \
u("""\
\n\
-3⋅A \n\
i\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = H(i, -j)
ascii_str = \
"""\
i \n\
H \n\
j\
"""
ucode_str = \
u("""\
i \n\
H \n\
j\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = H(i, -i)
ascii_str = \
"""\
L_0 \n\
H \n\
L_0\
"""
ucode_str = \
u("""\
L₀ \n\
H \n\
L₀\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = H(i, -j)*A(j)*B(k)
ascii_str = \
"""\
i L_0 k\n\
H *A *B \n\
L_0 \
"""
ucode_str = \
u("""\
i L₀ k\n\
H ⋅A ⋅B \n\
L₀ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (1+x)*A(i)
ascii_str = \
"""\
i\n\
(x + 1)*A \n\
\
"""
ucode_str = \
u("""\
i\n\
(x + 1)⋅A \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i) + 3*B(i)
ascii_str = \
"""\
i i\n\
A + 3*B \n\
\
"""
ucode_str = \
u("""\
i i\n\
A + 3⋅B \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_pretty_print_tensor_partial_deriv():
from sympy.tensor.toperators import PartialDerivative
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
i0 = tensor_indices("i0", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
expr = PartialDerivative(A(i), A(j))
ascii_str = \
"""\
d / i\\\n\
---|A |\n\
j\\ /\n\
dA \n\
\
"""
ucode_str = \
u("""\
∂ ⎛ i⎞\n\
───⎜A ⎟\n\
j⎝ ⎠\n\
∂A \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i)*PartialDerivative(H(k, -i), A(j))
ascii_str = \
"""\
L_0 d / k \\\n\
A *---|H |\n\
j\\ L_0/\n\
dA \n\
\
"""
ucode_str = \
u("""\
L₀ ∂ ⎛ k ⎞\n\
A ⋅───⎜H ⎟\n\
j⎝ L₀⎠\n\
∂A \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j))
ascii_str = \
"""\
L_0 d / k k \\\n\
A *---|B *C + 3*H |\n\
j\\ L_0 L_0/\n\
dA \n\
\
"""
ucode_str = \
u("""\
L₀ ∂ ⎛ k k ⎞\n\
A ⋅───⎜B ⋅C + 3⋅H ⎟\n\
j⎝ L₀ L₀⎠\n\
∂A \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (A(i) + B(i))*PartialDerivative(C(-j), D(j))
ascii_str = \
"""\
/ i i\\ d / \\\n\
|A + B |*-----|C |\n\
\\ / L_0\\ L_0/\n\
dD \n\
\
"""
ucode_str = \
u("""\
⎛ i i⎞ ∂ ⎛ ⎞\n\
⎜A + B ⎟⋅────⎜C ⎟\n\
⎝ ⎠ L₀⎝ L₀⎠\n\
∂D \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = (A(i) + B(i))*PartialDerivative(C(-i), D(j))
ascii_str = \
"""\
/ L_0 L_0\\ d / \\\n\
|A + B |*---|C |\n\
\\ / j\\ L_0/\n\
dD \n\
\
"""
ucode_str = \
u("""\
⎛ L₀ L₀⎞ ∂ ⎛ ⎞\n\
⎜A + B ⎟⋅───⎜C ⎟\n\
⎝ ⎠ j⎝ L₀⎠\n\
∂D \n\
\
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = TensorElement(H(i, j), {i:1})
ascii_str = \
"""\
i=1,j\n\
H \n\
\
"""
ucode_str = ascii_str
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = TensorElement(H(i, j), {i:1, j:1})
ascii_str = \
"""\
i=1,j=1\n\
H \n\
\
"""
ucode_str = ascii_str
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = TensorElement(H(i, j), {j:1})
ascii_str = \
"""\
i,j=1\n\
H \n\
\
"""
ucode_str = ascii_str
expr = TensorElement(H(-i, j), {-i:1})
ascii_str = \
"""\
j\n\
H \n\
i=1 \
"""
ucode_str = ascii_str
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_15560():
a = MatrixSymbol('a', 1, 1)
e = pretty(a*(KroneckerProduct(a, a)))
result = 'a*(a x a)'
assert e == result
def test_print_lerchphi():
# Part of issue 6013
a = Symbol('a')
pretty(lerchphi(a, 1, 2))
uresult = u'Φ(a, 1, 2)'
aresult = 'lerchphi(a, 1, 2)'
assert pretty(lerchphi(a, 1, 2)) == aresult
assert upretty(lerchphi(a, 1, 2)) == uresult
def test_issue_15583():
N = mechanics.ReferenceFrame('N')
result = '(n_x, n_y, n_z)'
e = pretty((N.x, N.y, N.z))
assert e == result
def test_matrixSymbolBold():
# Issue 15871
def boldpretty(expr):
return xpretty(expr, use_unicode=True, wrap_line=False, mat_symbol_style="bold")
from sympy import trace
A = MatrixSymbol("A", 2, 2)
assert boldpretty(trace(A)) == u'tr(𝐀)'
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
assert boldpretty(-A) == u'-𝐀'
assert boldpretty(A - A*B - B) == u'-𝐁 -𝐀⋅𝐁 + 𝐀'
assert boldpretty(-A*B - A*B*C - B) == u'-𝐁 -𝐀⋅𝐁 -𝐀⋅𝐁⋅𝐂'
A = MatrixSymbol("Addot", 3, 3)
assert boldpretty(A) == u'𝐀̈'
omega = MatrixSymbol("omega", 3, 3)
assert boldpretty(omega) == u'ω'
omega = MatrixSymbol("omeganorm", 3, 3)
assert boldpretty(omega) == u'‖ω‖'
a = Symbol('alpha')
b = Symbol('b')
c = MatrixSymbol("c", 3, 1)
d = MatrixSymbol("d", 3, 1)
assert boldpretty(a*B*c+b*d) == u'b⋅𝐝 + α⋅𝐁⋅𝐜'
d = MatrixSymbol("delta", 3, 1)
B = MatrixSymbol("Beta", 3, 3)
assert boldpretty(a*B*c+b*d) == u'b⋅δ + α⋅Β⋅𝐜'
A = MatrixSymbol("A_2", 3, 3)
assert boldpretty(A) == u'𝐀₂'
def test_center_accent():
assert center_accent('a', u'\N{COMBINING TILDE}') == u'ã'
assert center_accent('aa', u'\N{COMBINING TILDE}') == u'aã'
assert center_accent('aaa', u'\N{COMBINING TILDE}') == u'aãa'
assert center_accent('aaaa', u'\N{COMBINING TILDE}') == u'aaãa'
assert center_accent('aaaaa', u'\N{COMBINING TILDE}') == u'aaãaa'
assert center_accent('abcdefg', u'\N{COMBINING FOUR DOTS ABOVE}') == u'abcd⃜efg'
def test_imaginary_unit():
from sympy import pretty # As it is redefined above
assert pretty(1 + I, use_unicode=False) == '1 + I'
assert pretty(1 + I, use_unicode=True) == u'1 + ⅈ'
assert pretty(1 + I, use_unicode=False, imaginary_unit='j') == '1 + I'
assert pretty(1 + I, use_unicode=True, imaginary_unit='j') == u'1 + ⅉ'
raises(TypeError, lambda: pretty(I, imaginary_unit=I))
raises(ValueError, lambda: pretty(I, imaginary_unit="kkk"))
def test_str_special_matrices():
from sympy.matrices import Identity, ZeroMatrix, OneMatrix
assert pretty(Identity(4)) == 'I'
assert upretty(Identity(4)) == u'𝕀'
assert pretty(ZeroMatrix(2, 2)) == '0'
assert upretty(ZeroMatrix(2, 2)) == u'𝟘'
assert pretty(OneMatrix(2, 2)) == '1'
assert upretty(OneMatrix(2, 2)) == u'𝟙'
def test_pretty_misc_functions():
assert pretty(LambertW(x)) == 'W(x)'
assert upretty(LambertW(x)) == u'W(x)'
assert pretty(LambertW(x, y)) == 'W(x, y)'
assert upretty(LambertW(x, y)) == u'W(x, y)'
assert pretty(airyai(x)) == 'Ai(x)'
assert upretty(airyai(x)) == u'Ai(x)'
assert pretty(airybi(x)) == 'Bi(x)'
assert upretty(airybi(x)) == u'Bi(x)'
assert pretty(airyaiprime(x)) == "Ai'(x)"
assert upretty(airyaiprime(x)) == u"Ai'(x)"
assert pretty(airybiprime(x)) == "Bi'(x)"
assert upretty(airybiprime(x)) == u"Bi'(x)"
assert pretty(fresnelc(x)) == 'C(x)'
assert upretty(fresnelc(x)) == u'C(x)'
assert pretty(fresnels(x)) == 'S(x)'
assert upretty(fresnels(x)) == u'S(x)'
assert pretty(Heaviside(x)) == 'Heaviside(x)'
assert upretty(Heaviside(x)) == u'θ(x)'
assert pretty(Heaviside(x, y)) == 'Heaviside(x, y)'
assert upretty(Heaviside(x, y)) == u'θ(x, y)'
assert pretty(dirichlet_eta(x)) == 'dirichlet_eta(x)'
assert upretty(dirichlet_eta(x)) == u'η(x)'
def test_hadamard_power():
m, n, p = symbols('m, n, p', integer=True)
A = MatrixSymbol('A', m, n)
B = MatrixSymbol('B', m, n)
C = MatrixSymbol('C', m, p)
# Testing printer:
expr = hadamard_power(A, n)
ascii_str = \
"""\
.n\n\
A \
"""
ucode_str = \
u("""\
∘n\n\
A \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hadamard_power(A, 1+n)
ascii_str = \
"""\
.(n + 1)\n\
A \
"""
ucode_str = \
u("""\
∘(n + 1)\n\
A \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
expr = hadamard_power(A*B.T, 1+n)
ascii_str = \
"""\
.(n + 1)\n\
/ T\\ \n\
\\A*B / \
"""
ucode_str = \
u("""\
∘(n + 1)\n\
⎛ T⎞ \n\
⎝A⋅B ⎠ \
""")
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
def test_issue_17258():
n = Symbol('n', integer=True)
assert pretty(Sum(n, (n, -oo, 1))) == \
' 1 \n'\
' __ \n'\
' \\ ` \n'\
' ) n\n'\
' /_, \n'\
'n = -oo '
assert upretty(Sum(n, (n, -oo, 1))) == \
u("""\
1 \n\
___ \n\
╲ \n\
╲ \n\
╱ n\n\
╱ \n\
‾‾‾ \n\
n = -∞ \
""")
|
a5be7d81bab024f0c5e7d72018926150d947613c5839a83391aaa02bc24133c3 | """
Utility functions for Rubi integration.
See: http://www.apmaths.uwo.ca/~arich/IntegrationRules/PortableDocumentFiles/Integration%20utility%20functions.pdf
"""
from sympy.external import import_module
matchpy = import_module("matchpy")
from sympy.utilities.decorator import doctest_depends_on
from sympy.functions.elementary.integers import floor, frac
from sympy.functions import (log as sym_log , sin, cos, tan, cot, csc, sec, sqrt, erf, gamma, uppergamma, polygamma, digamma,
loggamma, factorial, zeta, LambertW)
from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch
from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec, atan2
from sympy.polys.polytools import Poly, quo, rem, total_degree, degree
from sympy.simplify.simplify import fraction, simplify, cancel, powsimp
from sympy.core.sympify import sympify
from sympy.utilities.iterables import postorder_traversal
from sympy.functions.special.error_functions import fresnelc, fresnels, erfc, erfi, Ei, expint, li, Si, Ci, Shi, Chi
from sympy.functions.elementary.complexes import im, re, Abs
from sympy.core.exprtools import factor_terms
from sympy import (Basic, E, polylog, N, Wild, WildFunction, factor, gcd, Sum, S, I, Mul, Integer, Float, Dict, Symbol, Rational,
Add, hyper, symbols, sqf_list, sqf, Max, factorint, factorrat, Min, sign, E, Function, collect, FiniteSet, nsimplify,
expand_trig, expand, poly, apart, lcm, And, Pow, pi, zoo, oo, Integral, UnevaluatedExpr, PolynomialError, Dummy, exp as sym_exp,
powdenest, PolynomialDivisionFailed, discriminant, UnificationFailed, appellf1)
from sympy.functions.special.hyper import TupleArg
from sympy.functions.special.elliptic_integrals import elliptic_f, elliptic_e, elliptic_pi
from sympy.utilities.iterables import flatten
from random import randint
from sympy.logic.boolalg import Or
class rubi_unevaluated_expr(UnevaluatedExpr):
"""
This is needed to convert `exp` as `Pow`.
sympy's UnevaluatedExpr has an issue with `is_commutative`.
"""
@property
def is_commutative(self):
from sympy.core.logic import fuzzy_and
return fuzzy_and(a.is_commutative for a in self.args)
_E = rubi_unevaluated_expr(E)
class rubi_exp(Function):
"""
sympy's exp is not identified as `Pow`. So it is not matched with `Pow`.
Like `a = exp(2)` is not identified as `Pow(E, 2)`. Rubi rules need it.
So, another exp has been created only for rubi module.
Examples
========
>>> from sympy import Pow, exp as sym_exp
>>> isinstance(sym_exp(2), Pow)
False
>>> from sympy.integrals.rubi.utility_function import rubi_exp
>>> isinstance(rubi_exp(2), Pow)
True
"""
@classmethod
def eval(cls, *args):
return Pow(_E, args[0])
class rubi_log(Function):
"""
For rule matching different `exp` has been used. So for proper results,
`log` is modified little only for case when it encounters rubi's `exp`.
For other cases it is same.
Examples
========
>>> from sympy.integrals.rubi.utility_function import rubi_exp, rubi_log
>>> a = rubi_exp(2)
>>> rubi_log(a)
2
"""
@classmethod
def eval(cls, *args):
if args[0].has(_E):
return sym_log(args[0]).doit()
else:
return sym_log(args[0])
if matchpy:
from matchpy import Arity, Operation, CommutativeOperation, AssociativeOperation, OneIdentityOperation, CustomConstraint, Pattern, ReplacementRule, ManyToOneReplacer
from matchpy.expressions.functions import op_iter, create_operation_expression, op_len
from sympy.integrals.rubi.symbol import WC
from matchpy import is_match, replace_all
from sympy.utilities.matchpy_connector import Operation
class UtilityOperator(Operation):
name = 'UtilityOperator'
arity = Arity.variadic
commutative=False
associative=True
Operation.register(rubi_log)
Operation.register(rubi_exp)
A_, B_, C_, F_, G_, a_, b_, c_, d_, e_, f_, g_, h_, i_, j_, k_, l_, m_, n_, p_, q_, r_, t_, u_, v_, s_, w_, x_, z_ = [WC(i) for i in 'ABCFGabcdefghijklmnpqrtuvswxz']
a, b, c, d, e = symbols('a b c d e')
Int = Integral
def replace_pow_exp(z):
"""
This function converts back rubi's `exp` to general sympy's `exp`.
Examples
========
>>> from sympy.integrals.rubi.utility_function import rubi_exp, replace_pow_exp
>>> expr = rubi_exp(5)
>>> expr
E**5
>>> replace_pow_exp(expr)
exp(5)
"""
z = S(z)
if z.has(_E):
z = z.replace(_E, E)
return z
def Simplify(expr):
expr = simplify(expr)
return expr
def Set(expr, value):
return {expr: value}
def With(subs, expr):
if isinstance(subs, dict):
k = list(subs.keys())[0]
expr = expr.xreplace({k: subs[k]})
else:
for i in subs:
k = list(i.keys())[0]
expr = expr.xreplace({k: i[k]})
return expr
def Module(subs, expr):
return With(subs, expr)
def Scan(f, expr):
# evaluates f applied to each element of expr in turn.
for i in expr:
yield f(i)
def MapAnd(f, l, x=None):
# MapAnd[f,l] applies f to the elements of list l until False is returned; else returns True
if x:
for i in l:
if f(i, x) == False:
return False
return True
else:
for i in l:
if f(i) == False:
return False
return True
def FalseQ(u):
if isinstance(u, (Dict, dict)):
return FalseQ(*list(u.values()))
return u == False
def ZeroQ(*expr):
if len(expr) == 1:
if isinstance(expr[0], list):
return list(ZeroQ(i) for i in expr[0])
else:
return Simplify(expr[0]) == 0
else:
return all(ZeroQ(i) for i in expr)
def OneQ(a):
if a == S(1):
return True
return False
def NegativeQ(u):
u = Simplify(u)
if u in (zoo, oo):
return False
if u.is_comparable:
res = u < 0
if not res.is_Relational:
return res
return False
def NonzeroQ(expr):
return Simplify(expr) != 0
def FreeQ(nodes, var):
if isinstance(nodes, list):
return not any(S(expr).has(var) for expr in nodes)
else:
nodes = S(nodes)
return not nodes.has(var)
def NFreeQ(nodes, var):
""" Note that in rubi 4.10.8 this function was not defined in `Integration Utility Functions.m`,
but was used in rules. So explicitly its returning `False`
"""
return False
# return not FreeQ(nodes, var)
def List(*var):
return list(var)
def PositiveQ(var):
var = Simplify(var)
if var in (zoo, oo):
return False
if var.is_comparable:
res = var > 0
if not res.is_Relational:
return res
return False
def PositiveIntegerQ(*args):
return all(var.is_Integer and PositiveQ(var) for var in args)
def NegativeIntegerQ(*args):
return all(var.is_Integer and NegativeQ(var) for var in args)
def IntegerQ(var):
var = Simplify(var)
if isinstance(var, (int, Integer)):
return True
else:
return var.is_Integer
def IntegersQ(*var):
return all(IntegerQ(i) for i in var)
def _ComplexNumberQ(var):
i = S(im(var))
if isinstance(i, (Integer, Float)):
return i != 0
else:
return False
def ComplexNumberQ(*var):
"""
ComplexNumberQ(m, n,...) returns True if m, n, ... are all explicit complex numbers, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import ComplexNumberQ
>>> from sympy import I
>>> ComplexNumberQ(1 + I*2, I)
True
>>> ComplexNumberQ(2, I)
False
"""
return all(_ComplexNumberQ(i) for i in var)
def PureComplexNumberQ(*var):
return all((_ComplexNumberQ(i) and re(i)==0) for i in var)
def RealNumericQ(u):
return u.is_real
def PositiveOrZeroQ(u):
return u.is_real and u >= 0
def NegativeOrZeroQ(u):
return u.is_real and u <= 0
def FractionOrNegativeQ(u):
return FractionQ(u) or NegativeQ(u)
def NegQ(var):
return Not(PosQ(var)) and NonzeroQ(var)
def Equal(a, b):
return a == b
def Unequal(a, b):
return a != b
def IntPart(u):
# IntPart[u] returns the sum of the integer terms of u.
if ProductQ(u):
if IntegerQ(First(u)):
return First(u)*IntPart(Rest(u))
elif IntegerQ(u):
return u
elif FractionQ(u):
return IntegerPart(u)
elif SumQ(u):
res = 0
for i in u.args:
res += IntPart(i)
return res
return 0
def FracPart(u):
# FracPart[u] returns the sum of the non-integer terms of u.
if ProductQ(u):
if IntegerQ(First(u)):
return First(u)*FracPart(Rest(u))
if IntegerQ(u):
return 0
elif FractionQ(u):
return FractionalPart(u)
elif SumQ(u):
res = 0
for i in u.args:
res += FracPart(i)
return res
else:
return u
def RationalQ(*nodes):
return all(var.is_Rational for var in nodes)
def ProductQ(expr):
return S(expr).is_Mul
def SumQ(expr):
return expr.is_Add
def NonsumQ(expr):
return not SumQ(expr)
def Subst(a, x, y):
if None in [a, x, y]:
return None
if a.has(Function('Integrate')):
# substituting in `Function(Integrate)` won't take care of properties of Integral
a = a.replace(Function('Integrate'), Integral)
return a.subs(x, y)
# return a.xreplace({x: y})
def First(expr, d=None):
"""
Gives the first element if it exists, or d otherwise.
Examples
========
>>> from sympy.integrals.rubi.utility_function import First
>>> from sympy.abc import a, b, c
>>> First(a + b + c)
a
>>> First(a*b*c)
a
"""
if isinstance(expr, list):
return expr[0]
if isinstance(expr, Symbol):
return expr
else:
if SumQ(expr) or ProductQ(expr):
l = Sort(expr.args)
return l[0]
else:
return expr.args[0]
def Rest(expr):
"""
Gives rest of the elements if it exists
Examples
========
>>> from sympy.integrals.rubi.utility_function import Rest
>>> from sympy.abc import a, b, c
>>> Rest(a + b + c)
b + c
>>> Rest(a*b*c)
b*c
"""
if isinstance(expr, list):
return expr[1:]
else:
if SumQ(expr) or ProductQ(expr):
l = Sort(expr.args)
return expr.func(*l[1:])
else:
return expr.args[1]
def SqrtNumberQ(expr):
# SqrtNumberQ[u] returns True if u^2 is a rational number; else it returns False.
if PowerQ(expr):
m = expr.base
n = expr.exp
return (IntegerQ(n) and SqrtNumberQ(m)) or (IntegerQ(n-S(1)/2) and RationalQ(m))
elif expr.is_Mul:
return all(SqrtNumberQ(i) for i in expr.args)
else:
return RationalQ(expr) or expr == I
def SqrtNumberSumQ(u):
return SumQ(u) and SqrtNumberQ(First(u)) and SqrtNumberQ(Rest(u)) or ProductQ(u) and SqrtNumberQ(First(u)) and SqrtNumberSumQ(Rest(u))
def LinearQ(expr, x):
"""
LinearQ(expr, x) returns True iff u is a polynomial of degree 1.
Examples
========
>>> from sympy.integrals.rubi.utility_function import LinearQ
>>> from sympy.abc import x, y, a
>>> LinearQ(a, x)
False
>>> LinearQ(3*x + y**2, x)
True
>>> LinearQ(3*x + y**2, y)
False
"""
if isinstance(expr, list):
return all(LinearQ(i, x) for i in expr)
elif expr.is_polynomial(x):
if degree(Poly(expr, x), gen=x) == 1:
return True
return False
def Sqrt(a):
return sqrt(a)
def ArcCosh(a):
return acosh(a)
class Util_Coefficient(Function):
def doit(self):
if len(self.args) == 2:
n = 1
else:
n = Simplify(self.args[2])
if NumericQ(n):
expr = expand(self.args[0])
if isinstance(n, (int, Integer)):
return expr.coeff(self.args[1], n)
else:
return expr.coeff(self.args[1]**n)
else:
return self
def Coefficient(expr, var, n=1):
"""
Coefficient(expr, var) gives the coefficient of form in the polynomial expr.
Coefficient(expr, var, n) gives the coefficient of var**n in expr.
Examples
========
>>> from sympy.integrals.rubi.utility_function import Coefficient
>>> from sympy.abc import x, a, b, c
>>> Coefficient(7 + 2*x + 4*x**3, x, 1)
2
>>> Coefficient(a + b*x + c*x**3, x, 0)
a
>>> Coefficient(a + b*x + c*x**3, x, 4)
0
>>> Coefficient(b*x + c*x**3, x, 3)
c
"""
if NumericQ(n):
if expr == 0 or n in (zoo, oo):
return 0
expr = expand(expr)
if isinstance(n, (int, Integer)):
return expr.coeff(var, n)
else:
return expr.coeff(var**n)
return Util_Coefficient(expr, var, n)
def Denominator(var):
var = Simplify(var)
if isinstance(var, Pow):
if isinstance(var.exp, Integer):
if var.exp > 0:
return Pow(Denominator(var.base), var.exp)
elif var.exp < 0:
return Pow(Numerator(var.base), -1*var.exp)
elif isinstance(var, Add):
var = factor(var)
return fraction(var)[1]
def Hypergeometric2F1(a, b, c, z):
return hyper([a, b], [c], z)
def Not(var):
if isinstance(var, bool):
return not var
elif var.is_Relational:
var = False
return not var
def FractionalPart(a):
return frac(a)
def IntegerPart(a):
return floor(a)
def AppellF1(a, b1, b2, c, x, y):
return appellf1(a, b1, b2, c, x, y)
def EllipticPi(*args):
return elliptic_pi(*args)
def EllipticE(*args):
return elliptic_e(*args)
def EllipticF(Phi, m):
return elliptic_f(Phi, m)
def ArcTan(a, b = None):
if b is None:
return atan(a)
else:
return atan2(a, b)
def ArcCot(a):
return acot(a)
def ArcCoth(a):
return acoth(a)
def ArcTanh(a):
return atanh(a)
def ArcSin(a):
return asin(a)
def ArcSinh(a):
return asinh(a)
def ArcCos(a):
return acos(a)
def ArcCsc(a):
return acsc(a)
def ArcSec(a):
return asec(a)
def ArcCsch(a):
return acsch(a)
def ArcSech(a):
return asech(a)
def Sinh(u):
return sinh(u)
def Tanh(u):
return tanh(u)
def Cosh(u):
return cosh(u)
def Sech(u):
return sech(u)
def Csch(u):
return csch(u)
def Coth(u):
return coth(u)
def LessEqual(*args):
for i in range(0, len(args) - 1):
try:
if args[i] > args[i + 1]:
return False
except:
return False
return True
def Less(*args):
for i in range(0, len(args) - 1):
try:
if args[i] >= args[i + 1]:
return False
except:
return False
return True
def Greater(*args):
for i in range(0, len(args) - 1):
try:
if args[i] <= args[i + 1]:
return False
except:
return False
return True
def GreaterEqual(*args):
for i in range(0, len(args) - 1):
try:
if args[i] < args[i + 1]:
return False
except:
return False
return True
def FractionQ(*args):
"""
FractionQ(m, n,...) returns True if m, n, ... are all explicit fractions, else it returns False.
Examples
========
>>> from sympy import S
>>> from sympy.integrals.rubi.utility_function import FractionQ
>>> FractionQ(S('3'))
False
>>> FractionQ(S('3')/S('2'))
True
"""
return all(i.is_Rational for i in args) and all(Denominator(i)!= S(1) for i in args)
def IntLinearcQ(a, b, c, d, m, n, x):
# returns True iff (a+b*x)^m*(c+d*x)^n is integrable wrt x in terms of non-hypergeometric functions.
return IntegerQ(m) or IntegerQ(n) or IntegersQ(S(3)*m, S(3)*n) or IntegersQ(S(4)*m, S(4)*n) or IntegersQ(S(2)*m, S(6)*n) or IntegersQ(S(6)*m, S(2)*n) or IntegerQ(m + n)
Defer = UnevaluatedExpr
def Expand(expr):
return expr.expand()
def IndependentQ(u, x):
"""
If u is free from x IndependentQ(u, x) returns True else False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import IndependentQ
>>> from sympy.abc import x, a, b
>>> IndependentQ(a + b*x, x)
False
>>> IndependentQ(a + b, x)
True
"""
return FreeQ(u, x)
def PowerQ(expr):
return expr.is_Pow or ExpQ(expr)
def IntegerPowerQ(u):
if isinstance(u, sym_exp): #special case for exp
return IntegerQ(u.args[0])
return PowerQ(u) and IntegerQ(u.args[1])
def PositiveIntegerPowerQ(u):
if isinstance(u, sym_exp):
return IntegerQ(u.args[0]) and PositiveQ(u.args[0])
return PowerQ(u) and IntegerQ(u.args[1]) and PositiveQ(u.args[1])
def FractionalPowerQ(u):
if isinstance(u, sym_exp):
return FractionQ(u.args[0])
return PowerQ(u) and FractionQ(u.args[1])
def AtomQ(expr):
expr = sympify(expr)
if isinstance(expr, list):
return False
if expr in [None, True, False, _E]: # [None, True, False] are atoms in mathematica and _E is also an atom
return True
# elif isinstance(expr, list):
# return all(AtomQ(i) for i in expr)
else:
return expr.is_Atom
def ExpQ(u):
u = replace_pow_exp(u)
return Head(u) in (sym_exp, rubi_exp)
def LogQ(u):
return u.func in (sym_log, Log)
def Head(u):
return u.func
def MemberQ(l, u):
if isinstance(l, list):
return u in l
else:
return u in l.args
def TrigQ(u):
if AtomQ(u):
x = u
else:
x = Head(u)
return MemberQ([sin, cos, tan, cot, sec, csc], x)
def SinQ(u):
return Head(u) == sin
def CosQ(u):
return Head(u) == cos
def TanQ(u):
return Head(u) == tan
def CotQ(u):
return Head(u) == cot
def SecQ(u):
return Head(u) == sec
def CscQ(u):
return Head(u) == csc
def Sin(u):
return sin(u)
def Cos(u):
return cos(u)
def Tan(u):
return tan(u)
def Cot(u):
return cot(u)
def Sec(u):
return sec(u)
def Csc(u):
return csc(u)
def HyperbolicQ(u):
if AtomQ(u):
x = u
else:
x = Head(u)
return MemberQ([sinh, cosh, tanh, coth, sech, csch], x)
def SinhQ(u):
return Head(u) == sinh
def CoshQ(u):
return Head(u) == cosh
def TanhQ(u):
return Head(u) == tanh
def CothQ(u):
return Head(u) == coth
def SechQ(u):
return Head(u) == sech
def CschQ(u):
return Head(u) == csch
def InverseTrigQ(u):
if AtomQ(u):
x = u
else:
x = Head(u)
return MemberQ([asin, acos, atan, acot, asec, acsc], x)
def SinCosQ(f):
return MemberQ([sin, cos, sec, csc], Head(f))
def SinhCoshQ(f):
return MemberQ([sinh, cosh, sech, csch], Head(f))
def LeafCount(expr):
return len(list(postorder_traversal(expr)))
def Numerator(u):
u = Simplify(u)
if isinstance(u, Pow):
if isinstance(u.exp, Integer):
if u.exp > 0:
return Pow(Numerator(u.base), u.exp)
elif u.exp < 0:
return Pow(Denominator(u.base), -1*u.exp)
elif isinstance(u, Add):
u = factor(u)
return fraction(u)[0]
def NumberQ(u):
if isinstance(u, (int, float)):
return True
return u.is_number
def NumericQ(u):
return N(u).is_number
def Length(expr):
"""
Returns number of elements in the expression just as sympy's len.
Examples
========
>>> from sympy.integrals.rubi.utility_function import Length
>>> from sympy.abc import x, a, b
>>> from sympy import cos, sin
>>> Length(a + b)
2
>>> Length(sin(a)*cos(a))
2
"""
if isinstance(expr, list):
return len(expr)
return len(expr.args)
def ListQ(u):
return isinstance(u, list)
def Im(u):
u = S(u)
return im(u.doit())
def Re(u):
u = S(u)
return re(u.doit())
def InverseHyperbolicQ(u):
if not u.is_Atom:
u = Head(u)
return u in [acosh, asinh, atanh, acoth, acsch, acsch]
def InverseFunctionQ(u):
# returns True if u is a call on an inverse function; else returns False.
return LogQ(u) or InverseTrigQ(u) and Length(u) <= 1 or InverseHyperbolicQ(u) or u.func == polylog
def TrigHyperbolicFreeQ(u, x):
# If u is free of trig, hyperbolic and calculus functions involving x, TrigHyperbolicFreeQ[u,x] returns true; else it returns False.
if AtomQ(u):
return True
else:
if TrigQ(u) | HyperbolicQ(u) | CalculusQ(u):
return FreeQ(u, x)
else:
for i in u.args:
if not TrigHyperbolicFreeQ(i, x):
return False
return True
def InverseFunctionFreeQ(u, x):
# If u is free of inverse, calculus and hypergeometric functions involving x, InverseFunctionFreeQ[u,x] returns true; else it returns False.
if AtomQ(u):
return True
else:
if InverseFunctionQ(u) or CalculusQ(u) or u.func == hyper or u.func == appellf1:
return FreeQ(u, x)
else:
for i in u.args:
if not ElementaryFunctionQ(i):
return False
return True
def RealQ(u):
if ListQ(u):
return MapAnd(RealQ, u)
elif NumericQ(u):
return ZeroQ(Im(N(u)))
elif PowerQ(u):
u = u.base
v = u.exp
return RealQ(u) & RealQ(v) & (IntegerQ(v) | PositiveOrZeroQ(u))
elif u.is_Mul:
return all(RealQ(i) for i in u.args)
elif u.is_Add:
return all(RealQ(i) for i in u.args)
elif u.is_Function:
f = u.func
u = u.args[0]
if f in [sin, cos, tan, cot, sec, csc, atan, acot, erf]:
return RealQ(u)
else:
if f in [asin, acos]:
return LE(-1, u, 1)
else:
if f == sym_log:
return PositiveOrZeroQ(u)
else:
return False
else:
return False
def EqQ(u, v):
return ZeroQ(u - v)
def FractionalPowerFreeQ(u):
if AtomQ(u):
return True
elif FractionalPowerQ(u):
return False
def ComplexFreeQ(u):
if AtomQ(u) and Not(ComplexNumberQ(u)):
return True
else:
return False
def PolynomialQ(u, x = None):
if x is None :
return u.is_polynomial()
if isinstance(x, Pow):
if isinstance(x.exp, Integer):
deg = degree(u, x.base)
if u.is_polynomial(x):
if deg % x.exp !=0 :
return False
try:
p = Poly(u, x.base)
except PolynomialError:
return False
c_list = p.all_coeffs()
coeff_list = c_list[:-1:x.exp]
coeff_list += [c_list[-1]]
for i in coeff_list:
if not i == 0:
index = c_list.index(i)
c_list[index] = 0
if all(i == 0 for i in c_list):
return True
else:
return False
return u.is_polynomial(x)
else:
return False
elif isinstance(x.exp, (Float, Rational)): #not full - proof
if FreeQ(simplify(u), x.base) and Exponent(u, x.base) == 0:
if not all(FreeQ(u, i) for i in x.base.free_symbols):
return False
if isinstance(x, Mul):
return all(PolynomialQ(u, i) for i in x.args)
return u.is_polynomial(x)
def FactorSquareFree(u):
return sqf(u)
def PowerOfLinearQ(expr, x):
u = Wild('u')
w = Wild('w')
m = Wild('m')
n = Wild('n')
Match = expr.match(u**m)
if PolynomialQ(Match[u], x) and FreeQ(Match[m], x):
if IntegerQ(Match[m]):
e = FactorSquareFree(Match[u]).match(w**n)
if FreeQ(e[n], x) and LinearQ(e[w], x):
return True
else:
return False
else:
return LinearQ(Match[u], x)
else:
return False
def Exponent(expr, x, h = None):
expr = Expand(S(expr))
if h is None:
if S(expr).is_number or (not expr.has(x)):
return 0
if PolynomialQ(expr, x):
if isinstance(x, Rational):
return degree(Poly(expr, x), x)
return degree(expr, gen = x)
else:
return 0
else:
if S(expr).is_number or (not expr.has(x)):
res = [0]
if expr.is_Add:
expr = collect(expr, x)
lst = []
k = 1
for t in expr.args:
if t.has(x):
if isinstance(x, Rational):
lst += [degree(Poly(t, x), x)]
else:
lst += [degree(t, gen = x)]
else:
if k == 1:
lst += [0]
k += 1
lst.sort()
res = lst
else:
if isinstance(x, Rational):
res = [degree(Poly(expr, x), x)]
else:
res = [degree(expr, gen = x)]
return h(*res)
def QuadraticQ(u, x):
# QuadraticQ(u, x) returns True iff u is a polynomial of degree 2 and not a monomial of the form a x^2
if ListQ(u):
for expr in u:
if Not(PolyQ(expr, x, 2) and Not(Coefficient(expr, x, 0) == 0 and Coefficient(expr, x, 1) == 0)):
return False
return True
else:
return PolyQ(u, x, 2) and Not(Coefficient(u, x, 0) == 0 and Coefficient(u, x, 1) == 0)
def LinearPairQ(u, v, x):
# LinearPairQ(u, v, x) returns True iff u and v are linear not equal x but u/v is a constant wrt x
return LinearQ(u, x) and LinearQ(v, x) and NonzeroQ(u-x) and ZeroQ(Coefficient(u, x, 0)*Coefficient(v, x, 1)-Coefficient(u, x, 1)*Coefficient(v, x, 0))
def BinomialParts(u, x):
if PolynomialQ(u, x):
if Exponent(u, x) > 0:
lst = Exponent(u, x, List)
if len(lst)==1:
return [0, Coefficient(u, x, Exponent(u, x)), Exponent(u,x)]
elif len(lst) == 2 and lst[0] == 0:
return [Coefficient(u, x, 0), Coefficient(u, x, Exponent(u, x)), Exponent(u, x)]
else:
return False
else:
return False
elif PowerQ(u):
if u.base == x and FreeQ(u.exp, x):
return [0, 1, u.exp]
else:
return False
elif ProductQ(u):
if FreeQ(First(u), x):
lst2 = BinomialParts(Rest(u), x)
if AtomQ(lst2):
return False
else:
return [First(u)*lst2[0], First(u)*lst2[1], lst2[2]]
elif FreeQ(Rest(u), x):
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
else:
return [Rest(u)*lst1[0], Rest(u)*lst1[1], lst1[2]]
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
lst2 = BinomialParts(Rest(u), x)
if AtomQ(lst2):
return False
a = lst1[0]
b = lst1[1]
m = lst1[2]
c = lst2[0]
d = lst2[1]
n = lst2[2]
if ZeroQ(a):
if ZeroQ(c):
return [0, b*d, m + n]
elif ZeroQ(m + n):
return [b*d, b*c, m]
else:
return False
if ZeroQ(c):
if ZeroQ(m + n):
return [b*d, a*d, n]
else:
return False
if EqQ(m, n) and ZeroQ(a*d + b*c):
return [a*c, b*d, 2*m]
else:
return False
elif SumQ(u):
if FreeQ(First(u),x):
lst2 = BinomialParts(Rest(u), x)
if AtomQ(lst2):
return False
else:
return [First(u) + lst2[0], lst2[1], lst2[2]]
elif FreeQ(Rest(u), x):
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
else:
return[Rest(u) + lst1[0], lst1[1], lst1[2]]
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
lst2 = BinomialParts(Rest(u),x)
if AtomQ(lst2):
return False
if EqQ(lst1[2], lst2[2]):
return [lst1[0] + lst2[0], lst1[1] + lst2[1], lst1[2]]
else:
return False
else:
return False
def TrinomialParts(u, x):
# If u is equivalent to a trinomial of the form a + b*x^n + c*x^(2*n) where n!=0, b!=0 and c!=0, TrinomialParts[u,x] returns the list {a,b,c,n}; else it returns False.
u = sympify(u)
if PolynomialQ(u, x):
lst = CoefficientList(u, x)
if len(lst)<3 or EvenQ(sympify(len(lst))) or ZeroQ((len(lst)+1)/2):
return False
#Catch(
# Scan(Function(if ZeroQ(lst), Null, Throw(False), Drop(Drop(Drop(lst, [(len(lst)+1)/2]), 1), -1];
# [First(lst), lst[(len(lst)+1)/2], Last(lst), (len(lst)-1)/2]):
if PowerQ(u):
if EqQ(u.exp, 2):
lst = BinomialParts(u.base, x)
if not lst or ZeroQ(lst[0]):
return False
else:
return [lst[0]**2, 2*lst[0]*lst[1], lst[1]**2, lst[2]]
else:
return False
if ProductQ(u):
if FreeQ(First(u), x):
lst2 = TrinomialParts(Rest(u), x)
if not lst2:
return False
else:
return [First(u)*lst2[0], First(u)*lst2[1], First(u)*lst2[2], lst2[3]]
if FreeQ(Rest(u), x):
lst1 = TrinomialParts(First(u), x)
if not lst1:
return False
else:
return [Rest(u)*lst1[0], Rest(u)*lst1[1], Rest(u)*lst1[2], lst1[3]]
lst1 = BinomialParts(First(u), x)
if not lst1:
return False
lst2 = BinomialParts(Rest(u), x)
if not lst2:
return False
a = lst1[0]
b = lst1[1]
m = lst1[2]
c = lst2[0]
d = lst2[1]
n = lst2[2]
if EqQ(m, n) and NonzeroQ(a*d+b*c):
return [a*c, a*d + b*c, b*d, m]
else:
return False
if SumQ(u):
if FreeQ(First(u), x):
lst2 = TrinomialParts(Rest(u), x)
if not lst2:
return False
else:
return [First(u)+lst2[0], lst2[1], lst2[2], lst2[3]]
if FreeQ(Rest(u), x):
lst1 = TrinomialParts(First(u), x)
if not lst1:
return False
else:
return [Rest(u)+lst1[0], lst1[1], lst1[2], lst1[3]]
lst1 = TrinomialParts(First(u), x)
if not lst1:
lst3 = BinomialParts(First(u), x)
if not lst3:
return False
lst2 = TrinomialParts(Rest(u), x)
if not lst2:
lst4 = BinomialParts(Rest(u), x)
if not lst4:
return False
if EqQ(lst3[2], 2*lst4[2]):
return [lst3[0]+lst4[0], lst4[1], lst3[1], lst4[2]]
if EqQ(lst4[2], 2*lst3[2]):
return [lst3[0]+lst4[0], lst3[1], lst4[1], lst3[2]]
else:
return False
if EqQ(lst3[2], lst2[3]) and NonzeroQ(lst3[1]+lst2[1]):
return [lst3[0]+lst2[0], lst3[1]+lst2[1], lst2[2], lst2[3]]
if EqQ(lst3[2], 2*lst2[3]) and NonzeroQ(lst3[1]+lst2[2]):
return [lst3[0]+lst2[0], lst2[1], lst3[1]+lst2[2], lst2[3]]
else:
return False
lst2 = TrinomialParts(Rest(u), x)
if AtomQ(lst2):
lst4 = BinomialParts(Rest(u), x)
if not lst4:
return False
if EqQ(lst4[2], lst1[3]) and NonzeroQ(lst1[1]+lst4[0]):
return [lst1[0]+lst4[0], lst1[1]+lst4[1], lst1[2], lst1[3]]
if EqQ(lst4[2], 2*lst1[3]) and NonzeroQ(lst1[2]+lst4[1]):
return [lst1[0]+lst4[0], lst1[1], lst1[2]+lst4[1], lst1[3]]
else:
return False
if EqQ(lst1[3], lst2[3]) and NonzeroQ(lst1[1]+lst2[1]) and NonzeroQ(lst1[2]+lst2[2]):
return [lst1[0]+lst2[0], lst1[1]+lst2[1], lst1[2]+lst2[2], lst1[3]]
else:
return False
else:
return False
def PolyQ(u, x, n=None):
# returns True iff u is a polynomial of degree n.
if ListQ(u):
return all(PolyQ(i, x) for i in u)
if n==None:
if u == x:
return False
elif isinstance(x, Pow):
n = x.exp
x_base = x.base
if FreeQ(n, x_base):
if PositiveIntegerQ(n):
return PolyQ(u, x_base) and (PolynomialQ(u, x) or PolynomialQ(Together(u), x))
elif AtomQ(n):
return PolynomialQ(u, x) and FreeQ(CoefficientList(u, x), x_base)
else:
return False
return PolynomialQ(u, x) or PolynomialQ(u, Together(x))
else:
return PolynomialQ(u, x) and Coefficient(u, x, n) != 0 and Exponent(u, x) == n
def EvenQ(u):
# gives True if expr is an even integer, and False otherwise.
return isinstance(u, (Integer, int)) and u%2 == 0
def OddQ(u):
# gives True if expr is an odd integer, and False otherwise.
return isinstance(u, (Integer, int)) and u%2 == 1
def PerfectSquareQ(u):
# (* If u is a rational number whose squareroot is rational or if u is of the form u1^n1 u2^n2 ...
# and n1, n2, ... are even, PerfectSquareQ[u] returns True; else it returns False. *)
if RationalQ(u):
return Greater(u, 0) and RationalQ(Sqrt(u))
elif PowerQ(u):
return EvenQ(u.exp)
elif ProductQ(u):
return PerfectSquareQ(First(u)) and PerfectSquareQ(Rest(u))
elif SumQ(u):
s = Simplify(u)
if NonsumQ(s):
return PerfectSquareQ(s)
return False
else:
return False
def NiceSqrtAuxQ(u):
if RationalQ(u):
return u > 0
elif PowerQ(u):
return EvenQ(u.exp)
elif ProductQ(u):
return NiceSqrtAuxQ(First(u)) and NiceSqrtAuxQ(Rest(u))
elif SumQ(u):
s = Simplify(u)
return NonsumQ(s) and NiceSqrtAuxQ(s)
else:
return False
def NiceSqrtQ(u):
return Not(NegativeQ(u)) and NiceSqrtAuxQ(u)
def Together(u):
return factor(u)
def PosAux(u):
if RationalQ(u):
return u>0
elif NumberQ(u):
if ZeroQ(Re(u)):
return Im(u) > 0
else:
return Re(u) > 0
elif NumericQ(u):
v = N(u)
if ZeroQ(Re(v)):
return Im(v) > 0
else:
return Re(v) > 0
elif PowerQ(u):
if OddQ(u.exp):
return PosAux(u.base)
else:
return True
elif ProductQ(u):
if PosAux(First(u)):
return PosAux(Rest(u))
else:
return not PosAux(Rest(u))
elif SumQ(u):
return PosAux(First(u))
else:
res = u > 0
if res in(True, False):
return res
return True
def PosQ(u):
# If u is not 0 and has a positive form, PosQ[u] returns True, else it returns False.
return PosAux(TogetherSimplify(u))
def CoefficientList(u, x):
if PolynomialQ(u, x):
return list(reversed(Poly(u, x).all_coeffs()))
else:
return []
def ReplaceAll(expr, args):
if isinstance(args, list):
n_args = {}
for i in args:
n_args.update(i)
return expr.subs(n_args)
return expr.subs(args)
def ExpandLinearProduct(v, u, a, b, x):
# If u is a polynomial in x, ExpandLinearProduct[v,u,a,b,x] expands v*u into a sum of terms of the form c*v*(a+b*x)^n.
if FreeQ([a, b], x) and PolynomialQ(u, x):
lst = CoefficientList(ReplaceAll(u, {x: (x - a)/b}), x)
lst = [SimplifyTerm(i, x) for i in lst]
res = 0
for k in range(1, len(lst)+1):
res = res + Simplify(v*lst[k-1]*(a + b*x)**(k - 1))
return res
return u*v
def GCD(*args):
args = S(args)
if len(args) == 1:
if isinstance(args[0], (int, Integer)):
return args[0]
else:
return S(1)
return gcd(*args)
def ContentFactor(expn):
return factor_terms(expn)
def NumericFactor(u):
# returns the real numeric factor of u.
if NumberQ(u):
if ZeroQ(Im(u)):
return u
elif ZeroQ(Re(u)):
return Im(u)
else:
return S(1)
elif PowerQ(u):
if RationalQ(u.base) and RationalQ(u.exp):
if u.exp > 0:
return 1/Denominator(u.base)
else:
return 1/(1/Denominator(u.base))
else:
return S(1)
elif ProductQ(u):
return Mul(*[NumericFactor(i) for i in u.args])
elif SumQ(u):
if LeafCount(u) < 50:
c = ContentFactor(u)
if SumQ(c):
return S(1)
else:
return NumericFactor(c)
else:
m = NumericFactor(First(u))
n = NumericFactor(Rest(u))
if m < 0 and n < 0:
return -GCD(-m, -n)
else:
return GCD(m, n)
return S(1)
def NonnumericFactors(u):
if NumberQ(u):
if ZeroQ(Im(u)):
return S(1)
elif ZeroQ(Re(u)):
return I
return u
elif PowerQ(u):
if RationalQ(u.base) and FractionQ(u.exp):
return u/NumericFactor(u)
return u
elif ProductQ(u):
result = 1
for i in u.args:
result *= NonnumericFactors(i)
return result
elif SumQ(u):
if LeafCount(u) < 50:
i = ContentFactor(u)
if SumQ(i):
return u
else:
return NonnumericFactors(i)
n = NumericFactor(u)
result = 0
for i in u.args:
result += i/n
return result
return u
def MakeAssocList(u, x, alst=None):
# (* MakeAssocList[u,x,alst] returns an association list of gensymed symbols with the nonatomic
# parameters of a u that are not integer powers, products or sums. *)
if alst is None:
alst = []
u = replace_pow_exp(u)
x = replace_pow_exp(x)
if AtomQ(u):
return alst
elif IntegerPowerQ(u):
return MakeAssocList(u.base, x, alst)
elif ProductQ(u) or SumQ(u):
return MakeAssocList(Rest(u), x, MakeAssocList(First(u), x, alst))
elif FreeQ(u, x):
tmp = []
for i in alst:
if PowerQ(i):
if i.exp == u:
tmp.append(i)
break
elif len(i.args) > 1: # make sure args has length > 1, else causes index error some times
if i.args[1] == u:
tmp.append(i)
break
if tmp == []:
alst.append(u)
return alst
return alst
def GensymSubst(u, x, alst=None):
# (* GensymSubst[u,x,alst] returns u with the kernels in alst free of x replaced by gensymed names. *)
if alst is None:
alst =[]
u = replace_pow_exp(u)
x = replace_pow_exp(x)
if AtomQ(u):
return u
elif IntegerPowerQ(u):
return GensymSubst(u.base, x, alst)**u.exp
elif ProductQ(u) or SumQ(u):
return u.func(*[GensymSubst(i, x, alst) for i in u.args])
elif FreeQ(u, x):
tmp = []
for i in alst:
if PowerQ(i):
if i.exp == u:
tmp.append(i)
break
elif len(i.args) > 1: # make sure args has length > 1, else causes index error some times
if i.args[1] == u:
tmp.append(i)
break
if tmp == []:
return u
return tmp[0][0]
return u
def KernelSubst(u, x, alst):
# (* KernelSubst[u,x,alst] returns u with the gensymed names in alst replaced by kernels free of x. *)
if AtomQ(u):
tmp = []
for i in alst:
if i.args[0] == u:
tmp.append(i)
break
if tmp == []:
return u
elif len(tmp[0].args) > 1: # make sure args has length > 1, else causes index error some times
return tmp[0].args[1]
elif IntegerPowerQ(u):
tmp = KernelSubst(u.base, x, alst)
if u.exp < 0 and ZeroQ(tmp):
return 'Indeterminate'
return tmp**u.exp
elif ProductQ(u) or SumQ(u):
return u.func(*[KernelSubst(i, x, alst) for i in u.args])
return u
def ExpandExpression(u, x):
if AlgebraicFunctionQ(u, x) and Not(RationalFunctionQ(u, x)):
v = ExpandAlgebraicFunction(u, x)
else:
v = S(0)
if SumQ(v):
return ExpandCleanup(v, x)
v = SmartApart(u, x)
if SumQ(v):
return ExpandCleanup(v, x)
v = SmartApart(RationalFunctionFactors(u, x), x, x)
if SumQ(v):
w = NonrationalFunctionFactors(u, x)
return ExpandCleanup(v.func(*[i*w for i in v.args]), x)
v = Expand(u)
if SumQ(v):
return ExpandCleanup(v, x)
v = Expand(u)
if SumQ(v):
return ExpandCleanup(v, x)
return SimplifyTerm(u, x)
def Apart(u, x):
if RationalFunctionQ(u, x):
return apart(u, x)
return u
def SmartApart(*args):
if len(args) == 2:
u, x = args
alst = MakeAssocList(u, x)
tmp = KernelSubst(Apart(GensymSubst(u, x, alst), x), x, alst)
if tmp == 'Indeterminate':
return u
return tmp
u, v, x = args
alst = MakeAssocList(u, x)
tmp = KernelSubst(Apart(GensymSubst(u, x, alst), x), x, alst)
if tmp == 'Indeterminate':
return u
return tmp
def MatchQ(expr, pattern, *var):
# returns the matched arguments after matching pattern with expression
match = expr.match(pattern)
if match:
return tuple(match[i] for i in var)
else:
return None
def PolynomialQuotientRemainder(p, q, x):
return [PolynomialQuotient(p, q, x), PolynomialRemainder(p, q, x)]
def FreeFactors(u, x):
# returns the product of the factors of u free of x.
if ProductQ(u):
result = 1
for i in u.args:
if FreeQ(i, x):
result *= i
return result
elif FreeQ(u, x):
return u
else:
return S(1)
def NonfreeFactors(u, x):
"""
Returns the product of the factors of u not free of x.
Examples
========
>>> from sympy.integrals.rubi.utility_function import NonfreeFactors
>>> from sympy.abc import x, a, b
>>> NonfreeFactors(a, x)
1
>>> NonfreeFactors(x + a, x)
a + x
>>> NonfreeFactors(a*b*x, x)
x
"""
if ProductQ(u):
result = 1
for i in u.args:
if not FreeQ(i, x):
result *= i
return result
elif FreeQ(u, x):
return 1
else:
return u
def RemoveContentAux(expr, x):
return RemoveContentAux_replacer.replace(UtilityOperator(expr, x))
def RemoveContent(u, x):
v = NonfreeFactors(u, x)
w = Together(v)
if EqQ(FreeFactors(w, x), 1):
return RemoveContentAux(v, x)
else:
return RemoveContentAux(NonfreeFactors(w, x), x)
def FreeTerms(u, x):
"""
Returns the sum of the terms of u free of x.
Examples
========
>>> from sympy.integrals.rubi.utility_function import FreeTerms
>>> from sympy.abc import x, a, b
>>> FreeTerms(a, x)
a
>>> FreeTerms(x*a, x)
0
>>> FreeTerms(a*x + b, x)
b
"""
if SumQ(u):
result = 0
for i in u.args:
if FreeQ(i, x):
result += i
return result
elif FreeQ(u, x):
return u
else:
return 0
def NonfreeTerms(u, x):
# returns the sum of the terms of u free of x.
if SumQ(u):
result = S(0)
for i in u.args:
if not FreeQ(i, x):
result += i
return result
elif not FreeQ(u, x):
return u
else:
return S(0)
def ExpandAlgebraicFunction(expr, x):
if ProductQ(expr):
u_ = Wild('u', exclude=[x])
n_ = Wild('n', exclude=[x])
v_ = Wild('v')
pattern = u_*v_
match = expr.match(pattern)
if match:
keys = [u_, v_]
if len(keys) == len(match):
u, v = tuple([match[i] for i in keys])
if SumQ(v):
u, v = v, u
if not FreeQ(u, x) and SumQ(u):
result = 0
for i in u.args:
result += i*v
return result
pattern = u_**n_*v_
match = expr.match(pattern)
if match:
keys = [u_, n_, v_]
if len(keys) == len(match):
u, n, v = tuple([match[i] for i in keys])
if PositiveIntegerQ(n) and SumQ(u):
w = Expand(u**n)
result = 0
for i in w.args:
result += i*v
return result
return expr
def CollectReciprocals(expr, x):
# Basis: e/(a+b x)+f/(c+d x)==(c e+a f+(d e+b f) x)/(a c+(b c+a d) x+b d x^2)
if SumQ(expr):
u_ = Wild('u')
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x])
e_ = Wild('e', exclude=[x])
f_ = Wild('f', exclude=[x])
pattern = u_ + e_/(a_ + b_*x) + f_/(c_+d_*x)
match = expr.match(pattern)
if match:
try: # .match() does not work peoperly always
keys = [u_, a_, b_, c_, d_, e_, f_]
u, a, b, c, d, e, f = tuple([match[i] for i in keys])
if ZeroQ(b*c + a*d) & ZeroQ(d*e + b*f):
return CollectReciprocals(u + (c*e + a*f)/(a*c + b*d*x**2),x)
elif ZeroQ(b*c + a*d) & ZeroQ(c*e + a*f):
return CollectReciprocals(u + (d*e + b*f)*x/(a*c + b*d*x**2),x)
except:
pass
return expr
def ExpandCleanup(u, x):
v = CollectReciprocals(u, x)
if SumQ(v):
res = 0
for i in v.args:
res += SimplifyTerm(i, x)
v = res
if SumQ(v):
return UnifySum(v, x)
else:
return v
else:
return v
def AlgebraicFunctionQ(u, x, flag=False):
if ListQ(u):
if u == []:
return True
elif AlgebraicFunctionQ(First(u), x, flag):
return AlgebraicFunctionQ(Rest(u), x, flag)
else:
return False
elif AtomQ(u) or FreeQ(u, x):
return True
elif PowerQ(u):
if RationalQ(u.exp) | flag & FreeQ(u.exp, x):
return AlgebraicFunctionQ(u.base, x, flag)
elif ProductQ(u) | SumQ(u):
for i in u.args:
if not AlgebraicFunctionQ(i, x, flag):
return False
return True
return False
def Coeff(expr, form, n=1):
if n == 1:
return Coefficient(Together(expr), form, n)
else:
coef1 = Coefficient(expr, form, n)
coef2 = Coefficient(Together(expr), form, n)
if Simplify(coef1 - coef2) == 0:
return coef1
else:
return coef2
def LeadTerm(u):
if SumQ(u):
return First(u)
return u
def RemainingTerms(u):
if SumQ(u):
return Rest(u)
return u
def LeadFactor(u):
# returns the leading factor of u.
if ComplexNumberQ(u) and Re(u) == 0:
if Im(u) == S(1):
return u
else:
return LeadFactor(Im(u))
elif ProductQ(u):
return LeadFactor(First(u))
return u
def RemainingFactors(u):
# returns the remaining factors of u.
if ComplexNumberQ(u) and Re(u) == 0:
if Im(u) == 1:
return S(1)
else:
return I*RemainingFactors(Im(u))
elif ProductQ(u):
return RemainingFactors(First(u))*Rest(u)
return S(1)
def LeadBase(u):
"""
returns the base of the leading factor of u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import LeadBase
>>> from sympy.abc import a, b, c
>>> LeadBase(a**b)
a
>>> LeadBase(a**b*c)
a
"""
v = LeadFactor(u)
if PowerQ(v):
return v.base
return v
def LeadDegree(u):
# returns the degree of the leading factor of u.
v = LeadFactor(u)
if PowerQ(v):
return v.exp
return v
def Numer(expr):
# returns the numerator of u.
if PowerQ(expr):
if expr.exp < 0:
return 1
if ProductQ(expr):
return Mul(*[Numer(i) for i in expr.args])
return Numerator(expr)
def Denom(u):
# returns the denominator of u
if PowerQ(u):
if u.exp < 0:
return u.args[0]**(-u.args[1])
elif ProductQ(u):
return Mul(*[Denom(i) for i in u.args])
return Denominator(u)
def hypergeom(n, d, z):
return hyper(n, d, z)
def Expon(expr, form, h=None):
if h:
return Exponent(Together(expr), form, h)
else:
return Exponent(Together(expr), form)
def MergeMonomials(expr, x):
u_ = Wild('u')
p_ = Wild('p', exclude=[x, 1, 0])
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x, 0])
n_ = Wild('n', exclude=[x])
m_ = Wild('m', exclude=[x])
# Basis: If m/n\[Element]\[DoubleStruckCapitalZ], then z^m (c z^n)^p==(c z^n)^(m/n+p)/c^(m/n)
pattern = u_*(a_ + b_*x)**m_*(c_*(a_ + b_*x)**n_)**p_
match = expr.match(pattern)
if match:
keys = [u_, a_, b_, m_, c_, n_, p_]
if len(keys) == len(match):
u, a, b, m, c, n, p = tuple([match[i] for i in keys])
if IntegerQ(m/n):
if u*(c*(a + b*x)**n)**(m/n + p)/c**(m/n) is S.NaN:
return expr
else:
return u*(c*(a + b*x)**n)**(m/n + p)/c**(m/n)
# Basis: If m\[Element]\[DoubleStruckCapitalZ] \[And] b c-a d==0, then (a+b z)^m==b^m/d^m (c+d z)^m
pattern = u_*(a_ + b_*x)**m_*(c_ + d_*x)**n_
match = expr.match(pattern)
if match:
keys = [u_, a_, b_, m_, c_, d_, n_]
if len(keys) == len(match):
u, a, b, m, c, d, n = tuple([match[i] for i in keys])
if IntegerQ(m) and ZeroQ(b*c - a*d):
if u*b**m/d**m*(c + d*x)**(m + n) is S.NaN:
return expr
else:
return u*b**m/d**m*(c + d*x)**(m + n)
return expr
def PolynomialDivide(u, v, x):
quo = PolynomialQuotient(u, v, x)
rem = PolynomialRemainder(u, v, x)
s = 0
for i in Exponent(quo, x, List):
s += Simp(Together(Coefficient(quo, x, i)*x**i), x)
quo = s
rem = Together(rem)
free = FreeFactors(rem, x)
rem = NonfreeFactors(rem, x)
monomial = x**Exponent(rem, x, Min)
if NegQ(Coefficient(rem, x, 0)):
monomial = -monomial
s = 0
for i in Exponent(rem, x, List):
s += Simp(Together(Coefficient(rem, x, i)*x**i/monomial), x)
rem = s
if BinomialQ(v, x):
return quo + free*monomial*rem/ExpandToSum(v, x)
else:
return quo + free*monomial*rem/v
def BinomialQ(u, x, n=None):
"""
If u is equivalent to an expression of the form a + b*x**n, BinomialQ(u, x, n) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import BinomialQ
>>> from sympy.abc import x
>>> BinomialQ(x**9, x)
True
>>> BinomialQ((1 + x)**3, x)
False
"""
if ListQ(u):
for i in u:
if Not(BinomialQ(i, x, n)):
return False
return True
elif NumberQ(x):
return False
return ListQ(BinomialParts(u, x))
def TrinomialQ(u, x):
"""
If u is equivalent to an expression of the form a + b*x**n + c*x**(2*n) where n, b and c are not 0,
TrinomialQ(u, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import TrinomialQ
>>> from sympy.abc import x
>>> TrinomialQ((7 + 2*x**6 + 3*x**12), x)
True
>>> TrinomialQ(x**2, x)
False
"""
if ListQ(u):
for i in u.args:
if Not(TrinomialQ(i, x)):
return False
return True
check = False
u = replace_pow_exp(u)
if PowerQ(u):
if u.exp == 2 and BinomialQ(u.base, x):
check = True
return ListQ(TrinomialParts(u,x)) and Not(QuadraticQ(u, x)) and Not(check)
def GeneralizedBinomialQ(u, x):
"""
If u is equivalent to an expression of the form a*x**q+b*x**n where n, q and b are not 0,
GeneralizedBinomialQ(u, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import GeneralizedBinomialQ
>>> from sympy.abc import a, x, q, b, n
>>> GeneralizedBinomialQ(a*x**q, x)
False
"""
if ListQ(u):
return all(GeneralizedBinomialQ(i, x) for i in u)
return ListQ(GeneralizedBinomialParts(u, x))
def GeneralizedTrinomialQ(u, x):
"""
If u is equivalent to an expression of the form a*x**q+b*x**n+c*x**(2*n-q) where n, q, b and c are not 0,
GeneralizedTrinomialQ(u, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import GeneralizedTrinomialQ
>>> from sympy.abc import x
>>> GeneralizedTrinomialQ(7 + 2*x**6 + 3*x**12, x)
False
"""
if ListQ(u):
return all(GeneralizedTrinomialQ(i, x) for i in u)
return ListQ(GeneralizedTrinomialParts(u, x))
def FactorSquareFreeList(poly):
r = sqf_list(poly)
result = [[1, 1]]
for i in r[1]:
result.append(list(i))
return result
def PerfectPowerTest(u, x):
# If u (x) is equivalent to a polynomial raised to an integer power greater than 1,
# PerfectPowerTest[u,x] returns u (x) as an expanded polynomial raised to the power;
# else it returns False.
if PolynomialQ(u, x):
lst = FactorSquareFreeList(u)
gcd = 0
v = 1
if lst[0] == [1, 1]:
lst = Rest(lst)
for i in lst:
gcd = GCD(gcd, i[1])
if gcd > 1:
for i in lst:
v = v*i[0]**(i[1]/gcd)
return Expand(v)**gcd
else:
return False
return False
def SquareFreeFactorTest(u, x):
# If u (x) can be square free factored, SquareFreeFactorTest[u,x] returns u (x) in
# factored form; else it returns False.
if PolynomialQ(u, x):
v = FactorSquareFree(u)
if PowerQ(v) or ProductQ(v):
return v
return False
return False
def RationalFunctionQ(u, x):
# If u is a rational function of x, RationalFunctionQ[u,x] returns True; else it returns False.
if AtomQ(u) or FreeQ(u, x):
return True
elif IntegerPowerQ(u):
return RationalFunctionQ(u.base, x)
elif ProductQ(u) or SumQ(u):
for i in u.args:
if Not(RationalFunctionQ(i, x)):
return False
return True
return False
def RationalFunctionFactors(u, x):
# RationalFunctionFactors[u,x] returns the product of the factors of u that are rational functions of x.
if ProductQ(u):
res = 1
for i in u.args:
if RationalFunctionQ(i, x):
res *= i
return res
elif RationalFunctionQ(u, x):
return u
return S(1)
def NonrationalFunctionFactors(u, x):
if ProductQ(u):
res = 1
for i in u.args:
if not RationalFunctionQ(i, x):
res *= i
return res
elif RationalFunctionQ(u, x):
return S(1)
return u
def Reverse(u):
if isinstance(u, list):
return list(reversed(u))
else:
l = list(u.args)
return u.func(*list(reversed(l)))
def RationalFunctionExponents(u, x):
"""
u is a polynomial or rational function of x.
RationalFunctionExponents(u, x) returns a list of the exponent of the
numerator of u and the exponent of the denominator of u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import RationalFunctionExponents
>>> from sympy.abc import x, a
>>> RationalFunctionExponents(x, x)
[1, 0]
>>> RationalFunctionExponents(x**(-1), x)
[0, 1]
>>> RationalFunctionExponents(x**(-1)*a, x)
[0, 1]
"""
if PolynomialQ(u, x):
return [Exponent(u, x), 0]
elif IntegerPowerQ(u):
if PositiveQ(u.exp):
return u.exp*RationalFunctionExponents(u.base, x)
return (-u.exp)*Reverse(RationalFunctionExponents(u.base, x))
elif ProductQ(u):
lst1 = RationalFunctionExponents(First(u), x)
lst2 = RationalFunctionExponents(Rest(u), x)
return [lst1[0] + lst2[0], lst1[1] + lst2[1]]
elif SumQ(u):
v = Together(u)
if SumQ(v):
lst1 = RationalFunctionExponents(First(u), x)
lst2 = RationalFunctionExponents(Rest(u), x)
return [Max(lst1[0] + lst2[1], lst2[0] + lst1[1]), lst1[1] + lst2[1]]
else:
return RationalFunctionExponents(v, x)
return [0, 0]
def RationalFunctionExpand(expr, x):
# expr is a polynomial or rational function of x.
# RationalFunctionExpand[u,x] returns the expansion of the factors of u that are rational functions times the other factors.
def cons_f1(n):
return FractionQ(n)
cons1 = CustomConstraint(cons_f1)
def cons_f2(x, v):
if not isinstance(x, Symbol):
return False
return UnsameQ(v, x)
cons2 = CustomConstraint(cons_f2)
def With1(n, u, x, v):
w = RationalFunctionExpand(u, x)
return If(SumQ(w), Add(*[i*v**n for i in w.args]), v**n*w)
pattern1 = Pattern(UtilityOperator(u_*v_**n_, x_), cons1, cons2)
rule1 = ReplacementRule(pattern1, With1)
def With2(u, x):
v = ExpandIntegrand(u, x)
def _consf_u(a, b, c, d, p, m, n, x):
return And(FreeQ(List(a, b, c, d, p), x), IntegersQ(m, n), Equal(m, Add(n, S(-1))))
cons_u = CustomConstraint(_consf_u)
pat = Pattern(UtilityOperator(x_**WC('m', S(1))*(x_*WC('d', S(1)) + c_)**p_/(x_**n_*WC('b', S(1)) + a_), x_), cons_u)
result_matchq = is_match(UtilityOperator(u, x), pat)
if UnsameQ(v, u) and not result_matchq:
return v
else:
v = ExpandIntegrand(RationalFunctionFactors(u, x), x)
w = NonrationalFunctionFactors(u, x)
if SumQ(v):
return Add(*[i*w for i in v.args])
else:
return v*w
pattern2 = Pattern(UtilityOperator(u_, x_))
rule2 = ReplacementRule(pattern2, With2)
expr = expr.replace(sym_exp, rubi_exp)
res = replace_all(UtilityOperator(expr, x), [rule1, rule2])
return replace_pow_exp(res)
def ExpandIntegrand(expr, x, extra=None):
expr = replace_pow_exp(expr)
if not extra is None:
extra, x = x, extra
w = ExpandIntegrand(extra, x)
r = NonfreeTerms(w, x)
if SumQ(r):
result = [expr*FreeTerms(w, x)]
for i in r.args:
result.append(MergeMonomials(expr*i, x))
return r.func(*result)
else:
return expr*FreeTerms(w, x) + MergeMonomials(expr*r, x)
else:
u_ = Wild('u', exclude=[0, 1])
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
F_ = Wild('F', exclude=[0])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x, 0])
n_ = Wild('n', exclude=[0, 1])
pattern = u_*(a_ + b_*F_)**n_
match = expr.match(pattern)
if match:
if MemberQ([asin, acos, asinh, acosh], match[F_].func):
keys = [u_, a_, b_, F_, n_]
if len(match) == len(keys):
u, a, b, F, n = tuple([match[i] for i in keys])
match = F.args[0].match(c_ + d_*x)
if match:
keys = c_, d_
if len(keys) == len(match):
c, d = tuple([match[i] for i in keys])
if PolynomialQ(u, x):
F = F.func
return ExpandLinearProduct((a + b*F(c + d*x))**n, u, c, d, x)
expr = expr.replace(sym_exp, rubi_exp)
res = replace_all(UtilityOperator(expr, x), ExpandIntegrand_rules, max_count = 1)
return replace_pow_exp(res)
def SimplerQ(u, v):
# If u is simpler than v, SimplerQ(u, v) returns True, else it returns False. SimplerQ(u, u) returns False
if IntegerQ(u):
if IntegerQ(v):
if Abs(u)==Abs(v):
return v<0
else:
return Abs(u)<Abs(v)
else:
return True
elif IntegerQ(v):
return False
elif FractionQ(u):
if FractionQ(v):
if Denominator(u) == Denominator(v):
return SimplerQ(Numerator(u), Numerator(v))
else:
return Denominator(u)<Denominator(v)
else:
return True
elif FractionQ(v):
return False
elif (Re(u)==0 or Re(u) == 0) and (Re(v)==0 or Re(v) == 0):
return SimplerQ(Im(u), Im(v))
elif ComplexNumberQ(u):
if ComplexNumberQ(v):
if Re(u) == Re(v):
return SimplerQ(Im(u), Im(v))
else:
return SimplerQ(Re(u),Re(v))
else:
return False
elif NumberQ(u):
if NumberQ(v):
return OrderedQ([u,v])
else:
return True
elif NumberQ(v):
return False
elif AtomQ(u) or (Head(u) == re) or (Head(u) == im):
if AtomQ(v) or (Head(u) == re) or (Head(u) == im):
return OrderedQ([u,v])
else:
return True
elif AtomQ(v) or (Head(u) == re) or (Head(u) == im):
return False
elif Head(u) == Head(v):
if Length(u) == Length(v):
for i in range(len(u.args)):
if not u.args[i] == v.args[i]:
return SimplerQ(u.args[i], v.args[i])
return False
return Length(u) < Length(v)
elif LeafCount(u) < LeafCount(v):
return True
elif LeafCount(v) < LeafCount(u):
return False
return Not(OrderedQ([v,u]))
def SimplerSqrtQ(u, v):
# If Rt(u, 2) is simpler than Rt(v, 2), SimplerSqrtQ(u, v) returns True, else it returns False. SimplerSqrtQ(u, u) returns False
if NegativeQ(v) and Not(NegativeQ(u)):
return True
if NegativeQ(u) and Not(NegativeQ(v)):
return False
sqrtu = Rt(u, S(2))
sqrtv = Rt(v, S(2))
if IntegerQ(sqrtu):
if IntegerQ(sqrtv):
return sqrtu<sqrtv
else:
return True
if IntegerQ(sqrtv):
return False
if RationalQ(sqrtu):
if RationalQ(sqrtv):
return sqrtu<sqrtv
else:
return True
if RationalQ(sqrtv):
return False
if PosQ(u):
if PosQ(v):
return LeafCount(sqrtu)<LeafCount(sqrtv)
else:
return True
if PosQ(v):
return False
if LeafCount(sqrtu)<LeafCount(sqrtv):
return True
if LeafCount(sqrtv)<LeafCount(sqrtu):
return False
else:
return Not(OrderedQ([v, u]))
def SumSimplerQ(u, v):
"""
If u + v is simpler than u, SumSimplerQ(u, v) returns True, else it returns False.
If for every term w of v there is a term of u equal to n*w where n<-1/2, u + v will be simpler than u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import SumSimplerQ
>>> from sympy.abc import x
>>> from sympy import S
>>> SumSimplerQ(S(4 + x),S(3 + x**3))
False
"""
if RationalQ(u, v):
if v == S(0):
return False
elif v > S(0):
return u < -S(1)
else:
return u >= -v
else:
return SumSimplerAuxQ(Expand(u), Expand(v))
def BinomialDegree(u, x):
# if u is a binomial. BinomialDegree[u,x] returns the degree of x in u.
bp = BinomialParts(u, x)
if bp == False:
return bp
return bp[2]
def TrinomialDegree(u, x):
# If u is equivalent to a trinomial of the form a + b*x^n + c*x^(2*n) where n!=0, b!=0 and c!=0, TrinomialDegree[u,x] returns n
t = TrinomialParts(u, x)
if t:
return t[3]
return t
def CancelCommonFactors(u, v):
def _delete_cases(a, b):
# only for CancelCommonFactors
lst = []
deleted = False
for i in a.args:
if i == b and not deleted:
deleted = True
continue
lst.append(i)
return a.func(*lst)
# CancelCommonFactors[u,v] returns {u',v'} are the noncommon factors of u and v respectively.
if ProductQ(u):
if ProductQ(v):
if MemberQ(v, First(u)):
return CancelCommonFactors(Rest(u), _delete_cases(v, First(u)))
else:
lst = CancelCommonFactors(Rest(u), v)
return [First(u)*lst[0], lst[1]]
else:
if MemberQ(u, v):
return [_delete_cases(u, v), 1]
else:
return[u, v]
elif ProductQ(v):
if MemberQ(v, u):
return [1, _delete_cases(v, u)]
else:
return [u, v]
return[u, v]
def SimplerIntegrandQ(u, v, x):
lst = CancelCommonFactors(u, v)
u1 = lst[0]
v1 = lst[1]
if Head(u1) == Head(v1) and Length(u1) == 1 and Length(v1) == 1:
return SimplerIntegrandQ(u1.args[0], v1.args[0], x)
if 4*LeafCount(u1) < 3*LeafCount(v1):
return True
if RationalFunctionQ(u1, x):
if RationalFunctionQ(v1, x):
t1 = 0
t2 = 0
for i in RationalFunctionExponents(u1, x):
t1 += i
for i in RationalFunctionExponents(v1, x):
t2 += i
return t1 < t2
else:
return True
else:
return False
def GeneralizedBinomialDegree(u, x):
b = GeneralizedBinomialParts(u, x)
if b:
return b[2] - b[3]
def GeneralizedBinomialParts(expr, x):
expr = Expand(expr)
if GeneralizedBinomialMatchQ(expr, x):
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
n = Wild('n', exclude=[x])
q = Wild('q', exclude=[x])
Match = expr.match(a*x**q + b*x**n)
if Match and PosQ(Match[q] - Match[n]):
return [Match[b], Match[a], Match[q], Match[n]]
else:
return False
def GeneralizedTrinomialDegree(u, x):
t = GeneralizedTrinomialParts(u, x)
if t:
return t[3] - t[4]
def GeneralizedTrinomialParts(expr, x):
expr = Expand(expr)
if GeneralizedTrinomialMatchQ(expr, x):
a = Wild('a', exclude=[x, 0])
b = Wild('b', exclude=[x, 0])
c = Wild('c', exclude=[x])
n = Wild('n', exclude=[x, 0])
q = Wild('q', exclude=[x])
Match = expr.match(a*x**q + b*x**n+c*x**(2*n-q))
if Match and expr.is_Add:
return [Match[c], Match[b], Match[a], Match[n], 2*Match[n]-Match[q]]
else:
return False
def MonomialQ(u, x):
# If u is of the form a*x^n where n!=0 and a!=0, MonomialQ[u,x] returns True; else False
if isinstance(u, list):
return all(MonomialQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
re = u.match(a*x**b)
if re:
return True
return False
def MonomialSumQ(u, x):
# if u(x) is a sum and each term is free of x or an expression of the form a*x^n, MonomialSumQ(u, x) returns True; else it returns False
if SumQ(u):
for i in u.args:
if Not(FreeQ(i, x) or MonomialQ(i, x)):
return False
return True
@doctest_depends_on(modules=('matchpy',))
def MinimumMonomialExponent(u, x):
"""
u is sum whose terms are monomials. MinimumMonomialExponent(u, x) returns the exponent of the term having the smallest exponent
Examples
========
>>> from sympy.integrals.rubi.utility_function import MinimumMonomialExponent
>>> from sympy.abc import x
>>> MinimumMonomialExponent(x**2 + 5*x**2 + 3*x**5, x)
2
>>> MinimumMonomialExponent(x**2 + 5*x**2 + 1, x)
0
"""
n =MonomialExponent(First(u), x)
for i in u.args:
if PosQ(n - MonomialExponent(i, x)):
n = MonomialExponent(i, x)
return n
def MonomialExponent(u, x):
# u is a monomial. MonomialExponent(u, x) returns the exponent of x in u
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
re = u.match(a*x**b)
if re:
return re[b]
def LinearMatchQ(u, x):
# LinearMatchQ(u, x) returns True iff u matches patterns of the form a+b*x where a and b are free of x
if isinstance(u, list):
return all(LinearMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
re = u.match(a + b*x)
if re:
return True
return False
def PowerOfLinearMatchQ(u, x):
if isinstance(u, list):
for i in u:
if not PowerOfLinearMatchQ(i, x):
return False
return True
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x, 0])
m = Wild('m', exclude=[x, 0])
Match = u.match((a + b*x)**m)
if Match:
return True
else:
return False
def QuadraticMatchQ(u, x):
if ListQ(u):
return all(QuadraticMatchQ(i, x) for i in u)
pattern1 = Pattern(UtilityOperator(x_**2*WC('c', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, c, x: FreeQ([a, b, c], x)))
pattern2 = Pattern(UtilityOperator(x_**2*WC('c', 1) + WC('a', 0), x_), CustomConstraint(lambda a, c, x: FreeQ([a, c], x)))
u1 = UtilityOperator(u, x)
return is_match(u1, pattern1) or is_match(u1, pattern2)
def CubicMatchQ(u, x):
if isinstance(u, list):
return all(CubicMatchQ(i, x) for i in u)
else:
pattern1 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_**2*WC('c', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, c, d, x: FreeQ([a, b, c, d], x)))
pattern2 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, d, x: FreeQ([a, b, d], x)))
pattern3 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_**2*WC('c', 1) + WC('a', 0), x_), CustomConstraint(lambda a, c, d, x: FreeQ([a, c, d], x)))
pattern4 = Pattern(UtilityOperator(x_**3*WC('d', 1) + WC('a', 0), x_), CustomConstraint(lambda a, d, x: FreeQ([a, d], x)))
u1 = UtilityOperator(u, x)
if is_match(u1, pattern1) or is_match(u1, pattern2) or is_match(u1, pattern3) or is_match(u1, pattern4):
return True
else:
return False
def BinomialMatchQ(u, x):
if isinstance(u, list):
return all(BinomialMatchQ(i, x) for i in u)
else:
pattern = Pattern(UtilityOperator(x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)), x_) , CustomConstraint(lambda a, b, n, x: FreeQ([a,b,n],x)))
u = UtilityOperator(u, x)
return is_match(u, pattern)
def TrinomialMatchQ(u, x):
if isinstance(u, list):
return all(TrinomialMatchQ(i, x) for i in u)
else:
pattern = Pattern(UtilityOperator(x_**WC('j', S(1))*WC('c', S(1)) + x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)), x_) , CustomConstraint(lambda a, b, c, n, x: FreeQ([a, b, c, n], x)), CustomConstraint(lambda j, n: ZeroQ(j-2*n) ))
u = UtilityOperator(u, x)
return is_match(u, pattern)
def GeneralizedBinomialMatchQ(u, x):
if isinstance(u, list):
return all(GeneralizedBinomialMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x, 0])
b = Wild('b', exclude=[x, 0])
n = Wild('n', exclude=[x, 0])
q = Wild('q', exclude=[x, 0])
Match = u.match(a*x**q + b*x**n)
if Match and len(Match) == 4 and Match[q] != 0 and Match[n] != 0:
return True
else:
return False
def GeneralizedTrinomialMatchQ(u, x):
if isinstance(u, list):
return all(GeneralizedTrinomialMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x, 0])
b = Wild('b', exclude=[x, 0])
n = Wild('n', exclude=[x, 0])
c = Wild('c', exclude=[x, 0])
q = Wild('q', exclude=[x, 0])
Match = u.match(a*x**q + b*x**n + c*x**(2*n - q))
if Match and len(Match) == 5 and 2*Match[n] - Match[q] != 0 and Match[n] != 0:
return True
else:
return False
def QuotientOfLinearsMatchQ(u, x):
if isinstance(u, list):
return all(QuotientOfLinearsMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
d = Wild('d', exclude=[x])
c = Wild('c', exclude=[x])
e = Wild('e')
Match = u.match(e*(a + b*x)/(c + d*x))
if Match and len(Match) == 5:
return True
else:
return False
def PolynomialTermQ(u, x):
a = Wild('a', exclude=[x])
n = Wild('n', exclude=[x])
Match = u.match(a*x**n)
if Match and IntegerQ(Match[n]) and Greater(Match[n], S(0)):
return True
else:
return False
def PolynomialTerms(u, x):
s = 0
for i in u.args:
if PolynomialTermQ(i, x):
s = s + i
return s
def NonpolynomialTerms(u, x):
s = 0
for i in u.args:
if not PolynomialTermQ(i, x):
s = s + i
return s
def PseudoBinomialParts(u, x):
if PolynomialQ(u, x) and Greater(Expon(u, x), S(2)):
n = Expon(u, x)
d = Rt(Coefficient(u, x, n), n)
c = d**(-n + S(1))*Coefficient(u, x, n + S(-1))/n
a = Simplify(u - (c + d*x)**n)
if NonzeroQ(a) and FreeQ(a, x):
return [a, S(1), c, d, n]
else:
return False
else:
return False
def NormalizePseudoBinomial(u, x):
lst = PseudoBinomialParts(u, x)
if lst:
return (lst[0] + lst[1]*(lst[2] + lst[3]*x)**lst[4])
def PseudoBinomialPairQ(u, v, x):
lst1 = PseudoBinomialParts(u, x)
if AtomQ(lst1):
return False
else:
lst2 = PseudoBinomialParts(v, x)
if AtomQ(lst2):
return False
else:
return Drop(lst1, 2) == Drop(lst2, 2)
def PseudoBinomialQ(u, x):
lst = PseudoBinomialParts(u, x)
if lst:
return True
else:
return False
def PolynomialGCD(f, g):
return gcd(f, g)
def PolyGCD(u, v, x):
# (* u and v are polynomials in x. *)
# (* PolyGCD[u,v,x] returns the factors of the gcd of u and v dependent on x. *)
return NonfreeFactors(PolynomialGCD(u, v), x)
def AlgebraicFunctionFactors(u, x, flag=False):
# (* AlgebraicFunctionFactors[u,x] returns the product of the factors of u that are algebraic functions of x. *)
if ProductQ(u):
result = 1
for i in u.args:
if AlgebraicFunctionQ(i, x, flag):
result *= i
return result
if AlgebraicFunctionQ(u, x, flag):
return u
return 1
def NonalgebraicFunctionFactors(u, x):
"""
NonalgebraicFunctionFactors[u,x] returns the product of the factors of u that are not algebraic functions of x.
Examples
========
>>> from sympy.integrals.rubi.utility_function import NonalgebraicFunctionFactors
>>> from sympy.abc import x
>>> from sympy import sin
>>> NonalgebraicFunctionFactors(sin(x), x)
sin(x)
>>> NonalgebraicFunctionFactors(x, x)
1
"""
if ProductQ(u):
result = 1
for i in u.args:
if not AlgebraicFunctionQ(i, x):
result *= i
return result
if AlgebraicFunctionQ(u, x):
return 1
return u
def QuotientOfLinearsP(u, x):
if LinearQ(u, x):
return True
elif SumQ(u):
if FreeQ(u.args[0], x):
return QuotientOfLinearsP(Rest(u), x)
elif LinearQ(Numerator(u), x) and LinearQ(Denominator(u), x):
return True
elif ProductQ(u):
if FreeQ(First(u), x):
return QuotientOfLinearsP(Rest(u), x)
elif Numerator(u) == 1 and PowerQ(u):
return QuotientOfLinearsP(Denominator(u), x)
return u == x or FreeQ(u, x)
def QuotientOfLinearsParts(u, x):
# If u is equivalent to an expression of the form (a+b*x)/(c+d*x), QuotientOfLinearsParts[u,x]
# returns the list {a, b, c, d}.
if LinearQ(u, x):
return [Coefficient(u, x, 0), Coefficient(u, x, 1), 1, 0]
elif PowerQ(u):
if Numerator(u) == 1:
u = Denominator(u)
r = QuotientOfLinearsParts(u, x)
return [r[2], r[3], r[0], r[1]]
elif SumQ(u):
a = First(u)
if FreeQ(a, x):
u = Rest(u)
r = QuotientOfLinearsParts(u, x)
return [r[0] + a*r[2], r[1] + a*r[3], r[2], r[3]]
elif ProductQ(u):
a = First(u)
if FreeQ(a, x):
r = QuotientOfLinearsParts(Rest(u), x)
return [a*r[0], a*r[1], r[2], r[3]]
a = Numerator(u)
d = Denominator(u)
if LinearQ(a, x) and LinearQ(d, x):
return [Coefficient(a, x, 0), Coefficient(a, x, 1), Coefficient(d, x, 0), Coefficient(d, x, 1)]
elif u == x:
return [0, 1, 1, 0]
elif FreeQ(u, x):
return [u, 0, 1, 0]
return [u, 0, 1, 0]
def QuotientOfLinearsQ(u, x):
# (*QuotientOfLinearsQ[u,x] returns True iff u is equivalent to an expression of the form (a+b x)/(c+d x) where b!=0 and d!=0.*)
if ListQ(u):
for i in u:
if not QuotientOfLinearsQ(i, x):
return False
return True
q = QuotientOfLinearsParts(u, x)
return QuotientOfLinearsP(u, x) and NonzeroQ(q[1]) and NonzeroQ(q[3])
def Flatten(l):
return flatten(l)
def Sort(u, r=False):
return sorted(u, key=lambda x: x.sort_key(), reverse=r)
# (*Definition: A number is absurd if it is a rational number, a positive rational number raised to a fractional power, or a product of absurd numbers.*)
def AbsurdNumberQ(u):
# (* AbsurdNumberQ[u] returns True if u is an absurd number, else it returns False. *)
if PowerQ(u):
v = u.exp
u = u.base
return RationalQ(u) and u > 0 and FractionQ(v)
elif ProductQ(u):
return all(AbsurdNumberQ(i) for i in u.args)
return RationalQ(u)
def AbsurdNumberFactors(u):
# (* AbsurdNumberFactors[u] returns the product of the factors of u that are absurd numbers. *)
if AbsurdNumberQ(u):
return u
elif ProductQ(u):
result = S(1)
for i in u.args:
if AbsurdNumberQ(i):
result *= i
return result
return NumericFactor(u)
def NonabsurdNumberFactors(u):
# (* NonabsurdNumberFactors[u] returns the product of the factors of u that are not absurd numbers. *)
if AbsurdNumberQ(u):
return S(1)
elif ProductQ(u):
result = 1
for i in u.args:
result *= NonabsurdNumberFactors(i)
return result
return NonnumericFactors(u)
def SumSimplerAuxQ(u, v):
if SumQ(v):
return (RationalQ(First(v)) or SumSimplerAuxQ(u,First(v))) and (RationalQ(Rest(v)) or SumSimplerAuxQ(u,Rest(v)))
elif SumQ(u):
return SumSimplerAuxQ(First(u), v) or SumSimplerAuxQ(Rest(u), v)
else:
return v!=0 and NonnumericFactors(u)==NonnumericFactors(v) and (NumericFactor(u)/NumericFactor(v)<-1/2 or NumericFactor(u)/NumericFactor(v)==-1/2 and NumericFactor(u)<0)
def Prepend(l1, l2):
if not isinstance(l2, list):
return [l2] + l1
return l2 + l1
def Drop(lst, n):
if isinstance(lst, list):
if isinstance(n, list):
lst = lst[:(n[0]-1)] + lst[n[1]:]
elif n > 0:
lst = lst[n:]
elif n < 0:
lst = lst[:-n]
else:
return lst
return lst
return lst.func(*[i for i in Drop(list(lst.args), n)])
def CombineExponents(lst):
if Length(lst) < 2:
return lst
elif lst[0][0] == lst[1][0]:
return CombineExponents(Prepend(Drop(lst,2),[lst[0][0], lst[0][1] + lst[1][1]]))
return Prepend(CombineExponents(Rest(lst)), First(lst))
def FactorInteger(n, l=None):
if isinstance(n, (int, Integer)):
return sorted(factorint(n, limit=l).items())
else:
return sorted(factorrat(n, limit=l).items())
def FactorAbsurdNumber(m):
# (* m must be an absurd number. FactorAbsurdNumber[m] returns the prime factorization of m *)
# (* as list of base-degree pairs where the bases are prime numbers and the degrees are rational. *)
if RationalQ(m):
return FactorInteger(m)
elif PowerQ(m):
r = FactorInteger(m.base)
return [r[0], r[1]*m.exp]
# CombineExponents[Sort[Flatten[Map[FactorAbsurdNumber,Apply[List,m]],1], Function[i1[[1]]<i2[[1]]]]]
return list((m.as_base_exp(),))
def SubstForInverseFunction(*args):
"""
SubstForInverseFunction(u, v, w, x) returns u with subexpressions equal to v replaced by x and x replaced by w.
Examples
========
>>> from sympy.integrals.rubi.utility_function import SubstForInverseFunction
>>> from sympy.abc import x, a, b
>>> SubstForInverseFunction(a, a, b, x)
a
>>> SubstForInverseFunction(x**a, x**a, b, x)
x
>>> SubstForInverseFunction(a*x**a, a, b, x)
a*b**a
"""
if len(args) == 3:
u, v, x = args[0], args[1], args[2]
return SubstForInverseFunction(u, v, (-Coefficient(v.args[0], x, 0) + InverseFunction(Head(v))(x))/Coefficient(v.args[0], x, 1), x)
elif len(args) == 4:
u, v, w, x = args[0], args[1], args[2], args[3]
if AtomQ(u):
if u == x:
return w
return u
elif Head(u) == Head(v) and ZeroQ(u.args[0] - v.args[0]):
return x
res = [SubstForInverseFunction(i, v, w, x) for i in u.args]
return u.func(*res)
def SubstForFractionalPower(u, v, n, w, x):
# (* SubstForFractionalPower[u,v,n,w,x] returns u with subexpressions equal to v^(m/n) replaced
# by x^m and x replaced by w. *)
if AtomQ(u):
if u == x:
return w
return u
elif FractionalPowerQ(u):
if ZeroQ(u.base - v):
return x**(n*u.exp)
res = [SubstForFractionalPower(i, v, n, w, x) for i in u.args]
return u.func(*res)
def SubstForFractionalPowerOfQuotientOfLinears(u, x):
# (* If u has a subexpression of the form ((a+b*x)/(c+d*x))^(m/n) where m and n>1 are integers,
# SubstForFractionalPowerOfQuotientOfLinears[u,x] returns the list {v,n,(a+b*x)/(c+d*x),b*c-a*d} where v is u
# with subexpressions of the form ((a+b*x)/(c+d*x))^(m/n) replaced by x^m and x replaced
lst = FractionalPowerOfQuotientOfLinears(u, 1, False, x)
if AtomQ(lst) or AtomQ(lst[1]):
return False
n = lst[0]
tmp = lst[1]
lst = QuotientOfLinearsParts(tmp, x)
a, b, c, d = lst[0], lst[1], lst[2], lst[3]
if ZeroQ(d):
return False
lst = Simplify(x**(n - 1)*SubstForFractionalPower(u, tmp, n, (-a + c*x**n)/(b - d*x**n), x)/(b - d*x**n)**2)
return [NonfreeFactors(lst, x), n, tmp, FreeFactors(lst, x)*(b*c - a*d)]
def FractionalPowerOfQuotientOfLinears(u, n, v, x):
# (* If u has a subexpression of the form ((a+b*x)/(c+d*x))^(m/n),
# FractionalPowerOfQuotientOfLinears[u,1,False,x] returns {n,(a+b*x)/(c+d*x)}; else it returns False. *)
if AtomQ(u) or FreeQ(u, x):
return [n, v]
elif CalculusQ(u):
return False
elif FractionalPowerQ(u):
if QuotientOfLinearsQ(u.base, x) and Not(LinearQ(u.base, x)) and (FalseQ(v) or ZeroQ(u.base - v)):
return [LCM(Denominator(u.exp), n), u.base]
lst = [n, v]
for i in u.args:
lst = FractionalPowerOfQuotientOfLinears(i, lst[0], lst[1],x)
if AtomQ(lst):
return False
return lst
def SubstForFractionalPowerQ(u, v, x):
# (* If the substitution x=v^(1/n) will not complicate algebraic subexpressions of u,
# SubstForFractionalPowerQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u) or FreeQ(u, x):
return True
elif FractionalPowerQ(u):
return SubstForFractionalPowerAuxQ(u, v, x)
return all(SubstForFractionalPowerQ(i, v, x) for i in u.args)
def SubstForFractionalPowerAuxQ(u, v, x):
if AtomQ(u):
return False
elif FractionalPowerQ(u):
if ZeroQ(u.base - v):
return True
return any(SubstForFractionalPowerAuxQ(i, v, x) for i in u.args)
def FractionalPowerOfSquareQ(u):
# (* If a subexpression of u is of the form ((v+w)^2)^n where n is a fraction, *)
# (* FractionalPowerOfSquareQ[u] returns (v+w)^2; else it returns False. *)
if AtomQ(u):
return False
elif FractionalPowerQ(u):
a_ = Wild('a', exclude=[0])
b_ = Wild('b', exclude=[0])
c_ = Wild('c', exclude=[0])
match = u.base.match(a_*(b_ + c_)**(S(2)))
if match:
keys = [a_, b_, c_]
if len(keys) == len(match):
a, b, c = tuple(match[i] for i in keys)
if NonsumQ(a):
return (b + c)**S(2)
for i in u.args:
tmp = FractionalPowerOfSquareQ(i)
if Not(FalseQ(tmp)):
return tmp
return False
def FractionalPowerSubexpressionQ(u, v, w):
# (* If a subexpression of u is of the form w^n where n is a fraction but not equal to v, *)
# (* FractionalPowerSubexpressionQ[u,v,w] returns True; else it returns False. *)
if AtomQ(u):
return False
elif FractionalPowerQ(u):
if PositiveQ(u.base/w):
return Not(u.base == v) and LeafCount(w) < 3*LeafCount(v)
for i in u.args:
if FractionalPowerSubexpressionQ(i, v, w):
return True
return False
def Apply(f, lst):
return f(*lst)
def FactorNumericGcd(u):
# (* FactorNumericGcd[u] returns u with the gcd of the numeric coefficients of terms of sums factored out. *)
if PowerQ(u):
if RationalQ(u.exp):
return FactorNumericGcd(u.base)**u.exp
elif ProductQ(u):
res = [FactorNumericGcd(i) for i in u.args]
return Mul(*res)
elif SumQ(u):
g = GCD([NumericFactor(i) for i in u.args])
r = Add(*[i/g for i in u.args])
return g*r
return u
def MergeableFactorQ(bas, deg, v):
# (* MergeableFactorQ[bas,deg,v] returns True iff bas equals the base of a factor of v or bas is a factor of every term of v. *)
if bas == v:
return RationalQ(deg + S(1)) and (deg + 1>=0 or RationalQ(deg) and deg>0)
elif PowerQ(v):
if bas == v.base:
return RationalQ(deg+v.exp) and (deg+v.exp>=0 or RationalQ(deg) and deg>0)
return SumQ(v.base) and IntegerQ(v.exp) and (Not(IntegerQ(deg) or IntegerQ(deg/v.exp))) and MergeableFactorQ(bas, deg/v.exp, v.base)
elif ProductQ(v):
return MergeableFactorQ(bas, deg, First(v)) or MergeableFactorQ(bas, deg, Rest(v))
return SumQ(v) and MergeableFactorQ(bas, deg, First(v)) and MergeableFactorQ(bas, deg, Rest(v))
def MergeFactor(bas, deg, v):
# (* If MergeableFactorQ[bas,deg,v], MergeFactor[bas,deg,v] return the product of bas^deg and v,
# but with bas^deg merged into the factor of v whose base equals bas. *)
if bas == v:
return bas**(deg + 1)
elif PowerQ(v):
if bas == v.base:
return bas**(deg + v.exp)
return MergeFactor(bas, deg/v.exp, v.base**v.exp)
elif ProductQ(v):
if MergeableFactorQ(bas, deg, First(v)):
return MergeFactor(bas, deg, First(v))*Rest(v)
return First(v)*MergeFactor(bas, deg, Rest(v))
return MergeFactor(bas, deg, First(v)) + MergeFactor(bas, deg, Rest(v))
def MergeFactors(u, v):
# (* MergeFactors[u,v] returns the product of u and v, but with the mergeable factors of u merged into v. *)
if ProductQ(u):
return MergeFactors(Rest(u), MergeFactors(First(u), v))
elif PowerQ(u):
if MergeableFactorQ(u.base, u.exp, v):
return MergeFactor(u.base, u.exp, v)
elif RationalQ(u.exp) and u.exp < -1 and MergeableFactorQ(u.base, -S(1), v):
return MergeFactors(u.base**(u.exp + 1), MergeFactor(u.base, -S(1), v))
return u*v
elif MergeableFactorQ(u, S(1), v):
return MergeFactor(u, S(1), v)
return u*v
def TrigSimplifyQ(u):
# (* TrigSimplifyQ[u] returns True if TrigSimplify[u] actually simplifies u; else False. *)
return ActivateTrig(u) != TrigSimplify(u)
def TrigSimplify(u):
# (* TrigSimplify[u] returns a bottom-up trig simplification of u. *)
return ActivateTrig(TrigSimplifyRecur(u))
def TrigSimplifyRecur(u):
if AtomQ(u):
return u
return TrigSimplifyAux(u.func(*[TrigSimplifyRecur(i) for i in u.args]))
def Order(expr1, expr2):
if expr1 == expr2:
return 0
elif expr1.sort_key() > expr2.sort_key():
return -1
return 1
def FactorOrder(u, v):
if u == 1:
if v == 1:
return 0
return -1
elif v == 1:
return 1
return Order(u, v)
def Smallest(num1, num2=None):
if num2 is None:
lst = num1
num = lst[0]
for i in Rest(lst):
num = Smallest(num, i)
return num
return Min(num1, num2)
def OrderedQ(l):
return l == Sort(l)
def MinimumDegree(deg1, deg2):
if RationalQ(deg1):
if RationalQ(deg2):
return Min(deg1, deg2)
return deg1
elif RationalQ(deg2):
return deg2
deg = Simplify(deg1- deg2)
if RationalQ(deg):
if deg > 0:
return deg2
return deg1
elif OrderedQ([deg1, deg2]):
return deg1
return deg2
def PositiveFactors(u):
# (* PositiveFactors[u] returns the positive factors of u *)
if ZeroQ(u):
return S(1)
elif RationalQ(u):
return Abs(u)
elif PositiveQ(u):
return u
elif ProductQ(u):
res = 1
for i in u.args:
res *= PositiveFactors(i)
return res
return 1
def Sign(u):
return sign(u)
def NonpositiveFactors(u):
# (* NonpositiveFactors[u] returns the nonpositive factors of u *)
if ZeroQ(u):
return u
elif RationalQ(u):
return Sign(u)
elif PositiveQ(u):
return S(1)
elif ProductQ(u):
res = S(1)
for i in u.args:
res *= NonpositiveFactors(i)
return res
return u
def PolynomialInAuxQ(u, v, x):
if u == v:
return True
elif AtomQ(u):
return u != x
elif PowerQ(u):
if PowerQ(v):
if u.base == v.base:
return PositiveIntegerQ(u.exp/v.exp)
return PositiveIntegerQ(u.exp) and PolynomialInAuxQ(u.base, v, x)
elif SumQ(u) or ProductQ(u):
for i in u.args:
if Not(PolynomialInAuxQ(i, v, x)):
return False
return True
return False
def PolynomialInQ(u, v, x):
"""
If u is a polynomial in v(x), PolynomialInQ(u, v, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import PolynomialInQ
>>> from sympy.abc import x
>>> from sympy import log, S
>>> PolynomialInQ(S(1), log(x), x)
True
>>> PolynomialInQ(log(x), log(x), x)
True
>>> PolynomialInQ(1 + log(x)**2, log(x), x)
True
"""
return PolynomialInAuxQ(u, NonfreeFactors(NonfreeTerms(v, x), x), x)
def ExponentInAux(u, v, x):
if u == v:
return S(1)
elif AtomQ(u):
return S(0)
elif PowerQ(u):
if PowerQ(v):
if u.base == v.base:
return u.exp/v.exp
return u.exp*ExponentInAux(u.base, v, x)
elif ProductQ(u):
return Add(*[ExponentInAux(i, v, x) for i in u.args])
return Max(*[ExponentInAux(i, v, x) for i in u.args])
def ExponentIn(u, v, x):
return ExponentInAux(u, NonfreeFactors(NonfreeTerms(v, x), x), x)
def PolynomialInSubstAux(u, v, x):
if u == v:
return x
elif AtomQ(u):
return u
elif PowerQ(u):
if PowerQ(v):
if u.base == v.base:
return x**(u.exp/v.exp)
return PolynomialInSubstAux(u.base, v, x)**u.exp
return u.func(*[PolynomialInSubstAux(i, v, x) for i in u.args])
def PolynomialInSubst(u, v, x):
# If u is a polynomial in v[x], PolynomialInSubst[u,v,x] returns the polynomial u in x.
w = NonfreeTerms(v, x)
return ReplaceAll(PolynomialInSubstAux(u, NonfreeFactors(w, x), x), {x: x - FreeTerms(v, x)/FreeFactors(w, x)})
def Distrib(u, v):
# Distrib[u,v] returns the sum of u times each term of v.
if SumQ(v):
return Add(*[u*i for i in v.args])
return u*v
def DistributeDegree(u, m):
# DistributeDegree[u,m] returns the product of the factors of u each raised to the mth degree.
if AtomQ(u):
return u**m
elif PowerQ(u):
return u.base**(u.exp*m)
elif ProductQ(u):
return Mul(*[DistributeDegree(i, m) for i in u.args])
return u**m
def FunctionOfPower(*args):
"""
FunctionOfPower[u,x] returns the gcd of the integer degrees of x in u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import FunctionOfPower
>>> from sympy.abc import x
>>> FunctionOfPower(x, x)
1
>>> FunctionOfPower(x**3, x)
3
"""
if len(args) == 2:
return FunctionOfPower(args[0], None, args[1])
u, n, x = args
if FreeQ(u, x):
return n
elif u == x:
return S(1)
elif PowerQ(u):
if u.base == x and IntegerQ(u.exp):
if n is None:
return u.exp
return GCD(n, u.exp)
tmp = n
for i in u.args:
tmp = FunctionOfPower(i, tmp, x)
return tmp
def DivideDegreesOfFactors(u, n):
"""
DivideDegreesOfFactors[u,n] returns the product of the base of the factors of u raised to the degree of the factors divided by n.
Examples
========
>>> from sympy import S
>>> from sympy.integrals.rubi.utility_function import DivideDegreesOfFactors
>>> from sympy.abc import a, b
>>> DivideDegreesOfFactors(a**b, S(3))
a**(b/3)
"""
if ProductQ(u):
return Mul(*[LeadBase(i)**(LeadDegree(i)/n) for i in u.args])
return LeadBase(u)**(LeadDegree(u)/n)
def MonomialFactor(u, x):
# MonomialFactor[u,x] returns the list {n,v} where x^n*v==u and n is free of x.
if AtomQ(u):
if u == x:
return [S(1), S(1)]
return [S(0), u]
elif PowerQ(u):
if IntegerQ(u.exp):
lst = MonomialFactor(u.base, x)
return [lst[0]*u.exp, lst[1]**u.exp]
elif u.base == x and FreeQ(u.exp, x):
return [u.exp, S(1)]
return [S(0), u]
elif ProductQ(u):
lst1 = MonomialFactor(First(u), x)
lst2 = MonomialFactor(Rest(u), x)
return [lst1[0] + lst2[0], lst1[1]*lst2[1]]
elif SumQ(u):
lst = [MonomialFactor(i, x) for i in u.args]
deg = lst[0][0]
for i in Rest(lst):
deg = MinimumDegree(deg, i[0])
if ZeroQ(deg) or RationalQ(deg) and deg < 0:
return [S(0), u]
return [deg, Add(*[x**(i[0] - deg)*i[1] for i in lst])]
return [S(0), u]
def FullSimplify(expr):
return Simplify(expr)
def FunctionOfLinearSubst(u, a, b, x):
if FreeQ(u, x):
return u
elif LinearQ(u, x):
tmp = Coefficient(u, x, 1)
if tmp == b:
tmp = S(1)
else:
tmp = tmp/b
return Coefficient(u, x, S(0)) - a*tmp + tmp*x
elif PowerQ(u):
if FreeQ(u.base, x):
return E**(FullSimplify(FunctionOfLinearSubst(Log(u.base)*u.exp, a, b, x)))
lst = MonomialFactor(u, x)
if ProductQ(u) and NonzeroQ(lst[0]):
if RationalQ(LeadFactor(lst[1])) and LeadFactor(lst[1]) < 0:
return -FunctionOfLinearSubst(DivideDegreesOfFactors(-lst[1], lst[0])*x, a, b, x)**lst[0]
return FunctionOfLinearSubst(DivideDegreesOfFactors(lst[1], lst[0])*x, a, b, x)**lst[0]
return u.func(*[FunctionOfLinearSubst(i, a, b, x) for i in u.args])
def FunctionOfLinear(*args):
# (* If u (x) is equivalent to an expression of the form f (a+b*x) and not the case that a==0 and
# b==1, FunctionOfLinear[u,x] returns the list {f (x),a,b}; else it returns False. *)
if len(args) == 2:
u, x = args
lst = FunctionOfLinear(u, False, False, x, False)
if AtomQ(lst) or FalseQ(lst[0]) or (lst[0] == 0 and lst[1] == 1):
return False
return [FunctionOfLinearSubst(u, lst[0], lst[1], x), lst[0], lst[1]]
u, a, b, x, flag = args
if FreeQ(u, x):
return [a, b]
elif CalculusQ(u):
return False
elif LinearQ(u, x):
if FalseQ(a):
return [Coefficient(u, x, 0), Coefficient(u, x, 1)]
lst = CommonFactors([b, Coefficient(u, x, 1)])
if ZeroQ(Coefficient(u, x, 0)) and Not(flag):
return [0, lst[0]]
elif ZeroQ(b*Coefficient(u, x, 0) - a*Coefficient(u, x, 1)):
return [a/lst[1], lst[0]]
return [0, 1]
elif PowerQ(u):
if FreeQ(u.base, x):
return FunctionOfLinear(Log(u.base)*u.exp, a, b, x, False)
lst = MonomialFactor(u, x)
if ProductQ(u) and NonzeroQ(lst[0]):
if False and IntegerQ(lst[0]) and lst[0] != -1 and FreeQ(lst[1], x):
if RationalQ(LeadFactor(lst[1])) and LeadFactor(lst[1]) < 0:
return FunctionOfLinear(DivideDegreesOfFactors(-lst[1], lst[0])*x, a, b, x, False)
return FunctionOfLinear(DivideDegreesOfFactors(lst[1], lst[0])*x, a, b, x, False)
return False
lst = [a, b]
for i in u.args:
lst = FunctionOfLinear(i, lst[0], lst[1], x, SumQ(u))
if AtomQ(lst):
return False
return lst
def NormalizeIntegrand(u, x):
v = NormalizeLeadTermSigns(NormalizeIntegrandAux(u, x))
if v == NormalizeLeadTermSigns(u):
return u
else:
return v
def NormalizeIntegrandAux(u, x):
if SumQ(u):
l = 0
for i in u.args:
l += NormalizeIntegrandAux(i, x)
return l
if ProductQ(MergeMonomials(u, x)):
l = 1
for i in MergeMonomials(u, x).args:
l *= NormalizeIntegrandFactor(i, x)
return l
else:
return NormalizeIntegrandFactor(MergeMonomials(u, x), x)
def NormalizeIntegrandFactor(u, x):
if PowerQ(u):
if FreeQ(u.exp, x):
bas = NormalizeIntegrandFactorBase(u.base, x)
deg = u.exp
if IntegerQ(deg) and SumQ(bas):
if all(MonomialQ(i, x) for i in bas.args):
mi = MinimumMonomialExponent(bas, x)
q = 0
for i in bas.args:
q += Simplify(i/x**mi)
return x**(mi*deg)*q**deg
else:
return bas**deg
else:
return bas**deg
if PowerQ(u):
if FreeQ(u.base, x):
return u.base**NormalizeIntegrandFactorBase(u.exp, x)
bas = NormalizeIntegrandFactorBase(u, x)
if SumQ(bas):
if all(MonomialQ(i, x) for i in bas.args):
mi = MinimumMonomialExponent(bas, x)
z = 0
for j in bas.args:
z += j/x**mi
return x**mi*z
else:
return bas
else:
return bas
def NormalizeIntegrandFactorBase(expr, x):
m = Wild('m', exclude=[x])
u = Wild('u')
match = expr.match(x**m*u)
if match and SumQ(u):
l = 0
for i in u.args:
l += NormalizeIntegrandFactorBase((x**m*i), x)
return l
if BinomialQ(expr, x):
if BinomialMatchQ(expr, x):
return expr
else:
return ExpandToSum(expr, x)
elif TrinomialQ(expr, x):
if TrinomialMatchQ(expr, x):
return expr
else:
return ExpandToSum(expr, x)
elif ProductQ(expr):
l = 1
for i in expr.args:
l *= NormalizeIntegrandFactor(i, x)
return l
elif PolynomialQ(expr, x) and Exponent(expr, x)<=4:
return ExpandToSum(expr, x)
elif SumQ(expr):
w = Wild('w')
m = Wild('m', exclude=[x])
v = TogetherSimplify(expr)
if SumQ(v) or v.match(x**m*w) and SumQ(w) or LeafCount(v)>LeafCount(expr)+2:
return UnifySum(expr, x)
else:
return NormalizeIntegrandFactorBase(v, x)
else:
return expr
def NormalizeTogether(u):
return NormalizeLeadTermSigns(Together(u))
def NormalizeLeadTermSigns(u):
if ProductQ(u):
t = 1
for i in u.args:
lst = SignOfFactor(i)
if lst[0] == 1:
t *= lst[1]
else:
t *= AbsorbMinusSign(lst[1])
return t
else:
lst = SignOfFactor(u)
if lst[0] == 1:
return lst[1]
else:
return AbsorbMinusSign(lst[1])
def AbsorbMinusSign(expr, *x):
m = Wild('m', exclude=[x])
u = Wild('u')
v = Wild('v')
match = expr.match(u*v**m)
if match:
if len(match) == 3:
if SumQ(match[v]) and OddQ(match[m]):
return match[u]*(-match[v])**match[m]
return -expr
def NormalizeSumFactors(u):
if AtomQ(u):
return u
elif ProductQ(u):
k = 1
for i in u.args:
k *= NormalizeSumFactors(i)
return SignOfFactor(k)[0]*SignOfFactor(k)[1]
elif SumQ(u):
k = 0
for i in u.args:
k += NormalizeSumFactors(i)
return k
else:
return u
def SignOfFactor(u):
if RationalQ(u) and u < 0 or SumQ(u) and NumericFactor(First(u)) < 0:
return [-1, -u]
elif IntegerPowerQ(u):
if SumQ(u.base) and NumericFactor(First(u.base)) < 0:
return [(-1)**u.exp, (-u.base)**u.exp]
elif ProductQ(u):
k = 1
h = 1
for i in u.args:
k *= SignOfFactor(i)[0]
h *= SignOfFactor(i)[1]
return [k, h]
return [1, u]
def NormalizePowerOfLinear(u, x):
v = FactorSquareFree(u)
if PowerQ(v):
if LinearQ(v.base, x) and FreeQ(v.exp, x):
return ExpandToSum(v.base, x)**v.exp
return ExpandToSum(v, x)
def SimplifyIntegrand(u, x):
v = NormalizeLeadTermSigns(NormalizeIntegrandAux(Simplify(u), x))
if 5*LeafCount(v) < 4*LeafCount(u):
return v
if v != NormalizeLeadTermSigns(u):
return v
else:
return u
def SimplifyTerm(u, x):
v = Simplify(u)
w = Together(v)
if LeafCount(v) < LeafCount(w):
return NormalizeIntegrand(v, x)
else:
return NormalizeIntegrand(w, x)
def TogetherSimplify(u):
v = Together(Simplify(Together(u)))
return FixSimplify(v)
def SmartSimplify(u):
v = Simplify(u)
w = factor(v)
if LeafCount(w) < LeafCount(v):
v = w
if Not(FalseQ(w == FractionalPowerOfSquareQ(v))) and FractionalPowerSubexpressionQ(u, w, Expand(w)):
v = SubstForExpn(v, w, Expand(w))
else:
v = FactorNumericGcd(v)
return FixSimplify(v)
def SubstForExpn(u, v, w):
if u == v:
return w
if AtomQ(u):
return u
else:
k = 0
for i in u.args:
k += SubstForExpn(i, v, w)
return k
def ExpandToSum(u, *x):
if len(x) == 1:
x = x[0]
expr = 0
if PolyQ(S(u), x):
for t in Exponent(u, x, List):
expr += Coeff(u, x, t)*x**t
return expr
if BinomialQ(u, x):
i = BinomialParts(u, x)
expr += i[0] + i[1]*x**i[2]
return expr
if TrinomialQ(u, x):
i = TrinomialParts(u, x)
expr += i[0] + i[1]*x**i[3] + i[2]*x**(2*i[3])
return expr
if GeneralizedBinomialMatchQ(u, x):
i = GeneralizedBinomialParts(u, x)
expr += i[0]*x**i[3] + i[1]*x**i[2]
return expr
if GeneralizedTrinomialMatchQ(u, x):
i = GeneralizedTrinomialParts(u, x)
expr += i[0]*x**i[4] + i[1]*x**i[3] + i[2]*x**(2*i[3]-i[4])
return expr
else:
return Expand(u)
else:
v = x[0]
x = x[1]
w = ExpandToSum(v, x)
r = NonfreeTerms(w, x)
if SumQ(r):
k = u*FreeTerms(w, x)
for i in r.args:
k += MergeMonomials(u*i, x)
return k
else:
return u*FreeTerms(w, x) + MergeMonomials(u*r, x)
def UnifySum(u, x):
if SumQ(u):
t = 0
lst = []
for i in u.args:
lst += [i]
for j in UnifyTerms(lst, x):
t += j
return t
else:
return SimplifyTerm(u, x)
def UnifyTerms(lst, x):
if lst==[]:
return lst
else:
return UnifyTerm(First(lst), UnifyTerms(Rest(lst), x), x)
def UnifyTerm(term, lst, x):
if lst==[]:
return [term]
tmp = Simplify(First(lst)/term)
if FreeQ(tmp, x):
return Prepend(Rest(lst), [(1+tmp)*term])
else:
return Prepend(UnifyTerm(term, Rest(lst), x), [First(lst)])
def CalculusQ(u):
return False
def FunctionOfInverseLinear(*args):
# (* If u is a function of an inverse linear binomial of the form 1/(a+b*x),
# FunctionOfInverseLinear[u,x] returns the list {a,b}; else it returns False. *)
if len(args) == 2:
u, x = args
return FunctionOfInverseLinear(u, None, x)
u, lst, x = args
if FreeQ(u, x):
return lst
elif u == x:
return False
elif QuotientOfLinearsQ(u, x):
tmp = Drop(QuotientOfLinearsParts(u, x), 2)
if tmp[1] == 0:
return False
elif lst is None:
return tmp
elif ZeroQ(lst[0]*tmp[1] - lst[1]*tmp[0]):
return lst
return False
elif CalculusQ(u):
return False
tmp = lst
for i in u.args:
tmp = FunctionOfInverseLinear(i, tmp, x)
if AtomQ(tmp):
return False
return tmp
def PureFunctionOfSinhQ(u, v, x):
# (* If u is a pure function of Sinh[v] and/or Csch[v], PureFunctionOfSinhQ[u,v,x] returns True;
# else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return SinhQ(u) or CschQ(u)
for i in u.args:
if Not(PureFunctionOfSinhQ(i, v, x)):
return False
return True
def PureFunctionOfTanhQ(u, v , x):
# (* If u is a pure function of Tanh[v] and/or Coth[v], PureFunctionOfTanhQ[u,v,x] returns True;
# else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return TanhQ(u) or CothQ(u)
for i in u.args:
if Not(PureFunctionOfTanhQ(i, v, x)):
return False
return True
def PureFunctionOfCoshQ(u, v, x):
# (* If u is a pure function of Cosh[v] and/or Sech[v], PureFunctionOfCoshQ[u,v,x] returns True;
# else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return CoshQ(u) or SechQ(u)
for i in u.args:
if Not(PureFunctionOfCoshQ(i, v, x)):
return False
return True
def IntegerQuotientQ(u, v):
# (* If u/v is an integer, IntegerQuotientQ[u,v] returns True; else it returns False. *)
return IntegerQ(Simplify(u/v))
def OddQuotientQ(u, v):
# (* If u/v is odd, OddQuotientQ[u,v] returns True; else it returns False. *)
return OddQ(Simplify(u/v))
def EvenQuotientQ(u, v):
# (* If u/v is even, EvenQuotientQ[u,v] returns True; else it returns False. *)
return EvenQ(Simplify(u/v))
def FindTrigFactor(func1, func2, u, v, flag):
# (* If func[w]^m is a factor of u where m is odd and w is an integer multiple of v,
# FindTrigFactor[func1,func2,u,v,True] returns the list {w,u/func[w]^n}; else it returns False. *)
# (* If func[w]^m is a factor of u where m is odd and w is an integer multiple of v not equal to v,
# FindTrigFactor[func1,func2,u,v,False] returns the list {w,u/func[w]^n}; else it returns False. *)
if u == 1:
return False
elif (Head(LeadBase(u)) == func1 or Head(LeadBase(u)) == func2) and OddQ(LeadDegree(u)) and IntegerQuotientQ(LeadBase(u).args[0], v) and (flag or NonzeroQ(LeadBase(u).args[0] - v)):
return [LeadBase[u].args[0], RemainingFactors(u)]
lst = FindTrigFactor(func1, func2, RemainingFactors(u), v, flag)
if AtomQ(lst):
return False
return [lst[0], LeadFactor(u)*lst[1]]
def FunctionOfSinhQ(u, v, x):
# (* If u is a function of Sinh[v], FunctionOfSinhQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
if OddQuotientQ(u.args[0], v):
# (* Basis: If m odd, Sinh[m*v]^n is a function of Sinh[v]. *)
return SinhQ(u) or CschQ(u)
# (* Basis: If m even, Cos[m*v]^n is a function of Sinh[v]. *)
return CoshQ(u) or SechQ(u)
elif IntegerPowerQ(u):
if HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# (* Basis: If m integer and n even, Hyper[m*v]^n is a function of Sinh[v]. *)
return True
return FunctionOfSinhQ(u.base, v, x)
elif ProductQ(u):
if CoshQ(u.args[0]) and SinhQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return FunctionOfSinhQ(Drop(u, 2), v, x)
lst = FindTrigFactor(Sinh, Csch, u, v, False)
if ListQ(lst) and EvenQuotientQ(lst[0], v):
# (* Basis: If m even and n odd, Sinh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *)
return FunctionOfSinhQ(Cosh(v)*lst[1], v, x)
lst = FindTrigFactor(Cosh, Sech, u, v, False)
if ListQ(lst) and OddQuotientQ(lst[0], v):
# (* Basis: If m odd and n odd, Cosh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *)
return FunctionOfSinhQ(Cosh(v)*lst[1], v, x)
lst = FindTrigFactor(Tanh, Coth, u, v, True)
if ListQ(lst):
# (* Basis: If m integer and n odd, Tanh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *)
return FunctionOfSinhQ(Cosh(v)*lst[1], v, x)
return all(FunctionOfSinhQ(i, v, x) for i in u.args)
return all(FunctionOfSinhQ(i, v, x) for i in u.args)
def FunctionOfCoshQ(u, v, x):
#(* If u is a function of Cosh[v], FunctionOfCoshQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
# (* Basis: If m integer, Cosh[m*v]^n is a function of Cosh[v]. *)
return CoshQ(u) or SechQ(u)
elif IntegerPowerQ(u):
if HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# (* Basis: If m integer and n even, Hyper[m*v]^n is a function of Cosh[v]. *)
return True
return FunctionOfCoshQ(u.base, v, x)
elif ProductQ(u):
lst = FindTrigFactor(Sinh, Csch, u, v, False)
if ListQ(lst):
# (* Basis: If m integer and n odd, Sinh[m*v]^n == Sinh[v]*u where u is a function of Cosh[v]. *)
return FunctionOfCoshQ(Sinh(v)*lst[1], v, x)
lst = FindTrigFactor(Tanh, Coth, u, v, True)
if ListQ(lst):
# (* Basis: If m integer and n odd, Tanh[m*v]^n == Sinh[v]*u where u is a function of Cosh[v]. *)
return FunctionOfCoshQ(Sinh(v)*lst[1], v, x)
return all(FunctionOfCoshQ(i, v, x) for i in u.args)
return all(FunctionOfCoshQ(i, v, x) for i in u.args)
def OddHyperbolicPowerQ(u, v, x):
if SinhQ(u) or CoshQ(u) or SechQ(u) or CschQ(u):
return OddQuotientQ(u.args[0], v)
if PowerQ(u):
return OddQ(u.exp) and OddHyperbolicPowerQ(u.base, v, x)
if ProductQ(u):
if Not(EqQ(FreeFactors(u, x), 1)):
return OddHyperbolicPowerQ(NonfreeFactors(u, x), v, x)
lst = []
for i in u.args:
if Not(FunctionOfTanhQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==1 and OddHyperbolicPowerQ(lst[0], v, x)
if SumQ(u):
return all(OddHyperbolicPowerQ(i, v, x) for i in u.args)
return False
def FunctionOfTanhQ(u, v, x):
#(* If u is a function of the form f[Tanh[v],Coth[v]] where f is independent of x,
# FunctionOfTanhQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
return TanhQ(u) or CothQ(u) or EvenQuotientQ(u.args[0], v)
elif PowerQ(u):
if EvenQ(u.exp) and HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
return True
elif EvenQ(u.args[1]) and SumQ(u.args[0]):
return FunctionOfTanhQ(Expand(u.args[0]**2, v, x))
if ProductQ(u):
lst = []
for i in u.args:
if Not(FunctionOfTanhQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==2 and OddHyperbolicPowerQ(lst[0], v, x) and OddHyperbolicPowerQ(lst[1], v, x)
return all(FunctionOfTanhQ(i, v, x) for i in u.args)
def FunctionOfTanhWeight(u, v, x):
"""
u is a function of the form f(tanh(v), coth(v)) where f is independent of x.
FunctionOfTanhWeight(u, v, x) returns a nonnegative number if u is best considered a function of tanh(v), else it returns a negative number.
Examples
========
>>> from sympy import sinh, log, tanh
>>> from sympy.abc import x
>>> from sympy.integrals.rubi.utility_function import FunctionOfTanhWeight
>>> FunctionOfTanhWeight(x, log(x), x)
0
>>> FunctionOfTanhWeight(sinh(log(x)), log(x), x)
0
>>> FunctionOfTanhWeight(tanh(log(x)), log(x), x)
1
"""
if AtomQ(u):
return S(0)
elif CalculusQ(u):
return S(0)
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
if TanhQ(u) and ZeroQ(u.args[0] - v):
return S(1)
elif CothQ(u) and ZeroQ(u.args[0] - v):
return S(-1)
return S(0)
elif PowerQ(u):
if EvenQ(u.exp) and HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if TanhQ(u.base) or CoshQ(u.base) or SechQ(u.base):
return S(1)
return S(-1)
if ProductQ(u):
if all(FunctionOfTanhQ(i, v, x) for i in u.args):
return Add(*[FunctionOfTanhWeight(i, v, x) for i in u.args])
return S(0)
return Add(*[FunctionOfTanhWeight(i, v, x) for i in u.args])
def FunctionOfHyperbolicQ(u, v, x):
# (* If u (x) is equivalent to a function of the form f (Sinh[v],Cosh[v],Tanh[v],Coth[v],Sech[v],Csch[v])
# where f is independent of x, FunctionOfHyperbolicQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
return True
return all(FunctionOfHyperbolicQ(i, v, x) for i in u.args)
def SmartNumerator(expr):
if PowerQ(expr):
n = expr.exp
u = expr.base
if RationalQ(n) and n < 0:
return SmartDenominator(u**(-n))
elif ProductQ(expr):
return Mul(*[SmartNumerator(i) for i in expr.args])
return Numerator(expr)
def SmartDenominator(expr):
if PowerQ(expr):
u = expr.base
n = expr.exp
if RationalQ(n) and n < 0:
return SmartNumerator(u**(-n))
elif ProductQ(expr):
return Mul(*[SmartDenominator(i) for i in expr.args])
return Denominator(expr)
def ActivateTrig(u):
return u
def ExpandTrig(*args):
if len(args) == 2:
u, x = args
return ActivateTrig(ExpandIntegrand(u, x))
u, v, x = args
w = ExpandTrig(v, x)
z = ActivateTrig(u)
if SumQ(w):
return w.func(*[z*i for i in w.args])
return z*w
def TrigExpand(u):
return expand_trig(u)
# SubstForTrig[u_,sin_,cos_,v_,x_] :=
# If[AtomQ[u],
# u,
# If[TrigQ[u] && IntegerQuotientQ[u[[1]],v],
# If[u[[1]]===v || ZeroQ[u[[1]]-v],
# If[SinQ[u],
# sin,
# If[CosQ[u],
# cos,
# If[TanQ[u],
# sin/cos,
# If[CotQ[u],
# cos/sin,
# If[SecQ[u],
# 1/cos,
# 1/sin]]]]],
# Map[Function[SubstForTrig[#,sin,cos,v,x]],
# ReplaceAll[TrigExpand[Head[u][Simplify[u[[1]]/v]*x]],x->v]]],
# If[ProductQ[u] && CosQ[u[[1]]] && SinQ[u[[2]]] && ZeroQ[u[[1,1]]-v/2] && ZeroQ[u[[2,1]]-v/2],
# sin/2*SubstForTrig[Drop[u,2],sin,cos,v,x],
# Map[Function[SubstForTrig[#,sin,cos,v,x]],u]]]]
def SubstForTrig(u, sin_ , cos_, v, x):
# (* u (v) is an expression of the form f (Sin[v],Cos[v],Tan[v],Cot[v],Sec[v],Csc[v]). *)
# (* SubstForTrig[u,sin,cos,v,x] returns the expression f (sin,cos,sin/cos,cos/sin,1/cos,1/sin). *)
if AtomQ(u):
return u
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
if u.args[0] == v or ZeroQ(u.args[0] - v):
if SinQ(u):
return sin_
elif CosQ(u):
return cos_
elif TanQ(u):
return sin_/cos_
elif CotQ(u):
return cos_/sin_
elif SecQ(u):
return 1/cos_
return 1/sin_
r = ReplaceAll(TrigExpand(Head(u)(Simplify(u.args[0]/v*x))), {x: v})
return r.func(*[SubstForTrig(i, sin_, cos_, v, x) for i in r.args])
if ProductQ(u) and CosQ(u.args[0]) and SinQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return sin(x)/2*SubstForTrig(Drop(u, 2), sin_, cos_, v, x)
return u.func(*[SubstForTrig(i, sin_, cos_, v, x) for i in u.args])
def SubstForHyperbolic(u, sinh_, cosh_, v, x):
# (* u (v) is an expression of the form f (Sinh[v],Cosh[v],Tanh[v],Coth[v],Sech[v],Csch[v]). *)
# (* SubstForHyperbolic[u,sinh,cosh,v,x] returns the expression
# f (sinh,cosh,sinh/cosh,cosh/sinh,1/cosh,1/sinh). *)
if AtomQ(u):
return u
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
if u.args[0] == v or ZeroQ(u.args[0] - v):
if SinhQ(u):
return sinh_
elif CoshQ(u):
return cosh_
elif TanhQ(u):
return sinh_/cosh_
elif CothQ(u):
return cosh_/sinh_
if SechQ(u):
return 1/cosh_
return 1/sinh_
r = ReplaceAll(TrigExpand(Head(u)(Simplify(u.args[0]/v)*x)), {x: v})
return r.func(*[SubstForHyperbolic(i, sinh_, cosh_, v, x) for i in r.args])
elif ProductQ(u) and CoshQ(u.args[0]) and SinhQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return sinh(x)/2*SubstForHyperbolic(Drop(u, 2), sinh_, cosh_, v, x)
return u.func(*[SubstForHyperbolic(i, sinh_, cosh_, v, x) for i in u.args])
def InertTrigFreeQ(u):
return FreeQ(u, sin) and FreeQ(u, cos) and FreeQ(u, tan) and FreeQ(u, cot) and FreeQ(u, sec) and FreeQ(u, csc)
def LCM(a, b):
return lcm(a, b)
def SubstForFractionalPowerOfLinear(u, x):
# (* If u has a subexpression of the form (a+b*x)^(m/n) where m and n>1 are integers,
# SubstForFractionalPowerOfLinear[u,x] returns the list {v,n,a+b*x,1/b} where v is u
# with subexpressions of the form (a+b*x)^(m/n) replaced by x^m and x replaced
# by -a/b+x^n/b, and all times x^(n-1); else it returns False. *)
lst = FractionalPowerOfLinear(u, S(1), False, x)
if AtomQ(lst) or FalseQ(lst[1]):
return False
n = lst[0]
a = Coefficient(lst[1], x, 0)
b = Coefficient(lst[1], x, 1)
tmp = Simplify(x**(n-1)*SubstForFractionalPower(u, lst[1], n, -a/b + x**n/b, x))
return [NonfreeFactors(tmp, x), n, lst[1], FreeFactors(tmp, x)/b]
def FractionalPowerOfLinear(u, n, v, x):
# If u has a subexpression of the form (a + b*x)**(m/n), FractionalPowerOfLinear(u, 1, False, x) returns [n, a + b*x], else it returns False.
if AtomQ(u) or FreeQ(u, x):
return [n, v]
elif CalculusQ(u):
return False
elif FractionalPowerQ(u):
if LinearQ(u.base, x) and (FalseQ(v) or ZeroQ(u.base - v)):
return [LCM(Denominator(u.exp), n), u.base]
lst = [n, v]
for i in u.args:
lst = FractionalPowerOfLinear(i, lst[0], lst[1], x)
if AtomQ(lst):
return False
return lst
def InverseFunctionOfLinear(u, x):
# (* If u has a subexpression of the form g[a+b*x] where g is an inverse function,
# InverseFunctionOfLinear[u,x] returns g[a+b*x]; else it returns False. *)
if AtomQ(u) or CalculusQ(u) or FreeQ(u, x):
return False
elif InverseFunctionQ(u) and LinearQ(u.args[0], x):
return u
for i in u.args:
tmp = InverseFunctionOfLinear(i, x)
if Not(AtomQ(tmp)):
return tmp
return False
def InertTrigQ(*args):
if len(args) == 1:
f = args[0]
l = [sin,cos,tan,cot,sec,csc]
return any(Head(f) == i for i in l)
elif len(args) == 2:
f, g = args
if f == g:
return InertTrigQ(f)
return InertReciprocalQ(f, g) or InertReciprocalQ(g, f)
else:
f, g, h = args
return InertTrigQ(g, f) and InertTrigQ(g, h)
def InertReciprocalQ(f, g):
return (f.func == sin and g.func == csc) or (f.func == cos and g.func == sec) or (f.func == tan and g.func == cot)
def DeactivateTrig(u, x):
# (* u is a function of trig functions of a linear function of x. *)
# (* DeactivateTrig[u,x] returns u with the trig functions replaced with inert trig functions. *)
return FixInertTrigFunction(DeactivateTrigAux(u, x), x)
def FixInertTrigFunction(u, x):
return u
def DeactivateTrigAux(u, x):
if AtomQ(u):
return u
elif TrigQ(u) and LinearQ(u.args[0], x):
v = ExpandToSum(u.args[0], x)
if SinQ(u):
return sin(v)
elif CosQ(u):
return cos(v)
elif TanQ(u):
return tan(u)
elif CotQ(u):
return cot(v)
elif SecQ(u):
return sec(v)
return csc(v)
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
v = ExpandToSum(I*u.args[0], x)
if SinhQ(u):
return -I*sin(v)
elif CoshQ(u):
return cos(v)
elif TanhQ(u):
return -I*tan(v)
elif CothQ(u):
I*cot(v)
elif SechQ(u):
return sec(v)
return I*csc(v)
return u.func(*[DeactivateTrigAux(i, x) for i in u.args])
def PowerOfInertTrigSumQ(u, func, x):
p_ = Wild('p', exclude=[x])
q_ = Wild('q', exclude=[x])
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x])
n_ = Wild('n', exclude=[x])
w_ = Wild('w')
pattern = (a_ + b_*(c_*func(w_))**p_)**n_
match = u.match(pattern)
if match:
keys = [a_, b_, c_, n_, p_, w_]
if len(keys) == len(match):
return True
pattern = (a_ + b_*(d_*func(w_))**p_ + c_*(d_*func(w_))**q_)**n_
match = u.match(pattern)
if match:
keys = [a_, b_, c_, d_, n_, p_, q_, w_]
if len(keys) == len(match):
return True
return False
def PiecewiseLinearQ(*args):
# (* If the derivative of u wrt x is a constant wrt x, PiecewiseLinearQ[u,x] returns True;
# else it returns False. *)
if len(args) == 3:
u, v, x = args
return PiecewiseLinearQ(u, x) and PiecewiseLinearQ(v, x)
u, x = args
if LinearQ(u, x):
return True
c_ = Wild('c', exclude=[x])
F_ = Wild('F', exclude=[x])
v_ = Wild('v')
match = u.match(Log(c_*F_**v_))
if match:
if len(match) == 3:
if LinearQ(match[v_], x):
return True
try:
F = type(u)
G = type(u.args[0])
v = u.args[0].args[0]
if LinearQ(v, x):
if MemberQ([[atanh, tanh], [atanh, coth], [acoth, coth], [acoth, tanh], [atan, tan], [atan, cot], [acot, cot], [acot, tan]], [F, G]):
return True
except:
pass
return False
def KnownTrigIntegrandQ(lst, u, x):
if u == 1:
return True
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
func_ = WildFunction('func')
m_ = Wild('m', exclude=[x])
A_ = Wild('A', exclude=[x])
B_ = Wild('B', exclude=[x, 0])
C_ = Wild('C', exclude=[x, 0])
match = u.match((a_ + b_*func_)**m_)
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match((a_ + b_*func_)**m_*(A_ + B_*func_))
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match(A_ + C_*func_**2)
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match(A_ + B_*func_ + C_*func_**2)
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match((a_ + b_*func_)**m_*(A_ + C_*func_**2))
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match((a_ + b_*func_)**m_*(A_ + B_*func_ + C_*func_**2))
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
return False
def KnownSineIntegrandQ(u, x):
return KnownTrigIntegrandQ([sin, cos], u, x)
def KnownTangentIntegrandQ(u, x):
return KnownTrigIntegrandQ([tan], u, x)
def KnownCotangentIntegrandQ(u, x):
return KnownTrigIntegrandQ([cot], u, x)
def KnownSecantIntegrandQ(u, x):
return KnownTrigIntegrandQ([sec, csc], u, x)
def TryPureTanSubst(u, x):
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x])
c_ = Wild('c', exclude=[x])
G_ = Wild('G')
F = u.func
try:
if MemberQ([atan, acot, atanh, acoth], F):
match = u.args[0].match(c_*(a_ + b_*G_))
if match:
if len(match) == 4:
G = match[G_]
if MemberQ([tan, cot, tanh, coth], G.func):
if LinearQ(G.args[0], x):
return True
except:
pass
return False
def TryTanhSubst(u, x):
if LogQ(u):
return False
elif not FalseQ(FunctionOfLinear(u, x)):
return False
a_ = Wild('a', exclude=[x])
m_ = Wild('m', exclude=[x])
p_ = Wild('p', exclude=[x])
r_, s_, t_, n_, b_, f_, g_ = map(Wild, 'rstnbfg')
match = u.match(r_*(s_ + t_)**n_)
if match:
if len(match) == 4:
r, s, t, n = [match[i] for i in [r_, s_, t_, n_]]
if IntegerQ(n) and PositiveQ(n):
return False
match = u.match(1/(a_ + b_*f_**n_))
if match:
if len(match) == 4:
a, b, f, n = [match[i] for i in [a_, b_, f_, n_]]
if SinhCoshQ(f) and IntegerQ(n) and n > 2:
return False
match = u.match(f_*g_)
if match:
if len(match) == 2:
f, g = match[f_], match[g_]
if SinhCoshQ(f) and SinhCoshQ(g):
if IntegersQ(f.args[0]/x, g.args[0]/x):
return False
match = u.match(r_*(a_*s_**m_)**p_)
if match:
if len(match) == 5:
r, a, s, m, p = [match[i] for i in [r_, a_, s_, m_, p_]]
if Not(m==2 and (s == Sech(x) or s == Csch(x))):
return False
if u != ExpandIntegrand(u, x):
return False
return True
def TryPureTanhSubst(u, x):
F = u.func
a_ = Wild('a', exclude=[x])
G_ = Wild('G')
if F == sym_log:
return False
match = u.args[0].match(a_*G_)
if match and len(match) == 2:
G = match[G_].func
if MemberQ([atanh, acoth], F) and MemberQ([tanh, coth], G):
return False
if u != ExpandIntegrand(u, x):
return False
return True
def AbsurdNumberGCD(*seq):
# (* m, n, ... must be absurd numbers. AbsurdNumberGCD[m,n,...] returns the gcd of m, n, ... *)
lst = list(seq)
if Length(lst) == 1:
return First(lst)
return AbsurdNumberGCDList(FactorAbsurdNumber(First(lst)), FactorAbsurdNumber(AbsurdNumberGCD(*Rest(lst))))
def AbsurdNumberGCDList(lst1, lst2):
# (* lst1 and lst2 must be absurd number prime factorization lists. *)
# (* AbsurdNumberGCDList[lst1,lst2] returns the gcd of the absurd numbers represented by lst1 and lst2. *)
if lst1 == []:
return Mul(*[i[0]**Min(i[1],0) for i in lst2])
elif lst2 == []:
return Mul(*[i[0]**Min(i[1],0) for i in lst1])
elif lst1[0][0] == lst2[0][0]:
if lst1[0][1] <= lst2[0][1]:
return lst1[0][0]**lst1[0][1]*AbsurdNumberGCDList(Rest(lst1), Rest(lst2))
return lst1[0][0]**lst2[0][1]*AbsurdNumberGCDList(Rest(lst1), Rest(lst2))
elif lst1[0][0] < lst2[0][0]:
if lst1[0][1] < 0:
return lst1[0][0]**lst1[0][1]*AbsurdNumberGCDList(Rest(lst1), lst2)
return AbsurdNumberGCDList(Rest(lst1), lst2)
elif lst2[0][1] < 0:
return lst2[0][0]**lst2[0][1]*AbsurdNumberGCDList(lst1, Rest(lst2))
return AbsurdNumberGCDList(lst1, Rest(lst2))
def ExpandTrigExpand(u, F, v, m, n, x):
w = Expand(TrigExpand(F.xreplace({x: n*x}))**m).xreplace({x: v})
if SumQ(w):
t = 0
for i in w.args:
t += u*i
return t
else:
return u*w
def ExpandTrigReduce(*args):
if len(args) == 3:
u = args[0]
v = args[1]
x = args[2]
w = ExpandTrigReduce(v, x)
if SumQ(w):
t = 0
for i in w.args:
t += u*i
return t
else:
return u*w
else:
u = args[0]
x = args[1]
return ExpandTrigReduceAux(u, x)
def ExpandTrigReduceAux(u, x):
v = TrigReduce(u).expand()
if SumQ(v):
t = 0
for i in v.args:
t += NormalizeTrig(i, x)
return t
return NormalizeTrig(v, x)
def NormalizeTrig(v, x):
a = Wild('a', exclude=[x])
n = Wild('n', exclude=[x, 0])
F = Wild('F')
expr = a*F**n
M = v.match(expr)
if M and len(M[F].args) == 1 and PolynomialQ(M[F].args[0], x) and Exponent(M[F].args[0], x)>0:
u = M[F].args[0]
return M[a]*M[F].xreplace({u: ExpandToSum(u, x)})**M[n]
else:
return v
#=================================
def TrigToExp(expr):
ex = expr.rewrite(sin, sym_exp).rewrite(cos, sym_exp).rewrite(tan, sym_exp).rewrite(sec, sym_exp).rewrite(csc, sym_exp).rewrite(cot, sym_exp)
return ex.replace(sym_exp, rubi_exp)
def ExpandTrigToExp(u, *args):
if len(args) == 1:
x = args[0]
return ExpandTrigToExp(1, u, x)
else:
v = args[0]
x = args[1]
w = TrigToExp(v)
k = 0
if SumQ(w):
for i in w.args:
k += SimplifyIntegrand(u*i, x)
w = k
else:
w = SimplifyIntegrand(u*w, x)
return ExpandIntegrand(FreeFactors(w, x), NonfreeFactors(w, x),x)
#======================================
def TrigReduce(i):
"""
TrigReduce(expr) rewrites products and powers of trigonometric functions in expr in terms of trigonometric functions with combined arguments.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.integrals.rubi.utility_function import TrigReduce
>>> from sympy.abc import x
>>> TrigReduce(cos(x)**2)
cos(2*x)/2 + 1/2
>>> TrigReduce(cos(x)**2*sin(x))
sin(x)/4 + sin(3*x)/4
>>> TrigReduce(cos(x)**2+sin(x))
sin(x) + cos(2*x)/2 + 1/2
"""
if SumQ(i):
t = 0
for k in i.args:
t += TrigReduce(k)
return t
if ProductQ(i):
if any(PowerQ(k) for k in i.args):
if (i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin)).has(I, cosh, sinh):
return i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin).simplify()
else:
return i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin)
else:
a = Wild('a')
b = Wild('b')
v = Wild('v')
Match = i.match(v*sin(a)*cos(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sin(a)*cos(b), v*S(1)/2*(sin(a + b) + sin(a - b)))
Match = i.match(v*sin(a)*sin(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sin(a)*sin(b), v*S(1)/2*cos(a - b) - cos(a + b))
Match = i.match(v*cos(a)*cos(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*cos(a)*cos(b), v*S(1)/2*cos(a + b) + cos(a - b))
Match = i.match(v*sinh(a)*cosh(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sinh(a)*cosh(b), v*S(1)/2*(sinh(a + b) + sinh(a - b)))
Match = i.match(v*sinh(a)*sinh(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sinh(a)*sinh(b), v*S(1)/2*cosh(a - b) - cosh(a + b))
Match = i.match(v*cosh(a)*cosh(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*cosh(a)*cosh(b), v*S(1)/2*cosh(a + b) + cosh(a - b))
if PowerQ(i):
if i.has(sin, sinh):
if (i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin)).has(I, cosh, sinh):
return i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin).simplify()
else:
return i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin)
if i.has(cos, cosh):
if (i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos)).has(I, cosh, sinh):
return i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos).simplify()
else:
return i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos)
return i
def FunctionOfTrig(u, *args):
# If u is a function of trig functions of v where v is a linear function of x,
# FunctionOfTrig[u,x] returns v; else it returns False.
if len(args) == 1:
x = args[0]
v = FunctionOfTrig(u, None, x)
if v:
return v
else:
return False
else:
v, x = args
if AtomQ(u):
if u == x:
return False
else:
return v
if TrigQ(u) and LinearQ(u.args[0], x):
if v is None:
return u.args[0]
else:
a = Coefficient(v, x, 0)
b = Coefficient(v, x, 1)
c = Coefficient(u.args[0], x, 0)
d = Coefficient(u.args[0], x, 1)
if ZeroQ(a*d - b*c) and RationalQ(b/d):
return a/Numerator(b/d) + b*x/Numerator(b/d)
else:
return False
if HyperbolicQ(u) and LinearQ(u.args[0], x):
if v is None:
return I*u.args[0]
a = Coefficient(v, x, 0)
b = Coefficient(v, x, 1)
c = I*Coefficient(u.args[0], x, 0)
d = I*Coefficient(u.args[0], x, 1)
if ZeroQ(a*d - b*c) and RationalQ(b/d):
return a/Numerator(b/d) + b*x/Numerator(b/d)
else:
return False
if CalculusQ(u):
return False
else:
w = v
for i in u.args:
w = FunctionOfTrig(i, w, x)
if FalseQ(w):
return False
return w
def AlgebraicTrigFunctionQ(u, x):
# If u is algebraic function of trig functions, AlgebraicTrigFunctionQ(u,x) returns True; else it returns False.
if AtomQ(u):
return True
elif TrigQ(u) and LinearQ(u.args[0], x):
return True
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
return True
elif PowerQ(u):
if FreeQ(u.exp, x):
return AlgebraicTrigFunctionQ(u.base, x)
elif ProductQ(u) or SumQ(u):
for i in u.args:
if not AlgebraicTrigFunctionQ(i, x):
return False
return True
return False
def FunctionOfHyperbolic(u, *x):
# If u is a function of hyperbolic trig functions of v where v is linear in x,
# FunctionOfHyperbolic(u,x) returns v; else it returns False.
if len(x) == 1:
x = x[0]
v = FunctionOfHyperbolic(u, None, x)
if v==None:
return False
else:
return v
else:
v = x[0]
x = x[1]
if AtomQ(u):
if u == x:
return False
return v
if HyperbolicQ(u) and LinearQ(u.args[0], x):
if v is None:
return u.args[0]
a = Coefficient(v, x, 0)
b = Coefficient(v, x, 1)
c = Coefficient(u.args[0], x, 0)
d = Coefficient(u.args[0], x, 1)
if ZeroQ(a*d - b*c) and RationalQ(b/d):
return a/Numerator(b/d) + b*x/Numerator(b/d)
else:
return False
if CalculusQ(u):
return False
w = v
for i in u.args:
if w == FunctionOfHyperbolic(i, w, x):
return False
return w
def FunctionOfQ(v, u, x, PureFlag=False):
# v is a function of x. If u is a function of v, FunctionOfQ(v, u, x) returns True; else it returns False. *)
if FreeQ(u, x):
return False
elif AtomQ(v):
return True
elif ProductQ(v) and Not(EqQ(FreeFactors(v, x), 1)):
return FunctionOfQ(NonfreeFactors(v, x), u, x, PureFlag)
elif PureFlag:
if SinQ(v) or CscQ(v):
return PureFunctionOfSinQ(u, v.args[0], x)
elif CosQ(v) or SecQ(v):
return PureFunctionOfCosQ(u, v.args[0], x)
elif TanQ(v):
return PureFunctionOfTanQ(u, v.args[0], x)
elif CotQ(v):
return PureFunctionOfCotQ(u, v.args[0], x)
elif SinhQ(v) or CschQ(v):
return PureFunctionOfSinhQ(u, v.args[0], x)
elif CoshQ(v) or SechQ(v):
return PureFunctionOfCoshQ(u, v.args[0], x)
elif TanhQ(v):
return PureFunctionOfTanhQ(u, v.args[0], x)
elif CothQ(v):
return PureFunctionOfCothQ(u, v.args[0], x)
else:
return FunctionOfExpnQ(u, v, x) != False
elif SinQ(v) or CscQ(v):
return FunctionOfSinQ(u, v.args[0], x)
elif CosQ(v) or SecQ(v):
return FunctionOfCosQ(u, v.args[0], x)
elif TanQ(v) or CotQ(v):
FunctionOfTanQ(u, v.args[0], x)
elif SinhQ(v) or CschQ(v):
return FunctionOfSinhQ(u, v.args[0], x)
elif CoshQ(v) or SechQ(v):
return FunctionOfCoshQ(u, v.args[0], x)
elif TanhQ(v) or CothQ(v):
return FunctionOfTanhQ(u, v.args[0], x)
return FunctionOfExpnQ(u, v, x) != False
def FunctionOfExpnQ(u, v, x):
if u == v:
return 1
if AtomQ(u):
if u == x:
return False
else:
return 0
if CalculusQ(u):
return False
if PowerQ(u):
if FreeQ(u.exp, x):
if ZeroQ(u.base - v):
if IntegerQ(u.exp):
return u.exp
else:
return 1
if PowerQ(v):
if FreeQ(v.exp, x) and ZeroQ(u.base-v.base):
if RationalQ(v.exp):
if RationalQ(u.exp) and IntegerQ(u.exp/v.exp) and (v.exp>0 or u.exp<0):
return u.exp/v.exp
else:
return False
if IntegerQ(Simplify(u.exp/v.exp)):
return Simplify(u.exp/v.exp)
else:
return False
return FunctionOfExpnQ(u.base, v, x)
if ProductQ(u) and Not(EqQ(FreeFactors(u, x), 1)):
return FunctionOfExpnQ(NonfreeFactors(u, x), v, x)
if ProductQ(u) and ProductQ(v):
deg1 = FunctionOfExpnQ(First(u), First(v), x)
if deg1==False:
return False
deg2 = FunctionOfExpnQ(Rest(u), Rest(v), x);
if deg1==deg2 and FreeQ(Simplify(u/v^deg1), x):
return deg1
else:
return False
lst = []
for i in u.args:
if FunctionOfExpnQ(i, v, x) is False:
return False
lst.append(FunctionOfExpnQ(i, v, x))
return Apply(GCD, lst)
def PureFunctionOfSinQ(u, v, x):
# If u is a pure function of Sin(v) and/or Csc(v), PureFunctionOfSinQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return SinQ(u) or CscQ(u)
for i in u.args:
if Not(PureFunctionOfSinQ(i, v, x)):
return False
return True
def PureFunctionOfCosQ(u, v, x):
# If u is a pure function of Cos(v) and/or Sec(v), PureFunctionOfCosQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return CosQ(u) or SecQ(u)
for i in u.args:
if Not(PureFunctionOfCosQ(i, v, x)):
return False
return True
def PureFunctionOfTanQ(u, v, x):
# If u is a pure function of Tan(v) and/or Cot(v), PureFunctionOfTanQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return TanQ(u) or CotQ(u)
for i in u.args:
if Not(PureFunctionOfTanQ(i, v, x)):
return False
return True
def PureFunctionOfCotQ(u, v, x):
# If u is a pure function of Cot(v), PureFunctionOfCotQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return CotQ(u)
for i in u.args:
if Not(PureFunctionOfCotQ(i, v, x)):
return False
return True
def FunctionOfCosQ(u, v, x):
# If u is a function of Cos[v], FunctionOfCosQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
# Basis: If m integer, Cos[m*v]^n is a function of Cos[v]. *)
return CosQ(u) or SecQ(u)
elif IntegerPowerQ(u):
if TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# Basis: If m integer and n even, Trig[m*v]^n is a function of Cos[v]. *)
return True
return FunctionOfCosQ(u.base, v, x)
elif ProductQ(u):
lst = FindTrigFactor(sin, csc, u, v, False)
if ListQ(lst):
# (* Basis: If m integer and n odd, Sin[m*v]^n == Sin[v]*u where u is a function of Cos[v]. *)
return FunctionOfCosQ(Sin(v)*lst[1], v, x)
lst = FindTrigFactor(tan, cot, u, v, True)
if ListQ(lst):
# (* Basis: If m integer and n odd, Tan[m*v]^n == Sin[v]*u where u is a function of Cos[v]. *)
return FunctionOfCosQ(Sin(v)*lst[1], v, x)
return all(FunctionOfCosQ(i, v, x) for i in u.args)
return all(FunctionOfCosQ(i, v, x) for i in u.args)
def FunctionOfSinQ(u, v, x):
# If u is a function of Sin[v], FunctionOfSinQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
if OddQuotientQ(u.args[0], v):
# Basis: If m odd, Sin[m*v]^n is a function of Sin[v].
return SinQ(u) or CscQ(u)
# Basis: If m even, Cos[m*v]^n is a function of Sin[v].
return CosQ(u) or SecQ(u)
elif IntegerPowerQ(u):
if TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# Basis: If m integer and n even, Hyper[m*v]^n is a function of Sin[v].
return True
return FunctionOfSinQ(u.base, v, x)
elif ProductQ(u):
if CosQ(u.args[0]) and SinQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return FunctionOfSinQ(Drop(u, 2), v, x)
lst = FindTrigFactor(sin, csch, u, v, False)
if ListQ(lst) and EvenQuotientQ(lst[0], v):
# Basis: If m even and n odd, Sin[m*v]^n == Cos[v]*u where u is a function of Sin[v].
return FunctionOfSinQ(Cos(v)*lst[1], v, x)
lst = FindTrigFactor(cos, sec, u, v, False)
if ListQ(lst) and OddQuotientQ(lst[0], v):
# Basis: If m odd and n odd, Cos[m*v]^n == Cos[v]*u where u is a function of Sin[v].
return FunctionOfSinQ(Cos(v)*lst[1], v, x)
lst = FindTrigFactor(tan, cot, u, v, True)
if ListQ(lst):
# Basis: If m integer and n odd, Tan[m*v]^n == Cos[v]*u where u is a function of Sin[v].
return FunctionOfSinQ(Cos(v)*lst[1], v, x)
return all(FunctionOfSinQ(i, v, x) for i in u.args)
return all(FunctionOfSinQ(i, v, x) for i in u.args)
def OddTrigPowerQ(u, v, x):
if SinQ(u) or CosQ(u) or SecQ(u) or CscQ(u):
return OddQuotientQ(u.args[0], v)
if PowerQ(u):
return OddQ(u.exp) and OddTrigPowerQ(u.base, v, x)
if ProductQ(u):
if not FreeFactors(u, x) == 1:
return OddTrigPowerQ(NonfreeFactors(u, x), v, x)
lst = []
for i in u.args:
if Not(FunctionOfTanQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==1 and OddTrigPowerQ(lst[0], v, x)
if SumQ(u):
return all(OddTrigPowerQ(i, v, x) for i in u.args)
return False
def FunctionOfTanQ(u, v, x):
# If u is a function of the form f[Tan[v],Cot[v]] where f is independent of x,
# FunctionOfTanQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
return TanQ(u) or CotQ(u) or EvenQuotientQ(u.args[0], v)
elif PowerQ(u):
if EvenQ(u.exp) and TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
return True
elif EvenQ(u.exp) and SumQ(u.base):
return FunctionOfTanQ(Expand(u.base**2, v, x))
if ProductQ(u):
lst = []
for i in u.args:
if Not(FunctionOfTanQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==2 and OddTrigPowerQ(lst[0], v, x) and OddTrigPowerQ(lst[1], v, x)
return all(FunctionOfTanQ(i, v, x) for i in u.args)
def FunctionOfTanWeight(u, v, x):
# (* u is a function of the form f[Tan[v],Cot[v]] where f is independent of x.
# FunctionOfTanWeight[u,v,x] returns a nonnegative number if u is best considered a function
# of Tan[v]; else it returns a negative number. *)
if AtomQ(u):
return S(0)
elif CalculusQ(u):
return S(0)
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
if TanQ(u) and ZeroQ(u.args[0] - v):
return S(1)
elif CotQ(u) and ZeroQ(u.args[0] - v):
return S(-1)
return S(0)
elif PowerQ(u):
if EvenQ(u.exp) and TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if TanQ(u.base) or CosQ(u.base) or SecQ(u.base):
return S(1)
return S(-1)
if ProductQ(u):
if all(FunctionOfTanQ(i, v, x) for i in u.args):
return Add(*[FunctionOfTanWeight(i, v, x) for i in u.args])
return S(0)
return Add(*[FunctionOfTanWeight(i, v, x) for i in u.args])
def FunctionOfTrigQ(u, v, x):
# If u (x) is equivalent to a function of the form f (Sin[v],Cos[v],Tan[v],Cot[v],Sec[v],Csc[v]) where f is independent of x, FunctionOfTrigQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
return True
return all(FunctionOfTrigQ(i, v, x) for i in u.args)
def FunctionOfDensePolynomialsQ(u, x):
# If all occurrences of x in u (x) are in dense polynomials, FunctionOfDensePolynomialsQ[u,x] returns True; else it returns False.
if FreeQ(u, x):
return True
if PolynomialQ(u, x):
return Length(Exponent(u,x,List))>1
return all(FunctionOfDensePolynomialsQ(i, x) for i in u.args)
def FunctionOfLog(u, *args):
# If u (x) is equivalent to an expression of the form f (Log[a*x^n]), FunctionOfLog[u,x] returns
# the list {f (x),a*x^n,n}; else it returns False.
if len(args) == 1:
x = args[0]
lst = FunctionOfLog(u, False, False, x)
if AtomQ(lst) or FalseQ(lst[1]) or not isinstance(x, Symbol):
return False
else:
return lst
else:
v = args[0]
n = args[1]
x = args[2]
if AtomQ(u):
if u==x:
return False
else:
return [u, v, n]
if CalculusQ(u):
return False
lst = BinomialParts(u.args[0], x)
if LogQ(u) and ListQ(lst) and ZeroQ(lst[0]):
if FalseQ(v) or u.args[0] == v:
return [x, u.args[0], lst[2]]
else:
return False
lst = [0, v, n]
l = []
for i in u.args:
lst = FunctionOfLog(i, lst[1], lst[2], x)
if AtomQ(lst):
return False
else:
l.append(lst[0])
return [u.func(*l), lst[1], lst[2]]
def PowerVariableExpn(u, m, x):
# If m is an integer, u is an expression of the form f((c*x)**n) and g=GCD(m,n)>1,
# PowerVariableExpn(u,m,x) returns the list {x**(m/g)*f((c*x)**(n/g)),g,c}; else it returns False.
if IntegerQ(m):
lst = PowerVariableDegree(u, m, 1, x)
if not lst:
return False
else:
return [x**(m/lst[0])*PowerVariableSubst(u, lst[0], x), lst[0], lst[1]]
else:
return False
def PowerVariableDegree(u, m, c, x):
if FreeQ(u, x):
return [m, c]
if AtomQ(u) or CalculusQ(u):
return False
if PowerQ(u):
if FreeQ(u.base/x, x):
if ZeroQ(m) or m == u.exp and c == u.base/x:
return [u.exp, u.base/x]
if IntegerQ(u.exp) and IntegerQ(m) and GCD(m, u.exp)>1 and c==u.base/x:
return [GCD(m, u.exp), c]
else:
return False
lst = [m, c]
for i in u.args:
if PowerVariableDegree(i, lst[0], lst[1], x) == False:
return False
lst1 = PowerVariableDegree(i, lst[0], lst[1], x)
if not lst1:
return False
else:
return lst1
def PowerVariableSubst(u, m, x):
if FreeQ(u, x) or AtomQ(u) or CalculusQ(u):
return u
if PowerQ(u):
if FreeQ(u.base/x, x):
return x**(u.exp/m)
if ProductQ(u):
l = 1
for i in u.args:
l *= (PowerVariableSubst(i, m, x))
return l
if SumQ(u):
l = 0
for i in u.args:
l += (PowerVariableSubst(i, m, x))
return l
return u
def EulerIntegrandQ(expr, x):
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
n = Wild('n', exclude=[x, 0])
m = Wild('m', exclude=[x, 0])
p = Wild('p', exclude=[x, 0])
u = Wild('u')
v = Wild('v')
# Pattern 1
M = expr.match((a*x + b*u**n)**p)
if M:
if len(M) == 5 and FreeQ([M[a], M[b]], x) and IntegerQ(M[n] + 1/2) and QuadraticQ(M[u], x) and Not(RationalQ(M[p])) or NegativeIntegerQ(M[p]) and Not(BinomialQ(M[u], x)):
return True
# Pattern 2
M = expr.match(v**m*(a*x + b*u**n)**p)
if M:
if len(M) == 6 and FreeQ([M[a], M[b]], x) and ZeroQ(M[u] - M[v]) and IntegersQ(2*M[m], M[n] + 1/2) and QuadraticQ(M[u], x) and Not(RationalQ(M[p])) or NegativeIntegerQ(M[p]) and Not(BinomialQ(M[u], x)):
return True
# Pattern 3
M = expr.match(u**n*v**p)
if M:
if len(M) == 3 and NegativeIntegerQ(M[p]) and IntegerQ(M[n] + 1/2) and QuadraticQ(M[u], x) and QuadraticQ(M[v], x) and Not(BinomialQ(M[v], x)):
return True
else:
return False
def FunctionOfSquareRootOfQuadratic(u, *args):
if len(args) == 1:
x = args[0]
pattern = Pattern(UtilityOperator(x_**WC('m', 1)*(a_ + x**WC('n', 1)*WC('b', 1))**p_, x), CustomConstraint(lambda a, b, m, n, p, x: FreeQ([a, b, m, n, p], x)))
M = is_match(UtilityOperator(u, args[0]), pattern)
if M:
return False
tmp = FunctionOfSquareRootOfQuadratic(u, False, x)
if AtomQ(tmp) or FalseQ(tmp[0]):
return False
tmp = tmp[0]
a = Coefficient(tmp, x, 0)
b = Coefficient(tmp, x, 1)
c = Coefficient(tmp, x, 2)
if ZeroQ(a) and ZeroQ(b) or ZeroQ(b**2-4*a*c):
return False
if PosQ(c):
sqrt = Rt(c, S(2));
q = a*sqrt + b*x + sqrt*x**2
r = b + 2*sqrt*x
return [Simplify(SquareRootOfQuadraticSubst(u, q/r, (-a+x**2)/r, x)*q/r**2), Simplify(sqrt*x + Sqrt(tmp)), 2]
if PosQ(a):
sqrt = Rt(a, S(2))
q = c*sqrt - b*x + sqrt*x**2
r = c - x**2
return [Simplify(SquareRootOfQuadraticSubst(u, q/r, (-b+2*sqrt*x)/r, x)*q/r**2), Simplify((-sqrt+Sqrt(tmp))/x), 1]
sqrt = Rt(b**2 - 4*a*c, S(2))
r = c - x**2
return[Simplify(-sqrt*SquareRootOfQuadraticSubst(u, -sqrt*x/r, -(b*c+c*sqrt+(-b+sqrt)*x**2)/(2*c*r), x)*x/r**2), FullSimplify(2*c*Sqrt(tmp)/(b-sqrt+2*c*x)), 3]
else:
v = args[0]
x = args[1]
if AtomQ(u) or FreeQ(u, x):
return [v]
if PowerQ(u):
if FreeQ(u.exp, x):
if FractionQ(u.exp) and Denominator(u.exp)==2 and PolynomialQ(u.base, x) and Exponent(u.base, x)==2:
if FalseQ(v) or u.base == v:
return [u.base]
else:
return False
return FunctionOfSquareRootOfQuadratic(u.base, v, x)
if ProductQ(u) or SumQ(u):
lst = [v]
lst1 = []
for i in u.args:
if FunctionOfSquareRootOfQuadratic(i, lst[0], x) == False:
return False
lst1 = FunctionOfSquareRootOfQuadratic(i, lst[0], x)
return lst1
else:
return False
def SquareRootOfQuadraticSubst(u, vv, xx, x):
# SquareRootOfQuadraticSubst(u, vv, xx, x) returns u with fractional powers replaced by vv raised to the power and x replaced by xx.
if AtomQ(u) or FreeQ(u, x):
if u==x:
return xx
return u
if PowerQ(u):
if FreeQ(u.exp, x):
if FractionQ(u.exp) and Denominator(u.exp)==2 and PolynomialQ(u.base, x) and Exponent(u.base, x)==2:
return vv**Numerator(u.exp)
return SquareRootOfQuadraticSubst(u.base, vv, xx, x)**u.exp
elif SumQ(u):
t = 0
for i in u.args:
t += SquareRootOfQuadraticSubst(i, vv, xx, x)
return t
elif ProductQ(u):
t = 1
for i in u.args:
t *= SquareRootOfQuadraticSubst(i, vv, xx, x)
return t
def Divides(y, u, x):
# If u divided by y is free of x, Divides[y,u,x] returns the quotient; else it returns False.
v = Simplify(u/y)
if FreeQ(v, x):
return v
else:
return False
def DerivativeDivides(y, u, x):
"""
If y not equal to x, y is easy to differentiate wrt x, and u divided by the derivative of y
is free of x, DerivativeDivides[y,u,x] returns the quotient; else it returns False.
"""
from matchpy import is_match
pattern0 = Pattern(Mul(a , b_), CustomConstraint(lambda a, b : FreeQ(a, b)))
def f1(y, u, x):
if PolynomialQ(y, x):
return PolynomialQ(u, x) and Exponent(u, x)==Exponent(y, x)-1
else:
return EasyDQ(y, x)
if is_match(y, pattern0):
return False
elif f1(y, u, x):
v = D(y ,x)
if EqQ(v, 0):
return False
else:
v = Simplify(u/v)
if FreeQ(v, x):
return v
else:
return False
else:
return False
def EasyDQ(expr, x):
# If u is easy to differentiate wrt x, EasyDQ(u, x) returns True; else it returns False *)
u = Wild('u',exclude=[1])
m = Wild('m',exclude=[x, 0])
M = expr.match(u*x**m)
if M:
return EasyDQ(M[u], x)
if AtomQ(expr) or FreeQ(expr, x) or Length(expr)==0:
return True
elif CalculusQ(expr):
return False
elif Length(expr)==1:
return EasyDQ(expr.args[0], x)
elif BinomialQ(expr, x) or ProductOfLinearPowersQ(expr, x):
return True
elif RationalFunctionQ(expr, x) and RationalFunctionExponents(expr, x)==[1, 1]:
return True
elif ProductQ(expr):
if FreeQ(First(expr), x):
return EasyDQ(Rest(expr), x)
elif FreeQ(Rest(expr), x):
return EasyDQ(First(expr), x)
else:
return False
elif SumQ(expr):
return EasyDQ(First(expr), x) and EasyDQ(Rest(expr), x)
elif Length(expr)==2:
if FreeQ(expr.args[0], x):
EasyDQ(expr.args[1], x)
elif FreeQ(expr.args[1], x):
return EasyDQ(expr.args[0], x)
else:
return False
return False
def ProductOfLinearPowersQ(u, x):
# ProductOfLinearPowersQ(u, x) returns True iff u is a product of factors of the form v^n where v is linear in x
v = Wild('v')
n = Wild('n', exclude=[x])
M = u.match(v**n)
return FreeQ(u, x) or M and LinearQ(M[v], x) or ProductQ(u) and ProductOfLinearPowersQ(First(u), x) and ProductOfLinearPowersQ(Rest(u), x)
def Rt(u, n):
return RtAux(TogetherSimplify(u), n)
def NthRoot(u, n):
return nsimplify(u**(S(1)/n))
def AtomBaseQ(u):
# If u is an atom or an atom raised to an odd degree, AtomBaseQ(u) returns True; else it returns False
return AtomQ(u) or PowerQ(u) and OddQ(u.args[1]) and AtomBaseQ(u.args[0])
def SumBaseQ(u):
# If u is a sum or a sum raised to an odd degree, SumBaseQ(u) returns True; else it returns False
return SumQ(u) or PowerQ(u) and OddQ(u.args[1]) and SumBaseQ(u.args[0])
def NegSumBaseQ(u):
# If u is a sum or a sum raised to an odd degree whose lead term has a negative form, NegSumBaseQ(u) returns True; else it returns False
return SumQ(u) and NegQ(First(u)) or PowerQ(u) and OddQ(u.args[1]) and NegSumBaseQ(u.args[0])
def AllNegTermQ(u):
# If all terms of u have a negative form, AllNegTermQ(u) returns True; else it returns False
if PowerQ(u):
if OddQ(u.exp):
return AllNegTermQ(u.base)
if SumQ(u):
return NegQ(First(u)) and AllNegTermQ(Rest(u))
return NegQ(u)
def SomeNegTermQ(u):
# If some term of u has a negative form, SomeNegTermQ(u) returns True; else it returns False
if PowerQ(u):
if OddQ(u.exp):
return SomeNegTermQ(u.base)
if SumQ(u):
return NegQ(First(u)) or SomeNegTermQ(Rest(u))
return NegQ(u)
def TrigSquareQ(u):
# If u is an expression of the form Sin(z)^2 or Cos(z)^2, TrigSquareQ(u) returns True, else it returns False
return PowerQ(u) and EqQ(u.args[1], 2) and MemberQ([sin, cos], Head(u.args[0]))
def RtAux(u, n):
if PowerQ(u):
return u.base**(u.exp/n)
if ComplexNumberQ(u):
a = Re(u)
b = Im(u)
if Not(IntegerQ(a) and IntegerQ(b)) and IntegerQ(a/(a**2 + b**2)) and IntegerQ(b/(a**2 + b**2)):
# Basis: a+b*I==1/(a/(a^2+b^2)-b/(a^2+b^2)*I)
return S(1)/RtAux(a/(a**2 + b**2) - b/(a**2 + b**2)*I, n)
else:
return NthRoot(u, n)
if ProductQ(u):
lst = SplitProduct(PositiveQ, u)
if ListQ(lst):
return RtAux(lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(NegativeQ, u)
if ListQ(lst):
if EqQ(lst[0], -1):
v = lst[1]
if PowerQ(v):
if NegativeQ(v.exp):
return 1/RtAux(-v.base**(-v.exp), n)
if ProductQ(v):
if ListQ(SplitProduct(SumBaseQ, v)):
lst = SplitProduct(AllNegTermQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(NegSumBaseQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(SomeNegTermQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(SumBaseQ, v)
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(AtomBaseQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
else:
return RtAux(-First(v), n)*RtAux(Rest(v), n)
if OddQ(n):
return -RtAux(v, n)
else:
return NthRoot(u, n)
else:
return RtAux(-lst[0], n)*RtAux(-lst[1], n)
lst = SplitProduct(AllNegTermQ, u)
if ListQ(lst) and ListQ(SplitProduct(SumBaseQ, lst[1])):
return RtAux(-lst[0], n)*RtAux(-lst[1], n)
lst = SplitProduct(NegSumBaseQ, u)
if ListQ(lst) and ListQ(SplitProduct(NegSumBaseQ, lst[1])):
return RtAux(-lst[0], n)*RtAux(-lst[1], n)
return u.func(*[RtAux(i, n) for i in u.args])
v = TrigSquare(u)
if Not(AtomQ(v)):
return RtAux(v, n)
if OddQ(n) and NegativeQ(u):
return -RtAux(-u, n)
if OddQ(n) and NegQ(u) and PosQ(-u):
return -RtAux(-u, n)
else:
return NthRoot(u, n)
def TrigSquare(u):
# If u is an expression of the form a-a*Sin(z)^2 or a-a*Cos(z)^2, TrigSquare(u) returns Cos(z)^2 or Sin(z)^2 respectively,
# else it returns False.
if SumQ(u):
for i in u.args:
v = SplitProduct(TrigSquareQ, i)
if v == False or SplitSum(v, u) == False:
return False
lst = SplitSum(SplitProduct(TrigSquareQ, i))
if lst and ZeroQ(lst[1][2] + lst[1]):
if Head(lst[0][0].args[0]) == sin:
return lst[1]*cos(lst[1][1][1][1])**2
return lst[1]*sin(lst[1][1][1][1])**2
else:
return False
else:
return False
def IntSum(u, x):
# If u is free of x or of the form c*(a+b*x)^m, IntSum[u,x] returns the antiderivative of u wrt x;
# else it returns d*Int[v,x] where d*v=u and d is free of x.
return Add(*[Integral(i, x) for i in u.args])
return Simp(FreeTerms(u, x)*x, x) + IntTerm(NonfreeTerms(u, x), x)
def IntTerm(expr, x):
# If u is of the form c*(a+b*x)**m, IntTerm(u,x) returns the antiderivative of u wrt x;
# else it returns d*Int(v,x) where d*v=u and d is free of x.
c = Wild('c', exclude=[x])
m = Wild('m', exclude=[x, 0])
v = Wild('v')
M = expr.match(c/v)
if M and len(M) == 2 and FreeQ(M[c], x) and LinearQ(M[v], x):
return Simp(M[c]*Log(RemoveContent(M[v], x))/Coefficient(M[v], x, 1), x)
M = expr.match(c*v**m)
if M and len(M) == 3 and NonzeroQ(M[m] + 1) and LinearQ(M[v], x):
return Simp(M[c]*M[v]**(M[m] + 1)/(Coefficient(M[v], x, 1)*(M[m] + 1)), x)
if SumQ(expr):
t = 0
for i in expr.args:
t += IntTerm(i, x)
return t
else:
u = expr
return Dist(FreeFactors(u,x), Integral(NonfreeFactors(u, x), x), x)
def Map2(f, lst1, lst2):
result = []
for i in range(0, len(lst1)):
result.append(f(lst1[i], lst2[i]))
return result
def ConstantFactor(u, x):
# (* ConstantFactor[u,x] returns a 2-element list of the factors of u[x] free of x and the
# factors not free of u[x]. Common constant factors of the terms of sums are also collected. *)
if FreeQ(u, x):
return [u, S(1)]
elif AtomQ(u):
return [S(1), u]
elif PowerQ(u):
if FreeQ(u.exp, x):
lst = ConstantFactor(u.base, x)
if IntegerQ(u.exp):
return [lst[0]**u.exp, lst[1]**u.exp]
tmp = PositiveFactors(lst[0])
if tmp == 1:
return [S(1), u]
return [tmp**u.exp, (NonpositiveFactors(lst[0])*lst[1])**u.exp]
elif ProductQ(u):
lst = [ConstantFactor(i, x) for i in u.args]
return [Mul(*[First(i) for i in lst]), Mul(*[i[1] for i in lst])]
elif SumQ(u):
lst1 = [ConstantFactor(i, x) for i in u.args]
if SameQ(*[i[1] for i in lst1]):
return [Add(*[i[0] for i in lst]), lst1[0][1]]
lst2 = CommonFactors([First(i) for i in lst1])
return [First(lst2), Add(*Map2(Mul, Rest(lst2), [i[1] for i in lst1]))]
return [S(1), u]
def SameQ(*args):
for i in range(0, len(args) - 1):
if args[i] != args[i+1]:
return False
return True
def ReplacePart(lst, a, b):
lst[b] = a
return lst
def CommonFactors(lst):
# (* If lst is a list of n terms, CommonFactors[lst] returns a n+1-element list whose first
# element is the product of the factors common to all terms of lst, and whose remaining
# elements are quotients of each term divided by the common factor. *)
lst1 = [NonabsurdNumberFactors(i) for i in lst]
lst2 = [AbsurdNumberFactors(i) for i in lst]
num = AbsurdNumberGCD(*lst2)
common = num
lst2 = [i/num for i in lst2]
while (True):
lst3 = [LeadFactor(i) for i in lst1]
if SameQ(*lst3):
common = common*lst3[0]
lst1 = [RemainingFactors(i) for i in lst1]
elif (all((LogQ(i) and IntegerQ(First(i)) and First(i) > 0) for i in lst3) and
all(RationalQ(i) for i in [FullSimplify(j/First(lst3)) for j in lst3])):
lst4 = [FullSimplify(j/First(lst3)) for j in lst3]
num = GCD(*lst4)
common = common*Log((First(lst3)[0])**num)
lst2 = [lst2[i]*lst4[i]/num for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
lst4 = [LeadDegree(i) for i in lst1]
if SameQ(*[LeadBase(i) for i in lst1]) and RationalQ(*lst4):
num = Smallest(lst4)
base = LeadBase(lst1[0])
if num != 0:
common = common*base**num
lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
elif (Length(lst1) == 2 and ZeroQ(LeadBase(lst1[0]) + LeadBase(lst1[1])) and
NonzeroQ(lst1[0] - 1) and IntegerQ(lst4[0]) and FractionQ(lst4[1])):
num = Min(lst4)
base = LeadBase(lst1[1])
if num != 0:
common = common*base**num
lst2 = [lst2[0]*(-1)**lst4[0], lst2[1]]
lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
elif (Length(lst1) == 2 and ZeroQ(lst1[0] + LeadBase(lst1[1])) and
NonzeroQ(lst1[1] - 1) and IntegerQ(lst1[1]) and FractionQ(lst4[0])):
num = Min(lst4)
base = LeadBase(lst1[0])
if num != 0:
common = common*base**num
lst2 = [lst2[0], lst2[1]*(-1)**lst4[1]]
lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
else:
num = MostMainFactorPosition(lst3)
lst2 = ReplacePart(lst2, lst3[num]*lst2[num], num)
lst1 = ReplacePart(lst1, RemainingFactors(lst1[num]), num)
if all(i==1 for i in lst1):
return Prepend(lst2, common)
def MostMainFactorPosition(lst):
factor = S(1)
num = 0
for i in range(0, Length(lst)):
if FactorOrder(lst[i], factor) > 0:
factor = lst[i]
num = i
return num
SbaseS, SexponS = None, None
SexponFlagS = False
def FunctionOfExponentialQ(u, x):
# (* FunctionOfExponentialQ[u,x] returns True iff u is a function of F^v where F is a constant and v is linear in x, *)
# (* and such an exponential explicitly occurs in u (i.e. not just implicitly in hyperbolic functions). *)
global SbaseS, SexponS, SexponFlagS
SbaseS, SexponS = None, None
SexponFlagS = False
res = FunctionOfExponentialTest(u, x)
return res and SexponFlagS
def FunctionOfExponential(u, x):
global SbaseS, SexponS, SexponFlagS
# (* u is a function of F^v where v is linear in x. FunctionOfExponential[u,x] returns F^v. *)
SbaseS, SexponS = None, None
SexponFlagS = False
FunctionOfExponentialTest(u, x)
return SbaseS**SexponS
def FunctionOfExponentialFunction(u, x):
global SbaseS, SexponS, SexponFlagS
# (* u is a function of F^v where v is linear in x. FunctionOfExponentialFunction[u,x] returns u with F^v replaced by x. *)
SbaseS, SexponS = None, None
SexponFlagS = False
FunctionOfExponentialTest(u, x)
return SimplifyIntegrand(FunctionOfExponentialFunctionAux(u, x), x)
def FunctionOfExponentialFunctionAux(u, x):
# (* u is a function of F^v where v is linear in x, and the fluid variables $base$=F and $expon$=v. *)
# (* FunctionOfExponentialFunctionAux[u,x] returns u with F^v replaced by x. *)
global SbaseS, SexponS, SexponFlagS
if AtomQ(u):
return u
elif PowerQ(u):
if FreeQ(u.base, x) and LinearQ(u.exp, x):
if ZeroQ(Coefficient(SexponS, x, 0)):
return u.base**Coefficient(u.exp, x, 0)*x**FullSimplify(Log(u.base)*Coefficient(u.exp, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
return x**FullSimplify(Log(u.base)*Coefficient(u.exp, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
tmp = x**FullSimplify(Coefficient(u.args[0], x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
if SinhQ(u):
return tmp/2 - 1/(2*tmp)
elif CoshQ(u):
return tmp/2 + 1/(2*tmp)
elif TanhQ(u):
return (tmp - 1/tmp)/(tmp + 1/tmp)
elif CothQ(u):
return (tmp + 1/tmp)/(tmp - 1/tmp)
elif SechQ(u):
return 2/(tmp + 1/tmp)
return 2/(tmp - 1/tmp)
if PowerQ(u):
if FreeQ(u.base, x) and SumQ(u.exp):
return FunctionOfExponentialFunctionAux(u.base**First(u.exp), x)*FunctionOfExponentialFunctionAux(u.base**Rest(u.exp), x)
return u.func(*[FunctionOfExponentialFunctionAux(i, x) for i in u.args])
def FunctionOfExponentialTest(u, x):
# (* FunctionOfExponentialTest[u,x] returns True iff u is a function of F^v where F is a constant and v is linear in x. *)
# (* Before it is called, the fluid variables $base$ and $expon$ should be set to Null and $exponFlag$ to False. *)
# (* If u is a function of F^v, $base$ and $expon$ are set to F and v, respectively. *)
# (* If an explicit exponential occurs in u, $exponFlag$ is set to True. *)
global SbaseS, SexponS, SexponFlagS
if FreeQ(u, x):
return True
elif u == x or CalculusQ(u):
return False
elif PowerQ(u):
if FreeQ(u.base, x) and LinearQ(u.exp, x):
SexponFlagS = True
return FunctionOfExponentialTestAux(u.base, u.exp, x)
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
return FunctionOfExponentialTestAux(E, u.args[0], x)
if PowerQ(u):
if FreeQ(u.base, x) and SumQ(u.exp):
return FunctionOfExponentialTest(u.base**First(u.exp), x) and FunctionOfExponentialTest(u.base**Rest(u.exp), x)
return all(FunctionOfExponentialTest(i, x) for i in u.args)
def FunctionOfExponentialTestAux(base, expon, x):
global SbaseS, SexponS, SexponFlagS
if SbaseS is None:
SbaseS = base
SexponS = expon
return True
tmp = FullSimplify(Log(base)*Coefficient(expon, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
if Not(RationalQ(tmp)):
return False
elif ZeroQ(Coefficient(SexponS, x, 0)) or NonzeroQ(tmp - FullSimplify(Log(base)*Coefficient(expon, x, 0)/(Log(SbaseS)*Coefficient(SexponS, x, 0)))):
if PositiveIntegerQ(base, SbaseS) and base<SbaseS:
SbaseS = base
SexponS = expon
tmp = 1/tmp
SexponS = Coefficient(SexponS, x, 1)*x/Denominator(tmp)
if tmp < 0 and NegQ(Coefficient(SexponS, x, 1)):
SexponS = -SexponS
return True
else:
return True
if PositiveIntegerQ(base, SbaseS) and base < SbaseS:
SbaseS = base
SexponS = expon
tmp = 1/tmp
SexponS = SexponS/Denominator(tmp)
if tmp < 0 and NegQ(Coefficient(SexponS, x, 1)):
SexponS = -SexponS
return True
return True
def stdev(lst):
"""Calculates the standard deviation for a list of numbers."""
num_items = len(lst)
mean = sum(lst) / num_items
differences = [x - mean for x in lst]
sq_differences = [d ** 2 for d in differences]
ssd = sum(sq_differences)
variance = ssd / num_items
sd = sqrt(variance)
return sd
def rubi_test(expr, x, optimal_output, expand=False, _hyper_check=False, _diff=False, _numerical=False):
#Returns True if (expr - optimal_output) is equal to 0 or a constant
#expr: integrated expression
#x: integration variable
#expand=True equates `expr` with `optimal_output` in expanded form
#_hyper_check=True evaluates numerically
#_diff=True differentiates the expressions before equating
#_numerical=True equates the expressions at random `x`. Normally used for large expressions.
from sympy import nsimplify
if not expr.has(csc, sec, cot, csch, sech, coth):
optimal_output = process_trig(optimal_output)
if expr == optimal_output:
return True
if simplify(expr) == simplify(optimal_output):
return True
if nsimplify(expr) == nsimplify(optimal_output):
return True
if expr.has(sym_exp):
expr = powsimp(powdenest(expr), force=True)
if simplify(expr) == simplify(powsimp(optimal_output, force=True)):
return True
res = expr - optimal_output
if _numerical:
args = res.free_symbols
rand_val = []
try:
for i in range(0, 5): # check at 5 random points
rand_x = randint(1, 40)
substitutions = dict((s, rand_x) for s in args)
rand_val.append(float(abs(res.subs(substitutions).n())))
if stdev(rand_val) < Pow(10, -3):
return True
except:
pass
# return False
dres = res.diff(x)
if _numerical:
args = dres.free_symbols
rand_val = []
try:
for i in range(0, 5): # check at 5 random points
rand_x = randint(1, 40)
substitutions = dict((s, rand_x) for s in args)
rand_val.append(float(abs(dres.subs(substitutions).n())))
if stdev(rand_val) < Pow(10, -3):
return True
# return False
except:
pass
# return False
r = Simplify(nsimplify(res))
if r == 0 or (not r.has(x)):
return True
if _diff:
if dres == 0:
return True
elif Simplify(dres) == 0:
return True
if expand: # expands the expression and equates
e = res.expand()
if Simplify(e) == 0 or (not e.has(x)):
return True
return False
def If(cond, t, f):
# returns t if condition is true else f
if cond:
return t
return f
def IntQuadraticQ(a, b, c, d, e, m, p, x):
# (* IntQuadraticQ[a,b,c,d,e,m,p,x] returns True iff (d+e*x)^m*(a+b*x+c*x^2)^p is integrable wrt x in terms of non-Appell functions. *)
return IntegerQ(p) or PositiveIntegerQ(m) or IntegersQ(2*m, 2*p) or IntegersQ(m, 4*p) or IntegersQ(m, p + S(1)/3) and (ZeroQ(c**2*d**2 - b*c*d*e + b**2*e**2 - 3*a*c*e**2) or ZeroQ(c**2*d**2 - b*c*d*e - 2*b**2*e**2 + 9*a*c*e**2))
def IntBinomialQ(*args):
#(* IntBinomialQ(a,b,c,n,m,p,x) returns True iff (c*x)^m*(a+b*x^n)^p is integrable wrt x in terms of non-hypergeometric functions. *)
if len(args) == 8:
a, b, c, d, n, p, q, x = args
return IntegersQ(p,q) or PositiveIntegerQ(p) or PositiveIntegerQ(q) or (ZeroQ(n-2) or ZeroQ(n-4)) and (IntegersQ(p,4*q) or IntegersQ(4*p,q)) or ZeroQ(n-2) and (IntegersQ(2*p,2*q) or IntegersQ(3*p,q) and ZeroQ(b*c+3*a*d) or IntegersQ(p,3*q) and ZeroQ(3*b*c+a*d))
elif len(args) == 7:
a, b, c, n, m, p, x = args
return IntegerQ(2*p) or IntegerQ((m+1)/n + p) or (ZeroQ(n - 2) or ZeroQ(n - 4)) and IntegersQ(2*m, 4*p) or ZeroQ(n - 2) and IntegerQ(6*p) and (IntegerQ(m) or IntegerQ(m - p))
elif len(args) == 10:
a, b, c, d, e, m, n, p, q, x = args
return IntegersQ(p,q) or PositiveIntegerQ(p) or PositiveIntegerQ(q) or ZeroQ(n-2) and IntegerQ(m) and IntegersQ(2*p,2*q) or ZeroQ(n-4) and (IntegersQ(m,p,2*q) or IntegersQ(m,2*p,q))
def RectifyTangent(*args):
# (* RectifyTangent(u,a,b,r,x) returns an expression whose derivative equals the derivative of r*ArcTan(a+b*Tan(u)) wrt x. *)
if len(args) == 5:
u, a, b, r, x = args
t1 = Together(a)
t2 = Together(b)
if (PureComplexNumberQ(t1) or (ProductQ(t1) and any(PureComplexNumberQ(i) for i in t1.args))) and (PureComplexNumberQ(t2) or ProductQ(t2) and any(PureComplexNumberQ(i) for i in t2.args)):
c = a/I
d = b/I
if NegativeQ(d):
return RectifyTangent(u, -a, -b, -r, x)
e = SmartDenominator(Together(c + d*x))
c = c*e
d = d*e
if EvenQ(Denominator(NumericFactor(Together(u)))):
return I*r*Log(RemoveContent(Simplify((c+e)**2+d**2)+Simplify((c+e)**2-d**2)*Cos(2*u)+Simplify(2*(c+e)*d)*Sin(2*u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2+d**2)+Simplify((c-e)**2-d**2)*Cos(2*u)+Simplify(2*(c-e)*d)*Sin(2*u),x))/4
return I*r*Log(RemoveContent(Simplify((c+e)**2)+Simplify(2*(c+e)*d)*Cos(u)*Sin(u)-Simplify((c+e)**2-d**2)*Sin(u)**2,x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2)+Simplify(2*(c-e)*d)*Cos(u)*Sin(u)-Simplify((c-e)**2-d**2)*Sin(u)**2,x))/4
elif NegativeQ(b):
return RectifyTangent(u, -a, -b, -r, x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
return r*SimplifyAntiderivative(u,x) + r*ArcTan(Simplify((2*a*b*Cos(2*u)-(1+a**2-b**2)*Sin(2*u))/(a**2+(1+b)**2+(1+a**2-b**2)*Cos(2*u)+2*a*b*Sin(2*u))))
return r*SimplifyAntiderivative(u,x) - r*ArcTan(ActivateTrig(Simplify((a*b-2*a*b*cos(u)**2+(1+a**2-b**2)*cos(u)*sin(u))/(b*(1+b)+(1+a**2-b**2)*cos(u)**2+2*a*b*cos(u)*sin(u)))))
u, a, b, x = args
t = Together(a)
if PureComplexNumberQ(t) or (ProductQ(t) and any(PureComplexNumberQ(i) for i in t.args)):
c = a/I
if NegativeQ(c):
return RectifyTangent(u, -a, -b, x)
if ZeroQ(c - 1):
if EvenQ(Denominator(NumericFactor(Together(u)))):
return I*b*ArcTanh(Sin(2*u))/2
return I*b*ArcTanh(2*cos(u)*sin(u))/2
e = SmartDenominator(c)
c = c*e
return I*b*Log(RemoveContent(e*Cos(u)+c*Sin(u),x))/2 - I*b*Log(RemoveContent(e*Cos(u)-c*Sin(u),x))/2
elif NegativeQ(a):
return RectifyTangent(u, -a, -b, x)
elif ZeroQ(a - 1):
return b*SimplifyAntiderivative(u, x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
c = Simplify((1 + a)/(1 - a))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Sin(2*u)/(numr+denr*Cos(2*u)))),
elif PositiveQ(a - 1):
c = Simplify(1/(a - 1))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) + b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Sin(u)**2))),
c = Simplify(a/(1 - a))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Cos(u)**2)))
def RectifyCotangent(*args):
#(* RectifyCotangent[u,a,b,r,x] returns an expression whose derivative equals the derivative of r*ArcTan[a+b*Cot[u]] wrt x. *)
if len(args) == 5:
u, a, b, r, x = args
t1 = Together(a)
t2 = Together(b)
if (PureComplexNumberQ(t1) or (ProductQ(t1) and any(PureComplexNumberQ(i) for i in t1.args))) and (PureComplexNumberQ(t2) or ProductQ(t2) and any(PureComplexNumberQ(i) for i in t2.args)):
c = a/I
d = b/I
if NegativeQ(d):
return RectifyTangent(u,-a,-b,-r,x)
e = SmartDenominator(Together(c + d*x))
c = c*e
d = d*e
if EvenQ(Denominator(NumericFactor(Together(u)))):
return I*r*Log(RemoveContent(Simplify((c+e)**2+d**2)-Simplify((c+e)**2-d**2)*Cos(2*u)+Simplify(2*(c+e)*d)*Sin(2*u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2+d**2)-Simplify((c-e)**2-d**2)*Cos(2*u)+Simplify(2*(c-e)*d)*Sin(2*u),x))/4
return I*r*Log(RemoveContent(Simplify((c+e)**2)-Simplify((c+e)**2-d**2)*Cos(u)**2+Simplify(2*(c+e)*d)*Cos(u)*Sin(u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2)-Simplify((c-e)**2-d**2)*Cos(u)**2+Simplify(2*(c-e)*d)*Cos(u)*Sin(u),x))/4
elif NegativeQ(b):
return RectifyCotangent(u,-a,-b,-r,x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
return -r*SimplifyAntiderivative(u,x) - r*ArcTan(Simplify((2*a*b*Cos(2*u)+(1+a**2-b**2)*Sin(2*u))/(a**2+(1+b)**2-(1+a**2-b**2)*Cos(2*u)+2*a*b*Sin(2*u))))
return -r*SimplifyAntiderivative(u,x) - r*ArcTan(ActivateTrig(Simplify((a*b-2*a*b*sin(u)**2+(1+a**2-b**2)*cos(u)*sin(u))/(b*(1+b)+(1+a**2-b**2)*sin(u)**2+2*a*b*cos(u)*sin(u)))))
u, a, b, x = args
t = Together(a)
if PureComplexNumberQ(t) or (ProductQ(t) and any(PureComplexNumberQ(i) for i in t.args)):
c = a/I
if NegativeQ(c):
return RectifyCotangent(u,-a,-b,x)
elif ZeroQ(c - 1):
if EvenQ(Denominator(NumericFactor(Together(u)))):
return -I*b*ArcTanh(Sin(2*u))/2
return -I*b*ArcTanh(2*Cos(u)*Sin(u))/2
e = SmartDenominator(c)
c = c*e
return -I*b*Log(RemoveContent(c*Cos(u)+e*Sin(u),x))/2 + I*b*Log(RemoveContent(c*Cos(u)-e*Sin(u),x))/2
elif NegativeQ(a):
return RectifyCotangent(u,-a,-b,x)
elif ZeroQ(a-1):
return b*SimplifyAntiderivative(u,x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
c = Simplify(a - 1)
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Cos(u)**2)))
c = Simplify(a/(1-a))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) + b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Sin(u)**2)))
def Inequality(*args):
f = args[1::2]
e = args[0::2]
r = []
for i in range(0, len(f)):
r.append(f[i](e[i], e[i + 1]))
return all(r)
def Condition(r, c):
# returns r if c is True
if c:
return r
else:
raise NotImplementedError('In Condition()')
def Simp(u, x):
u = replace_pow_exp(u)
return NormalizeSumFactors(SimpHelp(u, x))
def SimpHelp(u, x):
if AtomQ(u):
return u
elif FreeQ(u, x):
v = SmartSimplify(u)
if LeafCount(v) <= LeafCount(u):
return v
return u
elif ProductQ(u):
#m = MatchQ[Rest[u],a_.+n_*Pi+b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]]
#if EqQ(First(u), S(1)/2) and m:
# if
#If[EqQ[First[u],1/2] && MatchQ[Rest[u],a_.+n_*Pi+b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]],
# If[MatchQ[Rest[u],n_*Pi+b_.*v_ /; FreeQ[b,x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]],
# Map[Function[1/2*#],Rest[u]],
# If[MatchQ[Rest[u],m_*a_.+n_*Pi+p_*b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && IntegersQ[m/2,p/2]],
# Map[Function[1/2*#],Rest[u]],
# u]],
v = FreeFactors(u, x)
w = NonfreeFactors(u, x)
v = NumericFactor(v)*SmartSimplify(NonnumericFactors(v)*x**2)/x**2
if ProductQ(w):
w = Mul(*[SimpHelp(i,x) for i in w.args])
else:
w = SimpHelp(w, x)
w = FactorNumericGcd(w)
v = MergeFactors(v, w)
if ProductQ(v):
return Mul(*[SimpFixFactor(i, x) for i in v.args])
return v
elif SumQ(u):
Pi = pi
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
n_ = Wild('n', exclude=[x, 0, 0])
pattern = a_ + n_*Pi + b_*x
match = u.match(pattern)
m = False
if match:
if EqQ(match[n_]**3, S(1)/16):
m = True
if m:
return u
elif PolynomialQ(u, x) and Exponent(u, x)<=0:
return SimpHelp(Coefficient(u, x, 0), x)
elif PolynomialQ(u, x) and Exponent(u, x) == 1 and Coefficient(u, x, 0) == 0:
return SimpHelp(Coefficient(u, x, 1), x)*x
v = 0
w = 0
for i in u.args:
if FreeQ(i, x):
v = i + v
else:
w = i + w
v = SmartSimplify(v)
if SumQ(w):
w = Add(*[SimpHelp(i, x) for i in w.args])
else:
w = SimpHelp(w, x)
return v + w
return u.func(*[SimpHelp(i, x) for i in u.args])
def SplitProduct(func, u):
#(* If func[v] is True for a factor v of u, SplitProduct[func,u] returns {v, u/v} where v is the first such factor; else it returns False. *)
if ProductQ(u):
if func(First(u)):
return [First(u), Rest(u)]
lst = SplitProduct(func, Rest(u))
if AtomQ(lst):
return False
return [lst[0], First(u)*lst[1]]
if func(u):
return [u, 1]
return False
def SplitSum(func, u):
# (* If func[v] is nonatomic for a term v of u, SplitSum[func,u] returns {func[v], u-v} where v is the first such term; else it returns False. *)
if SumQ(u):
if Not(AtomQ(func(First(u)))):
return [func(First(u)), Rest(u)]
lst = SplitSum(func, Rest(u))
if AtomQ(lst):
return False
return [lst[0], First(u) + lst[1]]
elif Not(AtomQ(func(u))):
return [func(u), 0]
return False
def SubstFor(*args):
if len(args) == 4:
w, v, u, x = args
# u is a function of v. SubstFor(w,v,u,x) returns w times u with v replaced by x.
return SimplifyIntegrand(w*SubstFor(v, u, x), x)
v, u, x = args
# u is a function of v. SubstFor(v, u, x) returns u with v replaced by x.
if AtomQ(v):
return Subst(u, v, x)
elif Not(EqQ(FreeFactors(v, x), 1)):
return SubstFor(NonfreeFactors(v, x), u, x/FreeFactors(v, x))
elif SinQ(v):
return SubstForTrig(u, x, Sqrt(1 - x**2), v.args[0], x)
elif CosQ(v):
return SubstForTrig(u, Sqrt(1 - x**2), x, v.args[0], x)
elif TanQ(v):
return SubstForTrig(u, x/Sqrt(1 + x**2), 1/Sqrt(1 + x**2), v.args[0], x)
elif CotQ(v):
return SubstForTrig(u, 1/Sqrt(1 + x**2), x/Sqrt(1 + x**2), v.args[0], x)
elif SecQ(v):
return SubstForTrig(u, 1/Sqrt(1 - x**2), 1/x, v.args[0], x)
elif CscQ(v):
return SubstForTrig(u, 1/x, 1/Sqrt(1 - x**2), v.args[0], x)
elif SinhQ(v):
return SubstForHyperbolic(u, x, Sqrt(1 + x**2), v.args[0], x)
elif CoshQ(v):
return SubstForHyperbolic(u, Sqrt( - 1 + x**2), x, v.args[0], x)
elif TanhQ(v):
return SubstForHyperbolic(u, x/Sqrt(1 - x**2), 1/Sqrt(1 - x**2), v.args[0], x)
elif CothQ(v):
return SubstForHyperbolic(u, 1/Sqrt( - 1 + x**2), x/Sqrt( - 1 + x**2), v.args[0], x)
elif SechQ(v):
return SubstForHyperbolic(u, 1/Sqrt( - 1 + x**2), 1/x, v.args[0], x)
elif CschQ(v):
return SubstForHyperbolic(u, 1/x, 1/Sqrt(1 + x**2), v.args[0], x)
else:
return SubstForAux(u, v, x)
def SubstForAux(u, v, x):
# u is a function of v. SubstForAux(u, v, x) returns u with v replaced by x.
if u==v:
return x
elif AtomQ(u):
if PowerQ(v):
if FreeQ(v.exp, x) and ZeroQ(u - v.base):
return x**Simplify(1/v.exp)
return u
elif PowerQ(u):
if FreeQ(u.exp, x):
if ZeroQ(u.base - v):
return x**u.exp
if PowerQ(v):
if FreeQ(v.exp, x) and ZeroQ(u.base - v.base):
return x**Simplify(u.exp/v.exp)
return SubstForAux(u.base, v, x)**u.exp
elif ProductQ(u) and Not(EqQ(FreeFactors(u, x), 1)):
return FreeFactors(u, x)*SubstForAux(NonfreeFactors(u, x), v, x)
elif ProductQ(u) and ProductQ(v):
return SubstForAux(First(u), First(v), x)
return u.func(*[SubstForAux(i, v, x) for i in u.args])
def FresnelS(x):
return fresnels(x)
def FresnelC(x):
return fresnelc(x)
def Erf(x):
return erf(x)
def Erfc(x):
return erfc(x)
def Erfi(x):
return erfi(x)
class Gamma(Function):
@classmethod
def eval(cls,*args):
a = args[0]
if len(args) == 1:
return gamma(a)
else:
b = args[1]
if (NumericQ(a) and NumericQ(b)) or a == 1:
return uppergamma(a, b)
def FunctionOfTrigOfLinearQ(u, x):
# If u is an algebraic function of trig functions of a linear function of x,
# FunctionOfTrigOfLinearQ[u,x] returns True; else it returns False.
if FunctionOfTrig(u, None, x) and AlgebraicTrigFunctionQ(u, x) and FunctionOfLinear(FunctionOfTrig(u, None, x), x):
return True
else:
return False
def ElementaryFunctionQ(u):
# ElementaryExpressionQ[u] returns True if u is a sum, product, or power and all the operands
# are elementary expressions; or if u is a call on a trig, hyperbolic, or inverse function
# and all the arguments are elementary expressions; else it returns False.
if AtomQ(u):
return True
elif SumQ(u) or ProductQ(u) or PowerQ(u) or TrigQ(u) or HyperbolicQ(u) or InverseFunctionQ(u):
for i in u.args:
if not ElementaryFunctionQ(i):
return False
return True
return False
def Complex(a, b):
return a + I*b
def UnsameQ(a, b):
return a != b
@doctest_depends_on(modules=('matchpy',))
def _SimpFixFactor():
replacer = ManyToOneReplacer()
pattern1 = Pattern(UtilityOperator(Pow(Add(Mul(Complex(S(0), c_), WC('a', S(1))), Mul(Complex(S(0), d_), WC('b', S(1)))), WC('p', S(1))), x_), CustomConstraint(lambda p: IntegerQ(p)))
rule1 = ReplacementRule(pattern1, lambda b, c, x, a, p, d : Mul(Pow(I, p), SimpFixFactor(Pow(Add(Mul(a, c), Mul(b, d)), p), x)))
replacer.add(rule1)
pattern2 = Pattern(UtilityOperator(Pow(Add(Mul(Complex(S(0), d_), WC('a', S(1))), Mul(Complex(S(0), e_), WC('b', S(1))), Mul(Complex(S(0), f_), WC('c', S(1)))), WC('p', S(1))), x_), CustomConstraint(lambda p: IntegerQ(p)))
rule2 = ReplacementRule(pattern2, lambda b, c, x, f, a, p, e, d : Mul(Pow(I, p), SimpFixFactor(Pow(Add(Mul(a, d), Mul(b, e), Mul(c, f)), p), x)))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, r_)), Mul(WC('b', S(1)), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda c: AtomQ(c)), CustomConstraint(lambda r: RationalQ(r)), CustomConstraint(lambda r: Less(r, S(0))))
rule3 = ReplacementRule(pattern3, lambda b, c, r, n, x, a, p : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(a, Mul(Mul(b, Pow(Pow(c, r), S(-1))), Pow(x, n))), p), x)))
replacer.add(rule3)
pattern4 = Pattern(UtilityOperator(Pow(Add(WC('a', S(0)), Mul(WC('b', S(1)), Pow(c_, r_), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda c: AtomQ(c)), CustomConstraint(lambda r: RationalQ(r)), CustomConstraint(lambda r: Less(r, S(0))))
rule4 = ReplacementRule(pattern4, lambda b, c, r, n, x, a, p : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(Mul(a, Pow(Pow(c, r), S(-1))), Mul(b, Pow(x, n))), p), x)))
replacer.add(rule4)
pattern5 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, WC('s', S(1)))), Mul(WC('b', S(1)), Pow(c_, WC('r', S(1))), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda r, s: RationalQ(s, r)), CustomConstraint(lambda r, s: Inequality(S(0), Less, s, LessEqual, r)), CustomConstraint(lambda p, c, s: UnsameQ(Pow(c, Mul(s, p)), S(-1))))
rule5 = ReplacementRule(pattern5, lambda b, c, r, n, x, a, p, s : Mul(Pow(c, Mul(s, p)), SimpFixFactor(Pow(Add(a, Mul(b, Pow(c, Add(r, Mul(S(-1), s))), Pow(x, n))), p), x)))
replacer.add(rule5)
pattern6 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, WC('s', S(1)))), Mul(WC('b', S(1)), Pow(c_, WC('r', S(1))), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda r, s: RationalQ(s, r)), CustomConstraint(lambda s, r: Less(S(0), r, s)), CustomConstraint(lambda p, c, r: UnsameQ(Pow(c, Mul(r, p)), S(-1))))
rule6 = ReplacementRule(pattern6, lambda b, c, r, n, x, a, p, s : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(Mul(a, Pow(c, Add(s, Mul(S(-1), r)))), Mul(b, Pow(x, n))), p), x)))
replacer.add(rule6)
return replacer
@doctest_depends_on(modules=('matchpy',))
def SimpFixFactor(expr, x):
r = SimpFixFactor_replacer.replace(UtilityOperator(expr, x))
if isinstance(r, UtilityOperator):
return expr
return r
@doctest_depends_on(modules=('matchpy',))
def _FixSimplify():
Plus = Add
def cons_f1(n):
return OddQ(n)
cons1 = CustomConstraint(cons_f1)
def cons_f2(m):
return RationalQ(m)
cons2 = CustomConstraint(cons_f2)
def cons_f3(n):
return FractionQ(n)
cons3 = CustomConstraint(cons_f3)
def cons_f4(u):
return SqrtNumberSumQ(u)
cons4 = CustomConstraint(cons_f4)
def cons_f5(v):
return SqrtNumberSumQ(v)
cons5 = CustomConstraint(cons_f5)
def cons_f6(u):
return PositiveQ(u)
cons6 = CustomConstraint(cons_f6)
def cons_f7(v):
return PositiveQ(v)
cons7 = CustomConstraint(cons_f7)
def cons_f8(v):
return SqrtNumberSumQ(S(1)/v)
cons8 = CustomConstraint(cons_f8)
def cons_f9(m):
return IntegerQ(m)
cons9 = CustomConstraint(cons_f9)
def cons_f10(u):
return NegativeQ(u)
cons10 = CustomConstraint(cons_f10)
def cons_f11(n, m, a, b):
return RationalQ(a, b, m, n)
cons11 = CustomConstraint(cons_f11)
def cons_f12(a):
return Greater(a, S(0))
cons12 = CustomConstraint(cons_f12)
def cons_f13(b):
return Greater(b, S(0))
cons13 = CustomConstraint(cons_f13)
def cons_f14(p):
return PositiveIntegerQ(p)
cons14 = CustomConstraint(cons_f14)
def cons_f15(p):
return IntegerQ(p)
cons15 = CustomConstraint(cons_f15)
def cons_f16(p, n):
return Greater(-n + p, S(0))
cons16 = CustomConstraint(cons_f16)
def cons_f17(a, b):
return SameQ(a + b, S(0))
cons17 = CustomConstraint(cons_f17)
def cons_f18(n):
return Not(IntegerQ(n))
cons18 = CustomConstraint(cons_f18)
def cons_f19(c, a, b, d):
return ZeroQ(-a*d + b*c)
cons19 = CustomConstraint(cons_f19)
def cons_f20(a):
return Not(RationalQ(a))
cons20 = CustomConstraint(cons_f20)
def cons_f21(t):
return IntegerQ(t)
cons21 = CustomConstraint(cons_f21)
def cons_f22(n, m):
return RationalQ(m, n)
cons22 = CustomConstraint(cons_f22)
def cons_f23(n, m):
return Inequality(S(0), Less, m, LessEqual, n)
cons23 = CustomConstraint(cons_f23)
def cons_f24(p, n, m):
return RationalQ(m, n, p)
cons24 = CustomConstraint(cons_f24)
def cons_f25(p, n, m):
return Inequality(S(0), Less, m, LessEqual, n, LessEqual, p)
cons25 = CustomConstraint(cons_f25)
def cons_f26(p, n, m, q):
return Inequality(S(0), Less, m, LessEqual, n, LessEqual, p, LessEqual, q)
cons26 = CustomConstraint(cons_f26)
def cons_f27(w):
return Not(RationalQ(w))
cons27 = CustomConstraint(cons_f27)
def cons_f28(n):
return Less(n, S(0))
cons28 = CustomConstraint(cons_f28)
def cons_f29(n, w, v):
return ZeroQ(v + w**(-n))
cons29 = CustomConstraint(cons_f29)
def cons_f30(n):
return IntegerQ(n)
cons30 = CustomConstraint(cons_f30)
def cons_f31(w, v):
return ZeroQ(v + w)
cons31 = CustomConstraint(cons_f31)
def cons_f32(p, n):
return IntegerQ(n/p)
cons32 = CustomConstraint(cons_f32)
def cons_f33(w, v):
return ZeroQ(v - w)
cons33 = CustomConstraint(cons_f33)
def cons_f34(p, n):
return IntegersQ(n, n/p)
cons34 = CustomConstraint(cons_f34)
def cons_f35(a):
return AtomQ(a)
cons35 = CustomConstraint(cons_f35)
def cons_f36(b):
return AtomQ(b)
cons36 = CustomConstraint(cons_f36)
pattern1 = Pattern(UtilityOperator((w_ + Complex(S(0), b_)*WC('v', S(1)))**WC('n', S(1))*Complex(S(0), a_)*WC('u', S(1))), cons1)
def replacement1(n, u, w, v, a, b):
return (S(-1))**(n/S(2) + S(1)/2)*a*u*FixSimplify((b*v - w*Complex(S(0), S(1)))**n)
rule1 = ReplacementRule(pattern1, replacement1)
def With2(m, n, u, w, v):
z = u**(m/GCD(m, n))*v**(n/GCD(m, n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern2 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons2, cons3, cons4, cons5, cons6, cons7, CustomConstraint(With2))
def replacement2(m, n, u, w, v):
z = u**(m/GCD(m, n))*v**(n/GCD(m, n))
return FixSimplify(w*z**GCD(m, n))
rule2 = ReplacementRule(pattern2, replacement2)
def With3(m, n, u, w, v):
z = u**(m/GCD(m, -n))*v**(n/GCD(m, -n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern3 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons2, cons3, cons4, cons8, cons6, cons7, CustomConstraint(With3))
def replacement3(m, n, u, w, v):
z = u**(m/GCD(m, -n))*v**(n/GCD(m, -n))
return FixSimplify(w*z**GCD(m, -n))
rule3 = ReplacementRule(pattern3, replacement3)
def With4(m, n, u, w, v):
z = v**(n/GCD(m, n))*(-u)**(m/GCD(m, n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern4 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons9, cons3, cons4, cons5, cons10, cons7, CustomConstraint(With4))
def replacement4(m, n, u, w, v):
z = v**(n/GCD(m, n))*(-u)**(m/GCD(m, n))
return FixSimplify(-w*z**GCD(m, n))
rule4 = ReplacementRule(pattern4, replacement4)
def With5(m, n, u, w, v):
z = v**(n/GCD(m, -n))*(-u)**(m/GCD(m, -n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern5 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons9, cons3, cons4, cons8, cons10, cons7, CustomConstraint(With5))
def replacement5(m, n, u, w, v):
z = v**(n/GCD(m, -n))*(-u)**(m/GCD(m, -n))
return FixSimplify(-w*z**GCD(m, -n))
rule5 = ReplacementRule(pattern5, replacement5)
def With6(p, m, n, u, w, v, a, b):
c = a**(m/p)*b**n
if RationalQ(c):
return True
return False
pattern6 = Pattern(UtilityOperator(a_**m_*(b_**n_*WC('v', S(1)) + u_)**WC('p', S(1))*WC('w', S(1))), cons11, cons12, cons13, cons14, CustomConstraint(With6))
def replacement6(p, m, n, u, w, v, a, b):
c = a**(m/p)*b**n
return FixSimplify(w*(a**(m/p)*u + c*v)**p)
rule6 = ReplacementRule(pattern6, replacement6)
pattern7 = Pattern(UtilityOperator(a_**WC('m', S(1))*(a_**n_*WC('u', S(1)) + b_**WC('p', S(1))*WC('v', S(1)))*WC('w', S(1))), cons2, cons3, cons15, cons16, cons17)
def replacement7(p, m, n, u, w, v, a, b):
return FixSimplify(a**(m + n)*w*((S(-1))**p*a**(-n + p)*v + u))
rule7 = ReplacementRule(pattern7, replacement7)
def With8(m, d, n, w, c, a, b):
q = b/d
if FreeQ(q, Plus):
return True
return False
pattern8 = Pattern(UtilityOperator((a_ + b_)**WC('m', S(1))*(c_ + d_)**n_*WC('w', S(1))), cons9, cons18, cons19, CustomConstraint(With8))
def replacement8(m, d, n, w, c, a, b):
q = b/d
return FixSimplify(q**m*w*(c + d)**(m + n))
rule8 = ReplacementRule(pattern8, replacement8)
pattern9 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons22, cons23)
def replacement9(m, n, u, w, v, a, t):
return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + u)**t)
rule9 = ReplacementRule(pattern9, replacement9)
pattern10 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('z', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons24, cons25)
def replacement10(p, m, n, u, w, v, a, z, t):
return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + a**(-m + p)*z + u)**t)
rule10 = ReplacementRule(pattern10, replacement10)
pattern11 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('z', S(1)) + a_**WC('q', S(1))*WC('y', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons24, cons26)
def replacement11(p, m, n, u, q, w, v, a, z, y, t):
return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + a**(-m + p)*z + a**(-m + q)*y + u)**t)
rule11 = ReplacementRule(pattern11, replacement11)
pattern12 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('c', S(1)) + sqrt(v_)*WC('d', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1))))
def replacement12(d, u, w, v, c, a, b):
return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b + c + d)))
rule12 = ReplacementRule(pattern12, replacement12)
pattern13 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('c', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1))))
def replacement13(u, w, v, c, a, b):
return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b + c)))
rule13 = ReplacementRule(pattern13, replacement13)
pattern14 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1))))
def replacement14(u, w, v, a, b):
return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b)))
rule14 = ReplacementRule(pattern14, replacement14)
pattern15 = Pattern(UtilityOperator(v_**m_*w_**n_*WC('u', S(1))), cons2, cons27, cons3, cons28, cons29)
def replacement15(m, n, u, w, v):
return -FixSimplify(u*v**(m + S(-1)))
rule15 = ReplacementRule(pattern15, replacement15)
pattern16 = Pattern(UtilityOperator(v_**m_*w_**WC('n', S(1))*WC('u', S(1))), cons2, cons27, cons30, cons31)
def replacement16(m, n, u, w, v):
return (S(-1))**n*FixSimplify(u*v**(m + n))
rule16 = ReplacementRule(pattern16, replacement16)
pattern17 = Pattern(UtilityOperator(w_**WC('n', S(1))*(-v_**WC('p', S(1)))**m_*WC('u', S(1))), cons2, cons27, cons32, cons33)
def replacement17(p, m, n, u, w, v):
return (S(-1))**(n/p)*FixSimplify(u*(-v**p)**(m + n/p))
rule17 = ReplacementRule(pattern17, replacement17)
pattern18 = Pattern(UtilityOperator(w_**WC('n', S(1))*(-v_**WC('p', S(1)))**m_*WC('u', S(1))), cons2, cons27, cons34, cons31)
def replacement18(p, m, n, u, w, v):
return (S(-1))**(n + n/p)*FixSimplify(u*(-v**p)**(m + n/p))
rule18 = ReplacementRule(pattern18, replacement18)
pattern19 = Pattern(UtilityOperator((a_ - b_)**WC('m', S(1))*(a_ + b_)**WC('m', S(1))*WC('u', S(1))), cons9, cons35, cons36)
def replacement19(m, u, a, b):
return u*(a**S(2) - b**S(2))**m
rule19 = ReplacementRule(pattern19, replacement19)
pattern20 = Pattern(UtilityOperator((S(729)*c - e*(-S(20)*e + S(540)))**WC('m', S(1))*WC('u', S(1))), cons2)
def replacement20(m, u):
return u*(a*e**S(2) - b*d*e + c*d**S(2))**m
rule20 = ReplacementRule(pattern20, replacement20)
pattern21 = Pattern(UtilityOperator((S(729)*c + e*(S(20)*e + S(-540)))**WC('m', S(1))*WC('u', S(1))), cons2)
def replacement21(m, u):
return u*(a*e**S(2) - b*d*e + c*d**S(2))**m
rule21 = ReplacementRule(pattern21, replacement21)
pattern22 = Pattern(UtilityOperator(u_))
def replacement22(u):
return u
rule22 = ReplacementRule(pattern22, replacement22)
return [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, ]
@doctest_depends_on(modules=('matchpy',))
def FixSimplify(expr):
if isinstance(expr, (list, tuple, TupleArg)):
return [replace_all(UtilityOperator(i), FixSimplify_rules) for i in expr]
return replace_all(UtilityOperator(expr), FixSimplify_rules)
@doctest_depends_on(modules=('matchpy',))
def _SimplifyAntiderivativeSum():
replacer = ManyToOneReplacer()
pattern1 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Cos(u_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, n: ZeroQ(Add(Mul(n, A), Mul(S(1), B)))))
rule1 = ReplacementRule(pattern1, lambda n, x, v, b, B, A, u, a : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x)))))
replacer.add(rule1)
pattern2 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Sin(u_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, n: ZeroQ(Add(Mul(n, A), Mul(S(1), B)))))
rule2 = ReplacementRule(pattern2, lambda n, x, v, b, B, A, a, u : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Sin(u), n)), Mul(b, Pow(Cos(u), n))), x)))))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Add(c_, Mul(WC('d', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A: ZeroQ(Add(A, B))))
rule3 = ReplacementRule(pattern3, lambda n, x, v, b, A, B, u, c, d, a : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(c, Pow(Cos(u), n)), Mul(d, Pow(Sin(u), n))), x)))))
replacer.add(rule3)
pattern4 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('d', S(1))), c_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A: ZeroQ(Add(A, B))))
rule4 = ReplacementRule(pattern4, lambda n, x, v, b, A, B, c, a, d, u : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(b, Pow(Cos(u), n)), Mul(a, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(d, Pow(Cos(u), n)), Mul(c, Pow(Sin(u), n))), x)))))
replacer.add(rule4)
pattern5 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Add(c_, Mul(WC('d', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('B', S(1))), Mul(Log(Add(e_, Mul(WC('f', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('C', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda e, x: FreeQ(e, x)), CustomConstraint(lambda f, x: FreeQ(f, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda C, x: FreeQ(C, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, C: ZeroQ(Add(A, B, C))))
rule5 = ReplacementRule(pattern5, lambda n, e, x, v, b, A, B, u, c, f, d, a, C : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(c, Pow(Cos(u), n)), Mul(d, Pow(Sin(u), n))), x))), Mul(C, Log(RemoveContent(Add(Mul(e, Pow(Cos(u), n)), Mul(f, Pow(Sin(u), n))), x)))))
replacer.add(rule5)
pattern6 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('d', S(1))), c_)), WC('B', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('f', S(1))), e_)), WC('C', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda e, x: FreeQ(e, x)), CustomConstraint(lambda f, x: FreeQ(f, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda C, x: FreeQ(C, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, C: ZeroQ(Add(A, B, C))))
rule6 = ReplacementRule(pattern6, lambda n, e, x, v, b, A, B, c, a, f, d, u, C : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(b, Pow(Cos(u), n)), Mul(a, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(d, Pow(Cos(u), n)), Mul(c, Pow(Sin(u), n))), x))), Mul(C, Log(RemoveContent(Add(Mul(f, Pow(Cos(u), n)), Mul(e, Pow(Sin(u), n))), x)))))
replacer.add(rule6)
return replacer
@doctest_depends_on(modules=('matchpy',))
def SimplifyAntiderivativeSum(expr, x):
r = SimplifyAntiderivativeSum_replacer.replace(UtilityOperator(expr, x))
if isinstance(r, UtilityOperator):
return expr
return r
@doctest_depends_on(modules=('matchpy',))
def _SimplifyAntiderivative():
replacer = ManyToOneReplacer()
pattern2 = Pattern(UtilityOperator(Log(Mul(c_, u_)), x_), CustomConstraint(lambda c, x: FreeQ(c, x)))
rule2 = ReplacementRule(pattern2, lambda x, c, u : SimplifyAntiderivative(Log(u), x))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Log(Pow(u_, n_)), x_), CustomConstraint(lambda n, x: FreeQ(n, x)))
rule3 = ReplacementRule(pattern3, lambda x, n, u : Mul(n, SimplifyAntiderivative(Log(u), x)))
replacer.add(rule3)
pattern7 = Pattern(UtilityOperator(Log(Pow(f_, u_)), x_), CustomConstraint(lambda f, x: FreeQ(f, x)))
rule7 = ReplacementRule(pattern7, lambda x, f, u : Mul(Log(f), SimplifyAntiderivative(u, x)))
replacer.add(rule7)
pattern8 = Pattern(UtilityOperator(Log(Add(a_, Mul(WC('b', S(1)), Tan(u_)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S(2)), Pow(b, S(2))))))
rule8 = ReplacementRule(pattern8, lambda x, b, u, a : Add(Mul(Mul(b, Pow(a, S(1))), SimplifyAntiderivative(u, x)), Mul(S(1), SimplifyAntiderivative(Log(Cos(u)), x))))
replacer.add(rule8)
pattern9 = Pattern(UtilityOperator(Log(Add(Mul(Cot(u_), WC('b', S(1))), a_)), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S(2)), Pow(b, S(2))))))
rule9 = ReplacementRule(pattern9, lambda x, b, u, a : Add(Mul(Mul(Mul(S(1), b), Pow(a, S(1))), SimplifyAntiderivative(u, x)), Mul(S(1), SimplifyAntiderivative(Log(Sin(u)), x))))
replacer.add(rule9)
pattern10 = Pattern(UtilityOperator(ArcTan(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule10 = ReplacementRule(pattern10, lambda x, u, a : RectifyTangent(u, a, S(1), x))
replacer.add(rule10)
pattern11 = Pattern(UtilityOperator(ArcCot(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule11 = ReplacementRule(pattern11, lambda x, u, a : RectifyTangent(u, a, S(1), x))
replacer.add(rule11)
pattern12 = Pattern(UtilityOperator(ArcCot(Mul(WC('a', S(1)), Tanh(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule12 = ReplacementRule(pattern12, lambda x, u, a : Mul(S(1), SimplifyAntiderivative(ArcTan(Mul(a, Tanh(u))), x)))
replacer.add(rule12)
pattern13 = Pattern(UtilityOperator(ArcTanh(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule13 = ReplacementRule(pattern13, lambda x, u, a : RectifyTangent(u, Mul(I, a), Mul(S(1), I), x))
replacer.add(rule13)
pattern14 = Pattern(UtilityOperator(ArcCoth(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule14 = ReplacementRule(pattern14, lambda x, u, a : RectifyTangent(u, Mul(I, a), Mul(S(1), I), x))
replacer.add(rule14)
pattern15 = Pattern(UtilityOperator(ArcTanh(Tanh(u_)), x_))
rule15 = ReplacementRule(pattern15, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule15)
pattern16 = Pattern(UtilityOperator(ArcCoth(Tanh(u_)), x_))
rule16 = ReplacementRule(pattern16, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule16)
pattern17 = Pattern(UtilityOperator(ArcCot(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule17 = ReplacementRule(pattern17, lambda x, u, a : RectifyCotangent(u, a, S(1), x))
replacer.add(rule17)
pattern18 = Pattern(UtilityOperator(ArcTan(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule18 = ReplacementRule(pattern18, lambda x, u, a : RectifyCotangent(u, a, S(1), x))
replacer.add(rule18)
pattern19 = Pattern(UtilityOperator(ArcTan(Mul(Coth(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule19 = ReplacementRule(pattern19, lambda x, u, a : Mul(S(1), SimplifyAntiderivative(ArcTan(Mul(Tanh(u), Pow(a, S(1)))), x)))
replacer.add(rule19)
pattern20 = Pattern(UtilityOperator(ArcCoth(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule20 = ReplacementRule(pattern20, lambda x, u, a : RectifyCotangent(u, Mul(I, a), I, x))
replacer.add(rule20)
pattern21 = Pattern(UtilityOperator(ArcTanh(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule21 = ReplacementRule(pattern21, lambda x, u, a : RectifyCotangent(u, Mul(I, a), I, x))
replacer.add(rule21)
pattern22 = Pattern(UtilityOperator(ArcCoth(Coth(u_)), x_))
rule22 = ReplacementRule(pattern22, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule22)
pattern23 = Pattern(UtilityOperator(ArcTanh(Mul(Coth(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule23 = ReplacementRule(pattern23, lambda x, u, a : SimplifyAntiderivative(ArcTanh(Mul(Tanh(u), Pow(a, S(1)))), x))
replacer.add(rule23)
pattern24 = Pattern(UtilityOperator(ArcTanh(Coth(u_)), x_))
rule24 = ReplacementRule(pattern24, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule24)
pattern25 = Pattern(UtilityOperator(ArcTan(Mul(WC('c', S(1)), Add(a_, Mul(WC('b', S(1)), Tan(u_))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule25 = ReplacementRule(pattern25, lambda x, a, b, u, c : RectifyTangent(u, Mul(a, c), Mul(b, c), S(1), x))
replacer.add(rule25)
pattern26 = Pattern(UtilityOperator(ArcTanh(Mul(WC('c', S(1)), Add(a_, Mul(WC('b', S(1)), Tan(u_))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule26 = ReplacementRule(pattern26, lambda x, a, b, u, c : RectifyTangent(u, Mul(I, a, c), Mul(I, b, c), Mul(S(1), I), x))
replacer.add(rule26)
pattern27 = Pattern(UtilityOperator(ArcTan(Mul(WC('c', S(1)), Add(Mul(Cot(u_), WC('b', S(1))), a_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule27 = ReplacementRule(pattern27, lambda x, a, b, u, c : RectifyCotangent(u, Mul(a, c), Mul(b, c), S(1), x))
replacer.add(rule27)
pattern28 = Pattern(UtilityOperator(ArcTanh(Mul(WC('c', S(1)), Add(Mul(Cot(u_), WC('b', S(1))), a_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule28 = ReplacementRule(pattern28, lambda x, a, b, u, c : RectifyCotangent(u, Mul(I, a, c), Mul(I, b, c), Mul(S(1), I), x))
replacer.add(rule28)
pattern29 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('b', S(1)), Tan(u_)), Mul(WC('c', S(1)), Pow(Tan(u_), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule29 = ReplacementRule(pattern29, lambda x, a, b, u, c : If(EvenQ(Denominator(NumericFactor(Together(u)))), ArcTan(NormalizeTogether(Mul(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u))), Mul(b, Sin(Mul(S(2), u)))), Pow(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u))), Mul(b, Sin(Mul(S(2), u)))), S(1))))), ArcTan(NormalizeTogether(Mul(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2))), Mul(b, Cos(u), Sin(u))), Pow(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2))), Mul(b, Cos(u), Sin(u))), S(1)))))))
replacer.add(rule29)
pattern30 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('b', S(1)), Add(WC('d', S(0)), Mul(WC('e', S(1)), Tan(u_)))), Mul(WC('c', S(1)), Pow(Add(WC('f', S(0)), Mul(WC('g', S(1)), Tan(u_))), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule30 = ReplacementRule(pattern30, lambda x, d, a, e, f, b, u, c, g : SimplifyAntiderivative(ArcTan(Add(a, Mul(b, d), Mul(c, Pow(f, S(2))), Mul(Add(Mul(b, e), Mul(S(2), c, f, g)), Tan(u)), Mul(c, Pow(g, S(2)), Pow(Tan(u), S(2))))), x))
replacer.add(rule30)
pattern31 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(Tan(u_), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule31 = ReplacementRule(pattern31, lambda x, c, u, a : If(EvenQ(Denominator(NumericFactor(Together(u)))), ArcTan(NormalizeTogether(Mul(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u)))), Pow(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u)))), S(1))))), ArcTan(NormalizeTogether(Mul(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2)))), Pow(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2)))), S(1)))))))
replacer.add(rule31)
pattern32 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(Add(WC('f', S(0)), Mul(WC('g', S(1)), Tan(u_))), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule32 = ReplacementRule(pattern32, lambda x, a, f, u, c, g : SimplifyAntiderivative(ArcTan(Add(a, Mul(c, Pow(f, S(2))), Mul(Mul(S(2), c, f, g), Tan(u)), Mul(c, Pow(g, S(2)), Pow(Tan(u), S(2))))), x))
replacer.add(rule32)
return replacer
@doctest_depends_on(modules=('matchpy',))
def SimplifyAntiderivative(expr, x):
r = SimplifyAntiderivative_replacer.replace(UtilityOperator(expr, x))
if isinstance(r, UtilityOperator):
if ProductQ(expr):
u, c = S(1), S(1)
for i in expr.args:
if FreeQ(i, x):
c *= i
else:
u *= i
if FreeQ(c, x) and c != S(1):
v = SimplifyAntiderivative(u, x)
if SumQ(v) and NonsumQ(u):
return Add(*[c*i for i in v.args])
return c*v
elif LogQ(expr):
F = expr.args[0]
if MemberQ([cot, sec, csc, coth, sech, csch], Head(F)):
return -SimplifyAntiderivative(Log(1/F), x)
if MemberQ([Log, atan, acot], Head(expr)):
F = Head(expr)
G = expr.args[0]
if MemberQ([cot, sec, csc, coth, sech, csch], Head(G)):
return -SimplifyAntiderivative(F(1/G), x)
if MemberQ([atanh, acoth], Head(expr)):
F = Head(expr)
G = expr.args[0]
if MemberQ([cot, sec, csc, coth, sech, csch], Head(G)):
return SimplifyAntiderivative(F(1/G), x)
u = expr
if FreeQ(u, x):
return S(0)
elif LogQ(u):
return Log(RemoveContent(u.args[0], x))
elif SumQ(u):
return SimplifyAntiderivativeSum(Add(*[SimplifyAntiderivative(i, x) for i in u.args]), x)
return u
else:
return r
@doctest_depends_on(modules=('matchpy',))
def _TrigSimplifyAux():
replacer = ManyToOneReplacer()
pattern1 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('a', S(1)), Pow(v_, WC('m', S(1)))), Mul(WC('b', S(1)), Pow(v_, WC('n', S(1))))), p_))), CustomConstraint(lambda v: InertTrigQ(v)), CustomConstraint(lambda p: IntegerQ(p)), CustomConstraint(lambda n, m: RationalQ(m, n)), CustomConstraint(lambda n, m: Less(m, n)))
rule1 = ReplacementRule(pattern1, lambda n, a, p, m, u, v, b : Mul(u, Pow(v, Mul(m, p)), Pow(TrigSimplifyAux(Add(a, Mul(b, Pow(v, Add(n, Mul(S(-1), m)))))), p)))
replacer.add(rule1)
pattern2 = Pattern(UtilityOperator(Add(Mul(Pow(cos(u_), S('2')), WC('a', S(1))), WC('v', S(0)), Mul(WC('b', S(1)), Pow(sin(u_), S('2'))))), CustomConstraint(lambda b, a: SameQ(a, b)))
rule2 = ReplacementRule(pattern2, lambda u, v, b, a : Add(a, v))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Add(WC('v', S(0)), Mul(WC('a', S(1)), Pow(sec(u_), S('2'))), Mul(WC('b', S(1)), Pow(tan(u_), S('2'))))), CustomConstraint(lambda b, a: SameQ(a, Mul(S(-1), b))))
rule3 = ReplacementRule(pattern3, lambda u, v, b, a : Add(a, v))
replacer.add(rule3)
pattern4 = Pattern(UtilityOperator(Add(Mul(Pow(csc(u_), S('2')), WC('a', S(1))), Mul(Pow(cot(u_), S('2')), WC('b', S(1))), WC('v', S(0)))), CustomConstraint(lambda b, a: SameQ(a, Mul(S(-1), b))))
rule4 = ReplacementRule(pattern4, lambda u, v, b, a : Add(a, v))
replacer.add(rule4)
pattern5 = Pattern(UtilityOperator(Pow(Add(Mul(Pow(cos(u_), S('2')), WC('a', S(1))), WC('v', S(0)), Mul(WC('b', S(1)), Pow(sin(u_), S('2')))), n_)))
rule5 = ReplacementRule(pattern5, lambda n, a, u, v, b : Pow(Add(Mul(Add(b, Mul(S(-1), a)), Pow(Sin(u), S('2'))), a, v), n))
replacer.add(rule5)
pattern6 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(sin(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule6 = ReplacementRule(pattern6, lambda u, w, z, v : Add(Mul(u, Pow(Cos(z), S('2'))), w))
replacer.add(rule6)
pattern7 = Pattern(UtilityOperator(Add(Mul(Pow(cos(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule7 = ReplacementRule(pattern7, lambda z, w, v, u : Add(Mul(u, Pow(Sin(z), S('2'))), w))
replacer.add(rule7)
pattern8 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(tan(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, v)))
rule8 = ReplacementRule(pattern8, lambda u, w, z, v : Add(Mul(u, Pow(Sec(z), S('2'))), w))
replacer.add(rule8)
pattern9 = Pattern(UtilityOperator(Add(Mul(Pow(cot(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, v)))
rule9 = ReplacementRule(pattern9, lambda z, w, v, u : Add(Mul(u, Pow(Csc(z), S('2'))), w))
replacer.add(rule9)
pattern10 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(sec(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule10 = ReplacementRule(pattern10, lambda u, w, z, v : Add(Mul(v, Pow(Tan(z), S('2'))), w))
replacer.add(rule10)
pattern11 = Pattern(UtilityOperator(Add(Mul(Pow(csc(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule11 = ReplacementRule(pattern11, lambda z, w, v, u : Add(Mul(v, Pow(Cot(z), S('2'))), w))
replacer.add(rule11)
pattern12 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(cos(v_), WC('b', S(1))), a_), S(-1)), Pow(sin(v_), S('2')))), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S('2')), Mul(S(-1), Pow(b, S('2')))))))
rule12 = ReplacementRule(pattern12, lambda u, v, b, a : Mul(u, Add(Mul(S(1), Pow(a, S(-1))), Mul(S(-1), Mul(Cos(v), Pow(b, S(-1)))))))
replacer.add(rule12)
pattern13 = Pattern(UtilityOperator(Mul(Pow(cos(v_), S('2')), WC('u', S(1)), Pow(Add(a_, Mul(WC('b', S(1)), sin(v_))), S(-1)))), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S('2')), Mul(S(-1), Pow(b, S('2')))))))
rule13 = ReplacementRule(pattern13, lambda u, v, b, a : Mul(u, Add(Mul(S(1), Pow(a, S(-1))), Mul(S(-1), Mul(Sin(v), Pow(b, S(-1)))))))
replacer.add(rule13)
pattern14 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(tan(v_), WC('n', S(1))), Pow(Add(a_, Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule14 = ReplacementRule(pattern14, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Cot(v), n))), S(-1))))
replacer.add(rule14)
pattern15 = Pattern(UtilityOperator(Mul(Pow(cot(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule15 = ReplacementRule(pattern15, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Tan(v), n))), S(-1))))
replacer.add(rule15)
pattern16 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(sec(v_), WC('n', S(1))), Pow(Add(a_, Mul(WC('b', S(1)), Pow(sec(v_), WC('n', S(1))))), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule16 = ReplacementRule(pattern16, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Cos(v), n))), S(-1))))
replacer.add(rule16)
pattern17 = Pattern(UtilityOperator(Mul(Pow(csc(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule17 = ReplacementRule(pattern17, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Sin(v), n))), S(-1))))
replacer.add(rule17)
pattern18 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(a_, Mul(WC('b', S(1)), Pow(sec(v_), WC('n', S(1))))), S(-1)), Pow(tan(v_), WC('n', S(1))))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule18 = ReplacementRule(pattern18, lambda n, a, u, v, b : Mul(u, Mul(Pow(Sin(v), n), Pow(Add(b, Mul(a, Pow(Cos(v), n))), S(-1)))))
replacer.add(rule18)
pattern19 = Pattern(UtilityOperator(Mul(Pow(cot(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule19 = ReplacementRule(pattern19, lambda n, a, u, v, b : Mul(u, Mul(Pow(Cos(v), n), Pow(Add(b, Mul(a, Pow(Sin(v), n))), S(-1)))))
replacer.add(rule19)
pattern20 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('a', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule20 = ReplacementRule(pattern20, lambda n, a, p, u, v, b : Mul(u, Pow(Sec(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Sin(v), n))), p)))
replacer.add(rule20)
pattern21 = Pattern(UtilityOperator(Mul(Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('a', S(1))), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule21 = ReplacementRule(pattern21, lambda n, a, p, u, v, b : Mul(u, Pow(Csc(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Cos(v), n))), p)))
replacer.add(rule21)
pattern22 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('b', S(1)), Pow(sin(v_), WC('n', S(1)))), Mul(WC('a', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule22 = ReplacementRule(pattern22, lambda n, a, p, u, v, b : Mul(u, Pow(Tan(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Cos(v), n))), p)))
replacer.add(rule22)
pattern23 = Pattern(UtilityOperator(Mul(Pow(Add(Mul(Pow(cot(v_), WC('n', S(1))), WC('a', S(1))), Mul(Pow(cos(v_), WC('n', S(1))), WC('b', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule23 = ReplacementRule(pattern23, lambda n, a, p, u, v, b : Mul(u, Pow(Cot(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Sin(v), n))), p)))
replacer.add(rule23)
pattern24 = Pattern(UtilityOperator(Mul(Pow(cos(v_), WC('m', S(1))), WC('u', S(1)), Pow(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule24 = ReplacementRule(pattern24, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Cos(v), Add(m, Mul(S(-1), Mul(n, p)))), Pow(Add(c, Mul(b, Pow(Sin(v), n)), Mul(a, Pow(Cos(v), n))), p)))
replacer.add(rule24)
pattern25 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(sec(v_), WC('m', S(1))), Pow(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule25 = ReplacementRule(pattern25, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Sec(v), Add(m, Mul(n, p))), Pow(Add(c, Mul(b, Pow(Sin(v), n)), Mul(a, Pow(Cos(v), n))), p)))
replacer.add(rule25)
pattern26 = Pattern(UtilityOperator(Mul(Pow(Add(WC('a', S(0)), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), Mul(Pow(csc(v_), WC('n', S(1))), WC('c', S(1)))), WC('p', S(1))), WC('u', S(1)), Pow(sin(v_), WC('m', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule26 = ReplacementRule(pattern26, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Sin(v), Add(m, Mul(S(-1), Mul(n, p)))), Pow(Add(c, Mul(b, Pow(Cos(v), n)), Mul(a, Pow(Sin(v), n))), p)))
replacer.add(rule26)
pattern27 = Pattern(UtilityOperator(Mul(Pow(csc(v_), WC('m', S(1))), Pow(Add(WC('a', S(0)), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), Mul(Pow(csc(v_), WC('n', S(1))), WC('c', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule27 = ReplacementRule(pattern27, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Csc(v), Add(m, Mul(n, p))), Pow(Add(c, Mul(b, Pow(Cos(v), n)), Mul(a, Pow(Sin(v), n))), p)))
replacer.add(rule27)
pattern28 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('m', S(1))), WC('a', S(1))), Mul(WC('b', S(1)), Pow(sin(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, m: IntegersQ(m, n)))
rule28 = ReplacementRule(pattern28, lambda n, a, p, m, u, v, b : If(And(ZeroQ(Add(m, n, S(-2))), ZeroQ(Add(a, b))), Mul(u, Pow(Mul(a, Mul(Pow(Cos(v), S('2')), Pow(Pow(Sin(v), m), S(-1)))), p)), Mul(u, Pow(Mul(Add(a, Mul(b, Pow(Sin(v), Add(m, n)))), Pow(Pow(Sin(v), m), S(-1))), p))))
replacer.add(rule28)
pattern29 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(Pow(cos(v_), WC('n', S(1))), WC('b', S(1))), Mul(WC('a', S(1)), Pow(sec(v_), WC('m', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, m: IntegersQ(m, n)))
rule29 = ReplacementRule(pattern29, lambda n, a, p, m, u, v, b : If(And(ZeroQ(Add(m, n, S(-2))), ZeroQ(Add(a, b))), Mul(u, Pow(Mul(a, Mul(Pow(Sin(v), S('2')), Pow(Pow(Cos(v), m), S(-1)))), p)), Mul(u, Pow(Mul(Add(a, Mul(b, Pow(Cos(v), Add(m, n)))), Pow(Pow(Cos(v), m), S(-1))), p))))
replacer.add(rule29)
pattern30 = Pattern(UtilityOperator(u_))
rule30 = ReplacementRule(pattern30, lambda u : u)
replacer.add(rule30)
return replacer
@doctest_depends_on(modules=('matchpy',))
def TrigSimplifyAux(expr):
return TrigSimplifyAux_replacer.replace(UtilityOperator(expr))
def Cancel(expr):
return cancel(expr)
class Util_Part(Function):
def doit(self):
i = Simplify(self.args[0])
if len(self.args) > 2 :
lst = list(self.args[1:])
else:
lst = self.args[1]
if isinstance(i, (int, Integer)):
if isinstance(lst, list):
return lst[i - 1]
elif AtomQ(lst):
return lst
return lst.args[i - 1]
else:
return self
def Part(lst, i): #see i = -1
if isinstance(lst, list):
return Util_Part(i, *lst).doit()
return Util_Part(i, lst).doit()
def PolyLog(n, p, z=None):
return polylog(n, p)
def D(f, x):
try:
return f.diff(x)
except ValueError:
return Function('D')(f, x)
def IntegralFreeQ(u):
return FreeQ(u, Integral)
def Dist(u, v, x):
#Dist(u,v) returns the sum of u times each term of v, provided v is free of Int
u = replace_pow_exp(u) # to replace back to sympy's exp
v = replace_pow_exp(v)
w = Simp(u*x**2, x)/x**2
if u == 1:
return v
elif u == 0:
return 0
elif NumericFactor(u) < 0 and NumericFactor(-u) > 0:
return -Dist(-u, v, x)
elif SumQ(v):
return Add(*[Dist(u, i, x) for i in v.args])
elif IntegralFreeQ(v):
return Simp(u*v, x)
elif w != u and FreeQ(w, x) and w == Simp(w, x) and w == Simp(w*x**2, x)/x**2:
return Dist(w, v, x)
else:
return Simp(u*v, x)
def PureFunctionOfCothQ(u, v, x):
# If u is a pure function of Coth[v], PureFunctionOfCothQ[u,v,x] returns True;
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return CothQ(u)
return all(PureFunctionOfCothQ(i, v, x) for i in u.args)
def LogIntegral(z):
return li(z)
def ExpIntegralEi(z):
return Ei(z)
def ExpIntegralE(a, b):
return expint(a, b).evalf()
def SinIntegral(z):
return Si(z)
def CosIntegral(z):
return Ci(z)
def SinhIntegral(z):
return Shi(z)
def CoshIntegral(z):
return Chi(z)
class PolyGamma(Function):
@classmethod
def eval(cls, *args):
if len(args) == 2:
return polygamma(args[0], args[1])
return digamma(args[0])
def LogGamma(z):
return loggamma(z)
class ProductLog(Function):
@classmethod
def eval(cls, *args):
if len(args) == 2:
return LambertW(args[1], args[0]).evalf()
return LambertW(args[0]).evalf()
def Factorial(a):
return factorial(a)
def Zeta(*args):
return zeta(*args)
def HypergeometricPFQ(a, b, c):
return hyper(a, b, c)
def Sum_doit(exp, args):
"""
This function perform summation using sympy's `Sum`.
Examples
========
>>> from sympy.integrals.rubi.utility_function import Sum_doit
>>> from sympy.abc import x
>>> Sum_doit(2*x + 2, [x, 0, 1.7])
6
"""
exp = replace_pow_exp(exp)
if not isinstance(args[2], (int, Integer)):
new_args = [args[0], args[1], Floor(args[2])]
return Sum(exp, new_args).doit()
return Sum(exp, args).doit()
def PolynomialQuotient(p, q, x):
try:
p = poly(p, x)
q = poly(q, x)
except:
p = poly(p)
q = poly(q)
try:
return quo(p, q).as_expr()
except (PolynomialDivisionFailed, UnificationFailed):
return p/q
def PolynomialRemainder(p, q, x):
try:
p = poly(p, x)
q = poly(q, x)
except:
p = poly(p)
q = poly(q)
try:
return rem(p, q).as_expr()
except (PolynomialDivisionFailed, UnificationFailed):
return S(0)
def Floor(x, a = None):
if a is None:
return floor(x)
return a*floor(x/a)
def Factor(var):
return factor(var)
def Rule(a, b):
return {a: b}
def Distribute(expr, *args):
if len(args) == 1:
if isinstance(expr, args[0]):
return expr
else:
return expr.expand()
if len(args) == 2:
if isinstance(expr, args[1]):
return expr.expand()
else:
return expr
return expr.expand()
def CoprimeQ(*args):
args = S(args)
g = gcd(*args)
if g == 1:
return True
return False
def Discriminant(a, b):
try:
return discriminant(a, b)
except PolynomialError:
return Function('Discriminant')(a, b)
def Negative(x):
return x < S(0)
def Quotient(m, n):
return Floor(m/n)
def process_trig(expr):
"""
This function processes trigonometric expressions such that all `cot` is
rewritten in terms of `tan`, `sec` in terms of `cos`, `csc` in terms of `sin` and
similarly for `coth`, `sech` and `csch`.
Examples
========
>>> from sympy.integrals.rubi.utility_function import process_trig
>>> from sympy.abc import x
>>> from sympy import coth, cot, csc
>>> process_trig(x*cot(x))
x/tan(x)
>>> process_trig(coth(x)*csc(x))
1/(sin(x)*tanh(x))
"""
expr = expr.replace(lambda x: isinstance(x, cot), lambda x: 1/tan(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, sec), lambda x: 1/cos(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, csc), lambda x: 1/sin(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, coth), lambda x: 1/tanh(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, sech), lambda x: 1/cosh(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, csch), lambda x: 1/sinh(x.args[0]))
return expr
def _ExpandIntegrand():
Plus = Add
Times = Mul
def cons_f1(m):
return PositiveIntegerQ(m)
cons1 = CustomConstraint(cons_f1)
def cons_f2(d, c, b, a):
return ZeroQ(-a*d + b*c)
cons2 = CustomConstraint(cons_f2)
def cons_f3(a, x):
return FreeQ(a, x)
cons3 = CustomConstraint(cons_f3)
def cons_f4(b, x):
return FreeQ(b, x)
cons4 = CustomConstraint(cons_f4)
def cons_f5(c, x):
return FreeQ(c, x)
cons5 = CustomConstraint(cons_f5)
def cons_f6(d, x):
return FreeQ(d, x)
cons6 = CustomConstraint(cons_f6)
def cons_f7(e, x):
return FreeQ(e, x)
cons7 = CustomConstraint(cons_f7)
def cons_f8(f, x):
return FreeQ(f, x)
cons8 = CustomConstraint(cons_f8)
def cons_f9(g, x):
return FreeQ(g, x)
cons9 = CustomConstraint(cons_f9)
def cons_f10(h, x):
return FreeQ(h, x)
cons10 = CustomConstraint(cons_f10)
def cons_f11(e, b, c, f, n, p, F, x, d, m):
if not isinstance(x, Symbol):
return False
return FreeQ(List(F, b, c, d, e, f, m, n, p), x)
cons11 = CustomConstraint(cons_f11)
def cons_f12(F, x):
return FreeQ(F, x)
cons12 = CustomConstraint(cons_f12)
def cons_f13(m, x):
return FreeQ(m, x)
cons13 = CustomConstraint(cons_f13)
def cons_f14(n, x):
return FreeQ(n, x)
cons14 = CustomConstraint(cons_f14)
def cons_f15(p, x):
return FreeQ(p, x)
cons15 = CustomConstraint(cons_f15)
def cons_f16(e, b, c, f, n, a, p, F, x, d, m):
if not isinstance(x, Symbol):
return False
return FreeQ(List(F, a, b, c, d, e, f, m, n, p), x)
cons16 = CustomConstraint(cons_f16)
def cons_f17(n, m):
return IntegersQ(m, n)
cons17 = CustomConstraint(cons_f17)
def cons_f18(n):
return Less(n, S(0))
cons18 = CustomConstraint(cons_f18)
def cons_f19(x, u):
if not isinstance(x, Symbol):
return False
return PolynomialQ(u, x)
cons19 = CustomConstraint(cons_f19)
def cons_f20(G, F, u):
return SameQ(F(u)*G(u), S(1))
cons20 = CustomConstraint(cons_f20)
def cons_f21(q, x):
return FreeQ(q, x)
cons21 = CustomConstraint(cons_f21)
def cons_f22(F):
return MemberQ(List(ArcSin, ArcCos, ArcSinh, ArcCosh), F)
cons22 = CustomConstraint(cons_f22)
def cons_f23(j, n):
return ZeroQ(j - S(2)*n)
cons23 = CustomConstraint(cons_f23)
def cons_f24(A, x):
return FreeQ(A, x)
cons24 = CustomConstraint(cons_f24)
def cons_f25(B, x):
return FreeQ(B, x)
cons25 = CustomConstraint(cons_f25)
def cons_f26(m, u, x):
if not isinstance(x, Symbol):
return False
def _cons_f_u(d, w, c, p, x):
return And(FreeQ(List(c, d), x), IntegerQ(p), Greater(p, m))
cons_u = CustomConstraint(_cons_f_u)
pat = Pattern(UtilityOperator((c_ + x_*WC('d', S(1)))**p_*WC('w', S(1)), x_), cons_u)
result_matchq = is_match(UtilityOperator(u, x), pat)
return Not(And(PositiveIntegerQ(m), result_matchq))
cons26 = CustomConstraint(cons_f26)
def cons_f27(b, v, n, a, x, u, m):
if not isinstance(x, Symbol):
return False
return And(FreeQ(List(a, b, m), x), NegativeIntegerQ(n), Not(IntegerQ(m)), PolynomialQ(u, x), PolynomialQ(v, x),\
RationalQ(m), Less(m, -1), GreaterEqual(Exponent(u, x), (-n - IntegerPart(m))*Exponent(v, x)))
cons27 = CustomConstraint(cons_f27)
def cons_f28(v, n, x, u, m):
if not isinstance(x, Symbol):
return False
return And(FreeQ(List(a, b, m), x), NegativeIntegerQ(n), Not(IntegerQ(m)), PolynomialQ(u, x),\
PolynomialQ(v, x), GreaterEqual(Exponent(u, x), -n*Exponent(v, x)))
cons28 = CustomConstraint(cons_f28)
def cons_f29(n):
return PositiveIntegerQ(n/S(4))
cons29 = CustomConstraint(cons_f29)
def cons_f30(n):
return IntegerQ(n)
cons30 = CustomConstraint(cons_f30)
def cons_f31(n):
return Greater(n, S(1))
cons31 = CustomConstraint(cons_f31)
def cons_f32(n, m):
return Less(S(0), m, n)
cons32 = CustomConstraint(cons_f32)
def cons_f33(n, m):
return OddQ(n/GCD(m, n))
cons33 = CustomConstraint(cons_f33)
def cons_f34(a, b):
return PosQ(a/b)
cons34 = CustomConstraint(cons_f34)
def cons_f35(n, m, p):
return IntegersQ(m, n, p)
cons35 = CustomConstraint(cons_f35)
def cons_f36(n, m, p):
return Less(S(0), m, p, n)
cons36 = CustomConstraint(cons_f36)
def cons_f37(q, n, m, p):
return IntegersQ(m, n, p, q)
cons37 = CustomConstraint(cons_f37)
def cons_f38(n, q, m, p):
return Less(S(0), m, p, q, n)
cons38 = CustomConstraint(cons_f38)
def cons_f39(n):
return IntegerQ(n/S(2))
cons39 = CustomConstraint(cons_f39)
def cons_f40(p):
return NegativeIntegerQ(p)
cons40 = CustomConstraint(cons_f40)
def cons_f41(n, m):
return IntegersQ(m, n/S(2))
cons41 = CustomConstraint(cons_f41)
def cons_f42(n, m):
return Unequal(m, n/S(2))
cons42 = CustomConstraint(cons_f42)
def cons_f43(c, b, a):
return NonzeroQ(-S(4)*a*c + b**S(2))
cons43 = CustomConstraint(cons_f43)
def cons_f44(j, n, m):
return IntegersQ(m, n, j)
cons44 = CustomConstraint(cons_f44)
def cons_f45(n, m):
return Less(S(0), m, S(2)*n)
cons45 = CustomConstraint(cons_f45)
def cons_f46(n, m, p):
return Not(And(Equal(m, n), Equal(p, S(-1))))
cons46 = CustomConstraint(cons_f46)
def cons_f47(v, x):
if not isinstance(x, Symbol):
return False
return PolynomialQ(v, x)
cons47 = CustomConstraint(cons_f47)
def cons_f48(v, x):
if not isinstance(x, Symbol):
return False
return BinomialQ(v, x)
cons48 = CustomConstraint(cons_f48)
def cons_f49(v, x, u):
if not isinstance(x, Symbol):
return False
return Inequality(Exponent(u, x), Equal, Exponent(v, x) + S(-1), GreaterEqual, S(2))
cons49 = CustomConstraint(cons_f49)
def cons_f50(v, x, u):
if not isinstance(x, Symbol):
return False
return GreaterEqual(Exponent(u, x), Exponent(v, x))
cons50 = CustomConstraint(cons_f50)
def cons_f51(p):
return Not(IntegerQ(p))
cons51 = CustomConstraint(cons_f51)
def With2(e, b, c, f, n, a, g, h, x, d, m):
tmp = a*h - b*g
k = Symbol('k')
return f**(e*(c + d*x)**n)*SimplifyTerm(h**(-m)*tmp**m, x)/(g + h*x) + Sum_doit(f**(e*(c + d*x)**n)*(a + b*x)**(-k + m)*SimplifyTerm(b*h**(-k)*tmp**(k - 1), x), List(k, 1, m))
pattern2 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))/(x_*WC('h', S(1)) + WC('g', S(0))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons9, cons10, cons1, cons2)
rule2 = ReplacementRule(pattern2, With2)
pattern3 = Pattern(UtilityOperator(F_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('b', S(1)))*x_**WC('m', S(1))*(e_ + x_*WC('f', S(1)))**WC('p', S(1)), x_), cons12, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons15, cons11)
def replacement3(e, b, c, f, n, p, F, x, d, m):
return If(And(PositiveIntegerQ(m, p), LessEqual(m, p), Or(EqQ(n, S(1)), ZeroQ(-c*f + d*e))), ExpandLinearProduct(F**(b*(c + d*x)**n)*(e + f*x)**p, x**m, e, f, x), If(PositiveIntegerQ(p), Distribute(F**(b*(c + d*x)**n)*x**m*(e + f*x)**p, Plus, Times), ExpandIntegrand(F**(b*(c + d*x)**n), x**m*(e + f*x)**p, x)))
rule3 = ReplacementRule(pattern3, replacement3)
pattern4 = Pattern(UtilityOperator(F_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))*x_**WC('m', S(1))*(e_ + x_*WC('f', S(1)))**WC('p', S(1)), x_), cons12, cons3, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons15, cons16)
def replacement4(e, b, c, f, n, a, p, F, x, d, m):
return If(And(PositiveIntegerQ(m, p), LessEqual(m, p), Or(EqQ(n, S(1)), ZeroQ(-c*f + d*e))), ExpandLinearProduct(F**(a + b*(c + d*x)**n)*(e + f*x)**p, x**m, e, f, x), If(PositiveIntegerQ(p), Distribute(F**(a + b*(c + d*x)**n)*x**m*(e + f*x)**p, Plus, Times), ExpandIntegrand(F**(a + b*(c + d*x)**n), x**m*(e + f*x)**p, x)))
rule4 = ReplacementRule(pattern4, replacement4)
def With5(b, v, c, n, a, F, u, x, d, m):
if not isinstance(x, Symbol) or not (FreeQ([F, a, b, c, d], x) and IntegersQ(m, n) and n < 0):
return False
w = ExpandIntegrand((a + b*x)**m*(c + d*x)**n, x)
w = ReplaceAll(w, Rule(x, F**v))
if SumQ(w):
return True
return False
pattern5 = Pattern(UtilityOperator((F_**v_*WC('b', S(1)) + a_)**WC('m', S(1))*(F_**v_*WC('d', S(1)) + c_)**n_*WC('u', S(1)), x_), cons12, cons3, cons4, cons5, cons6, cons17, cons18, CustomConstraint(With5))
def replacement5(b, v, c, n, a, F, u, x, d, m):
w = ReplaceAll(ExpandIntegrand((a + b*x)**m*(c + d*x)**n, x), Rule(x, F**v))
return w.func(*[u*i for i in w.args])
rule5 = ReplacementRule(pattern5, replacement5)
def With6(e, b, c, f, n, a, x, u, d, m):
if not isinstance(x, Symbol) or not (FreeQ([a, b, c, d, e, f, m, n], x) and PolynomialQ(u,x)):
return False
v = ExpandIntegrand(u*(a + b*x)**m, x)
if SumQ(v):
return True
return False
pattern6 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*u_*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1)), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons19, CustomConstraint(With6))
def replacement6(e, b, c, f, n, a, x, u, d, m):
v = ExpandIntegrand(u*(a + b*x)**m, x)
return Distribute(f**(e*(c + d*x)**n)*v, Plus, Times)
rule6 = ReplacementRule(pattern6, replacement6)
pattern7 = Pattern(UtilityOperator(u_*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))*Log((x_**WC('n', S(1))*WC('e', S(1)) + WC('d', S(0)))**WC('p', S(1))*WC('c', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons13, cons14, cons15, cons19)
def replacement7(e, b, c, n, a, p, x, u, d, m):
return ExpandIntegrand(Log(c*(d + e*x**n)**p), u*(a + b*x)**m, x)
rule7 = ReplacementRule(pattern7, replacement7)
pattern8 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*u_, x_), cons5, cons6, cons7, cons8, cons14, cons19)
def replacement8(e, c, f, n, x, u, d):
return If(EqQ(n, S(1)), ExpandIntegrand(f**(e*(c + d*x)**n), u, x), ExpandLinearProduct(f**(e*(c + d*x)**n), u, c, d, x))
rule8 = ReplacementRule(pattern8, replacement8)
# pattern9 = Pattern(UtilityOperator(F_**u_*(G_*u_*WC('b', S(1)) + a_)**WC('n', S(1)), x_), cons3, cons4, cons17, cons20)
# def replacement9(b, G, n, a, F, u, x, m):
# return ReplaceAll(ExpandIntegrand(x**(-m)*(a + b*x)**n, x), Rule(x, G(u)))
# rule9 = ReplacementRule(pattern9, replacement9)
pattern10 = Pattern(UtilityOperator(u_*(WC('a', S(0)) + WC('b', S(1))*Log(((x_*WC('f', S(1)) + WC('e', S(0)))**WC('p', S(1))*WC('d', S(1)))**WC('q', S(1))*WC('c', S(1))))**n_, x_), cons3, cons4, cons5, cons6, cons7, cons8, cons14, cons15, cons21, cons19)
def replacement10(e, b, c, f, n, a, p, x, u, d, q):
return ExpandLinearProduct((a + b*Log(c*(d*(e + f*x)**p)**q))**n, u, e, f, x)
rule10 = ReplacementRule(pattern10, replacement10)
# pattern11 = Pattern(UtilityOperator(u_*(F_*(x_*WC('d', S(1)) + WC('c', S(0)))*WC('b', S(1)) + WC('a', S(0)))**n_, x_), cons3, cons4, cons5, cons6, cons14, cons19, cons22)
# def replacement11(b, c, n, a, F, u, x, d):
# return ExpandLinearProduct((a + b*F(c + d*x))**n, u, c, d, x)
# rule11 = ReplacementRule(pattern11, replacement11)
pattern12 = Pattern(UtilityOperator(WC('u', S(1))/(x_**n_*WC('a', S(1)) + sqrt(c_ + x_**j_*WC('d', S(1)))*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons14, cons23)
def replacement12(b, c, n, a, x, u, d, j):
return ExpandIntegrand(u*(a*x**n - b*sqrt(c + d*x**(S(2)*n)))/(-b**S(2)*c + x**(S(2)*n)*(a**S(2) - b**S(2)*d)), x)
rule12 = ReplacementRule(pattern12, replacement12)
pattern13 = Pattern(UtilityOperator((a_ + x_*WC('b', S(1)))**m_/(c_ + x_*WC('d', S(1))), x_), cons3, cons4, cons5, cons6, cons1)
def replacement13(b, c, a, x, d, m):
if RationalQ(a, b, c, d):
return ExpandExpression((a + b*x)**m/(c + d*x), x)
else:
tmp = a*d - b*c
k = Symbol("k")
return Sum_doit((a + b*x)**(-k + m)*SimplifyTerm(b*d**(-k)*tmp**(k + S(-1)), x), List(k, S(1), m)) + SimplifyTerm(d**(-m)*tmp**m, x)/(c + d*x)
rule13 = ReplacementRule(pattern13, replacement13)
pattern14 = Pattern(UtilityOperator((A_ + x_*WC('B', S(1)))*(a_ + x_*WC('b', S(1)))**WC('m', S(1))/(c_ + x_*WC('d', S(1))), x_), cons3, cons4, cons5, cons6, cons24, cons25, cons1)
def replacement14(b, B, A, c, a, x, d, m):
if RationalQ(a, b, c, d, A, B):
return ExpandExpression((A + B*x)*(a + b*x)**m/(c + d*x), x)
else:
tmp1 = (A*d - B*c)/d
tmp2 = ExpandIntegrand((a + b*x)**m/(c + d*x), x)
tmp2 = If(SumQ(tmp2), tmp2.func(*[SimplifyTerm(tmp1*i, x) for i in tmp2.args]), SimplifyTerm(tmp1*tmp2, x))
return SimplifyTerm(B/d, x)*(a + b*x)**m + tmp2
rule14 = ReplacementRule(pattern14, replacement14)
def With15(b, a, x, u, m):
tmp1 = Symbol('tmp1')
tmp2 = Symbol('tmp2')
tmp1 = ExpandLinearProduct((a + b*x)**m, u, a, b, x)
if not IntegerQ(m):
return tmp1
else:
tmp2 = ExpandExpression(u*(a + b*x)**m, x)
if SumQ(tmp2) and LessEqual(LeafCount(tmp2), LeafCount(tmp1) + S(2)):
return tmp2
else:
return tmp1
pattern15 = Pattern(UtilityOperator(u_*(a_ + x_*WC('b', S(1)))**m_, x_), cons3, cons4, cons13, cons19, cons26)
rule15 = ReplacementRule(pattern15, With15)
pattern16 = Pattern(UtilityOperator(u_*v_**n_*(a_ + x_*WC('b', S(1)))**m_, x_), cons27)
def replacement16(b, v, n, a, x, u, m):
s = PolynomialQuotientRemainder(u, v**(-n)*(a+b*x)**(-IntegerPart(m)), x)
return ExpandIntegrand((a + b*x)**FractionalPart(m)*s[0], x) + ExpandIntegrand(v**n*(a + b*x)**m*s[1], x)
rule16 = ReplacementRule(pattern16, replacement16)
pattern17 = Pattern(UtilityOperator(u_*v_**n_*(a_ + x_*WC('b', S(1)))**m_, x_), cons28)
def replacement17(b, v, n, a, x, u, m):
s = PolynomialQuotientRemainder(u, v**(-n),x)
return ExpandIntegrand((a + b*x)**(m)*s[0], x) + ExpandIntegrand(v**n*(a + b*x)**m*s[1], x)
rule17 = ReplacementRule(pattern17, replacement17)
def With18(b, n, a, x, u):
r = Numerator(Rt(-a/b, S(2)))
s = Denominator(Rt(-a/b, S(2)))
return r/(S(2)*a*(r + s*u**(n/S(2)))) + r/(S(2)*a*(r - s*u**(n/S(2))))
pattern18 = Pattern(UtilityOperator(S(1)/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons29)
rule18 = ReplacementRule(pattern18, With18)
def With19(b, n, a, x, u):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit(r/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern19 = Pattern(UtilityOperator(S(1)/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons30, cons31)
rule19 = ReplacementRule(pattern19, With19)
def With20(b, n, a, x, u, m):
k = Symbol("k")
g = GCD(m, n)
r = Numerator(Rt(a/b, n/GCD(m, n)))
s = Denominator(Rt(a/b, n/GCD(m, n)))
return If(CoprimeQ(g + m, n), Sum_doit((-1)**(-2*k*m/n)*r*(-r/s)**(m/g)/(a*n*((-1)**(2*g*k/n)*s*u**g + r)), List(k, 1, n/g)), Sum_doit((-1)**(2*k*(g + m)/n)*r*(-r/s)**(m/g)/(a*n*((-1)**(2*g*k/n)*r + s*u**g)), List(k, 1, n/g)))
pattern20 = Pattern(UtilityOperator(u_**WC('m', S(1))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons17, cons32, cons33, cons34)
rule20 = ReplacementRule(pattern20, With20)
def With21(b, n, a, x, u, m):
k = Symbol("k")
g = GCD(m, n)
r = Numerator(Rt(-a/b, n/GCD(m, n)))
s = Denominator(Rt(-a/b, n/GCD(m, n)))
return If(Equal(n/g, S(2)), s/(S(2)*b*(r + s*u**g)) - s/(S(2)*b*(r - s*u**g)), If(CoprimeQ(g + m, n), Sum_doit((S(-1))**(-S(2)*k*m/n)*r*(r/s)**(m/g)/(a*n*(-(S(-1))**(S(2)*g*k/n)*s*u**g + r)), List(k, S(1), n/g)), Sum_doit((S(-1))**(S(2)*k*(g + m)/n)*r*(r/s)**(m/g)/(a*n*((S(-1))**(S(2)*g*k/n)*r - s*u**g)), List(k, S(1), n/g))))
pattern21 = Pattern(UtilityOperator(u_**WC('m', S(1))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons17, cons32)
rule21 = ReplacementRule(pattern21, With21)
def With22(b, c, n, a, x, u, d, m):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit((c*r + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern22 = Pattern(UtilityOperator((c_ + u_**WC('m', S(1))*WC('d', S(1)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons17, cons32)
rule22 = ReplacementRule(pattern22, With22)
def With23(e, b, c, n, a, p, x, u, d, m):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit((c*r + (-1)**(-2*k*p/n)*e*r*(r/s)**p + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern23 = Pattern(UtilityOperator((u_**p_*WC('e', S(1)) + u_**WC('m', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons35, cons36)
rule23 = ReplacementRule(pattern23, With23)
def With24(e, b, c, f, n, a, p, x, u, d, q, m):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit((c*r + (-1)**(-2*k*q/n)*f*r*(r/s)**q + (-1)**(-2*k*p/n)*e*r*(r/s)**p + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern24 = Pattern(UtilityOperator((u_**p_*WC('e', S(1)) + u_**q_*WC('f', S(1)) + u_**WC('m', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons37, cons38)
rule24 = ReplacementRule(pattern24, With24)
def With25(c, n, a, p, x, u):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(c**(-p), (c*x - q)**p*(c*x + q)**p, x), List(Rule(q, Rt(-a*c, S(2))), Rule(x, u**(n/S(2)))))
pattern25 = Pattern(UtilityOperator((a_ + u_**WC('n', S(1))*WC('c', S(1)))**p_, x_), cons3, cons5, cons39, cons40)
rule25 = ReplacementRule(pattern25, With25)
def With26(c, n, a, p, x, u, m):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(c**(-p), x**m*(c*x**(n/S(2)) - q)**p*(c*x**(n/S(2)) + q)**p, x), List(Rule(q, Rt(-a*c, S(2))), Rule(x, u)))
pattern26 = Pattern(UtilityOperator(u_**WC('m', S(1))*(u_**WC('n', S(1))*WC('c', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons5, cons41, cons40, cons32, cons42)
rule26 = ReplacementRule(pattern26, With26)
def With27(b, c, n, a, p, x, u, j):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(S(4)**(-p)*c**(-p), (b + S(2)*c*x - q)**p*(b + S(2)*c*x + q)**p, x), List(Rule(q, Rt(-S(4)*a*c + b**S(2), S(2))), Rule(x, u**n)))
pattern27 = Pattern(UtilityOperator((u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons4, cons5, cons30, cons23, cons40, cons43)
rule27 = ReplacementRule(pattern27, With27)
def With28(b, c, n, a, p, x, u, j, m):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(S(4)**(-p)*c**(-p), x**m*(b + S(2)*c*x**n - q)**p*(b + S(2)*c*x**n + q)**p, x), List(Rule(q, Rt(-S(4)*a*c + b**S(2), S(2))), Rule(x, u)))
pattern28 = Pattern(UtilityOperator(u_**WC('m', S(1))*(u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons4, cons5, cons44, cons23, cons40, cons45, cons46, cons43)
rule28 = ReplacementRule(pattern28, With28)
def With29(b, c, n, a, x, u, d, j):
q = Rt(-a/b, S(2))
return -(c - d*q)/(S(2)*b*q*(q + u**n)) - (c + d*q)/(S(2)*b*q*(q - u**n))
pattern29 = Pattern(UtilityOperator((u_**WC('n', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**WC('j', S(1))*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons14, cons23)
rule29 = ReplacementRule(pattern29, With29)
def With30(e, b, c, f, n, a, g, x, u, d, j):
q = Rt(-S(4)*a*c + b**S(2), S(2))
r = TogetherSimplify((-b*e*g + S(2)*c*(d + e*f))/q)
return (e*g - r)/(b + 2*c*u**n + q) + (e*g + r)/(b + 2*c*u**n - q)
pattern30 = Pattern(UtilityOperator(((u_**WC('n', S(1))*WC('g', S(1)) + WC('f', S(0)))*WC('e', S(1)) + WC('d', S(0)))/(u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons9, cons14, cons23, cons43)
rule30 = ReplacementRule(pattern30, With30)
def With31(v, x, u):
lst = CoefficientList(u, x)
i = Symbol('i')
return x**Exponent(u, x)*lst[-1]/v + Sum_doit(x**(i - 1)*Part(lst, i), List(i, 1, Exponent(u, x)))/v
pattern31 = Pattern(UtilityOperator(u_/v_, x_), cons19, cons47, cons48, cons49)
rule31 = ReplacementRule(pattern31, With31)
pattern32 = Pattern(UtilityOperator(u_/v_, x_), cons19, cons47, cons50)
def replacement32(v, x, u):
return PolynomialDivide(u, v, x)
rule32 = ReplacementRule(pattern32, replacement32)
pattern33 = Pattern(UtilityOperator(u_*(x_*WC('a', S(1)))**p_, x_), cons51, cons19)
def replacement33(x, a, u, p):
return ExpandToSum((a*x)**p, u, x)
rule33 = ReplacementRule(pattern33, replacement33)
pattern34 = Pattern(UtilityOperator(v_**p_*WC('u', S(1)), x_), cons51)
def replacement34(v, x, u, p):
return ExpandIntegrand(NormalizeIntegrand(v**p, x), u, x)
rule34 = ReplacementRule(pattern34, replacement34)
pattern35 = Pattern(UtilityOperator(u_, x_))
def replacement35(x, u):
return ExpandExpression(u, x)
rule35 = ReplacementRule(pattern35, replacement35)
return [ rule2,rule3, rule4, rule5, rule6, rule7, rule8, rule10, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28, rule29, rule30, rule31, rule32, rule33, rule34, rule35]
def _RemoveContentAux():
def cons_f1(b, a):
return IntegersQ(a, b)
cons1 = CustomConstraint(cons_f1)
def cons_f2(b, a):
return Equal(a + b, S(0))
cons2 = CustomConstraint(cons_f2)
def cons_f3(m):
return RationalQ(m)
cons3 = CustomConstraint(cons_f3)
def cons_f4(m, n):
return RationalQ(m, n)
cons4 = CustomConstraint(cons_f4)
def cons_f5(m, n):
return GreaterEqual(-m + n, S(0))
cons5 = CustomConstraint(cons_f5)
def cons_f6(a, x):
return FreeQ(a, x)
cons6 = CustomConstraint(cons_f6)
def cons_f7(m, n, p):
return RationalQ(m, n, p)
cons7 = CustomConstraint(cons_f7)
def cons_f8(m, p):
return GreaterEqual(-m + p, S(0))
cons8 = CustomConstraint(cons_f8)
pattern1 = Pattern(UtilityOperator(a_**m_*WC('u', S(1)) + b_*WC('v', S(1)), x_), cons1, cons2, cons3)
def replacement1(v, x, a, u, m, b):
return If(Greater(m, S(1)), RemoveContentAux(a**(m + S(-1))*u - v, x), RemoveContentAux(-a**(-m + S(1))*v + u, x))
rule1 = ReplacementRule(pattern1, replacement1)
pattern2 = Pattern(UtilityOperator(a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)), x_), cons6, cons4, cons5)
def replacement2(n, v, x, u, m, a):
return RemoveContentAux(a**(-m + n)*v + u, x)
rule2 = ReplacementRule(pattern2, replacement2)
pattern3 = Pattern(UtilityOperator(a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('w', S(1)), x_), cons6, cons7, cons5, cons8)
def replacement3(n, v, x, p, u, w, m, a):
return RemoveContentAux(a**(-m + n)*v + a**(-m + p)*w + u, x)
rule3 = ReplacementRule(pattern3, replacement3)
pattern4 = Pattern(UtilityOperator(u_, x_))
def replacement4(u, x):
return If(And(SumQ(u), NegQ(First(u))), -u, u)
rule4 = ReplacementRule(pattern4, replacement4)
return [rule1, rule2, rule3, rule4, ]
IntHide = Int
Log = rubi_log
Null = None
if matchpy:
RemoveContentAux_replacer = ManyToOneReplacer(* _RemoveContentAux())
ExpandIntegrand_rules = _ExpandIntegrand()
TrigSimplifyAux_replacer = _TrigSimplifyAux()
SimplifyAntiderivative_replacer = _SimplifyAntiderivative()
SimplifyAntiderivativeSum_replacer = _SimplifyAntiderivativeSum()
FixSimplify_rules = _FixSimplify()
SimpFixFactor_replacer = _SimpFixFactor()
|
9e65f120c3d17c0147ab469ac97fc0c39856306ffbc84d3e2496213821ea5ffe | from sympy.core.compatibility import range
from sympy import cos, DiracDelta, Heaviside, Function, pi, S, sin, symbols, Rational
from sympy.integrals.deltafunctions import change_mul, deltaintegrate
f = Function("f")
x_1, x_2, x, y, z = symbols("x_1 x_2 x y z")
def test_change_mul():
assert change_mul(x, x) == (None, None)
assert change_mul(x*y, x) == (None, None)
assert change_mul(x*y*DiracDelta(x), x) == (DiracDelta(x), x*y)
assert change_mul(x*y*DiracDelta(x)*DiracDelta(y), x) == \
(DiracDelta(x), x*y*DiracDelta(y))
assert change_mul(DiracDelta(x)**2, x) == \
(DiracDelta(x), DiracDelta(x))
assert change_mul(y*DiracDelta(x)**2, x) == \
(DiracDelta(x), y*DiracDelta(x))
def test_deltaintegrate():
assert deltaintegrate(x, x) is None
assert deltaintegrate(x + DiracDelta(x), x) is None
assert deltaintegrate(DiracDelta(x, 0), x) == Heaviside(x)
for n in range(10):
assert deltaintegrate(DiracDelta(x, n + 1), x) == DiracDelta(x, n)
assert deltaintegrate(DiracDelta(x), x) == Heaviside(x)
assert deltaintegrate(DiracDelta(-x), x) == Heaviside(x)
assert deltaintegrate(DiracDelta(x - y), x) == Heaviside(x - y)
assert deltaintegrate(DiracDelta(y - x), x) == Heaviside(x - y)
assert deltaintegrate(x*DiracDelta(x), x) == 0
assert deltaintegrate((x - y)*DiracDelta(x - y), x) == 0
assert deltaintegrate(DiracDelta(x)**2, x) == DiracDelta(0)*Heaviside(x)
assert deltaintegrate(y*DiracDelta(x)**2, x) == \
y*DiracDelta(0)*Heaviside(x)
assert deltaintegrate(DiracDelta(x, 1), x) == DiracDelta(x, 0)
assert deltaintegrate(y*DiracDelta(x, 1), x) == y*DiracDelta(x, 0)
assert deltaintegrate(DiracDelta(x, 1)**2, x) == -DiracDelta(0, 2)*Heaviside(x)
assert deltaintegrate(y*DiracDelta(x, 1)**2, x) == -y*DiracDelta(0, 2)*Heaviside(x)
assert deltaintegrate(DiracDelta(x) * f(x), x) == f(0) * Heaviside(x)
assert deltaintegrate(DiracDelta(-x) * f(x), x) == f(0) * Heaviside(x)
assert deltaintegrate(DiracDelta(x - 1) * f(x), x) == f(1) * Heaviside(x - 1)
assert deltaintegrate(DiracDelta(1 - x) * f(x), x) == f(1) * Heaviside(x - 1)
assert deltaintegrate(DiracDelta(x**2 + x - 2), x) == \
Heaviside(x - 1)/3 + Heaviside(x + 2)/3
p = cos(x)*(DiracDelta(x) + DiracDelta(x**2 - 1))*sin(x)*(x - pi)
assert deltaintegrate(p, x) - (-pi*(cos(1)*Heaviside(-1 + x)*sin(1)/2 - \
cos(1)*Heaviside(1 + x)*sin(1)/2) + \
cos(1)*Heaviside(1 + x)*sin(1)/2 + \
cos(1)*Heaviside(-1 + x)*sin(1)/2) == 0
p = x_2*DiracDelta(x - x_2)*DiracDelta(x_2 - x_1)
assert deltaintegrate(p, x_2) == x*DiracDelta(x - x_1)*Heaviside(x_2 - x)
p = x*y**2*z*DiracDelta(y - x)*DiracDelta(y - z)*DiracDelta(x - z)
assert deltaintegrate(p, y) == x**3*z*DiracDelta(x - z)**2*Heaviside(y - x)
assert deltaintegrate((x + 1)*DiracDelta(2*x), x) == S.Half * Heaviside(x)
assert deltaintegrate((x + 1)*DiracDelta(x*Rational(2, 3) + Rational(4, 9)), x) == \
S.Half * Heaviside(x + Rational(2, 3))
a, b, c = symbols('a b c', commutative=False)
assert deltaintegrate(DiracDelta(x - y)*f(x - b)*f(x - a), x) == \
f(y - b)*f(y - a)*Heaviside(x - y)
p = f(x - a)*DiracDelta(x - y)*f(x - c)*f(x - b)
assert deltaintegrate(p, x) == f(y - a)*f(y - c)*f(y - b)*Heaviside(x - y)
p = DiracDelta(x - z)*f(x - b)*f(x - a)*DiracDelta(x - y)
assert deltaintegrate(p, x) == DiracDelta(y - z)*f(y - b)*f(y - a) * \
Heaviside(x - y)
|
45900886e0a257d0ca728b649ddf04f175c22f46e67a7dacb620daf73d99549e | """Most of these tests come from the examples in Bronstein's book."""
from sympy import Poly, S, symbols, oo, I, Rational
from sympy.core.compatibility import PY3
from sympy.integrals.risch import (DifferentialExtension,
NonElementaryIntegralException)
from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer,
normal_denom, special_denom, bound_degree, spde, solve_poly_rde,
no_cancel_equal, cancel_primitive, cancel_exp, rischDE)
from sympy.utilities.pytest import raises, XFAIL
from sympy.abc import x, t, z, n
t0, t1, t2, k = symbols('t:3 k')
def test_order_at():
a = Poly(t**4, t)
b = Poly((t**2 + 1)**3*t, t)
c = Poly((t**2 + 1)**6*t, t)
d = Poly((t**2 + 1)**10*t**10, t)
e = Poly((t**2 + 1)**100*t**37, t)
p1 = Poly(t, t)
p2 = Poly(1 + t**2, t)
assert order_at(a, p1, t) == 4
assert order_at(b, p1, t) == 1
assert order_at(c, p1, t) == 1
assert order_at(d, p1, t) == 10
assert order_at(e, p1, t) == 37
assert order_at(a, p2, t) == 0
assert order_at(b, p2, t) == 3
assert order_at(c, p2, t) == 6
assert order_at(d, p1, t) == 10
assert order_at(e, p2, t) == 100
assert order_at(Poly(0, t), Poly(t, t), t) is oo
assert order_at_oo(Poly(t**2 - 1, t), Poly(t + 1), t) == \
order_at_oo(Poly(t - 1, t), Poly(1, t), t) == -1
assert order_at_oo(Poly(0, t), Poly(1, t), t) is oo
def test_weak_normalizer():
a = Poly((1 + x)*t**5 + 4*t**4 + (-1 - 3*x)*t**3 - 4*t**2 + (-2 + 2*x)*t, t)
d = Poly(t**4 - 3*t**2 + 2, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
r = weak_normalizer(a, d, DE, z)
assert r == (Poly(t**5 - t**4 - 4*t**3 + 4*t**2 + 4*t - 4, t),
(Poly((1 + x)*t**2 + x*t, t), Poly(t + 1, t)))
assert weak_normalizer(r[1][0], r[1][1], DE) == (Poly(1, t), r[1])
r = weak_normalizer(Poly(1 + t**2), Poly(t**2 - 1, t), DE, z)
assert r == (Poly(t**4 - 2*t**2 + 1, t), (Poly(-3*t**2 + 1, t), Poly(t**2 - 1, t)))
assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1])
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2)]})
r = weak_normalizer(Poly(1 + t**2), Poly(t, t), DE, z)
assert r == (Poly(t, t), (Poly(0, t), Poly(1, t)))
assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1])
def test_normal_denom():
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
raises(NonElementaryIntegralException, lambda: normal_denom(Poly(1, x), Poly(1, x),
Poly(1, x), Poly(x, x), DE))
fa, fd = Poly(t**2 + 1, t), Poly(1, t)
ga, gd = Poly(1, t), Poly(t**2, t)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert normal_denom(fa, fd, ga, gd, DE) == \
(Poly(t, t), (Poly(t**3 - t**2 + t - 1, t), Poly(1, t)), (Poly(1, t),
Poly(1, t)), Poly(t, t))
def test_special_denom():
# TODO: add more tests here
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t),
Poly(t, t), DE) == \
(Poly(1, t), Poly(t**2 - 1, t), Poly(t**2 - 1, t), Poly(t, t))
# assert special_denom(Poly(1, t), Poly(2*x, t), Poly((1 + 2*x)*t, t), DE) == 1
# issue 3940
# Note, this isn't a very good test, because the denominator is just 1,
# but at least it tests the exp cancellation case
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0),
Poly(I*k*t1, t1)]})
DE.decrement_level()
assert special_denom(Poly(1, t0), Poly(I*k, t0), Poly(1, t0), Poly(t0, t0),
Poly(1, t0), DE) == \
(Poly(1, t0), Poly(I*k, t0), Poly(t0, t0), Poly(1, t0))
assert special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t),
Poly(t, t), DE, case='tan') == \
(Poly(1, t, t0, domain='ZZ'), Poly(t**2, t0, t, domain='ZZ[x]'),
Poly(t, t, t0, domain='ZZ'), Poly(1, t0, domain='ZZ'))
raises(ValueError, lambda: special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t),
Poly(t, t), DE, case='unrecognized_case'))
# @XFAIL
# Probably only fails in Python 2.7
def test_bound_degree_fail():
# Primitive
DE = DifferentialExtension(extension={'D': [Poly(1, x),
Poly(t0/x**2, t0), Poly(1/x, t)]})
assert bound_degree(Poly(t**2, t), Poly(-(1/x**2*t**2 + 1/x), t),
Poly((2*x - 1)*t**4 + (t0 + x)/x*t**3 - (t0 + 4*x**2)/2*x*t**2 + x*t,
t), DE) == 3
if not PY3:
test_bound_degree_fail = XFAIL(test_bound_degree_fail)
def test_bound_degree():
# Base
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert bound_degree(Poly(1, x), Poly(-2*x, x), Poly(1, x), DE) == 0
# Primitive (see above test_bound_degree_fail)
# TODO: Add test for when the degree bound becomes larger after limited_integrate
# TODO: Add test for db == da - 1 case
# Exp
# TODO: Add tests
# TODO: Add test for when the degree becomes larger after parametric_log_deriv()
# Nonlinear
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert bound_degree(Poly(t, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), DE) == 0
def test_spde():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
raises(NonElementaryIntegralException, lambda: spde(Poly(t, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert spde(Poly(t**2 + x*t*2 + x**2, t), Poly(t**2/x**2 + (2/x - 1)*t, t),
Poly(t**2/x**2 + (2/x - 1)*t, t), 0, DE) == \
(Poly(0, t), Poly(0, t), 0, Poly(0, t), Poly(1, t))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0/x**2, t0), Poly(1/x, t)]})
assert spde(Poly(t**2, t), Poly(-t**2/x**2 - 1/x, t),
Poly((2*x - 1)*t**4 + (t0 + x)/x*t**3 - (t0 + 4*x**2)/(2*x)*t**2 + x*t, t), 3, DE) == \
(Poly(0, t), Poly(0, t), 0, Poly(0, t),
Poly(t0*t**2/2 + x**2*t**2 - x**2*t, t))
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 +
3*x**4/4 + x**3 - x**2 + 1, x), 4, DE) == \
(Poly(0, x), Poly(x/2 - Rational(1, 4), x), 2, Poly(x**2 + x + 1, x), Poly(x*Rational(5, 4), x))
assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 +
3*x**4/4 + x**3 - x**2 + 1, x), n, DE) == \
(Poly(0, x), Poly(x/2 - Rational(1, 4), x), -2 + n, Poly(x**2 + x + 1, x), Poly(x*Rational(5, 4), x))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]})
raises(NonElementaryIntegralException, lambda: spde(Poly((t - 1)*(t**2 + 1)**2, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE))
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert spde(Poly(x**2 - x, x), Poly(1, x), Poly(9*x**4 - 10*x**3 + 2*x**2, x), 4, DE) == (Poly(0, x), Poly(0, x), 0, Poly(0, x), Poly(3*x**3 - 2*x**2, x))
assert spde(Poly(x**2 - x, x), Poly(x**2 - 5*x + 3, x), Poly(x**7 - x**6 - 2*x**4 + 3*x**3 - x**2, x), 5, DE) == \
(Poly(1, x), Poly(x + 1, x), 1, Poly(x**4 - x**3, x), Poly(x**3 - x**2, x))
def test_solve_poly_rde_no_cancel():
# deg(b) large
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
assert solve_poly_rde(Poly(t**2 + 1, t), Poly(t**3 + (x + 1)*t**2 + t + x + 2, t),
oo, DE) == Poly(t + x, t)
# deg(b) small
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert solve_poly_rde(Poly(0, x), Poly(x/2 - Rational(1, 4), x), oo, DE) == \
Poly(x**2/4 - x/4, x)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert solve_poly_rde(Poly(2, t), Poly(t**2 + 2*t + 3, t), 1, DE) == \
Poly(t + 1, t, x)
# deg(b) == deg(D) - 1
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
assert no_cancel_equal(Poly(1 - t, t),
Poly(t**3 + t**2 - 2*x*t - 2*x, t), oo, DE) == \
(Poly(t**2, t), 1, Poly((-2 - 2*x)*t - 2*x, t))
def test_solve_poly_rde_cancel():
# exp
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert cancel_exp(Poly(2*x, t), Poly(2*x, t), 0, DE) == \
Poly(1, t)
assert cancel_exp(Poly(2*x, t), Poly((1 + 2*x)*t, t), 1, DE) == \
Poly(t, t)
# TODO: Add more exp tests, including tests that require is_deriv_in_field()
# primitive
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
# If the DecrementLevel context manager is working correctly, this shouldn't
# cause any problems with the further tests.
raises(NonElementaryIntegralException, lambda: cancel_primitive(Poly(1, t), Poly(t, t), oo, DE))
assert cancel_primitive(Poly(1, t), Poly(t + 1/x, t), 2, DE) == \
Poly(t, t)
assert cancel_primitive(Poly(4*x, t), Poly(4*x*t**2 + 2*t/x, t), 3, DE) == \
Poly(t**2, t)
# TODO: Add more primitive tests, including tests that require is_deriv_in_field()
def test_rischDE():
# TODO: Add more tests for rischDE, including ones from the text
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
DE.decrement_level()
assert rischDE(Poly(-2*x, x), Poly(1, x), Poly(1 - 2*x - 2*x**2, x),
Poly(1, x), DE) == \
(Poly(x + 1, x), Poly(1, x))
|
a3f5b8a5f23c7e5d6bc95adc175fa6f5bcebe19ed2886a4bc47849362351adbd | from sympy import sqrt, Abs
from sympy.core import S, Rational
from sympy.integrals.intpoly import (decompose, best_origin, distance_to_side,
polytope_integrate, point_sort,
hyperplane_parameters, main_integrate3d,
main_integrate, polygon_integrate,
lineseg_integrate, integration_reduction,
integration_reduction_dynamic, is_vertex)
from sympy.geometry.line import Segment2D
from sympy.geometry.polygon import Polygon
from sympy.geometry.point import Point, Point2D
from sympy.abc import x, y, z
from sympy.utilities.pytest import slow
def test_decompose():
assert decompose(x) == {1: x}
assert decompose(x**2) == {2: x**2}
assert decompose(x*y) == {2: x*y}
assert decompose(x + y) == {1: x + y}
assert decompose(x**2 + y) == {1: y, 2: x**2}
assert decompose(8*x**2 + 4*y + 7) == {0: 7, 1: 4*y, 2: 8*x**2}
assert decompose(x**2 + 3*y*x) == {2: x**2 + 3*x*y}
assert decompose(9*x**2 + y + 4*x + x**3 + y**2*x + 3) ==\
{0: 3, 1: 4*x + y, 2: 9*x**2, 3: x**3 + x*y**2}
assert decompose(x, True) == {x}
assert decompose(x ** 2, True) == {x**2}
assert decompose(x * y, True) == {x * y}
assert decompose(x + y, True) == {x, y}
assert decompose(x ** 2 + y, True) == {y, x ** 2}
assert decompose(8 * x ** 2 + 4 * y + 7, True) == {7, 4*y, 8*x**2}
assert decompose(x ** 2 + 3 * y * x, True) == {x ** 2, 3 * x * y}
assert decompose(9 * x ** 2 + y + 4 * x + x ** 3 + y ** 2 * x + 3, True) == \
{3, y, 4*x, 9*x**2, x*y**2, x**3}
def test_best_origin():
expr1 = y ** 2 * x ** 5 + y ** 5 * x ** 7 + 7 * x + x ** 12 + y ** 7 * x
l1 = Segment2D(Point(0, 3), Point(1, 1))
l2 = Segment2D(Point(S(3) / 2, 0), Point(S(3) / 2, 3))
l3 = Segment2D(Point(0, S(3) / 2), Point(3, S(3) / 2))
l4 = Segment2D(Point(0, 2), Point(2, 0))
l5 = Segment2D(Point(0, 2), Point(1, 1))
l6 = Segment2D(Point(2, 0), Point(1, 1))
assert best_origin((2, 1), 3, l1, expr1) == (0, 3)
assert best_origin((2, 0), 3, l2, x ** 7) == (S(3) / 2, 0)
assert best_origin((0, 2), 3, l3, x ** 7) == (0, S(3) / 2)
assert best_origin((1, 1), 2, l4, x ** 7 * y ** 3) == (0, 2)
assert best_origin((1, 1), 2, l4, x ** 3 * y ** 7) == (2, 0)
assert best_origin((1, 1), 2, l5, x ** 2 * y ** 9) == (0, 2)
assert best_origin((1, 1), 2, l6, x ** 9 * y ** 2) == (2, 0)
@slow
def test_polytope_integrate():
# Convex 2-Polytopes
# Vertex representation
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 2),
Point(4, 0)), 1, dims=(x, y)) == 4
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
Point(1, 1), Point(1, 0)), x * y) ==\
Rational(1, 4)
assert polytope_integrate(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)),
6*x**2 - 40*y) == Rational(-935, 3)
assert polytope_integrate(Polygon(Point(0, 0), Point(0, sqrt(3)),
Point(sqrt(3), sqrt(3)),
Point(sqrt(3), 0)), 1) == 3
hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, S.Half),
Point(-sqrt(3) / 2, S(3) / 2), Point(0, 2),
Point(sqrt(3) / 2, S(3) / 2), Point(sqrt(3) / 2, S.Half))
assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
# Hyperplane representation
assert polytope_integrate([((-1, 0), 0), ((1, 2), 4),
((0, -1), 0)], 1, dims=(x, y)) == 4
assert polytope_integrate([((-1, 0), 0), ((0, 1), 1),
((1, 0), 1), ((0, -1), 0)], x * y) == Rational(1, 4)
assert polytope_integrate([((0, 1), 3), ((1, -2), -1),
((-2, -1), -3)], 6*x**2 - 40*y) == Rational(-935, 3)
assert polytope_integrate([((-1, 0), 0), ((0, sqrt(3)), 3),
((sqrt(3), 0), 3), ((0, -1), 0)], 1) == 3
hexagon = [((Rational(-1, 2), -sqrt(3) / 2), 0),
((-1, 0), sqrt(3) / 2),
((Rational(-1, 2), sqrt(3) / 2), sqrt(3)),
((S.Half, sqrt(3) / 2), sqrt(3)),
((1, 0), sqrt(3) / 2),
((S.Half, -sqrt(3) / 2), 0)]
assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
# Non-convex polytopes
# Vertex representation
assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
Point(1, 1), Point(0, 0),
Point(1, -1)), 1) == 3
assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
Point(0, 0), Point(1, 1),
Point(1, -1), Point(0, 0)), 1) == 2
# Hyperplane representation
assert polytope_integrate([((-1, 0), 1), ((0, 1), 1), ((1, -1), 0),
((1, 1), 0), ((0, -1), 1)], 1) == 3
assert polytope_integrate([((-1, 0), 1), ((1, 1), 0), ((-1, 1), 0),
((1, 0), 1), ((-1, -1), 0),
((1, -1), 0)], 1) == 2
# Tests for 2D polytopes mentioned in Chin et al(Page 10):
# http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf
fig1 = Polygon(Point(1.220, -0.827), Point(-1.490, -4.503),
Point(-3.766, -1.622), Point(-4.240, -0.091),
Point(-3.160, 4), Point(-0.981, 4.447),
Point(0.132, 4.027))
assert polytope_integrate(fig1, x**2 + x*y + y**2) ==\
S(2031627344735367)/(8*10**12)
fig2 = Polygon(Point(4.561, 2.317), Point(1.491, -1.315),
Point(-3.310, -3.164), Point(-4.845, -3.110),
Point(-4.569, 1.867))
assert polytope_integrate(fig2, x**2 + x*y + y**2) ==\
S(517091313866043)/(16*10**11)
fig3 = Polygon(Point(-2.740, -1.888), Point(-3.292, 4.233),
Point(-2.723, -0.697), Point(-0.643, -3.151))
assert polytope_integrate(fig3, x**2 + x*y + y**2) ==\
S(147449361647041)/(8*10**12)
fig4 = Polygon(Point(0.211, -4.622), Point(-2.684, 3.851),
Point(0.468, 4.879), Point(4.630, -1.325),
Point(-0.411, -1.044))
assert polytope_integrate(fig4, x**2 + x*y + y**2) ==\
S(180742845225803)/(10**12)
# Tests for many polynomials with maximum degree given(2D case).
tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
polys = []
expr1 = x**9*y + x**7*y**3 + 2*x**2*y**8
expr2 = x**6*y**4 + x**5*y**5 + 2*y**10
expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5
polys.extend((expr1, expr2, expr3))
result_dict = polytope_integrate(tri, polys, max_degree=10)
assert result_dict[expr1] == Rational(615780107, 594)
assert result_dict[expr2] == Rational(13062161, 27)
assert result_dict[expr3] == Rational(1946257153, 924)
# Tests when all integral of all monomials up to a max_degree is to be
# calculated.
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
Point(1, 1), Point(1, 0)),
max_degree=4) == {0: 0, 1: 1, x: S.Half,
x ** 2 * y ** 2: S.One / 9,
x ** 4: S.One / 5,
y ** 4: S.One / 5,
y: S.Half,
x * y ** 2: S.One / 6,
y ** 2: S.One / 3,
x ** 3: S.One / 4,
x ** 2 * y: S.One / 6,
x ** 3 * y: S.One / 8,
x * y: S.One / 4,
y ** 3: S.One / 4,
x ** 2: S.One / 3,
x * y ** 3: S.One / 8}
# Tests for 3D polytopes
cube1 = [[(0, 0, 0), (0, 6, 6), (6, 6, 6), (3, 6, 0),
(0, 6, 0), (6, 0, 6), (3, 0, 0), (0, 0, 6)],
[1, 2, 3, 4], [3, 2, 5, 6], [1, 7, 5, 2], [0, 6, 5, 7],
[1, 4, 0, 7], [0, 4, 3, 6]]
assert polytope_integrate(cube1, 1) == S(162)
# 3D Test cases in Chin et al(2015)
cube2 = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),
(5, 0, 5), (5, 5, 0), (5, 5, 5)],
[3, 7, 6, 2], [1, 5, 7, 3], [5, 4, 6, 7], [0, 4, 5, 1],
[2, 0, 1, 3], [2, 6, 4, 0]]
cube3 = [[(0, 0, 0), (5, 0, 0), (5, 4, 0), (3, 2, 0), (3, 5, 0),
(0, 5, 0), (0, 0, 5), (5, 0, 5), (5, 4, 5), (3, 2, 5),
(3, 5, 5), (0, 5, 5)],
[6, 11, 5, 0], [1, 7, 6, 0], [5, 4, 3, 2, 1, 0], [11, 10, 4, 5],
[10, 9, 3, 4], [9, 8, 2, 3], [8, 7, 1, 2], [7, 8, 9, 10, 11, 6]]
cube4 = [[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1),
(S.One / 4, S.One / 4, S.One / 4)],
[0, 2, 1], [1, 3, 0], [4, 2, 3], [4, 3, 1],
[0, 1, 2], [2, 4, 1], [0, 3, 2]]
assert polytope_integrate(cube2, x ** 2 + y ** 2 + x * y + z ** 2) ==\
Rational(15625, 4)
assert polytope_integrate(cube3, x ** 2 + y ** 2 + x * y + z ** 2) ==\
S(33835) / 12
assert polytope_integrate(cube4, x ** 2 + y ** 2 + x * y + z ** 2) ==\
S(37) / 960
# Test cases from Mathematica's PolyhedronData library
octahedron = [[(S.NegativeOne / sqrt(2), 0, 0), (0, S.One / sqrt(2), 0),
(0, 0, S.NegativeOne / sqrt(2)), (0, 0, S.One / sqrt(2)),
(0, S.NegativeOne / sqrt(2), 0), (S.One / sqrt(2), 0, 0)],
[3, 4, 5], [3, 5, 1], [3, 1, 0], [3, 0, 4], [4, 0, 2],
[4, 2, 5], [2, 0, 1], [5, 2, 1]]
assert polytope_integrate(octahedron, 1) == sqrt(2) / 3
great_stellated_dodecahedron =\
[[(-0.32491969623290634095, 0, 0.42532540417601993887),
(0.32491969623290634095, 0, -0.42532540417601993887),
(-0.52573111211913359231, 0, 0.10040570794311363956),
(0.52573111211913359231, 0, -0.10040570794311363956),
(-0.10040570794311363956, -0.3090169943749474241, 0.42532540417601993887),
(-0.10040570794311363956, 0.30901699437494742410, 0.42532540417601993887),
(0.10040570794311363956, -0.3090169943749474241, -0.42532540417601993887),
(0.10040570794311363956, 0.30901699437494742410, -0.42532540417601993887),
(-0.16245984811645317047, -0.5, 0.10040570794311363956),
(-0.16245984811645317047, 0.5, 0.10040570794311363956),
(0.16245984811645317047, -0.5, -0.10040570794311363956),
(0.16245984811645317047, 0.5, -0.10040570794311363956),
(-0.42532540417601993887, -0.3090169943749474241, -0.10040570794311363956),
(-0.42532540417601993887, 0.30901699437494742410, -0.10040570794311363956),
(-0.26286555605956679615, 0.1909830056250525759, -0.42532540417601993887),
(-0.26286555605956679615, -0.1909830056250525759, -0.42532540417601993887),
(0.26286555605956679615, 0.1909830056250525759, 0.42532540417601993887),
(0.26286555605956679615, -0.1909830056250525759, 0.42532540417601993887),
(0.42532540417601993887, -0.3090169943749474241, 0.10040570794311363956),
(0.42532540417601993887, 0.30901699437494742410, 0.10040570794311363956)],
[12, 3, 0, 6, 16], [17, 7, 0, 3, 13],
[9, 6, 0, 7, 8], [18, 2, 1, 4, 14],
[15, 5, 1, 2, 19], [11, 4, 1, 5, 10],
[8, 19, 2, 18, 9], [10, 13, 3, 12, 11],
[16, 14, 4, 11, 12], [13, 10, 5, 15, 17],
[14, 16, 6, 9, 18], [19, 8, 7, 17, 15]]
# Actual volume is : 0.163118960624632
assert Abs(polytope_integrate(great_stellated_dodecahedron, 1) -\
0.163118960624632) < 1e-12
expr = x **2 + y ** 2 + z ** 2
octahedron_five_compound = [[(0, -0.7071067811865475244, 0),
(0, 0.70710678118654752440, 0),
(0.1148764602736805918,
-0.35355339059327376220, -0.60150095500754567366),
(0.1148764602736805918, 0.35355339059327376220,
-0.60150095500754567366),
(0.18587401723009224507,
-0.57206140281768429760, 0.37174803446018449013),
(0.18587401723009224507, 0.57206140281768429760,
0.37174803446018449013),
(0.30075047750377283683, -0.21850801222441053540,
0.60150095500754567366),
(0.30075047750377283683, 0.21850801222441053540,
0.60150095500754567366),
(0.48662449473386508189, -0.35355339059327376220,
-0.37174803446018449013),
(0.48662449473386508189, 0.35355339059327376220,
-0.37174803446018449013),
(-0.60150095500754567366, 0, -0.37174803446018449013),
(-0.30075047750377283683, -0.21850801222441053540,
-0.60150095500754567366),
(-0.30075047750377283683, 0.21850801222441053540,
-0.60150095500754567366),
(0.60150095500754567366, 0, 0.37174803446018449013),
(0.4156269377774534286, -0.57206140281768429760, 0),
(0.4156269377774534286, 0.57206140281768429760, 0),
(0.37174803446018449013, 0, -0.60150095500754567366),
(-0.4156269377774534286, -0.57206140281768429760, 0),
(-0.4156269377774534286, 0.57206140281768429760, 0),
(-0.67249851196395732696, -0.21850801222441053540, 0),
(-0.67249851196395732696, 0.21850801222441053540, 0),
(0.67249851196395732696, -0.21850801222441053540, 0),
(0.67249851196395732696, 0.21850801222441053540, 0),
(-0.37174803446018449013, 0, 0.60150095500754567366),
(-0.48662449473386508189, -0.35355339059327376220,
0.37174803446018449013),
(-0.48662449473386508189, 0.35355339059327376220,
0.37174803446018449013),
(-0.18587401723009224507, -0.57206140281768429760,
-0.37174803446018449013),
(-0.18587401723009224507, 0.57206140281768429760,
-0.37174803446018449013),
(-0.11487646027368059176, -0.35355339059327376220,
0.60150095500754567366),
(-0.11487646027368059176, 0.35355339059327376220,
0.60150095500754567366)],
[0, 10, 16], [23, 10, 0], [16, 13, 0],
[0, 13, 23], [16, 10, 1], [1, 10, 23],
[1, 13, 16], [23, 13, 1], [2, 4, 19],
[22, 4, 2], [2, 19, 27], [27, 22, 2],
[20, 5, 3], [3, 5, 21], [26, 20, 3],
[3, 21, 26], [29, 19, 4], [4, 22, 29],
[5, 20, 28], [28, 21, 5], [6, 8, 15],
[17, 8, 6], [6, 15, 25], [25, 17, 6],
[14, 9, 7], [7, 9, 18], [24, 14, 7],
[7, 18, 24], [8, 12, 15], [17, 12, 8],
[14, 11, 9], [9, 11, 18], [11, 14, 24],
[24, 18, 11], [25, 15, 12], [12, 17, 25],
[29, 27, 19], [20, 26, 28], [28, 26, 21],
[22, 27, 29]]
assert Abs(polytope_integrate(octahedron_five_compound, expr)) - 0.353553\
< 1e-6
cube_five_compound = [[(-0.1624598481164531631, -0.5, -0.6881909602355867691),
(-0.1624598481164531631, 0.5, -0.6881909602355867691),
(0.1624598481164531631, -0.5, 0.68819096023558676910),
(0.1624598481164531631, 0.5, 0.68819096023558676910),
(-0.52573111211913359231, 0, -0.6881909602355867691),
(0.52573111211913359231, 0, 0.68819096023558676910),
(-0.26286555605956679615, -0.8090169943749474241,
-0.1624598481164531631),
(-0.26286555605956679615, 0.8090169943749474241,
-0.1624598481164531631),
(0.26286555605956680301, -0.8090169943749474241,
0.1624598481164531631),
(0.26286555605956680301, 0.8090169943749474241,
0.1624598481164531631),
(-0.42532540417601993887, -0.3090169943749474241,
0.68819096023558676910),
(-0.42532540417601993887, 0.30901699437494742410,
0.68819096023558676910),
(0.42532540417601996609, -0.3090169943749474241,
-0.6881909602355867691),
(0.42532540417601996609, 0.30901699437494742410,
-0.6881909602355867691),
(-0.6881909602355867691, -0.5, 0.1624598481164531631),
(-0.6881909602355867691, 0.5, 0.1624598481164531631),
(0.68819096023558676910, -0.5, -0.1624598481164531631),
(0.68819096023558676910, 0.5, -0.1624598481164531631),
(-0.85065080835203998877, 0, -0.1624598481164531631),
(0.85065080835203993218, 0, 0.1624598481164531631)],
[18, 10, 3, 7], [13, 19, 8, 0], [18, 0, 8, 10],
[3, 19, 13, 7], [18, 7, 13, 0], [8, 19, 3, 10],
[6, 2, 11, 18], [1, 9, 19, 12], [11, 9, 1, 18],
[6, 12, 19, 2], [1, 12, 6, 18], [11, 2, 19, 9],
[4, 14, 11, 7], [17, 5, 8, 12], [4, 12, 8, 14],
[11, 5, 17, 7], [4, 7, 17, 12], [8, 5, 11, 14],
[6, 10, 15, 4], [13, 9, 5, 16], [15, 9, 13, 4],
[6, 16, 5, 10], [13, 16, 6, 4], [15, 10, 5, 9],
[14, 15, 1, 0], [16, 17, 3, 2], [14, 2, 3, 15],
[1, 17, 16, 0], [14, 0, 16, 2], [3, 17, 1, 15]]
assert Abs(polytope_integrate(cube_five_compound, expr) - 1.25) < 1e-12
echidnahedron = [[(0, 0, -2.4898982848827801995),
(0, 0, 2.4898982848827802734),
(0, -4.2360679774997896964, -2.4898982848827801995),
(0, -4.2360679774997896964, 2.4898982848827802734),
(0, 4.2360679774997896964, -2.4898982848827801995),
(0, 4.2360679774997896964, 2.4898982848827802734),
(-4.0287400534704067567, -1.3090169943749474241, -2.4898982848827801995),
(-4.0287400534704067567, -1.3090169943749474241, 2.4898982848827802734),
(-4.0287400534704067567, 1.3090169943749474241, -2.4898982848827801995),
(-4.0287400534704067567, 1.3090169943749474241, 2.4898982848827802734),
(4.0287400534704069747, -1.3090169943749474241, -2.4898982848827801995),
(4.0287400534704069747, -1.3090169943749474241, 2.4898982848827802734),
(4.0287400534704069747, 1.3090169943749474241, -2.4898982848827801995),
(4.0287400534704069747, 1.3090169943749474241, 2.4898982848827802734),
(-2.4898982848827801995, -3.4270509831248422723, -2.4898982848827801995),
(-2.4898982848827801995, -3.4270509831248422723, 2.4898982848827802734),
(-2.4898982848827801995, 3.4270509831248422723, -2.4898982848827801995),
(-2.4898982848827801995, 3.4270509831248422723, 2.4898982848827802734),
(2.4898982848827802734, -3.4270509831248422723, -2.4898982848827801995),
(2.4898982848827802734, -3.4270509831248422723, 2.4898982848827802734),
(2.4898982848827802734, 3.4270509831248422723, -2.4898982848827801995),
(2.4898982848827802734, 3.4270509831248422723, 2.4898982848827802734),
(-4.7169310137059934362, -0.8090169943749474241, -1.1135163644116066184),
(-4.7169310137059934362, 0.8090169943749474241, -1.1135163644116066184),
(4.7169310137059937438, -0.8090169943749474241, 1.11351636441160673519),
(4.7169310137059937438, 0.8090169943749474241, 1.11351636441160673519),
(-4.2916056095299737777, -2.1180339887498948482, 1.11351636441160673519),
(-4.2916056095299737777, 2.1180339887498948482, 1.11351636441160673519),
(4.2916056095299737777, -2.1180339887498948482, -1.1135163644116066184),
(4.2916056095299737777, 2.1180339887498948482, -1.1135163644116066184),
(-3.6034146492943870399, 0, -3.3405490932348205213),
(3.6034146492943870399, 0, 3.3405490932348202056),
(-3.3405490932348205213, -3.4270509831248422723, 1.11351636441160673519),
(-3.3405490932348205213, 3.4270509831248422723, 1.11351636441160673519),
(3.3405490932348202056, -3.4270509831248422723, -1.1135163644116066184),
(3.3405490932348202056, 3.4270509831248422723, -1.1135163644116066184),
(-2.9152236890588002395, -2.1180339887498948482, 3.3405490932348202056),
(-2.9152236890588002395, 2.1180339887498948482, 3.3405490932348202056),
(2.9152236890588002395, -2.1180339887498948482, -3.3405490932348205213),
(2.9152236890588002395, 2.1180339887498948482, -3.3405490932348205213),
(-2.2270327288232132368, 0, -1.1135163644116066184),
(-2.2270327288232132368, -4.2360679774997896964, -1.1135163644116066184),
(-2.2270327288232132368, 4.2360679774997896964, -1.1135163644116066184),
(2.2270327288232134704, 0, 1.11351636441160673519),
(2.2270327288232134704, -4.2360679774997896964, 1.11351636441160673519),
(2.2270327288232134704, 4.2360679774997896964, 1.11351636441160673519),
(-1.8017073246471935200, -1.3090169943749474241, 1.11351636441160673519),
(-1.8017073246471935200, 1.3090169943749474241, 1.11351636441160673519),
(1.8017073246471935043, -1.3090169943749474241, -1.1135163644116066184),
(1.8017073246471935043, 1.3090169943749474241, -1.1135163644116066184),
(-1.3763819204711735382, 0, -4.7169310137059934362),
(-1.3763819204711735382, 0, 0.26286555605956679615),
(1.37638192047117353821, 0, 4.7169310137059937438),
(1.37638192047117353821, 0, -0.26286555605956679615),
(-1.1135163644116066184, -3.4270509831248422723, -3.3405490932348205213),
(-1.1135163644116066184, -0.8090169943749474241, 4.7169310137059937438),
(-1.1135163644116066184, -0.8090169943749474241, -0.26286555605956679615),
(-1.1135163644116066184, 0.8090169943749474241, 4.7169310137059937438),
(-1.1135163644116066184, 0.8090169943749474241, -0.26286555605956679615),
(-1.1135163644116066184, 3.4270509831248422723, -3.3405490932348205213),
(1.11351636441160673519, -3.4270509831248422723, 3.3405490932348202056),
(1.11351636441160673519, -0.8090169943749474241, -4.7169310137059934362),
(1.11351636441160673519, -0.8090169943749474241, 0.26286555605956679615),
(1.11351636441160673519, 0.8090169943749474241, -4.7169310137059934362),
(1.11351636441160673519, 0.8090169943749474241, 0.26286555605956679615),
(1.11351636441160673519, 3.4270509831248422723, 3.3405490932348202056),
(-0.85065080835203998877, 0, 1.11351636441160673519),
(0.85065080835203993218, 0, -1.1135163644116066184),
(-0.6881909602355867691, -0.5, -1.1135163644116066184),
(-0.6881909602355867691, 0.5, -1.1135163644116066184),
(-0.6881909602355867691, -4.7360679774997896964, -1.1135163644116066184),
(-0.6881909602355867691, -2.1180339887498948482, -1.1135163644116066184),
(-0.6881909602355867691, 2.1180339887498948482, -1.1135163644116066184),
(-0.6881909602355867691, 4.7360679774997896964, -1.1135163644116066184),
(0.68819096023558676910, -0.5, 1.11351636441160673519),
(0.68819096023558676910, 0.5, 1.11351636441160673519),
(0.68819096023558676910, -4.7360679774997896964, 1.11351636441160673519),
(0.68819096023558676910, -2.1180339887498948482, 1.11351636441160673519),
(0.68819096023558676910, 2.1180339887498948482, 1.11351636441160673519),
(0.68819096023558676910, 4.7360679774997896964, 1.11351636441160673519),
(-0.42532540417601993887, -1.3090169943749474241, -4.7169310137059934362),
(-0.42532540417601993887, -1.3090169943749474241, 0.26286555605956679615),
(-0.42532540417601993887, 1.3090169943749474241, -4.7169310137059934362),
(-0.42532540417601993887, 1.3090169943749474241, 0.26286555605956679615),
(-0.26286555605956679615, -0.8090169943749474241, 1.11351636441160673519),
(-0.26286555605956679615, 0.8090169943749474241, 1.11351636441160673519),
(0.26286555605956679615, -0.8090169943749474241, -1.1135163644116066184),
(0.26286555605956679615, 0.8090169943749474241, -1.1135163644116066184),
(0.42532540417601996609, -1.3090169943749474241, 4.7169310137059937438),
(0.42532540417601996609, -1.3090169943749474241, -0.26286555605956679615),
(0.42532540417601996609, 1.3090169943749474241, 4.7169310137059937438),
(0.42532540417601996609, 1.3090169943749474241, -0.26286555605956679615)],
[9, 66, 47], [44, 62, 77], [20, 91, 49], [33, 47, 83],
[3, 77, 84], [12, 49, 53], [36, 84, 66], [28, 53, 62],
[73, 83, 91], [15, 84, 46], [25, 64, 43], [16, 58, 72],
[26, 46, 51], [11, 43, 74], [4, 72, 91], [60, 74, 84],
[35, 91, 64], [23, 51, 58], [19, 74, 77], [79, 83, 78],
[6, 56, 40], [76, 77, 81], [21, 78, 75], [8, 40, 58],
[31, 75, 74], [42, 58, 83], [41, 81, 56], [13, 75, 43],
[27, 51, 47], [2, 89, 71], [24, 43, 62], [17, 47, 85],
[14, 71, 56], [65, 85, 75], [22, 56, 51], [34, 62, 89],
[5, 85, 78], [32, 81, 46], [10, 53, 48], [45, 78, 64],
[7, 46, 66], [18, 48, 89], [37, 66, 85], [70, 89, 81],
[29, 64, 53], [88, 74, 1], [38, 67, 48], [42, 83, 72],
[57, 1, 85], [34, 48, 62], [59, 72, 87], [19, 62, 74],
[63, 87, 67], [17, 85, 83], [52, 75, 1], [39, 87, 49],
[22, 51, 40], [55, 1, 66], [29, 49, 64], [30, 40, 69],
[13, 64, 75], [82, 69, 87], [7, 66, 51], [90, 85, 1],
[59, 69, 72], [70, 81, 71], [88, 1, 84], [73, 72, 83],
[54, 71, 68], [5, 83, 85], [50, 68, 69], [3, 84, 81],
[57, 66, 1], [30, 68, 40], [28, 62, 48], [52, 1, 74],
[23, 40, 51], [38, 48, 86], [9, 51, 66], [80, 86, 68],
[11, 74, 62], [55, 84, 1], [54, 86, 71], [35, 64, 49],
[90, 1, 75], [41, 71, 81], [39, 49, 67], [15, 81, 84],
[61, 67, 86], [21, 75, 64], [24, 53, 43], [50, 69, 0],
[37, 85, 47], [31, 43, 75], [61, 0, 67], [27, 47, 58],
[10, 67, 53], [8, 58, 69], [90, 75, 85], [45, 91, 78],
[80, 68, 0], [36, 66, 46], [65, 78, 85], [63, 0, 87],
[32, 46, 56], [20, 87, 91], [14, 56, 68], [57, 85, 66],
[33, 58, 47], [61, 86, 0], [60, 84, 77], [37, 47, 66],
[82, 0, 69], [44, 77, 89], [16, 69, 58], [18, 89, 86],
[55, 66, 84], [26, 56, 46], [63, 67, 0], [31, 74, 43],
[36, 46, 84], [50, 0, 68], [25, 43, 53], [6, 68, 56],
[12, 53, 67], [88, 84, 74], [76, 89, 77], [82, 87, 0],
[65, 75, 78], [60, 77, 74], [80, 0, 86], [79, 78, 91],
[2, 86, 89], [4, 91, 87], [52, 74, 75], [21, 64, 78],
[18, 86, 48], [23, 58, 40], [5, 78, 83], [28, 48, 53],
[6, 40, 68], [25, 53, 64], [54, 68, 86], [33, 83, 58],
[17, 83, 47], [12, 67, 49], [41, 56, 71], [9, 47, 51],
[35, 49, 91], [2, 71, 86], [79, 91, 83], [38, 86, 67],
[26, 51, 56], [7, 51, 46], [4, 87, 72], [34, 89, 48],
[15, 46, 81], [42, 72, 58], [10, 48, 67], [27, 58, 51],
[39, 67, 87], [76, 81, 89], [3, 81, 77], [8, 69, 40],
[29, 53, 49], [19, 77, 62], [22, 40, 56], [20, 49, 87],
[32, 56, 81], [59, 87, 69], [24, 62, 53], [11, 62, 43],
[14, 68, 71], [73, 91, 72], [13, 43, 64], [70, 71, 89],
[16, 72, 69], [44, 89, 62], [30, 69, 68], [45, 64, 91]]
# Actual volume is : 51.405764746872634
assert Abs(polytope_integrate(echidnahedron, 1) - 51.4057647468726) < 1e-12
assert Abs(polytope_integrate(echidnahedron, expr) - 253.569603474519) <\
1e-12
# Tests for many polynomials with maximum degree given(2D case).
assert polytope_integrate(cube2, [x**2, y*z], max_degree=2) == \
{y * z: 3125 / S(4), x ** 2: 3125 / S(3)}
assert polytope_integrate(cube2, max_degree=2) == \
{1: 125, x: 625 / S(2), x * z: 3125 / S(4), y: 625 / S(2),
y * z: 3125 / S(4), z ** 2: 3125 / S(3), y ** 2: 3125 / S(3),
z: 625 / S(2), x * y: 3125 / S(4), x ** 2: 3125 / S(3)}
def test_point_sort():
assert point_sort([Point(0, 0), Point(1, 0), Point(1, 1)]) == \
[Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)]
fig6 = Polygon((0, 0), (1, 0), (1, 1))
assert polytope_integrate(fig6, x*y) == Rational(-1, 8)
assert polytope_integrate(fig6, x*y, clockwise = True) == Rational(1, 8)
def test_polytopes_intersecting_sides():
fig5 = Polygon(Point(-4.165, -0.832), Point(-3.668, 1.568),
Point(-3.266, 1.279), Point(-1.090, -2.080),
Point(3.313, -0.683), Point(3.033, -4.845),
Point(-4.395, 4.840), Point(-1.007, -3.328))
assert polytope_integrate(fig5, x**2 + x*y + y**2) ==\
S(1633405224899363)/(24*10**12)
fig6 = Polygon(Point(-3.018, -4.473), Point(-0.103, 2.378),
Point(-1.605, -2.308), Point(4.516, -0.771),
Point(4.203, 0.478))
assert polytope_integrate(fig6, x**2 + x*y + y**2) ==\
S(88161333955921)/(3*10**12)
def test_max_degree():
polygon = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
polys = [1, x, y, x*y, x**2*y, x*y**2]
assert polytope_integrate(polygon, polys, max_degree=3) == \
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)}
def test_main_integrate3d():
cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
vertices = cube[0]
faces = cube[1:]
hp_params = hyperplane_parameters(faces, vertices)
assert main_integrate3d(1, faces, vertices, hp_params) == -125
assert main_integrate3d(1, faces, vertices, hp_params, max_degree=1) == \
{1: -125, y: Rational(-625, 2), z: Rational(-625, 2), x: Rational(-625, 2)}
def test_main_integrate():
triangle = Polygon((0, 3), (5, 3), (1, 1))
facets = triangle.sides
hp_params = hyperplane_parameters(triangle)
assert main_integrate(x**2 + y**2, facets, hp_params) == Rational(325, 6)
assert main_integrate(x**2 + y**2, facets, hp_params, max_degree=1) == \
{0: 0, 1: 5, y: Rational(35, 3), x: 10}
def test_polygon_integrate():
cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
facet = cube[1]
facets = cube[1:]
vertices = cube[0]
assert polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0) == -25
def test_distance_to_side():
point = (0, 0, 0)
assert distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0)) == -sqrt(2)/2
def test_lineseg_integrate():
polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)]
line_seg = [(0, 5, 0), (5, 5, 0)]
assert lineseg_integrate(polygon, 0, line_seg, 1, 0) == 5
assert lineseg_integrate(polygon, 0, line_seg, 0, 0) == 0
def test_integration_reduction():
triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
facets = triangle.sides
a, b = hyperplane_parameters(triangle)[0]
assert integration_reduction(facets, 0, a, b, 1, (x, y), 0) == 5
assert integration_reduction(facets, 0, a, b, 0, (x, y), 0) == 0
def test_integration_reduction_dynamic():
triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
facets = triangle.sides
a, b = hyperplane_parameters(triangle)[0]
x0 = facets[0].points[0]
monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\
[y, 0, 1, 15], [x, 1, 0, None]]
assert integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1,\
0, 1, x0, monomial_values, 3) == Rational(25, 2)
assert integration_reduction_dynamic(facets, 0, a, b, 0, 1, (x, y), 1,\
0, 1, x0, monomial_values, 3) == 0
def test_is_vertex():
assert is_vertex(2) is False
assert is_vertex((2, 3)) is True
assert is_vertex(Point(2, 3)) is True
assert is_vertex((2, 3, 4)) is True
assert is_vertex((2, 3, 4, 5)) is False
|
34d18326d761316d9ed7f9a8583da3cef9ac7276b06771006addd5caa595819f | from sympy import Rational, sqrt, symbols, sin, exp, log, sinh, cosh, cos, pi, \
I, erf, tan, asin, asinh, acos, atan, Function, Derivative, diff, simplify, \
LambertW, Ne, Piecewise, Symbol, Add, ratsimp, Integral, Sum, \
besselj, besselk, bessely, jn, tanh
from sympy.integrals.heurisch import components, heurisch, heurisch_wrapper
from sympy.utilities.pytest import XFAIL, skip, slow, ON_TRAVIS
from sympy.integrals.integrals import integrate
x, y, z, nu = symbols('x,y,z,nu')
f = Function('f')
def test_components():
assert components(x*y, x) == {x}
assert components(1/(x + y), x) == {x}
assert components(sin(x), x) == {sin(x), x}
assert components(sin(x)*sqrt(log(x)), x) == \
{log(x), sin(x), sqrt(log(x)), x}
assert components(x*sin(exp(x)*y), x) == \
{sin(y*exp(x)), x, exp(x)}
assert components(x**Rational(17, 54)/sqrt(sin(x)), x) == \
{sin(x), x**Rational(1, 54), sqrt(sin(x)), x}
assert components(f(x), x) == \
{x, f(x)}
assert components(Derivative(f(x), x), x) == \
{x, f(x), Derivative(f(x), x)}
assert components(f(x)*diff(f(x), x), x) == \
{x, f(x), Derivative(f(x), x), Derivative(f(x), x)}
def test_issue_10680():
assert isinstance(integrate(x**log(x**log(x**log(x))),x), Integral)
def test_heurisch_polynomials():
assert heurisch(1, x) == x
assert heurisch(x, x) == x**2/2
assert heurisch(x**17, x) == x**18/18
# For coverage
assert heurisch_wrapper(y, x) == y*x
def test_heurisch_fractions():
assert heurisch(1/x, x) == log(x)
assert heurisch(1/(2 + x), x) == log(x + 2)
assert heurisch(1/(x + sin(y)), x) == log(x + sin(y))
# Up to a constant, where C = pi*I*Rational(5, 12), Mathematica gives identical
# result in the first case. The difference is because sympy changes
# signs of expressions without any care.
# XXX ^ ^ ^ is this still correct?
assert heurisch(5*x**5/(
2*x**6 - 5), x) in [5*log(2*x**6 - 5) / 12, 5*log(-2*x**6 + 5) / 12]
assert heurisch(5*x**5/(2*x**6 + 5), x) == 5*log(2*x**6 + 5) / 12
assert heurisch(1/x**2, x) == -1/x
assert heurisch(-1/x**5, x) == 1/(4*x**4)
def test_heurisch_log():
assert heurisch(log(x), x) == x*log(x) - x
assert heurisch(log(3*x), x) == -x + x*log(3) + x*log(x)
assert heurisch(log(x**2), x) in [x*log(x**2) - 2*x, 2*x*log(x) - 2*x]
def test_heurisch_exp():
assert heurisch(exp(x), x) == exp(x)
assert heurisch(exp(-x), x) == -exp(-x)
assert heurisch(exp(17*x), x) == exp(17*x) / 17
assert heurisch(x*exp(x), x) == x*exp(x) - exp(x)
assert heurisch(x*exp(x**2), x) == exp(x**2) / 2
assert heurisch(exp(-x**2), x) is None
assert heurisch(2**x, x) == 2**x/log(2)
assert heurisch(x*2**x, x) == x*2**x/log(2) - 2**x*log(2)**(-2)
assert heurisch(Integral(x**z*y, (y, 1, 2), (z, 2, 3)).function, x) == (x*x**z*y)/(z+1)
assert heurisch(Sum(x**z, (z, 1, 2)).function, z) == x**z/log(x)
def test_heurisch_trigonometric():
assert heurisch(sin(x), x) == -cos(x)
assert heurisch(pi*sin(x) + 1, x) == x - pi*cos(x)
assert heurisch(cos(x), x) == sin(x)
assert heurisch(tan(x), x) in [
log(1 + tan(x)**2)/2,
log(tan(x) + I) + I*x,
log(tan(x) - I) - I*x,
]
assert heurisch(sin(x)*sin(y), x) == -cos(x)*sin(y)
assert heurisch(sin(x)*sin(y), y) == -cos(y)*sin(x)
# gives sin(x) in answer when run via setup.py and cos(x) when run via py.test
assert heurisch(sin(x)*cos(x), x) in [sin(x)**2 / 2, -cos(x)**2 / 2]
assert heurisch(cos(x)/sin(x), x) == log(sin(x))
assert heurisch(x*sin(7*x), x) == sin(7*x) / 49 - x*cos(7*x) / 7
assert heurisch(1/pi/4 * x**2*cos(x), x) == 1/pi/4*(x**2*sin(x) -
2*sin(x) + 2*x*cos(x))
assert heurisch(acos(x/4) * asin(x/4), x) == 2*x - (sqrt(16 - x**2))*asin(x/4) \
+ (sqrt(16 - x**2))*acos(x/4) + x*asin(x/4)*acos(x/4)
assert heurisch(sin(x)/(cos(x)**2+1), x) == -atan(cos(x)) #fixes issue 13723
assert heurisch(1/(cos(x)+2), x) == 2*sqrt(3)*atan(sqrt(3)*tan(x/2)/3)/3
assert heurisch(2*sin(x)*cos(x)/(sin(x)**4 + 1), x) == atan(sqrt(2)*sin(x)
- 1) - atan(sqrt(2)*sin(x) + 1)
assert heurisch(1/cosh(x), x) == 2*atan(tanh(x/2))
def test_heurisch_hyperbolic():
assert heurisch(sinh(x), x) == cosh(x)
assert heurisch(cosh(x), x) == sinh(x)
assert heurisch(x*sinh(x), x) == x*cosh(x) - sinh(x)
assert heurisch(x*cosh(x), x) == x*sinh(x) - cosh(x)
assert heurisch(
x*asinh(x/2), x) == x**2*asinh(x/2)/2 + asinh(x/2) - x*sqrt(4 + x**2)/4
def test_heurisch_mixed():
assert heurisch(sin(x)*exp(x), x) == exp(x)*sin(x)/2 - exp(x)*cos(x)/2
def test_heurisch_radicals():
assert heurisch(1/sqrt(x), x) == 2*sqrt(x)
assert heurisch(1/sqrt(x)**3, x) == -2/sqrt(x)
assert heurisch(sqrt(x)**3, x) == 2*sqrt(x)**5/5
assert heurisch(sin(x)*sqrt(cos(x)), x) == -2*sqrt(cos(x))**3/3
y = Symbol('y')
assert heurisch(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
2*sqrt(x)*cos(y*sqrt(x))/y
assert heurisch_wrapper(sin(y*sqrt(x)), x) == Piecewise(
(-2*sqrt(x)*cos(sqrt(x)*y)/y + 2*sin(sqrt(x)*y)/y**2, Ne(y, 0)),
(0, True))
y = Symbol('y', positive=True)
assert heurisch_wrapper(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
2*sqrt(x)*cos(y*sqrt(x))/y
def test_heurisch_special():
assert heurisch(erf(x), x) == x*erf(x) + exp(-x**2)/sqrt(pi)
assert heurisch(exp(-x**2)*erf(x), x) == sqrt(pi)*erf(x)**2 / 4
def test_heurisch_symbolic_coeffs():
assert heurisch(1/(x + y), x) == log(x + y)
assert heurisch(1/(x + sqrt(2)), x) == log(x + sqrt(2))
assert simplify(diff(heurisch(log(x + y + z), y), y)) == log(x + y + z)
def test_heurisch_symbolic_coeffs_1130():
y = Symbol('y')
assert heurisch_wrapper(1/(x**2 + y), x) == Piecewise(
(-I*log(x - I*sqrt(y))/(2*sqrt(y))
+ I*log(x + I*sqrt(y))/(2*sqrt(y)), Ne(y, 0)),
(-1/x, True))
y = Symbol('y', positive=True)
assert heurisch_wrapper(1/(x**2 + y), x) == (atan(x/sqrt(y))/sqrt(y))
def test_heurisch_hacking():
assert heurisch(sqrt(1 + 7*x**2), x, hints=[]) == \
x*sqrt(1 + 7*x**2)/2 + sqrt(7)*asinh(sqrt(7)*x)/14
assert heurisch(sqrt(1 - 7*x**2), x, hints=[]) == \
x*sqrt(1 - 7*x**2)/2 + sqrt(7)*asin(sqrt(7)*x)/14
assert heurisch(1/sqrt(1 + 7*x**2), x, hints=[]) == \
sqrt(7)*asinh(sqrt(7)*x)/7
assert heurisch(1/sqrt(1 - 7*x**2), x, hints=[]) == \
sqrt(7)*asin(sqrt(7)*x)/7
assert heurisch(exp(-7*x**2), x, hints=[]) == \
sqrt(7*pi)*erf(sqrt(7)*x)/14
assert heurisch(1/sqrt(9 - 4*x**2), x, hints=[]) == \
asin(x*Rational(2, 3))/2
assert heurisch(1/sqrt(9 + 4*x**2), x, hints=[]) == \
asinh(x*Rational(2, 3))/2
def test_heurisch_function():
assert heurisch(f(x), x) is None
@XFAIL
def test_heurisch_function_derivative():
# TODO: it looks like this used to work just by coincindence and
# thanks to sloppy implementation. Investigate why this used to
# work at all and if support for this can be restored.
df = diff(f(x), x)
assert heurisch(f(x)*df, x) == f(x)**2/2
assert heurisch(f(x)**2*df, x) == f(x)**3/3
assert heurisch(df/f(x), x) == log(f(x))
def test_heurisch_wrapper():
f = 1/(y + x)
assert heurisch_wrapper(f, x) == log(x + y)
f = 1/(y - x)
assert heurisch_wrapper(f, x) == -log(x - y)
f = 1/((y - x)*(y + x))
assert heurisch_wrapper(f, x) == Piecewise(
(-log(x - y)/(2*y) + log(x + y)/(2*y), Ne(y, 0)), (1/x, True))
# issue 6926
f = sqrt(x**2/((y - x)*(y + x)))
assert heurisch_wrapper(f, x) == x*sqrt(x**2)*sqrt(1/(-x**2 + y**2)) \
- y**2*sqrt(x**2)*sqrt(1/(-x**2 + y**2))/x
def test_issue_3609():
assert heurisch(1/(x * (1 + log(x)**2)), x) == atan(log(x))
### These are examples from the Poor Man's Integrator
### http://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/examples/
def test_pmint_rat():
# TODO: heurisch() is off by a constant: -3/4. Possibly different permutation
# would give the optimal result?
def drop_const(expr, x):
if expr.is_Add:
return Add(*[ arg for arg in expr.args if arg.has(x) ])
else:
return expr
f = (x**7 - 24*x**4 - 4*x**2 + 8*x - 8)/(x**8 + 6*x**6 + 12*x**4 + 8*x**2)
g = (4 + 8*x**2 + 6*x + 3*x**3)/(x**5 + 4*x**3 + 4*x) + log(x)
assert drop_const(ratsimp(heurisch(f, x)), x) == g
def test_pmint_trig():
f = (x - tan(x)) / tan(x)**2 + tan(x)
g = -x**2/2 - x/tan(x) + log(tan(x)**2 + 1)/2
assert heurisch(f, x) == g
@slow # 8 seconds on 3.4 GHz
def test_pmint_logexp():
if ON_TRAVIS:
# See https://github.com/sympy/sympy/pull/12795
skip("Too slow for travis.")
f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x
g = log(x + exp(x) + log(x)) + 1/(x + exp(x) + log(x))
assert ratsimp(heurisch(f, x)) == g
@XFAIL # there's a hash dependent failure lurking here
def test_pmint_erf():
f = exp(-x**2)*erf(x)/(erf(x)**3 - erf(x)**2 - erf(x) + 1)
g = sqrt(pi)*log(erf(x) - 1)/8 - sqrt(pi)*log(erf(x) + 1)/8 - sqrt(pi)/(4*erf(x) - 4)
assert ratsimp(heurisch(f, x)) == g
def test_pmint_LambertW():
f = LambertW(x)
g = x*LambertW(x) - x + x/LambertW(x)
assert heurisch(f, x) == g
def test_pmint_besselj():
f = besselj(nu + 1, x)/besselj(nu, x)
g = nu*log(x) - log(besselj(nu, x))
assert heurisch(f, x) == g
f = (nu*besselj(nu, x) - x*besselj(nu + 1, x))/x
g = besselj(nu, x)
assert heurisch(f, x) == g
f = jn(nu + 1, x)/jn(nu, x)
g = nu*log(x) - log(jn(nu, x))
assert heurisch(f, x) == g
@slow
def test_pmint_bessel_products():
# Note: Derivatives of Bessel functions have many forms.
# Recurrence relations are needed for comparisons.
if ON_TRAVIS:
skip("Too slow for travis.")
f = x*besselj(nu, x)*bessely(nu, 2*x)
g = -2*x*besselj(nu, x)*bessely(nu - 1, 2*x)/3 + x*besselj(nu - 1, x)*bessely(nu, 2*x)/3
assert heurisch(f, x) == g
f = x*besselj(nu, x)*besselk(nu, 2*x)
g = -2*x*besselj(nu, x)*besselk(nu - 1, 2*x)/5 - x*besselj(nu - 1, x)*besselk(nu, 2*x)/5
assert heurisch(f, x) == g
@slow # 110 seconds on 3.4 GHz
def test_pmint_WrightOmega():
if ON_TRAVIS:
skip("Too slow for travis.")
def omega(x):
return LambertW(exp(x))
f = (1 + omega(x) * (2 + cos(omega(x)) * (x + omega(x))))/(1 + omega(x))/(x + omega(x))
g = log(x + LambertW(exp(x))) + sin(LambertW(exp(x)))
assert heurisch(f, x) == g
def test_RR():
# Make sure the algorithm does the right thing if the ring is RR. See
# issue 8685.
assert heurisch(sqrt(1 + 0.25*x**2), x, hints=[]) == \
0.5*x*sqrt(0.25*x**2 + 1) + 1.0*asinh(0.5*x)
# TODO: convert the rest of PMINT tests:
# Airy functions
# f = (x - AiryAi(x)*AiryAi(1, x)) / (x**2 - AiryAi(x)**2)
# g = Rational(1,2)*ln(x + AiryAi(x)) + Rational(1,2)*ln(x - AiryAi(x))
# f = x**2 * AiryAi(x)
# g = -AiryAi(x) + AiryAi(1, x)*x
# Whittaker functions
# f = WhittakerW(mu + 1, nu, x) / (WhittakerW(mu, nu, x) * x)
# g = x/2 - mu*ln(x) - ln(WhittakerW(mu, nu, x))
|
88531da9c937ea090bfb292c2df95ac083989b0fb43f33b6b458ffa9d2ba1e38 | from sympy.core import S, Rational
from sympy.integrals.quadrature import (gauss_legendre, gauss_laguerre,
gauss_hermite, gauss_gen_laguerre,
gauss_chebyshev_t, gauss_chebyshev_u,
gauss_jacobi, gauss_lobatto)
def test_legendre():
x, w = gauss_legendre(1, 17)
assert [str(r) for r in x] == ['0']
assert [str(r) for r in w] == ['2.0000000000000000']
x, w = gauss_legendre(2, 17)
assert [str(r) for r in x] == [
'-0.57735026918962576',
'0.57735026918962576']
assert [str(r) for r in w] == [
'1.0000000000000000',
'1.0000000000000000']
x, w = gauss_legendre(3, 17)
assert [str(r) for r in x] == [
'-0.77459666924148338',
'0',
'0.77459666924148338']
assert [str(r) for r in w] == [
'0.55555555555555556',
'0.88888888888888889',
'0.55555555555555556']
x, w = gauss_legendre(4, 17)
assert [str(r) for r in x] == [
'-0.86113631159405258',
'-0.33998104358485626',
'0.33998104358485626',
'0.86113631159405258']
assert [str(r) for r in w] == [
'0.34785484513745386',
'0.65214515486254614',
'0.65214515486254614',
'0.34785484513745386']
def test_legendre_precise():
x, w = gauss_legendre(3, 40)
assert [str(r) for r in x] == [
'-0.7745966692414833770358530799564799221666',
'0',
'0.7745966692414833770358530799564799221666']
assert [str(r) for r in w] == [
'0.5555555555555555555555555555555555555556',
'0.8888888888888888888888888888888888888889',
'0.5555555555555555555555555555555555555556']
def test_laguerre():
x, w = gauss_laguerre(1, 17)
assert [str(r) for r in x] == ['1.0000000000000000']
assert [str(r) for r in w] == ['1.0000000000000000']
x, w = gauss_laguerre(2, 17)
assert [str(r) for r in x] == [
'0.58578643762690495',
'3.4142135623730950']
assert [str(r) for r in w] == [
'0.85355339059327376',
'0.14644660940672624']
x, w = gauss_laguerre(3, 17)
assert [str(r) for r in x] == [
'0.41577455678347908',
'2.2942803602790417',
'6.2899450829374792',
]
assert [str(r) for r in w] == [
'0.71109300992917302',
'0.27851773356924085',
'0.010389256501586136',
]
x, w = gauss_laguerre(4, 17)
assert [str(r) for r in x] == [
'0.32254768961939231',
'1.7457611011583466',
'4.5366202969211280',
'9.3950709123011331']
assert [str(r) for r in w] == [
'0.60315410434163360',
'0.35741869243779969',
'0.038887908515005384',
'0.00053929470556132745']
x, w = gauss_laguerre(5, 17)
assert [str(r) for r in x] == [
'0.26356031971814091',
'1.4134030591065168',
'3.5964257710407221',
'7.0858100058588376',
'12.640800844275783']
assert [str(r) for r in w] == [
'0.52175561058280865',
'0.39866681108317593',
'0.075942449681707595',
'0.0036117586799220485',
'2.3369972385776228e-5']
def test_laguerre_precise():
x, w = gauss_laguerre(3, 40)
assert [str(r) for r in x] == [
'0.4157745567834790833115338731282744735466',
'2.294280360279041719822050361359593868960',
'6.289945082937479196866415765512131657493']
assert [str(r) for r in w] == [
'0.7110930099291730154495901911425944313094',
'0.2785177335692408488014448884567264810349',
'0.01038925650158613574896492040067908765572']
def test_hermite():
x, w = gauss_hermite(1, 17)
assert [str(r) for r in x] == ['0']
assert [str(r) for r in w] == ['1.7724538509055160']
x, w = gauss_hermite(2, 17)
assert [str(r) for r in x] == [
'-0.70710678118654752',
'0.70710678118654752']
assert [str(r) for r in w] == [
'0.88622692545275801',
'0.88622692545275801']
x, w = gauss_hermite(3, 17)
assert [str(r) for r in x] == [
'-1.2247448713915890',
'0',
'1.2247448713915890']
assert [str(r) for r in w] == [
'0.29540897515091934',
'1.1816359006036774',
'0.29540897515091934']
x, w = gauss_hermite(4, 17)
assert [str(r) for r in x] == [
'-1.6506801238857846',
'-0.52464762327529032',
'0.52464762327529032',
'1.6506801238857846']
assert [str(r) for r in w] == [
'0.081312835447245177',
'0.80491409000551284',
'0.80491409000551284',
'0.081312835447245177']
x, w = gauss_hermite(5, 17)
assert [str(r) for r in x] == [
'-2.0201828704560856',
'-0.95857246461381851',
'0',
'0.95857246461381851',
'2.0201828704560856']
assert [str(r) for r in w] == [
'0.019953242059045913',
'0.39361932315224116',
'0.94530872048294188',
'0.39361932315224116',
'0.019953242059045913']
def test_hermite_precise():
x, w = gauss_hermite(3, 40)
assert [str(r) for r in x] == [
'-1.224744871391589049098642037352945695983',
'0',
'1.224744871391589049098642037352945695983']
assert [str(r) for r in w] == [
'0.2954089751509193378830279138901908637996',
'1.181635900603677351532111655560763455198',
'0.2954089751509193378830279138901908637996']
def test_gen_laguerre():
x, w = gauss_gen_laguerre(1, Rational(-1, 2), 17)
assert [str(r) for r in x] == ['0.50000000000000000']
assert [str(r) for r in w] == ['1.7724538509055160']
x, w = gauss_gen_laguerre(2, Rational(-1, 2), 17)
assert [str(r) for r in x] == [
'0.27525512860841095',
'2.7247448713915890']
assert [str(r) for r in w] == [
'1.6098281800110257',
'0.16262567089449035']
x, w = gauss_gen_laguerre(3, Rational(-1, 2), 17)
assert [str(r) for r in x] == [
'0.19016350919348813',
'1.7844927485432516',
'5.5253437422632603']
assert [str(r) for r in w] == [
'1.4492591904487850',
'0.31413464064571329',
'0.0090600198110176913']
x, w = gauss_gen_laguerre(4, Rational(-1, 2), 17)
assert [str(r) for r in x] == [
'0.14530352150331709',
'1.3390972881263614',
'3.9269635013582872',
'8.5886356890120343']
assert [str(r) for r in w] == [
'1.3222940251164826',
'0.41560465162978376',
'0.034155966014826951',
'0.00039920814442273524']
x, w = gauss_gen_laguerre(5, Rational(-1, 2), 17)
assert [str(r) for r in x] == [
'0.11758132021177814',
'1.0745620124369040',
'3.0859374437175500',
'6.4147297336620305',
'11.807189489971737']
assert [str(r) for r in w] == [
'1.2217252674706516',
'0.48027722216462937',
'0.067748788910962126',
'0.0026872914935624654',
'1.5280865710465241e-5']
x, w = gauss_gen_laguerre(1, 2, 17)
assert [str(r) for r in x] == ['3.0000000000000000']
assert [str(r) for r in w] == ['2.0000000000000000']
x, w = gauss_gen_laguerre(2, 2, 17)
assert [str(r) for r in x] == [
'2.0000000000000000',
'6.0000000000000000']
assert [str(r) for r in w] == [
'1.5000000000000000',
'0.50000000000000000']
x, w = gauss_gen_laguerre(3, 2, 17)
assert [str(r) for r in x] == [
'1.5173870806774125',
'4.3115831337195203',
'9.1710297856030672']
assert [str(r) for r in w] == [
'1.0374949614904253',
'0.90575000470306537',
'0.056755033806509347']
x, w = gauss_gen_laguerre(4, 2, 17)
assert [str(r) for r in x] == [
'1.2267632635003021',
'3.4125073586969460',
'6.9026926058516134',
'12.458036771951139']
assert [str(r) for r in w] == [
'0.72552499769865438',
'1.0634242919791946',
'0.20669613102835355',
'0.0043545792937974889']
x, w = gauss_gen_laguerre(5, 2, 17)
assert [str(r) for r in x] == [
'1.0311091440933816',
'2.8372128239538217',
'5.6202942725987079',
'9.6829098376640271',
'15.828473921690062']
assert [str(r) for r in w] == [
'0.52091739683509184',
'1.0667059331592211',
'0.38354972366693113',
'0.028564233532974658',
'0.00026271280578124935']
def test_gen_laguerre_precise():
x, w = gauss_gen_laguerre(3, Rational(-1, 2), 40)
assert [str(r) for r in x] == [
'0.1901635091934881328718554276203028970878',
'1.784492748543251591186722461957367638500',
'5.525343742263260275941422110422329464413']
assert [str(r) for r in w] == [
'1.449259190448785048183829411195134343108',
'0.3141346406457132878326231270167565378246',
'0.009060019811017691281714945129254301865020']
x, w = gauss_gen_laguerre(3, 2, 40)
assert [str(r) for r in x] == [
'1.517387080677412495020323111016672547482',
'4.311583133719520302881184669723530562299',
'9.171029785603067202098492219259796890218']
assert [str(r) for r in w] == [
'1.037494961490425285817554606541269153041',
'0.9057500047030653669269785048806009945254',
'0.05675503380650934725546688857812985243312']
def test_chebyshev_t():
x, w = gauss_chebyshev_t(1, 17)
assert [str(r) for r in x] == ['0']
assert [str(r) for r in w] == ['3.1415926535897932']
x, w = gauss_chebyshev_t(2, 17)
assert [str(r) for r in x] == [
'0.70710678118654752',
'-0.70710678118654752']
assert [str(r) for r in w] == [
'1.5707963267948966',
'1.5707963267948966']
x, w = gauss_chebyshev_t(3, 17)
assert [str(r) for r in x] == [
'0.86602540378443865',
'0',
'-0.86602540378443865']
assert [str(r) for r in w] == [
'1.0471975511965977',
'1.0471975511965977',
'1.0471975511965977']
x, w = gauss_chebyshev_t(4, 17)
assert [str(r) for r in x] == [
'0.92387953251128676',
'0.38268343236508977',
'-0.38268343236508977',
'-0.92387953251128676']
assert [str(r) for r in w] == [
'0.78539816339744831',
'0.78539816339744831',
'0.78539816339744831',
'0.78539816339744831']
x, w = gauss_chebyshev_t(5, 17)
assert [str(r) for r in x] == [
'0.95105651629515357',
'0.58778525229247313',
'0',
'-0.58778525229247313',
'-0.95105651629515357']
assert [str(r) for r in w] == [
'0.62831853071795865',
'0.62831853071795865',
'0.62831853071795865',
'0.62831853071795865',
'0.62831853071795865']
def test_chebyshev_t_precise():
x, w = gauss_chebyshev_t(3, 40)
assert [str(r) for r in x] == [
'0.8660254037844386467637231707529361834714',
'0',
'-0.8660254037844386467637231707529361834714']
assert [str(r) for r in w] == [
'1.047197551196597746154214461093167628066',
'1.047197551196597746154214461093167628066',
'1.047197551196597746154214461093167628066']
def test_chebyshev_u():
x, w = gauss_chebyshev_u(1, 17)
assert [str(r) for r in x] == ['0']
assert [str(r) for r in w] == ['1.5707963267948966']
x, w = gauss_chebyshev_u(2, 17)
assert [str(r) for r in x] == [
'0.50000000000000000',
'-0.50000000000000000']
assert [str(r) for r in w] == [
'0.78539816339744831',
'0.78539816339744831']
x, w = gauss_chebyshev_u(3, 17)
assert [str(r) for r in x] == [
'0.70710678118654752',
'0',
'-0.70710678118654752']
assert [str(r) for r in w] == [
'0.39269908169872415',
'0.78539816339744831',
'0.39269908169872415']
x, w = gauss_chebyshev_u(4, 17)
assert [str(r) for r in x] == [
'0.80901699437494742',
'0.30901699437494742',
'-0.30901699437494742',
'-0.80901699437494742']
assert [str(r) for r in w] == [
'0.21707871342270599',
'0.56831944997474231',
'0.56831944997474231',
'0.21707871342270599']
x, w = gauss_chebyshev_u(5, 17)
assert [str(r) for r in x] == [
'0.86602540378443865',
'0.50000000000000000',
'0',
'-0.50000000000000000',
'-0.86602540378443865']
assert [str(r) for r in w] == [
'0.13089969389957472',
'0.39269908169872415',
'0.52359877559829887',
'0.39269908169872415',
'0.13089969389957472']
def test_chebyshev_u_precise():
x, w = gauss_chebyshev_u(3, 40)
assert [str(r) for r in x] == [
'0.7071067811865475244008443621048490392848',
'0',
'-0.7071067811865475244008443621048490392848']
assert [str(r) for r in w] == [
'0.3926990816987241548078304229099378605246',
'0.7853981633974483096156608458198757210493',
'0.3926990816987241548078304229099378605246']
def test_jacobi():
x, w = gauss_jacobi(1, Rational(-1, 2), S.Half, 17)
assert [str(r) for r in x] == ['0.50000000000000000']
assert [str(r) for r in w] == ['3.1415926535897932']
x, w = gauss_jacobi(2, Rational(-1, 2), S.Half, 17)
assert [str(r) for r in x] == [
'-0.30901699437494742',
'0.80901699437494742']
assert [str(r) for r in w] == [
'0.86831485369082398',
'2.2732777998989693']
x, w = gauss_jacobi(3, Rational(-1, 2), S.Half, 17)
assert [str(r) for r in x] == [
'-0.62348980185873353',
'0.22252093395631440',
'0.90096886790241913']
assert [str(r) for r in w] == [
'0.33795476356635433',
'1.0973322242791115',
'1.7063056657443274']
x, w = gauss_jacobi(4, Rational(-1, 2), S.Half, 17)
assert [str(r) for r in x] == [
'-0.76604444311897804',
'-0.17364817766693035',
'0.50000000000000000',
'0.93969262078590838']
assert [str(r) for r in w] == [
'0.16333179083642836',
'0.57690240318269103',
'1.0471975511965977',
'1.3541609083740761']
x, w = gauss_jacobi(5, Rational(-1, 2), S.Half, 17)
assert [str(r) for r in x] == [
'-0.84125353283118117',
'-0.41541501300188643',
'0.14231483827328514',
'0.65486073394528506',
'0.95949297361449739']
assert [str(r) for r in w] == [
'0.090675770007435372',
'0.33391416373675607',
'0.65248870981926643',
'0.94525424081394926',
'1.1192597692123861']
x, w = gauss_jacobi(1, 2, 3, 17)
assert [str(r) for r in x] == ['0.14285714285714286']
assert [str(r) for r in w] == ['1.0666666666666667']
x, w = gauss_jacobi(2, 2, 3, 17)
assert [str(r) for r in x] == [
'-0.24025307335204215',
'0.46247529557426437']
assert [str(r) for r in w] == [
'0.48514624517838660',
'0.58152042148828007']
x, w = gauss_jacobi(3, 2, 3, 17)
assert [str(r) for r in x] == [
'-0.46115870378089762',
'0.10438533038323902',
'0.62950064612493132']
assert [str(r) for r in w] == [
'0.17937613502213266',
'0.61595640991147154',
'0.27133412173306246']
x, w = gauss_jacobi(4, 2, 3, 17)
assert [str(r) for r in x] == [
'-0.59903470850824782',
'-0.14761105199952565',
'0.32554377081188859',
'0.72879429738819258']
assert [str(r) for r in w] == [
'0.067809641836772187',
'0.38956404952032481',
'0.47995970868024150',
'0.12933326662932816']
x, w = gauss_jacobi(5, 2, 3, 17)
assert [str(r) for r in x] == [
'-0.69045775012676106',
'-0.32651993134900065',
'0.082337849552034905',
'0.47517887061283164',
'0.79279429464422850']
assert [str(r) for r in w] == [
'0.027410178066337099',
'0.21291786060364828',
'0.43908437944395081',
'0.32220656547221822',
'0.065047683080512268']
def test_jacobi_precise():
x, w = gauss_jacobi(3, Rational(-1, 2), S.Half, 40)
assert [str(r) for r in x] == [
'-0.6234898018587335305250048840042398106323',
'0.2225209339563144042889025644967947594664',
'0.9009688679024191262361023195074450511659']
assert [str(r) for r in w] == [
'0.3379547635663543330553835737094171534907',
'1.097332224279111467485302294320899710461',
'1.706305665744327437921957515249186020246']
x, w = gauss_jacobi(3, 2, 3, 40)
assert [str(r) for r in x] == [
'-0.4611587037808976179121958105554375981274',
'0.1043853303832390210914918407615869143233',
'0.6295006461249313240934312425211234110769']
assert [str(r) for r in w] == [
'0.1793761350221326596137764371503859752628',
'0.6159564099114715430909548532229749439714',
'0.2713341217330624639619353762933057474325']
def test_lobatto():
x, w = gauss_lobatto(2, 17)
assert [str(r) for r in x] == [
'-1',
'1']
assert [str(r) for r in w] == [
'1.0000000000000000',
'1.0000000000000000']
x, w = gauss_lobatto(3, 17)
assert [str(r) for r in x] == [
'-1',
'0',
'1']
assert [str(r) for r in w] == [
'0.33333333333333333',
'1.3333333333333333',
'0.33333333333333333']
x, w = gauss_lobatto(4, 17)
assert [str(r) for r in x] == [
'-1',
'-0.44721359549995794',
'0.44721359549995794',
'1']
assert [str(r) for r in w] == [
'0.16666666666666667',
'0.83333333333333333',
'0.83333333333333333',
'0.16666666666666667']
x, w = gauss_lobatto(5, 17)
assert [str(r) for r in x] == [
'-1',
'-0.65465367070797714',
'0',
'0.65465367070797714',
'1']
assert [str(r) for r in w] == [
'0.10000000000000000',
'0.54444444444444444',
'0.71111111111111111',
'0.54444444444444444',
'0.10000000000000000']
def test_lobatto_precise():
x, w = gauss_lobatto(3, 40)
assert [str(r) for r in x] == [
'-1',
'0',
'1']
assert [str(r) for r in w] == [
'0.3333333333333333333333333333333333333333',
'1.333333333333333333333333333333333333333',
'0.3333333333333333333333333333333333333333']
|
c0b1faddbc64874b18a9b13072cf566ec0cf576a3ac566da42bf77c603fca02c | from sympy import (
Abs, acos, acosh, Add, And, asin, asinh, atan, Ci, cos, sinh, cosh,
tanh, Derivative, diff, DiracDelta, E, Ei, Eq, exp, erf, erfc, erfi,
EulerGamma, Expr, factor, Function, gamma, gammasimp, I, Idx, im, IndexedBase,
integrate, Interval, Lambda, LambertW, log, Matrix, Max, meijerg, Min, nan,
Ne, O, oo, pi, Piecewise, polar_lift, Poly, polygamma, Rational, re, S, Si, sign,
simplify, sin, sinc, SingularityFunction, sqrt, sstr, Sum, Symbol,
symbols, sympify, tan, trigsimp, Tuple, lerchphi, exp_polar, li, hyper
)
from sympy.core.compatibility import range
from sympy.core.expr import unchanged
from sympy.functions.elementary.complexes import periodic_argument
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.utilities.pytest import raises, slow, skip, ON_TRAVIS
from sympy.utilities.randtest import verify_numerically
x, y, a, t, x_1, x_2, z, s, b = symbols('x y a t x_1 x_2 z s b')
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_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() == -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_integrate_poly():
p = Poly(x + x**2*y + y**3, x, y)
qx = integrate(p, x)
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_defined():
p = Poly(x + x**2*y + y**3, x, y)
Qx = integrate(p, (x, 0, 1))
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 import expand_func, 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_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_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))
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))
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_is_number():
from sympy.abc import x, y, z
from sympy import cos, sin
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_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}
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) == \
-z**2*acosh(x/z)/2 + 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))
@slow
def test_issue_3940():
a, b, c, d = symbols('a:d', positive=True, finite=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 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 import meijerg
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)) == \
(log(z) + EulerGamma + log(pi))/z - Ci(pi**2*z)/z + 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():
from sympy import Si
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():
from sympy import simplify
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 import simplify, expand_func, polygamma, gamma
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 import lowergamma, simplify
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?
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)) == 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)), 1 < Abs(x**2)/5),
((-2*x**5 + 15*x**3 - 25*x + 25*sqrt(-x**2 + 5)*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_8368():
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)
),
And(
Abs(periodic_argument(polar_lift(s)**2, oo)) < pi,
cos(Abs(periodic_argument(polar_lift(s)**2, oo))/2)*sqrt(Abs(s**2)) - 1 > 0,
Ne(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(
Ne(1/s, 1),
Abs(periodic_argument(s, oo)) < pi/2,
Abs(periodic_argument(s, oo)) <= pi/2,
cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1 > 0)),
( 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_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(2*log(x))/5 - 2*x*cos(2*log(x))/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(-1 + 1/sqrt(exp(x) + 1)) - log(1 + 1/sqrt(exp(x) + 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():
assert Eq(x, y).integrate(x) == Eq(x**2/2, x*y)
assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x))
assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*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', real=True, positive=True)
x = Symbol('x', real=True)
m = Symbol('m', 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) == -sqrt(I)*log(x - sqrt(I))/2 +\
sqrt(I)*log(x + sqrt(I))/2
assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I))
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)
def test_issue_15494():
s = symbols('s', real=True, 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) + 3*log(y)/2)/(sqrt(y)*sqrt(x**2)), Ne(y, 0)),
(0, True))
def test_issue_17473():
x = Symbol('x')
n = Symbol('n')
assert integrate(sin(x**n), x) == \
x*x**n*gamma(S(1)/2 + 1/(2*n))*hyper((S(1)/2 + 1/(2*n),),
(S(3)/2, S(3)/2 + 1/(2*n)),
-x**(2*n)/4)/(2*n*gamma(S(3)/2 + 1/(2*n)))
|
a26970762299d8be3530d86755a8975a023b3c8936c74c1e5b258dc742c427e0 | """Most of these tests come from the examples in Bronstein's book."""
from sympy import (Poly, I, S, Function, log, symbols, exp, tan, sqrt,
Symbol, Lambda, sin, Ne, Piecewise, factor, expand_log, cancel,
diff, pi, atan, Rational)
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.utilities.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))
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), 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), (Poly(0, t),
Poly(1, t)), (Poly(-t + x, t),
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), (Poly(t**5 + t**3 + x**2*t + 1, t),
Poly(t**6 + 3*t**4 + 3*t**2 + 1, t)), (Poly(0, t), Poly(1, t)))
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), Poly(t, t)), (Poly(0, t), Poly(1, t)), (Poly(-x, t), Poly(1, t)))
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), Poly(4*t**2 + 2*x**2 + 4, t)),
(Poly((-2*nu**2 - x**4)*t - (2*x**3 + 2*x), t), Poly(2*x**2*t**2 + x**4 + 2*x**2, t)),
(Poly(x*t + 1, t), Poly(x, t)))
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), Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t)),
(Poly(0, t), Poly(1, t)),
(Poly(0, t), Poly(1, t)))
assert hermite_reduce(
Poly(-t**2 + 2*t + 2, t),
Poly(-x*t**2 + 2*x*t - x, t), DE) == \
((Poly(3, t), Poly(t - 1, t)),
(Poly(0, t), Poly(1, t)),
(Poly(1, t), Poly(x, t)))
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),
Poly(x**4*t**6 - 2*x**2*t**3 + 1, t), DE) == \
((Poly(x**3*t + x**4 + 1, t), Poly(x**3*t**3 - x, t)),
(Poly(0, t), Poly(1, t)),
(Poly(-1, t), Poly(x**2, t)))
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), Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t)),
(Poly(0, t), Poly(1, t)),
(Poly(0, t), Poly(1, t)))
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), Poly(2*t**6 + 6*t**5 - 8*t**3, t)])
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), 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))], False)
assert residue_reduce(a, d, DE, z, invert=True) == \
([(Poly(z**2 - Rational(1, 4), z), 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), Poly(-2*z*t/x - 2/x, t))], True)
ans = residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t), DE, z, invert=True)
assert ans == ([(Poly(z**2 - 1, z), 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='EX'))], 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), 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)')]})")
|
84a4c7ed0febe5942f6412b3d98824b608269edc2804891cf33ee101e2995fb9 | from sympy import (sin, cos, tan, sec, csc, cot, log, exp, atan, asin, acos,
Symbol, Integral, integrate, pi, Dummy, Derivative,
diff, I, sqrt, erf, Piecewise, Ne, symbols, Rational,
And, Heaviside, S, asinh, acosh, atanh, acoth, expand,
Function, jacobi, gegenbauer, chebyshevt, chebyshevu,
legendre, hermite, laguerre, assoc_laguerre, uppergamma, li,
Ei, Ci, Si, Chi, Shi, fresnels, fresnelc, polylog, erfi,
sinh, cosh, elliptic_f, elliptic_e)
from sympy.integrals.manualintegrate import (manualintegrate, find_substitutions,
_parts_rule, integral_steps, contains_dont_know, manual_subs)
from sympy.utilities.pytest import raises, slow
x, y, z, u, n, a, b, c = symbols('x y z u n a b c')
f = Function('f')
def test_find_substitutions():
assert find_substitutions((cot(x)**2 + 1)**2*csc(x)**2*cot(x)**2, x, u) == \
[(cot(x), 1, -u**6 - 2*u**4 - u**2)]
assert find_substitutions((sec(x)**2 + tan(x) * sec(x)) / (sec(x) + tan(x)),
x, u) == [(sec(x) + tan(x), 1, 1/u)]
assert find_substitutions(x * exp(-x**2), x, u) == [(-x**2, Rational(-1, 2), exp(u))]
def test_manualintegrate_polynomials():
assert manualintegrate(y, x) == x*y
assert manualintegrate(exp(2), x) == x * exp(2)
assert manualintegrate(x**2, x) == x**3 / 3
assert manualintegrate(3 * x**2 + 4 * x**3, x) == x**3 + x**4
assert manualintegrate((x + 2)**3, x) == (x + 2)**4 / 4
assert manualintegrate((3*x + 4)**2, x) == (3*x + 4)**3 / 9
assert manualintegrate((u + 2)**3, u) == (u + 2)**4 / 4
assert manualintegrate((3*u + 4)**2, u) == (3*u + 4)**3 / 9
def test_manualintegrate_exponentials():
assert manualintegrate(exp(2*x), x) == exp(2*x) / 2
assert manualintegrate(2**x, x) == (2 ** x) / log(2)
assert manualintegrate(1 / x, x) == log(x)
assert manualintegrate(1 / (2*x + 3), x) == log(2*x + 3) / 2
assert manualintegrate(log(x)**2 / x, x) == log(x)**3 / 3
def test_manualintegrate_parts():
assert manualintegrate(exp(x) * sin(x), x) == \
(exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2
assert manualintegrate(2*x*cos(x), x) == 2*x*sin(x) + 2*cos(x)
assert manualintegrate(x * log(x), x) == x**2*log(x)/2 - x**2/4
assert manualintegrate(log(x), x) == x * log(x) - x
assert manualintegrate((3*x**2 + 5) * exp(x), x) == \
3*x**2*exp(x) - 6*x*exp(x) + 11*exp(x)
assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2
# Make sure _parts_rule does not go into an infinite loop here
assert manualintegrate(log(1/x)/(x + 1), x).has(Integral)
# Make sure _parts_rule doesn't pick u = constant but can pick dv =
# constant if necessary, e.g. for integrate(atan(x))
assert _parts_rule(cos(x), x) == None
assert _parts_rule(exp(x), x) == None
assert _parts_rule(x**2, x) == None
result = _parts_rule(atan(x), x)
assert result[0] == atan(x) and result[1] == 1
def test_manualintegrate_trigonometry():
assert manualintegrate(sin(x), x) == -cos(x)
assert manualintegrate(tan(x), x) == -log(cos(x))
assert manualintegrate(sec(x), x) == log(sec(x) + tan(x))
assert manualintegrate(csc(x), x) == -log(csc(x) + cot(x))
assert manualintegrate(sin(x) * cos(x), x) in [sin(x) ** 2 / 2, -cos(x)**2 / 2]
assert manualintegrate(-sec(x) * tan(x), x) == -sec(x)
assert manualintegrate(csc(x) * cot(x), x) == -csc(x)
assert manualintegrate(sec(x)**2, x) == tan(x)
assert manualintegrate(csc(x)**2, x) == -cot(x)
assert manualintegrate(x * sec(x**2), x) == log(tan(x**2) + sec(x**2))/2
assert manualintegrate(cos(x)*csc(sin(x)), x) == -log(cot(sin(x)) + csc(sin(x)))
assert manualintegrate(cos(3*x)*sec(x), x) == -x + sin(2*x)
assert manualintegrate(sin(3*x)*sec(x), x) == \
-3*log(cos(x)) + 2*log(cos(x)**2) - 2*cos(x)**2
def test_manualintegrate_trigpowers():
assert manualintegrate(sin(x)**2 * cos(x), x) == sin(x)**3 / 3
assert manualintegrate(sin(x)**2 * cos(x) **2, x) == \
x / 8 - sin(4*x) / 32
assert manualintegrate(sin(x) * cos(x)**3, x) == -cos(x)**4 / 4
assert manualintegrate(sin(x)**3 * cos(x)**2, x) == \
cos(x)**5 / 5 - cos(x)**3 / 3
assert manualintegrate(tan(x)**3 * sec(x), x) == sec(x)**3/3 - sec(x)
assert manualintegrate(tan(x) * sec(x) **2, x) == sec(x)**2/2
assert manualintegrate(cot(x)**5 * csc(x), x) == \
-csc(x)**5/5 + 2*csc(x)**3/3 - csc(x)
assert manualintegrate(cot(x)**2 * csc(x)**6, x) == \
-cot(x)**7/7 - 2*cot(x)**5/5 - cot(x)**3/3
def test_manualintegrate_inversetrig():
# atan
assert manualintegrate(exp(x) / (1 + exp(2*x)), x) == atan(exp(x))
assert manualintegrate(1 / (4 + 9 * x**2), x) == atan(3 * x/2) / 6
assert manualintegrate(1 / (16 + 16 * x**2), x) == atan(x) / 16
assert manualintegrate(1 / (4 + x**2), x) == atan(x / 2) / 2
assert manualintegrate(1 / (1 + 4 * x**2), x) == atan(2*x) / 2
ra = Symbol('a', real=True)
rb = Symbol('b', real=True)
assert manualintegrate(1/(ra + rb*x**2), x) == \
Piecewise((atan(x/sqrt(ra/rb))/(rb*sqrt(ra/rb)), ra/rb > 0),
(-acoth(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 > -ra/rb)),
(-atanh(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 < -ra/rb)))
assert manualintegrate(1/(4 + rb*x**2), x) == \
Piecewise((atan(x/(2*sqrt(1/rb)))/(2*rb*sqrt(1/rb)), 4/rb > 0),
(-acoth(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 > -4/rb)),
(-atanh(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 < -4/rb)))
assert manualintegrate(1/(ra + 4*x**2), x) == \
Piecewise((atan(2*x/sqrt(ra))/(2*sqrt(ra)), ra/4 > 0),
(-acoth(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 > -ra/4)),
(-atanh(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 < -ra/4)))
assert manualintegrate(1/(4 + 4*x**2), x) == atan(x) / 4
assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b))
# asin
assert manualintegrate(1/sqrt(1-x**2), x) == asin(x)
assert manualintegrate(1/sqrt(4-4*x**2), x) == asin(x)/2
assert manualintegrate(3/sqrt(1-9*x**2), x) == asin(3*x)
assert manualintegrate(1/sqrt(4-9*x**2), x) == asin(x*Rational(3, 2))/3
# asinh
assert manualintegrate(1/sqrt(x**2 + 1), x) == \
asinh(x)
assert manualintegrate(1/sqrt(x**2 + 4), x) == \
asinh(x/2)
assert manualintegrate(1/sqrt(4*x**2 + 4), x) == \
asinh(x)/2
assert manualintegrate(1/sqrt(4*x**2 + 1), x) == \
asinh(2*x)/2
assert manualintegrate(1/sqrt(a*x**2 + 1), x) == \
Piecewise((sqrt(-1/a)*asin(x*sqrt(-a)), a < 0), (sqrt(1/a)*asinh(sqrt(a)*x), a > 0))
assert manualintegrate(1/sqrt(a + x**2), x) == \
Piecewise((asinh(x*sqrt(1/a)), a > 0), (acosh(x*sqrt(-1/a)), a < 0))
# acosh
assert manualintegrate(1/sqrt(x**2 - 1), x) == \
acosh(x)
assert manualintegrate(1/sqrt(x**2 - 4), x) == \
acosh(x/2)
assert manualintegrate(1/sqrt(4*x**2 - 4), x) == \
acosh(x)/2
assert manualintegrate(1/sqrt(9*x**2 - 1), x) == \
acosh(3*x)/3
assert manualintegrate(1/sqrt(a*x**2 - 4), x) == \
Piecewise((sqrt(1/a)*acosh(sqrt(a)*x/2), a > 0))
assert manualintegrate(1/sqrt(-a + 4*x**2), x) == \
Piecewise((asinh(2*x*sqrt(-1/a))/2, -a > 0), (acosh(2*x*sqrt(1/a))/2, -a < 0))
# piecewise
assert manualintegrate(1/sqrt(a-b*x**2), x) == \
Piecewise((sqrt(a/b)*asin(x*sqrt(b/a))/sqrt(a), And(-b < 0, a > 0)),
(sqrt(-a/b)*asinh(x*sqrt(-b/a))/sqrt(a), And(-b > 0, a > 0)),
(sqrt(a/b)*acosh(x*sqrt(b/a))/sqrt(-a), And(-b > 0, a < 0)))
assert manualintegrate(1/sqrt(a + b*x**2), x) == \
Piecewise((sqrt(-a/b)*asin(x*sqrt(-b/a))/sqrt(a), And(a > 0, b < 0)),
(sqrt(a/b)*asinh(x*sqrt(b/a))/sqrt(a), And(a > 0, b > 0)),
(sqrt(-a/b)*acosh(x*sqrt(-b/a))/sqrt(-a), And(a < 0, b > 0)))
def test_manualintegrate_trig_substitution():
assert manualintegrate(sqrt(16*x**2 - 9)/x, x) == \
Piecewise((sqrt(16*x**2 - 9) - 3*acos(3/(4*x)),
And(x < Rational(3, 4), x > Rational(-3, 4))))
assert manualintegrate(1/(x**4 * sqrt(25-x**2)), x) == \
Piecewise((-sqrt(-x**2/25 + 1)/(125*x) -
(-x**2/25 + 1)**(3*S.Half)/(15*x**3), And(x < 5, x > -5)))
assert manualintegrate(x**7/(49*x**2 + 1)**(3 * S.Half), x) == \
((49*x**2 + 1)**(5*S.Half)/28824005 -
(49*x**2 + 1)**(3*S.Half)/5764801 +
3*sqrt(49*x**2 + 1)/5764801 + 1/(5764801*sqrt(49*x**2 + 1)))
def test_manualintegrate_trivial_substitution():
assert manualintegrate((exp(x) - exp(-x))/x, x) == -Ei(-x) + Ei(x)
f = Function('f')
assert manualintegrate((f(x) - f(-x))/x, x) == \
-Integral(f(-x)/x, x) + Integral(f(x)/x, x)
def test_manualintegrate_rational():
assert manualintegrate(1/(4 - x**2), x) == Piecewise((acoth(x/2)/2, x**2 > 4), (atanh(x/2)/2, x**2 < 4))
assert manualintegrate(1/(-1 + x**2), x) == Piecewise((-acoth(x), x**2 > 1), (-atanh(x), x**2 < 1))
def test_manualintegrate_special():
f, F = 4*exp(-x**2/3), 2*sqrt(3)*sqrt(pi)*erf(sqrt(3)*x/3)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = 3*exp(4*x**2), 3*sqrt(pi)*erfi(2*x)/4
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = x**Rational(1, 3)*exp(-x/8), -16*uppergamma(Rational(4, 3), x/8)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = exp(2*x)/x, Ei(2*x)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = exp(1 + 2*x - x**2), sqrt(pi)*exp(2)*erf(x - 1)/2
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f = sin(x**2 + 4*x + 1)
F = (sqrt(2)*sqrt(pi)*(-sin(3)*fresnelc(sqrt(2)*(2*x + 4)/(2*sqrt(pi))) +
cos(3)*fresnels(sqrt(2)*(2*x + 4)/(2*sqrt(pi))))/2)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = cos(4*x**2), sqrt(2)*sqrt(pi)*fresnelc(2*sqrt(2)*x/sqrt(pi))/4
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = sin(3*x + 2)/x, sin(2)*Ci(3*x) + cos(2)*Si(3*x)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = sinh(3*x - 2)/x, -sinh(2)*Chi(3*x) + cosh(2)*Shi(3*x)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = 5*cos(2*x - 3)/x, 5*cos(3)*Ci(2*x) + 5*sin(3)*Si(2*x)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = cosh(x/2)/x, Chi(x/2)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = cos(x**2)/x, Ci(x**2)/2
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = 1/log(2*x + 1), li(2*x + 1)/2
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = polylog(2, 5*x)/x, polylog(3, 5*x)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = 5/sqrt(3 - 2*sin(x)**2), 5*sqrt(3)*elliptic_f(x, Rational(2, 3))/3
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
f, F = sqrt(4 + 9*sin(x)**2), 2*elliptic_e(x, Rational(-9, 4))
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
def test_manualintegrate_derivative():
assert manualintegrate(pi * Derivative(x**2 + 2*x + 3), x) == \
pi * ((x**2 + 2*x + 3))
assert manualintegrate(Derivative(x**2 + 2*x + 3, y), x) == \
Integral(Derivative(x**2 + 2*x + 3, y))
assert manualintegrate(Derivative(sin(x), x, x, x, y), x) == \
Derivative(sin(x), x, x, y)
def test_manualintegrate_Heaviside():
assert manualintegrate(Heaviside(x), x) == x*Heaviside(x)
assert manualintegrate(x*Heaviside(2), x) == x**2/2
assert manualintegrate(x*Heaviside(-2), x) == 0
assert manualintegrate(x*Heaviside( x), x) == x**2*Heaviside( x)/2
assert manualintegrate(x*Heaviside(-x), x) == x**2*Heaviside(-x)/2
assert manualintegrate(Heaviside(2*x + 4), x) == (x+2)*Heaviside(2*x + 4)
assert manualintegrate(x*Heaviside(x), x) == x**2*Heaviside(x)/2
assert manualintegrate(Heaviside(x + 1)*Heaviside(1 - x)*x**2, x) == \
((x**3/3 + Rational(1, 3))*Heaviside(x + 1) - Rational(2, 3))*Heaviside(-x + 1)
y = Symbol('y')
assert manualintegrate(sin(7 + x)*Heaviside(3*x - 7), x) == \
(- cos(x + 7) + cos(Rational(28, 3)))*Heaviside(3*x - S(7))
assert manualintegrate(sin(y + x)*Heaviside(3*x - y), x) == \
(cos(y*Rational(4, 3)) - cos(x + y))*Heaviside(3*x - y)
def test_manualintegrate_orthogonal_poly():
n = symbols('n')
a, b = 7, Rational(5, 3)
polys = [jacobi(n, a, b, x), gegenbauer(n, a, x), chebyshevt(n, x),
chebyshevu(n, x), legendre(n, x), hermite(n, x), laguerre(n, x),
assoc_laguerre(n, a, x)]
for p in polys:
integral = manualintegrate(p, x)
for deg in [-2, -1, 0, 1, 3, 5, 8]:
# some accept negative "degree", some do not
try:
p_subbed = p.subs(n, deg)
except ValueError:
continue
assert (integral.subs(n, deg).diff(x) - p_subbed).expand() == 0
# can also integrate simple expressions with these polynomials
q = x*p.subs(x, 2*x + 1)
integral = manualintegrate(q, x)
for deg in [2, 4, 7]:
assert (integral.subs(n, deg).diff(x) - q.subs(n, deg)).expand() == 0
# cannot integrate with respect to any other parameter
t = symbols('t')
for i in range(len(p.args) - 1):
new_args = list(p.args)
new_args[i] = t
assert isinstance(manualintegrate(p.func(*new_args), t), Integral)
def test_issue_6799():
r, x, phi = map(Symbol, 'r x phi'.split())
n = Symbol('n', integer=True, positive=True)
integrand = (cos(n*(x-phi))*cos(n*x))
limits = (x, -pi, pi)
assert manualintegrate(integrand, x) == \
((n*x/2 + sin(2*n*x)/4)*cos(n*phi) - sin(n*phi)*cos(n*x)**2/2)/n
assert r * integrate(integrand, limits).trigsimp() / pi == r * cos(n * phi)
assert not integrate(integrand, limits).has(Dummy)
def test_issue_12251():
assert manualintegrate(x**y, x) == Piecewise(
(x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True))
def test_issue_3796():
assert manualintegrate(diff(exp(x + x**2)), x) == exp(x + x**2)
assert integrate(x * exp(x**4), x, risch=False) == -I*sqrt(pi)*erf(I*x**2)/4
def test_manual_true():
assert integrate(exp(x) * sin(x), x, manual=True) == \
(exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2
assert integrate(sin(x) * cos(x), x, manual=True) in \
[sin(x) ** 2 / 2, -cos(x)**2 / 2]
def test_issue_6746():
y = Symbol('y')
n = Symbol('n')
assert manualintegrate(y**x, x) == Piecewise(
(y**x/log(y), Ne(log(y), 0)), (x, True))
assert manualintegrate(y**(n*x), x) == Piecewise(
(Piecewise(
(y**(n*x)/log(y), Ne(log(y), 0)),
(n*x, True)
)/n, Ne(n, 0)),
(x, True))
assert manualintegrate(exp(n*x), x) == Piecewise(
(exp(n*x)/n, Ne(n, 0)), (x, True))
y = Symbol('y', positive=True)
assert manualintegrate((y + 1)**x, x) == (y + 1)**x/log(y + 1)
y = Symbol('y', zero=True)
assert manualintegrate((y + 1)**x, x) == x
y = Symbol('y')
n = Symbol('n', nonzero=True)
assert manualintegrate(y**(n*x), x) == Piecewise(
(y**(n*x)/log(y), Ne(log(y), 0)), (n*x, True))/n
y = Symbol('y', positive=True)
assert manualintegrate((y + 1)**(n*x), x) == \
(y + 1)**(n*x)/(n*log(y + 1))
a = Symbol('a', negative=True)
b = Symbol('b')
assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b))
b = Symbol('b', negative=True)
assert manualintegrate(1/(a + b*x**2), x) == \
atan(x/(sqrt(-a)*sqrt(-1/b)))/(b*sqrt(-a)*sqrt(-1/b))
assert manualintegrate(1/((x**a + y**b + 4)*sqrt(a*x**2 + 1)), x) == \
y**(-b)*Integral(x**(-a)/(y**(-b)*sqrt(a*x**2 + 1) +
x**(-a)*sqrt(a*x**2 + 1) + 4*x**(-a)*y**(-b)*sqrt(a*x**2 + 1)), x)
assert manualintegrate(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) == \
Integral(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x)
assert manualintegrate(1/(x - a**x + x*b**2), x) == \
Integral(1/(-a**x + b**2*x + x), x)
@slow
def test_issue_2850():
assert manualintegrate(asin(x)*log(x), x) == -x*asin(x) - sqrt(-x**2 + 1) \
+ (x*asin(x) + sqrt(-x**2 + 1))*log(x) - Integral(sqrt(-x**2 + 1)/x, x)
assert manualintegrate(acos(x)*log(x), x) == -x*acos(x) + sqrt(-x**2 + 1) + \
(x*acos(x) - sqrt(-x**2 + 1))*log(x) + Integral(sqrt(-x**2 + 1)/x, x)
assert manualintegrate(atan(x)*log(x), x) == -x*atan(x) + (x*atan(x) - \
log(x**2 + 1)/2)*log(x) + log(x**2 + 1)/2 + Integral(log(x**2 + 1)/x, x)/2
def test_issue_9462():
assert manualintegrate(sin(2*x)*exp(x), x) == exp(x)*sin(2*x)/5 - 2*exp(x)*cos(2*x)/5
assert not contains_dont_know(integral_steps(sin(2*x)*exp(x), x))
assert manualintegrate((x - 3) / (x**2 - 2*x + 2)**2, x) == \
Integral(x/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) \
- 3*Integral(1/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x)
def test_cyclic_parts():
f = cos(x)*exp(x/4)
F = 16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17
assert manualintegrate(f, x) == F and F.diff(x) == f
f = x*cos(x)*exp(x/4)
F = (x*(16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17) -
128*exp(x/4)*sin(x)/289 + 240*exp(x/4)*cos(x)/289)
assert manualintegrate(f, x) == F and F.diff(x) == f
@slow
def test_issue_10847_slow():
assert manualintegrate((4*x**4 + 4*x**3 + 16*x**2 + 12*x + 8)
/ (x**6 + 2*x**5 + 3*x**4 + 4*x**3 + 3*x**2 + 2*x + 1), x) == \
2*x/(x**2 + 1) + 3*atan(x) - 1/(x**2 + 1) - 3/(x + 1)
def test_issue_10847():
assert manualintegrate(x**2 / (x**2 - c), x) == c*atan(x/sqrt(-c))/sqrt(-c) + x
rc = Symbol('c', real=True)
assert manualintegrate(x**2 / (x**2 - rc), x) == \
rc*Piecewise((atan(x/sqrt(-rc))/sqrt(-rc), -rc > 0),
(-acoth(x/sqrt(rc))/sqrt(rc), And(-rc < 0, x**2 > rc)),
(-atanh(x/sqrt(rc))/sqrt(rc), And(-rc < 0, x**2 < rc))) + x
assert manualintegrate(sqrt(x - y) * log(z / x), x) == \
4*y**Rational(3, 2)*atan(sqrt(x - y)/sqrt(y))/3 - 4*y*sqrt(x - y)/3 +\
2*(x - y)**Rational(3, 2)*log(z/x)/3 + 4*(x - y)**Rational(3, 2)/9
ry = Symbol('y', real=True)
rz = Symbol('z', real=True)
assert manualintegrate(sqrt(x - ry) * log(rz / x), x) == \
4*ry**2*Piecewise((atan(sqrt(x - ry)/sqrt(ry))/sqrt(ry), ry > 0),
(-acoth(sqrt(x - ry)/sqrt(-ry))/sqrt(-ry), And(x - ry > -ry, ry < 0)),
(-atanh(sqrt(x - ry)/sqrt(-ry))/sqrt(-ry), And(x - ry < -ry, ry < 0)))/3 \
- 4*ry*sqrt(x - ry)/3 + 2*(x - ry)**Rational(3, 2)*log(rz/x)/3 \
+ 4*(x - ry)**Rational(3, 2)/9
assert manualintegrate(sqrt(x) * log(x), x) == 2*x**Rational(3, 2)*log(x)/3 - 4*x**Rational(3, 2)/9
assert manualintegrate(sqrt(a*x + b) / x, x) == \
2*b*atan(sqrt(a*x + b)/sqrt(-b))/sqrt(-b) + 2*sqrt(a*x + b)
ra = Symbol('a', real=True)
rb = Symbol('b', real=True)
assert manualintegrate(sqrt(ra*x + rb) / x, x) == \
-2*rb*Piecewise((-atan(sqrt(ra*x + rb)/sqrt(-rb))/sqrt(-rb), -rb > 0),
(acoth(sqrt(ra*x + rb)/sqrt(rb))/sqrt(rb), And(-rb < 0, ra*x + rb > rb)),
(atanh(sqrt(ra*x + rb)/sqrt(rb))/sqrt(rb), And(-rb < 0, ra*x + rb < rb))) \
+ 2*sqrt(ra*x + rb)
assert expand(manualintegrate(sqrt(ra*x + rb) / (x + rc), x)) == -2*ra*rc*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), \
ra*rc - rb > 0), (-acoth(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb > -ra*rc + rb)), \
(-atanh(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb < -ra*rc + rb))) \
+ 2*rb*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), ra*rc - rb > 0), \
(-acoth(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb > -ra*rc + rb)), \
(-atanh(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb < -ra*rc + rb))) + 2*sqrt(ra*x + rb)
assert manualintegrate(sqrt(2*x + 3) / (x + 1), x) == 2*sqrt(2*x + 3) - log(sqrt(2*x + 3) + 1) + log(sqrt(2*x + 3) - 1)
assert manualintegrate(sqrt(2*x + 3) / 2 * x, x) == (2*x + 3)**Rational(5, 2)/20 - (2*x + 3)**Rational(3, 2)/4
assert manualintegrate(x**Rational(3,2) * log(x), x) == 2*x**Rational(5,2)*log(x)/5 - 4*x**Rational(5,2)/25
assert manualintegrate(x**(-3) * log(x), x) == -log(x)/(2*x**2) - 1/(4*x**2)
assert manualintegrate(log(y)/(y**2*(1 - 1/y)), y) == \
log(y)*log(-1 + 1/y) - Integral(log(-1 + 1/y)/y, y)
def test_issue_12899():
assert manualintegrate(f(x,y).diff(x),y) == Integral(Derivative(f(x,y),x),y)
assert manualintegrate(f(x,y).diff(y).diff(x),y) == Derivative(f(x,y),x)
def test_constant_independent_of_symbol():
assert manualintegrate(Integral(y, (x, 1, 2)), x) == \
x*Integral(y, (x, 1, 2))
def test_issue_12641():
assert manualintegrate(sin(2*x), x) == -cos(2*x)/2
assert manualintegrate(cos(x)*sin(2*x), x) == -2*cos(x)**3/3
assert manualintegrate((sin(2*x)*cos(x))/(1 + cos(x)), x) == \
-2*log(cos(x) + 1) - cos(x)**2 + 2*cos(x)
def test_issue_13297():
assert manualintegrate(sin(x) * cos(x)**5, x) == -cos(x)**6 / 6
def test_issue_14470():
assert manualintegrate(1/(x*sqrt(x + 1)), x) == \
log(-1 + 1/sqrt(x + 1)) - log(1 + 1/sqrt(x + 1))
@slow
def test_issue_9858():
assert manualintegrate(exp(x)*cos(exp(x)), x) == sin(exp(x))
assert manualintegrate(exp(2*x)*cos(exp(x)), x) == \
exp(x)*sin(exp(x)) + cos(exp(x))
res = manualintegrate(exp(10*x)*sin(exp(x)), x)
assert not res.has(Integral)
assert res.diff(x) == exp(10*x)*sin(exp(x))
# an example with many similar integrations by parts
assert manualintegrate(sum([x*exp(k*x) for k in range(1, 8)]), x) == (
x*exp(7*x)/7 + x*exp(6*x)/6 + x*exp(5*x)/5 + x*exp(4*x)/4 +
x*exp(3*x)/3 + x*exp(2*x)/2 + x*exp(x) - exp(7*x)/49 -exp(6*x)/36 -
exp(5*x)/25 - exp(4*x)/16 - exp(3*x)/9 - exp(2*x)/4 - exp(x))
def test_issue_8520():
assert manualintegrate(x/(x**4 + 1), x) == atan(x**2)/2
assert manualintegrate(x**2/(x**6 + 25), x) == atan(x**3/5)/15
f = x/(9*x**4 + 4)**2
assert manualintegrate(f, x).diff(x).factor() == f
def test_manual_subs():
x, y = symbols('x y')
expr = log(x) + exp(x)
# if log(x) is y, then exp(y) is x
assert manual_subs(expr, log(x), y) == y + exp(exp(y))
# if exp(x) is y, then log(y) need not be x
assert manual_subs(expr, exp(x), y) == log(x) + y
raises(ValueError, lambda: manual_subs(expr, x))
raises(ValueError, lambda: manual_subs(expr, exp(x), x, y))
def test_issue_15471():
f = log(x)*cos(log(x))/x**Rational(3, 4)
F = -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)
assert manualintegrate(f, x) == F and F.diff(x).equals(f)
def test_quadratic_denom():
f = (5*x + 2)/(3*x**2 - 2*x + 8)
assert manualintegrate(f, x) == 5*log(3*x**2 - 2*x + 8)/6 + 11*sqrt(23)*atan(3*sqrt(23)*(x - Rational(1, 3))/23)/69
g = 3/(2*x**2 + 3*x + 1)
assert manualintegrate(g, x) == 3*log(4*x + 2) - 3*log(4*x + 4)
|
c428d8e7df96dc8caf36e50c6713ed2c73c4144070db9ede4810c8d379ff49bd | # A collection of failing integrals from the issues.
from sympy import (
integrate, Integral, exp, oo, pi, sign, sqrt, sin, cos, Piecewise,
tan, S, log, gamma, sinh, sec, acos, atan, sech, csch, DiracDelta, Rational
)
from sympy.utilities.pytest import XFAIL, SKIP, slow, skip, ON_TRAVIS
from sympy.abc import x, k, c, y, b, h, a, m, z, n, t
@SKIP("Too slow for @slow")
@XFAIL
def test_issue_3880():
# integrate_hyperexponential(Poly(t*2*(1 - t0**2)*t0*(x**3 + x**2), t), Poly((1 + t0**2)**2*2*(x**2 + x + 1), t), [Poly(1, x), Poly(1 + t0**2, t0), Poly(t, t)], [x, t0, t], [exp, tan])
assert not integrate(exp(x)*cos(2*x)*sin(2*x) * (x**3 + x**2)/(2*(x**2 + x + 1)), x).has(Integral)
@XFAIL
def test_issue_4212():
assert not integrate(sign(x), x).has(Integral)
@XFAIL
def test_issue_4491():
# Can be solved via variable transformation x = y - 1
assert not integrate(x*sqrt(x**2 + 2*x + 4), x).has(Integral)
@XFAIL
def test_issue_4511():
# This works, but gives a complicated answer. The correct answer is x - cos(x).
# If current answer is simplified, 1 - cos(x) + x is obtained.
# The last one is what Maple gives. It is also quite slow.
assert integrate(cos(x)**2 / (1 - sin(x))) in [x - cos(x), 1 - cos(x) + x,
-2/(tan((S.Half)*x)**2 + 1) + x]
@XFAIL
def test_integrate_DiracDelta_fails():
# issue 6427
assert integrate(integrate(integrate(
DiracDelta(x - y - z), (z, 0, oo)), (y, 0, 1)), (x, 0, 1)) == S.Half
@XFAIL
@slow
def test_issue_4525():
# Warning: takes a long time
assert not integrate((x**m * (1 - x)**n * (a + b*x + c*x**2))/(1 + x**2), (x, 0, 1)).has(Integral)
@XFAIL
@slow
def test_issue_4540():
if ON_TRAVIS:
skip("Too slow for travis.")
# Note, this integral is probably nonelementary
assert not integrate(
(sin(1/x) - x*exp(x)) /
((-sin(1/x) + x*exp(x))*x + x*sin(1/x)), x).has(Integral)
@XFAIL
@slow
def test_issue_4891():
# Requires the hypergeometric function.
assert not integrate(cos(x)**y, x).has(Integral)
@XFAIL
@slow
def test_issue_1796a():
assert not integrate(exp(2*b*x)*exp(-a*x**2), x).has(Integral)
@XFAIL
def test_issue_4895b():
assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, 0)).has(Integral)
@XFAIL
def test_issue_4895c():
assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, oo)).has(Integral)
@XFAIL
def test_issue_4895d():
assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, 0, oo)).has(Integral)
@XFAIL
@slow
def test_issue_4941():
if ON_TRAVIS:
skip("Too slow for travis.")
assert not integrate(sqrt(1 + sinh(x/20)**2), (x, -25, 25)).has(Integral)
@XFAIL
def test_issue_4992():
# Nonelementary integral. Requires hypergeometric/Meijer-G handling.
assert not integrate(log(x) * x**(k - 1) * exp(-x) / gamma(k), (x, 0, oo)).has(Integral)
@XFAIL
def test_issue_16396a():
i = integrate(1/(1+sqrt(tan(x))), (x, pi/3, pi/6))
assert not i.has(Integral)
@XFAIL
def test_issue_16396b():
i = integrate(x*sin(x)/(1+cos(x)**2), (x, 0, pi))
assert not i.has(Integral)
@XFAIL
def test_issue_16161():
i = integrate(x*sec(x)**2, x)
assert not i.has(Integral)
# assert i == x*tan(x) + log(cos(x))
@XFAIL
def test_issue_16046():
assert integrate(exp(exp(I*x)), [x, 0, 2*pi]) == 2*pi
@XFAIL
def test_issue_15925a():
assert not integrate(sqrt((1+sin(x))**2+(cos(x))**2), (x, -pi/2, pi/2)).has(Integral)
@XFAIL
@slow
def test_issue_15925b():
if ON_TRAVIS:
skip("Too slow for travis.")
assert not integrate(sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2),
(x, 0, pi/6)).has(Integral)
@XFAIL
def test_issue_15925b_manual():
assert not integrate(sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2),
(x, 0, pi/6), manual=True).has(Integral)
@XFAIL
@slow
def test_issue_15227():
if ON_TRAVIS:
skip("Too slow for travis.")
i = integrate(log(1-x)*log((1+x)**2)/x, (x, 0, 1))
assert not i.has(Integral)
# assert i == -5*zeta(3)/4
@XFAIL
@slow
def test_issue_14716():
i = integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1))
assert not i.has(Integral)
# Mathematica can not solve it either, but
# integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1)).transform(x, y - 5).doit()
# works
# assert i == -log(Rational(11, 2))/pi - Si(pi*Rational(11, 2))/pi + Si(6*pi)/pi
@XFAIL
def test_issue_14709a():
i = integrate(x*acos(1 - 2*x/h), (x, 0, h))
assert not i.has(Integral)
# assert i == 5*h**2*pi/16
@slow
@XFAIL
def test_issue_14398():
assert not integrate(exp(x**2)*cos(x), x).has(Integral)
@XFAIL
def test_issue_14074():
i = integrate(log(sin(x)), (x, 0, pi/2))
assert not i.has(Integral)
# assert i == -pi*log(2)/2
@XFAIL
@slow
def test_issue_14078b():
i = integrate((atan(4*x)-atan(2*x))/x, (x, 0, oo))
assert not i.has(Integral)
# assert i == pi*log(2)/2
@XFAIL
def test_issue_13792():
i = integrate(log(1/x) / (1 - x), (x, 0, 1))
assert not i.has(Integral)
# assert i in [polylog(2, -exp_polar(I*pi)), pi**2/6]
@XFAIL
def test_issue_11845a():
assert not integrate(exp(y - x**3), (x, 0, 1)).has(Integral)
@XFAIL
def test_issue_11845b():
assert not integrate(exp(-y - x**3), (x, 0, 1)).has(Integral)
@XFAIL
def test_issue_11813():
assert not integrate((a - x)**Rational(-1, 2)*x, (x, 0, a)).has(Integral)
@XFAIL
def test_issue_11742():
i = integrate(sqrt(-x**2 + 8*x + 48), (x, 4, 12))
assert not i.has(Integral)
# assert i == 16*pi
@XFAIL
def test_issue_11254a():
assert not integrate(sech(x), (x, 0, 1)).has(Integral)
@XFAIL
def test_issue_11254b():
assert not integrate(csch(x), (x, 0, 1)).has(Integral)
@XFAIL
def test_issue_10584():
assert not integrate(sqrt(x**2 + 1/x**2), x).has(Integral)
@XFAIL
def test_issue_9723():
assert not integrate(sqrt(x + sqrt(x))).has(Integral)
@XFAIL
def test_issue_9101():
assert not integrate(log(x + sqrt(x**2 + y**2 + z**2)), z).has(Integral)
@XFAIL
def test_issue_7264():
assert not integrate(exp(x)*sqrt(1 + exp(2*x))).has(Integral)
@XFAIL
def test_issue_7147():
assert not integrate(x/sqrt(a*x**2 + b*x + c)**3, x).has(Integral)
@XFAIL
def test_issue_7109():
assert not integrate(sqrt(a**2/(a**2 - x**2)), x).has(Integral)
@XFAIL
def test_integrate_Piecewise_rational_over_reals():
f = Piecewise(
(0, t - 478.515625*pi < 0),
(13.2075145209219*pi/(0.000871222*t + 0.995)**2, t - 478.515625*pi >= 0))
assert abs((integrate(f, (t, 0, oo)) - 15235.9375*pi).evalf()) <= 1e-7
@XFAIL
def test_issue_4311_slow():
# Not slow when bypassing heurish
assert not integrate(x*abs(9-x**2), x).has(Integral)
|
633c90c87d2dfd813230c53ceb72f5659224eafb914b539d8fde804e1a6f49b9 | from sympy import (meijerg, I, S, integrate, Integral, oo, gamma, cosh, sinc,
hyperexpand, exp, simplify, sqrt, pi, erf, erfc, sin, cos,
exp_polar, polygamma, hyper, log, expand_func, Rational)
from sympy.integrals.meijerint import (_rewrite_single, _rewrite1,
meijerint_indefinite, _inflate_g, _create_lookup_table,
meijerint_definite, meijerint_inversion)
from sympy.utilities import default_sort_key
from sympy.utilities.pytest import slow
from sympy.utilities.randtest import (verify_numerically,
random_complex_number as randcplx)
from sympy.core.compatibility import range
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 import Add, exp, exp_polar
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 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 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 import symbols, expand, arg
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:
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')
from sympy import And, re
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)),
And(0 < -2*re(4*s) + 8, 0 < re(a/2 + b/2 + s), re(2*s) < 1))
# 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 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 import besselj, besseli
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 import piecewise_fold, besselj, sqrt, sin, cos, 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 import Symbol, 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 import Symbol, 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 random import uniform, randrange
from sympy 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 a in list(formula.free_symbols) + [z_dummy]:
if hasattr(a, 'properties') and a.properties:
# these Wilds match positive integers
subs[a] = randrange(1, 10)
else:
subs[a] = 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 import powdenest, lowergamma
# 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 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.abc import x, y
from sympy import symbols, Symbol, Abs, expand_mul, gammasimp, powsimp, sin
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] == (1 < beta - 1)
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 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 import (expint, unpolarify, Symbol, Ci, Si, Shi, Chi,
sin, cos, sinh, cosh, Ei)
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 import (laplace_transform, Si, Shi, Chi, atan, Piecewise,
acoth, E1, besselj, acosh, asin, And, re,
fourier_transform, sqrt)
assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True)
assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True)
# where should the logs be simplified?
assert laplace_transform(Chi(x), x, s) == \
((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True)
# TODO maybe simplify the inequalities?
assert laplace_transform(besselj(a, x), x, s)[1:] == \
(0, And(re(a/2) + S.Half > S.Zero, re(a/2) + 1 > S.Zero))
# NOTE s < 0 can be done, but argument reduction is not good enough yet
assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \
(Piecewise((0, 4*abs(pi**2*s**2) > 1),
(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 import fresnels, fresnelc
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 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 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 import Symbol
a = Symbol('a', real=True, positive=True)
assert integrate(1/x**2, (x, oo, a)) == -1/a
def test_issue_6462():
from sympy 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))
|
ec55421fd54b07fa529e4e02e5fbe79da5104138a8c68793e3fa820fc48811f7 | 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 import (
gamma, exp, oo, Heaviside, symbols, Symbol, re, factorial, pi, arg,
cos, S, Abs, And, sin, sqrt, I, log, tan, hyperexpand, meijerg,
EulerGamma, erf, erfc, besselj, bessely, besseli, besselk,
exp_polar, unpolarify, Function, expint, expand_mul, Rational,
gammasimp, trigsimp, atan, sinh, cosh, Ne, periodic_argument, atan2)
from sympy.utilities.pytest import XFAIL, slow, skip, raises
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 import Function, 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), (0, oo), True)
assert laplace_transform(2*f(x), x, s) == 2*LaplaceTransform(f(x), x, s)
# TODO test derivative and other rules when implemented
def test_free_symbols():
from sympy import Function
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 import Function, 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(x**(-s)*f(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 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, -re(beta) + 1), re(beta) > 0)
assert MT((1 + x)**(-rho), x, s) == \
(gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True)
# TODO also the conditions should be simplified, e.g.
# And(re(rho) - 1 < 0, re(rho) < 1) should just be
# re(rho) < 1
assert MT(abs(1 - x)**(-rho), x, s) == (
2*sin(pi*rho/2)*gamma(1 - rho)*
cos(pi*(rho/2 - s))*gamma(s)*gamma(rho-s)/pi,
(0, re(rho)), And(re(rho) - 1 < 0, 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(-re(a), 0), Min(1 - re(a), 1)), 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)
@slow
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 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 + S.Half)/(
(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 import E1, expint, Max, re, lerchphi, Symbol, simplify, Si, Ci, Ei
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 import (sin, simplify, Max, Min, expand,
powsimp, exp_polar, cos, cot)
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)*(sqrt(1 + x/b**2) + 1)**(a - 1)*(b**2*sqrt(1 + x/b**2) +
b**2 + x)/(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 import expand, logcombine, powsimp
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 fresnels, fresnelc
LT = laplace_transform
a, b, c, = symbols('a b c', positive=True)
t = symbols('t')
w = Symbol("w")
f = Function("f")
# Test unevaluated form
assert laplace_transform(f(t), t, w) == LaplaceTransform(f(t), t, w)
assert inverse_laplace_transform(
f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0)
# test a bug
spos = symbols('s', positive=True)
assert LT(exp(t), t, spos)[:2] == (1/(spos - 1), 1)
# 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(t**a, t, s) == (s**(-a - 1)*gamma(a + 1), 0, True)
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(1 - exp(-a*t), t, s) == (a/(s*(a + s)), 0, True)
assert LT((exp(2*t) - 1)*exp(-b - t)*Heaviside(t)/2, t, s, noconds=True) \
== exp(-b)/(s**2 - 1)
assert LT(exp(t), t, s)[:2] == (1/(s - 1), 1)
assert LT(exp(2*t), t, s)[:2] == (1/(s - 2), 2)
assert LT(exp(a*t), t, s)[:2] == (1/(s - a), a)
assert LT(log(t/a), t, s) == ((log(a*s) + EulerGamma)/s/-1, 0, True)
assert LT(erf(t), t, s) == (erfc(s/2)*exp(s**2/4)/s, 0, True)
assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True)
assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True)
# TODO would be nice to have these come out better
assert LT(exp(-a*t)*sin(b*t), t, s) == (b/(b**2 + (a + s)**2), -a, True)
assert LT(exp(-a*t)*cos(b*t), t, s) == \
((a + s)/(b**2 + (a + s)**2), -a, True)
assert LT(besselj(0, t), t, s) == (1/sqrt(1 + s**2), 0, True)
assert LT(besselj(1, t), t, s) == (1 - 1/sqrt(1 + 1/s**2), 0, True)
# TODO general order works, but is a *mess*
# TODO besseli also works, but is an even greater mess
# test a bug in conditions processing
# TODO the auxiliary condition should be recognised/simplified
assert LT(exp(t)*cos(t), t, s)[:-1] in [
((s - 1)/(s**2 - 2*s + 2), -oo),
((s - 1)/((s - 1)**2 + 1), -oo),
]
# 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))
cond = Ne(1/s, 1) & (
0 < cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1)
assert LT(Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]]), t, s) ==\
Matrix([
[(1/(s - 1), 1, True), ((s + 1)**(-2), 0, True)],
[((s + 1)**(-2), 0, True), (1/(s - 1), 1, True)]
])
def test_issue_8368_7173():
LT = laplace_transform
# hyperbolic
assert LT(sinh(x), x, s) == (1/(s**2 - 1), 1, True)
assert LT(cosh(x), x, s) == (s/(s**2 - 1), 1, True)
assert LT(sinh(x + 3), x, s) == (
(-s + (s + 1)*exp(6) + 1)*exp(-3)/(s - 1)/(s + 1)/2, 1, True)
assert LT(sinh(x)*cosh(x), x, s) == (
1/(s**2 - 4), 2, Ne(s/2, 1))
# trig (make sure they are not being rewritten in terms of exp)
assert LT(cos(x + 3), x, s) == ((s*cos(3) - sin(3))/(s**2 + 1), 0, True)
def test_inverse_laplace_transform():
from sympy import sinh, cosh, besselj, besseli, simplify, factor_terms
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)
# just test inverses of all of the above
assert ILT(1/s, s, t) == Heaviside(t)
assert ILT(1/s**2, s, t) == t*Heaviside(t)
assert ILT(1/s**5, s, t) == t**4*Heaviside(t)/24
assert ILT(exp(-a*s)/s, s, t) == Heaviside(t - a)
assert ILT(exp(-a*s)/(s + b), s, t) == exp(b*(a - t))*Heaviside(-a + t)
assert ILT(a/(s**2 + a**2), s, t) == sin(a*t)*Heaviside(t)
assert ILT(s/(s**2 + a**2), s, t) == cos(a*t)*Heaviside(t)
# TODO is there a way around simp_hyp?
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)
assert ILT(a/((s + b)**2 + a**2), s, t) == exp(-b*t)*sin(a*t)*Heaviside(t)
assert ILT(
(s + b)/((s + b)**2 + a**2), s, t) == exp(-b*t)*cos(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 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 import DiracDelta, Eq, im, Heaviside
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 import simplify, expand, expand_complex, factor, expand_trig
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():
from sympy import EulerGamma
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 import Si, Ci
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():
from sympy import gamma, sqrt, exp
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_7173():
from sympy import cse
x0, x1, x2, x3 = symbols('x:4')
ans = laplace_transform(sinh(a*x)*cosh(a*x), x, s)
r, e = cse(ans)
assert r == [
(x0, arg(a)),
(x1, Abs(x0)),
(x2, pi/2),
(x3, Abs(x0 + pi))]
assert e == [
a/(-4*a**2 + s**2),
0,
((x1 <= x2) | (x1 < x2)) & ((x3 <= x2) | (x3 < x2))]
def test_issue_8514():
from sympy 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)
|
94bebe2f03fd3012b06549984fc30ecdd85c4351c2f1b8e5980cd6e798dc44b0 | from sympy import S, symbols, I, atan, log, Poly, sqrt, simplify, integrate, Rational
from sympy.integrals.rationaltools import ratint, ratint_logpart, log_to_atan
from sympy.abc import a, b, x, t
half = S.Half
def test_ratint():
assert ratint(S.Zero, x) == 0
assert ratint(S(7), x) == 7*x
assert ratint(x, x) == x**2/2
assert ratint(2*x, x) == x**2
assert ratint(-2*x, x) == -x**2
assert ratint(8*x**7 + 2*x + 1, x) == x**8 + x**2 + x
f = S.One
g = x + 1
assert ratint(f / g, x) == log(x + 1)
assert ratint((f, g), x) == log(x + 1)
f = x**3 - x
g = x - 1
assert ratint(f/g, x) == x**3/3 + x**2/2
f = x
g = (x - a)*(x + a)
assert ratint(f/g, x) == log(x**2 - a**2)/2
f = S.One
g = x**2 + 1
assert ratint(f/g, x, real=None) == atan(x)
assert ratint(f/g, x, real=True) == atan(x)
assert ratint(f/g, x, real=False) == I*log(x + I)/2 - I*log(x - I)/2
f = S(36)
g = x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2
assert ratint(f/g, x) == \
-4*log(x + 1) + 4*log(x - 2) + (12*x + 6)/(x**2 - 1)
f = x**4 - 3*x**2 + 6
g = x**6 - 5*x**4 + 5*x**2 + 4
assert ratint(f/g, x) == \
atan(x) + atan(x**3) + atan(x/2 - Rational(3, 2)*x**3 + S.Half*x**5)
f = x**7 - 24*x**4 - 4*x**2 + 8*x - 8
g = x**8 + 6*x**6 + 12*x**4 + 8*x**2
assert ratint(f/g, x) == \
(4 + 6*x + 8*x**2 + 3*x**3)/(4*x + 4*x**3 + x**5) + log(x)
assert ratint((x**3*f)/(x*g), x) == \
-(12 - 16*x + 6*x**2 - 14*x**3)/(4 + 4*x**2 + x**4) - \
5*sqrt(2)*atan(x*sqrt(2)/2) + S.Half*x**2 - 3*log(2 + x**2)
f = x**5 - x**4 + 4*x**3 + x**2 - x + 5
g = x**4 - 2*x**3 + 5*x**2 - 4*x + 4
assert ratint(f/g, x) == \
x + S.Half*x**2 + S.Half*log(2 - x + x**2) - (4*x - 9)/(14 - 7*x + 7*x**2) + \
13*sqrt(7)*atan(Rational(-1, 7)*sqrt(7) + 2*x*sqrt(7)/7)/49
assert ratint(1/(x**2 + x + 1), x) == \
2*sqrt(3)*atan(sqrt(3)/3 + 2*x*sqrt(3)/3)/3
assert ratint(1/(x**3 + 1), x) == \
-log(1 - x + x**2)/6 + log(1 + x)/3 + sqrt(3)*atan(-sqrt(3)
/3 + 2*x*sqrt(3)/3)/3
assert ratint(1/(x**2 + x + 1), x, real=False) == \
-I*3**half*log(half + x - half*I*3**half)/3 + \
I*3**half*log(half + x + half*I*3**half)/3
assert ratint(1/(x**3 + 1), x, real=False) == log(1 + x)/3 + \
(Rational(-1, 6) + I*3**half/6)*log(-half + x + I*3**half/2) + \
(Rational(-1, 6) - I*3**half/6)*log(-half + x - I*3**half/2)
# issue 4991
assert ratint(1/(x*(a + b*x)**3), x) == \
(3*a + 2*b*x)/(2*a**4 + 4*a**3*b*x + 2*a**2*b**2*x**2) + (
log(x) - log(a/b + x))/a**3
assert ratint(x/(1 - x**2), x) == -log(x**2 - 1)/2
assert ratint(-x/(1 - x**2), x) == log(x**2 - 1)/2
assert ratint((x/4 - 4/(1 - x)).diff(x), x) == x/4 + 4/(x - 1)
ans = atan(x)
assert ratint(1/(x**2 + 1), x, symbol=x) == ans
assert ratint(1/(x**2 + 1), x, symbol='x') == ans
assert ratint(1/(x**2 + 1), x, symbol=a) == ans
def test_ratint_logpart():
assert ratint_logpart(x, x**2 - 9, x, t) == \
[(Poly(x**2 - 9, x), Poly(-2*t + 1, t))]
assert ratint_logpart(x**2, x**3 - 5, x, t) == \
[(Poly(x**3 - 5, x), Poly(-3*t + 1, t))]
def test_issue_5414():
assert ratint(1/(x**2 + 16), x) == atan(x/4)/4
def test_issue_5249():
assert ratint(
1/(x**2 + a**2), x) == (-I*log(-I*a + x)/2 + I*log(I*a + x)/2)/a
def test_issue_5817():
a, b, c = symbols('a,b,c', positive=True)
assert simplify(ratint(a/(b*c*x**2 + a**2 + b*a), x)) == \
sqrt(a)*atan(sqrt(
b)*sqrt(c)*x/(sqrt(a)*sqrt(a + b)))/(sqrt(b)*sqrt(c)*sqrt(a + b))
def test_issue_5981():
u = symbols('u')
assert integrate(1/(u**2 + 1)) == atan(u)
def test_issue_10488():
a,b,c,x = symbols('a b c x', real=True, positive=True)
assert integrate(x/(a*x+b),x) == x/a - b*log(a*x + b)/a**2
def test_issues_8246_12050_13501_14080():
a = symbols('a', nonzero=True)
assert integrate(a/(x**2 + a**2), x) == atan(x/a)
assert integrate(1/(x**2 + a**2), x) == atan(x/a)/a
assert integrate(1/(1 + a**2*x**2), x) == atan(a*x)/a
def test_issue_6308():
k, a0 = symbols('k a0', real=True)
assert integrate((x**2 + 1 - k**2)/(x**2 + 1 + a0**2), x) == \
x - (a0**2 + k**2)*atan(x/sqrt(a0**2 + 1))/sqrt(a0**2 + 1)
def test_issue_5907():
a = symbols('a', nonzero=True)
assert integrate(1/(x**2 + a**2)**2, x) == \
x/(2*a**4 + 2*a**2*x**2) + atan(x/a)/(2*a**3)
def test_log_to_atan():
f, g = (Poly(x + S.Half, x, domain='QQ'), Poly(sqrt(3)/2, x, domain='EX'))
fg_ans = 2*atan(2*sqrt(3)*x/3 + sqrt(3)/3)
assert log_to_atan(f, g) == fg_ans
assert log_to_atan(g, f) == -fg_ans
|
e0d4035e2c437e11d946041636a1e75a3c2db8778cacb3c59aa61c6e5ff1144b | """Most of these tests come from the examples in Bronstein's book."""
from sympy.integrals.risch import (DifferentialExtension, NonElementaryIntegral,
derivation, risch_integrate)
from sympy.integrals.prde import (prde_normal_denom, prde_special_denom,
prde_linear_constraints, constant_system, prde_spde, prde_no_cancel_b_large,
prde_no_cancel_b_small, limited_integrate_reduce, limited_integrate,
is_deriv_k, is_log_deriv_k_t_radical, parametric_log_deriv_heu,
is_log_deriv_k_t_radical_in_field, param_poly_rischDE, param_rischDE,
prde_cancel_liouvillian)
from sympy.polys.polymatrix import PolyMatrix as Matrix
from sympy import Poly, S, symbols, Rational
from sympy.abc import x, t, n
t0, t1, t2, t3, k = symbols('t:4 k')
def test_prde_normal_denom():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
fa = Poly(1, t)
fd = Poly(x, t)
G = [(Poly(t, t), Poly(1 + t**2, t)), (Poly(1, t), Poly(x + x*t**2, t))]
assert prde_normal_denom(fa, fd, G, DE) == \
(Poly(x, t), (Poly(1, t), Poly(1, t)), [(Poly(x*t, t),
Poly(t**2 + 1, t)), (Poly(1, t), Poly(t**2 + 1, t))], Poly(1, t))
G = [(Poly(t, t), Poly(t**2 + 2*t + 1, t)), (Poly(x*t, t),
Poly(t**2 + 2*t + 1, t)), (Poly(x*t**2, t), Poly(t**2 + 2*t + 1, t))]
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert prde_normal_denom(Poly(x, t), Poly(1, t), G, DE) == \
(Poly(t + 1, t), (Poly((-1 + x)*t + x, t), Poly(1, t)), [(Poly(t, t),
Poly(1, t)), (Poly(x*t, t), Poly(1, t)), (Poly(x*t**2, t),
Poly(1, t))], Poly(t + 1, t))
def test_prde_special_denom():
a = Poly(t + 1, t)
ba = Poly(t**2, t)
bd = Poly(1, t)
G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))]
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert prde_special_denom(a, ba, bd, G, DE) == \
(Poly(t + 1, t), Poly(t**2, t), [(Poly(t, t), Poly(1, t)),
(Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))], Poly(1, t))
G = [(Poly(t, t), Poly(1, t)), (Poly(1, t), Poly(t, t))]
assert prde_special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), G, DE) == \
(Poly(1, t), Poly(t**2 - 1, t), [(Poly(t**2, t), Poly(1, t)),
(Poly(1, t), Poly(1, t))], Poly(t, t))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0)]})
DE.decrement_level()
G = [(Poly(t, t), Poly(t**2, t)), (Poly(2*t, t), Poly(t, t))]
assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3 + 2, t), G, DE) == \
(Poly(5*x*t + 1, t), Poly(0, t), [(Poly(t, t), Poly(t**2, t)),
(Poly(2*t, t), Poly(t, t))], Poly(1, x))
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly((t**2 + 1)*2*x, t)]})
G = [(Poly(t + x, t), Poly(t*x, t)), (Poly(2*t, t), Poly(x**2, x))]
assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3, t), G, DE) == \
(Poly(5*x*t + 1, t), Poly(0, t), [(Poly(t + x, t), Poly(x*t, t)),
(Poly(2*t, t, x), Poly(x**2, t, x))], Poly(1, t))
assert prde_special_denom(Poly(t + 1, t), Poly(t**2, t), Poly(t**3, t), G, DE) == \
(Poly(t + 1, t), Poly(0, t), [(Poly(t + x, t), Poly(x*t, t)), (Poly(2*t, t, x),
Poly(x**2, t, x))], Poly(1, t))
def test_prde_linear_constraints():
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
G = [(Poly(2*x**3 + 3*x + 1, x), Poly(x**2 - 1, x)), (Poly(1, x), Poly(x - 1, x)),
(Poly(1, x), Poly(x + 1, x))]
assert prde_linear_constraints(Poly(1, x), Poly(0, x), G, DE) == \
((Poly(2*x, x), Poly(0, x), Poly(0, x)), Matrix([[1, 1, -1], [5, 1, 1]]))
G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))]
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
assert prde_linear_constraints(Poly(t + 1, t), Poly(t**2, t), G, DE) == \
((Poly(t, t), Poly(t**2, t), Poly(t**3, t)), Matrix(0, 3, []))
G = [(Poly(2*x, t), Poly(t, t)), (Poly(-x, t), Poly(t, t))]
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
assert prde_linear_constraints(Poly(1, t), Poly(0, t), G, DE) == \
((Poly(0, t), Poly(0, t)), Matrix([[2*x, -x]]))
def test_constant_system():
A = Matrix([[-(x + 3)/(x - 1), (x + 1)/(x - 1), 1],
[-x - 3, x + 1, x - 1],
[2*(x + 3)/(x - 1), 0, 0]])
u = Matrix([(x + 1)/(x - 1), x + 1, 0])
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert constant_system(A, u, DE) == \
(Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 0],
[0, 0, 1]]), Matrix([0, 1, 0, 0]))
def test_prde_spde():
D = [Poly(x, t), Poly(-x*t, t)]
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
# TODO: when bound_degree() can handle this, test degree bound from that too
assert prde_spde(Poly(t, t), Poly(-1/x, t), D, n, DE) == \
(Poly(t, t), Poly(0, t), [Poly(2*x, t), Poly(-x, t)],
[Poly(-x**2, t), Poly(0, t)], n - 1)
def test_prde_no_cancel():
# b large
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**2, x), Poly(1, x)], 2, DE) == \
([Poly(x**2 - 2*x + 2, x), Poly(1, x)], Matrix([[1, 0, -1, 0],
[0, 1, 0, -1]]))
assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**3, x), Poly(1, x)], 3, DE) == \
([Poly(x**3 - 3*x**2 + 6*x - 6, x), Poly(1, x)], Matrix([[1, 0, -1, 0],
[0, 1, 0, -1]]))
assert prde_no_cancel_b_large(Poly(x, x), [Poly(x**2, x), Poly(1, x)], 1, DE) == \
([Poly(x, x, domain='ZZ'), Poly(0, x, domain='ZZ')], Matrix([[1, -1, 0, 0],
[1, 0, -1, 0],
[0, 1, 0, -1]]))
# b small
# XXX: Is there a better example of a monomial with D.degree() > 2?
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**3 + 1, t)]})
# My original q was t**4 + t + 1, but this solution implies q == t**4
# (c1 = 4), with some of the ci for the original q equal to 0.
G = [Poly(t**6, t), Poly(x*t**5, t), Poly(t**3, t), Poly(x*t**2, t), Poly(1 + x, t)]
assert prde_no_cancel_b_small(Poly(x*t, t), G, 4, DE) == \
([Poly(t**4/4 - x/12*t**3 + x**2/24*t**2 + (Rational(-11, 12) - x**3/24)*t + x/24, t),
Poly(x/3*t**3 - x**2/6*t**2 + (Rational(-1, 3) + x**3/6)*t - x/6, t), Poly(t, t),
Poly(0, t), Poly(0, t)], Matrix([[1, 0, -1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, Rational(-1, 4), 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, -1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, -1, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, -1, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, -1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, -1]]))
# TODO: Add test for deg(b) <= 0 with b small
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
b = Poly(-1/x**2, t, field=True) # deg(b) == 0
q = [Poly(x**i*t**j, t, field=True) for i in range(2) for j in range(3)]
h, A = prde_no_cancel_b_small(b, q, 3, DE)
V = A.nullspace()
assert len(V) == 1
assert V[0] == Matrix([Rational(-1, 2), 0, 0, 1, 0, 0]*3)
assert (Matrix([h])*V[0][6:, :])[0] == Poly(x**2/2, t, domain='ZZ(x)')
assert (Matrix([q])*V[0][:6, :])[0] == Poly(x - S.Half, t, domain='QQ(x)')
def test_prde_cancel_liouvillian():
### 1. case == 'primitive'
# used when integrating f = log(x) - log(x - 1)
# Not taken from 'the' book
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
p0 = Poly(0, t, field=True)
h, A = prde_cancel_liouvillian(Poly(-1/(x - 1), t), [Poly(-x + 1, t), Poly(1, t)], 1, DE)
V = A.nullspace()
h == [p0, p0, Poly((x - 1)*t, t), p0, p0, p0, p0, p0, p0, p0, Poly(x - 1, t), Poly(-x**2 + x, t), p0, p0, p0, p0]
assert A.rank() == 16
assert (Matrix([h])*V[0][:16, :]) == Matrix([[Poly(0, t, domain='QQ(x)')]])
### 2. case == 'exp'
# used when integrating log(x/exp(x) + 1)
# Not taken from book
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t, t)]})
assert prde_cancel_liouvillian(Poly(0, t, domain='QQ[x]'), [Poly(1, t, domain='QQ(x)')], 0, DE) == \
([Poly(1, t, domain='QQ'), Poly(x, t)], Matrix([[-1, 0, 1]]))
def test_param_poly_rischDE():
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
a = Poly(x**2 - x, x, field=True)
b = Poly(1, x, field=True)
q = [Poly(x, x, field=True), Poly(x**2, x, field=True)]
h, A = param_poly_rischDE(a, b, q, 3, DE)
assert A.nullspace() == [Matrix([0, 1, 1, 1])] # c1, c2, d1, d2
# Solution of a*Dp + b*p = c1*q1 + c2*q2 = q2 = x**2
# is d1*h1 + d2*h2 = h1 + h2 = x.
assert h[0] + h[1] == Poly(x, x)
# a*Dp + b*p = q1 = x has no solution.
a = Poly(x**2 - x, x, field=True)
b = Poly(x**2 - 5*x + 3, x, field=True)
q = [Poly(1, x, field=True), Poly(x, x, field=True),
Poly(x**2, x, field=True)]
h, A = param_poly_rischDE(a, b, q, 3, DE)
assert A.nullspace() == [Matrix([3, -5, 1, -5, 1, 1])]
p = -5*h[0] + h[1] + h[2] # Poly(1, x)
assert a*derivation(p, DE) + b*p == Poly(x**2 - 5*x + 3, x)
def test_param_rischDE():
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
p1, px = Poly(1, x, field=True), Poly(x, x, field=True)
G = [(p1, px), (p1, p1), (px, p1)] # [1/x, 1, x]
h, A = param_rischDE(-p1, Poly(x**2, x, field=True), G, DE)
assert len(h) == 3
p = [hi[0].as_expr()/hi[1].as_expr() for hi in h]
V = A.nullspace()
assert len(V) == 2
assert V[0] == Matrix([-1, 1, 0, -1, 1, 0])
y = -p[0] + p[1] + 0*p[2] # x
assert y.diff(x) - y/x**2 == 1 - 1/x # Dy + f*y == -G0 + G1 + 0*G2
# the below test computation takes place while computing the integral
# of 'f = log(log(x + exp(x)))'
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
G = [(Poly(t + x, t, domain='ZZ(x)'), Poly(1, t, domain='QQ')), (Poly(0, t, domain='QQ'), Poly(1, t, domain='QQ'))]
h, A = param_rischDE(Poly(-t - 1, t, field=True), Poly(t + x, t, field=True), G, DE)
assert len(h) == 5
p = [hi[0].as_expr()/hi[1].as_expr() for hi in h]
V = A.nullspace()
assert len(V) == 3
assert V[0] == Matrix([0, 0, 0, 0, 1, 0, 0])
y = 0*p[0] + 0*p[1] + 1*p[2] + 0*p[3] + 0*p[4]
assert y.diff(t) - y/(t + x) == 0 # Dy + f*y = 0*G0 + 0*G1
def test_limited_integrate_reduce():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
assert limited_integrate_reduce(Poly(x, t), Poly(t**2, t), [(Poly(x, t),
Poly(t, t))], DE) == \
(Poly(t, t), Poly(-1/x, t), Poly(t, t), 1, (Poly(x, t), Poly(1, t)),
[(Poly(-x*t, t), Poly(1, t))])
def test_limited_integrate():
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
G = [(Poly(x, x), Poly(x + 1, x))]
assert limited_integrate(Poly(-(1 + x + 5*x**2 - 3*x**3), x),
Poly(1 - x - x**2 + x**3, x), G, DE) == \
((Poly(x**2 - x + 2, x), Poly(x - 1, x)), [2])
G = [(Poly(1, x), Poly(x, x))]
assert limited_integrate(Poly(5*x**2, x), Poly(3, x), G, DE) == \
((Poly(5*x**3/9, x), Poly(1, x)), [0])
def test_is_log_deriv_k_t_radical():
DE = DifferentialExtension(extension={'D': [Poly(1, x)], 'exts': [None],
'extargs': [None]})
assert is_log_deriv_k_t_radical(Poly(2*x, x), Poly(1, x), DE) is None
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*t1, t1), Poly(1/x, t2)],
'exts': [None, 'exp', 'log'], 'extargs': [None, 2*x, x]})
assert is_log_deriv_k_t_radical(Poly(x + t2/2, t2), Poly(1, t2), DE) == \
([(t1, 1), (x, 1)], t1*x, 2, 0)
# TODO: Add more tests
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(1/x, t)],
'exts': [None, 'exp', 'log'], 'extargs': [None, x, x]})
assert is_log_deriv_k_t_radical(Poly(x + t/2 + 3, t), Poly(1, t), DE) == \
([(t0, 2), (x, 1)], x*t0**2, 2, 3)
def test_is_deriv_k():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)],
'exts': [None, 'log', 'log'], 'extargs': [None, x, x + 1]})
assert is_deriv_k(Poly(2*x**2 + 2*x, t2), Poly(1, t2), DE) == \
([(t1, 1), (t2, 1)], t1 + t2, 2)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t2, t2)],
'exts': [None, 'log', 'exp'], 'extargs': [None, x, x]})
assert is_deriv_k(Poly(x**2*t2**3, t2), Poly(1, t2), DE) == \
([(x, 3), (t1, 2)], 2*t1 + 3*x, 1)
# TODO: Add more tests, including ones with exponentials
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/x, t1)],
'exts': [None, 'log'], 'extargs': [None, x**2]})
assert is_deriv_k(Poly(x, t1), Poly(1, t1), DE) == \
([(t1, S.Half)], t1/2, 1)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/(1 + x), t0)],
'exts': [None, 'log'], 'extargs': [None, x**2 + 2*x + 1]})
assert is_deriv_k(Poly(1 + x, t0), Poly(1, t0), DE) == \
([(t0, S.Half)], t0/2, 1)
# Issue 10798
# DE = DifferentialExtension(log(1/x), x)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-1/x, t)],
'exts': [None, 'log'], 'extargs': [None, 1/x]})
assert is_deriv_k(Poly(1, t), Poly(x, t), DE) == ([(t, 1)], t, 1)
def test_is_log_deriv_k_t_radical_in_field():
# NOTE: any potential constant factor in the second element of the result
# doesn't matter, because it cancels in Da/a.
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
assert is_log_deriv_k_t_radical_in_field(Poly(5*t + 1, t), Poly(2*t*x, t), DE) == \
(2, t*x**5)
assert is_log_deriv_k_t_radical_in_field(Poly(2 + 3*t, t), Poly(5*x*t, t), DE) == \
(5, x**3*t**2)
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t/x**2, t)]})
assert is_log_deriv_k_t_radical_in_field(Poly(-(1 + 2*t), t),
Poly(2*x**2 + 2*x**2*t, t), DE) == \
(2, t + t**2)
assert is_log_deriv_k_t_radical_in_field(Poly(-1, t), Poly(x**2, t), DE) == \
(1, t)
assert is_log_deriv_k_t_radical_in_field(Poly(1, t), Poly(2*x**2, t), DE) == \
(2, 1/t)
def test_parametric_log_deriv():
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
assert parametric_log_deriv_heu(Poly(5*t**2 + t - 6, t), Poly(2*x*t**2, t),
Poly(-1, t), Poly(x*t**2, t), DE) == \
(2, 6, t*x**5)
|
3fd09a908d2bf9335e6054e61ca30526bca1a9bf98807ef1382376679decb65d | import sys
from sympy.external import import_module
matchpy = import_module("matchpy")
if not matchpy:
#bin/test will not execute any tests now
disabled = True
if sys.version_info[:2] < (3, 6):
disabled = True
from sympy.integrals.rubi.utility_function import (Int, Set, With, Module, Scan, MapAnd, FalseQ, ZeroQ, NegativeQ, NonzeroQ, FreeQ, NFreeQ, List, Log, PositiveQ, PositiveIntegerQ, NegativeIntegerQ, IntegerQ, IntegersQ, ComplexNumberQ, PureComplexNumberQ, RealNumericQ, PositiveOrZeroQ, NegativeOrZeroQ, FractionOrNegativeQ, NegQ, Equal, Unequal, IntPart, FracPart, RationalQ, ProductQ, SumQ, NonsumQ, Subst, First, Rest, SqrtNumberQ, SqrtNumberSumQ, LinearQ, Sqrt, ArcCosh, Coefficient, Denominator, Hypergeometric2F1, Not, Simplify, FractionalPart, IntegerPart, AppellF1, EllipticPi, PolynomialQuotient,
EllipticE, EllipticF, ArcTan, ArcCot, ArcCoth, ArcTanh, ArcSin, ArcSinh, ArcCos, ArcCsc, ArcSec, ArcCsch, ArcSech, Sinh, Tanh, Cosh, Sech, Csch, Coth, LessEqual, Less, Greater, GreaterEqual, FractionQ, IntLinearcQ, Expand, IndependentQ, PowerQ, IntegerPowerQ, PositiveIntegerPowerQ, FractionalPowerQ, AtomQ, ExpQ, LogQ, Head, MemberQ, TrigQ, SinQ, CosQ, TanQ, CotQ, SecQ, CscQ, Sin, Cos, Tan, Cot, Sec, Csc, HyperbolicQ, SinhQ, CoshQ, TanhQ, CothQ, SechQ, CschQ, InverseTrigQ, SinCosQ, SinhCoshQ, LeafCount, Numerator, NumberQ, NumericQ, Length, ListQ, Im, Re, InverseHyperbolicQ,
InverseFunctionQ, TrigHyperbolicFreeQ, InverseFunctionFreeQ, RealQ, EqQ, FractionalPowerFreeQ, ComplexFreeQ, PolynomialQ, FactorSquareFree, PowerOfLinearQ, Exponent, QuadraticQ, LinearPairQ, BinomialParts, TrinomialParts, PolyQ, EvenQ, OddQ, PerfectSquareQ, NiceSqrtAuxQ, NiceSqrtQ, Together, PosAux, PosQ, CoefficientList, ReplaceAll, ExpandLinearProduct, GCD, ContentFactor, NumericFactor, NonnumericFactors, MakeAssocList, GensymSubst, KernelSubst, ExpandExpression, Apart, SmartApart, MatchQ, PolynomialQuotientRemainder, FreeFactors, NonfreeFactors, RemoveContentAux, RemoveContent, FreeTerms, NonfreeTerms, ExpandAlgebraicFunction, CollectReciprocals, ExpandCleanup, AlgebraicFunctionQ, Coeff, LeadTerm, RemainingTerms, LeadFactor, RemainingFactors, LeadBase, LeadDegree, Numer, Denom, hypergeom, Expon, MergeMonomials, PolynomialDivide, BinomialQ, TrinomialQ, GeneralizedBinomialQ, GeneralizedTrinomialQ, FactorSquareFreeList, PerfectPowerTest, SquareFreeFactorTest, RationalFunctionQ, RationalFunctionFactors, NonrationalFunctionFactors, Reverse, RationalFunctionExponents, RationalFunctionExpand, ExpandIntegrand, SimplerQ, SimplerSqrtQ, SumSimplerQ, BinomialDegree, TrinomialDegree, CancelCommonFactors, SimplerIntegrandQ, GeneralizedBinomialDegree, GeneralizedBinomialParts, GeneralizedTrinomialDegree, GeneralizedTrinomialParts, MonomialQ, MonomialSumQ, MinimumMonomialExponent, MonomialExponent, LinearMatchQ, PowerOfLinearMatchQ, QuadraticMatchQ, CubicMatchQ, BinomialMatchQ, TrinomialMatchQ, GeneralizedBinomialMatchQ, GeneralizedTrinomialMatchQ, QuotientOfLinearsMatchQ, PolynomialTermQ, PolynomialTerms, NonpolynomialTerms, PseudoBinomialParts, NormalizePseudoBinomial, PseudoBinomialPairQ, PseudoBinomialQ, PolynomialGCD, PolyGCD, AlgebraicFunctionFactors, NonalgebraicFunctionFactors, QuotientOfLinearsP, QuotientOfLinearsParts, QuotientOfLinearsQ, Flatten, Sort, AbsurdNumberQ, AbsurdNumberFactors, NonabsurdNumberFactors, SumSimplerAuxQ, Prepend, Drop, CombineExponents, FactorInteger, FactorAbsurdNumber, SubstForInverseFunction, SubstForFractionalPower, SubstForFractionalPowerOfQuotientOfLinears, FractionalPowerOfQuotientOfLinears, SubstForFractionalPowerQ, SubstForFractionalPowerAuxQ, FractionalPowerOfSquareQ, FractionalPowerSubexpressionQ, Apply, FactorNumericGcd, MergeableFactorQ, MergeFactor, MergeFactors, TrigSimplifyQ, TrigSimplify, TrigSimplifyRecur, Order, FactorOrder, Smallest, OrderedQ, MinimumDegree, PositiveFactors, Sign, NonpositiveFactors, PolynomialInAuxQ, PolynomialInQ, ExponentInAux, ExponentIn, PolynomialInSubstAux, PolynomialInSubst, Distrib, DistributeDegree, FunctionOfPower, DivideDegreesOfFactors, MonomialFactor, FullSimplify, FunctionOfLinearSubst, FunctionOfLinear, NormalizeIntegrand, NormalizeIntegrandAux, NormalizeIntegrandFactor, NormalizeIntegrandFactorBase, NormalizeTogether, NormalizeLeadTermSigns, AbsorbMinusSign, NormalizeSumFactors, SignOfFactor, NormalizePowerOfLinear, SimplifyIntegrand, SimplifyTerm, TogetherSimplify, SmartSimplify, SubstForExpn, ExpandToSum, UnifySum, UnifyTerms, UnifyTerm, CalculusQ, FunctionOfInverseLinear, PureFunctionOfSinhQ, PureFunctionOfTanhQ, PureFunctionOfCoshQ, IntegerQuotientQ, OddQuotientQ, EvenQuotientQ, FindTrigFactor, FunctionOfSinhQ, FunctionOfCoshQ, OddHyperbolicPowerQ, FunctionOfTanhQ, FunctionOfTanhWeight, FunctionOfHyperbolicQ, SmartNumerator, SmartDenominator, SubstForAux, ActivateTrig, ExpandTrig, TrigExpand, SubstForTrig, SubstForHyperbolic, InertTrigFreeQ, LCM, SubstForFractionalPowerOfLinear, FractionalPowerOfLinear, InverseFunctionOfLinear, InertTrigQ, InertReciprocalQ, DeactivateTrig, FixInertTrigFunction, DeactivateTrigAux, PowerOfInertTrigSumQ, PiecewiseLinearQ, KnownTrigIntegrandQ, KnownSineIntegrandQ, KnownTangentIntegrandQ, KnownCotangentIntegrandQ, KnownSecantIntegrandQ, TryPureTanSubst, TryTanhSubst, TryPureTanhSubst, AbsurdNumberGCD, AbsurdNumberGCDList, ExpandTrigExpand, ExpandTrigReduce, ExpandTrigReduceAux, NormalizeTrig, TrigToExp, ExpandTrigToExp, TrigReduce, FunctionOfTrig, AlgebraicTrigFunctionQ, FunctionOfHyperbolic, FunctionOfQ, FunctionOfExpnQ, PureFunctionOfSinQ, PureFunctionOfCosQ, PureFunctionOfTanQ, PureFunctionOfCotQ, FunctionOfCosQ, FunctionOfSinQ, OddTrigPowerQ, FunctionOfTanQ, FunctionOfTanWeight, FunctionOfTrigQ, FunctionOfDensePolynomialsQ, FunctionOfLog, PowerVariableExpn, PowerVariableDegree, PowerVariableSubst, EulerIntegrandQ, FunctionOfSquareRootOfQuadratic, SquareRootOfQuadraticSubst, Divides, EasyDQ, ProductOfLinearPowersQ, Rt, NthRoot, AtomBaseQ, SumBaseQ, NegSumBaseQ, AllNegTermQ, SomeNegTermQ, TrigSquareQ, RtAux, TrigSquare, IntSum, IntTerm, Map2, ConstantFactor, SameQ, ReplacePart, CommonFactors, MostMainFactorPosition, FunctionOfExponentialQ, FunctionOfExponential, FunctionOfExponentialFunction, FunctionOfExponentialFunctionAux, FunctionOfExponentialTest, FunctionOfExponentialTestAux, stdev, rubi_test, If, IntQuadraticQ, IntBinomialQ, RectifyTangent, RectifyCotangent, Inequality, Condition, Simp, SimpHelp, SplitProduct, SplitSum, SubstFor, SubstForAux, FresnelS, FresnelC, Erfc, Erfi, Gamma, FunctionOfTrigOfLinearQ, ElementaryFunctionQ, Complex, UnsameQ, _SimpFixFactor,
DerivativeDivides, SimpFixFactor, _FixSimplify, FixSimplify, _SimplifyAntiderivativeSum, SimplifyAntiderivativeSum, PureFunctionOfCothQ, _SimplifyAntiderivative, SimplifyAntiderivative, _TrigSimplifyAux, TrigSimplifyAux, Cancel, Part, PolyLog, D, Dist, IntegralFreeQ, Sum_doit, rubi_exp, rubi_log, rubi_log as log,
PolynomialRemainder, CoprimeQ, Distribute, ProductLog, Floor, PolyGamma, process_trig, replace_pow_exp)
from sympy.core.expr import unchanged
from sympy.core.symbol import symbols, S
from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec, atan2
from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acsch, cosh, sinh, tanh, coth, sech, csch, acoth
from sympy.functions import (sin, cos, tan, cot, sec, csc, sqrt, log as sym_log)
from sympy import (I, E, pi, hyper, Add, Wild, simplify, Symbol, exp, UnevaluatedExpr, Pow, li, Ei, expint,
Si, Ci, Shi, Chi, loggamma, zeta, zoo, gamma, polylog, oo, polygamma)
from sympy import Integral, nsimplify, Min
A, B, a, b, c, d, e, f, g, h, y, z, m, n, p, q, u, v, w, F = symbols('A B a b c d e f g h y z m n p q u v w F', real=True, imaginary=False)
x = Symbol('x')
def test_ZeroQ():
e = b*(n*p + n + 1)
d = a
assert ZeroQ(a*e - b*d*(n*(p + S(1)) + S(1)))
assert ZeroQ(S(0))
assert not ZeroQ(S(10))
assert not ZeroQ(S(-2))
assert ZeroQ(0, 2-2)
assert ZeroQ([S(2), (4), S(0), S(8)]) == [False, False, True, False]
assert ZeroQ([S(2), S(4), S(8)]) == [False, False, False]
def test_NonzeroQ():
assert NonzeroQ(S(1)) == True
def test_FreeQ():
l = [a*b, x, a + b]
assert FreeQ(l, x) == False
l = [a*b, a + b]
assert FreeQ(l, x) == True
def test_List():
assert List(a, b, c) == [a, b, c]
def test_Log():
assert Log(a) == log(a)
def test_PositiveIntegerQ():
assert PositiveIntegerQ(S(1))
assert not PositiveIntegerQ(S(-3))
assert not PositiveIntegerQ(S(0))
def test_NegativeIntegerQ():
assert not NegativeIntegerQ(S(1))
assert NegativeIntegerQ(S(-3))
assert not NegativeIntegerQ(S(0))
def test_PositiveQ():
assert PositiveQ(S(1))
assert not PositiveQ(S(-3))
assert not PositiveQ(S(0))
assert not PositiveQ(zoo)
assert not PositiveQ(I)
assert PositiveQ(b/(b*(b*c/(-a*d + b*c)) - a*(b*d/(-a*d + b*c))))
def test_IntegerQ():
assert IntegerQ(S(1))
assert not IntegerQ(S(-1.9))
assert not IntegerQ(S(0.0))
assert IntegerQ(S(-1))
def test_FracPart():
assert FracPart(S(10)) == 0
assert FracPart(S(10)+0.5) == 10.5
def test_IntPart():
assert IntPart(m*n) == 0
assert IntPart(S(10)) == 10
assert IntPart(1 + m) == 1
def test_NegQ():
assert NegQ(-S(3))
assert not NegQ(S(0))
assert not NegQ(S(0))
def test_RationalQ():
assert RationalQ(S(5)/6)
assert RationalQ(S(5)/6, S(4)/5)
assert not RationalQ(Sqrt(1.6))
assert not RationalQ(Sqrt(1.6), S(5)/6)
assert not RationalQ(log(2))
def test_ArcCosh():
assert ArcCosh(x) == acosh(x)
def test_LinearQ():
assert not LinearQ(a, x)
assert LinearQ(3*x + y**2, x)
assert not LinearQ(3*x + y**2, y)
assert not LinearQ(S(3), x)
def test_Sqrt():
assert Sqrt(x) == sqrt(x)
assert Sqrt(25) == 5
def test_Util_Coefficient():
from sympy.integrals.rubi.utility_function import Util_Coefficient
assert unchanged(Util_Coefficient, a + b*x + c*x**3, x, a)
assert Util_Coefficient(a + b*x + c*x**3, x, 4).doit() == 0
def test_Coefficient():
assert Coefficient(7 + 2*x + 4*x**3, x, 1) == 2
assert Coefficient(a + b*x + c*x**3, x, 0) == a
assert Coefficient(a + b*x + c*x**3, x, 4) == 0
assert Coefficient(b*x + c*x**3, x, 3) == c
assert Coefficient(x, x, -1) == 0
def test_Denominator():
assert Denominator((-S(1)/S(2) + I/3)) == 6
assert Denominator((-a/b)**3) == (b)**(3)
assert Denominator(S(3)/2) == 2
assert Denominator(x/y) == y
assert Denominator(S(4)/5) == 5
def test_Hypergeometric2F1():
assert Hypergeometric2F1(1, 2, 3, x) == hyper((1, 2), (3,), x)
def test_ArcTan():
assert ArcTan(x) == atan(x)
assert ArcTan(x, y) == atan2(x, y)
def test_Not():
a = 10
assert Not(a == 2)
def test_FractionalPart():
assert FractionalPart(S(3.0)) == 0.0
def test_IntegerPart():
assert IntegerPart(3.6) == 3
assert IntegerPart(-3.6) == -4
def test_AppellF1():
assert AppellF1(1,0,0.5,1,0.5,0.25).evalf() == 1.154700538379251529018298
assert unchanged(AppellF1, a, b, c, d, e, f)
def test_Simplify():
assert Simplify(sin(x)**2 + cos(x)**2) == 1
assert Simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1)) == x - 1
def test_ArcTanh():
assert ArcTanh(a) == atanh(a)
def test_ArcSin():
assert ArcSin(a) == asin(a)
def test_ArcSinh():
assert ArcSinh(a) == asinh(a)
def test_ArcCos():
assert ArcCos(a) == acos(a)
def test_ArcCsc():
assert ArcCsc(a) == acsc(a)
def test_ArcCsch():
assert ArcCsch(a) == acsch(a)
def test_Equal():
assert Equal(a, a)
assert not Equal(a, b)
def test_LessEqual():
assert LessEqual(1, 2, 3)
assert LessEqual(1, 1)
assert not LessEqual(3, 2, 1)
def test_With():
assert With(Set(x, 3), x + y) == 3 + y
assert With(List(Set(x, 3), Set(y, c)), x + y) == 3 + c
def test_Less():
assert Less(1, 2, 3)
assert not Less(1, 1, 3)
def test_Greater():
assert Greater(3, 2, 1)
assert not Greater(3, 2, 2)
def test_GreaterEqual():
assert GreaterEqual(3, 2, 1)
assert GreaterEqual(3, 2, 2)
assert not GreaterEqual(2, 3)
def test_Unequal():
assert Unequal(1, 2)
assert not Unequal(1, 1)
def test_FractionQ():
assert not FractionQ(S('3'))
assert FractionQ(S('3')/S('2'))
def test_Expand():
assert Expand((1 + x)**10) == x**10 + 10*x**9 + 45*x**8 + 120*x**7 + 210*x**6 + 252*x**5 + 210*x**4 + 120*x**3 + 45*x**2 + 10*x + 1
def test_Scan():
assert list(Scan(sin, [a, b])) == [sin(a), sin(b)]
def test_MapAnd():
assert MapAnd(PositiveQ, [S(1), S(2), S(3), S(0)]) == False
assert MapAnd(PositiveQ, [S(1), S(2), S(3)]) == True
def test_FalseQ():
assert FalseQ(True) == False
assert FalseQ(False) == True
def test_ComplexNumberQ():
assert ComplexNumberQ(1 + I*2, I) == True
assert ComplexNumberQ(a + b, I) == False
def test_Re():
assert Re(1 + I) == 1
def test_Im():
assert Im(1 + 2*I) == 2
assert Im(a*I) == a
def test_PositiveOrZeroQ():
assert PositiveOrZeroQ(S(0)) == True
assert PositiveOrZeroQ(S(1)) == True
assert PositiveOrZeroQ(-S(1)) == False
def test_RealNumericQ():
assert RealNumericQ(S(1)) == True
assert RealNumericQ(-S(1)) == True
def test_NegativeOrZeroQ():
assert NegativeOrZeroQ(S(0)) == True
assert NegativeOrZeroQ(-S(1)) == True
assert NegativeOrZeroQ(S(1)) == False
def test_FractionOrNegativeQ():
assert FractionOrNegativeQ(S(1)/2) == True
assert FractionOrNegativeQ(-S(1)) == True
def test_ProductQ():
assert ProductQ(a*b) == True
assert ProductQ(a + b) == False
def test_SumQ():
assert SumQ(a*b) == False
assert SumQ(a + b) == True
def test_NonsumQ():
assert NonsumQ(a*b) == True
assert NonsumQ(a + b) == False
def test_SqrtNumberQ():
assert SqrtNumberQ(sqrt(2)) == True
def test_IntLinearcQ():
assert IntLinearcQ(1, 2, 3, 4, 5, 6, x) == True
assert IntLinearcQ(S(1)/100, S(2)/100, S(3)/100, S(4)/100, S(5)/100, S(6)/100, x) == False
def test_IndependentQ():
assert IndependentQ(a + b*x, x) == False
assert IndependentQ(a + b, x) == True
def test_PowerQ():
assert PowerQ(a**b) == True
assert PowerQ(a + b) == False
def test_IntegerPowerQ():
assert IntegerPowerQ(a**2) == True
assert IntegerPowerQ(a**0.5) == False
def test_PositiveIntegerPowerQ():
assert PositiveIntegerPowerQ(a**3) == True
assert PositiveIntegerPowerQ(a**(-2)) == False
def test_FractionalPowerQ():
assert FractionalPowerQ(a**(S(2)/S(3)))
assert FractionalPowerQ(a**sqrt(2)) == False
def test_AtomQ():
assert AtomQ(x)
assert not AtomQ(x+1)
assert not AtomQ([a, b])
def test_ExpQ():
assert ExpQ(E**2)
assert not ExpQ(2**E)
def test_LogQ():
assert LogQ(log(x))
assert not LogQ(sin(x) + log(x))
def test_Head():
assert Head(sin(x)) == sin
assert Head(log(x**3 + 3)) in (sym_log, log)
def test_MemberQ():
assert MemberQ([a, b, c], b)
assert MemberQ([sin, cos, log, tan], Head(sin(x)))
assert MemberQ([[sin, cos], [tan, cot]], [sin, cos])
assert not MemberQ([[sin, cos], [tan, cot]], [sin, tan])
def test_TrigQ():
assert TrigQ(sin(x))
assert TrigQ(tan(x**2 + 2))
assert not TrigQ(sin(x) + tan(x))
def test_SinQ():
assert SinQ(sin(x))
assert not SinQ(tan(x))
def test_CosQ():
assert CosQ(cos(x))
assert not CosQ(csc(x))
def test_TanQ():
assert TanQ(tan(x))
assert not TanQ(cot(x))
def test_CotQ():
assert not CotQ(tan(x))
assert CotQ(cot(x))
def test_SecQ():
assert SecQ(sec(x))
assert not SecQ(csc(x))
def test_CscQ():
assert not CscQ(sec(x))
assert CscQ(csc(x))
def test_HyperbolicQ():
assert HyperbolicQ(sinh(x))
assert HyperbolicQ(cosh(x))
assert HyperbolicQ(tanh(x))
assert not HyperbolicQ(sinh(x) + cosh(x) + tanh(x))
def test_SinhQ():
assert SinhQ(sinh(x))
assert not SinhQ(cosh(x))
def test_CoshQ():
assert not CoshQ(sinh(x))
assert CoshQ(cosh(x))
def test_TanhQ():
assert TanhQ(tanh(x))
assert not TanhQ(coth(x))
def test_CothQ():
assert not CothQ(tanh(x))
assert CothQ(coth(x))
def test_SechQ():
assert SechQ(sech(x))
assert not SechQ(csch(x))
def test_CschQ():
assert not CschQ(sech(x))
assert CschQ(csch(x))
def test_InverseTrigQ():
assert InverseTrigQ(acot(x))
assert InverseTrigQ(asec(x))
assert not InverseTrigQ(acsc(x) + asec(x))
def test_SinCosQ():
assert SinCosQ(sin(x))
assert SinCosQ(cos(x))
assert SinCosQ(sec(x))
assert not SinCosQ(acsc(x))
def test_SinhCoshQ():
assert not SinhCoshQ(sin(x))
assert SinhCoshQ(cosh(x))
assert SinhCoshQ(sech(x))
assert SinhCoshQ(csch(x))
def test_LeafCount():
assert LeafCount(1 + a + x**2) == 6
def test_Numerator():
assert Numerator((-S(1)/S(2) + I/3)) == -3 + 2*I
assert Numerator((-a/b)**3) == (-a)**(3)
assert Numerator(S(3)/2) == 3
assert Numerator(x/y) == x
def test_Length():
assert Length(a + b) == 2
assert Length(sin(a)*cos(a)) == 2
def test_ListQ():
assert ListQ([1, 2])
assert not ListQ(a)
def test_InverseHyperbolicQ():
assert InverseHyperbolicQ(acosh(a))
def test_InverseFunctionQ():
assert InverseFunctionQ(log(a))
assert InverseFunctionQ(acos(a))
assert not InverseFunctionQ(a)
assert InverseFunctionQ(acosh(a))
assert InverseFunctionQ(polylog(a, b))
def test_EqQ():
assert EqQ(a, a)
assert not EqQ(a, b)
def test_FactorSquareFree():
assert FactorSquareFree(x**5 - x**3 - x**2 + 1) == (x**3 + 2*x**2 + 2*x + 1)*(x - 1)**2
def test_FactorSquareFreeList():
assert FactorSquareFreeList(x**5-x**3-x**2 + 1) == [[1, 1], [x**3 + 2*x**2 + 2*x + 1, 1], [x - 1, 2]]
assert FactorSquareFreeList(x**4 - 2*x**2 + 1) == [[1, 1], [x**2 - 1, 2]]
def test_PerfectPowerTest():
assert not PerfectPowerTest(sqrt(x), x)
assert not PerfectPowerTest(x**5-x**3-x**2 + 1, x)
assert PerfectPowerTest(x**4 - 2*x**2 + 1, x) == (x**2 - 1)**2
def test_SquareFreeFactorTest():
assert not SquareFreeFactorTest(sqrt(x), x)
assert SquareFreeFactorTest(x**5 - x**3 - x**2 + 1, x) == (x**3 + 2*x**2 + 2*x + 1)*(x - 1)**2
def test_Rest():
assert Rest([2, 3, 5, 7]) == [3, 5, 7]
assert Rest(a + b + c) == b + c
assert Rest(a*b*c) == b*c
assert Rest(1/b) == -1
def test_First():
assert First([2, 3, 5, 7]) == 2
assert First(y**S(2)) == y
assert First(a + b + c) == a
assert First(a*b*c) == a
def test_ComplexFreeQ():
assert ComplexFreeQ(a)
assert not ComplexFreeQ(a + 2*I)
def test_FractionalPowerFreeQ():
assert not FractionalPowerFreeQ(x**(S(2)/3))
assert FractionalPowerFreeQ(x)
def test_Exponent():
assert Exponent(x**2 + x + 1 + 5, x, Min) == 0
assert Exponent(x**2 + x + 1 + 5, x, List) == [0, 1, 2]
assert Exponent(x**2 + x + 1, x, List) == [0, 1, 2]
assert Exponent(x**2 + 2*x + 1, x, List) == [0, 1, 2]
assert Exponent(x**3 + x + 1, x) == 3
assert Exponent(x**2 + 2*x + 1, x) == 2
assert Exponent(x**3, x, List) == [3]
assert Exponent(S(1), x) == 0
assert Exponent(x**(-3), x) == 0
def test_Expon():
assert Expon(x**2+2*x+1, x) == 2
assert Expon(x**3, x, List) == [3]
def test_QuadraticQ():
assert not QuadraticQ([x**2+x+1, 5*x**2], x)
assert QuadraticQ([x**2+x+1, 5*x**2+3*x+6], x)
assert not QuadraticQ(x**2+1+x**3, x)
assert QuadraticQ(x**2+1+x, x)
assert not QuadraticQ(x**2, x)
def test_BinomialQ():
assert BinomialQ(x**9, x)
assert not BinomialQ((1 + x)**3, x)
def test_BinomialParts():
assert BinomialParts(2 + x*(9*x), x) == [2, 9, 2]
assert BinomialParts(x**9, x) == [0, 1, 9]
assert BinomialParts(2*x**3, x) == [0, 2, 3]
assert BinomialParts(2 + x, x) == [2, 1, 1]
def test_BinomialDegree():
assert BinomialDegree(b + 2*c*x**n, x) == n
assert BinomialDegree(2 + x*(9*x), x) == 2
assert BinomialDegree(x**9, x) == 9
def test_PolynomialQ():
assert not PolynomialQ(x*(-1 + x**2), (1 + x)**(S(1)/2))
assert not PolynomialQ((16*x + 1)/((x + 5)**2*(x**2 + x + 1)), 2*x)
C = Symbol('C')
assert not PolynomialQ(A + b*x + c*x**2, x**2)
assert PolynomialQ(A + B*x + C*x**2)
assert PolynomialQ(A + B*x**4 + C*x**2, x**2)
assert PolynomialQ(x**3, x)
assert not PolynomialQ(sqrt(x), x)
def test_PolyQ():
assert PolyQ(-2*a*d**3*e**2 + x**6*(a*e**5 - b*d*e**4 + c*d**2*e**3)\
+ x**4*(-2*a*d*e**4 + 2*b*d**2*e**3 - 2*c*d**3*e**2) + x**2*(2*a*d**2*e**3 - 2*b*d**3*e**2), x)
assert not PolyQ(1/sqrt(a + b*x**2 - c*x**4), x**2)
assert PolyQ(x, x, 1)
assert PolyQ(x**2, x, 2)
assert not PolyQ(x**3, x, 2)
def test_EvenQ():
assert EvenQ(S(2))
assert not EvenQ(S(1))
def test_OddQ():
assert OddQ(S(1))
assert not OddQ(S(2))
def test_PerfectSquareQ():
assert PerfectSquareQ(S(4))
assert PerfectSquareQ(a**S(2)*b**S(4))
assert not PerfectSquareQ(S(1)/3)
def test_NiceSqrtQ():
assert NiceSqrtQ(S(1)/3)
assert not NiceSqrtQ(-S(1))
assert NiceSqrtQ(pi**2)
assert NiceSqrtQ(pi**2*sin(4)**4)
assert not NiceSqrtQ(pi**2*sin(4)**3)
def test_Together():
assert Together(1/a + b/2) == (a*b + 2)/(2*a)
def test_PosQ():
#assert not PosQ((b*e - c*d)/(c*e))
assert not PosQ(S(0))
assert PosQ(S(1))
assert PosQ(pi)
assert PosQ(pi**3)
assert PosQ((-pi)**4)
assert PosQ(sin(1)**2*pi**4)
def test_NumericQ():
assert NumericQ(sin(cos(2)))
def test_NumberQ():
assert NumberQ(pi)
def test_CoefficientList():
assert CoefficientList(1 + a*x, x) == [1, a]
assert CoefficientList(1 + a*x**3, x) == [1, 0, 0, a]
assert CoefficientList(sqrt(x), x) == []
def test_ReplaceAll():
assert ReplaceAll(x, {x: a}) == a
assert ReplaceAll(a*x, {x: a + b}) == a*(a + b)
assert ReplaceAll(a*x, {a: b, x: a + b}) == b*(a + b)
def test_ExpandLinearProduct():
assert ExpandLinearProduct(log(x), x**2, a, b, x) == a**2*log(x)/b**2 - 2*a*(a + b*x)*log(x)/b**2 + (a + b*x)**2*log(x)/b**2
assert ExpandLinearProduct((a + b*x)**n, x**3, a, b, x) == -a**3*(a + b*x)**n/b**3 + 3*a**2*(a + b*x)**(n + 1)/b**3 - 3*a*(a + b*x)**(n + 2)/b**3 + (a + b*x)**(n + 3)/b**3
def test_PolynomialDivide():
assert PolynomialDivide((a*c - b*c*x)**2, (a + b*x)**2, x) == -4*a*b*c**2*x/(a + b*x)**2 + c**2
assert PolynomialDivide(x + x**2, x, x) == x + 1
assert PolynomialDivide((1 + x)**3, (1 + x)**2, x) == x + 1
assert PolynomialDivide((a + b*x)**3, x**3, x) == a*(a**2 + 3*a*b*x + 3*b**2*x**2)/x**3 + b**3
assert PolynomialDivide(x**3*(a + b*x), S(1), x) == b*x**4 + a*x**3
assert PolynomialDivide(x**6, (a + b*x)**2, x) == -a**5*(5*a + 6*b*x)/(b**6*(a + b*x)**2) + 5*a**4/b**6 - 4*a**3*x/b**5 + 3*a**2*x**2/b**4 - 2*a*x**3/b**3 + x**4/b**2
def test_MatchQ():
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x])
c_ = Wild('c', exclude=[x])
assert MatchQ(a*b + c, a_*b_ + c_, a_, b_, c_) == (a, b, c)
def test_PolynomialQuotientRemainder():
assert PolynomialQuotientRemainder(x**2, x+a, x) == [-a + x, a**2]
def test_FreeFactors():
assert FreeFactors(a, x) == a
assert FreeFactors(x + a, x) == 1
assert FreeFactors(a*b*x, x) == a*b
def test_NonfreeFactors():
assert NonfreeFactors(a, x) == 1
assert NonfreeFactors(x + a, x) == x + a
assert NonfreeFactors(a*b*x, x) == x
def test_FreeTerms():
assert FreeTerms(a, x) == a
assert FreeTerms(x*a, x) == 0
assert FreeTerms(a*x + b, x) == b
def test_NonfreeTerms():
assert NonfreeTerms(a, x) == 0
assert NonfreeTerms(a*x, x) == a*x
assert NonfreeTerms(a*x + b, x) == a*x
def test_RemoveContent():
assert RemoveContent(a + b*x, x) == a + b*x
def test_ExpandAlgebraicFunction():
assert ExpandAlgebraicFunction((a + b)*x, x) == a*x + b*x
assert ExpandAlgebraicFunction((a + b)**2*x, x)== a**2*x + 2*a*b*x + b**2*x
assert ExpandAlgebraicFunction((a + b)**2*x**2, x) == a**2*x**2 + 2*a*b*x**2 + b**2*x**2
def test_CollectReciprocals():
assert CollectReciprocals(-1/(1 + 1*x) - 1/(1 - 1*x), x) == -2/(-x**2 + 1)
assert CollectReciprocals(1/(1 + 1*x) - 1/(1 - 1*x), x) == -2*x/(-x**2 + 1)
def test_ExpandCleanup():
assert ExpandCleanup(a + b, x) == a*(1 + b/a)
assert ExpandCleanup(b**2/(a**2*(a + b*x)**2) + 1/(a**2*x**2) + 2*b**2/(a**3*(a + b*x)) - 2*b/(a**3*x), x) == b**2/(a**2*(a + b*x)**2) + 1/(a**2*x**2) + 2*b**2/(a**3*(a + b*x)) - 2*b/(a**3*x)
def test_AlgebraicFunctionQ():
assert not AlgebraicFunctionQ(1/(a + c*x**(2*n)), x)
assert AlgebraicFunctionQ(a, x) == True
assert AlgebraicFunctionQ(a*b, x) == True
assert AlgebraicFunctionQ(x**2, x) == True
assert AlgebraicFunctionQ(x**2*a, x) == True
assert AlgebraicFunctionQ(x**2 + a, x) == True
assert AlgebraicFunctionQ(sin(x), x) == False
assert AlgebraicFunctionQ([], x) == True
assert AlgebraicFunctionQ([a, a*b], x) == True
assert AlgebraicFunctionQ([sin(x)], x) == False
def test_MonomialQ():
assert not MonomialQ(2*x**7 + 6, x)
assert MonomialQ(2*x**7, x)
assert not MonomialQ(2*x**7 + 5*x**3, x)
assert not MonomialQ([2*x**7 + 6, 2*x**7], x)
assert MonomialQ([2*x**7, 5*x**3], x)
def test_MonomialSumQ():
assert MonomialSumQ(2*x**7 + 6, x) == True
assert MonomialSumQ(x**2 + x**3 + 5*x, x) == True
def test_MinimumMonomialExponent():
assert MinimumMonomialExponent(x**2 + 5*x**2 + 3*x**5, x) == 2
assert MinimumMonomialExponent(x**2 + 5*x**2 + 1, x) == 0
def test_MonomialExponent():
assert MonomialExponent(3*x**7, x) == 7
assert not MonomialExponent(3+x**3, x)
def test_LinearMatchQ():
assert LinearMatchQ(2 + 3*x, x)
assert LinearMatchQ(3*x, x)
assert not LinearMatchQ(3*x**2, x)
def test_SimplerQ():
a1, b1 = symbols('a1 b1')
assert SimplerQ(a1, b1)
assert SimplerQ(2*a, a + 2)
assert SimplerQ(2, x)
assert not SimplerQ(x**2, x)
assert SimplerQ(2*x, x + 2 + 6*x**3)
def test_GeneralizedTrinomialParts():
assert not GeneralizedTrinomialParts((7 + 2*x**6 + 3*x**12), x)
assert GeneralizedTrinomialParts(x**2 + x**3 + x**4, x) == [1, 1, 1, 3, 2]
assert not GeneralizedTrinomialParts(2*x + 3*x + 4*x, x)
def test_TrinomialQ():
assert TrinomialQ((7 + 2*x**6 + 3*x**12), x)
assert not TrinomialQ(x**2, x)
def test_GeneralizedTrinomialDegree():
assert not GeneralizedTrinomialDegree((7 + 2*x**6 + 3*x**12), x)
assert GeneralizedTrinomialDegree(x**2 + x**3 + x**4, x) == 1
def test_GeneralizedBinomialParts():
assert GeneralizedBinomialParts(3*x*(3 + x**6), x) == [9, 3, 7, 1]
assert GeneralizedBinomialParts((3*x + x**7), x) == [3, 1, 7, 1]
def test_GeneralizedBinomialDegree():
assert GeneralizedBinomialDegree(3*x*(3 + x**6), x) == 6
assert GeneralizedBinomialDegree((3*x + x**7), x) == 6
def test_PowerOfLinearQ():
assert PowerOfLinearQ((6*x), x)
assert not PowerOfLinearQ((3 + 6*x**3), x)
assert PowerOfLinearQ((3 + 6*x)**3, x)
def test_LinearPairQ():
assert not LinearPairQ(6*x**2 + 4, 3*x**2 + 2, x)
assert LinearPairQ(6*x + 4, 3*x + 2, x)
assert not LinearPairQ(6*x, 3*x + 2, x)
assert LinearPairQ(6*x, 3*x, x)
def test_LeadTerm():
assert LeadTerm(a*b*c) == a*b*c
assert LeadTerm(a + b + c) == a
def test_RemainingTerms():
assert RemainingTerms(a*b*c) == a*b*c
assert RemainingTerms(a + b + c) == b + c
def test_LeadFactor():
assert LeadFactor(a*b*c) == a
assert LeadFactor(a + b + c) == a + b + c
assert LeadFactor(b*I) == I
assert LeadFactor(c*a**b) == a**b
assert LeadFactor(S(2)) == S(2)
def test_RemainingFactors():
assert RemainingFactors(a*b*c) == b*c
assert RemainingFactors(a + b + c) == 1
assert RemainingFactors(a*I) == a
def test_LeadBase():
assert LeadBase(a**b) == a
assert LeadBase(a**b*c) == a
def test_LeadDegree():
assert LeadDegree(a**b) == b
assert LeadDegree(a**b*c) == b
def test_Numer():
assert Numer(a/b) == a
assert Numer(a**(-2)) == 1
assert Numer(a**(-2)*a/b) == 1
def test_Denom():
assert Denom(a/b) == b
assert Denom(a**(-2)) == a**2
assert Denom(a**(-2)*a/b) == a*b
def test_Coeff():
assert Coeff(7 + 2*x + 4*x**3, x, 1) == 2
assert Coeff(a + b*x + c*x**3, x, 0) == a
assert Coeff(a + b*x + c*x**3, x, 4) == 0
assert Coeff(b*x + c*x**3, x, 3) == c
def test_MergeMonomials():
assert MergeMonomials(x**2*(1 + 1*x)**3*(1 + 1*x)**n, x) == x**2*(x + 1)**(n + 3)
assert MergeMonomials(x**2*(1 + 1*x)**2*(1*(1 + 1*x)**1)**2, x) == x**2*(x + 1)**4
assert MergeMonomials(b**2/a**3, x) == b**2/a**3
def test_RationalFunctionQ():
assert RationalFunctionQ(a, x)
assert RationalFunctionQ(x**2, x)
assert RationalFunctionQ(x**3 + x**4, x)
assert RationalFunctionQ(x**3*S(2), x)
assert not RationalFunctionQ(x**3 + x**(0.5), x)
assert not RationalFunctionQ(x**(S(2)/3)*(a + b*x)**2, x)
def test_Apart():
assert Apart(1/(x**2*(a + b*x)**2), x) == b**2/(a**2*(a + b*x)**2) + 1/(a**2*x**2) + 2*b**2/(a**3*(a + b*x)) - 2*b/(a**3*x)
assert Apart(x**(S(2)/3)*(a + b*x)**2, x) == x**(S(2)/3)*(a + b*x)**2
def test_RationalFunctionFactors():
assert RationalFunctionFactors(a, x) == a
assert RationalFunctionFactors(sqrt(x), x) == 1
assert RationalFunctionFactors(x*x**3, x) == x*x**3
assert RationalFunctionFactors(x*sqrt(x), x) == 1
def test_NonrationalFunctionFactors():
assert NonrationalFunctionFactors(x, x) == 1
assert NonrationalFunctionFactors(sqrt(x), x) == sqrt(x)
assert NonrationalFunctionFactors(sqrt(x)*log(x), x) == sqrt(x)*log(x)
def test_Reverse():
assert Reverse([1, 2, 3]) == [3, 2, 1]
assert Reverse(a**b) == b**a
def test_RationalFunctionExponents():
assert RationalFunctionExponents(sqrt(x), x) == [0, 0]
assert RationalFunctionExponents(a, x) == [0, 0]
assert RationalFunctionExponents(x, x) == [1, 0]
assert RationalFunctionExponents(x**(-1), x)== [0, 1]
assert RationalFunctionExponents(x**(-1)*a, x) == [0, 1]
assert RationalFunctionExponents(x**(-1) + a, x) == [1, 1]
def test_PolynomialGCD():
assert PolynomialGCD(x**2 - 1, x**2 - 3*x + 2) == x - 1
def test_PolyGCD():
assert PolyGCD(x**2 - 1, x**2 - 3*x + 2, x) == x - 1
def test_AlgebraicFunctionFactors():
assert AlgebraicFunctionFactors(sin(x)*x, x) == x
assert AlgebraicFunctionFactors(sin(x), x) == 1
assert AlgebraicFunctionFactors(x, x) == x
def test_NonalgebraicFunctionFactors():
assert NonalgebraicFunctionFactors(sin(x)*x, x) == sin(x)
assert NonalgebraicFunctionFactors(sin(x), x) == sin(x)
assert NonalgebraicFunctionFactors(x, x) == 1
def test_QuotientOfLinearsP():
assert QuotientOfLinearsP((a + b*x)/(x), x)
assert QuotientOfLinearsP(x*a, x)
assert not QuotientOfLinearsP(x**2*a, x)
assert not QuotientOfLinearsP(x**2 + a, x)
assert QuotientOfLinearsP(x + a, x)
assert QuotientOfLinearsP(x, x)
assert QuotientOfLinearsP(1 + x, x)
def test_QuotientOfLinearsParts():
assert QuotientOfLinearsParts((b*x)/(c), x) == [0, b/c, 1, 0]
assert QuotientOfLinearsParts((b*x)/(c + x), x) == [0, b, c, 1]
assert QuotientOfLinearsParts((b*x)/(c + d*x), x) == [0, b, c, d]
assert QuotientOfLinearsParts((a + b*x)/(c + d*x), x) == [a, b, c, d]
assert QuotientOfLinearsParts(x**2 + a, x) == [a + x**2, 0, 1, 0]
assert QuotientOfLinearsParts(a/x, x) == [a, 0, 0, 1]
assert QuotientOfLinearsParts(1/x, x) == [1, 0, 0, 1]
assert QuotientOfLinearsParts(a*x + 1, x) == [1, a, 1, 0]
assert QuotientOfLinearsParts(x, x) == [0, 1, 1, 0]
assert QuotientOfLinearsParts(a, x) == [a, 0, 1, 0]
def test_QuotientOfLinearsQ():
assert not QuotientOfLinearsQ((a + x), x)
assert QuotientOfLinearsQ((a + x)/(x), x)
assert QuotientOfLinearsQ((a + b*x)/(x), x)
def test_Flatten():
assert Flatten([a, b, [c, [d, e]]]) == [a, b, c, d, e]
def test_Sort():
assert Sort([b, a, c]) == [a, b, c]
assert Sort([b, a, c], True) == [c, b, a]
def test_AbsurdNumberQ():
assert AbsurdNumberQ(S(1))
assert not AbsurdNumberQ(a*x)
assert not AbsurdNumberQ(a**(S(1)/2))
assert AbsurdNumberQ((S(1)/3)**(S(1)/3))
def test_AbsurdNumberFactors():
assert AbsurdNumberFactors(S(1)) == S(1)
assert AbsurdNumberFactors((S(1)/3)**(S(1)/3)) == S(3)**(S(2)/3)/S(3)
assert AbsurdNumberFactors(a) == S(1)
def test_NonabsurdNumberFactors():
assert NonabsurdNumberFactors(a) == a
assert NonabsurdNumberFactors(S(1)) == S(1)
assert NonabsurdNumberFactors(a*S(2)) == a
def test_NumericFactor():
assert NumericFactor(S(1)) == S(1)
assert NumericFactor(1*I) == S(1)
assert NumericFactor(S(1) + I) == S(1)
assert NumericFactor(a**(S(1)/3)) == S(1)
assert NumericFactor(a*S(3)) == S(3)
assert NumericFactor(a + b) == S(1)
def test_NonnumericFactors():
assert NonnumericFactors(S(3)) == S(1)
assert NonnumericFactors(I) == I
assert NonnumericFactors(S(3) + I) == S(3) + I
assert NonnumericFactors((S(1)/3)**(S(1)/3)) == S(1)
assert NonnumericFactors(log(a)) == log(a)
def test_Prepend():
assert Prepend([1, 2, 3], [4, 5]) == [4, 5, 1, 2, 3]
def test_SumSimplerQ():
assert not SumSimplerQ(S(4 + x),S(3 + x**3))
assert SumSimplerQ(S(4 + x), S(3 - x))
def test_SumSimplerAuxQ():
assert SumSimplerAuxQ(S(4 + x), S(3 - x))
assert not SumSimplerAuxQ(S(4), S(3))
def test_SimplerSqrtQ():
assert SimplerSqrtQ(S(2), S(16*x**3))
assert not SimplerSqrtQ(S(x*2), S(16))
assert not SimplerSqrtQ(S(-4), S(16))
assert SimplerSqrtQ(S(4), S(16))
assert not SimplerSqrtQ(S(4), S(0))
def test_TrinomialParts():
assert TrinomialParts((1 + 5*x**3)**2, x) == [1, 10, 25, 3]
assert TrinomialParts(1 + 5*x**3 + 2*x**6, x) == [1, 5, 2, 3]
assert TrinomialParts(((1 + 5*x**3)**2) + 6, x) == [7, 10, 25, 3]
assert not TrinomialParts(1 + 5*x**3 + 2*x**5, x)
def test_TrinomialDegree():
assert TrinomialDegree((7 + 2*x**6)**2, x) == 6
assert TrinomialDegree(1 + 5*x**3 + 2*x**6, x) == 3
assert not TrinomialDegree(1 + 5*x**3 + 2*x**5, x)
def test_CubicMatchQ():
assert not CubicMatchQ(S(3 + x**6), x)
assert CubicMatchQ(S(x**3), x)
assert not CubicMatchQ(S(3), x)
assert CubicMatchQ(S(3 + x**3), x)
assert CubicMatchQ(S(3 + x**3 + 2*x), x)
def test_BinomialMatchQ():
assert BinomialMatchQ(x, x)
assert BinomialMatchQ(2 + 3*x**5, x)
assert BinomialMatchQ(3*x**5, x)
assert BinomialMatchQ(3*x, x)
assert not BinomialMatchQ(x + x**2 + x**3, x)
def test_TrinomialMatchQ():
assert not TrinomialMatchQ((5 + 2*x**6)**2, x)
assert not TrinomialMatchQ((7 + 8*x**6), x)
assert TrinomialMatchQ((7 + 2*x**6 + 3*x**3), x)
assert TrinomialMatchQ(b*x**2 + c*x**4, x)
def test_GeneralizedBinomialMatchQ():
assert not GeneralizedBinomialMatchQ((1 + x**4), x)
assert GeneralizedBinomialMatchQ((3*x + x**7), x)
def test_QuadraticMatchQ():
assert not QuadraticMatchQ((a + b*x)*(c + d*x), x)
assert QuadraticMatchQ(x**2 + x, x)
assert QuadraticMatchQ(x**2+1+x, x)
assert QuadraticMatchQ(x**2, x)
def test_PowerOfLinearMatchQ():
assert PowerOfLinearMatchQ(x, x)
assert not PowerOfLinearMatchQ(S(6)**3, x)
assert not PowerOfLinearMatchQ(S(6 + 3*x**2)**3, x)
assert PowerOfLinearMatchQ(S(6 + 3*x)**3, x)
def test_GeneralizedTrinomialMatchQ():
assert not GeneralizedTrinomialMatchQ(7 + 2*x**6 + 3*x**12, x)
assert not GeneralizedTrinomialMatchQ(7 + 2*x**6 + 3*x**3, x)
assert not GeneralizedTrinomialMatchQ(7 + 2*x**6 + 3*x**5, x)
assert GeneralizedTrinomialMatchQ(x**2 + x**3 + x**4, x)
def test_QuotientOfLinearsMatchQ():
assert QuotientOfLinearsMatchQ((1 + x)*(3 + 4*x**2)/(2 + 4*x), x)
assert not QuotientOfLinearsMatchQ(x*(3 + 4*x**2)/(2 + 4*x**3), x)
assert QuotientOfLinearsMatchQ(x*(3 + 4*x)/(2 + 4*x), x)
assert QuotientOfLinearsMatchQ(2*(3 + 4*x)/(2 + 4*x), x)
def test_PolynomialTermQ():
assert not PolynomialTermQ(S(3), x)
assert PolynomialTermQ(3*x**6, x)
assert not PolynomialTermQ(3*x**6+5*x, x)
def test_PolynomialTerms():
assert PolynomialTerms(x + 6*x**3 + log(x), x) == 6*x**3 + x
assert PolynomialTerms(x + 6*x**3 + 6*x, x) == 6*x**3 + 7*x
assert PolynomialTerms(x + 6*x**3 + 6, x) == 6*x**3 + x
def test_NonpolynomialTerms():
assert NonpolynomialTerms(x + 6*x**3 + log(x), x) == log(x)
assert NonpolynomialTerms(x + 6*x**3 + 6*x, x) == 0
assert NonpolynomialTerms(x + 6*x**3 + 6, x) == 6
def test_PseudoBinomialQ():
assert PseudoBinomialQ(3 + 5*(x)**6, x)
assert PseudoBinomialQ(3 + 5*(2 + 5*x)**6, x)
def test_PseudoBinomialParts():
assert PseudoBinomialParts(3 + 7*(1 + x)**6, x) == [3, 1, 7**(S(1)/S(6)), 7**(S(1)/S(6)), 6]
assert PseudoBinomialParts(3 + 7*(1 + x)**3, x) == [3, 1, 7**(S(1)/S(3)), 7**(S(1)/S(3)), 3]
assert not PseudoBinomialParts(3 + 7*(1 + x)**2, x)
assert PseudoBinomialParts(3 + 7*(x)**5, x) == [3, 1, 0, 7**(S(1)/S(5)), 5]
def test_PseudoBinomialPairQ():
assert not PseudoBinomialPairQ(3 + 5*(x)**6,3 + (x)**6, x)
assert not PseudoBinomialPairQ(3 + 5*(1 + x)**6,3 + (1 + x)**6, x)
def test_NormalizePseudoBinomial():
assert NormalizePseudoBinomial(3 + 5*(1 + x)**6, x) == 3+(5**(S(1)/S(6))+5**(S(1)/S(6))*x)**S(6)
assert NormalizePseudoBinomial(3 + 5*(x)**6, x) == 3+5*x**6
def test_CancelCommonFactors():
assert CancelCommonFactors(S(x*y*S(6))**S(6), S(x*y*S(6))) == [46656*x**6*y**6, 6*x*y]
assert CancelCommonFactors(S(y*6)**S(6), S(x*y*S(6))) == [46656*y**6, 6*x*y]
assert CancelCommonFactors(S(6), S(3)) == [6, 3]
def test_SimplerIntegrandQ():
assert SimplerIntegrandQ(S(5), 4*x, x)
assert not SimplerIntegrandQ(S(x + 5*x**3), S(x**2 + 3*x), x)
assert SimplerIntegrandQ(S(x + 8), S(x**2 + 3*x), x)
def test_Drop():
assert Drop([1, 2, 3, 4, 5, 6], [2, 4]) == [1, 5, 6]
assert Drop([1, 2, 3, 4, 5, 6], -3) == [1, 2, 3]
assert Drop([1, 2, 3, 4, 5, 6], 2) == [3, 4, 5, 6]
assert Drop(a*b*c, 1) == b*c
def test_SubstForInverseFunction():
assert SubstForInverseFunction(x, a, b, x) == b
assert SubstForInverseFunction(a, a, b, x) == a
assert SubstForInverseFunction(x**a, x**a, b, x) == x
assert SubstForInverseFunction(a*x**a, a, b, x) == a*b**a
def test_SubstForFractionalPower():
assert SubstForFractionalPower(a, b, n, c, x) == a
assert SubstForFractionalPower(x, b, n, c, x) == c
assert SubstForFractionalPower(a**(S(1)/2), a, n, b, x) == x**(n/2)
def test_CombineExponents():
assert True
def test_FractionalPowerOfSquareQ():
assert not FractionalPowerOfSquareQ(x)
assert not FractionalPowerOfSquareQ((a + b)**(S(2)/S(3)))
assert not FractionalPowerOfSquareQ((a + b)**(S(2)/S(3))*c)
assert FractionalPowerOfSquareQ(((a + b*x)**(S(2)))**(S(1)/3)) == (a + b*x)**S(2)
def test_FractionalPowerSubexpressionQ():
assert not FractionalPowerSubexpressionQ(x, a, x)
assert FractionalPowerSubexpressionQ(x**(S(2)/S(3)), a, x)
assert not FractionalPowerSubexpressionQ(b*a, a, x)
def test_FactorNumericGcd():
assert FactorNumericGcd(5*a**2*e**4 + 2*a*b*d*e**3 + 2*a*c*d**2*e**2 + b**2*d**2*e**2 - 6*b*c*d**3*e + 21*c**2*d**4) ==\
5*a**2*e**4 + 2*a*b*d*e**3 + 2*a*c*d**2*e**2 + b**2*d**2*e**2 - 6*b*c*d**3*e + 21*c**2*d**4
assert FactorNumericGcd(x**(S(2))) == x**S(2)
assert FactorNumericGcd(log(x)) == log(x)
assert FactorNumericGcd(log(x)*x) == x*log(x)
assert FactorNumericGcd(log(x) + x**S(2)) == log(x) + x**S(2)
def test_Apply():
assert Apply(List, [a, b, c]) == [a, b, c]
def test_TrigSimplify():
assert TrigSimplify(a*sin(x)**2 + a*cos(x)**2 + v) == a + v
assert TrigSimplify(a*sec(x)**2 - a*tan(x)**2 + v) == a + v
assert TrigSimplify(a*csc(x)**2 - a*cot(x)**2 + v) == a + v
assert TrigSimplify(S(1) - sin(x)**2) == cos(x)**2
assert TrigSimplify(1 + tan(x)**2) == sec(x)**2
assert TrigSimplify(1 + cot(x)**2) == csc(x)**2
assert TrigSimplify(-S(1) + sec(x)**2) == tan(x)**2
assert TrigSimplify(-1 + csc(x)**2) == cot(x)**2
def test_MergeFactors():
assert simplify(MergeFactors(b/(a - c)**3 , 8*c**3*(b*x + c)**(3/2)/(3*b**4) - 24*c**2*(b*x + c)**(5/2)/(5*b**4) + \
24*c*(b*x + c)**(7/2)/(7*b**4) - 8*(b*x + c)**(9/2)/(9*b**4)) - (8*c**3*(b*x + c)**1.5/(3*b**3) - 24*c**2*(b*x + c)**2.5/(5*b**3) + \
24*c*(b*x + c)**3.5/(7*b**3) - 8*(b*x + c)**4.5/(9*b**3))/(a - c)**3) == 0
assert MergeFactors(x, x) == x**2
assert MergeFactors(x*y, x) == x**2*y
def test_FactorInteger():
assert FactorInteger(2434500) == [(2, 2), (3, 2), (5, 3), (541, 1)]
def test_ContentFactor():
assert ContentFactor(a*b + a*c) == a*(b + c)
def test_Order():
assert Order(a, b) == 1
assert Order(b, a) == -1
assert Order(a, a) == 0
def test_FactorOrder():
assert FactorOrder(1, 1) == 0
assert FactorOrder(1, 2) == -1
assert FactorOrder(2, 1) == 1
assert FactorOrder(a, b) == 1
def test_Smallest():
assert Smallest([2, 1, 3, 4]) == 1
assert Smallest(1, 2) == 1
assert Smallest(-1, -2) == -2
def test_MostMainFactorPosition():
assert MostMainFactorPosition([S(1), S(2), S(3)]) == 1
assert MostMainFactorPosition([S(1), S(7), S(3), S(4), S(5)]) == 2
def test_OrderedQ():
assert OrderedQ([a, b])
assert not OrderedQ([b, a])
def test_MinimumDegree():
assert MinimumDegree(S(1), S(2)) == 1
assert MinimumDegree(S(1), sqrt(2)) == 1
assert MinimumDegree(sqrt(2), S(1)) == 1
assert MinimumDegree(sqrt(3), sqrt(2)) == sqrt(2)
assert MinimumDegree(sqrt(2), sqrt(2)) == sqrt(2)
def test_PositiveFactors():
assert PositiveFactors(S(0)) == 1
assert PositiveFactors(-S(1)) == S(1)
assert PositiveFactors(sqrt(2)) == sqrt(2)
assert PositiveFactors(-log(2)) == log(2)
assert PositiveFactors(sqrt(2)*S(-1)) == sqrt(2)
def test_NonpositiveFactors():
assert NonpositiveFactors(S(0)) == 0
assert NonpositiveFactors(-S(1)) == -1
assert NonpositiveFactors(sqrt(2)) == 1
assert NonpositiveFactors(-log(2)) == -1
def test_Sign():
assert Sign(S(0)) == 0
assert Sign(S(1)) == 1
assert Sign(-S(1)) == -1
def test_PolynomialInQ():
v = log(x)
assert PolynomialInQ(S(1), v, x)
assert PolynomialInQ(v, v, x)
assert PolynomialInQ(1 + v**2, v, x)
assert PolynomialInQ(1 + a*v**2, v, x)
assert not PolynomialInQ(sqrt(v), v, x)
def test_ExponentIn():
v = log(x)
assert ExponentIn(S(1), log(x), x) == 0
assert ExponentIn(S(1) + v, log(x), x) == 1
assert ExponentIn(S(1) + v + v**3, log(x), x) == 3
assert ExponentIn(S(2)*sqrt(v)*v**3, log(x), x) == 3.5
def test_PolynomialInSubst():
v = log(x)
assert PolynomialInSubst(S(1) + log(x)**3, log(x), x) == 1 + x**3
assert PolynomialInSubst(S(1) + log(x), log(x), x) == x + 1
def test_Distrib():
assert Distrib(x, a) == x*a
assert Distrib(x, a + b) == a*x + b*x
def test_DistributeDegree():
assert DistributeDegree(x, m) == x**m
assert DistributeDegree(x**a, m) == x**(a*m)
assert DistributeDegree(a*b, m) == a**m * b**m
def test_FunctionOfPower():
assert FunctionOfPower(a, x) == None
assert FunctionOfPower(x, x) == 1
assert FunctionOfPower(x**3, x) == 3
assert FunctionOfPower(x**3*cos(x**6), x) == 3
def test_DivideDegreesOfFactors():
assert DivideDegreesOfFactors(a**b, S(3)) == a**(b/3)
assert DivideDegreesOfFactors(a**b*c, S(3)) == a**(b/3)*c**(c/3)
def test_MonomialFactor():
assert MonomialFactor(a, x) == [0, a]
assert MonomialFactor(x, x) == [1, 1]
assert MonomialFactor(x + y, x) == [0, x + y]
assert MonomialFactor(log(x), x) == [0, log(x)]
assert MonomialFactor(log(x)*x, x) == [1, log(x)]
def test_NormalizeIntegrand():
assert NormalizeIntegrand((x**2 + 8), x) == x**2 + 8
assert NormalizeIntegrand((x**2 + 3*x)**2, x) == x**2*(x + 3)**2
assert NormalizeIntegrand(a**2*(a + b*x)**2, x) == a**2*(a + b*x)**2
assert NormalizeIntegrand(b**2/(a**2*(a + b*x)**2), x) == b**2/(a**2*(a + b*x)**2)
def test_NormalizeIntegrandAux():
v = (6*A*a*c - 2*A*b**2 + B*a*b)/(a*x**2) - (6*A*a**2*c**2 - 10*A*a*b**2*c - 8*A*a*b*c**2*x + 2*A*b**4 + 2*A*b**3*c*x + 5*B*a**2*b*c + 4*B*a**2*c**2*x - B*a*b**3 - B*a*b**2*c*x)/(a**2*(a + b*x + c*x**2)) + (-2*A*b + B*a)*(4*a*c - b**2)/(a**2*x)
assert NormalizeIntegrandAux(v, x) == (6*A*a*c - 2*A*b**2 + B*a*b)/(a*x**2) - (6*A*a**2*c**2 - 10*A*a*b**2*c + 2*A*b**4 + 5*B*a**2*b*c - B*a*b**3 + x*(-8*A*a*b*c**2 + 2*A*b**3*c + 4*B*a**2*c**2 - B*a*b**2*c))/(a**2*(a + b*x + c*x**2)) + (-2*A*b + B*a)*(4*a*c - b**2)/(a**2*x)
assert NormalizeIntegrandAux((x**2 + 3*x)**2, x) == x**2*(x + 3)**2
assert NormalizeIntegrandAux((x**2 + 8), x) == x**2 + 8
def test_NormalizeIntegrandFactor():
assert NormalizeIntegrandFactor((3*x + x**3)**2, x) == x**2*(x**2 + 3)**2
assert NormalizeIntegrandFactor((x**2 + 8), x) == x**2 + 8
def test_NormalizeIntegrandFactorBase():
assert NormalizeIntegrandFactorBase((x**2 + 8)**3, x) == (x**2 + 8)**3
assert NormalizeIntegrandFactorBase((x**2 + 8), x) == x**2 + 8
assert NormalizeIntegrandFactorBase(a**2*(a + b*x)**2, x) == a**2*(a + b*x)**2
def test_AbsorbMinusSign():
assert AbsorbMinusSign((x + 2)**5*(x + 3)**5) == (-x - 3)**5*(x + 2)**5
assert AbsorbMinusSign((x + 2)**5*(x + 3)**2) == -(x + 2)**5*(x + 3)**2
def test_NormalizeLeadTermSigns():
assert NormalizeLeadTermSigns((-x + 3)*(x**2 + 3)) == (-x + 3)*(x**2 + 3)
assert NormalizeLeadTermSigns(x + 3) == x + 3
def test_SignOfFactor():
assert SignOfFactor(S(-x + 3)) == [1, -x + 3]
assert SignOfFactor(S(-x)) == [-1, x]
def test_NormalizePowerOfLinear():
assert NormalizePowerOfLinear((x + 3)**5, x) == (x + 3)**5
assert NormalizePowerOfLinear(((x + 3)**2) + 3, x) == x**2 + 6*x + 12
def test_SimplifyIntegrand():
assert SimplifyIntegrand((x**2 + 3)**2, x) == (x**2 + 3)**2
assert SimplifyIntegrand(x**2 + 3 + (x**6) + 6, x) == x**6 + x**2 + 9
def test_SimplifyTerm():
assert SimplifyTerm(a**2/b**2, x) == a**2/b**2
assert SimplifyTerm(-6*x/5 + (5*x + 3)**2/25 - 9/25, x) == x**2
def test_togetherSimplify():
assert TogetherSimplify(-6*x/5 + (5*x + 3)**2/25 - 9/25) == x**2
def test_ExpandToSum():
qq = 6
Pqq = e**3
Pq = (d+e*x**2)**3
aa = 2
nn = 2
cc = 1
pp = -1/2
bb = 3
assert nsimplify(ExpandToSum(Pq - Pqq*x**qq - Pqq*(aa*x**(-2*nn + qq)*(-2*nn + qq + 1) + bb*x**(-nn + qq)*(nn*(pp - 1) + qq + 1))/(cc*(2*nn*pp + qq + 1)), x) - \
(d**3 + x**4*(3*d*e**2 - 2.4*e**3) + x**2*(3*d**2*e - 1.2*e**3))) == 0
assert ExpandToSum(x**2 + 3*x + 3, x**3 + 3, x) == x**3*(x**2 + 3*x + 3) + 3*x**2 + 9*x + 9
assert ExpandToSum(x**3 + 6, x) == x**3 + 6
assert ExpandToSum(S(x**2 + 3*x + 3)*3, x) == 3*x**2 + 9*x + 9
assert ExpandToSum((a + b*x), x) == a + b*x
def test_UnifySum():
assert UnifySum((3 + x + 6*x**3 + sin(x)), x) == 6*x**3 + x + sin(x) + 3
assert UnifySum((3 + x + 6*x**3)*3, x) == 18*x**3 + 3*x + 9
def test_FunctionOfInverseLinear():
assert FunctionOfInverseLinear((x)/(a + b*x), x) == [a, b]
assert FunctionOfInverseLinear((c + d*x)/(a + b*x), x) == [a, b]
assert not FunctionOfInverseLinear(1/(a + b*x), x)
def test_PureFunctionOfSinhQ():
v = log(x)
f = sinh(v)
assert PureFunctionOfSinhQ(f, v, x)
assert not PureFunctionOfSinhQ(cosh(v), v, x)
assert PureFunctionOfSinhQ(f**2, v, x)
def test_PureFunctionOfTanhQ():
v = log(x)
f = tanh(v)
assert PureFunctionOfTanhQ(f, v, x)
assert not PureFunctionOfTanhQ(cosh(v), v, x)
assert PureFunctionOfTanhQ(f**2, v, x)
def test_PureFunctionOfCoshQ():
v = log(x)
f = cosh(v)
assert PureFunctionOfCoshQ(f, v, x)
assert not PureFunctionOfCoshQ(sinh(v), v, x)
assert PureFunctionOfCoshQ(f**2, v, x)
def test_IntegerQuotientQ():
u = S(2)*sin(x)
v = sin(x)
assert IntegerQuotientQ(u, v)
assert IntegerQuotientQ(u, u)
assert not IntegerQuotientQ(S(1), S(2))
def test_OddQuotientQ():
u = S(3)*sin(x)
v = sin(x)
assert OddQuotientQ(u, v)
assert OddQuotientQ(u, u)
assert not OddQuotientQ(S(1), S(2))
def test_EvenQuotientQ():
u = S(2)*sin(x)
v = sin(x)
assert EvenQuotientQ(u, v)
assert not EvenQuotientQ(u, u)
assert not EvenQuotientQ(S(1), S(2))
def test_FunctionOfSinhQ():
v = log(x)
assert FunctionOfSinhQ(cos(sinh(v)), v, x)
assert FunctionOfSinhQ(sinh(v), v, x)
assert FunctionOfSinhQ(sinh(v)*cos(sinh(v)), v, x)
def test_FunctionOfCoshQ():
v = log(x)
assert FunctionOfCoshQ(cos(cosh(v)), v, x)
assert FunctionOfCoshQ(cosh(v), v, x)
assert FunctionOfCoshQ(cosh(v)*cos(cosh(v)), v, x)
def test_FunctionOfTanhQ():
v = log(x)
t = Tanh(v)
c = Coth(v)
assert FunctionOfTanhQ(t, v, x)
assert FunctionOfTanhQ(c, v, x)
assert FunctionOfTanhQ(t + c, v, x)
assert FunctionOfTanhQ(t*c, v, x)
assert not FunctionOfTanhQ(sin(x), v, x)
def test_FunctionOfTanhWeight():
v = log(x)
t = Tanh(v)
c = Coth(v)
assert FunctionOfTanhWeight(x, v, x) == 0
assert FunctionOfTanhWeight(sinh(v), v, x) == 0
assert FunctionOfTanhWeight(tanh(v), v, x) == 1
assert FunctionOfTanhWeight(coth(v), v, x) == -1
assert FunctionOfTanhWeight(t**2, v, x) == 1
assert FunctionOfTanhWeight(sinh(v)**2, v, x) == -1
assert FunctionOfTanhWeight(coth(v)*sinh(v)**2, v, x) == -2
def test_FunctionOfHyperbolicQ():
v = log(x)
s = Sinh(v)
t = Tanh(v)
assert not FunctionOfHyperbolicQ(x, v, x)
assert FunctionOfHyperbolicQ(s + t, v, x)
assert FunctionOfHyperbolicQ(sinh(t), v, x)
def test_SmartNumerator():
assert SmartNumerator(x**(-2)) == 1
assert SmartNumerator(x**(2)*a) == x**2*a
def test_SmartDenominator():
assert SmartDenominator(x**(-2)) == x**2
assert SmartDenominator(x**(-2)*1/S(3)) == x**2*3
def test_SubstForAux():
v = log(x)
assert SubstForAux(v, v, x) == x
assert SubstForAux(v**2, v, x) == x**2
assert SubstForAux(x, v, x) == x
assert SubstForAux(v**2, v**4, x) == sqrt(x)
assert SubstForAux(v**2*v, v, x) == x**3
def test_SubstForTrig():
v = log(x)
s, c, t = sin(v), cos(v), tan(v)
assert SubstForTrig(cos(a/2 + b*x/2), x/sqrt(x**2 + 1), 1/sqrt(x**2 + 1), a/2 + b*x/2, x) == 1/sqrt(x**2 + 1)
assert SubstForTrig(s, sin, cos, v, x) == sin
assert SubstForTrig(t, sin(v), cos(v), v, x) == sin(log(x))/cos(log(x))
assert SubstForTrig(sin(2*v), sin(x), cos(x), v, x) == 2*sin(x)*cos(x)
assert SubstForTrig(s*t, sin(x), cos(x), v, x) == sin(x)**2/cos(x)
def test_SubstForHyperbolic():
v = log(x)
s, c, t = sinh(v), cosh(v), tanh(v)
assert SubstForHyperbolic(s, sinh(x), cosh(x), v, x) == sinh(x)
assert SubstForHyperbolic(t, sinh(x), cosh(x), v, x) == sinh(x)/cosh(x)
assert SubstForHyperbolic(sinh(2*v), sinh(x), cosh(x), v, x) == 2*sinh(x)*cosh(x)
assert SubstForHyperbolic(s*t, sinh(x), cosh(x), v, x) == sinh(x)**2/cosh(x)
def test_SubstForFractionalPowerOfLinear():
u = a + b*x
assert not SubstForFractionalPowerOfLinear(u, x)
assert not SubstForFractionalPowerOfLinear(u**(S(2)), x)
assert SubstForFractionalPowerOfLinear(u**(S(1)/2), x) == [x**2, 2, a + b*x, 1/b]
def test_InverseFunctionOfLinear():
u = a + b*x
assert InverseFunctionOfLinear(log(u)*sin(x), x) == log(u)
assert InverseFunctionOfLinear(log(u), x) == log(u)
def test_InertTrigQ():
s = sin(x)
c = cos(x)
assert not InertTrigQ(sin(x), csc(x), cos(h))
assert InertTrigQ(sin(x), csc(x))
assert not InertTrigQ(s, c)
assert InertTrigQ(c)
def test_PowerOfInertTrigSumQ():
func = sin
assert PowerOfInertTrigSumQ((1 + S(2)*(S(3)*func(x**2))**S(5))**3, func, x)
assert PowerOfInertTrigSumQ((1 + 2*(S(3)*func(x**2))**3 + 4*(S(5)*func(x**2))**S(3))**2, func, x)
def test_PiecewiseLinearQ():
assert PiecewiseLinearQ(a + b*x, x)
assert not PiecewiseLinearQ(Log(c*sin(a)**S(3)), x)
assert not PiecewiseLinearQ(x**3, x)
assert PiecewiseLinearQ(atanh(tanh(a + b*x)), x)
assert PiecewiseLinearQ(tanh(atanh(a + b*x)), x)
assert not PiecewiseLinearQ(coth(atanh(a + b*x)), x)
def test_KnownTrigIntegrandQ():
func = sin(a + b*x)
assert KnownTrigIntegrandQ([sin], S(1), x)
assert KnownTrigIntegrandQ([sin], (a + b*func)**m, x)
assert KnownTrigIntegrandQ([sin], (a + b*func)**m*(1 + 2*func), x)
assert KnownTrigIntegrandQ([sin], a + c*func**2, x)
assert KnownTrigIntegrandQ([sin], a + b*func + c*func**2, x)
assert KnownTrigIntegrandQ([sin], (a + b*func)**m*(c + d*func**2), x)
assert KnownTrigIntegrandQ([sin], (a + b*func)**m*(c + d*func + e*func**2), x)
assert not KnownTrigIntegrandQ([cos], (a + b*func)**m, x)
def test_KnownSineIntegrandQ():
assert KnownSineIntegrandQ((a + b*sin(a + b*x))**m, x)
def test_KnownTangentIntegrandQ():
assert KnownTangentIntegrandQ((a + b*tan(a + b*x))**m, x)
def test_KnownCotangentIntegrandQ():
assert KnownCotangentIntegrandQ((a + b*cot(a + b*x))**m, x)
def test_KnownSecantIntegrandQ():
assert KnownSecantIntegrandQ((a + b*sec(a + b*x))**m, x)
def test_TryPureTanSubst():
assert TryPureTanSubst(atan(c*(a + b*tan(a + b*x))), x)
assert TryPureTanSubst(atanh(c*(a + b*cot(a + b*x))), x)
assert not TryPureTanSubst(tan(c*(a + b*cot(a + b*x))), x)
def test_TryPureTanhSubst():
assert not TryPureTanhSubst(log(x), x)
assert TryPureTanhSubst(sin(x), x)
assert not TryPureTanhSubst(atanh(a*tanh(x)), x)
assert not TryPureTanhSubst((a + b*x)**S(2), x)
def test_TryTanhSubst():
assert not TryTanhSubst(log(x), x)
assert not TryTanhSubst(a*(b + c)**3, x)
assert not TryTanhSubst(1/(a + b*sinh(x)**S(3)), x)
assert not TryTanhSubst(sinh(S(3)*x)*cosh(S(4)*x), x)
assert not TryTanhSubst(a*(b*sech(x)**3)**c, x)
def test_GeneralizedBinomialQ():
assert GeneralizedBinomialQ(a*x**q + b*x**n, x)
assert not GeneralizedBinomialQ(a*x**q, x)
def test_GeneralizedTrinomialQ():
assert not GeneralizedTrinomialQ(7 + 2*x**6 + 3*x**12, x)
assert not GeneralizedTrinomialQ(a*x**q + c*x**(2*n-q), x)
def test_SubstForFractionalPowerOfQuotientOfLinears():
assert SubstForFractionalPowerOfQuotientOfLinears(((a + b*x)/(c + d*x))**(S(3)/2), x) == [x**4/(b - d*x**2)**2, 2, (a + b*x)/(c + d*x), -a*d + b*c]
def test_SubstForFractionalPowerQ():
assert SubstForFractionalPowerQ(x, sin(x), x)
assert SubstForFractionalPowerQ(x**2, sin(x), x)
assert not SubstForFractionalPowerQ(x**(S(3)/2), sin(x), x)
assert SubstForFractionalPowerQ(sin(x)**(S(3)/2), sin(x), x)
def test_AbsurdNumberGCD():
assert AbsurdNumberGCD(S(4)) == 4
assert AbsurdNumberGCD(S(4), S(8), S(12)) == 4
assert AbsurdNumberGCD(S(2), S(3), S(12)) == 1
def test_TrigReduce():
assert TrigReduce(cos(x)**2) == cos(2*x)/2 + 1/2
assert TrigReduce(cos(x)**2*sin(x)) == sin(x)/4 + sin(3*x)/4
assert TrigReduce(cos(x)**2+sin(x)) == sin(x) + cos(2*x)/2 + 1/2
assert TrigReduce(cos(x)**2*sin(x)**5) == 5*sin(x)/64 + sin(3*x)/64 - 3*sin(5*x)/64 + sin(7*x)/64
assert TrigReduce(2*sin(x)*cos(x) + 2*cos(x)**2) == sin(2*x) + cos(2*x) + 1
assert TrigReduce(sinh(a + b*x)**2) == cosh(2*a + 2*b*x)/2 - 1/2
assert TrigReduce(sinh(a + b*x)*cosh(a + b*x)) == sinh(2*a + 2*b*x)/2
def test_FunctionOfDensePolynomialsQ():
assert FunctionOfDensePolynomialsQ(x**2 + 3, x)
assert not FunctionOfDensePolynomialsQ(x**2, x)
assert not FunctionOfDensePolynomialsQ(x, x)
assert FunctionOfDensePolynomialsQ(S(2), x)
def test_PureFunctionOfSinQ():
v = log(x)
f = sin(v)
assert PureFunctionOfSinQ(f, v, x)
assert not PureFunctionOfSinQ(cos(v), v, x)
assert PureFunctionOfSinQ(f**2, v, x)
def test_PureFunctionOfTanQ():
v = log(x)
f = tan(v)
assert PureFunctionOfTanQ(f, v, x)
assert not PureFunctionOfTanQ(cos(v), v, x)
assert PureFunctionOfTanQ(f**2, v, x)
def test_PowerVariableSubst():
assert PowerVariableSubst((2*x)**3, 2, x) == 8*x**(3/2)
assert PowerVariableSubst((2*x)**3, 2, x) == 8*x**(3/2)
assert PowerVariableSubst((2*x), 2, x) == 2*x
assert PowerVariableSubst((2*x)**3, 2, x) == 8*x**(3/2)
assert PowerVariableSubst((2*x)**7, 2, x) == 128*x**(7/2)
assert PowerVariableSubst((6+2*x)**7, 2, x) == (2*x + 6)**7
assert PowerVariableSubst((2*x)**7+3, 2, x) == 128*x**(7/2) + 3
def test_PowerVariableDegree():
assert PowerVariableDegree(S(2), 0, 2*x, x) == [0, 2*x]
assert PowerVariableDegree((2*x)**2, 0, 2*x, x) == [2, 1]
assert PowerVariableDegree(x**2, 0, 2*x, x) == [2, 1]
assert PowerVariableDegree(S(4), 0, 2*x, x) == [0, 2*x]
def test_PowerVariableExpn():
assert not PowerVariableExpn((x)**3, 2, x)
assert not PowerVariableExpn((2*x)**3, 2, x)
assert PowerVariableExpn((2*x)**2, 4, x) == [4*x**3, 2, 1]
def test_FunctionOfQ():
assert FunctionOfQ(x**2, sqrt(-exp(2*x**2) + 1)*exp(x**2),x)
assert not FunctionOfQ(S(x**3), x*2, x)
assert FunctionOfQ(S(a), x*2, x)
assert FunctionOfQ(S(3*x), x*2, x)
def test_ExpandTrigExpand():
assert ExpandTrigExpand(1, cos(x), x**2, 2, 2, x) == 4*cos(x**2)**4 - 4*cos(x**2)**2 + 1
assert ExpandTrigExpand(1, cos(x) + sin(x), x**2, 2, 2, x) == 4*sin(x**2)**2*cos(x**2)**2 + 8*sin(x**2)*cos(x**2)**3 - 4*sin(x**2)*cos(x**2) + 4*cos(x**2)**4 - 4*cos(x**2)**2 + 1
def test_TrigToExp():
from sympy.integrals.rubi.utility_function import rubi_exp as exp
assert TrigToExp(sin(x)) == -I*(exp(I*x) - exp(-I*x))/2
assert TrigToExp(cos(x)) == exp(I*x)/2 + exp(-I*x)/2
assert TrigToExp(cos(x)*tan(x**2)) == I*(exp(I*x)/2 + exp(-I*x)/2)*(-exp(I*x**2) + exp(-I*x**2))/(exp(I*x**2) + exp(-I*x**2))
assert TrigToExp(cos(x) + sin(x)**2) == -(exp(I*x) - exp(-I*x))**2/4 + exp(I*x)/2 + exp(-I*x)/2
assert Simplify(TrigToExp(cos(x)*tan(x**S(2))*sin(x)**S(2))-(-I*(exp(I*x)/S(2) + exp(-I*x)/S(2))*(exp(I*x) - exp(-I*x))**S(2)*(-exp(I*x**S(2)) + exp(-I*x**S(2)))/(S(4)*(exp(I*x**S(2)) + exp(-I*x**S(2)))))) == 0
def test_ExpandTrigReduce():
assert ExpandTrigReduce(2*cos(3 + x)**3, x) == 3*cos(x + 3)/2 + cos(3*x + 9)/2
assert ExpandTrigReduce(2*sin(x)**3+cos(2 + x), x) == 3*sin(x)/2 - sin(3*x)/2 + cos(x + 2)
assert ExpandTrigReduce(cos(x + 3)**2, x) == cos(2*x + 6)/2 + 1/2
def test_NormalizeTrig():
assert NormalizeTrig(S(2*sin(2 + x)), x) == 2*sin(x + 2)
assert NormalizeTrig(S(2*sin(2 + x)**3), x) == 2*sin(x + 2)**3
assert NormalizeTrig(S(2*sin((2 + x)**2)**3), x) == 2*sin(x**2 + 4*x + 4)**3
def test_FunctionOfTrigQ():
v = log(x)
s = sin(v)
t = tan(v)
assert not FunctionOfTrigQ(x, v, x)
assert FunctionOfTrigQ(s + t, v, x)
assert FunctionOfTrigQ(sin(t), v, x)
def test_RationalFunctionExpand():
assert RationalFunctionExpand(x**S(5)*(e + f*x)**n/(a + b*x**S(3)), x) == -a*x**2*(e + f*x)**n/(b*(a + b*x**3)) +\
e**2*(e + f*x)**n/(b*f**2) - 2*e*(e + f*x)**(n + 1)/(b*f**2) + (e + f*x)**(n + 2)/(b*f**2)
assert RationalFunctionExpand(x**S(3)*(S(2)*x + 2)**S(2)/(2*x**2 + 1), x) == 2*x**3 + 4*x**2 + x + (- x + 2)/(2*x**2 + 1) - 2
assert RationalFunctionExpand((a + b*x + c*x**4)*log(x)**3, x) == a*log(x)**3 + b*x*log(x)**3 + c*x**4*log(x)**3
assert RationalFunctionExpand(a + b*x + c*x**4, x) == a + b*x + c*x**4
def test_SameQ():
assert SameQ(1, 1, 1)
assert not SameQ(1, 1, 2)
def test_Map2():
assert Map2(Add, [a, b, c], [x, y, z]) == [a + x, b + y, c + z]
def test_ConstantFactor():
assert ConstantFactor(a + a*x**3, x) == [a, x**3 + 1]
assert ConstantFactor(a, x) == [a, 1]
assert ConstantFactor(x, x) == [1, x]
assert ConstantFactor(x**S(3), x) == [1, x**3]
assert ConstantFactor(x**(S(3)/2), x) == [1, x**(3/2)]
assert ConstantFactor(a*x**3, x) == [a, x**3]
assert ConstantFactor(a + x**3, x) == [1, a + x**3]
def test_CommonFactors():
assert CommonFactors([a, a, a]) == [a, 1, 1, 1]
assert CommonFactors([x*S(2), x**S(3)*S(2), sin(x)*x*S(2)]) == [2, x, x**3, x*sin(x)]
assert CommonFactors([x, x**S(3), sin(x)*x]) == [1, x, x**3, x*sin(x)]
assert CommonFactors([S(2), S(4), S(6)]) == [2, 1, 2, 3]
def test_FunctionOfLinear():
f = sin(a + b*x)
assert FunctionOfLinear(f, x) == [sin(x), a, b]
assert FunctionOfLinear(a + b*x, x) == [x, a, b]
assert not FunctionOfLinear(a, x)
def test_FunctionOfExponentialQ():
assert FunctionOfExponentialQ(exp(x + exp(x) + exp(exp(x))), x)
assert FunctionOfExponentialQ(a**(a + b*x), x)
assert FunctionOfExponentialQ(a**(b*x), x)
assert not FunctionOfExponentialQ(a**sin(a + b*x), x)
def test_FunctionOfExponential():
assert FunctionOfExponential(a**(a + b*x), x)
def test_FunctionOfExponentialFunction():
assert FunctionOfExponentialFunction(a**(a + b*x), x) == x
assert FunctionOfExponentialFunction(S(2)*a**(a + b*x), x) == 2*x
def test_FunctionOfTrig():
assert FunctionOfTrig(sin(x + 1), x + 1, x) == x + 1
assert FunctionOfTrig(sin(x), x) == x
assert not FunctionOfTrig(cos(x**2 + 1), x)
assert FunctionOfTrig(sin(a+b*x)**3, x) == a+b*x
def test_AlgebraicTrigFunctionQ():
assert AlgebraicTrigFunctionQ(sin(x + 3), x)
assert AlgebraicTrigFunctionQ(x, x)
assert AlgebraicTrigFunctionQ(x + 1, x)
assert AlgebraicTrigFunctionQ(sinh(x + 1), x)
assert AlgebraicTrigFunctionQ(sinh(x + 1)**2, x)
assert not AlgebraicTrigFunctionQ(sinh(x**2 + 1)**2, x)
def test_FunctionOfHyperbolic():
assert FunctionOfTrig(sin(x + 1), x + 1, x) == x + 1
assert FunctionOfTrig(sin(x), x) == x
assert not FunctionOfTrig(cos(x**2 + 1), x)
def test_FunctionOfExpnQ():
assert FunctionOfExpnQ(x, x, x) == 1
assert FunctionOfExpnQ(x**2, x, x) == 2
assert FunctionOfExpnQ(x**2.1, x, x) == 1
assert not FunctionOfExpnQ(x, x**2, x)
assert not FunctionOfExpnQ(x + 1, (x + 5)**2, x)
assert not FunctionOfExpnQ(x + 1, (x + 1)**2, x)
def test_PureFunctionOfCosQ():
v = log(x)
f = cos(v)
assert PureFunctionOfCosQ(f, v, x)
assert not PureFunctionOfCosQ(sin(v), v, x)
assert PureFunctionOfCosQ(f**2, v, x)
def test_PureFunctionOfCotQ():
v = log(x)
f = cot(v)
assert PureFunctionOfCotQ(f, v, x)
assert not PureFunctionOfCotQ(sin(v), v, x)
assert PureFunctionOfCotQ(f**2, v, x)
def test_FunctionOfSinQ():
v = log(x)
assert FunctionOfSinQ(cos(sin(v)), v, x)
assert FunctionOfSinQ(sin(v), v, x)
assert FunctionOfSinQ(sin(v)*cos(sin(v)), v, x)
def test_FunctionOfCosQ():
v = log(x)
assert FunctionOfCosQ(cos(cos(v)), v, x)
assert FunctionOfCosQ(cos(v), v, x)
assert FunctionOfCosQ(cos(v)*cos(cos(v)), v, x)
def test_FunctionOfTanQ():
v = log(x)
t = tan(v)
c = cot(v)
assert FunctionOfTanQ(t, v, x)
assert FunctionOfTanQ(c, v, x)
assert FunctionOfTanQ(t + c, v, x)
assert FunctionOfTanQ(t*c, v, x)
assert not FunctionOfTanQ(sin(x), v, x)
def test_FunctionOfTanWeight():
v = log(x)
t = tan(v)
c = cot(v)
assert FunctionOfTanWeight(x, v, x) == 0
assert FunctionOfTanWeight(sin(v), v, x) == 0
assert FunctionOfTanWeight(tan(v), v, x) == 1
assert FunctionOfTanWeight(cot(v), v, x) == -1
assert FunctionOfTanWeight(t**2, v, x) == 1
assert FunctionOfTanWeight(sin(v)**2, v, x) == -1
assert FunctionOfTanWeight(cot(v)*sin(v)**2, v, x) == -2
def test_OddTrigPowerQ():
assert not OddTrigPowerQ(sin(x)**3, 1, x)
assert OddTrigPowerQ(sin(3),1,x)
assert OddTrigPowerQ(sin(3*x),x,x)
assert OddTrigPowerQ(sin(3*x)**3,x,x)
def test_FunctionOfLog():
assert not FunctionOfLog(x**2*(a + b*x)**3*exp(-a - b*x) ,False, False, x)
assert FunctionOfLog(log(2*x**8)*2 + log(2*x**8) + 1, x) == [3*x + 1, 2*x**8, 8]
assert FunctionOfLog(log(2*x)**2,x) == [x**2, 2*x, 1]
assert FunctionOfLog(log(3*x**3)**2 + 1,x) == [x**2 + 1, 3*x**3, 3]
assert FunctionOfLog(log(2*x**8)*2,x) == [2*x, 2*x**8, 8]
assert not FunctionOfLog(2*sin(x)*2,x)
def test_EulerIntegrandQ():
assert EulerIntegrandQ((2*x + 3*((x + 1)**3)**1.5)**(-3), x)
assert not EulerIntegrandQ((2*x + (2*x**2)**2)**3, x)
assert not EulerIntegrandQ(3*x**2 + 5*x + 1, x)
def test_Divides():
assert not Divides(x, a*x**2, x)
assert Divides(x, a*x, x) == a
def test_EasyDQ():
assert EasyDQ(3*x**2, x)
assert EasyDQ(3*x**3 - 6, x)
assert EasyDQ(x**3, x)
assert EasyDQ(sin(x**log(3)), x)
def test_ProductOfLinearPowersQ():
assert ProductOfLinearPowersQ(S(1), x)
assert ProductOfLinearPowersQ((x + 1)**3, x)
assert not ProductOfLinearPowersQ((x**2 + 1)**3, x)
assert ProductOfLinearPowersQ(x + 1, x)
def test_Rt():
b = symbols('b')
assert Rt(-b**2, 4) == (-b**2)**(S(1)/S(4))
assert Rt(x**2, 2) == x
assert Rt(S(2 + 3*I), S(8)) == (2 + 3*I)**(1/8)
assert Rt(x**2 + 4 + 4*x, 2) == x + 2
assert Rt(S(8), S(3)) == 2
assert Rt(S(16807), S(5)) == 7
def test_NthRoot():
assert NthRoot(S(14580), S(3)) == 9*2**(S(2)/S(3))*5**(S(1)/S(3))
assert NthRoot(9, 2) == 3.0
assert NthRoot(81, 2) == 9.0
assert NthRoot(81, 4) == 3.0
def test_AtomBaseQ():
assert not AtomBaseQ(x**2)
assert AtomBaseQ(x**3)
assert AtomBaseQ(x)
assert AtomBaseQ(S(2)**3)
assert not AtomBaseQ(sin(x))
def test_SumBaseQ():
assert not SumBaseQ((x + 1)**2)
assert SumBaseQ((x + 1)**3)
assert SumBaseQ((3*x+3))
assert not SumBaseQ(x)
def test_NegSumBaseQ():
assert not NegSumBaseQ(-x + 1)
assert NegSumBaseQ(x - 1)
assert not NegSumBaseQ((x - 1)**2)
assert NegSumBaseQ((x - 1)**3)
def test_AllNegTermQ():
x = Symbol('x', negative=True)
assert AllNegTermQ(x)
assert not AllNegTermQ(x + 2)
assert AllNegTermQ(x - 2)
assert AllNegTermQ((x - 2)**3)
assert not AllNegTermQ((x - 2)**2)
def test_TrigSquareQ():
assert TrigSquareQ(sin(x)**2)
assert TrigSquareQ(cos(x)**2)
assert not TrigSquareQ(tan(x)**2)
def test_Inequality():
assert not Inequality(S('0'), Less, m, LessEqual, S('1'))
assert Inequality(S('0'), Less, S('1'))
assert Inequality(S('0'), Less, S('1'), LessEqual, S('5'))
def test_SplitProduct():
assert SplitProduct(OddQ, S(3)*x) == [3, x]
assert not SplitProduct(OddQ, S(2)*x)
def test_SplitSum():
assert SplitSum(FracPart, sin(x)) == [sin(x), 0]
assert SplitSum(FracPart, sin(x) + S(2)) == [sin(x), S(2)]
def test_Complex():
assert Complex(a, b) == a + I*b
def test_SimpFixFactor():
assert SimpFixFactor((a*c + b*c)**S(4), x) == (a*c + b*c)**4
assert SimpFixFactor((a*Complex(0, c) + b*Complex(0, d))**S(3), x) == -I*(a*c + b*d)**3
assert SimpFixFactor((a*Complex(0, d) + b*Complex(0, e) + c*Complex(0, f))**S(2), x) == -(a*d + b*e + c*f)**2
assert SimpFixFactor((a + b*x**(-1/S(2))*x**S(3))**S(3), x) == (a + b*x**(5/2))**3
assert SimpFixFactor((a*c + b*c**S(2)*x**S(2))**S(3), x) == c**3*(a + b*c*x**2)**3
assert SimpFixFactor((a*c**S(2) + b*c**S(1)*x**S(2))**S(3), x) == c**3*(a*c + b*x**2)**3
assert SimpFixFactor(a*cos(x)**2 + a*sin(x)**2 + v, x) == a*cos(x)**2 + a*sin(x)**2 + v
def test_SimplifyAntiderivative():
assert SimplifyAntiderivative(acoth(coth(x)), x) == x
assert SimplifyAntiderivative(a*x, x) == a*x
assert SimplifyAntiderivative(atanh(cot(x)), x) == atanh(2*sin(x)*cos(x))/2
assert SimplifyAntiderivative(a*cos(x)**2 + a*sin(x)**2 + v, x) == a*cos(x)**2 + a*sin(x)**2
def test_FixSimplify():
assert FixSimplify(x*Complex(0, a)*(v*Complex(0, b) + w)**S(3)) == a*x*(b*v - I*w)**3
def test_TrigSimplifyAux():
assert TrigSimplifyAux(a*cos(x)**2 + a*sin(x)**2 + v) == a + v
assert TrigSimplifyAux(x**2) == x**2
def test_SubstFor():
assert SubstFor(x**2 + 1, tanh(x), x) == tanh(x)
assert SubstFor(x**2, sinh(x), x) == sinh(sqrt(x))
def test_FresnelS():
assert FresnelS(oo) == 1/2
assert FresnelS(0) == 0
def test_FresnelC():
assert FresnelC(0) == 0
assert FresnelC(oo) == 1/2
def test_Erfc():
assert Erfc(0) == 1
assert Erfc(oo) == 0
def test_Erfi():
assert Erfi(oo) is oo
assert Erfi(0) == 0
def test_Gamma():
assert Gamma(u) == gamma(u)
def test_ElementaryFunctionQ():
assert ElementaryFunctionQ(x + y)
assert ElementaryFunctionQ(sin(x + y))
assert ElementaryFunctionQ(E**(x*a))
def test_Util_Part():
from sympy.integrals.rubi.utility_function import Util_Part
assert Util_Part(1, a + b).doit() == a
assert Util_Part(c, a + b).doit() == Util_Part(c, a + b)
def test_Part():
assert Part([1, 2, 3], 1) == 1
assert Part(a*b, 1) == a
def test_PolyLog():
assert PolyLog(a, b) == polylog(a, b)
def test_PureFunctionOfCothQ():
v = log(x)
assert PureFunctionOfCothQ(coth(v), v, x)
assert PureFunctionOfCothQ(a + coth(v), v, x)
assert not PureFunctionOfCothQ(sin(v), v, x)
def test_ExpandIntegrand():
assert ExpandIntegrand(sqrt(a + b*x**S(2) + c*x**S(4)), (f*x)**(S(3)/2)*(d + e*x**S(2)), x) == \
d*(f*x)**(3/2)*sqrt(a + b*x**2 + c*x**4) + e*(f*x)**(7/2)*sqrt(a + b*x**2 + c*x**4)/f**2
assert ExpandIntegrand((6*A*a*c - 2*A*b**2 + B*a*b - 2*c*x*(A*b - 2*B*a))/(x**2*(a + b*x + c*x**2)), x) == \
(6*A*a*c - 2*A*b**2 + B*a*b)/(a*x**2) + (-6*A*a**2*c**2 + 10*A*a*b**2*c - 2*A*b**4 - 5*B*a**2*b*c + B*a*b**3 + x*(8*A*a*b*c**2 - 2*A*b**3*c - 4*B*a**2*c**2 + B*a*b**2*c))/(a**2*(a + b*x + c*x**2)) + (-2*A*b + B*a)*(4*a*c - b**2)/(a**2*x)
assert ExpandIntegrand(x**2*(e + f*x)**3*F**(a + b*(c + d*x)**1), x) == F**(a + b*(c + d*x))*e**2*(e + f*x)**3/f**2 - 2*F**(a + b*(c + d*x))*e*(e + f*x)**4/f**2 + F**(a + b*(c + d*x))*(e + f*x)**5/f**2
assert ExpandIntegrand((x)*(a + b*x)**2*f**(e*(c + d*x)**n), x) == a**2*f**(e*(c + d*x)**n)*x + 2*a*b*f**(e*(c + d*x)**n)*x**2 + b**2*f**(e*(c + d*x)**n)*x**3
assert ExpandIntegrand(sin(x)**3*(a + b*(1/sin(x)))**2, x) == a**2*sin(x)**3 + 2*a*b*sin(x)**2 + b**2*sin(x)
assert ExpandIntegrand(x*(a + b*ArcSin(c + d*x))**n, x) == -c*(a + b*asin(c + d*x))**n/d + (a + b*asin(c + d*x))**n*(c + d*x)/d
assert ExpandIntegrand((a + b*x)**S(3)*(A + B*x)/(c + d*x), x) == B*(a + b*x)**3/d + b*(a + b*x)**2*(A*d - B*c)/d**2 + b*(a + b*x)*(A*d - B*c)*(a*d - b*c)/d**3 + b*(A*d - B*c)*(a*d - b*c)**2/d**4 + (A*d - B*c)*(a*d - b*c)**3/(d**4*(c + d*x))
assert ExpandIntegrand((x**2)*(S(3)*x)**(S(1)/2), x) ==sqrt(3)*x**(5/2)
assert ExpandIntegrand((x)*(sin(x))**(S(1)/2), x) == x*sqrt(sin(x))
assert ExpandIntegrand(x*(e + f*x)**2*F**(b*(c + d*x)), x) == -F**(b*(c + d*x))*e*(e + f*x)**2/f + F**(b*(c + d*x))*(e + f*x)**3/f
assert ExpandIntegrand(x**m*(e + f*x)**2*F**(b*(c + d*x)**n), x) == F**(b*(c + d*x)**n)*e**2*x**m + 2*F**(b*(c + d*x)**n)*e*f*x*x**m + F**(b*(c + d*x)**n)*f**2*x**2*x**m
assert simplify(ExpandIntegrand((S(1) - S(1)*x**S(2))**(-S(3)), x) - (-S(3)/(8*(x**2 - 1)) + S(3)/(16*(x + 1)**2) + S(1)/(S(8)*(x + 1)**3) + S(3)/(S(16)*(x - 1)**2) - S(1)/(S(8)*(x - 1)**3))) == 0
assert ExpandIntegrand(-S(1), 1/((-q - x)**3*(q - x)**3), x) == 1/(8*q**3*(q + x)**3) - 1/(8*q**3*(-q + x)**3) - 3/(8*q**4*(-q**2 + x**2)) + 3/(16*q**4*(q + x)**2) + 3/(16*q**4*(-q + x)**2)
assert ExpandIntegrand((1 + 1*x)**(3)/(2 + 1*x), x) == x**2 + x + 1 - 1/(x + 2)
assert ExpandIntegrand((c + d*x**1 + e*x**2)/(1 - x**3), x) == (c - (-1)**(S(1)/3)*d + (-1)**(S(2)/3)*e)/(-3*(-1)**(S(2)/3)*x + 3) + (c + (-1)**(S(2)/3)*d - (-1)**(S(1)/3)*e)/(3*(-1)**(S(1)/3)*x + 3) + (c + d + e)/(-3*x + 3)
assert ExpandIntegrand((c + d*x**1 + e*x**2 + f*x**3)/(1 - x**4), x) == (c + I*d - e - I*f)/(4*I*x + 4) + (c - I*d - e + I*f)/(-4*I*x + 4) + (c - d + e - f)/(4*x + 4) + (c + d + e + f)/(-4*x + 4)
assert ExpandIntegrand((d + e*(f + g*x))/(2 + 3*x + 1*x**2), x) == (-2*d - 2*e*f + 4*e*g)/(2*x + 4) + (2*d + 2*e*f - 2*e*g)/(2*x + 2)
assert ExpandIntegrand(x/(a*x**3 + b*Sqrt(c + d*x**6)), x) == a*x**4/(-b**2*c + x**6*(a**2 - b**2*d)) + b*x*sqrt(c + d*x**6)/(b**2*c + x**6*(-a**2 + b**2*d))
assert simplify(ExpandIntegrand(x**1*(1 - x**4)**(-2), x) - (x/(S(4)*(x**2 + 1)) + x/(S(4)*(x**2 + 1)**2) - x/(S(4)*(x**2 - 1)) + x/(S(4)*(x**2 - 1)**2))) == 0
assert simplify(ExpandIntegrand((-1 + x**S(6))**(-3), x) - (S(3)/(S(8)*(x**6 - 1)) - S(3)/(S(16)*(x**S(3) + S(1))**S(2)) - S(1)/(S(8)*(x**S(3) + S(1))**S(3)) - S(3)/(S(16)*(x**S(3) - S(1))**S(2)) + S(1)/(S(8)*(x**S(3) - S(1))**S(3)))) == 0
assert simplify(ExpandIntegrand(u**1*(a + b*u**2 + c*u**4)**(-1), x)) == simplify(1/(2*b*(u + sqrt(-(a + c*u**4)/b))) - 1/(2*b*(-u + sqrt(-(a + c*u**4)/b))))
assert simplify(ExpandIntegrand((1 + 1*u + 1*u**2)**(-2), x) - (S(1)/(S(2)*(-u - 1)*(-u**2 - u - 1)) + S(1)/(S(4)*(-u - 1)*(u + sqrt(-u - 1))**2) + S(1)/(S(4)*(-u - 1)*(u - sqrt(-u - 1))**2))) == 0
assert ExpandIntegrand(x*(a + b*Log(c*(d*(e + f*x)**p)**q))**n, x) == -e*(a + b*log(c*(d*(e + f*x)**p)**q))**n/f + (a + b*log(c*(d*(e + f*x)**p)**q))**n*(e + f*x)/f
assert ExpandIntegrand(x*f**(e*(c + d*x)*S(1)), x) == f**(e*(c + d*x))*x
assert simplify(ExpandIntegrand((x)*(a + b*x)**m*Log(c*(d + e*x**n)**p), x) - (-a*(a + b*x)**m*log(c*(d + e*x**n)**p)/b + (a + b*x)**(m + S(1))*log(c*(d + e*x**n)**p)/b)) == 0
assert simplify(ExpandIntegrand(u*(a + b*F**v)**S(2)*(c + d*F**v)**S(-3), x) - (b**2*u/(d**2*(F**v*d + c)) + 2*b*u*(a*d - b*c)/(d**2*(F**v*d + c)**2) + u*(a*d - b*c)**2/(d**2*(F**v*d + c)**3))) == 0
assert ExpandIntegrand((S(1) + 1*x)**S(2)*f**(e*(1 + S(1)*x)**n)/(g + h*x), x) == f**(e*(x + 1)**n)*(x + 1)/h + f**(e*(x + 1)**n)*(-g + h)/h**2 + f**(e*(x + 1)**n)*(g - h)**2/(h**2*(g + h*x))
assert ExpandIntegrand((a*c - b*c*x)**2/(a + b*x)**2, x) == 4*a**2*c**2/(a + b*x)**2 - 4*a*c**2/(a + b*x) + c**2
assert simplify(ExpandIntegrand(x**2*(1 - 1*x**2)**(-2), x) - (1/(S(2)*(x**2 - 1)) + 1/(S(4)*(x + 1)**2) + 1/(S(4)*(x - 1)**2))) == 0
assert ExpandIntegrand((a + x)**2, x) == a**2 + 2*a*x + x**2
assert ExpandIntegrand((a + b*x)**S(2)/x**3, x) == a**2/x**3 + 2*a*b/x**2 + b**2/x
assert ExpandIntegrand(1/(x**2*(a + b*x)**2), x) == b**2/(a**2*(a + b*x)**2) + 1/(a**2*x**2) + 2*b**2/(a**3*(a + b*x)) - 2*b/(a**3*x)
assert ExpandIntegrand((1 + x)**3/x, x) == x**2 + 3*x + 3 + 1/x
assert ExpandIntegrand((1 + 2*(3 + 4*x**2))/(2 + 3*x**2 + 1*x**4), x) == 18/(2*x**2 + 4) - 2/(2*x**2 + 2)
assert ExpandIntegrand((c + d*x**2 + e*x**3)/(1 - 1*x**4), x) == (c - d - I*e)/(4*I*x + 4) + (c - d + I*e)/(-4*I*x + 4) + (c + d - e)/(4*x + 4) + (c + d + e)/(-4*x + 4)
assert ExpandIntegrand((a + b*x)**2/(c + d*x), x) == b*(a + b*x)/d + b*(a*d - b*c)/d**2 + (a*d - b*c)**2/(d**2*(c + d*x))
assert ExpandIntegrand(x**2*(a + b*Log(c*(d*(e + f*x)**p)**q))**n, x) == e**2*(a + b*log(c*(d*(e + f*x)**p)**q))**n/f**2 - 2*e*(a + b*log(c*(d*(e + f*x)**p)**q))**n*(e + f*x)/f**2 + (a + b*log(c*(d*(e + f*x)**p)**q))**n*(e + f*x)**2/f**2
assert ExpandIntegrand(x*(1 + 2*x)**3*log(2*(1 + 1*x**2)**1), x) == 8*x**4*log(2*x**2 + 2) + 12*x**3*log(2*x**2 + 2) + 6*x**2*log(2*x**2 + 2) + x*log(2*x**2 + 2)
assert ExpandIntegrand((1 + 1*x)**S(3)*f**(e*(1 + 1*x)**n)/(g + h*x), x) == f**(e*(x + 1)**n)*(x + 1)**2/h + f**(e*(x + 1)**n)*(-g + h)*(x + 1)/h**2 + f**(e*(x + 1)**n)*(-g + h)**2/h**3 - f**(e*(x + 1)**n)*(g - h)**3/(h**3*(g + h*x))
def test_Dist():
assert Dist(x, a + b, x) == a*x + b*x
assert Dist(x, Integral(a + b , x), x) == x*Integral(a + b, x)
assert Dist(3*x,(a+b), x) - Dist(2*x, (a+b), x) == a*x + b*x
assert Dist(3*x,(a+b), x) + Dist(2*x, (a+b), x) == 5*a*x + 5*b*x
assert Dist(x, c*Integral((a + b), x), x) == c*x*Integral(a + b, x)
def test_IntegralFreeQ():
assert not IntegralFreeQ(Integral(a, x))
assert IntegralFreeQ(a + b)
def test_OneQ():
from sympy.integrals.rubi.utility_function import OneQ
assert OneQ(S(1))
assert not OneQ(S(2))
def test_DerivativeDivides():
assert not DerivativeDivides(x, x, x)
assert not DerivativeDivides(a, x + y, b)
assert DerivativeDivides(a + x, a, x) == a
assert DerivativeDivides(a + b, x + y, b) == x + y
def test_LogIntegral():
from sympy.integrals.rubi.utility_function import LogIntegral
assert LogIntegral(a) == li(a)
def test_SinIntegral():
from sympy.integrals.rubi.utility_function import SinIntegral
assert SinIntegral(a) == Si(a)
def test_CosIntegral():
from sympy.integrals.rubi.utility_function import CosIntegral
assert CosIntegral(a) == Ci(a)
def test_SinhIntegral():
from sympy.integrals.rubi.utility_function import SinhIntegral
assert SinhIntegral(a) == Shi(a)
def test_CoshIntegral():
from sympy.integrals.rubi.utility_function import CoshIntegral
assert CoshIntegral(a) == Chi(a)
def test_ExpIntegralEi():
from sympy.integrals.rubi.utility_function import ExpIntegralEi
assert ExpIntegralEi(a) == Ei(a)
def test_ExpIntegralE():
from sympy.integrals.rubi.utility_function import ExpIntegralE
assert ExpIntegralE(a, z) == expint(a, z)
def test_LogGamma():
from sympy.integrals.rubi.utility_function import LogGamma
assert LogGamma(a) == loggamma(a)
def test_Factorial():
from sympy.integrals.rubi.utility_function import Factorial
assert Factorial(S(5)) == 120
def test_Zeta():
from sympy.integrals.rubi.utility_function import Zeta
assert Zeta(a, z) == zeta(a, z)
def test_HypergeometricPFQ():
from sympy.integrals.rubi.utility_function import HypergeometricPFQ
assert HypergeometricPFQ([a, b], [c], z) == hyper([a, b], [c], z)
def test_PolyGamma():
assert PolyGamma(S(2), S(3)) == polygamma(2, 3)
def test_ProductLog():
from sympy import N
assert N(ProductLog(S(5.0)), 5) == N(1.32672466524220, 5)
assert N(ProductLog(S(2), S(3.5)), 5) == N(-1.14064876353898 + 10.8912237027092*I, 5)
def test_PolynomialQuotient():
assert PolynomialQuotient(log((-a*d + b*c)/(b*(c + d*x)))/(c + d*x), a + b*x, e) == log((-a*d + b*c)/(b*(c + d*x)))/((a + b*x)*(c + d*x))
assert PolynomialQuotient(x**2, x + a, x) == -a + x
def test_PolynomialRemainder():
assert PolynomialRemainder(log((-a*d + b*c)/(b*(c + d*x)))/(c + d*x), a + b*x, e) == 0
assert PolynomialRemainder(x**2, x + a, x) == a**2
def test_Floor():
assert Floor(S(7.5)) == 7
assert Floor(S(15.5), S(6)) == 12
def test_Factor():
from sympy.integrals.rubi.utility_function import Factor
assert Factor(a*b + a*c) == a*(b + c)
def test_Rule():
from sympy.integrals.rubi.utility_function import Rule
assert Rule(x, S(5)) == {x: 5}
def test_Distribute():
assert Distribute((a + b)*c + (a + b)*d, Add) == c*(a + b) + d*(a + b)
assert Distribute((a + b)*(c + e), Add) == a*c + a*e + b*c + b*e
def test_CoprimeQ():
assert CoprimeQ(S(7), S(5))
assert not CoprimeQ(S(6), S(3))
def test_Discriminant():
from sympy.integrals.rubi.utility_function import Discriminant
assert Discriminant(a*x**2 + b*x + c, x) == b**2 - 4*a*c
assert unchanged(Discriminant, 1/x, x)
def test_Sum_doit():
assert Sum_doit(2*x + 2, [x, 0, 1.7]) == 6
def test_DeactivateTrig():
assert DeactivateTrig(sec(a + b*x), x) == sec(a + b*x)
def test_Negative():
from sympy.integrals.rubi.utility_function import Negative
assert Negative(S(-2))
assert not Negative(S(0))
def test_Quotient():
from sympy.integrals.rubi.utility_function import Quotient
assert Quotient(17, 5) == 3
def test_process_trig():
assert process_trig(x*cot(x)) == x/tan(x)
assert process_trig(coth(x)*csc(x)) == S(1)/(tanh(x)*sin(x))
def test_replace_pow_exp():
assert replace_pow_exp(rubi_exp(S(5))) == exp(S(5))
def test_rubi_unevaluated_expr():
from sympy.integrals.rubi.utility_function import rubi_unevaluated_expr
assert rubi_unevaluated_expr(a)*rubi_unevaluated_expr(b) == rubi_unevaluated_expr(b)*rubi_unevaluated_expr(a)
def test_rubi_exp():
# class name in utility_function is `exp`. To avoid confusion `rubi_exp` has been used here
assert isinstance(rubi_exp(a), Pow)
def test_rubi_log():
# class name in utility_function is `log`. To avoid confusion `rubi_log` has been used here
assert rubi_log(rubi_exp(S(a))) == a
|
cf0d2e581f23ca0f3c019991e8b6ed9c080d524d11206712b9d0893a8d8ecc19 | from sympy import (
Symbol, Wild, sin, cos, exp, sqrt, pi, Function, Derivative,
Integer, Eq, symbols, Add, I, Float, log, Rational,
Lambda, atan2, cse, cot, tan, S, Tuple, Basic, Dict,
Piecewise, oo, Mul, factor, nsimplify, zoo, Subs, RootOf,
AccumBounds, Matrix, zeros, ZeroMatrix)
from sympy.core.basic import _aresame
from sympy.utilities.pytest import XFAIL, raises
from sympy.abc import a, x, y, z
def test_subs():
n3 = Rational(3)
e = x
e = e.subs(x, n3)
assert e == Rational(3)
e = 2*x
assert e == 2*x
e = e.subs(x, n3)
assert e == Rational(6)
def test_subs_Matrix():
z = zeros(2)
z1 = ZeroMatrix(2, 2)
assert (x*y).subs({x:z, y:0}) in [z, z1]
assert (x*y).subs({y:z, x:0}) == 0
assert (x*y).subs({y:z, x:0}, simultaneous=True) in [z, z1]
assert (x + y).subs({x: z, y: z}, simultaneous=True) in [z, z1]
assert (x + y).subs({x: z, y: z}) in [z, z1]
# Issue #15528
assert Mul(Matrix([[3]]), x).subs(x, 2.0) == Matrix([[6.0]])
# Does not raise a TypeError, see comment on the MatAdd postprocessor
assert Add(Matrix([[3]]), x).subs(x, 2.0) == Add(Matrix([[3]]), 2.0)
def test_subs_AccumBounds():
e = x
e = e.subs(x, AccumBounds(1, 3))
assert e == AccumBounds(1, 3)
e = 2*x
e = e.subs(x, AccumBounds(1, 3))
assert e == AccumBounds(2, 6)
e = x + x**2
e = e.subs(x, AccumBounds(-1, 1))
assert e == AccumBounds(-1, 2)
def test_trigonometric():
n3 = Rational(3)
e = (sin(x)**2).diff(x)
assert e == 2*sin(x)*cos(x)
e = e.subs(x, n3)
assert e == 2*cos(n3)*sin(n3)
e = (sin(x)**2).diff(x)
assert e == 2*sin(x)*cos(x)
e = e.subs(sin(x), cos(x))
assert e == 2*cos(x)**2
assert exp(pi).subs(exp, sin) == 0
assert cos(exp(pi)).subs(exp, sin) == 1
i = Symbol('i', integer=True)
zoo = S.ComplexInfinity
assert tan(x).subs(x, pi/2) is zoo
assert cot(x).subs(x, pi) is zoo
assert cot(i*x).subs(x, pi) is zoo
assert tan(i*x).subs(x, pi/2) == tan(i*pi/2)
assert tan(i*x).subs(x, pi/2).subs(i, 1) is zoo
o = Symbol('o', odd=True)
assert tan(o*x).subs(x, pi/2) == tan(o*pi/2)
def test_powers():
assert sqrt(1 - sqrt(x)).subs(x, 4) == I
assert (sqrt(1 - x**2)**3).subs(x, 2) == - 3*I*sqrt(3)
assert (x**Rational(1, 3)).subs(x, 27) == 3
assert (x**Rational(1, 3)).subs(x, -27) == 3*(-1)**Rational(1, 3)
assert ((-x)**Rational(1, 3)).subs(x, 27) == 3*(-1)**Rational(1, 3)
n = Symbol('n', negative=True)
assert (x**n).subs(x, 0) is S.ComplexInfinity
assert exp(-1).subs(S.Exp1, 0) is S.ComplexInfinity
assert (x**(4.0*y)).subs(x**(2.0*y), n) == n**2.0
assert (2**(x + 2)).subs(2, 3) == 3**(x + 3)
def test_logexppow(): # no eval()
x = Symbol('x', real=True)
w = Symbol('w')
e = (3**(1 + x) + 2**(1 + x))/(3**x + 2**x)
assert e.subs(2**x, w) != e
assert e.subs(exp(x*log(Rational(2))), w) != e
def test_bug():
x1 = Symbol('x1')
x2 = Symbol('x2')
y = x1*x2
assert y.subs(x1, Float(3.0)) == Float(3.0)*x2
def test_subbug1():
# see that they don't fail
(x**x).subs(x, 1)
(x**x).subs(x, 1.0)
def test_subbug2():
# Ensure this does not cause infinite recursion
assert Float(7.7).epsilon_eq(abs(x).subs(x, -7.7))
def test_dict_set():
a, b, c = map(Wild, 'abc')
f = 3*cos(4*x)
r = f.match(a*cos(b*x))
assert r == {a: 3, b: 4}
e = a/b*sin(b*x)
assert e.subs(r) == r[a]/r[b]*sin(r[b]*x)
assert e.subs(r) == 3*sin(4*x) / 4
s = set(r.items())
assert e.subs(s) == r[a]/r[b]*sin(r[b]*x)
assert e.subs(s) == 3*sin(4*x) / 4
assert e.subs(r) == r[a]/r[b]*sin(r[b]*x)
assert e.subs(r) == 3*sin(4*x) / 4
assert x.subs(Dict((x, 1))) == 1
def test_dict_ambigous(): # see issue 3566
f = x*exp(x)
g = z*exp(z)
df = {x: y, exp(x): y}
dg = {z: y, exp(z): y}
assert f.subs(df) == y**2
assert g.subs(dg) == y**2
# and this is how order can affect the result
assert f.subs(x, y).subs(exp(x), y) == y*exp(y)
assert f.subs(exp(x), y).subs(x, y) == y**2
# length of args and count_ops are the same so
# default_sort_key resolves ordering...if one
# doesn't want this result then an unordered
# sequence should not be used.
e = 1 + x*y
assert e.subs({x: y, y: 2}) == 5
# here, there are no obviously clashing keys or values
# but the results depend on the order
assert exp(x/2 + y).subs({exp(y + 1): 2, x: 2}) == exp(y + 1)
def test_deriv_sub_bug3():
f = Function('f')
pat = Derivative(f(x), x, x)
assert pat.subs(y, y**2) == Derivative(f(x), x, x)
assert pat.subs(y, y**2) != Derivative(f(x), x)
def test_equality_subs1():
f = Function('f')
eq = Eq(f(x)**2, x)
res = Eq(Integer(16), x)
assert eq.subs(f(x), 4) == res
def test_equality_subs2():
f = Function('f')
eq = Eq(f(x)**2, 16)
assert bool(eq.subs(f(x), 3)) is False
assert bool(eq.subs(f(x), 4)) is True
def test_issue_3742():
e = sqrt(x)*exp(y)
assert e.subs(sqrt(x), 1) == exp(y)
def test_subs_dict1():
assert (1 + x*y).subs(x, pi) == 1 + pi*y
assert (1 + x*y).subs({x: pi, y: 2}) == 1 + 2*pi
c2, c3, q1p, q2p, c1, s1, s2, s3 = symbols('c2 c3 q1p q2p c1 s1 s2 s3')
test = (c2**2*q2p*c3 + c1**2*s2**2*q2p*c3 + s1**2*s2**2*q2p*c3
- c1**2*q1p*c2*s3 - s1**2*q1p*c2*s3)
assert (test.subs({c1**2: 1 - s1**2, c2**2: 1 - s2**2, c3**3: 1 - s3**2})
== c3*q2p*(1 - s2**2) + c3*q2p*s2**2*(1 - s1**2)
- c2*q1p*s3*(1 - s1**2) + c3*q2p*s1**2*s2**2 - c2*q1p*s3*s1**2)
def test_mul():
x, y, z, a, b, c = symbols('x y z a b c')
A, B, C = symbols('A B C', commutative=0)
assert (x*y*z).subs(z*x, y) == y**2
assert (z*x).subs(1/x, z) == 1
assert (x*y/z).subs(1/z, a) == a*x*y
assert (x*y/z).subs(x/z, a) == a*y
assert (x*y/z).subs(y/z, a) == a*x
assert (x*y/z).subs(x/z, 1/a) == y/a
assert (x*y/z).subs(x, 1/a) == y/(z*a)
assert (2*x*y).subs(5*x*y, z) != z*Rational(2, 5)
assert (x*y*A).subs(x*y, a) == a*A
assert (x**2*y**(x*Rational(3, 2))).subs(x*y**(x/2), 2) == 4*y**(x/2)
assert (x*exp(x*2)).subs(x*exp(x), 2) == 2*exp(x)
assert ((x**(2*y))**3).subs(x**y, 2) == 64
assert (x*A*B).subs(x*A, y) == y*B
assert (x*y*(1 + x)*(1 + x*y)).subs(x*y, 2) == 6*(1 + x)
assert ((1 + A*B)*A*B).subs(A*B, x*A*B)
assert (x*a/z).subs(x/z, A) == a*A
assert (x**3*A).subs(x**2*A, a) == a*x
assert (x**2*A*B).subs(x**2*B, a) == a*A
assert (x**2*A*B).subs(x**2*A, a) == a*B
assert (b*A**3/(a**3*c**3)).subs(a**4*c**3*A**3/b**4, z) == \
b*A**3/(a**3*c**3)
assert (6*x).subs(2*x, y) == 3*y
assert (y*exp(x*Rational(3, 2))).subs(y*exp(x), 2) == 2*exp(x/2)
assert (y*exp(x*Rational(3, 2))).subs(y*exp(x), 2) == 2*exp(x/2)
assert (A**2*B*A**2*B*A**2).subs(A*B*A, C) == A*C**2*A
assert (x*A**3).subs(x*A, y) == y*A**2
assert (x**2*A**3).subs(x*A, y) == y**2*A
assert (x*A**3).subs(x*A, B) == B*A**2
assert (x*A*B*A*exp(x*A*B)).subs(x*A, B) == B**2*A*exp(B*B)
assert (x**2*A*B*A*exp(x*A*B)).subs(x*A, B) == B**3*exp(B**2)
assert (x**3*A*exp(x*A*B)*A*exp(x*A*B)).subs(x*A, B) == \
x*B*exp(B**2)*B*exp(B**2)
assert (x*A*B*C*A*B).subs(x*A*B, C) == C**2*A*B
assert (-I*a*b).subs(a*b, 2) == -2*I
# issue 6361
assert (-8*I*a).subs(-2*a, 1) == 4*I
assert (-I*a).subs(-a, 1) == I
# issue 6441
assert (4*x**2).subs(2*x, y) == y**2
assert (2*4*x**2).subs(2*x, y) == 2*y**2
assert (-x**3/9).subs(-x/3, z) == -z**2*x
assert (-x**3/9).subs(x/3, z) == -z**2*x
assert (-2*x**3/9).subs(x/3, z) == -2*x*z**2
assert (-2*x**3/9).subs(-x/3, z) == -2*x*z**2
assert (-2*x**3/9).subs(-2*x, z) == z*x**2/9
assert (-2*x**3/9).subs(2*x, z) == -z*x**2/9
assert (2*(3*x/5/7)**2).subs(3*x/5, z) == 2*(Rational(1, 7))**2*z**2
assert (4*x).subs(-2*x, z) == 4*x # try keep subs literal
def test_subs_simple():
a = symbols('a', commutative=True)
x = symbols('x', commutative=False)
assert (2*a).subs(1, 3) == 2*a
assert (2*a).subs(2, 3) == 3*a
assert (2*a).subs(a, 3) == 6
assert sin(2).subs(1, 3) == sin(2)
assert sin(2).subs(2, 3) == sin(3)
assert sin(a).subs(a, 3) == sin(3)
assert (2*x).subs(1, 3) == 2*x
assert (2*x).subs(2, 3) == 3*x
assert (2*x).subs(x, 3) == 6
assert sin(x).subs(x, 3) == sin(3)
def test_subs_constants():
a, b = symbols('a b', commutative=True)
x, y = symbols('x y', commutative=False)
assert (a*b).subs(2*a, 1) == a*b
assert (1.5*a*b).subs(a, 1) == 1.5*b
assert (2*a*b).subs(2*a, 1) == b
assert (2*a*b).subs(4*a, 1) == 2*a*b
assert (x*y).subs(2*x, 1) == x*y
assert (1.5*x*y).subs(x, 1) == 1.5*y
assert (2*x*y).subs(2*x, 1) == y
assert (2*x*y).subs(4*x, 1) == 2*x*y
def test_subs_commutative():
a, b, c, d, K = symbols('a b c d K', commutative=True)
assert (a*b).subs(a*b, K) == K
assert (a*b*a*b).subs(a*b, K) == K**2
assert (a*a*b*b).subs(a*b, K) == K**2
assert (a*b*c*d).subs(a*b*c, K) == d*K
assert (a*b**c).subs(a, K) == K*b**c
assert (a*b**c).subs(b, K) == a*K**c
assert (a*b**c).subs(c, K) == a*b**K
assert (a*b*c*b*a).subs(a*b, K) == c*K**2
assert (a**3*b**2*a).subs(a*b, K) == a**2*K**2
def test_subs_noncommutative():
w, x, y, z, L = symbols('w x y z L', commutative=False)
alpha = symbols('alpha', commutative=True)
someint = symbols('someint', commutative=True, integer=True)
assert (x*y).subs(x*y, L) == L
assert (w*y*x).subs(x*y, L) == w*y*x
assert (w*x*y*z).subs(x*y, L) == w*L*z
assert (x*y*x*y).subs(x*y, L) == L**2
assert (x*x*y).subs(x*y, L) == x*L
assert (x*x*y*y).subs(x*y, L) == x*L*y
assert (w*x*y).subs(x*y*z, L) == w*x*y
assert (x*y**z).subs(x, L) == L*y**z
assert (x*y**z).subs(y, L) == x*L**z
assert (x*y**z).subs(z, L) == x*y**L
assert (w*x*y*z*x*y).subs(x*y*z, L) == w*L*x*y
assert (w*x*y*y*w*x*x*y*x*y*y*x*y).subs(x*y, L) == w*L*y*w*x*L**2*y*L
# Check fractional power substitutions. It should not do
# substitutions that choose a value for noncommutative log,
# or inverses that don't already appear in the expressions.
assert (x*x*x).subs(x*x, L) == L*x
assert (x*x*x*y*x*x*x*x).subs(x*x, L) == L*x*y*L**2
for p in range(1, 5):
for k in range(10):
assert (y * x**k).subs(x**p, L) == y * L**(k//p) * x**(k % p)
assert (x**Rational(3, 2)).subs(x**S.Half, L) == x**Rational(3, 2)
assert (x**S.Half).subs(x**S.Half, L) == L
assert (x**Rational(-1, 2)).subs(x**S.Half, L) == x**Rational(-1, 2)
assert (x**Rational(-1, 2)).subs(x**Rational(-1, 2), L) == L
assert (x**(2*someint)).subs(x**someint, L) == L**2
assert (x**(2*someint + 3)).subs(x**someint, L) == L**2*x**3
assert (x**(3*someint + 3)).subs(x**someint, L) == L**3*x**3
assert (x**(3*someint)).subs(x**(2*someint), L) == L * x**someint
assert (x**(4*someint)).subs(x**(2*someint), L) == L**2
assert (x**(4*someint + 1)).subs(x**(2*someint), L) == L**2 * x
assert (x**(4*someint)).subs(x**(3*someint), L) == L * x**someint
assert (x**(4*someint + 1)).subs(x**(3*someint), L) == L * x**(someint + 1)
assert (x**(2*alpha)).subs(x**alpha, L) == x**(2*alpha)
assert (x**(2*alpha + 2)).subs(x**2, L) == x**(2*alpha + 2)
assert ((2*z)**alpha).subs(z**alpha, y) == (2*z)**alpha
assert (x**(2*someint*alpha)).subs(x**someint, L) == x**(2*someint*alpha)
assert (x**(2*someint + alpha)).subs(x**someint, L) == x**(2*someint + alpha)
# This could in principle be substituted, but is not currently
# because it requires recognizing that someint**2 is divisible by
# someint.
assert (x**(someint**2 + 3)).subs(x**someint, L) == x**(someint**2 + 3)
# alpha**z := exp(log(alpha) z) is usually well-defined
assert (4**z).subs(2**z, y) == y**2
# Negative powers
assert (x**(-1)).subs(x**3, L) == x**(-1)
assert (x**(-2)).subs(x**3, L) == x**(-2)
assert (x**(-3)).subs(x**3, L) == L**(-1)
assert (x**(-4)).subs(x**3, L) == L**(-1) * x**(-1)
assert (x**(-5)).subs(x**3, L) == L**(-1) * x**(-2)
assert (x**(-1)).subs(x**(-3), L) == x**(-1)
assert (x**(-2)).subs(x**(-3), L) == x**(-2)
assert (x**(-3)).subs(x**(-3), L) == L
assert (x**(-4)).subs(x**(-3), L) == L * x**(-1)
assert (x**(-5)).subs(x**(-3), L) == L * x**(-2)
assert (x**1).subs(x**(-3), L) == x
assert (x**2).subs(x**(-3), L) == x**2
assert (x**3).subs(x**(-3), L) == L**(-1)
assert (x**4).subs(x**(-3), L) == L**(-1) * x
assert (x**5).subs(x**(-3), L) == L**(-1) * x**2
def test_subs_basic_funcs():
a, b, c, d, K = symbols('a b c d K', commutative=True)
w, x, y, z, L = symbols('w x y z L', commutative=False)
assert (x + y).subs(x + y, L) == L
assert (x - y).subs(x - y, L) == L
assert (x/y).subs(x, L) == L/y
assert (x**y).subs(x, L) == L**y
assert (x**y).subs(y, L) == x**L
assert ((a - c)/b).subs(b, K) == (a - c)/K
assert (exp(x*y - z)).subs(x*y, L) == exp(L - z)
assert (a*exp(x*y - w*z) + b*exp(x*y + w*z)).subs(z, 0) == \
a*exp(x*y) + b*exp(x*y)
assert ((a - b)/(c*d - a*b)).subs(c*d - a*b, K) == (a - b)/K
assert (w*exp(a*b - c)*x*y/4).subs(x*y, L) == w*exp(a*b - c)*L/4
def test_subs_wild():
R, S, T, U = symbols('R S T U', cls=Wild)
assert (R*S).subs(R*S, T) == T
assert (S*R).subs(R*S, T) == T
assert (R + S).subs(R + S, T) == T
assert (R**S).subs(R, T) == T**S
assert (R**S).subs(S, T) == R**T
assert (R*S**T).subs(R, U) == U*S**T
assert (R*S**T).subs(S, U) == R*U**T
assert (R*S**T).subs(T, U) == R*S**U
def test_subs_mixed():
a, b, c, d, K = symbols('a b c d K', commutative=True)
w, x, y, z, L = symbols('w x y z L', commutative=False)
R, S, T, U = symbols('R S T U', cls=Wild)
assert (a*x*y).subs(x*y, L) == a*L
assert (a*b*x*y*x).subs(x*y, L) == a*b*L*x
assert (R*x*y*exp(x*y)).subs(x*y, L) == R*L*exp(L)
assert (a*x*y*y*x - x*y*z*exp(a*b)).subs(x*y, L) == a*L*y*x - L*z*exp(a*b)
e = c*y*x*y*x**(R*S - a*b) - T*(a*R*b*S)
assert e.subs(x*y, L).subs(a*b, K).subs(R*S, U) == \
c*y*L*x**(U - K) - T*(U*K)
def test_division():
a, b, c = symbols('a b c', commutative=True)
x, y, z = symbols('x y z', commutative=True)
assert (1/a).subs(a, c) == 1/c
assert (1/a**2).subs(a, c) == 1/c**2
assert (1/a**2).subs(a, -2) == Rational(1, 4)
assert (-(1/a**2)).subs(a, -2) == Rational(-1, 4)
assert (1/x).subs(x, z) == 1/z
assert (1/x**2).subs(x, z) == 1/z**2
assert (1/x**2).subs(x, -2) == Rational(1, 4)
assert (-(1/x**2)).subs(x, -2) == Rational(-1, 4)
#issue 5360
assert (1/x).subs(x, 0) == 1/S.Zero
def test_add():
a, b, c, d, x, y, t = symbols('a b c d x y t')
assert (a**2 - b - c).subs(a**2 - b, d) in [d - c, a**2 - b - c]
assert (a**2 - c).subs(a**2 - c, d) == d
assert (a**2 - b - c).subs(a**2 - c, d) in [d - b, a**2 - b - c]
assert (a**2 - x - c).subs(a**2 - c, d) in [d - x, a**2 - x - c]
assert (a**2 - b - sqrt(a)).subs(a**2 - sqrt(a), c) == c - b
assert (a + b + exp(a + b)).subs(a + b, c) == c + exp(c)
assert (c + b + exp(c + b)).subs(c + b, a) == a + exp(a)
assert (a + b + c + d).subs(b + c, x) == a + d + x
assert (a + b + c + d).subs(-b - c, x) == a + d - x
assert ((x + 1)*y).subs(x + 1, t) == t*y
assert ((-x - 1)*y).subs(x + 1, t) == -t*y
assert ((x - 1)*y).subs(x + 1, t) == y*(t - 2)
assert ((-x + 1)*y).subs(x + 1, t) == y*(-t + 2)
# this should work every time:
e = a**2 - b - c
assert e.subs(Add(*e.args[:2]), d) == d + e.args[2]
assert e.subs(a**2 - c, d) == d - b
# the fallback should recognize when a change has
# been made; while .1 == Rational(1, 10) they are not the same
# and the change should be made
assert (0.1 + a).subs(0.1, Rational(1, 10)) == Rational(1, 10) + a
e = (-x*(-y + 1) - y*(y - 1))
ans = (-x*(x) - y*(-x)).expand()
assert e.subs(-y + 1, x) == ans
def test_subs_issue_4009():
assert (I*Symbol('a')).subs(1, 2) == I*Symbol('a')
def test_functions_subs():
f, g = symbols('f g', cls=Function)
l = Lambda((x, y), sin(x) + y)
assert (g(y, x) + cos(x)).subs(g, l) == sin(y) + x + cos(x)
assert (f(x)**2).subs(f, sin) == sin(x)**2
assert (f(x, y)).subs(f, log) == log(x, y)
assert (f(x, y)).subs(f, sin) == f(x, y)
assert (sin(x) + atan2(x, y)).subs([[atan2, f], [sin, g]]) == \
f(x, y) + g(x)
assert (g(f(x + y, x))).subs([[f, l], [g, exp]]) == exp(x + sin(x + y))
def test_derivative_subs():
f = Function('f')
g = Function('g')
assert Derivative(f(x), x).subs(f(x), y) != 0
# need xreplace to put the function back, see #13803
assert Derivative(f(x), x).subs(f(x), y).xreplace({y: f(x)}) == \
Derivative(f(x), x)
# issues 5085, 5037
assert cse(Derivative(f(x), x) + f(x))[1][0].has(Derivative)
assert cse(Derivative(f(x, y), x) +
Derivative(f(x, y), y))[1][0].has(Derivative)
eq = Derivative(g(x), g(x))
assert eq.subs(g, f) == Derivative(f(x), f(x))
assert eq.subs(g(x), f(x)) == Derivative(f(x), f(x))
assert eq.subs(g, cos) == Subs(Derivative(y, y), y, cos(x))
def test_derivative_subs2():
f_func, g_func = symbols('f g', cls=Function)
f, g = f_func(x, y, z), g_func(x, y, z)
assert Derivative(f, x, y).subs(Derivative(f, x, y), g) == g
assert Derivative(f, y, x).subs(Derivative(f, x, y), g) == g
assert Derivative(f, x, y).subs(Derivative(f, x), g) == Derivative(g, y)
assert Derivative(f, x, y).subs(Derivative(f, y), g) == Derivative(g, x)
assert (Derivative(f, x, y, z).subs(
Derivative(f, x, z), g) == Derivative(g, y))
assert (Derivative(f, x, y, z).subs(
Derivative(f, z, y), g) == Derivative(g, x))
assert (Derivative(f, x, y, z).subs(
Derivative(f, z, y, x), g) == g)
# Issue 9135
assert (Derivative(f, x, x, y).subs(
Derivative(f, y, y), g) == Derivative(f, x, x, y))
assert (Derivative(f, x, y, y, z).subs(
Derivative(f, x, y, y, y), g) == Derivative(f, x, y, y, z))
assert Derivative(f, x, y).subs(Derivative(f_func(x), x, y), g) == Derivative(f, x, y)
def test_derivative_subs3():
dex = Derivative(exp(x), x)
assert Derivative(dex, x).subs(dex, exp(x)) == dex
assert dex.subs(exp(x), dex) == Derivative(exp(x), x, x)
def test_issue_5284():
A, B = symbols('A B', commutative=False)
assert (x*A).subs(x**2*A, B) == x*A
assert (A**2).subs(A**3, B) == A**2
assert (A**6).subs(A**3, B) == B**2
def test_subs_iter():
assert x.subs(reversed([[x, y]])) == y
it = iter([[x, y]])
assert x.subs(it) == y
assert x.subs(Tuple((x, y))) == y
def test_subs_dict():
a, b, c, d, e = symbols('a b c d e')
assert (2*x + y + z).subs(dict(x=1, y=2)) == 4 + z
l = [(sin(x), 2), (x, 1)]
assert (sin(x)).subs(l) == \
(sin(x)).subs(dict(l)) == 2
assert sin(x).subs(reversed(l)) == sin(1)
expr = sin(2*x) + sqrt(sin(2*x))*cos(2*x)*sin(exp(x)*x)
reps = dict([
(sin(2*x), c),
(sqrt(sin(2*x)), a),
(cos(2*x), b),
(exp(x), e),
(x, d),
])
assert expr.subs(reps) == c + a*b*sin(d*e)
l = [(x, 3), (y, x**2)]
assert (x + y).subs(l) == 3 + x**2
assert (x + y).subs(reversed(l)) == 12
# If changes are made to convert lists into dictionaries and do
# a dictionary-lookup replacement, these tests will help to catch
# some logical errors that might occur
l = [(y, z + 2), (1 + z, 5), (z, 2)]
assert (y - 1 + 3*x).subs(l) == 5 + 3*x
l = [(y, z + 2), (z, 3)]
assert (y - 2).subs(l) == 3
def test_no_arith_subs_on_floats():
assert (x + 3).subs(x + 3, a) == a
assert (x + 3).subs(x + 2, a) == a + 1
assert (x + y + 3).subs(x + 3, a) == a + y
assert (x + y + 3).subs(x + 2, a) == a + y + 1
assert (x + 3.0).subs(x + 3.0, a) == a
assert (x + 3.0).subs(x + 2.0, a) == x + 3.0
assert (x + y + 3.0).subs(x + 3.0, a) == a + y
assert (x + y + 3.0).subs(x + 2.0, a) == x + y + 3.0
def test_issue_5651():
a, b, c, K = symbols('a b c K', commutative=True)
assert (a/(b*c)).subs(b*c, K) == a/K
assert (a/(b**2*c**3)).subs(b*c, K) == a/(c*K**2)
assert (1/(x*y)).subs(x*y, 2) == S.Half
assert ((1 + x*y)/(x*y)).subs(x*y, 1) == 2
assert (x*y*z).subs(x*y, 2) == 2*z
assert ((1 + x*y)/(x*y)/z).subs(x*y, 1) == 2/z
def test_issue_6075():
assert Tuple(1, True).subs(1, 2) == Tuple(2, True)
def test_issue_6079():
# since x + 2.0 == x + 2 we can't do a simple equality test
assert _aresame((x + 2.0).subs(2, 3), x + 2.0)
assert _aresame((x + 2.0).subs(2.0, 3), x + 3)
assert not _aresame(x + 2, x + 2.0)
assert not _aresame(Basic(cos, 1), Basic(cos, 1.))
assert _aresame(cos, cos)
assert not _aresame(1, S.One)
assert not _aresame(x, symbols('x', positive=True))
def test_issue_4680():
N = Symbol('N')
assert N.subs(dict(N=3)) == 3
def test_issue_6158():
assert (x - 1).subs(1, y) == x - y
assert (x - 1).subs(-1, y) == x + y
assert (x - oo).subs(oo, y) == x - y
assert (x - oo).subs(-oo, y) == x + y
def test_Function_subs():
f, g, h, i = symbols('f g h i', cls=Function)
p = Piecewise((g(f(x, y)), x < -1), (g(x), x <= 1))
assert p.subs(g, h) == Piecewise((h(f(x, y)), x < -1), (h(x), x <= 1))
assert (f(y) + g(x)).subs({f: h, g: i}) == i(x) + h(y)
def test_simultaneous_subs():
reps = {x: 0, y: 0}
assert (x/y).subs(reps) != (y/x).subs(reps)
assert (x/y).subs(reps, simultaneous=True) == \
(y/x).subs(reps, simultaneous=True)
reps = reps.items()
assert (x/y).subs(reps) != (y/x).subs(reps)
assert (x/y).subs(reps, simultaneous=True) == \
(y/x).subs(reps, simultaneous=True)
assert Derivative(x, y, z).subs(reps, simultaneous=True) == \
Subs(Derivative(0, y, z), y, 0)
def test_issue_6419_6421():
assert (1/(1 + x/y)).subs(x/y, x) == 1/(1 + x)
assert (-2*I).subs(2*I, x) == -x
assert (-I*x).subs(I*x, x) == -x
assert (-3*I*y**4).subs(3*I*y**2, x) == -x*y**2
def test_issue_6559():
assert (-12*x + y).subs(-x, 1) == 12 + y
# though this involves cse it generated a failure in Mul._eval_subs
x0, x1 = symbols('x0 x1')
e = -log(-12*sqrt(2) + 17)/24 - log(-2*sqrt(2) + 3)/12 + sqrt(2)/3
# XXX modify cse so x1 is eliminated and x0 = -sqrt(2)?
assert cse(e) == (
[(x0, sqrt(2))], [x0/3 - log(-12*x0 + 17)/24 - log(-2*x0 + 3)/12])
def test_issue_5261():
x = symbols('x', real=True)
e = I*x
assert exp(e).subs(exp(x), y) == y**I
assert (2**e).subs(2**x, y) == y**I
eq = (-2)**e
assert eq.subs((-2)**x, y) == eq
def test_issue_6923():
assert (-2*x*sqrt(2)).subs(2*x, y) == -sqrt(2)*y
def test_2arg_hack():
N = Symbol('N', commutative=False)
ans = Mul(2, y + 1, evaluate=False)
assert (2*x*(y + 1)).subs(x, 1, hack2=True) == ans
assert (2*(y + 1 + N)).subs(N, 0, hack2=True) == ans
@XFAIL
def test_mul2():
"""When this fails, remove things labelled "2-arg hack"
1) remove special handling in the fallback of subs that
was added in the same commit as this test
2) remove the special handling in Mul.flatten
"""
assert (2*(x + 1)).is_Mul
def test_noncommutative_subs():
x,y = symbols('x,y', commutative=False)
assert (x*y*x).subs([(x, x*y), (y, x)], simultaneous=True) == (x*y*x**2*y)
def test_issue_2877():
f = Float(2.0)
assert (x + f).subs({f: 2}) == x + 2
def r(a, b, c):
return factor(a*x**2 + b*x + c)
e = r(5.0/6, 10, 5)
assert nsimplify(e) == 5*x**2/6 + 10*x + 5
def test_issue_5910():
t = Symbol('t')
assert (1/(1 - t)).subs(t, 1) is zoo
n = t
d = t - 1
assert (n/d).subs(t, 1) is zoo
assert (-n/-d).subs(t, 1) is zoo
def test_issue_5217():
s = Symbol('s')
z = (1 - 2*x*x)
w = (1 + 2*x*x)
q = 2*x*x*2*y*y
sub = {2*x*x: s}
assert w.subs(sub) == 1 + s
assert z.subs(sub) == 1 - s
assert q == 4*x**2*y**2
assert q.subs(sub) == 2*y**2*s
def test_issue_10829():
assert (4**x).subs(2**x, y) == y**2
assert (9**x).subs(3**x, y) == y**2
def test_pow_eval_subs_no_cache():
# Tests pull request 9376 is working
from sympy.core.cache import clear_cache
s = 1/sqrt(x**2)
# This bug only appeared when the cache was turned off.
# We need to approximate running this test without the cache.
# This creates approximately the same situation.
clear_cache()
# This used to fail with a wrong result.
# It incorrectly returned 1/sqrt(x**2) before this pull request.
result = s.subs(sqrt(x**2), y)
assert result == 1/y
def test_RootOf_issue_10092():
x = Symbol('x', real=True)
eq = x**3 - 17*x**2 + 81*x - 118
r = RootOf(eq, 0)
assert (x < r).subs(x, r) is S.false
def test_issue_8886():
from sympy.physics.mechanics import ReferenceFrame as R
# if something can't be sympified we assume that it
# doesn't play well with SymPy and disallow the
# substitution
v = R('A').x
assert x.subs(x, v) == x
assert v.subs(v, x) == v
assert v.__eq__(x) is False
def test_issue_12657():
# treat -oo like the atom that it is
reps = [(-oo, 1), (oo, 2)]
assert (x < -oo).subs(reps) == (x < 1)
assert (x < -oo).subs(list(reversed(reps))) == (x < 1)
reps = [(-oo, 2), (oo, 1)]
assert (x < oo).subs(reps) == (x < 1)
assert (x < oo).subs(list(reversed(reps))) == (x < 1)
def test_recurse_Application_args():
F = Lambda((x, y), exp(2*x + 3*y))
f = Function('f')
A = f(x, f(x, x))
C = F(x, F(x, x))
assert A.subs(f, F) == A.replace(f, F) == C
def test_Subs_subs():
assert Subs(x*y, x, x).subs(x, y) == Subs(x*y, x, y)
assert Subs(x*y, x, x + 1).subs(x, y) == \
Subs(x*y, x, y + 1)
assert Subs(x*y, y, x + 1).subs(x, y) == \
Subs(y**2, y, y + 1)
a = Subs(x*y*z, (y, x, z), (x + 1, x + z, x))
b = Subs(x*y*z, (y, x, z), (x + 1, y + z, y))
assert a.subs(x, y) == b and \
a.doit().subs(x, y) == a.subs(x, y).doit()
f = Function('f')
g = Function('g')
assert Subs(2*f(x, y) + g(x), f(x, y), 1).subs(y, 2) == Subs(
2*f(x, y) + g(x), (f(x, y), y), (1, 2))
def test_issue_13333():
eq = 1/x
assert eq.subs(dict(x='1/2')) == 2
assert eq.subs(dict(x='(1/2)')) == 2
def test_issue_15234():
x, y = symbols('x y', real=True)
p = 6*x**5 + x**4 - 4*x**3 + 4*x**2 - 2*x + 3
p_subbed = 6*x**5 - 4*x**3 - 2*x + y**4 + 4*y**2 + 3
assert p.subs([(x**i, y**i) for i in [2, 4]]) == p_subbed
x, y = symbols('x y', complex=True)
p = 6*x**5 + x**4 - 4*x**3 + 4*x**2 - 2*x + 3
p_subbed = 6*x**5 - 4*x**3 - 2*x + y**4 + 4*y**2 + 3
assert p.subs([(x**i, y**i) for i in [2, 4]]) == p_subbed
def test_issue_6976():
x, y = symbols('x y')
assert (sqrt(x)**3 + sqrt(x) + x + x**2).subs(sqrt(x), y) == \
y**4 + y**3 + y**2 + y
assert (x**4 + x**3 + x**2 + x + sqrt(x)).subs(x**2, y) == \
sqrt(x) + x**3 + x + y**2 + y
assert x.subs(x**3, y) == x
assert x.subs(x**Rational(1, 3), y) == y**3
# More substitutions are possible with nonnegative symbols
x, y = symbols('x y', nonnegative=True)
assert (x**4 + x**3 + x**2 + x + sqrt(x)).subs(x**2, y) == \
y**Rational(1, 4) + y**Rational(3, 2) + sqrt(y) + y**2 + y
assert x.subs(x**3, y) == y**Rational(1, 3)
|
6c88e38901596a5dcda2afa3de48735434fe8eb2fedac7194350bfddec062438 | from sympy.abc import x, y
from sympy.core.evaluate import evaluate
from sympy.core import Mul, Add, Pow, S
from sympy import sqrt
def test_add():
with evaluate(False):
expr = x + x
assert isinstance(expr, Add)
assert expr.args == (x, x)
with evaluate(True):
assert (x + x).args == (2, x)
assert (x + x).args == (x, x)
assert isinstance(x + x, Mul)
with evaluate(False):
assert S.One + 1 == Add(1, 1)
assert 1 + S.One == Add(1, 1)
assert S(4) - 3 == Add(4, -3)
assert -3 + S(4) == Add(4, -3)
assert S(2) * 4 == Mul(2, 4)
assert 4 * S(2) == Mul(2, 4)
assert S(6) / 3 == Mul(6, S.One / 3)
assert S.One / 3 * 6 == Mul(S.One / 3, 6)
assert 9 ** S(2) == Pow(9, 2)
assert S(2) ** 9 == Pow(2, 9)
assert S(2) / 2 == Mul(2, S.One / 2)
assert S.One / 2 * 2 == Mul(S.One / 2, 2)
assert S(2) / 3 + 1 == Add(S(2) / 3, 1)
assert 1 + S(2) / 3 == Add(1, S(2) / 3)
assert S(4) / 7 - 3 == Add(S(4) / 7, -3)
assert -3 + S(4) / 7 == Add(-3, S(4) / 7)
assert S(2) / 4 * 4 == Mul(S(2) / 4, 4)
assert 4 * (S(2) / 4) == Mul(4, S(2) / 4)
assert S(6) / 3 == Mul(6, S.One / 3)
assert S.One / 3 * 6 == Mul(S.One / 3, 6)
assert S.One / 3 + sqrt(3) == Add(S.One / 3, sqrt(3))
assert sqrt(3) + S.One / 3 == Add(sqrt(3), S.One / 3)
assert S.One / 2 * 10.333 == Mul(S.One / 2, 10.333)
assert 10.333 * S.One / 2 == Mul(10.333, S.One / 2)
assert sqrt(2) * sqrt(2) == Mul(sqrt(2), sqrt(2))
assert S.One / 2 + x == Add(S.One / 2, x)
assert x + S.One / 2 == Add(x, S.One / 2)
assert S.One / x * x == Mul(S.One / x, x)
assert x * S.One / x == Mul(x, S.One / x)
def test_nested():
with evaluate(False):
expr = (x + x) + (y + y)
assert expr.args == ((x + x), (y + y))
assert expr.args[0].args == (x, x)
|
609321d55d9e5cc92c32eba50320bc2924fe7ea0bad5baa8e23efcd9783b2dc1 | from sympy import (Add, Basic, Expr, S, Symbol, Wild, Float, Integer, Rational, I,
sin, cos, tan, exp, log, nan, oo, sqrt, symbols, Integral, sympify,
WildFunction, Poly, Function, Derivative, Number, pi, NumberSymbol, zoo,
Piecewise, Mul, Pow, nsimplify, ratsimp, trigsimp, radsimp, powsimp,
simplify, together, collect, factorial, apart, combsimp, factor, refine,
cancel, Tuple, default_sort_key, DiracDelta, gamma, Dummy, Sum, E,
exp_polar, expand, diff, O, Heaviside, Si, Max, UnevaluatedExpr,
integrate, gammasimp, Gt, cot)
from sympy.core.expr import ExprBuilder, unchanged
from sympy.core.function import AppliedUndef
from sympy.core.compatibility import range, round, PY3
from sympy.physics.secondquant import FockState
from sympy.physics.units import meter
from sympy.utilities.pytest import raises, XFAIL
from sympy.abc import a, b, c, n, t, u, x, y, z
# replace 3 instances with int when PY2 is dropped and
# delete this line
_rint = int if PY3 else float
class DummyNumber(object):
"""
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 __truediv__(a, b):
return a.__div__(b)
def __rtruediv__(a, b):
return a.__rdiv__(b)
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 __rdiv__(self, a):
if isinstance(a, (int, float)):
return a / self.number
return NotImplemented
def __div__(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 x in all_objs:
for y in all_objs:
s(x, y)
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
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)
def test_relational():
from sympy 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():
from sympy import Lt, Gt, Le, Ge
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
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))
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 + 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}
assert Poly(1, x).atoms() == {S.One}
assert Poly(x, x).atoms() == {x}
assert Poly(x, x, y).atoms() == {x}
assert Poly(x + y, x, y).atoms() == {x, y}
assert Poly(x + y, x, y, z).atoms() == {x, y}
assert Poly(x + y*t, x, y, z).atoms() == {t, x, y}
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
f = Function('f')
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
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
assert (S.NaN).is_rational_function() is False
assert (S.Infinity).is_rational_function() is False
assert (S.NegativeInfinity).is_rational_function() is False
assert (S.ComplexInfinity).is_rational_function() is False
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(object):
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)
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)
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
f = Function('f')
assert (2*f)(x) == 2*f(x)
def test_replace():
f = log(sin(x)) + tan(sin(x**2))
assert f.replace(sin, cos) == log(cos(x)) + tan(cos(x**2))
assert f.replace(
sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
a = Wild('a')
b = Wild('b')
assert f.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2))
assert f.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) == O(1, x)
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)
f = Function('f')
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
f = Function('f')
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():
f = Function('f')
g = Function('g')
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)
g = Function('g')
h = Function('h')
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():
f = Function('f')
g = Function('g')
h = Function('h')
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))
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) is True # .has(1) will also be True
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
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
f = Function('f')
fx = D(f(x), x)
assert fx.as_coeff_exponent(f(x)) == (fx, 0)
def test_extractions():
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
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 True
assert (-(x + x*y)/y).could_extract_minus_sign() is True
assert ((x + x*y)/(-y)).could_extract_minus_sign() is True
assert ((x + x*y)/y).could_extract_minus_sign() is False
assert (x*(-x - x**3)).could_extract_minus_sign() is True
assert ((-x - y)/(x + y)).could_extract_minus_sign() is True
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
# The results of each of these will vary on different machines, e.g.
# the first one might be False and the other (then) is true or vice versa,
# so both are included.
assert ((-x - y)/(x - y)).could_extract_minus_sign() is False or \
((-x - y)/(y - x)).could_extract_minus_sign() is False
assert (x - y).could_extract_minus_sign() is False
assert (-x + y).could_extract_minus_sign() is True
# 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
f = Function('f')
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=1) == 1
assert (n*m + n*m*n).coeff(n*m, right=1) == 1 + n # = n*m*(n + 1)
assert (x*y).coeff(z, 0) == x*y
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
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_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 S.Zero.as_coeff_Mul() == (S.One, S.Zero)
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():
f, g = symbols('f,g', cls=Function)
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():
f, g = symbols('f,g', cls=Function)
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():
f, g = symbols('f,g', cls=Function)
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]
f = x**2*y**2 + x*y**4 + y + 2
assert f.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2]
assert f.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2]
assert f.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2]
assert f.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
# first subs and limit gives NaN
a = x/y
assert a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero) is S.NaN
# second subs and limit gives NaN
assert a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo) is S.NaN
# difference gives S.NaN
a = x - y
assert a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One) is S.NaN
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
Sum(x, (x, 1, 10)).is_constant() is True
Sum(x, (x, 1, n)).is_constant() is False
Sum(x, (x, 1, n)).is_constant(y) is True
Sum(x, (x, 1, n)).is_constant(n) is False
Sum(x, (x, 1, n)).is_constant(x) is True
eq = a*cos(x)**2 + a*sin(x)**2 - a
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 checksol(x, x, Sum(x, (x, 1, n))) is False
assert checksol(x, x, Sum(x, (x, 1, n))) is False
f = Function('f')
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
assert Poly(3,x).is_constant() is True
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 False
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 import posify, lucas
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():
from sympy.abc import x
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())
f = Function('f')
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):
f = float(i)
# 2 args
assert all(type(round(i, p)) is _rint for p in (-1, 0, 1))
assert all(S(i).round(p).is_Integer for p in (-1, 0, 1))
assert all(type(round(f, p)) is float for p in (-1, 0, 1))
assert all(S(f).round(p).is_Float for p in (-1, 0, 1))
# 1 arg (p is None)
assert type(round(i)) is _rint
assert S(i).round().is_Integer
assert type(round(f)) is _rint
assert S(f).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
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
|
c5a318f6a317cd9c76c492e1e145402832f6ffab3f93445b2ebb3375ba5677c6 | """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
import io
from sympy import (Basic, S, symbols, sqrt, sin, oo, Interval, exp, Lambda, pi,
Eq, log, Function, Rational)
from sympy.core.compatibility import range
from sympy.utilities.pytest import XFAIL, SKIP
x, y, z = symbols('x,y,z')
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 io.open(os.path.join(root, file), "r", encoding='utf-8') as f:
text = f.read()
submodule = module + '.' + file[:-3]
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
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):
return all(isinstance(arg, Basic) for arg in obj.args)
def test_sympy__assumptions__assume__AppliedPredicate():
from sympy.assumptions.assume import AppliedPredicate, Predicate
from sympy import Q
assert _test_args(AppliedPredicate(Predicate("test"), 2))
assert _test_args(Q.is_true(True))
def test_sympy__assumptions__assume__Predicate():
from sympy.assumptions.assume import Predicate
assert _test_args(Predicate("test"))
def test_sympy__assumptions__sathandlers__UnevaluatedOnFree():
from sympy.assumptions.sathandlers import UnevaluatedOnFree
from sympy import Q
assert _test_args(UnevaluatedOnFree(Q.positive))
def test_sympy__assumptions__sathandlers__AllArgs():
from sympy.assumptions.sathandlers import AllArgs
from sympy import Q
assert _test_args(AllArgs(Q.positive))
def test_sympy__assumptions__sathandlers__AnyArgs():
from sympy.assumptions.sathandlers import AnyArgs
from sympy import Q
assert _test_args(AnyArgs(Q.positive))
def test_sympy__assumptions__sathandlers__ExactlyOneArg():
from sympy.assumptions.sathandlers import ExactlyOneArg
from sympy import Q
assert _test_args(ExactlyOneArg(Q.positive))
def test_sympy__assumptions__sathandlers__CheckOldAssump():
from sympy.assumptions.sathandlers import CheckOldAssump
from sympy import Q
assert _test_args(CheckOldAssump(Q.positive))
def test_sympy__assumptions__sathandlers__CheckIsPrime():
from sympy.assumptions.sathandlers import CheckIsPrime
from sympy import Q
# Input must be a number
assert _test_args(CheckIsPrime(Q.positive))
@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 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'))
@XFAIL
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__subsets__Subset():
from sympy.combinatorics.subsets import Subset
assert _test_args(Subset([0, 1], [0, 1, 2, 3]))
assert _test_args(Subset(['c', 'd'], ['a', 'b', 'c', 'd']))
def test_sympy__combinatorics__permutations__Permutation():
from sympy.combinatorics.permutations import Permutation
assert _test_args(Permutation([0, 1, 2, 3]))
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))
@XFAIL
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]))
@XFAIL
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__algebras__quaternion__Quaternion():
from sympy.algebras.quaternion import Quaternion
assert _test_args(Quaternion(x, 1, 2, 3))
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__util__AccumulationBounds():
from sympy.calculus.util 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__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
assert _test_args(Intersection(Interval(0, 3), Interval(2, 4),
evaluate=False))
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
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__core__trace__Tr():
from sympy.core.trace import Tr
a, b = symbols('a b')
assert _test_args(Tr(a + b))
def test_sympy__sets__setexpr__SetExpr():
from sympy.sets.setexpr import SetExpr
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 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__ImageSet():
from sympy.sets.fancysets import ImageSet
from sympy import S, 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 import S, 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.stats.crv import ContinuousDomain
assert _test_args(ContinuousDomain({x}, Interval(-oo, oo)))
def test_sympy__stats__crv__SingleContinuousDomain():
from sympy.stats.crv import SingleContinuousDomain
assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo)))
def test_sympy__stats__crv__ProductContinuousDomain():
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.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.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__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__JointDistributionHandmade():
from sympy import Indexed
from sympy.stats.joint_rv 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__joint_rv__CompoundDistribution():
from sympy.stats.joint_rv import CompoundDistribution
from sympy.stats.drv_types import PoissonDistribution
r = PoissonDistribution(x)
assert _test_args(CompoundDistribution(PoissonDistribution(r)))
@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__PSpace():
from sympy.stats.rv import PSpace, RandomDomain
from sympy 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.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__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__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 import Symbol
assert _test_args(SingleFinitePSpace(Symbol('x'), die))
def test_sympy__stats__frv__ProductFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpace
from sympy 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 import Dict
assert _test_args(FiniteDistributionHandmade(Dict({1: 1})))
def test_sympy__stats__crv__ContinuousDistributionHandmade():
from sympy.stats.crv import ContinuousDistributionHandmade
from sympy import Symbol, Interval
assert _test_args(ContinuousDistributionHandmade(Symbol('x'),
Interval(0, 2)))
def test_sympy__stats__drv__DiscreteDistributionHandmade():
from sympy.stats.drv import DiscreteDistributionHandmade
assert _test_args(DiscreteDistributionHandmade(x, S.Naturals))
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__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__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__LogNormalDistribution():
from sympy.stats.crv_types import LogNormalDistribution
assert _test_args(LogNormalDistribution(0, 1))
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__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__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__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__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__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.tensor import Indexed
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 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 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
from sympy import MatrixSymbol
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 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 import MatrixSymbol
assert _test_args(ContinuousMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3)))
def test_sympy__stats__random_matrix__RandomMatrixPSpace():
from sympy.stats.random_matrix import RandomMatrixPSpace
from sympy.stats.random_matrix_models import RandomMatrixEnsemble
assert _test_args(RandomMatrixPSpace('P', RandomMatrixEnsemble('R', 3)))
def test_sympy__stats__random_matrix_models__RandomMatrixEnsemble():
from sympy.stats.random_matrix_models import RandomMatrixEnsemble
assert _test_args(RandomMatrixEnsemble('R', 3))
def test_sympy__stats__random_matrix_models__GaussianEnsemble():
from sympy.stats.random_matrix_models import GaussianEnsemble
assert _test_args(GaussianEnsemble('G', 3))
def test_sympy__stats__random_matrix_models__GaussianUnitaryEnsemble():
from sympy.stats import GaussianUnitaryEnsemble
assert _test_args(GaussianUnitaryEnsemble('U', 3))
def test_sympy__stats__random_matrix_models__GaussianOrthogonalEnsemble():
from sympy.stats import GaussianOrthogonalEnsemble
assert _test_args(GaussianOrthogonalEnsemble('U', 3))
def test_sympy__stats__random_matrix_models__GaussianSymplecticEnsemble():
from sympy.stats import GaussianSymplecticEnsemble
assert _test_args(GaussianSymplecticEnsemble('U', 3))
def test_sympy__stats__random_matrix_models__CircularEnsemble():
from sympy.stats import CircularEnsemble
assert _test_args(CircularEnsemble('C', 3))
def test_sympy__stats__random_matrix_models__CircularUnitaryEnsemble():
from sympy.stats import CircularUnitaryEnsemble
assert _test_args(CircularUnitaryEnsemble('U', 3))
def test_sympy__stats__random_matrix_models__CircularOrthogonalEnsemble():
from sympy.stats import CircularOrthogonalEnsemble
assert _test_args(CircularOrthogonalEnsemble('O', 3))
def test_sympy__stats__random_matrix_models__CircularSymplecticEnsemble():
from sympy.stats import CircularSymplecticEnsemble
assert _test_args(CircularSymplecticEnsemble('S', 3))
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(1))
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__carmichael():
from sympy.functions.combinatorial.numbers import carmichael
assert _test_args(carmichael(x))
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(2))
def test_sympy__functions__elementary__hyperbolic__acsch():
from sympy.functions.elementary.hyperbolic import acsch
assert _test_args(acsch(2))
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("does this work at all?")
def test_sympy__functions__elementary__integers__RoundFunction():
from sympy.functions.elementary.integers import RoundFunction
assert _test_args(RoundFunction())
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__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(2))
def test_sympy__functions__elementary__trigonometric__acsc():
from sympy.functions.elementary.trigonometric import acsc
assert _test_args(acsc(2))
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(2))
@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(2))
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__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, x))
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, 2, 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__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(1, 1, x, y))
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__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))
@XFAIL
def test_sympy__liealgebras__cartan_type__CartanType_generator():
from sympy.liealgebras.cartan_type import CartanType_generator
assert _test_args(CartanType_generator("A2"))
@XFAIL
def test_sympy__liealgebras__cartan_type__Standard_Cartan():
from sympy.liealgebras.cartan_type import Standard_Cartan
assert _test_args(Standard_Cartan("A", 2))
@XFAIL
def test_sympy__liealgebras__weyl_group__WeylGroup():
from sympy.liealgebras.weyl_group import WeylGroup
assert _test_args(WeylGroup("B4"))
@XFAIL
def test_sympy__liealgebras__root_system__RootSystem():
from sympy.liealgebras.root_system import RootSystem
assert _test_args(RootSystem("A2"))
@XFAIL
def test_sympy__liealgebras__type_a__TypeA():
from sympy.liealgebras.type_a import TypeA
assert _test_args(TypeA(2))
@XFAIL
def test_sympy__liealgebras__type_b__TypeB():
from sympy.liealgebras.type_b import TypeB
assert _test_args(TypeB(4))
@XFAIL
def test_sympy__liealgebras__type_c__TypeC():
from sympy.liealgebras.type_c import TypeC
assert _test_args(TypeC(4))
@XFAIL
def test_sympy__liealgebras__type_d__TypeD():
from sympy.liealgebras.type_d import TypeD
assert _test_args(TypeD(4))
@XFAIL
def test_sympy__liealgebras__type_e__TypeE():
from sympy.liealgebras.type_e import TypeE
assert _test_args(TypeE(6))
@XFAIL
def test_sympy__liealgebras__type_f__TypeF():
from sympy.liealgebras.type_f import TypeF
assert _test_args(TypeF(4))
@XFAIL
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__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
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))
def test_sympy__matrices__expressions__matexpr__Identity():
from sympy.matrices.expressions.matexpr import Identity
assert _test_args(Identity(3))
def test_sympy__matrices__expressions__matexpr__GenericIdentity():
from sympy.matrices.expressions.matexpr import GenericIdentity
assert _test_args(GenericIdentity())
@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 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__matexpr__ZeroMatrix():
from sympy.matrices.expressions.matexpr import ZeroMatrix
assert _test_args(ZeroMatrix(3, 5))
def test_sympy__matrices__expressions__matexpr__OneMatrix():
from sympy.matrices.expressions.matexpr import OneMatrix
assert _test_args(OneMatrix(3, 5))
def test_sympy__matrices__expressions__matexpr__GenericZeroMatrix():
from sympy.matrices.expressions.matexpr import GenericZeroMatrix
assert _test_args(GenericZeroMatrix())
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__DiagonalizeVector():
from sympy.matrices.expressions.diagonal import DiagonalizeVector
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagonalizeVector(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 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__funcmatrix__FunctionMatrix():
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
from sympy 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 import S
assert _test_args(DFT(S(2)))
def test_sympy__matrices__expressions__fourier__IDFT():
from sympy.matrices.expressions.fourier import IDFT
from sympy 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__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 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 import Integer, Tuple
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))
@SKIP("TODO: sympy.physics")
def test_sympy__physics__quantum__grover__OracleGate():
from sympy.physics.quantum.grover import OracleGate
assert _test_args(OracleGate())
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 import oo, 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 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__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 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
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
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
from sympy import I
assert _test_args(Dagger(2*I))
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__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.dimensions 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
from sympy.physics.units import length
assert _test_args(Quantity("dam"))
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():
from sympy.series.sequences 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, (0, 1)))
assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y, 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__arrayop__Flatten():
from sympy.tensor.array.arrayop import Flatten
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
fla = Flatten(ImmutableDenseNDimArray(range(24)).reshape(2, 3, 4))
assert _test_args(fla)
def test_sympy__tensor__functions__TensorProduct():
from sympy.tensor.functions import TensorProduct
tp = TensorProduct(3, 4, evaluate=False)
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(1, (0, 10)))
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', metric=False))
@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_fmt='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_fmt='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_fmt='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_fmt='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_fmt='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_fmt='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))))
@XFAIL
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))), [x, y]))
def test_sympy__diffgeom__diffgeom__BaseScalarField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
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)))
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)))
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)))
cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)))
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)))
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)))
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)))
d = Differential(BaseScalarField(cs, 0))
v = BaseVectorField(cs, 0)
assert _test_args(LieDerivative(v, d))
@XFAIL
def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)))
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)))
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"))
@XFAIL
def test_sympy__categories__baseclasses__Morphism():
from sympy.categories import Object, Morphism
assert _test_args(Morphism(Object("A"), Object("B")))
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))
def test_sympy__physics__optics__medium__Medium():
from sympy.physics.optics import Medium
assert _test_args(Medium('m'))
def test_sympy__codegen__array_utils__CodegenArrayContraction():
from sympy.codegen.array_utils import CodegenArrayContraction
from sympy import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(CodegenArrayContraction(A, (0, 1)))
def test_sympy__codegen__array_utils__CodegenArrayDiagonal():
from sympy.codegen.array_utils import CodegenArrayDiagonal
from sympy import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(CodegenArrayDiagonal(A, (0, 1)))
def test_sympy__codegen__array_utils__CodegenArrayTensorProduct():
from sympy.codegen.array_utils import CodegenArrayTensorProduct
from sympy import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(CodegenArrayTensorProduct(A, B))
def test_sympy__codegen__array_utils__CodegenArrayElementwiseAdd():
from sympy.codegen.array_utils import CodegenArrayElementwiseAdd
from sympy import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(CodegenArrayElementwiseAdd(A, B))
def test_sympy__codegen__array_utils__CodegenArrayPermuteDims():
from sympy.codegen.array_utils import CodegenArrayPermuteDims
from sympy import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(CodegenArrayPermuteDims(A, (1, 0)))
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
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
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
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
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__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
def test_sympy__vector__orienters__ThreeAngleOrienter():
from sympy.vector.orienters import ThreeAngleOrienter
#Not to be initialized
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__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(5))
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, 1))
def test_sympy__integrals__rubi__utility_function__ProductLog():
from sympy.integrals.rubi.utility_function import ProductLog
assert _test_args(ProductLog(1))
|
429f059f1203b149bb303d3f2521cd964330ffea90978433e82b98b5fed6e38b | from sympy import symbols, sin, exp, cos, Derivative, Integral, Basic, \
count_ops, S, And, I, pi, Eq, Or, Not, Xor, Nand, Nor, Implies, \
Equivalent, MatrixSymbol, Symbol, ITE, Rel, Rational
from sympy.core.containers import Tuple
x, y, z = symbols('x,y,z')
a, b, c = symbols('a,b,c')
def test_count_ops_non_visual():
def count(val):
return count_ops(val, visual=False)
assert count(x) == 0
assert count(x) is not S.Zero
assert count(x + y) == 1
assert count(x + y) is not S.One
assert count(x + y*x + 2*y) == 4
assert count({x + y: x}) == 1
assert count({x + y: S(2) + x}) is not S.One
assert count(x < y) == 1
assert count(Or(x,y)) == 1
assert count(And(x,y)) == 1
assert count(Not(x)) == 1
assert count(Nor(x,y)) == 2
assert count(Nand(x,y)) == 2
assert count(Xor(x,y)) == 1
assert count(Implies(x,y)) == 1
assert count(Equivalent(x,y)) == 1
assert count(ITE(x,y,z)) == 1
assert count(ITE(True,x,y)) == 0
def test_count_ops_visual():
ADD, MUL, POW, SIN, COS, EXP, AND, D, G = symbols(
'Add Mul Pow sin cos exp And Derivative Integral'.upper())
DIV, SUB, NEG = symbols('DIV SUB NEG')
LT, LE, GT, GE, EQ, NE = symbols('LT LE GT GE EQ NE')
NOT, OR, AND, XOR, IMPLIES, EQUIVALENT, _ITE, BASIC, TUPLE = symbols(
'Not Or And Xor Implies Equivalent ITE Basic Tuple'.upper())
def count(val):
return count_ops(val, visual=True)
assert count(7) is S.Zero
assert count(S(7)) is S.Zero
assert count(-1) == NEG
assert count(-2) == NEG
assert count(S(2)/3) == DIV
assert count(Rational(2, 3)) == DIV
assert count(pi/3) == DIV
assert count(-pi/3) == DIV + NEG
assert count(I - 1) == SUB
assert count(1 - I) == SUB
assert count(1 - 2*I) == SUB + MUL
assert count(x) is S.Zero
assert count(-x) == NEG
assert count(-2*x/3) == NEG + DIV + MUL
assert count(Rational(-2, 3)*x) == NEG + DIV + MUL
assert count(1/x) == DIV
assert count(1/(x*y)) == DIV + MUL
assert count(-1/x) == NEG + DIV
assert count(-2/x) == NEG + DIV
assert count(x/y) == DIV
assert count(-x/y) == NEG + DIV
assert count(x**2) == POW
assert count(-x**2) == POW + NEG
assert count(-2*x**2) == POW + MUL + NEG
assert count(x + pi/3) == ADD + DIV
assert count(x + S.One/3) == ADD + DIV
assert count(x + Rational(1, 3)) == ADD + DIV
assert count(x + y) == ADD
assert count(x - y) == SUB
assert count(y - x) == SUB
assert count(-1/(x - y)) == DIV + NEG + SUB
assert count(-1/(y - x)) == DIV + NEG + SUB
assert count(1 + x**y) == ADD + POW
assert count(1 + x + y) == 2*ADD
assert count(1 + x + y + z) == 3*ADD
assert count(1 + x**y + 2*x*y + y**2) == 3*ADD + 2*POW + 2*MUL
assert count(2*z + y + x + 1) == 3*ADD + MUL
assert count(2*z + y**17 + x + 1) == 3*ADD + MUL + POW
assert count(2*z + y**17 + x + sin(x)) == 3*ADD + POW + MUL + SIN
assert count(2*z + y**17 + x + sin(x**2)) == 3*ADD + MUL + 2*POW + SIN
assert count(2*z + y**17 + x + sin(
x**2) + exp(cos(x))) == 4*ADD + MUL + 2*POW + EXP + COS + SIN
assert count(Derivative(x, x)) == D
assert count(Integral(x, x) + 2*x/(1 + x)) == G + DIV + MUL + 2*ADD
assert count(Basic()) is S.Zero
assert count({x + 1: sin(x)}) == ADD + SIN
assert count([x + 1, sin(x) + y, None]) == ADD + SIN + ADD
assert count({x + 1: sin(x), y: cos(x) + 1}) == SIN + COS + 2*ADD
assert count({}) is S.Zero
assert count([x + 1, sin(x)*y, None]) == SIN + ADD + MUL
assert count([]) is S.Zero
assert count(Basic()) == 0
assert count(Basic(Basic(),Basic(x,x+y))) == ADD + 2*BASIC
assert count(Basic(x, x + y)) == ADD + BASIC
assert [count(Rel(x, y, op)) for op in '< <= > >= == <> !='.split()
] == [LT, LE, GT, GE, EQ, NE, NE]
assert count(Or(x, y)) == OR
assert count(And(x, y)) == AND
assert count(Or(x, Or(y, And(z, a)))) == AND + OR
assert count(Nor(x, y)) == NOT + OR
assert count(Nand(x, y)) == NOT + AND
assert count(Xor(x, y)) == XOR
assert count(Implies(x, y)) == IMPLIES
assert count(Equivalent(x, y)) == EQUIVALENT
assert count(ITE(x, y, z)) == _ITE
assert count([Or(x, y), And(x, y), Basic(x + y)]
) == ADD + AND + BASIC + OR
assert count(Basic(Tuple(x))) == BASIC + TUPLE
#It checks that TUPLE is counted as an operation.
assert count(Eq(x + y, S(2))) == ADD + EQ
def test_issue_9324():
def count(val):
return count_ops(val, visual=False)
M = MatrixSymbol('M', 10, 10)
assert count(M[0, 0]) == 0
assert count(2 * M[0, 0] + M[5, 7]) == 2
P = MatrixSymbol('P', 3, 3)
Q = MatrixSymbol('Q', 3, 3)
assert count(P + Q) == 1
m = Symbol('m', integer=True)
n = Symbol('n', integer=True)
M = MatrixSymbol('M', m + n, m * m)
assert count(M[0, 1]) == 2
|
aca636fc72dc2b1e60bc82798beed3d987f37dca26ea100931ab0ebfe11797b6 | from __future__ import absolute_import
import numbers as nums
import decimal
from sympy import (Rational, Symbol, Float, I, sqrt, cbrt, oo, nan, pi, E,
Integer, S, factorial, Catalan, EulerGamma, GoldenRatio,
TribonacciConstant, cos, exp,
Number, zoo, log, Mul, Pow, Tuple, latex, Gt, Lt, Ge, Le,
AlgebraicNumber, simplify, sin, fibonacci, RealField,
sympify, srepr)
from sympy.core.compatibility import long
from sympy.core.expr import unchanged
from sympy.core.logic import fuzzy_not
from sympy.core.numbers import (igcd, ilcm, igcdex, seterr,
igcd2, igcd_lehmer, mpf_norm, comp, mod_inverse)
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.utilities.pytest import XFAIL, raises
from mpmath import mpf
from mpmath.rational import mpq
import mpmath
from sympy 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)
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(u'-1') is S.NegativeOne
i = Integer(10)
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls(u'10'))
assert _strictly_equal(i, cls(long(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)
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))
x2_str = Float((0, '26666666666666', -53, 54))
x_hex = Float((0, long(0x13333333333333), -52, 53))
x_dec = Float(mpf)
assert x_str == 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, long(0), -123, -1)) is S.NaN
assert Float((0, long(0), -456, -2)) is S.Infinity
assert Float((1, long(0), -789, -3)) is S.NegativeInfinity
# if you don't give the full signature, it's not special
assert Float((0, long(0), -123)) == Float(0)
assert Float((0, long(0), -456)) == Float(0)
assert Float((1, long(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
Float('123 456.123 456') == Float('123456.123456')
Integer('123 456') == Integer('123456')
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_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('1_'))
raises(ValueError, lambda: Float('1_.'))
raises(ValueError, lambda: Float('1._'))
raises(ValueError, lambda: Float('1__2'))
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 '{0:.3f}'.format(Float(4.236622)) == '4.237'
assert '{0:.35f}'.format(Float(pi.n(40), 40)) == \
'3.14159265358979323846264338327950288'
# unicode
assert Float(u'0.73908513321516064100000000') == \
Float('0.73908513321516064100000000')
assert Float(u'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
@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
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 == S.Infinity + S.Infinity * S.ImaginaryUnit
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 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 == \
S.Infinity + S.Infinity * S.ImaginaryUnit
# 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_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)
assert int(pi) == 3
assert int(E) == 2
assert int(GoldenRatio) == 1
assert int(TribonacciConstant) == 2
# issue 10368
a = Rational(32442016954, 78058255275)
assert type(int(a)) is type(int(-a)) is int
def test_long():
a = Rational(5)
assert long(a) == 5
a = Rational(9, 10)
assert long(a) == long(-a) == 0
a = Integer(2**100)
assert long(a) == a
assert long(pi) == 3
assert long(E) == 2
assert long(GoldenRatio) == 1
assert long(TribonacciConstant) == 2
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
with raises(ImportError):
from sympy import Pi
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, finite=True)
nb = Symbol('nb', negative=True, finite=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 set([Integer(3)]) == set([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, long(0), -123, -1, 53, rnd) # nan
assert _normalize(mpf, 53) != (0, long(0), 0, 0)
mpf = (0, long(0), -456, -2, 53, rnd) # +inf
assert _normalize(mpf, 53) != (0, long(0), 0, 0)
mpf = (1, long(0), -789, -3, 53, rnd) # -inf
assert _normalize(mpf, 53) != (0, long(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, long(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, long(302627), -19, 19)
assert f._prec == 20
assert n._as_mpf_val(20) == f._mpf_
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_int_NumberSymbols():
assert [int(i) for i in [pi, EulerGamma, E, GoldenRatio, Catalan]] == \
[3, 0, 2, 1, 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(object):
"""
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(object):
"""
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.utilities.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))
def test_floordiv():
assert S(2)//S.Half == 4
|
d8defc7d5c00a640365c92aef5ede216d56cd222273f9d916b650a2624f83cc5 | from sympy import (Lambda, Symbol, Function, Derivative, Subs, sqrt,
log, exp, Rational, Float, sin, cos, acos, diff, I, re, im,
E, expand, pi, O, Sum, S, polygamma, loggamma, expint,
Tuple, Dummy, Eq, Expr, symbols, nfloat, Piecewise, Indexed,
Matrix, Basic, Dict, oo, zoo, nan, Pow)
from sympy.core.basic import _aresame
from sympy.core.cache import clear_cache
from sympy.core.compatibility import range
from sympy.core.expr import unchanged
from sympy.core.function import (PoleError, _mexpand, arity,
BadSignatureError, BadArgumentsError)
from sympy.core.sympify import sympify
from sympy.sets.sets import FiniteSet
from sympy.solvers.solveset import solveset
from sympy.tensor.array import NDimArray
from sympy.utilities.iterables import subsets, variations
from sympy.utilities.pytest import XFAIL, raises, warns_deprecated_sympy
from sympy.abc import t, w, x, y, z
f, g, h = symbols('f g h', cls=Function)
_xi_1, _xi_2, _xi_3 = [Dummy() for i in range(3)]
def test_f_expand_complex():
x = Symbol('x', real=True)
assert f(x).expand(complex=True) == I*im(f(x)) + re(f(x))
assert exp(x).expand(complex=True) == exp(x)
assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x)
assert exp(z).expand(complex=True) == cos(im(z))*exp(re(z)) + \
I*sin(im(z))*exp(re(z))
def test_bug1():
e = sqrt(-log(w))
assert e.subs(log(w), -x) == sqrt(x)
e = sqrt(-5*log(w))
assert e.subs(log(w), -x) == sqrt(5*x)
def test_general_function():
nu = Function('nu')
e = nu(x)
edx = e.diff(x)
edy = e.diff(y)
edxdx = e.diff(x).diff(x)
edxdy = e.diff(x).diff(y)
assert e == nu(x)
assert edx != nu(x)
assert edx == diff(nu(x), x)
assert edy == 0
assert edxdx == diff(diff(nu(x), x), x)
assert edxdy == 0
def test_general_function_nullary():
nu = Function('nu')
e = nu()
edx = e.diff(x)
edxdx = e.diff(x).diff(x)
assert e == nu()
assert edx != nu()
assert edx == 0
assert edxdx == 0
def test_derivative_subs_bug():
e = diff(g(x), x)
assert e.subs(g(x), f(x)) != e
assert e.subs(g(x), f(x)) == Derivative(f(x), x)
assert e.subs(g(x), -f(x)) == Derivative(-f(x), x)
assert e.subs(x, y) == Derivative(g(y), y)
def test_derivative_subs_self_bug():
d = diff(f(x), x)
assert d.subs(d, y) == y
def test_derivative_linearity():
assert diff(-f(x), x) == -diff(f(x), x)
assert diff(8*f(x), x) == 8*diff(f(x), x)
assert diff(8*f(x), x) != 7*diff(f(x), x)
assert diff(8*f(x)*x, x) == 8*f(x) + 8*x*diff(f(x), x)
assert diff(8*f(x)*y*x, x).expand() == 8*y*f(x) + 8*y*x*diff(f(x), x)
def test_derivative_evaluate():
assert Derivative(sin(x), x) != diff(sin(x), x)
assert Derivative(sin(x), x).doit() == diff(sin(x), x)
assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x)
assert Derivative(sin(x), x, 0) == sin(x)
assert Derivative(sin(x), (x, y), (x, -y)) == sin(x)
def test_diff_symbols():
assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z)
assert diff(f(x, y, z), x, x, x) == Derivative(f(x, y, z), x, x, x) == Derivative(f(x, y, z), (x, 3))
assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3)
# issue 5028
assert [diff(-z + x/y, sym) for sym in (z, x, y)] == [-1, 1/y, -x/y**2]
assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z)
assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \
Derivative(f(x, y, z), x, y, z, z)
assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \
Derivative(f(x, y, z), x, y, z, z)
assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \
Derivative(f(x, y, z), x, y, z)
raises(TypeError, lambda: cos(x).diff((x, y)).variables)
assert cos(x).diff((x, y))._wrt_variables == [x]
def test_Function():
class myfunc(Function):
@classmethod
def eval(cls): # zero args
return
assert myfunc.nargs == FiniteSet(0)
assert myfunc().nargs == FiniteSet(0)
raises(TypeError, lambda: myfunc(x).nargs)
class myfunc(Function):
@classmethod
def eval(cls, x): # one arg
return
assert myfunc.nargs == FiniteSet(1)
assert myfunc(x).nargs == FiniteSet(1)
raises(TypeError, lambda: myfunc(x, y).nargs)
class myfunc(Function):
@classmethod
def eval(cls, *x): # star args
return
assert myfunc.nargs == S.Naturals0
assert myfunc(x).nargs == S.Naturals0
def test_nargs():
f = Function('f')
assert f.nargs == S.Naturals0
assert f(1).nargs == S.Naturals0
assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2)
assert sin.nargs == FiniteSet(1)
assert sin(2).nargs == FiniteSet(1)
assert log.nargs == FiniteSet(1, 2)
assert log(2).nargs == FiniteSet(1, 2)
assert Function('f', nargs=2).nargs == FiniteSet(2)
assert Function('f', nargs=0).nargs == FiniteSet(0)
assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1)
assert Function('f', nargs=None).nargs == S.Naturals0
raises(ValueError, lambda: Function('f', nargs=()))
def test_arity():
f = lambda x, y: 1
assert arity(f) == 2
def f(x, y, z=None):
pass
assert arity(f) == (2, 3)
assert arity(lambda *x: x) is None
assert arity(log) == (1, 2)
def test_Lambda():
e = Lambda(x, x**2)
assert e(4) == 16
assert e(x) == x**2
assert e(y) == y**2
assert Lambda((), 42)() == 42
assert unchanged(Lambda, (), 42)
assert Lambda((), 42) != Lambda((), 43)
assert Lambda((), f(x))() == f(x)
assert Lambda((), 42).nargs == FiniteSet(0)
assert unchanged(Lambda, (x,), x**2)
assert Lambda(x, x**2) == Lambda((x,), x**2)
assert Lambda(x, x**2) == Lambda(y, y**2)
assert Lambda(x, x**2) != Lambda(y, y**2 + 1)
assert Lambda((x, y), x**y) == Lambda((y, x), y**x)
assert Lambda((x, y), x**y) != Lambda((x, y), y**x)
assert Lambda((x, y), x**y)(x, y) == x**y
assert Lambda((x, y), x**y)(3, 3) == 3**3
assert Lambda((x, y), x**y)(x, 3) == x**3
assert Lambda((x, y), x**y)(3, y) == 3**y
assert Lambda(x, f(x))(x) == f(x)
assert Lambda(x, x**2)(e(x)) == x**4
assert e(e(x)) == x**4
x1, x2 = (Indexed('x', i) for i in (1, 2))
assert Lambda((x1, x2), x1 + x2)(x, y) == x + y
assert Lambda((x, y), x + y).nargs == FiniteSet(2)
p = x, y, z, t
assert Lambda(p, t*(x + y + z))(*p) == t * (x + y + z)
assert Lambda(x, 2*x) + Lambda(y, 2*y) == 2*Lambda(x, 2*x)
assert Lambda(x, 2*x) not in [ Lambda(x, x) ]
raises(BadSignatureError, lambda: Lambda(1, x))
assert Lambda(x, 1)(1) is S.One
raises(BadSignatureError, lambda: Lambda((x, x), x + 2))
raises(BadSignatureError, lambda: Lambda(((x, x), y), x))
raises(BadSignatureError, lambda: Lambda(((y, x), x), x))
raises(BadSignatureError, lambda: Lambda(((y, 1), 2), x))
with warns_deprecated_sympy():
assert Lambda([x, y], x+y) == Lambda((x, y), x+y)
flam = Lambda( ((x, y),) , x + y)
assert flam((2, 3)) == 5
flam = Lambda( ((x, y), z) , x + y + z)
assert flam((2, 3), 1) == 6
flam = Lambda( (((x,y),z),) , x+y+z)
assert flam( ((2,3),1) ) == 6
raises(BadArgumentsError, lambda: flam(1, 2, 3))
flam = Lambda( (x,), (x, x))
assert flam(1,) == (1, 1)
assert flam((1,)) == ((1,), (1,))
flam = Lambda( ((x,),) , (x, x))
raises(BadArgumentsError, lambda: flam(1))
assert flam((1,)) == (1, 1)
# Previously TypeError was raised so this is potentially needed for
# backwards compatibility.
assert issubclass(BadSignatureError, TypeError)
assert issubclass(BadArgumentsError, TypeError)
# These are tested to see they don't raise:
hash(Lambda(x, 2*x))
hash(Lambda(x, x)) # IdentityFunction subclass
def test_IdentityFunction():
assert Lambda(x, x) is Lambda(y, y) is S.IdentityFunction
assert Lambda(x, 2*x) is not S.IdentityFunction
assert Lambda((x, y), x) is not S.IdentityFunction
def test_Lambda_symbols():
assert Lambda(x, 2*x).free_symbols == set()
assert Lambda(x, x*y).free_symbols == {y}
assert Lambda((), 42).free_symbols == set()
assert Lambda((), x*y).free_symbols == {x,y}
def test_functionclas_symbols():
assert f.free_symbols == set()
def test_Lambda_arguments():
raises(TypeError, lambda: Lambda(x, 2*x)(x, y))
raises(TypeError, lambda: Lambda((x, y), x + y)(x))
raises(TypeError, lambda: Lambda((), 42)(x))
def test_Lambda_equality():
assert Lambda(x, 2*x) == Lambda(y, 2*y)
# although variables are casts as Dummies, the expressions
# should still compare equal
assert Lambda((x, y), 2*x) == Lambda((x, y), 2*x)
assert Lambda(x, 2*x) != Lambda((x, y), 2*x)
assert Lambda(x, 2*x) != 2*x
def test_Subs():
assert Subs(1, (), ()) is S.One
# check null subs influence on hashing
assert Subs(x, y, z) != Subs(x, y, 1)
# neutral subs works
assert Subs(x, x, 1).subs(x, y).has(y)
# self mapping var/point
assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x)
assert Subs(x, x, 0).has(x) # it's a structural answer
assert not Subs(x, x, 0).free_symbols
assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1))
assert Subs(x, (x,), (0,)) == Subs(x, x, 0)
assert Subs(x, x, 0) == Subs(y, y, 0)
assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0)
assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0)
assert Subs(f(x), x, 0).doit() == f(0)
assert Subs(f(x**2), x**2, 0).doit() == f(0)
assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \
Subs(f(x, y, z), (x, y, z), (0, 0, 1))
assert Subs(x, y, 2).subs(x, y).doit() == 2
assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \
Subs(f(x, y) + z, (x, y, z), (0, 1, 0))
assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1)
assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1)
raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1)))
raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1)))
assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2
assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1)
assert Subs(f(x), x, 0) == Subs(f(y), y, 0)
assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0))
assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1))
assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1))
assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2)
assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y
assert Subs(f(x), x, 0).free_symbols == set([])
assert Subs(f(x, y), x, z).free_symbols == {y, z}
assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0)
assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0)
assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \
2*Subs(Derivative(f(x, 2), x), x, 0)
assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0)
e = Subs(y**2*f(x), x, y)
assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y)
assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0)
e1 = Subs(z*f(x), x, 1)
e2 = Subs(z*f(y), y, 1)
assert e1 + e2 == 2*e1
assert e1.__hash__() == e2.__hash__()
assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ]
assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x))
assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x),
x, x + y)
assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \
Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \
z + Rational('1/2').n(2)*f(0)
assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0)
assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0)
assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
).doit() == 2*exp(x)
assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
).doit(deep=False) == 2*Derivative(exp(x), x)
assert Derivative(f(x, g(x)), x).doit() == Derivative(
f(x, g(x)), g(x))*Derivative(g(x), x) + Subs(Derivative(
f(y, g(x)), y), y, x)
def test_doitdoit():
done = Derivative(f(x, g(x)), x, g(x)).doit()
assert done == done.doit()
@XFAIL
def test_Subs2():
# this reflects a limitation of subs(), probably won't fix
assert Subs(f(x), x**2, x).doit() == f(sqrt(x))
def test_expand_function():
assert expand(x + y) == x + y
assert expand(x + y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y)
assert expand((x + y)**11, modulus=11) == x**11 + y**11
def test_function_comparable():
assert sin(x).is_comparable is False
assert cos(x).is_comparable is False
assert sin(Float('0.1')).is_comparable is True
assert cos(Float('0.1')).is_comparable is True
assert sin(E).is_comparable is True
assert cos(E).is_comparable is True
assert sin(Rational(1, 3)).is_comparable is True
assert cos(Rational(1, 3)).is_comparable is True
def test_function_comparable_infinities():
assert sin(oo).is_comparable is False
assert sin(-oo).is_comparable is False
assert sin(zoo).is_comparable is False
assert sin(nan).is_comparable is False
def test_deriv1():
# These all require derivatives evaluated at a point (issue 4719) to work.
# See issue 4624
assert f(2*x).diff(x) == 2*Subs(Derivative(f(x), x), x, 2*x)
assert (f(x)**3).diff(x) == 3*f(x)**2*f(x).diff(x)
assert (f(2*x)**3).diff(x) == 6*f(2*x)**2*Subs(
Derivative(f(x), x), x, 2*x)
assert f(2 + x).diff(x) == Subs(Derivative(f(x), x), x, x + 2)
assert f(2 + 3*x).diff(x) == 3*Subs(
Derivative(f(x), x), x, 3*x + 2)
assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs(
Derivative(f(x), x), x, 3*sin(x))
# See issue 8510
assert f(x, x + z).diff(x) == (
Subs(Derivative(f(y, x + z), y), y, x) +
Subs(Derivative(f(x, y), y), y, x + z))
assert f(x, x**2).diff(x) == (
2*x*Subs(Derivative(f(x, y), y), y, x**2) +
Subs(Derivative(f(y, x**2), y), y, x))
# but Subs is not always necessary
assert f(x, g(y)).diff(g(y)) == Derivative(f(x, g(y)), g(y))
def test_deriv2():
assert (x**3).diff(x) == 3*x**2
assert (x**3).diff(x, evaluate=False) != 3*x**2
assert (x**3).diff(x, evaluate=False) == Derivative(x**3, x)
assert diff(x**3, x) == 3*x**2
assert diff(x**3, x, evaluate=False) != 3*x**2
assert diff(x**3, x, evaluate=False) == Derivative(x**3, x)
def test_func_deriv():
assert f(x).diff(x) == Derivative(f(x), x)
# issue 4534
assert f(x, y).diff(x, y) - f(x, y).diff(y, x) == 0
assert Derivative(f(x, y), x, y).args[1:] == ((x, 1), (y, 1))
assert Derivative(f(x, y), y, x).args[1:] == ((y, 1), (x, 1))
assert (Derivative(f(x, y), x, y) - Derivative(f(x, y), y, x)).doit() == 0
def test_suppressed_evaluation():
a = sin(0, evaluate=False)
assert a != 0
assert a.func is sin
assert a.args == (0,)
def test_function_evalf():
def eq(a, b, eps):
return abs(a - b) < eps
assert eq(sin(1).evalf(15), Float("0.841470984807897"), 1e-13)
assert eq(
sin(2).evalf(25), Float("0.9092974268256816953960199", 25), 1e-23)
assert eq(sin(1 + I).evalf(
15), Float("1.29845758141598") + Float("0.634963914784736")*I, 1e-13)
assert eq(exp(1 + I).evalf(15), Float(
"1.46869393991588") + Float("2.28735528717884239")*I, 1e-13)
assert eq(exp(-0.5 + 1.5*I).evalf(15), Float(
"0.0429042815937374") + Float("0.605011292285002")*I, 1e-13)
assert eq(log(pi + sqrt(2)*I).evalf(
15), Float("1.23699044022052") + Float("0.422985442737893")*I, 1e-13)
assert eq(cos(100).evalf(15), Float("0.86231887228768"), 1e-13)
def test_extensibility_eval():
class MyFunc(Function):
@classmethod
def eval(cls, *args):
return (0, 0, 0)
assert MyFunc(0) == (0, 0, 0)
def test_function_non_commutative():
x = Symbol('x', commutative=False)
assert f(x).is_commutative is False
assert sin(x).is_commutative is False
assert exp(x).is_commutative is False
assert log(x).is_commutative is False
assert f(x).is_complex is False
assert sin(x).is_complex is False
assert exp(x).is_complex is False
assert log(x).is_complex is False
def test_function_complex():
x = Symbol('x', complex=True)
assert f(x).is_commutative is True
assert sin(x).is_commutative is True
assert exp(x).is_commutative is True
assert log(x).is_commutative is True
assert f(x).is_complex is True
assert sin(x).is_complex is True
assert exp(x).is_complex is True
assert log(x).is_complex is True
def test_function__eval_nseries():
n = Symbol('n')
assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2)
assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2)
assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2)
assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x**2) + O(x**2)
assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \
polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2)
raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None))
assert acos(1 - x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x) + O(x)
assert acos(1 + x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(-x) + O(x) # XXX: wrong, branch cuts
assert loggamma(1/x)._eval_nseries(x, 0, None) == \
log(x)/2 - log(x)/x - 1/x + O(1, x)
assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y)
# issue 6725:
assert expint(Rational(3, 2), -x)._eval_nseries(x, 5, None) == \
2 - 2*sqrt(pi)*sqrt(-x) - 2*x - x**2/3 - x**3/15 - x**4/84 + O(x**5)
assert sin(sqrt(x))._eval_nseries(x, 3, None) == \
sqrt(x) - x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + O(x**3)
def test_doit():
n = Symbol('n', integer=True)
f = Sum(2 * n * x, (n, 1, 3))
d = Derivative(f, x)
assert d.doit() == 12
assert d.doit(deep=False) == Sum(2*n, (n, 1, 3))
def test_evalf_default():
from sympy.functions.special.gamma_functions import polygamma
assert type(sin(4.0)) == Float
assert type(re(sin(I + 1.0))) == Float
assert type(im(sin(I + 1.0))) == Float
assert type(sin(4)) == sin
assert type(polygamma(2.0, 4.0)) == Float
assert type(sin(Rational(1, 4))) == sin
def test_issue_5399():
args = [x, y, S(2), S.Half]
def ok(a):
"""Return True if the input args for diff are ok"""
if not a:
return False
if a[0].is_Symbol is False:
return False
s_at = [i for i in range(len(a)) if a[i].is_Symbol]
n_at = [i for i in range(len(a)) if not a[i].is_Symbol]
# every symbol is followed by symbol or int
# every number is followed by a symbol
return (all(a[i + 1].is_Symbol or a[i + 1].is_Integer
for i in s_at if i + 1 < len(a)) and
all(a[i + 1].is_Symbol
for i in n_at if i + 1 < len(a)))
eq = x**10*y**8
for a in subsets(args):
for v in variations(a, len(a)):
if ok(v):
eq.diff(*v) # does not raise
else:
raises(ValueError, lambda: eq.diff(*v))
def test_derivative_numerically():
from random import random
z0 = random() + I*random()
assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15
def test_fdiff_argument_index_error():
from sympy.core.function import ArgumentIndexError
class myfunc(Function):
nargs = 1 # define since there is no eval routine
def fdiff(self, idx):
raise ArgumentIndexError
mf = myfunc(x)
assert mf.diff(x) == Derivative(mf, x)
raises(TypeError, lambda: myfunc(x, x))
def test_deriv_wrt_function():
x = f(t)
xd = diff(x, t)
xdd = diff(xd, t)
y = g(t)
yd = diff(y, t)
assert diff(x, t) == xd
assert diff(2 * x + 4, t) == 2 * xd
assert diff(2 * x + 4 + y, t) == 2 * xd + yd
assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y
assert diff(2 * x + 4 + y * x, x) == 2 + y
assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y +
8 * x * xd)
assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y +
8 * x * xd)
assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3
assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0
assert diff(sin(x), t) == xd * cos(x)
assert diff(exp(x), t) == xd * exp(x)
assert diff(sqrt(x), t) == xd / (2 * sqrt(x))
def test_diff_wrt_value():
assert Expr()._diff_wrt is False
assert x._diff_wrt is True
assert f(x)._diff_wrt is True
assert Derivative(f(x), x)._diff_wrt is True
assert Derivative(x**2, x)._diff_wrt is False
def test_diff_wrt():
fx = f(x)
dfx = diff(f(x), x)
ddfx = diff(f(x), x, x)
assert diff(sin(fx) + fx**2, fx) == cos(fx) + 2*fx
assert diff(sin(dfx) + dfx**2, dfx) == cos(dfx) + 2*dfx
assert diff(sin(ddfx) + ddfx**2, ddfx) == cos(ddfx) + 2*ddfx
assert diff(fx**2, dfx) == 0
assert diff(fx**2, ddfx) == 0
assert diff(dfx**2, fx) == 0
assert diff(dfx**2, ddfx) == 0
assert diff(ddfx**2, dfx) == 0
assert diff(fx*dfx*ddfx, fx) == dfx*ddfx
assert diff(fx*dfx*ddfx, dfx) == fx*ddfx
assert diff(fx*dfx*ddfx, ddfx) == fx*dfx
assert diff(f(x), x).diff(f(x)) == 0
assert (sin(f(x)) - cos(diff(f(x), x))).diff(f(x)) == cos(f(x))
assert diff(sin(fx), fx, x) == diff(sin(fx), x, fx)
# Chain rule cases
assert f(g(x)).diff(x) == \
Derivative(g(x), x)*Derivative(f(g(x)), g(x))
assert diff(f(g(x), h(y)), x) == \
Derivative(g(x), x)*Derivative(f(g(x), h(y)), g(x))
assert diff(f(g(x), h(x)), x) == (
Subs(Derivative(f(y, h(x)), y), y, g(x))*Derivative(g(x), x) +
Subs(Derivative(f(g(x), y), y), y, h(x))*Derivative(h(x), x))
assert f(
sin(x)).diff(x) == cos(x)*Subs(Derivative(f(x), x), x, sin(x))
assert diff(f(g(x)), g(x)) == Derivative(f(g(x)), g(x))
def test_diff_wrt_func_subs():
assert f(g(x)).diff(x).subs(g, Lambda(x, 2*x)).doit() == f(2*x).diff(x)
def test_subs_in_derivative():
expr = sin(x*exp(y))
u = Function('u')
v = Function('v')
assert Derivative(expr, y).subs(expr, y) == Derivative(y, y)
assert Derivative(expr, y).subs(y, x).doit() == \
Derivative(expr, y).doit().subs(y, x)
assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x)
assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y)
assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit()
assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y))
assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y))
assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \
Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit()
assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z)
assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y))
assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \
Derivative(f(g(x), u(y)), u(y))
assert Derivative(f(x, f(x, x)), f(x, x)).subs(
f, Lambda((x, y), x + y)) == Subs(
Derivative(z + x, z), z, 2*x)
assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x))
assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x))
# Issue 13791. No comparison (it's a long formula) but this used to raise an exception.
assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr)
# This is also related to issues 13791 and 13795; issue 15190
F = Lambda((x, y), exp(2*x + 3*y))
abstract = f(x, f(x, x)).diff(x, 2)
concrete = F(x, F(x, x)).diff(x, 2)
assert (abstract.subs(f, F).doit() - concrete).simplify() == 0
# don't introduce a new symbol if not necessary
assert x in f(x).diff(x).subs(x, 0).atoms()
# case (4)
assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y)
) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y))
assert Derivative(f(x, x), x).subs(x, 0
) == Subs(Derivative(f(x, x), x), x, 0)
# issue 15194
assert Derivative(f(y, g(x)), (x, z)).subs(z, x
) == Derivative(f(y, g(x)), (x, x))
df = f(x).diff(x)
assert df.subs(df, 1) is S.One
assert df.diff(df) is S.One
dxy = Derivative(f(x, y), x, y)
dyx = Derivative(f(x, y), y, x)
assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One
assert dxy.diff(dyx) is S.One
assert Derivative(f(x, y), x, 2, y, 3).subs(
dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2)
assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs(
Derivative(f(x, x - y), y), x, x + y)
def test_diff_wrt_not_allowed():
# issue 7027 included
for wrt in (
cos(x), re(x), x**2, x*y, 1 + x,
Derivative(cos(x), x), Derivative(f(f(x)), x)):
raises(ValueError, lambda: diff(f(x), wrt))
# if we don't differentiate wrt then don't raise error
assert diff(exp(x*y), x*y, 0) == exp(x*y)
def test_klein_gordon_lagrangian():
m = Symbol('m')
phi = f(x, t)
L = -(diff(phi, t)**2 - diff(phi, x)**2 - m**2*phi**2)/2
eqna = Eq(
diff(L, phi) - diff(L, diff(phi, x), x) - diff(L, diff(phi, t), t), 0)
eqnb = Eq(diff(phi, t, t) - diff(phi, x, x) + m**2*phi, 0)
assert eqna == eqnb
def test_sho_lagrangian():
m = Symbol('m')
k = Symbol('k')
x = f(t)
L = m*diff(x, t)**2/2 - k*x**2/2
eqna = Eq(diff(L, x), diff(L, diff(x, t), t))
eqnb = Eq(-k*x, m*diff(x, t, t))
assert eqna == eqnb
assert diff(L, x, t) == diff(L, t, x)
assert diff(L, diff(x, t), t) == m*diff(x, t, 2)
assert diff(L, t, diff(x, t)) == -k*x + m*diff(x, t, 2)
def test_straight_line():
F = f(x)
Fd = F.diff(x)
L = sqrt(1 + Fd**2)
assert diff(L, F) == 0
assert diff(L, Fd) == Fd/sqrt(1 + Fd**2)
def test_sort_variable():
vsort = Derivative._sort_variable_count
def vsort0(*v, **kw):
reverse = kw.get('reverse', False)
return [i[0] for i in vsort([(i, 0) for i in (
reversed(v) if reverse else v)])]
for R in range(2):
assert vsort0(y, x, reverse=R) == [x, y]
assert vsort0(f(x), x, reverse=R) == [x, f(x)]
assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)]
assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)]
assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)]
fx = f(x).diff(x)
assert vsort0(fx, y, reverse=R) == [y, fx]
fy = f(y).diff(y)
assert vsort0(fy, fx, reverse=R) == [fx, fy]
fxx = fx.diff(x)
assert vsort0(fxx, fx, reverse=R) == [fx, fxx]
assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)]
assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)]
assert vsort0(Basic(y, z), Basic(x), reverse=R) == [
Basic(x), Basic(y, z)]
assert vsort0(fx, x, reverse=R) == [
x, fx] if R else [fx, x]
assert vsort0(Basic(x), x, reverse=R) == [
x, Basic(x)] if R else [Basic(x), x]
assert vsort0(Basic(f(x)), f(x), reverse=R) == [
f(x), Basic(f(x))] if R else [Basic(f(x)), f(x)]
assert vsort0(Basic(x, z), Basic(x), reverse=R) == [
Basic(x), Basic(x, z)] if R else [Basic(x, z), Basic(x)]
assert vsort([]) == []
assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)])
assert vsort([(x, y), (x, z)]) == [(x, y + z)]
assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)]
# coverage complete; legacy tests below
assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [
(f(x), 1), (g(x), 1), (h(x), 1)]
assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1),
(f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1),
(h(x), 1)]
assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1),
(y, 1), (f(x), 1), (f(y), 1)]
assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1),
(h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1),
(f(x), 1), (g(x), 1), (h(x), 1)]
assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1),
(g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)]
assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2),
(g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3),
(z, 4), (f(x), 3), (g(x), 1)]
assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)]
assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple)
assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)]
assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [
(f(x), 1), (g(x), 1), (h(y), 1)]
assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)]
assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [
(f(x), 2), (f(y), 1)]
dfx = f(x).diff(x)
self = [(dfx, 1), (x, 1)]
assert vsort(self) == self
assert vsort([
(dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [
(y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)]
dfy = f(y).diff(y)
assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)]
d2fx = dfx.diff(x)
assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)]
def test_multiple_derivative():
# Issue #15007
assert f(x, y).diff(y, y, x, y, x
) == Derivative(f(x, y), (x, 2), (y, 3))
def test_unhandled():
class MyExpr(Expr):
def _eval_derivative(self, s):
if not s.name.startswith('xi'):
return self
else:
return None
eq = MyExpr(f(x), y, z)
assert diff(eq, x, y, f(x), z) == Derivative(eq, f(x))
assert diff(eq, f(x), x) == Derivative(eq, f(x))
assert f(x, y).diff(x,(y, z)) == Derivative(f(x, y), x, (y, z))
assert f(x, y).diff(x,(y, 0)) == Derivative(f(x, y), x)
def test_nfloat():
from sympy.core.basic import _aresame
from sympy.polys.rootoftools import rootof
x = Symbol("x")
eq = x**Rational(4, 3) + 4*x**(S.One/3)/3
assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(S.One/3))
assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
eq = x**Rational(4, 3) + 4*x**(x/3)/3
assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(x/3))
big = 12345678901234567890
# specify precision to match value used in nfloat
Float_big = Float(big, 15)
assert _aresame(nfloat(big), Float_big)
assert _aresame(nfloat(big*x), Float_big*x)
assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))
# issue 6342
f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139)))
# issue 6632
assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
9.99999999800000e-11
# issue 7122
eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0)
assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'
# issue 10933
for t in (dict, Dict):
d = t({S.Half: S.Half})
n = nfloat(d)
assert isinstance(n, t)
assert _aresame(list(n.items()).pop(), (S.Half, Float(.5)))
for t in (dict, Dict):
d = t({S.Half: S.Half})
n = nfloat(d, dkeys=True)
assert isinstance(n, t)
assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5)))
d = [S.Half]
n = nfloat(d)
assert type(n) is list
assert _aresame(n[0], Float(.5))
assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5))
assert _aresame(nfloat(S(True)), S(True))
assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5))
assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false
# pass along kwargs
assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}]
def test_issue_7068():
from sympy.abc import a, b
f = Function('f')
y1 = Dummy('y')
y2 = Dummy('y')
func1 = f(a + y1 * b)
func2 = f(a + y2 * b)
func1_y = func1.diff(y1)
func2_y = func2.diff(y2)
assert func1_y != func2_y
z1 = Subs(f(a), a, y1)
z2 = Subs(f(a), a, y2)
assert z1 != z2
def test_issue_7231():
from sympy.abc import a
ans1 = f(x).series(x, a)
res = (f(a) + (-a + x)*Subs(Derivative(f(y), y), y, a) +
(-a + x)**2*Subs(Derivative(f(y), y, y), y, a)/2 +
(-a + x)**3*Subs(Derivative(f(y), y, y, y),
y, a)/6 +
(-a + x)**4*Subs(Derivative(f(y), y, y, y, y),
y, a)/24 +
(-a + x)**5*Subs(Derivative(f(y), y, y, y, y, y),
y, a)/120 + O((-a + x)**6, (x, a)))
assert res == ans1
ans2 = f(x).series(x, a)
assert res == ans2
def test_issue_7687():
from sympy.core.function import Function
from sympy.abc import x
f = Function('f')(x)
ff = Function('f')(x)
match_with_cache = ff.matches(f)
assert isinstance(f, type(ff))
clear_cache()
ff = Function('f')(x)
assert isinstance(f, type(ff))
assert match_with_cache == ff.matches(f)
def test_issue_7688():
from sympy.core.function import Function, UndefinedFunction
f = Function('f') # actually an UndefinedFunction
clear_cache()
class A(UndefinedFunction):
pass
a = A('f')
assert isinstance(a, type(f))
def test_mexpand():
from sympy.abc import x
assert _mexpand(None) is None
assert _mexpand(1) is S.One
assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand()
def test_issue_8469():
# This should not take forever to run
N = 40
def g(w, theta):
return 1/(1+exp(w-theta))
ws = symbols(['w%i'%i for i in range(N)])
import functools
expr = functools.reduce(g, ws)
assert isinstance(expr, Pow)
def test_issue_12996():
# foo=True imitates the sort of arguments that Derivative can get
# from Integral when it passes doit to the expression
assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x)
def test_should_evalf():
# This should not take forever to run (see #8506)
assert isinstance(sin((1.0 + 1.0*I)**10000 + 1), sin)
def test_Derivative_as_finite_difference():
# Central 1st derivative at gridpoint
x, h = symbols('x h', real=True)
dfdx = f(x).diff(x)
assert (dfdx.as_finite_difference([x-2, x-1, x, x+1, x+2]) -
(S.One/12*(f(x-2)-f(x+2)) + Rational(2, 3)*(f(x+1)-f(x-1)))).simplify() == 0
# Central 1st derivative "half-way"
assert (dfdx.as_finite_difference() -
(f(x + S.Half)-f(x - S.Half))).simplify() == 0
assert (dfdx.as_finite_difference(h) -
(f(x + h/S(2))-f(x - h/S(2)))/h).simplify() == 0
assert (dfdx.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
(S(9)/(8*2*h)*(f(x+h) - f(x-h)) +
S.One/(24*2*h)*(f(x - 3*h) - f(x + 3*h)))).simplify() == 0
# One sided 1st derivative at gridpoint
assert (dfdx.as_finite_difference([0, 1, 2], 0) -
(Rational(-3, 2)*f(0) + 2*f(1) - f(2)/2)).simplify() == 0
assert (dfdx.as_finite_difference([x, x+h], x) -
(f(x+h) - f(x))/h).simplify() == 0
assert (dfdx.as_finite_difference([x-h, x, x+h], x-h) -
(-S(3)/(2*h)*f(x-h) + 2/h*f(x) -
S.One/(2*h)*f(x+h))).simplify() == 0
# One sided 1st derivative "half-way"
assert (dfdx.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h, x + 7*h])
- 1/(2*h)*(-S(11)/(12)*f(x-h) + S(17)/(24)*f(x+h)
+ Rational(3, 8)*f(x + 3*h) - Rational(5, 24)*f(x + 5*h)
+ S.One/24*f(x + 7*h))).simplify() == 0
d2fdx2 = f(x).diff(x, 2)
# Central 2nd derivative at gridpoint
assert (d2fdx2.as_finite_difference([x-h, x, x+h]) -
h**-2 * (f(x-h) + f(x+h) - 2*f(x))).simplify() == 0
assert (d2fdx2.as_finite_difference([x - 2*h, x-h, x, x+h, x + 2*h]) -
h**-2 * (Rational(-1, 12)*(f(x - 2*h) + f(x + 2*h)) +
Rational(4, 3)*(f(x+h) + f(x-h)) - Rational(5, 2)*f(x))).simplify() == 0
# Central 2nd derivative "half-way"
assert (d2fdx2.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
(2*h)**-2 * (S.Half*(f(x - 3*h) + f(x + 3*h)) -
S.Half*(f(x+h) + f(x-h)))).simplify() == 0
# One sided 2nd derivative at gridpoint
assert (d2fdx2.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) -
h**-2 * (2*f(x) - 5*f(x+h) +
4*f(x+2*h) - f(x+3*h))).simplify() == 0
# One sided 2nd derivative at "half-way"
assert (d2fdx2.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) -
(2*h)**-2 * (Rational(3, 2)*f(x-h) - Rational(7, 2)*f(x+h) + Rational(5, 2)*f(x + 3*h) -
S.Half*f(x + 5*h))).simplify() == 0
d3fdx3 = f(x).diff(x, 3)
# Central 3rd derivative at gridpoint
assert (d3fdx3.as_finite_difference() -
(-f(x - Rational(3, 2)) + 3*f(x - S.Half) -
3*f(x + S.Half) + f(x + Rational(3, 2)))).simplify() == 0
assert (d3fdx3.as_finite_difference(
[x - 3*h, x - 2*h, x-h, x, x+h, x + 2*h, x + 3*h]) -
h**-3 * (S.One/8*(f(x - 3*h) - f(x + 3*h)) - f(x - 2*h) +
f(x + 2*h) + Rational(13, 8)*(f(x-h) - f(x+h)))).simplify() == 0
# Central 3rd derivative at "half-way"
assert (d3fdx3.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
(2*h)**-3 * (f(x + 3*h)-f(x - 3*h) +
3*(f(x-h)-f(x+h)))).simplify() == 0
# One sided 3rd derivative at gridpoint
assert (d3fdx3.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) -
h**-3 * (f(x + 3*h)-f(x) + 3*(f(x+h)-f(x + 2*h)))).simplify() == 0
# One sided 3rd derivative at "half-way"
assert (d3fdx3.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) -
(2*h)**-3 * (f(x + 5*h)-f(x-h) +
3*(f(x+h)-f(x + 3*h)))).simplify() == 0
# issue 11007
y = Symbol('y', real=True)
d2fdxdy = f(x, y).diff(x, y)
ref0 = Derivative(f(x + S.Half, y), y) - Derivative(f(x - S.Half, y), y)
assert (d2fdxdy.as_finite_difference(wrt=x) - ref0).simplify() == 0
half = S.Half
xm, xp, ym, yp = x-half, x+half, y-half, y+half
ref2 = f(xm, ym) + f(xp, yp) - f(xp, ym) - f(xm, yp)
assert (d2fdxdy.as_finite_difference() - ref2).simplify() == 0
def test_issue_11159():
# Tests Application._eval_subs
expr1 = E
expr0 = expr1 * expr1
expr1 = expr0.subs(expr1,expr0)
assert expr0 == expr1
def test_issue_12005():
e1 = Subs(Derivative(f(x), x), x, x)
assert e1.diff(x) == Derivative(f(x), x, x)
e2 = Subs(Derivative(f(x), x), x, x**2 + 1)
assert e2.diff(x) == 2*x*Subs(Derivative(f(x), x, x), x, x**2 + 1)
e3 = Subs(Derivative(f(x) + y**2 - y, y), y, y**2)
assert e3.diff(y) == 4*y
e4 = Subs(Derivative(f(x + y), y), y, (x**2))
assert e4.diff(y) is S.Zero
e5 = Subs(Derivative(f(x), x), (y, z), (y, z))
assert e5.diff(x) == Derivative(f(x), x, x)
assert f(g(x)).diff(g(x), g(x)) == Derivative(f(g(x)), g(x), g(x))
def test_issue_13843():
x = symbols('x')
f = Function('f')
m, n = symbols('m n', integer=True)
assert Derivative(Derivative(f(x), (x, m)), (x, n)) == Derivative(f(x), (x, m + n))
assert Derivative(Derivative(f(x), (x, m+5)), (x, n+3)) == Derivative(f(x), (x, m + n + 8))
assert Derivative(f(x), (x, n)).doit() == Derivative(f(x), (x, n))
def test_order_could_be_zero():
x, y = symbols('x, y')
n = symbols('n', integer=True, nonnegative=True)
m = symbols('m', integer=True, positive=True)
assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True))
assert diff(y, (x, n + 1)) is S.Zero
assert diff(y, (x, m)) is S.Zero
def test_undefined_function_eq():
f = Function('f')
f2 = Function('f')
g = Function('g')
f_real = Function('f', is_real=True)
# This test may only be meaningful if the cache is turned off
assert f == f2
assert hash(f) == hash(f2)
assert f == f
assert f != g
assert f != f_real
def test_function_assumptions():
x = Symbol('x')
f = Function('f')
f_real = Function('f', real=True)
f_real1 = Function('f', real=1)
f_real_inherit = Function(Symbol('f', real=True))
assert f_real == f_real1 # assumptions are sanitized
assert f != f_real
assert f(x) != f_real(x)
assert f(x).is_real is None
assert f_real(x).is_real is True
assert f_real_inherit(x).is_real is True and f_real_inherit.name == 'f'
# Can also do it this way, but it won't be equal to f_real because of the
# way UndefinedFunction.__new__ works. Any non-recognized assumptions
# are just added literally as something which is used in the hash
f_real2 = Function('f', is_real=True)
assert f_real2(x).is_real is True
def test_undef_fcn_float_issue_6938():
f = Function('ceil')
assert not f(0.3).is_number
f = Function('sin')
assert not f(0.3).is_number
assert not f(pi).evalf().is_number
x = Symbol('x')
assert not f(x).evalf(subs={x:1.2}).is_number
def test_undefined_function_eval():
# Issue 15170. Make sure UndefinedFunction with eval defined works
# properly. The issue there was that the hash was determined before _nargs
# was set, which is included in the hash, hence changing the hash. The
# class is added to sympy.core.core.all_classes before the hash is
# changed, meaning "temp in all_classes" would fail, causing sympify(temp(t))
# to give a new class. We will eventually remove all_classes, but make
# sure this continues to work.
fdiff = lambda self, argindex=1: cos(self.args[argindex - 1])
eval = classmethod(lambda cls, t: None)
_imp_ = classmethod(lambda cls, t: sin(t))
temp = Function('temp', fdiff=fdiff, eval=eval, _imp_=_imp_)
expr = temp(t)
assert sympify(expr) == expr
assert type(sympify(expr)).fdiff.__name__ == "<lambda>"
assert expr.diff(t) == cos(t)
def test_issue_15241():
F = f(x)
Fx = F.diff(x)
assert (F + x*Fx).diff(x, Fx) == 2
assert (F + x*Fx).diff(Fx, x) == 1
assert (x*F + x*Fx*F).diff(F, x) == x*Fx.diff(x) + Fx + 1
assert (x*F + x*Fx*F).diff(x, F) == x*Fx.diff(x) + Fx + 1
y = f(x)
G = f(y)
Gy = G.diff(y)
assert (G + y*Gy).diff(y, Gy) == 2
assert (G + y*Gy).diff(Gy, y) == 1
assert (y*G + y*Gy*G).diff(G, y) == y*Gy.diff(y) + Gy + 1
assert (y*G + y*Gy*G).diff(y, G) == y*Gy.diff(y) + Gy + 1
def test_issue_15226():
assert Subs(Derivative(f(y), x, y), y, g(x)).doit() != 0
def test_issue_7027():
for wrt in (cos(x), re(x), Derivative(cos(x), x)):
raises(ValueError, lambda: diff(f(x), wrt))
def test_derivative_quick_exit():
assert f(x).diff(y) == 0
assert f(x).diff(y, f(x)) == 0
assert f(x).diff(x, f(y)) == 0
assert f(f(x)).diff(x, f(x), f(y)) == 0
assert f(f(x)).diff(x, f(x), y) == 0
assert f(x).diff(g(x)) == 0
assert f(x).diff(x, f(x).diff(x)) == 1
df = f(x).diff(x)
assert f(x).diff(df) == 0
dg = g(x).diff(x)
assert dg.diff(df).doit() == 0
def test_issue_15084_13166():
eq = f(x, g(x))
assert eq.diff((g(x), y)) == Derivative(f(x, g(x)), (g(x), y))
# issue 13166
assert eq.diff(x, 2).doit() == (
(Derivative(f(x, g(x)), (g(x), 2))*Derivative(g(x), x) +
Subs(Derivative(f(x, _xi_2), _xi_2, x), _xi_2, g(x)))*Derivative(g(x),
x) + Derivative(f(x, g(x)), g(x))*Derivative(g(x), (x, 2)) +
Derivative(g(x), x)*Subs(Derivative(f(_xi_1, g(x)), _xi_1, g(x)),
_xi_1, x) + Subs(Derivative(f(_xi_1, g(x)), (_xi_1, 2)), _xi_1, x))
# issue 6681
assert diff(f(x, t, g(x, t)), x).doit() == (
Derivative(f(x, t, g(x, t)), g(x, t))*Derivative(g(x, t), x) +
Subs(Derivative(f(_xi_1, t, g(x, t)), _xi_1), _xi_1, x))
# make sure the order doesn't matter when using diff
assert eq.diff(x, g(x)) == eq.diff(g(x), x)
def test_negative_counts():
# issue 13873
raises(ValueError, lambda: sin(x).diff(x, -1))
def test_Derivative__new__():
raises(TypeError, lambda: f(x).diff((x, 2), 0))
assert f(x, y).diff([(x, y), 0]) == f(x, y)
assert f(x, y).diff([(x, y), 1]) == NDimArray([
Derivative(f(x, y), x), Derivative(f(x, y), y)])
assert f(x,y).diff(y, (x, z), y, x) == Derivative(
f(x, y), (x, z + 1), (y, 2))
assert Matrix([x]).diff(x, 2) == Matrix([0]) # is_zero exit
def test_issue_14719_10150():
class V(Expr):
_diff_wrt = True
is_scalar = False
assert V().diff(V()) == Derivative(V(), V())
assert (2*V()).diff(V()) == 2*Derivative(V(), V())
class X(Expr):
_diff_wrt = True
assert X().diff(X()) == 1
assert (2*X()).diff(X()) == 2
def test_noncommutative_issue_15131():
x = Symbol('x', commutative=False)
t = Symbol('t', commutative=False)
fx = Function('Fx', commutative=False)(x)
ft = Function('Ft', commutative=False)(t)
A = Symbol('A', commutative=False)
eq = fx * A * ft
eqdt = eq.diff(t)
assert eqdt.args[-1] == ft.diff(t)
def test_Subs_Derivative():
a = Derivative(f(g(x), h(x)), g(x), h(x),x)
b = Derivative(Derivative(f(g(x), h(x)), g(x), h(x)),x)
c = f(g(x), h(x)).diff(g(x), h(x), x)
d = f(g(x), h(x)).diff(g(x), h(x)).diff(x)
e = Derivative(f(g(x), h(x)), x)
eqs = (a, b, c, d, e)
subs = lambda arg: arg.subs(f, Lambda((x, y), exp(x + y))
).subs(g(x), 1/x).subs(h(x), x**3)
ans = 3*x**2*exp(1/x)*exp(x**3) - exp(1/x)*exp(x**3)/x**2
assert all(subs(i).doit().expand() == ans for i in eqs)
assert all(subs(i.doit()).doit().expand() == ans for i in eqs)
def test_issue_15360():
f = Function('f')
assert f.name == 'f'
def test_issue_15947():
assert f._diff_wrt is False
raises(TypeError, lambda: f(f))
raises(TypeError, lambda: f(x).diff(f))
def test_Derivative_free_symbols():
f = Function('f')
n = Symbol('n', integer=True, positive=True)
assert diff(f(x), (x, n)).free_symbols == {n, x}
|
6c559f23606b8dc1bf933a57929d415dc61e169aba3743c35f145da1b6cb1d7b | from sympy import Symbol, Function, exp, sqrt, Rational, I, cos, tan, S
from sympy.utilities.pytest import XFAIL
def test_add_eval():
a = Symbol("a")
b = Symbol("b")
c = Rational(1)
p = Rational(5)
assert a*b + c + p == a*b + 6
assert c + a + p == a + 6
assert c + a - p == a + (-4)
assert a + a == 2*a
assert a + p + a == 2*a + 5
assert c + p == Rational(6)
assert b + a - b == a
def test_addmul_eval():
a = Symbol("a")
b = Symbol("b")
c = Rational(1)
p = Rational(5)
assert c + a + b*c + a - p == 2*a + b + (-4)
assert a*2 + p + a == a*2 + 5 + a
assert a*2 + p + a == 3*a + 5
assert a*2 + a == 3*a
def test_pow_eval():
# XXX Pow does not fully support conversion of negative numbers
# to their complex equivalent
assert sqrt(-1) == I
assert sqrt(-4) == 2*I
assert sqrt( 4) == 2
assert (8)**Rational(1, 3) == 2
assert (-8)**Rational(1, 3) == 2*((-1)**Rational(1, 3))
assert sqrt(-2) == I*sqrt(2)
assert (-1)**Rational(1, 3) != I
assert (-10)**Rational(1, 3) != I*((10)**Rational(1, 3))
assert (-2)**Rational(1, 4) != (2)**Rational(1, 4)
assert 64**Rational(1, 3) == 4
assert 64**Rational(2, 3) == 16
assert 24/sqrt(64) == 3
assert (-27)**Rational(1, 3) == 3*(-1)**Rational(1, 3)
assert (cos(2) / tan(2))**2 == (cos(2) / tan(2))**2
@XFAIL
def test_pow_eval_X1():
assert (-1)**Rational(1, 3) == S.Half + S.Half*I*sqrt(3)
def test_mulpow_eval():
x = Symbol('x')
assert sqrt(50)/(sqrt(2)*x) == 5/x
assert sqrt(27)/sqrt(3) == 3
def test_evalpow_bug():
x = Symbol("x")
assert 1/(1/x) == x
assert 1/(-1/x) == -x
def test_symbol_expand():
x = Symbol('x')
y = Symbol('y')
f = x**4*y**4
assert f == x**4*y**4
assert f == f.expand()
g = (x*y)**4
assert g == f
assert g.expand() == f
assert g.expand() == g.expand().expand()
def test_function():
f, l = map(Function, 'fl')
x = Symbol('x')
assert exp(l(x))*l(x)/exp(l(x)) == l(x)
assert exp(f(x))*f(x)/exp(f(x)) == f(x)
|
45bcb4b2870b736658b969b382a0e5fcf894da0b2047db6a14bdc80f54edf1e1 | from sympy import Integer, S, symbols, Mul
from sympy.core.operations import AssocOp, LatticeOp
from sympy.utilities.pytest import raises
from sympy.core.sympify import SympifyError
from sympy.core.add import Add
# create the simplest possible Lattice class
class join(LatticeOp):
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert join(join(2, 3), 4) == join(2, join(3, 4))
assert join(2, 3) == join(3, 2)
assert join(0, 2) == 0
assert join(1, 2) == 2
assert join(2, 2) == 2
assert join(join(2, 3), 4) == join(2, 3, 4)
assert join() == 1
assert join(4) == 4
assert join(1, 4, 2, 3, 1, 3, 2) == join(2, 3, 4)
def test_lattice_shortcircuit():
raises(SympifyError, lambda: join(object))
assert join(0, object) == 0
def test_lattice_print():
assert str(join(5, 4, 3, 2)) == 'join(2, 3, 4, 5)'
def test_lattice_make_args():
assert join.make_args(join(2, 3, 4)) == {S(2), S(3), S(4)}
assert join.make_args(0) == {0}
assert list(join.make_args(0))[0] is S.Zero
assert Add.make_args(0)[0] is S.Zero
def test_issue_14025():
a, b, c, d = symbols('a,b,c,d', commutative=False)
assert Mul(a, b, c).has(c*b) == False
assert Mul(a, b, c).has(b*c) == True
assert Mul(a, b, c, d).has(b*c*d) == True
def test_AssocOp_flatten():
a, b, c, d = symbols('a,b,c,d')
class MyAssoc(AssocOp):
identity = S.One
assert MyAssoc(a, MyAssoc(b, c)).args == \
MyAssoc(MyAssoc(a, b), c).args == \
MyAssoc(MyAssoc(a, b, c)).args == \
MyAssoc(a, b, c).args == \
(a, b, c)
u = MyAssoc(b, c)
v = MyAssoc(u, d, evaluate=False)
assert v.args == (u, d)
# like Add, any unevaluated outer call will flatten inner args
assert MyAssoc(a, v).args == (a, b, c, d)
|
713063366ca44e0c1585f4c44d899500e79a93174c996aeeff7bdbc0bb108a02 | from sympy import (S, Symbol, sqrt, I, Integer, Rational, cos, sin, im, re, Abs,
exp, sinh, cosh, tan, tanh, conjugate, sign, cot, coth, pi, symbols,
expand_complex, Pow)
from sympy.core.expr import unchanged
def test_complex():
a = Symbol("a", real=True)
b = Symbol("b", real=True)
e = (a + I*b)*(a - I*b)
assert e.expand() == a**2 + b**2
assert sqrt(I) == Pow(I, S.Half)
def test_conjugate():
a = Symbol("a", real=True)
b = Symbol("b", real=True)
c = Symbol("c", imaginary=True)
d = Symbol("d", imaginary=True)
x = Symbol('x')
z = a + I*b + c + I*d
zc = a - I*b - c + I*d
assert conjugate(z) == zc
assert conjugate(exp(z)) == exp(zc)
assert conjugate(exp(I*x)) == exp(-I*conjugate(x))
assert conjugate(z**5) == zc**5
assert conjugate(abs(x)) == abs(x)
assert conjugate(sign(z)) == sign(zc)
assert conjugate(sin(z)) == sin(zc)
assert conjugate(cos(z)) == cos(zc)
assert conjugate(tan(z)) == tan(zc)
assert conjugate(cot(z)) == cot(zc)
assert conjugate(sinh(z)) == sinh(zc)
assert conjugate(cosh(z)) == cosh(zc)
assert conjugate(tanh(z)) == tanh(zc)
assert conjugate(coth(z)) == coth(zc)
def test_abs1():
a = Symbol("a", real=True)
b = Symbol("b", real=True)
assert abs(a) == Abs(a)
assert abs(-a) == abs(a)
assert abs(a + I*b) == sqrt(a**2 + b**2)
def test_abs2():
a = Symbol("a", real=False)
b = Symbol("b", real=False)
assert abs(a) != a
assert abs(-a) != a
assert abs(a + I*b) != sqrt(a**2 + b**2)
def test_evalc():
x = Symbol("x", real=True)
y = Symbol("y", real=True)
z = Symbol("z")
assert ((x + I*y)**2).expand(complex=True) == x**2 + 2*I*x*y - y**2
assert expand_complex(z**(2*I)) == (re((re(z) + I*im(z))**(2*I)) +
I*im((re(z) + I*im(z))**(2*I)))
assert expand_complex(
z**(2*I), deep=False) == I*im(z**(2*I)) + re(z**(2*I))
assert exp(I*x) != cos(x) + I*sin(x)
assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x)
assert exp(I*x + y).expand(complex=True) == exp(y)*cos(x) + I*sin(x)*exp(y)
assert sin(I*x).expand(complex=True) == I * sinh(x)
assert sin(x + I*y).expand(complex=True) == sin(x)*cosh(y) + \
I * sinh(y) * cos(x)
assert cos(I*x).expand(complex=True) == cosh(x)
assert cos(x + I*y).expand(complex=True) == cos(x)*cosh(y) - \
I * sinh(y) * sin(x)
assert tan(I*x).expand(complex=True) == tanh(x) * I
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)))
assert sinh(I*x).expand(complex=True) == I * sin(x)
assert sinh(x + I*y).expand(complex=True) == sinh(x)*cos(y) + \
I * sin(y) * cosh(x)
assert cosh(I*x).expand(complex=True) == cos(x)
assert cosh(x + I*y).expand(complex=True) == cosh(x)*cos(y) + \
I * sin(y) * sinh(x)
assert tanh(I*x).expand(complex=True) == tan(x) * I
assert tanh(x + I*y).expand(complex=True) == (
(sinh(x)*cosh(x) + I*cos(y)*sin(y)) /
(sinh(x)**2 + cos(y)**2)).expand()
def test_pythoncomplex():
x = Symbol("x")
assert 4j*x != 4*x*I
assert 4j*x == 4.0*x*I
assert 4.1j*x != 4*x*I
def test_rootcomplex():
R = Rational
assert ((+1 + I)**R(1, 2)).expand(
complex=True) == 2**R(1, 4)*cos( pi/8) + 2**R(1, 4)*sin( pi/8)*I
assert ((-1 - I)**R(1, 2)).expand(
complex=True) == 2**R(1, 4)*cos(3*pi/8) - 2**R(1, 4)*sin(3*pi/8)*I
assert (sqrt(-10)*I).as_real_imag() == (-sqrt(10), 0)
def test_expand_inverse():
assert (1/(1 + I)).expand(complex=True) == (1 - I)/2
assert ((1 + 2*I)**(-2)).expand(complex=True) == (-3 - 4*I)/25
assert ((1 + I)**(-8)).expand(complex=True) == Rational(1, 16)
def test_expand_complex():
assert ((2 + 3*I)**10).expand(complex=True) == -341525 - 145668*I
# the following two tests are to ensure the SymPy uses an efficient
# algorithm for calculating powers of complex numbers. They should execute
# in something like 0.01s.
assert ((2 + 3*I)**1000).expand(complex=True) == \
-81079464736246615951519029367296227340216902563389546989376269312984127074385455204551402940331021387412262494620336565547972162814110386834027871072723273110439771695255662375718498785908345629702081336606863762777939617745464755635193139022811989314881997210583159045854968310911252660312523907616129080027594310008539817935736331124833163907518549408018652090650537035647520296539436440394920287688149200763245475036722326561143851304795139005599209239350981457301460233967137708519975586996623552182807311159141501424576682074392689622074945519232029999 + \
46938745946789557590804551905243206242164799136976022474337918748798900569942573265747576032611189047943842446167719177749107138603040963603119861476016947257034472364028585381714774667326478071264878108114128915685688115488744955550920239128462489496563930809677159214598114273887061533057125164518549173898349061972857446844052995037423459472376202251620778517659247970283904820245958198842631651569984310559418135975795868314764489884749573052997832686979294085577689571149679540256349988338406458116270429842222666345146926395233040564229555893248370000*I
assert ((2 + 3*I/4)**1000).expand(complex=True) == \
Integer(1)*37079892761199059751745775382463070250205990218394308874593455293485167797989691280095867197640410033222367257278387021789651672598831503296531725827158233077451476545928116965316544607115843772405184272449644892857783761260737279675075819921259597776770965829089907990486964515784097181964312256560561065607846661496055417619388874421218472707497847700629822858068783288579581649321248495739224020822198695759609598745114438265083593711851665996586461937988748911532242908776883696631067311443171682974330675406616373422505939887984366289623091300746049101284856530270685577940283077888955692921951247230006346681086274961362500646889925803654263491848309446197554307105991537357310209426736453173441104334496173618419659521888945605315751089087820455852582920963561495787655250624781448951403353654348109893478206364632640344111022531861683064175862889459084900614967785405977231549003280842218501570429860550379522498497412180001/114813069527425452423283320117768198402231770208869520047764273682576626139237031385665948631650626991844596463898746277344711896086305533142593135616665318539129989145312280000688779148240044871428926990063486244781615463646388363947317026040466353970904996558162398808944629605623311649536164221970332681344168908984458505602379484807914058900934776500429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786419432054508915275783882625175435528800822842770817965453762184851149029376 + \
I*421638390580169706973991429333213477486930178424989246669892530737775352519112934278994501272111385966211392610029433824534634841747911783746811994443436271013377059560245191441549885048056920190833693041257216263519792201852046825443439142932464031501882145407459174948712992271510309541474392303461939389368955986650538525895866713074543004916049550090364398070215427272240155060576252568700906004691224321432509053286859100920489253598392100207663785243368195857086816912514025693453058403158416856847185079684216151337200057494966741268925263085619240941610301610538225414050394612058339070756009433535451561664522479191267503989904464718368605684297071150902631208673621618217106272361061676184840810762902463998065947687814692402219182668782278472952758690939877465065070481351343206840649517150634973307937551168752642148704904383991876969408056379195860410677814566225456558230131911142229028179902418223009651437985670625/1793954211366022694113801876840128100034871409513586250746316776290259783425578615401030447369541046747571819748417910583511123376348523955353017744010395602173906080395504375010762174191250701116076984219741972574712741619474818186676828531882286780795390571221287481389759837587864244524002565968286448146002639202882164150037179450123657170327105882819203167448541028601906377066191895183769810676831353109303069033234715310287563158747705988305326397404720186258671215368588625611876280581509852855552819149745718992630449787803625851701801184123166018366180137512856918294030710215034138299203584
assert ((2 + 3*I)**-1000).expand(complex=True) == \
Integer(1)*-81079464736246615951519029367296227340216902563389546989376269312984127074385455204551402940331021387412262494620336565547972162814110386834027871072723273110439771695255662375718498785908345629702081336606863762777939617745464755635193139022811989314881997210583159045854968310911252660312523907616129080027594310008539817935736331124833163907518549408018652090650537035647520296539436440394920287688149200763245475036722326561143851304795139005599209239350981457301460233967137708519975586996623552182807311159141501424576682074392689622074945519232029999/8777125472973511649630750050295188683351430110097915876250894978429797369155961290321829625004920141758416719066805645579710744290541337680113772670040386863849283653078324415471816788604945889094925784900885812724984087843737442111926413818245854362613018058774368703971604921858023116665586358870612944209398056562604561248859926344335598822815885851096698226775053153403320782439987679978321289537645645163767251396759519805603090332694449553371530571613352311006350058217982509738362083094920649452123351717366337410243853659113315547584871655479914439219520157174729130746351059075207407866012574386726064196992865627149566238044625779078186624347183905913357718850537058578084932880569701242598663149911276357125355850792073635533676541250531086757377369962506979378337216411188347761901006460813413505861461267545723590468627854202034450569581626648934062198718362303420281555886394558137408159453103395918783625713213314350531051312551733021627153081075080140680608080529736975658786227362251632725009435866547613598753584705455955419696609282059191031962604169242974038517575645939316377801594539335940001 - Integer(1)*46938745946789557590804551905243206242164799136976022474337918748798900569942573265747576032611189047943842446167719177749107138603040963603119861476016947257034472364028585381714774667326478071264878108114128915685688115488744955550920239128462489496563930809677159214598114273887061533057125164518549173898349061972857446844052995037423459472376202251620778517659247970283904820245958198842631651569984310559418135975795868314764489884749573052997832686979294085577689571149679540256349988338406458116270429842222666345146926395233040564229555893248370000*I/8777125472973511649630750050295188683351430110097915876250894978429797369155961290321829625004920141758416719066805645579710744290541337680113772670040386863849283653078324415471816788604945889094925784900885812724984087843737442111926413818245854362613018058774368703971604921858023116665586358870612944209398056562604561248859926344335598822815885851096698226775053153403320782439987679978321289537645645163767251396759519805603090332694449553371530571613352311006350058217982509738362083094920649452123351717366337410243853659113315547584871655479914439219520157174729130746351059075207407866012574386726064196992865627149566238044625779078186624347183905913357718850537058578084932880569701242598663149911276357125355850792073635533676541250531086757377369962506979378337216411188347761901006460813413505861461267545723590468627854202034450569581626648934062198718362303420281555886394558137408159453103395918783625713213314350531051312551733021627153081075080140680608080529736975658786227362251632725009435866547613598753584705455955419696609282059191031962604169242974038517575645939316377801594539335940001
assert ((2 + 3*I/4)**-1000).expand(complex=True) == \
Integer(1)*4257256305661027385394552848555894604806501409793288342610746813288539790051927148781268212212078237301273165351052934681382567968787279534591114913777456610214738290619922068269909423637926549603264174216950025398244509039145410016404821694746262142525173737175066432954496592560621330313807235750500564940782099283410261748370262433487444897446779072067625787246390824312580440138770014838135245148574339248259670887549732495841810961088930810608893772914812838358159009303794863047635845688453859317690488124382253918725010358589723156019888846606295866740117645571396817375322724096486161308083462637370825829567578309445855481578518239186117686659177284332344643124760453112513611749309168470605289172320376911472635805822082051716625171429727162039621902266619821870482519063133136820085579315127038372190224739238686708451840610064871885616258831386810233957438253532027049148030157164346719204500373766157143311767338973363806106967439378604898250533766359989107510507493549529158818602327525235240510049484816090584478644771183158342479140194633579061295740839490629457435283873180259847394582069479062820225159699506175855369539201399183443253793905149785994830358114153241481884290274629611529758663543080724574566578220908907477622643689220814376054314972190402285121776593824615083669045183404206291739005554569305329760211752815718335731118664756831942466773261465213581616104242113894521054475516019456867271362053692785300826523328020796670205463390909136593859765912483565093461468865534470710132881677639651348709376/2103100954337624833663208713697737151593634525061637972297915388685604042449504336765884978184588688426595940401280828953096857809292320006227881797146858511436638446932833617514351442216409828605662238790280753075176269765767010004889778647709740770757817960711900340755635772183674511158570690702969774966791073165467918123298694584729211212414462628433370481195120564586361368504153395406845170075275051749019600057116719726628746724489572189061061036426955163696859127711110719502594479795200686212257570291758725259007379710596548777812659422174199194837355646482046783616494013289495563083118517507178847555801163089723056310287760875135196081975602765511153122381201303871673391366630940702817360340900568748719988954847590748960761446218262344767250783946365392689256634180417145926390656439421745644011831124277463643383712803287985472471755648426749842410972650924240795946699346613614779460399530274263580007672855851663196114585312432954432654691485867618908420370875753749297487803461900447407917655296784879220450937110470920633595689721819488638484547259978337741496090602390463594556401615298457456112485536498177883358587125449801777718900375736758266215245325999241624148841915093787519330809347240990363802360596034171167818310322276373120180985148650099673289383722502488957717848531612020897298448601714154586319660314294591620415272119454982220034319689607295960162971300417552364254983071768070124456169427638371140064235083443242844616326538396503937972586505546495649094344512270582463639152160238137952390380581401171977159154009407415523525096743009110916334144716516647041176989758534635251844947906038080852185583742296318878233394998111078843229681030277039104786225656992262073797524057992347971177720807155842376332851559276430280477639539393920006008737472164850104411971830120295750221200029811143140323763349636629725073624360001 - Integer(1)*3098214262599218784594285246258841485430681674561917573155883806818465520660668045042109232930382494608383663464454841313154390741655282039877410154577448327874989496074260116195788919037407420625081798124301494353693248757853222257918294662198297114746822817460991242508743651430439120439020484502408313310689912381846149597061657483084652685283853595100434135149479564507015504022249330340259111426799121454516345905101620532787348293877485702600390665276070250119465888154331218827342488849948540687659846652377277250614246402784754153678374932540789808703029043827352976139228402417432199779415751301480406673762521987999573209628597459357964214510139892316208670927074795773830798600837815329291912002136924506221066071242281626618211060464126372574400100990746934953437169840312584285942093951405864225230033279614235191326102697164613004299868695519642598882914862568516635347204441042798206770888274175592401790040170576311989738272102077819127459014286741435419468254146418098278519775722104890854275995510700298782146199325790002255362719776098816136732897323406228294203133323296591166026338391813696715894870956511298793595675308998014158717167429941371979636895553724830981754579086664608880698350866487717403917070872269853194118364230971216854931998642990452908852258008095741042117326241406479532880476938937997238098399302185675832474590293188864060116934035867037219176916416481757918864533515526389079998129329045569609325290897577497835388451456680707076072624629697883854217331728051953671643278797380171857920000*I/2103100954337624833663208713697737151593634525061637972297915388685604042449504336765884978184588688426595940401280828953096857809292320006227881797146858511436638446932833617514351442216409828605662238790280753075176269765767010004889778647709740770757817960711900340755635772183674511158570690702969774966791073165467918123298694584729211212414462628433370481195120564586361368504153395406845170075275051749019600057116719726628746724489572189061061036426955163696859127711110719502594479795200686212257570291758725259007379710596548777812659422174199194837355646482046783616494013289495563083118517507178847555801163089723056310287760875135196081975602765511153122381201303871673391366630940702817360340900568748719988954847590748960761446218262344767250783946365392689256634180417145926390656439421745644011831124277463643383712803287985472471755648426749842410972650924240795946699346613614779460399530274263580007672855851663196114585312432954432654691485867618908420370875753749297487803461900447407917655296784879220450937110470920633595689721819488638484547259978337741496090602390463594556401615298457456112485536498177883358587125449801777718900375736758266215245325999241624148841915093787519330809347240990363802360596034171167818310322276373120180985148650099673289383722502488957717848531612020897298448601714154586319660314294591620415272119454982220034319689607295960162971300417552364254983071768070124456169427638371140064235083443242844616326538396503937972586505546495649094344512270582463639152160238137952390380581401171977159154009407415523525096743009110916334144716516647041176989758534635251844947906038080852185583742296318878233394998111078843229681030277039104786225656992262073797524057992347971177720807155842376332851559276430280477639539393920006008737472164850104411971830120295750221200029811143140323763349636629725073624360001
a = Symbol('a', real=True)
b = Symbol('b', real=True)
assert exp(a*(2 + I*b)).expand(complex=True) == \
I*exp(2*a)*sin(a*b) + exp(2*a)*cos(a*b)
def test_expand():
f = (16 - 2*sqrt(29))**2
assert f.expand() == 372 - 64*sqrt(29)
f = (Integer(1)/2 + I/2)**10
assert f.expand() == I/32
f = (Integer(1)/2 + I)**10
assert f.expand() == Integer(237)/1024 - 779*I/256
def test_re_im1652():
x = Symbol('x')
assert re(x) == re(conjugate(x))
assert im(x) == - im(conjugate(x))
assert im(x)*re(conjugate(x)) + im(conjugate(x)) * re(x) == 0
def test_issue_5084():
x = Symbol('x')
assert ((x + x*I)/(1 + I)).as_real_imag() == (re((x + I*x)/(1 + I)
), im((x + I*x)/(1 + I)))
def test_issue_5236():
assert (cos(1 + I)**3).as_real_imag() == (-3*sin(1)**2*sinh(1)**2*cos(1)*cosh(1) +
cos(1)**3*cosh(1)**3, -3*cos(1)**2*cosh(1)**2*sin(1)*sinh(1) + sin(1)**3*sinh(1)**3)
def test_real_imag():
x, y, z = symbols('x, y, z')
X, Y, Z = symbols('X, Y, Z', commutative=False)
a = Symbol('a', real=True)
assert (2*a*x).as_real_imag() == (2*a*re(x), 2*a*im(x))
# issue 5395:
assert (x*x.conjugate()).as_real_imag() == (Abs(x)**2, 0)
assert im(x*x.conjugate()) == 0
assert im(x*y.conjugate()*z*y) == im(x*z)*Abs(y)**2
assert im(x*y.conjugate()*x*y) == im(x**2)*Abs(y)**2
assert im(Z*y.conjugate()*X*y) == im(Z*X)*Abs(y)**2
assert im(X*X.conjugate()) == im(X*X.conjugate(), evaluate=False)
assert (sin(x)*sin(x).conjugate()).as_real_imag() == \
(Abs(sin(x))**2, 0)
# issue 6573:
assert (x**2).as_real_imag() == (re(x)**2 - im(x)**2, 2*re(x)*im(x))
# issue 6428:
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
assert (i*r*x).as_real_imag() == (I*i*r*im(x), -I*i*r*re(x))
assert (i*r*x*(y + 2)).as_real_imag() == (
I*i*r*(re(y) + 2)*im(x) + I*i*r*re(x)*im(y),
-I*i*r*(re(y) + 2)*re(x) + I*i*r*im(x)*im(y))
# issue 7106:
assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
assert ((1 + 2*I)*(1 + 3*I)).as_real_imag() == (-5, 5)
def test_pow_issue_1724():
e = ((S.NegativeOne)**(S.One/3))
assert e.conjugate().n() == e.n().conjugate()
e = S('-2/3 - (-29/54 + sqrt(93)/18)**(1/3) - 1/(9*(-29/54 + sqrt(93)/18)**(1/3))')
assert e.conjugate().n() == e.n().conjugate()
e = 2**I
assert e.conjugate().n() == e.n().conjugate()
def test_issue_5429():
assert sqrt(I).conjugate() != sqrt(I)
def test_issue_4124():
from sympy import oo
assert expand_complex(I*oo) == oo*I
def test_issue_11518():
x = Symbol("x", real=True)
y = Symbol("y", real=True)
r = sqrt(x**2 + y**2)
assert conjugate(r) == r
s = abs(x + I * y)
assert conjugate(s) == r
|
9e4935df59f215ab15d36deba1cc38e62d45e5ff0bb6f55cdf7040b07e6189fe | from sympy import (log, sqrt, Rational as R, Symbol, I, exp, pi, S,
cos, sin, Mul, Pow, O)
from sympy.simplify.radsimp import expand_numer
from sympy.core.function import expand, expand_multinomial, expand_power_base
from sympy.core.compatibility import range
from sympy.utilities.pytest import raises
from sympy.utilities.randtest 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, 3)/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_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
|
4efa32af656ce3e7155b61195c5f47efbe646b82391582df60a611a5ffe8615b | """Tests for tools for manipulating of large commutative expressions. """
from sympy import (S, Add, sin, Mul, Symbol, oo, Integral, sqrt, Tuple, I,
Function, Interval, O, symbols, simplify, collect, Sum,
Basic, Dict, root, exp, cos, Dummy, log, Rational)
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.utilities.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})
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(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(1, 3*y + 3*x*y), Tuple(1, 3))) == \
Basic((1, 3*y*(x + 1)), (1, 3))
# but we shouldn't change keys of a dictionary or some may be lost
assert gcd_terms(Dict((x*(1 + y), 2), (x + x*y, y + x*y))) == \
Dict({x*(y + 1): 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))
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(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 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
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 import Symbol, Range, Sum
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})
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
|
ced72bffdeffcc5b870e63c0ae65e0851f25a39e2aa042979d1f43d6bc60dd49 | from sympy.core import (
Rational, Symbol, S, Float, Integer, Mul, Number, Pow,
Basic, I, nan, pi, E, symbols, oo, zoo, Rational)
from sympy.core.tests.test_evalf import NS
from sympy.core.function import expand_multinomial
from sympy.functions.elementary.miscellaneous import sqrt, cbrt
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.special.error_functions import erf
from sympy.functions.elementary.trigonometric import (
sin, cos, tan, sec, csc, sinh, cosh, tanh, atan)
from sympy.series.order import O
from sympy.utilities.pytest import XFAIL
def test_rational():
a = Rational(1, 5)
r = sqrt(5)/5
assert sqrt(a) == r
assert 2*sqrt(a) == 2*r
r = a*a**S.Half
assert a**Rational(3, 2) == r
assert 2*a**Rational(3, 2) == 2*r
r = a**5*a**Rational(2, 3)
assert a**Rational(17, 3) == r
assert 2 * a**Rational(17, 3) == 2*r
def test_large_rational():
e = (Rational(123712**12 - 1, 7) + Rational(1, 7))**Rational(1, 3)
assert e == 234232585392159195136 * (Rational(1, 7)**Rational(1, 3))
def test_negative_real():
def feq(a, b):
return abs(a - b) < 1E-10
assert feq(S.One / Float(-0.5), -Integer(2))
def test_expand():
x = Symbol('x')
assert (2**(-1 - x)).expand() == S.Half*2**(-x)
def test_issue_3449():
#test if powers are simplified correctly
#see also issue 3995
x = Symbol('x')
assert ((x**Rational(1, 3))**Rational(2)) == x**Rational(2, 3)
assert (
(x**Rational(3))**Rational(2, 5)) == (x**Rational(3))**Rational(2, 5)
a = Symbol('a', real=True)
b = Symbol('b', real=True)
assert (a**2)**b == (abs(a)**b)**2
assert sqrt(1/a) != 1/sqrt(a) # e.g. for a = -1
assert (a**3)**Rational(1, 3) != a
assert (x**a)**b != x**(a*b) # e.g. x = -1, a=2, b=1/2
assert (x**.5)**b == x**(.5*b)
assert (x**.5)**.5 == x**.25
assert (x**2.5)**.5 != x**1.25 # e.g. for x = 5*I
k = Symbol('k', integer=True)
m = Symbol('m', integer=True)
assert (x**k)**m == x**(k*m)
assert Number(5)**Rational(2, 3) == Number(25)**Rational(1, 3)
assert (x**.5)**2 == x**1.0
assert (x**2)**k == (x**k)**2 == x**(2*k)
a = Symbol('a', positive=True)
assert (a**3)**Rational(2, 5) == a**Rational(6, 5)
assert (a**2)**b == (a**b)**2
assert (a**Rational(2, 3))**x == a**(x*Rational(2, 3)) != (a**x)**Rational(2, 3)
def test_issue_3866():
assert --sqrt(sqrt(5) - 1) == sqrt(sqrt(5) - 1)
def test_negative_one():
x = Symbol('x', complex=True)
y = Symbol('y', complex=True)
assert 1/x**y == x**(-y)
def test_issue_4362():
neg = Symbol('neg', negative=True)
nonneg = Symbol('nonneg', nonnegative=True)
any = Symbol('any')
num, den = sqrt(1/neg).as_numer_denom()
assert num == sqrt(-1)
assert den == sqrt(-neg)
num, den = sqrt(1/nonneg).as_numer_denom()
assert num == 1
assert den == sqrt(nonneg)
num, den = sqrt(1/any).as_numer_denom()
assert num == sqrt(1/any)
assert den == 1
def eqn(num, den, pow):
return (num/den)**pow
npos = 1
nneg = -1
dpos = 2 - sqrt(3)
dneg = 1 - sqrt(3)
assert dpos > 0 and dneg < 0 and npos > 0 and nneg < 0
# pos or neg integer
eq = eqn(npos, dpos, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2)
eq = eqn(npos, dneg, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2)
eq = eqn(nneg, dpos, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2)
eq = eqn(nneg, dneg, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2)
eq = eqn(npos, dpos, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1)
eq = eqn(npos, dneg, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1)
eq = eqn(nneg, dpos, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1)
eq = eqn(nneg, dneg, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1)
# pos or neg rational
pow = S.Half
eq = eqn(npos, dpos, pow)
assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow)
eq = eqn(npos, dneg, pow)
assert eq.is_Pow is False and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow)
eq = eqn(nneg, dpos, pow)
assert not eq.is_Pow or eq.as_numer_denom() == (nneg**pow, dpos**pow)
eq = eqn(nneg, dneg, pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow)
eq = eqn(npos, dpos, -pow)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, npos**pow)
eq = eqn(npos, dneg, -pow)
assert eq.is_Pow is False and eq.as_numer_denom() == (-(-npos)**pow*(-dneg)**pow, npos)
eq = eqn(nneg, dpos, -pow)
assert not eq.is_Pow or eq.as_numer_denom() == (dpos**pow, nneg**pow)
eq = eqn(nneg, dneg, -pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow)
# unknown exponent
pow = 2*any
eq = eqn(npos, dpos, pow)
assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow)
eq = eqn(npos, dneg, pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow)
eq = eqn(nneg, dpos, pow)
assert eq.is_Pow and eq.as_numer_denom() == (nneg**pow, dpos**pow)
eq = eqn(nneg, dneg, pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow)
eq = eqn(npos, dpos, -pow)
assert eq.as_numer_denom() == (dpos**pow, npos**pow)
eq = eqn(npos, dneg, -pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow)
eq = eqn(nneg, dpos, -pow)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, nneg**pow)
eq = eqn(nneg, dneg, -pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow)
x = Symbol('x')
y = Symbol('y')
assert ((1/(1 + x/3))**(-S.One)).as_numer_denom() == (3 + x, 3)
notp = Symbol('notp', positive=False) # not positive does not imply real
b = ((1 + x/notp)**-2)
assert (b**(-y)).as_numer_denom() == (1, b**y)
assert (b**(-S.One)).as_numer_denom() == ((notp + x)**2, notp**2)
nonp = Symbol('nonp', nonpositive=True)
assert (((1 + x/nonp)**-2)**(-S.One)).as_numer_denom() == ((-nonp -
x)**2, nonp**2)
n = Symbol('n', negative=True)
assert (x**n).as_numer_denom() == (1, x**-n)
assert sqrt(1/n).as_numer_denom() == (S.ImaginaryUnit, sqrt(-n))
n = Symbol('0 or neg', nonpositive=True)
# if x and n are split up without negating each term and n is negative
# then the answer might be wrong; if n is 0 it won't matter since
# 1/oo and 1/zoo are both zero as is sqrt(0)/sqrt(-x) unless x is also
# zero (in which case the negative sign doesn't matter):
# 1/sqrt(1/-1) = -I but sqrt(-1)/sqrt(1) = I
assert (1/sqrt(x/n)).as_numer_denom() == (sqrt(-n), sqrt(-x))
c = Symbol('c', complex=True)
e = sqrt(1/c)
assert e.as_numer_denom() == (e, 1)
i = Symbol('i', integer=True)
assert (((1 + x/y)**i)).as_numer_denom() == ((x + y)**i, y**i)
def test_Pow_signs():
"""Cf. issues 4595 and 5250"""
x = Symbol('x')
y = Symbol('y')
n = Symbol('n', even=True)
assert (3 - y)**2 != (y - 3)**2
assert (3 - y)**n != (y - 3)**n
assert (-3 + y - x)**2 != (3 - y + x)**2
assert (y - 3)**3 != -(3 - y)**3
def test_power_with_noncommutative_mul_as_base():
x = Symbol('x', commutative=False)
y = Symbol('y', commutative=False)
assert not (x*y)**3 == x**3*y**3
assert (2*x*y)**3 == 8*(x*y)**3
def test_power_rewrite_exp():
assert (I**I).rewrite(exp) == exp(-pi/2)
expr = (2 + 3*I)**(4 + 5*I)
assert expr.rewrite(exp) == exp((4 + 5*I)*(log(sqrt(13)) + I*atan(Rational(3, 2))))
assert expr.rewrite(exp).expand() == \
169*exp(5*I*log(13)/2)*exp(4*I*atan(Rational(3, 2)))*exp(-5*atan(Rational(3, 2)))
assert ((6 + 7*I)**5).rewrite(exp) == 7225*sqrt(85)*exp(5*I*atan(Rational(7, 6)))
expr = 5**(6 + 7*I)
assert expr.rewrite(exp) == exp((6 + 7*I)*log(5))
assert expr.rewrite(exp).expand() == 15625*exp(7*I*log(5))
assert Pow(123, 789, evaluate=False).rewrite(exp) == 123**789
assert (1**I).rewrite(exp) == 1**I
assert (0**I).rewrite(exp) == 0**I
expr = (-2)**(2 + 5*I)
assert expr.rewrite(exp) == exp((2 + 5*I)*(log(2) + I*pi))
assert expr.rewrite(exp).expand() == 4*exp(-5*pi)*exp(5*I*log(2))
assert ((-2)**S(-5)).rewrite(exp) == (-2)**S(-5)
x, y = symbols('x y')
assert (x**y).rewrite(exp) == exp(y*log(x))
assert (7**x).rewrite(exp) == exp(x*log(7), evaluate=False)
assert ((2 + 3*I)**x).rewrite(exp) == exp(x*(log(sqrt(13)) + I*atan(Rational(3, 2))))
assert (y**(5 + 6*I)).rewrite(exp) == exp(log(y)*(5 + 6*I))
assert all((1/func(x)).rewrite(exp) == 1/(func(x).rewrite(exp)) for func in
(sin, cos, tan, sec, csc, sinh, cosh, tanh))
def test_zero():
x = Symbol('x')
y = Symbol('y')
assert 0**x != 0
assert 0**(2*x) == 0**x
assert 0**(1.0*x) == 0**x
assert 0**(2.0*x) == 0**x
assert (0**(2 - x)).as_base_exp() == (0, 2 - x)
assert 0**(x - 2) != S.Infinity**(2 - x)
assert 0**(2*x*y) == 0**(x*y)
assert 0**(-2*x*y) == S.ComplexInfinity**(x*y)
def test_pow_as_base_exp():
x = Symbol('x')
assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x)
assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2)
p = S.Half**x
assert p.base, p.exp == p.as_base_exp() == (S(2), -x)
# issue 8344:
assert Pow(1, 2, evaluate=False).as_base_exp() == (S.One, S(2))
def test_issue_6100_12942_4473():
x = Symbol('x')
y = Symbol('y')
assert x**1.0 != x
assert x != x**1.0
assert True != x**1.0
assert x**1.0 is not True
assert x is not True
assert x*y != (x*y)**1.0
# Pow != Symbol
assert (x**1.0)**1.0 != x
assert (x**1.0)**2.0 != x**2
b = Basic()
assert Pow(b, 1.0, evaluate=False) != b
# if the following gets distributed as a Mul (x**1.0*y**1.0 then
# __eq__ methods could be added to Symbol and Pow to detect the
# power-of-1.0 case.
assert ((x*y)**1.0).func is Pow
def test_issue_6208():
from sympy import root, Rational
I = S.ImaginaryUnit
assert sqrt(33**(I*Rational(9, 10))) == -33**(I*Rational(9, 20))
assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3) # != 2*I/3
assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9
assert sqrt(exp(3*I)) == exp(I*Rational(3, 2))
assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I)
assert sqrt(exp(5*I)) == -exp(I*Rational(5, 2))
assert root(exp(5*I), 3).exp == Rational(1, 3)
def test_issue_6990():
x = Symbol('x')
a = Symbol('a')
b = Symbol('b')
assert (sqrt(a + b*x + x**2)).series(x, 0, 3).removeO() == \
b*x/(2*sqrt(a)) + x**2*(1/(2*sqrt(a)) - \
b**2/(8*a**Rational(3, 2))) + sqrt(a)
def test_issue_6068():
x = Symbol('x')
assert sqrt(sin(x)).series(x, 0, 7) == \
sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \
x**Rational(13, 2)/24192 + O(x**7)
assert sqrt(sin(x)).series(x, 0, 9) == \
sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \
x**Rational(13, 2)/24192 - 67*x**Rational(17, 2)/29030400 + O(x**9)
assert sqrt(sin(x**3)).series(x, 0, 19) == \
x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 + O(x**19)
assert sqrt(sin(x**3)).series(x, 0, 20) == \
x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 - \
x**Rational(39, 2)/24192 + O(x**20)
def test_issue_6782():
x = Symbol('x')
assert sqrt(sin(x**3)).series(x, 0, 7) == x**Rational(3, 2) + O(x**7)
assert sqrt(sin(x**4)).series(x, 0, 3) == x**2 + O(x**3)
def test_issue_6653():
x = Symbol('x')
assert (1 / sqrt(1 + sin(x**2))).series(x, 0, 3) == 1 - x**2/2 + O(x**3)
def test_issue_6429():
x = Symbol('x')
c = Symbol('c')
f = (c**2 + x)**(0.5)
assert f.series(x, x0=0, n=1) == (c**2)**0.5 + O(x)
assert f.taylor_term(0, x) == (c**2)**0.5
assert f.taylor_term(1, x) == 0.5*x*(c**2)**(-0.5)
assert f.taylor_term(2, x) == -0.125*x**2*(c**2)**(-1.5)
def test_issue_7638():
f = pi/log(sqrt(2))
assert ((1 + I)**(I*f/2))**0.3 == (1 + I)**(0.15*I*f)
# if 1/3 -> 1.0/3 this should fail since it cannot be shown that the
# sign will be +/-1; for the previous "small arg" case, it didn't matter
# that this could not be proved
assert (1 + I)**(4*I*f) == ((1 + I)**(12*I*f))**Rational(1, 3)
assert (((1 + I)**(I*(1 + 7*f)))**Rational(1, 3)).exp == Rational(1, 3)
r = symbols('r', real=True)
assert sqrt(r**2) == abs(r)
assert cbrt(r**3) != r
assert sqrt(Pow(2*I, 5*S.Half)) != (2*I)**Rational(5, 4)
p = symbols('p', positive=True)
assert cbrt(p**2) == p**Rational(2, 3)
assert NS(((0.2 + 0.7*I)**(0.7 + 1.0*I))**(0.5 - 0.1*I), 1) == '0.4 + 0.2*I'
assert sqrt(1/(1 + I)) == sqrt(1 - I)/sqrt(2) # or 1/sqrt(1 + I)
e = 1/(1 - sqrt(2))
assert sqrt(e) == I/sqrt(-1 + sqrt(2))
assert e**Rational(-1, 2) == -I*sqrt(-1 + sqrt(2))
assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp in [S.Half,
Rational(3, 2) + I/2]
assert sqrt(r**Rational(4, 3)) != r**Rational(2, 3)
assert sqrt((p + I)**Rational(4, 3)) == (p + I)**Rational(2, 3)
assert sqrt((p - p**2*I)**2) == p - p**2*I
assert sqrt((p + r*I)**2) != p + r*I
e = (1 + I/5)
assert sqrt(e**5) == e**(5*S.Half)
assert sqrt(e**6) == e**3
assert sqrt((1 + I*r)**6) != (1 + I*r)**3
def test_issue_8582():
assert 1**oo is nan
assert 1**(-oo) is nan
assert 1**zoo is nan
assert 1**(oo + I) is nan
assert 1**(1 + I*oo) is nan
assert 1**(oo + I*oo) is nan
def test_issue_8650():
n = Symbol('n', integer=True, nonnegative=True)
assert (n**n).is_positive is True
x = 5*n + 5
assert (x**(5*(n + 1))).is_positive is True
def test_issue_13914():
b = Symbol('b')
assert (-1)**zoo is nan
assert 2**zoo is nan
assert (S.Half)**(1 + zoo) is nan
assert I**(zoo + I) is nan
assert b**(I + zoo) is nan
def test_better_sqrt():
n = Symbol('n', integer=True, nonnegative=True)
assert sqrt(3 + 4*I) == 2 + I
assert sqrt(3 - 4*I) == 2 - I
assert sqrt(-3 - 4*I) == 1 - 2*I
assert sqrt(-3 + 4*I) == 1 + 2*I
assert sqrt(32 + 24*I) == 6 + 2*I
assert sqrt(32 - 24*I) == 6 - 2*I
assert sqrt(-32 - 24*I) == 2 - 6*I
assert sqrt(-32 + 24*I) == 2 + 6*I
# triple (3, 4, 5):
# parity of 3 matches parity of 5 and
# den, 4, is a square
assert sqrt((3 + 4*I)/4) == 1 + I/2
# triple (8, 15, 17)
# parity of 8 doesn't match parity of 17 but
# den/2, 8/2, is a square
assert sqrt((8 + 15*I)/8) == (5 + 3*I)/4
# handle the denominator
assert sqrt((3 - 4*I)/25) == (2 - I)/5
assert sqrt((3 - 4*I)/26) == (2 - I)/sqrt(26)
# mul
# issue #12739
assert sqrt((3 + 4*I)/(3 - 4*I)) == (3 + 4*I)/5
assert sqrt(2/(3 + 4*I)) == sqrt(2)/5*(2 - I)
assert sqrt(n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(2 - I)
assert sqrt(-2/(3 + 4*I)) == sqrt(2)/5*(1 + 2*I)
assert sqrt(-n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(1 + 2*I)
# power
assert sqrt(1/(3 + I*4)) == (2 - I)/5
assert sqrt(1/(3 - I)) == sqrt(10)*sqrt(3 + I)/10
# symbolic
i = symbols('i', imaginary=True)
assert sqrt(3/i) == Mul(sqrt(3), sqrt(-i)/abs(i), evaluate=False)
# multiples of 1/2; don't make this too automatic
assert sqrt((3 + 4*I))**3 == (2 + I)**3
assert Pow(3 + 4*I, Rational(3, 2)) == 2 + 11*I
assert Pow(6 + 8*I, Rational(3, 2)) == 2*sqrt(2)*(2 + 11*I)
n, d = (3 + 4*I), (3 - 4*I)**3
a = n/d
assert a.args == (1/d, n)
eq = sqrt(a)
assert eq.args == (a, S.Half)
assert expand_multinomial(eq) == sqrt((-117 + 44*I)*(3 + 4*I))/125
assert eq.expand() == (7 - 24*I)/125
# issue 12775
# pos im part
assert sqrt(2*I) == (1 + I)
assert sqrt(2*9*I) == Mul(3, 1 + I, evaluate=False)
assert Pow(2*I, 3*S.Half) == (1 + I)**3
# neg im part
assert sqrt(-I/2) == Mul(S.Half, 1 - I, evaluate=False)
# fractional im part
assert Pow(Rational(-9, 2)*I, Rational(3, 2)) == 27*(1 - I)**3/8
def test_issue_2993():
x = Symbol('x')
assert str((2.3*x - 4)**0.3) == '1.5157165665104*(0.575*x - 1)**0.3'
assert str((2.3*x + 4)**0.3) == '1.5157165665104*(0.575*x + 1)**0.3'
assert str((-2.3*x + 4)**0.3) == '1.5157165665104*(1 - 0.575*x)**0.3'
assert str((-2.3*x - 4)**0.3) == '1.5157165665104*(-0.575*x - 1)**0.3'
assert str((2.3*x - 2)**0.3) == '1.28386201800527*(x - 0.869565217391304)**0.3'
assert str((-2.3*x - 2)**0.3) == '1.28386201800527*(-x - 0.869565217391304)**0.3'
assert str((-2.3*x + 2)**0.3) == '1.28386201800527*(0.869565217391304 - x)**0.3'
assert str((2.3*x + 2)**0.3) == '1.28386201800527*(x + 0.869565217391304)**0.3'
assert str((2.3*x - 4)**Rational(1, 3)) == '1.5874010519682*(0.575*x - 1)**(1/3)'
eq = (2.3*x + 4)
assert eq**2 == 16.0*(0.575*x + 1)**2
assert (1/eq).args == (eq, -1) # don't change trivial power
def test_issue_17450():
assert (erf(cosh(1)**7)**I).is_real is None
assert (erf(cosh(1)**7)**I).is_imaginary is False
assert (Pow(exp(1+sqrt(2)), ((1-sqrt(2))*I*pi), evaluate=False)).is_real is None
assert ((-10)**(10*I*pi/3)).is_real is False
assert ((-5)**(4*I*pi)).is_real is False
|
cb19c64141258111be3f26891b5a5744fd2daed097d002b6414fa5de4eba098c | from sympy import I, sqrt, log, exp, sin, asin, factorial, Mod, pi
from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow
from sympy.core.facts import InconsistentAssumptions
from sympy import simplify
from sympy.core.compatibility import range
from sympy.utilities.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
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
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('a', 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
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)
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**r).is_algebraic
assert (a**x).is_algebraic is None
assert (na**r).is_algebraic is None
assert (ia**r).is_algebraic
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():
from sympy import Mul
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():
from sympy import Pow
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 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_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
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():
# complex -> finite | infinite
# with work on PR 16603 it may be changed in future to complex -> finite
x = Symbol('x', complex=True, finite=False)
y = Symbol('x', real=True, infinite=False)
assert x.is_infinite
assert y.is_finite
|
4ded4497dc5a39fb3e4fc73542d6e8f58610ae9db4cc0b390fff36b683232686 | from sympy.utilities.pytest import XFAIL, raises, warns_deprecated_sympy
from sympy import (S, Symbol, symbols, nan, oo, I, pi, Float, And, Or,
Not, Implies, Xor, zoo, sqrt, Rational, simplify, Function,
log, cos, sin, Add, floor, ceiling, trigsimp)
from sympy.core.compatibility import range
from sympy.core.relational import (Relational, Equality, Unequality,
GreaterThan, LessThan, StrictGreaterThan,
StrictLessThan, Rel, Eq, Lt, Le,
Gt, Ge, Ne)
from sympy.sets.sets import Interval, FiniteSet
from itertools import combinations
x, y, z, t = symbols('x,y,z,t')
def rel_check(a, b):
from sympy.utilities.pytest import raises
assert a.is_number and b.is_number
for do in range(len(set([type(a), type(b)]))):
if S.NaN in (a, b):
v = [(a == b), (a != b)]
assert len(set(v)) == 1 and v[0] == False
assert not (a != b) and not (a == b)
assert raises(TypeError, lambda: a < b)
assert raises(TypeError, lambda: a <= b)
assert raises(TypeError, lambda: a > b)
assert raises(TypeError, lambda: a >= b)
else:
E = [(a == b), (a != b)]
assert len(set(E)) == 2
v = [
(a < b), (a <= b), (a > b), (a >= b)]
i = [
[True, True, False, False],
[False, True, False, True], # <-- i == 1
[False, False, True, True]].index(v)
if i == 1:
assert E[0] or (a.is_Float != b.is_Float) # ugh
else:
assert E[1]
a, b = b, a
return True
def test_rel_ne():
assert Relational(x, y, '!=') == Ne(x, y)
# issue 6116
p = Symbol('p', positive=True)
assert Ne(p, 0) is S.true
def test_rel_subs():
e = Relational(x, y, '==')
e = e.subs(x, z)
assert isinstance(e, Equality)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '>=')
e = e.subs(x, z)
assert isinstance(e, GreaterThan)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '<=')
e = e.subs(x, z)
assert isinstance(e, LessThan)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '>')
e = e.subs(x, z)
assert isinstance(e, StrictGreaterThan)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '<')
e = e.subs(x, z)
assert isinstance(e, StrictLessThan)
assert e.lhs == z
assert e.rhs == y
e = Eq(x, 0)
assert e.subs(x, 0) is S.true
assert e.subs(x, 1) is S.false
def test_wrappers():
e = x + x**2
res = Relational(y, e, '==')
assert Rel(y, x + x**2, '==') == res
assert Eq(y, x + x**2) == res
res = Relational(y, e, '<')
assert Lt(y, x + x**2) == res
res = Relational(y, e, '<=')
assert Le(y, x + x**2) == res
res = Relational(y, e, '>')
assert Gt(y, x + x**2) == res
res = Relational(y, e, '>=')
assert Ge(y, x + x**2) == res
res = Relational(y, e, '!=')
assert Ne(y, x + x**2) == res
def test_Eq():
assert Eq(x, x) # issue 5719
with warns_deprecated_sympy():
assert Eq(x) == Eq(x, 0)
# issue 6116
p = Symbol('p', positive=True)
assert Eq(p, 0) is S.false
# issue 13348
assert Eq(True, 1) is S.false
assert Eq((), 1) is S.false
def test_rel_Infinity():
# NOTE: All of these are actually handled by sympy.core.Number, and do
# not create Relational objects.
assert (oo > oo) is S.false
assert (oo > -oo) is S.true
assert (oo > 1) is S.true
assert (oo < oo) is S.false
assert (oo < -oo) is S.false
assert (oo < 1) is S.false
assert (oo >= oo) is S.true
assert (oo >= -oo) is S.true
assert (oo >= 1) is S.true
assert (oo <= oo) is S.true
assert (oo <= -oo) is S.false
assert (oo <= 1) is S.false
assert (-oo > oo) is S.false
assert (-oo > -oo) is S.false
assert (-oo > 1) is S.false
assert (-oo < oo) is S.true
assert (-oo < -oo) is S.false
assert (-oo < 1) is S.true
assert (-oo >= oo) is S.false
assert (-oo >= -oo) is S.true
assert (-oo >= 1) is S.false
assert (-oo <= oo) is S.true
assert (-oo <= -oo) is S.true
assert (-oo <= 1) is S.true
def test_bool():
assert Eq(0, 0) is S.true
assert Eq(1, 0) is S.false
assert Ne(0, 0) is S.false
assert Ne(1, 0) is S.true
assert Lt(0, 1) is S.true
assert Lt(1, 0) is S.false
assert Le(0, 1) is S.true
assert Le(1, 0) is S.false
assert Le(0, 0) is S.true
assert Gt(1, 0) is S.true
assert Gt(0, 1) is S.false
assert Ge(1, 0) is S.true
assert Ge(0, 1) is S.false
assert Ge(1, 1) is S.true
assert Eq(I, 2) is S.false
assert Ne(I, 2) is S.true
raises(TypeError, lambda: Gt(I, 2))
raises(TypeError, lambda: Ge(I, 2))
raises(TypeError, lambda: Lt(I, 2))
raises(TypeError, lambda: Le(I, 2))
a = Float('.000000000000000000001', '')
b = Float('.0000000000000000000001', '')
assert Eq(pi + a, pi + b) is S.false
def test_rich_cmp():
assert (x < y) == Lt(x, y)
assert (x <= y) == Le(x, y)
assert (x > y) == Gt(x, y)
assert (x >= y) == Ge(x, y)
def test_doit():
from sympy import Symbol
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
np = Symbol('np', nonpositive=True)
nn = Symbol('nn', nonnegative=True)
assert Gt(p, 0).doit() is S.true
assert Gt(p, 1).doit() == Gt(p, 1)
assert Ge(p, 0).doit() is S.true
assert Le(p, 0).doit() is S.false
assert Lt(n, 0).doit() is S.true
assert Le(np, 0).doit() is S.true
assert Gt(nn, 0).doit() == Gt(nn, 0)
assert Lt(nn, 0).doit() is S.false
assert Eq(x, 0).doit() == Eq(x, 0)
def test_new_relational():
x = Symbol('x')
assert Eq(x, 0) == Relational(x, 0) # None ==> Equality
assert Eq(x, 0) == Relational(x, 0, '==')
assert Eq(x, 0) == Relational(x, 0, 'eq')
assert Eq(x, 0) == Equality(x, 0)
assert Eq(x, 0) != Relational(x, 1) # None ==> Equality
assert Eq(x, 0) != Relational(x, 1, '==')
assert Eq(x, 0) != Relational(x, 1, 'eq')
assert Eq(x, 0) != Equality(x, 1)
assert Eq(x, -1) == Relational(x, -1) # None ==> Equality
assert Eq(x, -1) == Relational(x, -1, '==')
assert Eq(x, -1) == Relational(x, -1, 'eq')
assert Eq(x, -1) == Equality(x, -1)
assert Eq(x, -1) != Relational(x, 1) # None ==> Equality
assert Eq(x, -1) != Relational(x, 1, '==')
assert Eq(x, -1) != Relational(x, 1, 'eq')
assert Eq(x, -1) != Equality(x, 1)
assert Ne(x, 0) == Relational(x, 0, '!=')
assert Ne(x, 0) == Relational(x, 0, '<>')
assert Ne(x, 0) == Relational(x, 0, 'ne')
assert Ne(x, 0) == Unequality(x, 0)
assert Ne(x, 0) != Relational(x, 1, '!=')
assert Ne(x, 0) != Relational(x, 1, '<>')
assert Ne(x, 0) != Relational(x, 1, 'ne')
assert Ne(x, 0) != Unequality(x, 1)
assert Ge(x, 0) == Relational(x, 0, '>=')
assert Ge(x, 0) == Relational(x, 0, 'ge')
assert Ge(x, 0) == GreaterThan(x, 0)
assert Ge(x, 1) != Relational(x, 0, '>=')
assert Ge(x, 1) != Relational(x, 0, 'ge')
assert Ge(x, 1) != GreaterThan(x, 0)
assert (x >= 1) == Relational(x, 1, '>=')
assert (x >= 1) == Relational(x, 1, 'ge')
assert (x >= 1) == GreaterThan(x, 1)
assert (x >= 0) != Relational(x, 1, '>=')
assert (x >= 0) != Relational(x, 1, 'ge')
assert (x >= 0) != GreaterThan(x, 1)
assert Le(x, 0) == Relational(x, 0, '<=')
assert Le(x, 0) == Relational(x, 0, 'le')
assert Le(x, 0) == LessThan(x, 0)
assert Le(x, 1) != Relational(x, 0, '<=')
assert Le(x, 1) != Relational(x, 0, 'le')
assert Le(x, 1) != LessThan(x, 0)
assert (x <= 1) == Relational(x, 1, '<=')
assert (x <= 1) == Relational(x, 1, 'le')
assert (x <= 1) == LessThan(x, 1)
assert (x <= 0) != Relational(x, 1, '<=')
assert (x <= 0) != Relational(x, 1, 'le')
assert (x <= 0) != LessThan(x, 1)
assert Gt(x, 0) == Relational(x, 0, '>')
assert Gt(x, 0) == Relational(x, 0, 'gt')
assert Gt(x, 0) == StrictGreaterThan(x, 0)
assert Gt(x, 1) != Relational(x, 0, '>')
assert Gt(x, 1) != Relational(x, 0, 'gt')
assert Gt(x, 1) != StrictGreaterThan(x, 0)
assert (x > 1) == Relational(x, 1, '>')
assert (x > 1) == Relational(x, 1, 'gt')
assert (x > 1) == StrictGreaterThan(x, 1)
assert (x > 0) != Relational(x, 1, '>')
assert (x > 0) != Relational(x, 1, 'gt')
assert (x > 0) != StrictGreaterThan(x, 1)
assert Lt(x, 0) == Relational(x, 0, '<')
assert Lt(x, 0) == Relational(x, 0, 'lt')
assert Lt(x, 0) == StrictLessThan(x, 0)
assert Lt(x, 1) != Relational(x, 0, '<')
assert Lt(x, 1) != Relational(x, 0, 'lt')
assert Lt(x, 1) != StrictLessThan(x, 0)
assert (x < 1) == Relational(x, 1, '<')
assert (x < 1) == Relational(x, 1, 'lt')
assert (x < 1) == StrictLessThan(x, 1)
assert (x < 0) != Relational(x, 1, '<')
assert (x < 0) != Relational(x, 1, 'lt')
assert (x < 0) != StrictLessThan(x, 1)
# finally, some fuzz testing
from random import randint
from sympy.core.compatibility import unichr
for i in range(100):
while 1:
strtype, length = (unichr, 65535) if randint(0, 1) else (chr, 255)
relation_type = strtype(randint(0, length))
if randint(0, 1):
relation_type += strtype(randint(0, length))
if relation_type not in ('==', 'eq', '!=', '<>', 'ne', '>=', 'ge',
'<=', 'le', '>', 'gt', '<', 'lt', ':=',
'+=', '-=', '*=', '/=', '%='):
break
raises(ValueError, lambda: Relational(x, 1, relation_type))
assert all(Relational(x, 0, op).rel_op == '==' for op in ('eq', '=='))
assert all(Relational(x, 0, op).rel_op == '!='
for op in ('ne', '<>', '!='))
assert all(Relational(x, 0, op).rel_op == '>' for op in ('gt', '>'))
assert all(Relational(x, 0, op).rel_op == '<' for op in ('lt', '<'))
assert all(Relational(x, 0, op).rel_op == '>=' for op in ('ge', '>='))
assert all(Relational(x, 0, op).rel_op == '<=' for op in ('le', '<='))
def test_relational_bool_output():
# https://github.com/sympy/sympy/issues/5931
raises(TypeError, lambda: bool(x > 3))
raises(TypeError, lambda: bool(x >= 3))
raises(TypeError, lambda: bool(x < 3))
raises(TypeError, lambda: bool(x <= 3))
raises(TypeError, lambda: bool(Eq(x, 3)))
raises(TypeError, lambda: bool(Ne(x, 3)))
def test_relational_logic_symbols():
# See issue 6204
assert (x < y) & (z < t) == And(x < y, z < t)
assert (x < y) | (z < t) == Or(x < y, z < t)
assert ~(x < y) == Not(x < y)
assert (x < y) >> (z < t) == Implies(x < y, z < t)
assert (x < y) << (z < t) == Implies(z < t, x < y)
assert (x < y) ^ (z < t) == Xor(x < y, z < t)
assert isinstance((x < y) & (z < t), And)
assert isinstance((x < y) | (z < t), Or)
assert isinstance(~(x < y), GreaterThan)
assert isinstance((x < y) >> (z < t), Implies)
assert isinstance((x < y) << (z < t), Implies)
assert isinstance((x < y) ^ (z < t), (Or, Xor))
def test_univariate_relational_as_set():
assert (x > 0).as_set() == Interval(0, oo, True, True)
assert (x >= 0).as_set() == Interval(0, oo)
assert (x < 0).as_set() == Interval(-oo, 0, True, True)
assert (x <= 0).as_set() == Interval(-oo, 0)
assert Eq(x, 0).as_set() == FiniteSet(0)
assert Ne(x, 0).as_set() == Interval(-oo, 0, True, True) + \
Interval(0, oo, True, True)
assert (x**2 >= 4).as_set() == Interval(-oo, -2) + Interval(2, oo)
@XFAIL
def test_multivariate_relational_as_set():
assert (x*y >= 0).as_set() == Interval(0, oo)*Interval(0, oo) + \
Interval(-oo, 0)*Interval(-oo, 0)
def test_Not():
assert Not(Equality(x, y)) == Unequality(x, y)
assert Not(Unequality(x, y)) == Equality(x, y)
assert Not(StrictGreaterThan(x, y)) == LessThan(x, y)
assert Not(StrictLessThan(x, y)) == GreaterThan(x, y)
assert Not(GreaterThan(x, y)) == StrictLessThan(x, y)
assert Not(LessThan(x, y)) == StrictGreaterThan(x, y)
def test_evaluate():
assert str(Eq(x, x, evaluate=False)) == 'Eq(x, x)'
assert Eq(x, x, evaluate=False).doit() == S.true
assert str(Ne(x, x, evaluate=False)) == 'Ne(x, x)'
assert Ne(x, x, evaluate=False).doit() == S.false
assert str(Ge(x, x, evaluate=False)) == 'x >= x'
assert str(Le(x, x, evaluate=False)) == 'x <= x'
assert str(Gt(x, x, evaluate=False)) == 'x > x'
assert str(Lt(x, x, evaluate=False)) == 'x < x'
def assert_all_ineq_raise_TypeError(a, b):
raises(TypeError, lambda: a > b)
raises(TypeError, lambda: a >= b)
raises(TypeError, lambda: a < b)
raises(TypeError, lambda: a <= b)
raises(TypeError, lambda: b > a)
raises(TypeError, lambda: b >= a)
raises(TypeError, lambda: b < a)
raises(TypeError, lambda: b <= a)
def assert_all_ineq_give_class_Inequality(a, b):
"""All inequality operations on `a` and `b` result in class Inequality."""
from sympy.core.relational import _Inequality as Inequality
assert isinstance(a > b, Inequality)
assert isinstance(a >= b, Inequality)
assert isinstance(a < b, Inequality)
assert isinstance(a <= b, Inequality)
assert isinstance(b > a, Inequality)
assert isinstance(b >= a, Inequality)
assert isinstance(b < a, Inequality)
assert isinstance(b <= a, Inequality)
def test_imaginary_compare_raises_TypeError():
# See issue #5724
assert_all_ineq_raise_TypeError(I, x)
def test_complex_compare_not_real():
# two cases which are not real
y = Symbol('y', imaginary=True)
z = Symbol('z', complex=True, extended_real=False)
for w in (y, z):
assert_all_ineq_raise_TypeError(2, w)
# some cases which should remain un-evaluated
t = Symbol('t')
x = Symbol('x', real=True)
z = Symbol('z', complex=True)
for w in (x, z, t):
assert_all_ineq_give_class_Inequality(2, w)
def test_imaginary_and_inf_compare_raises_TypeError():
# See pull request #7835
y = Symbol('y', imaginary=True)
assert_all_ineq_raise_TypeError(oo, y)
assert_all_ineq_raise_TypeError(-oo, y)
def test_complex_pure_imag_not_ordered():
raises(TypeError, lambda: 2*I < 3*I)
# more generally
x = Symbol('x', real=True, nonzero=True)
y = Symbol('y', imaginary=True)
z = Symbol('z', complex=True)
assert_all_ineq_raise_TypeError(I, y)
t = I*x # an imaginary number, should raise errors
assert_all_ineq_raise_TypeError(2, t)
t = -I*y # a real number, so no errors
assert_all_ineq_give_class_Inequality(2, t)
t = I*z # unknown, should be unevaluated
assert_all_ineq_give_class_Inequality(2, t)
def test_x_minus_y_not_same_as_x_lt_y():
"""
A consequence of pull request #7792 is that `x - y < 0` and `x < y`
are not synonymous.
"""
x = I + 2
y = I + 3
raises(TypeError, lambda: x < y)
assert x - y < 0
ineq = Lt(x, y, evaluate=False)
raises(TypeError, lambda: ineq.doit())
assert ineq.lhs - ineq.rhs < 0
t = Symbol('t', imaginary=True)
x = 2 + t
y = 3 + t
ineq = Lt(x, y, evaluate=False)
raises(TypeError, lambda: ineq.doit())
assert ineq.lhs - ineq.rhs < 0
# this one should give error either way
x = I + 2
y = 2*I + 3
raises(TypeError, lambda: x < y)
raises(TypeError, lambda: x - y < 0)
def test_nan_equality_exceptions():
# See issue #7774
import random
assert Equality(nan, nan) is S.false
assert Unequality(nan, nan) is S.true
# See issue #7773
A = (x, S.Zero, S.One/3, pi, oo, -oo)
assert Equality(nan, random.choice(A)) is S.false
assert Equality(random.choice(A), nan) is S.false
assert Unequality(nan, random.choice(A)) is S.true
assert Unequality(random.choice(A), nan) is S.true
def test_nan_inequality_raise_errors():
# See discussion in pull request #7776. We test inequalities with
# a set including examples of various classes.
for q in (x, S.Zero, S(10), S.One/3, pi, S(1.3), oo, -oo, nan):
assert_all_ineq_raise_TypeError(q, nan)
def test_nan_complex_inequalities():
# Comparisons of NaN with non-real raise errors, we're not too
# fussy whether its the NaN error or complex error.
for r in (I, zoo, Symbol('z', imaginary=True)):
assert_all_ineq_raise_TypeError(r, nan)
def test_complex_infinity_inequalities():
raises(TypeError, lambda: zoo > 0)
raises(TypeError, lambda: zoo >= 0)
raises(TypeError, lambda: zoo < 0)
raises(TypeError, lambda: zoo <= 0)
def test_inequalities_symbol_name_same():
"""Using the operator and functional forms should give same results."""
# We test all combinations from a set
# FIXME: could replace with random selection after test passes
A = (x, y, S.Zero, S.One/3, pi, oo, -oo)
for a in A:
for b in A:
assert Gt(a, b) == (a > b)
assert Lt(a, b) == (a < b)
assert Ge(a, b) == (a >= b)
assert Le(a, b) == (a <= b)
for b in (y, S.Zero, S.One/3, pi, oo, -oo):
assert Gt(x, b, evaluate=False) == (x > b)
assert Lt(x, b, evaluate=False) == (x < b)
assert Ge(x, b, evaluate=False) == (x >= b)
assert Le(x, b, evaluate=False) == (x <= b)
for b in (y, S.Zero, S.One/3, pi, oo, -oo):
assert Gt(b, x, evaluate=False) == (b > x)
assert Lt(b, x, evaluate=False) == (b < x)
assert Ge(b, x, evaluate=False) == (b >= x)
assert Le(b, x, evaluate=False) == (b <= x)
def test_inequalities_symbol_name_same_complex():
"""Using the operator and functional forms should give same results.
With complex non-real numbers, both should raise errors.
"""
# FIXME: could replace with random selection after test passes
for a in (x, S.Zero, S.One/3, pi, oo, Rational(1, 3)):
raises(TypeError, lambda: Gt(a, I))
raises(TypeError, lambda: a > I)
raises(TypeError, lambda: Lt(a, I))
raises(TypeError, lambda: a < I)
raises(TypeError, lambda: Ge(a, I))
raises(TypeError, lambda: a >= I)
raises(TypeError, lambda: Le(a, I))
raises(TypeError, lambda: a <= I)
def test_inequalities_cant_sympify_other():
# see issue 7833
from operator import gt, lt, ge, le
bar = "foo"
for a in (x, S.Zero, S.One/3, pi, I, zoo, oo, -oo, nan, Rational(1, 3)):
for op in (lt, gt, le, ge):
raises(TypeError, lambda: op(a, bar))
def test_ineq_avoid_wild_symbol_flip():
# see issue #7951, we try to avoid this internally, e.g., by using
# __lt__ instead of "<".
from sympy.core.symbol import Wild
p = symbols('p', cls=Wild)
# x > p might flip, but Gt should not:
assert Gt(x, p) == Gt(x, p, evaluate=False)
# Previously failed as 'p > x':
e = Lt(x, y).subs({y: p})
assert e == Lt(x, p, evaluate=False)
# Previously failed as 'p <= x':
e = Ge(x, p).doit()
assert e == Ge(x, p, evaluate=False)
def test_issue_8245():
a = S("6506833320952669167898688709329/5070602400912917605986812821504")
assert rel_check(a, a.n(10))
assert rel_check(a, a.n(20))
assert rel_check(a, a.n())
# prec of 30 is enough to fully capture a as mpf
assert Float(a, 30) == Float(str(a.p), '')/Float(str(a.q), '')
for i in range(31):
r = Rational(Float(a, i))
f = Float(r)
assert (f < a) == (Rational(f) < a)
# test sign handling
assert (-f < -a) == (Rational(-f) < -a)
# test equivalence handling
isa = Float(a.p,'')/Float(a.q,'')
assert isa <= a
assert not isa < a
assert isa >= a
assert not isa > a
assert isa > 0
a = sqrt(2)
r = Rational(str(a.n(30)))
assert rel_check(a, r)
a = sqrt(2)
r = Rational(str(a.n(29)))
assert rel_check(a, r)
assert Eq(log(cos(2)**2 + sin(2)**2), 0) == True
def test_issue_8449():
p = Symbol('p', nonnegative=True)
assert Lt(-oo, p)
assert Ge(-oo, p) is S.false
assert Gt(oo, -p)
assert Le(oo, -p) is S.false
def test_simplify_relational():
assert simplify(x*(y + 1) - x*y - x + 1 < x) == (x > 1)
assert simplify(x*(y + 1) - x*y - x - 1 < x) == (x > -1)
assert simplify(x < x*(y + 1) - x*y - x + 1) == (x < 1)
r = S.One < x
# canonical operations are not the same as simplification,
# so if there is no simplification, canonicalization will
# be done unless the measure forbids it
assert simplify(r) == r.canonical
assert simplify(r, ratio=0) != r.canonical
# this is not a random test; in _eval_simplify
# this will simplify to S.false and that is the
# reason for the 'if r.is_Relational' in Relational's
# _eval_simplify routine
assert simplify(-(2**(pi*Rational(3, 2)) + 6**pi)**(1/pi) +
2*(2**(pi/2) + 3**pi)**(1/pi) < 0) is S.false
# canonical at least
assert Eq(y, x).simplify() == Eq(x, y)
assert Eq(x - 1, 0).simplify() == Eq(x, 1)
assert Eq(x - 1, x).simplify() == S.false
assert Eq(2*x - 1, x).simplify() == Eq(x, 1)
assert Eq(2*x, 4).simplify() == Eq(x, 2)
z = cos(1)**2 + sin(1)**2 - 1 # z.is_zero is None
assert Eq(z*x, 0).simplify() == S.true
assert Ne(y, x).simplify() == Ne(x, y)
assert Ne(x - 1, 0).simplify() == Ne(x, 1)
assert Ne(x - 1, x).simplify() == S.true
assert Ne(2*x - 1, x).simplify() == Ne(x, 1)
assert Ne(2*x, 4).simplify() == Ne(x, 2)
assert Ne(z*x, 0).simplify() == S.false
# No real-valued assumptions
assert Ge(y, x).simplify() == Le(x, y)
assert Ge(x - 1, 0).simplify() == Ge(x, 1)
assert Ge(x - 1, x).simplify() == S.false
assert Ge(2*x - 1, x).simplify() == Ge(x, 1)
assert Ge(2*x, 4).simplify() == Ge(x, 2)
assert Ge(z*x, 0).simplify() == S.true
assert Ge(x, -2).simplify() == Ge(x, -2)
assert Ge(-x, -2).simplify() == Le(x, 2)
assert Ge(x, 2).simplify() == Ge(x, 2)
assert Ge(-x, 2).simplify() == Le(x, -2)
assert Le(y, x).simplify() == Ge(x, y)
assert Le(x - 1, 0).simplify() == Le(x, 1)
assert Le(x - 1, x).simplify() == S.true
assert Le(2*x - 1, x).simplify() == Le(x, 1)
assert Le(2*x, 4).simplify() == Le(x, 2)
assert Le(z*x, 0).simplify() == S.true
assert Le(x, -2).simplify() == Le(x, -2)
assert Le(-x, -2).simplify() == Ge(x, 2)
assert Le(x, 2).simplify() == Le(x, 2)
assert Le(-x, 2).simplify() == Ge(x, -2)
assert Gt(y, x).simplify() == Lt(x, y)
assert Gt(x - 1, 0).simplify() == Gt(x, 1)
assert Gt(x - 1, x).simplify() == S.false
assert Gt(2*x - 1, x).simplify() == Gt(x, 1)
assert Gt(2*x, 4).simplify() == Gt(x, 2)
assert Gt(z*x, 0).simplify() == S.false
assert Gt(x, -2).simplify() == Gt(x, -2)
assert Gt(-x, -2).simplify() == Lt(x, 2)
assert Gt(x, 2).simplify() == Gt(x, 2)
assert Gt(-x, 2).simplify() == Lt(x, -2)
assert Lt(y, x).simplify() == Gt(x, y)
assert Lt(x - 1, 0).simplify() == Lt(x, 1)
assert Lt(x - 1, x).simplify() == S.true
assert Lt(2*x - 1, x).simplify() == Lt(x, 1)
assert Lt(2*x, 4).simplify() == Lt(x, 2)
assert Lt(z*x, 0).simplify() == S.false
assert Lt(x, -2).simplify() == Lt(x, -2)
assert Lt(-x, -2).simplify() == Gt(x, 2)
assert Lt(x, 2).simplify() == Lt(x, 2)
assert Lt(-x, 2).simplify() == Gt(x, -2)
def test_equals():
w, x, y, z = symbols('w:z')
f = Function('f')
assert Eq(x, 1).equals(Eq(x*(y + 1) - x*y - x + 1, x))
assert Eq(x, y).equals(x < y, True) == False
assert Eq(x, f(1)).equals(Eq(x, f(2)), True) == f(1) - f(2)
assert Eq(f(1), y).equals(Eq(f(2), y), True) == f(1) - f(2)
assert Eq(x, f(1)).equals(Eq(f(2), x), True) == f(1) - f(2)
assert Eq(f(1), x).equals(Eq(x, f(2)), True) == f(1) - f(2)
assert Eq(w, x).equals(Eq(y, z), True) == False
assert Eq(f(1), f(2)).equals(Eq(f(3), f(4)), True) == f(1) - f(3)
assert (x < y).equals(y > x, True) == True
assert (x < y).equals(y >= x, True) == False
assert (x < y).equals(z < y, True) == False
assert (x < y).equals(x < z, True) == False
assert (x < f(1)).equals(x < f(2), True) == f(1) - f(2)
assert (f(1) < x).equals(f(2) < x, True) == f(1) - f(2)
def test_reversed():
assert (x < y).reversed == (y > x)
assert (x <= y).reversed == (y >= x)
assert Eq(x, y, evaluate=False).reversed == Eq(y, x, evaluate=False)
assert Ne(x, y, evaluate=False).reversed == Ne(y, x, evaluate=False)
assert (x >= y).reversed == (y <= x)
assert (x > y).reversed == (y < x)
def test_canonical():
c = [i.canonical for i in (
x + y < z,
x + 2 > 3,
x < 2,
S(2) > x,
x**2 > -x/y,
Gt(3, 2, evaluate=False)
)]
assert [i.canonical for i in c] == c
assert [i.reversed.canonical for i in c] == c
assert not any(i.lhs.is_Number and not i.rhs.is_Number for i in c)
c = [i.reversed.func(i.rhs, i.lhs, evaluate=False).canonical for i in c]
assert [i.canonical for i in c] == c
assert [i.reversed.canonical for i in c] == c
assert not any(i.lhs.is_Number and not i.rhs.is_Number for i in c)
@XFAIL
def test_issue_8444_nonworkingtests():
x = symbols('x', real=True)
assert (x <= oo) == (x >= -oo) == True
x = symbols('x')
assert x >= floor(x)
assert (x < floor(x)) == False
assert x <= ceiling(x)
assert (x > ceiling(x)) == False
def test_issue_8444_workingtests():
x = symbols('x')
assert Gt(x, floor(x)) == Gt(x, floor(x), evaluate=False)
assert Ge(x, floor(x)) == Ge(x, floor(x), evaluate=False)
assert Lt(x, ceiling(x)) == Lt(x, ceiling(x), evaluate=False)
assert Le(x, ceiling(x)) == Le(x, ceiling(x), evaluate=False)
i = symbols('i', integer=True)
assert (i > floor(i)) == False
assert (i < ceiling(i)) == False
def test_issue_10304():
d = cos(1)**2 + sin(1)**2 - 1
assert d.is_comparable is False # if this fails, find a new d
e = 1 + d*I
assert simplify(Eq(e, 0)) is S.false
def test_issue_10401():
x = symbols('x')
fin = symbols('inf', finite=True)
inf = symbols('inf', infinite=True)
inf2 = symbols('inf2', infinite=True)
zero = symbols('z', zero=True)
nonzero = symbols('nz', zero=False, finite=True)
assert Eq(1/(1/x + 1), 1).func is Eq
assert Eq(1/(1/x + 1), 1).subs(x, S.ComplexInfinity) is S.true
assert Eq(1/(1/fin + 1), 1) is S.false
T, F = S.true, S.false
assert Eq(fin, inf) is F
assert Eq(inf, inf2) is T and inf != inf2
assert Eq(inf/inf2, 0) is F
assert Eq(inf/fin, 0) is F
assert Eq(fin/inf, 0) is T
assert Eq(zero/nonzero, 0) is T and ((zero/nonzero) != 0)
assert Eq(inf, -inf) is F
assert Eq(fin/(fin + 1), 1) is S.false
o = symbols('o', odd=True)
assert Eq(o, 2*o) is S.false
p = symbols('p', positive=True)
assert Eq(p/(p - 1), 1) is F
def test_issue_10633():
assert Eq(True, False) == False
assert Eq(False, True) == False
assert Eq(True, True) == True
assert Eq(False, False) == True
def test_issue_10927():
x = symbols('x')
assert str(Eq(x, oo)) == 'Eq(x, oo)'
assert str(Eq(x, -oo)) == 'Eq(x, -oo)'
def test_issues_13081_12583_12534():
# 13081
r = Rational('905502432259640373/288230376151711744')
assert (r < pi) is S.false
assert (r > pi) is S.true
# 12583
v = sqrt(2)
u = sqrt(v) + 2/sqrt(10 - 8/sqrt(2 - v) + 4*v*(1/sqrt(2 - v) - 1))
assert (u >= 0) is S.true
# 12534; Rational vs NumberSymbol
# here are some precisions for which Rational forms
# at a lower and higher precision bracket the value of pi
# e.g. for p = 20:
# Rational(pi.n(p + 1)).n(25) = 3.14159265358979323846 2834
# pi.n(25) = 3.14159265358979323846 2643
# Rational(pi.n(p )).n(25) = 3.14159265358979323846 1987
assert [p for p in range(20, 50) if
(Rational(pi.n(p)) < pi) and
(pi < Rational(pi.n(p + 1)))] == [20, 24, 27, 33, 37, 43, 48]
# pick one such precision and affirm that the reversed operation
# gives the opposite result, i.e. if x < y is true then x > y
# must be false
for i in (20, 21):
v = pi.n(i)
assert rel_check(Rational(v), pi)
assert rel_check(v, pi)
assert rel_check(pi.n(20), pi.n(21))
# Float vs Rational
# the rational form is less than the floating representation
# at the same precision
assert [i for i in range(15, 50) if Rational(pi.n(i)) > pi.n(i)] == []
# this should be the same if we reverse the relational
assert [i for i in range(15, 50) if pi.n(i) < Rational(pi.n(i))] == []
def test_binary_symbols():
ans = set([x])
for f in Eq, Ne:
for t in S.true, S.false:
eq = f(x, S.true)
assert eq.binary_symbols == ans
assert eq.reversed.binary_symbols == ans
assert f(x, 1).binary_symbols == set()
def test_rel_args():
# can't have Boolean args; this is automatic with Python 3
# so this test and the __lt__, etc..., definitions in
# relational.py and boolalg.py which are marked with ///
# can be removed.
for op in ['<', '<=', '>', '>=']:
for b in (S.true, x < 1, And(x, y)):
for v in (0.1, 1, 2**32, t, S.One):
raises(TypeError, lambda: Relational(b, v, op))
def test_Equality_rewrite_as_Add():
eq = Eq(x + y, y - x)
assert eq.rewrite(Add) == 2*x
assert eq.rewrite(Add, evaluate=None).args == (x, x, y, -y)
assert eq.rewrite(Add, evaluate=False).args == (x, y, x, -y)
def test_issue_15847():
a = Ne(x*(x+y), x**2 + x*y)
assert simplify(a) == False
def test_negated_property():
eq = Eq(x, y)
assert eq.negated == Ne(x, y)
eq = Ne(x, y)
assert eq.negated == Eq(x, y)
eq = Ge(x + y, y - x)
assert eq.negated == Lt(x + y, y - x)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, y).negated.negated == f(x, y)
def test_reversedsign_property():
eq = Eq(x, y)
assert eq.reversedsign == Eq(-x, -y)
eq = Ne(x, y)
assert eq.reversedsign == Ne(-x, -y)
eq = Ge(x + y, y - x)
assert eq.reversedsign == Le(-x - y, x - y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, y).reversedsign.reversedsign == f(x, y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, y).reversedsign.reversedsign == f(-x, y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, -y).reversedsign.reversedsign == f(x, -y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, -y).reversedsign.reversedsign == f(-x, -y)
def test_reversed_reversedsign_property():
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, y).reversed.reversedsign == f(x, y).reversedsign.reversed
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, y).reversed.reversedsign == f(-x, y).reversedsign.reversed
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, -y).reversed.reversedsign == f(x, -y).reversedsign.reversed
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, -y).reversed.reversedsign == \
f(-x, -y).reversedsign.reversed
def test_improved_canonical():
def test_different_forms(listofforms):
for form1, form2 in combinations(listofforms, 2):
assert form1.canonical == form2.canonical
def generate_forms(expr):
return [expr, expr.reversed, expr.reversedsign,
expr.reversed.reversedsign]
test_different_forms(generate_forms(x > -y))
test_different_forms(generate_forms(x >= -y))
test_different_forms(generate_forms(Eq(x, -y)))
test_different_forms(generate_forms(Ne(x, -y)))
test_different_forms(generate_forms(pi < x))
test_different_forms(generate_forms(pi - 5*y < -x + 2*y**2 - 7))
assert (pi >= x).canonical == (x <= pi)
def test_set_equality_canonical():
a, b, c = symbols('a b c')
A = Eq(FiniteSet(a, b, c), FiniteSet(1, 2, 3))
B = Ne(FiniteSet(a, b, c), FiniteSet(4, 5, 6))
assert A.canonical == A.reversed
assert B.canonical == B.reversed
def test_trigsimp():
# issue 16736
s, c = sin(2*x), cos(2*x)
eq = Eq(s, c)
assert trigsimp(eq) == eq # no rearrangement of sides
# simplification of sides might result in
# an unevaluated Eq
changed = trigsimp(Eq(s + c, sqrt(2)))
assert isinstance(changed, Eq)
assert changed.subs(x, pi/8) is S.true
# or an evaluated one
assert trigsimp(Eq(cos(x)**2 + sin(x)**2, 1)) is S.true
def test_polynomial_relation_simplification():
assert Ge(3*x*(x + 1) + 4, 3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))]
assert Le(-(3*x*(x + 1) + 4), -3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))]
assert ((x**2+3)*(x**2-1)+3*x >= 2*x**2).simplify() in [(x**4 + 3*x >= 3), (-x**4 - 3*x <= -3)]
def test_multivariate_linear_function_simplification():
assert Ge(x + y, x - y).simplify() == Ge(y, 0)
assert Le(-x + y, -x - y).simplify() == Le(y, 0)
assert Eq(2*x + y, 2*x + y - 3).simplify() == False
assert (2*x + y > 2*x + y - 3).simplify() == True
assert (2*x + y < 2*x + y - 3).simplify() == False
assert (2*x + y < 2*x + y + 3).simplify() == True
a, b, c, d, e, f, g = symbols('a b c d e f g')
assert Lt(a + b + c + 2*d, 3*d - f + g). simplify() == Lt(a, -b - c + d - f + g)
def test_nonpolymonial_relations():
assert Eq(cos(x), 0).simplify() == Eq(cos(x), 0)
|
d6f895b201e5940a4a10e23a279a1ad3ea589e92d67512ba1f9d9310e18b24e9 | from collections import defaultdict
from sympy import Matrix, Tuple, symbols, sympify, Basic, Dict, S, FiniteSet, Integer
from sympy.core.compatibility import is_sequence, iterable, range
from sympy.core.containers import tuple_wrapper
from sympy.core.expr import unchanged
from sympy.core.function import Function, Lambda
from sympy.core.relational import Eq
from sympy.utilities.pytest import raises
from sympy.abc import x, y
def test_Tuple():
t = (1, 2, 3, 4)
st = Tuple(*t)
assert set(sympify(t)) == set(st)
assert len(t) == len(st)
assert set(sympify(t[:2])) == set(st[:2])
assert isinstance(st[:], Tuple)
assert st == Tuple(1, 2, 3, 4)
assert st.func(*st.args) == st
p, q, r, s = symbols('p q r s')
t2 = (p, q, r, s)
st2 = Tuple(*t2)
assert st2.atoms() == set(t2)
assert st == st2.subs({p: 1, q: 2, r: 3, s: 4})
# issue 5505
assert all(isinstance(arg, Basic) for arg in st.args)
assert Tuple(p, 1).subs(p, 0) == Tuple(0, 1)
assert Tuple(p, Tuple(p, 1)).subs(p, 0) == Tuple(0, Tuple(0, 1))
assert Tuple(t2) == Tuple(Tuple(*t2))
assert Tuple.fromiter(t2) == Tuple(*t2)
assert Tuple.fromiter(x for x in range(4)) == Tuple(0, 1, 2, 3)
assert st2.fromiter(st2.args) == st2
def test_Tuple_contains():
t1, t2 = Tuple(1), Tuple(2)
assert t1 in Tuple(1, 2, 3, t1, Tuple(t2))
assert t2 not in Tuple(1, 2, 3, t1, Tuple(t2))
def test_Tuple_concatenation():
assert Tuple(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4)
assert (1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4)
assert Tuple(1, 2) + (3, 4) == Tuple(1, 2, 3, 4)
raises(TypeError, lambda: Tuple(1, 2) + 3)
raises(TypeError, lambda: 1 + Tuple(2, 3))
#the Tuple case in __radd__ is only reached when a subclass is involved
class Tuple2(Tuple):
def __radd__(self, other):
return Tuple.__radd__(self, other + other)
assert Tuple(1, 2) + Tuple2(3, 4) == Tuple(1, 2, 1, 2, 3, 4)
assert Tuple2(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4)
def test_Tuple_equality():
assert not isinstance(Tuple(1, 2), tuple)
assert (Tuple(1, 2) == (1, 2)) is True
assert (Tuple(1, 2) != (1, 2)) is False
assert (Tuple(1, 2) == (1, 3)) is False
assert (Tuple(1, 2) != (1, 3)) is True
assert (Tuple(1, 2) == Tuple(1, 2)) is True
assert (Tuple(1, 2) != Tuple(1, 2)) is False
assert (Tuple(1, 2) == Tuple(1, 3)) is False
assert (Tuple(1, 2) != Tuple(1, 3)) is True
def test_Tuple_Eq():
assert Eq(Tuple(), Tuple()) is S.true
assert Eq(Tuple(1), 1) is S.false
assert Eq(Tuple(1, 2), Tuple(1)) is S.false
assert Eq(Tuple(1), Tuple(1)) is S.true
assert Eq(Tuple(1, 2), Tuple(1, 3)) is S.false
assert Eq(Tuple(1, 2), Tuple(1, 2)) is S.true
assert unchanged(Eq, Tuple(1, x), Tuple(1, 2))
assert Eq(Tuple(1, x), Tuple(1, 2)).subs(x, 2) is S.true
assert unchanged(Eq, Tuple(1, 2), x)
f = Function('f')
assert unchanged(Eq, Tuple(1), f(x))
assert Eq(Tuple(1), f(x)).subs(x, 1).subs(f, Lambda(y, (y,))) is S.true
def test_Tuple_comparision():
assert (Tuple(1, 3) >= Tuple(-10, 30)) is S.true
assert (Tuple(1, 3) <= Tuple(-10, 30)) is S.false
assert (Tuple(1, 3) >= Tuple(1, 3)) is S.true
assert (Tuple(1, 3) <= Tuple(1, 3)) is S.true
def test_Tuple_tuple_count():
assert Tuple(0, 1, 2, 3).tuple_count(4) == 0
assert Tuple(0, 4, 1, 2, 3).tuple_count(4) == 1
assert Tuple(0, 4, 1, 4, 2, 3).tuple_count(4) == 2
assert Tuple(0, 4, 1, 4, 2, 4, 3).tuple_count(4) == 3
def test_Tuple_index():
assert Tuple(4, 0, 1, 2, 3).index(4) == 0
assert Tuple(0, 4, 1, 2, 3).index(4) == 1
assert Tuple(0, 1, 4, 2, 3).index(4) == 2
assert Tuple(0, 1, 2, 4, 3).index(4) == 3
assert Tuple(0, 1, 2, 3, 4).index(4) == 4
raises(ValueError, lambda: Tuple(0, 1, 2, 3).index(4))
raises(ValueError, lambda: Tuple(4, 0, 1, 2, 3).index(4, 1))
raises(ValueError, lambda: Tuple(0, 1, 2, 3, 4).index(4, 1, 4))
def test_Tuple_mul():
assert Tuple(1, 2, 3)*2 == Tuple(1, 2, 3, 1, 2, 3)
assert 2*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3)
assert Tuple(1, 2, 3)*Integer(2) == Tuple(1, 2, 3, 1, 2, 3)
assert Integer(2)*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3)
raises(TypeError, lambda: Tuple(1, 2, 3)*S.Half)
raises(TypeError, lambda: S.Half*Tuple(1, 2, 3))
def test_tuple_wrapper():
@tuple_wrapper
def wrap_tuples_and_return(*t):
return t
p = symbols('p')
assert wrap_tuples_and_return(p, 1) == (p, 1)
assert wrap_tuples_and_return((p, 1)) == (Tuple(p, 1),)
assert wrap_tuples_and_return(1, (p, 2), 3) == (1, Tuple(p, 2), 3)
def test_iterable_is_sequence():
ordered = [list(), tuple(), Tuple(), Matrix([[]])]
unordered = [set()]
not_sympy_iterable = [{}, '', u'']
assert all(is_sequence(i) for i in ordered)
assert all(not is_sequence(i) for i in unordered)
assert all(iterable(i) for i in ordered + unordered)
assert all(not iterable(i) for i in not_sympy_iterable)
assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
def test_Dict():
x, y, z = symbols('x y z')
d = Dict({x: 1, y: 2, z: 3})
assert d[x] == 1
assert d[y] == 2
raises(KeyError, lambda: d[2])
assert len(d) == 3
assert set(d.keys()) == set((x, y, z))
assert set(d.values()) == set((S.One, S(2), S(3)))
assert d.get(5, 'default') == 'default'
assert x in d and z in d and not 5 in d
assert d.has(x) and d.has(1) # SymPy Basic .has method
# Test input types
# input - a python dict
# input - items as args - SymPy style
assert (Dict({x: 1, y: 2, z: 3}) ==
Dict((x, 1), (y, 2), (z, 3)))
raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3))))
with raises(NotImplementedError):
d[5] = 6 # assert immutability
assert set(
d.items()) == set((Tuple(x, S.One), Tuple(y, S(2)), Tuple(z, S(3))))
assert set(d) == {x, y, z}
assert str(d) == '{x: 1, y: 2, z: 3}'
assert d.__repr__() == '{x: 1, y: 2, z: 3}'
# Test creating a Dict from a Dict.
d = Dict({x: 1, y: 2, z: 3})
assert d == Dict(d)
# Test for supporting defaultdict
d = defaultdict(int)
assert d[x] == 0
assert d[y] == 0
assert d[z] == 0
assert Dict(d)
d = Dict(d)
assert len(d) == 3
assert set(d.keys()) == set((x, y, z))
assert set(d.values()) == set((S.Zero, S.Zero, S.Zero))
def test_issue_5788():
args = [(1, 2), (2, 1)]
for o in [Dict, Tuple, FiniteSet]:
# __eq__ and arg handling
if o != Tuple:
assert o(*args) == o(*reversed(args))
pair = [o(*args), o(*reversed(args))]
assert sorted(pair) == sorted(reversed(pair))
assert set(o(*args)) # doesn't fail
|
ca987a28872e9abbd2f668f98da8e80206d077197896c51c4c58cfcbb1aa0b79 | from sympy import (Symbol, exp, Integer, Float, sin, cos, log, Poly, Lambda,
Function, I, S, N, sqrt, srepr, Rational, Tuple, Matrix, Interval, Add, Mul,
Pow, Or, true, false, Abs, pi, Range, Xor)
from sympy.abc import x, y
from sympy.core.sympify import (sympify, _sympify, SympifyError, kernS,
CantSympify)
from sympy.core.decorators import _sympifyit
from sympy.external import import_module
from sympy.utilities.pytest import raises, XFAIL, skip
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.geometry import Point, Line
from sympy.functions.combinatorial.factorials import factorial, factorial2
from sympy.abc import _clash, _clash1, _clash2
from sympy.core.compatibility import exec_, HAS_GMPY, PY3
from sympy.sets import FiniteSet, EmptySet
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
import mpmath
from collections import defaultdict, OrderedDict
from mpmath.rational import mpq
numpy = import_module('numpy')
def test_issue_3538():
v = sympify("exp(x)")
assert v == exp(x)
assert type(v) == type(exp(x))
assert str(type(v)) == str(type(exp(x)))
def test_sympify1():
assert sympify("x") == Symbol("x")
assert sympify(" x") == Symbol("x")
assert sympify(" x ") == Symbol("x")
# issue 4877
n1 = S.Half
assert sympify('--.5') == n1
assert sympify('-1/2') == -n1
assert sympify('-+--.5') == -n1
assert sympify('-.[3]') == Rational(-1, 3)
assert sympify('.[3]') == Rational(1, 3)
assert sympify('+.[3]') == Rational(1, 3)
assert sympify('+0.[3]*10**-2') == Rational(1, 300)
assert sympify('.[052631578947368421]') == Rational(1, 19)
assert sympify('.0[526315789473684210]') == Rational(1, 19)
assert sympify('.034[56]') == Rational(1711, 49500)
# options to make reals into rationals
assert sympify('1.22[345]', rational=True) == \
1 + Rational(22, 100) + Rational(345, 99900)
assert sympify('2/2.6', rational=True) == Rational(10, 13)
assert sympify('2.6/2', rational=True) == Rational(13, 10)
assert sympify('2.6e2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e+2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000)
assert sympify('2.1+3/4', rational=True) == \
Rational(21, 10) + Rational(3, 4)
assert sympify('2.234456', rational=True) == Rational(279307, 125000)
assert sympify('2.234456e23', rational=True) == 223445600000000000000000
assert sympify('2.234456e-23', rational=True) == \
Rational(279307, 12500000000000000000000000000)
assert sympify('-2.234456e-23', rational=True) == \
Rational(-279307, 12500000000000000000000000000)
assert sympify('12345678901/17', rational=True) == \
Rational(12345678901, 17)
assert sympify('1/.3 + x', rational=True) == Rational(10, 3) + x
# make sure longs in fractions work
assert sympify('222222222222/11111111111') == \
Rational(222222222222, 11111111111)
# ... even if they come from repetend notation
assert sympify('1/.2[123456789012]') == Rational(333333333333, 70781892967)
# ... or from high precision reals
assert sympify('.1234567890123456', rational=True) == \
Rational(19290123283179, 156250000000000)
def test_sympify_Fraction():
try:
import fractions
except ImportError:
pass
else:
value = sympify(fractions.Fraction(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
def test_sympify_gmpy():
if HAS_GMPY:
if HAS_GMPY == 2:
import gmpy2 as gmpy
elif HAS_GMPY == 1:
import gmpy
value = sympify(gmpy.mpz(1000001))
assert value == Integer(1000001) and type(value) is Integer
value = sympify(gmpy.mpq(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
@conserve_mpmath_dps
def test_sympify_mpmath():
value = sympify(mpmath.mpf(1.0))
assert value == Float(1.0) and type(value) is Float
mpmath.mp.dps = 12
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-12")) == True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) == False
mpmath.mp.dps = 6
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) == True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-6")) == False
assert sympify(mpmath.mpc(1.0 + 2.0j)) == Float(1.0) + Float(2.0)*I
assert sympify(mpq(1, 2)) == S.Half
def test_sympify2():
class A:
def _sympy_(self):
return Symbol("x")**3
a = A()
assert _sympify(a) == x**3
assert sympify(a) == x**3
assert a == x**3
def test_sympify3():
assert sympify("x**3") == x**3
assert sympify("x^3") == x**3
assert sympify("1/2") == Integer(1)/2
raises(SympifyError, lambda: _sympify('x**3'))
raises(SympifyError, lambda: _sympify('1/2'))
def test_sympify_keywords():
raises(SympifyError, lambda: sympify('if'))
raises(SympifyError, lambda: sympify('for'))
raises(SympifyError, lambda: sympify('while'))
raises(SympifyError, lambda: sympify('lambda'))
def test_sympify_float():
assert sympify("1e-64") != 0
assert sympify("1e-20000") != 0
def test_sympify_bool():
assert sympify(True) is true
assert sympify(False) is false
def test_sympyify_iterables():
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify(['.3', '.2'], rational=True) == ans
assert sympify(dict(x=0, y=1)) == {x: 0, y: 1}
assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]]
@XFAIL
def test_issue_16772():
# because there is a converter for tuple, the
# args are only sympified without the flags being passed
# along; list, on the other hand, is not converted
# with a converter so its args are traversed later
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans)
def test_issue_16859():
class no(float, CantSympify):
pass
raises(SympifyError, lambda: sympify(no(1.2)))
def test_sympify4():
class A:
def _sympy_(self):
return Symbol("x")
a = A()
assert _sympify(a)**3 == x**3
assert sympify(a)**3 == x**3
assert a == x
def test_sympify_text():
assert sympify('some') == Symbol('some')
assert sympify('core') == Symbol('core')
assert sympify('True') is True
assert sympify('False') is False
assert sympify('Poly') == Poly
assert sympify('sin') == sin
def test_sympify_function():
assert sympify('factor(x**2-1, x)') == -(1 - x)*(x + 1)
assert sympify('sin(pi/2)*cos(pi)') == -Integer(1)
def test_sympify_poly():
p = Poly(x**2 + x + 1, x)
assert _sympify(p) is p
assert sympify(p) is p
def test_sympify_factorial():
assert sympify('x!') == factorial(x)
assert sympify('(x+1)!') == factorial(x + 1)
assert sympify('(1 + y*(x + 1))!') == factorial(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!)^2') == (1 + y*factorial(x + 1))**2
assert sympify('y*x!') == y*factorial(x)
assert sympify('x!!') == factorial2(x)
assert sympify('(x+1)!!') == factorial2(x + 1)
assert sympify('(1 + y*(x + 1))!!') == factorial2(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!!)^2') == (1 + y*factorial2(x + 1))**2
assert sympify('y*x!!') == y*factorial2(x)
assert sympify('factorial2(x)!') == factorial(factorial2(x))
raises(SympifyError, lambda: sympify("+!!"))
raises(SympifyError, lambda: sympify(")!!"))
raises(SympifyError, lambda: sympify("!"))
raises(SympifyError, lambda: sympify("(!)"))
raises(SympifyError, lambda: sympify("x!!!"))
def test_sage():
# how to effectivelly test for the _sage_() method without having SAGE
# installed?
assert hasattr(x, "_sage_")
assert hasattr(Integer(3), "_sage_")
assert hasattr(sin(x), "_sage_")
assert hasattr(cos(x), "_sage_")
assert hasattr(x**2, "_sage_")
assert hasattr(x + y, "_sage_")
assert hasattr(exp(x), "_sage_")
assert hasattr(log(x), "_sage_")
def test_issue_3595():
assert sympify("a_") == Symbol("a_")
assert sympify("_a") == Symbol("_a")
def test_lambda():
x = Symbol('x')
assert sympify('lambda: 1') == Lambda((), 1)
assert sympify('lambda x: x') == Lambda(x, x)
assert sympify('lambda x: 2*x') == Lambda(x, 2*x)
assert sympify('lambda x, y: 2*x+y') == Lambda((x, y), 2*x + y)
def test_lambda_raises():
raises(SympifyError, lambda: sympify("lambda *args: args")) # args argument error
raises(SympifyError, lambda: sympify("lambda **kwargs: kwargs[0]")) # kwargs argument error
raises(SympifyError, lambda: sympify("lambda x = 1: x")) # Keyword argument error
with raises(SympifyError):
_sympify('lambda: 1')
def test_sympify_raises():
raises(SympifyError, lambda: sympify("fx)"))
def test__sympify():
x = Symbol('x')
f = Function('f')
# positive _sympify
assert _sympify(x) is x
assert _sympify(f) is f
assert _sympify(1) == Integer(1)
assert _sympify(0.5) == Float("0.5")
assert _sympify(1 + 1j) == 1.0 + I*1.0
class A:
def _sympy_(self):
return Integer(5)
a = A()
assert _sympify(a) == Integer(5)
# negative _sympify
raises(SympifyError, lambda: _sympify('1'))
raises(SympifyError, lambda: _sympify([1, 2, 3]))
def test_sympifyit():
x = Symbol('x')
y = Symbol('y')
@_sympifyit('b', NotImplemented)
def add(a, b):
return a + b
assert add(x, 1) == x + 1
assert add(x, 0.5) == x + Float('0.5')
assert add(x, y) == x + y
assert add(x, '1') == NotImplemented
@_sympifyit('b')
def add_raises(a, b):
return a + b
assert add_raises(x, 1) == x + 1
assert add_raises(x, 0.5) == x + Float('0.5')
assert add_raises(x, y) == x + y
raises(SympifyError, lambda: add_raises(x, '1'))
def test_int_float():
class F1_1(object):
def __float__(self):
return 1.1
class F1_1b(object):
"""
This class is still a float, even though it also implements __int__().
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
class F1_1c(object):
"""
This class is still a float, because it implements _sympy_()
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
def _sympy_(self):
return Float(1.1)
class I5(object):
def __int__(self):
return 5
class I5b(object):
"""
This class implements both __int__() and __float__(), so it will be
treated as Float in SymPy. One could change this behavior, by using
float(a) == int(a), but deciding that integer-valued floats represent
exact numbers is arbitrary and often not correct, so we do not do it.
If, in the future, we decide to do it anyway, the tests for I5b need to
be changed.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
class I5c(object):
"""
This class implements both __int__() and __float__(), but also
a _sympy_() method, so it will be Integer.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
def _sympy_(self):
return Integer(5)
i5 = I5()
i5b = I5b()
i5c = I5c()
f1_1 = F1_1()
f1_1b = F1_1b()
f1_1c = F1_1c()
assert sympify(i5) == 5
assert isinstance(sympify(i5), Integer)
assert sympify(i5b) == 5
assert isinstance(sympify(i5b), Float)
assert sympify(i5c) == 5
assert isinstance(sympify(i5c), Integer)
assert abs(sympify(f1_1) - 1.1) < 1e-5
assert abs(sympify(f1_1b) - 1.1) < 1e-5
assert abs(sympify(f1_1c) - 1.1) < 1e-5
assert _sympify(i5) == 5
assert isinstance(_sympify(i5), Integer)
assert _sympify(i5b) == 5
assert isinstance(_sympify(i5b), Float)
assert _sympify(i5c) == 5
assert isinstance(_sympify(i5c), Integer)
assert abs(_sympify(f1_1) - 1.1) < 1e-5
assert abs(_sympify(f1_1b) - 1.1) < 1e-5
assert abs(_sympify(f1_1c) - 1.1) < 1e-5
def test_evaluate_false():
cases = {
'2 + 3': Add(2, 3, evaluate=False),
'2**2 / 3': Mul(Pow(2, 2, evaluate=False), Pow(3, -1, evaluate=False), evaluate=False),
'2 + 3 * 5': Add(2, Mul(3, 5, evaluate=False), evaluate=False),
'2 - 3 * 5': Add(2, Mul(-1, Mul(3, 5,evaluate=False), evaluate=False), evaluate=False),
'1 / 3': Mul(1, Pow(3, -1, evaluate=False), evaluate=False),
'True | False': Or(True, False, evaluate=False),
'1 + 2 + 3 + 5*3 + integrate(x)': Add(1, 2, 3, Mul(5, 3, evaluate=False), x**2/2, evaluate=False),
'2 * 4 * 6 + 8': Add(Mul(2, 4, 6, evaluate=False), 8, evaluate=False),
'2 - 8 / 4': Add(2, Mul(-1, Mul(8, Pow(4, -1, evaluate=False), evaluate=False), evaluate=False), evaluate=False),
'2 - 2**2': Add(2, Mul(-1, Pow(2, 2, evaluate=False), evaluate=False), evaluate=False),
}
for case, result in cases.items():
assert sympify(case, evaluate=False) == result
def test_issue_4133():
a = sympify('Integer(4)')
assert a == Integer(4)
assert a.is_Integer
def test_issue_3982():
a = [3, 2.0]
assert sympify(a) == [Integer(3), Float(2.0)]
assert sympify(tuple(a)) == Tuple(Integer(3), Float(2.0))
assert sympify(set(a)) == FiniteSet(Integer(3), Float(2.0))
def test_S_sympify():
assert S(1)/2 == sympify(1)/2
assert (-2)**(S(1)/2) == sqrt(2)*I
def test_issue_4788():
assert srepr(S(1.0 + 0J)) == srepr(S(1.0)) == srepr(Float(1.0))
def test_issue_4798_None():
assert S(None) is None
def test_issue_3218():
assert sympify("x+\ny") == x + y
def test_issue_4988_builtins():
C = Symbol('C')
vars = {'C': C}
exp1 = sympify('C')
assert exp1 == C # Make sure it did not get mixed up with sympy.C
exp2 = sympify('C', vars)
assert exp2 == C # Make sure it did not get mixed up with sympy.C
def test_geometry():
p = sympify(Point(0, 1))
assert p == Point(0, 1) and isinstance(p, Point)
L = sympify(Line(p, (1, 0)))
assert L == Line((0, 1), (1, 0)) and isinstance(L, Line)
def test_kernS():
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'
# when 1497 is fixed, this no longer should pass: the expression
# should be unchanged
assert -1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) == -1
# sympification should not allow the constant to enter a Mul
# or else the structure can change dramatically
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'.replace(
'x', '_kern')
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
# issue 6687
assert kernS('Interval(-1,-2 - 4*(-3))') == Interval(-1, 10)
assert kernS('_kern') == Symbol('_kern')
assert kernS('E**-(x)') == exp(-x)
e = 2*(x + y)*y
assert kernS(['2*(x + y)*y', ('2*(x + y)*y',)]) == [e, (e,)]
assert kernS('-(2*sin(x)**2 + 2*sin(x)*cos(x))*y/2') == \
-y*(2*sin(x)**2 + 2*sin(x)*cos(x))/2
# issue 15132
assert kernS('(1 - x)/(1 - x*(1-y))') == kernS('(1-x)/(1-(1-y)*x)')
assert kernS('(1-2**-(4+1)*(1-y)*x)') == (1 - x*(1 - y)/32)
assert kernS('(1-2**(4+1)*(1-y)*x)') == (1 - 32*x*(1 - y))
assert kernS('(1-2.*(1-y)*x)') == 1 - 2.*x*(1 - y)
one = kernS('x - (x - 1)')
assert one != 1 and one.expand() == 1
def test_issue_6540_6552():
assert S('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5),)]
assert S('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (S.Half,)]
assert S('[[[2*(1)]]]') == [[[2]]]
assert S('Matrix([2*(1)])') == Matrix([2])
def test_issue_6046():
assert str(S("Q & C", locals=_clash1)) == 'C & Q'
assert str(S('pi(x)', locals=_clash2)) == 'pi(x)'
assert str(S('pi(C, Q)', locals=_clash)) == 'pi(C, Q)'
locals = {}
exec_("from sympy.abc import Q, C", locals)
assert str(S('C&Q', locals)) == 'C & Q'
def test_issue_8821_highprec_from_str():
s = str(pi.evalf(128))
p = sympify(s)
assert Abs(sin(p)) < 1e-127
def test_issue_10295():
if not numpy:
skip("numpy not installed.")
A = numpy.array([[1, 3, -1],
[0, 1, 7]])
sA = S(A)
assert sA.shape == (2, 3)
for (ri, ci), val in numpy.ndenumerate(A):
assert sA[ri, ci] == val
B = numpy.array([-7, x, 3*y**2])
sB = S(B)
assert sB.shape == (3,)
assert B[0] == sB[0] == -7
assert B[1] == sB[1] == x
assert B[2] == sB[2] == 3*y**2
C = numpy.arange(0, 24)
C.resize(2,3,4)
sC = S(C)
assert sC[0, 0, 0].is_integer
assert sC[0, 0, 0] == 0
a1 = numpy.array([1, 2, 3])
a2 = numpy.array([i for i in range(24)])
a2.resize(2, 4, 3)
assert sympify(a1) == ImmutableDenseNDimArray([1, 2, 3])
assert sympify(a2) == ImmutableDenseNDimArray([i for i in range(24)], (2, 4, 3))
def test_Range():
# Only works in Python 3 where range returns a range type
if PY3:
builtin_range = range
else:
builtin_range = xrange
assert sympify(builtin_range(10)) == Range(10)
assert _sympify(builtin_range(10)) == Range(10)
def test_sympify_set():
n = Symbol('n')
assert sympify({n}) == FiniteSet(n)
assert sympify(set()) == EmptySet()
def test_sympify_numpy():
if not numpy:
skip('numpy not installed. Abort numpy tests.')
np = numpy
def equal(x, y):
return x == y and type(x) == type(y)
assert sympify(np.bool_(1)) is S(True)
try:
assert equal(
sympify(np.int_(1234567891234567891)), S(1234567891234567891))
assert equal(
sympify(np.intp(1234567891234567891)), S(1234567891234567891))
except OverflowError:
# May fail on 32-bit systems: Python int too large to convert to C long
pass
assert equal(sympify(np.intc(1234567891)), S(1234567891))
assert equal(sympify(np.int8(-123)), S(-123))
assert equal(sympify(np.int16(-12345)), S(-12345))
assert equal(sympify(np.int32(-1234567891)), S(-1234567891))
assert equal(
sympify(np.int64(-1234567891234567891)), S(-1234567891234567891))
assert equal(sympify(np.uint8(123)), S(123))
assert equal(sympify(np.uint16(12345)), S(12345))
assert equal(sympify(np.uint32(1234567891)), S(1234567891))
assert equal(
sympify(np.uint64(1234567891234567891)), S(1234567891234567891))
assert equal(sympify(np.float32(1.123456)), Float(1.123456, precision=24))
assert equal(sympify(np.float64(1.1234567891234)),
Float(1.1234567891234, precision=53))
assert equal(sympify(np.longdouble(1.123456789)),
Float(1.123456789, precision=80))
assert equal(sympify(np.complex64(1 + 2j)), S(1.0 + 2.0*I))
assert equal(sympify(np.complex128(1 + 2j)), S(1.0 + 2.0*I))
assert equal(sympify(np.longcomplex(1 + 2j)), S(1.0 + 2.0*I))
#float96 does not exist on all platforms
if hasattr(np, 'float96'):
assert equal(sympify(np.float96(1.123456789)),
Float(1.123456789, precision=80))
#float128 does not exist on all platforms
if hasattr(np, 'float128'):
assert equal(sympify(np.float128(1.123456789123)),
Float(1.123456789123, precision=80))
@XFAIL
def test_sympify_rational_numbers_set():
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify({'.3', '.2'}, rational=True) == FiniteSet(*ans)
def test_issue_13924():
if not numpy:
skip("numpy not installed.")
a = sympify(numpy.array([1]))
assert isinstance(a, ImmutableDenseNDimArray)
assert a[0] == 1
def test_numpy_sympify_args():
# Issue 15098. Make sure sympify args work with numpy types (like numpy.str_)
if not numpy:
skip("numpy not installed.")
a = sympify(numpy.str_('a'))
assert type(a) is Symbol
assert a == Symbol('a')
class CustomSymbol(Symbol):
pass
a = sympify(numpy.str_('a'), {"Symbol": CustomSymbol})
assert isinstance(a, CustomSymbol)
a = sympify(numpy.str_('x^y'))
assert a == x**y
a = sympify(numpy.str_('x^y'), convert_xor=False)
assert a == Xor(x, y)
raises(SympifyError, lambda: sympify(numpy.str_('x'), strict=True))
a = sympify(numpy.str_('1.1'))
assert isinstance(a, Float)
assert a == 1.1
a = sympify(numpy.str_('1.1'), rational=True)
assert isinstance(a, Rational)
assert a == Rational(11, 10)
a = sympify(numpy.str_('x + x'))
assert isinstance(a, Mul)
assert a == 2*x
a = sympify(numpy.str_('x + x'), evaluate=False)
assert isinstance(a, Add)
assert a == Add(x, x, evaluate=False)
def test_issue_5939():
a = Symbol('a')
b = Symbol('b')
assert sympify('''a+\nb''') == a + b
def test_issue_16759():
d = sympify({.5: 1})
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
d = sympify(OrderedDict({.5: 1}))
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
d = sympify(defaultdict(int, {.5: 1}))
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
|
931c9b9e4ff3fdb73748c44e98edeec10b91759b3b033d91caf5855bfc4e1c77 | from sympy import (Abs, Add, atan, ceiling, cos, E, Eq, exp, factor,
factorial, fibonacci, floor, Function, GoldenRatio, I, Integral,
integrate, log, Mul, N, oo, pi, Pow, product, Product,
Rational, S, Sum, simplify, sin, sqrt, sstr, sympify, Symbol, Max, nfloat, cosh, acosh, acos)
from sympy.core.numbers import comp, Rational
from sympy.core.evalf import (complex_accuracy, PrecisionExhausted,
scaled_zero, get_integer_part, as_mpmath, evalf)
from mpmath import inf, ninf
from mpmath.libmp.libmpf import from_float
from sympy.core.compatibility import long, range
from sympy.core.expr import unchanged
from sympy.utilities.pytest import raises, XFAIL
from sympy.abc import n, x, y
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_evalf_helpers():
assert complex_accuracy((from_float(2.0), None, 35, None)) == 35
assert complex_accuracy((from_float(2.0), from_float(10.0), 35, 100)) == 37
assert complex_accuracy(
(from_float(2.0), from_float(1000.0), 35, 100)) == 43
assert complex_accuracy((from_float(2.0), from_float(10.0), 100, 35)) == 35
assert complex_accuracy(
(from_float(2.0), from_float(1000.0), 100, 35)) == 35
def test_evalf_basic():
assert NS('pi', 15) == '3.14159265358979'
assert NS('2/3', 10) == '0.6666666667'
assert NS('355/113-pi', 6) == '2.66764e-7'
assert NS('16*atan(1/5)-4*atan(1/239)', 15) == '3.14159265358979'
def test_cancellation():
assert NS(Add(pi, Rational(1, 10**1000), -pi, evaluate=False), 15,
maxn=1200) == '1.00000000000000e-1000'
def test_evalf_powers():
assert NS('pi**(10**20)', 10) == '1.339148777e+49714987269413385435'
assert NS(pi**(10**100), 10) == ('4.946362032e+4971498726941338543512682882'
'9089887365167832438044244613405349992494711208'
'95526746555473864642912223')
assert NS('2**(1/10**50)', 15) == '1.00000000000000'
assert NS('2**(1/10**50)-1', 15) == '6.93147180559945e-51'
# Evaluation of Rump's ill-conditioned polynomial
def test_evalf_rump():
a = 1335*y**6/4 + x**2*(11*x**2*y**2 - y**6 - 121*y**4 - 2) + 11*y**8/2 + x/(2*y)
assert NS(a, 15, subs={x: 77617, y: 33096}) == '-0.827396059946821'
def test_evalf_complex():
assert NS('2*sqrt(pi)*I', 10) == '3.544907702*I'
assert NS('3+3*I', 15) == '3.00000000000000 + 3.00000000000000*I'
assert NS('E+pi*I', 15) == '2.71828182845905 + 3.14159265358979*I'
assert NS('pi * (3+4*I)', 15) == '9.42477796076938 + 12.5663706143592*I'
assert NS('I*(2+I)', 15) == '-1.00000000000000 + 2.00000000000000*I'
@XFAIL
def test_evalf_complex_bug():
assert NS('(pi+E*I)*(E+pi*I)', 15) in ('0.e-15 + 17.25866050002*I',
'0.e-17 + 17.25866050002*I', '-0.e-17 + 17.25866050002*I')
def test_evalf_complex_powers():
assert NS('(E+pi*I)**100000000000000000') == \
'-3.58896782867793e+61850354284995199 + 4.58581754997159e+61850354284995199*I'
# XXX: rewrite if a+a*I simplification introduced in sympy
#assert NS('(pi + pi*I)**2') in ('0.e-15 + 19.7392088021787*I', '0.e-16 + 19.7392088021787*I')
assert NS('(pi + pi*I)**2', chop=True) == '19.7392088021787*I'
assert NS(
'(pi + 1/10**8 + pi*I)**2') == '6.2831853e-8 + 19.7392088650106*I'
assert NS('(pi + 1/10**12 + pi*I)**2') == '6.283e-12 + 19.7392088021850*I'
assert NS('(pi + pi*I)**4', chop=True) == '-389.636364136010'
assert NS(
'(pi + 1/10**8 + pi*I)**4') == '-389.636366616512 + 2.4805021e-6*I'
assert NS('(pi + 1/10**12 + pi*I)**4') == '-389.636364136258 + 2.481e-10*I'
assert NS(
'(10000*pi + 10000*pi*I)**4', chop=True) == '-3.89636364136010e+18'
@XFAIL
def test_evalf_complex_powers_bug():
assert NS('(pi + pi*I)**4') == '-389.63636413601 + 0.e-14*I'
def test_evalf_exponentiation():
assert NS(sqrt(-pi)) == '1.77245385090552*I'
assert NS(Pow(pi*I, Rational(
1, 2), evaluate=False)) == '1.25331413731550 + 1.25331413731550*I'
assert NS(pi**I) == '0.413292116101594 + 0.910598499212615*I'
assert NS(pi**(E + I/3)) == '20.8438653991931 + 8.36343473930031*I'
assert NS((pi + I/3)**(E + I/3)) == '17.2442906093590 + 13.6839376767037*I'
assert NS(exp(pi)) == '23.1406926327793'
assert NS(exp(pi + E*I)) == '-21.0981542849657 + 9.50576358282422*I'
assert NS(pi**pi) == '36.4621596072079'
assert NS((-pi)**pi) == '-32.9138577418939 - 15.6897116534332*I'
assert NS((-pi)**(-pi)) == '-0.0247567717232697 + 0.0118013091280262*I'
# An example from Smith, "Multiple Precision Complex Arithmetic and Functions"
def test_evalf_complex_cancellation():
A = Rational('63287/100000')
B = Rational('52498/100000')
C = Rational('69301/100000')
D = Rational('83542/100000')
F = Rational('2231321613/2500000000')
# XXX: the number of returned mantissa digits in the real part could
# change with the implementation. What matters is that the returned digits are
# correct; those that are showing now are correct.
# >>> ((A+B*I)*(C+D*I)).expand()
# 64471/10000000000 + 2231321613*I/2500000000
# >>> 2231321613*4
# 8925286452L
assert NS((A + B*I)*(C + D*I), 6) == '6.44710e-6 + 0.892529*I'
assert NS((A + B*I)*(C + D*I), 10) == '6.447100000e-6 + 0.8925286452*I'
assert NS((A + B*I)*(
C + D*I) - F*I, 5) in ('6.4471e-6 + 0.e-14*I', '6.4471e-6 - 0.e-14*I')
def test_evalf_logs():
assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I'
assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I'
assert NS('log(-1 + 0.00001)', 2) == '-1.0e-5 + 3.1*I'
assert NS('log(100, 10, evaluate=False)', 15) == '2.00000000000000'
assert NS('-2*I*log(-(-1)**(S(1)/9))', 15) == '-5.58505360638185'
def test_evalf_trig():
assert NS('sin(1)', 15) == '0.841470984807897'
assert NS('cos(1)', 15) == '0.540302305868140'
assert NS('sin(10**-6)', 15) == '9.99999999999833e-7'
assert NS('cos(10**-6)', 15) == '0.999999999999500'
assert NS('sin(E*10**100)', 15) == '0.409160531722613'
# Some input near roots
assert NS(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12'
assert NS(sin(pi*10**100 + Rational(7, 10**5), evaluate=False), 15, maxn=120) == \
'6.99999999428333e-5'
assert NS(sin(Rational(7, 10**5), evaluate=False), 15) == \
'6.99999999428333e-5'
# Check detection of various false identities
def test_evalf_near_integers():
# Binet's formula
f = lambda n: ((1 + sqrt(5))**n)/(2**n * sqrt(5))
assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046'
# Some near-integer identities from
# http://mathworld.wolfram.com/AlmostInteger.html
assert NS('sin(2017*2**(1/5))', 15) == '-1.00000000000000'
assert NS('sin(2017*2**(1/5))', 20) == '-0.99999999999999997857'
assert NS('1+sin(2017*2**(1/5))', 15) == '2.14322287389390e-17'
assert NS('45 - 613*E/37 + 35/991', 15) == '6.03764498766326e-11'
def test_evalf_ramanujan():
assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13'
# A related identity
A = 262537412640768744*exp(-pi*sqrt(163))
B = 196884*exp(-2*pi*sqrt(163))
C = 103378831900730205293632*exp(-3*pi*sqrt(163))
assert NS(1 - A - B + C, 10) == '1.613679005e-59'
# Input that for various reasons have failed at some point
def test_evalf_bugs():
assert NS(sin(1) + exp(-10**10), 10) == NS(sin(1), 10)
assert NS(exp(10**10) + sin(1), 10) == NS(exp(10**10), 10)
assert NS('expand_log(log(1+1/10**50))', 20) == '1.0000000000000000000e-50'
assert NS('log(10**100,10)', 10) == '100.0000000'
assert NS('log(2)', 10) == '0.6931471806'
assert NS(
'(sin(x)-x)/x**3', 15, subs={x: '1/10**50'}) == '-0.166666666666667'
assert NS(sin(1) + Rational(
1, 10**100)*I, 15) == '0.841470984807897 + 1.00000000000000e-100*I'
assert x.evalf() == x
assert NS((1 + I)**2*I, 6) == '-2.00000'
d = {n: (
-1)**Rational(6, 7), y: (-1)**Rational(4, 7), x: (-1)**Rational(2, 7)}
assert NS((x*(1 + y*(1 + n))).subs(d).evalf(), 6) == '0.346011 + 0.433884*I'
assert NS(((-I - sqrt(2)*I)**2).evalf()) == '-5.82842712474619'
assert NS((1 + I)**2*I, 15) == '-2.00000000000000'
# issue 4758 (1/2):
assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71'
# issue 4758 (2/2): With the bug present, this still only fails if the
# terms are in the order given here. This is not generally the case,
# because the order depends on the hashes of the terms.
assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n,
subs={n: .01}) == '19.8100000000000'
assert NS(((x - 1)*((1 - x))**1000).n()
) == '(1.00000000000000 - x)**1000*(x - 1.00000000000000)'
assert NS((-x).n()) == '-x'
assert NS((-2*x).n()) == '-2.00000000000000*x'
assert NS((-2*x*y).n()) == '-2.00000000000000*x*y'
assert cos(x).n(subs={x: 1+I}) == cos(x).subs(x, 1+I).n()
# issue 6660. Also NaN != mpmath.nan
# In this order:
# 0*nan, 0/nan, 0*inf, 0/inf
# 0+nan, 0-nan, 0+inf, 0-inf
# >>> n = Some Number
# n*nan, n/nan, n*inf, n/inf
# n+nan, n-nan, n+inf, n-inf
assert (0*E**(oo)).n() is S.NaN
assert (0/E**(oo)).n() is S.Zero
assert (0+E**(oo)).n() is S.Infinity
assert (0-E**(oo)).n() is S.NegativeInfinity
assert (5*E**(oo)).n() is S.Infinity
assert (5/E**(oo)).n() is S.Zero
assert (5+E**(oo)).n() is S.Infinity
assert (5-E**(oo)).n() is S.NegativeInfinity
#issue 7416
assert as_mpmath(0.0, 10, {'chop': True}) == 0
#issue 5412
assert ((oo*I).n() == S.Infinity*I)
assert ((oo+oo*I).n() == S.Infinity + S.Infinity*I)
#issue 11518
assert NS(2*x**2.5, 5) == '2.0000*x**2.5000'
#issue 13076
assert NS(Mul(Max(0, y), x, evaluate=False).evalf()) == 'x*Max(0, y)'
def test_evalf_integer_parts():
a = floor(log(8)/log(2) - exp(-1000), evaluate=False)
b = floor(log(8)/log(2), evaluate=False)
assert a.evalf() == 3
assert b.evalf() == 3
# equals, as a fallback, can still fail but it might succeed as here
assert ceiling(10*(sin(1)**2 + cos(1)**2)) == 10
assert int(floor(factorial(50)/E, evaluate=False).evalf(70)) == \
long(11188719610782480504630258070757734324011354208865721592720336800)
assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \
long(11188719610782480504630258070757734324011354208865721592720336801)
assert int(floor((GoldenRatio**999 / sqrt(5) + S.Half))
.evalf(1000)) == fibonacci(999)
assert int(floor((GoldenRatio**1000 / sqrt(5) + S.Half))
.evalf(1000)) == fibonacci(1000)
assert ceiling(x).evalf(subs={x: 3}) == 3
assert ceiling(x).evalf(subs={x: 3*I}) == 3.0*I
assert ceiling(x).evalf(subs={x: 2 + 3*I}) == 2.0 + 3.0*I
assert ceiling(x).evalf(subs={x: 3.}) == 3
assert ceiling(x).evalf(subs={x: 3.*I}) == 3.0*I
assert ceiling(x).evalf(subs={x: 2. + 3*I}) == 2.0 + 3.0*I
assert float((floor(1.5, evaluate=False)+1/9).evalf()) == 1 + 1/9
assert float((floor(0.5, evaluate=False)+20).evalf()) == 20
def test_evalf_trig_zero_detection():
a = sin(160*pi, evaluate=False)
t = a.evalf(maxn=100)
assert abs(t) < 1e-100
assert t._prec < 2
assert a.evalf(chop=True) == 0
raises(PrecisionExhausted, lambda: a.evalf(strict=True))
def test_evalf_sum():
assert Sum(n,(n,1,2)).evalf() == 3.
assert Sum(n,(n,1,2)).doit().evalf() == 3.
# the next test should return instantly
assert Sum(1/n,(n,1,2)).evalf() == 1.5
# issue 8219
assert Sum(E/factorial(n), (n, 0, oo)).evalf() == (E*E).evalf()
# issue 8254
assert Sum(2**n*n/factorial(n), (n, 0, oo)).evalf() == (2*E*E).evalf()
# issue 8411
s = Sum(1/x**2, (x, 100, oo))
assert s.n() == s.doit().n()
def test_evalf_divergent_series():
raises(ValueError, lambda: Sum(1/n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(n/(n**2 + 1), (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(n**2, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(2**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-2)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((2*n + 3)/(3*n**2 + 4), (n, 0, oo)).evalf())
raises(ValueError, lambda: Sum((0.5*n**3)/(n**4 + 1), (n, 0, oo)).evalf())
def test_evalf_product():
assert Product(n, (n, 1, 10)).evalf() == 3628800.
assert comp(Product(1 - S.Half**2/n**2, (n, 1, oo)).n(5), 0.63662)
assert Product(n, (n, -1, 3)).evalf() == 0
def test_evalf_py_methods():
assert abs(float(pi + 1) - 4.1415926535897932) < 1e-10
assert abs(complex(pi + 1) - 4.1415926535897932) < 1e-10
assert abs(
complex(pi + E*I) - (3.1415926535897931 + 2.7182818284590451j)) < 1e-10
raises(TypeError, lambda: float(pi + x))
def test_evalf_power_subs_bugs():
assert (x**2).evalf(subs={x: 0}) == 0
assert sqrt(x).evalf(subs={x: 0}) == 0
assert (x**Rational(2, 3)).evalf(subs={x: 0}) == 0
assert (x**x).evalf(subs={x: 0}) == 1
assert (3**x).evalf(subs={x: 0}) == 1
assert exp(x).evalf(subs={x: 0}) == 1
assert ((2 + I)**x).evalf(subs={x: 0}) == 1
assert (0**x).evalf(subs={x: 0}) == 1
def test_evalf_arguments():
raises(TypeError, lambda: pi.evalf(method="garbage"))
def test_implemented_function_evalf():
from sympy.utilities.lambdify import implemented_function
f = Function('f')
f = implemented_function(f, lambda x: x + 1)
assert str(f(x)) == "f(x)"
assert str(f(2)) == "f(2)"
assert f(2).evalf() == 3
assert f(x).evalf() == f(x)
f = implemented_function(Function('sin'), lambda x: x + 1)
assert f(2).evalf() != sin(2)
del f._imp_ # XXX: due to caching _imp_ would influence all other tests
def test_evaluate_false():
for no in [0, False]:
assert Add(3, 2, evaluate=no).is_Add
assert Mul(3, 2, evaluate=no).is_Mul
assert Pow(3, 2, evaluate=no).is_Pow
assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0
def test_evalf_relational():
assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y)
# if this first assertion fails it should be replaced with
# one that doesn't
assert unchanged(Eq, (3 - I)**2/2 + I, 0)
assert Eq((3 - I)**2/2 + I, 0).n() is S.false
# note: these don't always evaluate to Boolean
assert nfloat(Eq((3 - I)**2 + I, 0)) == Eq((3.0 - I)**2 + I, 0)
def test_issue_5486():
assert not cos(sqrt(0.5 + I)).n().is_Function
def test_issue_5486_bug():
from sympy import I, Expr
assert abs(Expr._from_mpmath(I._to_mpmath(15), 15) - I) < 1.0e-15
def test_bugs():
from sympy import polar_lift, re
assert abs(re((1 + I)**2)) < 1e-15
# anything that evalf's to 0 will do in place of polar_lift
assert abs(polar_lift(0)).n() == 0
def test_subs():
assert NS('besseli(-x, y) - besseli(x, y)', subs={x: 3.5, y: 20.0}) == \
'-4.92535585957223e-10'
assert NS('Piecewise((x, x>0)) + Piecewise((1-x, x>0))', subs={x: 0.1}) == \
'1.00000000000000'
raises(TypeError, lambda: x.evalf(subs=(x, 1)))
def test_issue_4956_5204():
# issue 4956
v = S('''(-27*12**(1/3)*sqrt(31)*I +
27*2**(2/3)*3**(1/3)*sqrt(31)*I)/(-2511*2**(2/3)*3**(1/3) +
(29*18**(1/3) + 9*2**(1/3)*3**(2/3)*sqrt(31)*I +
87*2**(1/3)*3**(1/6)*I)**2)''')
assert NS(v, 1) == '0.e-118 - 0.e-118*I'
# issue 5204
v = S('''-(357587765856 + 18873261792*249**(1/2) + 56619785376*I*83**(1/2) +
108755765856*I*3**(1/2) + 41281887168*6**(1/3)*(1422 +
54*249**(1/2))**(1/3) - 1239810624*6**(1/3)*249**(1/2)*(1422 +
54*249**(1/2))**(1/3) - 3110400000*I*6**(1/3)*83**(1/2)*(1422 +
54*249**(1/2))**(1/3) + 13478400000*I*3**(1/2)*6**(1/3)*(1422 +
54*249**(1/2))**(1/3) + 1274950152*6**(2/3)*(1422 +
54*249**(1/2))**(2/3) + 32347944*6**(2/3)*249**(1/2)*(1422 +
54*249**(1/2))**(2/3) - 1758790152*I*3**(1/2)*6**(2/3)*(1422 +
54*249**(1/2))**(2/3) - 304403832*I*6**(2/3)*83**(1/2)*(1422 +
4*249**(1/2))**(2/3))/(175732658352 + (1106028 + 25596*249**(1/2) +
76788*I*83**(1/2))**2)''')
assert NS(v, 5) == '0.077284 + 1.1104*I'
assert NS(v, 1) == '0.08 + 1.*I'
def test_old_docstring():
a = (E + pi*I)*(E - pi*I)
assert NS(a) == '17.2586605000200'
assert a.n() == 17.25866050002001
def test_issue_4806():
assert integrate(atan(x)**2, (x, -1, 1)).evalf().round(1) == 0.5
assert atan(0, evaluate=False).n() == 0
def test_evalf_mul():
# sympy should not try to expand this; it should be handled term-wise
# in evalf through mpmath
assert NS(product(1 + sqrt(n)*I, (n, 1, 500)), 1) == '5.e+567 + 2.e+568*I'
def test_scaled_zero():
a, b = (([0], 1, 100, 1), -1)
assert scaled_zero(100) == (a, b)
assert scaled_zero(a) == (0, 1, 100, 1)
a, b = (([1], 1, 100, 1), -1)
assert scaled_zero(100, -1) == (a, b)
assert scaled_zero(a) == (1, 1, 100, 1)
raises(ValueError, lambda: scaled_zero(scaled_zero(100)))
raises(ValueError, lambda: scaled_zero(100, 2))
raises(ValueError, lambda: scaled_zero(100, 0))
raises(ValueError, lambda: scaled_zero((1, 5, 1, 3)))
def test_chop_value():
for i in range(-27, 28):
assert (Pow(10, i)*2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i)
def test_infinities():
assert oo.evalf(chop=True) == inf
assert (-oo).evalf(chop=True) == ninf
def test_to_mpmath():
assert sqrt(3)._to_mpmath(20)._mpf_ == (0, long(908093), -19, 20)
assert S(3.2)._to_mpmath(20)._mpf_ == (0, long(838861), -18, 20)
def test_issue_6632_evalf():
add = (-100000*sqrt(2500000001) + 5000000001)
assert add.n() == 9.999999998e-11
assert (add*add).n() == 9.999999996e-21
def test_issue_4945():
from sympy.abc import H
from sympy import zoo
assert (H/0).evalf(subs={H:1}) == zoo*H
def test_evalf_integral():
# test that workprec has to increase in order to get a result other than 0
eps = Rational(1, 1000000)
assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10
def test_issue_8821_highprec_from_str():
s = str(pi.evalf(128))
p = N(s)
assert Abs(sin(p)) < 1e-15
p = N(s, 64)
assert Abs(sin(p)) < 1e-64
def test_issue_8853():
p = Symbol('x', even=True, positive=True)
assert floor(-p - S.Half).is_even == False
assert floor(-p + S.Half).is_even == True
assert ceiling(p - S.Half).is_even == True
assert ceiling(p + S.Half).is_even == False
assert get_integer_part(S.Half, -1, {}, True) == (0, 0)
assert get_integer_part(S.Half, 1, {}, True) == (1, 0)
assert get_integer_part(Rational(-1, 2), -1, {}, True) == (-1, 0)
assert get_integer_part(Rational(-1, 2), 1, {}, True) == (0, 0)
def test_issue_9326():
from sympy import Dummy
d1 = Dummy('d')
d2 = Dummy('d')
e = d1 + d2
assert e.evalf(subs = {d1: 1, d2: 2}) == 3
def test_issue_10323():
assert ceiling(sqrt(2**30 + 1)) == 2**15 + 1
def test_AssocOp_Function():
# the first arg of Min is not comparable in the imaginary part
raises(ValueError, lambda: S('''
Min(-sqrt(3)*cos(pi/18)/6 + re(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3 + sin(pi/18)/2 + 2 + I*(-cos(pi/18)/2 -
sqrt(3)*sin(pi/18)/6 + im(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3), re(1/((-1/2 + sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*cos(pi/18)/6 - sin(pi/18)/2 + 2 +
I*(im(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 -
sqrt(3)*sin(pi/18)/6 + cos(pi/18)/2))'''))
# if that is changed so a non-comparable number remains as
# an arg, then the Min/Max instantiation needs to be changed
# to watch out for non-comparable args when making simplifications
# and the following test should be added instead (with e being
# the sympified expression above):
# raises(ValueError, lambda: e._eval_evalf(2))
def test_issue_10395():
eq = x*Max(0, y)
assert nfloat(eq) == eq
eq = x*Max(y, -1.1)
assert nfloat(eq) == eq
assert Max(y, 4).n() == Max(4.0, y)
def test_issue_13098():
assert floor(log(S('9.'+'9'*20), 10)) == 0
assert ceiling(log(S('9.'+'9'*20), 10)) == 1
assert floor(log(20 - S('9.'+'9'*20), 10)) == 1
assert ceiling(log(20 - S('9.'+'9'*20), 10)) == 2
def test_issue_14601():
e = 5*x*y/2 - y*(35*(x**3)/2 - 15*x/2)
subst = {x:0.0, y:0.0}
e2 = e.evalf(subs=subst)
assert float(e2) == 0.0
assert float((x + x*(x**2 + x)).evalf(subs={x: 0.0})) == 0.0
def test_issue_11151():
z = S.Zero
e = Sum(z, (x, 1, 2))
assert e != z # it shouldn't evaluate
# when it does evaluate, this is what it should give
assert evalf(e, 15, {}) == \
evalf(z, 15, {}) == (None, None, 15, None)
# so this shouldn't fail
assert (e/2).n() == 0
# this was where the issue appeared
expr0 = Sum(x**2 + x, (x, 1, 2))
expr1 = Sum(0, (x, 1, 2))
expr2 = expr1/expr0
assert simplify(factor(expr2) - expr2) == 0
def test_issue_13425():
assert N('2**.5', 30) == N('sqrt(2)', 30)
assert N('x - x', 30) == 0
assert abs((N('pi*.1', 22)*10 - pi).n()) < 1e-22
def test_issue_17421():
assert N(acos(-I + acosh(cosh(cosh(1) + I)))) == 1.0*I
|
addd4aafbe63c49ccf08998748830e9d75927be37ca978923f56515eff5f940f | from sympy import (abc, Add, cos, collect, Derivative, diff, exp, Float, Function,
I, Integer, log, Mul, oo, Poly, Rational, S, sin, sqrt, Symbol, symbols,
Wild, pi, meijerg
)
from sympy.utilities.pytest import XFAIL
def test_symbol():
x = Symbol('x')
a, b, c, p, q = map(Wild, 'abcpq')
e = x
assert e.match(x) == {}
assert e.matches(x) == {}
assert e.match(a) == {a: x}
e = Rational(5)
assert e.match(c) == {c: 5}
assert e.match(e) == {}
assert e.match(e + 1) is None
def test_add():
x, y, a, b, c = map(Symbol, 'xyabc')
p, q, r = map(Wild, 'pqr')
e = a + b
assert e.match(p + b) == {p: a}
assert e.match(p + a) == {p: b}
e = 1 + b
assert e.match(p + b) == {p: 1}
e = a + b + c
assert e.match(a + p + c) == {p: b}
assert e.match(b + p + c) == {p: a}
e = a + b + c + x
assert e.match(a + p + x + c) == {p: b}
assert e.match(b + p + c + x) == {p: a}
assert e.match(b) is None
assert e.match(b + p) == {p: a + c + x}
assert e.match(a + p + c) == {p: b + x}
assert e.match(b + p + c) == {p: a + x}
e = 4*x + 5
assert e.match(4*x + p) == {p: 5}
assert e.match(3*x + p) == {p: x + 5}
assert e.match(p*x + 5) == {p: 4}
def test_power():
x, y, a, b, c = map(Symbol, 'xyabc')
p, q, r = map(Wild, 'pqr')
e = (x + y)**a
assert e.match(p**q) == {p: x + y, q: a}
assert e.match(p**p) is None
e = (x + y)**(x + y)
assert e.match(p**p) == {p: x + y}
assert e.match(p**q) == {p: x + y, q: x + y}
e = (2*x)**2
assert e.match(p*q**r) == {p: 4, q: x, r: 2}
e = Integer(1)
assert e.match(x**p) == {p: 0}
def test_match_exclude():
x = Symbol('x')
y = Symbol('y')
p = Wild("p")
q = Wild("q")
r = Wild("r")
e = Rational(6)
assert e.match(2*p) == {p: 3}
e = 3/(4*x + 5)
assert e.match(3/(p*x + q)) == {p: 4, q: 5}
e = 3/(4*x + 5)
assert e.match(p/(q*x + r)) == {p: 3, q: 4, r: 5}
e = 2/(x + 1)
assert e.match(p/(q*x + r)) == {p: 2, q: 1, r: 1}
e = 1/(x + 1)
assert e.match(p/(q*x + r)) == {p: 1, q: 1, r: 1}
e = 4*x + 5
assert e.match(p*x + q) == {p: 4, q: 5}
e = 4*x + 5*y + 6
assert e.match(p*x + q*y + r) == {p: 4, q: 5, r: 6}
a = Wild('a', exclude=[x])
e = 3*x
assert e.match(p*x) == {p: 3}
assert e.match(a*x) == {a: 3}
e = 3*x**2
assert e.match(p*x) == {p: 3*x}
assert e.match(a*x) is None
e = 3*x + 3 + 6/x
assert e.match(p*x**2 + p*x + 2*p) == {p: 3/x}
assert e.match(a*x**2 + a*x + 2*a) is None
def test_mul():
x, y, a, b, c = map(Symbol, 'xyabc')
p, q = map(Wild, 'pq')
e = 4*x
assert e.match(p*x) == {p: 4}
assert e.match(p*y) is None
assert e.match(e + p*y) == {p: 0}
e = a*x*b*c
assert e.match(p*x) == {p: a*b*c}
assert e.match(c*p*x) == {p: a*b}
e = (a + b)*(a + c)
assert e.match((p + b)*(p + c)) == {p: a}
e = x
assert e.match(p*x) == {p: 1}
e = exp(x)
assert e.match(x**p*exp(x*q)) == {p: 0, q: 1}
e = I*Poly(x, x)
assert e.match(I*p) == {p: x}
def test_mul_noncommutative():
x, y = symbols('x y')
A, B, C = symbols('A B C', commutative=False)
u, v = symbols('u v', cls=Wild)
w, z = symbols('w z', cls=Wild, commutative=False)
assert (u*v).matches(x) in ({v: x, u: 1}, {u: x, v: 1})
assert (u*v).matches(x*y) in ({v: y, u: x}, {u: y, v: x})
assert (u*v).matches(A) is None
assert (u*v).matches(A*B) is None
assert (u*v).matches(x*A) is None
assert (u*v).matches(x*y*A) is None
assert (u*v).matches(x*A*B) is None
assert (u*v).matches(x*y*A*B) is None
assert (v*w).matches(x) is None
assert (v*w).matches(x*y) is None
assert (v*w).matches(A) == {w: A, v: 1}
assert (v*w).matches(A*B) == {w: A*B, v: 1}
assert (v*w).matches(x*A) == {w: A, v: x}
assert (v*w).matches(x*y*A) == {w: A, v: x*y}
assert (v*w).matches(x*A*B) == {w: A*B, v: x}
assert (v*w).matches(x*y*A*B) == {w: A*B, v: x*y}
assert (v*w).matches(-x) is None
assert (v*w).matches(-x*y) is None
assert (v*w).matches(-A) == {w: A, v: -1}
assert (v*w).matches(-A*B) == {w: A*B, v: -1}
assert (v*w).matches(-x*A) == {w: A, v: -x}
assert (v*w).matches(-x*y*A) == {w: A, v: -x*y}
assert (v*w).matches(-x*A*B) == {w: A*B, v: -x}
assert (v*w).matches(-x*y*A*B) == {w: A*B, v: -x*y}
assert (w*z).matches(x) is None
assert (w*z).matches(x*y) is None
assert (w*z).matches(A) is None
assert (w*z).matches(A*B) == {w: A, z: B}
assert (w*z).matches(B*A) == {w: B, z: A}
assert (w*z).matches(A*B*C) in [{w: A, z: B*C}, {w: A*B, z: C}]
assert (w*z).matches(x*A) is None
assert (w*z).matches(x*y*A) is None
assert (w*z).matches(x*A*B) is None
assert (w*z).matches(x*y*A*B) is None
assert (w*A).matches(A) is None
assert (A*w*B).matches(A*B) is None
assert (u*w*z).matches(x) is None
assert (u*w*z).matches(x*y) is None
assert (u*w*z).matches(A) is None
assert (u*w*z).matches(A*B) == {u: 1, w: A, z: B}
assert (u*w*z).matches(B*A) == {u: 1, w: B, z: A}
assert (u*w*z).matches(x*A) is None
assert (u*w*z).matches(x*y*A) is None
assert (u*w*z).matches(x*A*B) == {u: x, w: A, z: B}
assert (u*w*z).matches(x*B*A) == {u: x, w: B, z: A}
assert (u*w*z).matches(x*y*A*B) == {u: x*y, w: A, z: B}
assert (u*w*z).matches(x*y*B*A) == {u: x*y, w: B, z: A}
assert (u*A).matches(x*A) == {u: x}
assert (u*A).matches(x*A*B) is None
assert (u*B).matches(x*A) is None
assert (u*A*B).matches(x*A*B) == {u: x}
assert (u*A*B).matches(x*B*A) is None
assert (u*A*B).matches(x*A) is None
assert (u*w*A).matches(x*A*B) is None
assert (u*w*B).matches(x*A*B) == {u: x, w: A}
assert (u*v*A*B).matches(x*A*B) in [{u: x, v: 1}, {v: x, u: 1}]
assert (u*v*A*B).matches(x*B*A) is None
assert (u*v*A*B).matches(u*v*A*C) is None
def test_mul_noncommutative_mismatch():
A, B, C = symbols('A B C', commutative=False)
w = symbols('w', cls=Wild, commutative=False)
assert (w*B*w).matches(A*B*A) == {w: A}
assert (w*B*w).matches(A*C*B*A*C) == {w: A*C}
assert (w*B*w).matches(A*C*B*A*B) is None
assert (w*B*w).matches(A*B*C) is None
assert (w*w*C).matches(A*B*C) is None
def test_mul_noncommutative_pow():
A, B, C = symbols('A B C', commutative=False)
w = symbols('w', cls=Wild, commutative=False)
assert (A*B*w).matches(A*B**2) == {w: B}
assert (A*(B**2)*w*(B**3)).matches(A*B**8) == {w: B**3}
assert (A*B*w*C).matches(A*(B**4)*C) == {w: B**3}
assert (A*B*(w**(-1))).matches(A*B*(C**(-1))) == {w: C}
assert (A*(B*w)**(-1)*C).matches(A*(B*C)**(-1)*C) == {w: C}
assert ((w**2)*B*C).matches((A**2)*B*C) == {w: A}
assert ((w**2)*B*(w**3)).matches((A**2)*B*(A**3)) == {w: A}
assert ((w**2)*B*(w**4)).matches((A**2)*B*(A**2)) is None
def test_complex():
a, b, c = map(Symbol, 'abc')
x, y = map(Wild, 'xy')
assert (1 + I).match(x + I) == {x: 1}
assert (a + I).match(x + I) == {x: a}
assert (2*I).match(x*I) == {x: 2}
assert (a*I).match(x*I) == {x: a}
assert (a*I).match(x*y) == {x: I, y: a}
assert (2*I).match(x*y) == {x: 2, y: I}
assert (a + b*I).match(x + y*I) == {x: a, y: b}
def test_functions():
from sympy.core.function import WildFunction
x = Symbol('x')
g = WildFunction('g')
p = Wild('p')
q = Wild('q')
f = cos(5*x)
notf = x
assert f.match(p*cos(q*x)) == {p: 1, q: 5}
assert f.match(p*g) == {p: 1, g: cos(5*x)}
assert notf.match(g) is None
@XFAIL
def test_functions_X1():
from sympy.core.function import WildFunction
x = Symbol('x')
g = WildFunction('g')
p = Wild('p')
q = Wild('q')
f = cos(5*x)
assert f.match(p*g(q*x)) == {p: 1, g: cos, q: 5}
def test_interface():
x, y = map(Symbol, 'xy')
p, q = map(Wild, 'pq')
assert (x + 1).match(p + 1) == {p: x}
assert (x*3).match(p*3) == {p: x}
assert (x**3).match(p**3) == {p: x}
assert (x*cos(y)).match(p*cos(q)) == {p: x, q: y}
assert (x*y).match(p*q) in [{p:x, q:y}, {p:y, q:x}]
assert (x + y).match(p + q) in [{p:x, q:y}, {p:y, q:x}]
assert (x*y + 1).match(p*q) in [{p:1, q:1 + x*y}, {p:1 + x*y, q:1}]
def test_derivative1():
x, y = map(Symbol, 'xy')
p, q = map(Wild, 'pq')
f = Function('f', nargs=1)
fd = Derivative(f(x), x)
assert fd.match(p) == {p: fd}
assert (fd + 1).match(p + 1) == {p: fd}
assert (fd).match(fd) == {}
assert (3*fd).match(p*fd) is not None
assert (3*fd - 1).match(p*fd + q) == {p: 3, q: -1}
def test_derivative_bug1():
f = Function("f")
x = Symbol("x")
a = Wild("a", exclude=[f, x])
b = Wild("b", exclude=[f])
pattern = a * Derivative(f(x), x, x) + b
expr = Derivative(f(x), x) + x**2
d1 = {b: x**2}
d2 = pattern.xreplace(d1).matches(expr, d1)
assert d2 is None
def test_derivative2():
f = Function("f")
x = Symbol("x")
a = Wild("a", exclude=[f, x])
b = Wild("b", exclude=[f])
e = Derivative(f(x), x)
assert e.match(Derivative(f(x), x)) == {}
assert e.match(Derivative(f(x), x, x)) is None
e = Derivative(f(x), x, x)
assert e.match(Derivative(f(x), x)) is None
assert e.match(Derivative(f(x), x, x)) == {}
e = Derivative(f(x), x) + x**2
assert e.match(a*Derivative(f(x), x) + b) == {a: 1, b: x**2}
assert e.match(a*Derivative(f(x), x, x) + b) is None
e = Derivative(f(x), x, x) + x**2
assert e.match(a*Derivative(f(x), x) + b) is None
assert e.match(a*Derivative(f(x), x, x) + b) == {a: 1, b: x**2}
def test_match_deriv_bug1():
n = Function('n')
l = Function('l')
x = Symbol('x')
p = Wild('p')
e = diff(l(x), x)/x - diff(diff(n(x), x), x)/2 - \
diff(n(x), x)**2/4 + diff(n(x), x)*diff(l(x), x)/4
e = e.subs(n(x), -l(x)).doit()
t = x*exp(-l(x))
t2 = t.diff(x, x)/t
assert e.match( (p*t2).expand() ) == {p: Rational(-1, 2)}
def test_match_bug2():
x, y = map(Symbol, 'xy')
p, q, r = map(Wild, 'pqr')
res = (x + y).match(p + q + r)
assert (p + q + r).subs(res) == x + y
def test_match_bug3():
x, a, b = map(Symbol, 'xab')
p = Wild('p')
assert (b*x*exp(a*x)).match(x*exp(p*x)) is None
def test_match_bug4():
x = Symbol('x')
p = Wild('p')
e = x
assert e.match(-p*x) == {p: -1}
def test_match_bug5():
x = Symbol('x')
p = Wild('p')
e = -x
assert e.match(-p*x) == {p: 1}
def test_match_bug6():
x = Symbol('x')
p = Wild('p')
e = x
assert e.match(3*p*x) == {p: Rational(1)/3}
def test_match_polynomial():
x = Symbol('x')
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
c = Wild('c', exclude=[x])
d = Wild('d', exclude=[x])
eq = 4*x**3 + 3*x**2 + 2*x + 1
pattern = a*x**3 + b*x**2 + c*x + d
assert eq.match(pattern) == {a: 4, b: 3, c: 2, d: 1}
assert (eq - 3*x**2).match(pattern) == {a: 4, b: 0, c: 2, d: 1}
assert (x + sqrt(2) + 3).match(a + b*x + c*x**2) == \
{b: 1, a: sqrt(2) + 3, c: 0}
def test_exclude():
x, y, a = map(Symbol, 'xya')
p = Wild('p', exclude=[1, x])
q = Wild('q')
r = Wild('r', exclude=[sin, y])
assert sin(x).match(r) is None
assert cos(y).match(r) is None
e = 3*x**2 + y*x + a
assert e.match(p*x**2 + q*x + r) == {p: 3, q: y, r: a}
e = x + 1
assert e.match(x + p) is None
assert e.match(p + 1) is None
assert e.match(x + 1 + p) == {p: 0}
e = cos(x) + 5*sin(y)
assert e.match(r) is None
assert e.match(cos(y) + r) is None
assert e.match(r + p*sin(q)) == {r: cos(x), p: 5, q: y}
def test_floats():
a, b = map(Wild, 'ab')
e = cos(0.12345, evaluate=False)**2
r = e.match(a*cos(b)**2)
assert r == {a: 1, b: Float(0.12345)}
def test_Derivative_bug1():
f = Function("f")
x = abc.x
a = Wild("a", exclude=[f(x)])
b = Wild("b", exclude=[f(x)])
eq = f(x).diff(x)
assert eq.match(a*Derivative(f(x), x) + b) == {a: 1, b: 0}
def test_match_wild_wild():
p = Wild('p')
q = Wild('q')
r = Wild('r')
assert p.match(q + r) in [ {q: p, r: 0}, {q: 0, r: p} ]
assert p.match(q*r) in [ {q: p, r: 1}, {q: 1, r: p} ]
p = Wild('p')
q = Wild('q', exclude=[p])
r = Wild('r')
assert p.match(q + r) == {q: 0, r: p}
assert p.match(q*r) == {q: 1, r: p}
p = Wild('p')
q = Wild('q', exclude=[p])
r = Wild('r', exclude=[p])
assert p.match(q + r) is None
assert p.match(q*r) is None
def test__combine_inverse():
x, y = symbols("x y")
assert Mul._combine_inverse(x*I*y, x*I) == y
assert Mul._combine_inverse(x*x**(1 + y), x**(1 + y)) == x
assert Mul._combine_inverse(x*I*y, y*I) == x
assert Mul._combine_inverse(oo*I*y, y*I) is oo
assert Mul._combine_inverse(oo*I*y, oo*I) == y
assert Mul._combine_inverse(oo*I*y, oo*I) == y
assert Mul._combine_inverse(oo*y, -oo) == -y
assert Mul._combine_inverse(-oo*y, oo) == -y
assert Add._combine_inverse(oo, oo) is S.Zero
assert Add._combine_inverse(oo*I, oo*I) is S.Zero
assert Add._combine_inverse(x*oo, x*oo) is S.Zero
assert Add._combine_inverse(-x*oo, -x*oo) is S.Zero
assert Add._combine_inverse((x - oo)*(x + oo), -oo)
def test_issue_3773():
x = symbols('x')
z, phi, r = symbols('z phi r')
c, A, B, N = symbols('c A B N', cls=Wild)
l = Wild('l', exclude=(0,))
eq = z * sin(2*phi) * r**7
matcher = c * sin(phi*N)**l * r**A * log(r)**B
assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7, B: 0}
assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7, B: 0}
assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7, B: 0}
assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7, B: 0}
matcher = c*sin(phi*N)**l * r**A
assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7}
assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7}
assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7}
assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7}
def test_issue_3883():
from sympy.abc import gamma, mu, x
f = (-gamma * (x - mu)**2 - log(gamma) + log(2*pi))/2
a, b, c = symbols('a b c', cls=Wild, exclude=(gamma,))
assert f.match(a * log(gamma) + b * gamma + c) == \
{a: Rational(-1, 2), b: -(x - mu)**2/2, c: log(2*pi)/2}
assert f.expand().collect(gamma).match(a * log(gamma) + b * gamma + c) == \
{a: Rational(-1, 2), b: (-(x - mu)**2/2).expand(), c: (log(2*pi)/2).expand()}
g1 = Wild('g1', exclude=[gamma])
g2 = Wild('g2', exclude=[gamma])
g3 = Wild('g3', exclude=[gamma])
assert f.expand().match(g1 * log(gamma) + g2 * gamma + g3) == \
{g3: log(2)/2 + log(pi)/2, g1: Rational(-1, 2), g2: -mu**2/2 + mu*x - x**2/2}
def test_issue_4418():
x = Symbol('x')
a, b, c = symbols('a b c', cls=Wild, exclude=(x,))
f, g = symbols('f g', cls=Function)
eq = diff(g(x)*f(x).diff(x), x)
assert eq.match(
g(x).diff(x)*f(x).diff(x) + g(x)*f(x).diff(x, x) + c) == {c: 0}
assert eq.match(a*g(x).diff(
x)*f(x).diff(x) + b*g(x)*f(x).diff(x, x) + c) == {a: 1, b: 1, c: 0}
def test_issue_4700():
f = Function('f')
x = Symbol('x')
a, b = symbols('a b', cls=Wild, exclude=(f(x),))
p = a*f(x) + b
eq1 = sin(x)
eq2 = f(x) + sin(x)
eq3 = f(x) + x + sin(x)
eq4 = x + sin(x)
assert eq1.match(p) == {a: 0, b: sin(x)}
assert eq2.match(p) == {a: 1, b: sin(x)}
assert eq3.match(p) == {a: 1, b: x + sin(x)}
assert eq4.match(p) == {a: 0, b: x + sin(x)}
def test_issue_5168():
a, b, c = symbols('a b c', cls=Wild)
x = Symbol('x')
f = Function('f')
assert x.match(a) == {a: x}
assert x.match(a*f(x)**c) == {a: x, c: 0}
assert x.match(a*b) == {a: 1, b: x}
assert x.match(a*b*f(x)**c) == {a: 1, b: x, c: 0}
assert (-x).match(a) == {a: -x}
assert (-x).match(a*f(x)**c) == {a: -x, c: 0}
assert (-x).match(a*b) == {a: -1, b: x}
assert (-x).match(a*b*f(x)**c) == {a: -1, b: x, c: 0}
assert (2*x).match(a) == {a: 2*x}
assert (2*x).match(a*f(x)**c) == {a: 2*x, c: 0}
assert (2*x).match(a*b) == {a: 2, b: x}
assert (2*x).match(a*b*f(x)**c) == {a: 2, b: x, c: 0}
assert (-2*x).match(a) == {a: -2*x}
assert (-2*x).match(a*f(x)**c) == {a: -2*x, c: 0}
assert (-2*x).match(a*b) == {a: -2, b: x}
assert (-2*x).match(a*b*f(x)**c) == {a: -2, b: x, c: 0}
def test_issue_4559():
x = Symbol('x')
e = Symbol('e')
w = Wild('w', exclude=[x])
y = Wild('y')
# this is as it should be
assert (3/x).match(w/y) == {w: 3, y: x}
assert (3*x).match(w*y) == {w: 3, y: x}
assert (x/3).match(y/w) == {w: 3, y: x}
assert (3*x).match(y/w) == {w: S.One/3, y: x}
assert (3*x).match(y/w) == {w: Rational(1, 3), y: x}
# these could be allowed to fail
assert (x/3).match(w/y) == {w: S.One/3, y: 1/x}
assert (3*x).match(w/y) == {w: 3, y: 1/x}
assert (3/x).match(w*y) == {w: 3, y: 1/x}
# Note that solve will give
# multiple roots but match only gives one:
#
# >>> solve(x**r-y**2,y)
# [-x**(r/2), x**(r/2)]
r = Symbol('r', rational=True)
assert (x**r).match(y**2) == {y: x**(r/2)}
assert (x**e).match(y**2) == {y: sqrt(x**e)}
# since (x**i = y) -> x = y**(1/i) where i is an integer
# the following should also be valid as long as y is not
# zero when i is negative.
a = Wild('a')
e = S.Zero
assert e.match(a) == {a: e}
assert e.match(1/a) is None
assert e.match(a**.3) is None
e = S(3)
assert e.match(1/a) == {a: 1/e}
assert e.match(1/a**2) == {a: 1/sqrt(e)}
e = pi
assert e.match(1/a) == {a: 1/e}
assert e.match(1/a**2) == {a: 1/sqrt(e)}
assert (-e).match(sqrt(a)) is None
assert (-e).match(a**2) == {a: I*sqrt(pi)}
# The pattern matcher doesn't know how to handle (x - a)**2 == (a - x)**2. To
# avoid ambiguity in actual applications, don't put a coefficient (including a
# minus sign) in front of a wild.
@XFAIL
def test_issue_4883():
a = Wild('a')
x = Symbol('x')
e = [i**2 for i in (x - 2, 2 - x)]
p = [i**2 for i in (x - a, a- x)]
for eq in e:
for pat in p:
assert eq.match(pat) == {a: 2}
def test_issue_4319():
x, y = symbols('x y')
p = -x*(S.One/8 - y)
ans = {S.Zero, y - S.One/8}
def ok(pat):
assert set(p.match(pat).values()) == ans
ok(Wild("coeff", exclude=[x])*x + Wild("rest"))
ok(Wild("w", exclude=[x])*x + Wild("rest"))
ok(Wild("coeff", exclude=[x])*x + Wild("rest"))
ok(Wild("w", exclude=[x])*x + Wild("rest"))
ok(Wild("e", exclude=[x])*x + Wild("rest"))
ok(Wild("ress", exclude=[x])*x + Wild("rest"))
ok(Wild("resu", exclude=[x])*x + Wild("rest"))
def test_issue_3778():
p, c, q = symbols('p c q', cls=Wild)
x = Symbol('x')
assert (sin(x)**2).match(sin(p)*sin(q)*c) == {q: x, c: 1, p: x}
assert (2*sin(x)).match(sin(p) + sin(q) + c) == {q: x, c: 0, p: x}
def test_issue_6103():
x = Symbol('x')
a = Wild('a')
assert (-I*x*oo).match(I*a*oo) == {a: -x}
def test_issue_3539():
a = Wild('a')
x = Symbol('x')
assert (x - 2).match(a - x) is None
assert (6/x).match(a*x) is None
assert (6/x**2).match(a/x) == {a: 6/x}
def test_gh_issue_2711():
x = Symbol('x')
f = meijerg(((), ()), ((0,), ()), x)
a = Wild('a')
b = Wild('b')
assert f.find(a) == set([(S.Zero,), ((), ()), ((S.Zero,), ()), x, S.Zero,
(), meijerg(((), ()), ((S.Zero,), ()), x)])
assert f.find(a + b) == \
{meijerg(((), ()), ((S.Zero,), ()), x), x, S.Zero}
assert f.find(a**2) == {meijerg(((), ()), ((S.Zero,), ()), x), x}
def test_match_issue_17397():
f = Function("f")
x = Symbol("x")
a3 = Wild('a3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
b3 = Wild('b3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
c3 = Wild('c3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
deq = a3*(f(x).diff(x, 2)) + b3*f(x).diff(x) + c3*f(x)
eq = (x-2)**2*(f(x).diff(x, 2)) + (x-2)*(f(x).diff(x)) + ((x-2)**2 - 4)*f(x)
r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
assert r == {a3: (x - 2)**2, c3: (x - 2)**2 - 4, b3: x - 2}
eq =x*f(x) + x*Derivative(f(x), (x, 2)) - 4*f(x) + Derivative(f(x), x) \
- 4*Derivative(f(x), (x, 2)) - 2*Derivative(f(x), x)/x + 4*Derivative(f(x), (x, 2))/x
r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
assert r == {a3: x - 4 + 4/x, b3: 1 - 2/x, c3: x - 4}
|
a717d945b56551154ef419ddf79af02a4265d3682dfab7f0c0fd30a5c7eeb943 | from sympy import (Basic, Symbol, sin, cos, atan, exp, sqrt, Rational,
Float, re, pi, sympify, Add, Mul, Pow, Mod, I, log, S, Max, symbols,
oo, zoo, Integer, sign, im, nan, Dummy, factorial, comp, refine,
floor
)
from sympy.core.compatibility import long, range
from sympy.core.evaluate import distribute
from sympy.core.expr import unchanged
from sympy.utilities.iterables import cartes
from sympy.utilities.pytest import XFAIL, raises
from sympy.utilities.randtest import verify_numerically
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():
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
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_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_Add_Mul_is_integer():
x = Symbol('x')
k = Symbol('k', integer=True)
n = Symbol('n', integer=True)
assert (2*k).is_integer is True
assert (-k).is_integer is True
assert (k/3).is_integer is None
assert (x*k*n).is_integer is None
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 ((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
@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
x = Symbol('x', real=True, integer=False)
assert (x**2).is_integer is None # issue 8641
def test_Pow_is_real():
x = Symbol('x', real=True)
y = Symbol('y', real=True, 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
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)
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
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
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 ((-k)**n).is_nonnegative is True
assert ((-k)**m).is_nonpositive is True
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, finite=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():
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
@XFAIL
def test_issue_3531():
class MightyNumeric(tuple):
def __rdiv__(self, other):
return "something"
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 == (3, 2)
assert b != 6
assert b.func is Mul
assert b.args == (3, 2)
assert c != 9
assert c.func is Pow
assert c.args == (3, 2)
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():
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)
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():
from sympy import I, pi
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
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
factorial(18042, evaluate=False) % 18043 == 18042
p = Symbol('n', prime=True)
factorial(p - 1) % p == p - 1
factorial(p - 1) % -p == -1
(factorial(3, evaluate=False) % 4).doit() == 2
n = Symbol('n', composite=True, odd=True)
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)
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
@XFAIL
def test_failing_Mod_Pow_nested():
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
# XXX This fails in nondeterministic way because of the overflow
# error in mpmath
expr = Pow(expr, expr, evaluate=False)
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 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', '')) == \
long(112345678901234567890)
assert int(Float('1.123456789012345678901234567890e25', '')) == \
long(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, finite=True)
r = Dummy(real=True)
c = Dummy(real=False, complex=True, finite=True)
c2 = Dummy(real=False, complex=True, finite=True)
i = Dummy(imaginary=True, finite=True)
e = nz*r*c
assert e.is_imaginary is None
assert e.is_real is None
e = nz*c
assert e.is_imaginary is None
assert e.is_real is False
e = nz*i*c
assert e.is_imaginary is False
assert e.is_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_real is None
# _eval_is_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_real and e.is_zero
else:
assert e.is_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 cartes(*[[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 cartes(*[[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_positive is None
assert e.is_hermitian is None
e = Mul(inf, zer, evaluate=False)
assert e.is_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 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)
|
44830d1fd8f7832a7f360c4a5d699f3ef38b2f18c75b7607f28369c30b31f2ea | from sympy.polys.domains import QQ, EX, RR
from sympy.polys.rings import ring
from sympy.polys.ring_series import (_invert_monoms, rs_integrate,
rs_trunc, rs_mul, rs_square, rs_pow, _has_constant_term, rs_hadamard_exp,
rs_series_from_list, rs_exp, rs_log, rs_newton, rs_series_inversion,
rs_compose_add, rs_asin, rs_atan, rs_atanh, rs_tan, rs_cot, rs_sin, rs_cos,
rs_cos_sin, rs_sinh, rs_cosh, rs_tanh, _tan1, rs_fun, rs_nth_root,
rs_LambertW, rs_series_reversion, rs_is_puiseux, rs_series)
from sympy.utilities.pytest import raises
from sympy.core.compatibility import range
from sympy.core.symbol import symbols
from sympy.functions import (sin, cos, exp, tan, cot, atan, atanh,
tanh, log, sqrt)
from sympy.core.numbers import Rational
from sympy.core import expand, S
def is_close(a, b):
tol = 10**(-10)
assert abs(a - b) < tol
def test_ring_series1():
R, x = ring('x', QQ)
p = x**4 + 2*x**3 + 3*x + 4
assert _invert_monoms(p) == 4*x**4 + 3*x**3 + 2*x + 1
assert rs_hadamard_exp(p) == x**4/24 + x**3/3 + 3*x + 4
R, x = ring('x', QQ)
p = x**4 + 2*x**3 + 3*x + 4
assert rs_integrate(p, x) == x**5/5 + x**4/2 + 3*x**2/2 + 4*x
R, x, y = ring('x, y', QQ)
p = x**2*y**2 + x + 1
assert rs_integrate(p, x) == x**3*y**2/3 + x**2/2 + x
assert rs_integrate(p, y) == x**2*y**3/3 + x*y + y
def test_trunc():
R, x, y, t = ring('x, y, t', QQ)
p = (y + t*x)**4
p1 = rs_trunc(p, x, 3)
assert p1 == y**4 + 4*y**3*t*x + 6*y**2*t**2*x**2
def test_mul_trunc():
R, x, y, t = ring('x, y, t', QQ)
p = 1 + t*x + t*y
for i in range(2):
p = rs_mul(p, p, t, 3)
assert p == 6*x**2*t**2 + 12*x*y*t**2 + 6*y**2*t**2 + 4*x*t + 4*y*t + 1
p = 1 + t*x + t*y + t**2*x*y
p1 = rs_mul(p, p, t, 2)
assert p1 == 1 + 2*t*x + 2*t*y
R1, z = ring('z', QQ)
def test1(p):
p2 = rs_mul(p, z, x, 2)
raises(ValueError, lambda: test1(p))
p1 = 2 + 2*x + 3*x**2
p2 = 3 + x**2
assert rs_mul(p1, p2, x, 4) == 2*x**3 + 11*x**2 + 6*x + 6
def test_square_trunc():
R, x, y, t = ring('x, y, t', QQ)
p = (1 + t*x + t*y)*2
p1 = rs_mul(p, p, x, 3)
p2 = rs_square(p, x, 3)
assert p1 == p2
p = 1 + x + x**2 + x**3
assert rs_square(p, x, 4) == 4*x**3 + 3*x**2 + 2*x + 1
def test_pow_trunc():
R, x, y, z = ring('x, y, z', QQ)
p0 = y + x*z
p = p0**16
for xx in (x, y, z):
p1 = rs_trunc(p, xx, 8)
p2 = rs_pow(p0, 16, xx, 8)
assert p1 == p2
p = 1 + x
p1 = rs_pow(p, 3, x, 2)
assert p1 == 1 + 3*x
assert rs_pow(p, 0, x, 2) == 1
assert rs_pow(p, -2, x, 2) == 1 - 2*x
p = x + y
assert rs_pow(p, 3, y, 3) == x**3 + 3*x**2*y + 3*x*y**2
assert rs_pow(1 + x, Rational(2, 3), x, 4) == 4*x**3/81 - x**2/9 + x*Rational(2, 3) + 1
def test_has_constant_term():
R, x, y, z = ring('x, y, z', QQ)
p = y + x*z
assert _has_constant_term(p, x)
p = x + x**4
assert not _has_constant_term(p, x)
p = 1 + x + x**4
assert _has_constant_term(p, x)
p = x + y + x*z
def test_inversion():
R, x = ring('x', QQ)
p = 2 + x + 2*x**2
n = 5
p1 = rs_series_inversion(p, x, n)
assert rs_trunc(p*p1, x, n) == 1
R, x, y = ring('x, y', QQ)
p = 2 + x + 2*x**2 + y*x + x**2*y
p1 = rs_series_inversion(p, x, n)
assert rs_trunc(p*p1, x, n) == 1
R, x, y = ring('x, y', QQ)
p = 1 + x + y
def test2(p):
p1 = rs_series_inversion(p, x, 4)
raises(NotImplementedError, lambda: test2(p))
p = R.zero
def test3(p):
p1 = rs_series_inversion(p, x, 3)
raises(ZeroDivisionError, lambda: test3(p))
def test_series_reversion():
R, x, y = ring('x, y', QQ)
p = rs_tan(x, x, 10)
assert rs_series_reversion(p, x, 8, y) == rs_atan(y, y, 8)
p = rs_sin(x, x, 10)
assert rs_series_reversion(p, x, 8, y) == 5*y**7/112 + 3*y**5/40 + \
y**3/6 + y
def test_series_from_list():
R, x = ring('x', QQ)
p = 1 + 2*x + x**2 + 3*x**3
c = [1, 2, 0, 4, 4]
r = rs_series_from_list(p, c, x, 5)
pc = R.from_list(list(reversed(c)))
r1 = rs_trunc(pc.compose(x, p), x, 5)
assert r == r1
R, x, y = ring('x, y', QQ)
c = [1, 3, 5, 7]
p1 = rs_series_from_list(x + y, c, x, 3, concur=0)
p2 = rs_trunc((1 + 3*(x+y) + 5*(x+y)**2 + 7*(x+y)**3), x, 3)
assert p1 == p2
R, x = ring('x', QQ)
h = 25
p = rs_exp(x, x, h) - 1
p1 = rs_series_from_list(p, c, x, h)
p2 = 0
for i, cx in enumerate(c):
p2 += cx*rs_pow(p, i, x, h)
assert p1 == p2
def test_log():
R, x = ring('x', QQ)
p = 1 + x
p1 = rs_log(p, x, 4)/x**2
assert p1 == Rational(1, 3)*x - S.Half + x**(-1)
p = 1 + x +2*x**2/3
p1 = rs_log(p, x, 9)
assert p1 == -17*x**8/648 + 13*x**7/189 - 11*x**6/162 - x**5/45 + \
7*x**4/36 - x**3/3 + x**2/6 + x
p2 = rs_series_inversion(p, x, 9)
p3 = rs_log(p2, x, 9)
assert p3 == -p1
R, x, y = ring('x, y', QQ)
p = 1 + x + 2*y*x**2
p1 = rs_log(p, x, 6)
assert p1 == (4*x**5*y**2 - 2*x**5*y - 2*x**4*y**2 + x**5/5 + 2*x**4*y -
x**4/4 - 2*x**3*y + x**3/3 + 2*x**2*y - x**2/2 + x)
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_log(x + a, x, 5) == -EX(1/(4*a**4))*x**4 + EX(1/(3*a**3))*x**3 \
- EX(1/(2*a**2))*x**2 + EX(1/a)*x + EX(log(a))
assert rs_log(x + x**2*y + a, x, 4) == -EX(a**(-2))*x**3*y + \
EX(1/(3*a**3))*x**3 + EX(1/a)*x**2*y - EX(1/(2*a**2))*x**2 + \
EX(1/a)*x + EX(log(a))
p = x + x**2 + 3
assert rs_log(p, x, 10).compose(x, 5) == EX(log(3) + Rational(19281291595, 9920232))
def test_exp():
R, x = ring('x', QQ)
p = x + x**4
for h in [10, 30]:
q = rs_series_inversion(1 + p, x, h) - 1
p1 = rs_exp(q, x, h)
q1 = rs_log(p1, x, h)
assert q1 == q
p1 = rs_exp(p, x, 30)
assert p1.coeff(x**29) == QQ(74274246775059676726972369, 353670479749588078181744640000)
prec = 21
p = rs_log(1 + x, x, prec)
p1 = rs_exp(p, x, prec)
assert p1 == x + 1
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[exp(a), a])
assert rs_exp(x + a, x, 5) == exp(a)*x**4/24 + exp(a)*x**3/6 + \
exp(a)*x**2/2 + exp(a)*x + exp(a)
assert rs_exp(x + x**2*y + a, x, 5) == exp(a)*x**4*y**2/2 + \
exp(a)*x**4*y/2 + exp(a)*x**4/24 + exp(a)*x**3*y + \
exp(a)*x**3/6 + exp(a)*x**2*y + exp(a)*x**2/2 + exp(a)*x + exp(a)
R, x, y = ring('x, y', EX)
assert rs_exp(x + a, x, 5) == EX(exp(a)/24)*x**4 + EX(exp(a)/6)*x**3 + \
EX(exp(a)/2)*x**2 + EX(exp(a))*x + EX(exp(a))
assert rs_exp(x + x**2*y + a, x, 5) == EX(exp(a)/2)*x**4*y**2 + \
EX(exp(a)/2)*x**4*y + EX(exp(a)/24)*x**4 + EX(exp(a))*x**3*y + \
EX(exp(a)/6)*x**3 + EX(exp(a))*x**2*y + EX(exp(a)/2)*x**2 + \
EX(exp(a))*x + EX(exp(a))
def test_newton():
R, x = ring('x', QQ)
p = x**2 - 2
r = rs_newton(p, x, 4)
assert r == 8*x**4 + 4*x**2 + 2
def test_compose_add():
R, x = ring('x', QQ)
p1 = x**3 - 1
p2 = x**2 - 2
assert rs_compose_add(p1, p2) == x**6 - 6*x**4 - 2*x**3 + 12*x**2 - 12*x - 7
def test_fun():
R, x, y = ring('x, y', QQ)
p = x*y + x**2*y**3 + x**5*y
assert rs_fun(p, rs_tan, x, 10) == rs_tan(p, x, 10)
assert rs_fun(p, _tan1, x, 10) == _tan1(p, x, 10)
def test_nth_root():
R, x, y = ring('x, y', QQ)
assert rs_nth_root(1 + x**2*y, 4, x, 10) == -77*x**8*y**4/2048 + \
7*x**6*y**3/128 - 3*x**4*y**2/32 + x**2*y/4 + 1
assert rs_nth_root(1 + x*y + x**2*y**3, 3, x, 5) == -x**4*y**6/9 + \
5*x**4*y**5/27 - 10*x**4*y**4/243 - 2*x**3*y**4/9 + 5*x**3*y**3/81 + \
x**2*y**3/3 - x**2*y**2/9 + x*y/3 + 1
assert rs_nth_root(8*x, 3, x, 3) == 2*x**QQ(1, 3)
assert rs_nth_root(8*x + x**2 + x**3, 3, x, 3) == x**QQ(4,3)/12 + 2*x**QQ(1,3)
r = rs_nth_root(8*x + x**2*y + x**3, 3, x, 4)
assert r == -x**QQ(7,3)*y**2/288 + x**QQ(7,3)/12 + x**QQ(4,3)*y/12 + 2*x**QQ(1,3)
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_nth_root(x + a, 3, x, 4) == EX(5/(81*a**QQ(8, 3)))*x**3 - \
EX(1/(9*a**QQ(5, 3)))*x**2 + EX(1/(3*a**QQ(2, 3)))*x + EX(a**QQ(1, 3))
assert rs_nth_root(x**QQ(2, 3) + x**2*y + 5, 2, x, 3) == -EX(sqrt(5)/100)*\
x**QQ(8, 3)*y - EX(sqrt(5)/16000)*x**QQ(8, 3) + EX(sqrt(5)/10)*x**2*y + \
EX(sqrt(5)/2000)*x**2 - EX(sqrt(5)/200)*x**QQ(4, 3) + \
EX(sqrt(5)/10)*x**QQ(2, 3) + EX(sqrt(5))
def test_atan():
R, x, y = ring('x, y', QQ)
assert rs_atan(x, x, 9) == -x**7/7 + x**5/5 - x**3/3 + x
assert rs_atan(x*y + x**2*y**3, x, 9) == 2*x**8*y**11 - x**8*y**9 + \
2*x**7*y**9 - x**7*y**7/7 - x**6*y**9/3 + x**6*y**7 - x**5*y**7 + \
x**5*y**5/5 - x**4*y**5 - x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_atan(x + a, x, 5) == -EX((a**3 - a)/(a**8 + 4*a**6 + 6*a**4 + \
4*a**2 + 1))*x**4 + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + \
9*a**2 + 3))*x**3 - EX(a/(a**4 + 2*a**2 + 1))*x**2 + \
EX(1/(a**2 + 1))*x + EX(atan(a))
assert rs_atan(x + x**2*y + a, x, 4) == -EX(2*a/(a**4 + 2*a**2 + 1)) \
*x**3*y + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + 9*a**2 + 3))*x**3 + \
EX(1/(a**2 + 1))*x**2*y - EX(a/(a**4 + 2*a**2 + 1))*x**2 + EX(1/(a**2 \
+ 1))*x + EX(atan(a))
def test_asin():
R, x, y = ring('x, y', QQ)
assert rs_asin(x + x*y, x, 5) == x**3*y**3/6 + x**3*y**2/2 + x**3*y/2 + \
x**3/6 + x*y + x
assert rs_asin(x*y + x**2*y**3, x, 6) == x**5*y**7/2 + 3*x**5*y**5/40 + \
x**4*y**5/2 + x**3*y**3/6 + x**2*y**3 + x*y
def test_tan():
R, x, y = ring('x, y', QQ)
assert rs_tan(x, x, 9)/x**5 == \
Rational(17, 315)*x**2 + Rational(2, 15) + Rational(1, 3)*x**(-2) + x**(-4)
assert rs_tan(x*y + x**2*y**3, x, 9) == 4*x**8*y**11/3 + 17*x**8*y**9/45 + \
4*x**7*y**9/3 + 17*x**7*y**7/315 + x**6*y**9/3 + 2*x**6*y**7/3 + \
x**5*y**7 + 2*x**5*y**5/15 + x**4*y**5 + x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[tan(a), a])
assert rs_tan(x + a, x, 5) == (tan(a)**5 + 5*tan(a)**3/3 +
2*tan(a)/3)*x**4 + (tan(a)**4 + 4*tan(a)**2/3 + Rational(1, 3))*x**3 + \
(tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a)
assert rs_tan(x + x**2*y + a, x, 4) == (2*tan(a)**3 + 2*tan(a))*x**3*y + \
(tan(a)**4 + Rational(4, 3)*tan(a)**2 + Rational(1, 3))*x**3 + (tan(a)**2 + 1)*x**2*y + \
(tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a)
R, x, y = ring('x, y', EX)
assert rs_tan(x + a, x, 5) == EX(tan(a)**5 + 5*tan(a)**3/3 +
2*tan(a)/3)*x**4 + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \
EX(tan(a)**3 + tan(a))*x**2 + EX(tan(a)**2 + 1)*x + EX(tan(a))
assert rs_tan(x + x**2*y + a, x, 4) == EX(2*tan(a)**3 +
2*tan(a))*x**3*y + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \
EX(tan(a)**2 + 1)*x**2*y + EX(tan(a)**3 + tan(a))*x**2 + \
EX(tan(a)**2 + 1)*x + EX(tan(a))
p = x + x**2 + 5
assert rs_atan(p, x, 10).compose(x, 10) == EX(atan(5) + S(67701870330562640) / \
668083460499)
def test_cot():
R, x, y = ring('x, y', QQ)
assert rs_cot(x**6 + x**7, x, 8) == x**(-6) - x**(-5) + x**(-4) - \
x**(-3) + x**(-2) - x**(-1) + 1 - x + x**2 - x**3 + x**4 - x**5 + \
2*x**6/3 - 4*x**7/3
assert rs_cot(x + x**2*y, x, 5) == -x**4*y**5 - x**4*y/15 + x**3*y**4 - \
x**3/45 - x**2*y**3 - x**2*y/3 + x*y**2 - x/3 - y + x**(-1)
def test_sin():
R, x, y = ring('x, y', QQ)
assert rs_sin(x, x, 9)/x**5 == \
Rational(-1, 5040)*x**2 + Rational(1, 120) - Rational(1, 6)*x**(-2) + x**(-4)
assert rs_sin(x*y + x**2*y**3, x, 9) == x**8*y**11/12 - \
x**8*y**9/720 + x**7*y**9/12 - x**7*y**7/5040 - x**6*y**9/6 + \
x**6*y**7/24 - x**5*y**7/2 + x**5*y**5/120 - x**4*y**5/2 - \
x**3*y**3/6 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[sin(a), cos(a), a])
assert rs_sin(x + a, x, 5) == sin(a)*x**4/24 - cos(a)*x**3/6 - \
sin(a)*x**2/2 + cos(a)*x + sin(a)
assert rs_sin(x + x**2*y + a, x, 5) == -sin(a)*x**4*y**2/2 - \
cos(a)*x**4*y/2 + sin(a)*x**4/24 - sin(a)*x**3*y - cos(a)*x**3/6 + \
cos(a)*x**2*y - sin(a)*x**2/2 + cos(a)*x + sin(a)
R, x, y = ring('x, y', EX)
assert rs_sin(x + a, x, 5) == EX(sin(a)/24)*x**4 - EX(cos(a)/6)*x**3 - \
EX(sin(a)/2)*x**2 + EX(cos(a))*x + EX(sin(a))
assert rs_sin(x + x**2*y + a, x, 5) == -EX(sin(a)/2)*x**4*y**2 - \
EX(cos(a)/2)*x**4*y + EX(sin(a)/24)*x**4 - EX(sin(a))*x**3*y - \
EX(cos(a)/6)*x**3 + EX(cos(a))*x**2*y - EX(sin(a)/2)*x**2 + \
EX(cos(a))*x + EX(sin(a))
def test_cos():
R, x, y = ring('x, y', QQ)
assert rs_cos(x, x, 9)/x**5 == \
Rational(1, 40320)*x**3 - Rational(1, 720)*x + Rational(1, 24)*x**(-1) - S.Half*x**(-3) + x**(-5)
assert rs_cos(x*y + x**2*y**3, x, 9) == x**8*y**12/24 - \
x**8*y**10/48 + x**8*y**8/40320 + x**7*y**10/6 - \
x**7*y**8/120 + x**6*y**8/4 - x**6*y**6/720 + x**5*y**6/6 - \
x**4*y**6/2 + x**4*y**4/24 - x**3*y**4 - x**2*y**2/2 + 1
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[sin(a), cos(a), a])
assert rs_cos(x + a, x, 5) == cos(a)*x**4/24 + sin(a)*x**3/6 - \
cos(a)*x**2/2 - sin(a)*x + cos(a)
assert rs_cos(x + x**2*y + a, x, 5) == -cos(a)*x**4*y**2/2 + \
sin(a)*x**4*y/2 + cos(a)*x**4/24 - cos(a)*x**3*y + sin(a)*x**3/6 - \
sin(a)*x**2*y - cos(a)*x**2/2 - sin(a)*x + cos(a)
R, x, y = ring('x, y', EX)
assert rs_cos(x + a, x, 5) == EX(cos(a)/24)*x**4 + EX(sin(a)/6)*x**3 - \
EX(cos(a)/2)*x**2 - EX(sin(a))*x + EX(cos(a))
assert rs_cos(x + x**2*y + a, x, 5) == -EX(cos(a)/2)*x**4*y**2 + \
EX(sin(a)/2)*x**4*y + EX(cos(a)/24)*x**4 - EX(cos(a))*x**3*y + \
EX(sin(a)/6)*x**3 - EX(sin(a))*x**2*y - EX(cos(a)/2)*x**2 - \
EX(sin(a))*x + EX(cos(a))
def test_cos_sin():
R, x, y = ring('x, y', QQ)
cos, sin = rs_cos_sin(x, x, 9)
assert cos == rs_cos(x, x, 9)
assert sin == rs_sin(x, x, 9)
cos, sin = rs_cos_sin(x + x*y, x, 5)
assert cos == rs_cos(x + x*y, x, 5)
assert sin == rs_sin(x + x*y, x, 5)
def test_atanh():
R, x, y = ring('x, y', QQ)
assert rs_atanh(x, x, 9)/x**5 == Rational(1, 7)*x**2 + Rational(1, 5) + Rational(1, 3)*x**(-2) + x**(-4)
assert rs_atanh(x*y + x**2*y**3, x, 9) == 2*x**8*y**11 + x**8*y**9 + \
2*x**7*y**9 + x**7*y**7/7 + x**6*y**9/3 + x**6*y**7 + x**5*y**7 + \
x**5*y**5/5 + x**4*y**5 + x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_atanh(x + a, x, 5) == EX((a**3 + a)/(a**8 - 4*a**6 + 6*a**4 - \
4*a**2 + 1))*x**4 - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + \
9*a**2 - 3))*x**3 + EX(a/(a**4 - 2*a**2 + 1))*x**2 - EX(1/(a**2 - \
1))*x + EX(atanh(a))
assert rs_atanh(x + x**2*y + a, x, 4) == EX(2*a/(a**4 - 2*a**2 + \
1))*x**3*y - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + 9*a**2 - 3))*x**3 - \
EX(1/(a**2 - 1))*x**2*y + EX(a/(a**4 - 2*a**2 + 1))*x**2 - \
EX(1/(a**2 - 1))*x + EX(atanh(a))
p = x + x**2 + 5
assert rs_atanh(p, x, 10).compose(x, 10) == EX(Rational(-733442653682135, 5079158784) \
+ atanh(5))
def test_sinh():
R, x, y = ring('x, y', QQ)
assert rs_sinh(x, x, 9)/x**5 == Rational(1, 5040)*x**2 + Rational(1, 120) + Rational(1, 6)*x**(-2) + x**(-4)
assert rs_sinh(x*y + x**2*y**3, x, 9) == x**8*y**11/12 + \
x**8*y**9/720 + x**7*y**9/12 + x**7*y**7/5040 + x**6*y**9/6 + \
x**6*y**7/24 + x**5*y**7/2 + x**5*y**5/120 + x**4*y**5/2 + \
x**3*y**3/6 + x**2*y**3 + x*y
def test_cosh():
R, x, y = ring('x, y', QQ)
assert rs_cosh(x, x, 9)/x**5 == Rational(1, 40320)*x**3 + Rational(1, 720)*x + Rational(1, 24)*x**(-1) + \
S.Half*x**(-3) + x**(-5)
assert rs_cosh(x*y + x**2*y**3, x, 9) == x**8*y**12/24 + \
x**8*y**10/48 + x**8*y**8/40320 + x**7*y**10/6 + \
x**7*y**8/120 + x**6*y**8/4 + x**6*y**6/720 + x**5*y**6/6 + \
x**4*y**6/2 + x**4*y**4/24 + x**3*y**4 + x**2*y**2/2 + 1
def test_tanh():
R, x, y = ring('x, y', QQ)
assert rs_tanh(x, x, 9)/x**5 == Rational(-17, 315)*x**2 + Rational(2, 15) - Rational(1, 3)*x**(-2) + x**(-4)
assert rs_tanh(x*y + x**2*y**3, x, 9) == 4*x**8*y**11/3 - \
17*x**8*y**9/45 + 4*x**7*y**9/3 - 17*x**7*y**7/315 - x**6*y**9/3 + \
2*x**6*y**7/3 - x**5*y**7 + 2*x**5*y**5/15 - x**4*y**5 - \
x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_tanh(x + a, x, 5) == EX(tanh(a)**5 - 5*tanh(a)**3/3 +
2*tanh(a)/3)*x**4 + EX(-tanh(a)**4 + 4*tanh(a)**2/3 - QQ(1, 3))*x**3 + \
EX(tanh(a)**3 - tanh(a))*x**2 + EX(-tanh(a)**2 + 1)*x + EX(tanh(a))
p = rs_tanh(x + x**2*y + a, x, 4)
assert (p.compose(x, 10)).compose(y, 5) == EX(-1000*tanh(a)**4 + \
10100*tanh(a)**3 + 2470*tanh(a)**2/3 - 10099*tanh(a) + QQ(530, 3))
def test_RR():
rs_funcs = [rs_sin, rs_cos, rs_tan, rs_cot, rs_atan, rs_tanh]
sympy_funcs = [sin, cos, tan, cot, atan, tanh]
R, x, y = ring('x, y', RR)
a = symbols('a')
for rs_func, sympy_func in zip(rs_funcs, sympy_funcs):
p = rs_func(2 + x, x, 5).compose(x, 5)
q = sympy_func(2 + a).series(a, 0, 5).removeO()
is_close(p.as_expr(), q.subs(a, 5).n())
p = rs_nth_root(2 + x, 5, x, 5).compose(x, 5)
q = ((2 + a)**QQ(1, 5)).series(a, 0, 5).removeO()
is_close(p.as_expr(), q.subs(a, 5).n())
def test_is_regular():
R, x, y = ring('x, y', QQ)
p = 1 + 2*x + x**2 + 3*x**3
assert not rs_is_puiseux(p, x)
p = x + x**QQ(1,5)*y
assert rs_is_puiseux(p, x)
assert not rs_is_puiseux(p, y)
p = x + x**2*y**QQ(1,5)*y
assert not rs_is_puiseux(p, x)
def test_puiseux():
R, x, y = ring('x, y', QQ)
p = x**QQ(2,5) + x**QQ(2,3) + x
r = rs_series_inversion(p, x, 1)
r1 = -x**QQ(14,15) + x**QQ(4,5) - 3*x**QQ(11,15) + x**QQ(2,3) + \
2*x**QQ(7,15) - x**QQ(2,5) - x**QQ(1,5) + x**QQ(2,15) - x**QQ(-2,15) \
+ x**QQ(-2,5)
assert r == r1
r = rs_nth_root(1 + p, 3, x, 1)
assert r == -x**QQ(4,5)/9 + x**QQ(2,3)/3 + x**QQ(2,5)/3 + 1
r = rs_log(1 + p, x, 1)
assert r == -x**QQ(4,5)/2 + x**QQ(2,3) + x**QQ(2,5)
r = rs_LambertW(p, x, 1)
assert r == -x**QQ(4,5) + x**QQ(2,3) + x**QQ(2,5)
p1 = x + x**QQ(1,5)*y
r = rs_exp(p1, x, 1)
assert r == x**QQ(4,5)*y**4/24 + x**QQ(3,5)*y**3/6 + x**QQ(2,5)*y**2/2 + \
x**QQ(1,5)*y + 1
r = rs_atan(p, x, 2)
assert r == -x**QQ(9,5) - x**QQ(26,15) - x**QQ(22,15) - x**QQ(6,5)/3 + \
x + x**QQ(2,3) + x**QQ(2,5)
r = rs_atan(p1, x, 2)
assert r == x**QQ(9,5)*y**9/9 + x**QQ(9,5)*y**4 - x**QQ(7,5)*y**7/7 - \
x**QQ(7,5)*y**2 + x*y**5/5 + x - x**QQ(3,5)*y**3/3 + x**QQ(1,5)*y
r = rs_asin(p, x, 2)
assert r == x**QQ(9,5)/2 + x**QQ(26,15)/2 + x**QQ(22,15)/2 + \
x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5)
r = rs_cot(p, x, 1)
assert r == -x**QQ(14,15) + x**QQ(4,5) - 3*x**QQ(11,15) + \
2*x**QQ(2,3)/3 + 2*x**QQ(7,15) - 4*x**QQ(2,5)/3 - x**QQ(1,5) + \
x**QQ(2,15) - x**QQ(-2,15) + x**QQ(-2,5)
r = rs_cos_sin(p, x, 2)
assert r[0] == x**QQ(28,15)/6 - x**QQ(5,3) + x**QQ(8,5)/24 - x**QQ(7,5) - \
x**QQ(4,3)/2 - x**QQ(16,15) - x**QQ(4,5)/2 + 1
assert r[1] == -x**QQ(9,5)/2 - x**QQ(26,15)/2 - x**QQ(22,15)/2 - \
x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5)
r = rs_atanh(p, x, 2)
assert r == x**QQ(9,5) + x**QQ(26,15) + x**QQ(22,15) + x**QQ(6,5)/3 + x + \
x**QQ(2,3) + x**QQ(2,5)
r = rs_sinh(p, x, 2)
assert r == x**QQ(9,5)/2 + x**QQ(26,15)/2 + x**QQ(22,15)/2 + \
x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5)
r = rs_cosh(p, x, 2)
assert r == x**QQ(28,15)/6 + x**QQ(5,3) + x**QQ(8,5)/24 + x**QQ(7,5) + \
x**QQ(4,3)/2 + x**QQ(16,15) + x**QQ(4,5)/2 + 1
r = rs_tanh(p, x, 2)
assert r == -x**QQ(9,5) - x**QQ(26,15) - x**QQ(22,15) - x**QQ(6,5)/3 + \
x + x**QQ(2,3) + x**QQ(2,5)
def test1():
R, x = ring('x', QQ)
r = rs_sin(x, x, 15)*x**(-5)
assert r == x**8/6227020800 - x**6/39916800 + x**4/362880 - x**2/5040 + \
QQ(1,120) - x**-2/6 + x**-4
p = rs_sin(x, x, 10)
r = rs_nth_root(p, 2, x, 10)
assert r == -67*x**QQ(17,2)/29030400 - x**QQ(13,2)/24192 + \
x**QQ(9,2)/1440 - x**QQ(5,2)/12 + x**QQ(1,2)
p = rs_sin(x, x, 10)
r = rs_nth_root(p, 7, x, 10)
r = rs_pow(r, 5, x, 10)
assert r == -97*x**QQ(61,7)/124467840 - x**QQ(47,7)/16464 + \
11*x**QQ(33,7)/3528 - 5*x**QQ(19,7)/42 + x**QQ(5,7)
r = rs_exp(x**QQ(1,2), x, 10)
assert r == x**QQ(19,2)/121645100408832000 + x**9/6402373705728000 + \
x**QQ(17,2)/355687428096000 + x**8/20922789888000 + \
x**QQ(15,2)/1307674368000 + x**7/87178291200 + \
x**QQ(13,2)/6227020800 + x**6/479001600 + x**QQ(11,2)/39916800 + \
x**5/3628800 + x**QQ(9,2)/362880 + x**4/40320 + x**QQ(7,2)/5040 + \
x**3/720 + x**QQ(5,2)/120 + x**2/24 + x**QQ(3,2)/6 + x/2 + \
x**QQ(1,2) + 1
def test_puiseux2():
R, y = ring('y', QQ)
S, x = ring('x', R)
p = x + x**QQ(1,5)*y
r = rs_atan(p, x, 3)
assert r == (y**13/13 + y**8 + 2*y**3)*x**QQ(13,5) - (y**11/11 + y**6 +
y)*x**QQ(11,5) + (y**9/9 + y**4)*x**QQ(9,5) - (y**7/7 +
y**2)*x**QQ(7,5) + (y**5/5 + 1)*x - y**3*x**QQ(3,5)/3 + y*x**QQ(1,5)
def test_rs_series():
x, a, b, c = symbols('x, a, b, c')
assert rs_series(a, a, 5).as_expr() == a
assert rs_series(sin(a), a, 5).as_expr() == (sin(a).series(a, 0,
5)).removeO()
assert rs_series(sin(a) + cos(a), a, 5).as_expr() == ((sin(a) +
cos(a)).series(a, 0, 5)).removeO()
assert rs_series(sin(a)*cos(a), a, 5).as_expr() == ((sin(a)*
cos(a)).series(a, 0, 5)).removeO()
p = (sin(a) - a)*(cos(a**2) + a**4/2)
assert expand(rs_series(p, a, 10).as_expr()) == expand(p.series(a, 0,
10).removeO())
p = sin(a**2/2 + a/3) + cos(a/5)*sin(a/2)**3
assert expand(rs_series(p, a, 5).as_expr()) == expand(p.series(a, 0,
5).removeO())
p = sin(x**2 + a)*(cos(x**3 - 1) - a - a**2)
assert expand(rs_series(p, a, 5).as_expr()) == expand(p.series(a, 0,
5).removeO())
p = sin(a**2 - a/3 + 2)**5*exp(a**3 - a/2)
assert expand(rs_series(p, a, 10).as_expr()) == expand(p.series(a, 0,
10).removeO())
p = sin(a + b + c)
assert expand(rs_series(p, a, 5).as_expr()) == expand(p.series(a, 0,
5).removeO())
p = tan(sin(a**2 + 4) + b + c)
assert expand(rs_series(p, a, 6).as_expr()) == expand(p.series(a, 0,
6).removeO())
p = a**QQ(2,5) + a**QQ(2,3) + a
r = rs_series(tan(p), a, 2)
assert r.as_expr() == a**QQ(9,5) + a**QQ(26,15) + a**QQ(22,15) + a**QQ(6,5)/3 + \
a + a**QQ(2,3) + a**QQ(2,5)
r = rs_series(exp(p), a, 1)
assert r.as_expr() == a**QQ(4,5)/2 + a**QQ(2,3) + a**QQ(2,5) + 1
r = rs_series(sin(p), a, 2)
assert r.as_expr() == -a**QQ(9,5)/2 - a**QQ(26,15)/2 - a**QQ(22,15)/2 - \
a**QQ(6,5)/6 + a + a**QQ(2,3) + a**QQ(2,5)
r = rs_series(cos(p), a, 2)
assert r.as_expr() == a**QQ(28,15)/6 - a**QQ(5,3) + a**QQ(8,5)/24 - a**QQ(7,5) - \
a**QQ(4,3)/2 - a**QQ(16,15) - a**QQ(4,5)/2 + 1
assert rs_series(sin(a)/7, a, 5).as_expr() == (sin(a)/7).series(a, 0,
5).removeO()
assert rs_series(log(1 + x), x, 5).as_expr() == -x**4/4 + x**3/3 - \
x**2/2 + x
assert rs_series(log(1 + 4*x), x, 5).as_expr() == -64*x**4 + 64*x**3/3 - \
8*x**2 + 4*x
assert rs_series(log(1 + x + x**2), x, 10).as_expr() == -2*x**9/9 + \
x**8/8 + x**7/7 - x**6/3 + x**5/5 + x**4/4 - 2*x**3/3 + \
x**2/2 + x
assert rs_series(log(1 + x*a**2), x, 7).as_expr() == -x**6*a**12/6 + \
x**5*a**10/5 - x**4*a**8/4 + x**3*a**6/3 - \
x**2*a**4/2 + x*a**2
|
660ba415121c16b8a42e1c350d0aec9ba766f5b633c5f82fcac34bf9a44798d7 | """Tests for tools and arithmetics for monomials of distributed polynomials. """
from sympy.polys.monomials import (
itermonomials, monomial_count,
monomial_mul, monomial_div,
monomial_gcd, monomial_lcm,
monomial_max, monomial_min,
monomial_divides, monomial_pow,
Monomial,
)
from sympy.polys.polyerrors import ExactQuotientFailed
from sympy.abc import a, b, c, x, y, z
from sympy.core import S, symbols
from sympy.utilities.pytest import raises
def test_monomials():
# total_degree tests
assert set(itermonomials([], 0)) == {S.One}
assert set(itermonomials([], 1)) == {S.One}
assert set(itermonomials([], 2)) == {S.One}
assert set(itermonomials([], 0, 0)) == {S.One}
assert set(itermonomials([], 1, 0)) == {S.One}
assert set(itermonomials([], 2, 0)) == {S.One}
raises(StopIteration, lambda: next(itermonomials([], 0, 1)))
raises(StopIteration, lambda: next(itermonomials([], 0, 2)))
raises(StopIteration, lambda: next(itermonomials([], 0, 3)))
assert set(itermonomials([], 0, 1)) == set()
assert set(itermonomials([], 0, 2)) == set()
assert set(itermonomials([], 0, 3)) == set()
raises(ValueError, lambda: set(itermonomials([], -1)))
raises(ValueError, lambda: set(itermonomials([x], -1)))
raises(ValueError, lambda: set(itermonomials([x, y], -1)))
assert set(itermonomials([x], 0)) == {S.One}
assert set(itermonomials([x], 1)) == {S.One, x}
assert set(itermonomials([x], 2)) == {S.One, x, x**2}
assert set(itermonomials([x], 3)) == {S.One, x, x**2, x**3}
assert set(itermonomials([x, y], 0)) == {S.One}
assert set(itermonomials([x, y], 1)) == {S.One, x, y}
assert set(itermonomials([x, y], 2)) == {S.One, x, y, x**2, y**2, x*y}
assert set(itermonomials([x, y], 3)) == \
{S.One, x, y, x**2, x**3, y**2, y**3, x*y, x*y**2, y*x**2}
i, j, k = symbols('i j k', commutative=False)
assert set(itermonomials([i, j, k], 0)) == {S.One}
assert set(itermonomials([i, j, k], 1)) == {S.One, i, j, k}
assert set(itermonomials([i, j, k], 2)) == \
{S.One, i, j, k, i**2, j**2, k**2, i*j, i*k, j*i, j*k, k*i, k*j}
assert set(itermonomials([i, j, k], 3)) == \
{S.One, i, j, k, i**2, j**2, k**2, i*j, i*k, j*i, j*k, k*i, k*j,
i**3, j**3, k**3,
i**2 * j, i**2 * k, j * i**2, k * i**2,
j**2 * i, j**2 * k, i * j**2, k * j**2,
k**2 * i, k**2 * j, i * k**2, j * k**2,
i*j*i, i*k*i, j*i*j, j*k*j, k*i*k, k*j*k,
i*j*k, i*k*j, j*i*k, j*k*i, k*i*j, k*j*i,
}
assert set(itermonomials([x, i, j], 0)) == {S.One}
assert set(itermonomials([x, i, j], 1)) == {S.One, x, i, j}
assert set(itermonomials([x, i, j], 2)) == {S.One, x, i, j, x*i, x*j, i*j, j*i, x**2, i**2, j**2}
assert set(itermonomials([x, i, j], 3)) == \
{S.One, x, i, j, x*i, x*j, i*j, j*i, x**2, i**2, j**2,
x**3, i**3, j**3,
x**2 * i, x**2 * j,
x * i**2, j * i**2, i**2 * j, i*j*i,
x * j**2, i * j**2, j**2 * i, j*i*j,
x * i * j, x * j * i
}
# degree_list tests
assert set(itermonomials([], [])) == {S.One}
raises(ValueError, lambda: set(itermonomials([], [0])))
raises(ValueError, lambda: set(itermonomials([], [1])))
raises(ValueError, lambda: set(itermonomials([], [2])))
raises(ValueError, lambda: set(itermonomials([x], [1], [])))
raises(ValueError, lambda: set(itermonomials([x], [1, 2], [])))
raises(ValueError, lambda: set(itermonomials([x], [1, 2, 3], [])))
raises(ValueError, lambda: set(itermonomials([x], [], [1])))
raises(ValueError, lambda: set(itermonomials([x], [], [1, 2])))
raises(ValueError, lambda: set(itermonomials([x], [], [1, 2, 3])))
raises(ValueError, lambda: set(itermonomials([x, y], [1, 2], [1, 2, 3])))
raises(ValueError, lambda: set(itermonomials([x, y, z], [1, 2, 3], [0, 1])))
raises(ValueError, lambda: set(itermonomials([x], [1], [-1])))
raises(ValueError, lambda: set(itermonomials([x, y], [1, 2], [1, -1])))
raises(ValueError, lambda: set(itermonomials([], [], 1)))
raises(ValueError, lambda: set(itermonomials([], [], 2)))
raises(ValueError, lambda: set(itermonomials([], [], 3)))
raises(ValueError, lambda: set(itermonomials([x, y], [0, 1], [1, 2])))
raises(ValueError, lambda: set(itermonomials([x, y, z], [0, 0, 3], [0, 1, 2])))
assert set(itermonomials([x], [0])) == {S.One}
assert set(itermonomials([x], [1])) == {S.One, x}
assert set(itermonomials([x], [2])) == {S.One, x, x**2}
assert set(itermonomials([x], [3])) == {S.One, x, x**2, x**3}
assert set(itermonomials([x], [3], [1])) == {x, x**3, x**2}
assert set(itermonomials([x], [3], [2])) == {x**3, x**2}
assert set(itermonomials([x, y], [0, 0])) == {S.One}
assert set(itermonomials([x, y], [0, 1])) == {S.One, y}
assert set(itermonomials([x, y], [0, 2])) == {S.One, y, y**2}
assert set(itermonomials([x, y], [0, 2], [0, 1])) == {y, y**2}
assert set(itermonomials([x, y], [0, 2], [0, 2])) == {y**2}
assert set(itermonomials([x, y], [1, 0])) == {S.One, x}
assert set(itermonomials([x, y], [1, 1])) == {S.One, x, y, x*y}
assert set(itermonomials([x, y], [1, 2])) == {S.One, x, y, x*y, y**2, x*y**2}
assert set(itermonomials([x, y], [1, 2], [1, 1])) == {x*y, x*y**2}
assert set(itermonomials([x, y], [1, 2], [1, 2])) == {x*y**2}
assert set(itermonomials([x, y], [2, 0])) == {S.One, x, x**2}
assert set(itermonomials([x, y], [2, 1])) == {S.One, x, y, x*y, x**2, x**2*y}
assert set(itermonomials([x, y], [2, 2])) == \
{S.One, y**2, x*y**2, x, x*y, x**2, x**2*y**2, y, x**2*y}
i, j, k = symbols('i j k', commutative=False)
assert set(itermonomials([i, j, k], [0, 0, 0])) == {S.One}
assert set(itermonomials([i, j, k], [0, 0, 1])) == {1, k}
assert set(itermonomials([i, j, k], [0, 1, 0])) == {1, j}
assert set(itermonomials([i, j, k], [1, 0, 0])) == {i, 1}
assert set(itermonomials([i, j, k], [0, 0, 2])) == {k**2, 1, k}
assert set(itermonomials([i, j, k], [0, 2, 0])) == {1, j, j**2}
assert set(itermonomials([i, j, k], [2, 0, 0])) == {i, 1, i**2}
assert set(itermonomials([i, j, k], [1, 1, 1])) == {1, k, j, j*k, i*k, i, i*j, i*j*k}
assert set(itermonomials([i, j, k], [2, 2, 2])) == \
{1, k, i**2*k**2, j*k, j**2, i, i*k, j*k**2, i*j**2*k**2,
i**2*j, i**2*j**2, k**2, j**2*k, i*j**2*k,
j**2*k**2, i*j, i**2*k, i**2*j**2*k, j, i**2*j*k,
i*j**2, i*k**2, i*j*k, i**2*j**2*k**2, i*j*k**2, i**2, i**2*j*k**2
}
assert set(itermonomials([x, j, k], [0, 0, 0])) == {S.One}
assert set(itermonomials([x, j, k], [0, 0, 1])) == {1, k}
assert set(itermonomials([x, j, k], [0, 1, 0])) == {1, j}
assert set(itermonomials([x, j, k], [1, 0, 0])) == {x, 1}
assert set(itermonomials([x, j, k], [0, 0, 2])) == {k**2, 1, k}
assert set(itermonomials([x, j, k], [0, 2, 0])) == {1, j, j**2}
assert set(itermonomials([x, j, k], [2, 0, 0])) == {x, 1, x**2}
assert set(itermonomials([x, j, k], [1, 1, 1])) == {1, k, j, j*k, x*k, x, x*j, x*j*k}
assert set(itermonomials([x, j, k], [2, 2, 2])) == \
{1, k, x**2*k**2, j*k, j**2, x, x*k, j*k**2, x*j**2*k**2,
x**2*j, x**2*j**2, k**2, j**2*k, x*j**2*k,
j**2*k**2, x*j, x**2*k, x**2*j**2*k, j, x**2*j*k,
x*j**2, x*k**2, x*j*k, x**2*j**2*k**2, x*j*k**2, x**2, x**2*j*k**2
}
def test_monomial_count():
assert monomial_count(2, 2) == 6
assert monomial_count(2, 3) == 10
def test_monomial_mul():
assert monomial_mul((3, 4, 1), (1, 2, 0)) == (4, 6, 1)
def test_monomial_div():
assert monomial_div((3, 4, 1), (1, 2, 0)) == (2, 2, 1)
def test_monomial_gcd():
assert monomial_gcd((3, 4, 1), (1, 2, 0)) == (1, 2, 0)
def test_monomial_lcm():
assert monomial_lcm((3, 4, 1), (1, 2, 0)) == (3, 4, 1)
def test_monomial_max():
assert monomial_max((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (6, 5, 9)
def test_monomial_pow():
assert monomial_pow((1, 2, 3), 3) == (3, 6, 9)
def test_monomial_min():
assert monomial_min((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (0, 3, 1)
def test_monomial_divides():
assert monomial_divides((1, 2, 3), (4, 5, 6)) is True
assert monomial_divides((1, 2, 3), (0, 5, 6)) is False
def test_Monomial():
m = Monomial((3, 4, 1), (x, y, z))
n = Monomial((1, 2, 0), (x, y, z))
assert m.as_expr() == x**3*y**4*z
assert n.as_expr() == x**1*y**2
assert m.as_expr(a, b, c) == a**3*b**4*c
assert n.as_expr(a, b, c) == a**1*b**2
assert m.exponents == (3, 4, 1)
assert m.gens == (x, y, z)
assert n.exponents == (1, 2, 0)
assert n.gens == (x, y, z)
assert m == (3, 4, 1)
assert n != (3, 4, 1)
assert m != (1, 2, 0)
assert n == (1, 2, 0)
assert (m == 1) is False
assert m[0] == m[-3] == 3
assert m[1] == m[-2] == 4
assert m[2] == m[-1] == 1
assert n[0] == n[-3] == 1
assert n[1] == n[-2] == 2
assert n[2] == n[-1] == 0
assert m[:2] == (3, 4)
assert n[:2] == (1, 2)
assert m*n == Monomial((4, 6, 1))
assert m/n == Monomial((2, 2, 1))
assert m*(1, 2, 0) == Monomial((4, 6, 1))
assert m/(1, 2, 0) == Monomial((2, 2, 1))
assert m.gcd(n) == Monomial((1, 2, 0))
assert m.lcm(n) == Monomial((3, 4, 1))
assert m.gcd((1, 2, 0)) == Monomial((1, 2, 0))
assert m.lcm((1, 2, 0)) == Monomial((3, 4, 1))
assert m**0 == Monomial((0, 0, 0))
assert m**1 == m
assert m**2 == Monomial((6, 8, 2))
assert m**3 == Monomial((9, 12, 3))
raises(ExactQuotientFailed, lambda: m/Monomial((5, 2, 0)))
mm = Monomial((1, 2, 3))
raises(ValueError, lambda: mm.as_expr())
assert str(mm) == 'Monomial((1, 2, 3))'
assert str(m) == 'x**3*y**4*z**1'
raises(NotImplementedError, lambda: m*1)
raises(NotImplementedError, lambda: m/1)
raises(ValueError, lambda: m**-1)
raises(TypeError, lambda: m.gcd(3))
raises(TypeError, lambda: m.lcm(3))
|
377660e6ea690bea8a8994d84169ad85247c4d9c9bc779fde9abf6607fb43143 | """Test sparse polynomials. """
from operator import add, mul
from sympy.polys.rings import ring, xring, sring, PolyRing, PolyElement
from sympy.polys.fields import field, FracField
from sympy.polys.domains import ZZ, QQ, RR, FF, EX
from sympy.polys.orderings import lex, grlex
from sympy.polys.polyerrors import GeneratorsError, \
ExactQuotientFailed, MultivariatePolynomialError, CoercionFailed
from sympy.utilities.pytest import raises
from sympy.core import Symbol, symbols
from sympy.core.compatibility import reduce, range
from sympy import sqrt, pi, oo
def test_PolyRing___init__():
x, y, z, t = map(Symbol, "xyzt")
assert len(PolyRing("x,y,z", ZZ, lex).gens) == 3
assert len(PolyRing(x, ZZ, lex).gens) == 1
assert len(PolyRing(("x", "y", "z"), ZZ, lex).gens) == 3
assert len(PolyRing((x, y, z), ZZ, lex).gens) == 3
assert len(PolyRing("", ZZ, lex).gens) == 0
assert len(PolyRing([], ZZ, lex).gens) == 0
raises(GeneratorsError, lambda: PolyRing(0, ZZ, lex))
assert PolyRing("x", ZZ[t], lex).domain == ZZ[t]
assert PolyRing("x", 'ZZ[t]', lex).domain == ZZ[t]
assert PolyRing("x", PolyRing("t", ZZ, lex), lex).domain == ZZ[t]
raises(GeneratorsError, lambda: PolyRing("x", PolyRing("x", ZZ, lex), lex))
_lex = Symbol("lex")
assert PolyRing("x", ZZ, lex).order == lex
assert PolyRing("x", ZZ, _lex).order == lex
assert PolyRing("x", ZZ, 'lex').order == lex
R1 = PolyRing("x,y", ZZ, lex)
R2 = PolyRing("x,y", ZZ, lex)
R3 = PolyRing("x,y,z", ZZ, lex)
assert R1.x == R1.gens[0]
assert R1.y == R1.gens[1]
assert R1.x == R2.x
assert R1.y == R2.y
assert R1.x != R3.x
assert R1.y != R3.y
def test_PolyRing___hash__():
R, x, y, z = ring("x,y,z", QQ)
assert hash(R)
def test_PolyRing___eq__():
assert ring("x,y,z", QQ)[0] == ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] is ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] != ring("x,y,z", ZZ)[0]
assert ring("x,y,z", QQ)[0] is not ring("x,y,z", ZZ)[0]
assert ring("x,y,z", ZZ)[0] != ring("x,y,z", QQ)[0]
assert ring("x,y,z", ZZ)[0] is not ring("x,y,z", QQ)[0]
assert ring("x,y,z", QQ)[0] != ring("x,y", QQ)[0]
assert ring("x,y,z", QQ)[0] is not ring("x,y", QQ)[0]
assert ring("x,y", QQ)[0] != ring("x,y,z", QQ)[0]
assert ring("x,y", QQ)[0] is not ring("x,y,z", QQ)[0]
def test_PolyRing_ring_new():
R, x, y, z = ring("x,y,z", QQ)
assert R.ring_new(7) == R(7)
assert R.ring_new(7*x*y*z) == 7*x*y*z
f = x**2 + 2*x*y + 3*x + 4*z**2 + 5*z + 6
assert R.ring_new([[[1]], [[2], [3]], [[4, 5, 6]]]) == f
assert R.ring_new({(2, 0, 0): 1, (1, 1, 0): 2, (1, 0, 0): 3, (0, 0, 2): 4, (0, 0, 1): 5, (0, 0, 0): 6}) == f
assert R.ring_new([((2, 0, 0), 1), ((1, 1, 0), 2), ((1, 0, 0), 3), ((0, 0, 2), 4), ((0, 0, 1), 5), ((0, 0, 0), 6)]) == f
R, = ring("", QQ)
assert R.ring_new([((), 7)]) == R(7)
def test_PolyRing_drop():
R, x,y,z = ring("x,y,z", ZZ)
assert R.drop(x) == PolyRing("y,z", ZZ, lex)
assert R.drop(y) == PolyRing("x,z", ZZ, lex)
assert R.drop(z) == PolyRing("x,y", ZZ, lex)
assert R.drop(0) == PolyRing("y,z", ZZ, lex)
assert R.drop(0).drop(0) == PolyRing("z", ZZ, lex)
assert R.drop(0).drop(0).drop(0) == ZZ
assert R.drop(1) == PolyRing("x,z", ZZ, lex)
assert R.drop(2) == PolyRing("x,y", ZZ, lex)
assert R.drop(2).drop(1) == PolyRing("x", ZZ, lex)
assert R.drop(2).drop(1).drop(0) == ZZ
raises(ValueError, lambda: R.drop(3))
raises(ValueError, lambda: R.drop(x).drop(y))
def test_PolyRing___getitem__():
R, x,y,z = ring("x,y,z", ZZ)
assert R[0:] == PolyRing("x,y,z", ZZ, lex)
assert R[1:] == PolyRing("y,z", ZZ, lex)
assert R[2:] == PolyRing("z", ZZ, lex)
assert R[3:] == ZZ
def test_PolyRing_is_():
R = PolyRing("x", QQ, lex)
assert R.is_univariate is True
assert R.is_multivariate is False
R = PolyRing("x,y,z", QQ, lex)
assert R.is_univariate is False
assert R.is_multivariate is True
R = PolyRing("", QQ, lex)
assert R.is_univariate is False
assert R.is_multivariate is False
def test_PolyRing_add():
R, x = ring("x", ZZ)
F = [ x**2 + 2*i + 3 for i in range(4) ]
assert R.add(F) == reduce(add, F) == 4*x**2 + 24
R, = ring("", ZZ)
assert R.add([2, 5, 7]) == 14
def test_PolyRing_mul():
R, x = ring("x", ZZ)
F = [ x**2 + 2*i + 3 for i in range(4) ]
assert R.mul(F) == reduce(mul, F) == x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945
R, = ring("", ZZ)
assert R.mul([2, 3, 5]) == 30
def test_sring():
x, y, z, t = symbols("x,y,z,t")
R = PolyRing("x,y,z", ZZ, lex)
assert sring(x + 2*y + 3*z) == (R, R.x + 2*R.y + 3*R.z)
R = PolyRing("x,y,z", QQ, lex)
assert sring(x + 2*y + z/3) == (R, R.x + 2*R.y + R.z/3)
assert sring([x, 2*y, z/3]) == (R, [R.x, 2*R.y, R.z/3])
Rt = PolyRing("t", ZZ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + 2*t*y + 3*t**2*z, x, y, z) == (R, R.x + 2*Rt.t*R.y + 3*Rt.t**2*R.z)
Rt = PolyRing("t", QQ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + t*y/2 + t**2*z/3, x, y, z) == (R, R.x + Rt.t*R.y/2 + Rt.t**2*R.z/3)
Rt = FracField("t", ZZ, lex)
R = PolyRing("x,y,z", Rt, lex)
assert sring(x + 2*y/t + t**2*z/3, x, y, z) == (R, R.x + 2*R.y/Rt.t + Rt.t**2*R.z/3)
r = sqrt(2) - sqrt(3)
R, a = sring(r, extension=True)
assert R.domain == QQ.algebraic_field(r)
assert R.gens == ()
assert a == R.domain.from_sympy(r)
def test_PolyElement___hash__():
R, x, y, z = ring("x,y,z", QQ)
assert hash(x*y*z)
def test_PolyElement___eq__():
R, x, y = ring("x,y", ZZ, lex)
assert ((x*y + 5*x*y) == 6) == False
assert ((x*y + 5*x*y) == 6*x*y) == True
assert (6 == (x*y + 5*x*y)) == False
assert (6*x*y == (x*y + 5*x*y)) == True
assert ((x*y - x*y) == 0) == True
assert (0 == (x*y - x*y)) == True
assert ((x*y - x*y) == 1) == False
assert (1 == (x*y - x*y)) == False
assert ((x*y - x*y) == 1) == False
assert (1 == (x*y - x*y)) == False
assert ((x*y + 5*x*y) != 6) == True
assert ((x*y + 5*x*y) != 6*x*y) == False
assert (6 != (x*y + 5*x*y)) == True
assert (6*x*y != (x*y + 5*x*y)) == False
assert ((x*y - x*y) != 0) == False
assert (0 != (x*y - x*y)) == False
assert ((x*y - x*y) != 1) == True
assert (1 != (x*y - x*y)) == True
Rt, t = ring("t", ZZ)
R, x, y = ring("x,y", Rt)
assert (t**3*x/x == t**3) == True
assert (t**3*x/x == t**4) == False
def test_PolyElement__lt_le_gt_ge__():
R, x, y = ring("x,y", ZZ)
assert R(1) < x < x**2 < x**3
assert R(1) <= x <= x**2 <= x**3
assert x**3 > x**2 > x > R(1)
assert x**3 >= x**2 >= x >= R(1)
def test_PolyElement_copy():
R, x, y, z = ring("x,y,z", ZZ)
f = x*y + 3*z
g = f.copy()
assert f == g
g[(1, 1, 1)] = 7
assert f != g
def test_PolyElement_as_expr():
R, x, y, z = ring("x,y,z", ZZ)
f = 3*x**2*y - x*y*z + 7*z**3 + 1
X, Y, Z = R.symbols
g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1
assert f != g
assert f.as_expr() == g
X, Y, Z = symbols("x,y,z")
g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1
assert f != g
assert f.as_expr(X, Y, Z) == g
raises(ValueError, lambda: f.as_expr(X))
R, = ring("", ZZ)
R(3).as_expr() == 3
def test_PolyElement_from_expr():
x, y, z = symbols("x,y,z")
R, X, Y, Z = ring((x, y, z), ZZ)
f = R.from_expr(1)
assert f == 1 and isinstance(f, R.dtype)
f = R.from_expr(x)
assert f == X and isinstance(f, R.dtype)
f = R.from_expr(x*y*z)
assert f == X*Y*Z and isinstance(f, R.dtype)
f = R.from_expr(x*y*z + x*y + x)
assert f == X*Y*Z + X*Y + X and isinstance(f, R.dtype)
f = R.from_expr(x**3*y*z + x**2*y**7 + 1)
assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, R.dtype)
raises(ValueError, lambda: R.from_expr(1/x))
raises(ValueError, lambda: R.from_expr(2**x))
raises(ValueError, lambda: R.from_expr(7*x + sqrt(2)))
R, = ring("", ZZ)
f = R.from_expr(1)
assert f == 1 and isinstance(f, R.dtype)
def test_PolyElement_degree():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).degree() is -oo
assert R(1).degree() == 0
assert (x + 1).degree() == 1
assert (2*y**3 + z).degree() == 0
assert (x*y**3 + z).degree() == 1
assert (x**5*y**3 + z).degree() == 5
assert R(0).degree(x) is -oo
assert R(1).degree(x) == 0
assert (x + 1).degree(x) == 1
assert (2*y**3 + z).degree(x) == 0
assert (x*y**3 + z).degree(x) == 1
assert (7*x**5*y**3 + z).degree(x) == 5
assert R(0).degree(y) is -oo
assert R(1).degree(y) == 0
assert (x + 1).degree(y) == 0
assert (2*y**3 + z).degree(y) == 3
assert (x*y**3 + z).degree(y) == 3
assert (7*x**5*y**3 + z).degree(y) == 3
assert R(0).degree(z) is -oo
assert R(1).degree(z) == 0
assert (x + 1).degree(z) == 0
assert (2*y**3 + z).degree(z) == 1
assert (x*y**3 + z).degree(z) == 1
assert (7*x**5*y**3 + z).degree(z) == 1
R, = ring("", ZZ)
assert R(0).degree() is -oo
assert R(1).degree() == 0
def test_PolyElement_tail_degree():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).tail_degree() is -oo
assert R(1).tail_degree() == 0
assert (x + 1).tail_degree() == 0
assert (2*y**3 + x**3*z).tail_degree() == 0
assert (x*y**3 + x**3*z).tail_degree() == 1
assert (x**5*y**3 + x**3*z).tail_degree() == 3
assert R(0).tail_degree(x) is -oo
assert R(1).tail_degree(x) == 0
assert (x + 1).tail_degree(x) == 0
assert (2*y**3 + x**3*z).tail_degree(x) == 0
assert (x*y**3 + x**3*z).tail_degree(x) == 1
assert (7*x**5*y**3 + x**3*z).tail_degree(x) == 3
assert R(0).tail_degree(y) is -oo
assert R(1).tail_degree(y) == 0
assert (x + 1).tail_degree(y) == 0
assert (2*y**3 + x**3*z).tail_degree(y) == 0
assert (x*y**3 + x**3*z).tail_degree(y) == 0
assert (7*x**5*y**3 + x**3*z).tail_degree(y) == 0
assert R(0).tail_degree(z) is -oo
assert R(1).tail_degree(z) == 0
assert (x + 1).tail_degree(z) == 0
assert (2*y**3 + x**3*z).tail_degree(z) == 0
assert (x*y**3 + x**3*z).tail_degree(z) == 0
assert (7*x**5*y**3 + x**3*z).tail_degree(z) == 0
R, = ring("", ZZ)
assert R(0).tail_degree() is -oo
assert R(1).tail_degree() == 0
def test_PolyElement_degrees():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).degrees() == (-oo, -oo, -oo)
assert R(1).degrees() == (0, 0, 0)
assert (x**2*y + x**3*z**2).degrees() == (3, 1, 2)
def test_PolyElement_tail_degrees():
R, x,y,z = ring("x,y,z", ZZ)
assert R(0).tail_degrees() == (-oo, -oo, -oo)
assert R(1).tail_degrees() == (0, 0, 0)
assert (x**2*y + x**3*z**2).tail_degrees() == (2, 0, 0)
def test_PolyElement_coeff():
R, x, y, z = ring("x,y,z", ZZ, lex)
f = 3*x**2*y - x*y*z + 7*z**3 + 23
assert f.coeff(1) == 23
raises(ValueError, lambda: f.coeff(3))
assert f.coeff(x) == 0
assert f.coeff(y) == 0
assert f.coeff(z) == 0
assert f.coeff(x**2*y) == 3
assert f.coeff(x*y*z) == -1
assert f.coeff(z**3) == 7
raises(ValueError, lambda: f.coeff(3*x**2*y))
raises(ValueError, lambda: f.coeff(-x*y*z))
raises(ValueError, lambda: f.coeff(7*z**3))
R, = ring("", ZZ)
R(3).coeff(1) == 3
def test_PolyElement_LC():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LC == QQ(0)
assert (QQ(1,2)*x).LC == QQ(1, 2)
assert (QQ(1,4)*x*y + QQ(1,2)*x).LC == QQ(1, 4)
def test_PolyElement_LM():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LM == (0, 0)
assert (QQ(1,2)*x).LM == (1, 0)
assert (QQ(1,4)*x*y + QQ(1,2)*x).LM == (1, 1)
def test_PolyElement_LT():
R, x, y = ring("x,y", QQ, lex)
assert R(0).LT == ((0, 0), QQ(0))
assert (QQ(1,2)*x).LT == ((1, 0), QQ(1, 2))
assert (QQ(1,4)*x*y + QQ(1,2)*x).LT == ((1, 1), QQ(1, 4))
R, = ring("", ZZ)
assert R(0).LT == ((), 0)
assert R(1).LT == ((), 1)
def test_PolyElement_leading_monom():
R, x, y = ring("x,y", QQ, lex)
assert R(0).leading_monom() == 0
assert (QQ(1,2)*x).leading_monom() == x
assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_monom() == x*y
def test_PolyElement_leading_term():
R, x, y = ring("x,y", QQ, lex)
assert R(0).leading_term() == 0
assert (QQ(1,2)*x).leading_term() == QQ(1,2)*x
assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_term() == QQ(1,4)*x*y
def test_PolyElement_terms():
R, x,y,z = ring("x,y,z", QQ)
terms = (x**2/3 + y**3/4 + z**4/5).terms()
assert terms == [((2,0,0), QQ(1,3)), ((0,3,0), QQ(1,4)), ((0,0,4), QQ(1,5))]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.terms() == f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)]
assert f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.terms() == f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
assert f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)]
R, = ring("", ZZ)
assert R(3).terms() == [((), 3)]
def test_PolyElement_monoms():
R, x,y,z = ring("x,y,z", QQ)
monoms = (x**2/3 + y**3/4 + z**4/5).monoms()
assert monoms == [(2,0,0), (0,3,0), (0,0,4)]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.monoms() == f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)]
assert f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.monoms() == f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)]
assert f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)]
def test_PolyElement_coeffs():
R, x,y,z = ring("x,y,z", QQ)
coeffs = (x**2/3 + y**3/4 + z**4/5).coeffs()
assert coeffs == [QQ(1,3), QQ(1,4), QQ(1,5)]
R, x,y = ring("x,y", ZZ, lex)
f = x*y**7 + 2*x**2*y**3
assert f.coeffs() == f.coeffs(lex) == f.coeffs('lex') == [2, 1]
assert f.coeffs(grlex) == f.coeffs('grlex') == [1, 2]
R, x,y = ring("x,y", ZZ, grlex)
f = x*y**7 + 2*x**2*y**3
assert f.coeffs() == f.coeffs(grlex) == f.coeffs('grlex') == [1, 2]
assert f.coeffs(lex) == f.coeffs('lex') == [2, 1]
def test_PolyElement___add__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(x + 3*y) == {(1, 0, 0): 1, (0, 1, 0): 3}
assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u}
assert dict(u + x*y) == dict(x*y + u) == {(1, 1, 0): 1, (0, 0, 0): u}
assert dict(u + x*y + z) == dict(x*y + z + u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): u}
assert dict(u*x + x) == dict(x + u*x) == {(1, 0, 0): u + 1}
assert dict(u*x + x*y) == dict(x*y + u*x) == {(1, 1, 0): 1, (1, 0, 0): u}
assert dict(u*x + x*y + z) == dict(x*y + z + u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): u}
raises(TypeError, lambda: t + x)
raises(TypeError, lambda: x + t)
raises(TypeError, lambda: t + u)
raises(TypeError, lambda: u + t)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(EX(pi) + x*y*z) == dict(x*y*z + EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): EX(pi)}
def test_PolyElement___sub__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(x - 3*y) == {(1, 0, 0): 1, (0, 1, 0): -3}
assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u}
assert dict(-u + x*y) == dict(x*y - u) == {(1, 1, 0): 1, (0, 0, 0): -u}
assert dict(-u + x*y + z) == dict(x*y + z - u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): -u}
assert dict(-u*x + x) == dict(x - u*x) == {(1, 0, 0): -u + 1}
assert dict(-u*x + x*y) == dict(x*y - u*x) == {(1, 1, 0): 1, (1, 0, 0): -u}
assert dict(-u*x + x*y + z) == dict(x*y + z - u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): -u}
raises(TypeError, lambda: t - x)
raises(TypeError, lambda: x - t)
raises(TypeError, lambda: t - u)
raises(TypeError, lambda: u - t)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(-EX(pi) + x*y*z) == dict(x*y*z - EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): -EX(pi)}
def test_PolyElement___mul__():
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict(u*x) == dict(x*u) == {(1, 0, 0): u}
assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*x + z) == dict(2*x*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(u*x*2 + z) == dict(x*u*2 + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*x*y + z) == dict(2*x*y*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*x*y*2 + z) == dict(x*y*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*2*y*x + z) == dict(2*y*x*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(u*y*x*2 + z) == dict(y*x*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1}
assert dict(3*u*(x + y) + z) == dict((x + y)*3*u + z) == {(1, 0, 0): 3*u, (0, 1, 0): 3*u, (0, 0, 1): 1}
raises(TypeError, lambda: t*x + z)
raises(TypeError, lambda: x*t + z)
raises(TypeError, lambda: t*u + z)
raises(TypeError, lambda: u*t + z)
Fuv, u,v = field("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Fuv)
assert dict(u*x) == dict(x*u) == {(1, 0, 0): u}
Rxyz, x,y,z = ring("x,y,z", EX)
assert dict(EX(pi)*x*y*z) == dict(x*y*z*EX(pi)) == {(1, 1, 1): EX(pi)}
def test_PolyElement___div__():
R, x,y,z = ring("x,y,z", ZZ)
assert (2*x**2 - 4)/2 == x**2 - 2
assert (2*x**2 - 3)/2 == x**2
assert (x**2 - 1).quo(x) == x
assert (x**2 - x).quo(x) == x - 1
assert (x**2 - 1)/x == x - x**(-1)
assert (x**2 - x)/x == x - 1
assert (x**2 - 1)/(2*x) == x/2 - x**(-1)/2
assert (x**2 - 1).quo(2*x) == 0
assert (x**2 - x)/(x - 1) == (x**2 - x).quo(x - 1) == x
R, x,y,z = ring("x,y,z", ZZ)
assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 0
R, x,y,z = ring("x,y,z", QQ)
assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 3
Rt, t = ring("t", ZZ)
Ruv, u,v = ring("u,v", ZZ)
Rxyz, x,y,z = ring("x,y,z", Ruv)
assert dict((u**2*x + u)/u) == {(1, 0, 0): u, (0, 0, 0): 1}
raises(TypeError, lambda: u/(u**2*x + u))
raises(TypeError, lambda: t/x)
raises(TypeError, lambda: x/t)
raises(TypeError, lambda: t/u)
raises(TypeError, lambda: u/t)
R, x = ring("x", ZZ)
f, g = x**2 + 2*x + 3, R(0)
raises(ZeroDivisionError, lambda: f.div(g))
raises(ZeroDivisionError, lambda: divmod(f, g))
raises(ZeroDivisionError, lambda: f.rem(g))
raises(ZeroDivisionError, lambda: f % g)
raises(ZeroDivisionError, lambda: f.quo(g))
raises(ZeroDivisionError, lambda: f / g)
raises(ZeroDivisionError, lambda: f.exquo(g))
R, x, y = ring("x,y", ZZ)
f, g = x*y + 2*x + 3, R(0)
raises(ZeroDivisionError, lambda: f.div(g))
raises(ZeroDivisionError, lambda: divmod(f, g))
raises(ZeroDivisionError, lambda: f.rem(g))
raises(ZeroDivisionError, lambda: f % g)
raises(ZeroDivisionError, lambda: f.quo(g))
raises(ZeroDivisionError, lambda: f / g)
raises(ZeroDivisionError, lambda: f.exquo(g))
R, x = ring("x", ZZ)
f, g = x**2 + 1, 2*x - 4
q, r = R(0), x**2 + 1
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1
q, r = R(0), f
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, x**2 + 2*x + 3
q, r = 5*x**2 - 6*x, 20*x + 1
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 5*x**5 + 4*x**4 + 3*x**3 + 2*x**2 + x, x**4 + 2*x**3 + 9
q, r = 5*x - 6, 15*x**3 + 2*x**2 - 44*x + 54
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x = ring("x", QQ)
f, g = x**2 + 1, 2*x - 4
q, r = x/2 + 1, R(5)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1
q, r = QQ(3, 5)*x + QQ(14, 25), QQ(52, 25)*x + QQ(111, 25)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x,y = ring("x,y", ZZ)
f, g = x**2 - y**2, x - y
q, r = x + y, R(0)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
assert f.exquo(g) == q
f, g = x**2 + y**2, x - y
q, r = x + y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, -x + y
q, r = -x - y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, 2*x - 2*y
q, r = R(0), f
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
R, x,y = ring("x,y", QQ)
f, g = x**2 - y**2, x - y
q, r = x + y, R(0)
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
assert f.exquo(g) == q
f, g = x**2 + y**2, x - y
q, r = x + y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, -x + y
q, r = -x - y, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
f, g = x**2 + y**2, 2*x - 2*y
q, r = x/2 + y/2, 2*y**2
assert f.div(g) == divmod(f, g) == (q, r)
assert f.rem(g) == f % g == r
assert f.quo(g) == f / g == q
raises(ExactQuotientFailed, lambda: f.exquo(g))
def test_PolyElement___pow__():
R, x = ring("x", ZZ, grlex)
f = 2*x + 3
assert f**0 == 1
assert f**1 == f
raises(ValueError, lambda: f**(-1))
assert x**(-1) == x**(-1)
assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == 4*x**2 + 12*x + 9
assert f**3 == f._pow_generic(3) == f._pow_multinomial(3) == 8*x**3 + 36*x**2 + 54*x + 27
assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == 16*x**4 + 96*x**3 + 216*x**2 + 216*x + 81
assert f**5 == f._pow_generic(5) == f._pow_multinomial(5) == 32*x**5 + 240*x**4 + 720*x**3 + 1080*x**2 + 810*x + 243
R, x,y,z = ring("x,y,z", ZZ, grlex)
f = x**3*y - 2*x*y**2 - 3*z + 1
g = x**6*y**2 - 4*x**4*y**3 - 6*x**3*y*z + 2*x**3*y + 4*x**2*y**4 + 12*x*y**2*z - 4*x*y**2 + 9*z**2 - 6*z + 1
assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == g
R, t = ring("t", ZZ)
f = -11200*t**4 - 2604*t**2 + 49
g = 15735193600000000*t**16 + 14633730048000000*t**14 + 4828147466240000*t**12 \
+ 598976863027200*t**10 + 3130812416256*t**8 - 2620523775744*t**6 \
+ 92413760096*t**4 - 1225431984*t**2 + 5764801
assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == g
def test_PolyElement_div():
R, x = ring("x", ZZ, grlex)
f = x**3 - 12*x**2 - 42
g = x - 3
q = x**2 - 9*x - 27
r = -123
assert f.div([g]) == ([q], r)
R, x = ring("x", ZZ, grlex)
f = x**2 + 2*x + 2
assert f.div([R(1)]) == ([f], 0)
R, x = ring("x", QQ, grlex)
f = x**2 + 2*x + 2
assert f.div([R(2)]) == ([QQ(1,2)*x**2 + x + 1], 0)
R, x,y = ring("x,y", ZZ, grlex)
f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8
assert f.div([R(2)]) == ([2*x**2*y - x*y + 2*x - y + 4], 0)
assert f.div([2*y]) == ([2*x**2 - x - 1], 4*x + 8)
f = x - 1
g = y - 1
assert f.div([g]) == ([0], f)
f = x*y**2 + 1
G = [x*y + 1, y + 1]
Q = [y, -1]
r = 2
assert f.div(G) == (Q, r)
f = x**2*y + x*y**2 + y**2
G = [x*y - 1, y**2 - 1]
Q = [x + y, 1]
r = x + y + 1
assert f.div(G) == (Q, r)
G = [y**2 - 1, x*y - 1]
Q = [x + 1, x]
r = 2*x + 1
assert f.div(G) == (Q, r)
R, = ring("", ZZ)
assert R(3).div(R(2)) == (0, 3)
R, = ring("", QQ)
assert R(3).div(R(2)) == (QQ(3, 2), 0)
def test_PolyElement_rem():
R, x = ring("x", ZZ, grlex)
f = x**3 - 12*x**2 - 42
g = x - 3
r = -123
assert f.rem([g]) == f.div([g])[1] == r
R, x,y = ring("x,y", ZZ, grlex)
f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8
assert f.rem([R(2)]) == f.div([R(2)])[1] == 0
assert f.rem([2*y]) == f.div([2*y])[1] == 4*x + 8
f = x - 1
g = y - 1
assert f.rem([g]) == f.div([g])[1] == f
f = x*y**2 + 1
G = [x*y + 1, y + 1]
r = 2
assert f.rem(G) == f.div(G)[1] == r
f = x**2*y + x*y**2 + y**2
G = [x*y - 1, y**2 - 1]
r = x + y + 1
assert f.rem(G) == f.div(G)[1] == r
G = [y**2 - 1, x*y - 1]
r = 2*x + 1
assert f.rem(G) == f.div(G)[1] == r
def test_PolyElement_deflate():
R, x = ring("x", ZZ)
assert (2*x**2).deflate(x**4 + 4*x**2 + 1) == ((2,), [2*x, x**2 + 4*x + 1])
R, x,y = ring("x,y", ZZ)
assert R(0).deflate(R(0)) == ((1, 1), [0, 0])
assert R(1).deflate(R(0)) == ((1, 1), [1, 0])
assert R(1).deflate(R(2)) == ((1, 1), [1, 2])
assert R(1).deflate(2*y) == ((1, 1), [1, 2*y])
assert (2*y).deflate(2*y) == ((1, 1), [2*y, 2*y])
assert R(2).deflate(2*y**2) == ((1, 2), [2, 2*y])
assert (2*y**2).deflate(2*y**2) == ((1, 2), [2*y, 2*y])
f = x**4*y**2 + x**2*y + 1
g = x**2*y**3 + x**2*y + 1
assert f.deflate(g) == ((2, 1), [x**2*y**2 + x*y + 1, x*y**3 + x*y + 1])
def test_PolyElement_clear_denoms():
R, x,y = ring("x,y", QQ)
assert R(1).clear_denoms() == (ZZ(1), 1)
assert R(7).clear_denoms() == (ZZ(1), 7)
assert R(QQ(7,3)).clear_denoms() == (3, 7)
assert R(QQ(7,3)).clear_denoms() == (3, 7)
assert (3*x**2 + x).clear_denoms() == (1, 3*x**2 + x)
assert (x**2 + QQ(1,2)*x).clear_denoms() == (2, 2*x**2 + x)
rQQ, x,t = ring("x,t", QQ, lex)
rZZ, X,T = ring("x,t", ZZ, lex)
F = [x - QQ(17824537287975195925064602467992950991718052713078834557692023531499318507213727406844943097,413954288007559433755329699713866804710749652268151059918115348815925474842910720000)*t**7
- QQ(4882321164854282623427463828745855894130208215961904469205260756604820743234704900167747753,12936071500236232304854053116058337647210926633379720622441104650497671088840960000)*t**6
- QQ(36398103304520066098365558157422127347455927422509913596393052633155821154626830576085097433,25872143000472464609708106232116675294421853266759441244882209300995342177681920000)*t**5
- QQ(168108082231614049052707339295479262031324376786405372698857619250210703675982492356828810819,58212321751063045371843239022262519412449169850208742800984970927239519899784320000)*t**4
- QQ(5694176899498574510667890423110567593477487855183144378347226247962949388653159751849449037,1617008937529529038106756639507292205901365829172465077805138081312208886105120000)*t**3
- QQ(154482622347268833757819824809033388503591365487934245386958884099214649755244381307907779,60637835157357338929003373981523457721301218593967440417692678049207833228942000)*t**2
- QQ(2452813096069528207645703151222478123259511586701148682951852876484544822947007791153163,2425513406294293557160134959260938308852048743758697616707707121968313329157680)*t
- QQ(34305265428126440542854669008203683099323146152358231964773310260498715579162112959703,202126117191191129763344579938411525737670728646558134725642260164026110763140),
t**8 + QQ(693749860237914515552,67859264524169150569)*t**7
+ QQ(27761407182086143225024,610733380717522355121)*t**6
+ QQ(7785127652157884044288,67859264524169150569)*t**5
+ QQ(36567075214771261409792,203577793572507451707)*t**4
+ QQ(36336335165196147384320,203577793572507451707)*t**3
+ QQ(7452455676042754048000,67859264524169150569)*t**2
+ QQ(2593331082514399232000,67859264524169150569)*t
+ QQ(390399197427343360000,67859264524169150569)]
G = [3725588592068034903797967297424801242396746870413359539263038139343329273586196480000*X -
160420835591776763325581422211936558925462474417709511019228211783493866564923546661604487873*T**7 -
1406108495478033395547109582678806497509499966197028487131115097902188374051595011248311352864*T**6 -
5241326875850889518164640374668786338033653548841427557880599579174438246266263602956254030352*T**5 -
10758917262823299139373269714910672770004760114329943852726887632013485035262879510837043892416*T**4 -
13119383576444715672578819534846747735372132018341964647712009275306635391456880068261130581248*T**3 -
9491412317016197146080450036267011389660653495578680036574753839055748080962214787557853941760*T**2 -
3767520915562795326943800040277726397326609797172964377014046018280260848046603967211258368000*T -
632314652371226552085897259159210286886724229880266931574701654721512325555116066073245696000,
610733380717522355121*T**8 +
6243748742141230639968*T**7 +
27761407182086143225024*T**6 +
70066148869420956398592*T**5 +
109701225644313784229376*T**4 +
109009005495588442152960*T**3 +
67072101084384786432000*T**2 +
23339979742629593088000*T +
3513592776846090240000]
assert [ f.clear_denoms()[1].set_ring(rZZ) for f in F ] == G
def test_PolyElement_cofactors():
R, x, y = ring("x,y", ZZ)
f, g = R(0), R(0)
assert f.cofactors(g) == (0, 0, 0)
f, g = R(2), R(0)
assert f.cofactors(g) == (2, 1, 0)
f, g = R(-2), R(0)
assert f.cofactors(g) == (2, -1, 0)
f, g = R(0), R(-2)
assert f.cofactors(g) == (2, 0, -1)
f, g = R(0), 2*x + 4
assert f.cofactors(g) == (2*x + 4, 0, 1)
f, g = 2*x + 4, R(0)
assert f.cofactors(g) == (2*x + 4, 1, 0)
f, g = R(2), R(2)
assert f.cofactors(g) == (2, 1, 1)
f, g = R(-2), R(2)
assert f.cofactors(g) == (2, -1, 1)
f, g = R(2), R(-2)
assert f.cofactors(g) == (2, 1, -1)
f, g = R(-2), R(-2)
assert f.cofactors(g) == (2, -1, -1)
f, g = x**2 + 2*x + 1, R(1)
assert f.cofactors(g) == (1, x**2 + 2*x + 1, 1)
f, g = x**2 + 2*x + 1, R(2)
assert f.cofactors(g) == (1, x**2 + 2*x + 1, 2)
f, g = 2*x**2 + 4*x + 2, R(2)
assert f.cofactors(g) == (2, x**2 + 2*x + 1, 1)
f, g = R(2), 2*x**2 + 4*x + 2
assert f.cofactors(g) == (2, 1, x**2 + 2*x + 1)
f, g = 2*x**2 + 4*x + 2, x + 1
assert f.cofactors(g) == (x + 1, 2*x + 2, 1)
f, g = x + 1, 2*x**2 + 4*x + 2
assert f.cofactors(g) == (x + 1, 1, 2*x + 2)
R, x, y, z, t = ring("x,y,z,t", ZZ)
f, g = t**2 + 2*t + 1, 2*t + 2
assert f.cofactors(g) == (t + 1, t + 1, 2)
f, g = z**2*t**2 + 2*z**2*t + z**2 + z*t + z, t**2 + 2*t + 1
h, cff, cfg = t + 1, z**2*t + z**2 + z, t + 1
assert f.cofactors(g) == (h, cff, cfg)
assert g.cofactors(f) == (h, cfg, cff)
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**2 + x + QQ(1,2)
g = QQ(1,2)*x + QQ(1,2)
h = x + 1
assert f.cofactors(g) == (h, g, QQ(1,2))
assert g.cofactors(f) == (h, QQ(1,2), g)
R, x, y = ring("x,y", RR)
f = 2.1*x*y**2 - 2.1*x*y + 2.1*x
g = 2.1*x**3
h = 1.0*x
assert f.cofactors(g) == (h, f/h, g/h)
assert g.cofactors(f) == (h, g/h, f/h)
def test_PolyElement_gcd():
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**2 + x + QQ(1,2)
g = QQ(1,2)*x + QQ(1,2)
assert f.gcd(g) == x + 1
def test_PolyElement_cancel():
R, x, y = ring("x,y", ZZ)
f = 2*x**3 + 4*x**2 + 2*x
g = 3*x**2 + 3*x
F = 2*x + 2
G = 3
assert f.cancel(g) == (F, G)
assert (-f).cancel(g) == (-F, G)
assert f.cancel(-g) == (-F, G)
R, x, y = ring("x,y", QQ)
f = QQ(1,2)*x**3 + x**2 + QQ(1,2)*x
g = QQ(1,3)*x**2 + QQ(1,3)*x
F = 3*x + 3
G = 2
assert f.cancel(g) == (F, G)
assert (-f).cancel(g) == (-F, G)
assert f.cancel(-g) == (-F, G)
Fx, x = field("x", ZZ)
Rt, t = ring("t", Fx)
f = (-x**2 - 4)/4*t
g = t**2 + (x**2 + 2)/2
assert f.cancel(g) == ((-x**2 - 4)*t, 4*t**2 + 2*x**2 + 4)
def test_PolyElement_max_norm():
R, x, y = ring("x,y", ZZ)
assert R(0).max_norm() == 0
assert R(1).max_norm() == 1
assert (x**3 + 4*x**2 + 2*x + 3).max_norm() == 4
def test_PolyElement_l1_norm():
R, x, y = ring("x,y", ZZ)
assert R(0).l1_norm() == 0
assert R(1).l1_norm() == 1
assert (x**3 + 4*x**2 + 2*x + 3).l1_norm() == 10
def test_PolyElement_diff():
R, X = xring("x:11", QQ)
f = QQ(288,5)*X[0]**8*X[1]**6*X[4]**3*X[10]**2 + 8*X[0]**2*X[2]**3*X[4]**3 +2*X[0]**2 - 2*X[1]**2
assert f.diff(X[0]) == QQ(2304,5)*X[0]**7*X[1]**6*X[4]**3*X[10]**2 + 16*X[0]*X[2]**3*X[4]**3 + 4*X[0]
assert f.diff(X[4]) == QQ(864,5)*X[0]**8*X[1]**6*X[4]**2*X[10]**2 + 24*X[0]**2*X[2]**3*X[4]**2
assert f.diff(X[10]) == QQ(576,5)*X[0]**8*X[1]**6*X[4]**3*X[10]
def test_PolyElement___call__():
R, x = ring("x", ZZ)
f = 3*x + 1
assert f(0) == 1
assert f(1) == 4
raises(ValueError, lambda: f())
raises(ValueError, lambda: f(0, 1))
raises(CoercionFailed, lambda: f(QQ(1,7)))
R, x,y = ring("x,y", ZZ)
f = 3*x + y**2 + 1
assert f(0, 0) == 1
assert f(1, 7) == 53
Ry = R.drop(x)
assert f(0) == Ry.y**2 + 1
assert f(1) == Ry.y**2 + 4
raises(ValueError, lambda: f())
raises(ValueError, lambda: f(0, 1, 2))
raises(CoercionFailed, lambda: f(1, QQ(1,7)))
raises(CoercionFailed, lambda: f(QQ(1,7), 1))
raises(CoercionFailed, lambda: f(QQ(1,7), QQ(1,7)))
def test_PolyElement_evaluate():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.evaluate(x, 0)
assert r == 3 and not isinstance(r, PolyElement)
raises(CoercionFailed, lambda: f.evaluate(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = (x*y)**3 + 4*(x*y)**2 + 2*x*y + 3
r = f.evaluate(x, 0)
assert r == 3 and isinstance(r, R.drop(x).dtype)
r = f.evaluate([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.drop(x, y).dtype)
r = f.evaluate(y, 0)
assert r == 3 and isinstance(r, R.drop(y).dtype)
r = f.evaluate([(y, 0), (x, 0)])
assert r == 3 and isinstance(r, R.drop(y, x).dtype)
r = f.evaluate([(x, 0), (y, 0), (z, 0)])
assert r == 3 and not isinstance(r, PolyElement)
raises(CoercionFailed, lambda: f.evaluate([(x, 1), (y, QQ(1,7))]))
raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, 1)]))
raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, QQ(1,7))]))
def test_PolyElement_subs():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.subs(x, 0)
assert r == 3 and isinstance(r, R.dtype)
raises(CoercionFailed, lambda: f.subs(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.subs(x, 0)
assert r == 3 and isinstance(r, R.dtype)
r = f.subs([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.dtype)
raises(CoercionFailed, lambda: f.subs([(x, 1), (y, QQ(1,7))]))
raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, 1)]))
raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, QQ(1,7))]))
def test_PolyElement_compose():
R, x = ring("x", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.compose(x, 0)
assert r == 3 and isinstance(r, R.dtype)
assert f.compose(x, x) == f
assert f.compose(x, x**2) == x**6 + 4*x**4 + 2*x**2 + 3
raises(CoercionFailed, lambda: f.compose(x, QQ(1,7)))
R, x, y, z = ring("x,y,z", ZZ)
f = x**3 + 4*x**2 + 2*x + 3
r = f.compose(x, 0)
assert r == 3 and isinstance(r, R.dtype)
r = f.compose([(x, 0), (y, 0)])
assert r == 3 and isinstance(r, R.dtype)
r = (x**3 + 4*x**2 + 2*x*y*z + 3).compose(x, y*z**2 - 1)
q = (y*z**2 - 1)**3 + 4*(y*z**2 - 1)**2 + 2*(y*z**2 - 1)*y*z + 3
assert r == q and isinstance(r, R.dtype)
def test_PolyElement_is_():
R, x,y,z = ring("x,y,z", QQ)
assert (x - x).is_generator == False
assert (x - x).is_ground == True
assert (x - x).is_monomial == True
assert (x - x).is_term == True
assert (x - x + 1).is_generator == False
assert (x - x + 1).is_ground == True
assert (x - x + 1).is_monomial == True
assert (x - x + 1).is_term == True
assert x.is_generator == True
assert x.is_ground == False
assert x.is_monomial == True
assert x.is_term == True
assert (x*y).is_generator == False
assert (x*y).is_ground == False
assert (x*y).is_monomial == True
assert (x*y).is_term == True
assert (3*x).is_generator == False
assert (3*x).is_ground == False
assert (3*x).is_monomial == False
assert (3*x).is_term == True
assert (3*x + 1).is_generator == False
assert (3*x + 1).is_ground == False
assert (3*x + 1).is_monomial == False
assert (3*x + 1).is_term == False
assert R(0).is_zero is True
assert R(1).is_zero is False
assert R(0).is_one is False
assert R(1).is_one is True
assert (x - 1).is_monic is True
assert (2*x - 1).is_monic is False
assert (3*x + 2).is_primitive is True
assert (4*x + 2).is_primitive is False
assert (x + y + z + 1).is_linear is True
assert (x*y*z + 1).is_linear is False
assert (x*y + z + 1).is_quadratic is True
assert (x*y*z + 1).is_quadratic is False
assert (x - 1).is_squarefree is True
assert ((x - 1)**2).is_squarefree is False
assert (x**2 + x + 1).is_irreducible is True
assert (x**2 + 2*x + 1).is_irreducible is False
_, t = ring("t", FF(11))
assert (7*t + 3).is_irreducible is True
assert (7*t**2 + 3*t + 1).is_irreducible is False
_, u = ring("u", ZZ)
f = u**16 + u**14 - u**10 - u**8 - u**6 + u**2
assert f.is_cyclotomic is False
assert (f + 1).is_cyclotomic is True
raises(MultivariatePolynomialError, lambda: x.is_cyclotomic)
R, = ring("", ZZ)
assert R(4).is_squarefree is True
assert R(6).is_irreducible is True
def test_PolyElement_drop():
R, x,y,z = ring("x,y,z", ZZ)
assert R(1).drop(0).ring == PolyRing("y,z", ZZ, lex)
assert R(1).drop(0).drop(0).ring == PolyRing("z", ZZ, lex)
assert isinstance(R(1).drop(0).drop(0).drop(0), R.dtype) is False
raises(ValueError, lambda: z.drop(0).drop(0).drop(0))
raises(ValueError, lambda: x.drop(0))
def test_PolyElement_pdiv():
_, x, y = ring("x,y", ZZ)
f, g = x**2 - y**2, x - y
q, r = x + y, 0
assert f.pdiv(g) == (q, r)
assert f.prem(g) == r
assert f.pquo(g) == q
assert f.pexquo(g) == q
def test_PolyElement_gcdex():
_, x = ring("x", QQ)
f, g = 2*x, x**2 - 16
s, t, h = x/32, -QQ(1, 16), 1
assert f.half_gcdex(g) == (s, h)
assert f.gcdex(g) == (s, t, h)
def test_PolyElement_subresultants():
_, x = ring("x", ZZ)
f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2
assert f.subresultants(g) == [f, g, h]
def test_PolyElement_resultant():
_, x = ring("x", ZZ)
f, g, h = x**2 - 2*x + 1, x**2 - 1, 0
assert f.resultant(g) == h
def test_PolyElement_discriminant():
_, x = ring("x", ZZ)
f, g = x**3 + 3*x**2 + 9*x - 13, -11664
assert f.discriminant() == g
F, a, b, c = ring("a,b,c", ZZ)
_, x = ring("x", F)
f, g = a*x**2 + b*x + c, b**2 - 4*a*c
assert f.discriminant() == g
def test_PolyElement_decompose():
_, x = ring("x", ZZ)
f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9
g = x**4 - 2*x + 9
h = x**3 + 5*x
assert g.compose(x, h) == f
assert f.decompose() == [g, h]
def test_PolyElement_shift():
_, x = ring("x", ZZ)
assert (x**2 - 2*x + 1).shift(2) == x**2 + 2*x + 1
def test_PolyElement_sturm():
F, t = field("t", ZZ)
_, x = ring("x", F)
f = 1024/(15625*t**8)*x**5 - 4096/(625*t**8)*x**4 + 32/(15625*t**4)*x**3 - 128/(625*t**4)*x**2 + F(1)/62500*x - F(1)/625
assert f.sturm() == [
x**3 - 100*x**2 + t**4/64*x - 25*t**4/16,
3*x**2 - 200*x + t**4/64,
(-t**4/96 + F(20000)/9)*x + 25*t**4/18,
(-9*t**12 - 11520000*t**8 - 3686400000000*t**4)/(576*t**8 - 245760000*t**4 + 26214400000000),
]
def test_PolyElement_gff_list():
_, x = ring("x", ZZ)
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert f.gff_list() == [(x, 1), (x + 2, 4)]
f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5)
assert f.gff_list() == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
def test_PolyElement_sqf_norm():
R, x = ring("x", QQ.algebraic_field(sqrt(3)))
X = R.to_ground().x
assert (x**2 - 2).sqf_norm() == (1, x**2 - 2*sqrt(3)*x + 1, X**4 - 10*X**2 + 1)
R, x = ring("x", QQ.algebraic_field(sqrt(2)))
X = R.to_ground().x
assert (x**2 - 3).sqf_norm() == (1, x**2 - 2*sqrt(2)*x - 1, X**4 - 10*X**2 + 1)
def test_PolyElement_sqf_list():
_, x = ring("x", ZZ)
f = x**5 - x**3 - x**2 + 1
g = x**3 + 2*x**2 + 2*x + 1
h = x - 1
p = x**4 + x**3 - x - 1
assert f.sqf_part() == p
assert f.sqf_list() == (1, [(g, 1), (h, 2)])
def test_PolyElement_factor_list():
_, x = ring("x", ZZ)
f = x**5 - x**3 - x**2 + 1
u = x + 1
v = x - 1
w = x**2 + x + 1
assert f.factor_list() == (1, [(u, 1), (v, 2), (w, 1)])
|
707c33b5100cf1dfb40b8f0dc2112ddac493994d668e73cf322100164c5b1eeb | """Tests for tools for constructing domains for expressions. """
from sympy.polys.constructor import construct_domain
from sympy.polys.domains import ZZ, QQ, RR, EX
from sympy.polys.domains.realfield import RealField
from sympy import S, sqrt, sin, Float, E, GoldenRatio, pi, Catalan, Rational
from sympy.abc import x, y
def test_construct_domain():
assert construct_domain([1, 2, 3]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)])
assert construct_domain([1, 2, 3], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)])
assert construct_domain([S.One, S(2), S(3)]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)])
assert construct_domain([S.One, S(2), S(3)], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)])
assert construct_domain([S.Half, S(2)]) == (QQ, [QQ(1, 2), QQ(2)])
result = construct_domain([3.14, 1, S.Half])
assert isinstance(result[0], RealField)
assert result[1] == [RR(3.14), RR(1.0), RR(0.5)]
assert construct_domain([3.14, sqrt(2)], extension=None) == (EX, [EX(3.14), EX(sqrt(2))])
assert construct_domain([3.14, sqrt(2)], extension=True) == (EX, [EX(3.14), EX(sqrt(2))])
assert construct_domain([1, sqrt(2)], extension=None) == (EX, [EX(1), EX(sqrt(2))])
assert construct_domain([x, sqrt(x)]) == (EX, [EX(x), EX(sqrt(x))])
assert construct_domain([x, sqrt(x), sqrt(y)]) == (EX, [EX(x), EX(sqrt(x)), EX(sqrt(y))])
alg = QQ.algebraic_field(sqrt(2))
assert construct_domain([7, S.Half, sqrt(2)], extension=True) == \
(alg, [alg.convert(7), alg.convert(S.Half), alg.convert(sqrt(2))])
alg = QQ.algebraic_field(sqrt(2) + sqrt(3))
assert construct_domain([7, sqrt(2), sqrt(3)], extension=True) == \
(alg, [alg.convert(7), alg.convert(sqrt(2)), alg.convert(sqrt(3))])
dom = ZZ[x]
assert construct_domain([2*x, 3]) == \
(dom, [dom.convert(2*x), dom.convert(3)])
dom = ZZ[x, y]
assert construct_domain([2*x, 3*y]) == \
(dom, [dom.convert(2*x), dom.convert(3*y)])
dom = QQ[x]
assert construct_domain([x/2, 3]) == \
(dom, [dom.convert(x/2), dom.convert(3)])
dom = QQ[x, y]
assert construct_domain([x/2, 3*y]) == \
(dom, [dom.convert(x/2), dom.convert(3*y)])
dom = RR[x]
assert construct_domain([x/2, 3.5]) == \
(dom, [dom.convert(x/2), dom.convert(3.5)])
dom = RR[x, y]
assert construct_domain([x/2, 3.5*y]) == \
(dom, [dom.convert(x/2), dom.convert(3.5*y)])
dom = ZZ.frac_field(x)
assert construct_domain([2/x, 3]) == \
(dom, [dom.convert(2/x), dom.convert(3)])
dom = ZZ.frac_field(x, y)
assert construct_domain([2/x, 3*y]) == \
(dom, [dom.convert(2/x), dom.convert(3*y)])
dom = RR.frac_field(x)
assert construct_domain([2/x, 3.5]) == \
(dom, [dom.convert(2/x), dom.convert(3.5)])
dom = RR.frac_field(x, y)
assert construct_domain([2/x, 3.5*y]) == \
(dom, [dom.convert(2/x), dom.convert(3.5*y)])
dom = RealField(prec=336)[x]
assert construct_domain([pi.evalf(100)*x]) == \
(dom, [dom.convert(pi.evalf(100)*x)])
assert construct_domain(2) == (ZZ, ZZ(2))
assert construct_domain(S(2)/3) == (QQ, QQ(2, 3))
assert construct_domain(Rational(2, 3)) == (QQ, QQ(2, 3))
assert construct_domain({}) == (ZZ, {})
def test_composite_option():
assert construct_domain({(1,): sin(y)}, composite=False) == \
(EX, {(1,): EX(sin(y))})
assert construct_domain({(1,): y}, composite=False) == \
(EX, {(1,): EX(y)})
assert construct_domain({(1, 1): 1}, composite=False) == \
(ZZ, {(1, 1): 1})
assert construct_domain({(1, 0): y}, composite=False) == \
(EX, {(1, 0): EX(y)})
def test_precision():
f1 = Float("1.01")
f2 = Float("1.0000000000000000000001")
for x in [1, 1e-2, 1e-6, 1e-13, 1e-14, 1e-16, 1e-20, 1e-100, 1e-300,
f1, f2]:
result = construct_domain([x])
y = float(result[1][0])
assert abs(x - y) / x < 1e-14 # Test relative accuracy
result = construct_domain([f1])
y = result[1][0]
assert y-1 > 1e-50
result = construct_domain([f2])
y = result[1][0]
assert y-1 > 1e-50
def test_issue_11538():
for n in [E, pi, Catalan]:
assert construct_domain(n)[0] == ZZ[n]
assert construct_domain(x + n)[0] == ZZ[x, n]
assert construct_domain(GoldenRatio)[0] == EX
assert construct_domain(x + GoldenRatio)[0] == EX
|
fdc09673fda00f4f3f5d67e373b325e59ddf673bf752f08f4e4f0f3dfbe73b86 | """Tests for algorithms for partial fraction decomposition of rational
functions. """
from sympy.polys.partfrac import (
apart_undetermined_coeffs,
apart,
apart_list, assemble_partfrac_list
)
from sympy import (S, Poly, E, pi, I, Matrix, Eq, RootSum, Lambda,
Symbol, Dummy, factor, together, sqrt, Expr, Rational)
from sympy.utilities.pytest import raises, XFAIL
from sympy.abc import x, y, a, b, c
def test_apart():
assert apart(1) == 1
assert apart(1, x) == 1
f, g = (x**2 + 1)/(x + 1), 2/(x + 1) + x - 1
assert apart(f, full=False) == g
assert apart(f, full=True) == g
f, g = 1/(x + 2)/(x + 1), 1/(1 + x) - 1/(2 + x)
assert apart(f, full=False) == g
assert apart(f, full=True) == g
f, g = 1/(x + 1)/(x + 5), -1/(5 + x)/4 + 1/(1 + x)/4
assert apart(f, full=False) == g
assert apart(f, full=True) == g
assert apart((E*x + 2)/(x - pi)*(x - 1), x) == \
2 - E + E*pi + E*x + (E*pi + 2)*(pi - 1)/(x - pi)
assert apart(Eq((x**2 + 1)/(x + 1), x), x) == Eq(x - 1 + 2/(x + 1), x)
assert apart(x/2, y) == x/2
f, g = (x+y)/(2*x - y), Rational(3, 2)*y/((2*x - y)) + S.Half
assert apart(f, x, full=False) == g
assert apart(f, x, full=True) == g
f, g = (x+y)/(2*x - y), 3*x/(2*x - y) - 1
assert apart(f, y, full=False) == g
assert apart(f, y, full=True) == g
raises(NotImplementedError, lambda: apart(1/(x + 1)/(y + 2)))
def test_apart_matrix():
M = Matrix(2, 2, lambda i, j: 1/(x + i + 1)/(x + j))
assert apart(M) == Matrix([
[1/x - 1/(x + 1), (x + 1)**(-2)],
[1/(2*x) - (S.Half)/(x + 2), 1/(x + 1) - 1/(x + 2)],
])
def test_apart_symbolic():
f = a*x**4 + (2*b + 2*a*c)*x**3 + (4*b*c - a**2 + a*c**2)*x**2 + \
(-2*a*b + 2*b*c**2)*x - b**2
g = a**2*x**4 + (2*a*b + 2*c*a**2)*x**3 + (4*a*b*c + b**2 +
a**2*c**2)*x**2 + (2*c*b**2 + 2*a*b*c**2)*x + b**2*c**2
assert apart(f/g, x) == 1/a - 1/(x + c)**2 - b**2/(a*(a*x + b)**2)
assert apart(1/((x + a)*(x + b)*(x + c)), x) == \
1/((a - c)*(b - c)*(c + x)) - 1/((a - b)*(b - c)*(b + x)) + \
1/((a - b)*(a - c)*(a + x))
def test_apart_extension():
f = 2/(x**2 + 1)
g = I/(x + I) - I/(x - I)
assert apart(f, extension=I) == g
assert apart(f, gaussian=True) == g
f = x/((x - 2)*(x + I))
assert factor(together(apart(f)).expand()) == f
def test_apart_full():
f = 1/(x**2 + 1)
assert apart(f, full=False) == f
assert apart(f, full=True) == \
-RootSum(x**2 + 1, Lambda(a, a/(x - a)), auto=False)/2
f = 1/(x**3 + x + 1)
assert apart(f, full=False) == f
assert apart(f, full=True) == \
RootSum(x**3 + x + 1,
Lambda(a, (a**2*Rational(6, 31) - a*Rational(9, 31) + Rational(4, 31))/(x - a)), auto=False)
f = 1/(x**5 + 1)
assert apart(f, full=False) == \
(Rational(-1, 5))*((x**3 - 2*x**2 + 3*x - 4)/(x**4 - x**3 + x**2 -
x + 1)) + (Rational(1, 5))/(x + 1)
assert apart(f, full=True) == \
-RootSum(x**4 - x**3 + x**2 - x + 1,
Lambda(a, a/(x - a)), auto=False)/5 + (Rational(1, 5))/(x + 1)
def test_apart_undetermined_coeffs():
p = Poly(2*x - 3)
q = Poly(x**9 - x**8 - x**6 + x**5 - 2*x**2 + 3*x - 1)
r = (-x**7 - x**6 - x**5 + 4)/(x**8 - x**5 - 2*x + 1) + 1/(x - 1)
assert apart_undetermined_coeffs(p, q) == r
p = Poly(1, x, domain='ZZ[a,b]')
q = Poly((x + a)*(x + b), x, domain='ZZ[a,b]')
r = 1/((a - b)*(b + x)) - 1/((a - b)*(a + x))
assert apart_undetermined_coeffs(p, q) == r
def test_apart_list():
from sympy.utilities.iterables import numbered_symbols
w0, w1, w2 = Symbol("w0"), Symbol("w1"), Symbol("w2")
_a = Dummy("a")
f = (-2*x - 2*x**2) / (3*x**2 - 6*x)
assert apart_list(f, x, dummies=numbered_symbols("w")) == (-1,
Poly(Rational(2, 3), x, domain='QQ'),
[(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 2), Lambda(_a, -_a + x), 1)])
assert apart_list(2/(x**2-2), x, dummies=numbered_symbols("w")) == (1,
Poly(0, x, domain='ZZ'),
[(Poly(w0**2 - 2, w0, domain='ZZ'),
Lambda(_a, _a/2),
Lambda(_a, -_a + x), 1)])
f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2)
assert apart_list(f, x, dummies=numbered_symbols("w")) == (1,
Poly(0, x, domain='ZZ'),
[(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1),
(Poly(w1**2 - 1, w1, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2),
(Poly(w2 + 1, w2, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)])
def test_assemble_partfrac_list():
f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2)
pfd = apart_list(f)
assert assemble_partfrac_list(pfd) == -4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2)
a = Dummy("a")
pfd = (1, Poly(0, x, domain='ZZ'), [([sqrt(2),-sqrt(2)], Lambda(a, a/2), Lambda(a, -a + x), 1)])
assert assemble_partfrac_list(pfd) == -1/(sqrt(2)*(x + sqrt(2))) + 1/(sqrt(2)*(x - sqrt(2)))
@XFAIL
def test_noncommutative_pseudomultivariate():
# apart doesn't go inside noncommutative expressions
class foo(Expr):
is_commutative=False
e = x/(x + x*y)
c = 1/(1 + y)
assert apart(e + foo(e)) == c + foo(c)
assert apart(e*foo(e)) == c*foo(c)
def test_noncommutative():
class foo(Expr):
is_commutative=False
e = x/(x + x*y)
c = 1/(1 + y)
assert apart(e + foo()) == c + foo()
def test_issue_5798():
assert apart(
2*x/(x**2 + 1) - (x - 1)/(2*(x**2 + 1)) + 1/(2*(x + 1)) - 2/x) == \
(3*x + 1)/(x**2 + 1)/2 + 1/(x + 1)/2 - 2/x
|
174e3cd862111d0634d3d647cfe31f4bc014bd3c499aea02a0bae492faa0ff5a | """Tests for computational algebraic number field theory. """
from sympy import (S, Rational, Symbol, Poly, sqrt, I, oo, Tuple, expand,
pi, cos, sin, exp)
from sympy.utilities.pytest import raises, slow
from sympy.core.compatibility import range
from sympy.polys.numberfields import (
minimal_polynomial,
primitive_element,
is_isomorphism_possible,
field_isomorphism_pslq,
field_isomorphism,
to_number_field,
AlgebraicNumber,
isolate, IntervalPrinter,
)
from sympy.polys.polyerrors import (
IsomorphismFailed,
NotAlgebraic,
GeneratorsError,
)
from sympy.polys.polyclasses import DMP
from sympy.polys.domains import QQ
from sympy.polys.rootoftools import rootof
from sympy.polys.polytools import degree
from sympy.abc import x, y, z
Q = Rational
def test_minimal_polynomial():
assert minimal_polynomial(-7, x) == x + 7
assert minimal_polynomial(-1, x) == x + 1
assert minimal_polynomial( 0, x) == x
assert minimal_polynomial( 1, x) == x - 1
assert minimal_polynomial( 7, x) == x - 7
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(5), x) == x**2 - 5
assert minimal_polynomial(sqrt(6), x) == x**2 - 6
assert minimal_polynomial(2*sqrt(2), x) == x**2 - 8
assert minimal_polynomial(3*sqrt(5), x) == x**2 - 45
assert minimal_polynomial(4*sqrt(6), x) == x**2 - 96
assert minimal_polynomial(2*sqrt(2) + 3, x) == x**2 - 6*x + 1
assert minimal_polynomial(3*sqrt(5) + 6, x) == x**2 - 12*x - 9
assert minimal_polynomial(4*sqrt(6) + 7, x) == x**2 - 14*x - 47
assert minimal_polynomial(2*sqrt(2) - 3, x) == x**2 + 6*x + 1
assert minimal_polynomial(3*sqrt(5) - 6, x) == x**2 + 12*x - 9
assert minimal_polynomial(4*sqrt(6) - 7, x) == x**2 + 14*x - 47
assert minimal_polynomial(sqrt(1 + sqrt(6)), x) == x**4 - 2*x**2 - 5
assert minimal_polynomial(sqrt(I + sqrt(6)), x) == x**8 - 10*x**4 + 49
assert minimal_polynomial(2*I + sqrt(2 + I), x) == x**4 + 4*x**2 + 8*x + 37
assert minimal_polynomial(sqrt(2) + sqrt(3), x) == x**4 - 10*x**2 + 1
assert minimal_polynomial(
sqrt(2) + sqrt(3) + sqrt(6), x) == x**4 - 22*x**2 - 48*x - 23
a = 1 - 9*sqrt(2) + 7*sqrt(3)
assert minimal_polynomial(
1/a, x) == 392*x**4 - 1232*x**3 + 612*x**2 + 4*x - 1
assert minimal_polynomial(
1/sqrt(a), x) == 392*x**8 - 1232*x**6 + 612*x**4 + 4*x**2 - 1
raises(NotAlgebraic, lambda: minimal_polynomial(oo, x))
raises(NotAlgebraic, lambda: minimal_polynomial(2**y, x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(1), x))
assert minimal_polynomial(sqrt(2)).dummy_eq(x**2 - 2)
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(2), polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(sqrt(2), x, polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(sqrt(2), x, polys=True, compose=False) == Poly(x**2 - 2)
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
assert minimal_polynomial(a, x) == x**2 - 2
assert minimal_polynomial(b, x) == x**2 - 3
assert minimal_polynomial(a, x, polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(b, x, polys=True) == Poly(x**2 - 3)
assert minimal_polynomial(sqrt(a/2 + 17), x) == 2*x**4 - 68*x**2 + 577
assert minimal_polynomial(sqrt(b/2 + 17), x) == 4*x**4 - 136*x**2 + 1153
a, b = sqrt(2)/3 + 7, AlgebraicNumber(sqrt(2)/3 + 7)
f = 81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 - \
31608*x**2 - 189648*x + 141358
assert minimal_polynomial(sqrt(a) + sqrt(sqrt(a)), x) == f
assert minimal_polynomial(sqrt(b) + sqrt(sqrt(b)), x) == f
assert minimal_polynomial(
a**Q(3, 2), x) == 729*x**4 - 506898*x**2 + 84604519
# issue 5994
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
assert minimal_polynomial(eq, x) == 8000*x**2 - 1
ex = 1 + sqrt(2) + sqrt(3)
mp = minimal_polynomial(ex, x)
assert mp == x**4 - 4*x**3 - 4*x**2 + 16*x - 8
ex = 1/(1 + sqrt(2) + sqrt(3))
mp = minimal_polynomial(ex, x)
assert mp == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = (expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3))**Rational(1, 3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 512*x**7 - 118208*x**6 + 31131136*x**5 + 647362560*x**4 - 56026611712*x**3 + 116994310144*x**2 + 404854931456*x - 27216576512
assert minimal_polynomial(S("-sqrt(5)/2 - 1/2 + (-sqrt(5)/2 - 1/2)**2"), x) == x - 1
a = 1 + sqrt(2)
assert minimal_polynomial((a*sqrt(2) + a)**3, x) == x**2 - 198*x + 1
p = 1/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = 2/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == x**4 - 4*x**3 + 2*x**2 + 4*x - 2
assert minimal_polynomial(1 + sqrt(2)*I, x, compose=False) == x**2 - 2*x + 3
assert minimal_polynomial(1/(1 + sqrt(2)) + 1, x, compose=False) == x**2 - 2
assert minimal_polynomial(sqrt(2)*I + I*(1 + sqrt(2)), x,
compose=False) == x**4 + 18*x**2 + 49
# minimal polynomial of I
assert minimal_polynomial(I, x, domain=QQ.algebraic_field(I)) == x - I
K = QQ.algebraic_field(I*(sqrt(2) + 1))
assert minimal_polynomial(I, x, domain=K) == x - I
assert minimal_polynomial(I, x, domain=QQ) == x**2 + 1
assert minimal_polynomial(I, x, domain='QQ(y)') == x**2 + 1
def test_minimal_polynomial_hi_prec():
p = 1/sqrt(1 - 9*sqrt(2) + 7*sqrt(3) + Rational(1, 10)**30)
mp = minimal_polynomial(p, x)
# checked with Wolfram Alpha
assert mp.coeff(x**6) == -1232000000000000000000000000001223999999999999999999999999999987999999999999999999999999999996000000000000000000000000000000
def test_minimal_polynomial_sq():
from sympy import Add, expand_multinomial
p = expand_multinomial((1 + 5*sqrt(2) + 2*sqrt(3))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**4 - 4*x**3 - 118*x**2 + 244*x + 1321
p = expand_multinomial((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = Add(*[sqrt(i) for i in range(1, 12)])
mp = minimal_polynomial(p, x)
assert mp.subs({x: 0}) == -71965773323122507776
def test_minpoly_compose():
# issue 6868
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
mp = minimal_polynomial(eq + 3, x)
assert mp == 8000*x**2 - 48000*x + 71999
# issue 5888
assert minimal_polynomial(exp(I*pi/8), x) == x**8 + 1
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(exp(I*pi*Rational(2, 7)), x)
assert mp == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
mp = minimal_polynomial(exp(I*pi*Rational(2, 15)), x)
assert mp == x**8 - x**7 + x**5 - x**4 + x**3 - x + 1
mp = minimal_polynomial(cos(pi*Rational(2, 7)), x)
assert mp == 8*x**3 + 4*x**2 - 4*x - 1
mp = minimal_polynomial(sin(pi*Rational(2, 7)), x)
ex = (5*cos(pi*Rational(2, 7)) - 7)/(9*cos(pi/7) - 5*cos(pi*Rational(3, 7)))
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(-1/(2*cos(pi/7)), x) == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(sin(pi*Rational(2, 15)), x) == \
256*x**8 - 448*x**6 + 224*x**4 - 32*x**2 + 1
assert minimal_polynomial(sin(pi*Rational(5, 14)), x) == 8*x**3 - 4*x**2 - 4*x + 1
assert minimal_polynomial(cos(pi/15), x) == 16*x**4 + 8*x**3 - 16*x**2 - 8*x + 1
ex = rootof(x**3 +x*4 + 1, 0)
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 4*x + 1
mp = minimal_polynomial(ex + 1, x)
assert mp == x**3 - 3*x**2 + 7*x - 4
assert minimal_polynomial(exp(I*pi/3), x) == x**2 - x + 1
assert minimal_polynomial(exp(I*pi/4), x) == x**4 + 1
assert minimal_polynomial(exp(I*pi/6), x) == x**4 - x**2 + 1
assert minimal_polynomial(exp(I*pi/9), x) == x**6 - x**3 + 1
assert minimal_polynomial(exp(I*pi/10), x) == x**8 - x**6 + x**4 - x**2 + 1
assert minimal_polynomial(sin(pi/9), x) == 64*x**6 - 96*x**4 + 36*x**2 - 3
assert minimal_polynomial(sin(pi/11), x) == 1024*x**10 - 2816*x**8 + \
2816*x**6 - 1232*x**4 + 220*x**2 - 11
ex = 2**Rational(1, 3)*exp(Rational(2, 3)*I*pi)
assert minimal_polynomial(ex, x) == x**3 - 2
raises(NotAlgebraic, lambda: minimal_polynomial(cos(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(exp(I*pi*sqrt(2)), x))
# issue 5934
ex = 1/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) +
24*sqrt(10)*sqrt(-sqrt(5) + 5))**2) + 1
raises(ZeroDivisionError, lambda: minimal_polynomial(ex, x))
ex = sqrt(1 + 2**Rational(1,3)) + sqrt(1 + 2**Rational(1,4)) + sqrt(2)
mp = minimal_polynomial(ex, x)
assert degree(mp) == 48 and mp.subs({x:0}) == -16630256576
def test_minpoly_issue_7113():
# see discussion in https://github.com/sympy/sympy/pull/2234
from sympy.simplify.simplify import nsimplify
r = nsimplify(pi, tolerance=0.000000001)
mp = minimal_polynomial(r, x)
assert mp == 1768292677839237920489538677417507171630859375*x**109 - \
2734577732179183863586489182929671773182898498218854181690460140337930774573792597743853652058046464
def test_minpoly_issue_7574():
ex = -(-1)**Rational(1, 3) + (-1)**Rational(2,3)
assert minimal_polynomial(ex, x) == x + 1
def test_primitive_element():
assert primitive_element([sqrt(2)], x) == (x**2 - 2, [1])
assert primitive_element(
[sqrt(2), sqrt(3)], x) == (x**4 - 10*x**2 + 1, [1, 1])
assert primitive_element([sqrt(2)], x, polys=True) == (Poly(x**2 - 2), [1])
assert primitive_element([sqrt(
2), sqrt(3)], x, polys=True) == (Poly(x**4 - 10*x**2 + 1), [1, 1])
assert primitive_element(
[sqrt(2)], x, ex=True) == (x**2 - 2, [1], [[1, 0]])
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True) == \
(x**4 - 10*x**2 + 1, [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [-
Q(1, 2), 0, Q(11, 2), 0]])
assert primitive_element(
[sqrt(2)], x, ex=True, polys=True) == (Poly(x**2 - 2), [1], [[1, 0]])
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True, polys=True) == \
(Poly(x**4 - 10*x**2 + 1), [1, 1], [[Q(1, 2), 0, -Q(9, 2),
0], [-Q(1, 2), 0, Q(11, 2), 0]])
assert primitive_element([sqrt(2)], polys=True) == (Poly(x**2 - 2), [1])
raises(ValueError, lambda: primitive_element([], x, ex=False))
raises(ValueError, lambda: primitive_element([], x, ex=True))
# Issue 14117
a, b = I*sqrt(2*sqrt(2) + 3), I*sqrt(-2*sqrt(2) + 3)
assert primitive_element([a, b, I], x) == (x**4 + 6*x**2 + 1, [1, 0, 0])
def test_field_isomorphism_pslq():
a = AlgebraicNumber(I)
b = AlgebraicNumber(I*sqrt(3))
raises(NotImplementedError, lambda: field_isomorphism_pslq(a, b))
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
c = AlgebraicNumber(sqrt(7))
d = AlgebraicNumber(sqrt(2) + sqrt(3))
e = AlgebraicNumber(sqrt(2) + sqrt(3) + sqrt(7))
assert field_isomorphism_pslq(a, a) == [1, 0]
assert field_isomorphism_pslq(a, b) is None
assert field_isomorphism_pslq(a, c) is None
assert field_isomorphism_pslq(a, d) == [Q(1, 2), 0, -Q(9, 2), 0]
assert field_isomorphism_pslq(
a, e) == [Q(1, 80), 0, -Q(1, 2), 0, Q(59, 20), 0]
assert field_isomorphism_pslq(b, a) is None
assert field_isomorphism_pslq(b, b) == [1, 0]
assert field_isomorphism_pslq(b, c) is None
assert field_isomorphism_pslq(b, d) == [-Q(1, 2), 0, Q(11, 2), 0]
assert field_isomorphism_pslq(b, e) == [-Q(
3, 640), 0, Q(67, 320), 0, -Q(297, 160), 0, Q(313, 80), 0]
assert field_isomorphism_pslq(c, a) is None
assert field_isomorphism_pslq(c, b) is None
assert field_isomorphism_pslq(c, c) == [1, 0]
assert field_isomorphism_pslq(c, d) is None
assert field_isomorphism_pslq(c, e) == [Q(
3, 640), 0, -Q(71, 320), 0, Q(377, 160), 0, -Q(469, 80), 0]
assert field_isomorphism_pslq(d, a) is None
assert field_isomorphism_pslq(d, b) is None
assert field_isomorphism_pslq(d, c) is None
assert field_isomorphism_pslq(d, d) == [1, 0]
assert field_isomorphism_pslq(d, e) == [-Q(
3, 640), 0, Q(71, 320), 0, -Q(377, 160), 0, Q(549, 80), 0]
assert field_isomorphism_pslq(e, a) is None
assert field_isomorphism_pslq(e, b) is None
assert field_isomorphism_pslq(e, c) is None
assert field_isomorphism_pslq(e, d) is None
assert field_isomorphism_pslq(e, e) == [1, 0]
f = AlgebraicNumber(3*sqrt(2) + 8*sqrt(7) - 5)
assert field_isomorphism_pslq(
f, e) == [Q(3, 80), 0, -Q(139, 80), 0, Q(347, 20), 0, -Q(761, 20), -5]
def test_field_isomorphism():
assert field_isomorphism(3, sqrt(2)) == [3]
assert field_isomorphism( I*sqrt(3), I*sqrt(3)/2) == [ 2, 0]
assert field_isomorphism(-I*sqrt(3), I*sqrt(3)/2) == [-2, 0]
assert field_isomorphism( I*sqrt(3), -I*sqrt(3)/2) == [-2, 0]
assert field_isomorphism(-I*sqrt(3), -I*sqrt(3)/2) == [ 2, 0]
assert field_isomorphism( 2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [ Rational(6, 35), 0]
assert field_isomorphism(-2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [Rational(-6, 35), 0]
assert field_isomorphism( 2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [Rational(-6, 35), 0]
assert field_isomorphism(-2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [ Rational(6, 35), 0]
assert field_isomorphism(
2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [ Rational(6, 35), 27]
assert field_isomorphism(
-2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [Rational(-6, 35), 27]
assert field_isomorphism(
2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [Rational(-6, 35), 27]
assert field_isomorphism(
-2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [ Rational(6, 35), 27]
p = AlgebraicNumber( sqrt(2) + sqrt(3))
q = AlgebraicNumber(-sqrt(2) + sqrt(3))
r = AlgebraicNumber( sqrt(2) - sqrt(3))
s = AlgebraicNumber(-sqrt(2) - sqrt(3))
pos_coeffs = [ S.Half, S.Zero, Rational(-9, 2), S.Zero]
neg_coeffs = [Rational(-1, 2), S.Zero, Rational(9, 2), S.Zero]
a = AlgebraicNumber(sqrt(2))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == neg_coeffs
assert field_isomorphism(a, p, fast=False) == pos_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == neg_coeffs
a = AlgebraicNumber(-sqrt(2))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == pos_coeffs
assert field_isomorphism(a, r, fast=True) == neg_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == pos_coeffs
assert field_isomorphism(a, r, fast=False) == neg_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
pos_coeffs = [ S.Half, S.Zero, Rational(-11, 2), S.Zero]
neg_coeffs = [Rational(-1, 2), S.Zero, Rational(11, 2), S.Zero]
a = AlgebraicNumber(sqrt(3))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
a = AlgebraicNumber(-sqrt(3))
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_coeffs
assert field_isomorphism(a, q, fast=True) == pos_coeffs
assert field_isomorphism(a, r, fast=True) == neg_coeffs
assert field_isomorphism(a, s, fast=True) == neg_coeffs
assert field_isomorphism(a, p, fast=False) == pos_coeffs
assert field_isomorphism(a, q, fast=False) == pos_coeffs
assert field_isomorphism(a, r, fast=False) == neg_coeffs
assert field_isomorphism(a, s, fast=False) == neg_coeffs
pos_coeffs = [ Rational(3, 2), S.Zero, Rational(-33, 2), -S(8)]
neg_coeffs = [Rational(-3, 2), S.Zero, Rational(33, 2), -S(8)]
a = AlgebraicNumber(3*sqrt(3) - 8)
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == neg_coeffs
assert field_isomorphism(a, q, fast=True) == neg_coeffs
assert field_isomorphism(a, r, fast=True) == pos_coeffs
assert field_isomorphism(a, s, fast=True) == pos_coeffs
assert field_isomorphism(a, p, fast=False) == neg_coeffs
assert field_isomorphism(a, q, fast=False) == neg_coeffs
assert field_isomorphism(a, r, fast=False) == pos_coeffs
assert field_isomorphism(a, s, fast=False) == pos_coeffs
a = AlgebraicNumber(3*sqrt(2) + 2*sqrt(3) + 1)
pos_1_coeffs = [ S.Half, S.Zero, Rational(-5, 2), S.One]
neg_5_coeffs = [Rational(-5, 2), S.Zero, Rational(49, 2), S.One]
pos_5_coeffs = [ Rational(5, 2), S.Zero, Rational(-49, 2), S.One]
neg_1_coeffs = [Rational(-1, 2), S.Zero, Rational(5, 2), S.One]
assert is_isomorphism_possible(a, p) is True
assert is_isomorphism_possible(a, q) is True
assert is_isomorphism_possible(a, r) is True
assert is_isomorphism_possible(a, s) is True
assert field_isomorphism(a, p, fast=True) == pos_1_coeffs
assert field_isomorphism(a, q, fast=True) == neg_5_coeffs
assert field_isomorphism(a, r, fast=True) == pos_5_coeffs
assert field_isomorphism(a, s, fast=True) == neg_1_coeffs
assert field_isomorphism(a, p, fast=False) == pos_1_coeffs
assert field_isomorphism(a, q, fast=False) == neg_5_coeffs
assert field_isomorphism(a, r, fast=False) == pos_5_coeffs
assert field_isomorphism(a, s, fast=False) == neg_1_coeffs
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
c = AlgebraicNumber(sqrt(7))
assert is_isomorphism_possible(a, b) is True
assert is_isomorphism_possible(b, a) is True
assert is_isomorphism_possible(c, p) is False
assert field_isomorphism(sqrt(2), sqrt(3), fast=True) is None
assert field_isomorphism(sqrt(3), sqrt(2), fast=True) is None
assert field_isomorphism(sqrt(2), sqrt(3), fast=False) is None
assert field_isomorphism(sqrt(3), sqrt(2), fast=False) is None
def test_to_number_field():
assert to_number_field(sqrt(2)) == AlgebraicNumber(sqrt(2))
assert to_number_field(
[sqrt(2), sqrt(3)]) == AlgebraicNumber(sqrt(2) + sqrt(3))
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S.Half, S.Zero, Rational(-9, 2), S.Zero])
assert to_number_field(sqrt(2), sqrt(2) + sqrt(3)) == a
assert to_number_field(sqrt(2), AlgebraicNumber(sqrt(2) + sqrt(3))) == a
raises(IsomorphismFailed, lambda: to_number_field(sqrt(2), sqrt(3)))
def test_AlgebraicNumber():
minpoly, root = x**2 - 2, sqrt(2)
a = AlgebraicNumber(root, gen=x)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert a.coeffs() == [S.One, S.Zero]
assert a.native_coeffs() == [QQ(1), QQ(0)]
a = AlgebraicNumber(root, gen=x, alias='y')
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias == Symbol('y')
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is True
a = AlgebraicNumber(root, gen=x, alias=Symbol('y'))
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
assert a.root == root
assert a.alias == Symbol('y')
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is True
assert AlgebraicNumber(sqrt(2), []).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), ()).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), (0, 0)).rep == DMP([], QQ)
assert AlgebraicNumber(sqrt(2), [8]).rep == DMP([QQ(8)], QQ)
assert AlgebraicNumber(sqrt(2), [Rational(8, 3)]).rep == DMP([QQ(8, 3)], QQ)
assert AlgebraicNumber(sqrt(2), [7, 3]).rep == DMP([QQ(7), QQ(3)], QQ)
assert AlgebraicNumber(
sqrt(2), [Rational(7, 9), Rational(3, 2)]).rep == DMP([QQ(7, 9), QQ(3, 2)], QQ)
assert AlgebraicNumber(sqrt(2), [1, 2, 3]).rep == DMP([QQ(2), QQ(5)], QQ)
a = AlgebraicNumber(AlgebraicNumber(root, gen=x), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert a.coeffs() == [S.One, S(2)]
assert a.native_coeffs() == [QQ(1), QQ(2)]
a = AlgebraicNumber((minpoly, root), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
a = AlgebraicNumber((Poly(minpoly), root), [1, 2])
assert a.rep == DMP([QQ(1), QQ(2)], QQ)
assert a.root == root
assert a.alias is None
assert a.minpoly == minpoly
assert a.is_number
assert a.is_aliased is False
assert AlgebraicNumber( sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ)
assert AlgebraicNumber(-sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(2))
assert a == b
c = AlgebraicNumber(sqrt(2), gen=x)
d = AlgebraicNumber(sqrt(2), gen=x)
assert a == b
assert a == c
a = AlgebraicNumber(sqrt(2), [1, 2])
b = AlgebraicNumber(sqrt(2), [1, 3])
assert a != b and a != sqrt(2) + 3
assert (a == x) is False and (a != x) is True
a = AlgebraicNumber(sqrt(2), [1, 0])
b = AlgebraicNumber(sqrt(2), [1, 0], alias=y)
assert a.as_poly(x) == Poly(x)
assert b.as_poly() == Poly(y)
assert a.as_expr() == sqrt(2)
assert a.as_expr(x) == x
assert b.as_expr() == sqrt(2)
assert b.as_expr(x) == x
a = AlgebraicNumber(sqrt(2), [2, 3])
b = AlgebraicNumber(sqrt(2), [2, 3], alias=y)
p = a.as_poly()
assert p == Poly(2*p.gen + 3)
assert a.as_poly(x) == Poly(2*x + 3)
assert b.as_poly() == Poly(2*y + 3)
assert a.as_expr() == 2*sqrt(2) + 3
assert a.as_expr(x) == 2*x + 3
assert b.as_expr() == 2*sqrt(2) + 3
assert b.as_expr(x) == 2*x + 3
a = AlgebraicNumber(sqrt(2))
b = to_number_field(sqrt(2))
assert a.args == b.args == (sqrt(2), Tuple(1, 0))
b = AlgebraicNumber(sqrt(2), alias='alpha')
assert b.args == (sqrt(2), Tuple(1, 0), Symbol('alpha'))
a = AlgebraicNumber(sqrt(2), [1, 2, 3])
assert a.args == (sqrt(2), Tuple(1, 2, 3))
def test_to_algebraic_integer():
a = AlgebraicNumber(sqrt(3), gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 3
assert a.root == sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(2*sqrt(3), gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(3)/2, gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(1), QQ(0)], QQ)
a = AlgebraicNumber(sqrt(3)/2, [Rational(7, 19), 3], gen=x).to_algebraic_integer()
assert a.minpoly == x**2 - 12
assert a.root == 2*sqrt(3)
assert a.rep == DMP([QQ(7, 19), QQ(3)], QQ)
def test_IntervalPrinter():
ip = IntervalPrinter()
assert ip.doprint(x**Q(1, 3)) == "x**(mpi('1/3'))"
assert ip.doprint(sqrt(x)) == "x**(mpi('1/2'))"
def test_isolate():
assert isolate(1) == (1, 1)
assert isolate(S.Half) == (S.Half, S.Half)
assert isolate(sqrt(2)) == (1, 2)
assert isolate(-sqrt(2)) == (-2, -1)
assert isolate(sqrt(2), eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert isolate(-sqrt(2), eps=Rational(1, 100)) == (Rational(-17, 12), Rational(-24, 17))
raises(NotImplementedError, lambda: isolate(I))
def test_minpoly_fraction_field():
assert minimal_polynomial(1/x, y) == -x*y + 1
assert minimal_polynomial(1 / (x + 1), y) == (x + 1)*y - 1
assert minimal_polynomial(sqrt(x), y) == y**2 - x
assert minimal_polynomial(sqrt(x + 1), y) == y**2 - x - 1
assert minimal_polynomial(sqrt(x) / x, y) == x*y**2 - 1
assert minimal_polynomial(sqrt(2) * sqrt(x), y) == y**2 - 2 * x
assert minimal_polynomial(sqrt(2) + sqrt(x), y) == \
y**4 + (-2*x - 4)*y**2 + x**2 - 4*x + 4
assert minimal_polynomial(x**Rational(1,3), y) == y**3 - x
assert minimal_polynomial(x**Rational(1,3) + sqrt(x), y) == \
y**6 - 3*x*y**4 - 2*x*y**3 + 3*x**2*y**2 - 6*x**2*y - x**3 + x**2
assert minimal_polynomial(sqrt(x) / z, y) == z**2*y**2 - x
assert minimal_polynomial(sqrt(x) / (z + 1), y) == (z**2 + 2*z + 1)*y**2 - x
assert minimal_polynomial(1/x, y, polys=True) == Poly(-x*y + 1, y)
assert minimal_polynomial(1 / (x + 1), y, polys=True) == \
Poly((x + 1)*y - 1, y)
assert minimal_polynomial(sqrt(x), y, polys=True) == Poly(y**2 - x, y)
assert minimal_polynomial(sqrt(x) / z, y, polys=True) == \
Poly(z**2*y**2 - x, y)
# this is (sqrt(1 + x**3)/x).integrate(x).diff(x) - sqrt(1 + x**3)/x
a = sqrt(x)/sqrt(1 + x**(-3)) - sqrt(x**3 + 1)/x + 1/(x**Rational(5, 2)* \
(1 + x**(-3))**Rational(3, 2)) + 1/(x**Rational(11, 2)*(1 + x**(-3))**Rational(3, 2))
assert minimal_polynomial(a, y) == y
raises(NotAlgebraic, lambda: minimal_polynomial(exp(x), y))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x), x))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x) - y, x))
raises(NotImplementedError, lambda: minimal_polynomial(sqrt(x), y, compose=False))
@slow
def test_minpoly_fraction_field_slow():
assert minimal_polynomial(minimal_polynomial(sqrt(x**Rational(1,5) - 1),
y).subs(y, sqrt(x**Rational(1,5) - 1)), z) == z
def test_minpoly_domain():
assert minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - sqrt(2)
assert minimal_polynomial(sqrt(8), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - 2*sqrt(2)
assert minimal_polynomial(sqrt(Rational(3,2)), x,
domain=QQ.algebraic_field(sqrt(2))) == 2*x**2 - 3
raises(NotAlgebraic, lambda: minimal_polynomial(y, x, domain=QQ))
def test_issue_14831():
a = -2*sqrt(2)*sqrt(12*sqrt(2) + 17)
assert minimal_polynomial(a, x) == x**2 + 16*x - 8
e = (-3*sqrt(12*sqrt(2) + 17) + 12*sqrt(2) +
17 - 2*sqrt(2)*sqrt(12*sqrt(2) + 17))
assert minimal_polynomial(e, x) == x
|
c73f2ba464d876153d1cc53e1a7bdee3d38092902037cd0d96053826775abdb6 | """Test sparse rational functions. """
from sympy.polys.fields import field, sfield, FracField, FracElement
from sympy.polys.rings import ring
from sympy.polys.domains import ZZ, QQ
from sympy.polys.orderings import lex
from sympy.utilities.pytest import raises, XFAIL
from sympy.core import symbols, E, S
from sympy import sqrt, Rational, exp, log
def test_FracField___init__():
F1 = FracField("x,y", ZZ, lex)
F2 = FracField("x,y", ZZ, lex)
F3 = FracField("x,y,z", ZZ, lex)
assert F1.x == F1.gens[0]
assert F1.y == F1.gens[1]
assert F1.x == F2.x
assert F1.y == F2.y
assert F1.x != F3.x
assert F1.y != F3.y
def test_FracField___hash__():
F, x, y, z = field("x,y,z", QQ)
assert hash(F)
def test_FracField___eq__():
assert field("x,y,z", QQ)[0] == field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] is field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] != field("x,y,z", ZZ)[0]
assert field("x,y,z", QQ)[0] is not field("x,y,z", ZZ)[0]
assert field("x,y,z", ZZ)[0] != field("x,y,z", QQ)[0]
assert field("x,y,z", ZZ)[0] is not field("x,y,z", QQ)[0]
assert field("x,y,z", QQ)[0] != field("x,y", QQ)[0]
assert field("x,y,z", QQ)[0] is not field("x,y", QQ)[0]
assert field("x,y", QQ)[0] != field("x,y,z", QQ)[0]
assert field("x,y", QQ)[0] is not field("x,y,z", QQ)[0]
def test_sfield():
x = symbols("x")
F = FracField((E, exp(exp(x)), exp(x)), ZZ, lex)
e, exex, ex = F.gens
assert sfield(exp(x)*exp(exp(x) + 1 + log(exp(x) + 3)/2)**2/(exp(x) + 3)) \
== (F, e**2*exex**2*ex)
F = FracField((x, exp(1/x), log(x), x**QQ(1, 3)), ZZ, lex)
_, ex, lg, x3 = F.gens
assert sfield(((x-3)*log(x)+4*x**2)*exp(1/x+log(x)/3)/x**2) == \
(F, (4*F.x**2*ex + F.x*ex*lg - 3*ex*lg)/x3**5)
F = FracField((x, log(x), sqrt(x + log(x))), ZZ, lex)
_, lg, srt = F.gens
assert sfield((x + 1) / (x * (x + log(x))**QQ(3, 2)) - 1/(x * log(x)**2)) \
== (F, (F.x*lg**2 - F.x*srt + lg**2 - lg*srt)/
(F.x**2*lg**2*srt + F.x*lg**3*srt))
def test_FracElement___hash__():
F, x, y, z = field("x,y,z", QQ)
assert hash(x*y/z)
def test_FracElement_copy():
F, x, y, z = field("x,y,z", ZZ)
f = x*y/3*z
g = f.copy()
assert f == g
g.numer[(1, 1, 1)] = 7
assert f != g
def test_FracElement_as_expr():
F, x, y, z = field("x,y,z", ZZ)
f = (3*x**2*y - x*y*z)/(7*z**3 + 1)
X, Y, Z = F.symbols
g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1)
assert f != g
assert f.as_expr() == g
X, Y, Z = symbols("x,y,z")
g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1)
assert f != g
assert f.as_expr(X, Y, Z) == g
raises(ValueError, lambda: f.as_expr(X))
def test_FracElement_from_expr():
x, y, z = symbols("x,y,z")
F, X, Y, Z = field((x, y, z), ZZ)
f = F.from_expr(1)
assert f == 1 and isinstance(f, F.dtype)
f = F.from_expr(Rational(3, 7))
assert f == F(3)/7 and isinstance(f, F.dtype)
f = F.from_expr(x)
assert f == X and isinstance(f, F.dtype)
f = F.from_expr(Rational(3,7)*x)
assert f == X*Rational(3, 7) and isinstance(f, F.dtype)
f = F.from_expr(1/x)
assert f == 1/X and isinstance(f, F.dtype)
f = F.from_expr(x*y*z)
assert f == X*Y*Z and isinstance(f, F.dtype)
f = F.from_expr(x*y/z)
assert f == X*Y/Z and isinstance(f, F.dtype)
f = F.from_expr(x*y*z + x*y + x)
assert f == X*Y*Z + X*Y + X and isinstance(f, F.dtype)
f = F.from_expr((x*y*z + x*y + x)/(x*y + 7))
assert f == (X*Y*Z + X*Y + X)/(X*Y + 7) and isinstance(f, F.dtype)
f = F.from_expr(x**3*y*z + x**2*y**7 + 1)
assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, F.dtype)
raises(ValueError, lambda: F.from_expr(2**x))
raises(ValueError, lambda: F.from_expr(7*x + sqrt(2)))
assert isinstance(ZZ[2**x].get_field().convert(2**(-x)),
FracElement)
assert isinstance(ZZ[x**2].get_field().convert(x**(-6)),
FracElement)
assert isinstance(ZZ[exp(Rational(1, 3))].get_field().convert(E),
FracElement)
def test_FracElement__lt_le_gt_ge__():
F, x, y = field("x,y", ZZ)
assert F(1) < 1/x < 1/x**2 < 1/x**3
assert F(1) <= 1/x <= 1/x**2 <= 1/x**3
assert -7/x < 1/x < 3/x < y/x < 1/x**2
assert -7/x <= 1/x <= 3/x <= y/x <= 1/x**2
assert 1/x**3 > 1/x**2 > 1/x > F(1)
assert 1/x**3 >= 1/x**2 >= 1/x >= F(1)
assert 1/x**2 > y/x > 3/x > 1/x > -7/x
assert 1/x**2 >= y/x >= 3/x >= 1/x >= -7/x
def test_FracElement___neg__():
F, x,y = field("x,y", QQ)
f = (7*x - 9)/y
g = (-7*x + 9)/y
assert -f == g
assert -g == f
def test_FracElement___add__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f + g == g + f == (x + y)/(x*y)
assert x + F.ring.gens[0] == F.ring.gens[0] + x == 2*x
F, x,y = field("x,y", ZZ)
assert x + 3 == 3 + x
assert x + QQ(3,7) == QQ(3,7) + x == (7*x + 3)/7
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v + x)/(y + u*v)
assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v + x)/(y + u*v)
assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v}
def test_FracElement___sub__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f - g == (-x + y)/(x*y)
assert x - F.ring.gens[0] == F.ring.gens[0] - x == 0
F, x,y = field("x,y", ZZ)
assert x - 3 == -(3 - x)
assert x - QQ(3,7) == -(QQ(3,7) - x) == (7*x - 3)/7
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v - x)/(y - u*v)
assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v - x)/(y - u*v)
assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v}
assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v}
def test_FracElement___mul__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f*g == g*f == 1/(x*y)
assert x*F.ring.gens[0] == F.ring.gens[0]*x == x**2
F, x,y = field("x,y", ZZ)
assert x*3 == 3*x
assert x*QQ(3,7) == QQ(3,7)*x == x*Rational(3, 7)
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)
assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1}
assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)
assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1}
assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1}
def test_FracElement___div__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f/g == y/x
assert x/F.ring.gens[0] == F.ring.gens[0]/x == 1
F, x,y = field("x,y", ZZ)
assert x*3 == 3*x
assert x/QQ(3,7) == (QQ(3,7)/x)**-1 == x*Rational(7, 3)
raises(ZeroDivisionError, lambda: x/0)
raises(ZeroDivisionError, lambda: 1/(x - x))
raises(ZeroDivisionError, lambda: x/(x - x))
Fuv, u,v = field("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
f = (u*v)/(x*y)
assert dict(f.numer) == {(0, 0, 0, 0): u*v}
assert dict(f.denom) == {(1, 1, 0, 0): 1}
g = (x*y)/(u*v)
assert dict(g.numer) == {(1, 1, 0, 0): 1}
assert dict(g.denom) == {(0, 0, 0, 0): u*v}
Ruv, u,v = ring("u,v", ZZ)
Fxyzt, x,y,z,t = field("x,y,z,t", Ruv)
f = (u*v)/(x*y)
assert dict(f.numer) == {(0, 0, 0, 0): u*v}
assert dict(f.denom) == {(1, 1, 0, 0): 1}
g = (x*y)/(u*v)
assert dict(g.numer) == {(1, 1, 0, 0): 1}
assert dict(g.denom) == {(0, 0, 0, 0): u*v}
def test_FracElement___pow__():
F, x,y = field("x,y", QQ)
f, g = 1/x, 1/y
assert f**3 == 1/x**3
assert g**3 == 1/y**3
assert (f*g)**3 == 1/(x**3*y**3)
assert (f*g)**-3 == (x*y)**3
raises(ZeroDivisionError, lambda: (x - x)**-3)
def test_FracElement_diff():
F, x,y,z = field("x,y,z", ZZ)
assert ((x**2 + y)/(z + 1)).diff(x) == 2*x/(z + 1)
@XFAIL
def test_FracElement___call__():
F, x,y,z = field("x,y,z", ZZ)
f = (x**2 + 3*y)/z
r = f(1, 1, 1)
assert r == 4 and not isinstance(r, FracElement)
raises(ZeroDivisionError, lambda: f(1, 1, 0))
def test_FracElement_evaluate():
F, x,y,z = field("x,y,z", ZZ)
Fyz = field("y,z", ZZ)[0]
f = (x**2 + 3*y)/z
assert f.evaluate(x, 0) == 3*Fyz.y/Fyz.z
raises(ZeroDivisionError, lambda: f.evaluate(z, 0))
def test_FracElement_subs():
F, x,y,z = field("x,y,z", ZZ)
f = (x**2 + 3*y)/z
assert f.subs(x, 0) == 3*y/z
raises(ZeroDivisionError, lambda: f.subs(z, 0))
def test_FracElement_compose():
pass
|
2a9d0c32e980c07f8d8de6837679790963b5f1c45a7cadd7aa1e39ccd2eba429 | """Tests for the implementation of RootOf class and related tools. """
from sympy.polys.polytools import Poly
from sympy.polys.rootoftools import (rootof, RootOf, CRootOf, RootSum,
_pure_key_dict as D)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
GeneratorsNeeded,
PolynomialError,
)
from sympy import (
S, sqrt, I, Rational, Float, Lambda, log, exp, tan, Function, Eq,
solve, legendre_poly, Integral
)
from sympy.utilities.pytest import raises, slow
from sympy.core.expr import unchanged
from sympy.core.compatibility import range
from sympy.abc import a, b, x, y, z, r
def test_CRootOf___new__():
assert rootof(x, 0) == 0
assert rootof(x, -1) == 0
assert rootof(x, S.Zero) == 0
assert rootof(x - 1, 0) == 1
assert rootof(x - 1, -1) == 1
assert rootof(x + 1, 0) == -1
assert rootof(x + 1, -1) == -1
assert rootof(x**2 + 2*x + 3, 0) == -1 - I*sqrt(2)
assert rootof(x**2 + 2*x + 3, 1) == -1 + I*sqrt(2)
assert rootof(x**2 + 2*x + 3, -1) == -1 + I*sqrt(2)
assert rootof(x**2 + 2*x + 3, -2) == -1 - I*sqrt(2)
r = rootof(x**2 + 2*x + 3, 0, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, 1, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, -1, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, -2, radicals=False)
assert isinstance(r, RootOf) is True
assert rootof((x - 1)*(x + 1), 0, radicals=False) == -1
assert rootof((x - 1)*(x + 1), 1, radicals=False) == 1
assert rootof((x - 1)*(x + 1), -1, radicals=False) == 1
assert rootof((x - 1)*(x + 1), -2, radicals=False) == -1
assert rootof((x - 1)*(x + 1), 0, radicals=True) == -1
assert rootof((x - 1)*(x + 1), 1, radicals=True) == 1
assert rootof((x - 1)*(x + 1), -1, radicals=True) == 1
assert rootof((x - 1)*(x + 1), -2, radicals=True) == -1
assert rootof((x - 1)*(x**3 + x + 3), 0) == rootof(x**3 + x + 3, 0)
assert rootof((x - 1)*(x**3 + x + 3), 1) == 1
assert rootof((x - 1)*(x**3 + x + 3), 2) == rootof(x**3 + x + 3, 1)
assert rootof((x - 1)*(x**3 + x + 3), 3) == rootof(x**3 + x + 3, 2)
assert rootof((x - 1)*(x**3 + x + 3), -1) == rootof(x**3 + x + 3, 2)
assert rootof((x - 1)*(x**3 + x + 3), -2) == rootof(x**3 + x + 3, 1)
assert rootof((x - 1)*(x**3 + x + 3), -3) == 1
assert rootof((x - 1)*(x**3 + x + 3), -4) == rootof(x**3 + x + 3, 0)
assert rootof(x**4 + 3*x**3, 0) == -3
assert rootof(x**4 + 3*x**3, 1) == 0
assert rootof(x**4 + 3*x**3, 2) == 0
assert rootof(x**4 + 3*x**3, 3) == 0
raises(GeneratorsNeeded, lambda: rootof(0, 0))
raises(GeneratorsNeeded, lambda: rootof(1, 0))
raises(PolynomialError, lambda: rootof(Poly(0, x), 0))
raises(PolynomialError, lambda: rootof(Poly(1, x), 0))
raises(PolynomialError, lambda: rootof(x - y, 0))
# issue 8617
raises(PolynomialError, lambda: rootof(exp(x), 0))
raises(NotImplementedError, lambda: rootof(x**3 - x + sqrt(2), 0))
raises(NotImplementedError, lambda: rootof(x**3 - x + I, 0))
raises(IndexError, lambda: rootof(x**2 - 1, -4))
raises(IndexError, lambda: rootof(x**2 - 1, -3))
raises(IndexError, lambda: rootof(x**2 - 1, 2))
raises(IndexError, lambda: rootof(x**2 - 1, 3))
raises(ValueError, lambda: rootof(x**2 - 1, x))
assert rootof(Poly(x - y, x), 0) == y
assert rootof(Poly(x**2 - y, x), 0) == -sqrt(y)
assert rootof(Poly(x**2 - y, x), 1) == sqrt(y)
assert rootof(Poly(x**3 - y, x), 0) == y**Rational(1, 3)
assert rootof(y*x**3 + y*x + 2*y, x, 0) == -1
raises(NotImplementedError, lambda: rootof(x**3 + x + 2*y, x, 0))
assert rootof(x**3 + x + 1, 0).is_commutative is True
def test_CRootOf_attributes():
r = rootof(x**3 + x + 3, 0)
assert r.is_number
assert r.free_symbols == set()
# if the following assertion fails then multivariate polynomials
# are apparently supported and the RootOf.free_symbols routine
# should be changed to return whatever symbols would not be
# the PurePoly dummy symbol
raises(NotImplementedError, lambda: rootof(Poly(x**3 + y*x + 1, x), 0))
def test_CRootOf___eq__():
assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 0)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 1)) is False
assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 1)) is True
assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 2)) is False
assert (rootof(x**3 + x + 3, 2) == rootof(x**3 + x + 3, 2)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 0)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 1)) is False
assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 1)) is True
assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 2)) is False
assert (rootof(x**3 + x + 3, 2) == rootof(y**3 + y + 3, 2)) is True
def test_CRootOf___eval_Eq__():
f = Function('f')
eq = x**3 + x + 3
r = rootof(eq, 2)
r1 = rootof(eq, 1)
assert Eq(r, r1) is S.false
assert Eq(r, r) is S.true
assert unchanged(Eq, r, x)
assert Eq(r, 0) is S.false
assert Eq(r, S.Infinity) is S.false
assert Eq(r, I) is S.false
assert unchanged(Eq, r, f(0))
sol = solve(eq)
for s in sol:
if s.is_real:
assert Eq(r, s) is S.false
r = rootof(eq, 0)
for s in sol:
if s.is_real:
assert Eq(r, s) is S.true
eq = x**3 + x + 1
sol = solve(eq)
assert [Eq(rootof(eq, i), j) for i in range(3) for j in sol] == [
False, False, True, False, True, False, True, False, False]
assert Eq(rootof(eq, 0), 1 + S.ImaginaryUnit) == False
def test_CRootOf_is_real():
assert rootof(x**3 + x + 3, 0).is_real is True
assert rootof(x**3 + x + 3, 1).is_real is False
assert rootof(x**3 + x + 3, 2).is_real is False
def test_CRootOf_is_complex():
assert rootof(x**3 + x + 3, 0).is_complex is True
def test_CRootOf_subs():
assert rootof(x**3 + x + 1, 0).subs(x, y) == rootof(y**3 + y + 1, 0)
def test_CRootOf_diff():
assert rootof(x**3 + x + 1, 0).diff(x) == 0
assert rootof(x**3 + x + 1, 0).diff(y) == 0
@slow
def test_CRootOf_evalf():
real = rootof(x**3 + x + 3, 0).evalf(n=20)
assert real.epsilon_eq(Float("-1.2134116627622296341"))
re, im = rootof(x**3 + x + 3, 1).evalf(n=20).as_real_imag()
assert re.epsilon_eq( Float("0.60670583138111481707"))
assert im.epsilon_eq(-Float("1.45061224918844152650"))
re, im = rootof(x**3 + x + 3, 2).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("0.60670583138111481707"))
assert im.epsilon_eq(Float("1.45061224918844152650"))
p = legendre_poly(4, x, polys=True)
roots = [str(r.n(17)) for r in p.real_roots()]
# magnitudes are given by
# sqrt(3/S(7) - 2*sqrt(6/S(5))/7)
# and
# sqrt(3/S(7) + 2*sqrt(6/S(5))/7)
assert roots == [
"-0.86113631159405258",
"-0.33998104358485626",
"0.33998104358485626",
"0.86113631159405258",
]
re = rootof(x**5 - 5*x + 12, 0).evalf(n=20)
assert re.epsilon_eq(Float("-1.84208596619025438271"))
re, im = rootof(x**5 - 5*x + 12, 1).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("-0.351854240827371999559"))
assert im.epsilon_eq(Float("-1.709561043370328882010"))
re, im = rootof(x**5 - 5*x + 12, 2).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("-0.351854240827371999559"))
assert im.epsilon_eq(Float("+1.709561043370328882010"))
re, im = rootof(x**5 - 5*x + 12, 3).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("+1.272897223922499190910"))
assert im.epsilon_eq(Float("-0.719798681483861386681"))
re, im = rootof(x**5 - 5*x + 12, 4).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("+1.272897223922499190910"))
assert im.epsilon_eq(Float("+0.719798681483861386681"))
# issue 6393
assert str(rootof(x**5 + 2*x**4 + x**3 - 68719476736, 0).n(3)) == '147.'
eq = (531441*x**11 + 3857868*x**10 + 13730229*x**9 + 32597882*x**8 +
55077472*x**7 + 60452000*x**6 + 32172064*x**5 - 4383808*x**4 -
11942912*x**3 - 1506304*x**2 + 1453312*x + 512)
a, b = rootof(eq, 1).n(2).as_real_imag()
c, d = rootof(eq, 2).n(2).as_real_imag()
assert a == c
assert b < d
assert b == -d
# issue 6451
r = rootof(legendre_poly(64, x), 7)
assert r.n(2) == r.n(100).n(2)
# issue 9019
r0 = rootof(x**2 + 1, 0, radicals=False)
r1 = rootof(x**2 + 1, 1, radicals=False)
assert r0.n(4) == -1.0*I
assert r1.n(4) == 1.0*I
# make sure verification is used in case a max/min traps the "root"
assert str(rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).n(3)) == '-0.976'
# watch out for UnboundLocalError
c = CRootOf(90720*x**6 - 4032*x**4 + 84*x**2 - 1, 0)
assert c._eval_evalf(2) # doesn't fail
# watch out for imaginary parts that don't want to evaluate
assert str(RootOf(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 +
39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 +
877969, 10).n(2)) == '-3.4*I'
assert abs(RootOf(x**4 + 10*x**2 + 1, 0).n(2)) < 0.4
# check reset and args
r = [RootOf(x**3 + x + 3, i) for i in range(3)]
r[0]._reset()
for ri in r:
i = ri._get_interval()
n = ri.n(2)
assert i != ri._get_interval()
ri._reset()
assert i == ri._get_interval()
assert i == i.func(*i.args)
def test_CRootOf_evalf_caching_bug():
r = rootof(x**5 - 5*x + 12, 1)
r.n()
a = r._get_interval()
r = rootof(x**5 - 5*x + 12, 1)
r.n()
b = r._get_interval()
assert a == b
def test_CRootOf_real_roots():
assert Poly(x**5 + x + 1).real_roots() == [rootof(x**3 - x**2 + 1, 0)]
assert Poly(x**5 + x + 1).real_roots(radicals=False) == [rootof(
x**3 - x**2 + 1, 0)]
def test_CRootOf_all_roots():
assert Poly(x**5 + x + 1).all_roots() == [
rootof(x**3 - x**2 + 1, 0),
Rational(-1, 2) - sqrt(3)*I/2,
Rational(-1, 2) + sqrt(3)*I/2,
rootof(x**3 - x**2 + 1, 1),
rootof(x**3 - x**2 + 1, 2),
]
assert Poly(x**5 + x + 1).all_roots(radicals=False) == [
rootof(x**3 - x**2 + 1, 0),
rootof(x**2 + x + 1, 0, radicals=False),
rootof(x**2 + x + 1, 1, radicals=False),
rootof(x**3 - x**2 + 1, 1),
rootof(x**3 - x**2 + 1, 2),
]
def test_CRootOf_eval_rational():
p = legendre_poly(4, x, polys=True)
roots = [r.eval_rational(n=18) for r in p.real_roots()]
for r in roots:
assert isinstance(r, Rational)
roots = [str(r.n(17)) for r in roots]
assert roots == [
"-0.86113631159405258",
"-0.33998104358485626",
"0.33998104358485626",
"0.86113631159405258",
]
def test_RootSum___new__():
f = x**3 + x + 3
g = Lambda(r, log(r*x))
s = RootSum(f, g)
assert isinstance(s, RootSum) is True
assert RootSum(f**2, g) == 2*RootSum(f, g)
assert RootSum((x - 7)*f**3, g) == log(7*x) + 3*RootSum(f, g)
# issue 5571
assert hash(RootSum((x - 7)*f**3, g)) == hash(log(7*x) + 3*RootSum(f, g))
raises(MultivariatePolynomialError, lambda: RootSum(x**3 + x + y))
raises(ValueError, lambda: RootSum(x**2 + 3, lambda x: x))
assert RootSum(f, exp) == RootSum(f, Lambda(x, exp(x)))
assert RootSum(f, log) == RootSum(f, Lambda(x, log(x)))
assert isinstance(RootSum(f, auto=False), RootSum) is True
assert RootSum(f) == 0
assert RootSum(f, Lambda(x, x)) == 0
assert RootSum(f, Lambda(x, x**2)) == -2
assert RootSum(f, Lambda(x, 1)) == 3
assert RootSum(f, Lambda(x, 2)) == 6
assert RootSum(f, auto=False).is_commutative is True
assert RootSum(f, Lambda(x, 1/(x + x**2))) == Rational(11, 3)
assert RootSum(f, Lambda(x, y/(x + x**2))) == Rational(11, 3)*y
assert RootSum(x**2 - 1, Lambda(x, 3*x**2), x) == 6
assert RootSum(x**2 - y, Lambda(x, 3*x**2), x) == 6*y
assert RootSum(x**2 - 1, Lambda(x, z*x**2), x) == 2*z
assert RootSum(x**2 - y, Lambda(x, z*x**2), x) == 2*z*y
assert RootSum(
x**2 - 1, Lambda(x, exp(x)), quadratic=True) == exp(-1) + exp(1)
assert RootSum(x**3 + a*x + a**3, tan, x) == \
RootSum(x**3 + x + 1, Lambda(x, tan(a*x)))
assert RootSum(a**3*x**3 + a*x + 1, tan, x) == \
RootSum(x**3 + x + 1, Lambda(x, tan(x/a)))
def test_RootSum_free_symbols():
assert RootSum(x**3 + x + 3, Lambda(r, exp(r))).free_symbols == set()
assert RootSum(x**3 + x + 3, Lambda(r, exp(a*r))).free_symbols == {a}
assert RootSum(
x**3 + x + y, Lambda(r, exp(a*r)), x).free_symbols == {a, y}
def test_RootSum___eq__():
f = Lambda(x, exp(x))
assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 1, f)) is True
assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 1, f)) is True
assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 2, f)) is False
assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 2, f)) is False
def test_RootSum_doit():
rs = RootSum(x**2 + 1, exp)
assert isinstance(rs, RootSum) is True
assert rs.doit() == exp(-I) + exp(I)
rs = RootSum(x**2 + a, exp, x)
assert isinstance(rs, RootSum) is True
assert rs.doit() == exp(-sqrt(-a)) + exp(sqrt(-a))
def test_RootSum_evalf():
rs = RootSum(x**2 + 1, exp)
assert rs.evalf(n=20, chop=True).epsilon_eq(Float("1.0806046117362794348"))
assert rs.evalf(n=15, chop=True).epsilon_eq(Float("1.08060461173628"))
rs = RootSum(x**2 + a, exp, x)
assert rs.evalf() == rs
def test_RootSum_diff():
f = x**3 + x + 3
g = Lambda(r, exp(r*x))
h = Lambda(r, r*exp(r*x))
assert RootSum(f, g).diff(x) == RootSum(f, h)
def test_RootSum_subs():
f = x**3 + x + 3
g = Lambda(r, exp(r*x))
F = y**3 + y + 3
G = Lambda(r, exp(r*y))
assert RootSum(f, g).subs(y, 1) == RootSum(f, g)
assert RootSum(f, g).subs(x, y) == RootSum(F, G)
def test_RootSum_rational():
assert RootSum(
z**5 - z + 1, Lambda(z, z/(x - z))) == (4*x - 5)/(x**5 - x + 1)
f = 161*z**3 + 115*z**2 + 19*z + 1
g = Lambda(z, z*log(
-3381*z**4/4 - 3381*z**3/4 - 625*z**2/2 - z*Rational(125, 2) - 5 + exp(x)))
assert RootSum(f, g).diff(x) == -(
(5*exp(2*x) - 6*exp(x) + 4)*exp(x)/(exp(3*x) - exp(2*x) + 1))/7
def test_RootSum_independent():
f = (x**3 - a)**2*(x**4 - b)**3
g = Lambda(x, 5*tan(x) + 7)
h = Lambda(x, tan(x))
r0 = RootSum(x**3 - a, h, x)
r1 = RootSum(x**4 - b, h, x)
assert RootSum(f, g, x).as_ordered_terms() == [10*r0, 15*r1, 126]
def test_issue_7876():
l1 = Poly(x**6 - x + 1, x).all_roots()
l2 = [rootof(x**6 - x + 1, i) for i in range(6)]
assert frozenset(l1) == frozenset(l2)
def test_issue_8316():
f = Poly(7*x**8 - 9)
assert len(f.all_roots()) == 8
f = Poly(7*x**8 - 10)
assert len(f.all_roots()) == 8
def test__imag_count():
from sympy.polys.rootoftools import _imag_count_of_factor
def imag_count(p):
return sum([_imag_count_of_factor(f)*m for f, m in
p.factor_list()[1]])
assert imag_count(Poly(x**6 + 10*x**2 + 1)) == 2
assert imag_count(Poly(x**2)) == 0
assert imag_count(Poly([1]*3 + [-1], x)) == 0
assert imag_count(Poly(x**3 + 1)) == 0
assert imag_count(Poly(x**2 + 1)) == 2
assert imag_count(Poly(x**2 - 1)) == 0
assert imag_count(Poly(x**4 - 1)) == 2
assert imag_count(Poly(x**4 + 1)) == 0
assert imag_count(Poly([1, 2, 3], x)) == 0
assert imag_count(Poly(x**3 + x + 1)) == 0
assert imag_count(Poly(x**4 + x + 1)) == 0
def q(r1, r2, p):
return Poly(((x - r1)*(x - r2)).subs(x, x**p), x)
assert imag_count(q(-1, -2, 2)) == 4
assert imag_count(q(-1, 2, 2)) == 2
assert imag_count(q(1, 2, 2)) == 0
assert imag_count(q(1, 2, 4)) == 4
assert imag_count(q(-1, 2, 4)) == 2
assert imag_count(q(-1, -2, 4)) == 0
def test_RootOf_is_imaginary():
r = RootOf(x**4 + 4*x**2 + 1, 1)
i = r._get_interval()
assert r.is_imaginary and i.ax*i.bx <= 0
def test_is_disjoint():
eq = x**3 + 5*x + 1
ir = rootof(eq, 0)._get_interval()
ii = rootof(eq, 1)._get_interval()
assert ir.is_disjoint(ii)
assert ii.is_disjoint(ir)
def test_pure_key_dict():
p = D()
assert (x in p) is False
assert (1 in p) is False
p[x] = 1
assert x in p
assert y in p
assert p[y] == 1
raises(KeyError, lambda: p[1])
def dont(k):
p[k] = 2
raises(ValueError, lambda: dont(1))
@slow
def test_eval_approx_relative():
CRootOf.clear_cache()
t = [CRootOf(x**3 + 10*x + 1, i) for i in range(3)]
assert [i.eval_rational(1e-1) for i in t] == [
Rational(-21, 220), Rational(15, 256) - I*Rational(805, 256),
Rational(15, 256) + I*Rational(805, 256)]
t[0]._reset()
assert [i.eval_rational(1e-1, 1e-4) for i in t] == [
Rational(-21, 220), Rational(3275, 65536) - I*Rational(414645, 131072),
Rational(3275, 65536) + I*Rational(414645, 131072)]
assert S(t[0]._get_interval().dx) < 1e-1
assert S(t[1]._get_interval().dx) < 1e-1
assert S(t[1]._get_interval().dy) < 1e-4
assert S(t[2]._get_interval().dx) < 1e-1
assert S(t[2]._get_interval().dy) < 1e-4
t[0]._reset()
assert [i.eval_rational(1e-4, 1e-4) for i in t] == [
Rational(-2001, 20020), Rational(6545, 131072) - I*Rational(414645, 131072),
Rational(6545, 131072) + I*Rational(414645, 131072)]
assert S(t[0]._get_interval().dx) < 1e-4
assert S(t[1]._get_interval().dx) < 1e-4
assert S(t[1]._get_interval().dy) < 1e-4
assert S(t[2]._get_interval().dx) < 1e-4
assert S(t[2]._get_interval().dy) < 1e-4
# in the following, the actual relative precision is
# less than tested, but it should never be greater
t[0]._reset()
assert [i.eval_rational(n=2) for i in t] == [
Rational(-202201, 2024022), Rational(104755, 2097152) - I*Rational(6634255, 2097152),
Rational(104755, 2097152) + I*Rational(6634255, 2097152)]
assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-2
assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-2
assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-2
assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-2
assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-2
t[0]._reset()
assert [i.eval_rational(n=3) for i in t] == [
Rational(-202201, 2024022), Rational(1676045, 33554432) - I*Rational(106148135, 33554432),
Rational(1676045, 33554432) + I*Rational(106148135, 33554432)]
assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-3
assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-3
assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-3
assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-3
assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-3
t[0]._reset()
a = [i.eval_approx(2) for i in t]
assert [str(i) for i in a] == [
'-0.10', '0.05 - 3.2*I', '0.05 + 3.2*I']
assert all(abs(((a[i] - t[i])/t[i]).n()) < 1e-2 for i in range(len(a)))
def test_issue_15920():
r = rootof(x**5 - x + 1, 0)
p = Integral(x, (x, 1, y))
assert unchanged(Eq, r, p)
|
1dfdddce286eadea2488c09bba4809d4f23b3ffa624ed53cb039da1202eb8d57 | """Tests for user-friendly public interface to polynomial functions. """
from sympy.polys.polytools import (
Poly, PurePoly, poly,
parallel_poly_from_expr,
degree, degree_list,
total_degree,
LC, LM, LT,
pdiv, prem, pquo, pexquo,
div, rem, quo, exquo,
half_gcdex, gcdex, invert,
subresultants,
resultant, discriminant,
terms_gcd, cofactors,
gcd, gcd_list,
lcm, lcm_list,
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,
GroebnerBasis, is_zero_dimensional,
_torational_factor_list,
to_rational_coeffs)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
ExactQuotientFailed,
PolificationFailed,
ComputationFailed,
UnificationFailed,
RefinementFailed,
GeneratorsNeeded,
GeneratorsError,
PolynomialError,
CoercionFailed,
DomainError,
OptionError,
FlagError)
from sympy.polys.polyclasses import DMP
from sympy.polys.fields import field
from sympy.polys.domains import FF, ZZ, QQ, RR, EX
from sympy.polys.domains.realfield import RealField
from sympy.polys.orderings import lex, grlex, grevlex
from sympy import (
S, Integer, Rational, Float, Mul, Symbol, sqrt, Piecewise, Derivative,
exp, sin, tanh, expand, oo, I, pi, re, im, rootof, Eq, Tuple, Expr, diff)
from sympy.core.basic import _aresame
from sympy.core.compatibility import iterable, PY3
from sympy.core.mul import _keep_coeff
from sympy.utilities.pytest import raises, XFAIL
from sympy.abc import a, b, c, d, p, q, t, w, x, y, z
from sympy import MatrixSymbol
def _epsilon_eq(a, b):
for x, y in zip(a, b):
if abs(x - y) > 1e-10:
return False
return True
def _strict_eq(a, b):
if type(a) == type(b):
if iterable(a):
if len(a) == len(b):
return all(_strict_eq(c, d) for c, d in zip(a, b))
else:
return False
else:
return isinstance(a, Poly) and a.eq(b, strict=True)
else:
return False
def test_Poly_from_dict():
K = FF(3)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=(
x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K)
assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \
Poly(sin(y)*x, x, domain='EX')
assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \
Poly(y*x, x, domain='EX')
assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \
Poly(x*y, x, y, domain='ZZ')
assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \
Poly(y*x, x, z, domain='EX')
def test_Poly_from_list():
K = FF(3)
assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR)
assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR)
raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y)))
def test_Poly_from_poly():
f = Poly(x + 7, x, domain=ZZ)
g = Poly(x + 2, x, modulus=3)
h = Poly(x + y, x, y, domain=ZZ)
K = FF(3)
assert Poly.from_poly(f) == f
assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=x) == f
assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]')
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ))
assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ')
assert Poly.from_poly(
f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)')
K = FF(2)
assert Poly.from_poly(g) == g
assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ))
assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K)
assert Poly.from_poly(g, gens=x) == g
assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ))
assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K)
K = FF(3)
assert Poly.from_poly(h) == h
assert Poly.from_poly(
h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ))
assert Poly.from_poly(
h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ))
assert Poly.from_poly(
h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3))
assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ))
assert Poly.from_poly(
h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ))
assert Poly.from_poly(
h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3))
assert Poly.from_poly(h, gens=(x, y)) == h
assert Poly.from_poly(
h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
def test_Poly_from_expr():
raises(GeneratorsNeeded, lambda: Poly.from_expr(S.Zero))
raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7)))
F3 = FF(3)
assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ)
assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ)
def test_Poly__new__():
raises(GeneratorsError, lambda: Poly(x + 1, x, x))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x]))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y]))
raises(OptionError, lambda: Poly(x, x, symmetric=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False))
raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex'))
raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex'))
raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1}))
raises(GeneratorsNeeded, lambda: Poly([2, 1]))
raises(GeneratorsNeeded, lambda: Poly((2, 1)))
raises(GeneratorsNeeded, lambda: Poly(1))
f = a*x**2 + b*x + c
assert Poly({2: a, 1: b, 0: c}, x) == f
assert Poly(iter([a, b, c]), x) == f
assert Poly([a, b, c], x) == f
assert Poly((a, b, c), x) == f
f = Poly({}, x, y, z)
assert f.gens == (x, y, z) and f.as_expr() == 0
assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x)
assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='ZZ'))
assert Poly(
3*x**2/5 + x*Rational(2, 5) + 1, domain='QQ').all_coeffs() == [Rational(3, 5), Rational(2, 5), 1]
assert _epsilon_eq(
Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0])
assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(
3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ'))
assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [Rational(31, 10), Rational(21, 10), 1]
assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0]
assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \
Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y)
assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I)
f = 3*x**5 - x**4 + x**3 - x** 2 + 65538
assert Poly(f, x, modulus=65537, symmetric=True) == \
Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537,
symmetric=True)
assert Poly(f, x, modulus=65537, symmetric=False) == \
Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x,
modulus=65537, symmetric=False)
assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField)
def test_Poly__args():
assert Poly(x**2 + 1).args == (x**2 + 1,)
def test_Poly__gens():
assert Poly((x - p)*(x - q), x).gens == (x,)
assert Poly((x - p)*(x - q), p).gens == (p,)
assert Poly((x - p)*(x - q), q).gens == (q,)
assert Poly((x - p)*(x - q), x, p).gens == (x, p)
assert Poly((x - p)*(x - q), x, q).gens == (x, q)
assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q)
assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q)
assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x)
assert Poly((x - p)*(x - q)).gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q)
assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p)
assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p)
assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x)
def test_Poly_zero():
assert Poly(x).zero == Poly(0, x, domain=ZZ)
assert Poly(x/2).zero == Poly(0, x, domain=QQ)
def test_Poly_one():
assert Poly(x).one == Poly(1, x, domain=ZZ)
assert Poly(x/2).one == Poly(1, x, domain=QQ)
def test_Poly__unify():
raises(UnificationFailed, lambda: Poly(x)._unify(y))
F3 = FF(3)
F5 = FF(5)
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == (
DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == (
DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5))
assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
F, A, B = field("a,b", ZZ)
assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)'))
f = Poly(t**2 + t/3 + x, t, domain='QQ(x)')
g = Poly(t**2 + t/3 + x, t, domain='QQ[x]')
assert f._unify(g)[2:] == (f.rep, f.rep)
def test_Poly_free_symbols():
assert Poly(x**2 + 1).free_symbols == {x}
assert Poly(x**2 + y*z).free_symbols == {x, y, z}
assert Poly(x**2 + y*z, x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z}
assert Poly(1 + x + x**2, x, y, z).free_symbols == {x}
assert Poly(x + sin(y), z).free_symbols == {x, y}
def test_PurePoly_free_symbols():
assert PurePoly(x**2 + 1).free_symbols == set([])
assert PurePoly(x**2 + y*z).free_symbols == set([])
assert PurePoly(x**2 + y*z, x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z)).free_symbols == set([])
assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z}
def test_Poly__eq__():
assert (Poly(x, x) == Poly(x, x)) is True
assert (Poly(x, x, domain=QQ) == Poly(x, x)) is True
assert (Poly(x, x) == Poly(x, x, domain=QQ)) is True
assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is True
assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is True
assert (Poly(x*y, x, y) == Poly(x, x)) is False
assert (Poly(x, x, y) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, y)) is False
assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False
assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False
f = Poly(x, x, domain=ZZ)
g = Poly(x, x, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
t0 = Symbol('t0')
f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]')
g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)')
assert (f == g) is True
def test_PurePoly__eq__():
assert (PurePoly(x, x) == PurePoly(x, x)) is True
assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True
assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True
assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x) == PurePoly(x, x, y)) is False
assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True
assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(x, x, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(y, y, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
def test_PurePoly_Poly():
assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True
assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True
def test_Poly_get_domain():
assert Poly(2*x).get_domain() == ZZ
assert Poly(2*x, domain='ZZ').get_domain() == ZZ
assert Poly(2*x, domain='QQ').get_domain() == QQ
assert Poly(x/2).get_domain() == QQ
raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ'))
assert Poly(x/2, domain='QQ').get_domain() == QQ
assert isinstance(Poly(0.2*x).get_domain(), RealField)
def test_Poly_set_domain():
assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ')
assert Poly(Rational(2, 10)*x + Rational(1, 10)).set_domain('RR') == Poly(0.2*x + 0.1)
assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(Rational(2, 10)*x + Rational(1, 10))
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ))
raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ))
raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y]))
def test_Poly_get_modulus():
assert Poly(x**2 + 1, modulus=2).get_modulus() == 2
raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus())
def test_Poly_set_modulus():
assert Poly(
x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7)
assert Poly(
x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2)
assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2)
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2))
def test_Poly_add_ground():
assert Poly(x + 1).add_ground(2) == Poly(x + 3)
def test_Poly_sub_ground():
assert Poly(x + 1).sub_ground(2) == Poly(x - 1)
def test_Poly_mul_ground():
assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2)
def test_Poly_quo_ground():
assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2)
assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1)
def test_Poly_exquo_ground():
assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2)
raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2))
def test_Poly_abs():
assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x)
def test_Poly_neg():
assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x)
def test_Poly_add():
assert Poly(0, x).add(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) + Poly(0, x) == Poly(0, x)
assert Poly(1, x).add(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y)
assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y)
assert Poly(1, x) + x == Poly(x + 1, x)
assert Poly(1, x) + sin(x) == 1 + sin(x)
assert Poly(x, x) + 1 == Poly(x + 1, x)
assert 1 + Poly(x, x) == Poly(x + 1, x)
def test_Poly_sub():
assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) - Poly(0, x) == Poly(0, x)
assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y)
assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y)
assert Poly(1, x) - x == Poly(1 - x, x)
assert Poly(1, x) - sin(x) == 1 - sin(x)
assert Poly(x, x) - 1 == Poly(x - 1, x)
assert 1 - Poly(x, x) == Poly(1 - x, x)
def test_Poly_mul():
assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) * Poly(0, x) == Poly(0, x)
assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x)
assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y)
assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y)
assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y)
assert Poly(1, x) * x == Poly(x, x)
assert Poly(1, x) * sin(x) == sin(x)
assert Poly(x, x) * 2 == Poly(2*x, x)
assert 2 * Poly(x, x) == Poly(2*x, x)
def test_issue_13079():
assert Poly(x)*x == Poly(x**2, x, domain='ZZ')
assert x*Poly(x) == Poly(x**2, x, domain='ZZ')
assert -2*Poly(x) == Poly(-2*x, x, domain='ZZ')
assert S(-2)*Poly(x) == Poly(-2*x, x, domain='ZZ')
assert Poly(x)*S(-2) == Poly(-2*x, x, domain='ZZ')
def test_Poly_sqr():
assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y)
def test_Poly_pow():
assert Poly(x, x).pow(10) == Poly(x**10, x)
assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x)
assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y)
assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y)
assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y)
assert Poly(x*y + 1, x, y)**(-1) == (x*y + 1)**(-1)
assert Poly(x*y + 1, x, y)**x == (x*y + 1)**x
def test_Poly_divmod():
f, g = Poly(x**2), Poly(x)
q, r = g, Poly(0, x)
assert divmod(f, g) == (q, r)
assert f // g == q
assert f % g == r
assert divmod(f, x) == (q, r)
assert f // x == q
assert f % x == r
q, r = Poly(0, x), Poly(2, x)
assert divmod(2, g) == (q, r)
assert 2 // g == q
assert 2 % g == r
assert Poly(x)/Poly(x) == 1
assert Poly(x**2)/Poly(x) == x
assert Poly(x)/Poly(x**2) == 1/x
def test_Poly_eq_ne():
assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True
assert (Poly(x + y, x) == Poly(x + y, x, y)) is False
assert (Poly(x + y, x, y) == Poly(x + y, x)) is False
assert (Poly(x + y, x) == Poly(x + y, x)) is True
assert (Poly(x + y, y) == Poly(x + y, y)) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, y) == x + y) is True
assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False
assert (Poly(x + y, x) != Poly(x + y, x, y)) is True
assert (Poly(x + y, x, y) != Poly(x + y, x)) is True
assert (Poly(x + y, x) != Poly(x + y, x)) is False
assert (Poly(x + y, y) != Poly(x + y, y)) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, y) != x + y) is False
assert (Poly(x, x) == sin(x)) is False
assert (Poly(x, x) != sin(x)) is True
def test_Poly_nonzero():
assert not bool(Poly(0, x)) is True
assert not bool(Poly(1, x)) is False
def test_Poly_properties():
assert Poly(0, x).is_zero is True
assert Poly(1, x).is_zero is False
assert Poly(1, x).is_one is True
assert Poly(2, x).is_one is False
assert Poly(x - 1, x).is_sqf is True
assert Poly((x - 1)**2, x).is_sqf is False
assert Poly(x - 1, x).is_monic is True
assert Poly(2*x - 1, x).is_monic is False
assert Poly(3*x + 2, x).is_primitive is True
assert Poly(4*x + 2, x).is_primitive is False
assert Poly(1, x).is_ground is True
assert Poly(x, x).is_ground is False
assert Poly(x + y + z + 1).is_linear is True
assert Poly(x*y*z + 1).is_linear is False
assert Poly(x*y + z + 1).is_quadratic is True
assert Poly(x*y*z + 1).is_quadratic is False
assert Poly(x*y).is_monomial is True
assert Poly(x*y + 1).is_monomial is False
assert Poly(x**2 + x*y).is_homogeneous is True
assert Poly(x**3 + x*y).is_homogeneous is False
assert Poly(x).is_univariate is True
assert Poly(x*y).is_univariate is False
assert Poly(x*y).is_multivariate is True
assert Poly(x).is_multivariate is False
assert Poly(
x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False
assert Poly(
x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True
def test_Poly_is_irreducible():
assert Poly(x**2 + x + 1).is_irreducible is True
assert Poly(x**2 + 2*x + 1).is_irreducible is False
assert Poly(7*x + 3, modulus=11).is_irreducible is True
assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False
def test_Poly_subs():
assert Poly(x + 1).subs(x, 0) == 1
assert Poly(x + 1).subs(x, x) == Poly(x + 1)
assert Poly(x + 1).subs(x, y) == Poly(y + 1)
assert Poly(x*y, x).subs(y, x) == x**2
assert Poly(x*y, x).subs(x, y) == y**2
def test_Poly_replace():
assert Poly(x + 1).replace(x) == Poly(x + 1)
assert Poly(x + 1).replace(y) == Poly(y + 1)
raises(PolynomialError, lambda: Poly(x + y).replace(z))
assert Poly(x + 1).replace(x, x) == Poly(x + 1)
assert Poly(x + 1).replace(x, y) == Poly(y + 1)
assert Poly(x + y).replace(x, x) == Poly(x + y)
assert Poly(x + y).replace(x, z) == Poly(z + y, z, y)
assert Poly(x + y).replace(y, y) == Poly(x + y)
assert Poly(x + y).replace(y, z) == Poly(x + z, x, z)
assert Poly(x + y).replace(z, t) == Poly(x + y)
raises(PolynomialError, lambda: Poly(x + y).replace(x, y))
assert Poly(x + y, x).replace(x, z) == Poly(z + y, z)
assert Poly(x + y, y).replace(y, z) == Poly(x + z, z)
raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y))
raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x))
def test_Poly_reorder():
raises(PolynomialError, lambda: Poly(x + y).reorder(x, z))
assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x)
def test_Poly_ltrim():
f = Poly(y**2 + y*z**2, x, y, z).ltrim(y)
assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z)
assert Poly(x*y - x, z, x, y).ltrim(1) == Poly(x*y - x, x, y)
raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y))
raises(PolynomialError, lambda: Poly(x*y - x, x, y).ltrim(-1))
def test_Poly_has_only_gens():
assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True
assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False
raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t))
def test_Poly_to_ring():
assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ')
assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ')
raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring())
raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring())
def test_Poly_to_field():
assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ')
assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3)
assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0)
def test_Poly_to_exact():
assert Poly(2*x).to_exact() == Poly(2*x)
assert Poly(x/2).to_exact() == Poly(x/2)
assert Poly(0.1*x).to_exact() == Poly(x/10)
def test_Poly_retract():
f = Poly(x**2 + 1, x, domain=QQ[y])
assert f.retract() == Poly(x**2 + 1, x, domain='ZZ')
assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ')
assert Poly(0, x, y).retract() == Poly(0, x, y)
def test_Poly_slice():
f = Poly(x**3 + 2*x**2 + 3*x + 4)
assert f.slice(0, 0) == Poly(0, x)
assert f.slice(0, 1) == Poly(4, x)
assert f.slice(0, 2) == Poly(3*x + 4, x)
assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 0) == Poly(0, x)
assert f.slice(x, 0, 1) == Poly(4, x)
assert f.slice(x, 0, 2) == Poly(3*x + 4, x)
assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
def test_Poly_coeffs():
assert Poly(0, x).coeffs() == [0]
assert Poly(1, x).coeffs() == [1]
assert Poly(2*x + 1, x).coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2]
def test_Poly_monoms():
assert Poly(0, x).monoms() == [(0,)]
assert Poly(1, x).monoms() == [(0,)]
assert Poly(2*x + 1, x).monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)]
def test_Poly_terms():
assert Poly(0, x).terms() == [((0,), 0)]
assert Poly(1, x).terms() == [((0,), 1)]
assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
def test_Poly_all_coeffs():
assert Poly(0, x).all_coeffs() == [0]
assert Poly(1, x).all_coeffs() == [1]
assert Poly(2*x + 1, x).all_coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1]
def test_Poly_all_monoms():
assert Poly(0, x).all_monoms() == [(0,)]
assert Poly(1, x).all_monoms() == [(0,)]
assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)]
def test_Poly_all_terms():
assert Poly(0, x).all_terms() == [((0,), 0)]
assert Poly(1, x).all_terms() == [((0,), 1)]
assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \
[((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \
[((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)]
def test_Poly_termwise():
f = Poly(x**2 + 20*x + 400)
g = Poly(x**2 + 2*x + 4)
def func(monom, coeff):
(k,) = monom
return coeff//10**(2 - k)
assert f.termwise(func) == g
def func(monom, coeff):
(k,) = monom
return (k,), coeff//10**(2 - k)
assert f.termwise(func) == g
def test_Poly_length():
assert Poly(0, x).length() == 0
assert Poly(1, x).length() == 1
assert Poly(x, x).length() == 1
assert Poly(x + 1, x).length() == 2
assert Poly(x**2 + 1, x).length() == 2
assert Poly(x**2 + x + 1, x).length() == 3
def test_Poly_as_dict():
assert Poly(0, x).as_dict() == {}
assert Poly(0, x, y, z).as_dict() == {}
assert Poly(1, x).as_dict() == {(0,): 1}
assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1}
assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3}
assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3}
assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3,
(1, 1, 0): 4, (1, 0, 1): 5}
def test_Poly_as_expr():
assert Poly(0, x).as_expr() == 0
assert Poly(0, x, y, z).as_expr() == 0
assert Poly(1, x).as_expr() == 1
assert Poly(1, x, y, z).as_expr() == 1
assert Poly(x**2 + 3, x).as_expr() == x**2 + 3
assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3
assert Poly(
3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z
f = Poly(x**2 + 2*x*y**2 - y, x, y)
assert f.as_expr() == -y + x**2 + 2*x*y**2
assert f.as_expr({x: 5}) == 25 - y + 10*y**2
assert f.as_expr({y: 6}) == -6 + 72*x + x**2
assert f.as_expr({x: 5, y: 6}) == 379
assert f.as_expr(5, 6) == 379
raises(GeneratorsError, lambda: f.as_expr({z: 7}))
def test_Poly_lift():
assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \
Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521,
x, domain='QQ')
def test_Poly_deflate():
assert Poly(0, x).deflate() == ((1,), Poly(0, x))
assert Poly(1, x).deflate() == ((1,), Poly(1, x))
assert Poly(x, x).deflate() == ((1,), Poly(x, x))
assert Poly(x**2, x).deflate() == ((2,), Poly(x, x))
assert Poly(x**17, x).deflate() == ((17,), Poly(x, x))
assert Poly(
x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z))
def test_Poly_inject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x)
assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x)
def test_Poly_eject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
ex = x + y + z + t + w
g = Poly(ex, x, y, z, t, w)
assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]')
assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]')
assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]')
assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]')
assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[w, t]')
assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[w, t, z]')
raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y))
raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y))
def test_Poly_exclude():
assert Poly(x, x, y).exclude() == Poly(x, x)
assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y)
assert Poly(1, x, y).exclude() == Poly(1, x, y)
def test_Poly__gen_to_level():
assert Poly(1, x, y)._gen_to_level(-2) == 0
assert Poly(1, x, y)._gen_to_level(-1) == 1
assert Poly(1, x, y)._gen_to_level( 0) == 0
assert Poly(1, x, y)._gen_to_level( 1) == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2))
assert Poly(1, x, y)._gen_to_level(x) == 0
assert Poly(1, x, y)._gen_to_level(y) == 1
assert Poly(1, x, y)._gen_to_level('x') == 0
assert Poly(1, x, y)._gen_to_level('y') == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z'))
def test_Poly_degree():
assert Poly(0, x).degree() is -oo
assert Poly(1, x).degree() == 0
assert Poly(x, x).degree() == 1
assert Poly(0, x).degree(gen=0) is -oo
assert Poly(1, x).degree(gen=0) == 0
assert Poly(x, x).degree(gen=0) == 1
assert Poly(0, x).degree(gen=x) is -oo
assert Poly(1, x).degree(gen=x) == 0
assert Poly(x, x).degree(gen=x) == 1
assert Poly(0, x).degree(gen='x') is -oo
assert Poly(1, x).degree(gen='x') == 0
assert Poly(x, x).degree(gen='x') == 1
raises(PolynomialError, lambda: Poly(1, x).degree(gen=1))
raises(PolynomialError, lambda: Poly(1, x).degree(gen=y))
raises(PolynomialError, lambda: Poly(1, x).degree(gen='y'))
assert Poly(1, x, y).degree() == 0
assert Poly(2*y, x, y).degree() == 0
assert Poly(x*y, x, y).degree() == 1
assert Poly(1, x, y).degree(gen=x) == 0
assert Poly(2*y, x, y).degree(gen=x) == 0
assert Poly(x*y, x, y).degree(gen=x) == 1
assert Poly(1, x, y).degree(gen=y) == 0
assert Poly(2*y, x, y).degree(gen=y) == 1
assert Poly(x*y, x, y).degree(gen=y) == 1
assert degree(0, x) is -oo
assert degree(1, x) == 0
assert degree(x, x) == 1
assert degree(x*y**2, x) == 1
assert degree(x*y**2, y) == 2
assert degree(x*y**2, z) == 0
assert degree(pi) == 1
raises(TypeError, lambda: degree(y**2 + x**3))
raises(TypeError, lambda: degree(y**2 + x**3, 1))
raises(PolynomialError, lambda: degree(x, 1.1))
raises(PolynomialError, lambda: degree(x**2/(x**3 + 1), x))
assert degree(Poly(0,x),z) is -oo
assert degree(Poly(1,x),z) == 0
assert degree(Poly(x**2+y**3,y)) == 3
assert degree(Poly(y**2 + x**3, y, x), 1) == 3
assert degree(Poly(y**2 + x**3, x), z) == 0
assert degree(Poly(y**2 + x**3 + z**4, x), z) == 4
def test_Poly_degree_list():
assert Poly(0, x).degree_list() == (-oo,)
assert Poly(0, x, y).degree_list() == (-oo, -oo)
assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo)
assert Poly(1, x).degree_list() == (0,)
assert Poly(1, x, y).degree_list() == (0, 0)
assert Poly(1, x, y, z).degree_list() == (0, 0, 0)
assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2)
assert degree_list(1, x) == (0,)
assert degree_list(x, x) == (1,)
assert degree_list(x*y**2) == (1, 2)
raises(ComputationFailed, lambda: degree_list(1))
def test_Poly_total_degree():
assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5
assert Poly(x**2 + z**3).total_degree() == 3
assert Poly(x*y*z + z**4).total_degree() == 4
assert Poly(x**3 + x + 1).total_degree() == 3
assert total_degree(x*y + z**3) == 3
assert total_degree(x*y + z**3, x, y) == 2
assert total_degree(1) == 0
assert total_degree(Poly(y**2 + x**3 + z**4)) == 4
assert total_degree(Poly(y**2 + x**3 + z**4, x)) == 3
assert total_degree(Poly(y**2 + x**3 + z**4, x), z) == 4
assert total_degree(Poly(x**9 + x*z*y + x**3*z**2 + z**7,x), z) == 7
def test_Poly_homogenize():
assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z)
assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z)
assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2)
def test_Poly_homogeneous_order():
assert Poly(0, x, y).homogeneous_order() is -oo
assert Poly(1, x, y).homogeneous_order() == 0
assert Poly(x, x, y).homogeneous_order() == 1
assert Poly(x*y, x, y).homogeneous_order() == 2
assert Poly(x + 1, x, y).homogeneous_order() is None
assert Poly(x*y + x, x, y).homogeneous_order() is None
assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5
assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None
def test_Poly_LC():
assert Poly(0, x).LC() == 0
assert Poly(1, x).LC() == 1
assert Poly(2*x**2 + x, x).LC() == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1
assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2
assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1
def test_Poly_TC():
assert Poly(0, x).TC() == 0
assert Poly(1, x).TC() == 1
assert Poly(2*x**2 + x, x).TC() == 0
def test_Poly_EC():
assert Poly(0, x).EC() == 0
assert Poly(1, x).EC() == 1
assert Poly(2*x**2 + x, x).EC() == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2
def test_Poly_coeff():
assert Poly(0, x).coeff_monomial(1) == 0
assert Poly(0, x).coeff_monomial(x) == 0
assert Poly(1, x).coeff_monomial(1) == 1
assert Poly(1, x).coeff_monomial(x) == 0
assert Poly(x**8, x).coeff_monomial(1) == 0
assert Poly(x**8, x).coeff_monomial(x**7) == 0
assert Poly(x**8, x).coeff_monomial(x**8) == 1
assert Poly(x**8, x).coeff_monomial(x**9) == 0
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3
p = Poly(24*x*y*exp(8) + 23*x, x, y)
assert p.coeff_monomial(x) == 23
assert p.coeff_monomial(y) == 0
assert p.coeff_monomial(x*y) == 24*exp(8)
assert p.as_expr().coeff(x) == 24*y*exp(8) + 23
raises(NotImplementedError, lambda: p.coeff(x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y))
def test_Poly_nth():
assert Poly(0, x).nth(0) == 0
assert Poly(0, x).nth(1) == 0
assert Poly(1, x).nth(0) == 1
assert Poly(1, x).nth(1) == 0
assert Poly(x**8, x).nth(0) == 0
assert Poly(x**8, x).nth(7) == 0
assert Poly(x**8, x).nth(8) == 1
assert Poly(x**8, x).nth(9) == 0
assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1
assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3
raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1))
def test_Poly_LM():
assert Poly(0, x).LM() == (0,)
assert Poly(1, x).LM() == (0,)
assert Poly(2*x**2 + x, x).LM() == (2,)
assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3)
assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7)
assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3
assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_LM_custom_order():
f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1)
rev_lex = lambda monom: tuple(reversed(monom))
assert f.LM(order='lex') == (2, 3, 1)
assert f.LM(order=rev_lex) == (2, 1, 3)
def test_Poly_EM():
assert Poly(0, x).EM() == (0,)
assert Poly(1, x).EM() == (0,)
assert Poly(2*x**2 + x, x).EM() == (1,)
assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7)
assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3)
def test_Poly_LT():
assert Poly(0, x).LT() == ((0,), 0)
assert Poly(1, x).LT() == ((0,), 1)
assert Poly(2*x**2 + x, x).LT() == ((2,), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1)
assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3
assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_ET():
assert Poly(0, x).ET() == ((0,), 0)
assert Poly(1, x).ET() == ((0,), 1)
assert Poly(2*x**2 + x, x).ET() == ((1,), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2)
def test_Poly_max_norm():
assert Poly(-1, x).max_norm() == 1
assert Poly( 0, x).max_norm() == 0
assert Poly( 1, x).max_norm() == 1
def test_Poly_l1_norm():
assert Poly(-1, x).l1_norm() == 1
assert Poly( 0, x).l1_norm() == 0
assert Poly( 1, x).l1_norm() == 1
def test_Poly_clear_denoms():
coeff, poly = Poly(x + 2, x).clear_denoms()
assert coeff == 1 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/2 + 1, x).clear_denoms()
assert coeff == 2 and poly == Poly(
x + 2, x, domain='QQ') and poly.get_domain() == QQ
coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True)
assert coeff == 2 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True)
assert coeff == y and poly == Poly(
x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y]
coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms()
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
coeff, poly = Poly(
x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True)
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
def test_Poly_rat_clear_denoms():
f = Poly(x**2/y + 1, x)
g = Poly(x**3 + y, x)
assert f.rat_clear_denoms(g) == \
(Poly(x**2 + y, x), Poly(y*x**3 + y**2, x))
f = f.set_domain(EX)
g = g.set_domain(EX)
assert f.rat_clear_denoms(g) == (f, g)
def test_Poly_integrate():
assert Poly(x + 1).integrate() == Poly(x**2/2 + x)
assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x)
assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x)
assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x)
assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y)
assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y)
assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y)
def test_Poly_diff():
assert Poly(x**2 + x).diff() == Poly(2*x + 1)
assert Poly(x**2 + x).diff(x) == Poly(2*x + 1)
assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1)
assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y)
assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x)
assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1)
assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1)
def test_issue_9585():
assert diff(Poly(x**2 + x)) == Poly(2*x + 1)
assert diff(Poly(x**2 + x), x, evaluate=False) == \
Derivative(Poly(x**2 + x), x)
assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1)
def test_Poly_eval():
assert Poly(0, x).eval(7) == 0
assert Poly(1, x).eval(7) == 1
assert Poly(x, x).eval(7) == 7
assert Poly(0, x).eval(0, 7) == 0
assert Poly(1, x).eval(0, 7) == 1
assert Poly(x, x).eval(0, 7) == 7
assert Poly(0, x).eval(x, 7) == 0
assert Poly(1, x).eval(x, 7) == 1
assert Poly(x, x).eval(x, 7) == 7
assert Poly(0, x).eval('x', 7) == 0
assert Poly(1, x).eval('x', 7) == 1
assert Poly(x, x).eval('x', 7) == 7
raises(PolynomialError, lambda: Poly(1, x).eval(1, 7))
raises(PolynomialError, lambda: Poly(1, x).eval(y, 7))
raises(PolynomialError, lambda: Poly(1, x).eval('y', 7))
assert Poly(123, x, y).eval(7) == Poly(123, y)
assert Poly(2*y, x, y).eval(7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(7) == Poly(7*y, y)
assert Poly(123, x, y).eval(x, 7) == Poly(123, y)
assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y)
assert Poly(123, x, y).eval(y, 7) == Poly(123, x)
assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x)
assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x)
assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y)
assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x)
assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49
assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48
assert Poly(x*y + y, x, y).eval((6, 7)) == 49
assert Poly(x*y + y, x, y).eval([6, 7]) == 49
assert Poly(x + 1, domain='ZZ').eval(S.Half) == Rational(3, 2)
assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1
raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8)))
raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S.Half, auto=False))
# issue 6344
alpha = Symbol('alpha')
result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1)
f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]')
assert f.eval((z + 1)/(z - 1)) == result
g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]')
assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)')
def test_Poly___call__():
f = Poly(2*x*y + 3*x + y + 2*z)
assert f(2) == Poly(5*y + 2*z + 6)
assert f(2, 5) == Poly(2*z + 31)
assert f(2, 5, 7) == 45
def test_parallel_poly_from_expr():
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr([Poly(
x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(
x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([x - 1, Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(x - 1, x), Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \
[Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')]
raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1]))
def test_pdiv():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.pdiv(G) == (Q, R)
assert F.prem(G) == R
assert F.pquo(G) == Q
assert F.pexquo(G) == Q
assert pdiv(f, g) == (q, r)
assert prem(f, g) == r
assert pquo(f, g) == q
assert pexquo(f, g) == q
assert pdiv(f, g, x, y) == (q, r)
assert prem(f, g, x, y) == r
assert pquo(f, g, x, y) == q
assert pexquo(f, g, x, y) == q
assert pdiv(f, g, (x, y)) == (q, r)
assert prem(f, g, (x, y)) == r
assert pquo(f, g, (x, y)) == q
assert pexquo(f, g, (x, y)) == q
assert pdiv(F, G) == (Q, R)
assert prem(F, G) == R
assert pquo(F, G) == Q
assert pexquo(F, G) == Q
assert pdiv(f, g, polys=True) == (Q, R)
assert prem(f, g, polys=True) == R
assert pquo(f, g, polys=True) == Q
assert pexquo(f, g, polys=True) == Q
assert pdiv(F, G, polys=False) == (q, r)
assert prem(F, G, polys=False) == r
assert pquo(F, G, polys=False) == q
assert pexquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: pdiv(4, 2))
raises(ComputationFailed, lambda: prem(4, 2))
raises(ComputationFailed, lambda: pquo(4, 2))
raises(ComputationFailed, lambda: pexquo(4, 2))
def test_div():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.div(G) == (Q, R)
assert F.rem(G) == R
assert F.quo(G) == Q
assert F.exquo(G) == Q
assert div(f, g) == (q, r)
assert rem(f, g) == r
assert quo(f, g) == q
assert exquo(f, g) == q
assert div(f, g, x, y) == (q, r)
assert rem(f, g, x, y) == r
assert quo(f, g, x, y) == q
assert exquo(f, g, x, y) == q
assert div(f, g, (x, y)) == (q, r)
assert rem(f, g, (x, y)) == r
assert quo(f, g, (x, y)) == q
assert exquo(f, g, (x, y)) == q
assert div(F, G) == (Q, R)
assert rem(F, G) == R
assert quo(F, G) == Q
assert exquo(F, G) == Q
assert div(f, g, polys=True) == (Q, R)
assert rem(f, g, polys=True) == R
assert quo(f, g, polys=True) == Q
assert exquo(f, g, polys=True) == Q
assert div(F, G, polys=False) == (q, r)
assert rem(F, G, polys=False) == r
assert quo(F, G, polys=False) == q
assert exquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: div(4, 2))
raises(ComputationFailed, lambda: rem(4, 2))
raises(ComputationFailed, lambda: quo(4, 2))
raises(ComputationFailed, lambda: exquo(4, 2))
f, g = x**2 + 1, 2*x - 4
qz, rz = 0, x**2 + 1
qq, rq = x/2 + 1, 5
assert div(f, g) == (qq, rq)
assert div(f, g, auto=True) == (qq, rq)
assert div(f, g, auto=False) == (qz, rz)
assert div(f, g, domain=ZZ) == (qz, rz)
assert div(f, g, domain=QQ) == (qq, rq)
assert div(f, g, domain=ZZ, auto=True) == (qq, rq)
assert div(f, g, domain=ZZ, auto=False) == (qz, rz)
assert div(f, g, domain=QQ, auto=True) == (qq, rq)
assert div(f, g, domain=QQ, auto=False) == (qq, rq)
assert rem(f, g) == rq
assert rem(f, g, auto=True) == rq
assert rem(f, g, auto=False) == rz
assert rem(f, g, domain=ZZ) == rz
assert rem(f, g, domain=QQ) == rq
assert rem(f, g, domain=ZZ, auto=True) == rq
assert rem(f, g, domain=ZZ, auto=False) == rz
assert rem(f, g, domain=QQ, auto=True) == rq
assert rem(f, g, domain=QQ, auto=False) == rq
assert quo(f, g) == qq
assert quo(f, g, auto=True) == qq
assert quo(f, g, auto=False) == qz
assert quo(f, g, domain=ZZ) == qz
assert quo(f, g, domain=QQ) == qq
assert quo(f, g, domain=ZZ, auto=True) == qq
assert quo(f, g, domain=ZZ, auto=False) == qz
assert quo(f, g, domain=QQ, auto=True) == qq
assert quo(f, g, domain=QQ, auto=False) == qq
f, g, q = x**2, 2*x, x/2
assert exquo(f, g) == q
assert exquo(f, g, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False))
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ))
assert exquo(f, g, domain=QQ) == q
assert exquo(f, g, domain=ZZ, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False))
assert exquo(f, g, domain=QQ, auto=True) == q
assert exquo(f, g, domain=QQ, auto=False) == q
f, g = Poly(x**2), Poly(x)
q, r = f.div(g)
assert q.get_domain().is_ZZ and r.get_domain().is_ZZ
r = f.rem(g)
assert r.get_domain().is_ZZ
q = f.quo(g)
assert q.get_domain().is_ZZ
q = f.exquo(g)
assert q.get_domain().is_ZZ
f, g = Poly(x+y, x), Poly(2*x+y, x)
q, r = f.div(g)
assert q.get_domain().is_Frac and r.get_domain().is_Frac
def test_issue_7864():
q, r = div(a, .408248290463863*a)
assert abs(q - 2.44948974278318) < 1e-14
assert r == 0
def test_gcdex():
f, g = 2*x, x**2 - 16
s, t, h = x/32, Rational(-1, 16), 1
F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ]
assert F.half_gcdex(G) == (S, H)
assert F.gcdex(G) == (S, T, H)
assert F.invert(G) == S
assert half_gcdex(f, g) == (s, h)
assert gcdex(f, g) == (s, t, h)
assert invert(f, g) == s
assert half_gcdex(f, g, x) == (s, h)
assert gcdex(f, g, x) == (s, t, h)
assert invert(f, g, x) == s
assert half_gcdex(f, g, (x,)) == (s, h)
assert gcdex(f, g, (x,)) == (s, t, h)
assert invert(f, g, (x,)) == s
assert half_gcdex(F, G) == (S, H)
assert gcdex(F, G) == (S, T, H)
assert invert(F, G) == S
assert half_gcdex(f, g, polys=True) == (S, H)
assert gcdex(f, g, polys=True) == (S, T, H)
assert invert(f, g, polys=True) == S
assert half_gcdex(F, G, polys=False) == (s, h)
assert gcdex(F, G, polys=False) == (s, t, h)
assert invert(F, G, polys=False) == s
assert half_gcdex(100, 2004) == (-20, 4)
assert gcdex(100, 2004) == (-20, 1, 4)
assert invert(3, 7) == 5
raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False))
def test_revert():
f = Poly(1 - x**2/2 + x**4/24 - x**6/720)
g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1)
assert f.revert(8) == g
def test_subresultants():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.subresultants(G) == [F, G, H]
assert subresultants(f, g) == [f, g, h]
assert subresultants(f, g, x) == [f, g, h]
assert subresultants(f, g, (x,)) == [f, g, h]
assert subresultants(F, G) == [F, G, H]
assert subresultants(f, g, polys=True) == [F, G, H]
assert subresultants(F, G, polys=False) == [f, g, h]
raises(ComputationFailed, lambda: subresultants(4, 2))
def test_resultant():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 0
F, G = Poly(f), Poly(g)
assert F.resultant(G) == h
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == h
assert resultant(f, g, polys=True) == h
assert resultant(F, G, polys=False) == h
assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2])
f, g, h = x - a, x - b, a - b
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.resultant(G) == H
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == H
assert resultant(f, g, polys=True) == H
assert resultant(F, G, polys=False) == h
raises(ComputationFailed, lambda: resultant(4, 2))
def test_discriminant():
f, g = x**3 + 3*x**2 + 9*x - 13, -11664
F = Poly(f)
assert F.discriminant() == g
assert discriminant(f) == g
assert discriminant(f, x) == g
assert discriminant(f, (x,)) == g
assert discriminant(F) == g
assert discriminant(f, polys=True) == g
assert discriminant(F, polys=False) == g
f, g = a*x**2 + b*x + c, b**2 - 4*a*c
F, G = Poly(f), Poly(g)
assert F.discriminant() == G
assert discriminant(f) == g
assert discriminant(f, x, a, b, c) == g
assert discriminant(f, (x, a, b, c)) == g
assert discriminant(F) == G
assert discriminant(f, polys=True) == G
assert discriminant(F, polys=False) == g
raises(ComputationFailed, lambda: discriminant(4))
def test_dispersion():
# We test only the API here. For more mathematical
# tests see the dedicated test file.
fp = poly((x + 1)*(x + 2), x)
assert sorted(fp.dispersionset()) == [0, 1]
assert fp.dispersion() == 1
fp = poly(x**4 - 3*x**2 + 1, x)
gp = fp.shift(-3)
assert sorted(fp.dispersionset(gp)) == [2, 3, 4]
assert fp.dispersion(gp) == 4
def test_gcd_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert gcd_list(F) == x - 1
assert gcd_list(F, polys=True) == Poly(x - 1)
assert gcd_list([]) == 0
assert gcd_list([1, 2]) == 1
assert gcd_list([4, 6, 8]) == 2
assert gcd_list([x*(y + 42) - x*y - x*42]) == 0
gcd = gcd_list([], x)
assert gcd.is_Number and gcd is S.Zero
gcd = gcd_list([], x, polys=True)
assert gcd.is_Poly and gcd.is_zero
raises(ComputationFailed, lambda: gcd_list([], polys=True))
def test_lcm_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2
assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2)
assert lcm_list([]) == 1
assert lcm_list([1, 2]) == 2
assert lcm_list([4, 6, 8]) == 24
assert lcm_list([x*(y + 42) - x*y - x*42]) == 0
lcm = lcm_list([], x)
assert lcm.is_Number and lcm is S.One
lcm = lcm_list([], x, polys=True)
assert lcm.is_Poly and lcm.is_one
raises(ComputationFailed, lambda: lcm_list([], polys=True))
def test_gcd():
f, g = x**3 - 1, x**2 - 1
s, t = x**2 + x + 1, x + 1
h, r = x - 1, x**4 + x**3 - x - 1
F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ]
assert F.cofactors(G) == (H, S, T)
assert F.gcd(G) == H
assert F.lcm(G) == R
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == r
assert cofactors(f, g, x) == (h, s, t)
assert gcd(f, g, x) == h
assert lcm(f, g, x) == r
assert cofactors(f, g, (x,)) == (h, s, t)
assert gcd(f, g, (x,)) == h
assert lcm(f, g, (x,)) == r
assert cofactors(F, G) == (H, S, T)
assert gcd(F, G) == H
assert lcm(F, G) == R
assert cofactors(f, g, polys=True) == (H, S, T)
assert gcd(f, g, polys=True) == H
assert lcm(f, g, polys=True) == R
assert cofactors(F, G, polys=False) == (h, s, t)
assert gcd(F, G, polys=False) == h
assert lcm(F, G, polys=False) == r
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
assert cofactors(8, 6) == (2, 4, 3)
assert gcd(8, 6) == 2
assert lcm(8, 6) == 24
f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4
l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4
h, s, t = x - 4, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11) == (h, s, t)
assert gcd(f, g, modulus=11) == h
assert lcm(f, g, modulus=11) == l
f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7
l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7
h, s, t = x + 7, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t)
assert gcd(f, g, modulus=11, symmetric=False) == h
assert lcm(f, g, modulus=11, symmetric=False) == l
raises(TypeError, lambda: gcd(x))
raises(TypeError, lambda: lcm(x))
def test_gcd_numbers_vs_polys():
assert isinstance(gcd(3, 9), Integer)
assert isinstance(gcd(3*x, 9), Integer)
assert gcd(3, 9) == 3
assert gcd(3*x, 9) == 3
assert isinstance(gcd(Rational(3, 2), Rational(9, 4)), Rational)
assert isinstance(gcd(Rational(3, 2)*x, Rational(9, 4)), Rational)
assert gcd(Rational(3, 2), Rational(9, 4)) == Rational(3, 4)
assert gcd(Rational(3, 2)*x, Rational(9, 4)) == 1
assert isinstance(gcd(3.0, 9.0), Float)
assert isinstance(gcd(3.0*x, 9.0), Float)
assert gcd(3.0, 9.0) == 1.0
assert gcd(3.0*x, 9.0) == 1.0
def test_terms_gcd():
assert terms_gcd(1) == 1
assert terms_gcd(1, x) == 1
assert terms_gcd(x - 1) == x - 1
assert terms_gcd(-x - 1) == -x - 1
assert terms_gcd(2*x + 3) == 2*x + 3
assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False)
assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2)
assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2)
assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2)
assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == x*y*Rational(2, 15)*(5*x**2 + 6*y**2)
assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2)
assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3)
assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \
(3*x + 3)*(x*y + x)
assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \
3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1)
assert terms_gcd(sin(x + x*y), deep=True) == \
sin(x*(y + 1))
eq = Eq(2*x, 2*y + 2*z*y)
assert terms_gcd(eq) == eq
assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1))
def test_trunc():
f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f = Poly(x**2 + 2*x + 3, modulus=5)
assert f.trunc(2) == Poly(x**2 + 1, modulus=5)
def test_monic():
f, g = 2*x - 1, x - S.Half
F, G = Poly(f, domain='QQ'), Poly(g)
assert F.monic() == G
assert monic(f) == g
assert monic(f, x) == g
assert monic(f, (x,)) == g
assert monic(F) == G
assert monic(f, polys=True) == G
assert monic(F, polys=False) == g
raises(ComputationFailed, lambda: monic(4))
assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2
raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False))
assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0
assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2
def test_content():
f, F = 4*x + 2, Poly(4*x + 2)
assert F.content() == 2
assert content(f) == 2
raises(ComputationFailed, lambda: content(4))
f = Poly(2*x, modulus=3)
assert f.content() == 1
def test_primitive():
f, g = 4*x + 2, 2*x + 1
F, G = Poly(f), Poly(g)
assert F.primitive() == (2, G)
assert primitive(f) == (2, g)
assert primitive(f, x) == (2, g)
assert primitive(f, (x,)) == (2, g)
assert primitive(F) == (2, G)
assert primitive(f, polys=True) == (2, G)
assert primitive(F, polys=False) == (2, g)
raises(ComputationFailed, lambda: primitive(4))
f = Poly(2*x, modulus=3)
g = Poly(2.0*x, domain=RR)
assert f.primitive() == (1, f)
assert g.primitive() == (1.0, g)
assert primitive(S('-3*x/4 + y + 11/8')) == \
S('(1/8, -6*x + 8*y + 11)')
def test_compose():
f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9
g = x**4 - 2*x + 9
h = x**3 + 5*x
F, G, H = map(Poly, (f, g, h))
assert G.compose(H) == F
assert compose(g, h) == f
assert compose(g, h, x) == f
assert compose(g, h, (x,)) == f
assert compose(G, H) == F
assert compose(g, h, polys=True) == F
assert compose(G, H, polys=False) == f
assert F.decompose() == [G, H]
assert decompose(f) == [g, h]
assert decompose(f, x) == [g, h]
assert decompose(f, (x,)) == [g, h]
assert decompose(F) == [G, H]
assert decompose(f, polys=True) == [G, H]
assert decompose(F, polys=False) == [g, h]
raises(ComputationFailed, lambda: compose(4, 2))
raises(ComputationFailed, lambda: decompose(4))
assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y
assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y
def test_shift():
assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x)
def test_transform():
# Also test that 3-way unification is done correctly
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(4, x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(3*x**2/2 + Rational(5, 2), x) == \
cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S.Half), Poly(x - 1)) == \
Poly(Rational(9, 4), x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S.Half)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S.Half)) == \
Poly(Rational(9, 4), x) == \
cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S.Half)))
# Unify ZZ, QQ, and RR
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S.Half)) == \
Poly(Rational(9, 4), x) == \
cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S.Half)))
raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1)))
def test_sturm():
f, F = x, Poly(x, domain='QQ')
g, G = 1, Poly(1, x, domain='QQ')
assert F.sturm() == [F, G]
assert sturm(f) == [f, g]
assert sturm(f, x) == [f, g]
assert sturm(f, (x,)) == [f, g]
assert sturm(F) == [F, G]
assert sturm(f, polys=True) == [F, G]
assert sturm(F, polys=False) == [f, g]
raises(ComputationFailed, lambda: sturm(4))
raises(DomainError, lambda: sturm(f, auto=False))
f = Poly(S(1024)/(15625*pi**8)*x**5
- S(4096)/(625*pi**8)*x**4
+ S(32)/(15625*pi**4)*x**3
- S(128)/(625*pi**4)*x**2
+ Rational(1, 62500)*x
- Rational(1, 625), x, domain='ZZ(pi)')
assert sturm(f) == \
[Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'),
Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'),
Poly((Rational(20000, 9) - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'),
Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')]
def test_gff():
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)]
assert gff_list(f) == [(x, 1), (x + 2, 4)]
raises(NotImplementedError, lambda: gff(f))
f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5)
assert Poly(f).gff_list() == [(
Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)]
assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
raises(NotImplementedError, lambda: gff(f))
def test_norm():
a, b = sqrt(2), sqrt(3)
f = Poly(a*x + b*y, x, y, extension=(a, b))
assert f.norm() == Poly(4*x**4 - 12*x**2*y**2 + 9*y**4, x, y, domain='QQ')
def test_sqf_norm():
assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \
(1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1)
assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \
(1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1)
assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
def test_sqf():
f = x**5 - x**3 - x**2 + 1
g = x**3 + 2*x**2 + 2*x + 1
h = x - 1
p = x**4 + x**3 - x - 1
F, G, H, P = map(Poly, (f, g, h, p))
assert F.sqf_part() == P
assert sqf_part(f) == p
assert sqf_part(f, x) == p
assert sqf_part(f, (x,)) == p
assert sqf_part(F) == P
assert sqf_part(f, polys=True) == P
assert sqf_part(F, polys=False) == p
assert F.sqf_list() == (1, [(G, 1), (H, 2)])
assert sqf_list(f) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, x) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)])
assert sqf_list(F) == (1, [(G, 1), (H, 2)])
assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)])
assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)])
assert F.sqf_list_include() == [(G, 1), (H, 2)]
raises(ComputationFailed, lambda: sqf_part(4))
assert sqf(1) == 1
assert sqf_list(1) == (1, [])
assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert sqf(f) == g*h**2
assert sqf(f, x) == g*h**2
assert sqf(f, (x,)) == g*h**2
d = x**2 + y**2
assert sqf(f/d) == (g*h**2)/d
assert sqf(f/d, x) == (g*h**2)/d
assert sqf(f/d, (x,)) == (g*h**2)/d
assert sqf(x - 1) == x - 1
assert sqf(-x - 1) == -x - 1
assert sqf(x - 1) == x - 1
assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert sqf((6*x - 10)/(3*x - 6)) == Rational(2, 3)*((3*x - 5)/(x - 2))
assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2
f = 3 + x - x*(1 + x) + x**2
assert sqf(f) == 3
f = (x**2 + 2*x + 1)**20000000000
assert sqf(f) == (x + 1)**40000000000
assert sqf_list(f) == (1, [(x + 1, 40000000000)])
def test_factor():
f = x**5 - x**3 - x**2 + 1
u = x + 1
v = x - 1
w = x**2 + x + 1
F, U, V, W = map(Poly, (f, u, v, w))
assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)])
assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)]
assert factor_list(1) == (1, [])
assert factor_list(6) == (6, [])
assert factor_list(sqrt(3), x) == (sqrt(3), [])
assert factor_list((-1)**x, x) == (1, [(-1, x)])
assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)])
assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)])
assert factor(6) == 6 and factor(6).is_Integer
assert factor_list(3*x) == (3, [(x, 1)])
assert factor_list(3*x**2) == (3, [(x, 2)])
assert factor(3*x) == 3*x
assert factor(3*x**2) == 3*x**2
assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert factor(f) == u*v**2*w
assert factor(f, x) == u*v**2*w
assert factor(f, (x,)) == u*v**2*w
g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1
assert factor(f/g) == (u*v**2*w)/(p*q)
assert factor(f/g, x) == (u*v**2*w)/(p*q)
assert factor(f/g, (x,)) == (u*v**2*w)/(p*q)
p = Symbol('p', positive=True)
i = Symbol('i', integer=True)
r = Symbol('r', real=True)
assert factor(sqrt(x*y)).is_Pow is True
assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1))
assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1)
assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i
assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i
assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t
assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t
f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3))
g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1)
assert factor(f) == g
assert factor(g) == g
g = (x - 1)**5*(r**2 + 1)
f = sqrt(expand(g))
assert factor(f) == sqrt(g)
f = Poly(sin(1)*x + 1, x, domain=EX)
assert f.factor_list() == (1, [(f, 1)])
f = x**4 + 1
assert factor(f) == f
assert factor(f, extension=I) == (x**2 - I)*(x**2 + I)
assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I)
assert factor(
f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1)
f = x**2 + 2*sqrt(2)*x + 2
assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2
assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6
assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \
(x + sqrt(2)*y)*(x - sqrt(2)*y)
assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \
2*((x + sqrt(2)*y)*(x - sqrt(2)*y))
assert factor(x - 1) == x - 1
assert factor(-x - 1) == -x - 1
assert factor(x - 1) == x - 1
assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \
(x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1)
assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \
(x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 +
x**3 + 65536*x** 2 + 1)
f = x/pi + x*sin(x)/pi
g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1)
assert factor(f) == x*(sin(x) + 1)/pi
assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2
assert factor(Eq(
x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1))
f = (x**2 - 1)/(x**2 + 4*x + 4)
assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2
assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2
f = 3 + x - x*(1 + x) + x**2
assert factor(f) == 3
assert factor(f, x) == 3
assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 +
x**3)/(1 + 2*x**2 + x**3))
assert factor(f, expand=False) == f
raises(PolynomialError, lambda: factor(f, x, expand=False))
raises(FlagError, lambda: factor(x**2 - 1, polys=True))
assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \
[x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))]
assert not isinstance(
Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert isinstance(
PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert factor(sqrt(-x)) == sqrt(-x)
# issue 5917
e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x -
1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) +
x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)))
assert factor(e) == 0
# deep option
assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x
assert factor(sin(x**2 + x)*x, deep=True) == sin(x*(x + 1))*x
assert factor(sqrt(x**2)) == sqrt(x**2)
# issue 13149
assert factor(expand((0.5*x+1)*(0.5*y+1))) == Mul(1.0, 0.5*x + 1.0,
0.5*y + 1.0, evaluate = False)
assert factor(expand((0.5*x+0.5)**2)) == 0.25*(1.0*x + 1.0)**2
eq = x**2*y**2 + 11*x**2*y + 30*x**2 + 7*x*y**2 + 77*x*y + 210*x + 12*y**2 + 132*y + 360
assert factor(eq, x) == (x + 3)*(x + 4)*(y**2 + 11*y + 30)
assert factor(eq, x, deep=True) == (x + 3)*(x + 4)*(y**2 + 11*y + 30)
assert factor(eq, y, deep=True) == (y + 5)*(y + 6)*(x**2 + 7*x + 12)
# fraction option
f = 5*x + 3*exp(2 - 7*x)
assert factor(f, deep=True) == factor(f, deep=True, fraction=True)
assert factor(f, deep=True, fraction=False) == 5*x + 3*exp(2)*exp(-7*x)
def test_factor_large():
f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567
g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + (
x**2 + 2*x + 1)**3000)
assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134
assert factor(g) == (x + 1)**6000*(y + 1)**2
assert factor_list(
f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)])
assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)])
f = (x**2 - y**2)**200000*(x**7 + 1)
g = (x**2 + y**2)**200000*(x**7 + 1)
assert factor(f) == \
(x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor(g, gaussian=True) == \
(x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor_list(f) == \
(1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 -
x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
assert factor_list(g, gaussian=True) == \
(1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), (
x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
def test_factor_noeval():
assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert factor((6*x - 10)/(3*x - 6)) == Mul(Rational(2, 3), 3*x - 5, 1/(x - 2))
def test_intervals():
assert intervals(0) == []
assert intervals(1) == []
assert intervals(x, sqf=True) == [(0, 0)]
assert intervals(x) == [((0, 0), 1)]
assert intervals(x**128) == [((0, 0), 128)]
assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})]
f = Poly((x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257)))
assert f.intervals(sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(eps=Rational(1, 10)) == f.intervals(eps=0.1) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 100)) == f.intervals(eps=0.01) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 1000)) == f.intervals(eps=0.001) == \
[((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 10000)) == f.intervals(eps=0.0001) == \
[((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
f = (x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257))
assert intervals(f, sqf=True) == [(-1, 0), (14, 15)]
assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)]
assert intervals(f, eps=Rational(1, 10)) == intervals(f, eps=0.1) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 100)) == intervals(f, eps=0.01) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 1000)) == intervals(f, eps=0.001) == \
[((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 10000)) == intervals(f, eps=0.0001) == \
[((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3)
assert f.intervals() == \
[((-2, Rational(-3, 2)), 7), ((Rational(-3, 2), -1), 1),
((-1, -1), 1), ((-1, 0), 3),
((1, Rational(3, 2)), 1), ((Rational(3, 2), 2), 7)]
assert intervals([x**5 - 200, x**5 - 201]) == \
[((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})]
assert intervals([x**5 - 200, x**5 - 201], fast=True) == \
[((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})]
assert intervals([x**2 - 200, x**2 - 201]) == \
[((Rational(-71, 5), Rational(-85, 6)), {1: 1}), ((Rational(-85, 6), -14), {0: 1}),
((14, Rational(85, 6)), {0: 1}), ((Rational(85, 6), Rational(71, 5)), {1: 1})]
assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \
[((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2:
1, 5: 1, 6: 1}), ((2, 2), {7: 2})]
f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1
assert intervals(f, inf=Rational(7, 4), sqf=True) == []
assert intervals(f, inf=Rational(7, 5), sqf=True) == [(Rational(7, 5), Rational(3, 2))]
assert intervals(f, sup=Rational(7, 4), sqf=True) == [(-2, -1), (1, Rational(3, 2))]
assert intervals(f, sup=Rational(7, 5), sqf=True) == [(-2, -1)]
assert intervals(g, inf=Rational(7, 4)) == []
assert intervals(g, inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), 2)]
assert intervals(g, sup=Rational(7, 4)) == [((-2, -1), 2), ((1, Rational(3, 2)), 2)]
assert intervals(g, sup=Rational(7, 5)) == [((-2, -1), 2)]
assert intervals([g, h], inf=Rational(7, 4)) == []
assert intervals([g, h], inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), {0: 2})]
assert intervals([g, h], sup=S(
7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, Rational(3, 2)), {0: 2})]
assert intervals(
[g, h], sup=Rational(7, 5)) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})]
assert intervals([x + 2, x**2 - 2]) == \
[((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})]
assert intervals([x + 2, x**2 - 2], strict=True) == \
[((-2, -2), {0: 1}), ((Rational(-3, 2), -1), {1: 1}), ((1, 2), {1: 1})]
f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20
assert intervals(f) == []
real_part, complex_part = intervals(f, all=True, sqf=True)
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
assert complex_part == [(Rational(-40, 7) - I*Rational(40, 7), 0),
(Rational(-40, 7), I*Rational(40, 7)),
(I*Rational(-40, 7), Rational(40, 7)),
(0, Rational(40, 7) + I*Rational(40, 7))]
real_part, complex_part = intervals(f, all=True, sqf=True, eps=Rational(1, 10))
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000))
raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000))
raises(
ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000))
def test_refine_root():
f = Poly(x**2 - 2)
assert f.refine_root(1, 2, steps=0) == (1, 2)
assert f.refine_root(-2, -1, steps=0) == (-2, -1)
assert f.refine_root(1, 2, steps=None) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=None) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, steps=1) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=1) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, steps=1, fast=True) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=1, fast=True) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert f.refine_root(1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12))
raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True))
raises(RefinementFailed, lambda: (f**2).refine_root(1, 2))
raises(RefinementFailed, lambda: (f**2).refine_root(2, 3))
f = x**2 - 2
assert refine_root(f, 1, 2, steps=1) == (1, Rational(3, 2))
assert refine_root(f, -2, -1, steps=1) == (Rational(-3, 2), -1)
assert refine_root(f, 1, 2, steps=1, fast=True) == (1, Rational(3, 2))
assert refine_root(f, -2, -1, steps=1, fast=True) == (Rational(-3, 2), -1)
assert refine_root(f, 1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert refine_root(f, 1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12))
raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=Rational(1, 100)))
raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000))
raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000))
def test_count_roots():
assert count_roots(x**2 - 2) == 2
assert count_roots(x**2 - 2, inf=-oo) == 2
assert count_roots(x**2 - 2, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-2) == 2
assert count_roots(x**2 - 2, inf=-1) == 1
assert count_roots(x**2 - 2, sup=1) == 1
assert count_roots(x**2 - 2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 + 2) == 0
assert count_roots(x**2 + 2, inf=-2*I) == 2
assert count_roots(x**2 + 2, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=0) == 0
assert count_roots(x**2 + 2, sup=0) == 0
assert count_roots(x**2 + 2, inf=-I) == 1
assert count_roots(x**2 + 2, sup=+I) == 1
assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0
assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0
raises(PolynomialError, lambda: count_roots(1))
def test_Poly_root():
f = Poly(2*x**3 - 7*x**2 + 4*x + 4)
assert f.root(0) == Rational(-1, 2)
assert f.root(1) == 2
assert f.root(2) == 2
raises(IndexError, lambda: f.root(3))
assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0)
def test_real_roots():
assert real_roots(x) == [0]
assert real_roots(x, multiple=False) == [(0, 1)]
assert real_roots(x**3) == [0, 0, 0]
assert real_roots(x**3, multiple=False) == [(0, 3)]
assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0]
assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 1)]
assert real_roots(
x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0]
assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 3)]
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).real_roots() == [Rational(-1, 2), 2, 2]
assert Poly(g).real_roots() == [rootof(g, 0)]
def test_all_roots():
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).all_roots() == [Rational(-1, 2), 2, 2]
assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)]
def test_nroots():
assert Poly(0, x).nroots() == []
assert Poly(1, x).nroots() == []
assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0]
assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I]
roots = Poly(x**2 - 1, x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2 + 1, x).nroots()
assert roots == [-1.0*I, 1.0*I]
roots = Poly(x**2/3 - Rational(1, 3), x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2/3 + Rational(1, 3), x).nroots()
assert roots == [-1.0*I, 1.0*I]
assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(
x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(0.2*x + 0.1).nroots() == [-0.5]
roots = nroots(x**5 + x + 1, n=5)
eps = Float("1e-5")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true
assert im(roots[0]) == 0.0
assert re(roots[1]) == -0.5
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true
assert re(roots[2]) == -0.5
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true
eps = Float("1e-6")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false
assert im(roots[0]) == 0.0
assert re(roots[1]) == -0.5
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false
assert re(roots[2]) == -0.5
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false
raises(DomainError, lambda: Poly(x + y, x).nroots())
raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots())
assert nroots(x**2 - 1) == [-1.0, 1.0]
roots = nroots(x**2 - 1)
assert roots == [-1.0, 1.0]
assert nroots(x + I) == [-1.0*I]
assert nroots(x + 2*I) == [-2.0*I]
raises(PolynomialError, lambda: nroots(0))
# issue 8296
f = Poly(x**4 - 1)
assert f.nroots(2) == [w.n(2) for w in f.all_roots()]
assert str(Poly(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 +
39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 +
877969).nroots(2)) == ('[-1.7 - 1.9*I, -1.7 + 1.9*I, -1.7 '
'- 2.5*I, -1.7 + 2.5*I, -1.0*I, 1.0*I, -1.7*I, 1.7*I, -2.8*I, '
'2.8*I, -3.4*I, 3.4*I, 1.7 - 1.9*I, 1.7 + 1.9*I, 1.7 - 2.5*I, '
'1.7 + 2.5*I]')
def test_ground_roots():
f = x**6 - 4*x**4 + 4*x**3 - x**2
assert Poly(f).ground_roots() == {S.One: 2, S.Zero: 2}
assert ground_roots(f) == {S.One: 2, S.Zero: 2}
def test_nth_power_roots_poly():
f = x**4 - x**2 + 1
f_2 = (x**2 - x + 1)**2
f_3 = (x**2 + 1)**2
f_4 = (x**2 + x + 1)**2
f_12 = (x - 1)**4
assert nth_power_roots_poly(f, 1) == f
raises(ValueError, lambda: nth_power_roots_poly(f, 0))
raises(ValueError, lambda: nth_power_roots_poly(f, x))
assert factor(nth_power_roots_poly(f, 2)) == f_2
assert factor(nth_power_roots_poly(f, 3)) == f_3
assert factor(nth_power_roots_poly(f, 4)) == f_4
assert factor(nth_power_roots_poly(f, 12)) == f_12
raises(MultivariatePolynomialError, lambda: nth_power_roots_poly(
x + y, 2, x, y))
def test_torational_factor_list():
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}))
assert _torational_factor_list(p, x) == (-2, [
(-x*(1 + sqrt(2))/2 + 1, 1),
(-x*(1 + sqrt(2)) - 1, 1),
(-x*(1 + sqrt(2)) + 1, 1)])
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))}))
assert _torational_factor_list(p, x) is None
def test_cancel():
assert cancel(0) == 0
assert cancel(7) == 7
assert cancel(x) == x
assert cancel(oo) is oo
assert cancel((2, 3)) == (1, 2, 3)
assert cancel((1, 0), x) == (1, 1, 0)
assert cancel((0, 1), x) == (1, 0, 1)
f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1
F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ]
assert F.cancel(G) == (1, P, Q)
assert cancel((f, g)) == (1, p, q)
assert cancel((f, g), x) == (1, p, q)
assert cancel((f, g), (x,)) == (1, p, q)
assert cancel((F, G)) == (1, P, Q)
assert cancel((f, g), polys=True) == (1, P, Q)
assert cancel((F, G), polys=False) == (1, p, q)
f = (x**2 - 2)/(x + sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x - sqrt(2)
f = (x**2 - 2)/(x - sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x + sqrt(2)
assert cancel((x**2/4 - 1, x/2 - 1)) == (S.Half, x + 2, 1)
assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y)
assert cancel((x**2 - y**2)/(x - y), x) == x + y
assert cancel((x**2 - y**2)/(x - y), y) == x + y
assert cancel((x**2 - y**2)/(x - y)) == x + y
assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1)
assert cancel((x**3/2 - S.Half)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2)
assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1
f = Poly(x**2 - a**2, x)
g = Poly(x - a, x)
F = Poly(x + a, x)
G = Poly(1, x)
assert cancel((f, g)) == (1, F, G)
f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2)
g = x**2 - 2
assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2))
f = Poly(-2*x + 3, x)
g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x)
assert cancel((f, g)) == (1, -f, -g)
f = Poly(y, y, domain='ZZ(x)')
g = Poly(1, y, domain='ZZ[x]')
assert f.cancel(
g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
assert f.cancel(g, include=True) == (
Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
f = Poly(5*x*y + x, y, domain='ZZ(x)')
g = Poly(2*x**2*y, y, domain='ZZ(x)')
assert f.cancel(g, include=True) == (
Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)'))
f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2))
assert cancel(f).is_Mul == True
P = tanh(x - 3.0)
Q = tanh(x + 3.0)
f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \
+ (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**Rational(3, 2))
assert cancel(f).is_Mul == True
# issue 7022
A = Symbol('A', commutative=False)
p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p2 = Piecewise((A*(x - 1), x > 1), (1/x, True))
assert cancel(p1) == p2
assert cancel(2*p1) == 2*p2
assert cancel(1 + p1) == 1 + p2
assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2
assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2
p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p4 = Piecewise(((x - 1), x > 1), (1/x, True))
assert cancel(p3) == p4
assert cancel(2*p3) == 2*p4
assert cancel(1 + p3) == 1 + p4
assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4
assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4
# issue 9363
M = MatrixSymbol('M', 5, 5)
assert cancel(M[0,0] + 7) == M[0,0] + 7
expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z
assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z
def test_reduced():
f = 2*x**4 + y**2 - x**2 + y**3
G = [x**3 - x, y**3 - y]
Q = [2*x, 1]
r = x**2 + y**2 + y
assert reduced(f, G) == (Q, r)
assert reduced(f, G, x, y) == (Q, r)
H = groebner(G)
assert H.reduce(f) == (Q, r)
Q = [Poly(2*x, x, y), Poly(1, x, y)]
r = Poly(x**2 + y**2 + y, x, y)
assert _strict_eq(reduced(f, G, polys=True), (Q, r))
assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r))
H = groebner(G, polys=True)
assert _strict_eq(H.reduce(f), (Q, r))
f = 2*x**3 + y**3 + 3*y
G = groebner([x**2 + y**2 - 1, x*y - 2])
Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + y*Rational(3, 4)]
r = 0
assert reduced(f, G) == (Q, r)
assert G.reduce(f) == (Q, r)
assert reduced(f, G, auto=False)[1] != 0
assert G.reduce(f, auto=False)[1] != 0
assert G.contains(f) is True
assert G.contains(f + 1) is False
assert reduced(1, [1], x) == ([1], 0)
raises(ComputationFailed, lambda: reduced(1, [1]))
def test_groebner():
assert groebner([], x, y, z) == []
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2]
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \
[Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \
[Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)]
assert groebner([x**3 - 1, x**2 - 1]) == [x - 1]
assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1]
F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2]
f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5
G = groebner(F, x, y, z, modulus=7, symmetric=False)
assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5,
1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6,
1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6,
6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7]
Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True)
assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7)
F = [x*y - 2*y, 2*y**2 - x**2]
assert groebner(F, x, y, order='grevlex') == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner(F, y, x, order='grevlex') == \
[x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y]
assert groebner(F, order='grevlex', field=True) == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner([1], x) == [1]
assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y]
raises(ComputationFailed, lambda: groebner([1]))
assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1]
assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1]
raises(ValueError, lambda: groebner([x, y], method='unknown'))
def test_fglm():
F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1]
G = groebner(F, a, b, c, d, order=grlex)
B = [
4*a + 3*d**9 - 4*d**5 - 3*d,
4*b + 4*c - 3*d**9 + 4*d**5 + 7*d,
4*c**2 + 3*d**10 - 4*d**6 - 3*d**2,
4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d,
d**12 - d**8 - d**4 + 1,
]
assert groebner(F, a, b, c, d, order=lex) == B
assert G.fglm(lex) == B
F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
-72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \
108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96]
G = groebner(F, t, x, order=grlex)
B = [
203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \
10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \
20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194,
9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
]
assert groebner(F, t, x, order=lex) == B
assert G.fglm(lex) == B
F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1]
G = groebner(F, x, y, order=lex)
B = [
x**2 - x - 3*y + 1,
y**2 - 2*x + y - 1,
]
assert groebner(F, x, y, order=grlex) == B
assert G.fglm(grlex) == B
def test_is_zero_dimensional():
assert is_zero_dimensional([x, y], x, y) is True
assert is_zero_dimensional([x**3 + y**2], x, y) is False
assert is_zero_dimensional([x, y, z], x, y, z) is True
assert is_zero_dimensional([x, y, z], x, y, z, t) is False
F = [x*y - z, y*z - x, x*y - y]
assert is_zero_dimensional(F, x, y, z) is True
F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2]
assert is_zero_dimensional(F, x, y, z) is True
def test_GroebnerBasis():
F = [x*y - 2*y, 2*y**2 - x**2]
G = groebner(F, x, y, order='grevlex')
H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
P = [ Poly(h, x, y) for h in H ]
assert groebner(F + [0], x, y, order='grevlex') == G
assert isinstance(G, GroebnerBasis) is True
assert len(G) == 3
assert G[0] == H[0] and not G[0].is_Poly
assert G[1] == H[1] and not G[1].is_Poly
assert G[2] == H[2] and not G[2].is_Poly
assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:])
assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:])
assert G.exprs == H
assert G.polys == P
assert G.gens == (x, y)
assert G.domain == ZZ
assert G.order == grevlex
assert G == H
assert G == tuple(H)
assert G == P
assert G == tuple(P)
assert G != []
G = groebner(F, x, y, order='grevlex', polys=True)
assert G[0] == P[0] and G[0].is_Poly
assert G[1] == P[1] and G[1].is_Poly
assert G[2] == P[2] and G[2].is_Poly
assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:])
assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:])
def test_poly():
assert poly(x) == Poly(x, x)
assert poly(y) == Poly(y, y)
assert poly(x + y) == Poly(x + y, x, y)
assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x))
assert poly(x + y, wrt=y) == Poly(x + y, y, x)
assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x)
assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z)
assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z)
assert poly(
x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z)
assert poly(2*x*(
y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z)
assert poly(2*(
y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z)
assert poly(x*(
y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z)
assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*
x*z**2 - x - 1, x, y, z)
assert poly(x*y + (x + y)**2 + (x + z)**2) == \
Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z)
assert poly(x*y*(x + y)*(x + z)**2) == \
Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2*
y**2 + 2*y*z*x**3 + y*x**4, x, y, z)
assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z)
assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y])
assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x])
assert poly(1, x) == Poly(1, x)
raises(GeneratorsNeeded, lambda: poly(1))
# issue 6184
assert poly(x + y, x, y) == Poly(x + y, x, y)
assert poly(x + y, y, x) == Poly(x + y, y, x)
def test_keep_coeff():
u = Mul(2, x + 1, evaluate=False)
assert _keep_coeff(S.One, x) == x
assert _keep_coeff(S.NegativeOne, x) == -x
assert _keep_coeff(S(1.0), x) == 1.0*x
assert _keep_coeff(S(-1.0), x) == -1.0*x
assert _keep_coeff(S.One, 2*x) == 2*x
assert _keep_coeff(S(2), x/2) == x
assert _keep_coeff(S(2), sin(x)) == 2*sin(x)
assert _keep_coeff(S(2), x + 1) == u
assert _keep_coeff(x, 1/x) == 1
assert _keep_coeff(x + 1, S(2)) == u
# @XFAIL
# Seems to pass on Python 3.X, but not on Python 2.7
def test_poly_matching_consistency():
# Test for this issue:
# https://github.com/sympy/sympy/issues/5514
assert I * Poly(x, x) == Poly(I*x, x)
assert Poly(x, x) * I == Poly(I*x, x)
if not PY3:
test_poly_matching_consistency = XFAIL(test_poly_matching_consistency)
@XFAIL
def test_issue_5786():
assert expand(factor(expand(
(x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z
def test_noncommutative():
class foo(Expr):
is_commutative=False
e = x/(x + x*y)
c = 1/( 1 + y)
assert cancel(foo(e)) == foo(c)
assert cancel(e + foo(e)) == c + foo(c)
assert cancel(e*foo(c)) == c*foo(c)
def test_to_rational_coeffs():
assert to_rational_coeffs(
Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) is None
def test_factor_terms():
# issue 7067
assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
assert sqf_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
def test_as_list():
# issue 14496
assert Poly(x**3 + 2, x, domain='ZZ').as_list() == [1, 0, 0, 2]
assert Poly(x**2 + y + 1, x, y, domain='ZZ').as_list() == [[1], [], [1, 1]]
assert Poly(x**2 + y + 1, x, y, z, domain='ZZ').as_list() == \
[[[1]], [[]], [[1], [1]]]
def test_issue_11198():
assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)])
assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)])
def test_Poly_precision():
# Make sure Poly doesn't lose precision
p = Poly(pi.evalf(100)*x)
assert p.as_expr() == pi.evalf(100)*x
def test_issue_12400():
# Correction of check for negative exponents
assert poly(1/(1+sqrt(2)), x) == \
Poly(1/(1+sqrt(2)), x , domain='EX')
def test_issue_14364():
assert gcd(S(6)*(1 + sqrt(3))/5, S(3)*(1 + sqrt(3))/10) == Rational(3, 10) * (1 + sqrt(3))
assert gcd(sqrt(5)*Rational(4, 7), sqrt(5)*Rational(2, 3)) == sqrt(5)*Rational(2, 21)
assert lcm(Rational(2, 3)*sqrt(3), Rational(5, 6)*sqrt(3)) == S(10)*sqrt(3)/3
assert lcm(3*sqrt(3), 4/sqrt(3)) == 12*sqrt(3)
assert lcm(S(5)*(1 + 2**Rational(1, 3))/6, S(3)*(1 + 2**Rational(1, 3))/8) == Rational(15, 2) * (1 + 2**Rational(1, 3))
assert gcd(Rational(2, 3)*sqrt(3), Rational(5, 6)/sqrt(3)) == sqrt(3)/18
assert gcd(S(4)*sqrt(13)/7, S(3)*sqrt(13)/14) == sqrt(13)/14
# gcd_list and lcm_list
assert gcd([S(2)*sqrt(47)/7, S(6)*sqrt(47)/5, S(8)*sqrt(47)/5]) == sqrt(47)*Rational(2, 35)
assert gcd([S(6)*(1 + sqrt(7))/5, S(2)*(1 + sqrt(7))/7, S(4)*(1 + sqrt(7))/13]) == (1 + sqrt(7))*Rational(2, 455)
assert lcm((Rational(7, 2)/sqrt(15), Rational(5, 6)/sqrt(15), Rational(5, 8)/sqrt(15))) == Rational(35, 2)/sqrt(15)
assert lcm([S(5)*(2 + 2**Rational(5, 7))/6, S(7)*(2 + 2**Rational(5, 7))/2, S(13)*(2 + 2**Rational(5, 7))/4]) == Rational(455, 2) * (2 + 2**Rational(5, 7))
def test_issue_15669():
x = Symbol("x", positive=True)
expr = (16*x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2 -
2*2**Rational(4, 5)*x*(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**Rational(3, 5) + 10*x)
assert factor(expr, deep=True) == x*(x**2 + 2)
|
f097f08d2372ed7ef8a8938331a569d4648ba6b16244356de97ad873ffa89a04 | from sympy.core import Symbol, S, oo
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys import poly
from sympy.polys.dispersion import dispersion, dispersionset
def test_dispersion():
x = Symbol("x")
a = Symbol("a")
fp = poly(S.Zero, x)
assert sorted(dispersionset(fp)) == [0]
fp = poly(S(2), x)
assert sorted(dispersionset(fp)) == [0]
fp = poly(x + 1, x)
assert sorted(dispersionset(fp)) == [0]
assert dispersion(fp) == 0
fp = poly((x + 1)*(x + 2), x)
assert sorted(dispersionset(fp)) == [0, 1]
assert dispersion(fp) == 1
fp = poly(x*(x + 3), x)
assert sorted(dispersionset(fp)) == [0, 3]
assert dispersion(fp) == 3
fp = poly((x - 3)*(x + 3), x)
assert sorted(dispersionset(fp)) == [0, 6]
assert dispersion(fp) == 6
fp = poly(x**4 - 3*x**2 + 1, x)
gp = fp.shift(-3)
assert sorted(dispersionset(fp, gp)) == [2, 3, 4]
assert dispersion(fp, gp) == 4
assert sorted(dispersionset(gp, fp)) == []
assert dispersion(gp, fp) is -oo
fp = poly(x*(3*x**2+a)*(x-2536)*(x**3+a), x)
gp = fp.as_expr().subs(x, x-345).as_poly(x)
assert sorted(dispersionset(fp, gp)) == [345, 2881]
assert sorted(dispersionset(gp, fp)) == [2191]
gp = poly((x-2)**2*(x-3)**3*(x-5)**3, x)
assert sorted(dispersionset(gp)) == [0, 1, 2, 3]
assert sorted(dispersionset(gp, (gp+4)**2)) == [1, 2]
fp = poly(x*(x+2)*(x-1), x)
assert sorted(dispersionset(fp)) == [0, 1, 2, 3]
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)>')
assert sorted(dispersionset(fp, gp)) == [2]
assert sorted(dispersionset(gp, fp)) == [1, 4]
# There are some difficulties if we compute over Z[a]
# and alpha happenes to lie in Z[a] instead of simply Z.
# Hence we can not decide if alpha is indeed integral
# in general.
fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
assert sorted(dispersionset(fp)) == [0, 1]
# For any specific value of a, the dispersion is 3*a
# but the algorithm can not find this in general.
# This is the point where the resultant based Ansatz
# is superior to the current one.
fp = poly(a**2*x**3 + (a**3 + a**2 + a + 1)*x, x)
gp = fp.as_expr().subs(x, x - 3*a).as_poly(x)
assert sorted(dispersionset(fp, gp)) == []
fpa = fp.as_expr().subs(a, 2).as_poly(x)
gpa = gp.as_expr().subs(a, 2).as_poly(x)
assert sorted(dispersionset(fpa, gpa)) == [6]
# Work with Expr instead of Poly
f = (x + 1)*(x + 2)
assert sorted(dispersionset(f)) == [0, 1]
assert dispersion(f) == 1
f = x**4 - 3*x**2 + 1
g = x**4 - 12*x**3 + 51*x**2 - 90*x + 55
assert sorted(dispersionset(f, g)) == [2, 3, 4]
assert dispersion(f, g) == 4
# Work with Expr and specify a generator
f = (x + 1)*(x + 2)
assert sorted(dispersionset(f, None, x)) == [0, 1]
assert dispersion(f, None, x) == 1
f = x**4 - 3*x**2 + 1
g = x**4 - 12*x**3 + 51*x**2 - 90*x + 55
assert sorted(dispersionset(f, g, x)) == [2, 3, 4]
assert dispersion(f, g, x) == 4
|
bd0db4964a4ab0b6c13de65622ffeb94b0118f54ed6dad414221d8e75b786fb9 | """Tests for efficient functions for generating orthogonal polynomials. """
from sympy import Poly, S, Rational as Q
from sympy.utilities.pytest import raises
from sympy.polys.orthopolys import (
jacobi_poly,
gegenbauer_poly,
chebyshevt_poly,
chebyshevu_poly,
hermite_poly,
legendre_poly,
laguerre_poly,
)
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_legendre_poly():
raises(ValueError, lambda: legendre_poly(-1, x))
assert legendre_poly(1, x, polys=True) == Poly(x)
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)
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)
|
7d9bc66b6578b02385a8438498c6662e45791063cb94ffa081c4c1aa018185a6 | """Tests for dense recursive polynomials' basic tools. """
from sympy.polys.densebasic import (
dup_LC, dmp_LC,
dup_TC, dmp_TC,
dmp_ground_LC, dmp_ground_TC,
dmp_true_LT,
dup_degree, dmp_degree,
dmp_degree_in, dmp_degree_list,
dup_strip, dmp_strip,
dmp_validate,
dup_reverse,
dup_copy, dmp_copy,
dup_normal, dmp_normal,
dup_convert, dmp_convert,
dup_from_sympy, dmp_from_sympy,
dup_nth, dmp_nth, dmp_ground_nth,
dmp_zero_p, dmp_zero,
dmp_one_p, dmp_one,
dmp_ground_p, dmp_ground,
dmp_negative_p, dmp_positive_p,
dmp_zeros, dmp_grounds,
dup_from_dict, dup_from_raw_dict,
dup_to_dict, dup_to_raw_dict,
dmp_from_dict, dmp_to_dict,
dmp_swap, dmp_permute,
dmp_nest, dmp_raise,
dup_deflate, dmp_deflate,
dup_multi_deflate, dmp_multi_deflate,
dup_inflate, dmp_inflate,
dmp_exclude, dmp_include,
dmp_inject, dmp_eject,
dup_terms_gcd, dmp_terms_gcd,
dmp_list_terms, dmp_apply_pairs,
dup_slice,
dup_random,
)
from sympy.polys.specialpolys import f_polys
from sympy.polys.domains import ZZ, QQ
from sympy.polys.rings import ring
from sympy.core.singleton import S
from sympy.utilities.pytest import raises
from sympy import oo
f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ]
def test_dup_LC():
assert dup_LC([], ZZ) == 0
assert dup_LC([2, 3, 4, 5], ZZ) == 2
def test_dup_TC():
assert dup_TC([], ZZ) == 0
assert dup_TC([2, 3, 4, 5], ZZ) == 5
def test_dmp_LC():
assert dmp_LC([[]], ZZ) == []
assert dmp_LC([[2, 3, 4], [5]], ZZ) == [2, 3, 4]
assert dmp_LC([[[]]], ZZ) == [[]]
assert dmp_LC([[[2], [3, 4]], [[5]]], ZZ) == [[2], [3, 4]]
def test_dmp_TC():
assert dmp_TC([[]], ZZ) == []
assert dmp_TC([[2, 3, 4], [5]], ZZ) == [5]
assert dmp_TC([[[]]], ZZ) == [[]]
assert dmp_TC([[[2], [3, 4]], [[5]]], ZZ) == [[5]]
def test_dmp_ground_LC():
assert dmp_ground_LC([[]], 1, ZZ) == 0
assert dmp_ground_LC([[2, 3, 4], [5]], 1, ZZ) == 2
assert dmp_ground_LC([[[]]], 2, ZZ) == 0
assert dmp_ground_LC([[[2], [3, 4]], [[5]]], 2, ZZ) == 2
def test_dmp_ground_TC():
assert dmp_ground_TC([[]], 1, ZZ) == 0
assert dmp_ground_TC([[2, 3, 4], [5]], 1, ZZ) == 5
assert dmp_ground_TC([[[]]], 2, ZZ) == 0
assert dmp_ground_TC([[[2], [3, 4]], [[5]]], 2, ZZ) == 5
def test_dmp_true_LT():
assert dmp_true_LT([[]], 1, ZZ) == ((0, 0), 0)
assert dmp_true_LT([[7]], 1, ZZ) == ((0, 0), 7)
assert dmp_true_LT([[1, 0]], 1, ZZ) == ((0, 1), 1)
assert dmp_true_LT([[1], []], 1, ZZ) == ((1, 0), 1)
assert dmp_true_LT([[1, 0], []], 1, ZZ) == ((1, 1), 1)
def test_dup_degree():
assert dup_degree([]) is -oo
assert dup_degree([1]) == 0
assert dup_degree([1, 0]) == 1
assert dup_degree([1, 0, 0, 0, 1]) == 4
def test_dmp_degree():
assert dmp_degree([[]], 1) is -oo
assert dmp_degree([[[]]], 2) is -oo
assert dmp_degree([[1]], 1) == 0
assert dmp_degree([[2], [1]], 1) == 1
def test_dmp_degree_in():
assert dmp_degree_in([[[]]], 0, 2) is -oo
assert dmp_degree_in([[[]]], 1, 2) is -oo
assert dmp_degree_in([[[]]], 2, 2) is -oo
assert dmp_degree_in([[[1]]], 0, 2) == 0
assert dmp_degree_in([[[1]]], 1, 2) == 0
assert dmp_degree_in([[[1]]], 2, 2) == 0
assert dmp_degree_in(f_4, 0, 2) == 9
assert dmp_degree_in(f_4, 1, 2) == 12
assert dmp_degree_in(f_4, 2, 2) == 8
assert dmp_degree_in(f_6, 0, 2) == 4
assert dmp_degree_in(f_6, 1, 2) == 4
assert dmp_degree_in(f_6, 2, 2) == 6
assert dmp_degree_in(f_6, 3, 3) == 3
raises(IndexError, lambda: dmp_degree_in([[1]], -5, 1))
def test_dmp_degree_list():
assert dmp_degree_list([[[[ ]]]], 3) == (-oo, -oo, -oo, -oo)
assert dmp_degree_list([[[[1]]]], 3) == ( 0, 0, 0, 0)
assert dmp_degree_list(f_0, 2) == (2, 2, 2)
assert dmp_degree_list(f_1, 2) == (3, 3, 3)
assert dmp_degree_list(f_2, 2) == (5, 3, 3)
assert dmp_degree_list(f_3, 2) == (5, 4, 7)
assert dmp_degree_list(f_4, 2) == (9, 12, 8)
assert dmp_degree_list(f_5, 2) == (3, 3, 3)
assert dmp_degree_list(f_6, 3) == (4, 4, 6, 3)
def test_dup_strip():
assert dup_strip([]) == []
assert dup_strip([0]) == []
assert dup_strip([0, 0, 0]) == []
assert dup_strip([1]) == [1]
assert dup_strip([0, 1]) == [1]
assert dup_strip([0, 0, 0, 1]) == [1]
assert dup_strip([1, 2, 0]) == [1, 2, 0]
assert dup_strip([0, 1, 2, 0]) == [1, 2, 0]
assert dup_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0]
def test_dmp_strip():
assert dmp_strip([0, 1, 0], 0) == [1, 0]
assert dmp_strip([[]], 1) == [[]]
assert dmp_strip([[], []], 1) == [[]]
assert dmp_strip([[], [], []], 1) == [[]]
assert dmp_strip([[[]]], 2) == [[[]]]
assert dmp_strip([[[]], [[]]], 2) == [[[]]]
assert dmp_strip([[[]], [[]], [[]]], 2) == [[[]]]
assert dmp_strip([[[1]]], 2) == [[[1]]]
assert dmp_strip([[[]], [[1]]], 2) == [[[1]]]
assert dmp_strip([[[]], [[1]], [[]]], 2) == [[[1]], [[]]]
def test_dmp_validate():
assert dmp_validate([]) == ([], 0)
assert dmp_validate([0, 0, 0, 1, 0]) == ([1, 0], 0)
assert dmp_validate([[[]]]) == ([[[]]], 2)
assert dmp_validate([[0], [], [0], [1], [0]]) == ([[1], []], 1)
raises(ValueError, lambda: dmp_validate([[0], 0, [0], [1], [0]]))
def test_dup_reverse():
assert dup_reverse([1, 2, 0, 3]) == [3, 0, 2, 1]
assert dup_reverse([1, 2, 3, 0]) == [3, 2, 1]
def test_dup_copy():
f = [ZZ(1), ZZ(0), ZZ(2)]
g = dup_copy(f)
g[0], g[2] = ZZ(7), ZZ(0)
assert f != g
def test_dmp_copy():
f = [[ZZ(1)], [ZZ(2), ZZ(0)]]
g = dmp_copy(f, 1)
g[0][0], g[1][1] = ZZ(7), ZZ(1)
assert f != g
def test_dup_normal():
assert dup_normal([0, 0, 2, 1, 0, 11, 0], ZZ) == \
[ZZ(2), ZZ(1), ZZ(0), ZZ(11), ZZ(0)]
def test_dmp_normal():
assert dmp_normal([[0], [], [0, 2, 1], [0], [11], []], 1, ZZ) == \
[[ZZ(2), ZZ(1)], [], [ZZ(11)], []]
def test_dup_convert():
K0, K1 = ZZ['x'], ZZ
f = [K0(1), K0(2), K0(0), K0(3)]
assert dup_convert(f, K0, K1) == \
[ZZ(1), ZZ(2), ZZ(0), ZZ(3)]
def test_dmp_convert():
K0, K1 = ZZ['x'], ZZ
f = [[K0(1)], [K0(2)], [], [K0(3)]]
assert dmp_convert(f, 1, K0, K1) == \
[[ZZ(1)], [ZZ(2)], [], [ZZ(3)]]
def test_dup_from_sympy():
assert dup_from_sympy([S.One, S(2)], ZZ) == \
[ZZ(1), ZZ(2)]
assert dup_from_sympy([S.Half, S(3)], QQ) == \
[QQ(1, 2), QQ(3, 1)]
def test_dmp_from_sympy():
assert dmp_from_sympy([[S.One, S(2)], [S.Zero]], 1, ZZ) == \
[[ZZ(1), ZZ(2)], []]
assert dmp_from_sympy([[S.Half, S(2)]], 1, QQ) == \
[[QQ(1, 2), QQ(2, 1)]]
def test_dup_nth():
assert dup_nth([1, 2, 3], 0, ZZ) == 3
assert dup_nth([1, 2, 3], 1, ZZ) == 2
assert dup_nth([1, 2, 3], 2, ZZ) == 1
assert dup_nth([1, 2, 3], 9, ZZ) == 0
raises(IndexError, lambda: dup_nth([3, 4, 5], -1, ZZ))
def test_dmp_nth():
assert dmp_nth([[1], [2], [3]], 0, 1, ZZ) == [3]
assert dmp_nth([[1], [2], [3]], 1, 1, ZZ) == [2]
assert dmp_nth([[1], [2], [3]], 2, 1, ZZ) == [1]
assert dmp_nth([[1], [2], [3]], 9, 1, ZZ) == []
raises(IndexError, lambda: dmp_nth([[3], [4], [5]], -1, 1, ZZ))
def test_dmp_ground_nth():
assert dmp_ground_nth([[]], (0, 0), 1, ZZ) == 0
assert dmp_ground_nth([[1], [2], [3]], (0, 0), 1, ZZ) == 3
assert dmp_ground_nth([[1], [2], [3]], (1, 0), 1, ZZ) == 2
assert dmp_ground_nth([[1], [2], [3]], (2, 0), 1, ZZ) == 1
assert dmp_ground_nth([[1], [2], [3]], (2, 1), 1, ZZ) == 0
assert dmp_ground_nth([[1], [2], [3]], (3, 0), 1, ZZ) == 0
raises(IndexError, lambda: dmp_ground_nth([[3], [4], [5]], (2, -1), 1, ZZ))
def test_dmp_zero_p():
assert dmp_zero_p([], 0) is True
assert dmp_zero_p([[]], 1) is True
assert dmp_zero_p([[[]]], 2) is True
assert dmp_zero_p([[[1]]], 2) is False
def test_dmp_zero():
assert dmp_zero(0) == []
assert dmp_zero(2) == [[[]]]
def test_dmp_one_p():
assert dmp_one_p([1], 0, ZZ) is True
assert dmp_one_p([[1]], 1, ZZ) is True
assert dmp_one_p([[[1]]], 2, ZZ) is True
assert dmp_one_p([[[12]]], 2, ZZ) is False
def test_dmp_one():
assert dmp_one(0, ZZ) == [ZZ(1)]
assert dmp_one(2, ZZ) == [[[ZZ(1)]]]
def test_dmp_ground_p():
assert dmp_ground_p([], 0, 0) is True
assert dmp_ground_p([[]], 0, 1) is True
assert dmp_ground_p([[]], 1, 1) is False
assert dmp_ground_p([[ZZ(1)]], 1, 1) is True
assert dmp_ground_p([[[ZZ(2)]]], 2, 2) is True
assert dmp_ground_p([[[ZZ(2)]]], 3, 2) is False
assert dmp_ground_p([[[ZZ(3)], []]], 3, 2) is False
assert dmp_ground_p([], None, 0) is True
assert dmp_ground_p([[]], None, 1) is True
assert dmp_ground_p([ZZ(1)], None, 0) is True
assert dmp_ground_p([[[ZZ(1)]]], None, 2) is True
assert dmp_ground_p([[[ZZ(3)], []]], None, 2) is False
def test_dmp_ground():
assert dmp_ground(ZZ(0), 2) == [[[]]]
assert dmp_ground(ZZ(7), -1) == ZZ(7)
assert dmp_ground(ZZ(7), 0) == [ZZ(7)]
assert dmp_ground(ZZ(7), 2) == [[[ZZ(7)]]]
def test_dmp_zeros():
assert dmp_zeros(4, 0, ZZ) == [[], [], [], []]
assert dmp_zeros(0, 2, ZZ) == []
assert dmp_zeros(1, 2, ZZ) == [[[[]]]]
assert dmp_zeros(2, 2, ZZ) == [[[[]]], [[[]]]]
assert dmp_zeros(3, 2, ZZ) == [[[[]]], [[[]]], [[[]]]]
assert dmp_zeros(3, -1, ZZ) == [0, 0, 0]
def test_dmp_grounds():
assert dmp_grounds(ZZ(7), 0, 2) == []
assert dmp_grounds(ZZ(7), 1, 2) == [[[[7]]]]
assert dmp_grounds(ZZ(7), 2, 2) == [[[[7]]], [[[7]]]]
assert dmp_grounds(ZZ(7), 3, 2) == [[[[7]]], [[[7]]], [[[7]]]]
assert dmp_grounds(ZZ(7), 3, -1) == [7, 7, 7]
def test_dmp_negative_p():
assert dmp_negative_p([[[]]], 2, ZZ) is False
assert dmp_negative_p([[[1], [2]]], 2, ZZ) is False
assert dmp_negative_p([[[-1], [2]]], 2, ZZ) is True
def test_dmp_positive_p():
assert dmp_positive_p([[[]]], 2, ZZ) is False
assert dmp_positive_p([[[1], [2]]], 2, ZZ) is True
assert dmp_positive_p([[[-1], [2]]], 2, ZZ) is False
def test_dup_from_to_dict():
assert dup_from_raw_dict({}, ZZ) == []
assert dup_from_dict({}, ZZ) == []
assert dup_to_raw_dict([]) == {}
assert dup_to_dict([]) == {}
assert dup_to_raw_dict([], ZZ, zero=True) == {0: ZZ(0)}
assert dup_to_dict([], ZZ, zero=True) == {(0,): ZZ(0)}
f = [3, 0, 0, 2, 0, 0, 0, 0, 8]
g = {8: 3, 5: 2, 0: 8}
h = {(8,): 3, (5,): 2, (0,): 8}
assert dup_from_raw_dict(g, ZZ) == f
assert dup_from_dict(h, ZZ) == f
assert dup_to_raw_dict(f) == g
assert dup_to_dict(f) == h
R, x,y = ring("x,y", ZZ)
K = R.to_domain()
f = [R(3), R(0), R(2), R(0), R(0), R(8)]
g = {5: R(3), 3: R(2), 0: R(8)}
h = {(5,): R(3), (3,): R(2), (0,): R(8)}
assert dup_from_raw_dict(g, K) == f
assert dup_from_dict(h, K) == f
assert dup_to_raw_dict(f) == g
assert dup_to_dict(f) == h
def test_dmp_from_to_dict():
assert dmp_from_dict({}, 1, ZZ) == [[]]
assert dmp_to_dict([[]], 1) == {}
assert dmp_to_dict([], 0, ZZ, zero=True) == {(0,): ZZ(0)}
assert dmp_to_dict([[]], 1, ZZ, zero=True) == {(0, 0): ZZ(0)}
f = [[3], [], [], [2], [], [], [], [], [8]]
g = {(8, 0): 3, (5, 0): 2, (0, 0): 8}
assert dmp_from_dict(g, 1, ZZ) == f
assert dmp_to_dict(f, 1) == g
def test_dmp_swap():
f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ)
g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ)
assert dmp_swap(f, 1, 1, 1, ZZ) == f
assert dmp_swap(f, 0, 1, 1, ZZ) == g
assert dmp_swap(g, 0, 1, 1, ZZ) == f
raises(IndexError, lambda: dmp_swap(f, -1, -7, 1, ZZ))
def test_dmp_permute():
f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ)
g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ)
assert dmp_permute(f, [0, 1], 1, ZZ) == f
assert dmp_permute(g, [0, 1], 1, ZZ) == g
assert dmp_permute(f, [1, 0], 1, ZZ) == g
assert dmp_permute(g, [1, 0], 1, ZZ) == f
def test_dmp_nest():
assert dmp_nest(ZZ(1), 2, ZZ) == [[[1]]]
assert dmp_nest([[1]], 0, ZZ) == [[1]]
assert dmp_nest([[1]], 1, ZZ) == [[[1]]]
assert dmp_nest([[1]], 2, ZZ) == [[[[1]]]]
def test_dmp_raise():
assert dmp_raise([], 2, 0, ZZ) == [[[]]]
assert dmp_raise([[1]], 0, 1, ZZ) == [[1]]
assert dmp_raise([[1, 2, 3], [], [2, 3]], 2, 1, ZZ) == \
[[[[1]], [[2]], [[3]]], [[[]]], [[[2]], [[3]]]]
def test_dup_deflate():
assert dup_deflate([], ZZ) == (1, [])
assert dup_deflate([2], ZZ) == (1, [2])
assert dup_deflate([1, 2, 3], ZZ) == (1, [1, 2, 3])
assert dup_deflate([1, 0, 2, 0, 3], ZZ) == (2, [1, 2, 3])
assert dup_deflate(dup_from_raw_dict({7: 1, 1: 1}, ZZ), ZZ) == \
(1, [1, 0, 0, 0, 0, 0, 1, 0])
assert dup_deflate(dup_from_raw_dict({7: 1, 0: 1}, ZZ), ZZ) == \
(7, [1, 1])
assert dup_deflate(dup_from_raw_dict({7: 1, 3: 1}, ZZ), ZZ) == \
(1, [1, 0, 0, 0, 1, 0, 0, 0])
assert dup_deflate(dup_from_raw_dict({7: 1, 4: 1}, ZZ), ZZ) == \
(1, [1, 0, 0, 1, 0, 0, 0, 0])
assert dup_deflate(dup_from_raw_dict({8: 1, 4: 1}, ZZ), ZZ) == \
(4, [1, 1, 0])
assert dup_deflate(dup_from_raw_dict({8: 1}, ZZ), ZZ) == \
(8, [1, 0])
assert dup_deflate(dup_from_raw_dict({7: 1}, ZZ), ZZ) == \
(7, [1, 0])
assert dup_deflate(dup_from_raw_dict({1: 1}, ZZ), ZZ) == \
(1, [1, 0])
def test_dmp_deflate():
assert dmp_deflate([[]], 1, ZZ) == ((1, 1), [[]])
assert dmp_deflate([[2]], 1, ZZ) == ((1, 1), [[2]])
f = [[1, 0, 0], [], [1, 0], [], [1]]
assert dmp_deflate(f, 1, ZZ) == ((2, 1), [[1, 0, 0], [1, 0], [1]])
def test_dup_multi_deflate():
assert dup_multi_deflate(([2],), ZZ) == (1, ([2],))
assert dup_multi_deflate(([], []), ZZ) == (1, ([], []))
assert dup_multi_deflate(([1, 2, 3],), ZZ) == (1, ([1, 2, 3],))
assert dup_multi_deflate(([1, 0, 2, 0, 3],), ZZ) == (2, ([1, 2, 3],))
assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 0, 0]), ZZ) == \
(2, ([1, 2, 3], [2, 0]))
assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 1, 0]), ZZ) == \
(1, ([1, 0, 2, 0, 3], [2, 1, 0]))
def test_dmp_multi_deflate():
assert dmp_multi_deflate(([[]],), 1, ZZ) == \
((1, 1), ([[]],))
assert dmp_multi_deflate(([[]], [[]]), 1, ZZ) == \
((1, 1), ([[]], [[]]))
assert dmp_multi_deflate(([[1]], [[]]), 1, ZZ) == \
((1, 1), ([[1]], [[]]))
assert dmp_multi_deflate(([[1]], [[2]]), 1, ZZ) == \
((1, 1), ([[1]], [[2]]))
assert dmp_multi_deflate(([[1]], [[2, 0]]), 1, ZZ) == \
((1, 1), ([[1]], [[2, 0]]))
assert dmp_multi_deflate(([[2, 0]], [[2, 0]]), 1, ZZ) == \
((1, 1), ([[2, 0]], [[2, 0]]))
assert dmp_multi_deflate(
([[2]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2]], [[2, 0]]))
assert dmp_multi_deflate(
([[2, 0, 0]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2, 0]], [[2, 0]]))
assert dmp_multi_deflate(([2, 0, 0], [1, 0, 4, 0, 1]), 0, ZZ) == \
((2,), ([2, 0], [1, 4, 1]))
f = [[1, 0, 0], [], [1, 0], [], [1]]
g = [[1, 0, 1, 0], [], [1]]
assert dmp_multi_deflate((f,), 1, ZZ) == \
((2, 1), ([[1, 0, 0], [1, 0], [1]],))
assert dmp_multi_deflate((f, g), 1, ZZ) == \
((2, 1), ([[1, 0, 0], [1, 0], [1]],
[[1, 0, 1, 0], [1]]))
def test_dup_inflate():
assert dup_inflate([], 17, ZZ) == []
assert dup_inflate([1, 2, 3], 1, ZZ) == [1, 2, 3]
assert dup_inflate([1, 2, 3], 2, ZZ) == [1, 0, 2, 0, 3]
assert dup_inflate([1, 2, 3], 3, ZZ) == [1, 0, 0, 2, 0, 0, 3]
assert dup_inflate([1, 2, 3], 4, ZZ) == [1, 0, 0, 0, 2, 0, 0, 0, 3]
raises(IndexError, lambda: dup_inflate([1, 2, 3], 0, ZZ))
def test_dmp_inflate():
assert dmp_inflate([1], (3,), 0, ZZ) == [1]
assert dmp_inflate([[]], (3, 7), 1, ZZ) == [[]]
assert dmp_inflate([[2]], (1, 2), 1, ZZ) == [[2]]
assert dmp_inflate([[2, 0]], (1, 1), 1, ZZ) == [[2, 0]]
assert dmp_inflate([[2, 0]], (1, 2), 1, ZZ) == [[2, 0, 0]]
assert dmp_inflate([[2, 0]], (1, 3), 1, ZZ) == [[2, 0, 0, 0]]
assert dmp_inflate([[1, 0, 0], [1], [1, 0]], (2, 1), 1, ZZ) == \
[[1, 0, 0], [], [1], [], [1, 0]]
raises(IndexError, lambda: dmp_inflate([[]], (-3, 7), 1, ZZ))
def test_dmp_exclude():
assert dmp_exclude([[[]]], 2, ZZ) == ([], [[[]]], 2)
assert dmp_exclude([[[7]]], 2, ZZ) == ([], [[[7]]], 2)
assert dmp_exclude([1, 2, 3], 0, ZZ) == ([], [1, 2, 3], 0)
assert dmp_exclude([[1], [2, 3]], 1, ZZ) == ([], [[1], [2, 3]], 1)
assert dmp_exclude([[1, 2, 3]], 1, ZZ) == ([0], [1, 2, 3], 0)
assert dmp_exclude([[1], [2], [3]], 1, ZZ) == ([1], [1, 2, 3], 0)
assert dmp_exclude([[[1, 2, 3]]], 2, ZZ) == ([0, 1], [1, 2, 3], 0)
assert dmp_exclude([[[1]], [[2]], [[3]]], 2, ZZ) == ([1, 2], [1, 2, 3], 0)
def test_dmp_include():
assert dmp_include([1, 2, 3], [], 0, ZZ) == [1, 2, 3]
assert dmp_include([1, 2, 3], [0], 0, ZZ) == [[1, 2, 3]]
assert dmp_include([1, 2, 3], [1], 0, ZZ) == [[1], [2], [3]]
assert dmp_include([1, 2, 3], [0, 1], 0, ZZ) == [[[1, 2, 3]]]
assert dmp_include([1, 2, 3], [1, 2], 0, ZZ) == [[[1]], [[2]], [[3]]]
def test_dmp_inject():
R, x,y = ring("x,y", ZZ)
K = R.to_domain()
assert dmp_inject([], 0, K) == ([[[]]], 2)
assert dmp_inject([[]], 1, K) == ([[[[]]]], 3)
assert dmp_inject([R(1)], 0, K) == ([[[1]]], 2)
assert dmp_inject([[R(1)]], 1, K) == ([[[[1]]]], 3)
assert dmp_inject([R(1), 2*x + 3*y + 4], 0, K) == ([[[1]], [[2], [3, 4]]], 2)
f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11]
g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]]
assert dmp_inject(f, 0, K) == (g, 2)
def test_dmp_eject():
R, x,y = ring("x,y", ZZ)
K = R.to_domain()
assert dmp_eject([[[]]], 2, K) == []
assert dmp_eject([[[[]]]], 3, K) == [[]]
assert dmp_eject([[[1]]], 2, K) == [R(1)]
assert dmp_eject([[[[1]]]], 3, K) == [[R(1)]]
assert dmp_eject([[[1]], [[2], [3, 4]]], 2, K) == [R(1), 2*x + 3*y + 4]
f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11]
g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]]
assert dmp_eject(g, 2, K) == f
def test_dup_terms_gcd():
assert dup_terms_gcd([], ZZ) == (0, [])
assert dup_terms_gcd([1, 0, 1], ZZ) == (0, [1, 0, 1])
assert dup_terms_gcd([1, 0, 1, 0], ZZ) == (1, [1, 0, 1])
def test_dmp_terms_gcd():
assert dmp_terms_gcd([[]], 1, ZZ) == ((0, 0), [[]])
assert dmp_terms_gcd([1, 0, 1, 0], 0, ZZ) == ((1,), [1, 0, 1])
assert dmp_terms_gcd([[1], [], [1], []], 1, ZZ) == ((1, 0), [[1], [], [1]])
assert dmp_terms_gcd(
[[1, 0], [], [1]], 1, ZZ) == ((0, 0), [[1, 0], [], [1]])
assert dmp_terms_gcd(
[[1, 0], [1, 0, 0], [], []], 1, ZZ) == ((2, 1), [[1], [1, 0]])
def test_dmp_list_terms():
assert dmp_list_terms([[[]]], 2, ZZ) == [((0, 0, 0), 0)]
assert dmp_list_terms([[[1]]], 2, ZZ) == [((0, 0, 0), 1)]
assert dmp_list_terms([1, 2, 4, 3, 5], 0, ZZ) == \
[((4,), 1), ((3,), 2), ((2,), 4), ((1,), 3), ((0,), 5)]
assert dmp_list_terms([[1], [2, 4], [3, 5, 0]], 1, ZZ) == \
[((2, 0), 1), ((1, 1), 2), ((1, 0), 4), ((0, 2), 3), ((0, 1), 5)]
f = [[2, 0, 0, 0], [1, 0, 0], []]
assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 2), 1)]
assert dmp_list_terms(
f, 1, ZZ, order='grlex') == [((2, 3), 2), ((1, 2), 1)]
f = [[2, 0, 0, 0], [1, 0, 0, 0, 0, 0], []]
assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 5), 1)]
assert dmp_list_terms(
f, 1, ZZ, order='grlex') == [((1, 5), 1), ((2, 3), 2)]
def test_dmp_apply_pairs():
h = lambda a, b: a*b
assert dmp_apply_pairs([1, 2, 3], [4, 5, 6], h, [], 0, ZZ) == [4, 10, 18]
assert dmp_apply_pairs([2, 3], [4, 5, 6], h, [], 0, ZZ) == [10, 18]
assert dmp_apply_pairs([1, 2, 3], [5, 6], h, [], 0, ZZ) == [10, 18]
assert dmp_apply_pairs(
[[1, 2], [3]], [[4, 5], [6]], h, [], 1, ZZ) == [[4, 10], [18]]
assert dmp_apply_pairs(
[[1, 2], [3]], [[4], [5, 6]], h, [], 1, ZZ) == [[8], [18]]
assert dmp_apply_pairs(
[[1], [2, 3]], [[4, 5], [6]], h, [], 1, ZZ) == [[5], [18]]
def test_dup_slice():
f = [1, 2, 3, 4]
assert dup_slice(f, 0, 0, ZZ) == []
assert dup_slice(f, 0, 1, ZZ) == [4]
assert dup_slice(f, 0, 2, ZZ) == [3, 4]
assert dup_slice(f, 0, 3, ZZ) == [2, 3, 4]
assert dup_slice(f, 0, 4, ZZ) == [1, 2, 3, 4]
assert dup_slice(f, 0, 4, ZZ) == f
assert dup_slice(f, 0, 9, ZZ) == f
assert dup_slice(f, 1, 0, ZZ) == []
assert dup_slice(f, 1, 1, ZZ) == []
assert dup_slice(f, 1, 2, ZZ) == [3, 0]
assert dup_slice(f, 1, 3, ZZ) == [2, 3, 0]
assert dup_slice(f, 1, 4, ZZ) == [1, 2, 3, 0]
assert dup_slice([1, 2], 0, 3, ZZ) == [1, 2]
def test_dup_random():
f = dup_random(0, -10, 10, ZZ)
assert dup_degree(f) == 0
assert all(-10 <= c <= 10 for c in f)
f = dup_random(1, -20, 20, ZZ)
assert dup_degree(f) == 1
assert all(-20 <= c <= 20 for c in f)
f = dup_random(2, -30, 30, ZZ)
assert dup_degree(f) == 2
assert all(-30 <= c <= 30 for c in f)
f = dup_random(3, -40, 40, ZZ)
assert dup_degree(f) == 3
assert all(-40 <= c <= 40 for c in f)
|
f7dfc03aeeccbfe780f0a8e519e191d1a40bac69abd240b550ee189532f86bb0 | """Tests of monomial orderings. """
from sympy.polys.orderings import (
monomial_key, lex, grlex, grevlex, ilex, igrlex,
LexOrder, InverseOrder, ProductOrder, build_product_order,
)
from sympy.abc import x, y, z, t
from sympy.core import S
from sympy.utilities.pytest import raises
def test_lex_order():
assert lex((1, 2, 3)) == (1, 2, 3)
assert str(lex) == 'lex'
assert lex((1, 2, 3)) == lex((1, 2, 3))
assert lex((2, 2, 3)) > lex((1, 2, 3))
assert lex((1, 3, 3)) > lex((1, 2, 3))
assert lex((1, 2, 4)) > lex((1, 2, 3))
assert lex((0, 2, 3)) < lex((1, 2, 3))
assert lex((1, 1, 3)) < lex((1, 2, 3))
assert lex((1, 2, 2)) < lex((1, 2, 3))
assert lex.is_global is True
assert lex == LexOrder()
assert lex != grlex
def test_grlex_order():
assert grlex((1, 2, 3)) == (6, (1, 2, 3))
assert str(grlex) == 'grlex'
assert grlex((1, 2, 3)) == grlex((1, 2, 3))
assert grlex((2, 2, 3)) > grlex((1, 2, 3))
assert grlex((1, 3, 3)) > grlex((1, 2, 3))
assert grlex((1, 2, 4)) > grlex((1, 2, 3))
assert grlex((0, 2, 3)) < grlex((1, 2, 3))
assert grlex((1, 1, 3)) < grlex((1, 2, 3))
assert grlex((1, 2, 2)) < grlex((1, 2, 3))
assert grlex((2, 2, 3)) > grlex((1, 2, 4))
assert grlex((1, 3, 3)) > grlex((1, 2, 4))
assert grlex((0, 2, 3)) < grlex((1, 2, 2))
assert grlex((1, 1, 3)) < grlex((1, 2, 2))
assert grlex((0, 1, 1)) > grlex((0, 0, 2))
assert grlex((0, 3, 1)) < grlex((2, 2, 1))
assert grlex.is_global is True
def test_grevlex_order():
assert grevlex((1, 2, 3)) == (6, (-3, -2, -1))
assert str(grevlex) == 'grevlex'
assert grevlex((1, 2, 3)) == grevlex((1, 2, 3))
assert grevlex((2, 2, 3)) > grevlex((1, 2, 3))
assert grevlex((1, 3, 3)) > grevlex((1, 2, 3))
assert grevlex((1, 2, 4)) > grevlex((1, 2, 3))
assert grevlex((0, 2, 3)) < grevlex((1, 2, 3))
assert grevlex((1, 1, 3)) < grevlex((1, 2, 3))
assert grevlex((1, 2, 2)) < grevlex((1, 2, 3))
assert grevlex((2, 2, 3)) > grevlex((1, 2, 4))
assert grevlex((1, 3, 3)) > grevlex((1, 2, 4))
assert grevlex((0, 2, 3)) < grevlex((1, 2, 2))
assert grevlex((1, 1, 3)) < grevlex((1, 2, 2))
assert grevlex((0, 1, 1)) > grevlex((0, 0, 2))
assert grevlex((0, 3, 1)) < grevlex((2, 2, 1))
assert grevlex.is_global is True
def test_InverseOrder():
ilex = InverseOrder(lex)
igrlex = InverseOrder(grlex)
assert ilex((1, 2, 3)) > ilex((2, 0, 3))
assert igrlex((1, 2, 3)) < igrlex((0, 2, 3))
assert str(ilex) == "ilex"
assert str(igrlex) == "igrlex"
assert ilex.is_global is False
assert igrlex.is_global is False
assert ilex != igrlex
assert ilex == InverseOrder(LexOrder())
def test_ProductOrder():
P = ProductOrder((grlex, lambda m: m[:2]), (grlex, lambda m: m[2:]))
assert P((1, 3, 3, 4, 5)) > P((2, 1, 5, 5, 5))
assert str(P) == "ProductOrder(grlex, grlex)"
assert P.is_global is True
assert ProductOrder((grlex, None), (ilex, None)).is_global is None
assert ProductOrder((igrlex, None), (ilex, None)).is_global is False
def test_monomial_key():
assert monomial_key() == lex
assert monomial_key('lex') == lex
assert monomial_key('grlex') == grlex
assert monomial_key('grevlex') == grevlex
raises(ValueError, lambda: monomial_key('foo'))
raises(ValueError, lambda: monomial_key(1))
M = [x, x**2*z**2, x*y, x**2, S.One, y**2, x**3, y, z, x*y**2*z, x**2*y**2]
assert sorted(M, key=monomial_key('lex', [z, y, x])) == \
[S.One, x, x**2, x**3, y, x*y, y**2, x**2*y**2, z, x*y**2*z, x**2*z**2]
assert sorted(M, key=monomial_key('grlex', [z, y, x])) == \
[S.One, x, y, z, x**2, x*y, y**2, x**3, x**2*y**2, x*y**2*z, x**2*z**2]
assert sorted(M, key=monomial_key('grevlex', [z, y, x])) == \
[S.One, x, y, z, x**2, x*y, y**2, x**3, x**2*y**2, x**2*z**2, x*y**2*z]
def test_build_product_order():
assert build_product_order((("grlex", x, y), ("grlex", z, t)), [x, y, z, t])((4, 5, 6, 7)) == \
((9, (4, 5)), (13, (6, 7)))
assert build_product_order((("grlex", x, y), ("grlex", z, t)), [x, y, z, t]) == \
build_product_order((("grlex", x, y), ("grlex", z, t)), [x, y, z, t])
|
cb891eb54e9195075b387fccb9e640d9195da8af6883e384c01c620685da6622 | from sympy.matrices.dense import Matrix
from sympy.polys.polymatrix import PolyMatrix
from sympy.polys import Poly
from sympy import S, ZZ, QQ, EX
from sympy.abc import x
def test_polymatrix():
pm1 = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(x**3, x), Poly(-1 + x, x)]])
v1 = PolyMatrix([[1, 0], [-1, 0]], ring='ZZ[x]')
m1 = Matrix([[1, 0], [-1, 0]], ring='ZZ[x]')
A = PolyMatrix([[Poly(x**2 + x, x), Poly(0, x)], \
[Poly(x**3 - x + 1, x), Poly(0, x)]])
B = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(-x**2, x), Poly(x, x)]])
assert A.ring == ZZ[x]
assert isinstance(pm1*v1, PolyMatrix)
assert pm1*v1 == A
assert pm1*m1 == A
assert v1*pm1 == B
pm2 = PolyMatrix([[Poly(x**2, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**2, x, domain='QQ'), \
Poly(x**3, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**3, x, domain='QQ')]])
assert pm2.ring == QQ[x]
v2 = PolyMatrix([1, 0, 0, 0, 0, 0], ring='ZZ[x]')
m2 = Matrix([1, 0, 0, 0, 0, 0], ring='ZZ[x]')
C = PolyMatrix([[Poly(x**2, x, domain='QQ')]])
assert pm2*v2 == C
assert pm2*m2 == C
pm3 = PolyMatrix([[Poly(x**2, x), S.One]], ring='ZZ[x]')
v3 = S.Half*pm3
assert v3 == PolyMatrix([[Poly(S.Half*x**2, x, domain='QQ'), S.Half]], ring='EX')
assert pm3*S.Half == v3
assert v3.ring == EX
pm4 = PolyMatrix([[Poly(x**2, x, domain='ZZ'), Poly(-x**2, x, domain='ZZ')]])
v4 = Matrix([1, -1], ring='ZZ[x]')
assert pm4*v4 == PolyMatrix([[Poly(2*x**2, x, domain='ZZ')]])
assert len(PolyMatrix()) == 0
assert PolyMatrix([1, 0, 0, 1])/(-1) == PolyMatrix([-1, 0, 0, -1])
|
1145f4c01ee538683e37517b6e30ef2d1d18ddd31ce17650db5aa3e3efa7f16a | """Tests for tools for manipulation of rational expressions. """
from sympy.polys.rationaltools import together
from sympy import S, symbols, Rational, sin, exp, Eq, Integral, Mul
from sympy.abc import x, y, z
A, B = symbols('A,B', commutative=False)
def test_together():
assert together(0) == 0
assert together(1) == 1
assert together(x*y*z) == x*y*z
assert together(x + y) == x + y
assert together(1/x) == 1/x
assert together(1/x + 1) == (x + 1)/x
assert together(1/x + 3) == (3*x + 1)/x
assert together(1/x + x) == (x**2 + 1)/x
assert together(1/x + S.Half) == (x + 2)/(2*x)
assert together(S.Half + x/2) == Mul(S.Half, x + 1, evaluate=False)
assert together(1/x + 2/y) == (2*x + y)/(y*x)
assert together(1/(1 + 1/x)) == x/(1 + x)
assert together(x/(1 + 1/x)) == x**2/(1 + x)
assert together(1/x + 1/y + 1/z) == (x*y + x*z + y*z)/(x*y*z)
assert together(1/(1 + x + 1/y + 1/z)) == y*z/(y + z + y*z + x*y*z)
assert together(1/(x*y) + 1/(x*y)**2) == y**(-2)*x**(-2)*(1 + x*y)
assert together(1/(x*y) + 1/(x*y)**4) == y**(-4)*x**(-4)*(1 + x**3*y**3)
assert together(1/(x**7*y) + 1/(x*y)**4) == y**(-4)*x**(-7)*(x**3 + y**3)
assert together(5/(2 + 6/(3 + 7/(4 + 8/(5 + 9/x))))) == \
Rational(5, 2)*((171 + 119*x)/(279 + 203*x))
assert together(1 + 1/(x + 1)**2) == (1 + (x + 1)**2)/(x + 1)**2
assert together(1 + 1/(x*(1 + x))) == (1 + x*(1 + x))/(x*(1 + x))
assert together(
1/(x*(x + 1)) + 1/(x*(x + 2))) == (3 + 2*x)/(x*(1 + x)*(2 + x))
assert together(1 + 1/(2*x + 2)**2) == (4*(x + 1)**2 + 1)/(4*(x + 1)**2)
assert together(sin(1/x + 1/y)) == sin(1/x + 1/y)
assert together(sin(1/x + 1/y), deep=True) == sin((x + y)/(x*y))
assert together(1/exp(x) + 1/(x*exp(x))) == (1 + x)/(x*exp(x))
assert together(1/exp(2*x) + 1/(x*exp(3*x))) == (1 + exp(x)*x)/(x*exp(3*x))
assert together(Integral(1/x + 1/y, x)) == Integral((x + y)/(x*y), x)
assert together(Eq(1/x + 1/y, 1 + 1/z)) == Eq((x + y)/(x*y), (z + 1)/z)
assert together((A*B)**-1 + (B*A)**-1) == (A*B)**-1 + (B*A)**-1
|
10b080f456103725ef6e29dc1bd26e51e2e6e048372162406a781379926c2558 | """Tests for algorithms for computing symbolic roots of polynomials. """
from sympy import (S, symbols, Symbol, Wild, Rational, sqrt,
powsimp, sin, cos, pi, I, Interval, re, im, exp, ZZ, Piecewise,
acos, root, conjugate)
from sympy.polys import Poly, cyclotomic_poly, intervals, nroots, rootof
from sympy.polys.polyroots import (root_factors, roots_linear,
roots_quadratic, roots_cubic, roots_quartic, roots_cyclotomic,
roots_binomial, preprocess_roots, roots)
from sympy.polys.orthopolys import legendre_poly
from sympy.polys.polyutils import _nsort
from sympy.utilities.iterables import cartes
from sympy.utilities.pytest import raises, slow
from sympy.utilities.randtest import verify_numerically
from sympy.core.compatibility import range
import mpmath
a, b, c, d, e, q, t, x, y, z = symbols('a,b,c,d,e,q,t,x,y,z')
def _check(roots):
# this is the desired invariant for roots returned
# by all_roots. It is trivially true for linear
# polynomials.
nreal = sum([1 if i.is_real else 0 for i in roots])
assert list(sorted(roots[:nreal])) == list(roots[:nreal])
for ix in range(nreal, len(roots), 2):
if not (
roots[ix + 1] == roots[ix] or
roots[ix + 1] == conjugate(roots[ix])):
return False
return True
def test_roots_linear():
assert roots_linear(Poly(2*x + 1, x)) == [Rational(-1, 2)]
def test_roots_quadratic():
assert roots_quadratic(Poly(2*x**2, x)) == [0, 0]
assert roots_quadratic(Poly(2*x**2 + 3*x, x)) == [Rational(-3, 2), 0]
assert roots_quadratic(Poly(2*x**2 + 3, x)) == [-I*sqrt(6)/2, I*sqrt(6)/2]
assert roots_quadratic(Poly(2*x**2 + 4*x + 3, x)) == [-1 - I*sqrt(2)/2, -1 + I*sqrt(2)/2]
_check(Poly(2*x**2 + 4*x + 3, x).all_roots())
f = x**2 + (2*a*e + 2*c*e)/(a - c)*x + (d - b + a*e**2 - c*e**2)/(a - c)
assert roots_quadratic(Poly(f, x)) == \
[-e*(a + c)/(a - c) - sqrt((a*b + c*d - a*d - b*c + 4*a*c*e**2))/(a - c),
-e*(a + c)/(a - c) + sqrt((a*b + c*d - a*d - b*c + 4*a*c*e**2))/(a - c)]
# check for simplification
f = Poly(y*x**2 - 2*x - 2*y, x)
assert roots_quadratic(f) == \
[-sqrt(2*y**2 + 1)/y + 1/y, sqrt(2*y**2 + 1)/y + 1/y]
f = Poly(x**2 + (-y**2 - 2)*x + y**2 + 1, x)
assert roots_quadratic(f) == \
[1,y**2 + 1]
f = Poly(sqrt(2)*x**2 - 1, x)
r = roots_quadratic(f)
assert r == _nsort(r)
# issue 8255
f = Poly(-24*x**2 - 180*x + 264)
assert [w.n(2) for w in f.all_roots(radicals=True)] == \
[w.n(2) for w in f.all_roots(radicals=False)]
for _a, _b, _c in cartes((-2, 2), (-2, 2), (0, -1)):
f = Poly(_a*x**2 + _b*x + _c)
roots = roots_quadratic(f)
assert roots == _nsort(roots)
def test_issue_8438():
p = Poly([1, y, -2, -3], x).as_expr()
roots = roots_cubic(Poly(p, x), x)
z = Rational(-3, 2) - I*Rational(7, 2) # this will fail in code given in commit msg
post = [r.subs(y, z) for r in roots]
assert set(post) == \
set(roots_cubic(Poly(p.subs(y, z), x)))
# /!\ if p is not made an expression, this is *very* slow
assert all(p.subs({y: z, x: i}).n(2, chop=True) == 0 for i in post)
def test_issue_8285():
roots = (Poly(4*x**8 - 1, x)*Poly(x**2 + 1)).all_roots()
assert _check(roots)
f = Poly(x**4 + 5*x**2 + 6, x)
ro = [rootof(f, i) for i in range(4)]
roots = Poly(x**4 + 5*x**2 + 6, x).all_roots()
assert roots == ro
assert _check(roots)
# more than 2 complex roots from which to identify the
# imaginary ones
roots = Poly(2*x**8 - 1).all_roots()
assert _check(roots)
assert len(Poly(2*x**10 - 1).all_roots()) == 10 # doesn't fail
def test_issue_8289():
roots = (Poly(x**2 + 2)*Poly(x**4 + 2)).all_roots()
assert _check(roots)
roots = Poly(x**6 + 3*x**3 + 2, x).all_roots()
assert _check(roots)
roots = Poly(x**6 - x + 1).all_roots()
assert _check(roots)
# all imaginary roots with multiplicity of 2
roots = Poly(x**4 + 4*x**2 + 4, x).all_roots()
assert _check(roots)
def test_issue_14291():
assert Poly(((x - 1)**2 + 1)*((x - 1)**2 + 2)*(x - 1)
).all_roots() == [1, 1 - I, 1 + I, 1 - sqrt(2)*I, 1 + sqrt(2)*I]
p = x**4 + 10*x**2 + 1
ans = [rootof(p, i) for i in range(4)]
assert Poly(p).all_roots() == ans
_check(ans)
def test_issue_13340():
eq = Poly(y**3 + exp(x)*y + x, y, domain='EX')
roots_d = roots(eq)
assert len(roots_d) == 3
def test_issue_14522():
eq = Poly(x**4 + x**3*(16 + 32*I) + x**2*(-285 + 386*I) + x*(-2824 - 448*I) - 2058 - 6053*I, x)
roots_eq = roots(eq)
assert all(eq(r) == 0 for r in roots_eq)
def test_issue_15076():
sol = roots_quartic(Poly(t**4 - 6*t**2 + t/x - 3, t))
assert sol[0].has(x)
def test_issue_16589():
eq = Poly(x**4 - 8*sqrt(2)*x**3 + 4*x**3 - 64*sqrt(2)*x**2 + 1024*x, x)
roots_eq = roots(eq)
assert 0 in roots_eq
def test_roots_cubic():
assert roots_cubic(Poly(2*x**3, x)) == [0, 0, 0]
assert roots_cubic(Poly(x**3 - 3*x**2 + 3*x - 1, x)) == [1, 1, 1]
assert roots_cubic(Poly(x**3 + 1, x)) == \
[-1, S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]
assert roots_cubic(Poly(2*x**3 - 3*x**2 - 3*x - 1, x))[0] == \
S.Half + 3**Rational(1, 3)/2 + 3**Rational(2, 3)/2
eq = -x**3 + 2*x**2 + 3*x - 2
assert roots(eq, trig=True, multiple=True) == \
roots_cubic(Poly(eq, x), trig=True) == [
Rational(2, 3) + 2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3,
-2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + Rational(2, 3),
-2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + Rational(2, 3),
]
def test_roots_quartic():
assert roots_quartic(Poly(x**4, x)) == [0, 0, 0, 0]
assert roots_quartic(Poly(x**4 + x**3, x)) in [
[-1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, -1]
]
assert roots_quartic(Poly(x**4 - x**3, x)) in [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
]
lhs = roots_quartic(Poly(x**4 + x, x))
rhs = [S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2, S.Zero, -S.One]
assert sorted(lhs, key=hash) == sorted(rhs, key=hash)
# test of all branches of roots quartic
for i, (a, b, c, d) in enumerate([(1, 2, 3, 0),
(3, -7, -9, 9),
(1, 2, 3, 4),
(1, 2, 3, 4),
(-7, -3, 3, -6),
(-3, 5, -6, -4),
(6, -5, -10, -3)]):
if i == 2:
c = -a*(a**2/S(8) - b/S(2))
elif i == 3:
d = a*(a*(a**2*Rational(3, 256) - b/S(16)) + c/S(4))
eq = x**4 + a*x**3 + b*x**2 + c*x + d
ans = roots_quartic(Poly(eq, x))
assert all(eq.subs(x, ai).n(chop=True) == 0 for ai in ans)
# not all symbolic quartics are unresolvable
eq = Poly(q*x + q/4 + x**4 + x**3 + 2*x**2 - Rational(1, 3), x)
sol = roots_quartic(eq)
assert all(verify_numerically(eq.subs(x, i), 0) for i in sol)
z = symbols('z', negative=True)
eq = x**4 + 2*x**3 + 3*x**2 + x*(z + 11) + 5
zans = roots_quartic(Poly(eq, x))
assert all([verify_numerically(eq.subs(((x, i), (z, -1))), 0) for i in zans])
# but some are (see also issue 4989)
# it's ok if the solution is not Piecewise, but the tests below should pass
eq = Poly(y*x**4 + x**3 - x + z, x)
ans = roots_quartic(eq)
assert all(type(i) == Piecewise for i in ans)
reps = (
dict(y=Rational(-1, 3), z=Rational(-1, 4)), # 4 real
dict(y=Rational(-1, 3), z=Rational(-1, 2)), # 2 real
dict(y=Rational(-1, 3), z=-2)) # 0 real
for rep in reps:
sol = roots_quartic(Poly(eq.subs(rep), x))
assert all([verify_numerically(w.subs(rep) - s, 0) for w, s in zip(ans, sol)])
def test_roots_cyclotomic():
assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1]
assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1]
assert roots_cyclotomic(cyclotomic_poly(
3, x, polys=True)) == [Rational(-1, 2) - I*sqrt(3)/2, Rational(-1, 2) + I*sqrt(3)/2]
assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I]
assert roots_cyclotomic(cyclotomic_poly(
6, x, polys=True)) == [S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]
assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [
-cos(pi/7) - I*sin(pi/7),
-cos(pi/7) + I*sin(pi/7),
-cos(pi*Rational(3, 7)) - I*sin(pi*Rational(3, 7)),
-cos(pi*Rational(3, 7)) + I*sin(pi*Rational(3, 7)),
cos(pi*Rational(2, 7)) - I*sin(pi*Rational(2, 7)),
cos(pi*Rational(2, 7)) + I*sin(pi*Rational(2, 7)),
]
assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [
-sqrt(2)/2 - I*sqrt(2)/2,
-sqrt(2)/2 + I*sqrt(2)/2,
sqrt(2)/2 - I*sqrt(2)/2,
sqrt(2)/2 + I*sqrt(2)/2,
]
assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [
-sqrt(3)/2 - I/2,
-sqrt(3)/2 + I/2,
sqrt(3)/2 - I/2,
sqrt(3)/2 + I/2,
]
assert roots_cyclotomic(
cyclotomic_poly(1, x, polys=True), factor=True) == [1]
assert roots_cyclotomic(
cyclotomic_poly(2, x, polys=True), factor=True) == [-1]
assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == \
[-root(-1, 3), -1 + root(-1, 3)]
assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == \
[-I, I]
assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == \
[-root(-1, 5), -root(-1, 5)**3, root(-1, 5)**2, -1 - root(-1, 5)**2 + root(-1, 5) + root(-1, 5)**3]
assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == \
[1 - root(-1, 3), root(-1, 3)]
def test_roots_binomial():
assert roots_binomial(Poly(5*x, x)) == [0]
assert roots_binomial(Poly(5*x**4, x)) == [0, 0, 0, 0]
assert roots_binomial(Poly(5*x + 2, x)) == [Rational(-2, 5)]
A = 10**Rational(3, 4)/10
assert roots_binomial(Poly(5*x**4 + 2, x)) == \
[-A - A*I, -A + A*I, A - A*I, A + A*I]
_check(roots_binomial(Poly(x**8 - 2)))
a1 = Symbol('a1', nonnegative=True)
b1 = Symbol('b1', nonnegative=True)
r0 = roots_quadratic(Poly(a1*x**2 + b1, x))
r1 = roots_binomial(Poly(a1*x**2 + b1, x))
assert powsimp(r0[0]) == powsimp(r1[0])
assert powsimp(r0[1]) == powsimp(r1[1])
for a, b, s, n in cartes((1, 2), (1, 2), (-1, 1), (2, 3, 4, 5)):
if a == b and a != 1: # a == b == 1 is sufficient
continue
p = Poly(a*x**n + s*b)
ans = roots_binomial(p)
assert ans == _nsort(ans)
# issue 8813
assert roots(Poly(2*x**3 - 16*y**3, x)) == {
2*y*(Rational(-1, 2) - sqrt(3)*I/2): 1,
2*y: 1,
2*y*(Rational(-1, 2) + sqrt(3)*I/2): 1}
def test_roots_preprocessing():
f = a*y*x**2 + y - b
coeff, poly = preprocess_roots(Poly(f, x))
assert coeff == 1
assert poly == Poly(a*y*x**2 + y - b, x)
f = c**3*x**3 + c**2*x**2 + c*x + a
coeff, poly = preprocess_roots(Poly(f, x))
assert coeff == 1/c
assert poly == Poly(x**3 + x**2 + x + a, x)
f = c**3*x**3 + c**2*x**2 + a
coeff, poly = preprocess_roots(Poly(f, x))
assert coeff == 1/c
assert poly == Poly(x**3 + x**2 + a, x)
f = c**3*x**3 + c*x + a
coeff, poly = preprocess_roots(Poly(f, x))
assert coeff == 1/c
assert poly == Poly(x**3 + x + a, x)
f = c**3*x**3 + a
coeff, poly = preprocess_roots(Poly(f, x))
assert coeff == 1/c
assert poly == Poly(x**3 + a, x)
E, F, J, L = symbols("E,F,J,L")
f = -21601054687500000000*E**8*J**8/L**16 + \
508232812500000000*F*x*E**7*J**7/L**14 - \
4269543750000000*E**6*F**2*J**6*x**2/L**12 + \
16194716250000*E**5*F**3*J**5*x**3/L**10 - \
27633173750*E**4*F**4*J**4*x**4/L**8 + \
14840215*E**3*F**5*J**3*x**5/L**6 + \
54794*E**2*F**6*J**2*x**6/(5*L**4) - \
1153*E*J*F**7*x**7/(80*L**2) + \
633*F**8*x**8/160000
coeff, poly = preprocess_roots(Poly(f, x))
assert coeff == 20*E*J/(F*L**2)
assert poly == 633*x**8 - 115300*x**7 + 4383520*x**6 + 296804300*x**5 - 27633173750*x**4 + \
809735812500*x**3 - 10673859375000*x**2 + 63529101562500*x - 135006591796875
f = Poly(-y**2 + x**2*exp(x), y, domain=ZZ[x, exp(x)])
g = Poly(-y**2 + exp(x), y, domain=ZZ[exp(x)])
assert preprocess_roots(f) == (x, g)
def test_roots0():
assert roots(1, x) == {}
assert roots(x, x) == {S.Zero: 1}
assert roots(x**9, x) == {S.Zero: 9}
assert roots(((x - 2)*(x + 3)*(x - 4)).expand(), x) == {-S(3): 1, S(2): 1, S(4): 1}
assert roots(2*x + 1, x) == {Rational(-1, 2): 1}
assert roots((2*x + 1)**2, x) == {Rational(-1, 2): 2}
assert roots((2*x + 1)**5, x) == {Rational(-1, 2): 5}
assert roots((2*x + 1)**10, x) == {Rational(-1, 2): 10}
assert roots(x**4 - 1, x) == {I: 1, S.One: 1, -S.One: 1, -I: 1}
assert roots((x**4 - 1)**2, x) == {I: 2, S.One: 2, -S.One: 2, -I: 2}
assert roots(((2*x - 3)**2).expand(), x) == {Rational( 3, 2): 2}
assert roots(((2*x + 3)**2).expand(), x) == {Rational(-3, 2): 2}
assert roots(((2*x - 3)**3).expand(), x) == {Rational( 3, 2): 3}
assert roots(((2*x + 3)**3).expand(), x) == {Rational(-3, 2): 3}
assert roots(((2*x - 3)**5).expand(), x) == {Rational( 3, 2): 5}
assert roots(((2*x + 3)**5).expand(), x) == {Rational(-3, 2): 5}
assert roots(((a*x - b)**5).expand(), x) == { b/a: 5}
assert roots(((a*x + b)**5).expand(), x) == {-b/a: 5}
assert roots(x**2 + (-a - 1)*x + a, x) == {a: 1, S.One: 1}
assert roots(x**4 - 2*x**2 + 1, x) == {S.One: 2, S.NegativeOne: 2}
assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \
{S.One: 2, -1 - sqrt(2): 1, S.Zero: 2, -1 + sqrt(2): 1}
assert roots(x**8 - 1, x) == {
sqrt(2)/2 + I*sqrt(2)/2: 1,
sqrt(2)/2 - I*sqrt(2)/2: 1,
-sqrt(2)/2 + I*sqrt(2)/2: 1,
-sqrt(2)/2 - I*sqrt(2)/2: 1,
S.One: 1, -S.One: 1, I: 1, -I: 1
}
f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \
224*x**7 - 384*x**8 - 64*x**9
assert roots(f) == {S.Zero: 2, -S(2): 2, S(2): 1, Rational(-7, 2): 1,
Rational(-3, 2): 1, Rational(-1, 2): 1, Rational(3, 2): 1}
assert roots((a + b + c)*x - (a + b + c + d), x) == {(a + b + c + d)/(a + b + c): 1}
assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {}
assert roots(((x - 2)*(
x + 3)*(x - 4)).expand(), x, cubics=False) == {-S(3): 1, S(2): 1, S(4): 1}
assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \
{-S(3): 1, S(2): 1, S(4): 1, S(5): 1}
assert roots(x**3 + 2*x**2 + 4*x + 8, x) == {-S(2): 1, -2*I: 1, 2*I: 1}
assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \
{-2*I: 1, 2*I: 1, -S(2): 1}
assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x ) == \
{S.One: 1, S.Zero: 1, -S(2): 1, -2*I: 1, 2*I: 1}
r1_2, r1_3 = S.Half, Rational(1, 3)
x0 = (3*sqrt(33) + 19)**r1_3
x1 = 4/x0/3
x2 = x0/3
x3 = sqrt(3)*I/2
x4 = x3 - r1_2
x5 = -x3 - r1_2
assert roots(x**3 + x**2 - x + 1, x, cubics=True) == {
-x1 - x2 - r1_3: 1,
-x1/x4 - x2*x4 - r1_3: 1,
-x1/x5 - x2*x5 - r1_3: 1,
}
f = (x**2 + 2*x + 3).subs(x, 2*x**2 + 3*x).subs(x, 5*x - 4)
r13_20, r1_20 = [ Rational(*r)
for r in ((13, 20), (1, 20)) ]
s2 = sqrt(2)
assert roots(f, x) == {
r13_20 + r1_20*sqrt(1 - 8*I*s2): 1,
r13_20 - r1_20*sqrt(1 - 8*I*s2): 1,
r13_20 + r1_20*sqrt(1 + 8*I*s2): 1,
r13_20 - r1_20*sqrt(1 + 8*I*s2): 1,
}
f = x**4 + x**3 + x**2 + x + 1
r1_4, r1_8, r5_8 = [ Rational(*r) for r in ((1, 4), (1, 8), (5, 8)) ]
assert roots(f, x) == {
-r1_4 + r1_4*5**r1_2 + I*(r5_8 + r1_8*5**r1_2)**r1_2: 1,
-r1_4 + r1_4*5**r1_2 - I*(r5_8 + r1_8*5**r1_2)**r1_2: 1,
-r1_4 - r1_4*5**r1_2 + I*(r5_8 - r1_8*5**r1_2)**r1_2: 1,
-r1_4 - r1_4*5**r1_2 - I*(r5_8 - r1_8*5**r1_2)**r1_2: 1,
}
f = z**3 + (-2 - y)*z**2 + (1 + 2*y - 2*x**2)*z - y + 2*x**2
assert roots(f, z) == {
S.One: 1,
S.Half + S.Half*y + S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1,
S.Half + S.Half*y - S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1,
}
assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=False) == {}
assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=True) != {}
assert roots(x**4 - 1, x, filter='Z') == {S.One: 1, -S.One: 1}
assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1}
assert roots((x - 1)*(x + 1), x) == {S.One: 1, -S.One: 1}
assert roots(
(x - 1)*(x + 1), x, predicate=lambda r: r.is_positive) == {S.One: 1}
assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-S.One, S.One]
assert roots(x**4 - 1, x, filter='I', multiple=True) == [I, -I]
assert roots(x**3, x, multiple=True) == [S.Zero, S.Zero, S.Zero]
assert roots(1234, x, multiple=True) == []
f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1
assert roots(f) == {
-I*sin(pi/7) + cos(pi/7): 1,
-I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1,
-I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1,
I*sin(pi/7) + cos(pi/7): 1,
I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1,
I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1,
}
g = ((x**2 + 1)*f**2).expand()
assert roots(g) == {
-I*sin(pi/7) + cos(pi/7): 2,
-I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2,
-I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2,
I*sin(pi/7) + cos(pi/7): 2,
I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2,
I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2,
-I: 1, I: 1,
}
r = roots(x**3 + 40*x + 64)
real_root = [rx for rx in r if rx.is_real][0]
cr = 108 + 6*sqrt(1074)
assert real_root == -2*root(cr, 3)/3 + 20/root(cr, 3)
eq = Poly((7 + 5*sqrt(2))*x**3 + (-6 - 4*sqrt(2))*x**2 + (-sqrt(2) - 1)*x + 2, x, domain='EX')
assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2*sqrt(2): 1, -sqrt(2) + 1: 1}
eq = Poly(41*x**5 + 29*sqrt(2)*x**5 - 153*x**4 - 108*sqrt(2)*x**4 +
175*x**3 + 125*sqrt(2)*x**3 - 45*x**2 - 30*sqrt(2)*x**2 - 26*sqrt(2)*x -
26*x + 24, x, domain='EX')
assert roots(eq) == {-sqrt(2) + 1: 1, -2 + 2*sqrt(2): 1, -1 + sqrt(2): 1,
-4 + 4*sqrt(2): 1, -3 + 3*sqrt(2): 1}
eq = Poly(x**3 - 2*x**2 + 6*sqrt(2)*x**2 - 8*sqrt(2)*x + 23*x - 14 +
14*sqrt(2), x, domain='EX')
assert roots(eq) == {-2*sqrt(2) + 2: 1, -2*sqrt(2) + 1: 1, -2*sqrt(2) - 1: 1}
assert roots(Poly((x + sqrt(2))**3 - 7, x, domain='EX')) == \
{-sqrt(2) - root(7, 3)/2 - sqrt(3)*root(7, 3)*I/2: 1,
-sqrt(2) - root(7, 3)/2 + sqrt(3)*root(7, 3)*I/2: 1,
-sqrt(2) + root(7, 3): 1}
def test_roots_slow():
"""Just test that calculating these roots does not hang. """
a, b, c, d, x = symbols("a,b,c,d,x")
f1 = x**2*c + (a/b) + x*c*d - a
f2 = x**2*(a + b*(c - d)*a) + x*a*b*c/(b*d - d) + (a*d - c/d)
assert list(roots(f1, x).values()) == [1, 1]
assert list(roots(f2, x).values()) == [1, 1]
(zz, yy, xx, zy, zx, yx, k) = symbols("zz,yy,xx,zy,zx,yx,k")
e1 = (zz - k)*(yy - k)*(xx - k) + zy*yx*zx + zx - zy - yx
e2 = (zz - k)*yx*yx + zx*(yy - k)*zx + zy*zy*(xx - k)
assert list(roots(e1 - e2, k).values()) == [1, 1, 1]
f = x**3 + 2*x**2 + 8
R = list(roots(f).keys())
assert not any(i for i in [f.subs(x, ri).n(chop=True) for ri in R])
def test_roots_inexact():
R1 = roots(x**2 + x + 1, x, multiple=True)
R2 = roots(x**2 + x + 1.0, x, multiple=True)
for r1, r2 in zip(R1, R2):
assert abs(r1 - r2) < 1e-12
f = x**4 + 3.0*sqrt(2.0)*x**3 - (78.0 + 24.0*sqrt(3.0))*x**2 \
+ 144.0*(2*sqrt(3.0) + 9.0)
R1 = roots(f, multiple=True)
R2 = (-12.7530479110482, -3.85012393732929,
4.89897948556636, 7.46155167569183)
for r1, r2 in zip(R1, R2):
assert abs(r1 - r2) < 1e-10
def test_roots_preprocessed():
E, F, J, L = symbols("E,F,J,L")
f = -21601054687500000000*E**8*J**8/L**16 + \
508232812500000000*F*x*E**7*J**7/L**14 - \
4269543750000000*E**6*F**2*J**6*x**2/L**12 + \
16194716250000*E**5*F**3*J**5*x**3/L**10 - \
27633173750*E**4*F**4*J**4*x**4/L**8 + \
14840215*E**3*F**5*J**3*x**5/L**6 + \
54794*E**2*F**6*J**2*x**6/(5*L**4) - \
1153*E*J*F**7*x**7/(80*L**2) + \
633*F**8*x**8/160000
assert roots(f, x) == {}
R1 = roots(f.evalf(), x, multiple=True)
R2 = [-1304.88375606366, 97.1168816800648, 186.946430171876, 245.526792947065,
503.441004174773, 791.549343830097, 1273.16678129348, 1850.10650616851]
w = Wild('w')
p = w*E*J/(F*L**2)
assert len(R1) == len(R2)
for r1, r2 in zip(R1, R2):
match = r1.match(p)
assert match is not None and abs(match[w] - r2) < 1e-10
def test_roots_mixed():
f = -1936 - 5056*x - 7592*x**2 + 2704*x**3 - 49*x**4
_re, _im = intervals(f, all=True)
_nroots = nroots(f)
_sroots = roots(f, multiple=True)
_re = [ Interval(a, b) for (a, b), _ in _re ]
_im = [ Interval(re(a), re(b))*Interval(im(a), im(b)) for (a, b),
_ in _im ]
_intervals = _re + _im
_sroots = [ r.evalf() for r in _sroots ]
_nroots = sorted(_nroots, key=lambda x: x.sort_key())
_sroots = sorted(_sroots, key=lambda x: x.sort_key())
for _roots in (_nroots, _sroots):
for i, r in zip(_intervals, _roots):
if r.is_real:
assert r in i
else:
assert (re(r), im(r)) in i
def test_root_factors():
assert root_factors(Poly(1, x)) == [Poly(1, x)]
assert root_factors(Poly(x, x)) == [Poly(x, x)]
assert root_factors(x**2 - 1, x) == [x + 1, x - 1]
assert root_factors(x**2 - y, x) == [x - sqrt(y), x + sqrt(y)]
assert root_factors((x**4 - 1)**2) == \
[x + 1, x + 1, x - 1, x - 1, x - I, x - I, x + I, x + I]
assert root_factors(Poly(x**4 - 1, x), filter='Z') == \
[Poly(x + 1, x), Poly(x - 1, x), Poly(x**2 + 1, x)]
assert root_factors(8*x**2 + 12*x**4 + 6*x**6 + x**8, x, filter='Q') == \
[x, x, x**6 + 6*x**4 + 12*x**2 + 8]
@slow
def test_nroots1():
n = 64
p = legendre_poly(n, x, polys=True)
raises(mpmath.mp.NoConvergence, lambda: p.nroots(n=3, maxsteps=5))
roots = p.nroots(n=3)
# The order of roots matters. They are ordered from smallest to the
# largest.
assert [str(r) for r in roots] == \
['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961',
'-0.946', '-0.930', '-0.911', '-0.889', '-0.866', '-0.841',
'-0.813', '-0.784', '-0.753', '-0.720', '-0.685', '-0.649',
'-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402',
'-0.357', '-0.311', '-0.265', '-0.217', '-0.170', '-0.121',
'-0.0730', '-0.0243', '0.0243', '0.0730', '0.121', '0.170',
'0.217', '0.265', '0.311', '0.357', '0.402', '0.446', '0.489',
'0.531', '0.572', '0.611', '0.649', '0.685', '0.720', '0.753',
'0.784', '0.813', '0.841', '0.866', '0.889', '0.911', '0.930',
'0.946', '0.961', '0.973', '0.983', '0.991', '0.996', '0.999']
def test_nroots2():
p = Poly(x**5 + 3*x + 1, x)
roots = p.nroots(n=3)
# The order of roots matters. The roots are ordered by their real
# components (if they agree, then by their imaginary components),
# with real roots appearing first.
assert [str(r) for r in roots] == \
['-0.332', '-0.839 - 0.944*I', '-0.839 + 0.944*I',
'1.01 - 0.937*I', '1.01 + 0.937*I']
roots = p.nroots(n=5)
assert [str(r) for r in roots] == \
['-0.33199', '-0.83907 - 0.94385*I', '-0.83907 + 0.94385*I',
'1.0051 - 0.93726*I', '1.0051 + 0.93726*I']
def test_roots_composite():
assert len(roots(Poly(y**3 + y**2*sqrt(x) + y + x, y, composite=True))) == 3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.