+ 9

# How does the random() function works?

I have seen many codes in many languages using these functions. How does the computer decide to choose between 0 and 1 randomly. Or any given set of number how does it randomly selects any one of it.

7 Answers

+ 14

Rand() function in C, C++ or Random.Next() in C# uses an algorithm called “Pseudo Random Number Generator algorithm”.
All calculations are based on seed number which is like an initial number to begin with. If we define a seed for the same sequence of methods we will get the same results.
Every Pseudo Random Number algorithm has a period after which the same sequence may repeat.
More on Pseudo Random Number algorithms here:
https://en.m.wikipedia.org/wiki/...
Because the Pseudo Random Number algorithms have a small period, hence they are not cryptographically secure.

+ 11

Math.random() returns a pseudo random number between 0.0 and 1.0 so when you multiply this by a number for example Math.random()*255 a random number is returned to the random function and then multiplied by the right operand
So it would look somthimg like this once called
Math.random(returned 0.5)*100 which would equal 50

+ 8

search for "pseudorandom number generators" on google

+ 8

Hello,
Python random() uses Mersenne Twister.
The Mersenne Twister is a pseudorandom number generator (PRNG). It is by far the most widely used general-purpose PRNG. Its name derives from the fact that its period length is chosen to be a Mersenne prime.

+ 5

Thnks to all, it was helpful

+ 4

It is better to search this information on the Internet, in different languages this function is implemented in different ways, and it is constantly being improved. in fact, this is a pseudo-random, the formula can use constant values, the current time, the frequency of your processor and much more, the more entropy sources the better (the function is more cryptographically stable). nobody will tell you the formula)) although there was a case when someone provided a code that in 70-80% of cases predicted the value that the random function would give (I don’t remember for which language)

+ 4

Thanks to all