Seed random in 64-bit

With the iPhone 5S update, I want my app to support the new 64-bit processor.

However, the use of 64-bit code can lead to truncation if a larger data type is placed into a smaller one, as in the case of casting a long one in int. Most of the time, this can be easily fixed by simply using a larger data type, but in the case of random number generators that are sometimes sown using the "time (NULL)" function, I cannot do this.

The current code is simple:

srandom(time(NULL)); 

But in XCode 5 with a 64-bit result of the following error: Implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int' . This is because "time (NULL)" returns a long integer, and "srandom" requires an unsigned int. Therefore, there are two options:

  • Convert long integer to unsigned int
  • Replace "time (NULL)" with another function that performs the same task, but returns an unsigned int.

Which one would you recommend and which function should I use for this?

NOTE. I use random () instead of arc4random (), because I also need to be able to generate a random number generator in order to get a repeatable result.

+4
source share
2 answers

time() usually returns the number of seconds from the era (not counting the seconds of the jump), which means that if you use it more than once per second (or two people run the program at the same time), then it will return the same value, which leads to a repeated sequence even if you don’t want it. I recommend that you do not use time(NULL) as a seed even if there is no warning (or error with -Werror) caused by truncation.

You can use arc4random() to get a random seed instead of a time based seed. It also returns a 32-bit unsigned value, which corrects the error you see.

 srandom(arc4random()); 

Perhaps you should switch to Objective-C ++ so that you can use the standard C ++ <random> library, which is much more powerful and flexible, and also allows you to simplify and more direct expression of many ideas than these other libraries

C ++ documentation <random>

+7
source

On iOS, just use arc4random(3) and don't worry about sowing.

+3
source

Source: https://habr.com/ru/post/1501567/


All Articles