For the following piece of code:
#include<stdlib.h>
#include<stdio.h>
int main()
{
int x;
x = rand()%100;
printf("The Random Number is: %i", x);
return 0;
}
It always seems to print the random number as 83. Why is this?
But it turns out some – even most – computer-generated “random” numbers aren't actually random. They can follow subtle patterns that can be observed over long periods of time, or over many instances of generating random numbers.
The Problem. Just by using software, you can't generate truly random numbers because all current software is deterministic, which means that every output in a calculation will be the exact same given the same input (and providing zero input is still considered an input).
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.
Random number generators are typically software, pseudo random number generators. Their outputs are not truly random numbers. Instead they rely on algorithms to mimic the selection of a value to approximate true randomness.
Most random number generators are repeatable. You need to seed the generator before using it which you typically do using the system time.
#include <time.h>
srand(time(NULL));
Obligatory XKCD reference:
As people have said, you need to seed the pseudo random number generator properly.
The trouble is, it still only generates pseudo random numbers. Most "true" random number generators require access to some physical phenomenon that is random in nature (for example, clock skews or temperature fluctuations).
Otherwise, the XKCD reference is not too far from the truth. Nor is Dilbert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With