简体   繁体   中英

Java - Generate a random -1 or 1?

Does anyone have a quick way to randomly return either 1 or -1?

Something like this probably works, but seems less than ideal:

return Random.nextDouble() > .5 ? 1 : -1;

how about:

random.nextBoolean() ? 1 : -1;

where random is an instance of java.util.Random

return Random.nextInt(2) * 2 - 1;

new Random.nextInt(2) == 0? -1: 1;

How about

Random r = new Random();
n = r.nextInt(2) * 2 - 1;
return Math.floor(Math.random()*2)*2-1;
import java.util.Random;

public class RandomTest {

public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
        System.out.println(randomOneOrMinusOne());

    }
}
static int randomOneOrMinusOne() {
    Random rand = new Random();
    if (rand.nextBoolean()) return 1;
    else return -1;
}

}

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