SystemVerilog Reference
inside and dist in Constraints
inside limits a random variable to a set of values. dist also gives each value a weight.
Syntax
constraint c_len { len inside {[1:8], 16}; }
constraint c_kind { kind dist {0 := 8, [1:2] := 1}; }Rules
inside {...}takes values and ranges. Every listed value is equally likely.!(x inside {...})excludes a set.- In
dist,:=gives the weight to each value in a range. - In
dist,:/shares the weight across the range. - A value not listed in a
distis never chosen. - Always check the result of
randomize().
Example
class Packet;
rand bit [4:0] len;
rand bit [1:0] kind;
constraint c_len { len inside {[1:8], 16}; }
constraint c_kind { kind dist {0 := 8, [1:2] := 1}; }
endclass
module tb;
initial begin
Packet p = new();
int bad_len = 0, kind3 = 0;
repeat (200) begin
if (!p.randomize()) $fatal(1, "randomize failed");
if (!(p.len inside {[1:8], 16})) bad_len++;
if (p.kind == 3) kind3++;
end
$display("len outside the set: %0d of 200", bad_len);
$display("kind 3, not in the dist: %0d of 200", kind3);
end
endmodulelen outside the set: 0 of 200
kind 3, not in the dist: 0 of 200Common Mistake
Reading :/ as a weight per value
constraint c { x dist {[1:4] :/ 4, 5 := 4}; }
// 1, 2, 3 and 4 share the weight 4: each gets 1. The value 5 gets 4.With :/ the range as a whole gets the weight. Each value in a wide range becomes rare.
Fix: Use := when every value in the range should carry the full weight.
Learn It Properly
These lessons teach it step by step, with practice problems.
Standard
IEEE 1800-2023, 11.4.13 and 18.5.3.