다음과 같은 함수가 있습니다.
$$ f(x) = x^2 + x $$
위 함수를 코드로 정의하면 다음과 같습니다.
def function_1(x): return x**2 + x
수치 미분의 오차를 줄이기 위해서, 중앙차분 방법을 사용합니다.
def numerical_diff(f, x): h = 1e-4 # 0.0001 return (f(x+h) - f(x-h)) / (2*h)
미분의 결과인 접선을 표현하는 함수는 다음과 같습니다.
def tangent_line(f, x): d = numerical_diff(f, x) y = f(x) - d*x return lambda t: d*t + y
x = 5 일때의 접선을 그려보면 다음과 같습니다.
import numpy as np import matplotlib.pylab as plt x = np.arange(0.0, 20.0, 0.1) y = function_1(x) plt.xlabel("x") plt.ylabel("f(x)") tf = tangent_line(function_1, 5) y2 = tf(x) plt.plot(x, y) plt.plot(x, y2) plt.show()
