## 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)

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!

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

2. Thanks! Figured it out :)

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?

4. Did you find a way to plot only the boundaries of the unit circle? Could you please tell how that could be done?

5. Hi Saurav, just like this

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

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))

7. This comment has been removed by the author.

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

2. how to do that in coding?