Index
-----

Python tutorial Ipython / Sympy

- https://arachnoid.com/IPython/equation_processing.html

Continuous Statistical distribution

- https://arachnoid.com/NormalDistribution/index.html

Binomial probability

- https://arachnoid.com/binomial_probability/index.html

polynomial regression

- https://arachnoid.com/sage/polynomial.html
- https://arachnoid.com/polysolve/index.html

Finance

- https://arachnoid.com/finance/index.html#x_ircalc


```python
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
-------


```python
a,b,c,d,x  = symbols('a b c d x')
solve(a*x**2+b*x+c,x)
```

Expressions
-----------

- sum
- product


```python
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))

```


```python
display(Sum(expr, (x,1,10)))
display(Product(expr, (x,0,10)))

display (solve(expr))
```

substitution with matrix equation
---------------------------------


```python
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
```


```python
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
```

Diff
----


```python
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



```python
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))

```


```python
display(Integral(f,x))
display(Integral(f, (x, a,b)))
display(Integral(f, (x, a,b)).doit())

```


```python
eq_1 = Eq(F(x).diff(x), x / F(x))
display(eq_1)
eq_solved = dsolve(eq_1)
display(eq_solved)
```


```python
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)
```


```python
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}}$



```python
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()
```


```python
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
```


```python
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()

```


```python

```

Limit
-----


```python
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)
```


```python
print('Range approaching: ', Limit(1/x, x, oo).doit())
Limit(1/x, x, oo)
```


```python
print('Range approaching: ', Limit(1/x, x , 0, dir = '+').doit())
Limit(1/x, x , 0, dir = '+')
```


```python
print('Range approaching: ', Limit(1/x, x , 0, dir = '-').doit())
Limit(1/x, x , 0, dir = '-')
```


```python
print('Range approaching: ', Limit(1/x**2, x , - oo).doit())
Limit(1/x**2, x , - oo)
```

building expressions
--------------------
Lambdify
--------
pandas
------


```python
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



```python

```

plotting
--------
- https://arachnoid.com/IPython/tips_tricks.html

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
---


```python
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
```


```python
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))
```


```python
var('i, j')
plot3d((exp(-(i**2+j**2))),(i,-3,3),(j,-3,3))
```


```python
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
-------------------------


```python
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))
```


```python
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
-----


```python
from IPython.display import HTML

init_printing(use_latex=True)
```


```python
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
```


```python
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)
```


```python
def makeLatexToHTML(latex):
    return HTML(latex)
makeLatexToHTML(s)
```




Variables:<table style="border-color:white"><tr style="border-color:white"><tr style="border-color:white"><tr style="border-color:white"><tr style="border-color:white"><td style="border-color:white">&nbsp;</td><td style="border-color:white">$N$</td><td style="border-color:white">: Population at time t</td></tr><td style="border-color:white">&nbsp;</td><td style="border-color:white">$N_0$</td><td style="border-color:white">: Population at time zero</td></tr><td style="border-color:white">&nbsp;</td><td style="border-color:white">$t$</td><td style="border-color:white">: Time</td></tr><td style="border-color:white">&nbsp;</td><td style="border-color:white">$r$</td><td style="border-color:white">: Population growth rate</td></tr></table>Equations:<table style="border-color:white"><tr style="border-color:white"><tr style="border-color:white"><tr style="border-color:white"><tr style="border-color:white"><td style="border-color:white">&nbsp;</td><td style="border-color:white">$N$</td><td style="border-color:white">$\displaystyle = N_{0} e^{r t}$</td></tr><td style="border-color:white">&nbsp;</td><td style="border-color:white">$N_0$</td><td style="border-color:white">$\displaystyle = N e^{- r t}$</td></tr><td style="border-color:white">&nbsp;</td><td style="border-color:white">$t$</td><td style="border-color:white">$\displaystyle = \frac{1}{r} \log{\left (\frac{N}{N_{0}} \right )}$</td></tr><td style="border-color:white">&nbsp;</td><td style="border-color:white">$r$</td><td style="border-color:white">$\displaystyle = \frac{1}{t} \log{\left (\frac{N}{N_{0}} \right )}$</td></tr></table>




```python
[solve(b,v)[0] for v in vl]
```


```python

```

338d258df677ea12b8aa224d9bc490c8c486df80
ipynb
Jupyter Notebook
sympy_main.ipynb
markus-antero/Stock
492e9b26c376d5e5f779e3b5cc2e51c7f92c7feb
Apache-2.0
sympy_main.ipynb
markus-antero/Stock
492e9b26c376d5e5f779e3b5cc2e51c7f92c7feb
Apache-2.0
sympy_main.ipynb
markus-antero/Stock
492e9b26c376d5e5f779e3b5cc2e51c7f92c7feb
Apache-2.0
Qwen/Qwen-72B
1. YES
2. YES