Skip to content

Instantly share code, notes, and snippets.

@mrocklin
Forked from anonymous/func_plot.py
Created December 26, 2012 19:58
Show Gist options
  • Save mrocklin/4382671 to your computer and use it in GitHub Desktop.
Save mrocklin/4382671 to your computer and use it in GitHub Desktop.
A quick example of plotting real valued functions. This example highlights the use of functions as first class objects and higher order functions.
from numpy import linspace, sin
from pylab import plot, figure, show
def plotFunction(f):
""" Plot a function on the domain x in (-10, 10) """
xs = linspace(-10, 10, 100)
ys = map(f, xs)
plot(xs, ys)
def derivative(f, dx=.00001):
""" The derivative of a real valued function """
def fprime(x):
return (f(x + dx) - f(x)) / dx
return fprime
def sync(x):
""" An example function """
if x == 0:
return 1
else:
return sin(x) / x
if __name__ == '__main__':
figure()
plotFunction(sin)
plotFunction(derivative(sin))
figure()
plotFunction(sync)
plotFunction(derivative(sync))
plotFunction(derivative(derivative(sync)))
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment