STIR 6.4.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
26START_NAMESPACE_STIR
27
32
34
51inline double
52modulo(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
69inline float
70modulo(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
86inline int
87modulo(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
101template <int num_dimensions, typename T>
102inline BasicCoordinate<num_dimensions, 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
116template <typename FloatOrDouble>
117inline FloatOrDouble
118from_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
136template <typename FloatOrDouble>
137inline FloatOrDouble
138to_0_2pi(const FloatOrDouble phi)
139{
140 return modulo(phi, static_cast<FloatOrDouble>(2 * _PI));
141}
142
144
145END_NAMESPACE_STIR
146
147#endif
class BasicCoordinate<int num_dimensions, typename coordT> defines num_dimensions -dimensional coordi...
Definition BasicCoordinate.h:57
basic configuration include file
#define _PI
The constant pi to high precision.
Definition common.h:141
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
double modulo(const double a, const double b)
Like std::fmod() but with guaranteed nonnegative result.
Definition modulo.h:52