aimstil  5.0.5
math_functions.tpp
Go to the documentation of this file.
1 
2 
3 
4 namespace til { namespace math {
5 
6 
7  //---------------------------------------------------------------------------
8 
9  namespace detail
10  {
11  //-------------------------------------------------------------------------
12 
13  template < typename T >
14  T ahuber(T ax, T K)
15  {
16  // NB: testing K >= 0 is actually not needed.
17  if (ax < K)
18  {
19  return ax*ax;
20  }
21  else
22  {
23  return 2 * K * (ax - K);
24  }
25  }
26 
27  //-------------------------------------------------------------------------
28 
29  } // namespace detail
30 
31  //---------------------------------------------------------------------------
32 
33  template < typename T >
34  T huber(T x, T K)
35  {
36  return detail::ahuber(std::abs(x), K);
37  }
38 
39  //---------------------------------------------------------------------------
40 
41  template < typename T >
42  T d_huber(T x, T K)
43  {
44  if (std::abs(x) < K)
45  {
46  return 2 * x;
47  }
48  else if (x > 0)
49  {
50  return 2 * K;
51  }
52  else
53  {
54  return (-2) * K;
55  }
56  }
57 
58  //---------------------------------------------------------------------------
59 
60  template < typename T >
61  T shrink(T x, T K)
62  {
63  assert(K >= 0);
64  if (std::abs(x) < K)
65  {
66  return 0;
67  }
68  else if (x > 0)
69  {
70  return x - K;
71  }
72  else
73  {
74  return x + K;
75  }
76  }
77 
78  //---------------------------------------------------------------------------
79 
80  /// Constructor with Gaussian standard deviation.
81  template < typename TPrec >
82  Gaussian<TPrec>::Gaussian(prec_type sigma)
83  {
84  this->setSigma(sigma);
85  }
86 
87  //---------------------------------------------------------------------------
88 
89  template < typename TPrec >
90  void
91  Gaussian<TPrec>::setSigma(prec_type sigma)
92  {
93  assert(sigma > 0);
94  m_2var = 2 * sigma * sigma;
95  if (m_2var < 128 * std::numeric_limits<prec_type>::epsilon())
96  {
97  throw StandardDeviationTooSmall();
98  }
99  }
100 
101  //---------------------------------------------------------------------------
102 
103  template < typename TPrec >
104  typename Gaussian<TPrec>::prec_type
105  Gaussian<TPrec>::operator()(prec_type x) const
106  {
107  return squared_input(x*x);
108  }
109 
110  //---------------------------------------------------------------------------
111 
112  template < typename TPrec >
113  typename Gaussian<TPrec>::prec_type
114  Gaussian<TPrec>::squared_input(prec_type x2) const
115  {
116  return std::exp(-x2 / m_2var);
117  }
118 
119  //---------------------------------------------------------------------------
120 
121 }} // namespace til::math
122