mxlib
c++ tools for analyzing astronomical data and other tasks by Jared R. Males. [
git repo
]
randomSeed.hpp
Go to the documentation of this file.
1
/** \file randomSeed.hpp
2
* \author Jared R. Males
3
* \brief Defines a random number seed generator
4
* \ingroup gen_math_files
5
*
6
*/
7
8
//***********************************************************************//
9
// Copyright 2015, 2016, 2017, 2020 Jared R. Males (jaredmales@gmail.com)
10
//
11
// This file is part of mxlib.
12
//
13
// mxlib is free software: you can redistribute it and/or modify
14
// it under the terms of the GNU General Public License as published by
15
// the Free Software Foundation, either version 3 of the License, or
16
// (at your option) any later version.
17
//
18
// mxlib is distributed in the hope that it will be useful,
19
// but WITHOUT ANY WARRANTY; without even the implied warranty of
20
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
// GNU General Public License for more details.
22
//
23
// You should have received a copy of the GNU General Public License
24
// along with mxlib. If not, see <http://www.gnu.org/licenses/>.
25
//***********************************************************************//
26
27
#ifndef mx_math_randomSeed_hpp
28
#define mx_math_randomSeed_hpp
29
30
31
#include <unistd.h>
32
#include <fcntl.h>
33
34
35
#include "../mxError.hpp"
36
37
38
39
namespace
mx
40
{
41
namespace
math
42
{
43
44
///Get a value to use as a random seed
45
/** On Linux systems, uses /dev/urandom to populate the value with sizeof(intT) bytes.
46
* Otherwise, uses time(0) to get time since the epoch.
47
*
48
* \returns 0 on success.
49
* \returns -1 on error.
50
*
51
* \tparam intT is the integer type of seeval.
52
*
53
* \ingroup random
54
*
55
*/
56
template
<
typename
int
T>
57
int
randomSeed
(intT & seedval
/**< [out] will be populated with the seed.*/
)
58
{
59
#ifdef __linux__
60
61
int
fd;
62
63
errno = 0;
64
fd = open(
"/dev/urandom"
, O_RDONLY);
65
66
if
(fd < 0)
67
{
68
mxPError(
"randomSeed"
, errno,
"error opening /dev/urandom"
);
69
70
return
-1;
71
}
72
73
seedval = 0;
74
75
errno = 0;
76
int
rv = ::read(fd, &seedval,
sizeof
(intT));
77
78
79
if
(rv < 0)
80
{
81
mxPError(
"randomSeed"
, errno,
"Error on read from /dev/urandom."
);
82
close(fd);
83
return
-1;
84
}
85
86
close(fd);
87
88
int
sz =
sizeof
(intT);
89
90
if
(rv < sz)
91
{
92
mxError(
"randomSeed"
, MXE_FILERERR,
"Read from /dev/urandom did not return enough bytes"
);
93
94
return
-1;
95
}
96
97
return
0;
98
99
100
#endif
//__linux__
101
102
103
seedval = time(0);
104
105
return
0;
106
107
}
108
109
}
//namespace math
110
}
//namespace mx
111
112
113
#endif
//mx_math_randomSeed_hpp
mx::math::randomSeed
int randomSeed(intT &seedval)
Get a value to use as a random seed.
Definition:
randomSeed.hpp:57
mx
The mxlib c++ namespace.
Definition:
mxError.hpp:107
math
randomSeed.hpp
Generated on Sun Nov 26 2023 10:58:11 for mxlib by
1.9.1