原标题:如何用Python画各种著名数学图案 | 附图+代码

用Python绘制著名的数学图片或动画,展示数学中的算法魅力。

Mandelbrot 集

代码:46 lines (34 sloc) 1.01 KB

'''

A fast Mandelbrot set wallpaper renderer

reddit discussion: https://www.reddit.com/r/math/comments/2abwyt/smooth_colour_mandelbrot/

'''

importnumpy asnp

fromPILimportImage

fromnumba importjit

MAXITERS=200

RADIUS=100

@jit

defcolor(z, i):

v =np.log2(i +1-np.log2(np.log2(abs(z)))) /5

ifv <1.0:

returnv**4, v**2.5, v

else:

v =max(0, 2-v)

returnv, v**1.5, v**3

@jit

defiterate(c):

z =0j

fori inrange(MAXITERS):

ifz.real*z.real +z.imag*z.imag >RADIUS:

returncolor(z, i)

z =z*z +c

return0, 0,0

defmain(xmin, xmax, ymin, ymax, width, height):

x =np.linspace(xmin, xmax, width)

y =np.linspace(ymax, ymin, height)

z =x[None, :] +y[:, None]*1j

red, 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)

多米诺洗牌算法

代码链接:https://github.com/neozhaoliang/pywonderland/tree/master/src/domino

正二十面体万花筒

代码:53 lines (40 sloc) 1.24 KB

'''

A kaleidoscope pattern with icosahedral symmetry.

'''

importnumpy asnp

fromPILimportImage

frommatplotlib.colors importhsv_to_rgb

defKlein(z):

'''Klein's j-function'''

return1728*(z *(z**10+11*z**5-1))**5/

(-(z**20+1) +228*(z**15-z**5) -494*z**10)**3

defRiemannSphere(z):

'''

map the complex plane to Riemann's sphere via stereographic projection

'''

t =1+z.real*z.real +z.imag*z.imag

return2*z.real/t, 2*z.imag/t, 2/t-1

defMobius(z):

'''

distort the result image by a mobius transformation

'''

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]*1j

z =RiemannSphere(Klein(Mobius(Klein(z))))

#define colors in hsv space

H =np.sin(z[0]*np.pi)**2

S =np.cos(z[1]*np.pi)**2

V =abs(np.sin(z[2]*np.pi) *np.cos(z[2]*np.pi))**0.2

HSV=np.dstack((H, S, V))

#transform to rgb space

img =hsv_to_rgb(HSV)

Image.fromarray(np.uint8(img*255)).save('kaleidoscope.png')

if__name__=='__main__':

importtime

start =time.time()

main(imgsize=800)

end =time.time()

print('runtime: {:3f}seconds'.format(end -start))

Newton 迭代分形

代码:46 lines (35 sloc) 1.05 KB

importnumpy asnp

importmatplotlib.pyplot asplt

fromnumba importjit

#define functions manually, do not use numpy's poly1d funciton!

@jit('complex64(complex64)', nopython=True)

deff(z):

#z*z*z is faster than z**3

returnz*z*z -1

@jit('complex64(complex64)', nopython=True)

defdf(z):

return3*z*z

@jit('float64(complex64)', nopython=True)

defiterate(z):

num =0

whileabs(f(z)) >1e-4:

w =z -f(z)/df(z)

num +=np.exp(-1/abs(w-z))

z =w

returnnum

defrender(imgsize):

x =np.linspace(-1, 1, imgsize)

y =np.linspace(1, -1, imgsize)

z =x[None, :] +y[:, None] *1j

img =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__':

importtime

start =time.time()

render(imgsize=400)

end =time.time()

print('runtime: {:03f}seconds'.format(end -start))

李代数E8 的根系

代码链接:https://github.com/neozhaoliang/pywonderland/blob/master/src/misc/e8.py

模群的基本域

代码链接:

https://github.com/neozhaoliang/pywonderland/blob/master/src/misc/modulargroup.py

彭罗斯铺砌

代码链接:

https://github.com/neozhaoliang/pywonderland/blob/master/src/misc/penrose.py

Wilson 算法

代码链接:https://github.com/neozhaoliang/pywonderland/tree/master/src/wilson

反应扩散方程模拟

代码链接:https://github.com/neozhaoliang/pywonderland/tree/master/src/grayscott

120 胞腔

代码:69 lines (48 sloc) 2.18 KB

#pylint: disable=unused-import

#pylint: disable=undefined-variable

fromitertools importcombinations, product

importnumpy asnp

fromvapory import*

classPenrose(object):

GRIDS=[np.exp(2j*np.pi *i /5) fori inrange(5)]

def__init__(self, num_lines, shift, thin_color, fat_color, **config):

self.num_lines =num_lines

self.shift =shift

self.thin_color =thin_color

self.fat_color =fat_color

self.objs =self.compute_pov_objs(**config)

defcompute_pov_objs(self, **config):

objects_pool =[]

forrhombi, color inself.tile():

p1, p2, p3, p4 =rhombi

polygon =Polygon(5, p1, p2, p3, p4, p1,

Texture(Pigment('color', color), config['default']))

objects_pool.append(polygon)

forp, q inzip(rhombi, [p2, p3, p4, p1]):

cylinder =Cylinder(p, q, config['edge_thickness'], config['edge_texture'])

objects_pool.append(cylinder)

forpoint inrhombi:

x, y =point

sphere =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_color

else:

color =self.fat_color

point =(Penrose.GRIDS[r] *(ks -self.shift[s])

-Penrose.GRIDS[s] *(kr -self.shift[r])) *1j/Penrose.GRIDS[s-r].imag

index =[np.ceil((point/grid).real +shift)

forgrid, shift inzip(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) forz invertices]

returnvertices_real, color

deftile(self):

forr, s incombinations(range(5), 2):

forkr, ks inproduct(range(-self.num_lines, self.num_lines+1), repeat=2):

yieldself.rhombus(r, s, kr, ks)

defput_objs(self, *args):

returnObject(self.objs, *args)

1.

免责声明:本文系网络转载,版权归原作者所有。如涉及作品版权问题,请与我们联系,我们将根据您提供的版权证明材料确认版权并支付稿酬或者删除内容。返回搜狐,查看更多

责任编辑:

用python画简单的图案-如何用Python画各种著名数学图案 | 附图+代码相关推荐

  1. 用python画简单的动物-如何用python画简单的动物

    首先来看一下实现效果,如下图: 具体实现代码请看: (推荐学习:python视频教程)# -*- coding:utf-8 -*-# __author__ :kusy# __content__:文件说 ...

  2. python循环画简单烟花_如何用python画烟花

    用python画烟花的方法:首先创建一个所有粒子同时扩大的二维列表:然后实现粒子范围扩大,以自由落体坠落:接着移除超过最高时长的粒子:最后循环调用保持不停. 用python画烟花的方法:# -*- c ...

  3. 怎么用python制作简单的程序-如何用 Python 写一个简易的抽奖程序

    不知道有多少人是被这个头图骗进来的:) 事情的起因是这样的,上周有同学问小编,看着小编的示例代码敲代码,感觉自己也会写了,如果不看的话,七七八八可能也写的出来,但是一旦自己独立写一段程序,感觉到无从下 ...

  4. python画-如何用Python画各种著名数学图案 | 附图+代码

    原标题:如何用Python画各种著名数学图案 | 附图+代码 用Python绘制著名的数学图片或动画,展示数学中的算法魅力. Mandelbrot 集 代码:46 lines (34 sloc) 1. ...

  5. matlab画平面心型线,如何用matlab画出心形线

    心形线,是一个圆上的固定一点在它绕着与其相切且半径相同的另外一个圆周滚动时所形成的轨迹线.下面就简单讲解一下如何用matlab画出心形线. 1.心形线的数学定义 2.编制的绘制心形线的matlab程序 ...

  6. 怎样用python绘制简单的图形_用python 画几个简单图案

    原博文 2019-11-15 09:44 − 1 turtle turtle这个库真的很好玩,用很简单几行代码就能画出好看的图案,最近无聊翻了翻之前自己画的哈哈哈哈,分享几个代码 画一个类似五颜六色的 ...

  7. 如何用python画爱心型线_如何用python画爱心

    用python绘制爱心的基本步骤如下: 首先先下载安装好python程序. 在我们自己的电脑上找到python 的IDLE工具. 2.然后打开IDLE,新建一个文件,命名为test1.py. 3.接着 ...

  8. python爬虫抢火车票_如何用python写一个简单的12306抢票软件|python 爬火车票 教程...

    python 如果抓取验证码图片 类似12306的登录验证码图片 这个以前做次.最大的麻烦是码的识别算法的识别率太低.12306那种网站登陆错3次就限制你20分钟.所以除非你有33%以上的识别率否则不 ...

  9. python程序写蛇_如何用Python画一条蛇

    先上效果图 最近又打算重新学习Python了, 之前也入门过Python, 但是弄完Python的开发环境后, 停留在print("hello world")阶段 非科班出身, 没 ...

最新文章

  1. Q 版老黄带着硬核技术再登场,有点可爱,很有东西
  2. 如何在Markdown中链接到同一文档的一部分?
  3. java user directory,Java ProcessBuilder directory()方法与示例
  4. addView的误区
  5. Ctr点击率预估理论基础及项目实战
  6. Silverlight HTML5 Flash - RIA技术之三足鼎立
  7. 如何在 Laravel 中使用锁
  8. 例行性工作 排程(crontab)
  9. 002-Go通过ioutil 读写文件
  10. LuaForUnity3:Lua的分支结构、循环结构与数组
  11. 白鹭发布html5,白鹭Egret Engine 1.5发布 HTML5性能大幅提升
  12. 计算机仿真的特点,计算机仿真的基本特点与基本流程.doc
  13. python 管道游戏_用Python做flybird游戏
  14. linux怎么复制文件和移动文件
  15. 微信公众平台服务号配置JS接口安全域名
  16. python基础分析_数据分析之Python基础
  17. MTK平台双击Power打开Camera的简单流程
  18. blender 2.8的基本使用和使用形态键(Shape key)做帧动画
  19. 【入门】算法初步1 排序
  20. 数字图像处理11:阈值分割(基本全局阈值处理,Otsu 的最佳全局阈值,图像平滑改善全局阈值处理,图像分块的可变阈值)

热门文章

  1. sparkpython多线程_如何在PySpark(Spark流)中组合多个rdd?
  2. 数据结构与算法汇总详解(一)
  3. BZOJ 4043 [HAOI2015]树上操作 dfs序 线段树
  4. ethtool 命令输出的注意点--网卡参数
  5. (转)B-树、B+树、B*树
  6. Flask jQuery ajax
  7. 例子代码:web.xml
  8. 免费素材大荟萃:免费图标和UI设计
  9. 国内比较好的几大酷站收藏网分享
  10. “极度郁闷,要求慰安”