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.
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!
No, but you can do this easily with the following steps:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With