Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) UbuntuVirtualBoxWindows ::nrand48

 

::nrand48 is a function in the global namespace supplied with some STL's to draw a positive (that is: non-negative) random number uniformly distributed between 0 and 2^31.

 

::nrand48 needs to have a buffer supplied. Nrand48 is identical to ::nrand48.

 

#include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdint.h>

//From http://www.richelbilderbeek.nl/CppNrand48.htm
long int Nrand48(unsigned short int xsubi[3])
{
  //Factor in congruential formula
  static unsigned long long int a = 0x5deece66dull;
  // Additive constant in congruential formula
  static unsigned short int c = 0xb;
  const uint64_t x
    = static_cast<uint64_t>(xsubi[2]) << 32
    | static_cast<uint32_t>(xsubi[1]) << 16
    | xsubi[0];
  const uint64_t y = x * a + c;

  xsubi[0] = y & 0xffff;
  xsubi[1] = (y >> 16) & 0xffff;
  xsubi[2] = (y >> 32) & 0xffff;

  if (sizeof(unsigned short int) == 2)
  {
    return xsubi[2] << 15 | xsubi[1] >> 1;
  }
  else
  {
    return xsubi[2] >> 1;
  }
}

int main()
{
  unsigned short int buffer1[3] = {0,0,0};
  unsigned short int buffer2[3] = {0,0,0};

  for (int i=0; i!=10; ++i)
  {
    const long int a = ::nrand48(buffer1);
    const long int b = Nrand48(buffer2);
    assert(a==b);
    assert(buffer1[0]==buffer2[0]);
    assert(buffer1[1]==buffer2[1]);
    assert(buffer1[2]==buffer2[2]);
    std::cout
      << a << '\t'
      << buffer1[0] << '\t'
      << buffer1[1] << '\t'
      << buffer1[2] << '\t'
      << '\n';
  }
}

 

Screen output:

 

0 0 11 0 0
2116118 2116118 59066 37933 64
89401895 89401895 22845 21582 2728
379337186 379337186 52484 29636 11576
782977366 782977366 58047 37548 23894
196130996 196130996 9566 29032 5985
198207689 198207689 23825 53650 6048
1046291021 1046291021 58952 17562 31930
1131187612 1131187612 48307 6968 34521
975888346 975888346 10818 49077 29781

 

 

 

 

 

Technical facts about source code above

 

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict