Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
11 years ago

How to generate random numbers in Verilog TB?

As we all know there is a system function $random in Verilog, which can be used to generate the random numbers. I used it in my simulation and call $random() 5 times, then I found each time I simulated, the 10 numbers generated by $random() are always same, I mean e.g.:

The 1st simulation:

1 3 5 6 8

The 2nd simulation:

1 3 5 6 8

So it means although in once simulation, it looks like the random numbers are genrated, but in different simulation, these 5 numbers are always same. I guess this is because $random() needs a seed. But how can I generate a seed in Verilog? Or how can I generate random numbers that change simulation by simulation?

Thanks very much.

4 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Verilog behaves this way so if you find a bug, you can repeat the simulation using the exact same set of values and see if you fix eliminates the bug.

    You should call $urandom or $urandom_range(minval,maxval) instead of $random. When you simulate, you can provide a seed using a command switch. In ModelSim/Questa, the switch is -sv_seed random. It will display the random seed used for the simulation so you can repeat it with -sv_seed nnnn.
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    --- Quote Start ---

    Verilog behaves this way so if you find a bug, you can repeat the simulation using the exact same set of values and see if you fix eliminates the bug.

    You should call $urandom or $urandom_range(minval,maxval) instead of $random. When you simulate, you can provide a seed using a command switch. In ModelSim/Questa, the switch is -sv_seed random. It will display the random seed used for the simulation so you can repeat it with -sv_seed nnnn.

    --- Quote End ---

    Thanks for reply, dave. What is main difference between $urandom and $random? The seed?

    Thanks.
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Yes, the initial seed, and the fact that each thread (initial/always block) has an independent seed. $random has only one implicit global seed. See section 18.14 random stability of the 1800-2012 LRM

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    --- Quote Start ---

    Yes, the initial seed, and the fact that each thread (initial/always block) has an independent seed. $random has only one implicit global seed. See section 18.14 random stability of the 1800-2012 LRM

    --- Quote End ---

    Thanks very much, dave.