Constraint to have sum of elements in an array = 100

Trying to write a constraint where sum of all elements in array is equal to 100

rand bit[31:0] arr[];
constraint ab_k {arr.size() == 3;}
constraint sumk {arr.sum() with (int'(item)) == 100;}

this is resulting in negative values where sum is -100. If I change to rand bit[30:0] arr, it is working as expected. May I know why it is not working when using rand bit[31:0] arr?

Result when using bit[31:0] arr
2727338581
1871618958
3990977153

Result when using bit[30:0] arr
22
5
73

bit[31:0] represents a 32-bit unsigned number. However, when you cast the elements to int using int’(item), it forces a signed interpretation.
For example, if arr = 2727338581 (unsigned), its signed interpretation (int’(item)) would be negative because the MSB (bit 31) is 1.

bit[30:0], on the other hand, is a 31-bit unsigned number, which does not overflow into the sign bit when cast to int, so the constraint works correctly.

1 Like

thanks. could you please let me know how do I make it work with bit[31:0]? I tried removing the int cast and it’s still not working.
constraint sumk {arr.sum() with (item) == 100;}

Adding three 32-bit numbers requires 33 bits to prevent overflow.

constraint sumk {arr.sum() with (33'(item)) == 100;}

You can work out the expression outside of the constraint and display values which would help debug different scenarios.

Add this two Constraint :

  constraint sumk { arr.sum() == 100;}
  constraint element_c { foreach (arr[i]) arr[i] <=100;}

Reference Code