尽管使用了随机种子,随机数仍然保持不变 [英] Random numbers keep coming out the same, despite random seed being used
问题描述
我有以下一小段代码:
I have the following small piece of code:
REAL(8) :: x
INTEGER :: i
call system_clock(i)
WRITE(*,*) 'cpu time', i
CALL random_seed(i)
CALL random_number(x)
WRITE(*,*) 'uniform RandVar', x
CPU时间为工作正常,但每次运行这个时,我都会得到相同的制服 RandVar number = 0.99755959009261719
,几乎就像 random_number
正在使用一遍又一遍的相同默认种子,并忽略随机种子。
CPU time is working fine, but every time I run this I get the same uniform RandVar number = 0.99755959009261719
, almost like random_number
is using the same default seed over and over again and ignoring random seed.
我做错了什么?
What am I doing wrong?
推荐答案
很好被使用:这是依赖于处理器。原因是你对 random_seed
的调用不会设置种子。
The same seed may well be being used: that is processor-dependent. The reason for this is that your call to random_seed
is not setting the seed.
使用
CALL random_seed(i)
参数 i
不是( intent(in)
)种子,而是( intent(out)
)处理器使用的种子大小。这个调用就像
the argument i
is not the (intent(in)
) seed, but is the (intent(out)
) size of the seed used by the processor. This call is like
CALL random_seed(SIZE=i) ! SIZE is the first dummy argument
要设置种子,您需要明确地与<$ c $相关联c> PUT 伪参数:调用random_seed(put = seed)
。这里的种子是大小至少 n
的一级数组,其中 n
- 同样取决于处理器 - 是大小由调用random_seed(size = n)
给出。您的电话 i
保留此值。
To set the seed you need to explicitly associate with the PUT
dummy argument: call random_seed(put=seed)
. Here the seed is a rank 1 array of size at least n
where n
- again processor-dependent - is the size given by call random_seed(size=n)
. From your call i
holds this value.
详细信息在F2008的13.7.136中给出。
Full details are given in 13.7.136 of F2008.
生成生成器的常用方法是:
A common way to seed the generator is:
integer, allocatable :: seed(:)
integer size
call random_seed(size=size)
allocate(seed(size))
! set seed(:) somehow
call random_seed(put=seed)
设置 seed
并不是一个简单的过程。我在这里没有解决如何做到这一点,但详细信息可以在这个其他问题的答案中找到。
Setting seed
appropriately is not a simple process. I don't address how to do that here, but detail can be found in answers to this other question.
在评论中提到的 srand()
的使用是非标准的。
Use of srand()
, which is mentioned in the comments, is non-standard.
这篇关于尽管使用了随机种子,随机数仍然保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!