MathExtras.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2013 Apple Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
  14. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
  17. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  18. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  19. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  20. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  21. * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  23. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #ifndef WTF_MathExtras_h
  26. #define WTF_MathExtras_h
  27. #include <algorithm>
  28. #include <cmath>
  29. #include <float.h>
  30. #include <limits>
  31. #include <stdint.h>
  32. #include <stdlib.h>
  33. #include <wtf/StdLibExtras.h>
  34. #if OS(PSP2)
  35. #include <math.h>
  36. #endif
  37. #if OS(SOLARIS)
  38. #include <ieeefp.h>
  39. #endif
  40. #if OS(OPENBSD)
  41. #include <sys/types.h>
  42. #include <machine/ieee.h>
  43. #endif
  44. #if OS(QNX)
  45. // FIXME: Look into a way to have cmath import its functions into both the standard and global
  46. // namespace. For now, we include math.h since the QNX cmath header only imports its functions
  47. // into the standard namespace.
  48. #include <math.h>
  49. // These macros from math.h conflict with the real functions in the std namespace.
  50. #undef signbit
  51. #undef isnan
  52. #undef isinf
  53. #undef isfinite
  54. #endif
  55. #ifndef M_PI
  56. const double piDouble = 3.14159265358979323846;
  57. const float piFloat = 3.14159265358979323846f;
  58. #else
  59. const double piDouble = M_PI;
  60. const float piFloat = static_cast<float>(M_PI);
  61. #endif
  62. #ifndef M_PI_2
  63. const double piOverTwoDouble = 1.57079632679489661923;
  64. const float piOverTwoFloat = 1.57079632679489661923f;
  65. #else
  66. const double piOverTwoDouble = M_PI_2;
  67. const float piOverTwoFloat = static_cast<float>(M_PI_2);
  68. #endif
  69. #ifndef M_PI_4
  70. const double piOverFourDouble = 0.785398163397448309616;
  71. const float piOverFourFloat = 0.785398163397448309616f;
  72. #else
  73. const double piOverFourDouble = M_PI_4;
  74. const float piOverFourFloat = static_cast<float>(M_PI_4);
  75. #endif
  76. #if OS(DARWIN)
  77. // Work around a bug in the Mac OS X libc where ceil(-0.1) return +0.
  78. inline double wtf_ceil(double x) { return copysign(ceil(x), x); }
  79. #define ceil(x) wtf_ceil(x)
  80. #endif
  81. #if OS(SOLARIS)
  82. namespace std {
  83. #ifndef isfinite
  84. inline bool isfinite(double x) { return finite(x) && !isnand(x); }
  85. #endif
  86. #ifndef signbit
  87. inline bool signbit(double x) { return copysign(1.0, x) < 0; }
  88. #endif
  89. #ifndef isinf
  90. inline bool isinf(double x) { return !finite(x) && !isnand(x); }
  91. #endif
  92. } // namespace std
  93. #endif
  94. #if OS(OPENBSD)
  95. namespace std {
  96. #ifndef isfinite
  97. inline bool isfinite(double x) { return finite(x); }
  98. #endif
  99. #ifndef signbit
  100. inline bool signbit(double x) { struct ieee_double *p = (struct ieee_double *)&x; return p->dbl_sign; }
  101. #endif
  102. } // namespace std
  103. #endif
  104. #if COMPILER(MSVC)
  105. // We must not do 'num + 0.5' or 'num - 0.5' because they can cause precision loss.
  106. static double round(double num)
  107. {
  108. double integer = ceil(num);
  109. if (num > 0)
  110. return integer - num > 0.5 ? integer - 1.0 : integer;
  111. return integer - num >= 0.5 ? integer - 1.0 : integer;
  112. }
  113. static float roundf(float num)
  114. {
  115. float integer = ceilf(num);
  116. if (num > 0)
  117. return integer - num > 0.5f ? integer - 1.0f : integer;
  118. return integer - num >= 0.5f ? integer - 1.0f : integer;
  119. }
  120. inline long long llround(double num) { return static_cast<long long>(round(num)); }
  121. inline long long llroundf(float num) { return static_cast<long long>(roundf(num)); }
  122. inline long lround(double num) { return static_cast<long>(round(num)); }
  123. inline long lroundf(float num) { return static_cast<long>(roundf(num)); }
  124. inline double trunc(double num) { return num > 0 ? floor(num) : ceil(num); }
  125. #endif
  126. #if COMPILER(GCC) && OS(QNX)
  127. // The stdlib on QNX doesn't contain long abs(long). See PR #104666.
  128. inline long long abs(long num) { return labs(num); }
  129. #endif
  130. #if COMPILER(MSVC)
  131. // MSVC's math.h does not currently supply log2 or log2f.
  132. inline double log2(double num)
  133. {
  134. // This constant is roughly M_LN2, which is not provided by default on Windows.
  135. return log(num) / 0.693147180559945309417232121458176568;
  136. }
  137. inline float log2f(float num)
  138. {
  139. // This constant is roughly M_LN2, which is not provided by default on Windows.
  140. return logf(num) / 0.693147180559945309417232121458176568f;
  141. }
  142. #endif
  143. #if COMPILER(MSVC)
  144. // The 64bit version of abs() is already defined in stdlib.h which comes with VC10
  145. #if COMPILER(MSVC9_OR_LOWER)
  146. inline long long abs(long long num) { return _abs64(num); }
  147. #endif
  148. namespace std {
  149. inline bool isinf(double num) { return !_finite(num) && !_isnan(num); }
  150. inline bool isnan(double num) { return !!_isnan(num); }
  151. inline bool isfinite(double x) { return _finite(x); }
  152. inline bool signbit(double num) { return _copysign(1.0, num) < 0; }
  153. } // namespace std
  154. inline double nextafter(double x, double y) { return _nextafter(x, y); }
  155. inline float nextafterf(float x, float y) { return x > y ? x - FLT_EPSILON : x + FLT_EPSILON; }
  156. inline double copysign(double x, double y) { return _copysign(x, y); }
  157. // Work around a bug in Win, where atan2(+-infinity, +-infinity) yields NaN instead of specific values.
  158. extern "C" inline double wtf_atan2(double x, double y)
  159. {
  160. double posInf = std::numeric_limits<double>::infinity();
  161. double negInf = -std::numeric_limits<double>::infinity();
  162. double nan = std::numeric_limits<double>::quiet_NaN();
  163. double result = nan;
  164. if (x == posInf && y == posInf)
  165. result = piOverFourDouble;
  166. else if (x == posInf && y == negInf)
  167. result = 3 * piOverFourDouble;
  168. else if (x == negInf && y == posInf)
  169. result = -piOverFourDouble;
  170. else if (x == negInf && y == negInf)
  171. result = -3 * piOverFourDouble;
  172. else
  173. result = ::atan2(x, y);
  174. return result;
  175. }
  176. // Work around a bug in the Microsoft CRT, where fmod(x, +-infinity) yields NaN instead of x.
  177. extern "C" inline double wtf_fmod(double x, double y) { return (!std::isinf(x) && std::isinf(y)) ? x : fmod(x, y); }
  178. // Work around a bug in the Microsoft CRT, where pow(NaN, 0) yields NaN instead of 1.
  179. extern "C" inline double wtf_pow(double x, double y) { return y == 0 ? 1 : pow(x, y); }
  180. #define atan2(x, y) wtf_atan2(x, y)
  181. #define fmod(x, y) wtf_fmod(x, y)
  182. #define pow(x, y) wtf_pow(x, y)
  183. // MSVC's math functions do not bring lrint.
  184. inline long int lrint(double flt)
  185. {
  186. int64_t intgr;
  187. #if CPU(X86)
  188. __asm {
  189. fld flt
  190. fistp intgr
  191. };
  192. #else
  193. ASSERT(std::isfinite(flt));
  194. double rounded = round(flt);
  195. intgr = static_cast<int64_t>(rounded);
  196. // If the fractional part is exactly 0.5, we need to check whether
  197. // the rounded result is even. If it is not we need to add 1 to
  198. // negative values and subtract one from positive values.
  199. if ((fabs(intgr - flt) == 0.5) & intgr)
  200. intgr -= ((intgr >> 62) | 1); // 1 with the sign of result, i.e. -1 or 1.
  201. #endif
  202. return static_cast<long int>(intgr);
  203. }
  204. #endif // COMPILER(MSVC)
  205. inline double deg2rad(double d) { return d * piDouble / 180.0; }
  206. inline double rad2deg(double r) { return r * 180.0 / piDouble; }
  207. inline double deg2grad(double d) { return d * 400.0 / 360.0; }
  208. inline double grad2deg(double g) { return g * 360.0 / 400.0; }
  209. inline double turn2deg(double t) { return t * 360.0; }
  210. inline double deg2turn(double d) { return d / 360.0; }
  211. inline double rad2grad(double r) { return r * 200.0 / piDouble; }
  212. inline double grad2rad(double g) { return g * piDouble / 200.0; }
  213. inline float deg2rad(float d) { return d * piFloat / 180.0f; }
  214. inline float rad2deg(float r) { return r * 180.0f / piFloat; }
  215. inline float deg2grad(float d) { return d * 400.0f / 360.0f; }
  216. inline float grad2deg(float g) { return g * 360.0f / 400.0f; }
  217. inline float turn2deg(float t) { return t * 360.0f; }
  218. inline float deg2turn(float d) { return d / 360.0f; }
  219. inline float rad2grad(float r) { return r * 200.0f / piFloat; }
  220. inline float grad2rad(float g) { return g * piFloat / 200.0f; }
  221. // std::numeric_limits<T>::min() returns the smallest positive value for floating point types
  222. template<typename T> inline T defaultMinimumForClamp() { return std::numeric_limits<T>::min(); }
  223. template<> inline float defaultMinimumForClamp() { return -std::numeric_limits<float>::max(); }
  224. template<> inline double defaultMinimumForClamp() { return -std::numeric_limits<double>::max(); }
  225. template<typename T> inline T defaultMaximumForClamp() { return std::numeric_limits<T>::max(); }
  226. template<typename T> inline T clampTo(double value, T min = defaultMinimumForClamp<T>(), T max = defaultMaximumForClamp<T>())
  227. {
  228. if (value >= static_cast<double>(max))
  229. return max;
  230. if (value <= static_cast<double>(min))
  231. return min;
  232. return static_cast<T>(value);
  233. }
  234. template<> inline long long int clampTo(double, long long int, long long int); // clampTo does not support long long ints.
  235. inline int clampToInteger(double value)
  236. {
  237. return clampTo<int>(value);
  238. }
  239. inline float clampToFloat(double value)
  240. {
  241. return clampTo<float>(value);
  242. }
  243. inline int clampToPositiveInteger(double value)
  244. {
  245. return clampTo<int>(value, 0);
  246. }
  247. inline int clampToInteger(float value)
  248. {
  249. return clampTo<int>(value);
  250. }
  251. inline int clampToInteger(unsigned x)
  252. {
  253. const unsigned intMax = static_cast<unsigned>(std::numeric_limits<int>::max());
  254. if (x >= intMax)
  255. return std::numeric_limits<int>::max();
  256. return static_cast<int>(x);
  257. }
  258. inline bool isWithinIntRange(float x)
  259. {
  260. return x > static_cast<float>(std::numeric_limits<int>::min()) && x < static_cast<float>(std::numeric_limits<int>::max());
  261. }
  262. template<typename T> inline bool hasOneBitSet(T value)
  263. {
  264. return !((value - 1) & value) && value;
  265. }
  266. template<typename T> inline bool hasZeroOrOneBitsSet(T value)
  267. {
  268. return !((value - 1) & value);
  269. }
  270. template<typename T> inline bool hasTwoOrMoreBitsSet(T value)
  271. {
  272. return !hasZeroOrOneBitsSet(value);
  273. }
  274. template <typename T> inline unsigned getLSBSet(T value)
  275. {
  276. unsigned result = 0;
  277. while (value >>= 1)
  278. ++result;
  279. return result;
  280. }
  281. template<typename T> inline T timesThreePlusOneDividedByTwo(T value)
  282. {
  283. // Mathematically equivalent to:
  284. // (value * 3 + 1) / 2;
  285. // or:
  286. // (unsigned)ceil(value * 1.5));
  287. // This form is not prone to internal overflow.
  288. return value + (value >> 1) + (value & 1);
  289. }
  290. template<typename T> inline bool isNotZeroAndOrdered(T value)
  291. {
  292. return value > 0.0 || value < 0.0;
  293. }
  294. template<typename T> inline bool isZeroOrUnordered(T value)
  295. {
  296. return !isNotZeroAndOrdered(value);
  297. }
  298. #ifndef UINT64_C
  299. #if COMPILER(MSVC)
  300. #define UINT64_C(c) c ## ui64
  301. #else
  302. #define UINT64_C(c) c ## ull
  303. #endif
  304. #endif
  305. #if COMPILER(MINGW64) && (!defined(__MINGW64_VERSION_RC) || __MINGW64_VERSION_RC < 1)
  306. inline double wtf_pow(double x, double y)
  307. {
  308. // MinGW-w64 has a custom implementation for pow.
  309. // This handles certain special cases that are different.
  310. if ((x == 0.0 || std::isinf(x)) && std::isfinite(y)) {
  311. double f;
  312. if (modf(y, &f) != 0.0)
  313. return ((x == 0.0) ^ (y > 0.0)) ? std::numeric_limits<double>::infinity() : 0.0;
  314. }
  315. if (x == 2.0) {
  316. int yInt = static_cast<int>(y);
  317. if (y == yInt)
  318. return ldexp(1.0, yInt);
  319. }
  320. return pow(x, y);
  321. }
  322. #define pow(x, y) wtf_pow(x, y)
  323. #endif // COMPILER(MINGW64) && (!defined(__MINGW64_VERSION_RC) || __MINGW64_VERSION_RC < 1)
  324. // decompose 'number' to its sign, exponent, and mantissa components.
  325. // The result is interpreted as:
  326. // (sign ? -1 : 1) * pow(2, exponent) * (mantissa / (1 << 52))
  327. inline void decomposeDouble(double number, bool& sign, int32_t& exponent, uint64_t& mantissa)
  328. {
  329. ASSERT(std::isfinite(number));
  330. sign = std::signbit(number);
  331. uint64_t bits = WTF::bitwise_cast<uint64_t>(number);
  332. exponent = (static_cast<int32_t>(bits >> 52) & 0x7ff) - 0x3ff;
  333. mantissa = bits & 0xFFFFFFFFFFFFFull;
  334. // Check for zero/denormal values; if so, adjust the exponent,
  335. // if not insert the implicit, omitted leading 1 bit.
  336. if (exponent == -0x3ff)
  337. exponent = mantissa ? -0x3fe : 0;
  338. else
  339. mantissa |= 0x10000000000000ull;
  340. }
  341. // Calculate d % 2^{64}.
  342. inline void doubleToInteger(double d, unsigned long long& value)
  343. {
  344. if (std::isnan(d) || std::isinf(d))
  345. value = 0;
  346. else {
  347. // -2^{64} < fmodValue < 2^{64}.
  348. double fmodValue = fmod(trunc(d), std::numeric_limits<unsigned long long>::max() + 1.0);
  349. if (fmodValue >= 0) {
  350. // 0 <= fmodValue < 2^{64}.
  351. // 0 <= value < 2^{64}. This cast causes no loss.
  352. value = static_cast<unsigned long long>(fmodValue);
  353. } else {
  354. // -2^{64} < fmodValue < 0.
  355. // 0 < fmodValueInUnsignedLongLong < 2^{64}. This cast causes no loss.
  356. unsigned long long fmodValueInUnsignedLongLong = static_cast<unsigned long long>(-fmodValue);
  357. // -1 < (std::numeric_limits<unsigned long long>::max() - fmodValueInUnsignedLongLong) < 2^{64} - 1.
  358. // 0 < value < 2^{64}.
  359. value = std::numeric_limits<unsigned long long>::max() - fmodValueInUnsignedLongLong + 1;
  360. }
  361. }
  362. }
  363. namespace WTF {
  364. // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  365. inline uint32_t roundUpToPowerOfTwo(uint32_t v)
  366. {
  367. v--;
  368. v |= v >> 1;
  369. v |= v >> 2;
  370. v |= v >> 4;
  371. v |= v >> 8;
  372. v |= v >> 16;
  373. v++;
  374. return v;
  375. }
  376. inline unsigned fastLog2(unsigned i)
  377. {
  378. unsigned log2 = 0;
  379. if (i & (i - 1))
  380. log2 += 1;
  381. if (i >> 16)
  382. log2 += 16, i >>= 16;
  383. if (i >> 8)
  384. log2 += 8, i >>= 8;
  385. if (i >> 4)
  386. log2 += 4, i >>= 4;
  387. if (i >> 2)
  388. log2 += 2, i >>= 2;
  389. if (i >> 1)
  390. log2 += 1;
  391. return log2;
  392. }
  393. } // namespace WTF
  394. #endif // #ifndef WTF_MathExtras_h