Reputation: 71
I ran into this issue while writing a test bench for a project. I found how to use $random
in verilog but for some reason it produces strange results for me. I have 2 16 bit regs called A
and B
, I tested it with random number between 0-10 every second output is a value which is the max value that you can have in 16 bits. I wonder if anyone else had had similar issue and can offer help.
Thanks
reg[15:0]a;
reg[15:0]b;
integer seed,i,j;
initial begin
for (i=0; i<6; i=i+1)
begin
a=$random%10;
#100;
b=$random%20;
$display("A %d, B: %d",a,b);
end
$finish;
Upvotes: 6
Views: 127288
Reputation: 2901
output is a value which is the max value that you can have in 16 bits.
$random
produces signed random numbers. Negative numbers will appear to be large numbers when you print it as unsigned numbers.
The code that you posted might appear something like below and this is not within the range from 0 to 10.
A 8, B: 65517
A 65527, B: 65527
A 7, B: 17
A 65535, B: 65522
A 1, B: 9
A 8, B: 17
As a solution, use $urandom
to generate unsigned random numbers that you expect between 0 to 10 and 0 to 20.
Here is a modification from the code that you posted
module test;
initial begin
reg[15:0]a;
reg [15:0] b;
integer seed,i,j;
for (i=0; i<6; i=i+1)
begin
a=$urandom%10;
#100;
b=$urandom%20;
$display("A %d, B: %d",a,b);
end
$finish;
end
endmodule
The code above might produce an output something like:
A 8, B: 0
A 3, B: 10
A 7, B: 11
A 6, B: 3
A 2, B: 7
A 1, B: 10
Which I guess is what you expect.
The code can be found and run here.
Upvotes: 14