【问题标题】:Generating points within a Menger Sponge (fractal shape)在 Menger 海绵(分形)内生成点
【发布时间】:2022-11-30 01:44:29
【问题描述】:

我正在尝试生成 Menger 海绵或 Sierpinski 海绵形状的点格。

https://en.wikipedia.org/wiki/Menger_sponge 此链接详细说明了形状的数学构造方式。

我想找到一种方法,我可以使用递归来删除必要的立方体来制作这个形状。

我在网上查看,但只能找到生成形状 3D 渲染的代码,而不是点格。

值得一提的是,我不熟悉 OO 编程,这似乎是我找到的示例使用的通用方法。

然后我尝试制作一个 2D 版本,看看我是否可以实现它,但我唯一可以使用的版本是手动减去所需的区域。

这就是我要做的,只从中心移除第一个方块:

`

import numpy as np
import matplotlib.pyplot as plt

size = 12

x = []
y = []

for index_x in np.arange(size):
    for index_y in np.arange(size):
        x = np.append(x, index_x)
        y = np.append(y, index_y)


     

# step 1: remove central box
x_box = []
y_box = [] 
for index_1 in np.arange(144):
    
    if (x[index_1] < size/3 or x[index_1] >= 2/3 * size or 
        y[index_1] < size/3 or y[index_1] >= 2/3 * size):

        x_box = np.append(x_box, x[index_1])
        y_box = np.append(y_box, y[index_1])
        
# step 2: remove central square in each surrounding square
# Do the same steps as above but for the other smaller squares


            

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x_box, y_box)
ax.set_title('Menger Sponge')
ax.set_xlabel('x')
ax.set_ylabel('y')

plt.show()

`

这就是我的代码产生的结果。

有没有更简单/更好的方法来实现这个?

【问题讨论】:

    标签: python recursion fractals


    【解决方案1】:

    你需要添加一个递归的元素到您的代码。我还建议考虑 2D(最终是 3D)矩阵而不是 1D 数组,并深入探索 numpy 的能力:

    import numpy as np
    
    def menger(matrix, size):
        quotient, remainder = divmod(size, 3)
    
        if remainder == 0:
            for x in np.arange(0, size, quotient):
                for y in np.arange(0, size, quotient):
                    view = matrix[x:x + quotient, y:y + quotient]
    
                    if (x // quotient) % 3 == 1 and (y // quotient) % 3 == 1:
                        view *= 0
    
                    menger(view, quotient)
    
    if __name__ == "__main__":
        import matplotlib.pyplot as plt
    
        SIZE = 27
    
        matrix = np.ones((SIZE, SIZE))
    
        menger(matrix, SIZE)
    
        plt.matshow(matrix)
        plt.colorbar()
        plt.show()
    

    【讨论】:

      猜你喜欢
      • 2016-02-11
      • 1970-01-01
      • 2012-01-13
      • 2012-12-10
      • 2018-08-12
      • 2018-10-07
      • 2013-05-12
      • 2013-02-20
      • 1970-01-01
      相关资源
      最近更新 更多