how do random numbers on computers work?

1.42K views

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

In: 47

75 Answers

Anonymous 0 Comments

Complete (theoretical) randomness is hard to achieve.

Computers often generate pseudo random numbers by taking a measurable event and calculating a new value from that seed value in an attempt to give a result that behaves like a random number.

The most common approach is to use a value like the current time to calculate a number between 0 and 1. If you have special requirements for this number you need to look after them yourself.

As a simplified example, lets say I want a random number to approximate a coin flip (two options, heads or tails)

In this case you might choose heads for any value 0.5000 and above, and tails for any value below or equal to 0.4999.

If you want to simulate dice rolls (1,2,3,4,5, or 6) you might take the “random value (0 to 1), multiply by 6 and add 0.5 and then drop the part to the right of the decimal point.

If you are programming in C++ this give a [good intro](https://www.geeksforgeeks.org/rand-and-srand-in-ccpp/)

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