0

I'm currently trying to make a random number between -0.5 and 0.5 in this way:

public static double RandomNumberGenerator(long seed)
{
    Random r = new Random(seed);
    return r.nextDouble() >= 0.5? 0.5 : -0.5;

    //PRINTING AND USAGE, SHOULD GO ABOVE
    //System.out.println("Object after seed 12222222: " + RandomNumberGenerator(12222222) );
}

Which I then execute like this:

    for (int j = 0; j < weights_one.length ; j++) 
    {
        weights_one[j] = RandomNumberGenerator( System.currentTimeMillis() );
    }

But it's really dysfunctional, because I always end up with weights that will be the same, i.e.

weights_one[0]: -0.5
weights_one[1]: -0.5
weights_one[2]: -0.5
weights_one[3]: -0.5
weights_one[4]: -0.5

which is not good, they should be gausianly distributed, how can I achieve this?

smatthewenglish
  • 2,831
  • 4
  • 36
  • 72

1 Answers1

1

Random class create pseudo random numbers. I found two mistakes in your code:

  1. For every cycle iteration you create one random instance. Just create one at the beginning of the for.
  2. Random generate numbers between [0 ,1]. To translate to the interval [-0.5, 0.5] just subtract 0.5 to random function.

Your code can be replaced with:

Random r = new Random(System.currentTimeMillis());
for (int j = 0; j < weights_one.length ; j++) 
{
    weights_one[j] = r.nextDouble() -0.5;
}
xcesco
  • 4,690
  • 4
  • 34
  • 65