-
Notifications
You must be signed in to change notification settings - Fork 23
/
gradilac.h
468 lines (383 loc) · 11.1 KB
/
gradilac.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
* gradilac.h version 4.3.7
*
* The inclusion file for the "Gradilac", a flexible templated C++ PRNG, based
* on the PRVHASH core function. Standalone class, does not require PRVHASH
* header files.
*
* Description is available at https://github.com/avaneev/prvhash
*
* License
*
* Copyright (c) 2022 Aleksey Vaneev
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef GRADILAC_INCLUDED
#define GRADILAC_INCLUDED
#include <stdint.h>
#include <string.h>
#include <math.h>
/**
* Templated PRVHASH core function. For more information, please refer to the
* "prvhash_core64" function in the "prvhash_core.h" file.
*
* @param[in,out] Seed0 The current "Seed" value.
* @param[in,out] lcg0 The current "lcg" value.
* @param[in,out] Hash0 Current hashword in a hashword array.
* @return Current random value.
* @tparam stype State variable type, must be unsigned type, up to 64 bits.
*/
template< typename stype >
static inline stype prvhash_core( stype* const Seed0, stype* const lcg0,
stype* const Hash0 )
{
const int sh = sizeof( stype ) * 4;
stype Seed = *Seed0; stype lcg = *lcg0; stype Hash = *Hash0;
Seed *= (stype) ( lcg * 2 + 1 );
const stype rs = (stype) ( Seed >> sh | Seed << sh );
Hash += (stype) ( rs + (stype) 0xAAAAAAAAAAAAAAAA );
lcg += (stype) ( Seed + (stype) 0x5555555555555555 );
Seed ^= Hash;
const stype out = (stype) ( lcg ^ rs );
*Seed0 = Seed; *lcg0 = lcg; *Hash0 = Hash;
return( out );
}
/**
* Generalized templated PRVHASH-based PRNG class.
*
* Objects of this class do not use memory allocations and can be placed on
* stack (if "hcount" is not large).
*
* Note that random values returned by functions of this class return values
* in the "exclusive" range only, [0; 1) or [0; N). Also note that precision
* of floating-point random numbers depends on the "stype" in use.
*
* @tparam hcount The number of hashwords in array, must be >0. E.g. use 316
* and 64-bit "stype" to match Mersenne Twister's PRNG period.
* @tparam stype State variable type, must be unsigned integer type, up to 64
* bits wide. Using "stype" smaller than 24 bits is not advised.
* @tparam fuse PRVHASH fusing, must be > 0. Should be above 1 if PRNG output
* may be used as entropy input (output feedback), usually in open systems.
* @tparam cs Must be >= 0. If above 0, enable CSPRNG mode. "cs" defines the
* number of additional PRNG rounds and XOR operations, 1 is usually enough.
*/
template< size_t hcount = 1, typename stype = uint64_t, int fuse = 1,
int cs = 0 >
class Gradilac
{
public:
/**
* Constructor. Note that copy-constructor and copy operator remain
* default as class has no complex structures.
*
* @param iseed Initial "small" seed, can be zero.
*/
Gradilac( const stype iseed = 0 )
{
seed( iseed );
}
/**
* Function initializes/reinitializes the PRNG. This is not the on-the-go
* re-seeding. In CSPRNG mode, the "reseed" function should then be
* called.
*
* @param iseed Initial "small" seed, can be zero.
*/
void seed( const stype iseed = 0 )
{
memset( Seed, 0, fuse * sizeof( Seed[ 0 ]));
memset( lcg, 0, fuse * sizeof( lcg[ 0 ]));
memset( Hash, 0, hcount * sizeof( Hash[ 0 ]));
Seed[ 0 ] = iseed;
hpos = 0;
BitPool = 0;
BitsLeft = 0;
// Initialization involving only the first hashword, other zero
// hashwords will be initialized on the go: this approach was
// well-tested, and PRNG does produce a valid random output while
// initializing the hashwords.
int j;
for( j = 0; j < 5; j++ )
{
int i;
for( i = 0; i < fuse; i++ )
{
prvhash_core( Seed + i, lcg + i, Hash + 0 );
}
}
}
/**
* Function re-seeds PRNG on-the-go using a single entropy value. This
* function is not advised for use in CSPRNG mode. This function can be
* used to efficiently adjust initial seed after the default constructor
* call (iseed=0).
*
* @param ent Entropy value (can be any value).
*/
void reseed( const stype ent )
{
Seed[ 0 ] ^= ent;
lcg[ 0 ] ^= ent;
getRaw();
if( fuse > 1 )
{
getRaw();
}
}
/**
* Function re-seeds PRNG, starting from the current state, and using the
* specified data as entropy. This function should be used in CSPRNG mode.
*
* @param data Entropy data block, can be of any length and of any
* statistical quality. Usually it is any sequence of physics-dependent
* data from physical sources like timer, keyboard, mouse, network. Or
* from system's CSPRNG.
* @param dlen Data length, in bytes.
* @param psize Packet size, in bytes, >= 1. Should not exceed the size of
* "stype". The data will be divided into packets of this size per PRNG
* advancement. This value affects initialization overhead. Value of 1 is
* advised for sparsely-random data. High-quality entropy can use
* sizeof( stype ).
*/
void reseed( const void* const data, size_t dlen, const size_t psize = 1 )
{
const uint8_t* d = (const uint8_t*) data;
while( dlen > 0 )
{
size_t l = ( psize > dlen ? dlen : psize );
dlen -= l;
stype p = 0; // Packet.
while( l > 0 )
{
p <<= 8;
p |= *d;
d++;
l--;
}
Seed[ 0 ] ^= p;
lcg[ 0 ] ^= p;
getRaw();
}
// Make hashword array pass to eliminate traces of input entropy.
int i;
for( i = 0; i < hcount + ( hcount > 1 ) + ( fuse > 1 ); i++ )
{
getRaw();
}
}
/**
* @return The next floating-point random number in [0; 1) range.
*/
double get()
{
if( sizeof( stype ) * 8 > 53 )
{
return(( getRaw() >> ( sizeof( stype ) * 8 - 53 )) * 0x1p-53 );
}
else
{
return( getRaw() * im() );
}
}
/**
* @return The next floating-point random number in [0; N1) range.
*/
double get( const double N1 )
{
if( sizeof( stype ) * 8 > 53 )
{
return(( getRaw() >> ( sizeof( stype ) * 8 - 53 )) *
0x1p-53 * N1 );
}
else
{
return( getRaw() * im() * N1 );
}
}
/**
* Operator "object as function", for easier integration, same as the
* get() function.
*/
double operator()()
{
return( get() );
}
/**
* @return The next random integer number in the "raw", stype-value range.
* This is the actual PRNG advancement function.
*/
stype getRaw()
{
stype* h = Hash + hpos;
if( ++hpos == hcount )
{
hpos = 0;
}
int i;
for( i = 0; i < fuse - 1; i++ )
{
prvhash_core( Seed + i, lcg + i, h );
}
stype res = prvhash_core( Seed + i, lcg + i, h );
int j;
for( j = 0; j < cs; j++ )
{
h = Hash + hpos;
if( ++hpos == hcount )
{
hpos = 0;
}
for( i = 0; i < fuse - 1; i++ )
{
prvhash_core( Seed + i, lcg + i, h );
}
res ^= prvhash_core( Seed + i, lcg + i, h );
}
return( res );
}
/**
* @return The next random integer number in [0; N1) range (note the N's
* exclusivity). N1 specifies positive number of discrete bins, and not
* the extreme value.
*/
int getInt( const int N1 )
{
return( (int) get( (double) N1 ));
}
/**
* @return The next squared floating-point random number in [0; 1) range.
* This is Beta distribution, with alpha=0.5, beta=1.
*/
double getSqr()
{
const double v = get();
return( v * v );
}
/**
* @return TPDF random number in the range (-1; 1). Note that this
* function uses an optimized variant, with 32-bit precision, when
* stype=uint64_t.
*/
double getTPDF()
{
if( sizeof( stype ) == 8 )
{
const stype rv = getRaw();
return(( (int64_t) ( rv >> 32 ) - (int64_t) (uint32_t) rv ) *
0x1p-32 );
}
else
if( sizeof( stype ) * 8 > 53 )
{
const double v1 = get();
const double v2 = get();
return( v1 - v2 );
}
else
{
const double v1 = (double) getRaw();
const double v2 = (double) getRaw();
return(( v1 - v2 ) * im() );
}
}
/**
* Function generates a Gaussian (normal)-distributed pseudo-random number
* with mean=0 and std.dev=1.
*
* Algorithm is adopted from "Leva, J. L. 1992. "A Fast Normal Random
* Number Generator", ACM Transactions on Mathematical Software, vol. 18,
* no. 4, pp. 449-453".
*/
double getNorm()
{
double q, u, v;
do
{
u = get();
v = get();
if( u == 0.0 || v == 0.0 )
{
u = 1.0;
v = 1.0;
}
v = 1.7156 * ( v - 0.5 );
const double x = u - 0.449871;
const double y = fabs( v ) + 0.386595;
q = x * x + y * ( 0.19600 * y - 0.25472 * x );
if( q < 0.27597 )
{
break;
}
} while( q > 0.27846 || v * v > -4.0 * log( u ) * u * u );
return( v / u );
}
/**
* Function generates a Gaussian (normal)-distributed pseudo-random number
* with the specified mean and std.dev.
*/
double getNorm( const double mean, const double stddev )
{
return( mean + stddev * getNorm() );
}
/**
* @return The next random bit from the bit pool. Usually used for
* efficient 50% probability evaluations.
*/
int getBit()
{
if( BitsLeft == 0 )
{
BitPool = getRaw();
const int b = (int) ( BitPool & 1 );
BitsLeft = sizeof( stype ) * 8 - 1;
BitPool >>= 1;
return( b );
}
const int b = (int) ( BitPool & 1 );
BitsLeft--;
BitPool >>= 1;
return( b );
}
/**
* @return PRNG period's exponent (2^N) estimation.
*/
static size_t getPeriodExp()
{
return(( fuse * 8 + fuse * 4 + hcount * 8 ) * sizeof( stype ) -
hcount - cs );
}
protected:
stype Seed[ fuse ]; ///< PRNG seeds (>1 - fused).
stype lcg[ fuse ]; ///< PRNG lcg (>1 - fused).
stype Hash[ hcount ]; ///< PRNG hash array.
size_t hpos; ///< Hash array position (increments linearly, resets to 0).
stype BitPool; ///< Bit pool, optional feature.
int BitsLeft; ///< The number of bits left in the bit pool.
/**
* @return Inverse multiplier to scale stype's value range to [0; 1)
* range.
*/
static double im()
{
static const double v = 0.5 / ( 1ULL << ( sizeof( stype ) * 8 - 1 ));
return( v );
}
};
#endif // GRADILAC_INCLUDED