## Category Archives: Python

### 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 😉

Annunci

### 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)) 😜

### 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]).

### 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 😊

### 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`.

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

### SymPy – 11 – semplificazione – 3

Continuo da qui, copio qui.

Semplificazione trigonometrica
Note: SymPy follows Python’s naming conventions for inverse trigonometric functions, which is to append an `a` to the front of the function’s name. For example, the inverse cosine, or arc cosine, is called `acos()`.
Cosa abituale, nota forse inutile.

`trigsimp`
To simplify expressions using trigonometric identities, use `trigsimp()`.

`trigsimp()` also works with hyperbolic trig functions.

Much like `simplify()`, `trigsimp()` applies various trigonometric identities to the input expression, and then uses a heuristic to return the “best” one.

`expand_trig`
To expand trigonometric functions, that is, apply the sum or double angle identities, use `expand_trig()`.

Because `expand_trig()` tends to make trigonometric expressions larger, and `trigsimp()` tends to make them smaller, these identities can be applied in reverse using `trigsimp()`

Potenze
Before we introduce the power simplification functions, a mathematical discussion on the identities held by powers is in order. There are three kinds of identities satisfied by exponents

Identity 1 is always true.

Identity 2 is not always true. For example, if `x=y=−1` and `a=1/2`, then

whereas

However, identity 2 is true at least if `x` and `y` are nonnegative and `a` is real (it may also be true under other conditions as well). A common consequence of the failure of identity 2 is that

Identity 3 is not always true. For example, if `x=−1`, `a=2`, and `b=1/2`, then

and

However, identity 3 is true when `b` is an integer (again, it may also hold in other cases as well). Two common consequences of the failure of identity 3 are that

and that

To summarize

This is important to remember, because by default, SymPy will not perform simplifications if they are not true in general.

In order to make SymPy perform simplifications involving identities that are only true under certain assumptions, we need to put assumptions on our Symbols. We will undertake a full discussion of the assumptions system later, but for now, all we need to know are the following.

• By default, SymPy Symbols are assumed to be complex (elements of `C`). That is, a simplification will not be applied to an expression with a given Symbol unless it holds for all complex numbers.
• Symbols can be given different assumptions by passing the assumption to `symbols()`. For the rest of this section, we will be assuming that `x` and `y` are positive, and that `a` and `b` are real. We will leave `z`, `t`, and `c` as arbitrary complex Symbols to demonstrate what happens in that case.

Note: In SymPy, `sqrt(x)` is just a shortcut to `x**Rational(1, 2)`. They are exactly the same object.

`powsimp`
`powsimp()` applies identities 1 and 2 from above, from left to right.

Notice that `powsimp()` refuses to do the simplification if it is not valid.

If you know that you want to apply this simplification, but you don’t want to mess with assumptions, you can pass the `force=True` flag. This will force the simplification to take place, regardless of assumptions.

Note that in some instances, in particular, when the exponents are integers or rational numbers, and identity 2 holds, it will be applied automatically.

This means that it will be impossible to undo this identity with `powsimp()`, because even if `powsimp()` were to put the bases together, they would be automatically split apart again.

`expand_power_exp` e `expand_power_base`
`expand_power_exp()` e `expand_power_base()` apply identities 1 and 2 from right to left, respectively.

As with `powsimp()`, identity 2 is not applied if it is not valid.

And as with `powsimp()`, you can force the expansion to happen without fiddling with assumptions by using `force=True`.

As with identity 2, identity 1 is applied automatically if the power is a number, and hence cannot be undone with `expand_power_exp()`.

`powdenest`
`powdenest()` applies identity 3, from left to right.

As before, the identity is not applied if it is not true under the given assumptions.

And as before, this can be manually overridden with `force=True`.

### SymPy – 10 – semplificazione – 2

Continuo da qui, copio qui.

Semplificazione di funzioni polinomiali/razionali

`expand`
`expand()` is one of the most common simplification functions in SymPy. Although it has a lot of scopes, for now, we will consider its function in expanding polynomial expressions. For example:

Given a polynomial, `expand()` will put it into a canonical form of a sum of monomials.

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

`factor`
`factor()` takes a polynomial and factors it into irreducible factors over the rational numbers. For example:

For polynomials, `factor()` is the opposite of `expand()`. `factor()` uses a complete multivariate factorization algorithm over the rational numbers, which means that each of the factors returned by `factor()` is guaranteed to be irreducible.

If you are interested in the factors themselves, `factor_list` returns a more structured output.

Note that 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 note that the factors may not be irreducible if the input is no longer a polynomial over the rationals).

`collect`
`collect()` collects common powers of a term in an expression. For example

`collect()` is particularly useful in conjunction with the `.coeff()` method. `expr.coeff(x, n)` gives the coefficient of `x**n` in `expr`:

`cancel`
`cancel()` will take any rational function and put it into the standard canonical form, `pq`, where `p` and `q` are expanded polynomials with no common factors, and the leading coefficients of `p` and `q` do not have denominators (i.e., are integers).

Note that since `factor()` will completely factorize both the numerator and the denominator of an expression, it can also be used to do the same thing:

However, if you are only interested in making sure that the expression is in canceled form, `cancel()` is more efficient than `factor()`.

`apart`
`apart()` performs a partial fraction decomposition on a rational function.

😯 impressionante, vero? 😯

### SymPy – 9 – semplificazione – 1

Continuo da qui, copio qui.

To make this document easier to read, we are going to enable pretty printing.

`simplify`
Now let’s jump in and do some interesting mathematics. One of the most useful features of a symbolic manipulation system is the ability to simplify mathematical expressions. SymPy has dozens of functions to perform various kinds of simplification. There is also one general function called `simplify()` that attempts to apply all of these functions in an intelligent way to arrive at the simplest form of an expression. Here are some examples

Here, `gamma(x)` is `Γ(x)`, the gamma function. We see that `simplify()` is capable of handling a large class of expressions.

But `simplify()` has a pitfall. It just applies all the major simplification operations in SymPy, and uses heuristics to determine the simplest result. But “simplest” is not a well-defined term. For example, say we wanted to “simplify” `x2+2x+1` into `(x+1)2`:

We did not get what we want. There is a function to perform this simplification, called `factor()`, which will be discussed below.

Another pitfall to `simplify()` is that it can be unnecessarily slow, since it tries many kinds of simplifications before picking the best one. If you already know exactly what kind of simplification you are after, it is better to apply the specific simplification function(s) that apply those simplifications.

Applying specific simplification functions instead of `simplify()` also has the advantage that specific functions have certain guarantees about the form of their output. These will be discussed with each function below. For example, `factor()`, when called on a polynomial with rational coefficients, is guaranteed to factor the polynomial into irreducible factors. `simplify()` has no guarantees. It is entirely heuristical, and, as we saw above, it may even miss a possible type of simplification that SymPy is capable of doing.

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

Ottimo consiglio. L’argomento è lungo, pausa 😊

### SymPy – 8 – visualizzare i risultati (printing) – 2

Continuo da qui, copio qui.

In addition to automatic printing, you can explicitly use any one of the printers by calling the appropriate function.

`str`
To get a string form of an expression, use `str(expr)`. This is also the form that is produced by `print(expr)`. String forms are designed to be easy to read, but in a form that is correct Python syntax so that it can be copied and pasted. The `str()` form of an expression will usually look exactly the same as the expression as you would enter it.

`srepr`
The `srepr` form of an expression is designed to show the exact form of an expression. It will be discussed more in the Advanced Expression Manipulation section [prossimamente]. To get it, use `srepr()`.

Note: SymPy does not use the Python builtin `repr()` function for `repr` printing, because in Python `str(list)` calls `repr()` on the elements of the list, and some SymPy functions return lists (such as `solve()`). Since `srepr()` is so verbose, it is unlikely that anyone would want it called by default on the output of `solve()`.

The srepr form is mostly useful for understanding how an expression is built internally.

ASCII Pretty Printer
The ASCII pretty printer is accessed from `pprint()`. If the terminal does not support Unicode, the ASCII printer is used by default. Otherwise, you must pass `use_unicode=False`.

`pprint()` prints the output to the screen. If you want the string form, use `pretty()`.

Unicode Pretty Printer
The Unicode pretty printer is also accessed from `pprint()` and `pretty()`. If the terminal supports Unicode, it is used automatically. If `pprint()` is not able to detect that the terminal supports Unicode, you can pass `use_unicode=True` to force it to use Unicode.

LaTeX
To get the LaTeX form of an expression, use `latex()`.

usando LaTeX Equation Editor poi ottengo

MathML
There is also a printer to MathML, called `print_mathml()`. It must be imported from `sympy.printing.mathml`.

`print_mathml()` prints the output. If you want the string, use the function `mathml()`.

Dot
The `dotprint()` function in `sympy.printing.dot` prints output to dot format, which can be rendered with Graphviz. See the Advanced Expression Manipulation [prossimamente] section for some examples of the output of this printer.