C/JAVA:
int sum = 0;
for(int i=0;i<3;i++)
sum+=sum++;
Now print the value of sum
Answer...
C:
7
Java:
0
Why?...
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Thursday, June 05, 2008
Friday, October 19, 2007
Wednesday, October 03, 2007
Stupid Me, System.currentTimeMills()
for(int j=0;j<100;j++)
{
java.util.Random rnd = new java.util.Random(System.currentTimeMillis());
for(int i=0;i<100;i++)
{
System.out.print(rnd.nextInt(10)+"");
}
System.out.println();
}
please don't expect the above program to give 100 different sets of 100 random numbers, there will be repetitions like anything. why?
First: for a particular seed a Random number generator should give same set of numbers, when ever it is run,
Second: our computers are fast enough to finish execution in micro seconds
so the generation of 100 numbers takes few micro seconds and the System.currentTimeMills() has resolution in milliseconds so, a week of stupid searching and debugging, here is a post.
how to fix it:-
use new Random(); forget about seed, this produces 100 different sets of 100 random numbers.
{
java.util.Random rnd = new java.util.Random(System.currentTimeMillis());
for(int i=0;i<100;i++)
{
System.out.print(rnd.nextInt(10)+"");
}
System.out.println();
}
please don't expect the above program to give 100 different sets of 100 random numbers, there will be repetitions like anything. why?
First: for a particular seed a Random number generator should give same set of numbers, when ever it is run,
Second: our computers are fast enough to finish execution in micro seconds
so the generation of 100 numbers takes few micro seconds and the System.currentTimeMills() has resolution in milliseconds so, a week of stupid searching and debugging, here is a post.
how to fix it:-
use new Random(); forget about seed, this produces 100 different sets of 100 random numbers.
Blogged with Flock
Subscribe to:
Posts (Atom)