Error in user YAML: (<unknown>): could not find expected ':' while scanning a simple key at line 3 column 1
---
- oeasy Python 0826
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
本教程同步发布在:
个人网站: `https://oeasy.org`
蓝桥云课: `https://www.lanqiao.cn/courses/3584`
GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
Gitee: `https://gitee.com/overmind1980/oeasypython`
---import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
def mandelbrot(c, max_iter):
z = 0
for n in range(max_iter):
if abs(z) > 2:
return n
z = z*z + c
return max_iter
def generate_mandelbrot(width=800, height=800, x_min=-2.0, x_max=1.0, y_min=-1.5, y_max=1.5, max_iter=200):
# 创建复数平面
x = np.linspace(x_min, x_max, width)
y = np.linspace(y_min, y_max, height)
X, Y = np.meshgrid(x, y)
c = X + 1j * Y
# 向量化计算曼德博集合
mandelbrot_vectorized = np.vectorize(mandelbrot)
fractal = mandelbrot_vectorized(c, max_iter)
return fractal
def plot_fractal(fractal, title='Mandelbrot Set', cmap_name='inferno'):
# 创建自定义颜色映射
colors = [(0, 0, 0), (0.2, 0.1, 0.4), (0.8, 0.2, 0.8), (1, 0.5, 0), (1, 1, 0), (1, 1, 1)]
cmap = LinearSegmentedColormap.from_list('custom_cmap', colors, N=256)
# 绘制分形
plt.figure(figsize=(10, 10))
plt.imshow(fractal, cmap=cmap_name if cmap_name != 'custom' else cmap, extent=[-2.0, 1.0, -1.5, 1.5])
plt.colorbar(label='迭代次数')
plt.title(title, fontsize=16)
plt.xlabel('实部', fontsize=12)
plt.ylabel('虚部', fontsize=12)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
# 可调整参数:宽度、高度、最大迭代次数、颜色映射
# 颜色映射选项:'inferno', 'plasma', 'magma', 'cividis', 'custom'
fractal = generate_mandelbrot(width=1000, height=1000, max_iter=200)
plot_fractal(fractal, title='曼德博集合分形', cmap_name='custom')
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。
