sympy Library in Python

Suppose that in Python you want to   expand  an expression (x+y) to  x2 + y2 + 2 xy, this can be done using sympy library in Python, first of all see a simple program.

from sympy import *
x = Symbol('x')
y = Symbol('y')
z=(x + y)**2
print(expand(z))

Output:- x**2 + 2*x*y + y**2

sympy

How is it happening,

Actually statement x = Symbol(‘x’) is not defining x as a numerical value instead it is defining by a symbol x , i.e x is referring to x.

The same way

Statement y = Symbol(‘y’) is  not defining y as a numerical value instead it is defining by a symbol y , i.e y is referring to y.

And z is referring to (x + y)**2  and expand(z) statement expand it as  x**2 + 2*x*y + y**2.

sympy is not just limited to expanding expressions, using  diff() and  integrate() functions of  sympy differentiation and integration coefficients of functions can be computed, see below.

from sympy import *
x = Symbol('x')
y = Symbol('y')
dy=diff(x**3+3*x, x)
I=integrate(x**3+3*x, x)
print(expand(dy))
print(expand(I))

Outputs

3*x**2 + 3
x**4/4 + 3*x**2/2

sympy

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.