I’m working on a project for fun and I need an algorithm to do as follows:
Generate a list of numbers of Length n which add up to x
I would settle for list of integers, but ideally, I would like to be left with a set of floating point numbers.
I would be very surprised if this problem wasn’t heavily studied, but I’m not sure what to look for.
I’ve tackled similar problems in the past, but this one is decidedly different in nature. Before I’ve generated different combinations of a list of numbers that will add up to x. I’m sure that I could simply bruteforce this problem but that hardly seems like the ideal solution.
Anyone have any idea what this may be called, or how to approach it? Thanks all!
Edit: To clarify, I mean that the list should be length N while the numbers themselves can be of any size.
edit2: Sorry for my improper use of ‘set’, I was using it as a catch all term for a list or an array. I understand that it was causing confusion, my apologies.
This is how to do it in Python
Basically you pick n random numbers, compute their sum and compute a scale factor so that the sum will be what you want it to be.
Note that this approach will not produce “uniform” slices, i.e. the distribution you will get will tend to be more “egalitarian” than it should be if it was picked at random among all distribution with the given sum.
To see the reason you can just picture what the algorithm does in the case of two numbers with a prescribed sum (e.g. 1):
The point
Pis a generic point obtained by picking two random numbers and it will be uniform inside the square[0,1]x[0,1]. The pointQis the point obtained by scalingPso that the sum is required to be 1. As it’s clear from the picture the points close to the center of the have an higher probability; for example the exact center of the squares will be found by projecting any point on the diagonal(0,0)-(1,1), while the point(0, 1)will be found projecting only points from(0,0)-(0,1)… the diagonal length issqrt(2)=1.4142...while the square side is only1.0.