Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random list of numbers that add up to 1 [duplicate]

Tags:

c++

random

stl

Are there any STL functions that allow one to create a vector with random numbers that add up to 1? Ideally, this would be dependent on the size of the vector, so that I can make the vector size, say, 23 and this function will populate those 23 elements with random numbers between 0 and 1 that all add up to 1.

like image 451
user3193204 Avatar asked Dec 15 '22 02:12

user3193204


2 Answers

One option would be to use generate to fill the vector with random numbers, then using accumulate to sum up the values, and finally dividing all the values in the vector by the sum to normalize the sum to one. This is shown here:

std::vector<double> vec(23);
std::generate(vec.begin(), vec.end(), /* some random source */);
const double total = std::accumulate(vec.begin(), vec.end(), 0.0);
for (double& value: vec) value /= total;

Hope this helps!

like image 171
templatetypedef Avatar answered Dec 27 '22 10:12

templatetypedef


No, but you can do this easily with the following steps:

  1. Fill the vector with random float values, say 0 to 100.
  2. Calculate the sum.
  3. Divide each value by the sum.
like image 38
Matt Avatar answered Dec 27 '22 11:12

Matt