Constraint #48
Constraint to generate any Prime No. in a given range #2
To achieve the given constraint, we utilize the prime_number function developed earlier to generate all prime numbers in a specified range. Since directly generating prime numbers is challenging, we use this function to populate a queue with prime numbers and then use these numbers for our variable.
We populate the queue with prime numbers in the pre_randomize() method to ensure it is done before any randomization starts. To specify the range, we use a parameter, assuming MAX_VALUE is set to 100.
We will utilize the inside constraint to ensure that the variable prime_no takes on values only from the prime_q queue.
constraint prime_c { prime_no inside {prime_q} }
This queue is filled with prime numbers in the range of 0 to 100, populated using the prime_number function. This constraint guarantees that prime_no is assigned only prime numbers as the prime_q contains only the prime_no.
Even though you randomize 100 times, the number of prime numbers in a given range does not change. Therefore, it is unnecessary to generate prime numbers for every randomization. Instead, we can populate the prime_q queue once and then use it for multiple randomizations of the variable. To ensure efficiency, we guard the prime number generation function with an if condition that checks if prime_q.size() is 0. If the queue is empty, we populate it with all the prime numbers in the given range. Once the queue is populated, the if condition fails, preventing the function from executing in subsequent randomizations.
if(prime_q.size()==0) begin
prime_number function
end
Check the Below Code:
parameter MAX_VALUE = 100;
class sample;
rand int prime_no;
int prime_q [$];
constraint array_c {
prime_no inside { prime_q};
}
function void pre_randomize();
bit fail_f;
if(prime_q.size()==0) begin
$display("Prime Number Generation in the range %0d",MAX_VALUE);
for(int i=2; i< MAX_VALUE; i++) begin
fail_f = 0;
for(int j=2; j <= i**0.5; j++) begin
if(i%j ==0) begin
fail_f =1;
j = i;
end
end
if(fail_f == 0) prime_q.push_back(i);
end
$display("Prime_queue = %p",prime_q);
end
endfunction
endclass
module top;
sample s=new();
initial begin
$display("######## OUTPUT ########");
repeat(5) begin
assert(s.randomize());
$display("prime_no = %0d",s.prime_no);
end
$display("######## END ########");
end
endmodule
I appreciate your understanding of the methodology we've utilized to handle constraints and their real-world applications. Your support, through likes and reposts, will indeed encourage further exploration. I'm eagerly looking forward to engaging in meaningful discussions with you. Thank you! ????
领英推荐
Decoding of the Above Code :
Parameter Declaration
In Class
Function pre_randomize():
In Module Top
This program generates random prime numbers using a dynamic array "prime_q" to store precomputed prime numbers up to a maximum value defined by "MAX_VALUE". The output displays the generated values of "prime_no".