SymPy – Discussion

Discuss SymPy ”; Previous Next 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. Print Page Previous Next Advertisements ”;

SymPy – Solvers

SymPy – Solvers ”; Previous Next Since the symbols = and == are defined as assignment and equality operators in Python, they cannot be used to formulate symbolic equations. SymPy provides Eq() function to set up an equation. >>> from sympy import * >>> x,y=symbols(”x y”) >>> Eq(x,y) The above code snippet gives an output equivalent to the below expression − x = y Since x=y is possible if and only if x-y=0, above equation can be written as − >>> Eq(x-y,0) The above code snippet gives an output equivalent to the below expression − x − y = 0 The solver module in SymPy provides soveset() function whose prototype is as follows − solveset(equation, variable, domain) The domain is by default S.Complexes. Using solveset() function, we can solve an algebraic equation as follows − >>> solveset(Eq(x**2-9,0), x) The following output is obtained − {−3, 3} >>> solveset(Eq(x**2-3*x, -2),x) The following output is obtained after executing the above code snippet − {1,2} The output of solveset is a FiniteSet of the solutions. If there are no solutions, an EmptySet is returned >>> solveset(exp(x),x) The following output is obtained after executing the above code snippet − $varnothing$ Linear equation We have to use linsolve() function to solve linear equations. For example, the equations are as follows − x-y=4 x+y=1 >>> from sympy import * >>> x,y=symbols(”x y”) >>> linsolve([Eq(x-y,4),Eq( x + y ,1) ], (x, y)) The following output is obtained after executing the above code snippet − $lbrace(frac{5}{2},-frac{3}{2})rbrace$ The linsolve() function can also solve linear equations expressed in matrix form. >>> a,b=symbols(”a b”) >>> a=Matrix([[1,-1],[1,1]]) >>> b=Matrix([4,1]) >>> linsolve([a,b], (x,y)) We get the following output if we execute the above code snippet − $lbrace(frac{5}{2},-frac{3}{2})rbrace$ Non-linear equation For this purpose, we use nonlinsolve() function. Equations for this example − a2+a=0 a-b=0 >>> a,b=symbols(”a b”) >>> nonlinsolve([a**2 + a, a – b], [a, b]) We get the following output if we execute the above code snippet − $lbrace(-1, -1),(0,0)rbrace$ differential equation First, create an undefined function by passing cls=Function to the symbols function. To solve differential equations, use dsolve. >>> x=Symbol(”x”) >>> f=symbols(”f”, cls=Function) >>> f(x) The following output is obtained after executing the above code snippet − f(x) Here f(x) is an unevaluated function. Its derivative is as follows − >>> f(x).diff(x) The above code snippet gives an output equivalent to the below expression − $frac{d}{dx}f(x)$ We first create Eq object corresponding to following differential equation >>> eqn=Eq(f(x).diff(x)-f(x), sin(x)) >>> eqn The above code snippet gives an output equivalent to the below expression − $-f(x) + frac{d}{dx}f(x)= sin(x)$ >>> dsolve(eqn, f(x)) The above code snippet gives an output equivalent to the below expression − $f(x)=(c^1-frac{e^-xsin(x)}{2}-frac{e^-xcos(x)}{2})e^x$ Print Page Previous Next Advertisements ”;

SymPy – Function class

SymPy – Function class ”; Previous Next Sympy package has Function class, which is defined in sympy.core.function module. It is a base class for all applied mathematical functions, as also a constructor for undefined function classes. Following categories of functions are inherited from Function class − Functions for complex number Trigonometric functions Functions for integer number Combinatorial functions Other miscellaneous functions Functions for complex number This set of functions is defined in sympy.functions.elementary.complexes module. re This function returns real part of an expression − >>> from sympy import * >>> re(5+3*I) The output for the above code snippet is given below − 5 >>> re(I) The output for the above code snippet is − 0 Im This function returns imaginary part of an expression − >>> im(5+3*I) The output for the above code snippet is given below − 3 >>> im(I) The output for the above code snippet is given below − 1 sign This function returns the complex sign of an expression. For real expression, the sign will be − 1 if expression is positive 0 if expression is equal to zero -1 if expression is negative If expression is imaginary the sign returned is − I if im(expression) is positive -I if im(expression) is negative >>> sign(1.55), sign(-1), sign(S.Zero) The output for the above code snippet is given below − (1, -1, 0) >>> sign (-3*I), sign(I*2) The output for the above code snippet is given below − (-I, I) Abs This function return absolute value of a complex number. It is defined as the distance between the origin (0,0) and the point (a,b) in the complex plane. This function is an extension of the built-in function abs() to accept symbolic values. >>> Abs(2+3*I) The output for the above code snippet is given below − $sqrt13$ conjugate This function returns conjugate of a complex number. To find the complex conjugate we change the sign of the imaginary part. >>> conjugate(4+7*I) You get the following output after executing the above code snippet − 4 – 7i Trigonometric functions SymPy has defintions for all trigonometric ratios – sin cos, tan etc as well as well as its inverse counterparts such as asin, acos, atan etc. These functions compute respective value for given angle expressed in radians. >>> sin(pi/2), cos(pi/4), tan(pi/6) The output for the above code snippet is given below − (1, sqrt(2)/2, sqrt(3)/3) >>> asin(1), acos(sqrt(2)/2), atan(sqrt(3)/3) The output for the above code snippet is given below − (pi/2, pi/4, pi/6) Functions on Integer Number This is a set of functions to perform various operations on integer number. ceiling This is a univariate function which returns the smallest integer value not less than its argument. In case of complex numbers, ceiling of the real and imaginary parts separately. >>> ceiling(pi), ceiling(Rational(20,3)), ceiling(2.6+3.3*I) The output for the above code snippet is given below − (4, 7, 3 + 4*I) floor This function returns the largest integer value not greater than its argument. In case of complex numbers, this function too takes the floor of the real and imaginary parts separately. >>> floor(pi), floor(Rational(100,6)), floor(6.3-5.9*I) The output for the above code snippet is given below − (3, 16, 6 – 6*I) frac This function represents the fractional part of x. >>> frac(3.99), frac(Rational(10,3)), frac(10) The output for the above code snippet is given below − (0.990000000000000, 1/3, 0) Combinatorial functions Combinatorics is a field of mathematics concerned with problems of selection, arrangement, and operation within a finite or discrete system. factorial The factorial is very important in combinatorics where it gives the number of ways in which n objects can be permuted. It is symbolically represented as 𝑥! This function is implementation of factorial function over nonnegative integers, factorial of a negative integer is complex infinity. >>> x=Symbol(”x”) >>> factorial(x) The output for the above code snippet is given below − x! >>> factorial(5) The output for the above code snippet is given below − 120 >>> factorial(-1) The output for the above code snippet is given below − $inftybacksim$ binomial This function the number of ways we can choose k elements from a set of n elements. >>> x,y=symbols(”x y”) >>> binomial(x,y) The output for the above code snippet is given below − $(frac{x}{y})$ >>> binomial(4,2) The output for the above code snippet is given below − 6 Rows of Pascal”s triangle can be generated with the binomial function. >>> for i in range(5): print ([binomial(i,j) for j in range(i+1)]) You get the following output after executing the above code snippet − [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] fibonacci The Fibonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1 and the two-term recurrence relation Fn=Fn−1+Fn−2. >>> [fibonacci(x) for x in range(10)] The following output is obtained after executing the above code snippet − [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] tribonacci The Tribonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1, F2=1 and the three-term recurrence relation Fn=Fn-1+Fn-2+Fn-3. >>> tribonacci(5, Symbol(”x”)) The above code snippet gives an output equivalent to the

SymPy – Entities

SymPy – Entities ”; Previous Next The geometry module in SymPy allows creation of two dimensional entities such as line, circle, etc. We can then obtain information about them such as checking colinearity or finding intersection. Point Point class represents a point in Euclidean space. Following example checks for collinearity of points − >>> from sympy.geometry import Point >>> from sympy import * >>> x=Point(0,0) >>> y=Point(2,2) >>> z=Point(4,4) >>> Point.is_collinear(x,y,z) Output True >>> a=Point(2,3) >>> Point.is_collinear(x,y,a) Output False The distance() method of Point class calculates distance between two points >>> x.distance(y) Output $2sqrt2$ The distance may also be represented in terms of symbols. Line Line entity is obtained from two Point objects. The intersection() method returns point of intersection if two lines intersect each other. >>> from sympy.geometry import Point, Line >>> p1, p2=Point(0,5), Point(5,0) >>> l1=Line(p1,p2) >>> l2=Line(Point(0,0), Point(5,5)) >>> l1.intersection(l2) Output [Point2D(5/2, 5/2)] >>> l1.intersection(Line(Point(0,0), Point(2,2))) Output [Point2D(5/2, 5/2)] >>> x,y=symbols(”x y”) >>> p=Point(x,y) >>> p.distance(Point(0,0)) Output $sqrt{x^2 + y^2}$ Triangle This function builds a triangle entity from three point objects. Triangle(a,b,c) >>> t=Triangle(Point(0,0),Point(0,5), Point(5,0)) >>> t.area Output $-frac{25}{2}$ Ellipse An elliptical geometry entity is constructed by passing a Point object corresponding to center and two numbers each for horizontal and vertical radius. ellipse(center, hradius, vradius) >>> from sympy.geometry import Ellipse, Line >>> e=Ellipse(Point(0,0),8,3) >>> e.area Output $24pi$ The vradius can be indirectly provided by using eccentricity parameter. >>> e1=Ellipse(Point(2,2), hradius=5, eccentricity=Rational(3,4)) >>> e1.vradius Output $frac{5sqrt7}{4}$ The apoapsis of the ellipse is the greatest distance between the focus and the contour. >>> e1.apoapsis Output $frac{35}{4}$ Following statement calculates circumference of ellipse − >>> e1.circumference Output $20E(frac{9}{16})$ The equation method of ellipse returns equation of ellipse. >>> e1.equation(x,y) Output $(frac{x}{5}-frac{2}{5})^2 + frac{16(y-2)2}{175} – 1$ Print Page Previous Next Advertisements ”;

SymPy – Printing

SymPy – Printing ”; Previous Next There are several printers available in SymPy. Following is a partial list − str srepr ASCII pretty printer Unicode pretty printer LaTeX MathML Dot SymPy objects can also be sent as output to code of various languages, such as C, Fortran, Javascript, Theano, and Python. SymPy uses Unicode characters to render output in form of pretty print. If you are using Python console for executing SymPy session, the best pretty printing environment is activated by calling init_session() function. >>> from sympy import init_session >>> init_session() IPython console for SymPy 1.5.1 (Python 3.7.4-64-bit) (ground types: python). These commands were executed − >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols(”x y z t”) >>> k, m, n = symbols(”k m n”, integer=True) >>> f, g, h = symbols(”f g h”, cls=Function) >>> init_printing() Documentation can be found at https://docs.sympy.org/1.5.1/. >>> Integral(sqrt(1/x),x) $int sqrtfrac{1}{x} dx$ If LATEX is not installed, but Matplotlib is installed, it will use the Matplotlib rendering engine. If Matplotlib is not installed, it uses the Unicode pretty printer. However, Jupyter notebook uses MathJax to render LATEX. In a terminal that does not support Unicode, ASCII pretty printer is used. To use ASCII printer use pprint() function with use_unicode property set to False >>> pprint(Integral(sqrt(1/x),x),use_unicode=False) The Unicode pretty printer is also accessed from pprint() and pretty(). If the terminal supports Unicode, it is used automatically. If pprint() is not able to detect that the terminal supports unicode, you can pass use_unicode=True to force it to use Unicode. To get the LATEX form of an expression, use latex() function. >>> print(latex(Integral(sqrt(1/x),x))) int sqrt{frac{1}{x}}, dx You can also use mathml printer. for that purpose, import print_mathml function. A string version is obtained by mathml() function. >>> from sympy.printing.mathml import print_mathml >>> print_mathml(Integral(sqrt(1/x),x)) <apply> <int/> <bvar> <ci>x</ci> </bvar> <apply> <root/> <apply> <power/> <ci>x</ci> <cn>-1</cn> </apply> </apply> </apply> >>>mathml(Integral(sqrt(1/x),x)) ”<apply><int/><bvar><ci>x</ci></bvar><apply><root/><apply><power/><ci>x</ci><cn>-1</cn></apply></apply></apply>” Print Page Previous Next Advertisements ”;

SymPy – Useful Resources

SymPy – Useful Resources ”; Previous Next The following resources contain additional information on SymPy. Please use them to get more in-depth knowledge on this. Python Programming Certification 2024 Most Popular  9 Courses     1 eBooks Tutorialspoint More Detail Artificial Intelligence and Machine Learning Certification 2024 Most Popular  7 Courses     1 eBooks Tutorialspoint More Detail Java Certification 2024 Best Seller  7 Courses     1 eBooks Tutorialspoint More Detail Print Page Previous Next Advertisements ”;

SymPy – Sets

SymPy – Sets ”; Previous Next In mathematics, a set is a well-defined collection of distinct objects which may be numbers, people, letters of the alphabet, or even other sets. Set is also one of the built-in types in Python. SymPy provides sets module. It contains definitions of different types of set and has functionality to perform set operations such as intersection, union, etc. Set is a base class for any other type of set in SymPy. Note that it is different from built-in set data type of Python. Interval class represents real intervals and its boundary property returns a FiniteSet object. >>> from sympy import Interval >>> s=Interval(1,10).boundary >>> type(s) sympy.sets.sets.FiniteSet FiniteSet is a collection of discrete numbers. It can be obtained from any sequence object such as list or string. >>> from sympy import FiniteSet >>> FiniteSet(range(5)) Output $lbracelbrace0,1,…,4rbracerbrace$ >>> numbers=[1,3,5,2,8] >>> FiniteSet(*numbers) Output $lbrace1,2,3,5,8rbrace$ >>> s=”HelloWorld” >>> FiniteSet(*s) Output {H,W,d,e,l,o,r} Note that, as in built-in set, SymPy”s Set is also a collection of distinct objects. ConditionSet is a set of elements that satisfy a given condition >>> from sympy import ConditionSet, Eq, Symbol >>> x=Symbol(”x”) >>> s=ConditionSet(x, Eq(x**2-2*x,0), Interval(1,10)) >>> s Output $lbrace xmid xin[1,10]∧x^2 – 2x =0rbrace$ Union is a compound set. It includes all elements in two sets. Note that elements that are found in both, will appear only once in the Union. >>> from sympy import Union >>> l1=[3,1,5,7] >>> l2=[9,7,2,1] >>> a=FiniteSet(*l1) >>> b=FiniteSet(*l2) >>> Union(a,b) Intersection on the other hand contains only those elements that are present in both. >>> from sympy import Intersection >>> Intersection(a,b) ProductSet object represents Cartesian product of elements in both sets. >>> from sympy import ProductSet >>> l1=[1,2] >>> l2=[2,3] >>> a=FiniteSet(*l1) >>> b=FiniteSet(*l2) >>> set(ProductSet(a,b)) Complement(a,b) retains elements in a excluding elements that are common with b set. >>> from sympy import Complement >>> l1=[3,1,5,7] >>> l2=[9,7,2,1] >>> a=FiniteSet(*l1) >>> b=FiniteSet(*l2) >>> Complement(a,b), Complement(b,a) SymmetricDifference set contains only uncommon elements in both sets. >>> from sympy import SymmetricDifference >>> l1=[3,1,5,7] >>> l2=[9,7,2,1] >>> a=FiniteSet(*l1) >>> b=FiniteSet(*l2) >>> SymmetricDifference(a,b) Output {2,3,5,9} Print Page Previous Next Advertisements ”;

SymPy – Plotting

SymPy – Plotting ”; Previous Next SymPy uses Matplotlib library as a backend to render 2-D and 3-D plots of mathematical functions. Ensure that Matplotlib is available in current Python installation. If not, install the same using following command − pip install matplotlib Plotting support is defined in sympy.plotting module. Following functions are present in plotting module − plot − 2D line plots plot3d − 3D line plots plot_parametric − 2D parametric plots plot3d_parametric − 3D parametric plots The plot() function returns an instance of Plot class. A plot figure may have one or more SymPy expressions. Although it is capable of using Matplotlib as backend, other backends such as texplot, pyglet or Google charts API may also be used. plot(expr, range, kwargs) where expr is any valid symPy expression. If not mentioned, range uses default as (-10, 10). Following example plots values of x2 for each value in range(-10,10) − >>> from sympy.plotting import plot >>> from sympy import * >>> x=Symbol(”x”) >>> plot(x**2, line_color=”red”) To draw multiple plots for same range, give multiple expressions prior to the range tuple. >>> plot( sin(x),cos(x), (x, -pi, pi)) You can also specify separate range for each expression. plot((expr1, range1), (expr2, range2)) Following figure plots sin(x) and cos(x) over different ranges. >>> plot( (sin(x),(x, -2*pi, 2*pi)),(cos(x), (x, -pi, pi))) Following optional keyword arguments may be specified in plot() function. line_color − specifies color of the plot line. title − a string to be displayed as title xlabel − a string to be displayed as label for X axis ylabel − a string to be displayed as label for y axis >>> plot( (sin(x),(x, -2*pi, 2*pi)),(cos(x), (x, -pi, pi)), line_color=”red”, title=”SymPy plot example”) The plot3d() function renders a three dimensional plot. plot3d(expr, xrange, yrange, kwargs) Following example draws a 3D surface plot − >>> from sympy.plotting import plot3d >>> x,y=symbols(”x y”) >>> plot3d(x*y, (x, -10,10), (y, -10,10)) As in 2D plot, a three dimensional plot can also have multiple plots each with different range. >>> plot3d(x*y, x/y, (x, -5, 5), (y, -5, 5)) The plot3d_parametric_line() function renders a 3 dimensional parametric line plot. >>> from sympy.plotting import plot3d_parametric_line >>> plot3d_parametric_line(cos(x), sin(x), x, (x, -5, 5)) To draw a parametric surface plot, use plot3d_parametric_surface() function. plot3d_parametric_surface(xexpr, yexpr, zexpr, rangex, rangey, kwargs) >>> from sympy.plotting import plot3d_parametric_surface >>> plot3d_parametric_surface(cos(x+y), sin(x-y), x-y, (x, -5, 5), (y, -5, 5)) Print Page Previous Next Advertisements ”;

SymPy – Quaternion

SymPy – Quaternion ”; Previous Next In mathematics, Quaternion number system is an extension of complex numbers. Each Quaternion object contains four scalar variables and four dimensions, one real dimension and three imaginary dimensions. Quaternion is represented by following expression − q=a+bi+cj+dk where a, b, c and d are real numbers and i, j, k are quaternion units such that,i2==j2==k2==ijk The sympy.algebras.quaternion module has Quaternion class. >>> from sympy.algebras.quaternion import Quaternion >>> q=Quaternion(2,3,1,4) >>> q The above code snippet gives an output equivalent to the below expression − $2 + 3i + 1j + 4k$ Quaternions are used in pure mathematics, as well as in applied mathematics, computer graphics, computer vision, etc. >>> from sympy import * >>> x=Symbol(”x”) >>> q1=Quaternion(x**2, x**3, x) >>> q1 The above code snippet gives an output equivalent to the below expression − $x^2 + x^3i + xj + 0k$ Quaternion object can also have imaginary co-efficients >>> q2=Quaternion(2,(3+2*I), x**2, 3.5*I) >>> q2 The above code snippet gives an output equivalent to the below expression − $2 + (3 + 2i)i + x2j + 3.5ik$ add() This method available in Quaternion class performs addition of two Quaternion objects. >>> q1=Quaternion(1,2,3,4) >>> q2=Quaternion(4,3,2,1) >>> q1.add(q2) The above code snippet gives an output equivalent to the below expression − $5 + 5i + 5j + 5k$ It is possible to add a number or symbol in a Quaternion object. >>> q1+2 The following output is obtained after executing the above code snippet − $3 + 2i + 3j + 4k$ >>> q1+x The following output is obtained after executing the above code snippet − $(x + 1) + 2i + 3j + 4k$ mul() This method performs multiplication of two quaternion objects. >>> q1=Quaternion(1,2,1,2) >>> q2=Quaternion(2,4,3,1) >>> q1.mul(q2) The above code snippet gives an output equivalent to the below expression − $(-11) + 3i + 11j + 7k$ inverse() This method returns inverse of a quaternion object. >>> q1.inverse() The above code snippet gives an output equivalent to the below expression − $frac{1}{10} + (-frac{1}{5})i + (-frac{1}{10})j + (-frac{1}{5})k$ pow() This method returns power of a quaternion object. >>> q1.pow(2) The following output is obtained after executing the above code snippet − $(-8) + 4i + 2j + 4k$ exp() This method computes exponential of a Quaternion object i.e. eq >>> q=Quaternion(1,2,4,3) >>> q.exp() The following output is obtained after executing the above code snippet − $ecos(sqrt29) + frac{2sqrt29esin(sqrt29)}{29}i + frac{4sqrt29esin(sqrt29)}{29}j + frac{3sqrt29esin}{29}k$ Print Page Previous Next Advertisements ”;

SymPy – Querying

SymPy – Querying ”; Previous Next The assumptions module in SymPy package contains tools for extracting information about expressions. The module defines ask() function for this purpose. sympy.assumptions.ask(property) Following properties provide useful information about an expression − algebraic(x) To be algebraic, a number must be a root of a non-zero polynomial equation with rational coefficients. √2 because √2 is a solution to x2 − 2 = 0, so it is algebraic. complex(x) Complex number predicate. It is true if and only if x belongs to the set of complex numbers. composite(x) Composite number predicate returned by ask(Q.composite(x)) is true if and only if x is a positive integer and has at least one positive divisor other than 1 and the number itself. even, odd The ask() returns true of x is in the set of even numbers and set of odd numbers respectively. imaginary This property represents Imaginary number predicate. It is true if x can be written as a real number multiplied by the imaginary unit I. integer This property returned by Q.integer(x) returns true of x belong to set of even numbers. rational, irrational Q.irrational(x) is true if and only if x is any real number that cannot be expressed as a ratio of integers. For example, pi is an irrational number. positive, negative Predicates to check if number is positive or negative zero, nonzero Predicates to heck if a number is zero or not >>> from sympy import * >>> x=Symbol(”x”) >>> x=10 >>> ask(Q.algebraic(pi)) False >>> ask(Q.complex(5-4*I)), ask( Q.complex(100)) (True, True) >>> x,y=symbols(“x y”) >>> x,y=5,10 >>> ask(Q.composite(x)), ask(Q.composite(y)) (False, True) >>> ask(Q.even(x)), ask(Q.even(y)) (False, True) >>> x,y= 2*I, 4+5*I >>> ask(Q.imaginary(x)), ask(Q.imaginary(y)) (True, False) >>> x,y=5,10 >>> ask(Q.even(x)), ask(Q.even(y)), ask(Q.odd(x)), ask(Q.odd(y)) (False, True, True, False) >>> x,y=5,-5 >>> ask(Q.positive(x)), ask(Q.negative(y)), ask(Q.positive(x)), ask(Q.negative(y)) (True, True, True, True) >>> ask(Q.rational(pi)), ask(Q.irrational(S(2)/3)) (False, False) >>> ask(Q.zero(oo)), ask(Q.nonzero(I)) (False, False) Print Page Previous Next Advertisements ”;