Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

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