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.
10 * $Id: normal_distribution.hpp,v 1.20 2004/07/27 03:43:32 dgregor Exp $
13 * 2001-02-18 moved to individual header files
16 #ifndef BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP
17 #define BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP
22 #include <boost/limits.hpp>
23 #include <boost/static_assert.hpp>
27 // deterministic polar method, uses trigonometric functions
28 template<class RealType = double>
29 class normal_distribution
32 typedef RealType input_type;
33 typedef RealType result_type;
35 #if !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300)
36 BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);
39 explicit normal_distribution(const result_type& mean = result_type(0),
40 const result_type& sigma = result_type(1))
41 : _mean(mean), _sigma(sigma), _valid(false)
43 assert(sigma >= result_type(0));
46 // compiler-generated copy constructor is NOT fine, need to purge cache
47 normal_distribution(const normal_distribution& other)
48 : _mean(other._mean), _sigma(other._sigma), _valid(false)
52 // compiler-generated copy ctor and assignment operator are fine
54 RealType mean() const { return _mean; }
55 RealType sigma() const { return _sigma; }
57 void reset() { _valid = false; }
59 template<class Engine>
60 result_type operator()(Engine& eng)
62 #ifndef BOOST_NO_STDC_NAMESPACE
63 // allow for Koenig lookup
64 using std::sqrt; using std::log; using std::sin; using std::cos;
69 _cached_rho = sqrt(-result_type(2) * log(result_type(1)-_r2));
74 // Can we have a boost::mathconst please?
75 const result_type pi = result_type(3.14159265358979323846);
77 return _cached_rho * (_valid ?
78 cos(result_type(2)*pi*_r1) :
79 sin(result_type(2)*pi*_r1))
83 #if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
84 template<class CharT, class Traits>
85 friend std::basic_ostream<CharT,Traits>&
86 operator<<(std::basic_ostream<CharT,Traits>& os, const normal_distribution& nd)
88 os << nd._mean << " " << nd._sigma << " "
89 << nd._valid << " " << nd._cached_rho << " " << nd._r1;
93 template<class CharT, class Traits>
94 friend std::basic_istream<CharT,Traits>&
95 operator>>(std::basic_istream<CharT,Traits>& is, normal_distribution& nd)
97 is >> std::ws >> nd._mean >> std::ws >> nd._sigma
98 >> std::ws >> nd._valid >> std::ws >> nd._cached_rho
104 result_type _mean, _sigma;
105 result_type _r1, _r2, _cached_rho;
111 #endif // BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP