Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: random() function gives me the same random number everytime

Tags:

random

iphone

I am using function random()%x for the generation of a random number, but every time I start the application I see that it creates or generates the same number.

Like I am placing some images randomly based on that random number and I see all the images are placed at the same place no matter how many times I run the application.

like image 551
rkb Avatar asked Sep 19 '09 23:09

rkb


People also ask

Can random numbers repeat?

No, while nothing in computing is truly random, the algorithms that are used to create these "random" numbers are make it seem random so you will never get a repeating pattern.

What happens if you use the random number multiple times in your program?

If you use randomNumber() multiple times in your program it will generate new random numbers every time. You can think of each randomNumber() like a new roll of a die.

Does Google random number generator repeat?

If you choose No your random numbers will be unique and there is no chance of getting a duplicate number. If you choose Yes the random number generator may produce a duplicate number in your set of numbers.

What makes a number random?

A random number is a number chosen as if by chance from some specified distribution such that selection of a large set of these numbers reproduces the underlying distribution. Almost always, such numbers are also required to be independent, so that there are no correlations between successive numbers.


3 Answers

You'll likely have better luck with arc4random(), you don't need to explicitly seed it and it seems to be a "better" random.

like image 71
jbrennan Avatar answered Oct 27 '22 00:10

jbrennan


Obligatory XKCD comic:

alt text

like image 33
Adam Crume Avatar answered Oct 26 '22 23:10

Adam Crume


In your application delegate:

- (void) applicationDidFinishLaunching:(UIApplication *)application 
{
    srandom(time(NULL));

    // ...

    for (int i = 0; i < 100; i++) {
      NSLog(@"%d", random());
    }
}

The reason this works is because pseudorandom number generators require a starting, or seed value. By using the time, you are more likely to get different sequences of "random" numbers upon each execution.

If you do not specify a seed value, the same seed is used on each execution, which yields the same sequence. This is usually undesired behavior, but in some cases it is useful to be able to generate the same sequence, for example, for testing algorithms.

In most cases, you will want to specify a seed value that will change between runs, which is where the current time comes in handy.

like image 36
Alex Reynolds Avatar answered Oct 27 '22 00:10

Alex Reynolds