pythonnumpymandelbrot

Zooming in on Mandelbrot set


I have the following code:


# MANDELBROT

a = np.arange(-2, 2, 0.01)
b = np.arange(-2, 2, 0.01)
M_new = new_matrix(a, b)
plt.imshow(M_new, cmap='gray', extent=(-2, 2, -2, 2))
plt.show()

## ZOOMING

a_2 = np.arange(0.1, 0.5, 0.01)
b_2 = np.arange(0.1, 0.5, 0.01)
M_new_2 = new_matrix(a_2, b_2)
plt.imshow(M_new_2, cmap='gray', extent=(0.1, 0.5, 0.1, 0.5))
plt.show()

When I plot the Mandelbrot it looks fine, but what I want to do next is to zoom in on specific part of the set (between 0,1 - 0,5 both x and y-axis). I do not know if the second part of the code is incorrect or maybe I am thinking in a wrong way.


Solution

  • I did several changes to you code, mainly respecting the shape of the input arrays.

    import numpy as np
    from matplotlib import pyplot as plt
    
    def mandelbrot(c: complex):
        m = 0
        z = complex(0, 0)
        for i in range(0, 100):
            z = z*z+c
            m += 1
            if np.abs(z) > 2:
                return False
        return True
    
    def new_matrix(a_1, b_1):
        M = np.zeros((a_1.shape[0], b_1.shape[0]))
        for i, number1 in enumerate(a_1):
            for j, number2 in enumerate(b_1):
                M[i, j] = mandelbrot(complex(number1, number2))
        return M
    
    # MANDELBROT
    
    a = np.arange(-2, 2, 0.01)
    b = np.arange(-2, 2, 0.01)
    
    M_new = new_matrix(a, b)
    
    plt.imshow(M_new, cmap='gray', extent=(-2, 2, -2, 2))
    plt.show()
    
    ## ZOOMING
    
    a_2 = np.arange(0.1, 0.5, 0.01)
    b_2 = np.arange(0.1, 0.5, 0.01)
    
    M_new_2 = new_matrix(a_2, b_2)
    plt.imshow(M_new_2, cmap='gray', extent=(0.1, 0.5, 0.1, 0.5))
    plt.show()
    

    Check in particular the definition of the matrix M (using the shape of the input arguments, and the enumerate construct in the for loops.

    It could without doubt be optimized further, but at least this makes it working. You might want to use linspace in your application, to have better control over the number of points generated.