伪随机数的产生
1.2. 线性反馈移位寄存器
线性反馈移位寄存器(LFSR)是一个反馈移位寄存器。其反馈函数是寄存器中某些位的简单异或,这些位也称之为抽头序列。一个n位的LFSR能够在重复之前产生2^n-1位长的伪随机序列。只有具有一定抽头序列的LFSR才能通过所有2^n-1个内部状态,产生2^n - 1位长的伪随机序列,这个输出的序列就称之为m序列。
┌─┬─┬─┬─┬─┬─┬─┬─┐
┌─→┤ │ │ │ │ │ │ │ ├──→
│ └─┴─┴─┴─┴─┴─┴─┴─┘
| \ | /
└───────←⊙←─
为了使LFSR成为最大周期的LFSR,由抽头序列加上常数1形成的多项式必须是本原多项式模2。多项式的阶即移位寄存器的长度。一个n阶本原多项式是不可约多项式,它能整除x^(2*n-1)+1而不能整除x^d+1,其中d能整除2^n-1。例如(32,7,5,3,2,1,0)是指下面本原多项式模2:
x^32+x^7+x^5+x^3+x^2+x+1
把它转化为最大周期LFSR就是在LFSR小邓第32,7,5,2,1位抽头。更多的本原多项式模2
利用上述两种方法产生周期为m的伪随机序列后 ,只需要将产生的伪随机序列除以序列的周期,就可以得到(0,1)上均匀分布的伪随机序列了。
-------------------------------------------------------------------------
function x = rndgenm(n,options)
%RNDGENM Uniformly distributed random numbers generator.
% X = rndgenm(N,OPTIONS)
% where N is number of random variates needed, and OPTIONS give a
% tap sequence for Linear Feedback Shift Register (LFSR).A default
% choose of OPTIONS is [32,7,5,3,2,1,0].
%
% RNDGENM produces pseudo-random numbers. The sequence of numbers
% generated is determined by the state of the generator. RNDGENM use
% Linear Feedback Shift Register (LFSR) to generate a m-sequence.
%
% See also RAND, RNDGEN
%---------------------------------------------------------------------------
% xywu
% Fudan university.
%
% $Revision: 1.0 $
% $Date: 03/08/2002 $
%
%---------------------------------------------------------------------------
if nargin>2
error('Too many arguments! ');
end
if nargin<1
error('Requires at least one input argument.');
end
if nargin==1
options = [32,7,5,3,2,1,0];
end
options = options(find(options>0));
Len = max(options);
if Len>51 | Len<1
error('Tap sequence should be more than 1 and less than 51.');
end
x = [];
MAXVAL = 2^Len-1;
Register = 0;
while Register==0
Register = fix(rand(1)*MAXVAL);
end
for i = 1:n
Feedback = 0;
for j = 1:length(options)
Feedback = bitget(Register,options(j))+Feedback;
end
Register = bitshift(Register,-1);
Register = bitset(Register,Len,bitget(Feedback,1));
x(i) = Register/MAXVAL;
end