参考资料:https://www.labri.fr/perso/nrougier/from-python-to-numpy
Numpy向量化程序对于单线程实现性能很高,编写效率也很高。适用于小型项目,或者算法验证。
以生命游戏作为例子:Numpy的实现
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def update(*args):
global Z, M
N = (Z[0:-2, 0:-2] + Z[0:-2, 1:-1] + Z[0:-2, 2:] +
Z[1:-1, 0:-2] + Z[1:-1, 2:] +
Z[2: , 0:-2] + Z[2: , 1:-1] + Z[2: , 2:])
birth = (N == 3) & (Z[1:-1, 1:-1] == 0)
survive = ((N == 2) | (N == 3)) & (Z[1:-1, 1:-1] == 1)
Z[...] = 0
Z[1:-1, 1:-1][birth | survive] = 1
# Show past activities
M[M>0.25] = 0.25
M *= 0.995
M[Z==1] = 1
# Direct activity