1 /* boost random/normal_distribution.hpp header file
3 * Copyright Jens Maurer 2000-2001
4 * Distributed under the Boost Software License, Version 1.0. (See
5 * accompanying file LICENSE_1_0.txt or copy at
6 * http://www.boost.org/LICENSE_1_0.txt)
8 * See http://www.boost.org for most recent version including documentation.
13 * 2001-02-18 moved to individual header files
16 #ifndef BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP
17 #define BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP
19 #include <boost/config/no_tr1/cmath.hpp>
22 #include <boost/limits.hpp>
23 #include <boost/static_assert.hpp>
24 #include <boost/random/detail/config.hpp>
28 // deterministic Box-Muller method, uses trigonometric functions
29 template<class RealType
= double>
30 class normal_distribution
33 typedef RealType input_type
;
34 typedef RealType result_type
;
36 #if !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300)
37 BOOST_STATIC_ASSERT(!std::numeric_limits
<RealType
>::is_integer
);
40 explicit normal_distribution(const result_type
& mean_arg
= result_type(0),
41 const result_type
& sigma_arg
= result_type(1))
42 : _mean(mean_arg
), _sigma(sigma_arg
), _valid(false)
44 assert(_sigma
>= result_type(0));
47 // compiler-generated copy constructor is NOT fine, need to purge cache
48 normal_distribution(const normal_distribution
& other
)
49 : _mean(other
._mean
), _sigma(other
._sigma
), _valid(false)
53 // compiler-generated copy ctor and assignment operator are fine
55 RealType
mean() const { return _mean
; }
56 RealType
sigma() const { return _sigma
; }
58 void reset() { _valid
= false; }
60 template<class Engine
>
61 result_type
operator()(Engine
& eng
)
63 #ifndef BOOST_NO_STDC_NAMESPACE
64 // allow for Koenig lookup
65 using std::sqrt
; using std::log
; using std::sin
; using std::cos
;
70 _cached_rho
= sqrt(-result_type(2) * log(result_type(1)-_r2
));
75 // Can we have a boost::mathconst please?
76 const result_type pi
= result_type(3.14159265358979323846);
78 return _cached_rho
* (_valid
?
79 cos(result_type(2)*pi
*_r1
) :
80 sin(result_type(2)*pi
*_r1
))
84 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
85 template<class CharT
, class Traits
>
86 friend std::basic_ostream
<CharT
,Traits
>&
87 operator<<(std::basic_ostream
<CharT
,Traits
>& os
, const normal_distribution
& nd
)
89 os
<< nd
._mean
<< " " << nd
._sigma
<< " "
90 << nd
._valid
<< " " << nd
._cached_rho
<< " " << nd
._r1
;
94 template<class CharT
, class Traits
>
95 friend std::basic_istream
<CharT
,Traits
>&
96 operator>>(std::basic_istream
<CharT
,Traits
>& is
, normal_distribution
& nd
)
98 is
>> std::ws
>> nd
._mean
>> std::ws
>> nd
._sigma
99 >> std::ws
>> nd
._valid
>> std::ws
>> nd
._cached_rho
100 >> std::ws
>> nd
._r1
;
105 result_type _mean
, _sigma
;
106 result_type _r1
, _r2
, _cached_rho
;
112 #endif // BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP