1445 рядки
36 KiB

  1. //
  2. // Lol Engine
  3. //
  4. // Copyright: (c) 2010-2013 Sam Hocevar <sam@hocevar.net>
  5. // This program is free software; you can redistribute it and/or
  6. // modify it under the terms of the Do What The Fuck You Want To
  7. // Public License, Version 2, as published by Sam Hocevar. See
  8. // http://www.wtfpl.net/ for more details.
  9. //
  10. #if defined HAVE_CONFIG_H
  11. # include "config.h"
  12. #endif
  13. #include <new>
  14. #include <cstring>
  15. #include <cstdio>
  16. #include <cstdlib>
  17. #include "core.h"
  18. using namespace std;
  19. namespace lol
  20. {
  21. /*
  22. * First handle explicit specialisation of our templates.
  23. *
  24. * Initialisation order is not important because everything is
  25. * done on demand, but here is the dependency list anyway:
  26. * - fast_log() requires R_1
  27. * - log() requires R_LN2
  28. * - re() require R_2
  29. * - exp() requires R_0, R_1, R_LN2
  30. * - sqrt() requires R_3
  31. */
  32. static real fast_log(real const &x);
  33. static real fast_pi();
  34. #define LOL_CONSTANT_GETTER(name, value) \
  35. template<> real const& real::name() \
  36. { \
  37. static real const ret = value; \
  38. return ret; \
  39. }
  40. LOL_CONSTANT_GETTER(R_0, (real)0.0);
  41. LOL_CONSTANT_GETTER(R_1, (real)1.0);
  42. LOL_CONSTANT_GETTER(R_2, (real)2.0);
  43. LOL_CONSTANT_GETTER(R_3, (real)3.0);
  44. LOL_CONSTANT_GETTER(R_10, (real)10.0);
  45. LOL_CONSTANT_GETTER(R_LN2, fast_log(R_2()));
  46. LOL_CONSTANT_GETTER(R_LN10, log(R_10()));
  47. LOL_CONSTANT_GETTER(R_LOG2E, re(R_LN2()));
  48. LOL_CONSTANT_GETTER(R_LOG10E, re(R_LN10()));
  49. LOL_CONSTANT_GETTER(R_E, exp(R_1()));
  50. LOL_CONSTANT_GETTER(R_PI, fast_pi());
  51. LOL_CONSTANT_GETTER(R_PI_2, R_PI() / 2);
  52. LOL_CONSTANT_GETTER(R_PI_3, R_PI() / R_3());
  53. LOL_CONSTANT_GETTER(R_PI_4, R_PI() / 4);
  54. LOL_CONSTANT_GETTER(R_1_PI, re(R_PI()));
  55. LOL_CONSTANT_GETTER(R_2_PI, R_1_PI() * 2);
  56. LOL_CONSTANT_GETTER(R_2_SQRTPI, re(sqrt(R_PI())) * 2);
  57. LOL_CONSTANT_GETTER(R_SQRT2, sqrt(R_2()));
  58. LOL_CONSTANT_GETTER(R_SQRT3, sqrt(R_3()));
  59. LOL_CONSTANT_GETTER(R_SQRT1_2, R_SQRT2() / 2);
  60. #undef LOL_CONSTANT_GETTER
  61. /*
  62. * Now carry on with the rest of the Real class.
  63. */
  64. template<> real::Real()
  65. {
  66. m_mantissa = new uint32_t[BIGITS];
  67. memset(m_mantissa, 0, BIGITS * sizeof(uint32_t));
  68. m_signexp = 0;
  69. }
  70. template<> real::Real(real const &x)
  71. {
  72. m_mantissa = new uint32_t[BIGITS];
  73. memcpy(m_mantissa, x.m_mantissa, BIGITS * sizeof(uint32_t));
  74. m_signexp = x.m_signexp;
  75. }
  76. template<> real const &real::operator =(real const &x)
  77. {
  78. if (&x != this)
  79. {
  80. memcpy(m_mantissa, x.m_mantissa, BIGITS * sizeof(uint32_t));
  81. m_signexp = x.m_signexp;
  82. }
  83. return *this;
  84. }
  85. template<> real::~Real()
  86. {
  87. delete[] m_mantissa;
  88. }
  89. template<> real::Real(float f) { new(this) real((double)f); }
  90. template<> real::Real(int i) { new(this) real((double)i); }
  91. template<> real::Real(unsigned int i) { new(this) real((double)i); }
  92. template<> real::Real(double d)
  93. {
  94. new(this) real();
  95. union { double d; uint64_t x; } u = { d };
  96. uint32_t sign = (u.x >> 63) << 31;
  97. uint32_t exponent = (u.x << 1) >> 53;
  98. switch (exponent)
  99. {
  100. case 0x00:
  101. m_signexp = sign;
  102. break;
  103. case 0x7ff:
  104. m_signexp = sign | 0x7fffffffu;
  105. break;
  106. default:
  107. m_signexp = sign | (exponent + (1 << 30) - (1 << 10));
  108. break;
  109. }
  110. m_mantissa[0] = (uint32_t)(u.x >> 20);
  111. m_mantissa[1] = (uint32_t)(u.x << 12);
  112. memset(m_mantissa + 2, 0, (BIGITS - 2) * sizeof(m_mantissa[0]));
  113. }
  114. template<> real::operator float() const { return (float)(double)(*this); }
  115. template<> real::operator int() const { return (int)(double)(*this); }
  116. template<> real::operator unsigned() const { return (unsigned)(double)(*this); }
  117. template<> real::operator double() const
  118. {
  119. union { double d; uint64_t x; } u;
  120. /* Get sign */
  121. u.x = m_signexp >> 31;
  122. u.x <<= 11;
  123. /* Compute new exponent */
  124. uint32_t exponent = (m_signexp << 1) >> 1;
  125. int e = (int)exponent - (1 << 30) + (1 << 10);
  126. if (e < 0)
  127. u.x <<= 52;
  128. else if (e >= 0x7ff)
  129. {
  130. u.x |= 0x7ff;
  131. u.x <<= 52;
  132. }
  133. else
  134. {
  135. u.x |= e;
  136. /* Store mantissa if necessary */
  137. u.x <<= 32;
  138. u.x |= m_mantissa[0];
  139. u.x <<= 20;
  140. u.x |= m_mantissa[1] >> 12;
  141. /* Rounding */
  142. u.x += (m_mantissa[1] >> 11) & 1;
  143. }
  144. return u.d;
  145. }
  146. /*
  147. * Create a real number from an ASCII representation
  148. */
  149. template<> real::Real(char const *str)
  150. {
  151. real ret = 0;
  152. int exponent = 0;
  153. bool comma = false, nonzero = false, negative = false, finished = false;
  154. for (char const *p = str; *p && !finished; p++)
  155. {
  156. switch (*p)
  157. {
  158. case '-':
  159. case '+':
  160. if (p != str)
  161. break;
  162. negative = (*p == '-');
  163. break;
  164. case '.':
  165. if (comma)
  166. finished = true;
  167. comma = true;
  168. break;
  169. case '0': case '1': case '2': case '3': case '4':
  170. case '5': case '6': case '7': case '8': case '9':
  171. if (nonzero)
  172. {
  173. real x = ret + ret;
  174. x = x + x + ret;
  175. ret = x + x;
  176. }
  177. if (*p != '0')
  178. {
  179. ret += (int)(*p - '0');
  180. nonzero = true;
  181. }
  182. if (comma)
  183. exponent--;
  184. break;
  185. case 'e':
  186. case 'E':
  187. exponent += atoi(p + 1);
  188. finished = true;
  189. break;
  190. default:
  191. finished = true;
  192. break;
  193. }
  194. }
  195. if (exponent)
  196. ret *= pow(R_10(), (real)exponent);
  197. if (negative)
  198. ret = -ret;
  199. new(this) real(ret);
  200. }
  201. template<> real real::operator +() const
  202. {
  203. return *this;
  204. }
  205. template<> real real::operator -() const
  206. {
  207. real ret = *this;
  208. ret.m_signexp ^= 0x80000000u;
  209. return ret;
  210. }
  211. template<> real real::operator +(real const &x) const
  212. {
  213. if (x.m_signexp << 1 == 0)
  214. return *this;
  215. /* Ensure both arguments are positive. Otherwise, switch signs,
  216. * or replace + with -. */
  217. if (m_signexp >> 31)
  218. return -(-*this + -x);
  219. if (x.m_signexp >> 31)
  220. return *this - (-x);
  221. /* Ensure *this has the larger exponent (no need for the mantissa to
  222. * be larger, as in subtraction). Otherwise, switch. */
  223. if ((m_signexp << 1) < (x.m_signexp << 1))
  224. return x + *this;
  225. real ret;
  226. int e1 = m_signexp - (1 << 30) + 1;
  227. int e2 = x.m_signexp - (1 << 30) + 1;
  228. int bigoff = (e1 - e2) / BIGIT_BITS;
  229. int off = e1 - e2 - bigoff * BIGIT_BITS;
  230. if (bigoff > BIGITS)
  231. return *this;
  232. ret.m_signexp = m_signexp;
  233. uint64_t carry = 0;
  234. for (int i = BIGITS; i--; )
  235. {
  236. carry += m_mantissa[i];
  237. if (i - bigoff >= 0)
  238. carry += x.m_mantissa[i - bigoff] >> off;
  239. if (off && i - bigoff > 0)
  240. carry += (x.m_mantissa[i - bigoff - 1] << (BIGIT_BITS - off)) & 0xffffffffu;
  241. else if (i - bigoff == 0)
  242. carry += (uint64_t)1 << (BIGIT_BITS - off);
  243. ret.m_mantissa[i] = (uint32_t)carry;
  244. carry >>= BIGIT_BITS;
  245. }
  246. /* Renormalise in case we overflowed the mantissa */
  247. if (carry)
  248. {
  249. carry--;
  250. for (int i = 0; i < BIGITS; i++)
  251. {
  252. uint32_t tmp = ret.m_mantissa[i];
  253. ret.m_mantissa[i] = ((uint32_t)carry << (BIGIT_BITS - 1))
  254. | (tmp >> 1);
  255. carry = tmp & 1u;
  256. }
  257. ret.m_signexp++;
  258. }
  259. return ret;
  260. }
  261. template<> real real::operator -(real const &x) const
  262. {
  263. if (x.m_signexp << 1 == 0)
  264. return *this;
  265. /* Ensure both arguments are positive. Otherwise, switch signs,
  266. * or replace - with +. */
  267. if (m_signexp >> 31)
  268. return -(-*this + x);
  269. if (x.m_signexp >> 31)
  270. return (*this) + (-x);
  271. /* Ensure *this is larger than x */
  272. if (*this < x)
  273. return -(x - *this);
  274. real ret;
  275. int e1 = m_signexp - (1 << 30) + 1;
  276. int e2 = x.m_signexp - (1 << 30) + 1;
  277. int bigoff = (e1 - e2) / BIGIT_BITS;
  278. int off = e1 - e2 - bigoff * BIGIT_BITS;
  279. if (bigoff > BIGITS)
  280. return *this;
  281. ret.m_signexp = m_signexp;
  282. /* int64_t instead of uint64_t to preserve sign through shifts */
  283. int64_t carry = 0;
  284. for (int i = 0; i < bigoff; i++)
  285. {
  286. carry -= x.m_mantissa[BIGITS - 1 - i];
  287. /* Emulates a signed shift */
  288. carry >>= BIGIT_BITS;
  289. carry |= carry << BIGIT_BITS;
  290. }
  291. if (bigoff < BIGITS)
  292. carry -= x.m_mantissa[BIGITS - 1 - bigoff] & (((int64_t)1 << off) - 1);
  293. carry /= (int64_t)1 << off;
  294. for (int i = BIGITS; i--; )
  295. {
  296. carry += m_mantissa[i];
  297. if (i - bigoff >= 0)
  298. carry -= x.m_mantissa[i - bigoff] >> off;
  299. if (off && i - bigoff > 0)
  300. carry -= (x.m_mantissa[i - bigoff - 1] << (BIGIT_BITS - off)) & 0xffffffffu;
  301. else if (i - bigoff == 0)
  302. carry -= (uint64_t)1 << (BIGIT_BITS - off);
  303. ret.m_mantissa[i] = (uint32_t)carry;
  304. carry >>= BIGIT_BITS;
  305. carry |= carry << BIGIT_BITS;
  306. }
  307. carry += 1;
  308. /* Renormalise if we underflowed the mantissa */
  309. if (carry == 0)
  310. {
  311. /* How much do we need to shift the mantissa? FIXME: this could
  312. * be computed above */
  313. off = 0;
  314. for (int i = 0; i < BIGITS; i++)
  315. {
  316. if (!ret.m_mantissa[i])
  317. {
  318. off += BIGIT_BITS;
  319. continue;
  320. }
  321. for (uint32_t tmp = ret.m_mantissa[i]; tmp < 0x80000000u; tmp <<= 1)
  322. off++;
  323. break;
  324. }
  325. if (off == BIGITS * BIGIT_BITS)
  326. ret.m_signexp &= 0x80000000u;
  327. else
  328. {
  329. off++; /* Shift one more to get rid of the leading one */
  330. ret.m_signexp -= off;
  331. bigoff = off / BIGIT_BITS;
  332. off -= bigoff * BIGIT_BITS;
  333. for (int i = 0; i < BIGITS; i++)
  334. {
  335. uint32_t tmp = 0;
  336. if (i + bigoff < BIGITS)
  337. tmp |= ret.m_mantissa[i + bigoff] << off;
  338. if (off && i + bigoff + 1 < BIGITS)
  339. tmp |= ret.m_mantissa[i + bigoff + 1] >> (BIGIT_BITS - off);
  340. ret.m_mantissa[i] = tmp;
  341. }
  342. }
  343. }
  344. return ret;
  345. }
  346. template<> real real::operator *(real const &x) const
  347. {
  348. real ret;
  349. if (m_signexp << 1 == 0 || x.m_signexp << 1 == 0)
  350. {
  351. ret = (m_signexp << 1 == 0) ? *this : x;
  352. ret.m_signexp ^= x.m_signexp & 0x80000000u;
  353. return ret;
  354. }
  355. ret.m_signexp = (m_signexp ^ x.m_signexp) & 0x80000000u;
  356. int e = (m_signexp & 0x7fffffffu) - (1 << 30) + 1
  357. + (x.m_signexp & 0x7fffffffu) - (1 << 30) + 1;
  358. /* Accumulate low order product; no need to store it, we just
  359. * want the carry value */
  360. uint64_t carry = 0, hicarry = 0, prev;
  361. for (int i = 0; i < BIGITS; i++)
  362. {
  363. for (int j = 0; j < i + 1; j++)
  364. {
  365. prev = carry;
  366. carry += (uint64_t)m_mantissa[BIGITS - 1 - j]
  367. * (uint64_t)x.m_mantissa[BIGITS - 1 + j - i];
  368. if (carry < prev)
  369. hicarry++;
  370. }
  371. carry >>= BIGIT_BITS;
  372. carry |= hicarry << BIGIT_BITS;
  373. hicarry >>= BIGIT_BITS;
  374. }
  375. for (int i = 0; i < BIGITS; i++)
  376. {
  377. for (int j = i + 1; j < BIGITS; j++)
  378. {
  379. prev = carry;
  380. carry += (uint64_t)m_mantissa[BIGITS - 1 - j]
  381. * (uint64_t)x.m_mantissa[j - 1 - i];
  382. if (carry < prev)
  383. hicarry++;
  384. }
  385. prev = carry;
  386. carry += m_mantissa[BIGITS - 1 - i];
  387. carry += x.m_mantissa[BIGITS - 1 - i];
  388. if (carry < prev)
  389. hicarry++;
  390. ret.m_mantissa[BIGITS - 1 - i] = carry & 0xffffffffu;
  391. carry >>= BIGIT_BITS;
  392. carry |= hicarry << BIGIT_BITS;
  393. hicarry >>= BIGIT_BITS;
  394. }
  395. /* Renormalise in case we overflowed the mantissa */
  396. if (carry)
  397. {
  398. carry--;
  399. for (int i = 0; i < BIGITS; i++)
  400. {
  401. uint32_t tmp = (uint32_t)ret.m_mantissa[i];
  402. ret.m_mantissa[i] = ((uint32_t)carry << (BIGIT_BITS - 1))
  403. | (tmp >> 1);
  404. carry = tmp & 1u;
  405. }
  406. e++;
  407. }
  408. ret.m_signexp |= e + (1 << 30) - 1;
  409. return ret;
  410. }
  411. template<> real real::operator /(real const &x) const
  412. {
  413. return *this * re(x);
  414. }
  415. template<> real const &real::operator +=(real const &x)
  416. {
  417. real tmp = *this;
  418. return *this = tmp + x;
  419. }
  420. template<> real const &real::operator -=(real const &x)
  421. {
  422. real tmp = *this;
  423. return *this = tmp - x;
  424. }
  425. template<> real const &real::operator *=(real const &x)
  426. {
  427. real tmp = *this;
  428. return *this = tmp * x;
  429. }
  430. template<> real const &real::operator /=(real const &x)
  431. {
  432. real tmp = *this;
  433. return *this = tmp / x;
  434. }
  435. template<> bool real::operator ==(real const &x) const
  436. {
  437. if ((m_signexp << 1) == 0 && (x.m_signexp << 1) == 0)
  438. return true;
  439. if (m_signexp != x.m_signexp)
  440. return false;
  441. return memcmp(m_mantissa, x.m_mantissa, BIGITS * sizeof(uint32_t)) == 0;
  442. }
  443. template<> bool real::operator !=(real const &x) const
  444. {
  445. return !(*this == x);
  446. }
  447. template<> bool real::operator <(real const &x) const
  448. {
  449. /* Ensure both numbers are positive */
  450. if (m_signexp >> 31)
  451. return (x.m_signexp >> 31) ? -*this > -x : true;
  452. if (x.m_signexp >> 31)
  453. return false;
  454. /* Compare all relevant bits */
  455. if (m_signexp != x.m_signexp)
  456. return m_signexp < x.m_signexp;
  457. for (int i = 0; i < BIGITS; i++)
  458. if (m_mantissa[i] != x.m_mantissa[i])
  459. return m_mantissa[i] < x.m_mantissa[i];
  460. return false;
  461. }
  462. template<> bool real::operator <=(real const &x) const
  463. {
  464. return !(*this > x);
  465. }
  466. template<> bool real::operator >(real const &x) const
  467. {
  468. /* Ensure both numbers are positive */
  469. if (m_signexp >> 31)
  470. return (x.m_signexp >> 31) ? -*this < -x : false;
  471. if (x.m_signexp >> 31)
  472. return true;
  473. /* Compare all relevant bits */
  474. if (m_signexp != x.m_signexp)
  475. return m_signexp > x.m_signexp;
  476. for (int i = 0; i < BIGITS; i++)
  477. if (m_mantissa[i] != x.m_mantissa[i])
  478. return m_mantissa[i] > x.m_mantissa[i];
  479. return false;
  480. }
  481. template<> bool real::operator >=(real const &x) const
  482. {
  483. return !(*this < x);
  484. }
  485. template<> bool real::operator !() const
  486. {
  487. return !(bool)*this;
  488. }
  489. template<> real::operator bool() const
  490. {
  491. /* A real is "true" if it is non-zero (exponent is non-zero) AND
  492. * not NaN (exponent is not full bits OR higher order mantissa is zero) */
  493. uint32_t exponent = m_signexp << 1;
  494. return exponent && (~exponent || m_mantissa[0] == 0);
  495. }
  496. template<> real min(real const &a, real const &b)
  497. {
  498. return (a < b) ? a : b;
  499. }
  500. template<> real max(real const &a, real const &b)
  501. {
  502. return (a > b) ? a : b;
  503. }
  504. template<> real clamp(real const &x, real const &a, real const &b)
  505. {
  506. return (x < a) ? a : (x > b) ? b : x;
  507. }
  508. template<> real re(real const &x)
  509. {
  510. if (!(x.m_signexp << 1))
  511. {
  512. real ret = x;
  513. ret.m_signexp = x.m_signexp | 0x7fffffffu;
  514. ret.m_mantissa[0] = 0;
  515. return ret;
  516. }
  517. /* Use the system's float inversion to approximate 1/x */
  518. union { float f; uint32_t x; } u = { 1.0f }, v = { 1.0f };
  519. v.x |= x.m_mantissa[0] >> 9;
  520. v.f = 1.0f / v.f;
  521. real ret;
  522. ret.m_mantissa[0] = v.x << 9;
  523. uint32_t sign = x.m_signexp & 0x80000000u;
  524. ret.m_signexp = sign;
  525. int exponent = (x.m_signexp & 0x7fffffffu) + 1;
  526. exponent = -exponent + (v.x >> 23) - (u.x >> 23);
  527. ret.m_signexp |= (exponent - 1) & 0x7fffffffu;
  528. /* FIXME: 1+log2(BIGITS) steps of Newton-Raphson seems to be enough for
  529. * convergence, but this hasn't been checked seriously. */
  530. for (int i = 1; i <= real::BIGITS; i *= 2)
  531. ret = ret * (real::R_2() - ret * x);
  532. return ret;
  533. }
  534. template<> real sqrt(real const &x)
  535. {
  536. /* if zero, return x */
  537. if (!(x.m_signexp << 1))
  538. return x;
  539. /* if negative, return NaN */
  540. if (x.m_signexp >> 31)
  541. {
  542. real ret;
  543. ret.m_signexp = 0x7fffffffu;
  544. ret.m_mantissa[0] = 0xffffu;
  545. return ret;
  546. }
  547. /* Use the system's float inversion to approximate 1/sqrt(x). First
  548. * we construct a float in the [1..4[ range that has roughly the same
  549. * mantissa as our real. Its exponent is 0 or 1, depending on the
  550. * partity of x. The final exponent is 0, -1 or -2. We use the final
  551. * exponent and final mantissa to pre-fill the result. */
  552. union { float f; uint32_t x; } u = { 1.0f }, v = { 2.0f };
  553. v.x -= ((x.m_signexp & 1) << 23);
  554. v.x |= x.m_mantissa[0] >> 9;
  555. v.f = 1.0f / sqrtf(v.f);
  556. real ret;
  557. ret.m_mantissa[0] = v.x << 9;
  558. uint32_t sign = x.m_signexp & 0x80000000u;
  559. ret.m_signexp = sign;
  560. uint32_t exponent = (x.m_signexp & 0x7fffffffu);
  561. exponent = ((1 << 30) + (1 << 29) - 1) - (exponent + 1) / 2;
  562. exponent = exponent + (v.x >> 23) - (u.x >> 23);
  563. ret.m_signexp |= exponent & 0x7fffffffu;
  564. /* FIXME: 1+log2(BIGITS) steps of Newton-Raphson seems to be enough for
  565. * convergence, but this hasn't been checked seriously. */
  566. for (int i = 1; i <= real::BIGITS; i *= 2)
  567. {
  568. ret = ret * (real::R_3() - ret * ret * x);
  569. ret.m_signexp--;
  570. }
  571. return ret * x;
  572. }
  573. template<> real cbrt(real const &x)
  574. {
  575. /* if zero, return x */
  576. if (!(x.m_signexp << 1))
  577. return x;
  578. /* Use the system's float inversion to approximate cbrt(x). First
  579. * we construct a float in the [1..8[ range that has roughly the same
  580. * mantissa as our real. Its exponent is 0, 1 or 2, depending on the
  581. * value of x. The final exponent is 0 or 1 (special case). We use
  582. * the final exponent and final mantissa to pre-fill the result. */
  583. union { float f; uint32_t x; } u = { 1.0f }, v = { 1.0f };
  584. v.x += ((x.m_signexp % 3) << 23);
  585. v.x |= x.m_mantissa[0] >> 9;
  586. v.f = powf(v.f, 0.33333333333333333f);
  587. real ret;
  588. ret.m_mantissa[0] = v.x << 9;
  589. uint32_t sign = x.m_signexp & 0x80000000u;
  590. ret.m_signexp = sign;
  591. int exponent = (x.m_signexp & 0x7fffffffu) - (1 << 30) + 1;
  592. exponent = exponent / 3 + (v.x >> 23) - (u.x >> 23);
  593. ret.m_signexp |= (exponent + (1 << 30) - 1) & 0x7fffffffu;
  594. /* FIXME: 1+log2(BIGITS) steps of Newton-Raphson seems to be enough for
  595. * convergence, but this hasn't been checked seriously. */
  596. for (int i = 1; i <= real::BIGITS; i *= 2)
  597. {
  598. static real third = re(real::R_3());
  599. ret = third * (x / (ret * ret) + (ret / 2));
  600. }
  601. return ret;
  602. }
  603. template<> real pow(real const &x, real const &y)
  604. {
  605. if (!y)
  606. return real::R_1();
  607. if (!x)
  608. return real::R_0();
  609. if (x > real::R_0())
  610. return exp(y * log(x));
  611. else /* x < 0 */
  612. {
  613. /* Odd integer exponent */
  614. if (y == (round(y / 2) * 2))
  615. return exp(y * log(-x));
  616. /* Even integer exponent */
  617. if (y == round(y))
  618. return -exp(y * log(-x));
  619. /* FIXME: negative nth root */
  620. return real::R_0();
  621. }
  622. }
  623. static real fast_fact(unsigned int x)
  624. {
  625. real ret = real::R_1();
  626. unsigned int i = 1, multiplier = 1, exponent = 0;
  627. for (;;)
  628. {
  629. if (i++ >= x)
  630. /* Multiplication is a no-op if multiplier == 1 */
  631. return ldexp(ret * multiplier, exponent);
  632. unsigned int tmp = i;
  633. while ((tmp & 1) == 0)
  634. {
  635. tmp >>= 1;
  636. exponent++;
  637. }
  638. if (multiplier * tmp / tmp != multiplier)
  639. {
  640. ret *= multiplier;
  641. multiplier = 1;
  642. }
  643. multiplier *= tmp;
  644. }
  645. }
  646. template<> real gamma(real const &x)
  647. {
  648. /* We use Spouge's formula. FIXME: precision is far from acceptable,
  649. * especially with large values. We need to compute this with higher
  650. * precision values in order to attain the desired accuracy. It might
  651. * also be useful to sort the ck values by decreasing absolute value
  652. * and do the addition in this order. */
  653. int a = (int)ceilf(logf(2) / logf(2 * F_PI)
  654. * real::BIGITS * real::BIGIT_BITS);
  655. real ret = sqrt(real::R_PI() * 2);
  656. real fact_k_1 = real::R_1();
  657. for (int k = 1; k < a; k++)
  658. {
  659. real a_k = (real)(a - k);
  660. real ck = pow(a_k, (real)((float)k - 0.5)) * exp(a_k)
  661. / (fact_k_1 * (x + (real)(k - 1)));
  662. ret += ck;
  663. fact_k_1 *= (real)-k;
  664. }
  665. ret *= pow(x + (real)(a - 1), x - (real::R_1() / 2));
  666. ret *= exp(-x - (real)(a - 1));
  667. return ret;
  668. }
  669. template<> real fabs(real const &x)
  670. {
  671. real ret = x;
  672. ret.m_signexp &= 0x7fffffffu;
  673. return ret;
  674. }
  675. template<> real abs(real const &x)
  676. {
  677. return fabs(x);
  678. }
  679. template<> real fract(real const &x)
  680. {
  681. return x - floor(x);
  682. }
  683. template<> real degrees(real const &x)
  684. {
  685. static real mul = real(180) * real::R_1_PI();
  686. return x * mul;
  687. }
  688. template<> real radians(real const &x)
  689. {
  690. static real mul = real::R_PI() / real(180);
  691. return x * mul;
  692. }
  693. static real fast_log(real const &x)
  694. {
  695. /* This fast log method is tuned to work on the [1..2] range and
  696. * no effort whatsoever was made to improve convergence outside this
  697. * domain of validity. It can converge pretty fast, provided we use
  698. * the following variable substitutions:
  699. * y = sqrt(x)
  700. * z = (y - 1) / (y + 1)
  701. *
  702. * And the following identities:
  703. * ln(x) = 2 ln(y)
  704. * = 2 ln((1 + z) / (1 - z))
  705. * = 4 z (1 + z^2 / 3 + z^4 / 5 + z^6 / 7...)
  706. *
  707. * Any additional sqrt() call would halve the convergence time, but
  708. * would also impact the final precision. For now we stick with one
  709. * sqrt() call. */
  710. real y = sqrt(x);
  711. real z = (y - real::R_1()) / (y + real::R_1()), z2 = z * z, zn = z2;
  712. real sum = real::R_1();
  713. for (int i = 3; ; i += 2)
  714. {
  715. real newsum = sum + zn / (real)i;
  716. if (newsum == sum)
  717. break;
  718. sum = newsum;
  719. zn *= z2;
  720. }
  721. return z * sum * 4;
  722. }
  723. template<> real log(real const &x)
  724. {
  725. /* Strategy for log(x): if x = 2^E*M then log(x) = E log(2) + log(M),
  726. * with the property that M is in [1..2[, so fast_log() applies here. */
  727. real tmp = x;
  728. if (x.m_signexp >> 31 || x.m_signexp == 0)
  729. {
  730. tmp.m_signexp = 0xffffffffu;
  731. tmp.m_mantissa[0] = 0xffffffffu;
  732. return tmp;
  733. }
  734. tmp.m_signexp = (1 << 30) - 1;
  735. return (real)(int)(x.m_signexp - (1 << 30) + 1) * real::R_LN2()
  736. + fast_log(tmp);
  737. }
  738. template<> real log2(real const &x)
  739. {
  740. /* Strategy for log2(x): see log(x). */
  741. real tmp = x;
  742. if (x.m_signexp >> 31 || x.m_signexp == 0)
  743. {
  744. tmp.m_signexp = 0xffffffffu;
  745. tmp.m_mantissa[0] = 0xffffffffu;
  746. return tmp;
  747. }
  748. tmp.m_signexp = (1 << 30) - 1;
  749. return (real)(int)(x.m_signexp - (1 << 30) + 1)
  750. + fast_log(tmp) * real::R_LOG2E();
  751. }
  752. template<> real log10(real const &x)
  753. {
  754. return log(x) * real::R_LOG10E();
  755. }
  756. static real fast_exp_sub(real const &x, real const &y)
  757. {
  758. /* This fast exp method is tuned to work on the [-1..1] range and
  759. * no effort whatsoever was made to improve convergence outside this
  760. * domain of validity. The argument y is used for cases where we
  761. * don't want the leading 1 in the Taylor series. */
  762. real ret = real::R_1() - y, xn = x;
  763. int i = 1;
  764. for (;;)
  765. {
  766. real newret = ret + xn;
  767. if (newret == ret)
  768. break;
  769. ret = newret * ++i;
  770. xn *= x;
  771. }
  772. return ret / fast_fact(i);
  773. }
  774. template<> real exp(real const &x)
  775. {
  776. /* Strategy for exp(x): the Taylor series does not converge very fast
  777. * with large positive or negative values.
  778. *
  779. * However, we know that the result is going to be in the form M*2^E,
  780. * where M is the mantissa and E the exponent. We first try to predict
  781. * a value for E, which is approximately log2(exp(x)) = x / log(2).
  782. *
  783. * Let E0 be an integer close to x / log(2). We need to find a value x0
  784. * such that exp(x) = 2^E0 * exp(x0). We get x0 = x - E0 log(2).
  785. *
  786. * Thus the final algorithm:
  787. * int E0 = x / log(2)
  788. * real x0 = x - E0 log(2)
  789. * real x1 = exp(x0)
  790. * return x1 * 2^E0
  791. */
  792. int e0 = x / real::R_LN2();
  793. real x0 = x - (real)e0 * real::R_LN2();
  794. real x1 = fast_exp_sub(x0, real::R_0());
  795. x1.m_signexp += e0;
  796. return x1;
  797. }
  798. template<> real exp2(real const &x)
  799. {
  800. /* Strategy for exp2(x): see strategy in exp(). */
  801. int e0 = x;
  802. real x0 = x - (real)e0;
  803. real x1 = fast_exp_sub(x0 * real::R_LN2(), real::R_0());
  804. x1.m_signexp += e0;
  805. return x1;
  806. }
  807. template<> real sinh(real const &x)
  808. {
  809. /* We cannot always use (exp(x)-exp(-x))/2 because we'll lose
  810. * accuracy near zero. We only use this identity for |x|>0.5. If
  811. * |x|<=0.5, we compute exp(x)-1 and exp(-x)-1 instead. */
  812. bool near_zero = (fabs(x) < real::R_1() / 2);
  813. real x1 = near_zero ? fast_exp_sub(x, real::R_1()) : exp(x);
  814. real x2 = near_zero ? fast_exp_sub(-x, real::R_1()) : exp(-x);
  815. return (x1 - x2) / 2;
  816. }
  817. template<> real tanh(real const &x)
  818. {
  819. /* See sinh() for the strategy here */
  820. bool near_zero = (fabs(x) < real::R_1() / 2);
  821. real x1 = near_zero ? fast_exp_sub(x, real::R_1()) : exp(x);
  822. real x2 = near_zero ? fast_exp_sub(-x, real::R_1()) : exp(-x);
  823. real x3 = near_zero ? x1 + x2 + real::R_2() : x1 + x2;
  824. return (x1 - x2) / x3;
  825. }
  826. template<> real cosh(real const &x)
  827. {
  828. /* No need to worry about accuracy here; maybe the last bit is slightly
  829. * off, but that's about it. */
  830. return (exp(x) + exp(-x)) / 2;
  831. }
  832. template<> real frexp(real const &x, int *exp)
  833. {
  834. if (!x)
  835. {
  836. *exp = 0;
  837. return x;
  838. }
  839. real ret = x;
  840. int exponent = (ret.m_signexp & 0x7fffffffu) - (1 << 30) + 1;
  841. *exp = exponent + 1;
  842. ret.m_signexp -= exponent + 1;
  843. return ret;
  844. }
  845. template<> real ldexp(real const &x, int exp)
  846. {
  847. real ret = x;
  848. if (ret)
  849. ret.m_signexp += exp;
  850. return ret;
  851. }
  852. template<> real modf(real const &x, real *iptr)
  853. {
  854. real absx = fabs(x);
  855. real tmp = floor(absx);
  856. *iptr = copysign(tmp, x);
  857. return copysign(absx - tmp, x);
  858. }
  859. template<> real ulp(real const &x)
  860. {
  861. real ret = real::R_1();
  862. if (x)
  863. ret.m_signexp = x.m_signexp + 1 - real::BIGITS * real::BIGIT_BITS;
  864. else
  865. ret.m_signexp = 0;
  866. return ret;
  867. }
  868. template<> real nextafter(real const &x, real const &y)
  869. {
  870. if (x == y)
  871. return x;
  872. else if (x < y)
  873. return x + ulp(x);
  874. else
  875. return x - ulp(x);
  876. }
  877. template<> real copysign(real const &x, real const &y)
  878. {
  879. real ret = x;
  880. ret.m_signexp &= 0x7fffffffu;
  881. ret.m_signexp |= y.m_signexp & 0x80000000u;
  882. return ret;
  883. }
  884. template<> real floor(real const &x)
  885. {
  886. /* Strategy for floor(x):
  887. * - if negative, return -ceil(-x)
  888. * - if zero or negative zero, return x
  889. * - if less than one, return zero
  890. * - otherwise, if e is the exponent, clear all bits except the
  891. * first e. */
  892. if (x < -real::R_0())
  893. return -ceil(-x);
  894. if (!x)
  895. return x;
  896. if (x < real::R_1())
  897. return real::R_0();
  898. real ret = x;
  899. int exponent = x.m_signexp - (1 << 30) + 1;
  900. for (int i = 0; i < real::BIGITS; i++)
  901. {
  902. if (exponent <= 0)
  903. ret.m_mantissa[i] = 0;
  904. else if (exponent < real::BIGIT_BITS)
  905. ret.m_mantissa[i] &= ~((1 << (real::BIGIT_BITS - exponent)) - 1);
  906. exponent -= real::BIGIT_BITS;
  907. }
  908. return ret;
  909. }
  910. template<> real ceil(real const &x)
  911. {
  912. /* Strategy for ceil(x):
  913. * - if negative, return -floor(-x)
  914. * - if x == floor(x), return x
  915. * - otherwise, return floor(x) + 1 */
  916. if (x < -real::R_0())
  917. return -floor(-x);
  918. real ret = floor(x);
  919. if (x == ret)
  920. return ret;
  921. else
  922. return ret + real::R_1();
  923. }
  924. template<> real round(real const &x)
  925. {
  926. if (x < real::R_0())
  927. return -round(-x);
  928. return floor(x + (real::R_1() / 2));
  929. }
  930. template<> real fmod(real const &x, real const &y)
  931. {
  932. if (!y)
  933. return real::R_0(); /* FIXME: return NaN */
  934. if (!x)
  935. return x;
  936. real tmp = round(x / y);
  937. return x - tmp * y;
  938. }
  939. template<> real sin(real const &x)
  940. {
  941. int switch_sign = x.m_signexp & 0x80000000u;
  942. real absx = fmod(fabs(x), real::R_PI() * 2);
  943. if (absx > real::R_PI())
  944. {
  945. absx -= real::R_PI();
  946. switch_sign = !switch_sign;
  947. }
  948. if (absx > real::R_PI_2())
  949. absx = real::R_PI() - absx;
  950. real ret = real::R_0(), fact = real::R_1(), xn = absx, mx2 = -absx * absx;
  951. int i = 1;
  952. for (;;)
  953. {
  954. real newret = ret + xn;
  955. if (newret == ret)
  956. break;
  957. ret = newret * ((i + 1) * (i + 2));
  958. xn *= mx2;
  959. i += 2;
  960. }
  961. ret /= fast_fact(i);
  962. /* Propagate sign */
  963. if (switch_sign)
  964. ret.m_signexp ^= 0x80000000u;
  965. return ret;
  966. }
  967. template<> real cos(real const &x)
  968. {
  969. return sin(real::R_PI_2() - x);
  970. }
  971. template<> real tan(real const &x)
  972. {
  973. /* Constrain input to [-π,π] */
  974. real y = fmod(x, real::R_PI());
  975. /* Constrain input to [-π/2,π/2] */
  976. if (y < -real::R_PI_2())
  977. y += real::R_PI();
  978. else if (y > real::R_PI_2())
  979. y -= real::R_PI();
  980. /* In [-π/4,π/4] return sin/cos */
  981. if (fabs(y) <= real::R_PI_4())
  982. return sin(y) / cos(y);
  983. /* Otherwise, return cos/sin */
  984. if (y > real::R_0())
  985. y = real::R_PI_2() - y;
  986. else
  987. y = -real::R_PI_2() - y;
  988. return cos(y) / sin(y);
  989. }
  990. static inline real asinacos(real const &x, int is_asin, int is_negative)
  991. {
  992. /* Strategy for asin(): in [-0.5..0.5], use a Taylor series around
  993. * zero. In [0.5..1], use asin(x) = π/2 - 2*asin(sqrt((1-x)/2)), and
  994. * in [-1..-0.5] just revert the sign.
  995. * Strategy for acos(): use acos(x) = π/2 - asin(x) and try not to
  996. * lose the precision around x=1. */
  997. real absx = fabs(x);
  998. int around_zero = (absx < (real::R_1() / 2));
  999. if (!around_zero)
  1000. absx = sqrt((real::R_1() - absx) / 2);
  1001. real ret = absx, xn = absx, x2 = absx * absx, fact1 = 2, fact2 = 1;
  1002. for (int i = 1; ; i++)
  1003. {
  1004. xn *= x2;
  1005. real mul = (real)(2 * i + 1);
  1006. real newret = ret + ldexp(fact1 * xn / (mul * fact2), -2 * i);
  1007. if (newret == ret)
  1008. break;
  1009. ret = newret;
  1010. fact1 *= (real)((2 * i + 1) * (2 * i + 2));
  1011. fact2 *= (real)((i + 1) * (i + 1));
  1012. }
  1013. if (is_negative)
  1014. ret = -ret;
  1015. if (around_zero)
  1016. ret = is_asin ? ret : real::R_PI_2() - ret;
  1017. else
  1018. {
  1019. real adjust = is_negative ? real::R_PI() : real::R_0();
  1020. if (is_asin)
  1021. ret = real::R_PI_2() - adjust - ret * 2;
  1022. else
  1023. ret = adjust + ret * 2;
  1024. }
  1025. return ret;
  1026. }
  1027. template<> real asin(real const &x)
  1028. {
  1029. return asinacos(x, 1, x.m_signexp >> 31);
  1030. }
  1031. template<> real acos(real const &x)
  1032. {
  1033. return asinacos(x, 0, x.m_signexp >> 31);
  1034. }
  1035. template<> real atan(real const &x)
  1036. {
  1037. /* Computing atan(x): we choose a different Taylor series depending on
  1038. * the value of x to help with convergence.
  1039. *
  1040. * If |x| < 0.5 we evaluate atan(y) near 0:
  1041. * atan(y) = y - y^3/3 + y^5/5 - y^7/7 + y^9/9 ...
  1042. *
  1043. * If 0.5 <= |x| < 1.5 we evaluate atan(1+y) near 0:
  1044. * atan(1+y) = π/4 + y/(1*2^1) - y^2/(2*2^1) + y^3/(3*2^2)
  1045. * - y^5/(5*2^3) + y^6/(6*2^3) - y^7/(7*2^4)
  1046. * + y^9/(9*2^5) - y^10/(10*2^5) + y^11/(11*2^6) ...
  1047. *
  1048. * If 1.5 <= |x| < 2 we evaluate atan(sqrt(3)+2y) near 0:
  1049. * atan(sqrt(3)+2y) = π/3 + 1/2 y - sqrt(3)/2 y^2/2
  1050. * + y^3/3 - sqrt(3)/2 y^4/4 + 1/2 y^5/5
  1051. * - 1/2 y^7/7 + sqrt(3)/2 y^8/8
  1052. * - y^9/9 + sqrt(3)/2 y^10/10 - 1/2 y^11/11
  1053. * + 1/2 y^13/13 - sqrt(3)/2 y^14/14
  1054. * + y^15/15 - sqrt(3)/2 y^16/16 + 1/2 y^17/17 ...
  1055. *
  1056. * If |x| >= 2 we evaluate atan(y) near +∞:
  1057. * atan(y) = π/2 - y^-1 + y^-3/3 - y^-5/5 + y^-7/7 - y^-9/9 ...
  1058. */
  1059. real absx = fabs(x);
  1060. if (absx < (real::R_1() / 2))
  1061. {
  1062. real ret = x, xn = x, mx2 = -x * x;
  1063. for (int i = 3; ; i += 2)
  1064. {
  1065. xn *= mx2;
  1066. real newret = ret + xn / (real)i;
  1067. if (newret == ret)
  1068. break;
  1069. ret = newret;
  1070. }
  1071. return ret;
  1072. }
  1073. real ret = 0;
  1074. if (absx < (real::R_3() / 2))
  1075. {
  1076. real y = real::R_1() - absx;
  1077. real yn = y, my2 = -y * y;
  1078. for (int i = 0; ; i += 2)
  1079. {
  1080. real newret = ret + ldexp(yn / (real)(2 * i + 1), -i - 1);
  1081. yn *= y;
  1082. newret += ldexp(yn / (real)(2 * i + 2), -i - 1);
  1083. yn *= y;
  1084. newret += ldexp(yn / (real)(2 * i + 3), -i - 2);
  1085. if (newret == ret)
  1086. break;
  1087. ret = newret;
  1088. yn *= my2;
  1089. }
  1090. ret = real::R_PI_4() - ret;
  1091. }
  1092. else if (absx < real::R_2())
  1093. {
  1094. real y = (absx - real::R_SQRT3()) / 2;
  1095. real yn = y, my2 = -y * y;
  1096. for (int i = 1; ; i += 6)
  1097. {
  1098. real newret = ret + ((yn / (real)i) / 2);
  1099. yn *= y;
  1100. newret -= (real::R_SQRT3() / 2) * yn / (real)(i + 1);
  1101. yn *= y;
  1102. newret += yn / (real)(i + 2);
  1103. yn *= y;
  1104. newret -= (real::R_SQRT3() / 2) * yn / (real)(i + 3);
  1105. yn *= y;
  1106. newret += (yn / (real)(i + 4)) / 2;
  1107. if (newret == ret)
  1108. break;
  1109. ret = newret;
  1110. yn *= my2;
  1111. }
  1112. ret = real::R_PI_3() + ret;
  1113. }
  1114. else
  1115. {
  1116. real y = re(absx);
  1117. real yn = y, my2 = -y * y;
  1118. ret = y;
  1119. for (int i = 3; ; i += 2)
  1120. {
  1121. yn *= my2;
  1122. real newret = ret + yn / (real)i;
  1123. if (newret == ret)
  1124. break;
  1125. ret = newret;
  1126. }
  1127. ret = real::R_PI_2() - ret;
  1128. }
  1129. /* Propagate sign */
  1130. ret.m_signexp |= (x.m_signexp & 0x80000000u);
  1131. return ret;
  1132. }
  1133. template<> real atan2(real const &y, real const &x)
  1134. {
  1135. if (!y)
  1136. {
  1137. if ((x.m_signexp >> 31) == 0)
  1138. return y;
  1139. if (y.m_signexp >> 31)
  1140. return -real::R_PI();
  1141. return real::R_PI();
  1142. }
  1143. if (!x)
  1144. {
  1145. if (y.m_signexp >> 31)
  1146. return -real::R_PI();
  1147. return real::R_PI();
  1148. }
  1149. /* FIXME: handle the Inf and NaN cases */
  1150. real z = y / x;
  1151. real ret = atan(z);
  1152. if (x < real::R_0())
  1153. ret += (y > real::R_0()) ? real::R_PI() : -real::R_PI();
  1154. return ret;
  1155. }
  1156. template<> void real::hexprint() const
  1157. {
  1158. std::printf("%08x", m_signexp);
  1159. for (int i = 0; i < BIGITS; i++)
  1160. std::printf(" %08x", m_mantissa[i]);
  1161. }
  1162. template<> void real::sprintf(char *str, int ndigits) const;
  1163. template<> void real::print(int ndigits) const
  1164. {
  1165. char *buf = new char[ndigits + 32 + 10];
  1166. real::sprintf(buf, ndigits);
  1167. std::printf("%s", buf);
  1168. delete[] buf;
  1169. }
  1170. template<> void real::sprintf(char *str, int ndigits) const
  1171. {
  1172. real x = *this;
  1173. if (x.m_signexp >> 31)
  1174. {
  1175. *str++ = '-';
  1176. x = -x;
  1177. }
  1178. if (!x)
  1179. {
  1180. std::strcpy(str, "0.0");
  1181. return;
  1182. }
  1183. /* Normalise x so that mantissa is in [1..9.999] */
  1184. /* FIXME: better use int64_t when the cast is implemented */
  1185. int exponent = ceil(log10(x));
  1186. x /= pow(R_10(), (real)exponent);
  1187. if (x < R_1())
  1188. {
  1189. x *= R_10();
  1190. exponent--;
  1191. }
  1192. /* Print digits */
  1193. for (int i = 0; i < ndigits; i++)
  1194. {
  1195. int digit = (int)floor(x);
  1196. *str++ = '0' + digit;
  1197. if (i == 0)
  1198. *str++ = '.';
  1199. x -= real(digit);
  1200. x *= R_10();
  1201. }
  1202. /* Print exponent information */
  1203. if (exponent)
  1204. str += std::sprintf(str, "e%c%i",
  1205. exponent >= 0 ? '+' : '-', lol::abs(exponent));
  1206. *str++ = '\0';
  1207. }
  1208. static real fast_pi()
  1209. {
  1210. /* Approximate Pi using Machin's formula: 16*atan(1/5)-4*atan(1/239) */
  1211. real ret = 0, x0 = 5, x1 = 239;
  1212. real const m0 = -x0 * x0, m1 = -x1 * x1, r16 = 16, r4 = 4;
  1213. for (int i = 1; ; i += 2)
  1214. {
  1215. real newret = ret + r16 / (x0 * (real)i) - r4 / (x1 * (real)i);
  1216. if (newret == ret)
  1217. break;
  1218. ret = newret;
  1219. x0 *= m0;
  1220. x1 *= m1;
  1221. }
  1222. return ret;
  1223. }
  1224. } /* namespace lol */