您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

1444 行
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 = ceilf(logf(2) / logf(2 * F_PI) * real::BIGITS * real::BIGIT_BITS);
  654. real ret = sqrt(real::R_PI() * 2);
  655. real fact_k_1 = real::R_1();
  656. for (int k = 1; k < a; k++)
  657. {
  658. real a_k = (real)(a - k);
  659. real ck = pow(a_k, (real)((float)k - 0.5)) * exp(a_k)
  660. / (fact_k_1 * (x + (real)(k - 1)));
  661. ret += ck;
  662. fact_k_1 *= (real)-k;
  663. }
  664. ret *= pow(x + (real)(a - 1), x - (real::R_1() / 2));
  665. ret *= exp(-x - (real)(a - 1));
  666. return ret;
  667. }
  668. template<> real fabs(real const &x)
  669. {
  670. real ret = x;
  671. ret.m_signexp &= 0x7fffffffu;
  672. return ret;
  673. }
  674. template<> real abs(real const &x)
  675. {
  676. return fabs(x);
  677. }
  678. template<> real fract(real const &x)
  679. {
  680. return x - floor(x);
  681. }
  682. template<> real degrees(real const &x)
  683. {
  684. static real mul = real(180) * real::R_1_PI();
  685. return x * mul;
  686. }
  687. template<> real radians(real const &x)
  688. {
  689. static real mul = real::R_PI() / real(180);
  690. return x * mul;
  691. }
  692. static real fast_log(real const &x)
  693. {
  694. /* This fast log method is tuned to work on the [1..2] range and
  695. * no effort whatsoever was made to improve convergence outside this
  696. * domain of validity. It can converge pretty fast, provided we use
  697. * the following variable substitutions:
  698. * y = sqrt(x)
  699. * z = (y - 1) / (y + 1)
  700. *
  701. * And the following identities:
  702. * ln(x) = 2 ln(y)
  703. * = 2 ln((1 + z) / (1 - z))
  704. * = 4 z (1 + z^2 / 3 + z^4 / 5 + z^6 / 7...)
  705. *
  706. * Any additional sqrt() call would halve the convergence time, but
  707. * would also impact the final precision. For now we stick with one
  708. * sqrt() call. */
  709. real y = sqrt(x);
  710. real z = (y - real::R_1()) / (y + real::R_1()), z2 = z * z, zn = z2;
  711. real sum = real::R_1();
  712. for (int i = 3; ; i += 2)
  713. {
  714. real newsum = sum + zn / (real)i;
  715. if (newsum == sum)
  716. break;
  717. sum = newsum;
  718. zn *= z2;
  719. }
  720. return z * sum * 4;
  721. }
  722. template<> real log(real const &x)
  723. {
  724. /* Strategy for log(x): if x = 2^E*M then log(x) = E log(2) + log(M),
  725. * with the property that M is in [1..2[, so fast_log() applies here. */
  726. real tmp = x;
  727. if (x.m_signexp >> 31 || x.m_signexp == 0)
  728. {
  729. tmp.m_signexp = 0xffffffffu;
  730. tmp.m_mantissa[0] = 0xffffffffu;
  731. return tmp;
  732. }
  733. tmp.m_signexp = (1 << 30) - 1;
  734. return (real)(int)(x.m_signexp - (1 << 30) + 1) * real::R_LN2()
  735. + fast_log(tmp);
  736. }
  737. template<> real log2(real const &x)
  738. {
  739. /* Strategy for log2(x): see log(x). */
  740. real tmp = x;
  741. if (x.m_signexp >> 31 || x.m_signexp == 0)
  742. {
  743. tmp.m_signexp = 0xffffffffu;
  744. tmp.m_mantissa[0] = 0xffffffffu;
  745. return tmp;
  746. }
  747. tmp.m_signexp = (1 << 30) - 1;
  748. return (real)(int)(x.m_signexp - (1 << 30) + 1)
  749. + fast_log(tmp) * real::R_LOG2E();
  750. }
  751. template<> real log10(real const &x)
  752. {
  753. return log(x) * real::R_LOG10E();
  754. }
  755. static real fast_exp_sub(real const &x, real const &y)
  756. {
  757. /* This fast exp method is tuned to work on the [-1..1] range and
  758. * no effort whatsoever was made to improve convergence outside this
  759. * domain of validity. The argument y is used for cases where we
  760. * don't want the leading 1 in the Taylor series. */
  761. real ret = real::R_1() - y, xn = x;
  762. int i = 1;
  763. for (;;)
  764. {
  765. real newret = ret + xn;
  766. if (newret == ret)
  767. break;
  768. ret = newret * ++i;
  769. xn *= x;
  770. }
  771. return ret / fast_fact(i);
  772. }
  773. template<> real exp(real const &x)
  774. {
  775. /* Strategy for exp(x): the Taylor series does not converge very fast
  776. * with large positive or negative values.
  777. *
  778. * However, we know that the result is going to be in the form M*2^E,
  779. * where M is the mantissa and E the exponent. We first try to predict
  780. * a value for E, which is approximately log2(exp(x)) = x / log(2).
  781. *
  782. * Let E0 be an integer close to x / log(2). We need to find a value x0
  783. * such that exp(x) = 2^E0 * exp(x0). We get x0 = x - E0 log(2).
  784. *
  785. * Thus the final algorithm:
  786. * int E0 = x / log(2)
  787. * real x0 = x - E0 log(2)
  788. * real x1 = exp(x0)
  789. * return x1 * 2^E0
  790. */
  791. int e0 = x / real::R_LN2();
  792. real x0 = x - (real)e0 * real::R_LN2();
  793. real x1 = fast_exp_sub(x0, real::R_0());
  794. x1.m_signexp += e0;
  795. return x1;
  796. }
  797. template<> real exp2(real const &x)
  798. {
  799. /* Strategy for exp2(x): see strategy in exp(). */
  800. int e0 = x;
  801. real x0 = x - (real)e0;
  802. real x1 = fast_exp_sub(x0 * real::R_LN2(), real::R_0());
  803. x1.m_signexp += e0;
  804. return x1;
  805. }
  806. template<> real sinh(real const &x)
  807. {
  808. /* We cannot always use (exp(x)-exp(-x))/2 because we'll lose
  809. * accuracy near zero. We only use this identity for |x|>0.5. If
  810. * |x|<=0.5, we compute exp(x)-1 and exp(-x)-1 instead. */
  811. bool near_zero = (fabs(x) < real::R_1() / 2);
  812. real x1 = near_zero ? fast_exp_sub(x, real::R_1()) : exp(x);
  813. real x2 = near_zero ? fast_exp_sub(-x, real::R_1()) : exp(-x);
  814. return (x1 - x2) / 2;
  815. }
  816. template<> real tanh(real const &x)
  817. {
  818. /* See sinh() for the strategy here */
  819. bool near_zero = (fabs(x) < real::R_1() / 2);
  820. real x1 = near_zero ? fast_exp_sub(x, real::R_1()) : exp(x);
  821. real x2 = near_zero ? fast_exp_sub(-x, real::R_1()) : exp(-x);
  822. real x3 = near_zero ? x1 + x2 + real::R_2() : x1 + x2;
  823. return (x1 - x2) / x3;
  824. }
  825. template<> real cosh(real const &x)
  826. {
  827. /* No need to worry about accuracy here; maybe the last bit is slightly
  828. * off, but that's about it. */
  829. return (exp(x) + exp(-x)) / 2;
  830. }
  831. template<> real frexp(real const &x, int *exp)
  832. {
  833. if (!x)
  834. {
  835. *exp = 0;
  836. return x;
  837. }
  838. real ret = x;
  839. int exponent = (ret.m_signexp & 0x7fffffffu) - (1 << 30) + 1;
  840. *exp = exponent + 1;
  841. ret.m_signexp -= exponent + 1;
  842. return ret;
  843. }
  844. template<> real ldexp(real const &x, int exp)
  845. {
  846. real ret = x;
  847. if (ret)
  848. ret.m_signexp += exp;
  849. return ret;
  850. }
  851. template<> real modf(real const &x, real *iptr)
  852. {
  853. real absx = fabs(x);
  854. real tmp = floor(absx);
  855. *iptr = copysign(tmp, x);
  856. return copysign(absx - tmp, x);
  857. }
  858. template<> real ulp(real const &x)
  859. {
  860. real ret = real::R_1();
  861. if (x)
  862. ret.m_signexp = x.m_signexp + 1 - real::BIGITS * real::BIGIT_BITS;
  863. else
  864. ret.m_signexp = 0;
  865. return ret;
  866. }
  867. template<> real nextafter(real const &x, real const &y)
  868. {
  869. if (x == y)
  870. return x;
  871. else if (x < y)
  872. return x + ulp(x);
  873. else
  874. return x - ulp(x);
  875. }
  876. template<> real copysign(real const &x, real const &y)
  877. {
  878. real ret = x;
  879. ret.m_signexp &= 0x7fffffffu;
  880. ret.m_signexp |= y.m_signexp & 0x80000000u;
  881. return ret;
  882. }
  883. template<> real floor(real const &x)
  884. {
  885. /* Strategy for floor(x):
  886. * - if negative, return -ceil(-x)
  887. * - if zero or negative zero, return x
  888. * - if less than one, return zero
  889. * - otherwise, if e is the exponent, clear all bits except the
  890. * first e. */
  891. if (x < -real::R_0())
  892. return -ceil(-x);
  893. if (!x)
  894. return x;
  895. if (x < real::R_1())
  896. return real::R_0();
  897. real ret = x;
  898. int exponent = x.m_signexp - (1 << 30) + 1;
  899. for (int i = 0; i < real::BIGITS; i++)
  900. {
  901. if (exponent <= 0)
  902. ret.m_mantissa[i] = 0;
  903. else if (exponent < real::BIGIT_BITS)
  904. ret.m_mantissa[i] &= ~((1 << (real::BIGIT_BITS - exponent)) - 1);
  905. exponent -= real::BIGIT_BITS;
  906. }
  907. return ret;
  908. }
  909. template<> real ceil(real const &x)
  910. {
  911. /* Strategy for ceil(x):
  912. * - if negative, return -floor(-x)
  913. * - if x == floor(x), return x
  914. * - otherwise, return floor(x) + 1 */
  915. if (x < -real::R_0())
  916. return -floor(-x);
  917. real ret = floor(x);
  918. if (x == ret)
  919. return ret;
  920. else
  921. return ret + real::R_1();
  922. }
  923. template<> real round(real const &x)
  924. {
  925. if (x < real::R_0())
  926. return -round(-x);
  927. return floor(x + (real::R_1() / 2));
  928. }
  929. template<> real fmod(real const &x, real const &y)
  930. {
  931. if (!y)
  932. return real::R_0(); /* FIXME: return NaN */
  933. if (!x)
  934. return x;
  935. real tmp = round(x / y);
  936. return x - tmp * y;
  937. }
  938. template<> real sin(real const &x)
  939. {
  940. int switch_sign = x.m_signexp & 0x80000000u;
  941. real absx = fmod(fabs(x), real::R_PI() * 2);
  942. if (absx > real::R_PI())
  943. {
  944. absx -= real::R_PI();
  945. switch_sign = !switch_sign;
  946. }
  947. if (absx > real::R_PI_2())
  948. absx = real::R_PI() - absx;
  949. real ret = real::R_0(), fact = real::R_1(), xn = absx, mx2 = -absx * absx;
  950. int i = 1;
  951. for (;;)
  952. {
  953. real newret = ret + xn;
  954. if (newret == ret)
  955. break;
  956. ret = newret * ((i + 1) * (i + 2));
  957. xn *= mx2;
  958. i += 2;
  959. }
  960. ret /= fast_fact(i);
  961. /* Propagate sign */
  962. if (switch_sign)
  963. ret.m_signexp ^= 0x80000000u;
  964. return ret;
  965. }
  966. template<> real cos(real const &x)
  967. {
  968. return sin(real::R_PI_2() - x);
  969. }
  970. template<> real tan(real const &x)
  971. {
  972. /* Constrain input to [-π,π] */
  973. real y = fmod(x, real::R_PI());
  974. /* Constrain input to [-π/2,π/2] */
  975. if (y < -real::R_PI_2())
  976. y += real::R_PI();
  977. else if (y > real::R_PI_2())
  978. y -= real::R_PI();
  979. /* In [-π/4,π/4] return sin/cos */
  980. if (fabs(y) <= real::R_PI_4())
  981. return sin(y) / cos(y);
  982. /* Otherwise, return cos/sin */
  983. if (y > real::R_0())
  984. y = real::R_PI_2() - y;
  985. else
  986. y = -real::R_PI_2() - y;
  987. return cos(y) / sin(y);
  988. }
  989. static inline real asinacos(real const &x, int is_asin, int is_negative)
  990. {
  991. /* Strategy for asin(): in [-0.5..0.5], use a Taylor series around
  992. * zero. In [0.5..1], use asin(x) = π/2 - 2*asin(sqrt((1-x)/2)), and
  993. * in [-1..-0.5] just revert the sign.
  994. * Strategy for acos(): use acos(x) = π/2 - asin(x) and try not to
  995. * lose the precision around x=1. */
  996. real absx = fabs(x);
  997. int around_zero = (absx < (real::R_1() / 2));
  998. if (!around_zero)
  999. absx = sqrt((real::R_1() - absx) / 2);
  1000. real ret = absx, xn = absx, x2 = absx * absx, fact1 = 2, fact2 = 1;
  1001. for (int i = 1; ; i++)
  1002. {
  1003. xn *= x2;
  1004. real mul = (real)(2 * i + 1);
  1005. real newret = ret + ldexp(fact1 * xn / (mul * fact2), -2 * i);
  1006. if (newret == ret)
  1007. break;
  1008. ret = newret;
  1009. fact1 *= (real)((2 * i + 1) * (2 * i + 2));
  1010. fact2 *= (real)((i + 1) * (i + 1));
  1011. }
  1012. if (is_negative)
  1013. ret = -ret;
  1014. if (around_zero)
  1015. ret = is_asin ? ret : real::R_PI_2() - ret;
  1016. else
  1017. {
  1018. real adjust = is_negative ? real::R_PI() : real::R_0();
  1019. if (is_asin)
  1020. ret = real::R_PI_2() - adjust - ret * 2;
  1021. else
  1022. ret = adjust + ret * 2;
  1023. }
  1024. return ret;
  1025. }
  1026. template<> real asin(real const &x)
  1027. {
  1028. return asinacos(x, 1, x.m_signexp >> 31);
  1029. }
  1030. template<> real acos(real const &x)
  1031. {
  1032. return asinacos(x, 0, x.m_signexp >> 31);
  1033. }
  1034. template<> real atan(real const &x)
  1035. {
  1036. /* Computing atan(x): we choose a different Taylor series depending on
  1037. * the value of x to help with convergence.
  1038. *
  1039. * If |x| < 0.5 we evaluate atan(y) near 0:
  1040. * atan(y) = y - y^3/3 + y^5/5 - y^7/7 + y^9/9 ...
  1041. *
  1042. * If 0.5 <= |x| < 1.5 we evaluate atan(1+y) near 0:
  1043. * atan(1+y) = π/4 + y/(1*2^1) - y^2/(2*2^1) + y^3/(3*2^2)
  1044. * - y^5/(5*2^3) + y^6/(6*2^3) - y^7/(7*2^4)
  1045. * + y^9/(9*2^5) - y^10/(10*2^5) + y^11/(11*2^6) ...
  1046. *
  1047. * If 1.5 <= |x| < 2 we evaluate atan(sqrt(3)+2y) near 0:
  1048. * atan(sqrt(3)+2y) = π/3 + 1/2 y - sqrt(3)/2 y^2/2
  1049. * + y^3/3 - sqrt(3)/2 y^4/4 + 1/2 y^5/5
  1050. * - 1/2 y^7/7 + sqrt(3)/2 y^8/8
  1051. * - y^9/9 + sqrt(3)/2 y^10/10 - 1/2 y^11/11
  1052. * + 1/2 y^13/13 - sqrt(3)/2 y^14/14
  1053. * + y^15/15 - sqrt(3)/2 y^16/16 + 1/2 y^17/17 ...
  1054. *
  1055. * If |x| >= 2 we evaluate atan(y) near +∞:
  1056. * atan(y) = π/2 - y^-1 + y^-3/3 - y^-5/5 + y^-7/7 - y^-9/9 ...
  1057. */
  1058. real absx = fabs(x);
  1059. if (absx < (real::R_1() / 2))
  1060. {
  1061. real ret = x, xn = x, mx2 = -x * x;
  1062. for (int i = 3; ; i += 2)
  1063. {
  1064. xn *= mx2;
  1065. real newret = ret + xn / (real)i;
  1066. if (newret == ret)
  1067. break;
  1068. ret = newret;
  1069. }
  1070. return ret;
  1071. }
  1072. real ret = 0;
  1073. if (absx < (real::R_3() / 2))
  1074. {
  1075. real y = real::R_1() - absx;
  1076. real yn = y, my2 = -y * y;
  1077. for (int i = 0; ; i += 2)
  1078. {
  1079. real newret = ret + ldexp(yn / (real)(2 * i + 1), -i - 1);
  1080. yn *= y;
  1081. newret += ldexp(yn / (real)(2 * i + 2), -i - 1);
  1082. yn *= y;
  1083. newret += ldexp(yn / (real)(2 * i + 3), -i - 2);
  1084. if (newret == ret)
  1085. break;
  1086. ret = newret;
  1087. yn *= my2;
  1088. }
  1089. ret = real::R_PI_4() - ret;
  1090. }
  1091. else if (absx < real::R_2())
  1092. {
  1093. real y = (absx - real::R_SQRT3()) / 2;
  1094. real yn = y, my2 = -y * y;
  1095. for (int i = 1; ; i += 6)
  1096. {
  1097. real newret = ret + ((yn / (real)i) / 2);
  1098. yn *= y;
  1099. newret -= (real::R_SQRT3() / 2) * yn / (real)(i + 1);
  1100. yn *= y;
  1101. newret += yn / (real)(i + 2);
  1102. yn *= y;
  1103. newret -= (real::R_SQRT3() / 2) * yn / (real)(i + 3);
  1104. yn *= y;
  1105. newret += (yn / (real)(i + 4)) / 2;
  1106. if (newret == ret)
  1107. break;
  1108. ret = newret;
  1109. yn *= my2;
  1110. }
  1111. ret = real::R_PI_3() + ret;
  1112. }
  1113. else
  1114. {
  1115. real y = re(absx);
  1116. real yn = y, my2 = -y * y;
  1117. ret = y;
  1118. for (int i = 3; ; i += 2)
  1119. {
  1120. yn *= my2;
  1121. real newret = ret + yn / (real)i;
  1122. if (newret == ret)
  1123. break;
  1124. ret = newret;
  1125. }
  1126. ret = real::R_PI_2() - ret;
  1127. }
  1128. /* Propagate sign */
  1129. ret.m_signexp |= (x.m_signexp & 0x80000000u);
  1130. return ret;
  1131. }
  1132. template<> real atan2(real const &y, real const &x)
  1133. {
  1134. if (!y)
  1135. {
  1136. if ((x.m_signexp >> 31) == 0)
  1137. return y;
  1138. if (y.m_signexp >> 31)
  1139. return -real::R_PI();
  1140. return real::R_PI();
  1141. }
  1142. if (!x)
  1143. {
  1144. if (y.m_signexp >> 31)
  1145. return -real::R_PI();
  1146. return real::R_PI();
  1147. }
  1148. /* FIXME: handle the Inf and NaN cases */
  1149. real z = y / x;
  1150. real ret = atan(z);
  1151. if (x < real::R_0())
  1152. ret += (y > real::R_0()) ? real::R_PI() : -real::R_PI();
  1153. return ret;
  1154. }
  1155. template<> void real::hexprint() const
  1156. {
  1157. std::printf("%08x", m_signexp);
  1158. for (int i = 0; i < BIGITS; i++)
  1159. std::printf(" %08x", m_mantissa[i]);
  1160. }
  1161. template<> void real::sprintf(char *str, int ndigits) const;
  1162. template<> void real::print(int ndigits) const
  1163. {
  1164. char *buf = new char[ndigits + 32 + 10];
  1165. real::sprintf(buf, ndigits);
  1166. std::printf("%s", buf);
  1167. delete[] buf;
  1168. }
  1169. template<> void real::sprintf(char *str, int ndigits) const
  1170. {
  1171. real x = *this;
  1172. if (x.m_signexp >> 31)
  1173. {
  1174. *str++ = '-';
  1175. x = -x;
  1176. }
  1177. if (!x)
  1178. {
  1179. std::strcpy(str, "0.0");
  1180. return;
  1181. }
  1182. /* Normalise x so that mantissa is in [1..9.999] */
  1183. /* FIXME: better use int64_t when the cast is implemented */
  1184. int exponent = ceil(log10(x));
  1185. x /= pow(R_10(), (real)exponent);
  1186. if (x < R_1())
  1187. {
  1188. x *= R_10();
  1189. exponent--;
  1190. }
  1191. /* Print digits */
  1192. for (int i = 0; i < ndigits; i++)
  1193. {
  1194. int digit = (int)floor(x);
  1195. *str++ = '0' + digit;
  1196. if (i == 0)
  1197. *str++ = '.';
  1198. x -= real(digit);
  1199. x *= R_10();
  1200. }
  1201. /* Print exponent information */
  1202. if (exponent)
  1203. str += std::sprintf(str, "e%c%i",
  1204. exponent >= 0 ? '+' : '-', lol::abs(exponent));
  1205. *str++ = '\0';
  1206. }
  1207. static real fast_pi()
  1208. {
  1209. /* Approximate Pi using Machin's formula: 16*atan(1/5)-4*atan(1/239) */
  1210. real ret = 0, x0 = 5, x1 = 239;
  1211. real const m0 = -x0 * x0, m1 = -x1 * x1, r16 = 16, r4 = 4;
  1212. for (int i = 1; ; i += 2)
  1213. {
  1214. real newret = ret + r16 / (x0 * (real)i) - r4 / (x1 * (real)i);
  1215. if (newret == ret)
  1216. break;
  1217. ret = newret;
  1218. x0 *= m0;
  1219. x1 *= m1;
  1220. }
  1221. return ret;
  1222. }
  1223. } /* namespace lol */