How to get a random integer in java? - java

I'm trying to get a random integer, but the way I'm doing it takes a really long time to get that random number ( like 10 seconds!)
Random generator=new Random();
do {
id=generator.nextInt();
}
while(id<=0||id>=4);
I'm trying to get a random number between (and include) 0 to 4
This code so far gets the job done, but 10 seconds is too long!
what is a better way to do this?
Thanks!

You want
generator.nextInt(5);
which returns a random integer between 0 and 4. The reason why your original code took so long was because it was generating random integers over and over, until it got one between 1 and 3.
Note that as you were throwing away everything 0 or less, and everything 4 or more, you weren't even getting the range that you expected.
More information on the methods of the Random class can be found at http://docs.oracle.com/javase/7/docs/api/java/util/Random.html

That's because you're generating literally probably billions of random numbers and throwing them away until you get one between 0 and 4. Instead:
id = generator.nextInt(5); // number between 0 and 4, inclusive
In the future, please read the documentation for the classes you're using; this is clearly explained in the Javadoc.

Use Math.random() cast it into int
int i=(int)Math.random()*4;

Just include the upper bound (assuming you want 1, 2, or 3):
id = 1 + generator.nextInt(3);
From the javadoc:
public int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

try this:
Random random = new Random();
random.nextInt(4);

Related

Safely generate random numbers between some range in Java

How do I safely generate a random integer value in a specific range?
I know many people have asked this before, this post for example, but the method doesn't seem to be safe. Let me explain:
The 'Math' library has Math.random() which generates a random value in the range [0, 1). Using that, one can construct an algorithm like
int randomInteger = Math.floor(Math.random() * (Integer.MAX_VALUE - Integer.MIN_VALUE + 1) + Integer.MIN_VALUE)
to generate a random number between Integer.MAX_VALUE and Integer.MIN_VALUE. However, Integer.MAX_VALUE - Integer.MIN_VALUE will overflow.
The goal is not to merely generate random numbers but to generate them evenly, meaning 1 has the same probability to appear as Integer.MAX_VALUE. I know there are work-arounds to this, such as casting large values to long but then the problem again is how to generate a long integer value from Long.MIN_VALUE to Long.MAX_VALUE.
I'm also not sure about other pre-written algorithms as they can overflow too and cause the probability distribution to change. So my question is whether there is a mathematical equation that uses only integers (no casting to long anywhere) and Math.random() to generate random numbers from Integer.MIN_VALUE to Integer.MAX_VALUE. Or if anyone know any random generators that don't get overflow internally?
The 'Math' library have Math.random() which generates a random value in [0, 1) range.
So don't use Math.random() - use this:
Random r = new Random();
int i = r.nextInt();
The docs for nextInt say:
nextInt() - Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. All 2^32 possible int values are produced with (approximately) equal probability.
It appears I misread the question slightly, and you need long not int - luckily the contract is the same.
long l = r.nextLong()
This will quite literally take two ints and jam them together to make a long.
Still better might be to use
java.security.SecureRandom which is a cryptographically strong random number generator (RNG).
Random x = new Random(1000); // code running and generate values 1000
int i = x.nextInt();

Which of these method "java.util.Random class" and "Math.random() method" is faster in generating random number? [duplicate]

This question already has answers here:
Math.random() versus Random.nextInt(int)
(4 answers)
Closed 5 years ago.
As time matter the most in my code so I have asked this.
Actually I have to Generate Random Integer (int) in Java Programming language million of times in a loop so only a simple difference is going to work in this case.
I have to generate random number from 1 to 6 as said inside a loop.
First :- java.util.Random class
This is taken from this taken from here.
I have also posted the Screenshot below this.
import java.util.Random;
static Random randGen = new Random();
int spots;
spots = randGen.nextInt(6) + 1;
Screenshot
Second :- Math.random() method
int n = (int)(6.0 * Math.random()) + 1;
Cast is used as this method always returns a floating point value.
As now, I think you are familiar with the things So here is my question which one is the fastest and why?
Both uses other classes,
Both don't have argument of minimum value like in my case its one.
Random class have a argument of largest value But Math.random() Does not have that.
But on the other hand, in order to use Math.random() we have to use the cast (int) also, as the Random value should be a Integer.
I believe the fastest one is the second one (Math.random()), as you don't have to initialize a class, but I would recommed you to use the Random class, as you can specify the maximun number you want the method to go
Example:
Random rand = new Random();
rand.nextInt(10);
This will give you a number from 0 to 10. If you want another range (say for example from 4 to 12, you have to type:
rand.nextInt(8) + 4;
This will return a number from 0 to 8, and add 4, so you'll get a number between 4 and 12.
In reply to your question, I think the fastest method is the Math.random() one, but the most usefull one is the Random class one

How to change probability of random numbers

First of all, I did a search on this topic but I could not found anything similar to what I'm trying to accomplished, so this could be a duplicate question.
I would like to have a function that returns a number (1 or 2) with a probability of 0.8% for the number one and 0.2% for the number two.
How can I do it?
Generate a random number between 0 and 1. If the number is between 0 and 0.8, return 1. else, return 2:
return rnd.nextFloat() < 0.8 ? 1 : 2;
You just make intervals, and if your random number fits in the interval, you have a hit. In this most simple example, you make intervals 1-4 and 5. So you fetch random number from 1 to 5. if it's a 1-4 (80% probability) you act as it's 1, and if it's 5 (20% probability) you act as it's 2.
For example, make an array of 100 numbers. 20 numbers with number two, and 80 numbers with number one.
Use the Random class to generate a number between 0 and 100. Then you use that number to get the result from the array.
This is just an example, you can use another values in the array.

Trying to create a program that immitates a 6 sided dice using the Math class

I understand I have to use the random method but thats where my understanding ends
The Random class has a nextInt(int) method that makes it easy to select a value:
Random random = new Random(); // ... or possibly reuse an existing Random
int side = random.nextInt(6); // resulting side is in 0...5
In many other languages, there is only a method to obtain an evenly-distributed number between 0 and 1. In those cases, multiplying this value by the size of the range will give you an evenly distributed number in the desired range, and then you simply add an offset to shift the result into the range in question. This is the same principle by which the internals of nextInt() operates.

When using random numbers in Java

After I imported the math class...
Math.random()
I am confused at how to make the range of the numbers. I know you can multiply, and then add/subtract, but the logic is not making sense to me, and I am also not overly sure how to make the range. Can I get some help?
If you want the range [min, max], then you can use this formula:
Math.random() * (max - min) + min
random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Make your own arrangement like if you need it below 50 multiply it by 50.
If you're trying to get a range of integers from 0 to n, then look at java.util.Random nextInt(int n)
Math.random() returns a double in between 0 and 1. So, say you wanted a number between 0 and 10:
double random = Math.random()*10;
Or maybe a range from -10 to 10:
double random = (Math.random()-0.5)*20;
Notice how I did *20 instead of 10. Subtracting 0.5 would then return a value between -0.5 and 0.5, so 0.5*20 = 10 and -0.5*20 = -10.
You have to describe you problem more. Anyway, in Java, there is class which is created specifically for working with Random numbers. Which is java.util.Random. Refer java documentation for more details. It has many methods which helps you to work with random numbers in many ways.
Some of the methods are nextInt(int limit) will give a random value between zero(inclusive) and limit(exclusive). If you need real numbers, then you have nextDouble() which will give a value between 0.0 and 1.0.

Categories

Resources