向sum()和product()传递空数组

2024-09-28 17:25:11 发布

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

在下面的代码中,我将一个空数组传递给sum()product()函数。在

program test
    implicit none
    integer, allocatable :: A(:)

    allocate( A( 0 ) )

    print *, "sum     = ", sum( A )
    print *, "product = ", product( A )
end

然后,我尝试过的所有编译器都给出了相同的结果:

^{pr2}$

所以我想知道(1)是否允许它向这些函数传递一个空数组,(2)如果允许,结果保证为0和1(根据Fortran标准)。为了比较,其他一些语言(例如Python3)也给出了0和1,这(我猜)可能与sum( [1,2,...,n] )和{}到{}的限制有关。在

>>> import numpy as np
>>> np.sum( [] )
0.0
>>> np.prod( [] )
1.0

Tags: 函数代码testnonenpinteger数组product
2条回答

是的,它允许将零大小的数组传递给那些内部函数(以及其他许多函数),而且Fortran标准明确要求这些结果。在

对于product(F2008,13.7.133):

The result of PRODUCT (ARRAY) has a value equal to a processor-dependent approximation to the product of all the elements of ARRAY or has the value one if ARRAY has size zero.

对于sum(F2008,13.7.161):

The result of SUM (ARRAY) has a value equal to a processor-dependent approximation to the sum of all the elements of ARRAY or has the value zero if ARRAY has size zero.

自f90以来,这些内部函数具有相同的指定行为,一旦错误报告被处理,那些有错误的编译器就会被纠正。您可能会想到相关的内部函数,比如maxloc,它在f2003中首次定义为0大小,但是某些编译器仍然可以选择违反标准,在非零大小下使用正确的行为进行优化。在

相关问题 更多 >