Analiza matematyczna¶
Za pomocą biblioteki sympy można przedstawić i przekaształcać saymboolicznie działania na pochodnych i całkach.
Również z jej wykorzystaniem można dokonać obliczeń numerycznych zdefiniowanych wcześniej (sybolicznie) przykładów.
Za pomocą biblioteki plotly można graficznie przedstawiać wyniki obliczeń. Biblioteka ta generuje interaktywne wykresy, co pozwala analizować dokąłdnie wykres.
Pochodne¶
from IPython.display import display, Markdown
import sympy as sp
a, b, c, x = sp.symbols('a b c x')
fy = a*x**3+b*x**2+c
fyp = sp.diff(fy,x, evaluate=True)
fypp = sp.diff(fy,x,x, evaluate=True)
latex_code = fr"""
\begin{{array}}{{l}}
\\ \Large f={sp.latex(fy)}
\\ \\ \Large f'={sp.latex(fyp)}
\\ \\ \Large f''={sp.latex(fypp)}
\end{{array}}
"""
display(Markdown(latex_code))
#https://docs.sympy.org/latest/tutorials/intro-tutorial/calculus.html
\begin{array}{l} \\ \Large f=a x^{3} + b x^{2} + c \\ \\ \Large f'=3 a x^{2} + 2 b x \\ \\ \Large f''=2 \cdot \left(3 a x + b\right) \end{array}
Wykresy funkcji¶
import numpy as np
import sympy as sp
import plotly as pl
import plotly.express as px
import pandas as pd
pl.io.renderers.default = "notebook_connected" # musi być jeżeli chcemy do html-a
param = [(a, 2),
(b, 3),
(c, 4)
]
vx = np.linspace(-4, 4, 100)
fy = fy.subs(param)
fyp = fyp.subs(param)
fypp = fypp.subs(param)
vy = []
vyp = []
vypp = []
for x_ in vx:
vy.append(float(fy.subs(x, x_).evalf()))
vyp.append(float(fyp.subs(x, x_).evalf()))
vypp.append(float(fypp.subs(x, x_).evalf()))
data = {"f": vy,
"f'": vyp,
"f''": vypp}
df = pd.DataFrame(data=data, index=vx)
fig = px.line(df) #, width=750, height=550)
fig.update_layout(
title='Wykres funkcji i pochodnych',
xaxis_title=r'X',
yaxis_title=r'Y'
)
fig.show()
Badanie funkcji wielu zmiennych¶
import sympy as sp
x, y = sp.symbols('x y')
#f = x**3-3*x+2*y**2+4*y+5 # równanie
#f = 3*y-y**3+x**2-6*x+7 # równanie
f = x**2-x*y+2*y**2-x+4*y-5 # równanie
fdxs = sp.Derivative(f, x)
fdys = sp.Derivative(f, y)
fdx = sp.Derivative(f, x, evaluate=True)
fdy = sp.Derivative(f, y, evaluate=True)
fdxxs = sp.Derivative(f, x, x)
fdyys = sp.Derivative(f, y, y)
fdxys = sp.Derivative(f, x, y)
fdxx = sp.Derivative(f, x, x, evaluate=True)
fdyy = sp.Derivative(f, y, y, evaluate=True)
fdxy = sp.Derivative(f, x, y, evaluate=True)
m = sp.Matrix([
[fdxx, fdxy],
[fdxy, fdyy]
])
eq1 = sp.Eq(fdx, 0) # pierwsze rónanie pochodna x do 0
eq2 = sp.Eq(fdy, 0) # pierwsze rónanie pochodna y do 0
solution = sp.solve((eq1, eq2), (x, y)) # Rozwiązujemy układ równań
# wyświetlenie wyników
latex_code = fr"""
\begin{{align*}}
& \Large f(x,y)={sp.latex(f)} \\ \\
& \Large f'x(x,y)={sp.latex(fdxs)}={sp.latex(fdx)} \\ \\
& \Large f'y(x,y)={sp.latex(fdys)}={sp.latex(fdy)} \\ \\
& \left\{{\begin{{array}}{{l}}
\Large{sp.latex(eq1)} \\ \\
\Large {sp.latex(eq2)}
\end{{array}}\right.; \; \Large \text{{Rozwiązania}} \; P(x,y) = {sp.latex(solution)} \\ \\
& \Large f'xx(x,y)={sp.latex(fdxxs)}={sp.latex(fdxx)} \\ \\
& \Large f'yy(x,y)={sp.latex(fdyys)}={sp.latex(fdyy)} \\ \\
& \Large f'xy(x,y)={sp.latex(fdxys)}={sp.latex(fdxy)} \\ \\
& \Large H={sp.latex(m)}; \; \text{{macierz Hessego}} \\ \\
& \Large det(H)={sp.latex(m.det())}; \; \text{{hesjan > 0 to lokalne ekstremum}} \\ \\
& \Large f'xx(x,y) > 0; \; \text{{to minimum}} \\ \\
& \Large f'xx(x,y) < 0; \; \text{{to maksimum}} \\ \\
\end{{align*}}
"""
display(Markdown(latex_code))
\begin{align*} & \Large f(x,y)=x^{2} - x y - x + 2 y^{2} + 4 y - 5 \\ \\ & \Large f'x(x,y)=\frac{\partial}{\partial x} \left(x^{2} - x y - x + 2 y^{2} + 4 y - 5\right)=2 x - y - 1 \\ \\ & \Large f'y(x,y)=\frac{\partial}{\partial y} \left(x^{2} - x y - x + 2 y^{2} + 4 y - 5\right)=- x + 4 y + 4 \\ \\ & \left\{\begin{array}{l} \Large2 x - y - 1 = 0 \\ \\ \Large - x + 4 y + 4 = 0 \end{array}\right.; \; \Large \text{Rozwiązania} \; P(x,y) = \left\{ x : 0, \ y : -1\right\} \\ \\ & \Large f'xx(x,y)=\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} - x y - x + 2 y^{2} + 4 y - 5\right)=2 \\ \\ & \Large f'yy(x,y)=\frac{\partial^{2}}{\partial y^{2}} \left(x^{2} - x y - x + 2 y^{2} + 4 y - 5\right)=4 \\ \\ & \Large f'xy(x,y)=\frac{\partial^{2}}{\partial y\partial x} \left(x^{2} - x y - x + 2 y^{2} + 4 y - 5\right)=-1 \\ \\ & \Large H=\left[\begin{matrix}2 & -1\\-1 & 4\end{matrix}\right]; \; \text{macierz Hessego} \\ \\ & \Large det(H)=7; \; \text{hesjan > 0 to lokalne ekstremum} \\ \\ & \Large f'xx(x,y) > 0; \; \text{to minimum} \\ \\ & \Large f'xx(x,y) < 0; \; \text{to maksimum} \\ \\ \end{align*}
from fileinput import filename
from operator import index
from tracemalloc import stop
from xml.dom.expatbuilder import TEXT_NODE
import numpy as np
import pandas as pd
import plotly.graph_objects as go
surfaces = []
ox = np.linspace(-2, 2, 100)
oy = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(ox, oy)
fZ = sp.lambdify((x, y), f, 'numpy')
Z = fZ(X, Y)
surface = go.Surface(x=X, y=Y, z=Z,
colorscale=[[0, 'red'], [1, 'red']],
name='f', showlegend=True, showscale=False)
surfaces.append(surface)
fZ = sp.lambdify((x, y), fdx, 'numpy')
Z = fZ(X, Y)
surface = go.Surface(x=X, y=Y, z=Z,
colorscale=[[0, 'blue'], [1, 'blue']],
name="f'x", showlegend=True, showscale=False)
surfaces.append(surface)
fZ = sp.lambdify((x, y), fdy, 'numpy')
Z = fZ(X, Y)
surface = go.Surface(x=X, y=Y, z=Z,
colorscale=[[0, 'green'], [1, 'green']],
name="f'y", showlegend=True, showscale=False)
surfaces.append(surface)
fig = go.Figure(data=surfaces)
if type(solution) is dict: # jedno rozwiązanie
px = float(solution[x])
py = float(solution[y])
pz = float(f.subs([(x, px), (y, py)]).evalf())
fig.add_trace(go.Scatter3d(
x=[px], y=[py], z=[pz],
mode='markers',
marker=dict( size=10, color='yellow', opacity=0.8),
name=f"P({px},{py},{pz})"
))
else: # kilka rozwiązań
si = 0
for sol in solution:
px = float(sol[0])
py = float(sol[1])
pz = float(f.subs([(x, px), (y, py)]).evalf())
if si == 0:
c = 'yellow'
else:
c = 'orange'
fig.add_trace(go.Scatter3d(
x=[px], y=[py], z=[pz],
mode='markers',
marker=dict( size=10, color=c, opacity=0.8 ),
name=f"P({px},{py},{pz})"
))
si += 1
# Ustawienia osi i widoczności legendy
fig.update_layout(
scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z' ),
showlegend=True, # Włączenie legendy
title="Ekstrema funkcji"
)
fig.show()
Gradient i płąszczyzna styczna¶
import sympy as sp
x, y = sp.symbols('x y')
f = x**2*y-x*y**3
# Obliczenie gradientu
gradient = {i:sp.diff(f,i) for i in (x, y)}
# punkt stycznej
x0 = 1
y0 = 2
z0 = f.subs([(x,x0),(y,y0)])
p = [x0, y0, z0 ]
df_dx_at_P = gradient[x].subs({x: x0, y: y0})
df_dy_at_P = gradient[y].subs({x: x0, y: y0})
# równanie stycznej
s = z0 + df_dx_at_P * (x - x0) + df_dy_at_P * (y - y0)
# prezentacja wyników
latex_code = fr"""
\begin{{align*}}
& \Large f={sp.latex(f)} \\ \\
& \Large \nabla f={sp.latex(gradient)} \\ \\
& \Large P={sp.latex(p)}; \; \text{{Punkt w którym ma być styczna}} \\ \\
& \Large s={sp.latex(s)}; \; \text{{Równanie płaszczyzny stycznej}}
\end{{align*}}
"""
display(Markdown(latex_code))
\begin{align*} & \Large f=x^{2} y - x y^{3} \\ \\ & \Large \nabla f=\left\{ x : 2 x y - y^{3}, \ y : x^{2} - 3 x y^{2}\right\} \\ \\ & \Large P=\left[ 1, \ 2, \ -6\right]; \; \text{Punkt w którym ma być styczna} \\ \\ & \Large s=- 4 x - 11 y + 20; \; \text{Równanie płaszczyzny stycznej} \end{align*}
from fileinput import filename
from operator import index
from tracemalloc import stop
from xml.dom.expatbuilder import TEXT_NODE
import numpy as np
import pandas as pd
import plotly.graph_objects as go
surfaces = []
ox = np.linspace(-3, 3, 100)
oy = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(ox, oy)
fZ = sp.lambdify((x, y), f, 'numpy')
Z = fZ(X, Y)
surface = go.Surface(x=X, y=Y, z=Z, colorscale=[[0, 'red'], [1, 'red']], name='f', showlegend=True, showscale=False)
surfaces.append(surface)
fZ = sp.lambdify((x, y), s, 'numpy')
Z = fZ(X, Y)
surface = go.Surface(x=X, y=Y, z=Z, colorscale=[[0, 'blue'], [1, 'blue']], name='s', showlegend=True, showscale=False)
surfaces.append(surface)
fig = go.Figure(data=surfaces)
px = float(x0)
py = float(y0)
pz = float(z0)
fig.add_trace(go.Scatter3d(
x=[px], y=[py], z=[pz],
mode='markers',
marker=dict( size=10, color='yellow', opacity=0.8 ),
name=f"P({px},{py},{pz})"
))
# Ustawienia osi i widoczności legendy
fig.update_layout(
scene=dict( xaxis_title='X', yaxis_title='Y', zaxis_title='Z' ),
showlegend=True, # Włączenie legendy
title="Płaszczyzna styczna w punkcie"
)
fig.show()
import sympy as sp
# Definiowanie zmiennej i funkcji
x = sp.symbols('x')
y = sp.Function('y')(x)
# Definiowanie równania różniczkowego
ode1 = sp.Eq(y.diff(x), 2 * y * (x + 3))
# Rozwiązanie równania
sol1 = sp.dsolve(ode1, y)
ode2 = sp.Eq(sp.exp(y) * y.diff(x), 2*x + sp.cos(x))
sol2 = sp.dsolve(ode2, y)
ode3 = sp.Eq(y.diff(x), (y + 1) / (x + 1))
sol3 = sp.dsolve(ode3, y)
# Uwzględnienie warunku początkowego y(0) = 1
C1 = sp.symbols('C1')
ini_con = sol3.rhs.subs(x, 0) - 1
C_v = sp.solve(ini_con, C1)[0]
sol_with_ic = sol3.subs(C1, C_v)
# prezentacja wyników
latex_code = fr"""
\begin{{align*}}
& \Large {sp.latex(ode1)} \; \Rightarrow \; {sp.latex(sol1)} \\ \\
& \Large {sp.latex(ode2)} \; \Rightarrow \; {sp.latex(sol2)} \\ \\
& \Large {sp.latex(ode3)} \; \Rightarrow \; {sp.latex(sol3)} \\
& \Large y(0)=1 \Rightarrow C_1={C_v} \; \Rightarrow \; {sp.latex(sol_with_ic)}
\end{{align*}}
"""
display(Markdown(latex_code))
\begin{align*} & \Large \frac{d}{d x} y{\left(x \right)} = 2 \left(x + 3\right) y{\left(x \right)} \; \Rightarrow \; y{\left(x \right)} = C_{1} e^{x \left(x + 6\right)} \\ \\ & \Large e^{y{\left(x \right)}} \frac{d}{d x} y{\left(x \right)} = 2 x + \cos{\left(x \right)} \; \Rightarrow \; y{\left(x \right)} = \log{\left(C_{1} + x^{2} + \sin{\left(x \right)} \right)} \\ \\ & \Large \frac{d}{d x} y{\left(x \right)} = \frac{y{\left(x \right)} + 1}{x + 1} \; \Rightarrow \; y{\left(x \right)} = C_{1} x + C_{1} - 1 \\ & \Large y(0)=1 \Rightarrow C_1=2 \; \Rightarrow \; y{\left(x \right)} = 2 x + 1 \end{align*}
liniowe¶
import sympy as sp
# Definiowanie zmiennych
x = sp.symbols('x')
y = sp.Function('y')(x)
# Definiowanie równania różniczkowego
ode1 = sp.Eq(x * y.diff(x) + y, 3*x**2 - 6/x**2)
# Rozwiązanie równania
sol1 = sp.dsolve(ode1, y)
ode2 = sp.Eq(y.diff(x) + 2*x*y, x**3)
sol2 = sp.dsolve(ode2, y)
ode3 = sp.Eq(y.diff(x) + 3*y, 2*x)
sol3 = sp.dsolve(ode3, y)
# Warunek początkowy y(0) = 5
C1 = sp.symbols('C1')
init_con = sol3.rhs.subs(x, 0) - 5
C_v = sp.solve(ini_con, C1)[0]
# Rozwiązanie szczególne
sol_with_ic = sol3.subs(C1, C_v)
# prezentacja wyników
latex_code = fr"""
\begin{{align*}}
& \Large {sp.latex(ode1)} \; \Rightarrow \; {sp.latex(sol1)} \\ \\
& \Large {sp.latex(ode2)} \; \Rightarrow \; {sp.latex(sol2)} \\ \\
& \Large {sp.latex(ode3)} \; \Rightarrow \; {sp.latex(sol3)} \\
& \Large y(0)=5 \Rightarrow C_1={C_v} \; \Rightarrow \; {sp.latex(sol_with_ic)}
\end{{align*}}
"""
display(Markdown(latex_code))
\begin{align*} & \Large x \frac{d}{d x} y{\left(x \right)} + y{\left(x \right)} = 3 x^{2} - \frac{6}{x^{2}} \; \Rightarrow \; y{\left(x \right)} = \frac{C_{1} x + x^{4} + 6}{x^{2}} \\ \\ & \Large 2 x y{\left(x \right)} + \frac{d}{d x} y{\left(x \right)} = x^{3} \; \Rightarrow \; y{\left(x \right)} = C_{1} e^{- x^{2}} + \frac{x^{2}}{2} - \frac{1}{2} \\ \\ & \Large 3 y{\left(x \right)} + \frac{d}{d x} y{\left(x \right)} = 2 x \; \Rightarrow \; y{\left(x \right)} = C_{1} e^{- 3 x} + \frac{2 x}{3} - \frac{2}{9} \\ & \Large y(0)=5 \Rightarrow C_1=2 \; \Rightarrow \; y{\left(x \right)} = \frac{2 x}{3} - \frac{2}{9} + 2 e^{- 3 x} \end{align*}
Szereg Taylora ¶
import sympy as sp
# Definiujemy zmienną i funkcję
x = sp.symbols('x')
f = sp.exp(x) # e^x
# Rozwinięcie w szereg Taylora (Maclaurina) do 5. rzędu
f_t0 = sp.series(f, x, x0=0, n=6) # 6 oznacza do x^5 (liczy się też wyraz stały)
f_t1 = sp.series(f, x, x0=1, n=6) # 6 oznacza do x^5 (liczy się też wyraz stały)
# prezentacja wyników
latex_code = fr"""
\begin{{align*}}
& \Large f(x)={sp.latex(f)} \\ \\
& \Large x_0=0; f_{{t0}}(x)={sp.latex(f_t0)} \\
& \Large x_0=1; f_{{t1}}(x)={sp.latex(f_t1)} \\
\end{{align*}}
"""
display(Markdown(latex_code))
\begin{align*} & \Large f(x)=e^{x} \\ \\ & \Large x_0=0; f_{t0}(x)=1 + x + \frac{x^{2}}{2} + \frac{x^{3}}{6} + \frac{x^{4}}{24} + \frac{x^{5}}{120} + O\left(x^{6}\right) \\ & \Large x_0=1; f_{t1}(x)=e + e \left(x - 1\right) + \frac{e \left(x - 1\right)^{2}}{2} + \frac{e \left(x - 1\right)^{3}}{6} + \frac{e \left(x - 1\right)^{4}}{24} + \frac{e \left(x - 1\right)^{5}}{120} + O\left(\left(x - 1\right)^{6}; x\rightarrow 1\right) \\ \end{align*}
import numpy as np
import sympy as sp
import plotly as pl
import plotly.graph_objects as go
pl.io.renderers.default = "notebook_connected" # musi być jeżeli chcemy do html-a
# Tworzymy zakres wartości x
vx = np.linspace(-2, 2, 100)
fy1 = sp.lambdify((x), f, 'numpy')
y1 = fy1(vx)
f_t0 = f_t0.removeO()
fyt0 = sp.lambdify((x), f_t0, 'numpy')
yt0 = fyt0(vx)
f_t1 = f_t1.removeO()
fyt1 = sp.lambdify((x), f_t1, 'numpy')
yt1 = fyt1(vx)
fig = go.Figure()
fig.add_trace(go.Scatter(x=vx, y=y1, mode='lines', name='f', line=dict(color='red')))
fig.add_trace(go.Scatter(x=vx, y=yt0, mode='lines', name='ft0', line=dict(color='blue', dash='dash')))
fig.add_trace(go.Scatter(x=vx, y=yt1, mode='lines', name='ft1', line=dict(color='green', dash='dash')))
# Dodajemy tytuł i etykiety
fig.update_layout(
title="Szereg Taylora",
xaxis_title="x",
yaxis_title="y",
yaxis_type="linear",
legend=dict(x=0.1, y=0.9)
)
# Wyświetlamy wykres
fig.show()
Całki¶
w budowie, w planie przedstawienie w 3D interpretacji geonetrycznej funkcji 2 zmiennych, czyli objętości.
y = (x**2+5*x)*sp.exp(x)
integ = sp.Integral(y, x)
display(sp.Eq(integ, integ.doit(), evaluate=False))
integ = sp.Integral(y, (x, 0,2))
display(sp.Eq(integ, integ.doit(), evaluate=False))
y = sp.exp(-x)
integ = sp.Integral(y, (x, 0, sp.oo))
display(sp.Eq(integ, integ.doit(), evaluate=False))