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

徘徊边缘 提交于 2019-12-17 07:27:42

问题


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.


回答1:


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




回答2:


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



回答3:


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



回答4:


Generate numbers between 0 and 65535 then just subtract 32768




回答5:


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

n=n-(n*2)



回答6:


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



回答7:


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




回答8:


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


来源:https://stackoverflow.com/questions/3938992/how-to-generate-random-positive-and-negative-numbers-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!