简体   繁体   中英

Set parameters for Math.random

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

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();

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM