SystemVerilog Randomize Array
Most of the array usage application needs randomization of an array. randomization is possible for array size as well as for array elements.
一、constrained randomization of array
- It is possible to get the specific value on randomization, this can be achieved by writing/specifying the constraints.
- During randomization, constraints of size are solved first, and then the elements constraints.
二、Fixed Size Array Randomization
In a fixed size array, randomization is possible only for the array elements. as the size is fixed, it is not possible to change.
三、Generating random value for array elements.
In the below example, random values will be generated for array elements.
- Declare array as rand
- On randomization, the array will get random values
class fs_array;
rand bit [3:0] array1[4];
rand bit [7:0] array2[6];
function void display();
$display("array1 = %p",array1);
$display("array2 = %p",array2);
endfunction
endclass
program fixedsize_array_randomization;
fs_array pkt;
initial begin
pkt = new();
pkt.randomize();
pkt.display();
end
endprogram
Simulator Output:
array1 = ‘{‘he, ‘h4, ‘h4, ‘h8}
array2 = ‘{‘h9b, ‘h9a, ‘h10, ‘h5f, ‘hde, ‘h84}
四、Generate unique elements in an array
In the above example, we have seen randomization with random values. The below example shows the randomization with unique values by using the shuffle array method.
- Constrain array with element value same as an index value
- In post randomization shuffle the array, so that array will not have incremental value.
class fs_array;
rand bit [7:0] array1[6];
constraint array_c {
foreach(array1[i]) {
array1[i] == i;
}
}
function void post_randomize();
array1.shuffle();
endfunction
function void display();
$display("array1 = %p",array1);
endfunction
endclass
program fixedsize_array_randomization;
fs_array pkt;
initial begin
pkt = new();
pkt.randomize();
pkt.display();
end
endprogram
Simulator Output:
array1 = ‘{‘h2, ‘h1, ‘h4, ‘h0, ‘h5, ‘h3}
五、array sum constraint
In the below example, the array is randomized in such a way that the sum of all the elements equals 30.
- declare an array with rand.
- Constraint sum of an array using the array method sum().
class fs_array;
rand bit [7:0] array1[6];
constraint array_c {
array1.sum() == 30;
}
function void display();
$display("array1 = %p",array1);
endfunction
endclass
program fixedsize_array_randomization;
fs_array pkt;
initial begin
pkt = new();
pkt.randomize();
pkt.display();
end
endprogram
Simulator Output:
array1 = ‘{‘h7, ‘h0, ‘h17, ‘h0, ‘h0, ‘h0}