1414#define SIPM_RANDOM_H
1515
1616#include < cmath>
17+ #include < cstring>
1718#include < random>
1819#include < stdint.h>
1920#include < vector>
@@ -48,9 +49,9 @@ namespace SiPMRng {
4849class Xorshift256plus {
4950public:
5051 // / @brief Default contructor for Xorshift256plus
51- Xorshift256plus () { seed (); }
52+ Xorshift256plus () {seed ();}
5253 // / @brief Contructor for Xorshift256plus given a seed value
53- explicit Xorshift256plus (uint64_t aseed) { seed (aseed); }
54+ Xorshift256plus (uint64_t aseed) {seed (aseed);}
5455 // / @brief Returns a pseud-random 64-bits intger
5556 inline uint64_t operator ()() noexcept {
5657 const uint64_t result = s[0 ] + s[3 ];
@@ -66,15 +67,14 @@ class Xorshift256plus {
6667
6768 s[3 ] = (s[3 ] << 45U ) | (s[3 ] >> (64U - 45U ));
6869 return result;
69- }
70- __attribute__ ((hot))
70+ }__attribute__((hot))
71+
7172 // / @brief Jump function for the alghoritm.
7273 /* * Usefull in case the same generator is used in multiple instancies. The
7374 * jump function will make sure that pseudo-random values generated from the
7475 * different instancies are uncorrelated.
7576 */
76- void
77- jump ();
77+ void jump ();
7878 // / @brief Sets a random seed generated with rand()
7979 void seed ();
8080 // / @brief Sets a new seed
@@ -127,17 +127,19 @@ class SiPMRandom {
127127
128128private:
129129 SiPMRng::Xorshift256plus m_rng;
130- static constexpr double M_UINT64_MAX_RCP = 1 / static_cast <double >(UINT64_MAX);
131130};
132131
133132/* * Returns a uniform random in range (0,1)
134133 * Using getting highest 53 bits from a unit64 for the mantissa,
135- * setting the exponent to get values in range (0-1) and type punning
136- * to double
134+ * setting the exponent to get values in range (1-2), subtract 1 and type punning
135+ * to double.
137136 */
138137inline double SiPMRandom::Rand () {
139- uint64_t u = (m_rng () >> 11 ) | 0x3f0000000 ;
140- return *(double *)&u;
138+ double x;
139+ static constexpr uint64_t mask = 0x3ff0000000000000 ;
140+ const uint64_t u = (m_rng () >> 12 ) | mask;
141+ std::memcpy (&x, &u, 8 );
142+ return x - 1 ;
141143}
142144} // namespace sipm
143145#endif /* SIPM_RANDOM_H */
0 commit comments