The SymPy library in Python

SymPy is a robust Python library that helps solve and visualize complex mathematical expressions. These expressions may be related to differentiation, integration, trigonometry, and polynomials. There is a wide range of notable uses of SymPy. This is because researchers from various disciplines that require simplification of mathematical expressions, such as computer science and physics, use this library to save their necessary time.

In this Answer, we will discuss the applications and the functions provided by the Sympy library.

Applications of the SymPy library

The applications of the SymPy library are illustrated below.

Applications of SymPy
Applications of SymPy

Algebraic manipulations

SymPy library helps in manipulating the algebraic expressions. Below are key points that explain how we can perform different operations in SymPy.

  • It helps in simplifying algebraic expressions. To represent the variables in the expression, we declare them with the help of a function called sp.symbols(). There is no need to explain the code if you have basic programming knowledge.

import sympy as sp
# Symbol Variables
x, y = sp.symbols('x y')
# An algebraic expression
expr = 4*x**2 + 2*x + 2 + 2*x + 4*x**2
# Simplify the expression
simplified_expr = sp.simplify(expr)
print("Simplified expression : ",simplified_expr) # Output: 5*x**2 + 2*x + 1
  • It can multiply two algebraic expressions and expand them.

import sympy as sp
# Symbol Variables
x, y = sp.symbols('x y')
# Define an expression with parentheses
expr = (x + 1)*(x - 2)
# Expand the expression
expanded_expr = sp.expand(expr)
print(expanded_expr)
  • We can factorize an algebraic expression through a SymPy library.

import sympy as sp
# Symbol Variables
x, y = sp.symbols('x y')
expr=x**2 - x - 2
# Factorize the expression
factored_expr = sp.factor(expr)
print(factored_expr)
  • It can also simplify trigonometric equations as well.

import sympy as sp
# Symbol Variables
x, y = sp.symbols('x y')
# Define a trigonometric expression
expr = sp.sin(x)**2 + sp.cos(x)**2
# Simplify the trigonometric expression
simplified_trig_expr = sp.trigsimp(expr)
print(simplified_trig_expr) # Output: 1

You looked at how SymPy is useful for performing algebraic manipulations. In the next section, we will discuss solving differentiation and integration problems through the SymPy library.

Calculus

  • In machine learning, SymPy helps to analyze a function's behavior. We can check the derivative of a function with a single command of sp.diff(expression). Have a look at its code below.

import sympy as sp
# Symbol Variables
x, y = sp.symbols('x y')
# Define a function
f = x**3 + 2*x**2 - 5*x + 1
# Differentiate the function with respect to x
df_dx = sp.diff(f, x)
print("Differentiated function:", df_dx)
  • We can calculate the definite and indefinite integrals through SymPy. This is helpful for various mathematical and engineering applications where integration plays a crucial role.

import sympy as sp
# Symbol Variables
x, y = sp.symbols('x y')
# Define a function
g = sp.sin(x) + sp.exp(x)
# Integrate the function with respect to x
integrated_g = sp.integrate(g, x)
print("Integrated function:", integrated_g)
  • In SymPy, the limit() function is used to calculate the limit of a mathematical expression as a variable approaches a specific value or infinity. The general syntax of the limit() function is as follows:

import sympy as sp
# Symbol Variables
x, y = sp.symbols('x y')
# Define a function
h = (x**2 - 1) / (x - 1)
# Calculate the limit as x approaches 1
limit_h = sp.limit(h, x, 1)
print("Limit of the function:", limit_h)

Linear algebra

SymPy allows you to work with linear algebra concepts, such as matrices and vectors, and solve systems of linear equations. It is a valuable tool for symbolic computation in linear algebra. Here's an overview of some of the capabilities provided by SymPy in linear algebra. Please run the code belwo so that you can understand the application of the SymPy library in a better way.

import sympy as sp
# Define symbolic variables
x, y, z = sp.symbols('x y z')
# Define a matrix
A = sp.Matrix([[1, 6, 3], [4, 5, 6], [7, 8, 9]])
# Define a vector
v = sp.Matrix([x, y, z])
# Matrix Transpose
A_transpose = A.T
print("Matrix A Transpose:")
print(A_transpose)
# Matrix Determinant
det_A = A.det()
print("Determinant of matrix A:", det_A)
# Matrix Inverse
A_inv = A.inv()
print("Inverse of matrix A:")
print(A_inv)
# Matrix Multiplication
A_times_v = A * v
print("Matrix multiplication of A and the vector v:")
print(A_times_v)

Complex numbers

In SymPy, you can work with complex numbers using the I symbol to represent the imaginary unit. The I symbol represents 1\sqrt{-1}, making it possible to perform complex arithmetics and manipulate complex expressions symbolically.

import sympy as sp
# Define symbolic variables
z = sp.Symbol('z', complex=True)
# Define two complex numbers
z1 = 3 + 4j
z2 = 1 - 2j
# Addition
z_sum = z1 + z2
print("Sum of complex numbers:", z_sum)
# Subtraction
z_diff = z1 - z2
print("Difference of complex numbers:", z_diff)
# Multiplication
z_prod = z1 * z2
print("Product of complex numbers:", z_prod)
# Division
z_div = z1 / z2
print("Division of complex numbers:", z_div)
# Complex conjugate
z_conjugate = sp.conjugate(z1)
print("Complex conjugate of z1:", z_conjugate)

Differential equations

SymPy library also simplifies solving differential equations for researchers and saves their time. In the code below, check the syntax to solve a differential equation in SymPy.

import sympy as sp
# Define the symbolic variable and the function
x = sp.symbols('x')
y = sp.Function('y')(x)
# Define the differential equation
diff_eq = sp.Eq(y.diff(x, x) - 3*y.diff(x) + 2*y, sp.sin(x))
# Solve the differential equation
solution = sp.dsolve(diff_eq)
# Print the solution
print("Solution to the differential equation:")
print(solution)

Discrete math

SymPy's rich mathematical functionalities allow users to perform symbolic computations, making it a valuable tool for various mathematical, engineering, and scientific applications. The code to solve different mathematical problems is given below.

import sympy as sp
# Define symbolic variables
n, k = sp.symbols('n k')
# Calculate permutations
permutations = sp.factorial(n) / sp.factorial(n - k)
print("Permutations (nPk):", permutations)
# Calculate combinations
combinations = sp.factorial(n) / (sp.factorial(k) * sp.factorial(n - k))
print("Combinations (nCk):", combinations)
import sympy as sp
# Check primality
print("Is 7 prime?", sp.isprime(7))
# Find divisors of a number
print("Divisors of 12:", sp.divisors(12))
# Compute greatest common divisor (GCD)
print("GCD of 24 and 36:", sp.gcd(24, 36))
n = 5
# n-th Bell number
bell_number = sp.bell(n)
print(f"Bell({n}) =", bell_number) # Output: Bell(5) = 52
n = 5
# n-th Catalan number
catalan_number = sp.catalan(n)
print(f"Catalan({n}) =", catalan_number) # Output: Catalan(5) = 42
n = 5
# n-th harmonic number
harmonic_number = sp.harmonic(n)
print(f"Harmonic({n}) =", harmonic_number) # Output: Harmonic(5) = 137/60

Integral transforms

It supports various integral transforms and mathematical operations that convert functions from one domain to another. These transforms are essential tools in various fields of engineering and physics, as they often simplify complex problems and facilitate analysis. Some integral transforms supported by SymPy include the Laplace, Fourier, and Mellin transforms.

import sympy as sp
# Define the variable and the function
t, s = sp.symbols('t s')
f_t = sp.exp(-t)
# Compute the Laplace Transform
laplace_f_t = sp.laplace_transform(f_t, t, s)
print("Laplace Transform of f(t):", laplace_f_t)
# Compute the Inverse Laplace Transform
inverse_laplace_f_s = sp.inverse_laplace_transform(laplace_f_t[0], s, t)
print("Inverse Laplace Transform of F(s):", inverse_laplace_f_s)
# Define the variable and the function
x, k = sp.symbols('x k')
f_x = sp.sin(x)
# Compute the Fourier Transform
fourier_f_x = sp.fourier_transform(f_x, x, k)
print("Fourier Transform of f(x):", fourier_f_x)
# Compute the Inverse Fourier Transform
inverse_fourier_f_k = sp.inverse_fourier_transform(fourier_f_x, k, x)
print("Inverse Fourier Transform of F(k):", inverse_fourier_f_k)
# Define the variable and the function
t, s = sp.symbols('t s', positive=True)
f_t = t**(-s)
# Compute the Mellin Transform
mellin_f_t = sp.mellin_transform(f_t, t, s)
print("Mellin Transform of f(t):", mellin_f_t)

Sets

Sets are collections of distinct elements. SymPy's module for sets allows you to work with finite sets, intervals, unions, intersections, and more. Here's an overview of some standard set-related functionalities in SymPy:

import sympy as sp
# Define a finite set
A = sp.FiniteSet(1, 2, 3, 4, 5)
# Check if an element is in the set
print(1 in A) # Output: True
print(6 in A) # Output: False
# Define an open interval (1, 5)
I = sp.Interval(1, 5, left_open=True, right_open=True)
# Check if a number is in the interval
print(2 in I) # Output: True
print(5 in I) # Output: False
C = sp.FiniteSet(3, 4, 5)
# Intersection of sets A and C
intersection_AC = A.intersect(C)
print("Intersection of sets A and C:", intersection_AC) # Output: Intersection of sets A and C: {3, 4, 5}
# Complement of set A with respect to set C
complement_A_C = C.complement(A)
print("Complement of set A with respect to set C:", complement_A_C) # Output: Complement of set A with respect to set C: {4, 5}

Logic

SymPy library provides functionality for working with logical statements, such as conjunction (AND), disjunction (OR), negation (NOT), implication (implies), equivalence (equals), and more.

import sympy as sp
# Define symbolic variables
p, q, r = sp.symbols('p q r')
# Define logical expressions
expr_and = sp.And(p, q)
expr_or = sp.Or(p, q)
expr_not = sp.Not(p)
expr_implies = sp.Implies(p, q)
expr_equivalent = sp.Equivalent(p, q)
expr_xor = sp.Xor(p, q)
expr_nand = sp.Nand(p, q)
expr_nor = sp.Nor(p, q)
# Evaluate the logical expressions
values = {p: True, q: False}
print("AND:", expr_and.subs(values))
print("OR:", expr_or.subs(values))
print("NOT:", expr_not.subs(values))
print("IMPLIES:", expr_implies.subs(values))
print("EQUIVALENT:", expr_equivalent.subs(values))
print("XOR:", expr_xor.subs(values))
print("NAND:", expr_nand.subs(values))
print("NOR:", expr_nor.subs(values))

Simplification

In SymPy, simplification is a fundamental feature that reduces the complexity of mathematical expressions by performing algebraic manipulations and applying mathematical identities. Here are some examples that illustrate how we can reduce the expressions.

import sympy as sp
x, y = sp.symbols('x y')
# Define a complicated expression
expr = sp.sin(x)**2 + sp.cos(x)**2
# Simplify the expression
simplified_expr = sp.simplify(expr)
print(simplified_expr)
# Define a complex expression
expr = sp.sqrt(8)
# Numerically simplify the expression
numerically_simplified_expr = sp.nsimplify(expr)
print(numerically_simplified_expr)
# Define a rational expression
expr = (x**2 - 1)/(x**2 + x - 2)
# Simplify the rational expression
simplified_rational_expr = sp.ratsimp(expr)
print(simplified_rational_expr)
# Define a rational expression
expr = (x**2 - 1)/(x**2 - y**2)
# Cancel common factors
canceled_expr = sp.cancel(expr)
print(canceled_expr)

Statistics

In SymPy, the sympy.stats module provides functionalities for symbolic statistical computations. This module allows you to work symbolically with probability distributions and random variables and perform various statistical operations.

import sympy as sp
import sympy.stats as stats
# Define a normal distribution
x, mu, sigma = sp.symbols('x mu sigma')
normal_dist = stats.Normal('X', mu, sigma)
# Probability density function (PDF)
pdf = stats.density(normal_dist)(x)
print("Normal Distribution PDF:", pdf)
# Cumulative distribution function (CDF)
cdf = stats.cdf(normal_dist)(x)
print("Normal Distribution CDF:", cdf)

LaTeX printing

SymPy has built-in support for LaTeX printing, allowing you to render mathematical expressions in LaTeX format. For a better understanding, look at the example in the code below.

import sympy as sp
# Define symbolic variables
x, y = sp.symbols('x y')
# Define a mathematical expression
expr = x**2 + 3*x + sp.sqrt(y)
# Obtain the LaTeX representation
latex_expr = sp.latex(expr)
# Print the LaTeX representation
print(latex_expr)

Conclusion

SymPy is a powerful and versatile library for symbolic mathematics in Python. With SymPy, users can perform algebraic manipulations, solve equations, simplify expressions, calculate derivatives and integrals, work with matrices, perform statistical computations, and much more. Overall, SymPy empowers users to explore and solve complex mathematical problems, enabling a deeper understanding of the underlying mathematics and facilitating efficient and accurate computations in various scientific and engineering domains.

Q

Which SymPy function can be used to calculate the integral of a given expression?

A)

integrate()

B)

integral()

C)

integrate_expr()

D)

integration()

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved