开发者

How to generate random positive and negative numbers in Java [duplicate]

开发者 https://www.devze.com 2023-01-20 05:26 出处:网络
This q开发者_运维技巧uestion already has answers here: How do I generate random integers within a specific range in Java?
This q开发者_运维技巧uestion already has answers here: How do I generate random integers within a specific range in Java? (72 answers) Closed 4 years ago.

I am trying to generate random integers over the range (-32768, 32767) of the primitive data type short. The java Random object only generates positive numbers. How would I go about randomly creating numbers on that interval? Thanks.


You random on (0, 32767+32768) then subtract by 32768


Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);


public static int generatRandomPositiveNegitiveValue(int max , int min) {
    //Random rand = new Random();
    int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
    return ii;
}


Generate numbers between 0 and 65535 then just subtract 32768


This is an old question I know but um....

n=n-(n*2)


([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

example:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));


(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))


In case folks are interested in the double version (note this breaks down if passed MAX_VALUE or MIN_VALUE):

private static final Random generator = new Random();
public static double random(double min, double max) {
    return min + (generator.nextDouble() * (max - min));
 }
0

精彩评论

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

关注公众号