pythonnumpymatplotlibmandelbrot

Can't zoom in on a mandelbrot set with matplotlib, instead it just cuts off the part I try to zoom


My code is as follows:

import numpy as np
import matplotlib.pyplot as plt

def mandelbrot(c):
    z = complex(0, 0)
    for i in range(0, 100):
        z = z*z+c
        if abs(z) > 2:
            return(i)
    return 100

M = np.zeros([401, 401])
a = np.linspace(-2, 2, 401)
b = np.linspace(-2, 2, 401)

for x in a:
    for y in b:
        M[round((x+2)*100),  round((y+2)*100)] = mandelbrot(complex(x, y))


plt.imshow(M, cmap='jet', extent=(-2, -2, 2, 2))
plt.show()

This works perfectly. The next taxt was to change a and b so that it zooms in on a certain part of the set. I tried changing a and b such that: a = np.linspace(-0.5, 0.5, 401) b = np.linspace(-0.5, 0.5, 401)

And also changing extent such that extent=(amin, amax, bmin, bmax).

These are the results:

Original

Original

Zoom:

Zoom

AS you can see, it doesn't zoom in on that part and instead it just cuts off a part of it and displays only that. This is where I'm stuck as I can't find a way to actually make it zoom. Any suggestions?


Solution

  • You are using the values of your arrays a and b as the indices of the matrix M. What you want is M[x,y] = mandelbrot(a[x] + i*b[y]):

    import numpy as np
    import matplotlib.pyplot as plt
    
    def mandelbrot(c):
        z = complex(0, 0)
        for i in range(0, 100):
            z = z*z+c
            if abs(z) > 2:
                return(i)
        return 100
    
    numpts = 401
    xymin = -.5
    xymax = .5
    
    M = np.zeros([numpts, numpts])
    
    a = np.linspace(xymin, xymax, numpts)
    b = np.linspace(xymin, xymax, numpts)
    
    for x in range(numpts):
        for y in range(numpts):
            M[x, y] = mandelbrot(complex(a[x], b[y]))
    
    
    plt.imshow(M, cmap='jet', extent=(xymin, xymax, xymin, xymax))
    plt.show()
    

    Which gives you the correct result.