About random values

Possible duplicate:
Getting N random numbers that sum M

Hi I have a question that:

how can i get random values ​​where the sum of all of them is equal 1. for example {0.5,0.5}or {0.25,0.25,0.5}etc. also the number of these values ​​is different every time, once it can be 2and once it can be 3as an example above! thank.

+3
source share
5 answers

I will describe the basic algorithm for you:

  • select the number of random numbers that you will generate that will be added up.

  • generates a lot of random numbers.

  • decide what they should all add.

  • .

  • .

, , , , .

BTW: , , , , . , , .

+12

:

    java.util.Random rand = new java.util.Random();
    final int MAX_SIZE = 100;
    double[] a = new double[1 + rand.nextInt(MAX_SIZE)];

( , 100 .)

:

    for (int i = 0; i < a.length; ++ i)
    {
        a[i] = rand.nextDouble();
    }

( ). :

    double sum = 0.0;
    for (int i = 0; i < a.length; ++ i)
    {
        sum += a[i];
    }

:

    for (int i = 0; i < a.length; ++ i)
    {
        a[i] /= sum; 
    }

, , , . :

    java.util.Random rand = new java.util.Random();
    final int MAX_SIZE = 100;
    double[] a = new double[1 + rand.nextInt(MAX_SIZE)];

    double sum = 0.0;
    for (int i = 0; i < a.length; ++ i)
    {
        a[i] = rand.nextDouble();
        sum += a[i];
    }

    for (int i = 0; i < a.length; ++ i)
    {
        a[i] /= sum; 
    }
+1

, , :

:

r1 = new RandomNumber
r2 = 1 - r1

:

r1 = new RandomNumber
r2 = r1 / 2
r3 = 1 - r1
r1 = r1 / 2

, , - .

0

@dsg, . , .

public static double[] randomDoubles(int size, double sum) {
    double total=0, doubles[]=new double[size];
    for(int i=0;i<size;i++) total += doubles[i] = Math.random();
    for(int i=0;i<size;i++) doubles[i] *= sum/total;
    return doubles;
}
0

n :

r1 = random(0,1)
r2 = random(0, 1-r1)
r3 = random(0, 1-r1-r2)
...
r(n) = 1 - r1-r2-f3...-r(n-1)
0

Source: https://habr.com/ru/post/1779550/


All Articles