在Python中设置一个分形
时间: 2024-12-29 20:30:47 浏览: 18
在Python中创建分形图形通常使用递归算法,最著名的例子就是Mandelbrot集和Julia集。以下是创建一个基本的Mandelbrot集合的简单示例:
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
def mandelbrot(c, max_iter=256):
z = c
for n in range(max_iter):
if abs(z) > 2:
return n
z = z*z + c
return max_iter
# 定义图像的区域
x_min, x_max = -2.0, 1.0
y_min, y_max = -1.5, 1.5
image_width = 800
image_height = 800
# 创建像素点的网格
X, Y = np.meshgrid(np.linspace(x_min, x_max, image_width), np.linspace(y_min, y_max, image_height))
# 将复数坐标转换为Mandelbrot迭代
Z = X + 1j * Y
# 计算每个点的迭代次数,并将结果映射到颜色上
cmap = colors.ListedColormap(['blue', 'green', 'yellow', 'red'])
image = cmap(mandelbrot(Z))
plt.imshow(image, extent=(x_min, x_max, y_min, y_max))
plt.title('Mandelbrot Set')
plt.show()
这个代码生成了一个Mandelbrot集的图像,颜色深浅表示迭代次数,越深的颜色代表在给定的迭代次数内未逃离原点的复数更多。
相关推荐

















