简体   繁体   English

Java随机数介于-100和100之间

[英]Java Random number between -100 and 100

I have created this program to print numbers between -100 and 100 but I am wondering if this is the right way to do it or it has to be done between limits (pre-specified) a and b? 我已经创建了此程序来打印-100至100之间的数字,但是我想知道这是否是正确的方法,还是必须在极限值(预先指定)a和b之间完成?

public class RandomNumber {


public static void main (String [] args){


     for (int i = 1; i <= 10 ; i++)
       {
        int Random = (int)(Math.random()*-100);
        System.out.println(Random);
       }
     for (int i = 1; i <= 10 ; i++)
       {
        int Random1 = (int)(Math.random()*100);
        System.out.println(Random1);
       }


}

} }

If you want to generate numbers between -100 and 100: 如果要生成-100到100之间的数字:

public class RandomNumber {


public static void main (String [] args){


     for (int i = 1; i <= 10 ; i++)
       {
        int Random = (int)(Math.random()*(200 + 1)) - 100;
        System.out.println(Random);
       }


    }
}

This works because Math.random() generates a value between 0 and 1 . 这是有效的,因为Math.random()生成介于01之间的值。 The value is then multiplied by 200 and has 100 subtracted from it. 然后将该值乘以200,然后减去100。

Example: 例:

((0.75) * (200 + 1)) - 100 = 150 - 100 = 50

If you want a number between a (smaller) and b (larger), then try: 如果您想要一个介于a (较小)和b (较大)之间的数字,请尝试:

int Random = (int)(Math.random() * (b - a + 1)) + a;

Example ( a = 30, b = 70 ): 例子( a = 30, b = 70 ):

Random = 0
(0)(70 - 30 + 1) + 30 = 0 + 30 = 30

Random = 0.5
(0.5)(70 - 30 + 1) + 30 = 20 + 30 = 50

Random = 1
(0.999999)(70 - 30 + 1) + 30 = 40 + 30 = 70

Best way to do this would be 最好的方法是

Random r = new Random();
int n = -100 + (int)(r.nextFloat() * 200);

Because the range you're going between is 200 units. 因为您要选择的范围是200个单位。 nextFloat will return you a value between 0.0 and 1.0, and multiply that by 200 and subtract 100 and BAM! nextFloat将为您返回0.0到1.0之间的值,并将其乘以200并减去100和BAM! -100 to 100! -100至100!

I think this is simplest: 我认为这是最简单的:

public static final int getRandomBetweenInclusive(int min, int max)  {
   return  (min + (int)(Math.random() * ((max - min) + 1)));
}

Call it with 叫它

int random = RandomNumberUtil.getRandomBetweenInclusive(-100, 100);

It actually comes right from this answer . 它实际上就是这个答案 It's really smart and concise. 这确实很聪明和简洁。


I wrote this test application to confirm it distributes all possibilities evenly: 我编写了这个测试应用程序,以确认它均匀地分布了所有可能性:

  import  java.util.Iterator;
  import  java.util.TreeMap;
  import  java.util.Map;
  import  java.util.List;
  import  java.util.ArrayList;
/**
   <P>{@code java RandomNumberTest}</P>
 **/
public class RandomNumberTest  {
  private static final int tryCount = 1_000_000;
   public static final void main(String[] ignored)  {

     Map<Integer,Integer> randCountMap = new TreeMap<Integer,Integer>();
     for(int i = 0; i < tryCount; i++)  {
        int rand = getRandomBetweenInclusive(-10, 10);
        int value = ((!randCountMap.containsKey(rand)) ? 1
           :  randCountMap.get(rand) + 1);
        randCountMap.put(rand, value);
     }

     Iterator<Integer> allIntItr = randCountMap.keySet().iterator();

     List<NumWithCount> numWcountList = new ArrayList<NumWithCount>(randCountMap.size());

     while(allIntItr.hasNext())  {
        Integer I = allIntItr.next();
        int count = randCountMap.get(I);
        NumWithCount nwc = new NumWithCount(I, count);
        numWcountList.add(nwc);
     }

     Iterator<NumWithCount> intWCountItr = numWcountList.iterator();
     while(intWCountItr.hasNext())  {
        NumWithCount numWCount = intWCountItr.next();
        float pct = (float)numWCount.occurances  / tryCount * 100;
        System.out.println(numWCount.num + ": " + numWCount.occurances + "   " + String.format("%.3f", pct) + "%");
     }
   }
   public static final int getRandomBetweenInclusive(int min, int max)  {
     return  (min + (int)(Math.random() * ((max - min) + 1)));
   }
}
class NumWithCount  {
   public final int num;
   public final int occurances;
   public NumWithCount(int num, int occurances)  {
      this.num = num;
      this.occurances = occurances;
   }
   public String toString()  {
      return  "num=" + num + ", occurances=" + occurances;
   }
}

Output: 输出:

[R:\jeffy\programming\sandbox\xbnjava]java RandomNumberTest 1000000
-10: 47622   4.762%
-9:  48024   4.802%
-8:  47579   4.758%
-7:  47598   4.760%
-6:  47660   4.766%
-5:  47299   4.730%
-4:  47635   4.764%
-3:  47675   4.767%
-2:  47678   4.768%
-1:  47757   4.776%
 0:  47557   4.756%
 1:  47888   4.789%
 2:  47644   4.764%
 3:  47177   4.718%
 4:  47381   4.738%
 5:  47836   4.784%
 6:  47539   4.754%
 7:  47561   4.756%
 8:  47520   4.752%
 9:  47481   4.748%
 10: 47889   4.789%

It's always nice to have a more general function which you can reuse: 拥有可以重用的更通用的功能总是很高兴:

private static int getRandomNumber(int a, int b) {
    if (b < a)
        return getRandomNumber(b, a);
    return a + (int) ((1 + b - a) * Math.random());
}

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        System.out.format("%d ", getRandomNumber(-100, 100));
    }
}

It really depends on what you want to achieve. 这实际上取决于您要实现的目标。 If you want to print numbers between -100 and +100 in the same loop you could do it that way: 如果要在同一循环中打印介于-100到+100之间的数字,可以这样做:

 for (int i = 1; i <= 10 ; i++)
   {
    int random = (int)(Math.random()*200-100);
    System.out.println(random);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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