Search code examples
verilogfpgahdl

RANDOM 0, 1, -1 IN VERILOG


I would like to generate random decimal number 0, 1 or -1 in verilog, that I can add it to my basic signal and get some noise on it with it. I tried with

reg [1:0] SIGNAL_noise_ii;
SIGNAL_noise_ii <= {$random}%2;

but it doesnt work the way I want.

Could someone give me advice what to do?

Thanks


Solution

  • How about:

    reg signed [1:0] SIGNAL_noise_ii;
    SIGNAL_noise_ii <= $signed($urandom_range(0,2))-1;
    

    If SIGNAL_noise_ii is required to represent a "random decimal number 0, 1 or -1", it would seem a good idea to make it signed.

    $urandom_range(min,max) generates a random unsigned integer in the range min to max inclusive.

    So, let's used $signed to make that integer signed and then let's subtract 1 from it. Literals with no base (such as 1) are signed in Verilog by default. We need to make everything on the right hand side of the assignment signed, because if mix signed and unsigned quantities in Veriog, unsigned arithmetic is done.

    https://www.edaplayground.com/x/3tCK