Friday, April 29, 2011

Plotting p-norm unit circles with matplotlib

A unit circle is a circle with a radius of one, this concept is different in different vectorial norms. The following script will show the shape of the unit circle using differents p-norm.
import pylab
from numpy import array, linalg, random, sqrt, inf

def plotUnitCircle(p):
 """ plot some 2D vectors with p-norm < 1 """
 for i in range(5000):
  x = array([random.rand()*2-1,random.rand()*2-1])
  if linalg.norm(x,p) < 1:
   pylab.plot(x[0],x[1],'bo')
 pylab.axis([-1.5, 1.5, -1.5, 1.5])
 pylab.show()
And now we can plot the unit circles:
plotUnitCircle(1)
plotUnitCircle(2)
plotUnitCircle(5)
plotUnitCircle(inf)

No comments:

Post a Comment