[ Site Home | Journal Home ]
"Understanding Algorithms and Data Structures" by Brunskill and Turner was on the reading list of one the units on my CS course. It has some interesting exercises. Page 21 (in the chapter "Necessary Mathematics") has an exercise on sketching and comparing graphs for various mathematical functions. I thought I'd have a go at it with Python and Matplotlib (a Python library for graphs).
Using a combination of range and map (which applies a function to every item of an iterable), keeps the code fairly succinct:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import math_functions as mf
functions=[mf.f,mf.g,mf.h,mf.j,mf.m,mf.n]
figure=plt.figure()
ax=figure.add_subplot(111)
for i in functions:
plt.plot(range(5), map(i,range(1,6)), 'o-', label=i.__name__)
print i.__name__,map(i,range(1,6))
plt.legend(loc='upper left')
plt.ylabel('Y')
plt.xlabel('X')
ax.set_title("Excercises 2.1")
plt.show()
Image output:
posted at: 00:00 | path: /python | permanent link to this entry