Algorithm to generate N random numbers between A and B which sum up to X

Posted by Shaamaan on Programmers See other posts from Programmers or by Shaamaan
Published on 2014-08-24T15:30:00Z Indexed on 2014/08/24 16:28 UTC
Read the original article Hit count: 148

Filed under:
|

This problem seemed like something which should be solvable with but a few lines of code.

Unfortunately, once I actually started to write the thing, I've realized it's not as simple as it sounds.

What I need is a set of X random numbers, each of which is between A and B and they all add up to X. The exact variables for the problem I'm facing seem to be even simpler: I need 5 numbers, between -1 and 1 (note: these are decimal numbers), which add up to 1.

My initial "few lines of code, should be easy" approach was to randomize 4 numbers between -1 and 1 (which is simple enough), and then make the last one 1-(sum of previous numbers). This quickly proved wrong, as the last number could just as well be larger than 1 or smaller than -1.

What would be the best way to approach this problem?

PS. Just for reference: I'm using C#, but I don't think it matters. I'm actually having trouble creating a good enough solution for the problem in my head.

© Programmers or respective owner

Related posts about c#

Related posts about algorithms