write a c program for random numbers generation without using rand() function. The program is a simple modification of linear feedback shift registers (https://en.wikipedia.org/wiki/Linear-feedback_shift_register). This method uses the fact that when we allocate a memory, system returns the address of the memory address.

c program for random numbers generation without using rand() function

#include<stdio.h>
 
unsigned int lfsr = 0xACE1u;
unsigned int bit,temp=0;
 
unsigned int myrand(unsigned int start_range,unsigned int max_range)
{
    int *p = malloc(sizeof(int));
    temp = temp^(int)p;
    bit  = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
    lfsr = ((bit<<15) | (lfsr>>1) | temp)%max_range;
    while(lfsr< start_range){
        lfsr = lfsr + max_range - start_range;
    }
    return lfsr;
}
 
int main()
{
  int i=0; 
  for(i=0; i <10; i++)
  {
     printf("%u\n",myrand(100,200));
  }
  return 0;
}

C++ 11 based random number generation

#include <iostream>
#include <random>
using namespace std;

int main()
{
   random_device crypto_random_generator;
   uniform_int_distribution<int> int_distribution(0,9);

   int actual_distribution[10] = {0,0,0,0,0,0,0,0,0,0};

   for(int i = 0; i < 10000; i++) {
       int result = int_distribution(crypto_random_generator);
       actual_distribution[result]++;
   }

   for(int i = 0; i < 10; i++) {
       cout << actual_distribution[i] << " ";
   }
   cout << endl;
   return 0;
}

How to Compile and run

#g++ -std=c++11 sample.cpp

#./a.out

Note: The template parameter of std::uniform_int_distribution<T> specifies the type of integer that should be generated. The above c++ 11 based implementation is also known as true random number generator. it is used in cryptography applications.

A random number distribution post-processes the output of an random number engine in such a way that resulting output is distributed according to a defined statistical probability density function.

Ref:

Using rand() function

http://en.cppreference.com/w/cpp/numeric/random



Related Contents to follow