arc4random initialisation - objective-c

I am using random number generation as part of a procedure for minimising a function (using the Nelder-Mead simplex algorithm) in objective-c (for iOS). I have used arc4random() because it seems to be recommended everywhere on the grounds that a) it doesn't need to be seeded and b) it gives higher-quality random numbers than alternatives such as rand() and random(). I generate doubles between 0 and 1 using
#define ARC4RANDOM_MAX 0x100000000
-(double) Rnd{
return (double)arc4random() / (double)ARC4RANDOM_MAX ; }
However, to test the procedure I need to generate repeatable sequences of random numbers, and I can't find any reference to a way to initialise arc4random() to do this. Is it the case that arc4random() cannot be initialised to give a repeatable sequence? If so, how can anyone implement an automated unit test when every test will result in a different answer? Do I need to use the "lower quality" random numbers from random()? Thanks for your help.

The arc4random function gets random numbers from a pool over which it has no control. It has no mechanism to provide repeatability. For unit tests, you'll have to use something else.

Related

Generate random Float number in xCode [duplicate]

This is the first time I'm trying random numbers with C (I miss C#). Here is my code:
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
with this code, I get the same sequence every time I run the code. But it generates different random sequences if I add srand(/*somevalue/*) before the for loop. Can anyone explain why?
You have to seed it. Seeding it with the time is a good idea:
srand()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().
Edit
Due to comments
rand() will return a number between 0 and RAND_MAX (defined in the standard library). Using the modulo operator (%) gives the remainder of the division rand() / 100. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000.
rand() returns pseudo-random numbers. It generates numbers based on a given algorithm.
The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation. This is handy when you need to verify the behavior and consistency of your program.
You can set the "seed" of the random generator with the srand function(only call srand once in a program) One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:
srand(time(NULL)); or srand(getpid()); at the start of the program.
Generating real randomness is very very hard for a computer, but for practical non-crypto related work, an algorithm that tries to evenly distribute the generated sequences works fine.
To quote from man rand :
The srand() function sets its argument
as the seed for a new sequence of
pseudo-random integers to be returned
by rand(). These sequences are
repeatable by calling srand() with the
same seed value.
If no seed value is provided, the
rand() function is automatically
seeded with a value of 1.
So, with no seed value, rand() assumes the seed as 1 (every time in your case) and with the same seed value, rand() will produce the same sequence of numbers.
There's a lot of answers here, but no-one seems to have really explained why it is that rand() always generates the same sequence given the same seed - or even what the seed is really doing. So here goes.
The rand() function maintains an internal state. Conceptually, you could think of this as a global variable of some type called rand_state. Each time you call rand(), it does two things. It uses the existing state to calculate a new state, and it uses the new state to calculate a number to return to you:
state_t rand_state = INITIAL_STATE;
state_t calculate_next_state(state_t s);
int calculate_return_value(state_t s);
int rand(void)
{
rand_state = calculate_next_state(rand_state);
return calculate_return_value(rand_state);
}
Now you can see that each time you call rand(), it's going to make rand_state move one step along a pre-determined path. The random values you see are just based on where you are along that path, so they're going to follow a pre-determined sequence too.
Now here's where srand() comes in. It lets you jump to a different point on the path:
state_t generate_random_state(unsigned int seed);
void srand(unsigned int seed)
{
rand_state = generate_random_state(seed);
}
The exact details of state_t, calculate_next_state(), calculate_return_value() and generate_random_state() can vary from platform to platform, but they're usually quite simple.
You can see from this that every time your program starts, rand_state is going to start off at INITIAL_STATE (which is equivalent to generate_random_state(1)) - which is why you always get the same sequence if you don't use srand().
If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:
"Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".
Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.
Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.
Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.
Random number generators are not actually random, they like most software is completely predictable. What rand does is create a different pseudo-random number each time it is called One which appears to be random. In order to use it properly you need to give it a different starting point.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
/* initialize random seed: */
srand ( time(NULL) );
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
return 0;
}
This is from http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand:
Declaration:
void srand(unsigned int seed);
This function seeds the random number generator used by the function rand. Seeding srand with the same seed will cause rand to return the same sequence of pseudo-random numbers. If srand is not called, rand acts as if srand(1) has been called.
rand() returns the next (pseudo) random number in a series. What's happening is you have the same series each time its run (default '1'). To seed a new series, you have to call srand() before you start calling rand().
If you want something random every time, you might try:
srand (time (0));
Rand does not get you a random number. It gives you the next number in a sequence generated by a pseudorandom number generator. To get a different sequence every time you start your program, you have to seed the algorithm by calling srand.
A (very bad) way to do it is by passing it the current time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
return 0;
}
Why this is a bad way? Because a pseudorandom number generator is as good as its seed, and the seed must be unpredictable. That is why you may need a better source of entropy, like reading from /dev/urandom.
call srand(sameSeed) before calling rand(). More details here.
Seeding the rand()
void srand (unsigned int seed)
This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.
To produce a different pseudo-random series each time your program is run, do srand (time (0))
None of you guys are answering his question.
with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?
From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

How do I seed the rand() function in Objective-C?

Part of what I'm developing is a random company name generator. It draws from several arrays of name parts. I use the rand() function to draw the random name parts. However, the same "random" numbers are always generated in the same sequence every time I launch the app, so the same names always appear.
So I searched around SO, and in C there is an srand() function to "seed" the random function with something like the current time to make it more random - like srand(time(NULL)). Is there something like that for Objective-C that I can use for iOS development?
Why don't you use arc4random which doesn't require a seed? You use it like this:
int r = arc4random();
Here's an article comparing it to rand(). The arc4random() man page says this about it in comparison to rand():
The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8
bit S-Boxes. The S-Boxes can be in about (21700) states. The arc4random() function returns pseudo-
random numbers in the range of 0 to (232)-1, and therefore has twice the range of rand(3) and
random(3).
If you want a random number within a range, you can use the arc4random_uniform() function. For example, to generate a random number between 0 and 10, you would do this:
int i = arc4random_uniform(11);
Here's some info from the man page:
arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.
The functions rand() and srand() are part of the Standard C Library and like the rest of the C library fully available for you to us in iOS development with Objective-C. Note that these routines have been superseded by random() and srandom(), which have almost identically calling conventions to rand() and srand() but produce much better results with a larger period. There is also an srandomdev() routine which initializes the state of the random number generator using the random number device. These are also part of the Standard C Library and available for use on iOS in Objective-C.

Multiple random number generators in Objective C

In my current project I need multiple random number generators because I need to be able to repeat their sequences independently from each other.
So far I did not find any way to achieve this with the standard objective-c random number generators, because they only have one global state.
I think having an random number generator class would solve my problem. I could create several instances which I could reset individually.
Is something like this already available? I was not able to find any random number generator implementation in objective c. I would like to avoid implementing it myself because I have no experience with random numbers and I think it is something that's hard to get right.
I have a random class, based on the Mersenne Twister algorithm, which you can get from my dropbox here.
It's rather old, and isn't compiled for ARC, but that doesn't make it any less good :)
Example code:
MTRandom *randWithSeed = [[MTRandom alloc] initWithSeed:12345];
double d = [rand nextDouble];
int i = [rand nextInt];
MTRandom *timeBasedRand = [MTRandom new]; // seeds with current time
double d2 = [timeBasedRand nextDouble];
int i2 = [timeBasedRand nextInt];
EDIT: If you want to be really cool, you can use this:
Source
Have you tried
srandom(seed);
and then calling
random();
? If the seeds are the same then you should get the same sequence of random numbers.

How to make rand() more likely to select certain numbers?

Is it possible to use rand() or any other pseudo-random generator to pick out random numbers, but have it be more likely that it will pick certain numbers that the user feeds it? In other words, is there a way, with rand() or something else, to pick a pseudo random number, but be able to adjust the odds of getting certain outcomes, and how do you do that if it is possible.
BTW, I'm just asking how to change the numbers that rand() outputs, not how to get the user input.
Well, your question is a bit vague... but if you wanted to pick a number from 0-100 but with a bias for (say) 43 and 27, you could pick a number in the range [0, 102] and map 101 to 43 and 102 to 27. It will really depend on how much bias you want to put in, what your range is etc.
You want a mapping function between uniform density of rand() and the probability density that you desire. The mapping function can be done lots of different ways.
You can certainly use any random number generator to skew the results. Example in C#, since I don't know objective-c syntax. I assume that rand() return a number tween 0 and 1, 0 inclusive and 1 exclusive. It should be quite easy to understand the idear and convert the code to any other language.
/// <summary>
/// Dice roll with a double chance of rolling a 6.
/// </summary>
int SkewedDiceRoll()
{
// Set diceRool to a value from 1 to 7.
int diceRool = Math.Floor(7 * rand()) + 1;
// Treat a value of 7 as a 6.
if (diceRoll == 7)
{
diceRoll = 6;
}
return diceRoll;
}
This is not too difficult..
simply create an array of all possible numbers, then pad the array with extra numbers of which you want to result more often.
ie:
array('1',1','1','1','2','3','4','4');
Obviously when you query that array, it will call "1" the most, followed by "4"
In other words, is there a way, with rand() or something else, to pick a pseudo random number, but be able to adjust the odds of getting certain outcomes, and how do you do that if it is possible.
For simplicity sake, let's use the drand48() which returns "values uniformly distributed over the interval [0.0,1.0)".
To make the values close to one more likely to appear, apply skew function log2():
log2( drand48() + 1.0 ); // +1 since log2() in is [0.0, 1.0) for values in [1.0, 2.0)
To make the values close to zero more likely to appear, use the e.g. exp():
(exp(drand48()) - 1.0) * (1/(M_E-1.0)); // exp(0)=1, exp(1)=e
Generally you need to crate a function which would map the uniformly distributed values from the random function into values which are distributed differently, non-uniformly.
You can use the follwing trick
This example has a 50 percent chance of producing one of your 'favourite' numbers
int[] highlyProbable = new int[]{...};
public int biasedRand() {
double rand = rand();
if (rand < 0.5) {
return highlyProbable[(int)(highlyProbable.length * rand())];
} else {
return (int)YOUR_RANGE * rand();
}
}
In addition to what Kevin suggested, you could have your regular group of numbers (the wide range) chopped into a number of smaller ranges, and have the RNG pick from the ranges you find favorable. You could access these ranges in a particular order, or, you can access them in some random order (but I can assume this wouldn't be what you want.) Since you're using manually specified ranges to be accessed within the wide range of elements, you're likely to see the numbers you want pop up more than others. Of course, this is just how I'd approach it, and it may not seem all that rational.
Good luck.
By definition the output of a random number generator is random, which means that each number is equally likely to occur next (1/10 chance) and you should not be able to affect the outcome.
Of-course, a pseudo-random generator creates an output that will always follow the same pattern for a given input seed. So if you know the seed, then you may have some idea of the output sequence. You can, of-course, use the modulus operator to play around with the set of numbers being output from the generator (eg. %5 + 2 to generate numbers from 2 to 7).

Random Numbers in Objective-C Using Mod Range?

I have read here -- without understanding much -- that it's bad to use mod range. So this typical recommendation for Objective-C
int r = arc4random() % 45;
might be a bad idea to get a number from 0 to 45 (something about the distribution and this formula having a preference for low bits). What should one use in Objective-C?
<sarcasm>
I am so glad to be able to finally learn this stuff after using only high-level languages (Java et. al) all this time. Tomorrow I will try to make fire with two twigs. </sarcasm>
Java is just as high level as Objecive C here - in this case Java' Random.getInt() is the same as arc4random in that they both return a 32-bit pseudo-random number.
The issue raised in the URL (and I have seen elsewhere) is that rand()
could be repeating itself every 32768
values.
Whilst OSX's arc4random could have (2**1700) states.
But as in all uses of pseudo-random generators you need to be aware of their weaknesses before using them e.g. a preference for low bits in some generators and also the comment in the OpenBSD arc4random man page where it says
arc4random_uniform() is recommended
over constructions like ``arc4random()
% upper_bound'' as it avoids "modulo
bias" when the upper bound is not a
power of two.