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.

1 Like

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.

class sample;
  rand int arr[];
  
  constraint arr_sum{
    arr.size() == 10;
    arr.sum() with (((item>0) && (item<1000))?1:0)  == arr.size();
    arr.sum() == 100;
  };
  
  function void print();
    $display("array : %p | sum : %3d",arr,arr.sum());
  endfunction: print

endclass: sample


module tb_top();
  sample h;
  
  initial begin
    h = new();
    h.randomize();
    h.print();
  end
endmodule: tb_top

array : '{2, 11, 10, 20, 16, 11, 9, 7, 9, 5} | sum : 100

You definitely need to limit the maximum value of any signed element to avoid overflow and get the intended result.