COSA
An Object-Oriented Platform for Arduino Programming
Math.hh
Go to the documentation of this file.
1 
21 #ifndef COSA_MATH_HH
22 #define COSA_MATH_HH
23 
24 #include <math.h>
25 #include "Cosa/Types.h"
26 
33 inline uint16_t
34 rand(uint16_t range)
35 {
36  return (rand() % (range + 1));
37 }
38 
46 inline int16_t
47 rand(int16_t low, int16_t high)
48 {
49  return (rand() % (high - low + 1) + low);
50 }
51 
58 inline uint32_t
59 random(uint32_t range)
60 {
61  return (random() % (range + 1));
62 }
63 
71 inline int32_t
72 random(int32_t low, int32_t high)
73 {
74  return (random(high - low + 1) + low);
75 }
76 
84 template<class T>
85 inline uint8_t log2(T value)
86 {
87  uint8_t res = 0;
88  while (value != 0) {
89  res += 1;
90  value >>= 1;
91  }
92  return (res);
93 }
94 
105 template<class T, T in_min, T in_max, T out_min, T out_max>
106 T map(T x)
107 {
108  static_assert(in_min < in_max, "bad range for map function");
109  static_assert(out_min < out_max, "bad domain for map function");
110  if (UNLIKELY(x < in_min)) return (out_min);
111  if (UNLIKELY(x > in_max)) return (out_max);
112  T range = in_max - in_min;
113  T domain = out_max - out_min;
114  return ((((x - in_min) * domain) / range) + out_min);
115 }
116 
125 template<class T, T low, T high>
126 T constrain(T x)
127 {
128  static_assert(low < high, "bad range for contrain function");
129  return (x < low ? low : (x > high ? high : x));
130 }
131 
141 template<class T, T low, T high>
142 bool is_within(T x)
143 {
144  return (!(x < low || x > high));
145 }
146 
147 #endif
uint16_t rand(uint16_t range)
Definition: Math.hh:34
T constrain(T x)
Definition: Math.hh:126
uint32_t random(uint32_t range)
Definition: Math.hh:59
uint8_t log2(T value)
Definition: Math.hh:85
bool is_within(T x)
Definition: Math.hh:142
#define static_assert(condition, message)
Definition: Types.h:266
T map(T x)
Definition: Math.hh:106
#define UNLIKELY(x)
Definition: Types.h:153