title: How to generate a sequence of n random positive integers which add up to some value?
body: <p>I'm trying to generate an array of integers contains randoms adding up to a particular value. Here's my code:</p>
  
  <pre><code>private long[] getRandoms(long size , long sum) throws Exception {
    double iniSum = 0;
    System.out.println("sum = " + sum);
    long[] ret = new long[(int) size];
    for (int i = 0 ; i &lt; ret.length; i++) {
      ret[i] = randomInRange(1, sum);
      iniSum += ret[i];
    }
  
    double finSum = 0;
    for (int i = 0 ; i &lt; ret.length; i++) {
      ret[i] =  Math.round((sum * ret[i]) / iniSum);
      System.out.println("ret[" + i +"] = " + ret[i]);
      finSum += ret[i];
    }
  
    if (finSum != sum) throw new Exception("Could not find " + size + " numbers adding up to " + sum  + " . Final sum = " + finSum);
    return ret;
  }
  
  
  
  private long randomInRange(long min , long max) {
    Random rand = new Random();
    long ret = rand.nextInt((int) (max - min + 1)) + min;
    System.out.println("ret = " + ret);
    return ret;
  } 
  </code></pre>
  
  <p>However, the results are not accurate, for instance:</p>
  
  <blockquote>
    <p>Could not find 100 numbers adding up to 4194304 . Final sum =
    4194305.0</p>
  </blockquote>
  
  <p>I think I'm losing accuracy in this bit:</p>
  
  <pre><code>(sum * ret[i]) / iniSum
  </code></pre>
  
  <p>Can you recommend an alternative algorithm or a fix in my code which can help me achieve this objective?</p>