问题描述
# MANDELbroT
a = np.arange(-2,2,0.01)
b = np.arange(-2,0.01)
M_new = new_matrix(a,b)
plt.imshow(M_new,cmap='gray',extent=(-2,-2,2))
plt.show()
## ZOOMING
a_2 = np.arange(0.1,0.5,0.01)
b_2 = np.arange(0.1,0.01)
M_new_2 = new_matrix(a_2,b_2)
plt.imshow(M_new_2,extent=(0.1,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,0.01)
M_new = new_matrix(a,b)
plt.imshow(M_new,cmap='gray',extent=(-2,-2,2))
plt.show()
## ZOOMING
a_2 = np.arange(0.1,0.5,0.01)
b_2 = np.arange(0.1,0.01)
M_new_2 = new_matrix(a_2,b_2)
plt.imshow(M_new_2,extent=(0.1,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,number2))
return M
def show(x1,y1,x2,y2):
a = np.linspace(x1,SIZE)
b = np.linspace(x2,y2,SIZE)
M = new_matrix(a,b)
plt.imshow(M,extent=(x1,y2))
plt.show()
show(-2,2)
show(.1,.5,.1,.5)
输出: