﻿ python绘制超炫酷动态Julia集示例 - 鸿网互联

# python绘制超炫酷动态Julia集示例

• 前言
• Mandelbrot集
• 无限缩放
• Julia集

## Mandelbrot集

# 这些代码会在后面的程序中反复调用，不再说明
import numpy as np
import time
import matplotlib.pyplot as plt
import cupy as cp

#生成z坐标 x0,y0 为起始点， nx,ny为点数， delta为点距
def genZ(x0, y0, nx, ny, delta):
real, img = cp.indices([nx,ny])*delta
real += x0
img += y0
return real.T+img.T*1j

#获取Julia集，n为迭代次数，m为判定发散点，大于1即可
def getJulia(z,c,n,m=2):
t = time.time()
z,out = z*1, cp.abs(z)
c = cp.zeros_like(z)+c
for i in range(n):
absz = cp.abs(z)
z[absz>m]=0		#对开始发散的点置零
c[absz>m]=0
out[absz>m]=i	#记录发散点的发散速度
z = z*z + c
print("time:",time.time()-t)
return out

z1 = genZ(-2,-1.5,1000,1000,0.003)
mBrot = getJulia(z1,z1,50)
plt.imshow(mBrot.get(), cmap=plt.cm.jet)
plt.show()


from matplotlib import animation

fig = plt.figure()
ax = plt.subplot()

def getJulias(z,c,n,m=2):
z,out = z*1, cp.abs(z)
c = cp.zeros_like(z)+c
J = []
for i in range(n):
z = z*z + c
absz = cp.abs(z)
z[absz>m]=0		#对开始发散的点置零
c[absz>m]=0
out[absz>m]=i	#记录发散点的发散速度
im = ax.imshow(out.get(),cmap=plt.cm.jet, animated=True)
ax.set_axis_off()
J.append([im])
return J

N = 75     #迭代次数
z1 = genZ(-2,-1.5,1000,1000,0.003)
J = getJulias(z1,z1,N)

ani = animation.ArtistAnimation(fig, J, interval=50, blit=True,repeat_delay=1000)
plt.show()
ani.save('julias.gif',writer='imagemagick')


## 无限缩放

Mandelbrot集的分形特征意味着我们所生成的图片可以无限放大，但是受到栅格化尺寸的影响，手动的放大并不会更改其真实尺寸，

from matplotlib import animation

# 生成z坐标 xy=np.array([xc,yc]) 为起始点，
# nxy=np.array([nx,ny])为点数， delta为点距
def genZbyCenter(xy,nxy,delta):
x0, y0 = xy-np.array(nxy)*delta/2
return genZ(x0,y0,*nxy,delta)

mBrots = []
xy = [-0.75,-0.2]
nxy = [1000,1000]
delta0 = 0.003  #初始宽度

fig = plt.figure()
ax = plt.subplot()

for n in range(50):
z1 = genZbyCenter(xy,nxy,1.1**(-n)*delta0)
out = getJulia(z1,z1,40)
im = ax.imshow(out.get(),cmap=plt.cm.jet, animated=True)
ax.set_axis_off()
mBrots.append([im])

ani = animation.ArtistAnimation(fig, mBrots, interval=50, blit=True)
plt.show()
ani.save('zoom.gif',writer='imagemagick')


## Julia集

y = x y=x y=x

z1 = genZ(-2,-1.5,1000,1000,0.003)

fig = plt.figure()
ax = plt.subplot()

mBrots = []
for x in np.arange(0.5,1,0.01):
c = x + x*1j
out = getJulia(z1,c,40)
im = ax.imshow(out.get(),cmap=plt.cm.jet, animated=True)
ax.set_axis_off()
mBrots.append([im])

ani = animation.ArtistAnimation(fig, mBrots, interval=50)
plt.show()
ani.save('julia.gif',writer='imagemagick')


<