Tuesday, September 4, 2012

مشكلة في توليد الأرقام العشوائية بالجافا


for (int i = 0; i < 1000; i ++ )
        {
            Random r = new Random(i);
            System.out.println(r.nextInt(8));
        }

2 comments:

Unknown said...

I test the code as you write and I note some thing my be explain the result , I think you find it 5 every time.

if you write the code like this
you will get a random numbers "I chance the range to 10 rather than 8"
-------------------------------
for (int i = 0; i < 10; i ++ )
{
Random r = new Random(i);
System.out.println(r.nextInt(10));
}
-------------------------------
but note that if you run the code many times the random numbers generated in the same sequence , the algorithm are fixed , so most probably the value of the number used as a range used in the fixed algorithm to generate the random numbers , and because 8 is a very small number maybe the algorithm has some conditions make the result every time the same small number.

Mohammad Alaggan said...

8 is a power of 2, and the source code for Random shows that powers of 2 are handled by a special case (http://javasourcecode.org/html/open-source/jdk/jdk-5.0/java/util/Random.java.html).