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)

10 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. Thanks! Figured it out :)

      Delete
    3. 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
    4. Did you find a way to plot only the boundaries of the unit circle? Could you please tell how that could be done?

      Delete
    5. Hi Saurav, just like this

      t = np.linspace(0, 2*np.pi, 10)
      plt.plot(sin(t), cos(t))

      Delete
    6. JustGlowing: I didn't get how the following will produce only boundary line. I mean no need to fill the circle with colors just the boundary will be enough
      t = np.linspace(0, 2*np.pi, 10)
      plt.plot(sin(t), cos(t))

      Delete
    7. This comment has been removed by the author.

      Delete
    8. hi Hasan, have a look at this example in matlab: https://www.wire.tu-bs.de/lehre/ss18/UQ/linear_algebra/linear_algebra.html

      Delete

Note: Only a member of this blog may post a comment.