Thursday, February 10, 2011

A plot of the quadratic in Python


I have another simple matplotlib example, based on the parabola post from the other day (here). The conclusion from that post was that any function:


y(x) = ax2 + bx + c


can be manipulated to the form:


y - y0 = a(x - x0)2


That is, the parabola is just y = a(x)2 translated to have a different vertex. I didn't do a systematic examination or anything, but here is one example in Python.

The function quadratic takes arguments a, b, and c and returns the vertex (x0, y0) as well as a numpy array containing x such that |x - x0| <= 4, and a second one containing f(x) for each value of x.

We plot two sets of three parabolas, each set has one for each of a = 1, 2 and 3. One set is at the origin (cyan, blue and purple). The second set (magenta, salmon and red) has c = 3 and:


a = 1;  b = 2
a = 2; b = 4
a = 3; b = 6


Since x0 = -b/2a is the same for each parabola in the second set, they all have the same axis of symmetry. The only difference (besides the shape parameter a) is y0, which can be calculated either from plugging a, b, c and x0 into the standard form, or by using the fact that


y0 = b2/4a - b2/2a + c
= -b2/4a + c


Using the second method, I get:


a = 1;  b = 2;  y0 = -1 + 3 = 2
a = 2; b = 4; y0 = -2 + 3 = 1
a = 3; b = 6; y0 = -3 + 3 = 0


We ought to be able to solve for b and c to put the parabola anywhere on the x,y-plane..

UPDATE:


x0 = -b/2a
b = -2ax0

y0 = -b2/4a + c
c = y0 + b2/4a
= y0 + ax02

check:

y = ax2 + bx + c
= ax2 -2ax0x + y0 + ax02
y - y0 = a(x2 -2x0x + x02)
= a(x - x0)2




from __future__ import division
import matplotlib.pyplot as plt
import numpy as np

def func(a,b,c):
@np.vectorize
def f(x):
return a*x**2 + b*x + c
return f

def quadratic(a,b=0,c=0):
f = func(a,b,c)
x0 = -b/(2*a)
X = np.arange(x0-4,x0+4,0.01)
return x0,f(x0),X,f(X)

blues = ['cyan', 'blue', 'purple']
reds = ['magenta', 'salmon', 'red']

for i,(a,b) in enumerate(zip((1,2,3),(2,4,6))):
x0,y0,X,Y = quadratic(a,b,c=3)
c = reds[i]
plt.scatter(X,Y,s=2,color=c)
plt.scatter(x0,y0,s=100,color=c)
print 'x0',x0,'y0',y0

x0,y0,X,Y = quadratic(a)
c = blues[i]
plt.scatter(X,Y,s=2,color=c)
plt.scatter(x0,y0,s=100,color='k')

ax = plt.axes()
ax.set_xlim(-3,3)
ax.set_ylim(-1,5)
plt.grid(True)
plt.savefig('example.png')

No comments: