在SystemVerilog绿皮书中提到了inside,上面说使用inside指定一个集合来约束,如果不做其他约束,所有的元素出现的概率是相等的。
还提到了,inside指定数组作为集合,数组中有重复的数值,即使一个数值重复好几遍,也不会影响他们彼此之间的权重。
看到这里我就好奇,仿照它的例子写一个,测试了一下,我得到的结论恰恰相反,我不知道是什么的问题,是SV的语法有更新,还是其他原因,有没有人可以指点一下。
以下是我测试的代码:
program test;
class Weighted;
rand int val;
int array[] = '{0,1,1,2,2,2,3,3,3,3};
constraint c {
val inside array;
}
endclass
Weighted w;
initial begin
int count[4], summ;
w = new();
repeat (4000) begin
assert (w.randomize());
count[w.val] ++;
end
summ = count.sum();
foreach (count[i]) begin
if (count[i]) begin
$write("count[%0d] = %5d ", i, count[i]);
repeat(count[i] * 50 / summ) $write("*");
$display;
end
end
end
endprogram
以下是仿真结果:
(Specify +UVM_NO_RELNOTES to turn off this notice)
count[0] = 403 *****
count[1] = 827 **********
count[2] = 1165 **************
count[3] = 1605 ********************
$finish at simulation time 0
V C S S i m u l a t i o n R e p o r t
Time: 0 ps
CPU Time: 0.230 seconds; Data structure size: 0.2Mb
【以下回答由 GPT 生成】
根据你提供的代码和仿真结果,可以看出结果与文档描述相反。在这个例子中,元素出现的概率不是相等的。原因可能有以下几点:
权重数组的声明和初始化方式不正确。根据SystemVerilog的语法,应该使用int array[] = {0, 1, 1, 2, 2, 2, 3, 3, 3, 3};
的形式来声明和初始化数组。请注意花括号的使用。
可能存在其他约束条件。你的代码中只显示了val inside array
的约束条件,但实际可能还存在其他约束条件,这些条件可能会影响到生成的随机数的分布。
重新编写一下代码,进行正确的初始化和约束条件的设置:
program test;
class Weighted;
rand int val;
int array[] = {0, 1, 1, 2, 2, 2, 3, 3, 3, 3};
constraint c {
val inside array;
}
endclass
Weighted w;
initial begin
int count[4], summ;
w = new();
repeat (4000) begin
assert (w.randomize());
count[w.val]++;
end
summ = count.sum();
foreach (count[i]) begin
if (count[i]) begin
$write("count[%0d] = %5d ", i, count[i]);
repeat(count[i] * 50 / summ) $write("*");
$display;
end
end
end
endprogram
重新运行仿真,结果应该能够符合文档描述的相等概率分布。如果问题仍然存在,可能还需要检查其他约束条件或相关部分的代码。