It is recommended to download the .ipynb file and related resources here. Then you can test the codes in the article interactively while you are reading in Jupyter.
from IPython.display import display, Math
from sympy import *
init_printing()
from helper import comparator_factory, comparator_eval_factory, comparator_method_factory
x,y,z = symbols('x y z')
comparator = comparator_factory('Before applying {}:','After:')
method_comparator = comparator_method_factory('Before calling {}:','After:')
eval_comparator = comparator_eval_factory('Before evaluation:','After evaluation:')
expr = sin(x)
expr_diff = diff(expr,x)
comparator(expr, diff, x)
diff() can also be called as a method
expr = sin(x)
method_comparator(expr, 'diff', x)
To create an unevaluated derivative, use Derivative class and initiate it with the same syntax with diff()
expr = sin(x)
diff_expr = Derivative(expr,x)
print('Before evaluation:')
display(diff_expr)
And call doit()
method to evaluate it.
print('After evaluation:')
display(diff_expr.doit())
To reduce code duplication, we user eval_comparator
to handle the comparasion in later notes
expr = Derivative(x**4,x,x,x)
eval_comparator(expr)
You can achive the same calculation with the second syntax.
expr = Derivative(x**4,x,3)
eval_comparator(expr)
Just pass the symbols in order, with the same syntax with single variable derivative.
expr = Derivative(exp(x*y*z),x, y, y, z, z, z, z)
eval_comparator(expr)
Or user number to control the derivatives order for each symbol
expr = Derivative(exp(x*y*z),x, y, 2, z, 4)
eval_comparator(expr)
expr = Integral(cos(x),x)
eval_comparator(expr)
To perform a definite integral, pass in a tuple of variable symbol, lower bound and upper bound.
expr = Integral(exp(-x),(x,0,oo))
eval_comparator(expr)
Note, $\infty$ in Sympy is oo (double lower case 'O')
expr = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
eval_comparator(expr)
If Sympy cannot calculate an integral on an expression, it returns an unevaluated integral expression.
expr = Integral(x**x)
eval_comparator(expr)
Similiar with derivatives, limits can be performed through limit() by function or method. To construct an unevaluated expression, initialize an Limit class and call doit() to evaludate the calculation.
By default the limit is calculated from right to left with default setting dir = '+'
.
expr = Limit(sin(x)/x, x, 0)
eval_comparator(expr)
To caluculate a limit from left to right. Pass dir='-'
expr = Limit(sin(x)/x, x, 0, dir = '-')
eval_comparator(expr)
Sympy can calculate an asymptotic series expansion of a funciton around a point $x_0$ with respect to $O(x-x_0)^n$ by calling series
method of an expression.
expr = sin(x)
method_comparator(expr, 'series', x,0,6)
To remove the order term, call removeO()
method
print('Expanded expression without order term:')
expr.series(x,0,6).removeO()