normalizeSum(0)

how can I transfom a list of random numbers between -1 and 1 so that the sum is zero? is this possible? something like:

var l;
l = {rrand(-1,1.0)} ! 20; // l.sum = somethin g
l.normalizeSum(0); // sum of l now 0

thxs

Something to keep in mind: after normalization the elements will not necessarily still be between 1 and -1.
Here’s one way to do it: (note that due to finite precision for floats, the sum might actually show something like 1e-16 instead of exactly 0)

(
var l;
l = {rrand(-1,1.0)} ! 20;
l = l.normalizeSum - (1/l.size);
l.sum.debug("sum (should be zero)");
l.debug("elements");
)
1 Like

Here’s a variation that keeps all elements in the range -1, 1:

(
var l;
l = {rrand(-1,1.0)} ! 20;
l = l.normalizeSum - (1/l.size);
l = l / (l.abs.maxItem);
l.sum.debug("sum (should be zero)");
l.debug("elements")
)
1 Like