似乎 Matlab 中对 64 位随机整数(以及一般的 64 位整数)的支持仍然很差。
我怀疑“最好的”解决方法是做一些黑客攻击:
% create 32-bit uints, and cast to 64-bit
f = @() uint64( randi([0 intmax('uint32')], 'uint32') );
% bitshift and bitor to convert into a proper uint64
R = bitor( bitshift(f(),32), f() );
或typecast
按照 Andrew Jake 的建议使用,以提高可读性:
f = @() randi([0 intmax('uint32')], 'uint32');
R = typecast([f() f()], 'uint64');
创建多个随机数时,您必须更改g
为:
% bitshift and bitor:
% ------------
% create an Nx1 uint32, and cast to 64-bit
g = @(N) uint64( randi([0 intmax('uint32')], N,1, 'uint32') );
tic
R = bitor( bitshift(g(1e7),32), g(1e7) );
toc
% typecast
% ------------
% create a 1xN uint32, but leave the casting to typecast
g = @(N) randi([0 intmax('uint32')], 1,N, 'uint32');
tic
R = typecast([g(1e7) g(1e7)], 'uint64');
toc
结果:
Elapsed time is 0.717668 seconds. % bitor/bitshift
Elapsed time is 0.705700 seconds. % typecast w/ loop
它们同样快,所以它真的是你喜欢的任何东西。
Mersenne Twister 主页提到连接两个 s 时分布不会改变uint32
(感谢 Andrew 的提醒),因此您确实可以安全地执行此操作。