C: A true random number generator: Difference between revisions

From FSDeveloper Wiki
Jump to navigationJump to search
No edit summary
No edit summary
 
(8 intermediate revisions by the same user not shown)
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. The advantage of using this over the more usual time-seeded random number generator is that this can be used on succeeding code lines in a gauge and will return a different number from each line. A time-seeded random number generator will not have had time (!) to update and will give you the same 'random' number for a number of successive calls during a gauge update cycle.


[code]
iMin, iMax = the range of numbers to be randomised
#include <intrin.h>
#pragma intrinsic(__rdtsc)


#include <intrin.h>
#pragma intrinsic(__rdtsc)


// ------------------------------
// ---------------------------
//Randomiser - seed by CPU cycles
// 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;
}


int getRand(int iMin,int iMax)
{
  unsigned __int64 i; 


  i = __rdtsc();
[[Category: Aircraft Design]] [[Category: Panel and Gauge Design]]
  do
    i=(int)rand()%iMax;
  while (i < iMin);
 
  return (int)i;
}
[/code]

Latest revision as of 15:37, 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. The advantage of using this over the more usual time-seeded random number generator is that this can be used on succeeding code lines in a gauge and will return a different number from each line. A time-seeded random number generator will not have had time (!) to update and will give you the same 'random' number for a number of successive calls during a gauge update cycle.

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;
}