Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why random of 0 to 4 is 1 most of times?

Tags:

java

I am using a simple random calculations for a small range with 4 elements.

indexOfNext = new Random().nextInt(4); //randomize 0 to 3

When I attach the debugger I see that for the first 2-3 times every time the result is 1.

Is this the wrong method for a small range or I should implement another logic (detecting previous random result)?

NOTE: If this is just a coincidence, then using this method is the wrong way to go, right? If yes, can you suggest alternative method? Shuffle maybe? Ideally, the alternative method would have a way to check that next result is not the same as the previous result.

like image 757
sandalone Avatar asked Apr 07 '14 14:04

sandalone


People also ask

How to get a random number between 0 and 1?

you can use use numpy.random module, you can get array of random number in shape of your choice you want random.randrange (0,2) this works! For reference, the OP wanted a float between 0 and 1 but this will return a choice between integers 0 and 1. How does this answers the question?

What is the probability that the random number x is any particular number?

In other words, the probability that the random number X is any particular number x∈ [0,1] (confused?) should be some constant value; let's use c to denote this probability of any single number. But, now we run into trouble due to the fact that there are an infinite number of possibilities.

How can the probability of a random variable be zero?

A continuous random variable can realise an infinite count of real number values within its support -- as there are an infinitude of points in a line segment. So we have an infinitude of values whose sum of probabilities must equal one. Thus these probabilities must each be infinitesimal. That is the next best thing to actually being zero.

Can random numbers appear in streaks?

Random numbers can appear in streaks; that's part of being random.- love explaining that to the business sometimes. – tymeJV Jul 27, 2018 at 19:32 4 My first run they were both 5000!


2 Answers

Don't create a new Random() each time, create one object and call it many times.

This is because you need one random generator and many numbers from its
random sequence, as opposed to having many random generators and getting
just the 1st numbers of the random sequences they generate.

like image 191
peter.petrov Avatar answered Oct 01 '22 15:10

peter.petrov


You're abusing the random number generator by creating a new instance repeatedly. (This is due to the implementation setting a starting random number value that's a very deterministic function of your system clock time). This ruins the statistical properties of the generator.

You should create one instance, then call nextInt as you need numbers.

like image 30
Bathsheba Avatar answered Oct 01 '22 15:10

Bathsheba