from multiprocessing import Pool def escapes(cr, ci, it): """ Does iterating z <- z^2 + c escape after it iterations? Pure function. """ zr = 0.0 zi = 0.0 for i in xrange(it): # z <- z^2 + c zr,zi = zr*zr - zi*zi + cr, 2*zr*zi + ci if zr*zr + zi*zi > 4: return True return False def toChar(p): if p: return " " else: return "X" def doRow((xmin,xmax,xstep, ymin,ymax,ystep, iterations, yc)): """ Calculate one row of the output. Pure function. """ y = yc*(ymax-ymin)/ystep + ymin row = [] for xc in xrange(xstep): x = xc*(xmax-xmin)/xstep + xmin row.append( escapes(x, y, iterations) ) return "".join([toChar(p) for p in row]) def mandel(xmin,xmax,xstep, ymin,ymax,ystep, iterations): """ Calculate and print a Mandelbrot set. """ pool = Pool() args = [(xmin,xmax,xstep, ymin,ymax,ystep, iterations, yc) for yc in xrange(ystep)] #rows = pool.map(doRow, args, chunksize=1) rows = map(doRow, args) # serial version print "\n".join(rows) def mandelX(xmin,xmax,xstep, ymin,ymax,ystep, iterations): """ Calculate and print a Mandelbrot set. (Alternate implementation that prints each row as it is calculated.) """ pool = Pool() results = [] for yc in xrange(ystep): res = pool.apply_async(doRow, ((xmin,xmax,xstep, ymin,ymax,ystep, iterations, yc),)) results.append(res) for yc in xrange(ystep): print results[yc].get() if __name__=="__main__": mandel(-2.0, 1.0, 100, -1.0, 1.0, 60, 20000)