Sometimes, there is a need to generate unique values of the variables using randomization. There are different ways to generate unique values of variables. System Verilog has provided "unique" keyword which can be used to generate unique values in randomization.
Below is the example of randomization:
Example:
Example:
class my_class;
rand bit [1:0] a, b, c;
constraint u { unique {a, b, c};}
endclass
module top();
initial begin
my_class c;
int cntr;
c = new();
for(int i = 0; i < 5; i++) begin
c.randomize();
$display("a=%0d, b=%0d, c = %0d",c.a, c.b, c.c);
if((c.a == c.b) || (c.a == c.c) || (c.b == c.c)) begin
++cntr;
$display("value matched at:%0d", cntr);
end
end
end
endmodule
Output:
a=2, b=3, c = 1
a=0, b=3, c = 1
a=0, b=2, c = 3
a=2, b=1, c = 3
a=2, b=3, c = 1
As shown in above example, "c" is randomized 5 times but non of the fields of "c" has same value.
Note: randc variable shall not be used with unique constraint.
Short and very useful tip! thanks!
ReplyDeleteThanks
DeleteThis comment has been removed by the author.
ReplyDeleteif i modify for loop:
ReplyDeletefor(int i = 0; i < 15; i++) begin
output is:
# a=3, b=2, c = 1
# a=3, b=1, c = 2
# a=3, b=2, c = 0
# a=0, b=1, c = 3
# a=2, b=1, c = 3
# a=0, b=3, c = 2
# a=1, b=3, c = 0
# a=0, b=1, c = 2
# a=0, b=2, c = 3
# a=1, b=3, c = 2
# a=1, b=3, c = 2
# a=3, b=2, c = 0
# a=3, b=1, c = 0
# a=1, b=3, c = 0
# a=0, b=3, c = 1
i m getting fields of "c" with same value.
for example # a=3, b=2, c = 0
plz explain
It depends on the simulator. Here the intention of "unique" keyword is to generate values in such a way that all variables assigned with different values.
Deleterandc also getting the same unique values right.
ReplyDeleteis there any difference between unique and randc?
Hi Ravi,
DeleteSorry for late response.
randc is declared with a variable and every time during randomization of that variable will have different value. It doesn't depends on other variables.
For example, randc bit [1:0] a, b; and if I randomize it 4 times, a and b have values from 0 to 3. But there's possibility that a and b values matches. But if you use "unique" keyword, you will have a and b values from 0 to 3 and they will not match to each other.