matlab的rand函數生的是偽隨機數,即由種子遞推出來的,相同的種子,生成相同的隨機數.
matlab剛運行起來時,種子都為初始值,因此每次第壹次執行rand得到的隨機數都是相同的.
1.多次運行,生成相同的隨機數方法:
用rand('state',S)設定種子
S為35階向量,最簡單的設為0就好
例: rand('state',0);rand(10)
2. 任何生成相同的隨機數方法:
試著產生和時間相關的隨機數,種子與當前時間有關.
rand('state',sum(100*clock))
即: rand('state',sum(100*clock)) ;rand(10)
只要執行rand('state',sum(100*clock)) ;的當前計算機時間不現,生成的隨機值就不現.
也就是如果時間相同,生成的隨機數還是會相同.
在妳計算機速度足夠快的情況下,試運行壹下:
rand('state',sum(100*clock));A=rand(5,5);rand('state',sum(100*clock));B=rand(5,5);
A和B是相同.
所以建議再增加壹個隨機變量,變成:
rand('state',sum(100*clock)*rand(1));
%
據說matlab 的rand 函數還存在其它的根本性的問題,似乎是非隨機性問題.
沒具體研究及討論,驗證過,不感多言.
有興趣的可以查閱:
<<A strong nonrandom pattern in Matlab default random number generator>>
Petr Savicky
Institute of Computer Science
Academy of Sciences of CR
Czech Republic
savicky@cs.cas.cz
September 16, 2006
Abstract
The default random number generator in Matlab versions between 5 and at least
7.3 (R2006b) has a strong dependence between the numbers zi+1, zi+16, zi+28 in the
generated sequence. In particular, there is no index i such that the inequalities
zi+1 < 1/4, 1/4 zi+16 < 1/2, and 1/2 zi+28 are satisfied simultaneously. This
fact is proved as a consequence of the recurrence relation defining the generator. A
random sequence satisfies the inequalities with probability 1/32. Another example
demonstrating the dependence is a simple function f with values ?1 and 1, such that
the correlation between f(zi+1, zi+16) and sign(zi+28 ? 1/2) is at least 0.416, while it
should be zero.
A simple distribution on three variables that closely approximates the joint
distribution of zi+1, zi+16, zi+28 is described. The region of zero density in the
approximating distribution has volume 4/21 in the three dimensional unit cube. For
every integer 1 k 10, there is a parallelepiped with edges 1/2k+1, 1/2k and 1/2k+1,
where the density of the distribution is 2k. Numerical simulation confirms that the
distribution of the original generator matches the approximation within small random
error corresponding to the sample size.