STIR  6.2.0
modulo.h
Go to the documentation of this file.
1 //
2 //
3 #ifndef __stir_modulo_H__
4 #define __stir_modulo_H__
5 
15 /*
16  Copyright (C) 2004- 2009, Hammersmith Imanet Ltd
17  This file is part of STIR.
18 
19  SPDX-License-Identifier: Apache-2.0
20 
21  See STIR/LICENSE.txt for details
22 */
23 
24 #include "stir/common.h"
25 
26 START_NAMESPACE_STIR
27 
32 
34 
51 inline double
52 modulo(const double a, const double b)
53 {
54  const double res = fmod(a, b);
55  return res < 0 ? res + fabs(b) : res;
56 }
57 
59 
69 inline float
70 modulo(const float a, const float b)
71 {
72  float res = static_cast<float>(modulo(static_cast<double>(a), static_cast<double>(b)));
73  assert(res >= 0);
74  const float abs_b = b >= 0 ? b : -b;
75  if (res >= abs_b)
76  res -= abs_b;
77  assert(res >= 0);
78  return res;
79 }
80 
82 
86 inline int
87 modulo(const int a, const int b)
88 {
89  const int res = a % b;
90  const int res2 = res < 0 ? res + (b >= 0 ? b : -b) : res;
91  assert(res2 >= 0);
92  assert(res2 < (b >= 0 ? b : -b));
93  return res2;
94 }
95 
97 
101 template <int num_dimensions, typename T>
104 {
106  for (int d = 1; d <= num_dimensions; ++d)
107  result[d] = modulo(a[d], b[d]);
108  return result;
109 }
110 
112 
116 template <typename FloatOrDouble>
117 inline FloatOrDouble
118 from_min_pi_plus_pi_to_0_2pi(const FloatOrDouble phi)
119 {
120  static const FloatOrDouble two_pi = static_cast<FloatOrDouble>(2 * _PI);
121  assert(phi >= -two_pi);
122  assert(phi < two_pi);
123  if (phi >= 0)
124  return phi;
125  FloatOrDouble res = phi + two_pi;
126  // due to floating point finite precision, the following check is needed...
127  if (res >= two_pi)
128  res -= two_pi;
129  assert(res >= 0);
130  assert(res < two_pi);
131  return res;
132 }
133 
135 
136 template <typename FloatOrDouble>
137 inline FloatOrDouble
138 to_0_2pi(const FloatOrDouble phi)
139 {
140  return modulo(phi, static_cast<FloatOrDouble>(2 * _PI));
141 }
142 
144 
145 END_NAMESPACE_STIR
146 
147 #endif
#define _PI
The constant pi to high precision.
Definition: common.h:134
FloatOrDouble from_min_pi_plus_pi_to_0_2pi(const FloatOrDouble phi)
A function to convert an angle from one range to another.
Definition: modulo.h:118
FloatOrDouble to_0_2pi(const FloatOrDouble phi)
Convert angle to standard range.
Definition: modulo.h:138
BasicCoordinate< num_dimensions, T > modulo(const BasicCoordinate< num_dimensions, T > &a, const BasicCoordinate< num_dimensions, T > &b)
Performs the modulus operation on each element of the coordinates.
Definition: modulo.h:103
class BasicCoordinate<int num_dimensions, typename coordT> defines num_dimensions -dimensional coordi...
Definition: BasicCoordinate.h:53
basic configuration include file