当前位置: 首页 > 科技观察

如何用Python画出各种著名的数学图案

时间:2023-03-15 21:02:27 科技观察

编译组:AileenXuLingxiao用Python绘制著名的数学图片或动画,展现算法在数学中的魅力。Mandelbrot集代码:46行(34sloc)1.01KB'''AfastMandelbrotsetwallpaperrendererreddit讨论:https://www.reddit.com/r/math/comments/2abwyt/smooth_colour_mandelbrot/'''importnumpyasnpfromPILimportImagefromnumbaimportjitMAXITERS=1f00RADIUS,(i):v=np.log2(i+1-np.log2(np.log2(abs(z))))/5ifv<1.0:返回v**4,v**2.5,velse:v=max(0,2-v)返回v,v**1.5,v**3@jitdefiterate(c):z=0jforiinrange(MAXITERS):ifz.real*z.real+z.imag*z.imag>RADIUS:returncolor(z,i)zz=z*z+creturn0,0,0defmain(xmin,xmax,ymin,ymax,width,height):x=np.linspace(xmin,xmax,width)y=np.linspace(ymax,ymin,height)z=x[None,:]+y[:,None]*1jred,green,blue=np.asarray(np.frompyfunc(iterate,1,3)(z)).astype(np.float)img=np.dstack((red,green,blue))Image.fromarray(np.uint8(img*255)).save('mandelbrot.png')if__name__=='__main__':main(-2.1,0.8,-1.16,1.16,1200,960)Domino洗牌算法代码链接:https://github.com/neozhaoliang/pywonderland/tree/master/src/domino是二十面体万花筒代码:53lines(40sloc)1.24KB'''Akaleidoscopepatternwithicosahedralsymmetry.'''importnumpyasnpfromPILimportImagefrommatplotlib.colorsimporthsv_to_rgbdefKlein(z):'''Klein'sj-function'''return1728*(z+1(z**10)*z**5-1))**5/\(-(z**20+1)+228*(z**15-z**5)-494*z**10)**3defRiemannSphere(z):'''将复杂平面映射到黎曼球面立体投影'''t=1+z.real*z.real+z.imag*z.imagreturn2*z.real/t,2*z.imag/t,2/t-1defMobius(z):'''distorttheresultimagebyamobiustransformation'''return(z-20)/(3*z+1j)defmain(imgsize):x=np.linspace(-6,6,imgsize))y=np.linspace(6,-6,imgsize)z=x[None,:]+y[:,None]*1jz=RiemannSphere(Klein(Mobius(Klein(z))))#definecolorsinhsvspaceH=np.sin(z[0]*np.pi)**2S=np.cos(z[1]*np.pi)**2V=abs(np.sin(z[2]*np.pi)*np.cos(z[2]*np.pi))**0.2HSV=np.dstack((H,S,V))#transformtorgbspaceimg=hsv_to_rgb(HSV)Image.fromarray(np.uint8(img*255)).save('kaleidoscope.png')if__name__=='__main__':importtimestart=time.time()main(imgsize=800)end=time.time()print('runtime:{:3f}seconds'.format(end-Newton代分形代码:46行(35sloc)1.05KBImportnumpyasnpimportmatplotlib.pyplotaspltfromnumbaimportjit#definefunctionsmanually,donotusenumpy'spoly1dfunciton!@jit('complex64(complex64=',nopythonTrue)deff(z):#z*z*zisfasterthanz**3returnz*z*z-1@jit('complex64(complex64)',nopython=True)defdf(z):return3*z*z@jit('float64(complex64)',nopython=True)defiterate(z):num=0whileabs(f(z))>1e-4:w=z-f(z)/df(z)num+=np.exp(-1/abs(w-z))z=wreturnnumdefrender(imgsize):x=np.linspace(-1,1,imgsize)y=np.linspace(1,-1,imgsize)z=x[无,:]+y[:,无]*1jimg=np.frompyfunc(iterate,1,1)(z).astype(np.float)fig=plt.figure(figsize=(imgsize/100.0,imgsize/100.0),dpi=100)ax=fig.add_axes([0,0,1,1],aspect=1)ax.axis('off')ax.imshow(img,cmap='hot'))fig.savefig('newton.png')if__name__=='__main__':importtimestart=time.time()render(imgsize=400)end=time.time()print('runtime:{:03f}seconds'.format(end李代数E8的根代码链接:https://github.com/neozhaoliang/pywonderland/blob/master/src/misc/e8.py模块组基础域代码链接:https://github.com/neozhaoliang/pywonderland/blob/master/src/misc/modulargroup.pyPenrose铺贴代码链接:https://github.com/neozhaoliang/pywonderland/blob/master/src/misc/penrose.pyWilson算法代码链接:https://github.com/neozhaoliang/pywonderland/tree/master/src/wilson反应-扩散方程模拟代码链接:https://github.com/neozhaoliang/pywonderland/tree/master/src/grayscott120cellcavity#pylint:disable=unused-import#pylint:disable=undefined-variablefromitertoolsimportcombinations,productimportnumpyasnpfromvaporyimport*classPenrose(object):GRIDS=[np.exp(2j*np.pi*i/5)foriinrange(5)]def__init__(self,num_lines,shift,thin_color,fat_color,**config):self.num_lines=num_linesself.shift=shiftself.thin_color=thin_colorself.fat_color=fat_colorselfself.objs=self.compute_pov_objs(**config)defcompute_pov_objs(self,**config):objects_pool=[]forrhombi,colorinself.tile():p1,p2,p3,p4=rhombipolygon=多边形(5、p1,p2,p3,p4,p1,Texture(Pigment('color',color),config['default']))objects_pool.append(多边形)forp,qinzip(rhombi,[p2,p3,p4,p1]):cylinder=Cylinder(p,q,config['edge_thickness'],config['edge_texture'])objects_pool.append(cylinder)forpointinrhombi:x,y=pointsphere=Sphere((x,y,0),config['vertex_size'],config['vertex_texture'])objects_pool.append(sphere)returnObject(Union(*objects_pool))defrhombus(self,r,s,kr,ks):if(s-r)**2%5==1:color=self.thin_colorelse:color=self.fat_colorpoint=(Penrose.GRIDS[r]*(ks-self.shift[s])-Penrose.GRIDS[s]*(kr-self.shift[r]))*1j/Penrose.GRIDS[s-r].imagindex=[np.ceil((point/grid).real+shift)forgrid,shiftinzip(Penrose.GRIDS,self.shift)]vertices=[]forindex[r],index[s]in[(kr,ks),(kr+1,ks),(kr+1,ks+1),(kr,ks+1)]:vertices.append(np.dot(index,Penrose.GRIDS))vertices_real=[(z.real,z.imag)forzinvertices]returnvertices_real,colordeftile(self):forr,sincombinations(范围(5),2):forkr,ksinproduct(范围(-self.num_lines,self.num_lines+1),repeat=2):yieldself.rhombus(r,s,kr,ks)defput_objs(self,*args):返回对象(self.objs,*args)原文:https://github.com/neozhaoliang/pywonderland/blob/master/README.md【本文为专栏组织大数据文摘原创翻译,微信公众号》大数据文摘(id:BigDataDigest)》】点此查看作者更多好文