tensor-0.1.0
 All Data Structures Namespaces Functions Variables Typedefs Enumerations Enumerator Groups Pages
rand.h
1 // -*- mode: c++; fill-column: 80; c-basic-offset: 2; indent-tabs-mode: nil -*-
2 /*
3  Copyright (c) 2010 Juan Jose Garcia Ripoll
4 
5  Tensor is free software; you can redistribute it and/or modify it
6  under the terms of the GNU Library General Public License as published
7  by the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Library General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License along
16  with this program; if not, write to the Free Software Foundation, Inc.,
17  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 
20 #ifndef TENSOR_RAND_H
21 #define TENSOR_RAND_H
22 
23 #include <tensor/numbers.h>
24 
25 namespace tensor {
26 
31 void rand_reseed();
32 
39 template<class number> number rand() {
40  return static_cast<number>(rand<double>());
41 }
42 
43 template<> int rand<int>();
44 template<> unsigned int rand<unsigned int>();
45 template<> long rand<long>();
46 template<> unsigned long rand<unsigned long>();
47 template<> float rand<float>();
48 template<> double rand<double>();
49 template<> cdouble rand<cdouble>();
50 
51 template<class real_number> inline real_number rand(real_number upper_limit) {
52  return static_cast<real_number>(upper_limit * rand<double>());
53 }
54 
55 template<class real_number> inline real_number rand(real_number lower_limit,
56  real_number upper_limit) {
57  return rand<real_number>(upper_limit - lower_limit) + lower_limit;
58 }
59 
60 template<> inline int rand<int>(int upper) {
61  if (upper)
62  return rand<unsigned int>() % upper;
63  return 0;
64 }
65 
66 template<> inline int rand<int>(int lower, int upper) {
67  return rand<int>(upper - lower) + lower;
68 }
69 
70 template<> inline long rand<long>(long upper) {
71  if (upper)
72  return (long)rand<unsigned long>() % upper;
73  return 0;
74 }
75 
76 template<> inline long rand<long>(long lower, long upper) {
77  return rand<long>(upper - lower) + lower;
78 }
79 
80 template<> inline unsigned long rand<unsigned long>(unsigned long upper) {
81  if (upper)
82  return rand<unsigned long>() % upper;
83  return 0;
84 }
85 
86 template<> inline unsigned long rand<unsigned long>(unsigned long lower, unsigned long upper) {
87  return rand<unsigned long>(upper - lower) + lower;
88 }
89 } // tensor
90 
91 #endif // !TENSOR_RAND_H