Diofant’s documentation¶
Diofant is a Python library for symbolic mathematics. If you are new to Diofant, start with the Tutorial.
This is the central page for all of Diofant’s documentation.
Note
Documentation examples assume (unless otherwise clearly stated) that these statements were executed in the beginning of the interactive session:
>>> from diofant import *
>>> a, b, c, d, x, y, z, t = symbols('a b c d x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
Installation¶
The Diofant can be installed on any computer with Python 3.7 or above. You can install latest release with pip:
pip install diofant
or to install also extra dependencies:
pip install diofant[gmpy,plot]
Tip
Use venv
to create isolated Python environment first,
instead of installing everything systemwide.
To use Unicode pretty printing — configure your system to have good TTF fonts. The DejaVu Sans Mono seems to be an acceptable choice. On Debian you can install this font package with:
apt install fontsdejavu
From Sources¶
If you are a developer or like to get the latest updates as they come, be sure to install from git:
git clone git://github.com/diofant/diofant.git
cd diofant
pip install e .[develop,docs]
Note
Diofant requires setuptools for installation from sources.
Run Diofant¶
To verify that your freshlyinstalled Diofant works, please start up the Python interpreter and execute some simple statements like the ones below:
>>> from diofant.abc import x
>>> ((1 + x)**(1/x)).limit(x, 0)
E
Tip
Use IPython for interactive work. Please refer to the
documentation of module interactive
for details
of available configuration settings.
For a starter guide on using Diofant, refer to the Tutorial.
Also, you may want to run full set of unit tests to make sure everything works:
py.test pyargs diofant
pytest and some other packages are required for testing, so be sure to install the Diofant first with extra dependecies:
pip install diofant[tests]
Feedback¶
If you think there’s a bug, you have a question or you would like to request a feature, please open an issue ticket. General questions and comments can be sent to the Diofant mailing list.
Tutorial¶
Warning
It assumed that the reader already knows the Python programming language. If you do not, please start from the Python tutorial.
This tutorial aims to give an introduction to Diofant for someone who has not used the library before. Many features will be introduced in this tutorial, but they will not be exhaustive. In fact, virtually every functionality shown here will have more options or capabilities than what will be shown. The rest of documentation serves as API documentation, which extensively lists every feature and option of each function.
Introduction¶
Symbolic computation deals with the computation of mathematical objects symbolically. This means that the mathematical objects are represented exactly, not approximately, and mathematical expressions with unevaluated variables are left in symbolic form.
Let’s take an example. Say we wanted to use the builtin Python functions to compute square roots. We might do something like this
>>> import math
>>> math.sqrt(9)
3.0
Here we got the exact answer — 9 is a perfect square — but usually it will be an approximate result
>>> math.sqrt(8)
2.8284271247461903
This is where symbolic computation first comes in: with a symbolic computation system like Diofant, square roots of numbers that are not perfect squares are left unevaluated by default
>>> import diofant
>>> diofant.sqrt(3)
sqrt(3)
Furthermore — and this is where we start to see the real power of symbolic computation — results can be symbolically simplified.
>>> diofant.sqrt(8)
2*sqrt(2)
Yet we can also approximate this number with any precision
>>> _.evalf(20)
2.8284271247461900976
The above example starts to show how we can manipulate irrational numbers exactly using Diofant. Now we introduce symbols.
Let us define a symbolic expression, representing the mathematical expression \(x + 2y\).
>>> x, y = diofant.symbols('x y')
>>> expr = x + 2*y
>>> expr
x + 2*y
Note
Unlike many symbolic manipulation systems you may have used, in
Diofant, symbols are not defined automatically. To define symbols,
we must use symbols()
, that takes a
string of symbol names separated by spaces or commas, and creates
Symbol
instances out of them.
Note that we wrote x + 2*y
, using Python’s mathematical syntax,
just as we would if x
and y
were ordinary Python variables.
But in this case, instead of evaluating to something, the expression
remains as just x + 2*y
. Now let us play around with it:
>>> expr + 1
x + 2*y + 1
>>> expr  x
2*y
Notice something in the above example. When we typed expr  x
, we
did not get x + 2*y  x
, but rather just 2*y
. The x
and
the x
automatically canceled one another. This is similar to how
sqrt(8)
automatically turned into 2*sqrt(2)
above.
Tip
Use evaluate()
context or evaluate
flag to prevent automatic evaluation, for example:
>>> diofant.sqrt(8, evaluate=False)
sqrt(8)
>>> _.doit()
2*sqrt(2)
This isn’t always the case in Diofant, however:
>>> x*expr
x*(x + 2*y)
Here, we might have expected \(x(x + 2y)\) to transform into \(x^2 + 2xy\), but instead we see that the expression was left alone. This is a common theme in Diofant. Aside from obvious simplifications like \(x  x = 0\) and \(\sqrt{8} = 2\sqrt{2}\), most simplifications are not performed automatically. This is because we might prefer the factored form \(x(x + 2y)\), or we might prefer the expanded form \(x^2 + 2xy\) — both forms are useful in different circumstances. In Diofant, there are functions to go from one form to the other
>>> diofant.expand(x*expr)
x**2 + 2*x*y
>>> diofant.factor(_)
x*(x + 2*y)
The real power of a symbolic computation system (which by the way, are also often called computer algebra systems, or just CASs) such as Diofant is the ability to do all sorts of computations symbolically: simplify expressions, compute derivatives, integrals, and limits, solve equations, work with matrices, and much more. Diofant includes modules for plotting, printing (like 2D pretty printed output of math formulas, or \(\LaTeX\)), code generation, statistics, combinatorics, number theory, logic, and more. Here is a small sampling of the sort of symbolic power Diofant is capable of, to whet your appetite.
Note
From here on in this tutorial we assume that these statements were executed:
>>> from diofant import *
>>> x, y, z = symbols('x y z')
>>> init_printing(pretty_print=True, use_unicode=True)
Last one will make all further examples pretty print with unicode characters.
import *
has been used here to aid the readability of the
tutorial, but is best to avoid such wildcard import statements in
production code, as they make it unclear which names are present in
the namespace.
Take the derivative of \(\sin{(x)}e^x\).
>>> diff(sin(x)*exp(x), x)
x x
ℯ ⋅sin(x) + ℯ ⋅cos(x)
Compute \(\int(e^x\sin{(x)} + e^x\cos{(x)})\,dx\).
>>> integrate(exp(x)*sin(x) + exp(x)*cos(x), x)
x
ℯ ⋅sin(x)
Compute \(\int_{\infty}^\infty \sin{(x^2)}\,dx\).
>>> integrate(sin(x**2), (x, oo, oo))
___ ___
╲╱ 2 ⋅╲╱ π
───────────
2
Find \(\lim_{x\to 0^+}\frac{\sin{(x)}}{x}\).
>>> limit(sin(x)/x, x, 0)
1
Solve \(x^2  2 = 0\).
>>> solve(x**2  2, x)
⎡⎧ ___⎫ ⎧ ___⎫⎤
⎢⎨x: ╲╱ 2 ⎬, ⎨x: ╲╱ 2 ⎬⎥
⎣⎩ ⎭ ⎩ ⎭⎦
Solve the differential equation \(f''  f = e^x\).
>>> f = symbols('f', cls=Function)
>>> dsolve(Eq(f(x).diff(x, 2)  f(x), exp(x)), f(x))
x ⎛ x⎞ x
f(x) = ℯ ⋅⎜C₂ + ─⎟ + ℯ ⋅C₁
⎝ 2⎠
Find the eigenvalues of \(\left[\begin{smallmatrix}1 & 2\\2 & 2\end{smallmatrix}\right]\).
>>> Matrix([[1, 2], [2, 2]]).eigenvals()
⎧ ____ ____ ⎫
⎪3 ╲╱ 17 ╲╱ 17 3 ⎪
⎨─ + ──────: 1,  ────── + ─: 1⎬
⎪2 2 2 2 ⎪
⎩ ⎭
Rewrite the Bessel function \(J_{n}\left(z\right)\) in terms of the spherical Bessel function \(j_n(z)\).
>>> n = symbols('n')
>>> besselj(n, z).rewrite(jn)
___ ___
╲╱ 2 ⋅╲╱ z ⋅jn(n  1/2, z)
──────────────────────────
___
╲╱ π
Print \(\int_{0}^{\pi} \cos^{2}{\left (x \right )}\, dx\) using \(\LaTeX\).
>>> latex(Integral(cos(x)**2, (x, 0, pi)))
'\\int_{0}^{\\pi} \\cos^{2}{\\left (x \\right )}\\, dx'
Basics¶
Here we discuss some of the most basic aspects of expression manipulation in Diofant.
Assumptions¶
The assumptions system allows users to declare certain mathematical properties on symbols, such as being positive, imaginary or integer.
By default, all symbols are complex valued. This assumption makes it easier to treat mathematical problems in full generality.
>>> sqrt(x**2)
____
╱ 2
╲╱ x
Yet obviously we can simplify above expression if some additional
mathematical properties on x
are assumed. This is where
assumptions system come into play.
Assumptions are set on Symbol
objects
when they are created. For instance, we can create a symbol that is
assumed to be positive.
>>> p = symbols('p', positive=True)
And then, certain simplifications will be possible:
>>> sqrt(p**2)
p
The assumptions system additionally has deductive capabilities. You
might check assumptions on any expression with is_assumption
attributes, like is_positive
.
>>> p.is_positive
True
>>> (1 + p).is_positive
True
>>> (p).is_positive
False
Note
False
is returned also if certain assumption doesn’t make sense
for given object.
In a threevalued logic, used by system, None
represents the
“unknown” case.
>>> (p  1).is_positive is None
True
Substitution¶
One of the most common things you might want to do with a mathematical
expression is substitution with subs()
method. It replaces all instances of something in an expression with
something else.
>>> expr = cos(x) + 1
>>> expr.subs({x: y})
cos(y) + 1
>>> expr
cos(x) + 1
We see that performing substitution leaves original expression
expr
unchanged.
Note
Almost all Diofant expressions are immutable. No function (or method) will change them inplace.
Use several method calls to perform a sequence of substitutions in same variable:
>>> x**y
y
x
>>> _.subs({y: x**y}).subs({y: x**x})
⎛ ⎛ x⎞⎞
⎜ ⎝x ⎠⎟
⎝x ⎠
x
Use flag simultaneous
to do all substitutions at once.
>>> (x  y).subs({x: y, y: x})
0
>>> (x  y).subs({x: y, y: x}, simultaneous=True)
x + y
Numerics¶
To evaluate a numerical expression into a floating point number with
arbitrary precision, use evalf()
.
By default, 15 digits of precision are used.
>>> expr = sqrt(8)
>>> expr.evalf()
2.82842712474619
But you can change that. Let’s compute the first 70 digits of \(\pi\).
>>> pi.evalf(70)
3.141592653589793238462643383279502884197169399375105820974944592307816
Complex numbers are supported:
>>> (1/(pi + I)).evalf()
0.289025482222236  0.0919996683503752⋅ⅈ
If the expression contains symbols or for some other reason cannot be evaluated
numerically, calling evalf()
returns the
original expression or a partially evaluated expression.
>>> (pi*x**2 + x/3).evalf()
2
3.14159265358979⋅x + 0.333333333333333⋅x
You can also use the standard Python functions float
and
complex
to convert symbolic expressions to regular Python numbers:
>>> float(pi)
3.141592653589793
>>> complex(pi + E*I)
(3.141592653589793+2.718281828459045j)
Sometimes there are roundoff errors smaller than the desired precision
that remain after an expression is evaluated. Such numbers can be
removed by setting the chop
flag.
>>> one = cos(1)**2 + sin(1)**2
>>> (one  1).evalf(strict=False)
0.e146
>>> (one  1).evalf(chop=True)
0
Discussed above method is not effective enough if you intend to evaluate an expression at many points, there are better ways, especially if you only care about machine precision.
Substitution may be used to evaluate an expression for some floating point number
>>> expr = sin(x)/x
>>> expr.subs({x: 0.1})
0.998334166468282
but this method is slow.
The easiest way to convert an expression to the form that can be numerically
evaluated with libraries like numpy
or the standard library math
module — use the lambdify()
function.
>>> f = lambdify(x, expr, "math")
>>> f(0.1)
0.9983341664682815
Using the numpy
library gives the generated function access to powerful
vectorized ufuncs that are backed by compiled C code.
>>> f = lambdify(x, expr, "numpy")
>>> f(range(1, 5))
[ 0.84147098 0.45464871 0.04704 0.18920062]
Gotchas¶
Lets recall again, that Diofant is nothing more than a Python library,
like numpy
or even the Python standard library module
sys
. What this means is that Diofant does not add anything to
the Python language. Limitations that are inherent in the language
are also inherent in Diofant.
In this section we are trying to collect some things that could surprise newcomers.
Numbers¶
To begin with, it should be clear for you, that if you type a numeric
literal — it will create a Python number of type int
or
float
.
Diofant uses its own classes for numbers, for example
Integer
instead of int
. In
most cases, Python numeric types will be correctly coersed to Diofant
numbers during expression construction.
>>> 3 + x**2
2
x + 3
>>> type(_  x**2)
<class 'diofant.core.numbers.Integer'>
But if you use some arithmetic operators between two numerical literals, Python will evaluate such expression before Diofant has a chance to get to them.
>>> x**(3/2)
1.5
x
Tip
While working in the IPython console, you could use
IntegerDivisionWrapper
AST
transformer to wrap all integer divisions with
Rational
automatically.
The universal solution is using correct Diofant numeric class to
construct numbers explicitly. For example,
Rational
in the above example
>>> x**Rational(3, 2)
3/2
x
Equality¶
You may think that ==
, which is used for equality testing in
Python, is used for Diofant to test mathematical equality. This is
not quite correct either. Let us see what happens when we use ==
.
>>> (x + 1)**2 == x**2 + 2*x + 1
False
But, \((x + 1)^2\) does equal \(x^2 + 2x + 1\). What is going on here?
In Diofant, ==
represents structural equality testing and \((x +
1)^2\) and \(x^2 + 2x + 1\) are not the same in this sense. One is the
power and the other is the addition of three terms.
There is a separate class, called
Eq
, which can be used to create a
symbolic equation
>>> Eq((x + 1)**2  x**2, 2*x + 1)
2 2
 x + (x + 1) = 2⋅x + 1
It is not always return a bool
object, like ==
, but you
may use some simplification methods to prove (or disprove) equation.
>>> expand(_)
true
Printing¶
As we have already seen, Diofant can pretty print its output using Unicode characters. This is a short introduction to the most common printing options available in Diofant. The most common ones are
2D Pretty Printer (Unicode or ASCII)
In addition to these, there are also “printers” that can output Diofant objects to code, such as C, Fortran, or Mathematica.
Best printer is enabled automatically for interactive session
(i.e. \(\LaTeX\) in the IPython notebooks, pretty printer in the IPython
console or str printer in the Python console). If you want manually
configure pretty printing, please use the
init_printing()
function.
Lets take this simple expression
>>> expr = Integral(sqrt(1/x), x)
and try several available printers.
Str¶
To get a string form of an expression, use str
. This is also
the form that is produced by print()
. String forms are designed
to be easy to read and mostly to be in a form that is a correct Python syntax
so that it can be copied and pasted.
>>> str(expr)
'Integral(sqrt(1/x), x)'
>>> print(expr)
Integral(sqrt(1/x), x)
Repr¶
The repr form of an expression is designed to show the exact form of
an expression, it would yield an object with the same value when
passed to eval()
. To get it, use repr()
.
>>> repr(expr)
"Integral(Pow(Pow(Symbol('x'), Integer(1)), Rational(1, 2)), Tuple(Symbol('x')))"
The repr form is mostly useful for understanding how an expression is built internally.
2D Pretty Printer¶
A twodimensional (2D) textual representation of the expression can be
obtained with pretty()
.
>>> pretty(expr)
'⌠ \n⎮ ___ \n⎮ ╱ 1 \n⎮ ╱ ─ dx\n⎮ ╲╱ x \n⌡ '
>>> print(_)
⌠
⎮ ___
⎮ ╱ 1
⎮ ╱ ─ dx
⎮ ╲╱ x
⌡
Note
Unicode prettyprinting is enabled by default in the IPython terminal frontend.
You can pass use_unicode=False
to use ASCII symbols.
>>> print(pretty(expr, use_unicode=False))
/

 ___
 / 1
 /  dx
 \/ x

/
pprint()
prints the output to
the screen.
>>> pprint(expr)
⌠
⎮ ___
⎮ ╱ 1
⎮ ╱ ─ dx
⎮ ╲╱ x
⌡
LaTeX¶
To get the \(\LaTeX\) form of an expression, use
latex()
.
>>> print(latex(expr))
\int \sqrt{\frac{1}{x}}\, dx
Dot¶
dotprint()
function prints output to dot
format, which can be rendered with Graphviz:
Simplification¶
The generic way to do nontrivial simplifications of expressions is
calling simplify()
function.
>>> simplify(sin(x)**2 + cos(x)**2)
1
>>> simplify((x**3 + x**2  x  1)/(x**2 + 2*x + 1))
x  1
>>> simplify(gamma(x)/gamma(x  2))
(x  2)⋅(x  1)
There are also more directed simplification functions. These apply
very specific rules to the input expression and are typically able to
make guarantees about the output. For instance, the
factor()
function, given a polynomial
with rational coefficients in several variables, is guaranteed to
produce a factorization into irreducible factors.
The simplify()
function applies
almost all available in Diofant such specific simplification rules in
some heuristics sequence to produce the simplest result.
Tip
The optional measure
keyword argument for
simplify()
lets the user specify
the Python function used to determine how “simple” an expression
is. The default is count_ops()
, which
returns the total number of operations in the expression.
That is why it is usually slow. But more important pitfail is that
sometimes simplify()
doesn’t
“simplify” how you might expect, if, for example, it miss some
transformation or apply it too early or too late. Lets look on an
example
>>> simplify(x**2 + 2*x + 1)
2
x + 2⋅x + 1
>>> factor(_)
2
(x + 1)
Obviously, the factored form is more “simple”, as it has less arithmetic operations.
The function simplify()
is best when
used interactively, when you just want to whittle down an expression
to a simpler form. You may then choose to apply specific functions
once you see what simplify()
returns,
to get a more precise result. It is also useful when you have no idea
what form an expression will take, and you need a catchall function to
simplify it.
Rational Functions¶
expand()
is one of the most common
simplification functions in Diofant. Although it has a lot of scopes,
for now, we will consider its function in expanding polynomial
expressions.
>>> expand((x + 1)**2)
2
x + 2⋅x + 1
>>> expand((x + 2)*(x  3))
2
x  x  6
Given a polynomial, expand()
will put it
into a canonical form of a sum of monomials with help of more directed
expansion methods, namely
expand_multinomial()
and
expand_mul()
.
expand()
may not sound like a
simplification function. After all, by its very name, it makes
expressions bigger, not smaller. Usually this is the case, but often
an expression will become smaller upon calling
expand()
on it due to cancellation.
>>> expand((x + 1)*(x  2)  (x  1)*x)
2
Function factor()
takes a multivariate
polynomial with rational coefficients and factors it into irreducible
factors.
>>> factor(x**3  x**2 + x  1)
⎛ 2 ⎞
(x  1)⋅⎝x + 1⎠
>>> factor(x**2*z + 4*x*y*z + 4*y**2*z)
2
z⋅(x + 2⋅y)
For polynomials, factor()
is the
opposite of expand()
.
Note
The input to factor()
and
expand()
need not be polynomials in
the strict sense. They will intelligently factor or expand any
kind of expression (though, for example, the factors may not be
irreducible if the input is no longer a polynomial over the
rationals).
>>> expand((cos(x) + sin(x))**2)
2 2
sin (x) + 2⋅sin(x)⋅cos(x) + cos (x)
>>> factor(_)
2
(sin(x) + cos(x))
collect()
collects common powers of a
term in an expression.
>>> x*y + x  3 + 2*x**2  z*x**2 + x**3
3 2 2
x  x ⋅z + 2⋅x + x⋅y + x  3
>>> collect(_, x)
3 2
x + x ⋅(z + 2) + x⋅(y + 1)  3
collect()
is particularly useful in
conjunction with the coeff()
method.
>>> _.coeff(x, 2)
z + 2
cancel()
will take any rational
function and put it into the standard canonical form, \(p/q\), where \(p\)
and \(q\) are expanded polynomials with no common factors.
>>> 1/x + (3*x/2  2)/(x  4)
3⋅x
───  2
2 1
─────── + ─
x  4 x
>>> cancel(_)
2
3⋅x  2⋅x  8
──────────────
2
2⋅x  8⋅x
>>> expr = (x*y**2  2*x*y*z + x*z**2 + y**2  2*y*z + z**2)/(x**2  1)
>>> expr
2 2 2 2
x⋅y  2⋅x⋅y⋅z + x⋅z + y  2⋅y⋅z + z
───────────────────────────────────────
2
x  1
>>> cancel(_)
2 2
y  2⋅y⋅z + z
───────────────
x  1
Note
Since factor()
will completely
factorize both the numerator and the denominator of an expression,
it can also be used to do the same thing:
>>> factor(expr)
2
(y  z)
────────
x  1
However, it’s less efficient if you are only interested in making sure that the expression is in canceled form.
apart()
performs a partial fraction
decomposition on a
rational function.
>>> (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x)
3 2
4⋅x + 21⋅x + 10⋅x + 12
────────────────────────
4 3 2
x + 5⋅x + 5⋅x + 4⋅x
>>> apart(_)
2⋅x  1 1 3
──────────  ───── + ─
2 x + 4 x
x + x + 1
Trigonometric Functions¶
To simplify expressions using trigonometric identities, use
trigsimp()
function.
>>> trigsimp(sin(x)**2 + cos(x)**2)
1
>>> trigsimp(sin(x)**4  2*cos(x)**2*sin(x)**2 + cos(x)**4)
cos(4⋅x) 1
──────── + ─
2 2
>>> trigsimp(sin(x)*tan(x)/sec(x))
2
sin (x)
It also works with hyperbolic functions.
>>> trigsimp(cosh(x)**2 + sinh(x)**2)
cosh(2⋅x)
>>> trigsimp(sinh(x)/tanh(x))
cosh(x)
Much like simplify()
function,
trigsimp()
applies various
trigonometric identities to the input expression, and then uses a
heuristic to return the “best” one.
To expand trigonometric functions, that is, apply the sum or double
angle identities, use expand_trig()
function.
>>> expand_trig(sin(x + y))
sin(x)⋅cos(y) + sin(y)⋅cos(x)
>>> expand_trig(tan(2*x))
2⋅tan(x)
─────────────
2
 tan (x) + 1
Powers and Logarithms¶
powdenest()
function applies identity
\((x^a)^b = x^{a b}\), from left to right, if assumptions allow.
>>> a, b = symbols('a b', real=True)
>>> p = symbols('p', positive=True)
>>> powdenest((p**a)**b)
a⋅b
p
powsimp()
function reduces expression
by combining powers with similar bases and exponent.
>>> powsimp(z**x*z**y)
x + y
z
Again, as for powdenest()
above, for
the identity \(x^a y^a = (x y)^a\), that combine bases, we should be
careful about assumptions.
>>> q = symbols('q', positive=True)
>>> powsimp(p**a*q**a)
a
(p⋅q)
In general, this identity doesn’t hold. For example, if \(x = y = 1\) and \(a = 1/2\).
expand_power_exp()
and
expand_power_base()
functions do reverse
of powsimp()
.
>>> expand_power_exp(x**(y + z))
y z
x ⋅x
>>> expand_power_base((p*q)**a)
a a
p ⋅q
Logarithms have similar issues as powers. There are two main identities
\(\log{(xy)} = \log{(x)} + \log{(y)}\)
\(\log{(x^n)} = n\log{(x)}\)
Neither identity is true for arbitrary complex \(x\) and \(y\), due to the branch cut in the complex plane for the complex logarithm.
To apply above identities from left to right, use
expand_log()
. As for powers, the
identities will not be applied unless they are valid with given set of
assumptions for symbols.
>>> expand_log(log(p*q))
log(p) + log(q)
>>> expand_log(log(p/q))
log(p)  log(q)
>>> expand_log(log(p**2))
2⋅log(p)
>>> expand_log(log(p**a))
a⋅log(p)
>>> expand_log(log(x*y))
log(x⋅y)
To apply identities from right to left, i.e. do reverse of
expand_log()
, use
logcombine()
function.
>>> logcombine(log(p) + log(q))
log(p⋅q)
>>> logcombine(a*log(p))
⎛ a⎞
log⎝p ⎠
>>> logcombine(a*log(z))
a⋅log(z)
Special Functions¶
Diofant implements dozens of special functions, ranging from functions in combinatorics to mathematical physics.
To expand special functions in terms of some identities, use
expand_func()
. For example the gamma
function
gamma
can be
expanded as
>>> expand_func(gamma(x + 3))
x⋅(x + 1)⋅(x + 2)⋅Γ(x)
This method also can help if you would like to rewrite the generalized
hypergeometric function
hyper
or the Meijer
Gfunction meijerg
in terms
of more standard functions.
>>> expand_func(hyper([1, 1], [2], z))
log(z + 1)
─────────────
z
>>> meijerg([[1], [1]], [[1], []], z)
╭─╮1, 1 ⎛1 1 │ ⎞
│╶┐ ⎜ │ z⎟
╰─╯2, 1 ⎝1 │ ⎠
>>> expand_func(_)
z ___
╲╱ ℯ
Another type of expand rule is expanding complex valued expressions and putting
them into a normal form. For this expand_complex()
is used. Note that it will always perform arithmetic expand to obtain the
desired normal form.
>>> expand_complex(x + I*y)
ⅈ⋅(re(y) + im(x)) + re(x)  im(y)
The same behavior can be obtained by using
as_real_imag()
method.
>>> (x + I*y).as_real_imag()
(re(x)  im(y), re(y) + im(x))
To simplify combinatorial expressions, involving
factorial
,
binomial
or
gamma
— use
combsimp()
function.
>>> combsimp(factorial(x)/factorial(x  3))
x⋅(x  2)⋅(x  1)
>>> combsimp(binomial(x + 1, y + 1)/binomial(x, y))
x + 1
─────
y + 1
>>> combsimp(gamma(x)*gamma(1  x))
π
────────
sin(π⋅x)
CSE¶
Before evaluating a large expression, it is often useful to identify common
subexpressions, collect them and evaluate them at once. This is called common
subexpression elimination (CSE) and implemented in the
cse()
function.
>>> cse(sqrt(sin(x)))
⎛ ⎡ ________⎤⎞
⎝[], ⎣╲╱ sin(x) ⎦⎠
>>> cse(sqrt(sin(x) + 5)*sqrt(sin(x) + 4))
⎛ ⎡ ________ ________⎤⎞
⎝[(x₀, sin(x))], ⎣╲╱ x₀ + 4 ⋅╲╱ x₀ + 5 ⎦⎠
>>> cse(sqrt(sin(x + 1) + 5 + cos(y))*sqrt(sin(x + 1) + 4 + cos(y)))
⎛ ⎡ ________ ________⎤⎞
⎝[(x₀, sin(x + 1) + cos(y))], ⎣╲╱ x₀ + 4 ⋅╲╱ x₀ + 5 ⎦⎠
>>> cse((x  y)*(z  y) + sqrt((x  y)*(z  y)))
⎛ ⎡ ____ ⎤⎞
⎝[(x₀, y), (x₁, (x + x₀)⋅(x₀ + z))], ⎣╲╱ x₁ + x₁⎦⎠
Optimizations to be performed before and after common subexpressions elimination can be passed in the``optimizations`` optional argument.
>>> cse((x  y)*(z  y) + sqrt((x  y)*(z  y)), optimizations='basic')
⎛ ⎡ ____ ⎤⎞
⎝[(x₀, (x  y)⋅(y  z))], ⎣╲╱ x₀ + x₀⎦⎠
However, these optimizations can be very slow for large expressions. Moreover,
if speed is a concern, one can pass the option order='none'
. Order of
terms will then be dependent on hashing algorithm implementation, but speed
will be greatly improved.
Calculus¶
This section covers how to do basic calculus tasks such as derivatives, integrals, limits, and series expansions in Diofant.
Derivatives¶
To take derivatives, use the diff()
function.
>>> diff(cos(x), x)
sin(x)
>>> diff(exp(x**2), x)
⎛ 2⎞
⎝x ⎠
2⋅ℯ ⋅x
diff()
can take multiple derivatives at
once. To take multiple derivatives, pass the variable as many times
as you wish to differentiate, or pass a number after the variable.
For example, both of the following find the third derivative of \(x^4\).
>>> diff(x**4, x, x, x)
24⋅x
>>> diff(x**4, x, 3)
24⋅x
You can also take derivatives with respect to many variables at once. Just pass each derivative in order, using the same syntax as for single variable derivatives. For example, each of the following will compute \(\frac{\partial^7}{\partial x\partial y^2\partial z^4} e^{x y z}\).
>>> expr = exp(x*y*z)
>>> diff(expr, x, y, y, z, z, z, z)
x⋅y⋅z 3 2 ⎛ 3 3 3 2 2 2 ⎞
ℯ ⋅x ⋅y ⋅⎝x ⋅y ⋅z + 14⋅x ⋅y ⋅z + 52⋅x⋅y⋅z + 48⎠
>>> diff(expr, x, y, 2, z, 4)
x⋅y⋅z 3 2 ⎛ 3 3 3 2 2 2 ⎞
ℯ ⋅x ⋅y ⋅⎝x ⋅y ⋅z + 14⋅x ⋅y ⋅z + 52⋅x⋅y⋅z + 48⎠
>>> diff(expr, x, y, y, z, 4)
x⋅y⋅z 3 2 ⎛ 3 3 3 2 2 2 ⎞
ℯ ⋅x ⋅y ⋅⎝x ⋅y ⋅z + 14⋅x ⋅y ⋅z + 52⋅x⋅y⋅z + 48⎠
diff()
can also be called as a method
diff()
. The two ways of calling
diff()
are exactly the same, and are
provided only for convenience.
>>> expr.diff(x, y, y, z, 4)
x⋅y⋅z 3 2 ⎛ 3 3 3 2 2 2 ⎞
ℯ ⋅x ⋅y ⋅⎝x ⋅y ⋅z + 14⋅x ⋅y ⋅z + 52⋅x⋅y⋅z + 48⎠
To create an unevaluated derivative, use the
Derivative
class. It has the same
syntax as diff()
.
>>> Derivative(expr, x, y, y, z, 4)
7
∂ ⎛ x⋅y⋅z⎞
──────────⎝ℯ ⎠
4 2
∂z ∂y ∂x
Such unevaluated objects also used when Diofant does not know how to compute the derivative of an expression.
To evaluate an unevaluated derivative, use the
doit()
method.
>>> _.doit()
x⋅y⋅z 3 2 ⎛ 3 3 3 2 2 2 ⎞
ℯ ⋅x ⋅y ⋅⎝x ⋅y ⋅z + 14⋅x ⋅y ⋅z + 52⋅x⋅y⋅z + 48⎠
Integrals¶
To compute an integral, use the integrate()
function. There are two kinds of integrals, definite and indefinite. To
compute an indefinite integral, do
>>> integrate(cos(x), x)
sin(x)
Note
For indefinite integrals, Diofant does not include the constant of integration.
For example, to compute a definite integral
we would do
>>> integrate(exp(x), (x, 0, oo))
1
Tip
\(\infty\) in Diofant is oo
(that’s the lowercase letter “oh” twice).
As with indefinite integrals, you can pass multiple limit tuples to perform a multiple integral. For example, to compute
do
>>> integrate(exp(x**2  y**2), (x, oo, oo), (y, oo, oo))
π
If integrate()
is unable to compute an
integral, it returns an unevaluated
Integral
object.
>>> integrate(x**x, x)
⌠
⎮ x
⎮ x dx
⌡
>>> print(_)
Integral(x**x, x)
As with Derivative
, you can create an
unevaluated integral directly. To later evaluate this integral, call
doit()
.
>>> Integral(log(x)**2, x)
⌠
⎮ 2
⎮ log (x) dx
⌡
>>> _.doit()
2
x⋅log (x)  2⋅x⋅log(x) + 2⋅x
integrate()
uses powerful algorithms that
are always improving to compute both definite and indefinite integrals,
including a partial implementation of the Risch algorithm
>>> Integral((x**4 + x**2*exp(x)  x**2  2*x*exp(x)  2*x 
... exp(x))*exp(x)/((x  1)**2*(x + 1)**2*(exp(x) + 1)), x)
⌠
⎮ x ⎛ x 2 x x 4 2 ⎞
⎮ ℯ ⋅⎝ℯ ⋅x  2⋅ℯ ⋅x  ℯ + x  x  2⋅x⎠
⎮ ──────────────────────────────────────── dx
⎮ ⎛ x ⎞ 2 2
⎮ ⎝ℯ + 1⎠⋅(x  1) ⋅(x + 1)
⌡
>>> _.doit()
x
ℯ ⎛ x ⎞
────── + log⎝ℯ + 1⎠
2
x  1
and an algorithm using Meijer Gfunctions that is useful for computing integrals in terms of special functions, especially definite integrals
>>> Integral(sin(x**2), x)
⌠
⎮ ⎛ 2⎞
⎮ sin⎝x ⎠ dx
⌡
>>> _.doit()
⎛ ___ ⎞
___ ___ ⎜╲╱ 2 ⋅x⎟
3⋅╲╱ 2 ⋅╲╱ π ⋅fresnels⎜───────⎟⋅Γ(3/4)
⎜ ___ ⎟
⎝ ╲╱ π ⎠
──────────────────────────────────────
8⋅Γ(7/4)
>>> Integral(x**y*exp(x), (x, 0, oo))
∞
⌠
⎮ x y
⎮ ℯ ⋅x dx
⌡
0
>>> _.doit()
⎧ Γ(y + 1) for re(y) < 1
⎪
⎪∞
⎪⌠
⎨⎮ x y
⎪⎮ ℯ ⋅x dx otherwise
⎪⌡
⎪0
⎩
This last example returned a
Piecewise
expression because
the integral does not converge unless \(\Re(y) > 1.\)
Sums and Products¶
Much like integrals, there are
summation()
and
product()
to compute sums and
products respectively.
>>> summation(2**x, (x, 0, y  1))
y
2  1
>>> product(z, (x, 1, y))
y
z
Unevaluated sums and products are represented by
Sum
and
Product
classes.
>>> Sum(1, (x, 1, z))
z
___
╲
╲ 1
╱
╱
‾‾‾
x = 1
>>> _.doit()
z
Limits¶
Diofant can compute symbolic limits with the
limit()
function. To compute a directional limit
do
>>> limit(sin(x)/x, x, 0)
1
limit()
should be used instead of
subs()
whenever the point of evaluation is a
singularity. Even though Diofant has objects to represent \(\infty\), using them
for evaluation is not reliable because they do not keep track of things like
rate of growth. Also, things like \(\infty  \infty\) and
\(\frac{\infty}{\infty}\) return \(\mathrm{nan}\) (notanumber). For example
>>> expr = x**2/exp(x)
>>> expr.subs({x: oo})
nan
>>> limit(expr, x, oo)
0
Like Derivative
and
Integral
,
limit()
has an unevaluated counterpart,
Limit
. To evaluate it, use
doit()
.
>>> Limit((cos(x)  1)/x, x, 0)
cos(x)  1
lim ──────────
x─→0⁺ x
>>> _.doit()
0
To change side, pass ''
as a third argument to
limit()
. For example, to compute
do
>>> limit(1/x, x, 0, dir='')
∞
You can also evaluate bidirectional limit
>>> limit(sin(x)/x, x, 0, dir='real')
1
>>> limit(1/x, x, 0, dir='real')
Traceback (most recent call last):
...
PoleError: left and right limits for expression 1/x at point x=0 seems to be not equal
Series Expansion¶
Diofant can compute asymptotic series expansions of functions around a point.
>>> series(exp(sin(x)), x, 0, 4)
2
x ⎛ 4⎞
1 + x + ── + O⎝x ⎠
2
The \(O\left (x^4\right )\) term, an instance of O
at the end represents the Landau order term at \(x=0\) (not to be confused with
big O notation used in computer science, which generally represents the Landau
order term at \(x=\infty\)). Order terms can be created and manipulated outside
of series()
.
>>> x + x**3 + x**6 + O(x**4)
3 ⎛ 4⎞
x + x + O⎝x ⎠
>>> x*O(1)
O(x)
If you do not want the order term, use the
removeO()
method.
>>> series(exp(x), x, 0, 3).removeO()
2
x
── + x + 1
2
The O
notation supports arbitrary limit points
(other than 0):
>>> series(exp(x  1), x, x0=1)
2 3 4 5
(x  1) (x  1) (x  1) (x  1) ⎛ 6 ⎞
──────── + ──────── + ──────── + ──────── + x + O⎝(x  1) ; x → 1⎠
2 6 24 120
Solvers¶
This section covers equations solving.
Note
Any expression in input, that not in an
Eq
is automatically assumed to
be equal to 0 by the solving functions.
Algebraic Equations¶
The main function for solving algebraic equations is
solve()
.
When solving a single equation, the output is a list of the solutions.
>>> solve(x**2  x, x)
[{x: 0}, {x: 1}]
If no solutions are found, an empty list is returned.
>>> solve(exp(x), x)
[]
solve()
can also solve systems of equations.
>>> solve([x  y + 2, x + y  3], [x, y])
[{x: 1/2, y: 5/2}]
>>> solve([x*y  7, x + y  6], [x, y])
⎡⎧ ___ ___ ⎫ ⎧ ___ ___ ⎫⎤
⎢⎨x:  ╲╱ 2 + 3, y: ╲╱ 2 + 3⎬, ⎨x: ╲╱ 2 + 3, y:  ╲╱ 2 + 3⎬⎥
⎣⎩ ⎭ ⎩ ⎭⎦
solve()
reports each solution only once.
>>> solve(x**3  6*x**2 + 9*x, x)
[{x: 0}, {x: 3}]
To get the solutions of a polynomial including multiplicity use
roots()
.
>>> roots(x**3  6*x**2 + 9*x, x)
{0: 1, 3: 2}
Differential Equations¶
To solve differential equations, use
dsolve()
. First, create an undefined
function by passing cls=Function
to the
symbols()
function.
>>> f, g = symbols('f g', cls=Function)
f
and g
are now undefined functions. We can call f(x)
,
and it will represent an unknown function application. Derivatives of
f(x)
are unevaluated.
>>> f(x).diff(x)
d
──(f(x))
dx
To represent the differential equation \(f''(x)  2f'(x) + f(x) = \sin(x)\), we would thus use
>>> Eq(f(x).diff(x, x)  2*f(x).diff(x) + f(x), sin(x))
2
d d
f(x)  2⋅──(f(x)) + ───(f(x)) = sin(x)
dx 2
dx
To solve the ODE, pass it and the function to solve for to
dsolve()
.
>>> dsolve(_, f(x))
x cos(x)
f(x) = ℯ ⋅(C₁ + C₂⋅x) + ──────
2
dsolve()
returns an instance of
Eq
. This is because in general,
solutions to differential equations cannot be solved explicitly for
the function.
>>> dsolve(f(x).diff(x)*(1  sin(f(x))), f(x))
f(x) + cos(f(x)) = C₁
The arbitrary constants in the solutions from dsolve are symbols of
the form C1
, C2
, C3
, and so on.
dsolve()
can also solve systems of
equations, like solve()
.
>>> dsolve([f(x).diff(x)  g(x), g(x).diff(x)  f(x)], [f(x), g(x)])
⎡ ⎛ x x⎞ ⎛ x x⎞ ⎛ x x⎞ ⎛ x x⎞⎤
⎢ ⎜ℯ ℯ ⎟ ⎜ℯ ℯ ⎟ ⎜ℯ ℯ ⎟ ⎜ℯ ℯ ⎟⎥
⎢f(x) = C₁⋅⎜── + ───⎟ + C₂⋅⎜──  ───⎟, g(x) = C₁⋅⎜──  ───⎟ + C₂⋅⎜── + ───⎟⎥
⎣ ⎝2 2 ⎠ ⎝2 2 ⎠ ⎝2 2 ⎠ ⎝2 2 ⎠⎦
Polynomials¶
We show here some functions, that provide different algorithms dealing with polynomials in the form of Diofant expression.
Note, that coefficients of a polynomial can be elements of any
commutative ring, this ring is called the domain
of the polynomial
ring and may be specified as a keyword parameter for functions.
Polynomial generators also can be specified via an arbitrary number of
arguments after required arguments of functions.
Division¶
The function div()
provides
division of polynomials with remainder.
That is, for polynomials f
and g
, it computes q
and r
, such
that \(f = g \cdot q + r\) and \(\deg(r) < q\). For polynomials in one variables
with coefficients in a field, say, the rational numbers, q
and r
are
uniquely defined this way:
>>> f, g = 5*x**2 + 10*x + 3, 2*x + 2
>>> div(f, g)
⎛5⋅x 5 ⎞
⎜─── + ─, 2⎟
⎝ 2 2 ⎠
>>> expand(_[0]*g + _[1])
2
5⋅x + 10⋅x + 3
As you can see, q
has a noninteger coefficient. If you want to do division
only in the ring of polynomials with integer coefficients, you can specify an
additional parameter:
>>> div(f, g, field=False)
⎛ 2 ⎞
⎝5, 5⋅x  7⎠
But be warned, that this ring is no longer Euclidean and that the degree of the
remainder doesn’t need to be smaller than that of f
. Since 2 doesn’t divide 5,
\(2 x\) doesn’t divide \(5 x^2\), even if the degree is smaller. But:
>>> g = 5*x + 1
>>> div(f, g, field=False)
(x, 9⋅x + 3)
>>> expand(_[0]*g + _[1])
2
5⋅x + 10⋅x + 3
This also works for polynomials with multiple variables:
>>> div(x*y + y*z, 3*x + 3*z)
⎛y ⎞
⎜─, 0⎟
⎝3 ⎠
GCD and LCM¶
With division, there is also the computation of the greatest common divisor and the least common multiple.
When the polynomials have integer coefficients, the contents’ gcd is also considered:
>>> gcd((12*x + 12)*x, 16*x**2)
4⋅x
But if the polynomials have rational coefficients, then the returned polynomial is monic:
>>> gcd(3*x**2/2, 9*x/4)
x
Symbolic exponents are supported:
>>> gcd(2*x**(n + 4)  x**(n + 2), 4*x**(n + 1) + 3*x**n)
n
x
It also works with multiple variables. In this case, the variables are ordered alphabetically, be default, which has influence on the leading coefficient:
>>> gcd(x*y/2 + y**2, 3*x + 6*y)
x + 2⋅y
The lcm is connected with the gcd and one can be computed using the other:
>>> f, g = x*y**2 + x**2*y, x**2*y**2
>>> gcd(f, g)
x⋅y
>>> lcm(f, g)
3 2 2 3
x ⋅y + x ⋅y
>>> expand(f*g)
4 3 3 4
x ⋅y + x ⋅y
>>> expand(gcd(f, g, x, y)*lcm(f, g, x, y))
4 3 3 4
x ⋅y + x ⋅y
Squarefree factorization¶
The squarefree factorization of a univariate polynomial is the product of all factors (not necessarily irreducible) of degree 1, 2 etc.:
>>> sqf(2*x**2 + 5*x**3 + 4*x**4 + x**5)
2 2
x ⋅(x + 1) ⋅(x + 2)
Factorization¶
Factorization supported over different domains, lets compute one for the finite field with characteristic 5, rational field or its algebraic extension:
>>> f = x**4  3*x**2 + 1
>>> factor(f, modulus=5)
2 2
(x + 2) ⋅(x + 3)
>>> factor(f)
⎛ 2 ⎞ ⎛ 2 ⎞
⎝x  x  1⎠⋅⎝x + x  1⎠
>>> factor(f, extension=GoldenRatio)
(x  φ)⋅(x + φ)⋅(x  1 + φ)⋅(x  φ + 1)
You also may use gaussian
keyword to obtain a factorization over
Gaussian rationals:
>>> factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153, gaussian=True)
⎛ 3⋅ⅈ⎞ ⎛ 3⋅ⅈ⎞
4⋅⎜x  ───⎟⋅⎜x + ───⎟⋅(x + 1  4⋅ⅈ)⋅(x + 1 + 4⋅ⅈ)
⎝ 2 ⎠ ⎝ 2 ⎠
Computing with multivariate polynomials over various domains is as simple as in univariate case.
>>> factor(x**2 + 4*x*y + 4*y**2)
2
(x + 2⋅y)
>>> factor(x**3 + y**3, extension=sqrt(3))
⎛ ⎛ ___ ⎞⎞ ⎛ ⎛ ___ ⎞⎞
⎜ ⎜ 1 ╲╱ 3 ⋅ⅈ⎟⎟ ⎜ ⎜ 1 ╲╱ 3 ⋅ⅈ⎟⎟
(x + y)⋅⎜x + y⋅⎜ ─  ───────⎟⎟⋅⎜x + y⋅⎜ ─ + ───────⎟⎟
⎝ ⎝ 2 2 ⎠⎠ ⎝ ⎝ 2 2 ⎠⎠
Gröbner bases¶
Buchberger’s algorithm is implemented, supporting various monomial orders:
>>> groebner([x**2 + 1, y**4*x + x**3])
⎛⎡ 2 4 ⎤ ⎞
GroebnerBasis⎝⎣x + 1, y  1⎦, x, y, domain=ℤ, order=lex⎠
>>> groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], order=grevlex)
⎛⎡ 4 3 2 ⎤ ⎞
GroebnerBasis⎝⎣y  1, z , x + 1⎦, x, y, z, domain=ℤ, order=grevlex⎠
Matrices¶
To make a matrix in Diofant, use the
Matrix
object. A matrix is
constructed by providing a list of row vectors that make up the
matrix.
>>> Matrix([[1, 1], [3, 4], [0, 2]])
⎡1 1⎤
⎢ ⎥
⎢3 4 ⎥
⎢ ⎥
⎣0 2 ⎦
A list of elements is considered to be a column vector.
>>> Matrix([1, 2, 3])
⎡1⎤
⎢ ⎥
⎢2⎥
⎢ ⎥
⎣3⎦
One important thing to note about Diofant matrices is that, unlike
every other object in Diofant, they are mutable. This means that they
can be modified in place, as we will see below. Use
ImmutableMatrix
in places that
require immutability, such as inside other Diofant expressions or as
keys to dictionaries.
Indexing¶
Diofant matrices support subscription of matrix elements with pair of
integers or slice
instances. In last case, new
Matrix
instances will be returned.
>>> M = Matrix([[1, 2, 3], [4, 5, 6]])
>>> M[0, 1]
2
>>> M[1, 1]
5
>>> M[:, 1]
⎡2⎤
⎢ ⎥
⎣5⎦
>>> M[1, :1]
[4 5]
>>> M[0, :]
[1 2 3]
>>> M[:, 1]
⎡3⎤
⎢ ⎥
⎣6⎦
It’s possible to modify matrix elements.
>>> M[0, 0] = 0
>>> M
⎡0 2 3⎤
⎢ ⎥
⎣4 5 6⎦
>>> M[1, 1:] = Matrix([[0, 0]])
>>> M
⎡0 2 3⎤
⎢ ⎥
⎣4 0 0⎦
Reshape and Rearrange¶
To get the shape of a matrix use
shape
property
>>> M = Matrix([[1, 2, 3], [2, 0, 4]])
>>> M
⎡1 2 3⎤
⎢ ⎥
⎣2 0 4⎦
>>> M.shape
(2, 3)
To delete a row or column, use del
>>> del M[:, 0]
>>> M
⎡2 3⎤
⎢ ⎥
⎣0 4⎦
>>> del M[1, :]
>>> M
[2 3]
To insert rows or columns, use methods
row_insert()
or
col_insert()
.
>>> M
[2 3]
>>> M = M.row_insert(1, Matrix([[0, 4]]))
>>> M
⎡2 3⎤
⎢ ⎥
⎣0 4⎦
>>> M = M.col_insert(0, Matrix([1, 2]))
>>> M
⎡1 2 3⎤
⎢ ⎥
⎣2 0 4⎦
Note
You can see, that these methods will modify the Matrix in
place. In general, as a rule, such methods will return None
.
To swap two given rows or columns, use methods
row_swap()
or
col_swap()
.
>>> M.row_swap(0, 1)
>>> M
⎡2 0 4⎤
⎢ ⎥
⎣1 2 3⎦
>>> M.col_swap(1, 2)
>>> M
⎡2 4 0⎤
⎢ ⎥
⎣1 3 2⎦
To take the transpose of a Matrix, use
T
property.
>>> M.T
⎡2 1⎤
⎢ ⎥
⎢4 3⎥
⎢ ⎥
⎣0 2⎦
Algebraic Operations¶
Simple operations like addition and multiplication are done just by
using +
, *
, and **
. To find the inverse of a matrix, just
raise it to the 1
power.
>>> M, N = Matrix([[1, 3], [2, 3]]), Matrix([[0, 3], [0, 7]])
>>> M + N
⎡1 6 ⎤
⎢ ⎥
⎣2 10⎦
>>> M*N
⎡0 24⎤
⎢ ⎥
⎣0 15⎦
>>> 3*M
⎡3 9⎤
⎢ ⎥
⎣6 9⎦
>>> M**2
⎡5 12⎤
⎢ ⎥
⎣8 3 ⎦
>>> M**1
⎡1/3 1/3⎤
⎢ ⎥
⎣2/9 1/9 ⎦
>>> N**1
Traceback (most recent call last):
...
ValueError: Matrix det == 0; not invertible.
Special Matrices¶
Several constructors exist for creating common matrices. To create an
identity matrix, use eye()
function.
>>> eye(3)
⎡1 0 0⎤
⎢ ⎥
⎢0 1 0⎥
⎢ ⎥
⎣0 0 1⎦
>>> eye(4)
⎡1 0 0 0⎤
⎢ ⎥
⎢0 1 0 0⎥
⎢ ⎥
⎢0 0 1 0⎥
⎢ ⎥
⎣0 0 0 1⎦
To create a matrix of all zeros, use
zeros()
function.
>>> zeros(2, 3)
⎡0 0 0⎤
⎢ ⎥
⎣0 0 0⎦
Similarly, function ones()
creates a
matrix of ones.
>>> ones(3, 2)
⎡1 1⎤
⎢ ⎥
⎢1 1⎥
⎢ ⎥
⎣1 1⎦
To create diagonal matrices, use function
diag()
. Its arguments can be either
numbers or matrices. A number is interpreted as a \(1\times 1\)
matrix. The matrices are stacked diagonally.
>>> diag(1, 2, 3)
⎡1 0 0⎤
⎢ ⎥
⎢0 2 0⎥
⎢ ⎥
⎣0 0 3⎦
>>> diag(1, ones(2, 2), Matrix([5, 7, 5]))
⎡1 0 0 0⎤
⎢ ⎥
⎢0 1 1 0⎥
⎢ ⎥
⎢0 1 1 0⎥
⎢ ⎥
⎢0 0 0 5⎥
⎢ ⎥
⎢0 0 0 7⎥
⎢ ⎥
⎣0 0 0 5⎦
Advanced Methods¶
To compute the determinant of a matrix, use
det()
method.
>>> Matrix([[1, 0, 1], [2, 1, 3], [4, 3, 2]])
⎡1 0 1⎤
⎢ ⎥
⎢2 1 3⎥
⎢ ⎥
⎣4 3 2⎦
>>> det(_)
1
To put a matrix into reduced row echelon form, use method
rref()
. It returns a
tuple of two elements. The first is the reduced row echelon form, and
the second is a list of indices of the pivot columns.
>>> Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [1, 3, 3, 4]])
⎡1 0 1 3 ⎤
⎢ ⎥
⎢2 3 4 7 ⎥
⎢ ⎥
⎣1 3 3 4⎦
>>> _.rref()
⎛⎡1 0 1 3 ⎤ ⎞
⎜⎢ ⎥ ⎟
⎜⎢0 1 2/3 1/3⎥, [0, 1]⎟
⎜⎢ ⎥ ⎟
⎝⎣0 0 0 0 ⎦ ⎠
To find the nullspace of a matrix, use method
nullspace()
. It returns a
list of column vectors that span the nullspace of the matrix.
>>> Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]])
⎡1 2 3 0 0⎤
⎢ ⎥
⎣4 10 0 0 1⎦
>>> _.nullspace()
⎡⎡15⎤ ⎡0⎤ ⎡ 1 ⎤⎤
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎢⎢ 6 ⎥ ⎢0⎥ ⎢1/2⎥⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎢⎢ 1 ⎥, ⎢0⎥, ⎢ 0 ⎥⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎢⎢ 0 ⎥ ⎢1⎥ ⎢ 0 ⎥⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎣⎣ 0 ⎦ ⎣0⎦ ⎣ 1 ⎦⎦
To find the eigenvalues of a matrix, use method
eigenvals()
. It returns a
dictionary of roots including its multiplicity (similar to the output
of roots()
function).
>>> M = Matrix([[3, 2, 4, 2], [5, 3, 3, 2],
... [5, 2, 2, 2], [5, 2, 3, 3]])
>>> M
⎡3 2 4 2⎤
⎢ ⎥
⎢5 3 3 2⎥
⎢ ⎥
⎢5 2 2 2⎥
⎢ ⎥
⎣5 2 3 3 ⎦
>>> M.eigenvals()
{2: 1, 3: 1, 5: 2}
This means that M
has eigenvalues 2, 3, and 5, and that the
eigenvalues 2 and 3 have algebraic multiplicity 1 and that the
eigenvalue 5 has algebraic multiplicity 2.
Matrices can have symbolic elements.
>>> Matrix([[x, x + y], [y, x]])
⎡x x + y⎤
⎢ ⎥
⎣y x ⎦
>>> _.eigenvals()
⎧ ___________ ___________ ⎫
⎨x  ╲╱ y⋅(x + y) : 1, x + ╲╱ y⋅(x + y) : 1⎬
⎩ ⎭
To find the eigenvectors of a matrix, use method
eigenvects()
.
>>> M.eigenvects()
⎡⎛ ⎡⎡0⎤⎤⎞ ⎛ ⎡⎡1⎤⎤⎞ ⎛ ⎡⎡1⎤ ⎡0 ⎤⎤⎞⎤
⎢⎜ ⎢⎢ ⎥⎥⎟ ⎜ ⎢⎢ ⎥⎥⎟ ⎜ ⎢⎢ ⎥ ⎢ ⎥⎥⎟⎥
⎢⎜ ⎢⎢1⎥⎥⎟ ⎜ ⎢⎢1⎥⎥⎟ ⎜ ⎢⎢1⎥ ⎢1⎥⎥⎟⎥
⎢⎜2, 1, ⎢⎢ ⎥⎥⎟, ⎜3, 1, ⎢⎢ ⎥⎥⎟, ⎜5, 2, ⎢⎢ ⎥, ⎢ ⎥⎥⎟⎥
⎢⎜ ⎢⎢1⎥⎥⎟ ⎜ ⎢⎢1⎥⎥⎟ ⎜ ⎢⎢1⎥ ⎢0 ⎥⎥⎟⎥
⎢⎜ ⎢⎢ ⎥⎥⎟ ⎜ ⎢⎢ ⎥⎥⎟ ⎜ ⎢⎢ ⎥ ⎢ ⎥⎥⎟⎥
⎣⎝ ⎣⎣1⎦⎦⎠ ⎝ ⎣⎣1⎦⎦⎠ ⎝ ⎣⎣0⎦ ⎣1 ⎦⎦⎠⎦
This shows us that, for example, the eigenvalue 5 also has geometric
multiplicity 2, because it has two eigenvectors. Because the
algebraic and geometric multiplicities are the same for all the
eigenvalues, M
is diagonalizable.
To diagonalize a matrix, use method
diagonalize()
. It returns
a tuple \((P, D)\), where \(D\) is diagonal and \(M = PDP^{1}\).
>>> M.diagonalize()
⎛⎡0 1 1 0 ⎤ ⎡2 0 0 0⎤⎞
⎜⎢ ⎥ ⎢ ⎥⎟
⎜⎢1 1 1 1⎥ ⎢0 3 0 0⎥⎟
⎜⎢ ⎥, ⎢ ⎥⎟
⎜⎢1 1 1 0 ⎥ ⎢0 0 5 0⎥⎟
⎜⎢ ⎥ ⎢ ⎥⎟
⎝⎣1 1 0 1 ⎦ ⎣0 0 0 5⎦⎠
>>> _[0]*_[1]*_[0]**1 == M
True
If all you want is the characteristic polynomial, use method
charpoly()
. This is more
efficient than eigenvals()
method, because sometimes symbolic roots can be expensive to
calculate.
>>> M.charpoly(x)
PurePoly(x**4  11*x**3 + 29*x**2 + 35*x  150, x, domain='ZZ')
>>> factor(_)
2
(x  5) ⋅(x  3)⋅(x + 2)
To compute Jordan canonical form \(J\) for matrix \(M\) and its similarity
transformation \(P\) (i.e. such that \(J = P M P^{1}\)), use method
jordan_form()
.
>>> Matrix([[2, 4], [1, 3]]).jordan_form()
⎛⎡ 4 4 ⎤ ⎡ ____ ⎤⎞
⎜⎢──────────── ────────────⎥ ⎢1 ╲╱ 41 ⎥⎟
⎜⎢ ____ ____⎥ ⎢─ + ────── 0 ⎥⎟
⎜⎢ ╲╱ 41 5 5 ╲╱ 41 ⎥ ⎢2 2 ⎥⎟
⎜⎢ ──────  ─  ─ + ──────⎥, ⎢ ⎥⎟
⎜⎢ 2 2 2 2 ⎥ ⎢ ____ ⎥⎟
⎜⎢ ⎥ ⎢ ╲╱ 41 1⎥⎟
⎜⎣ 1 1 ⎦ ⎢ 0  ────── + ─⎥⎟
⎝ ⎣ 2 2⎦⎠
Expression Trees¶
Most generic interface to represent a mathematical expression in Diofant is a tree. Let us take the expression
>>> x*y + x**2
2
x + x⋅y
We can see what this expression looks like internally by using repr()
>>> repr(_)
"Add(Pow(Symbol('x'), Integer(2)), Mul(Symbol('x'), Symbol('y')))"
The easiest way to tear this apart is to look at a diagram of the expression tree
First, let’s look at the leaves of this tree. We got here instances
of the Symbol
class and the Diofant
version of integers, instance of the
Integer
class, even technically we
input integer literal 2
.
What about x*y
? As we might expect, this is the multiplication of
x
and y
. The Diofant class for multiplication is
Mul
>>> repr(x*y)
"Mul(Symbol('x'), Symbol('y'))"
Thus, we could have created the same object by writing
>>> Mul(x, y)
x⋅y
When we write x**2
, this creates a
Pow
class instance
>>> repr(x**2)
"Pow(Symbol('x'), Integer(2))"
We could have created the same object by calling
>>> Pow(x, 2)
2
x
Now we get to our final expression, x*y + x**2
. This is the
addition of our last two objects. The Diofant class for addition is
Add
, so, as you might expect, to create
this object, we also could use
>>> Add(Pow(x, 2), Mul(x, y))
2
x + x⋅y
Note
The arguments of Add
and the commutative
arguments of Mul
are stored in an order,
which is independent of the order inputted.
There is no subtraction class. x  y
is represented as
x + (1)*y
>>> repr(x  y)
"Add(Symbol('x'), Mul(Integer(1), Symbol('y')))"
Similarly to subtraction, there is no division class
>>> repr(x/y)
"Mul(Symbol('x'), Pow(Symbol('y'), Integer(1)))"
We see that x/y
is represented as x*y**(1)
.
But what about x/2
? Following the pattern of the previous
example, we might expect to see Mul(x, Pow(Integer(2), 1))
. But
instead, we have
>>> repr(x/2)
"Mul(Rational(1, 2), Symbol('x'))"
Rational numbers are always combined into a single term in a multiplication, so that when we divide by 2, it is represented as multiplying by 1/2.
Walking the Tree¶
Let’s look at how to dig our way through an expression tree, using a very
generic interface — attributes func
and
args
.
The head of the object is encoded in the func
attribute
>>> expr = 2 + x*y; expr
x⋅y + 2
>>> expr.func
<class 'diofant.core.add.Add'>
The class of an object need not be the same as the one used to create it
>>> Add(x, x)
2⋅x
>>> _.func
<class 'diofant.core.mul.Mul'>
Note
Diofant classes heavy use of the __new__()
class
constructor, which, unlike __init__()
, allows a
different class to be returned from the constructor.
The children of a node in the tree are held in the
args
attribute
>>> expr.args
(2, x⋅y)
Note
Every expression with nonempty args
can
be reconstructed, using
>>> expr.func(*expr.args)
x⋅y + 2
Empty args
signal that
we have hit a leaf of the expression tree
>>> x.args
()
>>> Integer(2).args
()
This interface allows us to write recursive generators that walk expression trees either in postorder or preorder fashion
>>> tuple(preorder_traversal(expr))
(x⋅y + 2, 2, x⋅y, x, y)
>>> tuple(postorder_traversal(expr))
(2, x, y, x⋅y, x⋅y + 2)
Reference¶
Most of the things are already documented though in this document, that is automatically generated using Diofant’s docstrings.
Tip
Because every feature of Diofant must have a test case, when you are not
sure how to use something, just look into the tests
subdirectories,
find that feature and read the tests for it.
Core¶
Core module. Provides the basic operations needed in diofant.
sympify¶
sympify¶

diofant.core.sympify.
sympify
(a, locals=None, convert_xor=True, strict=False, rational=False, evaluate=None)[source]¶ Converts an arbitrary expression to a type that can be used inside Diofant.
For example, it will convert Python ints into instance of diofant.Rational, floats into instances of diofant.Float, etc. It is also able to coerce symbolic expressions which inherit from Basic. This can be useful in cooperation with SAGE.
 It currently accepts as arguments:
any object defined in diofant
standard numeric python types: int, long, float, Decimal
strings (like “0.09” or “2e19”)
booleans, including
None
(will leaveNone
unchanged)lists, sets or tuples containing any of the above
If the argument is already a type that Diofant understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type.
>>> sympify(2).is_integer True >>> sympify(2).is_real True
>>> sympify(2.0).is_real True >>> sympify("2.0").is_real True >>> sympify("2e45").is_real True
If the expression could not be converted, a SympifyError is raised.
>>> sympify("x***2") Traceback (most recent call last): ... SympifyError: SympifyError: "could not parse u'x***2'"
Locals
The sympification happens with access to everything that is loaded by
from diofant import *
; anything used in a string that is not defined by that import will be converted to a symbol. In the following, thebitcount
function is treated as a symbol and theO
is interpreted as the Order object (used with series) and it raises an error when used improperly:>>> s = 'bitcount(42)' >>> sympify(s) bitcount(42) >>> sympify("O(x)") O(x) >>> sympify("O + 1") Traceback (most recent call last): ... TypeError: unbound method...
In order to have
bitcount
be recognized it can be imported into a namespace dictionary and passed as locals:>>> ns = {} >>> exec('from diofant.core.evalf import bitcount', ns) >>> sympify(s, locals=ns) 6
In order to have the
O
interpreted as a Symbol, identify it as such in the namespace dictionary. This can be done in a variety of ways; all three of the following are possibilities:>>> ns["O"] = Symbol("O") # method 1 >>> exec('from diofant.abc import O', ns) # method 2 >>> ns.update(dict(O=Symbol("O"))) # method 3 >>> sympify("O + 1", locals=ns) O + 1
If you want all singleletter and Greekletter variables to be symbols then you can use the clashingsymbols dictionaries that have been defined there as private variables: _clash1 (singleletter variables), _clash2 (the multiletter Greek names) or _clash (both single and multiletter names that are defined in abc).
>>> from diofant.abc import _clash1 >>> _clash1 {'E': E, 'I': I, 'N': N, 'O': O, 'S': S} >>> sympify('E & O', _clash1) E & O
Strict
If the option
strict
is set toTrue
, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised.>>> print(sympify(None)) None >>> sympify(None, strict=True) Traceback (most recent call last): ... SympifyError: SympifyError: None
Evaluation
If the option
evaluate
is set toFalse
, then arithmetic and operators will be converted into their Diofant equivalents and theevaluate=False
option will be added. NestedAdd
orMul
will be denested first. This is done via an AST transformation that replaces operators with their Diofant equivalents, so if an operand redefines any of those operations, the redefined operators will not be used.>>> sympify('2**2 / 3 + 5') 19/3 >>> sympify('2**2 / 3 + 5', evaluate=False) 2**2/3 + 5
Sometimes autosimplification during sympification results in expressions that are very different in structure than what was entered. Below you can see how an expression reduces to 1 by autosimplification, but does not do so when
evaluate
option is used.>>> 2*((x + 1/x)/(x*(x  1/x)**2)  1/(x*(x  1/x)))  1 1 >>> s = '2*((x + 1/x)/(x*(x  1/x)**2)  1/(x*(x  1/x)))  1' >>> sympify(s) 1 >>> sympify(s, evaluate=False) 2*((x  1/x)/(x*(x  1/x)**2)  1/(x*(x  1/x)))  1
Extending
To extend
sympify
to convert custom objects (not derived fromBasic
), just define a_diofant_
method to your class. You can do that even to classes that you do not own by subclassing or adding the method at runtime.>>> class MyList1: ... def __iter__(self): ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] ... def _diofant_(self): return Matrix(self) >>> sympify(MyList1()) Matrix([ [1], [2]])
If you do not have control over the class definition you could also use the
converter
global dictionary. The key is the class and the value is a function that takes a single argument and returns the desired Diofant object, e.g.converter[MyList] = lambda x: Matrix(x)
.>>> class MyList2: # XXX Do not do this if you control the class! ... def __iter__(self): # Use _diofant_! ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] >>> converter[MyList2] = lambda x: Matrix(x) >>> sympify(MyList2()) Matrix([ [1], [2]])
assumptions¶
This module contains the machinery handling assumptions.
All symbolic objects have assumption attributes that can be accessed via
.is_<assumption name> attribute, i.e.
is_integer
. Full set of defined
assumption names are accessible as
Expr.default_assumptions.rules.defined_facts
attribute.
Assumptions determine certain properties of symbolic objects and can have 3 possible values: True, False, None. True is returned if the object has the property and False is returned if it doesn’t or can’t (i.e. doesn’t make sense):
>>> I.is_algebraic
True
>>> I.is_real
False
>>> I.is_prime
False
When the property cannot be determined (or when a method is not implemented) None will be returned, e.g. a generic symbol, x, may or may not be positive so a value of None is returned for x.is_positive.
By default, all symbolic values are in the largest set in the given context without specifying the property. For example, a symbol that has a property being integer, is also real, complex, etc.
See also
Notes
Assumption values are stored in obj._assumptions dictionary or are returned by getter methods (with property decorators) or are attributes of objects/classes.

class
diofant.core.assumptions.
ManagedProperties
(*args, **kws)[source]¶ Metaclass for classes with oldstyle assumptions.

class
diofant.core.assumptions.
StdFactKB
(facts=None)[source]¶ A FactKB specialised for the builtin rules
This is the only kind of FactKB that Basic objects should use.

diofant.core.assumptions.
as_property
(fact)[source]¶ Convert a fact name to the name of the corresponding property.

diofant.core.assumptions.
check_assumptions
(expr, **assumptions)[source]¶ Checks if expression \(expr\) satisfies all assumptions.
 Parameters
expr (Expr) – Expression to test.
**assumptions (dict) – Keyword arguments to specify assumptions to test.
 Returns
True, False or None (if can’t conclude).
Examples
>>> check_assumptions(5, integer=True) True >>> x = Symbol('x', positive=True) >>> check_assumptions(2*x + 1, negative=True) False >>> check_assumptions(z, real=True) is None True
cache¶
basic¶
Base class for all the objects in Diofant.

class
diofant.core.basic.
Atom
[source]¶ A parent class for atomic things.
An atom is an expression with no subexpressions, for example Symbol, Number, Rational or Integer, but not Add, Mul, Pow.

class
diofant.core.basic.
Basic
[source]¶ Base class for all objects in Diofant.
Always use
args
property, when accessing parameters of some instance.
property
args
¶ Returns a tuple of arguments of ‘self’.
Examples
>>> cot(x).args (x,) >>> (x*y).args (x, y)

atoms
(*types)[source]¶ Returns the atoms that form the current object.
By default, only objects that are truly atomic and can’t be divided into smaller pieces are returned: symbols, numbers, and number symbols like I and pi. It is possible to request atoms of any type, however, as demonstrated below.
Examples
>>> e = 1 + x + 2*sin(y + I*pi) >>> e.atoms() {1, 2, I, pi, x, y}
If one or more types are given, the results will contain only those types of atoms.
>>> e.atoms(Symbol) {x, y}
>>> e.atoms(Number) {1, 2}
>>> e.atoms(Number, NumberSymbol) {1, 2, pi}
>>> e.atoms(Number, NumberSymbol, I) {1, 2, I, pi}
Note that I (imaginary unit) and zoo (complex infinity) are special types of number symbols and are not part of the NumberSymbol class.
The type can be given implicitly, too:
>>> e.atoms(x) {x, y}
Be careful to check your assumptions when using the implicit option since
Integer(1).is_Integer = True
buttype(Integer(1))
isOne
, a special type of diofant atom, whiletype(Integer(2))
is typeInteger
and will find all integers in an expression:>>> e.atoms(Integer(1)) {1}
>>> e.atoms(Integer(2)) {1, 2}
Finally, arguments to atoms() can select more than atomic atoms: any diofant type can be listed as an argument and those types of “atoms” as found in scanning the arguments of the expression recursively:
>>> from diofant.core.function import AppliedUndef
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul) {I*pi, 2*sin(y + I*pi)}
>>> f = Function('f') >>> e = 1 + f(x) + 2*sin(y + I*pi) >>> e.atoms(Function) {f(x), sin(y + I*pi)} >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef) {f(x)}

doit
(**hints)[source]¶ Evaluate objects that are not evaluated by default.
For example, limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.
Examples
>>> 2*Integral(x, x) 2*Integral(x, x)
>>> (2*Integral(x, x)).doit() x**2
>>> (2*Integral(x, x)).doit(deep=False) 2*Integral(x, x)

property
free_symbols
¶ Return from the atoms of self those which are free symbols.
For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.
Any other method that uses bound variables should implement a free_symbols method.

property
func
¶ The toplevel function in an expression.
The following should hold for all objects:
x == x.func(*x.args)
Examples
>>> a = 2*x >>> a.func <class 'diofant.core.mul.Mul'> >>> a.args (2, x) >>> a.func(*a.args) 2*x >>> a == a.func(*a.args) True

has
(*patterns)[source]¶ Test if any subexpression matches any of the patterns.
 Parameters
*patterns (tuple of Expr) – List of expressions to search for match.
 Returns
bool – False if there is no match or patterns list is empty, else True.
Examples
>>> e = x**2 + sin(x*y) >>> e.has(z) False >>> e.has(x, y, z) True >>> x.has() False

match
(pattern)[source]¶ Pattern matching.
Wild symbols match all.
 Parameters
pattern (Expr) – An expression that may contain Wild symbols.
 Returns
dict or None – If pattern match self, return a dictionary of replacement rules, such that:
pattern.xreplace(self.match(pattern)) == self
Examples
>>> p = Wild("p") >>> q = Wild("q") >>> e = (x + y)**(x + y) >>> e.match(p**p) {p_: x + y} >>> e.match(p**q) {p_: x + y, q_: x + y} >>> (p**q).xreplace(_) (x + y)**(x + y)
See also

rcall
(*args)[source]¶ Apply on the argument recursively through the expression tree.
This method is used to simulate a common abuse of notation for operators. For instance in Diofant the the following will not work:
(x+Lambda(y, 2*y))(z) == x+2*z
,however you can use
>>> (x + Lambda(y, 2*y)).rcall(z) x + 2*z

replace
(query, value, exact=False)[source]¶ Replace matching subexpressions of
self
withvalue
.Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree in a simultaneous fashion so changes made are targeted only once. In addition, if an expression containing more than one Wild symbol is being used to match subexpressions and the
exact
flag is True, then the match will only succeed if nonzero values are received for each Wild that appears in the match pattern.The list of possible combinations of queries and replacement values is listed below:
Examples
Initial setup
>>> f = log(sin(x)) + tan(sin(x**2))
 1.1. type > type
obj.replace(type, newtype)
When object of type
type
is found, replace it with the result of passing its argument(s) tonewtype
.>>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> (x*y).replace(Mul, Add) x + y
 1.2. type > func
obj.replace(type, func)
When object of type
type
is found, applyfunc
to its argument(s).func
must be written to handle the number of arguments oftype
.>>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args))) sin(2*x*y)
 2.1. pattern > expr
obj.replace(pattern(wild), expr(wild))
Replace subexpressions matching
pattern
with the expression written in terms of the Wild symbols inpattern
.>>> a = Wild('a') >>> f.replace(sin(a), tan(a)) log(tan(x)) + tan(tan(x**2)) >>> f.replace(sin(a), tan(a/2)) log(tan(x/2)) + tan(tan(x**2/2)) >>> f.replace(sin(a), a) log(x) + tan(x**2) >>> (x*y).replace(a*x, a) y
When the default value of False is used with patterns that have more than one Wild symbol, nonintuitive results may be obtained:
>>> b = Wild('b') >>> (2*x).replace(a*x + b, b  a) 2/x
For this reason, the
exact
option can be used to make the replacement only when the match gives nonzero values for all Wild symbols:>>> (2*x + y).replace(a*x + b, b  a, exact=True) y  2 >>> (2*x).replace(a*x + b, b  a, exact=True) 2*x
 2.2. pattern > func
obj.replace(pattern(wild), lambda wild: expr(wild))
All behavior is the same as in 2.1 but now a function in terms of pattern variables is used rather than an expression:
>>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2))
 3.1. func > func
obj.replace(filter, func)
Replace subexpression
e
withfunc(e)
iffilter(e)
is True.>>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9)
The expression itself is also targeted by the query but is done in such a fashion that changes are not made twice.
>>> e = x*(x*y + 1) >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x) 2*x*(2*x*y + 1)
See also
subs()
substitution of subexpressions as defined by the objects themselves.
xreplace()
exact node replacement in expr tree; also capable of using matching rules

rewrite
(*args, **hints)[source]¶ Rewrite functions in terms of other functions.
Rewrites expression containing applications of functions of one kind in terms of functions of different kind. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function.
As a pattern this function accepts a list of functions to to rewrite (instances of DefinedFunction class). As rule you can use string or a destination function instance (in this case rewrite() will use the str() function).
There is also the possibility to pass hints on how to rewrite the given expressions. For now there is only one such hint defined called ‘deep’. When ‘deep’ is set to False it will forbid functions to rewrite their contents.
Examples
Unspecified pattern:
>>> sin(x).rewrite(exp) I*(E**(I*x)  E**(I*x))/2
Pattern as a single function:
>>> sin(x).rewrite(sin, exp) I*(E**(I*x)  E**(I*x))/2
Pattern as a list of functions:
>>> sin(x).rewrite([sin], exp) I*(E**(I*x)  E**(I*x))/2

sort_key
(order=None)[source]¶ Return a sort key.
Examples
>>> sorted([Rational(1, 2), I, I], key=lambda x: x.sort_key()) [1/2, I, I]
>>> [x, 1/x, 1/x**2, x**2, sqrt(x), root(x, 4), x**Rational(3, 2)] [x, 1/x, x**(2), x**2, sqrt(x), x**(1/4), x**(3/2)] >>> sorted(_, key=lambda x: x.sort_key()) [x**(2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]

subs
(*args, **kwargs)[source]¶ Substitutes old for new in an expression after sympifying args.
 \(args\) is either:
 one iterable argument, e.g. foo.subs(iterable). The iterable may be
 o an iterable container with (old, new) pairs. In this case the
replacements are processed in the order given with successive patterns possibly affecting replacements already made.
 o a dict or set whose key/value items correspond to old/new pairs.
In this case the old/new pairs will be sorted by op count and in case of a tie, by number of args and the default_sort_key. The resulting sorted list is then processed as an iterable container (see previous).
If the keyword
simultaneous
is True, the subexpressions will not be evaluated until all the substitutions have been made.Examples
>>> (1 + x*y).subs({x: pi}) pi*y + 1 >>> (1 + x*y).subs({x: pi, y: 2}) 1 + 2*pi >>> (1 + x*y).subs([(x, pi), (y, 2)]) 1 + 2*pi >>> reps = [(y, x**2), (x, 2)] >>> (x + y).subs(reps) 6 >>> (x + y).subs(reversed(reps)) x**2 + 2
>>> (x**2 + x**4).subs({x**2: y}) y**2 + y
To replace only the x**2 but not the x**4, use xreplace:
>>> (x**2 + x**4).xreplace({x**2: y}) x**4 + y
To delay evaluation until all substitutions have been made, set the keyword
simultaneous
to True:>>> (x/y).subs([(x, 0), (y, 0)]) 0 >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True) nan
This has the added feature of not allowing subsequent substitutions to affect those already made:
>>> ((x + y)/y).subs({x + y: y, y: x + y}) 1 >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True) y/(x + y)
In order to obtain a canonical result, unordered iterables are sorted by count_op length, number of arguments and by the default_sort_key to break any ties. All other iterables are left unsorted.
>>> from diofant.abc import e
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
>>> expr.subs({sqrt(sin(2*x)): a, sin(2*x): b, ... cos(2*x): c, x: d, exp(x): e}) a*c*sin(d*e) + b
The resulting expression represents a literal replacement of the old arguments with the new arguments. This may not reflect the limiting behavior of the expression:
>>> (x**3  3*x).subs({x: oo}) nan
>>> limit(x**3  3*x, x, oo) oo
If the substitution will be followed by numerical evaluation, it is better to pass the substitution to evalf as
>>> (1/x).evalf(21, subs={x: 3.0}, strict=False) 0.333333333333333333333
rather than
>>> (1/x).subs({x: 3.0}).evalf(21, strict=False) 0.333333333333333
as the former will ensure that the desired level of precision is obtained.
See also
replace()
replacement capable of doing wildcardlike matching, parsing of match, and conditional replacements
xreplace()
exact node replacement in expr tree; also capable of using matching rules
diofant.core.evalf.EvalfMixin.evalf()
calculates the given formula to a desired level of precision

xreplace
(rule)[source]¶ Replace occurrences of objects within the expression.
 Parameters
rule (dictlike) – Expresses a replacement rule
 Returns
xreplace (the result of the replacement)
Examples
>>> (1 + x*y).xreplace({x: pi}) pi*y + 1 >>> (1 + x*y).xreplace({x: pi, y: 2}) 1 + 2*pi
Replacements occur only if an entire node in the expression tree is matched:
>>> (x*y + z).xreplace({x*y: pi}) z + pi >>> (x*y*z).xreplace({x*y: pi}) x*y*z >>> (2*x).xreplace({2*x: y, x: z}) y >>> (2*2*x).xreplace({2*x: y, x: z}) 4*z >>> (x + y + 2).xreplace({x + y: 2}) x + y + 2 >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y}) E**y + x + 2
xreplace doesn’t differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does:
>>> Integral(x, (x, 1, 2*x)).xreplace({x: y}) Integral(y, (y, 1, 2*y))
Trying to replace x with an expression raises an error:
>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) Traceback (most recent call last): ... ValueError: Invalid limits given: ((2*y, 1, 4*y),)

property

class
diofant.core.basic.
preorder_traversal
(node, keys=None)[source]¶ Do a preorder traversal of a tree.
This iterator recursively yields nodes that it has visited in a preorder fashion. That is, it yields the current node then descends through the tree breadthfirst to yield all of a node’s children’s preorder traversal.
For an expression, the order of the traversal depends on the order of .args, which in many cases can be arbitrary.
 Parameters
node (diofant expression) – The expression to traverse.
keys ((default None) sort key(s)) – The key(s) used to sort args of Basic objects. When None, args of Basic objects are processed in arbitrary order. If key is defined, it will be passed along to ordered() as the only key(s) to use to sort the arguments; if
key
is simply True then the default keys of ordered will be used.
 Yields
subtree (diofant expression) – All of the subtrees in the tree.
Examples
The nodes are returned in the order that they are encountered unless key is given; simply passing key=True will guarantee that the traversal is unique.
>>> list(preorder_traversal((x + y)*z, keys=True)) [z*(x + y), z, x + y, x, y]
core¶
singleton¶
Singleton mechanism

diofant.core.singleton.
S
= S¶ Alias for instance of
SingletonRegistry
.

class
diofant.core.singleton.
Singleton
[source]¶ Metaclass for singleton classes.
A singleton class has only one instance which is returned every time the class is instantiated. Additionally, this instance can be accessed through the global registry object
S
asS.<class_name>
.Examples
>>> class MySingleton(Basic, metaclass=Singleton): ... pass >>> Basic() is Basic() False >>> MySingleton() is MySingleton() True >>> S.MySingleton is MySingleton() True
Notes
Instance creation is delayed until the first time the value is accessed.
This metaclass is a subclass of ManagedProperties because that is the metaclass of many classes that need to be Singletons (Python does not allow subclasses to have a different metaclass than the superclass, except the subclass may use a subclassed metaclass).

class
diofant.core.singleton.
SingletonRegistry
[source]¶ The registry for the singleton classes.
Several classes in Diofant appear so often that they are singletonized, that is, using some metaprogramming they are made so that they can only be instantiated once (see the
diofant.core.singleton.Singleton
class for details). For instance, every time you createInteger(0)
, this will return the same instance,diofant.core.numbers.Zero
.>>> a = Integer(0) >>> a is S.Zero True
All singleton instances are attributes of the
S
object, soInteger(0)
can also be accessed asS.Zero
.Notes
For the most part, the fact that certain objects are singletonized is an implementation detail that users shouldn’t need to worry about. In Diofant library code,
is
comparison is often used for performance purposes. The primary advantage ofS
for end users is the convenient access to certain instances that are otherwise difficult to type, likeS.Half
(instead ofRational(1, 2)
).When using
is
comparison, make sure the argument is aBasic
instance. For example,>>> int(0) is S.Zero False
evaluate¶

diofant.core.evaluate.
evaluate
(x)[source]¶ Control automatic evaluation
This context managers controls whether or not all Diofant functions evaluate by default.
Note that much of Diofant expects evaluated expressions. This functionality is experimental and is unlikely to function as intended on large expressions.
Examples
>>> x + x 2*x >>> with evaluate(False): ... x + x x + x
expr¶
Expr¶

class
diofant.core.expr.
Expr
[source]¶ Base class for algebraic expressions.
Everything that requires arithmetic operations to be defined should subclass this class, instead of Basic (which should be used only for argument storage and expression manipulation, i.e. pattern matching, substitutions, etc).
See also

args_cnc
(cset=False, warn=True, split_1=True)[source]¶ Return [commutative factors, noncommutative factors] of self.
self is treated as a Mul and the ordering of the factors is maintained. If
cset
is True the commutative factors will be returned in a set. If there were repeated factors (as may happen with an unevaluated Mul) then an error will be raised unless it is explicitly suppressed by settingwarn
to False.Note: 1 is always separated from a Number unless split_1 is False.
>>> A, B = symbols('A B', commutative=0) >>> (2*x*y).args_cnc() [[1, 2, x, y], []] >>> (2.5*x).args_cnc() [[1, 2.5, x], []] >>> (2*x*A*B*y).args_cnc() [[1, 2, x, y], [A, B]] >>> (2*x*A*B*y).args_cnc(split_1=False) [[2, x, y], [A, B]] >>> (2*x*y).args_cnc(cset=True) [{1, 2, x, y}, []]
The arg is always treated as a Mul:
>>> (2 + x + A).args_cnc() [[], [x  2 + A]] >>> (oo).args_cnc() # oo is a singleton [[1, oo], []]

as_coeff_add
(*deps)[source]¶ Return the tuple (c, args) where self is written as an Add,
a
.c should be a Rational added to any terms of the Add that are independent of deps.
args should be a tuple of all other terms of
a
; args is empty if self is a Number or if self is independent of deps (when given).This should be used when you don’t know if self is an Add or not but you want to treat self as an Add or if you want to process the individual arguments of the tail of self as an Add.
if you know self is an Add and want only the head, use self.args[0];
if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail.
if you want to split self into an independent and dependent parts use
self.as_independent(*deps)
>>> (Integer(3)).as_coeff_add() (3, ()) >>> (3 + x).as_coeff_add() (3, (x,)) >>> (3 + x + y).as_coeff_add(x) (y + 3, (x,)) >>> (3 + y).as_coeff_add(x) (y + 3, ())

as_coeff_mul
(*deps, **kwargs)[source]¶ Return the tuple (c, args) where self is written as a Mul,
m
.c should be a Rational multiplied by any terms of the Mul that are independent of deps.
args should be a tuple of all other terms of m; args is empty if self is a Number or if self is independent of deps (when given).
This should be used when you don’t know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul.
if you know self is a Mul and want only the head, use self.args[0];
if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail;
if you want to split self into an independent and dependent parts use
self.as_independent(*deps)
>>> (Integer(3)).as_coeff_mul() (3, ()) >>> (3*x*y).as_coeff_mul() (3, (x, y)) >>> (3*x*y).as_coeff_mul(x) (3*y, (x,)) >>> (3*y).as_coeff_mul(x) (3*y, ())

as_coefficient
(expr)[source]¶ Extracts symbolic coefficient at the given expression.
In other words, this functions separates ‘self’ into the product of ‘expr’ and ‘expr’free coefficient. If such separation is not possible it will return None.
Examples
>>> E.as_coefficient(E) 1 >>> (2*E).as_coefficient(E) 2 >>> (2*sin(E)*E).as_coefficient(E)
Two terms have E in them so a sum is returned. (If one were desiring the coefficient of the term exactly matching E then the constant from the returned expression could be selected. Or, for greater precision, a method of Poly can be used to indicate the desired term from which the coefficient is desired.)
>>> (2*E + x*E).as_coefficient(E) x + 2 >>> _.args[0] # just want the exact match 2 >>> p = Poly(2*E + x*E); p Poly(x*E + 2*E, x, E, domain='ZZ') >>> p.coeff_monomial(E) 2
Since the following cannot be written as a product containing E as a factor, None is returned. (If the coefficient
2*x
is desired then thecoeff
method should be used.)>>> (2*E*x + x).as_coefficient(E) >>> (2*E*x + x).coeff(E) 2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I) 2 >>> (2*I).as_coefficient(pi*I)
See also
coeff()
return sum of terms have a given factor
as_coeff_Add()
separate the additive constant from an expression
as_coeff_Mul()
separate the multiplicative constant from an expression
as_independent()
separate xdependent terms/factors from others
diofant.polys.polytools.Poly.coeff_monomial()
efficiently find the single coefficient of a monomial in Poly

as_coefficients_dict
()[source]¶ Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. If an expression is not an Add it is considered to have a single term.
Examples
>>> (3*x + a*x + 4).as_coefficients_dict() {1: 4, x: 3, a*x: 1} >>> _[a] 0 >>> (3*a*x).as_coefficients_dict() {a*x: 3}

as_content_primitive
(radical=False)[source]¶ This method should recursively remove a Rational from all arguments and return that (content) and the new self (primitive). The content should always be positive and
Mul(*foo.as_content_primitive()) == foo
. The primitive need no be in canonical form and should try to preserve the underlying structure if possible (i.e. expand_mul should not be applied to self).Examples
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)
The as_content_primitive function is recursive and retains structure:
>>> eq.as_content_primitive() (2, x + 3*y*(y + 1) + 1)
Integer powers will have Rationals extracted from the base:
>>> ((2 + 6*x)**2).as_content_primitive() (4, (3*x + 1)**2) >>> ((2 + 6*x)**(2*y)).as_content_primitive() (1, (2*(3*x + 1))**(2*y))
Terms may end up joining once their as_content_primitives are added:
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (11, x*(y + 1)) >>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (9, x*(y + 1)) >>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive() (1, 6.0*x*(y + 1) + 3*z*(y + 1)) >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() (121, x**2*(y + 1)**2) >>> ((5*(x*(1 + y)) + 2.0*x*(3 + 3*y))**2).as_content_primitive() (1, 121.0*x**2*(y + 1)**2)
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5)))

as_expr
(*gens)[source]¶ Convert a polynomial to a Diofant expression.
Examples
>>> f = (x**2 + x*y).as_poly(x, y) >>> f.as_expr() x**2 + x*y
>>> sin(x).as_expr() sin(x)

as_independent
(*deps, **hint)[source]¶ A mostly naive separation of a Mul or Add into arguments that are not are dependent on deps. To obtain as complete a separation of variables as possible, use a separation method first, e.g.:
separatevars() to change Mul, Add and Pow (including exp) into Mul
.expand(mul=True) to change Add or Mul into Add
.expand(log=True) to change log expr into an Add
The only nonnaive thing that is done here is to respect noncommutative ordering of variables.
The returned tuple (i, d) has the following interpretation:
i will has no variable that appears in deps
d will be 1 or else have terms that contain variables that are in deps
if self is an Add then self = i + d
if self is a Mul then self = i*d
if self is anything else, either tuple (self, Integer(1)) or (Integer(1), self) is returned.
To force the expression to be treated as an Add, use the hint as_Add=True
Examples
– self is an Add
>>> (x + x*y).as_independent(x) (0, x*y + x) >>> (x + x*y).as_independent(y) (x, x*y) >>> (2*x*sin(x) + y + x + z).as_independent(x) (y + z, 2*x*sin(x) + x) >>> (2*x*sin(x) + y + x + z).as_independent(x, y) (z, 2*x*sin(x) + x + y)
– self is a Mul
>>> (x*sin(x)*cos(y)).as_independent(x) (cos(y), x*sin(x))
noncommutative terms cannot always be separated out when self is a Mul
>>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False) >>> (n1 + n1*n2).as_independent(n2) (n1, n1*n2) >>> (n2*n1 + n1*n2).as_independent(n2) (0, n1*n2 + n2*n1) >>> (n1*n2*n3).as_independent(n1) (1, n1*n2*n3) >>> (n1*n2*n3).as_independent(n2) (n1, n2*n3) >>> ((xn1)*(xy)).as_independent(x) (1, (x  y)*(x  n1))
– self is anything else:
>>> (sin(x)).as_independent(x) (1, sin(x)) >>> (sin(x)).as_independent(y) (sin(x), 1) >>> exp(x+y).as_independent(x) (1, E**(x + y))
– force self to be treated as an Add:
>>> (3*x).as_independent(x, as_Add=True) (0, 3*x)
– force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=False) (1, x + 3) >>> (3+x).as_independent(x, as_Add=False) (1, x  3)
Note how the below differs from the above in making the constant on the dep term positive.
>>> (y*(3+x)).as_independent(x) (y, x  3)
 – use .as_independent() for true independence testing instead
of .has(). The former considers only symbols in the free symbols while the latter considers all symbols
>>> I = Integral(x, (x, 1, 2)) >>> I.has(x) True >>> x in I.free_symbols False >>> I.as_independent(x) == (I, 1) True >>> (I + x).as_independent(x) == (I, x) True
Note: when trying to get independent terms, a separation method might need to be used first. In this case, it is important to keep track of what you send to this routine so you know how to interpret the returned values
>>> separatevars(exp(x+y)).as_independent(x) (E**y, E**x) >>> (x + x*y).as_independent(y) (x, x*y) >>> separatevars(x + x*y).as_independent(y) (x, y + 1) >>> (x*(1 + y)).as_independent(y) (x, y + 1) >>> (x*(1 + y)).expand(mul=True).as_independent(y) (x, x*y) >>> a, b=symbols('a b', positive=True) >>> (log(a*b).expand(log=True)).as_independent(b) (log(a), log(b))

as_leading_term
(*symbols)[source]¶ Returns the leading (nonzero) term of the series expansion of self.
The _eval_as_leading_term routines are used to do this, and they must always return a nonzero value.
Examples
>>> (1 + x + x**2).as_leading_term(x) 1 >>> (1/x**2 + x + x**2).as_leading_term(x) x**(2)

as_numer_denom
()[source]¶ expression > a/b > a, b
This is just a stub that should be defined by an object’s class methods to get anything else.
See also
normal()
return a/b instead of a, b

as_ordered_terms
(order=None, data=False)[source]¶ Transform an expression to an ordered list of terms.
Examples
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms() [sin(x)**2*cos(x), sin(x)**2, 1]

as_poly
(*gens, **args)[source]¶ Converts
self
to a polynomial or returnsNone
.Examples
>>> (x**2 + x*y).as_poly() Poly(x**2 + x*y, x, y, domain='ZZ')
>>> (x**2 + x*y).as_poly(x, y) Poly(x**2 + x*y, x, y, domain='ZZ')
>>> (x**2 + sin(y)).as_poly(x, y) is None True

as_powers_dict
()[source]¶ Return self as a dictionary of factors with each factor being treated as a power. The keys are the bases of the factors and the values, the corresponding exponents. The resulting dictionary should be used with caution if the expression is a Mul and contains non commutative factors since the order that they appeared will be lost in the dictionary.

as_real_imag
(deep=True, **hints)[source]¶ Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method can’t be confused with re() and im() functions, which does not perform complex expansion at evaluation.
However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.
>>> x, y = symbols('x y', real=True)
>>> (x + y*I).as_real_imag() (x, y)
>>> (z + t*I).as_real_imag() (re(z)  im(t), re(t) + im(z))

aseries
(x, n=6, bound=0, hir=False)[source]¶ Returns asymptotic expansion for “self”.
This is equivalent to
self.series(x, oo, n)
Use the
hir
parameter to produce hierarchical series. It stops the recursion at an early level and may provide nicer and more useful results.If the most rapidly varying subexpression of a given expression f is f itself, the algorithm tries to find a normalized representation of the mrv set and rewrites f using this normalized representation. Use the
bound
parameter to give limit on rewriting coefficients in its normalized form.If the expansion contains an order term, it will be either
O(x**(n))
orO(w**(n))
wherew
belongs to the most rapidly varying expression ofself
.Examples
>>> e = sin(1/x + exp(x))  sin(1/x) >>> e.aseries(x) E**(x)*(1/(24*x**4)  1/(2*x**2) + 1 + O(x**(6), (x, oo))) >>> e.aseries(x, n=3, hir=True) E**(2*x)*sin(1/x)/2 + E**(x)*cos(1/x) + O(E**(3*x), (x, oo))
>>> e = exp(exp(x)/(1  1/x)) >>> e.aseries(x, bound=3) E**(E**x)*E**(E**x/x**2)*E**(E**x/x)*E**(E**x + E**x/(1  1/x)  E**x/x  E**x/x**2) >>> e.aseries(x) E**(E**x/(1  1/x))
Notes
This algorithm is directly induced from the limit computational algorithm provided by Gruntz [Gru96], p.90. It majorly uses the mrv and rewrite subroutines. The overall idea of this algorithm is first to look for the most rapidly varying subexpression w of a given expression f and then expands f in a series in w. Then same thing is recursively done on the leading coefficient till we get constant coefficients.
References

property
canonical_variables
¶ Return a dictionary mapping any variable defined in
self.variables
as underscoresuffixed numbers corresponding to their position inself.variables
. Enough underscores are added to ensure that there will be no clash with existing free symbols.Examples
>>> Lambda(x, 2*x).canonical_variables {x: 0_}

coeff
(x, n=1, right=False)[source]¶ Returns the coefficient from the term(s) containing
x**n
. Ifn
is zero then all terms independent ofx
will be returned.When
x
is noncommutative, the coefficient to the left (default) or right ofx
can be returned. The keyword ‘right’ is ignored whenx
is commutative.See also
diofant.core.expr.Expr.as_coefficient()
,diofant.core.expr.Expr.as_coeff_Add()
,diofant.core.expr.Expr.as_coeff_Mul()
,diofant.core.expr.Expr.as_independent()
,diofant.polys.polytools.Poly.coeff_monomial()
Examples
You can select terms that have an explicit negative in front of them:
>>> (x + 2*y).coeff(1) x >>> (x  2*y).coeff(1) 2*y
You can select terms with no Rational coefficient:
>>> (x + 2*y).coeff(1) x >>> (3 + 2*x + 4*x**2).coeff(1) 0
You can select terms independent of x by making n=0; in this case expr.as_independent(x)[0] is returned (and 0 will be returned instead of None):
>>> (3 + 2*x + 4*x**2).coeff(x, 0) 3 >>> eq = ((x + 1)**3).expand() + 1 >>> eq x**3 + 3*x**2 + 3*x + 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 2] >>> eq = 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 0]
You can select terms that have a numerical term in front of them:
>>> (x  2*y).coeff(2) y >>> (x + sqrt(2)*x).coeff(sqrt(2)) x
The matching is exact:
>>> (3 + 2*x + 4*x**2).coeff(x) 2 >>> (3 + 2*x + 4*x**2).coeff(x**2) 4 >>> (3 + 2*x + 4*x**2).coeff(x**3) 0 >>> (z*(x + y)**2).coeff((x + y)**2) z >>> (z*(x + y)**2).coeff(x + y) 0
In addition, no factoring is done, so 1 + z*(1 + y) is not obtained from the following:
>>> (x + z*(x + x*y)).coeff(x) 1
If such factoring is desired, factor_terms can be used first:
>>> factor_terms(x + z*(x + x*y)).coeff(x) z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False) >>> n.coeff(n) 1 >>> (3*n).coeff(n) 3 >>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m 1 + m >>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m m
If there is more than one possible coefficient 0 is returned:
>>> (n*m + m*n).coeff(n) 0
If there is only one possible coefficient, it is returned:
>>> (n*m + x*m*n).coeff(m*n) x >>> (n*m + x*m*n).coeff(m*n, right=1) 1

collect
(syms, func=None, evaluate=True, exact=False, distribute_order_term=True)[source]¶ See the collect function in diofant.simplify.

compute_leading_term
(x, logx=None)[source]¶ as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first.

could_extract_minus_sign
()[source]¶ Canonical way to choose an element in the set {e, e} where e is any expression. If the canonical element is e, we have e.could_extract_minus_sign() == True, else e.could_extract_minus_sign() == False.
For any expression, the set
{e.could_extract_minus_sign(), (e).could_extract_minus_sign()}
must be{True, False}
.>>> (xy).could_extract_minus_sign() != (yx).could_extract_minus_sign() True

equals
(other, failing_expression=False)[source]¶ Return True if self == other, False if it doesn’t, or None. If failing_expression is True then the expression which did not simplify to a 0 will be returned instead of None.
If
self
is a Number (or complex number) that is not zero, then the result is False.If
self
is a number and has not evaluated to zero, evalf will be used to test whether the expression evaluates to zero. If it does so and the result has significance (i.e. the precision is either 1, for a Rational result, or is greater than 1) then the evalf value will be used to return True or False.

expand
(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[source]¶ Expand an expression using hints.
See also

extract_additively
(c)[source]¶ Return self  c if it’s possible to subtract c from self and make all matching coefficients move towards zero, else return None.
Examples
>>> e = 2*x + 3 >>> e.extract_additively(x + 1) x + 2 >>> e.extract_additively(3*x) >>> e.extract_additively(4) >>> (y*(x + 1)).extract_additively(x + 1) >>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1) (x + 1)*(x + 2*y) + 3
Sometimes autoexpansion will return a less simplified result than desired; gcd_terms might be used in such cases:
>>> (4*x*(y + 1) + y).extract_additively(x) 4*x*(y + 1) + x*(4*y + 3)  x*(4*y + 4) + y >>> gcd_terms(_) x*(4*y + 3) + y
See also

extract_branch_factor
(allow_half=False)[source]¶ Try to write self as
exp_polar(2*pi*I*n)*z
in a nice way. Return (z, n).>>> exp_polar(I*pi).extract_branch_factor() (exp_polar(I*pi), 0) >>> exp_polar(2*I*pi).extract_branch_factor() (1, 1) >>> exp_polar(pi*I).extract_branch_factor() (exp_polar(I*pi), 1) >>> exp_polar(3*pi*I + x).extract_branch_factor() (exp_polar(x + I*pi), 1) >>> (y*exp_polar(5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor() (y*exp_polar(2*pi*x), 1) >>> exp_polar(I*pi/2).extract_branch_factor() (exp_polar(I*pi/2), 0)
If allow_half is True, also extract exp_polar(I*pi):
>>> exp_polar(I*pi).extract_branch_factor(allow_half=True) (1, 1/2) >>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True) (1, 1) >>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True) (1, 3/2) >>> exp_polar(I*pi).extract_branch_factor(allow_half=True) (1, 1/2)

extract_multiplicatively
(c)[source]¶ Return None if it’s not possible to make self in the form c * something in a nice way, i.e. preserving the properties of arguments of self.
>>> x, y = symbols('x y', real=True)
>>> ((x*y)**3).extract_multiplicatively(x**2 * y) x*y**2
>>> ((x*y)**3).extract_multiplicatively(x**4 * y)
>>> (2*x).extract_multiplicatively(2) x
>>> (2*x).extract_multiplicatively(3)
>>> (Rational(1, 2)*x).extract_multiplicatively(3) x/6

getn
()[source]¶ Returns the order of the expression.
The order is determined either from the O(…) term. If there is no O(…) term, it returns None.
Examples
>>> (1 + x + O(x**2)).getn() 2 >>> (1 + x).getn()

invert
(g, *gens, **args)[source]¶ Return the multiplicative inverse of
self
modg
whereself
(andg
) may be symbolic expressions).

property
is_algebraic
¶ Test if self can have only values from the set of algebraic numbers.
References

is_algebraic_expr
(*syms)[source]¶ This tests whether a given expression is algebraic or not, in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.
This function returns False for expressions that are “algebraic expressions” with symbolic exponents. This is a simple extension to the is_rational_function, including rational exponentiation.
Examples
>>> x = Symbol('x', real=True) >>> sqrt(1 + x).is_rational_function() False >>> sqrt(1 + x).is_algebraic_expr() True
This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be an algebraic expression to become one.
>>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1) >>> a.is_algebraic_expr(x) False >>> factor(a).is_algebraic_expr() True
See also
References

property
is_commutative
¶ Test if self commutes with any other object wrt multiplication operation.

property
is_comparable
¶ Test if self can be computed to a real number with precision.
Examples
>>> (I*exp_polar(I*pi/2)).is_comparable True >>> (I*exp_polar(I*pi*2)).is_comparable False

property
is_complex
¶ Test if self can have only values from the set of complex numbers.
See also

property
is_composite
¶ Test if self is a positive integer that has at least one positive divisor other than
1
or the number itself.References

is_constant
(*wrt, **flags)[source]¶ Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.
If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, two strategies are tried:
1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if
wrt
is different than the free symbols.2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.
If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag
failing_number
is True – in that case the numerical value will be returned.If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.
Examples
>>> x.is_constant() False >>> Integer(2).is_constant() True >>> Sum(x, (x, 1, 10)).is_constant() True >>> Sum(x, (x, 1, n)).is_constant() False >>> Sum(x, (x, 1, n)).is_constant(y) True >>> Sum(x, (x, 1, n)).is_constant(n) False >>> Sum(x, (x, 1, n)).is_constant(x) True >>> eq = a*cos(x)**2 + a*sin(x)**2  a >>> eq.is_constant() True >>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0 True
>>> (0**x).is_constant() False >>> x.is_constant() False >>> (x**x).is_constant() False >>> one = cos(x)**2 + sin(x)**2 >>> one.is_constant() True >>> ((one  1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1 True

property
is_even
¶ Test if self can have only values from the set of even integers.
See also
References

property
is_extended_real
¶ Test if self can have only values on the extended real number line.
See also
References

property
is_finite
¶ Test if self absolute value is bounded.
References

property
is_imaginary
¶ Test if self is an imaginary number.
I.e. that it can be written as a real number multiplied by the imaginary unit
I
.References

property
is_infinite
¶ Test if self absolute value can be arbitrarily large.
References

property
is_integer
¶ Test if self can have only values from the set of integers.

property
is_irrational
¶ Test if self value cannot be represented exactly by Rational.
References

property
is_negative
¶ Test if self can have only negative values.
References

property
is_noninteger
¶ Test if self can have only values from the subset of real numbers, that aren’t integers.

property
is_nonnegative
¶ Test if self can have only nonnegative values.
See also
References

property
is_nonpositive
¶ Test if self can have only nonpositive values.

property
is_number
¶ Returns True if ‘self’ has no free symbols.
It will be faster than
if not self.free_symbols
, however, sinceis_number
will fail as soon as it hits a free symbol.Examples
>>> x.is_number False >>> (2*x).is_number False >>> (2 + log(2)).is_number True >>> (2 + Integral(2, x)).is_number False >>> (2 + Integral(2, (x, 1, 2))).is_number True

property
is_odd
¶ Test if self can have only values from the set of odd integers.
See also
References

property
is_polar
¶ Test if self can have values from the Riemann surface of the logarithm.

is_polynomial
(*syms)[source]¶ Return True if self is a polynomial in syms and False otherwise.
This checks if self is an exact polynomial in syms. This function returns False for expressions that are “polynomials” with symbolic exponents. Thus, you should be able to apply polynomial algorithms to expressions for which this returns True, and Poly(expr, *syms) should work if and only if expr.is_polynomial(*syms) returns True. The polynomial does not have to be in expanded form. If no symbols are given, all free symbols in the expression will be used.
This is not part of the assumptions system. You cannot do Symbol(‘z’, polynomial=True).
Examples
>>> ((x**2 + 1)**4).is_polynomial(x) True >>> ((x**2 + 1)**4).is_polynomial() True >>> (2**x + 1).is_polynomial(x) False
>>> n = Symbol('n', nonnegative=True, integer=True) >>> (x**n + 1).is_polynomial(x) False
This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a polynomial to become one.
>>> y = Symbol('y', positive=True) >>> a = sqrt(y**2 + 2*y + 1) >>> a.is_polynomial(y) False >>> factor(a) y + 1 >>> factor(a).is_polynomial(y) True
>>> b = (y**2 + 2*y + 1)/(y + 1) >>> b.is_polynomial(y) False >>> cancel(b) y + 1 >>> cancel(b).is_polynomial(y) True
See also

property
is_positive
¶ Test if self can have only positive values.

property
is_prime
¶ Test if self is a natural number greater than
1
that has no positive divisors other than1
and itself.References

property
is_rational
¶ Test if self can have only values from the set of rationals.

is_rational_function
(*syms)[source]¶ Test whether function is a ratio of two polynomials in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.
This function returns False for expressions that are “rational functions” with symbolic exponents. Thus, you should be able to call .as_numer_denom() and apply polynomial algorithms to the result for expressions for which this returns True.
This is not part of the assumptions system. You cannot do Symbol(‘z’, rational_function=True).
Examples
>>> (x/y).is_rational_function() True
>>> (x**2).is_rational_function() True
>>> (x/sin(y)).is_rational_function(y) False
>>> n = Symbol('n', integer=True) >>> (x**n + 1).is_rational_function(x) False
This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a rational function to become one.
>>> y = Symbol('y', positive=True) >>> a = sqrt(y**2 + 2*y + 1)/y >>> a.is_rational_function(y) False >>> factor(a) (y + 1)/y >>> factor(a).is_rational_function(y) True
See also

property
is_real
¶ Test if self can have only values from the set of real numbers.
See also
References

property
is_transcendental
¶ Test if self can have only values from the set of transcendental numbers.
References

property
is_zero
¶ Test if self is zero.
See also

lseries
(x=None, x0=0, dir='+', logx=None)[source]¶ Wrapper for series yielding an iterator of the terms of the series.
Note: an infinite series will yield an infinite iterator. The following, for exaxmple, will never terminate. It will just keep printing terms of the sin(x) series:
for term in sin(x).lseries(x): print term
The advantage of lseries() over nseries() is that many times you are just interested in the next term in the series (i.e. the first term for example), but you don’t know how many you should ask for in nseries() using the “n” parameter.
See also

nseries
(x, n=6, logx=None)[source]¶ Calculate “n” terms of series in x around 0
This calculates n terms of series in the innermost expressions and then builds up the final series just by “crossmultiplying” everything out.
Advantage – it’s fast, because we don’t have to determine how many terms we need to calculate in advance.
Disadvantage – you may end up with less terms than you may have expected, but the O(x**n) term appended will always be correct and so the result, though perhaps shorter, will also be correct.
 Parameters
x (Symbol) – variable for series expansion (positive and finite symbol)
n (Integer, optional) – number of terms to calculate. Default is 6.
logx (Symbol, optional) – This can be used to replace any log(x) in the returned series with a symbolic value to avoid evaluating log(x) at 0.
Examples
>>> sin(x).nseries(x) x  x**3/6 + x**5/120 + O(x**7) >>> log(x + 1).nseries(x, 5) x  x**2/2 + x**3/3  x**4/4 + O(x**5)
Handling of the
logx
parameter — in the following example the expansion fails sincesin
does not have an asymptotic expansion at oo (the limit of log(x) as x approaches 0).>>> e = sin(log(x)) >>> e.nseries(x) Traceback (most recent call last): ... PoleError: ... >>> logx = Symbol('logx') >>> e.nseries(x, logx=logx) sin(logx)
Notes
This method call the helper method _eval_nseries. Such methods should be implemented in subclasses.
The series expansion code is an important part of the gruntz algorithm for determining limits. _eval_nseries has to return a generalized power series with coefficients in C(log(x), log):
c_0*x**e_0 + ... (finitely many terms)
where e_i are numbers (not necessarily integers) and c_i involve only numbers, the function log, and log(x). (This also means it must not contain log(x(1 + p)), this has to be expanded to log(x) + log(1 + p) if p.is_positive.)

nsimplify
(constants=[], tolerance=None, full=False)[source]¶ See the nsimplify function in diofant.simplify.

primitive
()[source]¶ Return the positive Rational that can be extracted nonrecursively from every term of self (i.e., self is treated like an Add). This is like the as_coeff_Mul() method but primitive always extracts a positive Rational (never a negative or a Float).
Examples
>>> (3*(x + 1)**2).primitive() (3, (x + 1)**2) >>> a = (6*x + 2); a.primitive() (2, 3*x + 1) >>> b = (x/2 + 3); b.primitive() (1/2, x + 6) >>> (a*b).primitive() (1, (x/2 + 3)*(6*x + 2))

round
(p=0)[source]¶ Return x rounded to the given decimal place.
If a complex number would results, apply round to the real and imaginary components of the number.
Examples
>>> Float(10.5).round() 11. >>> pi.round() 3. >>> pi.round(2) 3.14 >>> (2*pi + E*I).round() 6.0 + 3.0*I
The round method has a chopping effect:
>>> (2*pi + I/10).round() 6. >>> (pi/10 + 2*I).round() 2.0*I >>> (pi/10 + E*I).round(2) 0.31 + 2.72*I
Notes
Do not confuse the Python builtin function, round, with the Diofant method of the same name. The former always returns a float (or raises an error if applied to a complex value) while the latter returns either a Number or a complex number:
>>> isinstance(round(Integer(123), 2), Number) False >>> isinstance(Integer(123).round(2), Number) True >>> isinstance((3*I).round(), Mul) True >>> isinstance((1 + 3*I).round(), Add) True

series
(x=None, x0=0, n=6, dir='+', logx=None)[source]¶ Series expansion of “self” around
x = x0
yielding either terms of the series one by one (the lazy series given when n=None), else all the terms at once when n != None.Returns the series expansion of “self” around the point
x = x0
with respect tox
up toO((x  x0)**n, x, x0)
(default n is 6).If
x=None
andself
is univariate, the univariate symbol will be supplied, otherwise an error will be raised.>>> cos(x).series() 1  x**2/2 + x**4/24 + O(x**6) >>> cos(x).series(n=4) 1  x**2/2 + O(x**4) >>> cos(x).series(x, x0=1, n=2) cos(1)  (x  1)*sin(1) + O((x  1)**2, (x, 1)) >>> e = cos(x + exp(y)) >>> e.series(y, n=2) cos(x + 1)  y*sin(x + 1) + O(y**2) >>> e.series(x, n=2) cos(E**y)  x*sin(E**y) + O(x**2)
If
n=None
then a generator of the series terms will be returned.>>> term = cos(x).series(n=None) >>> [next(term) for i in range(2)] [1, x**2/2]
For
dir=+
(default) the series is calculated from the right and fordir=
the series from the left. For smooth functions this flag will not alter the results.>>> abs(x).series(dir="+") x >>> abs(x).series(dir="") x
For rational expressions this method may return original expression.
>>> (1/x).series(x, n=8) 1/x

AtomicExpr¶
symbol¶
Symbol¶

class
diofant.core.symbol.
Symbol
[source]¶ Symbol is a placeholder for atomic symbolic expression.
It has a name and a set of assumptions.
 Parameters
name (str) – The name for Symbol.
**assumptions (dict) – Keyword arguments to specify assumptions for Symbol. Default assumption is commutative=True.
Examples
>>> a, b = symbols('a b') >>> bool(a*b == b*a) True
You can override default assumptions:
>>> A, B = symbols('A B', commutative = False) >>> bool(A*B != B*A) True >>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative True
See also
Wild¶

class
diofant.core.symbol.
Wild
[source]¶ A Wild symbol matches anything, whatever is not explicitly excluded.
Examples
>>> a = Wild('a') >>> x.match(a) {a_: x} >>> pi.match(a) {a_: pi} >>> (3*x**2).match(a*x) {a_: 3*x} >>> cos(x).match(a) {a_: cos(x)} >>> b = Wild('b', exclude=[x]) >>> (3*x**2).match(b*x) >>> b.match(a) {a_: b_} >>> A = WildFunction('A') >>> A.match(a) {a_: A_}
Notes
When using Wild, be sure to use the exclude keyword to make the pattern more precise. Without the exclude pattern, you may get matches that are technically correct, but not what you wanted. For example, using the above without exclude:
>>> a, b = symbols('a b', cls=Wild) >>> (2 + 3*y).match(a*x + b*y) {a_: 2/x, b_: 3}
This is technically correct, because (2/x)*x + 3*y == 2 + 3*y, but you probably wanted it to not match at all. The issue is that you really didn’t want a and b to include x and y, and the exclude parameter lets you specify exactly this. With the exclude parameter, the pattern will not match.
>>> a = Wild('a', exclude=[x, y]) >>> b = Wild('b', exclude=[x, y]) >>> (2 + 3*y).match(a*x + b*y)
Exclude also helps remove ambiguity from matches.
>>> E = 2*x**3*y*z >>> a, b = symbols('a b', cls=Wild) >>> E.match(a*b) {a_: 2*y*z, b_: x**3} >>> a = Wild('a', exclude=[x, y]) >>> E.match(a*b) {a_: z, b_: 2*x**3*y} >>> a = Wild('a', exclude=[x, y, z]) >>> E.match(a*b) {a_: 2, b_: x**3*y*z}
See also
Dummy¶

class
diofant.core.symbol.
Dummy
[source]¶ Dummy symbols are each unique, identified by an internal count index:
>>> bool(Dummy("x") == Dummy("x")) == True False
If a name is not supplied then a string value of the count index will be used. This is useful when a temporary variable is needed and the name of the variable used in the expression is not important.
>>> Dummy() #doctest: +SKIP _Dummy_10
See also
symbols¶

diofant.core.symbol.
symbols
(names, **args)[source]¶ Transform strings into instances of
Symbol
class.symbols()
function returns a sequence of symbols with names taken fromnames
argument, which can be a comma or whitespace delimited string, or a sequence of strings:>>> a, b, c = symbols('a b c')
The type of output is dependent on the properties of input arguments:
>>> symbols('x') x >>> symbols('x,') (x,) >>> symbols('x,y') (x, y) >>> symbols(('a', 'b', 'c')) (a, b, c) >>> symbols(['a', 'b', 'c']) [a, b, c] >>> symbols({'a', 'b', 'c'}) {a, b, c}
If an iterable container is needed for a single symbol, set the
seq
argument toTrue
or terminate the symbol name with a comma:>>> symbols('x', seq=True) (x,)
To reduce typing, range syntax is supported to create indexed symbols. Ranges are indicated by a colon and the type of range is determined by the character to the right of the colon. If the character is a digit then all contiguous digits to the left are taken as the nonnegative starting value (or 0 if there is no digit left of the colon) and all contiguous digits to the right are taken as 1 greater than the ending value:
>>> symbols('x:10') (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) >>> symbols('x5:10') (x5, x6, x7, x8, x9) >>> symbols('x5(:2)') (x50, x51) >>> symbols('x5:10 y:5') (x5, x6, x7, x8, x9, y0, y1, y2, y3, y4) >>> symbols(('x5:10', 'y:5')) ((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
If the character to the right of the colon is a letter, then the single letter to the left (or ‘a’ if there is none) is taken as the start and all characters in the lexicographic range through the letter to the right are used as the range:
>>> symbols('x:z') (x, y, z) >>> symbols('x:c') # null range () >>> symbols('x(:c)') (xa, xb, xc) >>> symbols(':c') (a, b, c) >>> symbols('a:d, x:z') (a, b, c, d, x, y, z) >>> symbols(('a:d', 'x:z')) ((a, b, c, d), (x, y, z))
Multiple ranges are supported; contiguous numerical ranges should be separated by parentheses to disambiguate the ending number of one range from the starting number of the next:
>>> symbols('x:2(1:3)') (x01, x02, x11, x12) >>> symbols(':3:2') # parsing is from left to right (00, 01, 10, 11, 20, 21)
Only one pair of parentheses surrounding ranges are removed, so to include parentheses around ranges, double them. And to include spaces, commas, or colons, escape them with a backslash:
>>> symbols('x((a:b))') (x(a), x(b)) >>> symbols(r'x(:1\,:2)') # or 'x((:1)\,(:2))' (x(0,0), x(0,1))
All newly created symbols have assumptions set according to
args
:>>> a = symbols('a', integer=True) >>> a.is_integer True >>> x, y, z = symbols('x y z', real=True) >>> x.is_real and y.is_real and z.is_real True
Despite its name,
symbols()
can create symbollike objects like instances of Function or Wild classes. To achieve this, setcls
keyword argument to the desired type:>>> symbols('f g h', cls=Function) (f, g, h) >>> type(_[0]) <class 'diofant.core.function.UndefinedFunction'>
var¶

diofant.core.symbol.
var
(names, **args)[source]¶ Create symbols and inject them into the global namespace.
This calls
symbols()
with the same arguments and puts the results into the global namespace. It’s recommended not to usevar()
in library code, wheresymbols()
has to be used.Examples
>>> var('x') x >>> x x
>>> var('a ab abc') (a, ab, abc) >>> abc abc
>>> var('x y', real=True) (x, y) >>> x.is_real and y.is_real True
See also
numbers¶
Number¶

class
diofant.core.numbers.
Number
[source]¶ Represents any kind of number in diofant.
Floating point numbers are represented by the Float class. Integer numbers (of any size), together with rational numbers (again, there is no limit on their size) are represented by the Rational class.
Float¶

class
diofant.core.numbers.
Float
[source]¶ Represent a floatingpoint number of arbitrary precision.
Examples
>>> Float(3.5) 3.50000000000000 >>> Float(3) 3.
Creating Floats from strings (and Python
int
type) will give a minimum precision of 15 digits, but the precision will automatically increase to capture all digits entered.>>> Float(1) 1. >>> Float(10**20) 100000000000000000000. >>> Float('1e20') 1.e+20
However, floatingpoint numbers (Python
float
types) retain only 15 digits of precision:>>> Float(1e20) 1.00000000000000e+20 >>> Float(1.23456789123456789) 1.23456789123457
It may be preferable to enter highprecision decimal numbers as strings:
>>> Float('1.23456789123456789') 1.23456789123456789
The desired number of digits can also be specified:
>>> Float('1e3', 3) 0.00100 >>> Float(100, 4) 100.0
Float can automatically count significant figures if decimal precision argument is omitted. (Autocounting is only allowed for strings and ints).
>>> Float('12e3') 0.012 >>> Float(3) 3. >>> Float('60.e2') # 2 digits significant 6.0e+3 >>> Float('6000.') # 4 digits significant 6000. >>> Float('600e2') # 3 digits significant 6.00
Notes
Floats are inexact by their nature unless their value is a binaryexact value.
>>> approx, exact = Float(.1, 1), Float(.125, 1)
For calculation purposes, you can change the precision of Float, but this will not increase the accuracy of the inexact value. The following is the most accurate 5digit approximation of a value of 0.1 that had only 1 digit of precision:
>>> Float(approx, 5) 0.099609
Please note that you can’t increase precision with evalf:
>>> approx.evalf(5) Traceback (most recent call last): ... PrecisionExhausted: ...
By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float constructor to obtain an arbitrary precision with matching accuracy:
>>> Float(exact, 5) 0.12500 >>> Float(exact, 20) 0.12500000000000000000
Trying to make a highprecision Float from a float is not disallowed, but one must keep in mind that the underlying float (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros:
>>> Float(0.3, 20) 0.29999999999999998890
If you want a 20digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python’s float is used:
>>> Float('0.3', 20) 0.30000000000000000000
Although you can increase the precision of an existing Float using Float it will not increase the accuracy – the underlying value is not changed:
>>> def show(f): # binary rep of Float ... from diofant import Mul, Pow ... s, m, e, b = f._mpf_ ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False) ... print('%s at prec=%s' % (v, f._prec)) ... >>> t = Float('0.3', 3) >>> show(t) 4915/2**14 at prec=13 >>> show(Float(t, 20)) # higher prec, not higher accuracy 4915/2**14 at prec=70 >>> show(Float(t, 2)) # lower prec 307/2**10 at prec=10

property
num
¶ Return mpmath representation.

property
Rational¶

class
diofant.core.numbers.
Rational
[source]¶ Represents integers and rational numbers (p/q) of any size.
Examples
>>> Rational(3) 3 >>> Rational(1, 2) 1/2
Rational is unprejudiced in accepting input. If a float is passed, the underlying value of the binary representation will be returned:
>>> Rational(.5) 1/2 >>> Rational(.2) 3602879701896397/18014398509481984
If the simpler representation of the float is desired then consider limiting the denominator to the desired value or convert the float to a string (which is roughly equivalent to limiting the denominator to 10**12):
>>> Rational(str(.2)) 1/5 >>> Rational(.2).limit_denominator(10**12) 1/5
An arbitrarily precise Rational is obtained when a string literal is passed:
>>> Rational("1.23") 123/100 >>> Rational('1e2') 1/100 >>> Rational(".1") 1/10
The conversion of floats to expressions or simple fractions can be handled with nsimplify:
>>> nsimplify(.3) # numbers that have a simple form 3/10
But if the input does not reduce to a literal Rational, an error will be raised:
>>> Rational(pi) Traceback (most recent call last): ... TypeError: invalid input: pi
Lowlevel access numerator and denominator:
>>> r = Rational(3, 4) >>> r 3/4 >>> r.numerator 3 >>> r.denominator 4
Note that these properties return integers (not Diofant Integers) so some care is needed when using them in expressions:
>>> r.numerator/r.denominator 0.75

as_content_primitive
(radical=False)[source]¶ Return the tuple (R, self/R) where R is the positive Rational extracted from self.
Examples
>>> Rational(3, 2).as_content_primitive() (3/2, 1)

Integer¶

class
diofant.core.numbers.
Integer
[source]¶ 
property
is_composite
¶ Test if self is a positive integer that has at least one positive divisor other than
1
or the number itself.References

property
is_even
¶ Test if self can have only values from the set of even integers.
See also
References

property
is_imaginary
¶ Test if self is an imaginary number.
I.e. that it can be written as a real number multiplied by the imaginary unit
I
.References

property
is_odd
¶ Test if self can have only values from the set of odd integers.
See also
References

property
is_prime
¶ Test if self is a natural number greater than
1
that has no positive divisors other than1
and itself.References

property
is_zero
¶ Test if self is zero.
See also

property
NumberSymbol¶
igcd¶
ilcm¶
mod_inverse¶

diofant.core.numbers.
mod_inverse
(a, m)[source]¶ Return the number c such that, ( a * c ) % m == 1 where c has the same sign as a. If no such value exists, a ValueError is raised.
Examples
Suppose we wish to find multiplicative inverse x of 3 modulo 11. This is the same as finding x such that 3 * x = 1 (mod 11). One value of x that satisfies this congruence is 4. Because 3 * 4 = 12 and 12 = 1 mod(11). This is the value return by mod_inverse:
>>> mod_inverse(3, 11) 4 >>> mod_inverse(3, 11) 4
When there is a common factor between the numerators of
a
andm
the inverse does not exist:>>> mod_inverse(2, 4) Traceback (most recent call last): ... ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(Integer(2)/7, Integer(5)/2) 7/2
References
integer_digits¶
Zero¶
One¶
NegativeOne¶
Half¶
NaN¶

class
diofant.core.numbers.
NaN
[source]¶ Not a Number.
This serves as a place holder for numeric values that are indeterminate. Most operations on NaN, produce another NaN. Most indeterminate forms, such as
0/0
oroo  oo` produce NaN. Two exceptions are ``0**0
andoo**0
, which all produce1
(this is consistent with Python’s float).NaN is loosely related to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python
float('nan')
. Differences are noted below.NaN is mathematically not equal to anything else, even NaN itself. This explains the initially counterintuitive results with
Eq
and==
in the examples below.NaN is not comparable so inequalities raise a TypeError. This is in constrast with floating point nan where all inequalities are false.
NaN is a singleton, and can be accessed by
nan
.Examples
>>> nan is nan True >>> oo  oo nan >>> nan + 1 nan >>> Eq(nan, nan) # mathematical equality false >>> nan == nan # structural equality True
References
Infinity¶

class
diofant.core.numbers.
Infinity
[source]¶ Positive infinite quantity.
In real analysis the symbol \(\infty\) denotes an unbounded limit: \(x\to\infty\) means that \(x\) grows without bound.
Infinity is often used not only to define a limit but as a value in the affinely extended real number system. Points labeled \(+\infty\) and \(\infty\) can be added to the topological space of the real numbers, producing the twopoint compactification of the real numbers. Adding algebraic properties to this gives us the extended real numbers.
Infinity is a singleton, and can be accessed by
oo
, or can be imported asoo
.Examples
>>> 1 + oo oo >>> 42/oo 0 >>> x = Symbol('x') >>> limit(exp(x), x, oo) oo
See also
References
NegativeInfinity¶
ComplexInfinity¶

class
diofant.core.numbers.
ComplexInfinity
[source]¶ Complex infinity.
In complex analysis the symbol \(\tilde\infty\), called “complex infinity”, represents a quantity with infinite magnitude, but undetermined complex phase.
ComplexInfinity is a singleton, and can be accessed by as
zoo
.Examples
>>> zoo + 42 zoo >>> 42/zoo 0 >>> zoo + zoo nan >>> zoo*zoo zoo
See also
Exp1¶

class
diofant.core.numbers.
Exp1
[source]¶ The \(e\) constant.
The transcendental number \(e = 2.718281828\ldots\) is the base of the natural logarithm and of the exponential function, \(e = \exp(1)\). Sometimes called Euler’s number or Napier’s constant.
Exp1 is a singleton, and can be imported as
E
.Examples
>>> E is exp(1) True >>> log(E) 1
References
ImaginaryUnit¶
Pi¶

class
diofant.core.numbers.
Pi
[source]¶ The \(\pi\) constant.
The transcendental number \(\pi = 3.141592654\ldots\) represents the ratio of a circle’s circumference to its diameter, the area of the unit circle, the halfperiod of trigonometric functions, and many other things in mathematics.
Pi is a singleton, and can be imported as
pi
.Examples
>>> pi > 3 true >>> pi.is_irrational True >>> x = Symbol('x') >>> sin(x + 2*pi) sin(x) >>> integrate(exp(x**2), (x, oo, oo)) sqrt(pi)
References
EulerGamma¶

class
diofant.core.numbers.
EulerGamma
[source]¶ The EulerMascheroni constant.
\(\gamma = 0.5772157\ldots\) (also called Euler’s constant) is a mathematical constant recurring in analysis and number theory. It is defined as the limiting difference between the harmonic series and the natural logarithm:
\[\gamma = \lim\limits_{n\to\infty} \left(\sum\limits_{k=1}^n\frac{1}{k}  \ln n\right)\]Examples
>>> EulerGamma.is_irrational >>> EulerGamma > 0 true >>> EulerGamma > 1 false
References
Catalan¶
GoldenRatio¶

class
diofant.core.numbers.
GoldenRatio
[source]¶ The golden ratio, \(\phi\).
\(\phi = \frac{1 + \sqrt{5}}{2}\) is algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum.
Examples
>>> GoldenRatio > 1 true >>> GoldenRatio.expand(func=True) 1/2 + sqrt(5)/2 >>> GoldenRatio.is_irrational True
References
power¶
Pow¶

class
diofant.core.power.
Pow
[source]¶ Defines the expression x**y as “x raised to a power y”.
For complex numbers \(x\) and \(y\),
Pow
gives the principal value of \(exp(y*log(x))\).Singleton definitions involving (0, 1, 1, oo, oo, I, I):
expr
value
reason
z**0
1
Although arguments over 0**0 exist, see [2].
z**1
z
(oo)**(1)
0
(1)**1
1
0**1
zoo
This is not strictly true, as 0**1 may be undefined, but is convenient in some contexts where the base is assumed to be positive.
1**1
1
oo**1
0
0**oo
0
Because for all complex numbers z near 0, z**oo > 0.
0**oo
zoo
This is not strictly true, as 0**oo may be oscillating between positive and negative values or rotating in the complex plane. It is convenient, however, when the base is positive.
1**oo 1**oo
nan
Because there are various cases where lim(x(t),t)=1, lim(y(t),t)=oo (or oo), but lim(x(t)**y(t), t) != 1. See [3].
z**zoo
nan
No limit for z**t for t > zoo.
(1)**oo (1)**(oo)
nan
Because of oscillations in the limit.
oo**oo
oo
oo**oo
0
(oo)**oo (oo)**oo
nan
oo**I (oo)**I
nan
oo**e could probably be best thought of as the limit of x**e for real x as x tends to oo. If e is I, then the limit does not exist and nan is used to indicate that.
oo**(1+I) (oo)**(1+I)
zoo
If the real part of e is positive, then the limit of abs(x**e) is oo. So the limit value is zoo.
oo**(1+I) oo**(1+I)
0
If the real part of e is negative, then the limit is 0.
Because symbolic computations are more flexible that floating point calculations and we prefer to never return an incorrect answer, we choose not to conform to all IEEE 754 conventions. This helps us avoid extra testcase code in the calculation of limits.
References

as_base_exp
()[source]¶ Return base and exp of self.
If base is 1/Integer, then return Integer, exp. If this extra processing is not needed, the base and exp properties will give the raw arguments
Examples
>>> p = Pow(Rational(1, 2), 2, evaluate=False) >>> p.as_base_exp() (2, 2) >>> p.args (1/2, 2)

as_content_primitive
(radical=False)[source]¶ Return the tuple (R, self/R) where R is the positive Rational extracted from self.
Examples
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive() (2, sqrt(1 + sqrt(2))) >>> sqrt(3 + 3*sqrt(2)).as_content_primitive() (1, sqrt(3)*sqrt(1 + sqrt(2)))
>>> ((2*x + 2)**2).as_content_primitive() (4, (x + 1)**2) >>> (4**((1 + y)/2)).as_content_primitive() (2, 4**(y/2)) >>> (3**((1 + y)/2)).as_content_primitive() (1, 3**((y + 1)/2)) >>> (3**((5 + y)/2)).as_content_primitive() (9, 3**((y + 1)/2)) >>> eq = 3**(2 + 2*x) >>> powsimp(eq) == eq True >>> eq.as_content_primitive() (9, 3**(2*x)) >>> powsimp(Mul(*_)) 3**(2*x + 2)
>>> eq = (2 + 2*x)**y >>> s = expand_power_base(eq); s.is_Mul, s (False, (2*x + 2)**y) >>> eq.as_content_primitive() (1, (2*(x + 1))**y) >>> s = expand_power_base(_[1]); s.is_Mul, s (True, 2**y*(x + 1)**y)

property
base
¶ Returns base of the power expression.

property
exp
¶ Returns exponent of the power expression.
mul¶
Mul¶

class
diofant.core.mul.
Mul
[source]¶ 

as_content_primitive
(radical=False)[source]¶ Return the tuple (R, self/R) where R is the positive Rational extracted from self.
Examples
>>> (3*sqrt(2)*(2  2*sqrt(2))).as_content_primitive() (6, sqrt(2)*(sqrt(2) + 1))

as_ordered_factors
(order=None)[source]¶ Transform an expression into an ordered list of factors.
Examples
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors() [2, x, y, sin(x), cos(x)]

as_powers_dict
()[source]¶ Return self as a dictionary of factors with each factor being treated as a power.

as_two_terms
()[source]¶ Return head and tail of self.
This is the most efficient way to get the head and tail of an expression.
if you want only the head, use self.args[0];
if you want to process the arguments of the tail then use self.as_coef_mul() which gives the head and a tuple containing the arguments of the tail when treated as a Mul.
if you want the coefficient when self is treated as an Add then use self.as_coeff_add()[0]
>>> (3*x*y).as_two_terms() (3, x*y)

classmethod
flatten
(seq)[source]¶ Return commutative, noncommutative and order arguments by combining related terms.
Notes
In an expression like
a*b*c
, python process this through diofant asMul(Mul(a, b), c)
. This can have undesirable consequences.Sometimes terms are not combined as one would like: {c.f. https://github.com/sympy/sympy/issues/4596}
>>> 2*(x + 1) # this is the 2arg Mul behavior 2*x + 2 >>> y*(x + 1)*2 2*y*(x + 1) >>> 2*(x + 1)*y # 2arg result will be obtained first y*(2*x + 2) >>> Mul(2, x + 1, y) # all 3 args simultaneously processed 2*y*(x + 1) >>> 2*((x + 1)*y) # parentheses can control this behavior 2*y*(x + 1)
Powers with compound bases may not find a single base to combine with unless all arguments are processed at once. Postprocessing may be necessary in such cases. {c.f. https://github.com/sympy/sympy/issues/5728}
>>> a = sqrt(x*sqrt(y)) >>> a**3 (x*sqrt(y))**(3/2) >>> Mul(a, a, a) (x*sqrt(y))**(3/2) >>> a*a*a x*sqrt(y)*sqrt(x*sqrt(y)) >>> _.subs({a.base: z}).subs({z: a.base}) (x*sqrt(y))**(3/2)
If more than two terms are being multiplied then all the previous terms will be reprocessed for each new argument. So if each of
a
,b
andc
wereMul
expression, thena*b*c
(or building up the product with*=
) will process all the arguments ofa
andb
twice: once whena*b
is computed and again whenc
is multiplied.Using
Mul(a, b, c)
will process all arguments once.
The results of Mul are cached according to arguments, so flatten will only be called once for
Mul(a, b, c)
. If you can structure a calculation so the arguments are most likely to be repeats then this can save time in computing the answer. For example, say you had a Mul, M, that you wished to divide byd[i]
and multiply byn[i]
and you suspect there are many repeats inn
. It would be better to computeM*n[i]/d[i]
rather thanM/d[i]*n[i]
since every time n[i] is a repeat, the product,M*n[i]
will be returned without flattening – the cached value will be returned. If you divide by thed[i]
first (and those are more unique than then[i]
) then that will create a new Mul,M/d[i]
the args of which will be traversed again when it is multiplied byn[i]
.{c.f. https://github.com/sympy/sympy/issues/5706}
This consideration is moot if the cache is turned off.
The validity of the above notes depends on the implementation details of Mul and flatten which may change at any time. Therefore, you should only consider them when your code is highly performance sensitive.

prod¶

diofant.core.mul.
prod
(a, start=1)[source]¶  Return product of elements of a. Start with int 1 so if only
ints are included then an int result is returned.
Examples
>>> prod(range(3)) 0 >>> type(_) is int True >>> prod([Integer(2), 3]) 6 >>> _.is_Integer True
You can start the product at something other than 1:
>>> prod([1, 2], 3) 6
add¶
Add¶

class
diofant.core.add.
Add
[source]¶ 

as_coeff_add
(*deps)[source]¶ Returns a tuple (coeff, args) where self is treated as an Add and coeff is the Number term and args is a tuple of all other terms.
Examples
>>> (7 + 3*x).as_coeff_add() (7, (3*x,)) >>> (7*x).as_coeff_add() (0, (7*x,))

as_coefficients_dict
()[source]¶ Return a dictionary mapping terms to their Rational coefficient.
Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. If an expression is not an Add it is considered to have a single term.
Examples
>>> (3*x + x*y + 4).as_coefficients_dict() {1: 4, x: 3, x*y: 1} >>> _[y] 0 >>> (3*y*x).as_coefficients_dict() {x*y: 3}

as_content_primitive
(radical=False)[source]¶ Return the tuple (R, self/R) where R is the positive Rational extracted from self. If radical is True (default is False) then common radicals will be removed and included as a factor of the primitive expression.
Examples
>>> (3 + 3*sqrt(2)).as_content_primitive() (3, 1 + sqrt(2))
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5)))

as_real_imag
(deep=True, **hints)[source]¶ returns a tuple representing a complex number
Examples
>>> (7 + 9*I).as_real_imag() (7, 9) >>> ((1 + I)/(1  I)).as_real_imag() (0, 1) >>> ((1 + 2*I)*(1 + 3*I)).as_real_imag() (5, 5)

as_two_terms
()[source]¶ Return head and tail of self.
This is the most efficient way to get the head and tail of an expression.
if you want only the head, use self.args[0];
if you want to process the arguments of the tail then use self.as_coef_add() which gives the head and a tuple containing the arguments of the tail when treated as an Add.
if you want the coefficient when self is treated as a Mul then use self.as_coeff_mul()[0]
>>> (3*x*y).as_two_terms() (3, x*y)

extract_leading_order
(symbols)[source]¶ Returns the leading term and its order.
Examples
>>> (x + 1 + 1/x**5).extract_leading_order(x) ((x**(5), O(x**(5))),) >>> (1 + x).extract_leading_order(x) ((1, O(1)),) >>> (x + x**2).extract_leading_order(x) ((x, O(x)),)

classmethod
flatten
(seq)[source]¶ Takes the sequence “seq” of nested Adds and returns a flatten list.
Returns: (commutative_part, noncommutative_part, order_symbols)
Applies associativity, all terms are commutable with respect to addition.
See also

primitive
()[source]¶ Return
(R, self/R)
whereR
is the Rational GCD ofself
.R
is collected only from the leading coefficient of each term.Examples
>>> (2*x + 4*y).primitive() (2, x + 2*y)
>>> (2*x/3 + 4*y/9).primitive() (2/9, 3*x + 2*y)
>>> (2*x/3 + 4.2*y).primitive() (1/3, 2*x + 12.6*y)
No subprocessing of term factors is performed:
>>> ((2 + 2*x)*x + 2).primitive() (1, x*(2*x + 2) + 2)
Recursive subprocessing can be done with the as_content_primitive() method:
>>> ((2 + 2*x)*x + 2).as_content_primitive() (2, x*(x + 1) + 1)
See also

relational¶
Rel¶

diofant.core.relational.
Rel
¶ alias of
diofant.core.relational.Relational
Eq¶

diofant.core.relational.
Eq
¶ alias of
diofant.core.relational.Equality
Ne¶

diofant.core.relational.
Ne
¶ alias of
diofant.core.relational.Unequality
Le¶

diofant.core.relational.
Le
¶ alias of
diofant.core.relational.LessThan
Ge¶

diofant.core.relational.
Ge
¶ alias of
diofant.core.relational.GreaterThan
Relational¶

class
diofant.core.relational.
Relational
[source]¶ Base class for all relation types.
Subclasses of Relational should generally be instantiated directly, but Relational can be instantiated with a valid \(rop\) value to dispatch to the appropriate subclass.
 Parameters
rop (str or None) – Indicates what subclass to instantiate. Valid values can be found in the keys of Relational.ValidRelationalOperator.
Examples
>>> Rel(y, x+x**2, '==') Eq(y, x**2 + x)

as_set
()[source]¶ Rewrites univariate inequality in terms of real sets
Examples
>>> x = Symbol('x', real=True) >>> (x > 0).as_set() (0, oo) >>> Eq(x, 0).as_set() {0}

property
canonical
¶ Return a canonical form of the relational.
 The rules for the canonical form, in order of decreasing priority are:
Number on right if left is not a Number;
Symbol on the left;
Gt/Ge changed to Lt/Le;
Lt/Le are unchanged;
Eq and Ne get ordered args.

equals
(other, failing_expression=False)[source]¶ Return True if the sides of the relationship are mathematically identical and the type of relationship is the same. If failing_expression is True, return the expression whose truth value was unknown.

property
lhs
¶ The lefthand side of the relation.

property
reversed
¶ Return the relationship with sides (and sign) reversed.
Examples
>>> Eq(x, 1) Eq(x, 1) >>> _.reversed Eq(1, x) >>> x < 1 x < 1 >>> _.reversed 1 > x

property
rhs
¶ The righthand side of the relation.
Equality¶

class
diofant.core.relational.
Equality
[source]¶ An equal relation between two objects.
Represents that two objects are equal. If they can be easily shown to be definitively equal (or unequal), this will reduce to True (or False). Otherwise, the relation is maintained as an unevaluated Equality object. Use the
simplify
function on this object for more nontrivial evaluation of the equality relation.As usual, the keyword argument
evaluate=False
can be used to prevent any evaluation.Examples
>>> Eq(y, x + x**2) Eq(y, x**2 + x) >>> Eq(2, 5) false >>> Eq(2, 5, evaluate=False) Eq(2, 5) >>> _.doit() false >>> Eq(exp(x), exp(x).rewrite(cos)) Eq(E**x, sinh(x) + cosh(x)) >>> simplify(_) true
See also
diofant.logic.boolalg.Equivalent
for representing equality between two boolean expressions
Notes
This class is not the same as the == operator. The == operator tests for exact structural equality between two expressions; this class compares expressions mathematically.
If either object defines an \(_eval_Eq\) method, it can be used in place of the default algorithm. If \(lhs._eval_Eq(rhs)\) or \(rhs._eval_Eq(lhs)\) returns anything other than None, that return value will be substituted for the Equality. If None is returned by \(_eval_Eq\), an Equality object will be created as usual.
GreaterThan¶

class
diofant.core.relational.
GreaterThan
[source]¶ Class representations of inequalities.
The
*Than
classes represent unequal relationships, where the lefthand side is generally bigger or smaller than the righthand side. For example, the GreaterThan class represents an unequal relationship where the lefthand side is at least as big as the right side, if not bigger. In mathematical notation:lhs >= rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
(>=)
LessThan
(<=)
StrictGreaterThan
(>)
StrictLessThan
(<)
All classes take two arguments, lhs and rhs.
Signature Example
Math equivalent
GreaterThan(lhs, rhs)
lhs >= rhs
LessThan(lhs, rhs)
lhs <= rhs
StrictGreaterThan(lhs, rhs)
lhs > rhs
StrictLessThan(lhs, rhs)
lhs < rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> e1 = Ge(x, 2) # Ge is a convenience wrapper >>> print(e1) x >= 2
>>> rels = Ge(x, 2), Gt(x, 2), Le(x, 2), Lt(x, 2) >>> print('%s\n%s\n%s\n%s' % rels) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).
>>> e2 = x >= 2 >>> print(e2) x >= 2 >>> print("e1: %s, e2: %s" % (e1, e2)) e1: x >= 2, e2: x >= 2 >>> e1 == e2 True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x >= 1 x >= 1 x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x > 1 x > 1 x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1) >>> print("%s\n%s\n%s" % rels) x <= 1 x <= 1 x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1) >>> print('%s\n%s\n%s' % rels) x < 1 x < 1 x < 1
Notes
There are a couple of “gotchas” when using Python’s operators.
The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a Diofant object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to Diofant to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).
>>> e1 = x > 1 >>> e2 = x >= 1 >>> e3 = x < 1 >>> e4 = x <= 1 >>> e5 = 1 > x >>> e6 = 1 >= x >>> e7 = 1 < x >>> e8 = 1 <= x >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) x > 1 x >= 1 x < 1 x <= 1 x < 1 x <= 1 x > 1 x >= 1
If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:
>>> e1 = Integer(1) > x >>> e2 = Integer(1) >= x >>> e3 = Integer(1) < x >>> e4 = Integer(1) <= x >>> e5 = Gt(1, x) >>> e6 = Ge(1, x) >>> e7 = Lt(1, x) >>> e8 = Le(1, x) >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) 1 > x 1 >= x 1 < x 1 <= x 1 > x 1 >= x 1 < x 1 <= x
The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:
>>> x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python, to create a chained inequality, the only method currently available is to make use of And:
>>> And(x < y, y < z) (x < y) & (y < z)
LessThan¶

class
diofant.core.relational.
LessThan
[source]¶ Class representations of inequalities.
The
*Than
classes represent unequal relationships, where the lefthand side is generally bigger or smaller than the righthand side. For example, the GreaterThan class represents an unequal relationship where the lefthand side is at least as big as the right side, if not bigger. In mathematical notation:lhs >= rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
(>=)
LessThan
(<=)
StrictGreaterThan
(>)
StrictLessThan
(<)
All classes take two arguments, lhs and rhs.
Signature Example
Math equivalent
GreaterThan(lhs, rhs)
lhs >= rhs
LessThan(lhs, rhs)
lhs <= rhs
StrictGreaterThan(lhs, rhs)
lhs > rhs
StrictLessThan(lhs, rhs)
lhs < rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> e1 = Ge(x, 2) # Ge is a convenience wrapper >>> print(e1) x >= 2
>>> rels = Ge(x, 2), Gt(x, 2), Le(x, 2), Lt(x, 2) >>> print('%s\n%s\n%s\n%s' % rels) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).
>>> e2 = x >= 2 >>> print(e2) x >= 2 >>> print("e1: %s, e2: %s" % (e1, e2)) e1: x >= 2, e2: x >= 2 >>> e1 == e2 True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x >= 1 x >= 1 x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x > 1 x > 1 x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1) >>> print("%s\n%s\n%s" % rels) x <= 1 x <= 1 x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1) >>> print('%s\n%s\n%s' % rels) x < 1 x < 1 x < 1
Notes
There are a couple of “gotchas” when using Python’s operators.
The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a Diofant object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to Diofant to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).
>>> e1 = x > 1 >>> e2 = x >= 1 >>> e3 = x < 1 >>> e4 = x <= 1 >>> e5 = 1 > x >>> e6 = 1 >= x >>> e7 = 1 < x >>> e8 = 1 <= x >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) x > 1 x >= 1 x < 1 x <= 1 x < 1 x <= 1 x > 1 x >= 1
If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:
>>> e1 = Integer(1) > x >>> e2 = Integer(1) >= x >>> e3 = Integer(1) < x >>> e4 = Integer(1) <= x >>> e5 = Gt(1, x) >>> e6 = Ge(1, x) >>> e7 = Lt(1, x) >>> e8 = Le(1, x) >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) 1 > x 1 >= x 1 < x 1 <= x 1 > x 1 >= x 1 < x 1 <= x
The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:
>>> x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python, to create a chained inequality, the only method currently available is to make use of And:
>>> And(x < y, y < z) (x < y) & (y < z)
Unequality¶

class
diofant.core.relational.
Unequality
[source]¶ An unequal relation between two objects.
Represents that two objects are not equal. If they can be shown to be definitively equal, this will reduce to False; if definitively unequal, this will reduce to True. Otherwise, the relation is maintained as an Unequality object.
Examples
>>> Ne(y, x+x**2) Ne(y, x**2 + x)
See also
Notes
This class is not the same as the != operator. The != operator tests for exact structural equality between two expressions; this class compares expressions mathematically.
This class is effectively the inverse of Equality. As such, it uses the same algorithms, including any available \(_eval_Eq\) methods.
StrictGreaterThan¶

class
diofant.core.relational.
StrictGreaterThan
[source]¶ Class representations of inequalities.
The
*Than
classes represent unequal relationships, where the lefthand side is generally bigger or smaller than the righthand side. For example, the GreaterThan class represents an unequal relationship where the lefthand side is at least as big as the right side, if not bigger. In mathematical notation:lhs >= rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
(>=)
LessThan
(<=)
StrictGreaterThan
(>)
StrictLessThan
(<)
All classes take two arguments, lhs and rhs.
Signature Example
Math equivalent
GreaterThan(lhs, rhs)
lhs >= rhs
LessThan(lhs, rhs)
lhs <= rhs
StrictGreaterThan(lhs, rhs)
lhs > rhs
StrictLessThan(lhs, rhs)
lhs < rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> e1 = Ge(x, 2) # Ge is a convenience wrapper >>> print(e1) x >= 2
>>> rels = Ge(x, 2), Gt(x, 2), Le(x, 2), Lt(x, 2) >>> print('%s\n%s\n%s\n%s' % rels) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).
>>> e2 = x >= 2 >>> print(e2) x >= 2 >>> print("e1: %s, e2: %s" % (e1, e2)) e1: x >= 2, e2: x >= 2 >>> e1 == e2 True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x >= 1 x >= 1 x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x > 1 x > 1 x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1) >>> print("%s\n%s\n%s" % rels) x <= 1 x <= 1 x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1) >>> print('%s\n%s\n%s' % rels) x < 1 x < 1 x < 1
Notes
There are a couple of “gotchas” when using Python’s operators.
The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a Diofant object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to Diofant to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).
>>> e1 = x > 1 >>> e2 = x >= 1 >>> e3 = x < 1 >>> e4 = x <= 1 >>> e5 = 1 > x >>> e6 = 1 >= x >>> e7 = 1 < x >>> e8 = 1 <= x >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) x > 1 x >= 1 x < 1 x <= 1 x < 1 x <= 1 x > 1 x >= 1
If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:
>>> e1 = Integer(1) > x >>> e2 = Integer(1) >= x >>> e3 = Integer(1) < x >>> e4 = Integer(1) <= x >>> e5 = Gt(1, x) >>> e6 = Ge(1, x) >>> e7 = Lt(1, x) >>> e8 = Le(1, x) >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) 1 > x 1 >= x 1 < x 1 <= x 1 > x 1 >= x 1 < x 1 <= x
The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:
>>> x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python, to create a chained inequality, the only method currently available is to make use of And:
>>> And(x < y, y < z) (x < y) & (y < z)
StrictLessThan¶

class
diofant.core.relational.
StrictLessThan
[source]¶ Class representations of inequalities.
The
*Than
classes represent unequal relationships, where the lefthand side is generally bigger or smaller than the righthand side. For example, the GreaterThan class represents an unequal relationship where the lefthand side is at least as big as the right side, if not bigger. In mathematical notation:lhs >= rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
(>=)
LessThan
(<=)
StrictGreaterThan
(>)
StrictLessThan
(<)
All classes take two arguments, lhs and rhs.
Signature Example
Math equivalent
GreaterThan(lhs, rhs)
lhs >= rhs
LessThan(lhs, rhs)
lhs <= rhs
StrictGreaterThan(lhs, rhs)
lhs > rhs
StrictLessThan(lhs, rhs)
lhs < rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> e1 = Ge(x, 2) # Ge is a convenience wrapper >>> print(e1) x >= 2
>>> rels = Ge(x, 2), Gt(x, 2), Le(x, 2), Lt(x, 2) >>> print('%s\n%s\n%s\n%s' % rels) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).
>>> e2 = x >= 2 >>> print(e2) x >= 2 >>> print("e1: %s, e2: %s" % (e1, e2)) e1: x >= 2, e2: x >= 2 >>> e1 == e2 True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x >= 1 x >= 1 x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1) >>> print('%s\n%s\n%s' % rels) x > 1 x > 1 x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1) >>> print("%s\n%s\n%s" % rels) x <= 1 x <= 1 x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1) >>> print('%s\n%s\n%s' % rels) x < 1 x < 1 x < 1
Notes
There are a couple of “gotchas” when using Python’s operators.
The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a Diofant object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to Diofant to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).
>>> e1 = x > 1 >>> e2 = x >= 1 >>> e3 = x < 1 >>> e4 = x <= 1 >>> e5 = 1 > x >>> e6 = 1 >= x >>> e7 = 1 < x >>> e8 = 1 <= x >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) x > 1 x >= 1 x < 1 x <= 1 x < 1 x <= 1 x > 1 x >= 1
If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:
>>> e1 = Integer(1) > x >>> e2 = Integer(1) >= x >>> e3 = Integer(1) < x >>> e4 = Integer(1) <= x >>> e5 = Gt(1, x) >>> e6 = Ge(1, x) >>> e7 = Lt(1, x) >>> e8 = Le(1, x) >>> print("%s %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)) 1 > x 1 >= x 1 < x 1 <= x 1 > x 1 >= x 1 < x 1 <= x
The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:
>>> x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python, to create a chained inequality, the only method currently available is to make use of And:
>>> And(x < y, y < z) (x < y) & (y < z)
multidimensional¶
vectorize¶

class
diofant.core.multidimensional.
vectorize
(*mdargs)[source]¶ Generalizes a function taking scalars to accept multidimensional arguments.
Examples
>>> @vectorize(0) ... def vsin(x): ... return sin(x)
>>> vsin([1, x, y]) [sin(1), sin(x), sin(y)]
>>> @vectorize(0, 1) ... def vdiff(f, y): ... return diff(f, y)
>>> vdiff([f(x, y), g(x, y)], [x, y]) [[Derivative(f(x, y), x), Derivative(f(x, y), y)], [Derivative(g(x, y), x), Derivative(g(x, y), y)]]
function¶
Lambda¶

class
diofant.core.function.
Lambda
[source]¶ Lambda(x, expr) represents a lambda function similar to Python’s ‘lambda x: expr’. A function of several variables is written as Lambda((x, y, …), expr).
A simple example:
>>> f = Lambda(x, x**2) >>> f(4) 16
For multivariate functions, use:
>>> f2 = Lambda((x, y, z, t), x + y**z + t**z) >>> f2(1, 2, 3, 4) 73
A handy shortcut for lots of arguments:
>>> p = x, y, z >>> f = Lambda(p, x + y*z) >>> f(*p) x + y*z

property
expr
¶ The return value of the function.

property
free_symbols
¶ Return from the atoms of self those which are free symbols.

property
variables
¶ The variables used in the internal representation of the function.

property
WildFunction¶

class
diofant.core.function.
WildFunction
(name, **assumptions)[source]¶ A WildFunction function matches any function (with its arguments).
Examples
>>> F = WildFunction('F') >>> F.nargs Naturals0() >>> x.match(F) >>> F.match(F) {F_: F_} >>> f(x).match(F) {F_: f(x)} >>> cos(x).match(F) {F_: cos(x)} >>> f(x, y).match(F) {F_: f(x, y)}
To match functions with a given number of arguments, set
nargs
to the desired value at instantiation:>>> F = WildFunction('F', nargs=2) >>> F.nargs {2} >>> f(x).match(F) >>> f(x, y).match(F) {F_: f(x, y)}
To match functions with a range of arguments, set
nargs
to a tuple containing the desired number of arguments, e.g. ifnargs = (1, 2)
then functions with 1 or 2 arguments will be matched.>>> F = WildFunction('F', nargs=(1, 2)) >>> F.nargs {1, 2} >>> f(x).match(F) {F_: f(x)} >>> f(x, y).match(F) {F_: f(x, y)} >>> f(x, y, 1).match(F)
Derivative¶

class
diofant.core.function.
Derivative
[source]¶ Carries out differentiation of the given expression with respect to symbols.
expr must define ._eval_derivative(symbol) method that returns the differentiation result. This function only needs to consider the nontrivial case where expr contains symbol and it should call the diff() method internally (not _eval_derivative); Derivative should be the only one to call _eval_derivative.
Simplification of highorder derivatives:
Because there can be a significant amount of simplification that can be done when multiple differentiations are performed, results will be automatically simplified in a fairly conservative fashion unless the keyword
simplify
is set to False.>>> e = sqrt((x + 1)**2 + x) >>> diff(e, x, 5, simplify=False).count_ops() 136 >>> diff(e, x, 5).count_ops() 30
Ordering of variables:
If evaluate is set to True and the expression can not be evaluated, the list of differentiation symbols will be sorted, that is, the expression is assumed to have continuous derivatives up to the order asked. This sorting assumes that derivatives wrt Symbols commute, derivatives wrt nonSymbols commute, but Symbol and nonSymbol derivatives don’t commute with each other.
Derivative wrt nonSymbols:
This class also allows derivatives wrt nonSymbols that have _diff_wrt set to True, such as Function and Derivative. When a derivative wrt a non Symbol is attempted, the nonSymbol is temporarily converted to a Symbol while the differentiation is performed.
Note that this may seem strange, that Derivative allows things like f(g(x)).diff(g(x)), or even f(cos(x)).diff(cos(x)). The motivation for allowing this syntax is to make it easier to work with variational calculus (i.e., the EulerLagrange method). The best way to understand this is that the action of derivative with respect to a nonSymbol is defined by the above description: the object is substituted for a Symbol and the derivative is taken with respect to that. This action is only allowed for objects for which this can be done unambiguously, for example Function and Derivative objects. Note that this leads to what may appear to be mathematically inconsistent results. For example:
>>> (2*cos(x)).diff(cos(x)) 2 >>> (2*sqrt(1  sin(x)**2)).diff(cos(x)) 0
This appears wrong because in fact 2*cos(x) and 2*sqrt(1  sin(x)**2) are identically equal. However this is the wrong way to think of this. Think of it instead as if we have something like this:
>>> from diofant.abc import s >>> def F(u): ... return 2*u ... >>> def G(u): ... return 2*sqrt(1  u**2) ... >>> F(cos(x)) 2*cos(x) >>> G(sin(x)) 2*sqrt(sin(x)**2 + 1) >>> F(c).diff(c) 2 >>> F(c).diff(c) 2 >>> G(s).diff(c) 0 >>> G(sin(x)).diff(cos(x)) 0
Here, the Symbols c and s act just like the functions cos(x) and sin(x), respectively. Think of 2*cos(x) as f(c).subs({c: cos(x)}) (or f(c) at c = cos(x)) and 2*sqrt(1  sin(x)**2) as g(s).subs({s: sin(x)}) (or g(s) at s = sin(x)), where f(u) == 2*u and g(u) == 2*sqrt(1  u**2). Here, we define the function first and evaluate it at the function, but we can actually unambiguously do this in reverse in Diofant, because expr.subs({Function: Symbol}) is welldefined: just structurally replace the function everywhere it appears in the expression.
This is the same notational convenience used in the EulerLagrange method when one says F(t, f(t), f’(t)).diff(f(t)). What is actually meant is that the expression in question is represented by some F(t, u, v) at u = f(t) and v = f’(t), and F(t, f(t), f’(t)).diff(f(t)) simply means F(t, u, v).diff(u) at u = f(t).
We do not allow derivatives to be taken with respect to expressions where this is not so well defined. For example, we do not allow expr.diff(x*y) because there are multiple ways of structurally defining where x*y appears in an expression, some of which may surprise the reader (for example, a very strict definition would have that (x*y*z).diff(x*y) == 0).
>>> (x*y*z).diff(x*y) Traceback (most recent call last): ... ValueError: Can't differentiate wrt the variable: x*y, 1
Note that this definition also fits in nicely with the definition of the chain rule. Note how the chain rule in Diofant is defined using unevaluated Subs objects:
>>> f(2*g(x)).diff(x) 2*Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), (_xi_1, 2*g(x))) >>> f(g(x)).diff(x) Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), (_xi_1, g(x)))
Finally, note that, to be consistent with variational calculus, and to ensure that the definition of substituting a Function for a Symbol in an expression is welldefined, derivatives of functions are assumed to not be related to the function. In other words, we have:
>>> diff(f(x), x).diff(f(x)) 0
The same is true for derivatives of different orders:
>>> diff(f(x), x, 2).diff(diff(f(x), x, 1)) 0 >>> diff(f(x), x, 1).diff(diff(f(x), x, 2)) 0
Note, any class can allow derivatives to be taken with respect to itself.
Examples
Some basic examples:
>>> Derivative(x**2, x, evaluate=True) 2*x >>> Derivative(Derivative(f(x, y), x), y) Derivative(f(x, y), x, y) >>> Derivative(f(x), x, 3) Derivative(f(x), x, x, x) >>> Derivative(f(x, y), y, x, evaluate=True) Derivative(f(x, y), x, y)
Now some derivatives wrt functions:
>>> Derivative(f(x)**2, f(x), evaluate=True) 2*f(x) >>> Derivative(f(g(x)), x, evaluate=True) Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), (_xi_1, g(x)))

doit_numerically
(z0)[source]¶ Evaluate the derivative at z numerically.
When we can represent derivatives at a point, this should be folded into the normal evalf. For now, we need a special method.

property
expr
¶ Return expression.

property
free_symbols
¶ Return from the atoms of self those which are free symbols.

property
variables
¶ Return tuple of symbols, wrt derivative is taken.

diff¶

diofant.core.function.
diff
(f, *symbols, **kwargs)[source]¶ Differentiate f with respect to symbols.
This is just a wrapper to unify .diff() and the Derivative class; its interface is similar to that of integrate(). You can use the same shortcuts for multiple variables as with Derivative. For example, diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative of f(x).
You can pass evaluate=False to get an unevaluated Derivative class. Note that if there are 0 symbols (such as diff(f(x), x, 0), then the result will be the function (the zeroth derivative), even if evaluate=False.
Examples
>>> diff(sin(x), x) cos(x) >>> diff(f(x), x, x, x) Derivative(f(x), x, x, x) >>> diff(f(x), x, 3) Derivative(f(x), x, x, x) >>> diff(sin(x)*cos(y), x, 2, y, 2) sin(x)*cos(y)
>>> type(diff(sin(x), x)) cos >>> type(diff(sin(x), x, evaluate=False)) <class 'diofant.core.function.Derivative'> >>> type(diff(sin(x), x, 0)) sin >>> type(diff(sin(x), x, 0, evaluate=False)) sin
>>> diff(sin(x)) cos(x) >>> diff(sin(x*y)) Traceback (most recent call last): ... ValueError: specify differentiation variables to differentiate sin(x*y)
Note that
diff(sin(x))
syntax is meant only for convenience in interactive sessions and should be avoided in library code.References
FunctionClass¶

class
diofant.core.function.
FunctionClass
(*args, **kwargs)[source]¶ Base class for function classes. FunctionClass is a subclass of type.
Use Function(‘<function name>’ [ , signature ]) to create undefined function classes.

property
nargs
¶ Return a set of the allowed number of arguments for the function.
Examples
If the function can take any number of arguments, the set of whole numbers is returned:
>>> Function('f').nargs Naturals0()
If the function was initialized to accept one or more arguments, a corresponding set will be returned:
>>> Function('f', nargs=1).nargs {1} >>> Function('f', nargs=(2, 1)).nargs {1, 2}
The undefined function, after application, also has the nargs attribute; the actual number of arguments is always available by checking the
args
attribute:>>> f(1).nargs Naturals0() >>> len(f(1).args) 1

property
Function¶

class
diofant.core.function.
Function
[source]¶ Base class for applied mathematical functions.
It also serves as a constructor for undefined function classes.
Examples
First example shows how to use Function as a constructor for undefined function classes:
>>> g = g(x) >>> f f >>> f(x) f(x) >>> g g(x) >>> f(x).diff(x) Derivative(f(x), x) >>> g.diff(x) Derivative(g(x), x)
In the following example Function is used as a base class for
my_func
that represents a mathematical function my_func. Suppose that it is well known, that my_func(0) is 1 and my_func at infinity goes to 0, so we want those two simplifications to occur automatically. Suppose also that my_func(x) is real exactly when x is real. Here is an implementation that honours those requirements:>>> class my_func(Function): ... ... @classmethod ... def eval(cls, x): ... if x.is_Number: ... if x == 0: ... return Integer(1) ... elif x is oo: ... return Integer(0) ... ... def _eval_is_real(self): ... return self.args[0].is_real ... >>> my_func(0) + sin(0) 1 >>> my_func(oo) 0 >>> my_func(3.54).evalf() # Not yet implemented for my_func. my_func(3.54) >>> my_func(I).is_real False
In order for
my_func
to become useful, several other methods would need to be implemented. See source code of some of the already implemented functions for more complete examples.Also, if the function can take more than one argument, then
nargs
must be defined, e.g. ifmy_func
can take one or two arguments then,>>> class my_func(Function): ... nargs = (1, 2) ... >>>
Note
Not all functions are the same
Diofant defines many functions (like cos
and factorial
). It also
allows the user to create generic functions which act as argument
holders. Such functions are created just like symbols:
>>> f = Function('f')
>>> f(2) + f(x)
f(2) + f(x)
If you want to see which functions appear in an expression you can use the atoms method:
>>> e = (f(x) + cos(x) + 2)
>>> e.atoms(Function)
{f(x), cos(x)}
If you just want the function you defined, not Diofant functions, the thing to search for is AppliedUndef:
>>> from diofant.core.function import AppliedUndef
>>> e.atoms(AppliedUndef)
{f(x)}
Subs¶

class
diofant.core.function.
Subs
[source]¶ Represents unevaluated substitutions of an expression.
Subs
receives at least 2 arguments: an expression, a pair of old and new expression to substitute or several such pairs.Subs
objects are generally useful to represent unevaluated derivatives calculated at a point.The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity.
There’s no automatic expansion  use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression.
When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects  in this case the expression is always expanded (for the unevaluated form, use Derivative()).
Examples
>>> e = Subs(f(x).diff(x), (x, y)) >>> e.subs({y: 0}) Subs(Derivative(f(x), x), (x, 0)) >>> e.subs({f: sin}).doit() cos(y)
>>> Subs(f(x)*sin(y) + z, (x, 0), (y, 1)) Subs(z + f(x)*sin(y), (x, 0), (y, 1)) >>> _.doit() z + f(0)*sin(1)

property
expr
¶ The expression on which the substitution operates.

property
free_symbols
¶ Return from the atoms of self those which are free symbols.

n
(dps=15, **options)¶

property
point
¶ The values for which the variables are to be substituted.

property
variables
¶ The variables to be evaluated.

property
expand¶

diofant.core.function.
expand
(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[source]¶ Expand an expression using methods given as hints.
Hints evaluated unless explicitly set to False are:
basic
,log
,multinomial
,mul
,power_base
, andpower_exp
. The following hints are supported but not applied unless set to True:complex
,func
, andtrig
. In addition, the following metahints are supported by some or all of the other hints:frac
,numer
,denom
,modulus
, andforce
.deep
is supported by all hints. Additionally, subclasses of Expr may define their own hints or metahints. Parameters
basic (boolean, optional) – This hint is used for any special rewriting of an object that should be done automatically (along with the other hints like
mul
) when expand is called. This is a catchall hint to handle any sort of expansion that may not be described by the existing hint names.deep (boolean, optional) – If
deep
is set toTrue
(the default), things like arguments of functions are recursively expanded. Usedeep=False
to only expand on the top level.mul (boolean, optional) – Distributes multiplication over addition (``):
>>> (y*(x + z)).expand(mul=True) x*y + y*z
multinomial (boolean, optional) – Expand (x + y + …)**n where n is a positive integer.
>>> ((x + y + z)**2).expand(multinomial=True) x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
power_exp (boolean, optional) – Expand addition in exponents into multiplied bases.
>>> exp(x + y).expand(power_exp=True) E**x*E**y >>> (2**(x + y)).expand(power_exp=True) 2**x*2**y
power_base (boolean, optional) – Split powers of multiplied bases.
This only happens by default if assumptions allow, or if the
force
metahint is used:>>> ((x*y)**z).expand(power_base=True) (x*y)**z >>> ((x*y)**z).expand(power_base=True, force=True) x**z*y**z >>> ((2*y)**z).expand(power_base=True) 2**z*y**z
Note that in some cases where this expansion always holds, Diofant performs it automatically:
>>> (x*y)**2 x**2*y**2
log (boolean, optional) – Pull out power of an argument as a coefficient and split logs products into sums of logs.
Note that these only work if the arguments of the log function have the proper assumptions–the arguments must be positive and the exponents must be real–or else the
force
hint must be True:>>> log(x**2*y).expand(log=True) log(x**2*y) >>> log(x**2*y).expand(log=True, force=True) 2*log(x) + log(y) >>> x, y = symbols('x y', positive=True) >>> log(x**2*y).expand(log=True) 2*log(x) + log(y)
complex (boolean, optional) – Split an expression into real and imaginary parts.
>>> x, y = symbols('x y') >>> (x + y).expand(complex=True) re(x) + re(y) + I*im(x) + I*im(y) >>> cos(x).expand(complex=True) I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))
Note that this is just a wrapper around
as_real_imag()
. Most objects that wish to redefine_eval_expand_complex()
should consider redefiningas_real_imag()
instead.func (boolean : optional) – Expand other functions.
>>> gamma(x + 1).expand(func=True) x*gamma(x)
trig (boolean, optional) – Do trigonometric expansions.
>>> cos(x + y).expand(trig=True) sin(x)*sin(y) + cos(x)*cos(y) >>> sin(2*x).expand(trig=True) 2*sin(x)*cos(x)
Note that the forms of
sin(n*x)
andcos(n*x)
in terms ofsin(x)
andcos(x)
are not unique, due to the identity \(\sin^2(x) + \cos^2(x) = 1\). The current implementation uses the form obtained from Chebyshev polynomials, but this may change.force (boolean, optional) – If the
force
hint is used, assumptions about variables will be ignored in making the expansion.
Notes
You can shut off unwanted methods:
>>> (exp(x + y)*(x + y)).expand() E**x*E**y*x + E**x*E**y*y >>> (exp(x + y)*(x + y)).expand(power_exp=False) E**(x + y)*x + E**(x + y)*y >>> (exp(x + y)*(x + y)).expand(mul=False) E**x*E**y*(x + y)
Use deep=False to only expand on the top level:
>>> exp(x + exp(x + y)).expand() E**x*E**(E**x*E**y) >>> exp(x + exp(x + y)).expand(deep=False) E**(E**(x + y))*E**x
Hints are applied in an arbitrary, but consistent order (in the current implementation, they are applied in alphabetical order, except multinomial comes before mul, but this may change). Because of this, some hints may prevent expansion by other hints if they are applied first. For example,
mul
may distribute multiplications and preventlog
andpower_base
from expanding them. Also, ifmul
is applied beforemultinomial
, the expression might not be fully distributed. The solution is to use the variousexpand_hint
helper functions or to usehint=False
to this function to finely control which hints are applied. Here are some examples:>>> x, y, z = symbols('x y z', positive=True) >>> expand(log(x*(y + z))) log(x) + log(y + z)
Here, we see that
log
was applied beforemul
. To get the mul expanded form, either of the following will work:>>> expand_mul(log(x*(y + z))) log(x*y + x*z) >>> expand(log(x*(y + z)), log=False) log(x*y + x*z)
A similar thing can happen with the
power_base
hint:>>> expand((x*(y + z))**x) (x*y + x*z)**x
To get the
power_base
expanded form, either of the following will work:>>> expand((x*(y + z))**x, mul=False) x**x*(y + z)**x >>> expand_power_base((x*(y + z))**x) x**x*(y + z)**x >>> expand((x + y)*y/x) y + y**2/x
The parts of a rational expression can be targeted:
>>> expand((x + y)*y/x/(x + 1), frac=True) (x*y + y**2)/(x**2 + x) >>> expand((x + y)*y/x/(x + 1), numer=True) (x*y + y**2)/(x*(x + 1)) >>> expand((x + y)*y/x/(x + 1), denom=True) y*(x + y)/(x**2 + x)
The
modulus
metahint can be used to reduce the coefficients of an expression postexpansion:>>> expand((3*x + 1)**2) 9*x**2 + 6*x + 1 >>> expand((3*x + 1)**2, modulus=5) 4*x**2 + x + 1
Either
expand()
the function or.expand()
the method can be used. Both are equivalent:>>> expand((x + 1)**2) x**2 + 2*x + 1 >>> ((x + 1)**2).expand() x**2 + 2*x + 1
Objects can define their own expand hints by defining
_eval_expand_hint()
. The function should take the form:def _eval_expand_hint(self, **hints): # Only apply the method to the toplevel expression ...
See also the example below. Objects should define
_eval_expand_hint()
methods only ifhint
applies to that specific object. The generic_eval_expand_hint()
method defined in Expr will handle the noop case.Each hint should be responsible for expanding that hint only. Furthermore, the expansion should be applied to the toplevel expression only.
expand()
takes care of the recursion that happens whendeep=True
.You should only call
_eval_expand_hint()
methods directly if you are 100% sure that the object has the method, as otherwise you are liable to get unexpectedAttributeError
’s. Note, again, that you do not need to recursively apply the hint to args of your object: this is handled automatically byexpand()
._eval_expand_hint()
should generally not be used at all outside of an_eval_expand_hint()
method. If you want to apply a specific expansion from within another method, use the publicexpand()
function, method, orexpand_hint()
functions.In order for expand to work, objects must be rebuildable by their args, i.e.,
obj.func(*obj.args) == obj
must hold.Expand methods are passed
**hints
so that expand hints may use ‘metahints’–hints that control how different expand methods are applied. For example, theforce=True
hint described above that causesexpand(log=True)
to ignore assumptions is such a metahint. Thedeep
metahint is handled exclusively byexpand()
and is not passed to_eval_expand_hint()
methods.Note that expansion hints should generally be methods that perform some kind of ‘expansion’. For hints that simply rewrite an expression, use the .rewrite() API.
Examples
>>> class MyClass(Expr): ... def __new__(cls, *args): ... args = sympify(args) ... return Expr.__new__(cls, *args) ... ... def _eval_expand_double(self, **hints): ... ''' ... Doubles the args of MyClass. ... ... If there more than four args, doubling is not performed, ... unless force=True is also used (False by default). ... ''' ... force = hints.pop('force', False) ... if not force and len(self.args) > 4: ... return self ... return self.func(*(self.args + self.args)) ... >>> a = MyClass(1, 2, MyClass(3, 4)) >>> a MyClass(1, 2, MyClass(3, 4)) >>> a.expand(double=True) MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) >>> a.expand(double=True, deep=False) MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))
>>> b = MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True) MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True, force=True) MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
See also
expand_log()
,expand_mul()
,expand_multinomial()
,expand_complex()
,expand_trig()
,expand_power_base()
,expand_power_exp()
,expand_func()
,diofant.simplify.hyperexpand.hyperexpand()
References
count_ops¶

diofant.core.function.
count_ops
(expr, visual=False)[source]¶ Return a representation (integer or expression) of the operations in expr.
If
visual
isFalse
(default) then the sum of the coefficients of the visual expression will be returned.If
visual
isTrue
then the number of each type of operation is shown with the core class types (or their virtual equivalent) multiplied by the number of times they occur.If expr is an iterable, the sum of the op counts of the items will be returned.
Examples
Although there isn’t a SUB object, minus signs are interpreted as either negations or subtractions:
>>> (x  y).count_ops(visual=True) SUB >>> (x).count_ops(visual=True) NEG
Here, there are two Adds and a Pow:
>>> (1 + a + b**2).count_ops(visual=True) 2*ADD + POW
In the following, an Add, Mul, Pow and two functions:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=True) ADD + MUL + POW + 2*SIN
for a total of 5:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=False) 5
Note that “what you type” is not always what you get. The expression 1/x/y is translated by diofant into 1/(x*y) so it gives a DIV and MUL rather than two DIVs:
>>> (1/x/y).count_ops(visual=True) DIV + MUL
The visual option can be used to demonstrate the difference in operations for expressions in different forms. Here, the Horner representation is compared with the expanded form of a polynomial:
>>> eq = x*(1 + x*(2 + x*(3 + x))) >>> count_ops(eq.expand(), visual=True)  count_ops(eq, visual=True) MUL + 3*POW
The count_ops function also handles iterables:
>>> count_ops([x, sin(x), None, True, x + 2], visual=False) 2 >>> count_ops([x, sin(x), None, True, x + 2], visual=True) ADD + SIN >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True) 2*ADD + SIN
expand_mul¶

diofant.core.function.
expand_mul
(expr, deep=True)[source]¶ Wrapper around expand that only uses the mul hint. See the expand docstring for more information.
Examples
>>> x, y = symbols('x y', positive=True) >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) E**(x + y)*x*log(x*y**2) + E**(x + y)*y*log(x*y**2)
expand_log¶

diofant.core.function.
expand_log
(expr, deep=True, force=False)[source]¶ Wrapper around expand that only uses the log hint. See the expand docstring for more information.
Examples
>>> x, y = symbols('x y', positive=True) >>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) E**(x + y)*(x + y)*(log(x) + 2*log(y))
expand_func¶
expand_trig¶
expand_complex¶
expand_multinomial¶

diofant.core.function.
expand_multinomial
(expr, deep=True)[source]¶ Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information.
Examples
>>> x, y = symbols('x y', positive=True) >>> expand_multinomial((x + exp(x + 1))**2) 2*E**(x + 1)*x + E**(2*x + 2) + x**2
expand_power_exp¶
expand_power_base¶

diofant.core.function.
expand_power_base
(expr, deep=True, force=False)[source]¶ Wrapper around expand that only uses the power_base hint.
A wrapper to expand(power_base=True) which separates a power with a base that is a Mul into a product of powers, without performing any other expansions, provided that assumptions about the power’s base and exponent allow.
deep=False (default is True) will only apply to the toplevel expression.
force=True (default is False) will cause the expansion to ignore assumptions about the base and exponent. When False, the expansion will only happen if the base is nonnegative or the exponent is an integer.
>>> (x*y)**2 x**2*y**2
>>> (2*x)**y (2*x)**y >>> expand_power_base(_) 2**y*x**y
>>> expand_power_base((x*y)**z) (x*y)**z >>> expand_power_base((x*y)**z, force=True) x**z*y**z >>> expand_power_base(sin((x*y)**z), deep=False) sin((x*y)**z) >>> expand_power_base(sin((x*y)**z), force=True) sin(x**z*y**z)
>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) 2**y*sin(x)**y + 2**y*cos(x)**y
>>> expand_power_base((2*exp(y))**x) 2**x*(E**y)**x
>>> expand_power_base((2*cos(x))**y) 2**y*cos(x)**y
Notice that sums are left untouched. If this is not the desired behavior, apply full
expand()
to the expression:>>> expand_power_base(((x+y)*z)**2) z**2*(x + y)**2 >>> (((x+y)*z)**2).expand() x**2*z**2 + 2*x*y*z**2 + y**2*z**2
>>> expand_power_base((2*y)**(1+z)) 2**(z + 1)*y**(z + 1) >>> ((2*y)**(1+z)).expand() 2*2**z*y*y**z
See also
nfloat¶

diofant.core.function.
nfloat
(expr, n=15, exponent=False)[source]¶ Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True).
Examples
>>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) x**4 + 0.5*x + sqrt(y) + 1.5 >>> nfloat(x**4 + sqrt(y), exponent=True) x**4.0 + y**0.5
evalf¶

class
diofant.core.evalf.
EvalfMixin
[source]¶ Mixin class adding evalf capability.

evalf
(dps=15, subs=None, maxn=110, chop=False, strict=True, quad=None)[source]¶ Evaluate the given formula to an accuracy of dps decimal digits. Optional keyword arguments:
 subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}. The substitutions must be given as a dictionary.
 maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=110)
 chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
 strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=True)
 quad=<str>
Choose algorithm for numerical quadrature. By default, tanhsinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.

n
(dps=15, subs=None, maxn=110, chop=False, strict=True, quad=None)¶ Evaluate the given formula to an accuracy of dps decimal digits. Optional keyword arguments:
 subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}. The substitutions must be given as a dictionary.
 maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=110)
 chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
 strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=True)
 quad=<str>
Choose algorithm for numerical quadrature. By default, tanhsinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.

N¶
containers¶
Tuple¶

class
diofant.core.containers.
Tuple
[source]¶ Wrapper around the builtin tuple object
The Tuple is a subclass of Basic, so that it works well in the Diofant framework. The wrapped tuple is available as self.args, but you can also access elements or slices with [:] syntax.
>>> Tuple(a, b, c)[1:] (b, c) >>> Tuple(a, b, c).subs({a: d}) (d, b, c)
Dict¶

class
diofant.core.containers.
Dict
[source]¶ Wrapper around the builtin dict object
The Dict is a subclass of Basic, so that it works well in the Diofant framework. Because it is immutable, it may be included in sets, but its values must all be given at instantiation and cannot be changed afterwards. Otherwise it behaves identically to the Python dict.
>>> D = Dict({1: 'one', 2: 'two'}) >>> for key in D: ... if key == 1: ... print('%s %s' % (key, D[key])) 1 one
The args are sympified so the 1 and 2 are Integers and the values are Symbols. Queries automatically sympify args so the following work:
>>> 1 in D True >>> D.has('one') # searches keys and values True >>> 'one' in D # not in the keys False >>> D[1] one

property
args
¶ Returns a tuple of arguments of ‘self’.
See also

property
compatibility¶
Reimplementations of constructs introduced in later versions of Python than we support. Also some functions that are needed Diofantwide and are located here for easy import.

class
diofant.core.compatibility.
NotIterable
[source]¶ Use this as mixin when creating a class which is not supposed to return true when iterable() is called on its instances. I.e. avoid infinite loop when calling e.g. list() on the instance

diofant.core.compatibility.
as_int
(n)[source]¶ Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is raised if the input has a nonintegral value.
Examples
>>> 3.0 3.0 >>> as_int(3.0) # convert to int and test for equality 3 >>> int(sqrt(10)) 3 >>> as_int(sqrt(10)) Traceback (most recent call last): ... ValueError: ... is not an integer

diofant.core.compatibility.
default_sort_key
(item, order=None)[source]¶ Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
item
is a Basic object or an object (other than a string) that sympifies to a Basic object. Otherwise, this function produces the key.The
order
argument is passed along to the sort_key routine and is used to determine how the terms within an expression are ordered. (See examples below)order
options are: ‘lex’, ‘grlex’, ‘grevlex’, and reversed values of the same (e.g. ‘revlex’). The default order value is None (which translates to ‘lex’).Examples
>>> from diofant.core.function import UndefinedFunction
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x) True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f')) ((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key('1') ((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key(Integer(1)) ((1, 0, 'Number'), (0, ()), (), 1) >>> default_sort_key(2) ((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for Diofant objects, default_sort_key will accept anything as an argument so it is more robust as a sorting key. For the following, using key= lambda i: i.sort_key() would fail because 2 doesn’t have a sort_key method; that’s why default_sort_key is used. Note, that it also handles sympification of nonstring items likes ints:
>>> a = [2, I, I] >>> sorted(a, key=default_sort_key) [2, I, I]
The returned key can be used anywhere that a key can be specified for a function, e.g. sort, min, max, etc…:
>>> a.sort(key=default_sort_key); a[0] 2 >>> min(a, key=default_sort_key) 2
Notes
The key returned is useful for getting items into a canonical order that will be the same across platforms. It is not directly useful for sorting lists of expressions:
>>> a, b = x, 1/x
Since
a
has only 1 term, its value of sort_key is unaffected byorder
:>>> a.sort_key() == a.sort_key('revlex') True
If
a
andb
are combined then the key will differ because there are terms that can be ordered:>>> eq = a + b >>> eq.sort_key() == eq.sort_key('revlex') False >>> eq.as_ordered_terms() [x, 1/x] >>> eq.as_ordered_terms('revlex') [1/x, x]
But since the keys for each of these terms are independent of
order
’s value, they don’t sort differently when they appear separately in a list:>>> sorted(eq.args, key=default_sort_key) [1/x, x] >>> sorted(eq.args, key=lambda i: default_sort_key(i, order='revlex')) [1/x, x]
The order of terms obtained when using these keys is the order that would be obtained if those terms were factors in a product.
Although it is useful for quickly putting expressions in canonical order, it does not sort expressions based on their complexity defined by the number of operations, power of variables and others:
>>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key) [sin(x)*cos(x), sin(x)] >>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key) [sqrt(x), x, x**2, x**3]

diofant.core.compatibility.
is_sequence
(i, include=None)[source]¶ Return a boolean indicating whether
i
is a sequence in the Diofant sense. If anything that fails the test below should be included as being a sequence for your application, set ‘include’ to that object’s type; multiple types should be passed as a tuple of types.Note: although generators can generate a sequence, they often need special handling to make sure their elements are captured before the generator is exhausted, so these are not included by default in the definition of a sequence.
See also
Examples
>>> from types import GeneratorType >>> is_sequence([]) True >>> is_sequence(set()) False >>> is_sequence('abc') False >>> is_sequence('abc', include=str) True >>> generator = (c for c in 'abc') >>> is_sequence(generator) False >>> is_sequence(generator, include=(str, GeneratorType)) True

diofant.core.compatibility.
iterable
(i, exclude=(<class 'str'>, <class 'dict'>, <class 'diofant.core.compatibility.NotIterable'>))[source]¶ Return a boolean indicating whether
i
is Diofant iterable. True also indicates that the iterator is finite, i.e. you e.g. call list(…) on the instance.When Diofant is working with iterables, it is almost always assuming that the iterable is not a string or a mapping, so those are excluded by default. If you want a pure Python definition, make exclude=None. To exclude multiple items, pass them as a tuple.
See also
Examples
>>> things = [[1], (1,), {1}, Tuple(1), (j for j in [1, 2]), {1: 2}, '1', 1] >>> for i in things: ... print('%s %s' % (iterable(i), type(i))) True <... 'list'> True <... 'tuple'> True <... 'set'> True <class 'diofant.core.containers.Tuple'> True <... 'generator'> False <... 'dict'> False <... 'str'> False <... 'int'>
>>> iterable({}, exclude=None) True >>> iterable({}, exclude=str) True >>> iterable("no", exclude=str) False

diofant.core.compatibility.
ordered
(seq, keys=None, default=True, warn=False)[source]¶ Return an iterator of the seq where keys are used to break ties in a conservative fashion: if, after applying a key, there are no ties then no other keys will be computed.
Two default keys will be applied if 1) keys are not provided or 2) the given keys don’t resolve all ties (but only if \(default\) is True). The two keys are \(_nodes\) (which places smaller expressions before large) and \(default_sort_key\) which (if the \(sort_key\) for an object is defined properly) should resolve any ties.
If
warn
is True then an error will be raised if there were no keys remaining to break ties. This can be used if it was expected that there should be no ties between items that are not identical.Examples
The count_ops is not sufficient to break ties in this list and the first two items appear in their original order (i.e. the sorting is stable):
>>> list(ordered([y + 2, x + 2, x**2 + y + 3], ... count_ops, default=False, warn=False)) [y + 2, x + 2, x**2 + y + 3]
The default_sort_key allows the tie to be broken:
>>> list(ordered([y + 2, x + 2, x**2 + y + 3])) [x + 2, y + 2, x**2 + y + 3]
Here, sequences are sorted by length, then sum:
>>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], ... [lambda x: len(x), lambda x: sum(x)]] >>> list(ordered(seq, keys, default=False, warn=False)) [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
If
warn
is True, an error will be raised if there were not enough keys to break ties:>>> list(ordered(seq, keys, default=False, warn=True)) Traceback (most recent call last): ... ValueError: not enough keys to break ties
Notes
The decorated sort is one of the fastest ways to sort a sequence for which special item comparison is desired: the sequence is decorated, sorted on the basis of the decoration (e.g. making all letters lower case) and then undecorated. If one wants to break ties for items that have the same decorated value, a second key can be used. But if the second key is expensive to compute then it is inefficient to decorate all items with both keys: only those items having identical first key values need to be decorated. This function applies keys successively only when needed to break ties. By yielding an iterator, use of the tiebreaker is delayed as long as possible.
This function is best used in cases when use of the first key is expected to be a good hashing function; if there are no unique hashes from application of a key then that key should not have been used. The exception, however, is that even if there are many collisions, if the first group is small and one does not need to process all items in the list then time will not be wasted sorting what one was not interested in. For example, if one were looking for the minimum in a list and there were several criteria used to define the sort order, then this function would be good at returning that quickly if the first group of candidates is small relative to the number of items being processed.
iterable¶

diofant.core.compatibility.
iterable
(i, exclude=(<class 'str'>, <class 'dict'>, <class 'diofant.core.compatibility.NotIterable'>))[source] Return a boolean indicating whether
i
is Diofant iterable. True also indicates that the iterator is finite, i.e. you e.g. call list(…) on the instance.When Diofant is working with iterables, it is almost always assuming that the iterable is not a string or a mapping, so those are excluded by default. If you want a pure Python definition, make exclude=None. To exclude multiple items, pass them as a tuple.
See also
Examples
>>> things = [[1], (1,), {1}, Tuple(1), (j for j in [1, 2]), {1: 2}, '1', 1] >>> for i in things: ... print('%s %s' % (iterable(i), type(i))) True <... 'list'> True <... 'tuple'> True <... 'set'> True <class 'diofant.core.containers.Tuple'> True <... 'generator'> False <... 'dict'> False <... 'str'> False <... 'int'>
>>> iterable({}, exclude=None) True >>> iterable({}, exclude=str) True >>> iterable("no", exclude=str) False
is_sequence¶

diofant.core.compatibility.
is_sequence
(i, include=None)[source] Return a boolean indicating whether
i
is a sequence in the Diofant sense. If anything that fails the test below should be included as being a sequence for your application, set ‘include’ to that object’s type; multiple types should be passed as a tuple of types.Note: although generators can generate a sequence, they often need special handling to make sure their elements are captured before the generator is exhausted, so these are not included by default in the definition of a sequence.
See also
Examples
>>> from types import GeneratorType >>> is_sequence([]) True >>> is_sequence(set()) False >>> is_sequence('abc') False >>> is_sequence('abc', include=str) True >>> generator = (c for c in 'abc') >>> is_sequence(generator) False >>> is_sequence(generator, include=(str, GeneratorType)) True
as_int¶

diofant.core.compatibility.
as_int
(n)[source] Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is raised if the input has a nonintegral value.
Examples
>>> 3.0 3.0 >>> as_int(3.0) # convert to int and test for equality 3 >>> int(sqrt(10)) 3 >>> as_int(sqrt(10)) Traceback (most recent call last): ... ValueError: ... is not an integer
exprtools¶
gcd_terms¶

diofant.core.exprtools.
gcd_terms
(terms, isprimitive=False, clear=True, fraction=True)[source]¶ Compute the GCD of
terms
and put them together.terms
can be an expression or a nonBasic sequence of expressions which will be handled as though they are terms from a sum.If
isprimitive
is True the _gcd_terms will not run the primitive method on the terms.clear
controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1.fraction
, when True (default), will put the expression over a common denominator.Examples
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2) y*(x + 1)*(x + y + 1) >>> gcd_terms(x/2 + 1) (x + 2)/2 >>> gcd_terms(x/2 + 1, clear=False) x/2 + 1 >>> gcd_terms(x/2 + y/2, clear=False) (x + y)/2 >>> gcd_terms(x/2 + 1/x) (x**2 + 2)/(2*x) >>> gcd_terms(x/2 + 1/x, fraction=False) (x + 2/x)/2 >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False) x/2 + 1/x
>>> gcd_terms(x/2/y + 1/x/y) (x**2 + 2)/(2*x*y) >>> gcd_terms(x/2/y + 1/x/y, fraction=False, clear=False) (x + 2/x)/(2*y)
The
clear
flag was ignored in this case because the returned expression was a rational expression, not a simple sum.
factor_terms¶

diofant.core.exprtools.
factor_terms
(expr, radical=False, clear=False, fraction=False, sign=True)[source]¶ Remove common factors from terms in all arguments without changing the underlying structure of the expr. No expansion or simplification (and no processing of noncommutatives) is performed.
If radical=True then a radical common to all terms will be factored out of any Add subexpressions of the expr.
If clear=False (default) then coefficients will not be separated from a single Add if they can be distributed to leave one or more terms with integer coefficients.
If fraction=True (default is False) then a common denominator will be constructed for the expression.
If sign=True (default) then even if the only factor in common is a 1, it will be factored out of the expression.
Examples
>>> factor_terms(x + x*(2 + 4*y)**3) x*(8*(2*y + 1)**3 + 1) >>> A = Symbol('A', commutative=False) >>> factor_terms(x*A + x*A + x*y*A) x*(y*A + 2*A)
When
clear
is False, a rational will only be factored out of an Add expression if all terms of the Add have coefficients that are fractions:>>> factor_terms(x/2 + 1, clear=False) x/2 + 1 >>> factor_terms(x/2 + 1, clear=True) (x + 2)/2
This only applies when there is a single Add that the coefficient multiplies:
>>> factor_terms(x*y/2 + y, clear=True) y*(x + 2)/2 >>> factor_terms(x*y/2 + y, clear=False) == _ True
If a 1 is all that can be factored out, to not factor it out, the flag
sign
must be False:>>> factor_terms(x  y) (x + y) >>> factor_terms(x  y, sign=False) x  y >>> factor_terms(2*x  2*y, sign=False) 2*(x + y)
Combinatorics¶
Partitions¶

class
diofant.combinatorics.partitions.
Partition
[source]¶ This class represents an abstract partition.
A partition is a set of disjoint sets whose union equals a given set.

property
RGS
¶ Returns the “restricted growth string” of the partition.
The RGS is returned as a list of indices, L, where L[i] indicates the block in which element i appears. For example, in a partition of 3 elements (a, b, c) into 2 blocks ([c], [a, b]) the RGS is [1, 1, 0]: “a” is in block 1, “b” is in block 1 and “c” is in block 0.
Examples
>>> a = Partition([1, 2], [3], [4, 5]) >>> a.members (1, 2, 3, 4, 5) >>> a.RGS (0, 0, 1, 2, 2) >>> a + 1 {{3}, {4}, {5}, {1, 2}} >>> _.RGS (0, 0, 1, 2, 3)

classmethod
from_rgs
(rgs, elements)[source]¶ Creates a set partition from a restricted growth string.
The indices given in rgs are assumed to be the index of the element as given in elements as provided (the elements are not sorted by this routine). Block numbering starts from 0. If any block was not referenced in
rgs
an error will be raised.Examples
>>> Partition.from_rgs([0, 1, 2, 0, 1], list('abcde')) {{c}, {a, d}, {b, e}} >>> Partition.from_rgs([0, 1, 2, 0, 1], list('cbead')) {{e}, {a, c}, {b, d}} >>> a = Partition([1, 4], [2], [3, 5]) >>> Partition.from_rgs(a.RGS, a.members) {{2}, {1, 4}, {3, 5}}

property
partition
¶ Return partition as a sorted list of lists.
Examples
>>> Partition([1], [2, 3]).partition [[1], [2, 3]]

property
rank
¶ Gets the rank of a partition.
Examples
>>> a = Partition([1, 2], [3], [4, 5]) >>> a.rank 13

sort_key
(order=None)[source]¶ Return a canonical key that can be used for sorting.
Ordering is based on the size and sorted elements of the partition and ties are broken with the rank.
Examples
>>> a = Partition([1, 2]) >>> b = Partition([3, 4]) >>> c = Partition([1, x]) >>> d = Partition(list(range(4))) >>> l = [d, b, a + 1, a, c] >>> l.sort(key=default_sort_key); l [{{1, 2}}, {{1}, {2}}, {{1, x}}, {{3, 4}}, {{0, 1, 2, 3}}]

property

class
diofant.combinatorics.partitions.
IntegerPartition
[source]¶ This class represents an integer partition.
In number theory and combinatorics, a partition of a positive integer,
n
, also called an integer partition, is a way of writingn
as a list of positive integers that sum to n. Two partitions that differ only in the order of summands are considered to be the same partition; if order matters then the partitions are referred to as compositions. For example, 4 has five partitions: [4], [3, 1], [2, 2], [2, 1, 1], and [1, 1, 1, 1]; the compositions [1, 2, 1] and [1, 1, 2] are the same as partition [2, 1, 1].References

as_dict
()[source]¶ Return the partition as a dictionary whose keys are the partition integers and the values are the multiplicity of that integer.
Examples
>>> IntegerPartition([1]*3 + [2] + [3]*4).as_dict() {1: 3, 2: 1, 3: 4}

as_ferrers
(char='#')[source]¶ Prints the ferrer diagram of a partition.
Examples
>>> print(IntegerPartition([1, 1, 5]).as_ferrers()) ##### # #

property
conjugate
¶ Computes the conjugate partition of itself.
Examples
>>> a = IntegerPartition([6, 3, 3, 2, 1]) >>> a.conjugate [5, 4, 3, 1, 1, 1]


diofant.combinatorics.partitions.
random_integer_partition
(n, seed=None)[source]¶ Generates a random integer partition summing to
n
as a list of reversesorted integers.Examples
For the following, a seed is given so a known value can be shown; in practice, the seed would not be given.
>>> random_integer_partition(100, seed=[1, 1, 12, 1, 2, 1, 85, 1]) [85, 12, 2, 1] >>> random_integer_partition(10, seed=[1, 2, 3, 1, 5, 1]) [5, 3, 1, 1] >>> random_integer_partition(1) [1]

diofant.combinatorics.partitions.
RGS_generalized
(m)[source]¶ Computes the m + 1 generalized unrestricted growth strings and returns them as rows in matrix.
Examples
>>> RGS_generalized(6) Matrix([ [ 1, 1, 1, 1, 1, 1, 1], [ 1, 2, 3, 4, 5, 6, 0], [ 2, 5, 10, 17, 26, 0, 0], [ 5, 15, 37, 77, 0, 0, 0], [ 15, 52, 151, 0, 0, 0, 0], [ 52, 203, 0, 0, 0, 0, 0], [203, 0, 0, 0, 0, 0, 0]])

diofant.combinatorics.partitions.
RGS_enum
(m)[source]¶ RGS_enum computes the total number of restricted growth strings possible for a superset of size m.
Examples
>>> RGS_enum(4) 15 >>> RGS_enum(5) 52 >>> RGS_enum(6) 203
We can check that the enumeration is correct by actually generating the partitions. Here, the 15 partitions of 4 items are generated:
>>> a = Partition(list(range(4))) >>> s = set() >>> for i in range(20): ...