开发者

Java - Generate a random -1 or 1?

开发者 https://www.devze.com 2023-03-13 10:25 出处:网络
Does anyone have a quick way to randomly retu开发者_运维技巧rn either 1 or -1? Something like this probably works, but seems less than ideal:

Does anyone have a quick way to randomly retu开发者_运维技巧rn 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;
}

}

0

精彩评论

暂无评论...
验证码 换一张
取 消