0

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?

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


}

}

user3421469
  • 61
  • 3
  • 10
  • The first 10 numbers will be from -100 to 0, the second 10 from 0 to 100. – tbodt Mar 19 '14 at 23:25
  • 1
    Very common question. See this thread on generating numbers in a range. http://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java – JBuenoJr Mar 19 '14 at 23:26
  • You shouldn't Capitalize you variable names someone might mistake them for a class! As for your question you can simply use `Random rand = new Random();` and `int n = rand.nextInt()%101;` the link @JBueno mentioned explains everything you'll need. – Dima Maligin Mar 19 '14 at 23:38

5 Answers5

3

If you want to generate numbers between -100 and 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. The value is then multiplied by 200 and has 100 subtracted from it.

Example:

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

If you want a number between a(smaller) and b(larger), then try:

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

Example (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
aliteralmind
  • 18,274
  • 16
  • 66
  • 102
Blue Ice
  • 7,294
  • 5
  • 30
  • 48
  • @user3421469 I added information on that to the answer. – Blue Ice Mar 19 '14 at 23:41
  • No, this is incorrect. Casting a double or a float to int always rounds towards zero. So this will product a number from -99 to 100, with 0 twice as likely as the other numbers. – Dawood ibn Kareem Mar 20 '14 at 00:06
  • @DavidWallace Can you explain why? I don't fully get it. – Blue Ice Mar 20 '14 at 00:47
  • Well, it works by casting a double between -100 and +100, not inclusive, to int. So the smallest number it produces is `(int)(-99.9999....)`, which is -99, and the largest number it produces is `(int)(99.999999....)`, which is 99. Moreover, if the double that it starts with is between -1 and 1, not inclusive, it will get cast to 0. So it is twice as likely to be 0 as anything else, and it will never be -100 or 100. In my earlier comment, I didn't see that you had also forgotten the +1 that other respondents included. – Dawood ibn Kareem Mar 20 '14 at 00:59
  • I just used the testing app from my answer against your function (just change the body of `getRandomIntBetween` to yours: `return (int)((Math.random()*(max-min))+min);`). It confirms everything said by @DavidWallace. – aliteralmind Mar 20 '14 at 01:24
  • @DavidWallace Edited. Thanks for the information- I was quite thrown off track by your comment about the generator actually reaching 100. Now that you have explained clearly what was wrong, I fixed it. Thanks for the tip. – Blue Ice Mar 20 '14 at 03:03
  • I still don't think this is ever going to put out -100, but at least the other numbers (-99 to 100) will now be evenly distributed. – Dawood ibn Kareem Mar 20 '14 at 03:05
  • @David Whoops- forgot the parenthesis on the top example. I tested it and it should work now :) Thanks again for helping me out here. – Blue Ice Mar 20 '14 at 03:12
1

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. nextFloat will return you a value between 0.0 and 1.0, and multiply that by 200 and subtract 100 and BAM! -100 to 100!

UtMan88
  • 35
  • 7
1

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%
Community
  • 1
  • 1
aliteralmind
  • 18,274
  • 16
  • 66
  • 102
1

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));
    }
}
principal-ideal-domain
  • 3,620
  • 5
  • 27
  • 62
0

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:

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