Development Tips - sympy/sympy GitHub Wiki

This is a list of little tips for SymPy. Feel free to edit this page and add some. They can be just basic things or advanced tips. If we get enough of them, we might do something with them. In general tips should be short and concise. They should be printable in a small amount of space. If you can try to keep it under 140 characters so that it may be included in a SymPy daily tips twitter stream.

Basic

  • You can define many numbered symbols at once using the slice syntax of symbols. symbols('a4:10') will create symbols a4 through a9 and symbols('a:3') will give 3 symbols: a0, a1, a2. You can also do symbols('a:z') to create the symbols a, b, ..., z.

  • SymPy runs under the Python Programming Language, so things may behave differently than in independent computer algebra systems like Maple or Mathematica.

  • C, O, S, I, N, E, and Q are special variables which already have meanings; it's best not to overwrite them. For example, I and E stand for the imaginary unit and Euler's number, respectively.

  • SymPy, like Python, has no implied multiplication. I.e. 2x would not work but 2*x would.

  • You can convert any string into a symbolic expression using the sympify() function. This will automatically define variables for you, so for example, you can type sympify("a^2 + cos(b)") and it will just work.

  • You can store special values in normal variables. so that you don't have to add ".evalf()" when you use the value. ex. x=pi.evalf() or y=E.evalf()

  • The best method to test equality is to use the simplify function to check whether the difference of two expressions is 0. For example, to check the equality of (x-1)**2 and x**2 - 2*x + 1, print simplify((x-1) ** 2 - (x**2 - 2*x + 1)) and see if it equals 0. If you suspect that an expression really does equal zero but simplify can't demonstrate it, try confirm your answer with expr.equals(0); this will answer False if expr is not (and cannot be) zero and None if it can't decide.

  • = is used to assign values to variables; the equality operator (==) tests whether expressions have identical form, not if they are mathematically equivalent.

  • All symbolic things are implemented using subclasses of the Basic class.

  • obj.args will give the arguments of obj. This can be used to move through the expression tree, such as obj.args[0].args[2].args.

  • For any SymPy object, obj == obj.func(*obj.args) should hold.

  • Some SymPy trig functions are named differently than their counterparts in other systems. In particular, SymPy inverse functions are asin, acos, and atan not arcsin/arccos/arctan.

  • To create a list of values, assign a variable to a list enclosed by brackets (e.g. x = [1,2,3,4,5]). To get the i-th value in x, you use x[i - 1]. Note that this means that to access the first value in the list, you must use x[0], so that print x[0] outputs 1, print x[1] outputs 2, and so on.

  • Tuples are like lists, but are less easy to use. They are created in the same way, just with parentheses instead of bracket. For example, x = (2,3,4). There are two other differences from lists. The major difference is that you cannot change values in tuples after creating them. This may be useful if you don't want to overwrite the data.

>>> y = (1,3,5)
>>> y
(1, 3, 5)
>>> y[1] = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

The last difference is that if you want a tuple with only only one element, you must put a comma after the element, e.x. x = (1,).

  • The Dummy() command can be used to take place of an undetermined variable that cannot be equal to anything else. Dummy('x') == Symbol('x') and Dummy('x') == Dummy('x') would both return False because each Dummy symbol is unique.

  • If you need help, the quickest resource is using the built in help tool by entering help(functionname). For example, if you need to find out what sin(x) does, type help(sin), or alternatively, sin? if you are using IPython.

  • Because multiplication and division have equal priority, these operators are evaluated from left to right. Addition and subtraction work in the same way. This occurs because Sympy uses Python's precedence rules, which evaluates them this way.

  • If you want to divide integers, it's a good idea to use from __future__ import division. This prevents Python from truncating the answer by stopping it from using the floor() command.

  • If you want to use integer division after you've already imported division from __future__, you can use a // in place of the /

  • Have an equation and a value for the variable(s)? Use the substitution method. For example, if you have: x + 14 and you know x = 1, do (x + 14).subs(x, 1) to get 15.

  • You can also use the substitution method to change variables. For example, if you have pi - 17*x and want to switch x for y, then (pi - 17*x).subs(x, y) produces pi - 17*y.

  • Remember that all variables must first be defined. You must do r = Symbol('r') before using the variable r.

  • Want to have your result printed in LaTeX? Just use the built-in latex() function. For example, latex(exp(x)) will print out e^x in LaTeX.

  • If you have pyglet, you can use the plot() command to plot a function in up to three dimensions.

  • Have a function plotted and want to easily zoom in and out without changing the window? Use the '-' and '+' keys on the number pad or the 'r' and 'f' keys.

  • Want to have SymPy print out numeric results? Use expr.evalf() or N(expr). For example, N(pi) will return 3.14159265358979 instead of pi.

  • If you want to numerically evaluate each of the elements in a list that was just printed, map N onto each of them:

[-sqrt(7)/2 + 3/2, sqrt(7)/2 + 3/2]
>>> map(N, _)
[0.177124344467705, 2.82287565553230]
  • Want to do definite integration? Use the integrate() function. The arguments are integrate(function, (variable, bottom bound, top bound)). For example, integrate(sin(x), (x, 0, pi/2)) will return 1.

  • Want to add or multiply a list of elements? Use sum or prod: sum([1,2,3]) gives 6. If there is a rule that defines each element, use the summation or product: summation(1/i, (i, 1, 3)) gives 11/6 while product(1/x, (x, 1, 3)) gives 1/6.

  • The expand method works not only for algebraic functions, but also for trigonometric functions. For example, sin(x + y).expand(trig=True) will return sin(x)*cos(y) + sin(y)*cos(x).

  • Want SymPy to print in Pretty Print? Use the Pretty Print function. To print out x/y in Pretty Print, do pprint(x/y). Alternatively use the isympy console.

  • Decomposition of functions: To decompose a fraction into its components or partialize we use the apart () function

  • There is a class representing mathematical infinity in SymPy, called oo, you can use it wherever you want. Example: oo > 99999.

  • Want to calculate a limit? Limits in SymPy follow the syntax: limit(function, variable, point), so to compute the limit of f(x) as x -> 0, you would use limit(f, x, 0).

  • To compute a one-sided limit, use limit(func, var, point, dir="+"), where dir="+"(default) calculates the limit from the right, and dir="-" from the left.

  • You can calculate the limit at infinity. Examples: limit(x, x, oo), limit(1/x, x, oo).

  • To get the square root of an expression use sqrt() function. For example: sqrt(x**2), sqrt(2).

  • There are Min() and Max() functions in Sympy, returning the minimum and the maximum value of a list of expressions correspondingly. For example: Min(1,2).

  • To get the binomial coefficient - C(n, k), use binomial() function. For example: binomial(15, 8).

  • There is an implementation of factorial function over nonnegative integers in SymPy. Examples: factorial(7), factorial(n).

  • If you want to know the sign of an expression, call sign() function. It will return -1 for negative expressions, 1 for positive, and 0 for zero expressions. Example: sign(x + y).

  • The factors() method will give you a dictionary of the (easy) factors of a number (and factorint, larger factors with more advanced techniques); divisors will list the divisors:

>>> S(24).factors()
{2: 3, 3: 1}
>>> list(divisors(24))
[1, 2, 3, 4, 6, 8, 12, 24]
  • Use solve() to solve algebraic equations. We suppose all equations are equaled to 0, so solving x**2 == 1 translates into: solve(x**2 - 1, x).

  • I represents imaginary unit in SymPy, so you can use it where necessary. For example: exp(I*x).expand() and I**2 = -1.

  • You can use print_gtk(expr) function to print any expression to Gtkmathview, a GTK widget that displays MathML code. Example: print_gtk(x**2+7). The Gtkmathview program is required.

  • You can create normal distribution with mean value mu and standard deviation sigma with Normal(mu, sigma) function. Example: N = Normal(0, 1).

  • To generate random numbers from the desired distribution you can use random method. For example, to generate random number in the interval from 5 to 15 you should call N = Normal(10, 5) and then N.random() functions.

Intermediate

  • Have a long expression that you want to copy from a console? Often, long expressions wrap at unintelligible places (like in the middle of a number). You can use python's textwrap module to help with this. In the example below, the breaks in the first output of eq are as they were in a cmd window of Windows.
>>> from sympy.abc import x
>>> eq=((x+1)**20).expand()
>>> eq
x**20 + 20*x**19 + 190*x**18 + 1140*x**17 + 4845*x**16 + 15504*x**15 + 38760*x**14 + 77520*x**13 + 125970*x**12 + 167960*x**11 + 184756*x**10 + 167960*x**9 + 125970*x**8 + 77520*x**7 + 38760*x**6 + 15504*x**5 + 4845*x**4 + 1140*x**3 + 190*x**2 + 20*x + 1
>>> import textwrap
>>> print '\\\\\n'.join(textwrap.wrap(str(eq)))
x**20 + 20*x**19 + 190*x**18 + 1140*x**17 + 4845*x**16 + 15504*x**15 +\\
38760*x**14 + 77520*x**13 + 125970*x**12 + 167960*x**11 + 184756*x**10\\
+ 167960*x**9 + 125970*x**8 + 77520*x**7 + 38760*x**6 + 15504*x**5 +\\
4845*x**4 + 1140*x**3 + 190*x**2 + 20*x + 1
>>> print '\\\\\n'.join(textwrap.wrap(str(eq), 50))
x**20 + 20*x**19 + 190*x**18 + 1140*x**17 +\\
4845*x**16 + 15504*x**15 + 38760*x**14 +\\
77520*x**13 + 125970*x**12 + 167960*x**11 +\\
184756*x**10 + 167960*x**9 + 125970*x**8 +\\
77520*x**7 + 38760*x**6 + 15504*x**5 + 4845*x**4 +\\
1140*x**3 + 190*x**2 + 20*x + 1
  • If you have some functions in an expression that you don't want, you can get rid of them by using expr.replace(function, Id). This will replace all instances of the function function, with Id, which is just the identity function. For example, if your expression is sin(Abs(x)) + cos(Abs(x)), and you don't want the absolute values, you can do expr.replace(Abs, Id) to get rid of them. This gives sin(x) + cos(x). (Notice that you have to use SymPy's Abs, and not the Python built-in abs function.)

  • To get a list of all the symbols in an expression, use .atoms(Symbol)

    >>> from sympy.abc import x, y, z
    >>> e = y - z*atan(x**3)

    >>> e.atoms(Symbol)
    set([x, y, z])
  • When defining a variable in terms of a symbol with an assignment (=) sign, the assigned variable will not change even if the variable containing the symbol does. When you type x = Symbol('x'), y = x, and x = 25, printing y will still give x, not 25.

  • SymPy allows you to use the Python method of writing functions in SymPy itself. You declare a function with def functionname(varlist):. Make sure your functions have return values. Sample function:

def add(n1, n2):
    return n1 + n2
  • SymPy has a lovely Geometry tool. To declare points, use pointname = Point(x, y). Most other objects are self-explanatory, such as Triangle(point1, point2, point3), and Circle(centerpoint, radius).

  • Want to combine fraction terms? Use the together function. For example, together(1/x + 1/y/x + 1/z) will return (x*y + y*z + z)/(x*y*z), having cancelled the x that the normal() method would have left: (1/x + 1/y/x + 1/z).normal() returns (x**2*y + x*y*z + x*z)/(x**2*y*z).

  • Want to break apart a fraction? Use the numer, denomorfractionfunctions, e.g.fraction(x/y)gives(x, y)`.

  • Numerical computing using Sympy:

SymPy represents π as a symbolic entity. The numerical approximation of π can be obtained by the use of either the evalf() method or N().

pi
>>> pi.evalf()
3.14159265358979
>>> pi.evalf(n=20)
3.1415926535897932385
  • Basics of expressions in SymPy:

We can use cancel () remove common factors from the numerator and the denominator of a function:

>>> (x**3-1)/(x-1)
(1 - x**3)/(1 - x)
>>> cancel(_)
1 + x + x**2
>>>
  • We use the force option with an expression manipulation function like expand() to expand forcibly a universally in valid function.
>>> log(a*b)
log(ab)
>>> expand(_)
log(ab)
>>> expand (log (a*b), force=True)
log (a) + log (b)

Some tips about symbols:

  • Do you know? It’s perfectly valid to create symbols containing special characters.
>>> Symbol ('#')
#
>>> Symbol('%')
%
>>> Symbol('@')
@
>>>
  • _ and ^ characters in symbols have special meaning and are used to denote subscripts and superscripts, respectively.
>>> Symbol('a^1')
a^1
>>> Symbol('a_1')
a_1
>>>
  • While creating symbols commas can be followed by or completely replaced by whitespace.
>>> symbols('a, b, c')
(a, b, c)
>>> symbols('a b c')
(a, b, c)
>>>
  • When we don’t know in advance how many symbols will be required to solve a certain problem we use the numbered_symbols() generator:
>>> A = numbered_symbols('a')
>>>
>>> A.next()
a0
>>> [ A.next() for i in xrange(10) ]
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10]
>>>
  • To construct a rational number in SymPy, one can use the Rational class.
>>> x = Rational(3,4)
>>> x
3/4
  • Unlike other mathematical systems, sympy uses ** to denote exponentiation and does not use ^ for exponentiation.
>>> a,b =symbols('a b')
>>> (a+b)**2
(a + b)**2
>>>
  • The equals sign (=) is the assignment operator in Python, not equality operator. Sympy uses the == operator or the Eq class for comparing equalities.
>>> var('a,b')
(a, b)
>>> a == b
False
>>>
>>> Eq(a,b)
a == b
>>> bool(_)
False
>>>

Advanced

  • You can use a dictionary to map text keys to values (syntax: sampledict = {'var1':2, 'var2':4}). This is particularly useful if you want to write a function that returns a list of variables, as the user can simply query the dictionary for some key representing a variable to get a value (query syntax: myvar = sampledict['var1']).

  • SymPy can manipulate boolean logic variables. And is represented by &, or by |, and implication by >> or <<. Alternatively, you can use textual representation of operations (ex. Or(x, y)). There are many other boolean algebra functions: check the documentation for a full listing.

  • If you're particularly curious about the inner workings of SymPy, try entering the function source(functionname). This will print the mess that's known as source code. You can also use functionname?? if you are using IPython.

⚠️ **GitHub.com Fallback** ⚠️