## 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 😊 Posta un commento o usa questo indirizzo per il trackback.