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.
The applications of the SymPy library are illustrated below.
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 Variablesx, y = sp.symbols('x y')# An algebraic expressionexpr = 4*x**2 + 2*x + 2 + 2*x + 4*x**2# Simplify the expressionsimplified_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 Variablesx, y = sp.symbols('x y')# Define an expression with parenthesesexpr = (x + 1)*(x - 2)# Expand the expressionexpanded_expr = sp.expand(expr)print(expanded_expr)
We can factorize an algebraic expression through a SymPy library.
import sympy as sp# Symbol Variablesx, y = sp.symbols('x y')expr=x**2 - x - 2# Factorize the expressionfactored_expr = sp.factor(expr)print(factored_expr)
It can also simplify trigonometric equations as well.
import sympy as sp# Symbol Variablesx, y = sp.symbols('x y')# Define a trigonometric expressionexpr = sp.sin(x)**2 + sp.cos(x)**2# Simplify the trigonometric expressionsimplified_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.
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 Variablesx, y = sp.symbols('x y')# Define a functionf = x**3 + 2*x**2 - 5*x + 1# Differentiate the function with respect to xdf_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 Variablesx, y = sp.symbols('x y')# Define a functiong = sp.sin(x) + sp.exp(x)# Integrate the function with respect to xintegrated_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 Variablesx, y = sp.symbols('x y')# Define a functionh = (x**2 - 1) / (x - 1)# Calculate the limit as x approaches 1limit_h = sp.limit(h, x, 1)print("Limit of the function:", limit_h)
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 variablesx, y, z = sp.symbols('x y z')# Define a matrixA = sp.Matrix([[1, 6, 3], [4, 5, 6], [7, 8, 9]])# Define a vectorv = sp.Matrix([x, y, z])# Matrix TransposeA_transpose = A.Tprint("Matrix A Transpose:")print(A_transpose)# Matrix Determinantdet_A = A.det()print("Determinant of matrix A:", det_A)# Matrix InverseA_inv = A.inv()print("Inverse of matrix A:")print(A_inv)# Matrix MultiplicationA_times_v = A * vprint("Matrix multiplication of A and the vector v:")print(A_times_v)
In SymPy, you can work with complex numbers using the I
symbol to represent the imaginary unit. The I
symbol represents
import sympy as sp# Define symbolic variablesz = sp.Symbol('z', complex=True)# Define two complex numbersz1 = 3 + 4jz2 = 1 - 2j# Additionz_sum = z1 + z2print("Sum of complex numbers:", z_sum)# Subtractionz_diff = z1 - z2print("Difference of complex numbers:", z_diff)# Multiplicationz_prod = z1 * z2print("Product of complex numbers:", z_prod)# Divisionz_div = z1 / z2print("Division of complex numbers:", z_div)# Complex conjugatez_conjugate = sp.conjugate(z1)print("Complex conjugate of z1:", z_conjugate)
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 functionx = sp.symbols('x')y = sp.Function('y')(x)# Define the differential equationdiff_eq = sp.Eq(y.diff(x, x) - 3*y.diff(x) + 2*y, sp.sin(x))# Solve the differential equationsolution = sp.dsolve(diff_eq)# Print the solutionprint("Solution to the differential equation:")print(solution)
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 variablesn, k = sp.symbols('n k')# Calculate permutationspermutations = sp.factorial(n) / sp.factorial(n - k)print("Permutations (nPk):", permutations)# Calculate combinationscombinations = sp.factorial(n) / (sp.factorial(k) * sp.factorial(n - k))print("Combinations (nCk):", combinations)import sympy as sp# Check primalityprint("Is 7 prime?", sp.isprime(7))# Find divisors of a numberprint("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 numberbell_number = sp.bell(n)print(f"Bell({n}) =", bell_number) # Output: Bell(5) = 52n = 5# n-th Catalan numbercatalan_number = sp.catalan(n)print(f"Catalan({n}) =", catalan_number) # Output: Catalan(5) = 42n = 5# n-th harmonic numberharmonic_number = sp.harmonic(n)print(f"Harmonic({n}) =", harmonic_number) # Output: Harmonic(5) = 137/60
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 functiont, s = sp.symbols('t s')f_t = sp.exp(-t)# Compute the Laplace Transformlaplace_f_t = sp.laplace_transform(f_t, t, s)print("Laplace Transform of f(t):", laplace_f_t)# Compute the Inverse Laplace Transforminverse_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 functionx, k = sp.symbols('x k')f_x = sp.sin(x)# Compute the Fourier Transformfourier_f_x = sp.fourier_transform(f_x, x, k)print("Fourier Transform of f(x):", fourier_f_x)# Compute the Inverse Fourier Transforminverse_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 functiont, s = sp.symbols('t s', positive=True)f_t = t**(-s)# Compute the Mellin Transformmellin_f_t = sp.mellin_transform(f_t, t, s)print("Mellin Transform of f(t):", mellin_f_t)
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 setA = sp.FiniteSet(1, 2, 3, 4, 5)# Check if an element is in the setprint(1 in A) # Output: Trueprint(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 intervalprint(2 in I) # Output: Trueprint(5 in I) # Output: FalseC = sp.FiniteSet(3, 4, 5)# Intersection of sets A and Cintersection_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 Ccomplement_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}
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 variablesp, q, r = sp.symbols('p q r')# Define logical expressionsexpr_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 expressionsvalues = {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))
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 spx, y = sp.symbols('x y')# Define a complicated expressionexpr = sp.sin(x)**2 + sp.cos(x)**2# Simplify the expressionsimplified_expr = sp.simplify(expr)print(simplified_expr)# Define a complex expressionexpr = sp.sqrt(8)# Numerically simplify the expressionnumerically_simplified_expr = sp.nsimplify(expr)print(numerically_simplified_expr)# Define a rational expressionexpr = (x**2 - 1)/(x**2 + x - 2)# Simplify the rational expressionsimplified_rational_expr = sp.ratsimp(expr)print(simplified_rational_expr)# Define a rational expressionexpr = (x**2 - 1)/(x**2 - y**2)# Cancel common factorscanceled_expr = sp.cancel(expr)print(canceled_expr)
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 spimport sympy.stats as stats# Define a normal distributionx, 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)
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 variablesx, y = sp.symbols('x y')# Define a mathematical expressionexpr = x**2 + 3*x + sp.sqrt(y)# Obtain the LaTeX representationlatex_expr = sp.latex(expr)# Print the LaTeX representationprint(latex_expr)
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.
Which SymPy function can be used to calculate the integral of a given expression?
integrate()
integral()
integrate_expr()
integration()
Free Resources