SystemVerilog random varaibles ordering
In this article, we will explore the concept of random variable ordering in SystemVerilog and its implications on the outcome of the solver. Through the analysis of an example from the Language Reference Manual (LRM), we aim to gain a deeper understanding of how the ordering of random variables directly influences the final results.
Here are the key points:
Sometimes, however, it is desirable to force certain combinations to occur more frequently. Consider the case where a 1-bit control variable s constrains a 32-bit data value d
class A;
? ? rand bit s;
? ? rand bit [31:0] d;
? ? constraint c { s -> d == 0; }
endclass
By looking at the constraint c we can say “s implies d equals zero.” Although this reads as if s determines d, in fact, s and d are determined together
To calculate the probability of d=0 we need first to calculate the number of legal combinations as follows:
? ? ?So the probability of (d=0) = 1/(2**32 + 1)
But if we introduced a solving order as follows
领英推荐
class B
? rand bit s;
? rand bit [31:0] d;
? constraint c { s -> d == 0; }
? constraint order { solve s before d; }
endclass;
In this case, the order constraint instructs the solver to solve for s before solving for d. The effect is that s is now chosen 0 or 1 with 50/50% probability, and then d is chosen subject to the value of s.
So the probability of (d=0) = 1/2
The other 1/2 is distributed equally between all possible values of d. i.e. the probability of d having any value other than 0 while s = 0 is = 1/2 * (1/(2**32))
Note that Adding this order constraint does not change the set of legal value combinations, but alters their probability of occurrence.
Here is an example that could be used as a proof of concept
//--------------------------------------//
class A;
? rand bit s;
? rand bit [7:0] d;
? constraint c { s -> d == 0; }
endclass
//--------------------------------------//
class B;
? rand bit s;
? rand bit [7:0] d;
? constraint c { s -> d == 0; }
? constraint order { solve s before d; }
endclass
//--------------------------------------//
program test();
? localparam NR_ITER = 100;
?
? A a = new();
? B b = new();
? bit [7:0] ad[$];
? bit [7:0] bd[$];
? bit [7:0] ad_0[$];
? bit [7:0] bd_0[$];
? initial begin
? ?
? ? repeat(NR_ITER) begin
? ? ? a.randomize();
? ? ? ad.push_back(a.d);
? ? ? b.randomize();
? ? ? bd.push_back(b.d);
? ? ? $display("a.s: %0d, a.d : %0d\n", a.s, a.d);
? ? ? $display("b.s: %0d, b.d : %0d\n", b.s, b.d);
? ? ? $display("-----------------------\n");
? ? end
? ? ad_0 = ad.find( x ) with ( x == 0 );
? ? bd_0 = bd.find( x ) with ( x == 0 );
? ? $display("ad_0 size: %0d, bd_0 size : %0d\n", ad_0.size, bd_0.size);
? ? $display("The percentage of a.d=0 is: %f\n, The percentage of b.d=0 is: %f\n", ad_0.size*1.0/NR_ITER, bd_0.size*1.0/NR_ITER);
? end
endprogram;