View Full Version : ClanLib Random Numer Generator

11-08-2014, 06:13 AM

Clanlib have something like HGE Random_Float or Random_Int functions? For example:

hge -> Random_Int( min, max ) etc.

I cannot find any in reference... :(:(:(

Thanks :)

11-10-2014, 05:07 AM
No, I don't think ClanLib has such a function. However, here's a simple implementation you can use:

#include <cstdlib>
#include <ctime>

float random(float min_value, float max_value)
static bool first_time = true;
if (first_time)
std::srand(std::time(0)); // use current time as seed for random generator

auto t = std::rand() / (double)RAND_MAX;
return min_value + t * (max_value - min_value);

Alternatively, you can use this C++11 syntax:

#include <random>

float random(float min_value, float max_value)
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(min_value, std::nextafter(max_value, std::numeric_limits<float>::max()));
return dis(gen);

What the standard committee was thinking when they made up the second syntax I don't know. Clearly they did not want to lure new developers to C++ with it. ;)

11-10-2014, 08:17 AM
ClanLib does have http://clanlib.org/documentation/3.0/classclan_1_1Random.html for the ClanLib 3 branch.

However, it uses ::CryptGenRandom for Windows and /dev/urandom for Linux for extreme randomness :) , so it probably will be too slow for repetitive calls.

I use Judas's method for non critical randomness