What is Randcase in SystemVerilog?

randcase is a case statement that randomly selects one of its branches.

Randcase can be used in class or modules.

The randcase item expressions are non-negative integral values that constitute the branch weights.

An item weight divided by the sum of all weights gives the probability of taking that branch.

  • Random Selection: The randcase structure allows the random selection of one out of multiple alternatives.
  • Probabilities: The selection of different cases can be based on predefined probabilities.
  • Procedural Block: randcase can be used inside procedural blocks (e.g., initial, always).

For example:
randcase
3 : x = 1;
1 : x = 2;
4 : x = 3;
endcase

The sum of all weights is 8; therefore, the probability of taking the first branch is (3/8)0.375, the probability


of taking the second is (1/8)0.125, and the probability of taking the third is (4/8)0.5.


If a branch specifies a zero weight, then that branch is not taken.

If all randcase_items specify zero weights, then no branch is taken and a warning can be issued.


The randcase weights can be arbitrary expressions, not just constants.

For example:
byte a, b;
randcase
a + b : x = 1;
a – b : x = 2;
a ^ ~b : x = 3;
12’b800 : x = 4;
endcase

In the preceding example, the first three weight expressions are computed using 8-bit precision, and the fourth


expression is computed using 12-bit precision.

The resulting weights are added as unsigned values using 12-bit precision. The weight selection then uses unsigned


12-bit comparison.


Each call to randcae statement will return a random number in the range from 0 to SUM.

$urandom_range(0,SUM) is used to generate a random number.

module rand_case;
integer x;
integer cnt_1, cnt_2, cnt_3;

initial begin
cnt_1 = 0;
cnt_2 = 0;
cnt_3 = 0;
repeat(100000) begin
randcase
3 : x = 1;
1 : x = 2;
4 : x = 3;
endcase
if(x == 1) begin
cnt_1++;
end
else if(x == 2) begin
cnt_2++;
end
else if(x ==3) begin
cnt_3++;
end
end
$display(“count_1 = %0d, count_2 = %0d, count_3 = %0d”, cnt_1, cnt_2, cnt_3);
$display(“Probability of count_1 = %0f, count_2 = %0f, count_3 = %0f”, (cnt_1/100000.0), (cnt_2/100000.0), (cnt_3/100000.0));
end
endmodule : rand_case

//Output:
// count_1 = 37378, count_2 = 12480, count_3 = 50142
// Probability of count_1 = 0.373780, count_2 = 0.124800, count_3 = 0.501420

 

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top