首页 > 解决方案 > 使用 matplotlib.pyplot 和 numpy 在 python 中显示 Mandelbrot 集

问题描述

我正在尝试获取 Mandelbrot 集的图,并且无法绘制预期的图。

据我了解,Mandelbrot 集由值 c 组成,如果通过以下等式 z = z**2 + c 迭代,它们将收敛。我使用了 z = 0 的初始值。

最初,我得到的是一条直线。我在网上寻找解决方案,看看我哪里出错了。特别是使用以下链接,我试图改进我的代码:

https://scipy-lectures.org/intro/numpy/auto_examples/plot_mandelbrot.html

这是我改进的代码。我真的不明白使用 np.newaxis 的原因以及为什么要绘制收敛的最终 z 值。我是否误解了 Mandelbrot 集的定义?

# initial values 
loop = 50 # number of interations
div = 600 # divisions
# all possible values of c
c = np.linspace(-2,2,div)[:,np.newaxis] + 1j*np.linspace(-2,2,div)[np.newaxis,:] 
z = 0 
for n in range(0,loop):
      z = z**2 + c

plt.rcParams['figure.figsize'] = [12, 7.5]
z = z[abs(z) < 2] # removing z values that diverge 
plt.scatter(z.real, z.imag, color = "black" ) # plotting points
plt.xlabel("Real")
plt.ylabel("i (imaginary)")
plt.xlim(-2,2)
plt.ylim(-1.5,1.5)
plt.savefig("plot.png")
plt.show()

得到了下面的图像,它看起来比我目前得到的任何东西都更接近曼德布洛特集。但它看起来更像是一只海星,周围散布着点。 图片

作为参考,这是我改进前的初始代码:

# initial values 
loop = 50
div = 50
clist = np.linspace(-2,2,div) + 1j*np.linspace(-1.5,1.5,div) # range of c values 
all_results = []

for c in clist: # for each value of c
    z = 0 # starting point
    for a in range(0,loop): 
        negative = 0 # unstable

        z = z**2 + c 

        if np.abs(z) > 2: 
            negative +=1
        if negative > 2: 
            break

    if negative == 0:
        all_results.append([c,"blue"]) #converging
    else:
        all_results.append([c,"black"]) # not converging

标签: pythonnumpymatplotlibplotmandelbrot

解决方案


或者,对问题中的代码进行另一个小的更改,可以使用 的值z来为绘图着色。可以存储n级数的绝对值变得大于 2(意味着它发散)的值,并用它为 Mandelbrot 集之外的点着色:

import pylab as plt
import numpy as np
# initial values 
loop = 50 # number of interations
div = 600 # divisions
# all possible values of c
c = np.linspace(-2,2,div)[:,np.newaxis] + 1j*np.linspace(-2,2,div)[np.newaxis,:] 
# array of ones of same dimensions as c
ones = np.ones(np.shape(c), np.int)
# Array that will hold colors for plot, initial value set here will be
# the color of the points in the mandelbrot set, i.e. where the series
# converges.
# For the code below to work, this initial value must at least be 'loop'.
# Here it is loop + 5
color = ones * loop + 5
z = 0
for n in range(0,loop):
      z = z**2 + c
      diverged = np.abs(z)>2
      # Store value of n at which series was detected to diverge.
      # The later the series is detected to diverge, the higher
      # the 'color' value.
      color[diverged] = np.minimum(color[diverged], ones[diverged]*n)

plt.rcParams['figure.figsize'] = [12, 7.5]
# contour plot with real and imaginary parts of c as axes
# and colored according to 'color'
plt.contourf(c.real, c.imag, color)
plt.xlabel("Real($c$)")
plt.ylabel("Imag($c$)")
plt.xlim(-2,2)
plt.ylim(-1.5,1.5)
plt.savefig("plot.png")
plt.show()

彩色曼德布洛图。


推荐阅读