Write a constraint where you have a 32 bit value bit [31:0] val where you’d want to randomize this to where every randomization would only allow 2 bits to differ from the previous randomization.
Can we solve it by using
$countones(prev_val^cur_val) == 2)
This is so because if only two bits are different in the previous and current value, their XOR should have only two bits set. Any other logic is welcome.
Could you please explain the need for the “const`” in this solution. Where exactly are you comparing the previous randomized value with the current one?
My apologies, I’m more than a little rusty at this, but does the constraint solver efficiently handle the ‘flip two bits’ constraint via $countones? (A long time ago) I would have generated two values between 0 and 31 and inverted those bits.
That might be fine if there were no other constraints on the random value. But what if there was another constraint like cur_val % 5 == 0 in addition to the number of changed bits? Generating the equations for that would be much less efficient.
I was trying this code and ended up with below error
Error-[SE] Syntax error
Following verilog source has syntax error :
“testbench.sv”, 458: token is ‘const’
$countones( const’(cur_val)^cur_val)==2;
^
SystemVerilog keyword ‘const’ is not expected to be used in this context.
I tried this way, and it worked for me. crude, but works if we cant remember solution using XOR!!! Thanks.
class class1;
rand bit [31:0] a;
static bit [31:0] prev_a;
static int cnt;
//make sure number of 1’s are always 2.
constraint c1{
$countones(a) == 2;
}
//constraint the same location to be not 1’b1.
constraint c2{
if(cnt >0)
{
foreach(prev_a[i]) {
if(prev_a[i] ==1){
a[i] != 1;
}
}
}
}
function post_randomize();
cnt = cnt+1;
prev_a = a;