To generate a random number in Verilog, use the $random system task for simulation, or build a Linear Feedback Shift Register (LFSR) for synthesizable hardware. $random returns a 32-bit signed integer each time it is called, while an LFSR produces a pseudo-random sequence of bits that you can use in FPGA or ASIC designs.
Why Verilog Needs Random Numbers
Random numbers are essential in digital design for two main reasons: testing and hardware applications. In simulation, you often need random stimulus to verify that a module behaves correctly under varied inputs—for example, randomizing data buses, addresses, or timing delays. In hardware, random number generators (RNGs) are used in cryptography, communications (spread spectrum), gaming, and Monte Carlo simulations. Verilog provides built-in system tasks for simulation, but for synthesizable logic you must implement your own generator.
Using $random and $urandom in Simulation
The simplest way to get a random number in a testbench is $random. It returns a 32-bit signed integer. For example:
reg [31:0] data;
initial begin
data = $random; // 32-bit signed random
end
To get an unsigned value or a value within a range, use the modulo operator or $urandom (SystemVerilog). $urandom returns an unsigned 32-bit number. To get a value between 0 and N-1, use $urandom % N. For a range [min, max], use min + ($urandom % (max-min+1)).
Note: $random is a Verilog-2001 system task; $urandom is SystemVerilog. Both are simulation-only and cannot be synthesized. Also, the random sequence is deterministic—it starts from a seed. You can set the seed with $srandom(seed) in SystemVerilog to reproduce the same sequence, which is useful for debugging.
Building a Synthesizable LFSR
For hardware, a Linear Feedback Shift Register (LFSR) is the standard approach. An LFSR shifts bits and uses XOR feedback to create a pseudo-random sequence. The width determines the maximum sequence length (2^n – 1 for a maximal-length LFSR). Here is a 4-bit LFSR with polynomial x^4 + x^3 + 1 (taps at bits 4 and 3):
module lfsr_4bit(input clk, input rst, output reg [3:0] out);
always @(posedge clk) begin
if (rst) out <= 4'b0001; // seed (non-zero)
else begin
out <= {out[2:0], out[3] ^ out[2]};
end
end
endmodule
This produces a 15-cycle repeating sequence. For wider outputs, use more bits and appropriate taps. Common tap tables are available in Xilinx and Altera application notes. Ensure the seed is non-zero; otherwise, the LFSR gets stuck at zero.
Choosing the Right Approach
Decide based on your context:
- Simulation only: Use
$randomor$urandom. They are simple and flexible. - Synthesizable hardware: Use an LFSR for most applications. It uses few resources and is fast.
- Cryptographic quality: An LFSR alone is not secure. For cryptography, use a dedicated block like a true RNG or a cryptographically secure PRNG (e.g., based on AES).
- Randomness quality: LFSRs have linear patterns; for better statistical properties, consider combining multiple LFSRs or using a cellular automaton.
Common Pitfalls and How to Avoid Them
Here are frequent issues when generating random numbers in Verilog:
- LFSR stuck at zero: Always initialize with a non-zero seed. Use a reset that loads a known seed.
- Using $random in synthesizable code: Synthesis tools will either ignore it or error. Keep it in testbenches only.
- Modulo bias: When you use
$urandom % N, if N does not divide 2^32 evenly, some values are slightly more likely. For most testbenches this is acceptable, but for critical applications, use rejection sampling. - Not seeding properly: In simulation, if you don't set a seed, the sequence is the same every run. Use
$srandomwith a different seed (e.g., from system time) to get varied runs. - Forgetting to declare the output width: An LFSR output width should match the number of bits you need. A 4-bit LFSR gives only 4-bit numbers.
LFSR vs. Other PRNGs
LFSRs are not the only option. Other pseudo-random number generators (PRNGs) include:
- Cellular Automata (e.g., Rule 90/150): Better statistical properties but more complex.
- Mersenne Twister: High quality, but too large for most FPGAs.
- Xorshift: A modern PRNG that is simple and fast, but uses more logic than an LFSR.
- True Random Number Generator (TRNG): Uses physical noise (e.g., ring oscillator jitter) for unpredictable randomness, needed for security.
For most digital design tasks, an LFSR is the best trade-off between simplicity, speed, and resource usage. If you need better statistical quality, a xorshift or a combination of LFSRs can help.
Implementing a Random Number Generator in FPGA
Here is a complete example of a 16-bit LFSR with a parallel load and enable, suitable for FPGA implementation:
module lfsr_16bit(
input clk,
input rst,
input en,
input [15:0] seed,
output reg [15:0] out
);
always @(posedge clk) begin
if (rst) out <= seed; // load seed on reset
else if (en) begin
// Taps for 16-bit LFSR: 16, 14, 13, 11 (from Xilinx app note)
out <= {out[14:0], out[15] ^ out[14] ^ out[13] ^ out[11]};
end
end
endmodule
In your design, you can connect this to a counter or a state machine to generate random numbers on demand. Remember to tie en low when you don't need a new number to save power.
Frequently Asked Questions
Can I use $random in synthesized hardware?
No. $random and $urandom are simulation-only system tasks. Synthesis tools will either ignore them or produce an error. For hardware, you must implement a PRNG like an LFSR.
How do I generate a random number between 0 and 100 in Verilog?
In simulation, use reg [31:0] r; r = $urandom % 101; to get a value from 0 to 100. In hardware, you would take the LFSR output and apply a modulo operation, but be aware of bias if 101 does not divide the LFSR's output range evenly.
What is the maximum length of an LFSR sequence?
For an n-bit LFSR with the correct taps (a primitive polynomial), the sequence length is 2^n - 1. For example, a 4-bit LFSR gives 15 states, and a 16-bit LFSR gives 65,535 states before repeating.
How do I seed an LFSR in Verilog?
Use a reset signal to load a non-zero seed into the shift register. For example, in the always block, on reset assign out <= seed where seed is a parameter or input. Never use all zeros as the seed.
Is an LFSR good for cryptographic applications?
No. An LFSR is linear and predictable; given enough output bits, an attacker can recover the state. For cryptography, use a true random number generator or a cryptographically secure PRNG (CSPRNG) like AES-CTR DRBG.
How can I make my random number generator produce a different sequence each time?
In simulation, set a random seed using $srandom($time) or from a system clock. In hardware, you can use a physical entropy source (like a ring oscillator) to seed an LFSR on startup, or use a counter that increments at an unpredictable rate.
Conclusion
Generating random numbers in Verilog is straightforward: use $random for testbenches and an LFSR for synthesizable logic. Understand the differences between simulation and hardware, choose the right generator for your quality requirements, and avoid common pitfalls like zero seeds or modulo bias. With this guide, you can confidently add randomness to your designs.
Related
- Java Enum Comparison: == vs equals Explained
- K Value to R Value Calculator: Convert Instantly
- Does Java Have Enums? Yes, and Here’s How They Work
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets SUMIFS: How to Sum with Multiple CriteriaThe SUMIFS function in Google Sheets sums numbers in a range only when they meet multiple criteria. Its…
- Compare Two Documents in Word: A Clear Step-by-Step GuideTo compare two documents in Microsoft Word for Microsoft 365 on Windows, open Word and choose Review >…
- How to Select a Cell and All Cells Below It in ExcelSelecting a single cell is easy, but what if you need to highlight that cell and every cell…
- Conditional Formatting Scatter Plots in ExcelExcel does not apply worksheet conditional-formatting rules directly to scatter-plot markers. To color points dynamically, split the data…
- How to Add Transitions in PowerPoint: Steps and TipsTo add a transition in PowerPoint, select the slide, open the Transitions tab, and choose an effect from…
- Add Slide Numbers in PowerPoint: A Step-by-Step GuideTo add slide numbers in PowerPoint for Microsoft 365 on Windows, go to Insert > Header & Footer,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.