Fortran中的加权采样

问题描述 投票:3回答:1

在Fortran程序中,我想通过使用权重随机选择特定变量(特别是其索引)。权重将在单独的向量中提供(元素1将包含变量1的权重,依此类推)。

[我有以下代码,谁在没有权重的情况下完成这项工作(mind是具有原始数据集中每个变量的索引的整数向量)

call rrand(xrand)
j = int(nn * xrand) + 1
mvar = mind(j)
fortran sampling weighted
1个回答
3
投票

这里有两个例子。第一个是

integer, parameter :: nn = 5
real :: weight( nn ), cumsum( nn ), x

weight( 1:nn ) = [ 1.0, 2.0, 5.0, 0.0, 2.0 ]

do j = 1, nn
    cumsum( j ) = sum( weight( 1:j ) ) / sum( weight( 1:nn ) )   !! cumulative sum
enddo

x = rand()
do j = 1, nn
    if ( x < cumsum( j ) ) exit
enddo

第二个取自this page

real :: sum_weight
sum_weight = sum( weight( 1:nn ) )

x = rand() * sum_weight
do j = 1, nn
    if ( x < weight( j ) ) exit
    x = x - weight( j )
enddo

与第一个基本相同。两者都从1,2,...,5中以权重(j)随机抽取j。 100000次试用提供的分布类似于

j     :    1           2           3           4       5
count :    10047       19879       50061       0       20013

编辑:下面附有最低限度的测试代码(使用gfortran-8 / 9测试):

program main
    implicit none
    integer j, num( 5 ), loop
    real    weights( 5 )

    weights(:) = [ 1.0, 2.0, 5.0, 0.0, 2.0 ]
    num(:) = 0

    do loop = 1, 100000
        call random_index( j, weights )
        num( j ) = num( j ) + 1
    enddo

    do j = 1, size( weights )
        print *, j, num( j )
    enddo

subroutine random_index( idx, weights )
    integer :: idx
    real, intent(in) :: weights(:)

    real x, wsum, prob

    wsum = sum( weights )

    call random_number( x )

    prob = 0
    do idx = 1, size( weights )
        prob = prob + weights( idx ) / wsum   !! 0 < prob < 1
        if ( x <= prob ) exit
    enddo
end subroutine

end program
© www.soinside.com 2019 - 2024. All rights reserved.