Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot the slope (tangent line) of parabola at any point?

I want to plot a simple illustration of using derivative to find out a slope of a function at any point. It would look kinda like this:

I have already plotted a simple parabola using this code:

import numpy as np
from matplotlib import pyplot as plt

inputs = 0.2
weights = np.arange(-6,14)
target_prediction = 0.7

prediction = inputs*weights
errors = (prediction - target_prediction) ** 2
plt.xlabel("Weight")
plt.ylabel("Error")
plt.plot(weights, error)

Now I want to add something like this:

current_weight = 5
# draw a short fraction of a line to represent slope
x = np.arange(optimal_weight - 3, optimal_weight + 3)
# derivative
slope = 2 * (inputs*current_weight - target_prediction)
y = slope*x # How should this equation look like?
plt.plot(x, y)

To draw a tangent line going through the current_weight.

But I can't seem to figure this out, can you help?

like image 692
lumenwrites Avatar asked Mar 02 '19 17:03

lumenwrites


People also ask

How do you find the slope of the tangent line to the parabola at the point?

To find the slope of a line tangent to a parabola at a specific point, find the derivative of the parabola's equation, then substitute the -coordinate of the specific point in the new equation.


Video Answer


1 Answers

Once you have the slope at the desired point, you need to write the equation for the tangent line using point-slope form:

# Define parabola
def f(x): 
    return x**2

# Define parabola derivative
def slope(x): 
    return 2*x

# Define x data range for parabola
x = np.linspace(-5,5,100)

# Choose point to plot tangent line
x1 = -3
y1 = f(x1)

# Define tangent line
# y = m*(x - x1) + y1
def line(x, x1, y1):
    return slope(x1)*(x - x1) + y1

# Define x data range for tangent line
xrange = np.linspace(x1-1, x1+1, 10)

# Plot the figure
plt.figure()
plt.plot(x, f(x))
plt.scatter(x1, y1, color='C1', s=50)
plt.plot(xrange, line(xrange, x1, y1), 'C1--', linewidth = 2)

Parabola with tangent line

You can do this for any differentiable function, and can use derivative approximation methods (such as finite differencing) to eliminate the need to provide the analytical derivative.

like image 92
Nathaniel Avatar answered Oct 22 '22 01:10

Nathaniel