image.png
    分形图形一般都有自相似性,这就是说如果将分形图形的局部不断放大并进行观察,将发现精细的结构,如果再放大,就会再度出现更精细的结构,可谓层出不穷,永无止境。

    1. import numpy as np
    2. import matplotlib.pyplot as plt
    3. # 蕨类植物叶子的迭代函数和其概率值
    4. eq1 = np.array([[0, 0, 0], [0, 0.16, 0]])
    5. p1 = 0.01
    6. eq2 = np.array([[0.2, -0.26, 0], [0.23, 0.22, 1.6]])
    7. p2 = 0.07
    8. eq3 = np.array([[-0.15, 0.28, 0], [0.26, 0.24, 0.44]])
    9. p3 = 0.07
    10. eq4 = np.array([[0.85, 0.04, 0], [-0.04, 0.85, 1.6]])
    11. p4 = 0.85
    12. def ifs(p, eq, init, n):
    13. """
    14. 进行函数迭代
    15. p: 每个函数的选择概率列表
    16. eq: 迭代函数列表
    17. init: 迭代初始点
    18. n: 迭代次数
    19. 返回值:每次迭代所得的X坐标数组, Y坐标数组, 计算所用的函数下标
    20. """
    21. # 迭代向量的初始化
    22. pos = np.ones(3, dtype=np.float)
    23. pos[:2] = init
    24. # 通过函数概率,计算函数的选择序列
    25. p = np.add.accumulate(p)
    26. rands = np.random.rand(n)
    27. select = np.ones(n, dtype=np.int) * (n - 1)
    28. for i, x in enumerate(p[::-1]):
    29. select[rands < x] = len(p) - i - 1
    30. # 结果的初始化
    31. result = np.zeros((n, 2), dtype=np.float)
    32. c = np.zeros(n, dtype=np.float)
    33. for i in range(n):
    34. eqidx = select[i] # 所选的函数下标
    35. tmp = np.dot(eq[eqidx], pos) # 进行迭代
    36. pos[:2] = tmp # 更新迭代向量
    37. # 保存结果
    38. result[i] = tmp
    39. c[i] = eqidx
    40. return result[:, 0], result[:, 1], c
    41. x, y, c = ifs([p1, p2, p3, p4], [eq1, eq2, eq3, eq4], [0, 0], 1000000)
    42. plt.figure(figsize=(6, 6))
    43. plt.subplot(121)
    44. plt.scatter(x, y, s=1, c="g", marker="s", linewidths=0)
    45. plt.axis("equal")
    46. plt.axis("off")
    47. plt.subplot(122)
    48. plt.scatter(x, y, s=1, c=c, marker="s", linewidths=0)
    49. plt.axis("equal")
    50. plt.axis("off")
    51. plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)
    52. plt.gcf().patch.set_facecolor("silver")
    53. plt.show()