使用Python的matplotlib繪製lozi混沌對映吸引子
使用Python的matplotlib繪製lozi混沌對映吸引子程式碼。
Python 3.6.7和matplotlib、numpy等庫,安裝不全的,請自行安裝一下。
Linux系統:Ubuntu 18.04.2
程式碼:
# -*- coding: utf-8 -*- #需要安裝matplotlib、numpy等庫才能執行 import numpy as np import pylab as pl import time from matplotlib import cm def iter_point2(x,y): #初始化公式的引數,需要改的話,可以改引數 a = 1 b = 1.75 iter = 0 #初始化迭代次數 for i in range(1, 10): iter = i dist = (x*x + y*y)#計算摸長,看是否超過最大限度 dist *= dist #print "dist:" + str(dist) ifdist > 200:#如果超出了最大長度,就跳出迴圈,返回這個迭代次數 break #臨時儲存一下x和y tempx = x tempy = y #這裡是公式 X = a-b|x| + y ; Y = 0.3x; x = a - b*abs(tempx) + tempy y = 0.3*tempx return iter #繪製圖形時,以cx,xy為中心,距離為d def draw_lozi(cx, cy, d): size = 400 x0, x1, y0, y1 = cx-d, cx+d, cy-d, cy+d y, x = np.ogrid[y1:y0:size*1j, x0:x1:size*1j] #使用範圍生成陣列,後面用這個進行迭代 c = x + y*1j x.shape = -1 #轉化成線性陣列 y.shape = -1 start = time.clock() lozi = np.ones(c.shape) #遍歷每一個點,計算迭代次數,賦值給陣列lozi for j in range(0,size): for i in range(0,size): lozi[j][i] = iter_point2(x[i],y[j]) pass print ("time="),time.clock() - start #使用陣列lozi,繪圖, 使用藍色調色盤,顯示到圖上的座標範圍是x0,x1,y0,y1 pl.imshow(lozi, cmap=cm.Blues_r, extent=[x0,x1,y0,y1]) #不顯示橫縱座標 pl.gca().set_axis_off() #重新整理畫布 pl.show() #滑鼠點選觸發執行的函式 def on_press(event): global g_size print (event) print (dir(event)) newx = event.xdata newy = event.ydata print (newx) print (newy) #不合理的滑鼠點選,直接返回,不繪製 if newx == None or newy == Noneor event.dblclick == True: return None #不合理的滑鼠點選,直接返回,不繪製 if event.button == 1:#button ==1 代表滑鼠左鍵按下, 是放大影象 g_size /= 2 elif event.button == 3: #button == 3 代表滑鼠右鍵按下, 是縮小影象 g_size *= 2 else: return None print (g_size) draw_lozi(newx,newy,g_size) fig, ax = pl.subplots(1) g_size = 4.5 #註冊滑鼠事件 fig.canvas.mpl_connect('button_press_event', on_press) #初始繪製一個圖 draw_lozi(0,0,g_size)
執行如下圖:
Henon對映的混沌吸引子
import matplotlib.pyplot as plt listx=[] listy=[] def Henon(x,y,n): for i in range(n): x1 = 1 - 1.4 * x ** 2 + y y1 = 0.3 * x x = x1 y = y1 listx.append(x) listy.append(y) if __name__ == '__main__': Henon(0.13245678,0.13246789,1000) plt.plot(listx, listy) plt.show()
執行效果如下:
Lorenz吸引子
# -*- coding: utf-8 -*- "Lorenz's strange attractor" import matplotlib as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt xs, ys, zs = [], [], [] def mkPoints(): a, b, c = 10.0, 28.0, 8.0 / 3.0 h = 0.01 x0, y0, z0 = 0.1, 0, 0 for i in range(10000): x1 = x0 + h * a * (y0 - x0) y1 = y0 + h * (x0 * (b - z0) - y0) z1 = z0 + h * (x0 * y0 - c * z0) x0, y0, z0 = x1, y1, z1 xs.append(x0) ys.append(y0) zs.append(z0) if __name__ == "__main__": # 畫3D的 fig = plt.figure() ax = Axes3D(fig) mkPoints() ax.plot(xs, ys, zs, label="Lorenz's strange attractor") ax.legend() plt.show() # 畫2D的 # mkPoints() # plt.plot(zs, ys) # plt.show()
執行效果如下:
更多Python相關資訊見 Python 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=17
Linux公社的RSS地址 : https://www.linuxidc.com/rssFeed.aspx
本文永久更新連結地址: https://www.linuxidc.com/Linux/2019-05/158413.htm