More pythonic circle?

Michael Tobis mtobis at gmail.com
Sun Apr 9 01:28:49 EDT 2006


Proving yet again that it's possible to write Fortran in any language.

You aren't getting any benefit from numpy or python here.  Are you
aiming for speed or legibility?

Also, with this code, you are using radius for the dimensions of the
enclosing box, as well as the radius of the circle, so it's guaranteed
to not to actually produce a whole circle. Recall what python does with
negative indices!

I'll bet this does the trick for you and runs faster than what you've
got

def circle(rad = 5,max_x = 20, max_y = 20,cx = 10, cy= 10, value=255):
   radsq = rad * rad
   return numpy.array([[((x - cx) ** 2 + (y - cy) ** 2 < radsq) and
value or 0  for x in range(max_x)] for y in range(max_y)],'u')

I think the pure numpy solution should be something like (untested)

def circle(rad = 5,max_x = 20, max_y = 20,cx = 10, cy= 10, value=255):
   def sqdist(x,y):
      return (x - cx) * (x - cx) + (y - cy) * (y - cy)
   distarray = numpy.fromfunction(sqdist,(max_y,max_x))
   return
numpy.asarray(numpy.choose(greater(distarray,rad*rad),(0,value),'u')

Neither approach will get you the eightfold speedup that the messy code
was aimed at, but in practice they will spend less time at the
interpreter level and will likely run faster.

mt




More information about the Python-list mailing list