Symbolic computing using Python. Part 1. Fundamentals
Implementation of algorithms in Python using symbolic calculations and interpreted language is very convenient when solving problems of mathematical modeling of processes and objects. Based on SymPy library, Python successfully copes with solving equations and systems, integrating and differentiating, calculating limits, expanding in series and summing up the series, simplifying expressions, and solving differential equations and systems.
When using symbolic calculations, the user is given the opportunity to control the work of the program during its execution by entering any admissible functions with a given number of variables.
As a teacher of the discipline "Computer technology and programming", in the module devoted to programming in Python, I familiarize students with the capabilities of this language for scientific research. Your attention is represented by a series of articles in which you can familiarize yourself with symbolic calculations in Python. I want to warn at once that these articles do not pretend to be absolutely unique, because they are collected on the basis of materials from various sources, their goal is to teach students the basics of symbolic calculations.
The very first step on the way to symbolic calculations is to import the functions of the SymPy module with pip, the package management system Python. If you do this, we will immediately go on to declare the variables.
Note. To shorten the record in all the following examples, the first line is not shown: from sympy import *
Explicit declaration of character variables
For symbolic calculations using the module. SymPy character variables and functions must be declared as such. In programs for mathematical calculations, such as Mathematica or Maple, variables are immediately treated as symbolic. In Python, you must force them to declare symbolic, and you can do this in several ways. The simplest way is to use the functions symbols () or var () . The first function returns a reference to a symbolic object in the form of a variable. The second, without assignment, creates a character variable.
Example code is [/b]
x, y, a, b = symbols ('x y a b') # four character variables are created, the previous values of the variables are overwritten
f = a ** 3 * x + 3 * a ** 2 * x ** 2/2 + a * x ** 3 + x ** 4/4 # the variable f becomes automatically symbolic
type (f)
var ('u, v')
(u, v)
f = sin (u) ** 2 + tan (v) # the variable f automatically becomes a symbolic
type (f)
The main difference between the functions symbols () and var () is that the first function returns a reference to a character object. For use in the future, it must be assigned a variable. The second, without assignment, creates a character variable.
In symbol () and var () functions, you can declare character variables with the index:
Example code is [/b]
x = symbols ('x: 9'); x # range of indices from 0 to 9
(x? x? x? x? x? x? x? x? x8)
x = symbols ('x5: 10'); x # range of indices from 5 to 9
(x? x? x? x? x9)
x = var ('x: 9'); x # range of indices from 0 to 9
(x? x? x? x? x? x? x? x? x8)
x = var ('x5: 10'); x # range of indices from 5 to 9
(x? x? x? x? x9)
You can also assign a type and impose restrictions on character variables directly in the symbols () and var () functions. Sometimes, without such restrictions, obvious transformations do not work, for example, compare:
Example code is [/b]
x = symbols ('x', integer = True) # assign the whole type
sqrt (x ** 2)
Abs (x)
x = symbols ('x', positive = True, integer = True)
sqrt (x ** 2)
x
x = symbols ('x')
sqrt (x ** 2) # this is x if x≥0
sqrt (x ** 2)
x = var ('x', integer = True)
sqrt (x ** 2)
Abs (x)
x = var ('x', positive = True, integer = True)
sqrt (x ** 2)
x
x = var ('x')
sqrt (x ** 2) # this is x if x≥0
sqrt (x ** 2)
To create a container for a single character, use the argument seq = True:
symbols ('x', seq = True)
(x,)
Definition of real values for character variables:
x, y, z = symbols ('x, y, z', real = True)
x.is_real and y.is_real and z.is_real
True
The function S ()
Sometimes, character expressions can be interpreted as numeric Python constants, not SymPy. Therefore, to declare character variables, and also to convert numerical constants to symbolic ones, use the function S (), for example, compare:
expr = x ** 2 + sin (y) + S (10) /2; expr
x ** 2 + sin (y) + 5
type (10)
type (S (10)) # character constant ten
The difference between a Python constant and a symbolic one is that a character constant can be calculated with a specified degree of accuracy, as shown in the following example in comparison with the standard function round () :
z = 1/7; z # calculates the variable z with processor precision
???r3r3447. z1 = S (1) /7; z1
1/7
z2 = z1.n (30); z2 # calculates the variable z2 with an accuracy of up to 30 significant digits
???r3r3447. z3 = round (z???); z3
???r3r3424.
Character names are
If in the current session it is necessary to use the symbolic math permanently, you can import the common symbolic names from the module sympy.abc :
Example code is [/b]
import sympy.abc
dir (sympy.abc)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_clash', '_clash1', '_clash2', 'a', 'alpha', 'b', 'beta', 'c', 'chi', 'd', 'delta', 'division', 'e', 'epsilon', 'eta', 'exec_', 'f', 'g', 'gamma', 'greeks', 'h', 'i', 'iota', 'j', 'k', 'kappa', 'l', 'lamda', 'm', 'mu', 'n', 'nu', 'o', 'omega', 'omicron', 'p', 'phi', 'pi', 'print_function', 'psi', 'q', 'r', 'rho', 's', 'sigma', 'string', 'symbols', 't', 'tau', 'theta', 'u', 'upsilon', 'v', 'w', 'x', 'xi', 'y', 'z', 'zeta']
The name of a variable from the namespace can be deleted with the command del name? name?
:
type (x)
del x, y
x
NameError: name 'x' is not defined
To restore the values of standard constants, as well as the names of some functions, you need to reload the sympy module.
from sympy import *
The method subs ()
It should be remembered that when you record a symbolic expression, it can automatically be simplified, for example:
a, b, c, d, x, y, z, u, v, w = symbols ('a b c d x y z u v w')
x - z + 20 -z-15 + 3 * sin (pi /2) + 2 * z
x + 8
Method subs () It is used to calculate a symbolic expression for given values of variables, for example:
a, x = symbols ('a x')
f = a ** 3 * x + 3 * a ** 2 * x ** 2/2 + a * x ** 3 + x ** 4/4
f.subs (a, 1) # in the expression f instead of the variable a the unit
was substituted. x ** 4/4 + x ** 3 + 3 * x ** 2/2 + x
If you use two arguments in the subs method, then they are interpreted as subs (old, new), ie. the old identifier old is replaced with the new one. The argument of the subs () method can be a sequence that must contain pairs (old, new), and can be a symbolic expression, for example:
a, b, c, d, x, y, z = symbols ('a b c d x y z')
f = a * x ** 3 + b * y ** 2 + c * z + d
f.subs ([(a,1),(b,2),(c,3),(d,4)]) # substitution a = ? b = ? c = ? d = 4
x ** 3 + 2 * y ** 2 + 3 * z + 4
pr = x ** 3 + 4 * x ** 2 + 6 * x + 10
pr.subs (x, 1 /x) # substitution of the character expression
10 + 6 /x + 4 /x ** 2 + x ** (-3)
We draw your attention to the following peculiarity of working with variables (symbolic and ordinary Python variables). Let's execute the following code:
x = 'Hello'
pr = x + 'world'
pr
'Helloworld'
x = 'AAA' # assigned the new value
to the character variable x. pr
'Helloworld'
Here the rule operates: if the variable has changed, then the expression created earlier containing this variable is not recalculated automatically. This rule also works for regular Python variables.
Operations with fractions
The SymPy module can perform calculations with fractions and bring them to a common denominator, for example, compare:
S (1) /3 + S (2) /5
11/15
1/3 + 2/5
???r3r3447.
Functions Rational (numerator, denominator) and Integer () are used to create rational fractions without decimal rounding:
z = Rational (? 7) + Rational (? 5); z
19/35
Integer (1) /Integer (5)
1/5
1/5
???r3r3447. z = Integer (1) /Integer (5) + Rational (? 7); z
17/35
Rounding Computing
In symbolic calculations, the rule works - if nothing is said, do not make any roundings. Look how Python converts the expression in the first case, but leaves the square root in the answer record and does not perform any roundings, and in the second, since one of the numbers is given with a decimal point, the result will be approximate:
sqrt (20)
2 * sqrt (5)
sqrt (20.0) # in the expression, a number with a decimal point of
is used. ???r3r3424.
For any character object, the method exists. evalf () (evaluate float) , which returns its decimal representation:
sqrt (20) .evalf () # The sqrt () function of the sympy
module. ???r3r3447. E.evalf ()
???r3r3424.
In the method evalf ([n,]) You can use an argument that specifies the accuracy of the result (n = the number of significant digits)
sqrt (20) .evalf (30)
???r3r3447. pi.evalf (20)
???r3r3424.
You should also always remember that the real arithmetic does not return the exact result, compare:
from sympy import *
one = S ('one')
one = cos (1) ** 2 + sin (1) ** 2
one.evalf () # equals 1
???r3r3447. (one-1) .evalf () # must be equal to 0
-0.e-124
If it is known that the result contains a calculation error, then using the option chop = True method evalf () it can be deleted. A very small value of the real or imaginary part of the result in this case is replaced by zero. Let's take the previous example:
(one-1) .evalf () # must be equal to 0
-0.e-124
(one - 1) .evalf (chop = True)
0
Infinity
After the first line is executed, from sympy import * The symbol of infinity becomes accessible - oo (two letters "o"), with which you can also perform certain operations:
oo + 1
oo
1000000
The symbol of infinity is mainly used by the functions limit () and integrate () when specifying the limits of integration, which we will discuss in one of the following articles.
Conclusion
The symbolic calculations considered in the article differ from numerical methods in that the results can be further investigated, for example, to determine the extremums of functions, to solve equations with embedded variables, and so on.
I hope my article will be useful to everyone.interested in programming in Python, students and those engaged in scientific research.
It may be interesting
weber
Author27-09-2018, 09:18
Publication DateProgramming / Python
Category- Comments: 0
- Views: 315