@ibilis
2017-01-08T12:29:33.000000Z
字数 3802
阅读 598
计算物理
# -*- coding: utf-8 -*-import numpy as npimport pylab as plimport timefrom matplotlib import cmdef iter_point(c):z = cfor i in xrange(1, 100): # 最多迭代100次if abs(z)>2: break # 半径大于2则认为逃逸z = z*z+creturn i # 返回迭代次数def draw_mandelbrot(cx, cy, d):"""绘制点(cx, cy)附近正负d的范围的Mandelbrot"""x0, x1, y0, y1 = cx-d, cx+d, cy-d, cy+dy, x = np.ogrid[y0:y1:200j, x0:x1:200j]c = x + y*1jstart = time.clock()mandelbrot = np.frompyfunc(iter_point,1,1)(c).astype(np.float)print "time=",time.clock() - startpl.imshow(mandelbrot, cmap=cm.Blues_r, extent=[x0,x1,y0,y1])pl.gca().set_axis_off()x,y = 0.27322626, 0.595153338pl.subplot(231)draw_mandelbrot(-0.5,0,1.5)for i in range(2,7):pl.subplot(230+i)draw_mandelbrot(x, y, 0.2**(i-1))pl.subplots_adjust(0.2, 0, 0.98, 1, 0.2, 0)pl.show()
# -*- coding: utf-8 -*-import numpy as npimport matplotlib.pyplot as plimport time# 蕨类植物叶子的迭代函数和其概率值eq1 = np.array([[0,0,0],[0,0.16,0]])p1 = 0.01eq2 = np.array([[0.2,-0.26,0],[0.23,0.22,1.6]])p2 = 0.07eq3 = np.array([[-0.05, 0.28, 0],[0.26,0.24,0.44]])p3 = 0.07eq4 = np.array([[0.85, 0.04, 0],[-0.04, 0.85, 1.6]])p4 = 0.85def ifs(p, eq, init, n):"""进行函数迭代p: 每个函数的选择概率列表eq: 迭代函数列表init: 迭代初始点n: 迭代次数返回值: 每次迭代所得的X坐标数组, Y坐标数组, 计算所用的函数下标"""# 迭代向量的初始化pos = np.ones(3, dtype=np.float)pos[:2] = init# 通过函数概率,计算函数的选择序列p = np.add.accumulate(p)rands = np.random.rand(n)select = np.ones(n, dtype=np.int)*(n-1)for i, x in enumerate(p[::-1]):select[rands<x] = len(p)-i-1# 结果的初始化result = np.zeros((n,2), dtype=np.float)c = np.zeros(n, dtype=np.float)for i in xrange(n):eqidx = select[i] # 所选的函数下标tmp = np.dot(eq[eqidx], pos) # 进行迭代pos[:2] = tmp # 更新迭代向量# 保存结果result[i] = tmpc[i] = eqidxreturn result[:,0], result[:, 1], cstart = time.clock()x, y, c = ifs([p1,p2,p3,p4],[eq1,eq2,eq3,eq4], [0,0], 100000)print time.clock() - startpl.figure(figsize=(6,6))pl.subplot(121)pl.scatter(x, y, s=1, c="g", marker="s", linewidths=0)pl.axis("equal")pl.axis("off")pl.subplot(122)pl.scatter(x, y, s=2,c = c, marker="s", linewidths=0)pl.axis("equal")pl.axis("off")pl.subplots_adjust(left=0,right=1,bottom=0,top=1,wspace=0,hspace=0)pl.gcf().patch.set_facecolor("white")pl.show()
# -*- coding: utf-8 -*-#L-System(Lindenmayer system)是一种用字符串替代产生分形图形的算法from math import sin, cos, piimport matplotlib.pyplot as plfrom matplotlib import collectionsclass L_System(object):def __init__(self, rule):info = rule['S']for i in range(rule['iter']):ninfo = []for c in info:if c in rule:ninfo.append(rule[c])else:ninfo.append(c)info = "".join(ninfo)self.rule = ruleself.info = infodef get_lines(self):d = self.rule['direct']a = self.rule['angle']p = (0.0, 0.0)l = 1.0lines = []stack = []for c in self.info:if c in "Ff":r = d * pi / 180t = p[0] + l*cos(r), p[1] + l*sin(r)lines.append(((p[0], p[1]), (t[0], t[1])))p = telif c == "+":d += aelif c == "-":d -= aelif c == "[":stack.append((p,d))elif c == "]":p, d = stack[-1]del stack[-1]return linesrules = [{"X":"F-[[X]+X]+F[+FX]-X", "F":"FF", "S":"X","direct":-45,"angle":25,"iter":6,"title":"Plant"},]def draw(ax, rule, iter=None):if iter!=None:rule["iter"] = iterlines = L_System(rule).get_lines()linecollections = collections.LineCollection(lines)ax.add_collection(linecollections, autolim=True)ax.axis("equal")ax.set_axis_off()ax.set_xlim(ax.dataLim.xmin, ax.dataLim.xmax,'g')ax.invert_yaxis()fig = pl.figure(figsize=(7,4.5))fig.patch.set_facecolor("w")for i in xrange(1):ax = fig.add_subplot(231+i)draw(ax, rules[0],)fig.subplots_adjust(left=0,right=2,bottom=0,top=2,wspace=0,hspace=0)pl.show()
import numpy as npimport pylab as pyfrom numpy.random import normalfrom mayavi import mlabdef hill2d(n,d):size=2**n+1scale=1.0a=np.zeros((size,size))for i in xrange(n,0,-1):s=2**(i-1)s2=s*2tmp=a[::s2,::s2]tmp1=(tmp[1:,:]+tmp[:-1,:]*0.5)tmp2=(tmp[:,1:]+tmp[:,:-1]*0.5)tmp3=(tmp1[:,1:]+tmp1[:,:-1]*0.5)a[s::s2,::s2]=tmp1+normal(0,scale,tmp1.shape)a[::s2,s::s2]=tmp2+normal(0,scale,tmp2.shape)a[s::s2,s::s2]=tmp3+normal(0,scale,tmp3.shape)scale *=dreturn aif __name__=='__main__':from mayavi import mlabfrom scipy.ndimage.filters import convolvea=hill2d(8,0.5)a/=np.ptp(a)/(0.5*2**8)a=convolve(a,np.ones((3,3))/9)mlab.surf(a)mlab.show()