How to implement divisible by both 4 and 10 constraint in system verilog?

Viewed 541

I am learning the SystemVerilog constraints concept. As a part of it, I want to have a constraint to randomize the div variable which are divisible by both 4 and 10. This is the code I tried. I am getting display as '0'. Can anyone please help me with what I am missing here?

class div_4_10;
    rand bit [3:0] div;
    constraint constr_4_10 { div % 20 == 0; }
endclass

module div_cons;
    div_4_10 divisible;
    initial begin
      divisible = new();
      for (int i = 0; i <5; i++) begin
        divisible.randomize();
        $display("Divisible by 4 and 10 : %0d", divisible.div);
      end
    end
endmodule
1 Answers

You declared div as 4-bit. This means its values range from 0 to 15. The only value that satisfies the constraint is 0. That is why your code always sets div=0 every time you call randomize.

You need to extend your range. For example, if you change:

rand bit [3:0] div;

to:

rand bit [7:0] div;

Then you should get different values of div. The new range is 8-bit (0 to 255). This is what I get:

Divisible by 4 and 10 : 100
Divisible by 4 and 10 : 60
Divisible by 4 and 10 : 240
Divisible by 4 and 10 : 60
Divisible by 4 and 10 : 20
Related