C ++ random number generator settlement

I have two questions.

  • What other methods exist for generating a pseudo-random number generator in C ++ without using srand(time(NULL))?

  • I asked the first question. I am currently using time for my generator, but the number that the generator returns is always the same. I am sure the reason is that the variable that stores the time is truncated to some extent. (I have a warning message with the message: "Implicit conversion loses its whole precision:" time_t "(aka" long ") for" unsigned int "). I assume this tells me that in essence my seed will not change until next year For my purposes, using the time when my seed will work fine, but I do not know how to get rid of this warning.

I have never received an error message before, so I assume this has something to do with my Mac. This is the 64-bit OS X v10.8. I also use Xcode for recording and compiling, but I had no problems on other computers with Xcode.

Edit: After much study and study of this, I discovered an error that 64-bit Macs have. (Please correct me if I am wrong.) If you try to make your mac select a random number from 1 to 7, using it time(NULL)as a seed, you will always get the number four. Is always. I ended up using mach_absolute_time()to seed my randomizer. Obviously, this removes all the portability of my program ... but I'm just an amateur.

Edit2: Source Code:

#include <iostream>
#include <time.h>

using namespace std;

int main(int argc, const char * argv[]) {

srand(time(NULL));

cout << rand() % 7 + 1;

return 0;
}

, . 3. , ++.

+5
4

1. . , . , .

2. , . :

unsigned int time_ui = unsigned int( time(NULL) );
srand( time_ui );

unsigned int time_ui = static_cast<unsigned int>( time(NULL) );

unsigned int time_ui = static_cast<unsigned int>( time(NULL)%1000 );

, ,

std::cout << time(NULL);
+7

Tl; dr, , , . , - :

for ( ... )
{
   srand(time(NULL));
   whatever = rand();
}

srand(time(NULL));
for ( ... )
{
   whatever = rand();
}
+7

You should see a random time at the beginning of your program:

int main()
{
    // When testing you probably want your code to be deterministic
    // Thus don't see random and you will get the same set of results each time
    // This will allow you to use unit tests on code that use rand().
    #if !defined(TESTING)
    srand(time(NULL));  // Never call again
    #endif

    // Your code here.

}
+3
source

For x86, you can use a direct counter call to the processor’s timestamp rdtscinstead of the TIME (NULL) library function. Below 1) the timestamp is read 2) the RAND seed assembly:

rdtsc
mov edi, eax
call    srand

For C ++, the following should be done with the g ++ compiler.

asm("rdtsc\n"
    "mov edi, eax\n"
    "call   srand");

NOTE. But not recommended if the code is running in a virtual machine.

0
source

All Articles