Integer dynamic array sum constraint not working

hi,
can someone explain why the sum constraint is not getting applied ?

class dynamic_array;
  rand int array[  ];
  int sum;
  
  constraint size_c  { array.size() inside {[4:10]}; }
  constraint array_c { foreach(array[i]) array[i] > 0;}
  constraint array_sum {array.sum() == sum;}
  
  
  function void post_randomize();
   // array.shuffle();  
  endfunction
  
  function void display();
    $display("array size is = %0d",array.size());
    $display("sum = %0d",sum);
    $display("array = %p",array);
  endfunction
  
endclass

program dynamic_array_randomization;
  dynamic_array pkt;

  initial begin
    pkt = new();
    pkt.sum=100;
    pkt.randomize();
    pkt.display();   
  end
endprogram

array size is = 5
sum = 100
array = '{555550237, 51794743, 886026138, 2100062112, 701534166}

Why are the individual elements so huge ? their sum should be =100.

The sum constraint is being applied. When you add large numbers, they will overflow, with the truncated result being equal to ‘sum’.

You should change your constraint:

constraint array_c { foreach(array[i]) array[i] inside {[0:sum]};}
1 Like

Please pay attention, your array elements are represented by int:
a signed 2-state variable of size 32 bits
-2^31 to 2^31-1

Do you really need such type to represent the elements?

1 Like

Thank you !

this was a practice code for learning constraints.