Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this number random?

Tags:

c

random

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?

like image 658
jones Avatar asked Apr 30 '11 13:04

jones


People also ask

Why is random number not random?

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.

Why is it impossible to generate true 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).

What makes a number random?

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.

Are RNGS truly random?

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.


2 Answers

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));
like image 75
David Heffernan Avatar answered Oct 14 '22 16:10

David Heffernan


Obligatory XKCD reference:

enter image description here

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.

enter image description here

like image 38
Peter K. Avatar answered Oct 14 '22 17:10

Peter K.