Generating random numbers#
int rand(void);
#include <stdio.h>
#include <stdlib.h>
const size_t NUMBER_COUNT = 3;
int main() {
printf("π² ");
for (size_t i = 0; i < NUMBER_COUNT; ++i)
printf("%d ", rand());
}
π² 1804289383 846930886 1681692777
Running the program again:
π² 1804289383 846930886 1681692777
Would you call rand a random number generator?
- pseudorandom number generator
an algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers β also known as deterministic random bit generator. β¦ is not truly random, because it is completely determined by an initial value, β¦ called seed.
Activity 23 (Generating random numbers in an interval)
Write code that generates five random numbers in the range [0, 4] and prints them.
Do you think that this way of generating numbers is useful in our problem?
Generating a different sequence#
void srand(unsigned int seed); // seed random number generator
From rand manual:
If no seed value is provided, the rand() function is automatically seeded with a value of 1.
#include <stdio.h>
#include <stdlib.h>
const size_t NUMBER_COUNT = 3;
void generate_and_print_random_numbers() {
printf("π² ");
for (size_t i = 0; i < NUMBER_COUNT; ++i)
printf("%d ", rand());
puts("");
}
int main() {
generate_and_print_random_numbers();
srand(1);
generate_and_print_random_numbers();
srand(0);
generate_and_print_random_numbers();
srand(2);
generate_and_print_random_numbers();
}
π² 1804289383 846930886 1681692777
π² 1804289383 846930886 1681692777
π² 1804289383 846930886 1681692777
π² 1505335290 1738766719 190686788
On my system, srand(0) and srand(1) have the same effect.
Do you think that this way of generating numbers is useful in our problem? Why?
Generating a different sequence at each run#
Example using the time now as a seed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const size_t NUMBER_COUNT = 3;
void generate_and_print_random_numbers() {
printf("π² ");
for (size_t i = 0; i < NUMBER_COUNT; ++i)
printf("%d ", rand());
puts("");
}
int main() {
generate_and_print_random_numbers();
srand(time(NULL));
generate_and_print_random_numbers();
}
π² 1804289383 846930886 1681692777
π² 1084239639 138562051 1375981530
Running the program again:
π² 1804289383 846930886 1681692777
π² 798292255 1868465636 138433779
Activity 24 (Generating random numbers in an interval for a game)
Modify your code from Activity 23 so that it is useful for our problem