Category Archives: Python

SymPy – 21 – matrici – 1

Continuo da qui, copio qui.

To make a matrix in SymPy, use the Matrix object. A matrix is constructed by providing a list of row vectors that make up the matrix. For example, to construct the matrix

use

To make it easy to make column vectors, a list of elements is considered to be a column vector.

Matrices are manipulated just like any other object in SymPy or Python.

One important thing to note about SymPy matrices is that, unlike every other object in SymPy, they are mutable. This means that they can be modified in place, as we will see below. The downside to this is that Matrix cannot be used in places that require immutability, such as inside other SymPy expressions or as keys to dictionaries. If you need an immutable version of Matrix, use ImmutableMatrix.

Operazioni di base
shape
Here are some basic operations on Matrix. To get the shape of a matrix use shape

accedere a righe e colonne
To get an individual row or column of a matrix, use row or col. For example, M.row(0) will get the first row. M.col(-1) will get the last column.

cancellare e inserire righe e colonne
To delete a row or column, use row_del or col_del. These operations will modify the Matrix in place.

To insert rows or columns, use row_insert or col_insert. These operations do not operate in place.

Unless explicitly stated, the methods mentioned below do not operate in place. In general, a method that does not operate in place will return a new Matrix and a method that does operate in place will return None.

Metodi base
As noted above, 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.

To take the transpose of a Matrix, use T.

Costruttori
Several constructors exist for creating common matrices. To create an identity matrix, use eye. eye(n) will create an n×n identity matrix.

To create a matrix of all zeros, use zeros. zeros(n, m) creates an n×m matrix of 0s.

Similarly, ones creates a matrix of ones.

To create diagonal matrices, use diag. The arguments to diag can be either numbers or matrices. A number is interpreted as a 1×1 matrix. The matrices are stacked diagonally. The remaining elements are filled with 0s.

:mrgreen:

Annunci

SymPy – 20 – risolutori – 2

Monument Valley – Masterson

Continuo da qui, copio qui.

Risolvere equazioni differenziali
To solve differential equations, use dsolve. First, create an undefined function by passing cls=Function to the symbols function.

f and g are now undefined functions. We can call f(x), and it will represent an unknown function.

Derivatives of f(x) are unevaluated.

(see the Derivatives [prossimamente] section for more on derivatives).

To represent the differential equation

we would thus use

To solve the ODE, pass it and the function to solve for to dsolve.

dsolve returns an instance of Eq. This is because in general, solutions to differential equations cannot be solved explicitly for the function.

The arbitrary constants in the solutions from dsolve are symbols of the form C1, C2, C3, and so on.

:mrgreen:

SymPy – 19 – risolutori – 1

Continuo da qui, copio qui.

Una nota a riguardo le equazioni
Recall from the gotchas [qui] section of this tutorial that symbolic equations in SymPy are not represented by = or ==, but by Eq.

However, there is an even easier way. In SymPy, any expression not in an Eq is automatically assumed to equal 0 by the solving functions. Since a=b if and only if a−b=0, this means that instead of using x == y, you can just use x - y. For example

This is particularly useful if the equation you wish to solve is already equal to 0. Instead of typing solveset(Eq(expr, 0), x), you can just use solveset(expr, x).

Risolvere algebricamente equazioni
The main function for solving algebraic equations is solveset. The syntax for solveset is solveset(equation, variable=None, domain=S.Complexes) Where equations may be in the form of Eq instances or expressions that are assumed to be equal to zero.

Please note that there is another function called solve which can also be used to solve equations. The syntax is solve(equations, variables) However, it is recommended to use solveset instead.

When solving a single equation, the output of solveset is a FiniteSet or an Interval or ImageSet of the solutions.

If there are no solutions, an EmptySet is returned and if it is not able to find solutions then a ConditionSet is returned.

In the solveset module, the linear system of equations is solved using linsolve. In future we would be able to use linsolve directly from solveset. Following is an example of the syntax of linsolve.

1. List of Equations Form:

2. Augmented Matrix Form:

3. A*x = b Form

Note: The order of solution corresponds the order of given symbols.

In the solveset module, the non linear system of equations is solved using nonlinsolve. Following are examples of nonlinsolve.

No, nonlinsolve risulta non definita, da indagare.
Uh! risolto, con l’aggiornamento di versione come raccontato nel post precedente; si continua 😊

In the solveset module, the non linear system of equations is solved using nonlinsolve. Following are examples of nonlinsolve.

1. When only real solution is present:

2. When only complex solution is present:

3. When both real and complex solution is present:

4. If non linear system of equations is Positive dimensional system (A system with infinitely many solutions is said to be positive-dimensional):

Note:

1. The order of solution corresponds the order of given symbols.

2. Currently nonlinsolve doesn’t return solution in form of LambertW (if there is solution present in the form of LambertW). solve can be used for such cases(not all solution):

3. Currently nonlinsolve is not properly capable of solving the system of equations having trigonometric functions. solve can be used for such cases(not all solution):

solveset reports each solution only once. To get the solutions of a polynomial including multiplicity use roots.

The output {0: 1, 3: 2} of roots means that 0 is a root of multiplicity 1 and 3 is a root of multiplicity 2.

Currently solveset is not capable of solving the equations solvable by LambertW (Transcendental equation solver). solve can be used for such cases:

:mrgreen:

SymPy – 18 – calcolo infinitesimale – 4

Continuo da qui, copio qui.

Ho avuto un po’ di problemi legati alla versione non aggiornata; chissà se ora è OK 😊
L’aggiornamento l’ho effettuato via Anaconda, seguendo le indicazioni qui.

Inoltre riconsidero anche l’uso della Sympy Live Shell: è lenta e torno a IPython 😊

Differenze finite
So far we have looked at expressions with analytic derivatives and primitive functions respectively. But what if we want to have an expression to estimate a derivative of a curve for which we lack a closed form representation, or for which we don’t know the functional values for yet. One approach would be to use a finite difference approach.

The simplest way the differentiate using finite differences is to use the differentiate_finite function:

If we want to expand the intermediate derivative we may pass the flag evaluate=True:

This form however does not respect the product rule.

If you already have a Derivative instance, you can use the as_finite_difference method to generate approximations of the derivative to arbitrary order:

here the first order derivative was approximated around x using a minimum number of points (2 for 1st order derivative) evaluated equidistantly using a step-size of 1. We can use arbitrary steps (possibly containing symbolic expressions):

If you are just interested in evaluating the weights, you can do so manually:

note that we only need the last element in the last sublist returned from finite_diff_weights. The reason for this is that the function also generates weights for lower derivatives and using fewer points (see the documentation of finite_diff_weights for more details).

If using finite_diff_weights directly looks complicated, and the as_finite_difference method of Derivative instances is not flexible enough, you can use apply_finite_diff which takes order, x_list, y_list and x0 as parameters:

:mrgreen:

SymPy – 17 – calcolo infinitesimale – 3

Continuo da qui, copio qui.

Limiti
SymPy can compute symbolic limits with the limit function. The syntax to compute

is limit(f(x), x, x0).

limit should be used instead of subs whenever the point of evaluation is a singularity. Even though SymPy has objects to represent , using them for evaluation is not reliable because they do not keep track of things like rate of growth. Also, things like ∞-∞ and ∞/∞ return NaN (not-a-number). For example

Like Derivative and Integral, limit has an unevaluated counterpart, Limit. To evaluate it, use doit.

To evaluate a limit at one side only, pass '+' or '-' as a third argument to limit. For example, to compute

do

Espansione di serie
SymPy can compute asymptotic series expansions of functions around a point. To compute the expansion of f(x) around the point x=x0 terms of order xn, use f(x).series(x, x0, n). x0 and n can be omitted, in which case the defaults x0=0 and n=6 will be used.

The O(x4) term 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=∞). It means that all x terms with power greater than or equal to x4 are omitted. Order terms can be created and manipulated outside of series. They automatically absorb higher order terms.

If you do not want the order term, use the removeO method.

The O notation supports arbitrary limit points (other than 0):

Aggiornamento: il capitolo continua con Finite differences ma semplicemente non funziona 😡
Le funzioni risultano non definite; Stack Overflow ha diversi post a riguardo, tutti segnalantio problemi. Salto 😜 Forse in futuro… 😉

Aggiornamento 2: era solo la versione da aggiornare; non leggete l’aggiornamento precedente, quello scancellato 😉

:mrgreen:

SymPy – 16 – calcolo infinitesimale – 2

Continuo da qui, copio qui.

Integrali
To compute an integral, use the integrate function. There are two kinds of integrals, definite and indefinite. To compute an indefinite integral, that is, an antiderivative, or primitive, just pass the variable after the expression.

Note that SymPy does not include the constant of integration. If you want it, you can add one yourself, or rephrase your problem as a differential equation and use dsolve to solve it, which does add the constant (see Solving Differential Equations [prossimamente]).

To compute a definite integral, pass the argument (integration_variable, lower_limit, upper_limit). For example, to compute

we would do

Quick Tip: in SymPy is oo (that’s the lowercase letter “oh” twice). This is because oo looks like , and is easy to type.

As with indefinite integrals, you can pass multiple limit tuples to perform a multiple integral. For example, to compute

do

If integrate is unable to compute an integral, it returns an unevaluated Integral object.

As with Derivative, you can create an unevaluated integral using Integral. To later evaluate this integral, call doit.

integrate uses powerful algorithms that are always improving to compute both definite and indefinite integrals, including heuristic pattern matching type algorithms, a partial implementation of the Risch algorithm, and an algorithm using Meijer G-functions that is useful for computing integrals in terms of special functions, especially definite integrals. Here is a sampling of some of the power of integrate.

This last example returned a Piecewise expression because the integral does not converge unless R(y)>1.

Impressionante vero? peccato aver già dato Analisi (I e II (inizio anni ’70)) 😜

:mrgreen:

SymPy – 15 – calcolo infinitesimale – 1

Continuo da qui, copio qui.

This section covers how to do basic calculus tasks such as derivatives, integrals, limits, and series expansions in SymPy.

Derivate
To take derivatives, use the diff function.

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 x4.

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

diff can also be called as a method. The two ways of calling diff are exactly the same, and are provided only for convenience.

To create an unevaluated derivative, use the Derivative class. It has the same syntax as diff.

To evaluate an unevaluated derivative, use the doit method.

These unevaluated objects are useful for delaying the evaluation of the derivative, or for printing purposes. They are also used when SymPy does not know how to compute the derivative of an expression (for example, if it contains an undefined function, which are described in the Solving Differential Equations section [prossimamente]).

:mrgreen:

SymPy – 14 – semplificazione – 6

Continuo da qui, copio qui.

Esempio: frazioni continue
Let’s use SymPy to explore continued fractions. A continued fraction is an expression of the form

where a0,...,an are integers, and a1,...,an are positive. A continued fraction can also be infinite, but infinite objects are more difficult to represent in computers, so we will only examine the finite case here.

A continued fraction of the above form is often represented as a list [a0;a1,...,an]. Let’s write a simple function that converts such a list to its continued fraction form. The easiest way to construct a continued fraction from a list is to work backwards. Note that despite the apparent symmetry of the definition, the first element, a0, must usually be handled differently from the rest.

We use Integer(0) in list_to_frac so that the result will always be a SymPy object, even if we only pass in Python ints.

Every finite continued fraction is a rational number, but we are interested in symbolics here, so let’s create a symbolic continued fraction. The symbols() function that we have been using has a shortcut to create numbered symbols. symbols('a0:5') will create the symbols a0, a1, ..., a5.

This form is useful for understanding continued fractions, but lets put it into standard rational function form using cancel().

Now suppose we were given frac in the above canceled form. In fact, we might be given the fraction in any form, but we can always put it into the above canonical form with cancel(). Suppose that we knew that it could be rewritten as a continued fraction. How could we do this with SymPy? A continued fraction is recursively c+1/f, where c is an integer and f is a (smaller) continued fraction. If we could write the expression in this form, we could pull out each c recursively and add it to a list. We could then get a continued fraction with our list_to_frac() function.

The key observation here is that we can convert an expression to the form c+1/f by doing a partial fraction decomposition with respect to c. This is because f does not contain c. This means we need to use the apart() function. We use apart() to pull the term out, then subtract it from the expression, and take the reciprocal to get the f part.

Now we repeat this process

Segue esercizio senza senso (o che non ho capito). Ora di passare a un altro capitolo 😊

:mrgreen:

SymPy – 13 – semplificazione – 5

Alice McWho

Continuo da qui, copio qui.

Funzioni speciali
SymPy implements dozens of special functions, ranging from functions in combinatorics to mathematical physics.

An extensive list of the special functions included with SymPy and their documentation is at the Functions Module page [prossimamente].

For the purposes of this tutorial, let’s introduce a few special functions in SymPy.

Let’s define x, y, and z as regular, complex Symbols, we will also define k, m, and n.

The factorial function is factorial. factorial(n) represents n!=1⋅2...(n−1)⋅n. n! represents the number of permutations of n distinct items.

The binomial coefficient function is binomial. binomial(n, k) represents

the number of ways to choose k items from a set of n distinct items. It is also often written as nCk, and is pronounced “n choose k“.

The factorial function is closely related to the gamma function, gamma. gamma(z) represents

which for positive integer z is the same as (z−1)!.

The generalized hypergeometric function is hyper. hyper([a_1, ..., a_p], [b_1, ..., b_q], z) represents

The most common case is 2F1, which is often referred to as the ordinary hypergeometric function.

rewrite
A common way to deal with special functions is to rewrite them in terms of one another. This works for any function in SymPy, not just special functions. To rewrite an expression in terms of a function, use expr.rewrite(function). For example,

For some tips on applying more targeted rewriting, see the Advanced Expression Manipulation section [prossimamente].

expand_func
To expand special functions in terms of some identities, use expand_func(). For example

hyperexpand
To rewrite hyper in terms of more standard functions, use hyperexpand().

hyperexpand() also works on the more general Meijer G-function (see its documentation [prossimamente] for more information).

combsimp
To simplify combinatorial expressions, use combsimp().

combsimp() also simplifies expressions with gamma.

:mrgreen:

SymPy – 12 – semplificazione – 4

Continuo da qui, copio qui.

Esponenziali e logaritmi
Note: In SymPy, as in Python and most programming languages, log is the natural logarithm, also known as ln. SymPy automatically provides an alias ln = log in case you forget this.

Logarithms have similar issues as powers. There are two main identities

Neither identity is true for arbitrary complex x and y, due to the branch cut in the complex plane for the complex logarithm. However, sufficient conditions for the identities to hold are if x and y are positive and n is real.
As before, z and t will be Symbols with no additional assumptions.

Note that the identity

is a special case of identities 1 and 2 by

and thus it also holds if x and y are positive, but may not hold in general.

We also see that

comes from

and thus holds when x is real (and it can be verified that it does not hold in general for arbitrary complex x, for example,

expand_log
To apply identities 1 and 2 from left to right, use expand_log(). As always, the identities will not be applied unless they are valid.

As with powsimp() and powdenest(), expand_log() has a force option that can be used to ignore assumptions.

logcombine
To apply identities 1 and 2 from right to left, use logcombine().

logcombine() also has a force option that can be used to ignore assumptions.

:mrgreen: