Wednesday, February 24, 2016

randomization int overflow

The scenario is to randomize a dynamic array with sum=10 and all the elements should be non-zero. The below code should do that but the simulator is not showing right results (i.e elements hold very high values but sum is 10).
Whereas if you use the constraint “_split_arr[i] inside {[1:init_num]};”, it is showing the right results.

module test_randomize;
int unsigned split_arr[];
  
initial begin
//  repeat(10)
  split_randomly(10,split_arr);
end
// splits a number randomly
   function split_randomly(int init_num, ref int unsigned _split_arr[]);
      int num_of_parts;
      num_of_parts = $urandom_range(6, 2);
      std::randomize(_split_arr) with {
         _split_arr.size() == num_of_parts;
         foreach(_split_arr[i]) {
            _split_arr[i] > 0;
//            _split_arr[i] inside {[1:init_num]};
         }
         _split_arr.sum()  == init_num;
      };

      $display("_split_arr.size()=%0d sum=%0d", _split_arr.size(), _split_arr.sum());
         foreach(_split_arr[i])
      $display("_split_arr[%0d]=%0d", i, _split_arr[i]);
   endfunction : split_randomly


endmodule


Results:-
Compiler version J-2014.12-SP2; Runtime version J-2014.12-SP2;  Feb 24 15:40 2016
_split_arr.size()=5 sum=10
_split_arr[0]=819246108
_split_arr[1]=2362606585
_split_arr[2]=3932011010
_split_arr[3]=3575085304
_split_arr[4]=2195952891

           V C S   S i m u l a t i o n   R e p o r t

How does it possible to have big values but their sum is 10 ?

Analysis:-
The problem is overflowing 32 bit value. Randomization adds all int value and does not check overflow, so as long as the final value's 32 bit is 10, it thinks its good and when limiting each number, it gives whats desired. 

We have to be careful with variable bit width when sum() is used in constraints. 

1 comment:

  1. Thanks. This is explained in detail in Chris Spear's book also.

    ReplyDelete