how do random numbers on computers work?

1.48K views

For example, is there a formula for a random number?

In: 47

75 Answers

Anonymous 0 Comments

There’s no formula for random numbers, as formulas will output the same result for the same input. Computers are deterministic, but random numbers require true randomness, which a function will never provide you with.

So you either use real random number generators that for example listen to cosmic background radiation, but they are slow and more expensive. If security is of high importance something like with will get used.

Or you can use pseudo random number generators. A simple one is a function like Y = (a * X + b) mod c where X is either the seed (for example the current time in milliseconds) or the last result. They will get used in applications where security isn’t as important but speed is, for in video games.

Let’s use an easy example (in the real world we would use larger and better numbers): a = 7, b = 3, c = 5

X = 0 -> 3 mod 5 = 3

X = 3 -> (7*3 + 3) mod 5 = 4

X = 4 -> (7*4 + 3) mod 5 = 1

X = 1 -> (7 + 3) mod 5 = 0

In this example we picked bad numbers as it would just cycle between 3, 4, 1 and 0 without ever producing a 2. You want to set a, b and c to values that result in every possible result coming out with the same frequency and in an order that appears to be random.

As you see it would always produce the same cycle of numbers so a pseudo random number generator will never be completely secure. If you initialize it with for example the current time an attacker could just try to pinpoint that time and end up with the same set of results as your application.

You are viewing 1 out of 75 answers, click here to view all answers.