Create a random list of numbers that are up to 1

Are there any STL functions that allow you to create a vector with random numbers that are up to 1? Ideally, this will depend on the size of the vector, so I can make the size of the vector say 23, and this function will fill these 23 elements with random numbers between 0 and 1, which all make up to 1.

+4
source share
4 answers

One option would be to use generaterandom numbers to fill the vector, and then use them to accumulatesum the values ​​and finally divide all the values ​​in the vector by the sum to normalize the sum to unity. 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!

+5

, :

  • float, 0 100.
  • .
  • .
+3

. , . (, , .) , , , , .

+2

, . ( ) , , .

- [0, 1), . ( 0 1 ). , , 1. , , 3 , : {0.38, 0.05, 0.96}. 0 1, :

{0, 0.05, 0.38, 0.96, 1}

:

{0.05, 0.33, 0.58, 0.04}

, 1. , , , 1, , ( , ). , . , .

Now, as I said, this approach will give you a different distribution of random numbers than the division method by sum, so do not consider them the same!

+2
source

All Articles