How to Use $random in Testbench in Verilog
In Verilog testbenches, use
$random to generate random 32-bit signed integers for testing your design. You can assign $random to variables inside an initial or always block to create random stimulus during simulation.Syntax
The $random system function returns a 32-bit signed random integer each time it is called. You can assign it to a variable like this:
variable = $random;— assigns a new random value.- You can also seed
$randomby calling$random(seed);to get repeatable sequences.
verilog
integer rand_val;
initial begin
rand_val = $random; // get a random 32-bit signed integer
endExample
This example shows a simple testbench that generates and prints 5 random numbers using $random. It demonstrates how to use $random inside an initial block and print the values.
verilog
module testbench;
integer i;
integer rand_num;
initial begin
for (i = 0; i < 5; i = i + 1) begin
rand_num = $random;
$display("Random number %0d: %0d", i+1, rand_num);
end
$finish;
end
endmoduleOutput
Random number 1: 123456789
Random number 2: -987654321
Random number 3: 135792468
Random number 4: -246813579
Random number 5: 192837465
Common Pitfalls
Common mistakes when using $random include:
- Expecting unsigned values:
$randomreturns signed integers, so negative values can appear. - Not seeding
$randomfor repeatability: Without a seed, results differ every run. - Using
$randomin synthesizable code: It is only for simulation/testbench, not hardware synthesis.
verilog
/* Wrong: Using $random in synthesizable module */ module wrong(input clk, output reg [7:0] out); always @(posedge clk) begin out <= $random; // Not synthesizable end endmodule /* Right: Use $random only in testbench */ module testbench; reg clk = 0; reg [7:0] out; always #5 clk = ~clk; initial begin @(posedge clk); out = $random; $display("Random output: %0d", out); $finish; end endmodule
Quick Reference
| Usage | Description |
|---|---|
| $random | Returns a 32-bit signed random integer |
| variable = $random; | Assigns a random value to variable |
| $random(seed); | Seeds the random number generator for repeatability |
| Use only in testbench | Not synthesizable, only for simulation |
| Returns signed values | May be negative, handle accordingly |
Key Takeaways
Use $random in testbench to generate random 32-bit signed integers for simulation.
Assign $random to variables inside initial or always blocks to create random stimulus.
Seed $random with a value for repeatable random sequences during testing.
$random is not synthesizable and should never be used in hardware design code.
Remember $random returns signed integers, so handle negative values if needed.