Python 绘制 Mandelbrot 集代码示例
以下是一个简单的绘制 Mandelbrot 集的 Python 代码:
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(c, max_iter):
z = 0
n = 0
while abs(z) <= 2 and n < max_iter:
z = z*z + c
n += 1
if n == max_iter:
return 0
else:
return n
def mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter):
x = np.linspace(xmin, xmax, width)
y = np.linspace(ymin, ymax, height)
pixels = np.zeros((height, width))
for i in range(height):
for j in range(width):
pixels[i,j] = mandelbrot(x[j] + 1j*y[i], max_iter)
return (x,y,pixels)
xmin, xmax, ymin, ymax = -2, 1, -1.5, 1.5
width, height = 500, 500
max_iter = 1000
x, y, pixels = mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter)
plt.figure(figsize=(10,10))
plt.imshow(pixels.T, cmap='hot', extent=[xmin, xmax, ymin, ymax])
plt.xlabel('Real')
plt.ylabel('Imaginary')
plt.show()
这个代码使用了 NumPy 和 Matplotlib 库。函数 mandelbrot(c, max_iter) 计算给定复数 c 对应的 Mandelbrot 集上的迭代次数,max_iter 为最大迭代次数。函数 mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter) 生成给定范围和分辨率的 Mandelbrot 集,并返回网格中每个点的迭代次数。最后,代码使用 Matplotlib 绘制了 Mandelbrot 集的图像。
原文地址: https://www.cveoy.top/t/topic/oRp9 著作权归作者所有。请勿转载和采集!