Tools.h
1 
45 #ifndef JIXIE_SVD_TOOLS_H
46 #define JIXIE_SVD_TOOLS_H
47 
48 #pragma GCC diagnostic push
49 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
50 #include <Eigen/Dense>
51 #include <Eigen/Core>
52 #include <Eigen/SVD>
53 #pragma GCC diagnostic pop
54 
55 #include <mmintrin.h>
56 #include <xmmintrin.h>
57 #include <cmath>
58 #include <random>
59 #include <chrono>
60 #include <iostream>
61 #include <iomanip>
62 
63 namespace JIXIE {
64 
68 template <class T>
69 class RandomNumber {
70 public:
71  std::mt19937 generator;
72 
73  RandomNumber(unsigned s = 123)
74  : generator(s)
75  {
76  }
77 
78  ~RandomNumber()
79  {
80  }
81 
85  T randReal(T a, T b)
86  {
87  std::uniform_real_distribution<T> distribution(a, b);
88  return distribution(generator);
89  }
90 
94  template <class Derived>
95  void fill(Eigen::DenseBase<Derived>& x, T a, T b)
96  {
97  for (typename Derived::Index i = 0; i < x.size(); i++)
98  x(i) = randReal(a, b);
99  }
100 };
101 
102 namespace MATH_TOOLS {
103 
110 inline float approx_rsqrt(float a)
111 {
112 return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(a)));
113 }
114 
119 inline float rsqrt(float a)
120 {
121  return (float)1.0f / std::sqrt(a);
122 
123 // float b = approx_rsqrt(a);
124 // // Newton step with f(x) = a - 1/x^2
125 // b = 0.5f * b * (3.0f - a * (b * b));
126 // return b;
127 }
128 
133 inline double rsqrt(double a)
134 {
135 using std::sqrt;
136 return 1 / sqrt(a);
137 }
138 }
139 
143 class Timer {
144 public:
145  Timer() {}
146 
147  ~Timer() {}
148 
152  void start()
153  {
154  start_time = std::chrono::steady_clock::now();
155  }
156 
160  double click()
161  {
162  to_time = std::chrono::steady_clock::now();
163  elapsed_seconds = to_time - start_time;
164  start_time = to_time;
165  return elapsed_seconds.count();
166  }
167 
168 private:
169  std::chrono::time_point<std::chrono::steady_clock> start_time;
170  std::chrono::time_point<std::chrono::steady_clock> to_time;
171  std::chrono::duration<double> elapsed_seconds;
172 };
173 
174 namespace INTERNAL {
175 using namespace std;
176 template <class T, class Enable = void>
178  using type = typename T::Scalar;
179 };
180 template <class T>
181 struct ScalarTypeHelper<T, enable_if_t<is_arithmetic<T>::value> > {
182  using type = T;
183 };
184 }
185 
186 template <class T>
187 using ScalarType = typename INTERNAL::ScalarTypeHelper<T>::type;
188 
189 template <class MatrixType>
190 constexpr bool isSize(int m, int n)
191 {
192  return MatrixType::RowsAtCompileTime == m && MatrixType::ColsAtCompileTime == n;
193 }
194 
195 }
196 #endif