IMP  2.0.0
The Integrative Modeling Platform
algebra/utility.h
Go to the documentation of this file.
1 /**
2  * \file IMP/algebra/utility.h
3  * \brief Functions to deal with very common math operations
4  *
5  * Copyright 2007-2013 IMP Inventors. All rights reserved.
6 */
7 
8 #ifndef IMPALGEBRA_UTILITY_H
9 #define IMPALGEBRA_UTILITY_H
10 
11 #include <cmath> // abs
12 #include <IMP/algebra/algebra_config.h>
13 #include <IMP/base/exception.h>
14 
15 IMPALGEBRA_BEGIN_NAMESPACE
16 #ifndef IMP_DOXYGEN
17 //! xor operation between two values
18 inline bool xorT(bool x, bool y)
19 {
20  return (((x) && !(y)) || (!(x) && (y)));
21 }
22 #endif
23 
24 inline double get_squared(double x){
25  return x*x;
26 }
27 
28 //! Sign of a number. 1 if the number is higher or equal to 0 and -1 otherwise
29 template<typename T>
30 inline int get_sign(const T& x)
31 {
32  if (x >= 0) return 1;
33  return -1;
34 }
35 
36 //! Rounds a number to next integer.
37 /**
38  * The result is of type integer but the argument can be of any type. Some
39  * examples:
40  *
41  * \code
42  * a = round(-0.7); // a = -1
43  * a = round(-0.2); // a = 0
44  * a = round(0.2); // a = 0
45  * a = round(0.7); // a = 1
46  * \endcode
47  */
48 template<typename T>
49 inline int get_rounded(const T& x)
50 {
51  if (x > 0) {
52  return static_cast<int>((x) + 0.5);
53  } else {
54  return static_cast<int>((x) - 0.5);
55  }
56 }
57 
58 
59 //! Constrains a value between two given limits
60 /*
61  * The limits act as the constrain to saturate the value. Examples:
62  * with x and constrain(x,-2,2):
63  *
64  * \code
65  * x = constrain(-8,-2,2); // x=-2;
66  * x = constrain(-2,-2,2); // x=-2;
67  * x = constrain(-1,-2,2); // x=-1;
68  * x = constrain(0,-2,2); // x=0;
69  * x = constrain(2,-2,2); // x=2;
70  * x = constrain(4,-2,2); // x=2;
71  * \endcode
72  */
73 template<typename T>
74 inline T get_constrained(const T x, const T x0, const T xF)
75 {
76  if (x < x0) return x0;
77  if (x > xF) return xF;
78  return x;
79 }
80 
81 
82 //! Closest power of 2 that can contain a number x
83 inline float get_next_larger_power_of_2(float x) {
84  float p=1;
85  while(p<x) {p*=2;}
86  return p;
87 }
88 
89 //! Closest power of 2 that can contain a number x
90 inline double get_next_larger_power_of_2(double x) {
91  double p=1;
92  while(p<x) {p*=2;}
93  return p;
94 }
95 
96 //! Closest power of 2 for a number, not necessarily higher
97 inline double get_closer_power_of_2(double x) {
98  double p=1;
99  double q=1;
100  while(p<x) {
101  q=p;
102  p*=2;
103  }
104  if((x-q)<(p-x)) { return q; }
105  return p;
106 }
107 
108 //! Compares two values (intended for doubles)
109 /**
110  * epsilon is the tolerance allowed to consider the values as equal
111  */
112 inline bool get_are_almost_equal(const double a, const double b,
113  const double epsilon)
114 {
115  return (std::abs(a-b) < epsilon);
116 }
117 
118 IMPALGEBRA_END_NAMESPACE
119 
120 #endif /* IMPALGEBRA_UTILITY_H */