我正在尝试使用以下代码来显示曼德布洛特集:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['toolbar'] = 'None'
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 mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
n3 = np.empty((width, height))
for i in range(width):
for j in range(height):
n3[i, j] = mandelbrot(r1[i] + 1j*r2[j], max_iter)
return n3.T
# Settings
xmin, xmax, ymin, ymax = -2.0, 1.0, -1.5, 1.5
width, height = 800, 800
max_iter = 256
# Generate Mandelbrot set
mandelbrot_image = mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter)
# Window
fig = plt.figure(figsize=(5, 5))
fig.canvas.manager.set_window_title('Mandelbrot Set')
ax = fig.add_axes([0, 0, 1, 1]) # Fill the whole window
ax.set_axis_off()
# Show fractal
ax.imshow(mandelbrot_image, extent=(xmin, xmax, ymin, ymax), cmap='hot')
plt.show()
我该如何持续放大分形,而不占用太多资源?我使用的是一台中端笔记本电脑,目前生成分形需要很长时间。在实现缩放功能时,有没有更快的方法来实现呢?
你正在使用Python代码来处理单个NumPy数字。这是最糟糕的方法。如果你使用 Python 数字,速度会快一倍,如下所示
.tolist()
:但最好正确使用 NumPy,例如并行处理所有像素,跟踪仍然具有 abs ≤ 2 的值(及其索引):
现在这花费了我大约 0.17 秒,而不是原来的 6.7 秒。
编辑:
曼德布洛特集逃逸时间算法的实现。请注意,该算法有很多实现和变体,例如,Matplotlib 库中提出的实现与原帖中提出的实现略有不同。本答案改编自 Matplotlib 示例。
在我的计算机上,它保持以下执行时间(仅使用 OP 中的参数进行测试):
快 <- 凯利·邦迪 <- 4x - 卡片 <- 5x - 普罗米修斯 (OP) <- 慢
原文:提高图形性能(另见评论)
matplotlib
通过调整一些matplotlibrc设置可以实现一些性能改进:快速样式:
mplstyle.use('fast')
“ 自动将简化和分块参数设置为合理的设置,以加快绘制大量数据的速度”。如果与其他样式结合使用,请将其放在最后使用,以避免覆盖其他配置。线段简化:
plt.rcParams['path.simplify_threshold'] = 1.0
“控制线段简化的程度”可以使用动画的位图传输技术来实现“类似缩放”的功能。