Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

1692 строки
44 KiB

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