BELFEM 0.9.0
Berkeley Lab Finite Element Framework
Loading...
Searching...
No Matches
random.hpp
Go to the documentation of this file.
1/*
2 * BELFEM -- The Berkeley Lab Finite Element Framework
3 * Copyright (c) 2026, The Regents of the University of California,
4 * through Lawrence Berkeley National Laboratory (subject to receipt of any required
5 * approvals from the U.S. Dept. of Energy). All rights reserved.
6 *
7 * Developers: Christian Messe, Gregory Giard
8 *
9 * See the top-level LICENSE file for the complete license and disclaimer.
10 */
11
12#ifndef BELFEM_RANDOM_HPP
13#define BELFEM_RANDOM_HPP
14
15#include <cstdlib>
16#include <cstring>
17#include <type_traits>
18#include <fstream>
19#include <random>
20#include "typedefs.hpp"
21
22#include "cl_Communicator.hpp"
23#ifdef BELFEM_MPI
25#else
26namespace belfem
27{
28 template < typename T >
29 void
30 random_seed( T & aSeed )
31 {
32 static_assert( std::is_integral< T >::value && std::is_unsigned< T >::value,
33 "random_seed: the seed must be an unsigned integer" );
34
35 std::ifstream tStream ( "/dev/urandom", std::ios::binary );
36
37 // test if stream exists
38 if( tStream )
39 {
40 char tMemblock[ sizeof( T ) ];
41 tStream.read( tMemblock, sizeof( T ) );
42 const bool tOk = tStream.gcount() == std::streamsize( sizeof( T ) );
43 tStream.close();
44
45 if ( tOk )
46 {
47 std::memcpy( &aSeed, tMemblock, sizeof( T ) );
48 return ;
49 }
50 }
51
52 // no random device, or a short read: use the clock
53 aSeed = ( T ) time( NULL ) ;
54 }
55}
56#endif
57namespace belfem
58{
59//------------------------------------------------------------------------------
60
65 inline
66 void
68 {
69#ifdef BELFEM_MPI
70 std::random_device rd;
71 gComm.random().seed(rd()); // Seed once using random device
72#else
73 unsigned int tSeed;
74 random_seed( tSeed );
75 std::srand( tSeed );
76#endif
77 }
78
79//------------------------------------------------------------------------------
80
85 inline real
87 {
88#ifdef BELFEM_MPI
89 std::uniform_real_distribution<real> distribution(0.0, 1.0);
90 return distribution( gComm.random() ); // Generates a real number between 0 and 1
91#else
92 return ( ( real ) std::rand() )/ RAND_MAX ;
93#endif
94 }
95
96//------------------------------------------------------------------------------
97}
98#endif //BELFEM_RANDOM_HPP
belfem::Communicator gComm
Definition belfem.cpp:35
Global MPI communicator manager.
Definition cl_Communicator.hpp:60
std::mt19937 & random()
Definition cl_Communicator.hpp:165
USER GUIDES:
Definition cl_Capacitor.cpp:16
void random_seed(T &aSeed)
Definition random.hpp:30
double real
Definition typedefs.hpp:36
real rand()
a random number between 0 and 1 must call seed first
Definition random.hpp:86