Srand (time (NULL)) generating similar results

I don’t understand why srand () generates so similar random numbers between runs!

I am trying to run the following code

srand ( time(NULL) );
int x = rand();
cout << x << endl;

However, instead of the correct random number, I always get almost the same number, which slowly grows over time. So I get numbers like: 11669, 11685, 11701, 11714, 11731.

What am I doing wrong?

I am using Visual Studio 2010 SP1.

Ok, is srand () really that simple? I mean, how can anyone call it a random function?

srand(1) => rand() = 41
srand(2) => rand() = 45
srand(3) => rand() = 48
srand(4) => rand() = 51
....
+3
source share
8 answers

-, srand() ; . , rand(), , , , , srand() , srand(). :

srand( time( NULL ) );
rand();
std::cout << rand() << std::endl;

, .

FWIW: Windows, Linux:

int
main()
{
    srand( time( NULL ) );
    int r1 = rand();
    std::cout << r1 << ' ' << rand() << std::endl;
    return 0;
}

10 , :

16391 14979
16394 25727
16397 3708
16404 25205
16407 3185
16410 13933
16417 2662
16420 13411
16427 2139

V++ Windows — rand()

1256800221 286343522
955907524 101665620
1731118607 991002476
1428701871 807009391
44395298 1688573463
817243457 1506183315
507034261 1310184381
1278902902 54648487
2049484769 942368151
1749966544 1833343137

g++ Windows; .

, , , Boost; , .

+8

,

srand ( time(NULL) );
while(condition) {
    int x = rand();
    cout << x << endl;
}

while(condition) {
    srand ( time(NULL) );
    int x = rand();
    cout << x << endl;
}

. , ( ).

+6

, - . , ; . time(NULL) QueryPerformanceCounter() , , - , .

+3

Visual Studio 2010, ++ time() seed srand()

#include <iostream>
#include <random>
#include <cstdlib>
int main()
{
    std::random_device rd;
    std::srand(rd());
    std::cout << std::rand() << '\n';
}

. GNU g++ Linux .

+3

, , , . , , Windows. , srand windows, srand() seed.

#include <windows.h>

int main()
{
  LARGE_INTEGER cicles;

  QueryPerformanceCounter(&cicles);
  srand (cicles.QuadPart);

  return 0;
}
+1

. . :

int FlRandomInt(int LowerLimit, int UpperLimit)
{
 int Result;
 Result = rand();
 Result=LowerLimit+Result*(UpperLimit-LowerLimit)/RAND_MAX;

 return Result;
}

, , , , , , .

, . 100:

srand(( unsigned )time( 0 ) * 100 );

, , , .

+1

@James Kanze , V++ C ( , ). RAND_MAX, .

The solution to the low variance of the initial value is simply to abandon it:

void seed_rand( unsigned int seed )
{
    srand( seed ) ;
    (void)rand() ;
}

int main()
{
    seed_rand( time( NULL ) );
    int r1 = rand();
    std::cout << r1 << ' ' << rand() << std::endl;
    return 0;
}
0
source
#include"stdio.h" //rmv coding for randam number access using c++

 #include"conio.h"

 #include"time.h"

void main()

{

time_t t;

int i;

srand(time(null));

for(i=1;i<=10;i++)

cout<<(unsigned)rand()%100-90<<"\t";

for(i=1;i<=10;i++)

cout<<(char)rand()%100-90<<"\t";


getch();

}
0
source

Source: https://habr.com/ru/post/1670481/


All Articles