Skip to content

Instantly share code, notes, and snippets.

@yingshaoxo
Created November 30, 2017 14:58
Show Gist options
  • Save yingshaoxo/190e2b9d883e2c59a9d07a1a50b18f4d to your computer and use it in GitHub Desktop.
Save yingshaoxo/190e2b9d883e2c59a9d07a1a50b18f4d to your computer and use it in GitHub Desktop.
pylab draw tangent lines
import numpy as np
import pylab
class MathDraw():
def __init__(self, func):
self.f = func
self.vf = np.vectorize(func)
def draw(self, x_start=-5.0, y_end=5.0):
x = np.arange(x_start, y_end, 0.1)
y = self.vf(x)
pylab.plot(x, y, 'b')
def draw_tangent(self, *args, length=1, color='--r'):
f = self.f
xlist = args
for x in xlist:
unit = 0.1
length = length / 2
tangent_x = np.arange(x-length, x+length+unit, unit)
h = 0.1 # the micro difference in x
f_prime = (f(x+h) - f(x)) / h # derivative
tangent_y = f_prime * (tangent_x - x) + f(x) # tangent
# plot of the point and the tangent
pylab.plot(x, f(x), 'om', tangent_x, tangent_y, color)
def show(self):
pylab.show()
def func(x): # sample function
return x*np.sin(np.power(x,2))
m = MathDraw(func)
m.draw(-2, 4)
m.draw_tangent(-1.5, 1.5, 2.15, length=2)
m.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment