In [1]:
import sympy as sym
import numpy as np
from IPython.display import display,Math
import matplotlib.pyplot as plt
In [2]:
print('Tangent lines')
display(Math('t = t\'_a(x-x_a)+f_a'))
display(Math('y = m x + b'))
Tangent lines
$\displaystyle t = t'_a(x-x_a)+f_a$
$\displaystyle y = m x + b$
In [3]:
x = sym.symbols('x')

# define the function and its derivative
f = x**2
df = sym.diff(f)

# value at which to compute the tangent line
xa = 1

# get the function and derivative value at z_a
fa = f.subs(x,xa)
print(fa)
dfa = df.subs(x,xa)
print(dfa)

xx = np.linspace(-2,2,200)
f_fun = sym.lambdify(x,f)
print(f_fun(10))
f_fun = sym.lambdify(x,f)(xx)
print(f_fun[10])

df_fun = sym.lambdify(x,df)(xx)

# compute the tangent line
tanline = dfa * (xx-xa) + fa
print(xx[0])
print((xx-xa)[0])

plt.plot(xx,f_fun,label='f(x)')
plt.plot(xx,tanline,label='tangent')
plt.plot(xa,fa,'ro')

plt.axis('square')
plt.axis([-2,2,-2,2])

ax = plt.gca()
print(ax.get_xlim())
print(ax.get_ylim())
plt.plot(ax.get_xlim(),[0,0],'k--')
plt.plot([0,0],ax.get_ylim(),'k--')

plt.legend()
plt.show()
1
2
100
3.236382919623242
-2.0
-3.0
(-2.0, 2.0)
(-2.0, 2.0)