기본 콘텐츠로 건너뛰기

pandas_ta를 적용한 통계적 인덱스 지표

함수 그래프 그리기: 최대와 최소 찾기

작성된 그림은 전자책 파이썬과 함께하는 미분적분에서 Chapter 5.1에서 소개한 여러 그래프들과 그 코드입니다.

import numpy as np 
from sympy import *
import matplotlib.pyplot as plt
import seaborn as sns 
def tgline(slope, x0, y0, x):
    b=y0-slope*x0
    re=slope*x+b
    return(re)
def scantline(x0, y0, x1, y1, x):
    s, b=symbols("s, b")
    eq1=x0*s+b-y0
    eq2=x1*s+b-y1
    re=solve([eq1, eq2], (s, b))
    re1=float(re[s])*x+float(re[b])
    return(re1)

CH 5.1

#그림 5.1.1
x=np.linspace(-4,4, 100)
y=x**2
plt.figure(figsize=(4, 3))
plt.plot(x, y, color="g", label=r"f(x)=$x^2$")
for i in np.arange(-3, 4):
    if i==-1:
        nme=r"$\frac{df(x)}{dx} < 0$"
    elif i==1:
        nme=r"$\frac{df(x)}{dx} \geq 0$"
    else:
        nme=""
    plt.plot(x, tgline(2*i, i, i**2, x), ls="--", alpha=0.5, color=['r' if i < 0 else 'b'][0], label=nme)
plt.xlabel("x", loc="right", fontsize="11")
plt.ylabel("y", rotation="horizontal", loc="top", fontsize="11")
plt.ylim([-2, 10])
plt.legend(loc="best", labelcolor=['g','r', 'b'])
plt.show()
#그림 5.1.2
x=np.linspace(-4,4, 100)
y=x**2
plt.figure(figsize=(4, 3))
plt.plot(x, y, color="g", label=r"f(x)=$x^2$")
plt.plot(x, scantline(-1,1, -3, 9, x), ls="--", lw=2, alpha=0.6, color="b")
plt.plot(x, scantline(1,1,3,9, x), ls="--", lw=2, alpha=0.6, color="r")
px, py=[(-3,-1,3, 1), (9, 1, 9, 1)]
nme=['a', 'b', 'c', 'd']
col=['b','b','r','r']
for i in range(4):
    plt.scatter(px[i], py[i],  s=50, c=col[i])
    plt.text(px[i]+0.2, py[i], f"({nme[i]}, f({nme[i]}))", color=col[i])
plt.hlines(0, -4, 4, lw=0.7, color="gray")
plt.vlines(0, -3, 16, lw=0.7, color="gray")
plt.xlabel("x", fontsize="11")
plt.ylabel("y", rotation="horizontal", fontsize="11")
plt.xticks([])
plt.yticks([])
plt.ylim([-2, 12])
plt.legend(loc=(0.5, 0.8), labelcolor='g', frameon=False)
plt.show()
#그림 5.1.3
a=symbols('a')
f=(a-1)*(a-2)*(a-3)
df=diff(f, a)
sol=solve(df, a)
x=np.linspace(0, 6, 100)
y=[f.subs(a, i) for i in x]
y1=[df.subs(a, i) for i in x]
plt.figure(figsize=(4, 3))
plt.plot(x, y, color="g", label="f(x)=(x-1)(x-2)(x-4)")
plt.plot(x, y1, color="b", label=r"$\frac{df(x)}{dx}=3x^2-12x+11$")
plt.scatter([sol[0], sol[1]], [df.subs(a, sol[0]), df.subs(a, sol[1])], c="r", s=50,label=r"$\frac{df(x)}{dx}=0$")
plt.xlabel("x", fontsize="11")
plt.ylabel("y", rotation="horizontal", fontsize="11")
plt.ylim([-2, 3])
plt.legend(loc=(0.7, 0.6), labelcolor=['g','b'])
plt.show()
#그림 5.1.4
x=np.linspace(-1, 1, 100)
f=x**2
y=tgline(2*0.3, 0.3, 0.09, x)
y1=tgline(2*(-0.3), -0.3, 0.09, x)
plt.figure(figsize=(4, 3))
plt.plot(x, f, color="g", label=r"f(x)=$x^2$")
plt.plot(x, y1, ls="--", alpha=0.6, color="b")
plt.plot(x, y, ls="--", alpha=0.6, color="r")
plt.scatter(-0.3, 0.09, color="b", s=50,label="A")
plt.scatter(0,0, color="k", s=50,label="B(cv, min)")
plt.scatter(0.3, 0.09, color="r", s=50,label="C")
plt.xlabel("x", fontsize="11")
plt.ylabel("y", rotation="horizontal", fontsize="11")
plt.ylim([-0.5,0.5])
plt.legend(loc="best", labelcolor=['g','b','k','r'])
plt.show()
#그림 5.1.5
x=np.linspace(-10, 10, 100)
a=symbols("a")
f=a**4-6*a**3-8*a**2+2
df=f.diff(a)
sol=solve(df, a)
y=[f.subs(a, i) for i in x]
y1=[df.subs(a, i) for i in x]
plt.figure(figsize=(4, 3))
plt.plot(x, y, color="g", label="f(x)")
plt.plot(x, y1, color="b", label=r"$\frac{df(x)}{dx}$")
plt.scatter(sol[0], f.subs(a, sol[0]), s=50, c='r', label="A")
plt.scatter(sol[1], f.subs(a, sol[1]), s=50, c='brown', label="B")
plt.scatter(sol[2], f.subs(a, sol[2]), s=50, c='orange', label="C")
plt.xlabel("x", fontsize="11")
plt.ylabel("y", rotation="horizontal", fontsize="11")
plt.ylim([-400, 400])
plt.legend(loc="best", labelcolor=['g','b','k','r'], frameon=False)
plt.show()
#그림 5.1.6
x=np.linspace(-2, 3, 100)
a=symbols("a")
f=2*a**3-3*a**2-12*a+12
df=f.diff(a)
sol=solve(df, a)
y=[f.subs(a, i) for i in x]
y1=[df.subs(a, i) for i in x]
plt.figure(figsize=(4, 3))
plt.plot(x, y, color="g", label="f(x)")
plt.plot(x, y1, color="b", label=r"$\frac{df(x)}{dx}$")
plt.scatter(sol[0], f.subs(a, sol[0]), s=50, c='r', label="A")
plt.scatter(sol[1], f.subs(a, sol[1]), s=50, c='brown', label="B")
plt.xlabel("x", fontsize="11")
plt.ylabel("y", rotation="horizontal", fontsize="11")
plt.legend(loc='best', labelcolor=['g','b','k','r'])
plt.show()
#그림 5.1.7
a=symbols('a')
f=2*a**3-a**4
df=f.diff(a)
sol=solve(df, a)
x=np.linspace(-2, 3, 100)
y=[f.subs(a, i) for i in x]
y1=[df.subs(a, i) for i in x]
plt.figure(figsize=(4, 3))
plt.plot(x, y, color="g", label="f(x)")
plt.plot(x, y1, color="b", label=r"$\frac{df(x)}{dx}$")
plt.scatter(sol[0], f.subs(a, sol[0]), s=50, c='r', label="A")
plt.scatter(sol[1], f.subs(a, sol[1]), s=50, c='brown', label="B")
plt.xlabel("x", fontsize="11")
plt.ylabel("y", rotation="horizontal",fontsize="11")
plt.ylim([-5, 5])
plt.legend(loc="best", labelcolor="linecolor")
plt.show()
#그림 5.1.8
x1=np.linspace(-2, 1.999, 30)
x2=np.linspace(2.001, 10, 70)
y1=np.cbrt((x1-2)**2)+1
y2=np.cbrt((x2-2)**2)+1
plt.figure(figsize=(4, 3))
plt.plot(x1, y1, color="g", label="f(x)")
plt.plot(x2, y2, color="g")
plt.scatter(2, 1, s=50, c='white', edgecolors="k")
plt.xlabel("x", fontsize="11")
plt.ylabel("y", rotation="horizontal",fontsize="11")
plt.legend(loc="best", labelcolor="g")
plt.show()
#그림 5.1.9
t=symbols('t', positive=True)
p=(1-exp(-0.004*t))*1000000*500-1000000*t
dp=p.diff(t)
cp=solve(dp, t)
x=np.linspace(0, 500, 500)
y=[p.subs(t, i) for i in x]
y1=[dp.subs(t, i) for i in x]
f, ax=plt.subplots(1,1, figsize=(4,3))
plt.plot(x, y, color="g")
plt.scatter(cp[0], p.subs(t, cp[0]), s=30, c="r", label="Maximum")
plt.xlabel("t")
plt.ylabel("p(t)", rotation="horizontal", color="g")
plt.legend(loc="best")
ax2=ax.twinx()
plt.plot(x, y1, ls="dashed", color="b", label=r"$\frac{dp(t)}{dt}$")
plt.ylabel(r"$\frac{dp(t)}{dt}$", rotation="horizontal", color="b")
plt.show()

댓글

이 블로그의 인기 게시물

[Linear Algebra] 유사변환(Similarity transformation)

유사변환(Similarity transformation) n×n 차원의 정방 행렬 A, B 그리고 가역 행렬 P 사이에 식 1의 관계가 성립하면 행렬 A와 B는 유사행렬(similarity matrix)이 되며 행렬 A를 가역행렬 P와 B로 분해하는 것을 유사 변환(similarity transformation) 이라고 합니다. $$\tag{1} A = PBP^{-1} \Leftrightarrow P^{-1}AP = B $$ 식 2는 식 1의 양변에 B의 고유값을 고려한 것입니다. \begin{align}\tag{식 2} B - \lambda I &= P^{-1}AP – \lambda P^{-1}P\\ &= P^{-1}(AP – \lambda P)\\ &= P^{-1}(A - \lambda I)P \end{align} 식 2의 행렬식은 식 3과 같이 정리됩니다. \begin{align} &\begin{aligned}\textsf{det}(B - \lambda I ) & = \textsf{det}(P^{-1}(AP – \lambda P))\\ &= \textsf{det}(P^{-1}) \textsf{det}((A – \lambda I)) \textsf{det}(P)\\ &= \textsf{det}(P^{-1}) \textsf{det}(P) \textsf{det}((A – \lambda I))\\ &= \textsf{det}(A – \lambda I)\end{aligned}\\ &\begin{aligned}\because \; \textsf{det}(P^{-1}) \textsf{det}(P) &= \textsf{det}(P^{-1}P)\\ &= \textsf{det}(I)\end{aligned}\end{align} 유사행렬의 특성 유사행렬인 두 정방행렬 A와 B는 'A ~ B' 와 같...

유리함수 그래프와 점근선 그리기

내용 유리함수(Rational Function) 점근선(asymptote) 유리함수 그래프와 점근선 그리기 유리함수(Rational Function) 유리함수는 분수형태의 함수를 의미합니다. 예를들어 다음 함수는 분수형태의 유리함수입니다. $$f(x)=\frac{x^{2} - 1}{x^{2} + x - 6}$$ 분수의 경우 분모가 0인 경우 정의할 수 없습니다. 이와 마찬가지로 유리함수 f(x)의 정의역은 분모가 0이 아닌 부분이어야 합니다. 그러므로 위함수의 정의역은 분모가 0인 부분을 제외한 부분들로 구성됩니다. sympt=solve(denom(f), a); asympt [-3, 2] $$-\infty \lt x \lt -3, \quad -3 \lt x \lt 2, \quad 2 \lt x \lt \infty$$ 이 정의역을 고려해 그래프를 작성을 위한 사용자 정의함수는 다음과 같습니다. def validX(x, f, symbol): ① a=[] b=[] for i in x: try: b.append(float(f.subs(symbol, i))) a.append(i) except: pass return(a, b) #x는 임의로 지정한 정의역으로 불연속선점을 기준으로 구분된 몇개의 구간으로 전달할 수 있습니다. #그러므로 인수 x는 2차원이어야 합니다. def RationalPlot(x, f, sym, dp=100): fig, ax=plt.subplots(dpi=dp) # ② for k in x: #③ x4, y4=validX(k, f, sym) ax.plot(x4, y4) ax.spines['left'].set_position(('data', 0)) ax.spines['right...

부분분수의 미분

내용 방법 1 방법 2 방법 3 부분분수의 미분 분수의 미분은 일정한 공식 을 적용하여 계산할 수 있습니다. 그러나 분수 자체가 단순한 표현으로 이루어지지 않았다면 미분 과정이나 결과는 매우 복잡할 수 있습니다. 만약 복잡한 분수 함수를 간단한 분수들로 분해할 수 있다면 계산이 보다 간편해질 것입니다. 이와 같이 분해된 간단한 분수들을 부분분수 라고 합니다. 예를 들어 다음 두 분수의 합을 계산해 봅니다. $$\begin{align} \frac{1}{x+1}+\frac{2}{x-1}&=\frac{x-1+2(x+1)}{(x+1)(x-1)}\\ &=\frac{3x+1}{x^2-1} \end{align}$$ 위 과정은 3개 이상의 여러 분수에서도 이루어질 수 있습니다. 또한 역으로 진행될 수 있습니다. 즉, 분수를 부분 분수로 분할할 수 있습니다. 그러나 이러한 과정은 대수분수 (분자의 가장 큰 차수가 분모의 최고의 차수보다 작은 분수)에서만 이루어질 수 있습니다. 예를 들어 $\displaystyle \frac {x^2+2}{x^2-1}$의 경우는 분자와 분모의 차수는 2차로 같습니다. 이러한 경우 다음과 같이 분리할 수 있습니다. $$\frac{x^2+2}{x^2-1}=1+\frac{3}{x^2-1}$$ 위의 식 중 $\displaystyle \frac{3}{x^2-1}$은 분자의 차수가 분모의 차수 보다 낮은 대수 분수이므로 부분 분수로 분리할 수 있습니다. 이와같이 부분 분수로 분해하는 방법은 다음과 같이 몇 가지로 구분할 수 있습니다. 방법 1 위 예의 결과 $\displaystyle \frac{3x+1}{x^2-1}$의 경우를 역으로 생각해 봅니다. 분모의 인수분해가 가능하면 그 분모의 인수에 의해 다음과 같이 분해할 수 있습니다. $$\begin{align} \frac{3x+1}{x^2-1}&=\frac{3x+1}{(x+1)(x-1)}\\ &=\frac{A}{x+1...