这里有两个例子。第一个是
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
这与第一个基本相同。两者都使用权重(j)从 1,2,...,5 中随机抽取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
contains
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