N
N
Nikolai Mokhov2014-09-25 17:29:12
C++ / C#
Nikolai Mokhov, 2014-09-25 17:29:12

How does the compiler get the coefficients to generate pseudo-random numbers?

Hello. I wondered about generating pseudo-random numbers in Visual Studio 2013 in c++ and c#. Information found on the Internet says that many compilers (like Visual Studio?) use the linear congruential method. This method uses coefficients ( link ).
And the question is, how does the compiler set these coefficients? On the basis of what does he receive them, from where does he take them, etc.? As I understand it, they cannot be hard-coded in the compiler, but must be different each time the random is called, otherwise the same sequences will always be obtained.
I would be grateful for information or links.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kyberman, 2014-09-25
@Kyberman

The coefficients are hardcoded. In order for the sequences to change, the initial value is changed (denoted by X 0 on Wikipedia at your link). Usually the current time is used for this.
For example like this:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
   int i, n;
   time_t t;
   
   n = 5;
   
   /* Intializes random number generator */
   srand((unsigned) time(&t));

   /* Print 5 random numbers from 0 to 50 */
   for (i = 0 ; i < n ; i++)
   {
      printf("%d\n", rand() % 50);
   }
   
  return 0;
}

D
Don Kaban, 2014-09-26
@donkaban

it's time to stop googling stdlib.h and start looking at random
www.cplusplus.com/reference/random

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question