伪随机数概述
伪随机序列又称为伪随机码,是一组人工生成的周期序列,具有某种确定的编码规则,同时又便于重复产生和处理,因而在通信领域应用广泛。通常产生伪随机序列的电路为反馈移位寄存器,分为线性反馈移位寄存器和非线性反馈移位寄存器。
线性反馈移位寄存器(LFSR)产生的周期最长的二进制数字序列称为最大长度线性反馈移位寄存器序列,简称m序列,移位寄存器的长度为n,则m序列的周期为2n-1,没有全0状态。
伪随机数生成器的初始状态由微处理器或其他模块通过seed(种子)给出。seed不能是全0,是因为0^0=0,模块会陷入0的死循环。
伪随机数生成器
使用LFSR设计一个伪随机数生成器。
randomgen.v
`timescale 1ns / 1ps
// Company:
// Engineer:
//
// Create Date: 2020/12/13
// Author Name: Sniper
// Module Name: randomgen
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
module randomgen(
input clk,
input rst_n,
input load,
input [7:0] seed,
output reg [7:0] rand_num
);
always@(posedge clk or negedge rst_n)
begin
if(!rst_n)
rand_num <= 0;
else if(load)
rand_num <= seed;
else
rand_num[7:0] <= {
rand_num[6:0], rand_num[1] ^ rand_num[2] ^ rand_num[7]};
end
endmodule
tb_randomgen.v
`timescale 1ns / 1ps
// Company:
// Engineer:
//
// Create Date: 2020/12/13
// Author Name: Sniper
// Module Name: tb_randomgen
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
module tb_randomgen;
//input
reg clk;
reg rst_n;
reg load;
reg [7:0] seed;
//output
wire [7:0] rand_num;
initial
begin
clk = 0;
rst_n = 0;
load = 0;
seed = 0;
#100;
rst_n = 1;
@(posedge clk);
seed <= 100;
load <= 1;
@(posedge clk);
load <= 0;
end
//clock
always #5 clk = ~clk;
//DUT
randomgen DUT
(
.clk(clk),
.rst_n(rst_n),
.load(load),
.seed(seed),
.rand_num(rand_num)
);
initial
begin
$dumpfile("tb_randomgen.vcd");
$dumpvars(0,tb_randomgen);
end
initial #1000 $finish;
endmodule
运行结果
vcs -R randomgen.v tb_randomgen.v