+ 2
Why does the rand() generally returns 41 as its output everytime first when it is called?
I have seen 2 of the codes in the basic tutorials which has given 41 as output when the rand function is called for the first time in the program. Here I am giving a basic code where I found it...!!! int main() { cout << rand(); } Output: 41
6 Answers
+ 5
rand() function is not completely random. it performs a certain number of calculations to return the pseudo random value. this value is dependant on the previous value generated by the function. this is the reason why the numbers keep cycling upon multiple calls.
the calculations are done on a certain seed (another number) and that seed is used for generating cycling sequences of pseudo random numbers. the seed is provide by the srand() function.
if you change the seed to, for example, 7878 you wouldnt get 41 as the starting number.
for generating more concise random numbers you have to pass a random seed each the program is run. this random seed is usually the machine time in ms. for eg this code would generate more concise random numbers.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int x=10;
while(x--) cout << rand() << endl;
}
+ 5
As for why it is 41:
The math for rand goes like this:
seed = (214013 * seed + 2531011) % 2147483648;
return seed / 65536;
The default value for seed is 1 so
(214013 * 1 + 2531011) % 2147483648 / 65536 = 41
+ 1
Sukruthi Pattabi They are the 3 constants, modulus ( m ), multiplier ( a ) and the increment ( c ) of a linear congruential generator.
https://en.m.wikipedia.org/wiki/Linear_congruential_generator
0
Pseudo-random algorithms
0
What are all those number ?! 214013 ? 2531011?2147483648? Can u please expain ? Dennis
0
Thank you âș Dennis