Skip to content

Instantly share code, notes, and snippets.

@ahmadyan
Created September 2, 2012 05:28
Show Gist options
  • Save ahmadyan/3595079 to your computer and use it in GitHub Desktop.
Save ahmadyan/3595079 to your computer and use it in GitHub Desktop.
Utility
#include "utility.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
namespace utility {
using namespace std;
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
double unifRand()
{
return rand() / double(RAND_MAX);
}
//
// Generate a random number in a real interval.
// param a one end point of the interval
// param b the other end of the interval
// return a inform rand numberin [a,b].
double unifRand(double a, double b)
{
return (b-a)*unifRand() + a;
}
//
// Generate a random integer between 1 and a given value.
// param n the largest value
// return a uniform random value in [1,...,n]
long unifRand(long n)
{
if (n < 0) n = -n;
if (n==0) return 0;
/* There is a slight error in that this code can produce a return value of n+1
**
** return long(unifRand()*n) + 1;
*/
//Fixed code
long guard = (long) (unifRand() * n) +1;
return (guard > n)? n : guard;
}
//Knuth method, from http://c-faq.com/lib/gaussian.html
double gaussrand(){
static double V1, V2, S;
static int phase = 0;
double X;
if(phase == 0){
do {
double U1 = (double)rand() / RAND_MAX;
double U2 = (double)rand() / RAND_MAX;
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1 || S == 0);
X = V1 * sqrt(-2 * log(S) / S);
} else
X = V2 * sqrt(-2 * log(S) / S);
phase = 1 - phase;
return X;
}
//
// Reset the random number generator with the system clock.
void seed()
{
srand(time(0));
}
}
#pragma once
namespace utility {
double unifRand();
double unifRand(double a, double b);
long unifRand(long n);
gaussrand();
void seed();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment