Tapkee
random.hpp
Go to the documentation of this file.
00001 /* This software is distributed under BSD 3-clause license (see LICENSE file).
00002  *
00003  * Copyright (c) 2012-2013 Sergey Lisitsyn
00004  */
00005 
00006 #ifndef TAPKEE_DEFINES_RANDOM_H_
00007 #define TAPKEE_DEFINES_RANDOM_H_
00008 
00009 #include <cstdlib>
00010 #include <algorithm>
00011 #include <limits>
00012 
00013 namespace tapkee
00014 {
00015 
00016 inline IndexType uniform_random_index() 
00017 {
00018 #ifdef CUSTOM_UNIFORM_RANDOM_INDEX_FUNCTION
00019     return CUSTOM_UNIFORM_RANDOM_INDEX_FUNCTION % std::numeric_limits<IndexType>::max();
00020 #else
00021     return std::rand();
00022 #endif
00023 }
00024 
00025 inline IndexType uniform_random_index_bounded(IndexType upper)
00026 {
00027     return uniform_random_index() % upper;
00028 }
00029 
00030 inline ScalarType uniform_random()
00031 {
00032 #ifdef CUSTOM_UNIFORM_RANDOM_FUNCTION
00033     return CUSTOM_UNIFORM_RANDOM_FUNCTION;
00034 #else
00035     return std::rand()/((double)RAND_MAX+1);
00036 #endif
00037 }
00038 
00039 inline ScalarType gaussian_random()
00040 {
00041 #ifdef CUSTOM_GAUSSIAN_RANDOM_FUNCTION
00042     return CUSTOM_GAUSSIAN_RANDOM_FUNCTION;
00043 #else
00044     ScalarType x, y, radius;
00045     do {
00046         x = 2*(std::rand()/((double)RAND_MAX+1)) - 1;
00047         y = 2*(std::rand()/((double)RAND_MAX+1)) - 1;
00048         radius = (x * x) + (y * y);
00049     } while ((radius >= 1.0) || (radius == 0.0));
00050     radius = std::sqrt(-2 * std::log(radius) / radius);
00051     x *= radius;
00052     y *= radius;
00053     return x;
00054 #endif
00055 }
00056 
00057 template <class RAI>
00058 inline void random_shuffle(RAI first, RAI last)
00059 {
00060     std::random_shuffle(first,last,uniform_random_index_bounded);
00061 }
00062 
00063 }
00064 
00065 #endif
00066 
00067 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines