Analysis Software
Documentation for sPHENIX simulation software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
fast_exp.h
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file fast_exp.h
1 // TRENTO: Reduced Thickness Event-by-event Nuclear Topology
2 // Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
3 // TRENTO3D: Three-dimensional extension of TRENTO by Weiyao Ke
4 // MIT License
5 
6 #ifndef FAST_EXP_H
7 #define FAST_EXP_H
8 
9 #include <cmath>
10 #include <stdexcept>
11 #include <vector>
12 
13 namespace trento {
14 
28 template <typename T = double>
29 class FastExp {
30  public:
33  FastExp(T xmin, T xmax, std::size_t nsteps);
34 
36  T operator()(T x) const;
37 
38  private:
40  const T xmin_, xmax_;
41 
43  const T dx_;
44 
46  std::vector<T> table_;
47 };
48 
49 template <typename T>
50 FastExp<T>::FastExp(T xmin, T xmax, std::size_t nsteps)
51  : xmin_(xmin),
52  xmax_(xmax),
53  dx_((xmax-xmin)/(nsteps-1)),
54  table_(nsteps) {
55  // Tabulate evenly-spaced exp() values.
56  for (std::size_t i = 0; i < nsteps; ++i)
57  table_[i] = std::exp(xmin_ + i*dx_);
58 }
59 
60 template <typename T>
61 inline T FastExp<T>::operator()(T x) const {
62 #ifndef NDEBUG
63  if (x < xmin_ || x > xmax_)
64  throw std::out_of_range{"argument must be within [xmin, xmax]"};
65 #endif
66 
67  // Determine the table index of the nearest tabulated value.
68  auto index = static_cast<std::size_t>((x - xmin_)/dx_ + .5);
69 
70  // Compute the leading-order Taylor expansion.
71  // exp(x) = exp(x0) * exp(x-x0) =~ exp(x0) * (1 + x - x0)
72  // exp(x0) = table_[index]
73  // x0 = xmin_ + index*dx_
74  return table_[index] * (1. + x - xmin_ - index*dx_);
75 }
76 
77 } // namespace trento
78 
79 #endif // FAST_EXP_H