Python Tangent to the Curve in Python

 Python Tangent to the Curve in Python


In this blog we will learn how to plot tangent line on a curve using python. We will use various modules like matplotlib.pyplot , numpy , ipywidgets to make it. I have a interactive one and here is the code .



Note : this code only works in Jupyter Notebook






import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from ipywidgets import interactive
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)

def t(x1):
  # Choose point to plot tangent line
  
  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)

interactive_plot = interactive(t ,x1 = (-5,5),step =100)
interactive_plot






Post a Comment

0 Comments