다음 그림들은 전자책 파이썬과 함께하는 미분적분의 5.5장에 수록된 그래프들과 코드들입니다.
import numpy as np import pandas as pd from sympy import * import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid")
def tgline(slope, x0, y0, x): b=y0-slope*x0 re=slope*x+b return(re)
#그림 5.5.1 x=symbols('x', real=True) f=x**3+2*x**2 df=f.diff(x) cp=solve(df) a=np.linspace(-1.618, 0.618, 100) y=[f.subs(x, i) for i in a] dy=[df.subs(x, i) for i in a] plt.figure(figsize=(4,3)) plt.plot(a, y, color='g', label="f(x)") plt.plot(a, dy, color='b', ls="dashed", alpha=0.3, label=r"$\frac{df(x)}{dx}$") idx=[(a[0],"r","A"), (cp[0], "b","D"), (cp[1], "k","C"), (a[-1], "brown","B")] for i in idx: plt.scatter(i[0], f.subs(x, i[0]), s=30, c=i[1], label=f"{i[2]}") plt.ylim(-0.5, 1.5) plt.xlabel("x") plt.ylabel("y", rotation="horizontal") plt.legend(bbox_to_anchor=(1, 1), labelcolor='linecolor') plt.show()
#그림 5.5.2 x=symbols('x') f=x**3-x f0=f.subs(x,0) f2=f.subs(x, 2) x=symbols('x') f=x**3-x avg=(f2-f0)/(2-0) df=f.diff(x) c=solve(Eq(df, avg)) a=np.linspace(0, 2, 100) y=[f.subs(x, i) for i in a] plt.figure(figsize=(4,3)) k=tgline(3, c[1], f.subs(x, c[1]), x) ky=[k.subs(x, i) for i in a] plt.plot(a, y, color="g", label="f(x)") plt.plot(a, ky, ls="dashed",color="b", label="tangent") plt.plot([0,2], [f0, f2], ls="dashed", color="r", label="average") plt.xlabel("x") plt.ylabel("y", rotation="horizontal") plt.legend(loc="best", labelcolor='linecolor') plt.show()
댓글
댓글 쓰기