![]() |
VOOZH | about |
Calculus is a branch of mathematics focused on limits, functions, derivatives, integrals, and infinite series. We will use SymPy library to do calculus with python. SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python.
Installation:
pip install sympyIf we want to write any sympy expression, first we have to declare its symbolic variables. To do this, we can use the following two functions :
We can differentiate any sympy expression by using diff(func, var) method. The parameter func denotes the sympy expression to be differentiated and var denotes the variable with respect to which we have to differentiate.
Example 1:
Output:
derivative w.r.t x: 3*x**2*y
derivative w.r.t y: x**3 + 3*y**2
We can also find higher derivatives using the diff(func, var, n) method. Here, the parameter n denotes the nth derivative to be found.
Example 2:
Output:
second derivative w.r.t. x: 6*x*y
second derivative w.r.t. y: 6*y
You can do indefinite and definite integration of transcendental elementary and special functions via integrate() function.
Syntax for indefinite integration: sympy.integrate(func, var)
Syntax for definite integration: sympy.integrate(func, (var, lower_limit, upper_limit))
The parameter func denotes the sympy expression to be differentiated, var denotes the variable with respect to which we have to differentiate, lower_limit denotes to the lower limit of the definite integration and upper_limit denotes the upper limit of the definite integration.
Note: ∞ in SymPy is oo.
Example 1:
Output:
indefinite integral of cos(x): sin(x)
definite integral of cos(x) between -1 to 1: 2*sin(1)
definite integral of exp(-x) between 0 to ∞: 1
You can calculate limit of a function by using limit(function, variable, point). So, if you want to compute the limit of f(x) as x->0, you would issue limit(f, x, 0).
Example:
Output:
oo
0
1
We can also compute Taylor series expansions of functions around a point. To compute the expansion of f(x) around the point x=x0 terms of order xn, use sympy.series(f, x, x0, n). x0 and n can be omitted, in which case the defaults x0=0 and n=6 will be used.
Example:
Output:
1 - x**2/2 + x**4/24 + O(x**6)
1 + x**2/2 + O(x**4)
The O(x4) or O(x6) term at the end means that all x terms with a power greater than or equal to x4 or x6 are omitted.