More pythonic circle?

Pythor pythor at gmail.com
Sun Apr 9 11:56:39 EDT 2006


Michael Tobis wrote:
> Proving yet again that it's possible to write Fortran in any language.
>
Ouch...

> You aren't getting any benefit from numpy or python here.  Are you
> aiming for speed or legibility?
>
Speed will be a necessity, eventually.  I was just really aiming for
something that works, and that I am capable of writing.

> 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'm not sure what you mean here.  It produces an eighth-circle, and
then plots each point in the 8 symmetrical positions on the circle.
Except for the (dx+1) point made above, what piece of the circle is
missing?

> 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')
>
I'll take a look at both of these.  At this point, I can't quite wrap
my head around what you're doing for either one.

> 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