Sum of elements in dynamic array

Hi,

I am trying to randomize a dynamic array such that the sum of all the elements are equal to a number. I have written a code as below:


class sim_cycles;
  rand int unsigned sim_cyc[];
  int unsigned total_sim_cycles = 1000;
  rand int unsigned total_stripes;
  
  constraint c_sim_cyc {
    sim_cyc.size() == total_stripes;
    //sim_cyc.sum() with (int'(item)) == total_sim_cycles; // This didnt make any difference
    sim_cyc.sum()  == total_sim_cycles; 
    foreach(sim_cyc[i]) {
      sim_cyc[i] >= 50;
      //sim_cyc[i] < total_sim_cycles;
    }
  }

endclass

With the above code I see the following values:

sim_cyc[0]: 2385876847
sim_cyc[1]: 217190463
sim_cyc[2]: 949546727
sim_cyc[3]: 1880026222
sim_cyc[4]: 3157295333

Don’t understand the results.

If I add a constraint sim_cyc[i] < total_sim_cycles, I get a randomization issue

as sim_cyc[0] happens to be equal to 1000, which conflicts with sim_cyc[i] < 1000.

Any help is much appreciated.

Thanks,
Madhu

In reply to mseyunni:

Hi Madhu,

Size of integer is 32bit. You have not mentioned the upper size for each element of array. In this case the elements that are getting generated are bigger numbers and sum is even bigger than 32bit value and while considering the sum the bits higher than 32 are simply ignored. So the sum is still satisfying the constraint. You can try this by manually adding the array elements.

It is always recommended to choose the variables of right size as per the requirement to avoid unexpected behavior. In your case it is bit [9:0] and compare against a variable sum that is of size maximum possible bits required for the sum to accommodate the entire result.

Hope this helps,
Manju

In reply to mbhat:

Hi Manju,

Thanks for your reply. My problem is that the size of total_sim_cycles can be variable based on the user configuration. Hence, I have to take a bigger size as int.

Thanks,
Madhu

In reply to mseyunni:

As a maximum, each sim_cyc element cannot greater than total_sim_cycles.

You need to constrain total_stripes to a minimum of one element to some reasonable maximum. You probably want

constraint c_sim_cyc {
    sim_cyc.size() == total_stripes;
    total_stripes inside {1:10000};
    sim_cyc.sum() with (longint'(item)) == total_sim_cycles; /
    foreach(sim_cyc[i]) {
      sim_cyc[i] >= 50;
      sim_cyc[i] <= total_sim_cycles;
    }
  }