iPhone: random() function gives me the same random

2019-01-18 00:08发布

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.

标签: iphone random
8条回答
太酷不给撩
2楼-- · 2019-01-18 00:48

arc4random will be better solution than rand() or random(). See this.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-18 00:49

Do use srandom (or the equivalent for your random number function of choice), but also use conditionals around it, so that if you are debugging, things always happen the same way. I also tend to put NSLog warnings when doing things like that, so I don't ship brian-dead code.

#if DEBUG==0
srandom(time(NULL));
#else
NSLog(@"Debug build: Random numbers are not random!");
#endif

or

if(!debuggingBuild)
    srandom(time(NULL));
else
    NSLog(@"Debug build: Random numbers are not random!");
查看更多
【Aperson】
4楼-- · 2019-01-18 00:52

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

查看更多
干净又极端
5楼-- · 2019-01-18 01:00

Obligatory XKCD comic:

alt text

查看更多
我命由我不由天
6楼-- · 2019-01-18 01:01

Call srandomdev() first.

srandomdev();
long my_rand = random();

查看更多
【Aperson】
7楼-- · 2019-01-18 01:04

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.

查看更多
登录 后发表回答