【问题标题】:How to Zoom in Recursively on a Numpy Array如何递归放大 Numpy 数组
【发布时间】:2020-12-19 20:46:12
【问题描述】:

我试图证明我生成的数组在多个长度尺度上看起来是自相似的。为此,我想编写一个函数来打印输入数组的左上角,然后打印该部分的左上角,依此类推,以指定迭代次数。我写了这个递归函数。但是,输出不是我所期望的。

def zoom(array, max_zoom, zoom_level):
    half_width = int(array.shape[0]/2)
    half_height = int(array.shape[1]/2)
    print(array)

    while zoom_level < max_zoom:
        array = array[:half_width, :half_height]
        zoom_level += 1
        zoom(array, max_zoom, zoom_level)

问题不是打印到所需的级别然后停止,而是数组开始再次变大,并且在几次额外的迭代后函数停止。

例如 zoom(array, 3, 0) 应该在下面给出 8x8 网格的输出。

[[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]] 

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

[[0. 0.]
[0. 0.]]

[[0.]]

而是给出:

[[0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
[[0. 0.]
 [0. 0.]]
[[0.]]
[[0. 0.]
 [0. 0.]]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
[[0. 0.]
 [0. 0.]]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

任何人都可以阐明为什么此功能行为不端吗?

【问题讨论】:

    标签: python arrays numpy recursion fractals


    【解决方案1】:

    问题在于您的递归函数有一段时间。您正在做的是为每个递归调用重复相同的过程,从而打印出不必要的结果。

    def zoom(array, max_zoom, zoom_level):
        print(array)
        if zoom_level < max_zoom:
            half_width = array.shape[0] // 2
            half_height = array.shape[1] // 2
            array = array[:half_width, :half_height]
            zoom_level += 1
            zoom(array, max_zoom, zoom_level)
    
    A = np.zeros((9, 9))
    
    zoom(A, 3, 0)
    

    输出将是:

    [[0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]
     [0. 0. 0. 0. 0. 0. 0. 0. 0.]]
    [[0. 0. 0. 0.]
     [0. 0. 0. 0.]
     [0. 0. 0. 0.]
     [0. 0. 0. 0.]]
    [[0. 0.]
     [0. 0.]]
    [[0.]]
    
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2012-03-04
      • 2018-10-21
      • 1970-01-01
      • 2018-12-28
      • 2011-08-05
      • 1970-01-01
      相关资源
      最近更新 更多