Tangent lines at different points of a differentiable function

import numpy as np from sympy import * import matplotlib.pyplot as plt x = symbols('x') f = x**3 - 6*x**2 diffx = diff(f, x) # compute the derivative only once points_x_start, points_x_end, points_count = -10, 10, 40 points_x_range = points_x_end - points_x_start points_x = np.linspace(points_x_start, points_x_end, points_count) points_y = [] for p in points_x: fp = f.subs(x, p) points_y.append(fp) slope = diffx.subs(x, p) # We could also use limits, but evaluating them at each point is slow # slope = limit((f - fp) / (x - p), x, p), # Obtain the equation of the tangent line at this point y = slope*(x - p) + fp # Plot only start and end points line_xs = [p - points_x_range/4, p + points_x_range/4] line_ys = [y.subs(x, line_xs[0]), y.subs(x, line_xs[1])] plt.plot(line_xs, line_ys, '-', color='#00DF63', linewidth=0.75) plt.title(r'$ x^3 - 6x^2 $') plt.plot(points_x, points_y, '-', color='#000000', linewidth=2) plt.xlim(points_x_start, points_x_end) plt.show()

Here are the tangent lines to the functions f(x) = x3 + 6x2 and f(x) = x2:

The tangent lines at some points on the function x^3 + 6x^2 The tangent lines at some points on the function x^2