Parameters to numpy's fromfunction

前端 未结 6 1814
终归单人心
终归单人心 2020-11-30 07:37

I haven\'t grokked the key concepts in numpy yet.

I would like to create a 3-dimensional array and populate each cell with the result of a function call

6条回答
  •  甜味超标
    2020-11-30 08:02

    Does this give you an incorrect result? a should be as expected (and is when I tested it) and seems like a fine way to do what you want.

    >>> a
    array([[[ 0.,  1.],    # 0+0+0, 0+0+1
            [ 1.,  2.]],   # 0+1+0, 0+1+1
    
           [[ 1.,  2.],    # 1+0+0, 1+0+1
            [ 2.,  3.]]])  # 1+1+0, 1+1+1
    

    Since fromfunction works on array indices for input, you can see that it only needs to be called once. The documentation does not make this clear, but you can see that the function is being called on arrays of indices in the source code (from numeric.py):

    def fromfunction(function, shape, **kwargs):
        . . .
        args = indices(shape, dtype=dtype)
        return function(*args,**kwargs)
    

    sum_of_indices is called on array inputs where each array holds the index values for that dimension.

    array([[[ 0.,  0.],
            [ 1.,  1.]],
    
           [[ 1.,  1.],
            [ 1.,  1.]]])
    
    +
    
    array([[[ 0.,  0.],
            [ 1.,  1.]],
    
           [[ 0.,  0.],
            [ 1.,  1.]]])
    
    +
    array([[[ 0.,  1.],
            [ 0.,  1.]],
    
           [[ 0.,  1.],
            [ 0.,  1.]]])
    
    =
    
    array([[[ 1.,  1.],
            [ 1.,  2.]],
    
           [[ 1.,  2.],
            [ 2.,  3.]]])
    

提交回复
热议问题