How does the random() function works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

2nd Jan 2019, 10:11 AM
Ritik Pal
Ritik Pal - avatar
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.
2nd Jan 2019, 6:20 PM
AKS
AKS - avatar
+ 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
2nd Jan 2019, 10:25 AM
D_Stark
D_Stark - avatar
+ 8
search for "pseudorandom number generators" on google
2nd Jan 2019, 10:25 AM
Rishi Anand
Rishi Anand - avatar
+ 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.
2nd Jan 2019, 10:28 AM
just trying to think
just trying to think - avatar
+ 5
Thnks to all, it was helpful
2nd Jan 2019, 10:45 AM
Ritik Pal
Ritik Pal - avatar
+ 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)
2nd Jan 2019, 10:43 AM
Игорь Яковенко
Игорь Яковенко - avatar
+ 4
Thanks to all
6th Jan 2019, 8:59 AM
#Ergashbek_Mατκαrιmoν
#Ergashbek_Mατκαrιmoν - avatar