问题描述
是否有任何方法可以生成伪随机数以降低精度,从而加快处理速度?
Is there any way to generate pseudo-random numbers to less precision and thus speed the process up?
另一件事是,我知道如果一次全部生成随机数(例如rand(100,1000)
)而不是一次生成一个随机数,则可以节省时间.有人可以解释为什么这是真的吗?
Another thing is that I know it saves time if random numbers are generated all at once (e.g. rand(100,1000)
), instead of one by one. Could someone explain why this is true?
推荐答案
MATLAB实际上实现了多个随机数生成器.它们在执行时间和随机性"方面有很大的不同(我认为,但我没有验证).但是,从您的问题中我了解到,速度对您来说更重要.
MATLAB actually implements more than one random number generator. They differ significantly in terms of execution time and in terms of "randomness" (I think, but I didn't verify). However, I understand from your question that speed is more important for you.
% 'twister' is the default in MATLAB Versions 7.4 and later
tic();
for i=1:1000000
rand('twister');
end
toc();
%Elapsed time is 2.912960 seconds.
% 'state' is the default in MATLAB versions 5 through 7.3
tic();
for i=1:1000000
rand('state');
end
toc();
% Elapsed time is 2.162040 seconds.
% 'seed' is the default in MATLAB version 4
tic();
for i=1:1000000
rand('seed');
end
toc();
% Elapsed time is 0.758830 seconds.
重要说明::我使用较旧版本的MATLAB(v.7.6,又名R2008a)运行了上面的脚本.在较新的版本中,语法rand(generator)
不鼓励.相反,您应该使用功能rng(seed, generator)
(在线文档).副作用是,rng(seed, generator)
为您提供了更多的随机数生成器供您选择.查看文档以了解详细信息.
Important note: I ran the script above with an rather old version of MATLAB (v.7.6, a.k.a. R2008a). In newer versions, the syntax rand(generator)
is discouraged . Instead, you should use the function rng(seed, generator)
(online documentation). As a side effect, rng(seed, generator)
gives you even more random number generators to choose from. Check the documentation for details.
关于第二个问题:无论选择哪种生成器,一次生成多个随机数总是比生成多个单个随机数快.这是因为MATLAB的内部结构针对并行处理进行了大量优化.
Regarding the second question: Whatever generator you pick, generating many random numbers at once will always be faster than generating many single random numbers. This is because MATLAB's internals are heavily optimized for parallel processing.
tic();
for i=1:100000
rand();
end
toc();
% Elapsed time is 0.024388 seconds.
tic();
rand(100, 1000);
toc();
% Elapsed time is 0.000680 seconds.
这篇关于加快MATLAB中随机数的生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!