Python language has both good support of numerical calculation as well as symbolic calculation. SymPy module actually is the one for symbolic calculation in python [1][2]. Here we give some brief introduction to its usage in symbolic calculation.
Basic symbolic operations
Define symbolic expressions
1 | import sympy |
Substitute value to symbolic expressions
Substitute number
1 | x_new = x.subs(3) |
Notice the difference between the value substitution for expressions with only one variable and that with more than one variables.
Substitute other symbolic expressions
1 | y_new = sympy.Subs(x**2, y-1) |
What you will get is: .
Simplify the displayed results
Sometimes, after symbolic calculation, the results will be a bunch of mass. You could make results displayed more elegantly with simplify commands [3].
1 | s_simple = sympy.simplify(s) |
Complex numbers variables
Define complex symbolic variables
The complex symbolic variables are a combination of real and imaginary part. The imaginary unit: can be defined as:
1 | import sympy |
Calculate absolute value of a complex variable
1 | # test complex symbolic calculation |
Plot with sympy
Basic plot
1 | # test equation solve with multi-variables |
Plot more curves in one figure
1 | sympy.plot(f0, f2) |
Notice that, sympy and pylab are separated modules, thus we do not need to create a new with pylab.figure().
Solve equations
Define an equation
1 | # test equation solve with multi-variables |
This defines the equation: .
Solve equation for a particular variable
1 | sol1 = sympy.solve(eq1, x) |
Notice that for an equation with more than one variable, eg: , you should specify which variable to solve. Otherwise the solver will solve the first variable by default.
Symbolic calculus
Limitation
With sympy, you can even calculate limitations in calculus.
1 | oo = sympy.oo # define infinity |
Differential
Notice that for functions with more than one variable, you shall specify which variable to conduct differential.
1 | f = c1*x + c2*y**2 |
Integration
You can calculate indefinite integration like this [3]:
1 | Ii = sympy.integrate(f, x) |
You can also calculate definite integration by setting upper and lower limits of integral range.
1 | # declare the infinity large |
Taylor’s expansion
You can even apply Taylor’s expansion on any given functions [3].
1 | sympy.series(sympy.cos(2*x), x) |
Practice example
Eg: Solve a complex circuit
1 | # test the solution to a simple circuit |
This is just the analytic solution of alternating circuit with resonance frequency at: .
Reference:
[1] https://zhuanlan.zhihu.com/p/96738286
[2] https://docs.sympy.org/latest/index.html
[3] https://scipy-lectures.org/packages/sympy.html#integration