SpectMorph
|
00001 /* 00002 * Copyright (C) 2010 Stefan Westerfeld 00003 * 00004 * This library is free software; you can redistribute it and/or modify it 00005 * under the terms of the GNU Lesser General Public License as published by the 00006 * Free Software Foundation; either version 3 of the License, or (at your 00007 * option) any later version. 00008 * 00009 * This library is distributed in the hope that it will be useful, but WITHOUT 00010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 00011 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 00012 * for more details. 00013 * 00014 * You should have received a copy of the GNU Lesser General Public License 00015 * along with this program. If not, see <http://www.gnu.org/licenses/>. 00016 */ 00017 00018 #ifndef SPECTMORPH_RANDOM_HH 00019 #define SPECTMORPH_RANDOM_HH 00020 00021 #include <stdlib.h> 00022 #include <stdio.h> 00023 #include <glib.h> 00024 00025 namespace SpectMorph 00026 { 00027 00028 class Random 00029 { 00030 char state[32]; 00031 struct random_data buf; 00032 public: 00033 Random(); 00034 00035 void set_seed (int seed); 00036 00037 inline double 00038 random_double_range (double begin, double end) 00039 { 00040 int32_t r; 00041 random_r (&buf, &r); 00042 00043 const double scale = 1.0 / (double (RAND_MAX) + 1.0); 00044 return r * scale * (end - begin) + begin; 00045 } 00046 inline int32_t 00047 random_int32() 00048 { 00049 int32_t r; 00050 random_r (&buf, &r); 00051 return r; 00052 } 00053 inline void 00054 random_block (size_t n_values, 00055 guint32 *values) 00056 { 00057 guint64 random_data = 0; 00058 int random_bits = 0; 00059 00060 while (n_values--) 00061 { 00062 while (random_bits < 32) 00063 { 00064 random_data ^= guint64 (random_int32()) << random_bits; 00065 random_bits += 31; 00066 } 00067 *values++ = random_data; 00068 random_data >>= 32; 00069 random_bits -= 32; 00070 } 00071 } 00072 }; 00073 00074 } 00075 00076 #endif