Calculus
Calculus
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 sympy
If 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 :
sympy.Symbol(): It is used to declare a single variable by passing the
variable as a string into its parameter.
sympy.symbols(): It is used to declare multivariable by passing the
variables as a string into its parameter. All the variables must be separated
by a space forming a string.
Differentiation
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:
Python3
# Importing library
import sympy as sym
# Declaring variables
x, y, z = sym.symbols('x y z')
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:
Python3
Output:
second derivative w.r.t. x: 6*x*y
second derivative w.r.t. y: 6*y
Integration
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:
Python3
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
Limits
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:
Python3
Output:
oo
0
1
Series Expansion
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:
Python3
# assign series
series1 = sym.series(sym.cos(x), x)
print(series1)
# assign series
series2 = sym.series(1/sym.cos(x), x, 0, 4)
print(series2)
Output:
1 - x**2/2 + x**4/24 + O(x**6)
1 + x**2/2 + O(x**4)
# Example usage
import numpy as np
mse = np.mean(np.square(error))
return mse