C: A true random number generator: Difference between revisions

From FSDeveloper Wiki
Jump to navigationJump to search
No edit summary
No edit summary
Line 1: Line 1:
This random number generator is about as close as it gets to being truly random. It works by using the number of CPU cycles from startup as the seed.
This random number generator is about as close as it gets to being truly random. It works by using the number of CPU cycles from startup as the seed. The downside is that intrin.h may not be available in a non-Microsoft compiler.
 
iMin, iMax = the range of numbers to be randomised


  #include <intrin.h>
  #include <intrin.h>
  #pragma intrinsic(__rdtsc)
  #pragma intrinsic(__rdtsc)
   
 
  // ---------------------------
// Random number generator
// ---------------------------
  int getRand(int iMin,int iMax)
  int getRand(int iMin,int iMax)
  {
  {

Revision as of 12:55, 30 April 2018

This random number generator is about as close as it gets to being truly random. It works by using the number of CPU cycles from startup as the seed. The downside is that intrin.h may not be available in a non-Microsoft compiler.

iMin, iMax = the range of numbers to be randomised
#include <intrin.h>
#pragma intrinsic(__rdtsc)
// ---------------------------
// Random number generator
// ---------------------------
int getRand(int iMin,int iMax)
{
  unsigned __int64 i;

  i = __rdtsc();
  do
    i=(int)rand()%iMax;
  while (i < iMin);

  return (int)i;
}