112
5 Some More Python Essentials
5.3.2 SymPy: Some Basic Functionality
The following script example_symbolic.py gives a quick demonstration of some
of the basic symbolic operations that are supported in Python.
import sympy as sym
x, y = sym.symbols(’x y’)
print(2*x + 3*x - y)
# Algebraic computation
print(sym.diff(x**2, x))
# Differentiates x**2 wrt. x
print(sym.integrate(sym.cos(x), x))
# Integrates cos(x) wrt. x
print(sym.simplify((x**2 + x**3)/x**2))
# Simplifies expression
print(sym.limit(sym.sin(x)/x, x, 0))
# lim of sin(x)/x as x->0
print(sym.solve(5*x - 15, x))
# Solves 5*x = 15
Another useful possibility with sympy, is that sympy expressions may be
converted to lambda functions, which then may be used as “normal” Python
functions for numerical calculations. An example will illustrate.
Let us use sympy to analytically find the derivative of the function f (x) = 5x 3 +
2x 2 − 1, and then make both f and its derivative into Python functions:
import sympy as sym
x = sym.symbols(’x’)
f_expr = 5*x**3 + 2*x**2 - 1
# symbolic expression for f(x)
dfdx_expr = sym.diff(f_expr, x)
# compute f’(x) symbolically
# turn symbolic expressions into functions
f
= sym.lambdify([x], f_expr)
# f = lambda x: 5*x**3 + 2*x**2 - 1
dfdx = sym.lambdify([x], dfdx_expr) # dfdx = lambda x: 15*x**2 + 4*x
print(f(1), dfdx(1))
# call and print, x = 1
Note the arguments to lambdify. The first argument [x] specifies the argument
that the generated function f (and the function dfdx) is supposed to take, while the
second argument f_expr (and dfdx_expr) specifies the expression to be evaluated.
When executed, the program prints 6 and 19, corresponding to f(1) and dfdx(1),
respectively.
Other symbolic calculations for, e.g., Taylor series 3 expansion, linear algebra
(with matrix and vector operations), and (some) differential equation solving are
also possible.
5.3.3 Symbolic Calculations with Some Other Tools
Symbolic computations are also readily accessible through the (partly) free online
tool WolframAlpha, 4 which applies the very advanced Mathematica 5 package as
symbolic engine. The disadvantage with WolframAlpha compared to the SymPy
3 See, e.g., https://en.wikipedia.org/wiki/Taylor_series.
4 http://www.wolframalpha.com.
5 http://en.wikipedia.org/wiki/Mathematica.
Précédent

- 133/350

Suivant