Math-Linux.com

Knowledge base dedicated to Linux and applied mathematics.

Home > Python > Sympy > Sympy how to define variable for functions, integrals and polynomials

Sympy how to define variable for functions, integrals and polynomials

All the versions of this article: <English> <français>

Sympy how to define variable for functions, integrals and polynomials

Define variables before :-)

from sympy import *
x,y,z,t,a,b,c,n,m,p,k = symbols('x y z t a b c n m p k')

Check if variable is well defined

sin(x)*exp(x)

$\displaystyle e^{x} \sin{\left(x \right)}$

v is not defined

sin(v)*exp(v)

Since v is not defined, we got an error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-e79911d4ea2b> in <module>
----> 1 sin(v)*exp(v)

NameError: name 'v' is not defined

Define polynomial use ** and not symbol ^

x**4-3*x**2 +15*x -1

$\displaystyle x^{4} - 3 x^{2} + 15 x - 1$

x^^2

Oups ... You got an error ...

  File "<ipython-input-5-5d18a81177b2>", line 1
   x^^2
     ^
SyntaxError: invalid syntax

Remember that ^ is a logic binary operator:

alpha,beta=1,10;
print(bin(alpha),bin(beta))
print(alpha^beta == (0b1)^(0b1010));
print(alpha^beta, bin(alpha^beta))

0b1 0b1010
True
11 0b1011

First way to define an function

def f(x):
   return x**2 + 1

Check f(3) value:

f(3)

10

Second way to define a function

g = x**2+1

Check g(3) value:

g.subs(x,3)

10

Calculate an integral

integrate(x**2 + x + 1, x)

$\displaystyle \frac{x^{3}}{3} + \frac{x^{2}}{2} + x$

integrate(t**2 * exp(t) * cos(t))

$\displaystyle \frac{t^{2} e^{t} \sin{\left(t \right)}}{2} + \frac{t^{2} e^{t} \cos{\left(t \right)}}{2} - t e^{t} \sin{\left(t \right)} + \frac{e^{t} \sin{\left(t \right)}}{2} - \frac{e^{t} \cos{\left(t \right)}}{2}$

integrate(f(x))

$\displaystyle \frac{x^{3}}{3} + x$

integrate(g(t))

Remember how g was defined !!!!

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-3849471c42ec> in <module>
----> 1 integrate(g(t))

TypeError: 'Add' object is not callable

Here is the good way to integrate it:

integrate(g)

$\displaystyle \frac{x^{3}}{3} + x$

That’s all folks !!! Below , jupyter’s notebook.