You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

To work with symbolic mathematics in Python we have chosen to use the libary SymPy. More detailed SymPy documentation and packages for installation can be found on http://sympy.org/.


Innholdsfortegnelse

Symbols

To make symbolic variables in SymPy you have to declare the variable explicitly:

>>> from sympy import *
>>> x = Symbol('x')
>>> y = Symbol('y')

Then may then manipulate them as you want:

>>> x + y + x - y
2*x


>>> (x + y)**2
(x + y)**2


>>> ((x + y)**2).expand()
x**2 + 2*x*y + y**2

You can also substitute variables for numbers or other symbolic variables with subs(var, substitution).

>>> ((x + y)**2).subs(x, 1)
(y + 1)**2

>>> ((x + y)**2).subs(x, y)
4*y**2

Some regular constants are already included in SymPy as symbols, like e, pi and infinite (oo)evalf() evaluates the symbols as floation-point numbers.

>>> pi**2
pi**2



>>> pi.evalf()
3.141592653589793238462643383


<<< E**2
exp(2)


>>> oo > 99999
True

>>> oo + 1
oo


Differentiation

You can differentiate any SymPy expression using diff(func, var). Higher derivatives can be solved using diff(func, var, n).

>>> from sympy import *
>>> x = Symbol('x')

>>> diff(sin(x), x)
cos(x)


>>> diff(sin(2*x), x, 1)
2*cos(2*x)

>>> diff(sin(2*x), x, 2)
-4*sin(2*x)

Integration

SymPy has support for both indefinite and definite integration:

>>> from sympy import *
>>> x, y = symbols('x y')

Indefinite integration of some elementary functions:

>>> integrate(6*x**5, x)
x**6


>>> integrate(log(x), x)
x*log(x) - x

>>> integrate(2*x + sinh(x), x)
x**2 + cosh(x)	

Definite integration:

>>> integrate(x**3, (x, -1, 1))
0

>>> integrate(sin(x), (x, 0, pi/2))
1

Some special integrals:

>>> integrate(exp(-x), (x, 0, oo))
1

>>> integrate(log(x), (x, 0, 1))
-1



  • No labels