SymPy – Simplification

SymPy – Simplification ”; Previous Next Sympy has powerful ability to simplify mathematical expressions. There are many functions in SymPy to perform various kinds of simplification. A general function called simplify() is there that attempts to arrive at the simplest form of an expression. simplify This function is defined in sympy.simplify module. simplify() tries to apply intelligent heuristics to make the input expression “simpler”. Following code shows simplifies expression $sin^2(x)+cos^2(x)$. >>> from sympy import * >>> x=Symbol(”x”) >>> expr=sin(x)**2 + cos(x)**2 >>> simplify(expr) The above code snippet gives the following output − 1 expand The expand() is one of the most common simplification functions in SymPy, used in expanding polynomial expressions. For example − >>> a,b=symbols(”a b”) >>> expand((a+b)**2) The above code snippet gives an output equivalent to the below expression − $a^2 + 2ab + b^2$ >>> expand((a+b)*(a-b)) The above code snippet gives an output equivalent to the below expression − $a^2 – b^2$ The expand() function makes expressions bigger, not smaller. Usually this is the case, but often an expression will become smaller upon calling expand() on it. >>> expand((x + 1)*(x – 2) – (x – 1)*x) The above code snippet gives the following output − -2 factor This function takes a polynomial and factors it into irreducible factors over the rational numbers. >>> x,y,z=symbols(”x y z”) >>> expr=(x**2*z + 4*x*y*z + 4*y**2*z) >>> factor(expr) The above code snippet gives an output equivalent to the below expression − $z(x + 2y)^2$ >>> factor(x**2+2*x+1) The above code snippet gives an output equivalent to the below expression − $(x + 1)^2$ The factor() function is the opposite of expand(). Each of the factors returned by factor() is guaranteed to be irreducible. The factor_list() function returns a more structured output. >>> expr=(x**2*z + 4*x*y*z + 4*y**2*z) >>> factor_list(expr) The above code snippet gives an output equivalent to the below expression − (1, [(z, 1), (x + 2*y, 2)]) collect This function collects additve terms of an expression with respect to a list of expression up to powers with rational exponents. >>> expr=x*y + x – 3 + 2*x**2 – z*x**2 + x**3 >>> expr The above code snippet gives an output equivalent to the below expression − $x^3 + x^2z + 2x^2 + xy + x – 3$ The collect() function on this expression results as follows − >>> collect(expr,x) The above code snippet gives an output equivalent to the below expression − $x^3 + x^2(2 – z) + x(y + 1) – 3$ >>> expr=y**2*x + 4*x*y*z + 4*y**2*z+y**3+2*x*y >>> collect(expr,y) The above code snippet gives an output equivalent to the below expression − $Y^3+Y^2(x+4z)+y(4xz+2x)$ cancel The cancel() function will take any rational function and put it into the standard canonical form, p/q, where p and q are expanded polynomials with no common factors. The leading coefficients of p and q do not have denominators i.e., they are integers. >>> expr1=x**2+2*x+1 >>> expr2=x+1 >>> cancel(expr1/expr2) The above code snippet gives an output equivalent to the below expression − $x+1$ >>> expr = 1/x + (3*x/2 – 2)/(x – 4) >>> expr The above code snippet gives an output equivalent to the below expression − $frac{frac{3x}{2} – 2}{x – 4} + frac{1}{x}$ >>> cancel(expr) The above code snippet gives an output equivalent to the below expression − $frac{3x^2 – 2x – 8}{2x^2 – 8}$ >>> expr=1/sin(x)**2 >>> expr1=sin(x) >>> cancel(expr1*expr) The above code snippet gives an output equivalent to the below expression − $frac{1}{sin(x)}$ trigsimp This function is used to simplify trigonometric identities. It may be noted that naming conventions for inverse trigonometric functions is to append an a to the front of the function’s name. For example, the inverse cosine, or arc cosine, is called acos(). >>> from sympy import trigsimp, sin, cos >>> from sympy.abc import x, y >>> expr = 2*sin(x)**2 + 2*cos(x)**2 >>> trigsimp(expr) 2 The trigsimp function uses heuristics to apply the best suitable trigonometric identity. powersimp This function reduces given expression by combining powers with similar bases and exponents. >>> expr=x**y*x**z*y**z >>> expr The above code snippet gives an output equivalent to the below expression − $x^y x^z y^z$ >>> powsimp(expr) The above code snippet gives an output equivalent to the below expression − $x^{y+z} y^z$ You can make powsimp() only combine bases or only combine exponents by changing combine=’base’ or combine=’exp’. By default, combine=’all’, which does both.If force is True then bases will be combined without checking for assumptions. >>> powsimp(expr, combine=”base”, force=True) The above code snippet gives an output equivalent to the below expression − $x^y(xy)^z$ combsimp Combinatorial expressions involving factorial an binomials can be simplified by using combsimp() function. SymPy provides a factorial() function >>> expr=factorial(x)/factorial(x – 3) >>> expr The above code snippet gives an output equivalent to the below expression − $frac{x!}{(x – 3)!}$ To simplify above combinatorial expression we use combsimp() function as follows − >>> combsimp(expr) The above code snippet gives an output equivalent to the below expression − $x(x-2)(x-1)$ The binomial(x, y) is the number of ways to choose y items from a set of x distinct items. It is also often written as xCy. >>> binomial(x,y) The above code snippet gives an output equivalent to the below expression − $(frac{x}{y})$ >>> combsimp(binomial(x+1, y+1)/binomial(x,

SymPy – Derivative

SymPy – Derivative ”; Previous Next The derivative of a function is its instantaneous rate of change with respect to one of its variables. This is equivalent to finding the slope of the tangent line to the function at a point.we can find the differentiation of mathematical expressions in the form of variables by using diff() function in SymPy package. diff(expr, variable) >>> from sympy import diff, sin, exp >>> from sympy.abc import x,y >>> expr=x*sin(x*x)+1 >>> expr The above code snippet gives an output equivalent to the below expression − $xsin(x^2) + 1$ >>> diff(expr,x) The above code snippet gives an output equivalent to the below expression − $2x^2cos(x^2) + sin(x^2)$ >>> diff(exp(x**2),x) The above code snippet gives an output equivalent to the below expression − 2xex2 To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable. >>> diff(x**4,x,3) The above code snippet gives an output equivalent to the below expression − $24x$ >>> for i in range(1,4): print (diff(x**4,x,i)) The above code snippet gives the below expression − 4*x**3 12*x**2 24*x It is also possible to call diff() method of an expression. It works similarly as diff() function. >>> expr=x*sin(x*x)+1 >>> expr.diff(x) The above code snippet gives an output equivalent to the below expression − $2x^2cos(x^2) + sin(x^2)$ An unevaluated derivative is created by using the Derivative class. It has the same syntax as diff() function. To evaluate an unevaluated derivative, use the doit method. >>> from sympy import Derivative >>> d=Derivative(expr) >>> d The above code snippet gives an output equivalent to the below expression − $frac{d}{dx}(xsin(x^2)+1)$ >>> d.doit() The above code snippet gives an output equivalent to the below expression − $2x^2cos(x^2) + sin(x^2)$ Print Page Previous Next Advertisements ”;

SymPy – sympify() function

SymPy – sympify() function ”; Previous Next The sympify() function is used to convert any arbitrary expression such that it can be used as a SymPy expression. Normal Python objects such as integer objects are converted in SymPy. Integer, etc.., strings are also converted to SymPy expressions. >>> expr=”x**2+3*x+2″ >>> expr1=sympify(expr) >>> expr1 >>> expr1.subs(x,2) The above code snippet gives the following output − 12 Any Python object can be converted in SymPy object. However, since the conversion internally uses eval() function, unsanitized expression should not be used, else SympifyError is raised. >>> sympify(“x***2″) ————————————————————————— SympifyError: Sympify of expression ”could not parse ”x***2”” failed, because of exception being raised. The sympify() function takes following arguments: * strict: default is False. If set to True, only the types for which an explicit conversion has been defined are converted. Otherwise, SympifyError is raised. * evaluate: If set to False, arithmetic and operators will be converted into their SymPy equivalents without evaluating expression. >>> sympify(“10/5+4/2”) The above code snippet gives the following output − 4 >>> sympify(“10/5+4/2″, evaluate=False) The above code snippet gives the following output − $frac{10}{5}+frac{4}{2}$ Print Page Previous Next Advertisements ”;

SymPy – Symbols

SymPy – Symbols ”; Previous Next Symbol is the most important class in symPy library. As mentioned earlier, symbolic computations are done with symbols. SymPy variables are objects of Symbols class. Symbol() function”s argument is a string containing symbol which can be assigned to a variable. >>> from sympy import Symbol >>> x=Symbol(”x”) >>> y=Symbol(”y”) >>> expr=x**2+y**2 >>> expr The above code snippet gives an output equivalent to the below expression − $x^2 + y^2$ A symbol may be of more than one alphabets. >>> s=Symbol(”side”) >>> s**3 The above code snippet gives an output equivalent to the below expression − $side^3$ SymPy also has a Symbols() function that can define multiple symbols at once. String contains names of variables separated by comma or space. >>> from sympy import symbols >>> x,y,z=symbols(“x,y,z”) In SymPy”s abc module, all Latin and Greek alphabets are defined as symbols. Hence, instead of instantiating Symbol object, this method is convenient. >>> from sympy.abc import x,y,z However, the names C, O, S, I, N, E and Q are predefined symbols. Also, symbols with more than one alphabets are not defined in abc module, for which you should use Symbol object as above. The abc module defines special names that can detect definitions in default SymPy namespace. clash1 contains single letters and clash2 has multi letter clashing symbols >>> from sympy.abc import _clash1, _clash2 >>> _clash1 The output of the above snippet is as follows − {”C”: C, ”O”: O, ”Q”: Q, ”N”: N, ”I”: I, ”E”: E, ”S”: S} >>> _clash2 The output of the above snippet is as follows − {”beta”: beta, ”zeta”: zeta, ”gamma”: gamma, ”pi”: pi} Indexed symbols can be defined using syntax similar to range() function. Ranges are indicated by a colon. Type of range is determined by the character to the right of the colon. If itr is a digit, all contiguous digits to the left are taken as the nonnegative starting value. All contiguous digits to the right are taken as 1 greater than the ending value. >>> from sympy import symbols >>> symbols(”a:5”) The output of the above snippet is as follows − (a0, a1, a2, a3, a4) >>> symbols(”mark(1:4)”) The output of the above snippet is as follows − (mark1, mark2, mark3) Print Page Previous Next Advertisements ”;

SymPy – Matrices

SymPy – Matrices ”; Previous Next In Mathematics, a matrix is a two dimensional array of numbers, symbols or expressions. Theory of matrix manipulation deals with performing arithmetic operations on matrix objects, subject to certain rules. Linear transformation is one of the important applications of matrices. Many scientific fields, specially related to Physics use matrix related applications. SymPy package has matrices module that deals with matrix handling. It includes Matrix class whose object represents a matrix. Note: If you want to execute all the snippets in this chapter individually, you need to import the matrix module as shown below − >>> from sympy.matrices import Matrix Example >>> from sympy.matrices import Matrix >>> m=Matrix([[1,2,3],[2,3,1]]) >>> m $displaystyle left[begin{matrix}1 & 2 & 3\2 & 3 & 1end{matrix}right]$ On executing the above command in python shell, following output will be generated − [1 2 3 2 3 1] Matrix is created from appropriately sized List objects. You can also obtain a matrix by distributing list items in specified number of rows and columns. >>> M=Matrix(2,3,[10,40,30,2,6,9]) >>> M $displaystyle left[begin{matrix}10 & 40 & 30\2 & 6 & 9end{matrix}right]$ On executing the above command in python shell, following output will be generated − [10 40 30 2 6 9] Matrix is a mutable object. The matrices module also provides ImmutableMatrix class for obtaining immutable matrix. Basic manipulation The shape property of Matrix object returns its size. >>> M.shape The output for the above code is as follows − (2,3) The row() and col() method respectively returns row or column of specified number. >>> M.row(0) $displaystyle left[begin{matrix}10 & 40 & 30end{matrix}right]$ The output for the above code is as follows − [10 40 30] >>> M.col(1) $displaystyle left[begin{matrix}40\6end{matrix}right]$ The output for the above code is as follows − [40 6] Use Python”s slice operator to fetch one or more items belonging to row or column. >>> M.row(1)[1:3] [6, 9] Matrix class has row_del() and col_del() methods that deletes specified row/column from given matrix − >>> M=Matrix(2,3,[10,40,30,2,6,9]) >>> M.col_del(1) >>> M On executing the above command in python shell, following output will be generated − Matrix([[10, 30],[ 2, 9]]) You can apply style to the output using the following command − $displaystyle left[begin{matrix}10 & 30\2 & 9end{matrix}right]$ You get the following output after executing the above code snippet − [10 30 2 9] >>> M.row_del(0) >>> M $displaystyle left[begin{matrix}2 & 9end{matrix}right]$ You get the following output after executing the above code snippet − [2 9] Similarly, row_insert() and col_insert() methods add rows or columns at specified row or column index >>> M1=Matrix([[10,30]]) >>> M=M.row_insert(0,M1) >>> M $displaystyle left[begin{matrix}10 & 30\2 & 9end{matrix}right]$ You get the following output after executing the above code snippet − [10 40 30 2 9] >>> M2=Matrix([40,6]) >>> M=M.col_insert(1,M2) >>> M $displaystyle left[begin{matrix}10 & 40 & 30\2 & 6 & 9end{matrix}right]$ You get the following output after executing the above code snippet − [10 40 30 6 9] Arithmetic Operations Usual operators +, – and * are defined for performing addition, subtraction and multiplication. >>> M1=Matrix([[1,2,3],[3,2,1]]) >>> M2=Matrix([[4,5,6],[6,5,4]]) >>> M1+M2 $displaystyle left[begin{matrix}5 & 7 & 9\9 & 7 & 5end{matrix}right]$ You get the following output after executing the above code snippet − [5 7 9 9 7 5] >>> M1-M2 $displaystyle left[begin{matrix}-3 & -3 & -3\-3 & -3 & -3end{matrix}right]$ You get the following output after executing the above code snippet − [- 3 -3 -3 -3 -3 -3] Matrix multiplication is possible only if – The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix. – And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix. >>> M1=Matrix([[1,2,3],[3,2,1]]) >>> M2=Matrix([[4,5],[6,6],[5,4]]) >>> M1*M2 $displaystyle left[begin{matrix}31 & 29\29 & 31end{matrix}right]$ The output for the above code is as follows − [31 29 29 31] >>> M1.T $displaystyle left[begin{matrix}1 & 3\2 & 2\3 & 1end{matrix}right]$ The following output is obtained after executing the code − [1 3 2 2 3 1] To calculate a determinant of matrix, use det() method. A determinant is a scalar value that can be computed from the elements of a square matrix.0 >>> M=Matrix(3,3,[10,20,30,5,8,12,9,6,15]) >>> M $displaystyle left[begin{matrix}10 & 20 & 30\5 & 8 & 12\9 & 6 & 15end{matrix}right]$ The output for the above code is as follows − [10 20 30 5 8 12 9 6 15] >>> M.det() The output for the above code is as follows − -120 Matrix Constructors SymPy provides many special type of matrix classes. For example, Identity matrix, matrix of all zeroes and ones, etc. These classes are named as eye, zeros and ones respectively. Identity matrix is a square matrix with elements falling on diagonal are set to 1, rest of the elements are 0. Example from sympy.matrices import eye eye(3) Output Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) $displaystyle left[begin{matrix}1 & 0 & 0\0 & 1 & 0\0 & 0 & 1end{matrix}right]$ The output for the above code is as follows − [1 0 0 0 1 0 0 0 1] In diag matrix, elements on diagonal are initialized as per arguments provided. >>> from sympy.matrices import diag >>> diag(1,2,3) $displaystyle left[begin{matrix}1 & 0 & 0\0 & 2 &

SymPy – Integration

SymPy – Integration ”; Previous Next The SymPy package contains integrals module. It implements methods to calculate definite and indefinite integrals of expressions. The integrate() method is used to compute both definite and indefinite integrals. To compute an indefinite or primitive integral, just pass the variable after the expression. For example − integrate(f, x) To compute a definite integral, pass the argument as follows − (integration_variable, lower_limit, upper_limit) >>> from sympy import * >>> x,y = symbols(”x y”) >>> expr=x**2 + x + 1 >>> integrate(expr, x) The above code snippet gives an output equivalent to the below expression − $frac{x^3}{3} + frac{x^2}{2} + x$ >>> expr=sin(x)*tan(x) >>> expr >>> integrate(expr,x) The above code snippet gives an output equivalent to the below expression − $-frac{log(sin(x) – 1)}{2} + frac{log(sin(x) + 1)}{2} – sin(x)$ The example of definite integral is given below − >>> expr=exp(-x**2) >>> integrate(expr,(x,0,oo) ) The above code snippet gives an output equivalent to the below expression − $frac{sqrtpi}{2}$ You can pass multiple limit tuples to perform a multiple integral. An example is given below − >>> expr=exp(-x**2 – y**2) >>> integrate(expr,(x,0,oo),(y,0,oo)) The above code snippet gives an output equivalent to the below expression − $frac{pi}{4}$ You can create unevaluated integral using Integral object, which can be evaluated by calling doit() method. >>> expr = Integral(log(x)**2, x) >>> expr The above code snippet gives an output equivalent to the below expression − $int mathrmlog(x)^2 mathrm{d}x$ >>> expr.doit() The above code snippet gives an output equivalent to the below expression − $xlog(x)^2 – 2xlog(x) + 2x$ Integral Transforms SymPy supports various types of integral transforms as follows − laplace_transform fourier_transform sine_transform cosine_transform hankel_transform These functions are defined in sympy.integrals.transforms module. Following examples compute Fourier transform and Laplace transform respectively. Example 1 >>> from sympy import fourier_transform, exp >>> from sympy.abc import x, k >>> expr=exp(-x**2) >>> fourier_transform(expr, x, k) On executing the above command in python shell, following output will be generated − sqrt(pi)*exp(-pi**2*k**2) Which is equivalent to − $sqrtpi * e^{pi^2k^2}$ Example 2 >>> from sympy.integrals import laplace_transform >>> from sympy.abc import t, s, a >>> laplace_transform(t**a, t, s) On executing the above command in python shell, following output will be generated − (s**(-a)*gamma(a + 1)/s, 0, re(a) > -1) Print Page Previous Next Advertisements ”;

SymPy – Quick Guide

SymPy – Quick Guide ”; Previous Next SymPy – Introduction SymPy is a Python library for performing symbolic computation. It is a computer algebra system (CAS) that can be used either as a standalone application, as a library to other applications. Its live session is also available at https://live.sympy.org/. Since it is a pure Python library, it can be used as interactive mode and as a programmatic application. SymPy has now become a popular symbolic library for the scientific Python ecosystem. SymPy has a wide range of features applicable in the field of basic symbolic arithmetic, calculus, algebra, discrete mathematics, quantum physics, etc. SymPy is capable of formatting the results in variety of formats including LaTeX, MathML, etc. SymPy is distributed under New BSD License. A team of developers led by Ondřej Čertík and Aaron Meurer published first version of SymPy in 2007. Its current version is 1.5.1. Some of the areas of applications of SymPy are − Polynomials Calculus Discrete maths Matrices Geometry Plotting Physics Statistics Combinatorics SymPy – Installation SymPy has one important prerequisite library named mpmath. It is a Python library for real and complex floating-point arithmetic with arbitrary precision. However, Python”s package installer PIP installs it automatically when SymPy is installed as follows − pip install sympy Other Python distributions such as Anaconda, Enthought Canopy, etc., may have SymPy already bundled in it. To verify, you can type the following in the Python prompt − >>> import sympy >>> sympy.__version__ And you get the below output as the current version of sympy − ”1.5.1” Source code of SymPy package is available at https://github.com/sympy/sympy. SymPy – Symbolic Computation Symbolic computation refers to development of algorithms for manipulating mathematical expressions and other mathematical objects. Symbolic computation integrates mathematics with computer science to solve mathematical expressions using mathematical symbols. A Computer Algebra System (CAS) such as SymPy evaluates algebraic expressions exactly (not approximately) using the same symbols that are used in traditional manual method. For example, we calculate square root of a number using Python”s math module as given below − >>> import math >>> print (math.sqrt(25), math.sqrt(7)) The output for the above code snippet is as follows − 5.0 2.6457513110645907 As you can see, square root of 7 is calculated approximately. But in SymPy square roots of numbers that are not perfect squares are left unevaluated by default as given below − >>> import sympy >>> print (sympy.sqrt(7)) The output for the above code snippet is as follows − sqrt(7) It is possible to simplify and show result of expression symbolically with the code snippet below − >>> import math >>> print (math.sqrt(12)) The output for the above code snippet is as follows − 3.4641016151377544 You need to use the below code snippet to execute the same using sympy − ##sympy output >>> print (sympy.sqrt(12)) And the output for that is as follows − 2*sqrt(3) SymPy code, when run in Jupyter notebook, makes use of MathJax library to render mathematical symbols in LatEx form. It is shown in the below code snippet − >>> from sympy import * >>> x=Symbol (”x”) >>> expr = integrate(x**x, x) >>> expr On executing the above command in python shell, following output will be generated − Integral(x**x, x) Which is equivalent to $int mathrm{x}^{x},mathrm{d}x$ The square root of a non-perfect square can be represented by Latex as follows using traditional symbol − >>> from sympy import * >>> x=7 >>> sqrt(x) The output for the above code snippet is as follows − $sqrt7$ A symbolic computation system such as SymPy does all sorts of computations (such as derivatives, integrals, and limits, solve equations, work with matrices) symbolically. SymPy package has different modules that support plotting, printing (like LATEX), physics, statistics, combinatorics, number theory, geometry, logic, etc. SymPy – Numbers The core module in SymPy package contains Number class which represents atomic numbers. This class has two subclasses: Float and Rational class. Rational class is further extended by Integer class. Float class represents a floating point number of arbitrary precision. >>> from sympy import Float >>> Float(6.32) The output for the above code snippet is as follows − 6.32 SymPy can convert an integer or a string to float. >>> Float(10) 10.0 Float(”1.33E5”)# scientific notation 133000.0 While converting to float, it is also possible to specify number of digits for precision as given below − >>> Float(1.33333,2) The output for the above code snippet is as follows − 1.3 A representation of a number (p/q) is represented as object of Rational class with q being a non-zero number. >>> Rational(3/4) The output for the above code snippet is as follows − $frac{3}{4}$ If a floating point number is passed to Rational() constructor, it returns underlying value of its binary representation >>> Rational(0.2) The output for the above code snippet is as follows − $frac{3602879701896397}{18014398509481984}$ For simpler representation, specify denominator limitation. >>> Rational(0.2).limit_denominator(100) The output for the above code snippet is as follows − $frac{1}{5}$ When a string is passed to Rational() constructor, a rational number of arbitrary precision is returned. >>> Rational(“3.65”) The output for the above code snippet is as follows − $frac{73}{20}$ Rational object can also be obtained if two number arguments are passed. Numerator and denominator parts are available as properties. >>> a=Rational(3,5) >>> print (a) >>> print (“numerator:{}, denominator:{}”.format(a.p, a.q))

SymPy – Lambdify() function

SymPy – Lambdify() function ”; Previous Next The lambdify function translates SymPy expressions into Python functions. If an expression is to be evaluated over a large range of values, the evalf() function is not efficient. lambdify acts like a lambda function, except it converts the SymPy names to the names of the given numerical library, usually NumPy. By default, lambdify on implementations in the math standard library. >>> expr=1/sin(x) >>> f=lambdify(x, expr) >>> f(3.14) The above code snippet gives the following output − 627.8831939138764 The expression might have more than one variables. In that case, first argument to lambdify() function is a list of variables, followed by the expression to be evaluated. >>> expr=a**2+b**2 >>> f=lambdify([a,b],expr) >>> f(2,3) The above code snippet gives the following output − 13 However, to leverage numpy library as numerical backend, we have to define the same as an argument for lambdify() function. >>> f=lambdify([a,b],expr, “numpy”) We use two numpy arrays for two arguments a and b in the above function. The execution time is considerably fast in case of numpy arrays. >>> import numpy >>> l1=numpy.arange(1,6) >>> l2=numpy.arange(6,11) >>> f(l1,l2) The above code snippet gives the following output − array([ 37, 53, 73, 97, 125], dtype=int32) Print Page Previous Next Advertisements ”;

SymPy – Symbolic Computation

SymPy – Symbolic Computation ”; Previous Next Symbolic computation refers to development of algorithms for manipulating mathematical expressions and other mathematical objects. Symbolic computation integrates mathematics with computer science to solve mathematical expressions using mathematical symbols. A Computer Algebra System (CAS) such as SymPy evaluates algebraic expressions exactly (not approximately) using the same symbols that are used in traditional manual method. For example, we calculate square root of a number using Python”s math module as given below − >>> import math >>> print (math.sqrt(25), math.sqrt(7)) The output for the above code snippet is as follows − 5.0 2.6457513110645907 As you can see, square root of 7 is calculated approximately. But in SymPy square roots of numbers that are not perfect squares are left unevaluated by default as given below − >>> import sympy >>> print (sympy.sqrt(7)) The output for the above code snippet is as follows − sqrt(7) It is possible to simplify and show result of expression symbolically with the code snippet below − >>> import math >>> print (math.sqrt(12)) The output for the above code snippet is as follows − 3.4641016151377544 You need to use the below code snippet to execute the same using sympy − ##sympy output >>> print (sympy.sqrt(12)) And the output for that is as follows − 2*sqrt(3) SymPy code, when run in Jupyter notebook, makes use of MathJax library to render mathematical symbols in LatEx form. It is shown in the below code snippet − >>> from sympy import * >>> x=Symbol (”x”) >>> expr = integrate(x**x, x) >>> expr On executing the above command in python shell, following output will be generated − Integral(x**x, x) Which is equivalent to $int mathrm{x}^{x},mathrm{d}x$ The square root of a non-perfect square can be represented by Latex as follows using traditional symbol − >>> from sympy import * >>> x=7 >>> sqrt(x) The output for the above code snippet is as follows − $sqrt7$ A symbolic computation system such as SymPy does all sorts of computations (such as derivatives, integrals, and limits, solve equations, work with matrices) symbolically. SymPy package has different modules that support plotting, printing (like LATEX), physics, statistics, combinatorics, number theory, geometry, logic, etc. Print Page Previous Next Advertisements ”;

SymPy – Numbers

SymPy – Numbers ”; Previous Next The core module in SymPy package contains Number class which represents atomic numbers. This class has two subclasses: Float and Rational class. Rational class is further extended by Integer class. Float class represents a floating point number of arbitrary precision. >>> from sympy import Float >>> Float(6.32) The output for the above code snippet is as follows − 6.32 SymPy can convert an integer or a string to float. >>> Float(10) 10.0 Float(”1.33E5”)# scientific notation 133000.0 While converting to float, it is also possible to specify number of digits for precision as given below − >>> Float(1.33333,2) The output for the above code snippet is as follows − 1.3 A representation of a number (p/q) is represented as object of Rational class with q being a non-zero number. >>> Rational(3/4) The output for the above code snippet is as follows − $frac{3}{4}$ If a floating point number is passed to Rational() constructor, it returns underlying value of its binary representation >>> Rational(0.2) The output for the above code snippet is as follows − $frac{3602879701896397}{18014398509481984}$ For simpler representation, specify denominator limitation. >>> Rational(0.2).limit_denominator(100) The output for the above code snippet is as follows − $frac{1}{5}$ When a string is passed to Rational() constructor, a rational number of arbitrary precision is returned. >>> Rational(“3.65”) The output for the above code snippet is as follows − $frac{73}{20}$ Rational object can also be obtained if two number arguments are passed. Numerator and denominator parts are available as properties. >>> a=Rational(3,5) >>> print (a) >>> print (“numerator:{}, denominator:{}”.format(a.p, a.q)) The output for the above code snippet is as follows − 3/5 numerator:3, denominator:5 >>> a The output for the above code snippet is as follows − $frac{3}{5}$ Integer class in SymPy represents an integer number of any size. The constructor can accept a Float or Rational number, but the fractional part is discarded >>> Integer(10) The output for the above code snippet is as follows − 10 >>> Integer(3.4) The output for the above code snippet is as follows − 3 >>> Integer(2/7) The output for the above code snippet is as follows − 0 SymPy has a RealNumber class that acts as alias for Float. SymPy also defines Zero and One as singleton classes accessible with S.Zero and S.One respectively as shown below − >>> S.Zero The output is as follows − 0 >>> S.One The output is as follows − 1 Other predefined Singleton number objects are Half, NaN, Infinity and ImaginaryUnit >>> from sympy import S >>> print (S.Half) The output is as follows − ½ >>> print (S.NaN) The output is as follows − nan Infinity is available as oo symbol object or S.Infinity >>> from sympy import oo >>> oo The output for the above code snippet is as follows − $infty$ >>> S.Infinity The output for the above code snippet is as follows − $infty$ ImaginaryUnit number can be imported as I symbol or accessed as S.ImaginaryUnit and represents square root of -1 >>> from sympy import I >>> I When you execute the above code snippet, you get the following output − i >>> S.ImaginaryUnit The output of the above snippet is as follows − i >>> from sympy import sqrt >>> i=sqrt(-1) >>> i*i When you execute the above code snippet, you get the following output − -1 Print Page Previous Next Advertisements ”;