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

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

 

编译团队:Aileen  徐凌霄

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

Mandelbrot 集

Mandelbrot 集

代码:46 lines (34 sloc) 1.01 KB

  1. '''  
  2. A fast Mandelbrot set wallpaper renderer 
  3.  
  4.   
  5. reddit discussion: https://www.reddit.com/r/math/comments/2abwyt/smooth_colour_mandelbrot/  
  6. '''  
  7. import numpy as np  
  8. from PIL import Image  
  9. from numba import jit 
  10.  
  11.   
  12. MAXITERS = 200 
  13. RADIUS = 100 
  14.  
  15.   
  16. @jit 
  17. def color(z, i):  
  18. v = np.log2(i + 1 - np.log2(np.log2(abs(z)))) / 5  
  19. if v < 1.0: 
  20. return v**4, v**2.5, v 
  21. else:  
  22. v = max(0, 2-v)  
  23. return v, v**1.5, v**3 
  24.  
  25.   
  26. @jit 
  27. def iterate(c): 
  28. z = 0j  
  29. for i in range(MAXITERS):  
  30. if z.real*z.real + z.imag*z.imag > RADIUS:  
  31. return color(z, i) 
  32. zz = z*z + c  
  33. return 0, 0 ,0 
  34.  
  35.   
  36. def main(xmin, xmax, ymin, ymax, width, height):  
  37. x = np.linspace(xmin, xmax, width) 
  38. y = np.linspace(ymax, ymin, height) 
  39. z = x[None, :] + y[:, None]*1j 
  40. red, green, blue = np.asarray(np.frompyfunc(iterate, 1, 3)(z)).astype(np.float) 
  41. img = np.dstack((red, green, blue))  
  42. Image.fromarray(np.uint8(img*255)).save('mandelbrot.png') 
  43.  
  44.   
  45. if __name__ == '__main__':  
  46. 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

  1. ''' 
  2. A kaleidoscope pattern with icosahedral symmetry. 
  3. ''' 
  4. import numpy as np 
  5. from PIL import Image 
  6. from matplotlib.colors import hsv_to_rgb 
  7.  
  8.   
  9. def Klein(z): 
  10. '''Klein's j-function'''  
  11. return 1728 * (z * (z**10 + 11 * z**5 - 1))**5 / \ 
  12. (-(z**20 + 1) + 228 * (z**15 - z**5) - 494 * z**10)**3 
  13.  
  14.   
  15. def RiemannSphere(z):  
  16. ''' 
  17.     map the complex plane to Riemann's sphere via stereographic projection 
  18.     ''' 
  19. t = 1 + z.real*z.real + z.imag*z.imag 
  20. return 2*z.real/t, 2*z.imag/t, 2/t-1 
  21.  
  22.   
  23. def Mobius(z): 
  24. ''' 
  25.     distort the result image by a mobius transformation 
  26.     ''' 
  27. return (z - 20)/(3*z + 1j) 
  28.  
  29.   
  30. def main(imgsize): 
  31. x = np.linspace(-6, 6, imgsize))
  32. y = np.linspace(6, -6, imgsize) 
  33. z = x[None, :] + y[:, None]*1j 
  34. z = RiemannSphere(Klein(Mobius(Klein(z)))) 
  35.  
  36.   
  37. # define colors in hsv space 
  38. H = np.sin(z[0]*np.pi)**2 
  39. S = np.cos(z[1]*np.pi)**2 
  40. V = abs(np.sin(z[2]*np.pi) * np.cos(z[2]*np.pi))**0.2 
  41. HSV = np.dstack((H, S, V)) 
  42.  
  43.   
  44. # transform to rgb space 
  45. img = hsv_to_rgb(HSV)  
  46. Image.fromarray(np.uint8(img*255)).save('kaleidoscope.png') 
  47.  
  48.   
  49. if __name__ == '__main__':  
  50. import time  
  51. start = time.time()  
  52. main(imgsize=800
  53. end = time.time() 
  54. print('runtime: {:3f} seconds'.format(end - 

Newton 迭代分形

Newton 迭代分形

代码:46 lines (35 sloc) 1.05 KB

  1. import numpy as np 
  2. import matplotlib.pyplot as plt 
  3. from numba import jit 
  4.  
  5.   
  6. # define functions manually, do not use numpy's poly1d funciton! 
  7. @jit('complex64(complex64)', nopython=True 
  8. def f(z):  
  9. # z*z*z is faster than z**3 
  10. return z*z*z - 1 
  11.  
  12.   
  13. @jit('complex64(complex64)', nopython=True
  14. def df(z):  
  15. return 3*z*z 
  16.  
  17.   
  18. @jit('float64(complex64)', nopython=True 
  19. def iterate(z):  
  20. num = 0  
  21. while abs(f(z)) > 1e-4:  
  22. w = z - f(z)/df(z)  
  23. num += np.exp(-1/abs(w-z)) 
  24. z = w 
  25. return num 
  26.  
  27.   
  28. def render(imgsize):  
  29. x = np.linspace(-1, 1, imgsize)  
  30. y = np.linspace(1, -1, imgsize)  
  31. z = x[None, :] + y[:, None] * 1j  
  32. img = np.frompyfunc(iterate, 1, 1)(z).astype(np.float) 
  33. fig = plt.figure(figsize=(imgsize/100.0, imgsize/100.0), dpi=100
  34. ax = fig.add_axes([0, 0, 1, 1], aspect=1
  35. ax.axis('off') 
  36. ax.imshow(img, cmap='hot'))
  37. fig.savefig('newton.png') 
  38.  
  39.   
  40. if __name__ == '__main__': 
  41. import time  
  42. start = time.time() 
  43. render(imgsize=400
  44. end = time.time()  
  45. print('runtime: {:03f} seconds'.format(end  

李代数E8 的根系

李代数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 胞腔

120 胞腔

 

  1. # pylint: disable=unused-import 
  2. # pylint: disable=undefined-variable 
  3.   
  4. from itertools import combinations, product 
  5. import numpy as np  
  6. from vapory import * 
  7.  
  8.  
  9. class Penrose(object): 
  10.   
  11. GRIDS = [np.exp(2j * np.pi * i / 5) for i in range(5)] 
  12.   
  13. def __init__(self, num_lines, shift, thin_color, fat_color, **config):  
  14. self.num_lines = num_lines 
  15. self.shift = shift 
  16. self.thin_color = thin_color 
  17. self.fat_color = fat_color 
  18. selfself.objs = self.compute_pov_objs(**config) 
  19.  
  20.  
  21. def compute_pov_objs(self, **config): 
  22. objects_pool = [] 
  23.   
  24. for rhombi, color in self.tile(): 
  25. p1, p2, p3, p4 = rhombi 
  26. polygon = Polygon(5, p1, p2, p3, p4, p1,  
  27. Texture(Pigment('color', color), config['default'])) 
  28. objects_pool.append(polygon) 
  29.   
  30. for p, q in zip(rhombi, [p2, p3, p4, p1]): 
  31. cylinder = Cylinder(p, q, config['edge_thickness'], config['edge_texture']) 
  32. objects_pool.append(cylinder) 
  33.   
  34. for point in rhombi:  
  35. x, y = point  
  36. sphere = Sphere((x, y, 0), config['vertex_size'], config['vertex_texture']) 
  37. objects_pool.append(sphere) 
  38.   
  39. return Object(Union(*objects_pool)) 
  40.  
  41.   
  42. def rhombus(self, r, s, kr, ks): 
  43. if (s - r)**2 % 5 == 1: 
  44. color = self.thin_color 
  45. else: 
  46. color = self.fat_color 
  47.   
  48. point = (Penrose.GRIDS[r] * (ks - self.shift[s]) 
  49. - Penrose.GRIDS[s] * (kr - self.shift[r])) *1j / Penrose.GRIDS[s-r].imag 
  50. index = [np.ceil((point/grid).real + shift) 
  51. for grid, shift in zip(Penrose.GRIDS, self.shift)] 
  52.   
  53. vertices = [] 
  54. for index[r], index[s] in [(kr, ks), (kr+1, ks), (kr+1, ks+1), (kr, ks+1)]: 
  55. vertices.append(np.dot(index, Penrose.GRIDS)) 
  56.   
  57. vertices_real = [(z.real, z.imag) for z in vertices] 
  58. return vertices_real, color 
  59.  
  60.   
  61. def tile(self): 
  62. for r, s in combinations(range(5), 2): 
  63. for kr, ks in product(range(-self.num_lines, self.num_lines+1), repeat=2): 
  64. yield self.rhombus(r, s, kr, ks) 
  65.  
  66.   
  67. def put_objs(self, *args): 
  68. return Object(self.objs, *args) 

原文:https://github.com/neozhaoliang/pywonderland/blob/master/README.md

【本文是51CTO专栏机构大数据文摘的原创译文,微信公众号“大数据文摘( id: BigDataDigest)”】

     大数据文摘二维码

 

戳这里,看该作者更多好文

责任编辑:赵宁宁 来源: 51CTO专栏
相关推荐

2018-09-12 16:30:45

Python编程语言马赛克画

2020-11-02 08:15:00

Python数据开发

2017-07-28 10:45:20

大数据TensorFlow分形图案

2014-04-22 09:58:25

数据中心

2018-10-10 09:00:00

前端框架Angular

2017-05-02 13:38:51

CSS绘制形状

2024-02-19 13:10:38

模型训练

2013-12-27 09:00:27

编程语言

2020-07-10 09:49:53

数据清理数据分析查找异常

2023-02-08 07:09:40

PythonChatGPT语言模型

2018-03-27 18:12:12

PythonHTML

2019-11-28 09:23:17

Python机器学习数据库

2018-05-17 10:05:24

运行iPadPython

2020-05-09 10:38:31

Python透视表数据

2020-12-10 10:46:23

PythonExcel图片

2017-06-29 11:11:17

2021-06-02 15:10:20

PythonScrapy视频

2020-11-06 17:42:02

Python开发工具

2019-08-01 15:08:37

PythonLine操作系统

2009-12-17 10:39:01

Ruby数学表达式
点赞
收藏

51CTO技术栈公众号