放大 Mandelbrot 集

Zooming in on Mandelbrot set

我有以下代码:


# 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()

当我绘制 Mandelbrot 时,它看起来不错,但我接下来要做的是放大集合的特定部分(x 轴和 y 轴都在 0,1 - 0,5 之间)。不知道第二部分的代码有没有错误,或者我的思路不对。

我对你的代码做了几处修改,主要是关于输入数组的形状。

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()

特别检查矩阵 M 的定义(使用输入参数的形状和 for 循环中的枚举构造。

毫无疑问,它可以进一步优化,但至少这让它可以正常工作。您可能希望在您的应用程序中使用 linspace,以便更好地控制生成的点数。

确保生成所需的数组大小 (401x401) 并在矩阵中正确绘制这些点。当您放大时,您不希望在范围之间增加 0.01,而是恰好 401 步。为此使用 np.linspace。还创建一个用于显示矩阵的通用函数有助于使数学一致:

import numpy as np
from matplotlib import pyplot as plt

SIZE = 401

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

def new_matrix(a_1, b_1):
    M = np.zeros(SIZE*SIZE).reshape(SIZE, SIZE)
    for i,number1 in enumerate(a_1):
        for j,number2 in enumerate(b_1):
            M[i,j] = mandelbrot(complex(number1, number2))
    return M

def show(x1,y1,x2,y2):
    a = np.linspace(x1, y1, SIZE)
    b = np.linspace(x2, y2, SIZE)
    M = new_matrix(a, b)
    plt.imshow(M, cmap='gray', extent=(x1, y1, x2, y2))
    plt.show()

show(-2,2,-2,2)
show(.1,.5,.1,.5)

输出: