기본 콘텐츠로 건너뛰기

[matplotlib] 등고선(Contour)

[matplotlib] 접선식 생성과 접선 그리기

접선 그리기

함수의 특정한 점에서 접선의 기울기는 그 지점에서의 미분값과 같습니다.

a=symbols("a")
f=(a-1)**2
df=f.diff('a')
df
2a - 2

함수 f위의 점(3, f(3))에서의 접선 식은 다음과 같이 계산할 수 있습니다.

slope=df.subs(a, 3); slope
4

$$\begin{align} y&=\text{slope}\times x+b \\ b&= y - \text{slope}\times x\\&=f(3)-f^\prime(3)\times 3\end{align}$$

b=f.subs(a, 3)-slope*3
eq=slope*a+b; eq
4a−8

위에서 생성한 두 식 f와 eq(접선식)에 대한 그래프를 작성합니다. 그래프 작성에 필요한 함수 plot()과 scatter() 그리고 축 설정은 조각함수 작성에서 적용한 것과 같습니다.

x=np.linspace(-1, 5, 100)
fy=[f.subs(a, i) for i in x]
eqy=[eq.subs(a, i) for i in x]
fig, ax=plt.subplots(figsize=(4, 3))
ax.plot(x, fy, color="g", label=r"f(x)=(x-1)^2")
ax.plot(x, eqy, color="b", label="g(x)=4x-8")
ax.scatter(3, f.subs(a, 3), s=50, c="b")
ax.spines['left'].set_position(("data", 0))
ax.spines['bottom'].set_position(("data", 0))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_xlabel("x", loc="right", fontsize="11")
ax.set_ylabel("y", rotation="horizontal", loc="top", fontsize="11")
ax.legend(loc='upper center', labelcolor="linecolor")
plt.show()

위 과정에서 접선의 식 생성을 위해 다음과 같이 함수를 작성하여 사용할 수 있습니다.

def tgline(f, sym, x, y):
    df=f.diff(sym)
    slope=df.subs(a, x)
    b=y-slope*x
    return(slope*sym+b)
tgline(f, a, 3, f.subs(a, 3))
4a - 8

또한 (0, 0)을 교차하는 축을 설정하기 위해 함수를 작성할 수 있습니다.

def axisTran(ax):
    ax.spines['left'].set_position(("data", 0))
    ax.spines['bottom'].set_position(("data", 0))
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

위 작성한 함수들을 적용하여 접선 그래프를 작성하기 위한 코드는 다음과 같습니다.

a=symbols("a")
f=(a-1)**2
x=np.linspace(-1, 5, 100)
fy=[f.subs(a, i) for i in x]
eq=tgline(f, a, 3, f.subs(a, 3))
eqy=[eq.subs(a, i) for i in x]
fig, ax=plt.subplots(figsize=(4, 3))
ax.plot(x, fy, color="g", label=r"f(x)=(x-1)^2")
ax.plot(x, eqy, color="b", label="g(x)=4x-8")
ax.scatter(3, f.subs(a, 3), s=50, c="b")
axisTran(ax)
ax.set_xlabel("x", loc="right", fontsize="11")
ax.set_ylabel("y", rotation="horizontal", loc="top", fontsize="11")
ax.legend(loc='upper center', labelcolor="linecolor")
plt.show()

댓글