1

Are you able to set parameters for Math.random?

for (Node car : cars) 
    car.setTranslateX(car.getTranslateX() -  11); 
 if (Math.random() <= 0.06 ) {
    cars.add(spawnCar()); 
    cars.add(SpawnzCar());}
    checkState(); 
    }

I would like Math.random to return a number between 0.02 and 0.06

MikaelF
  • 3,518
  • 4
  • 20
  • 33
  • Possible duplicate of [Math.random() explained](http://stackoverflow.com/questions/7961788/math-random-explained) – MikaelF Feb 01 '17 at 06:10

3 Answers3

4

I would like Math.random to return a number between 0.02 and 0.06

Why not just do

0.02 + 0.04 * Math.random();
James_D
  • 201,275
  • 16
  • 291
  • 322
0

Math.random() is basically a convenience method that uses a single instance of Random. If you want more flexibility, you should use a Random instance instead. But as James_D mentioned, setting a minimum range is usually done by adding the minimum to the random number.

Silverclaw
  • 1,316
  • 2
  • 15
  • 28
0

To get a random uniformly distributed number between real numbers a and b, you can always try

a + (b - a) r

where r is the random number between 0 and 1 you have from Math.random(). No need to put them as parameters.

SamCle88
  • 275
  • 3
  • 9
  • 22