Shani Moyal
Shani Moyal

Reputation: 13

Random values in matrix, how to set them with given probability?

I have this code:

import java.util.Random;

public class Vectors {

    public static int[][] vectors() {
        return vectors(200,150,12345);
    }

    // the function creates an array of vectors
    // size is the number of vectors
    // dim is the dimension
    // seed is for the random number generator
    //
    public static int[][] vectors(int size, int dimension, int seed) {

        Random rng = new Random(seed);
        int[][] answer = new int[size][dimension];

        for(int i=0; i<size; i++) {
            for(int j=0; j<dimension; j++) {
                answer[i][j] = rng.nextInt(20) - 10;
            }
        }

        return answer;
    }

}

I have to Build a random matrix M of 50 columns by 150 rows. The values ​​in the matrix are {-1 / √ 50, 1 / √ 50}, with the probability of 50% for each of the values.

How can i do it by helping with the code below?

Upvotes: 0

Views: 256

Answers (2)

david
david

Reputation: 3228

import java.util.Random;
import java.lang.Math;

public class Vectors {

    public static int[][] vectors() {
        return vectors(200,150);
    }

    public static int[][] vectors(int size, int dimension) {

        Random rng = new Random();
        int[][] answer = new int[size][dimension];
        int rand;

        for(int i=0; i<size; i++) {
            for(int j=0; j<dimension; j++) {
                rand = rng.nextInt(2);
                answer[i][j] = (rand == 0) ? (-1.0/Math.sqrt(50)) : (1.0/Math.sqrt(50));
            }
        }

        return answer;
    }
}

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308141

For each number you need to generate execute this:

  • generate a randum number between 0 and 99 (inclusive).
  • if the number is < 50, use the first value
  • otherwise use the second value.

This algorithm can be applied to all integer percentage values and can easily be extended to more than two options.

Of course in your particular case you could simplify the algorithm to generate a random number between 0 and 1 (inclusive), because you just have 2 equally-weighted options, but the one I show above is the more general one (even more general would be using floating point numbers between 0 and 1 (exclusive)).

Upvotes: 2

Related Questions