Skip to content

Instantly share code, notes, and snippets.

@KirinDave
Created August 5, 2010 15:47
Show Gist options
  • Select an option

  • Save KirinDave/509919 to your computer and use it in GitHub Desktop.

Select an option

Save KirinDave/509919 to your computer and use it in GitHub Desktop.
Random number in a range. Assumes you have GNU GSL in /usr/local/*
GSL_BUILDFLAGS=-I/usr/local/include -L/usr/local/lib -lgsl
all: rnd+gsl
rnd+gsl: rnd+gsl.c
g++ $(GSL_BUILDFLAGS) -o rnd+gsl rnd+gsl.c
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <sys/time.h>
/* A didactic example of how to generate uniform integers between 1-6.
Please don't ever consider this cryptographically strong; it is not. */
unsigned long cur_usec()
{
struct timeval c;
gettimeofday(&c,0);
return (unsigned long)(c.tv_usec);
}
int rndi_in_range(int lowerb, int upperb, gsl_rng *r)
{
double upperbd = (double)upperb;
return lowerb + floor(upperbd * gsl_rng_uniform(r));
}
int main (void)
{
const gsl_rng_type *T;
gsl_rng *r;
int i, n = 10;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
gsl_rng_set(r, cur_usec());
for (i = 0; i < n; i++)
{
int u = rndi_in_range(1, 6, r);
printf ("%d\n", u);
}
gsl_rng_free(r);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment