選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

1694 行
44 KiB

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