Python numpy数组阿贝尔沙堆

2024-07-04 07:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用一个简单的numpy数组来建立阿贝尔沙堆模型。
当“桩”为4时>;=,然后它会在它的邻居之间崩溃。
我理解“重力”是如何工作的,但我想不出一种方法来实现它。
下面是生成我的数组的代码:

import numpy as np
spile = np.zeros((5, 5), dtype=np.uint32)
spile[2, 2] = 16

这给了我以下信息:

array([[ 0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0],
       [ 0,  0, 16,  0,  0],
       [ 0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0]], dtype=uint32)

现在,我需要执行以下计算步骤的“重力”代码:

array([[ 0,  0,  0,  0,  0],
       [ 0,  0,  4,  0,  0],
       [ 0,  4,  0,  4,  0],
       [ 0,  0,  4,  0,  0],
       [ 0,  0,  0,  0,  0]], dtype=uint32)


array([[ 0,  0,  1,  0,  0],
       [ 0,  2,  1,  2,  0],
       [ 1,  1,  0,  1,  1],
       [ 0,  2,  1,  2,  0],
       [ 0,  0,  1,  0,  0]], dtype=uint32)

最后一个数组是我试图得到的最终结果。
我不是想让你们为我编码,我只是需要一些想法,因为我从来没有做过这样的事情(但如果你们是那种人,请随时提供代码:p)


Tags: 方法代码模型importgtnumpynp数组
1条回答
网友
1楼 · 发布于 2024-07-04 07:41:58

使用np.divmod标识单元格在何处翻滚以及翻滚多少。然后使用数组切片来移动翻滚的数量,并将其添加回沙堆中

import numpy as np      
spile = np.zeros((5, 5), dtype=np.uint32)
spile[2, 2] = 16         

def do_add( spile, tumbled ):
    """ Updates spile in place """
    spile[ :-1, :] += tumbled[ 1:, :] # Shift N and add                 
    spile[ 1:, :] += tumbled[ :-1, :] # Shift S   
    spile[ :, :-1] += tumbled[ :, 1:] # Shift W
    spile[ :, 1:] += tumbled[ :, :-1] # Shift E

def tumble( spile ):
    while ( spile > 3 ).any():
        tumbled, spile = np.divmod( spile, 4 )
        do_add( spile, tumbled )
        # print( spile, '\n' )  # Uncomment to print steps
    return spile

print( tumble( spile ) ) 
# or tumble( spile ); print( spile )

# [[0 0 1 0 0]
# [0 2 1 2 0]
# [1 1 0 1 1]
# [0 2 1 2 0]
# [0 0 1 0 0]]

未注释的print语句打印这些结果

[[0 0 0 0 0]
 [0 0 4 0 0]
 [0 4 0 4 0]
 [0 0 4 0 0]
 [0 0 0 0 0]] 

[[0 0 1 0 0]
 [0 2 0 2 0]
 [1 0 4 0 1]
 [0 2 0 2 0]
 [0 0 1 0 0]] 

[[0 0 1 0 0]
 [0 2 1 2 0]
 [1 1 0 1 1]
 [0 2 1 2 0]
 [0 0 1 0 0]] 

http://rosettacode.org/wiki/Abelian_sandpile_model

相关问题 更多 >

    热门问题