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)

5 comments:

  1. Thanks, that's helpful! Question - could you also specify how to plot the boundaries for different p's like p=1,p=2,p=10 etc.? So not create dots but boundaries (for example lines for given value of p. That would help me a lot, thanks!

    ReplyDelete
    Replies
    1. Hi, you have to find x such that the norm is 1. I'm pretty sure you can find an analytical solution.

      Delete
    2. the random.rand function gives a right-open interval, so never obtains the boundary. How can we close this interval? Or just plot where norm = 1?

      Delete