In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sympy import symbols, sqrt, Rational, lambdify, init_printing, solve, symbols, Subs

%matplotlib inline
init_printing(use_latex=True)

solve

symbols


In [2]:
a,b,c,d,x  = symbols('a b c d x')
solve(a*x**2+b*x+c,x)


Out[2]:
$$\left [ \frac{1}{2 a} \left(- b + \sqrt{- 4 a c + b^{2}}\right), \quad - \frac{1}{2 a} \left(b + \sqrt{- 4 a c + b^{2}}\right)\right ]$$

Expressions

  • sum
  • product

In [7]:
from sympy import(    diff,
    integrate,
    Integral,
    Sum,
    Product,
    Eq )

from IPython.display import *
from sympy.plotting import (
    plot, plot_implicit)

x, y, a, b, c = symbols("x y a b c")

expr = x**2*a + y**2*b
expr = expr.subs(a, 2)
expr = expr.subs(b, 2)

display(expr)

eq1 = Eq(expr, 5)
p1 = plot_implicit(eq1,  (x, -3, 3), (y, -3, 3))


$$2 x^{2} + 2 y^{2}$$

In [8]:
display(Sum(expr, (x,1,10)))
display(Product(expr, (x,0,10)))

display (solve(expr))


$$\sum_{x=1}^{10} \left(2 x^{2} + 2 y^{2}\right)$$
$$\prod_{x=0}^{10} \left(2 x^{2} + 2 y^{2}\right)$$
$$\left [ \left \{ x : - i y\right \}, \quad \left \{ x : i y\right \}\right ]$$

substitution with matrix equation


In [9]:
from sympy import Matrix

b11, b12, b13, b21, b22, b23, b31, b32, b33 = symbols ('b11 b12 b13 b21 b22 b23 b31 b32 b33')
c11, c21, c31 = symbols('c11 c21 c31')

mat_symbolic_1 = Matrix([[b11, b12, b13],[b21, b22, b23],[b31, b32, b33]])
mat_symbolic_2 = Matrix([[c11],[c21],[c31]])

mat_symbolic_1 * mat_symbolic_2


Out[9]:
$$\left[\begin{matrix}b_{11} c_{11} + b_{12} c_{21} + b_{13} c_{31}\\b_{21} c_{11} + b_{22} c_{21} + b_{23} c_{31}\\b_{31} c_{11} + b_{32} c_{21} + b_{33} c_{31}\end{matrix}\right]$$

In [88]:
mat = Matrix([[1.0, 2.0],[-(1.0 / 2.0), 1.0]])

print ('get eigenValues')
pprint ( Matrix(mat).eigenvals())

print ('\nget eigenVector')
pprint (Matrix(mat).eigenvects())

mat


get eigenValues
{1 - ⅈ: 1, 1 + ⅈ: 1}

get eigenVector
⎡⎛1.0 - 1.0⋅ⅈ, 1, ⎡⎡2.0⋅ⅈ⎤⎤⎞, ⎛1.0 + 1.0⋅ⅈ, 1, ⎡⎡-2.0⋅ⅈ⎤⎤⎞⎤
⎢⎜                ⎢⎢     ⎥⎥⎟  ⎜                ⎢⎢      ⎥⎥⎟⎥
⎣⎝                ⎣⎣ 1.0 ⎦⎦⎠  ⎝                ⎣⎣ 1.0  ⎦⎦⎠⎦
Out[88]:
$$\left[\begin{matrix}1.0 & 2.0\\-0.5 & 1.0\end{matrix}\right]$$

Diff


In [27]:
from sympy import Function, Eq, dsolve,pprint, cos, sin, Lambda, Derivative, var, latex


x,y,z,t = symbols('x y z t')
F = Function('F')

f = Eq(x**2 - x, 0)
f2 = Eq(x**2 + 2, x)
pprint (f)
pprint (f2)


 2        
x  - x = 0
 2        
x  + 2 = x

In [21]:
a,b,k = symbols('a b k')

display(cos(x*y) - sin(z*x))
display(Derivative(f, x))
display(Derivative(f, x).doit())
display(Derivative(f, x, 2))


$$- \sin{\left (x z \right )} + \cos{\left (x y \right )}$$
$$\frac{d}{d x} x^{2} - x = 0$$
$$\frac{d}{d x} x^{2} - x = 0$$
$$\frac{d^{2}}{d x^{2}} x^{2} - x = 0$$

In [22]:
display(Integral(f,x))
display(Integral(f, (x, a,b)))
display(Integral(f, (x, a,b)).doit())


$$\int x^{2} - x\, dx = \int 0\, dx$$
$$\int_{a}^{b} x^{2} - x\, dx = \int_{a}^{b} 0\, dx$$
$$- \frac{a^{3}}{3} + \frac{a^{2}}{2} + \frac{b^{3}}{3} - \frac{b^{2}}{2} = 0$$

In [12]:
eq_1 = Eq(F(x).diff(x), x / F(x))
display(eq_1)
eq_solved = dsolve(eq_1)
display(eq_solved)


$$\frac{d}{d x} F{\left (x \right )} = \frac{x}{F{\left (x \right )}}$$
$$\left [ F{\left (x \right )} = - \sqrt{C_{1} + x^{2}}, \quad F{\left (x \right )} = \sqrt{C_{1} + x^{2}}\right ]$$

In [25]:
var('a b t k C1')
u = Function("u")(t)
de = Eq(u+u.diff(t) * k)
display(de)

des = dsolve(de,u)
display(des)
des = des.subs(C1,0)
display(des)


$$k \frac{d}{d t} u{\left (t \right )} + u{\left (t \right )} = 0$$
$$u{\left (t \right )} = e^{\frac{1}{k} \left(C_{1} - t\right)}$$
$$u{\left (t \right )} = e^{- \frac{t}{k}}$$

In [28]:
f = Lambda((t,k,a,b),(a-b) * des.rhs + b)
display(Latex('$f(t,k,a,b) = ' + str(latex(f(t,k,a,b))) + '$'))
x = np.linspace(0,5,100)


$f(t,k,a,b) = b + \left(a - b\right) e^{- \frac{t}{k}}$

In [29]:
plt.grid(True)
plt.xlabel('Time t seconds',fontsize=12)
plt.ylabel('$f(t,1,4,8)$',fontsize=16)
plt.plot(x,[f(t,1,4,8) for t in x],color='#008000')
plt.show()



In [30]:
var('a b t k C1')
u = Function("u")(t)
de = Eq(u+u.diff(t) * k)
des = dsolve(de,u).subs(C1,0)
f = Lambda((t,k,a,b),(a-b) * des.rhs + b)
f


Out[30]:
$$\left( \left ( t, \quad k, \quad a, \quad b\right ) \mapsto b + \left(a - b\right) e^{- \frac{t}{k}} \right)$$

In [31]:
fig = plt.gcf()
fig.set_size_inches(8,5)
x = np.linspace(0,5,100)
plt.grid(True)
plt.xlabel('Time t seconds',fontsize=12)
plt.ylabel('Voltage',fontsize=12)
plt.title('R-C circuit decay profile',fontsize=16)
r = 10000 # resistor value Ω
c = 100e-6 # capacitor value farads
plt.text(2.1,7,'R = %.1f $\Omega$' % r,fontsize=14)
plt.text(2.1,6.3,'C = %.1f $\mu$f' % (c * 1e6),fontsize=14)
plt.plot(x,[f(t,r * c,0,10) for t in x],color='#008000')
plt.show()



In [ ]:

Limit


In [32]:
from sympy import Limit, sin, oo
x = symbols('x')

print('Range approaching: ', Limit(sin(x) / x, x, 0).doit())
Limit(sin(x) / x, x, 0)


Range approaching:  1
Out[32]:
$$\lim_{x \to 0^+}\left(\frac{1}{x} \sin{\left (x \right )}\right)$$

In [33]:
print('Range approaching: ', Limit(1/x, x, oo).doit())
Limit(1/x, x, oo)


Range approaching:  0
Out[33]:
$$\lim_{x \to \infty} \frac{1}{x}$$

In [65]:
print('Range approaching: ', Limit(1/x, x , 0, dir = '+').doit())
Limit(1/x, x , 0, dir = '+')


Range approaching:  oo
Out[65]:
$$\lim_{x \to 0^+} \frac{1}{x}$$

In [66]:
print('Range approaching: ', Limit(1/x, x , 0, dir = '-').doit())
Limit(1/x, x , 0, dir = '-')


Range approaching:  -oo
Out[66]:
$$\lim_{x \to 0^-} \frac{1}{x}$$

In [69]:
print('Range approaching: ', Limit(1/x**2, x , - oo).doit())
Limit(1/x**2, x , - oo)


Range approaching:  0
Out[69]:
$$\lim_{x \to -\infty} \frac{1}{x^{2}}$$

building expressions

Lambdify

pandas


In [35]:
from sympy import symbols, sqrt, Rational, lambdify

x, y = symbols("x y")
list1 = np.arange(1,1000)
list2 = pd.Series(list1)

def sympy_expr(x_val):
    expr = x**2 + sqrt(3)*x - Rational(1,3)
    return expr.subs(x, x_val)

expr_1 = [sympy_expr(item) for item in list2]
#print (expr_1)

%timeit [expr_1]

lambdifyFunction = f = lambdify(x, expr_1)

%timeit lambdifyFunction(list1)
%timeit lambdifyFunction(list2)


10000000 loops, best of 3: 101 ns per loop
10000 loops, best of 3: 206 µs per loop
1000 loops, best of 3: 205 µs per loop

In [29]:

plotting

class sympy.plotting.plot.BaseSeries[source]

Base class for the data objects containing stuff to be plotted.

The backend should check if it supports the data series that it’s given. (eg TextBackend supports only LineOver1DRange). It’s the backend responsibility to know how to use the class of data series that it’s given.

Some data series classes are grouped (using a class attribute like is_2Dline) according to the api they present (based only on convention). The backend is not obliged to use that api (eg. The LineOver1DRange belongs to the is_2Dline group and presents the get_points method, but the TextBackend does not use the get_points method).

class sympy.plotting.plot.Line2DBaseSeries[source]

A base class for 2D lines.

adding the label, steps and only_integers options
making is_2Dline true
defining get_segments and get_color_array

class sympy.plotting.plot.LineOver1DRangeSeries(expr, var_start_end, **kwargs)[source]

Representation for a line consisting of a SymPy expression over a range.

var


In [43]:
from sympy import var,E, pi, exp

var('x')
f = Lambda(x,E**-x**2)
x = np.linspace(-3,3,100)
y = np.array([f(v) for v in x],dtype='float')
a = 40
b = 60

In [40]:
import numpy as np
import matplotlib.pyplot as plt

from sympy.plotting import (
    plot, 
    plot_parametric, 
    plot3d,
    plot3d_parametric_line, 
    plot3d_parametric_surface
)

%matplotlib inline

var('i')
plot(sin(i),(i,0, 2*pi))


Out[40]:
<sympy.plotting.plot.Plot at 0x1a05b2dcb38>

In [44]:
var('i, j')
plot3d((exp(-(i**2+j**2))),(i,-3,3),(j,-3,3))


Out[44]:
<sympy.plotting.plot.Plot at 0x1a05af88dd8>

In [45]:
fig = plt.gcf()
fig.set_size_inches(8,5)
plt.grid(True)
plt.fill_between(x[:a+1],y[:a+1],0,color='#ffff40',alpha=.3)
plt.fill_between(x[a:b],y[a:b],0,color='#40ff40',alpha=.3)
plt.fill_between(x[b-1:],y[b-1:],0,color='#ffff40',alpha=.3)
plt.plot(x,y,color='black')
plt.show()


substitution and plotting


In [46]:
x, b1, b2 = symbols("i b1 b2")

f = x/(x+exp(b1-b2*i))
res = {b1:29.3930964972769,b2:0.327159886574049}

plot(f.subs(res), (i, 0, 100))


Out[46]:
<sympy.plotting.plot.Plot at 0x1a05b000748>

In [47]:
t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)
lam_x = lambdify(t, x, modules=['numpy'])

x_vals = np.linspace(0, 10, 100)
y_vals = lam_x(x_vals)

plt.plot(x_vals, y_vals)
plt.ylabel("Speed")
plt.show()


Latex


In [74]:
from IPython.display import HTML

init_printing(use_latex=True)

In [71]:
def wrap_tag(t,d):
   return '<%s style="border-color:white">%s</%s>' % (t,d,t) 
desc = (
  'Population at time t','Population at time zero',
  'Time','Population growth rate'
)

# source: http://mathworld.wolfram.com/PopulationGrowth.html
# problem: for a given multi-variable equation, generate all its forms
# create symbols
vl = (N,N_0,t,r) = symbols('N N_0 t r')
# base equation
b = log(N/N_0) - r*t

In [72]:
s = 'Variables:'
ss = ''
for n,x in enumerate(vl):
  ss += wrap_tag('td','&nbsp;')
  ss += wrap_tag('td','$%s$' % str(x))
  ss += wrap_tag('td',': %s' % desc[n])
  ss = wrap_tag('tr',ss)
s += wrap_tag('table',ss)
s += 'Equations:'
ss = ''
for v in vl:
  soln = solve(b,v)[0]
  ss += wrap_tag('td','&nbsp;')
  ss += wrap_tag('td','$%s$' % str(v))
  ss += wrap_tag('td','$\displaystyle = %s$' % latex(soln))
  ss = wrap_tag('tr',ss)
s += wrap_tag('table',ss)

In [77]:
def makeLatexToHTML(latex):
    return HTML(latex)
makeLatexToHTML(s)


Out[77]:
Variables:
 $N$: Population at time t
 $N_0$: Population at time zero
 $t$: Time
 $r$: Population growth rate
Equations:
 $N$$\displaystyle = N_{0} e^{r t}$
 $N_0$$\displaystyle = N e^{- r t}$
 $t$$\displaystyle = \frac{1}{r} \log{\left (\frac{N}{N_{0}} \right )}$
 $r$$\displaystyle = \frac{1}{t} \log{\left (\frac{N}{N_{0}} \right )}$

In [76]:
[solve(b,v)[0] for v in vl]


Out[76]:
$$\left [ N_{0} e^{r t}, \quad N e^{- r t}, \quad \frac{1}{r} \log{\left (\frac{N}{N_{0}} \right )}, \quad \frac{1}{t} \log{\left (\frac{N}{N_{0}} \right )}\right ]$$

In [ ]: