and e

Mathematics and other neat things

As you can probably tell by the little picture at the top there, I really like Mandelbrot Sets. Consequently I have been trying to write a program to draw some of my own. Unfortunately Mathematica is kind of slow when it comes to number crunching, so I tried to write something in python. With a little help from the pylab examples, I was able to come up with the following.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mplim
import matplotlib.colors as mplcolors
import matplotlib.figure as mplfig

w = 1366
h = 768
xlim = [-2.50, 1.50]

class Mandelbrot(object):
    def __init__(self):
        self.create_image()

    def draw(self, x1, x2, y1, y2, maxiter=20):
        y, x = np.ogrid[y1:y2:h*1j, x1:x2:w*1j]
        c = x + y*1j
        z = c
        divtime = maxiter + np.zeros(z.shape, dtype=int)
        for i in xrange(maxiter):
            z = z*z + c
            diverge = z*np.conj(z) > 4
            div_now = diverge & (divtime == maxiter)
            divtime[div_now] = i
            z[diverge] = 2
        self.mandel = divtime

    def cmap(self):
        self.cdict = {‘red’: ((0.0, 0.2, 0.2), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)),

                          ‘green’: ((0.0, 0.2, 0.2), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)),

                          ‘blue’: ((0.0, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0))}
        self.my_cmap = mplcolors.LinearSegmentedColormap(‘my_colormap’, self.cdict, 256)

    def create_image(self):
        self.draw(xlim[0], xlim[1], -(xlim[1]-xlim[0])/2 * float(h)/w, (xlim[1]-xlim[0])/2 * float(h)/w)
        self.cmap()
        plt.figure(figsize=(14.28, 8), edgecolor=’k’)
        plt.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0, wspace=0.0, hspace=0.0)
        plt.imshow(self.mandel, cmap=self.my_cmap)
        plt.axis(‘off’)
        #plt.savefig(‘filename.png’)
        plt.show()

if __name__ == ‘__main__’:
   
    do = Mandelbrot()

These particular settings create this:

6 months ago