1633 line
42 KiB

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