math.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <LibC/assert.h>
  27. #include <math.h>
  28. #include <stdint.h>
  29. #include <stdlib.h>
  30. template<size_t>
  31. constexpr double e_to_power();
  32. template<>
  33. constexpr double e_to_power<0>() { return 1; }
  34. template<size_t exponent>
  35. constexpr double e_to_power() { return M_E * e_to_power<exponent - 1>(); }
  36. template<size_t>
  37. constexpr size_t factorial();
  38. template<>
  39. constexpr size_t factorial<0>() { return 1; }
  40. template<size_t value>
  41. constexpr size_t factorial() { return value * factorial<value - 1>(); }
  42. template<size_t>
  43. constexpr size_t product_even();
  44. template<>
  45. constexpr size_t product_even<2>() { return 2; }
  46. template<size_t value>
  47. constexpr size_t product_even() { return value * product_even<value - 2>(); }
  48. template<size_t>
  49. constexpr size_t product_odd();
  50. template<>
  51. constexpr size_t product_odd<1>() { return 1; }
  52. template<size_t value>
  53. constexpr size_t product_odd() { return value * product_odd<value - 2>(); }
  54. enum class RoundingMode {
  55. ToZero,
  56. Up,
  57. Down,
  58. ToEven
  59. };
  60. template<typename T>
  61. union FloatExtractor;
  62. template<>
  63. union FloatExtractor<double> {
  64. static const int mantissa_bits = 52;
  65. static const unsigned long long mantissa_max = (1ull << 52) - 1;
  66. static const int exponent_bias = 1023;
  67. static const int exponent_bits = 11;
  68. static const unsigned exponent_max = 2047;
  69. struct {
  70. unsigned long long mantissa : 52;
  71. unsigned exponent : 11;
  72. unsigned sign : 1;
  73. };
  74. double d;
  75. };
  76. template<>
  77. union FloatExtractor<float> {
  78. static const int mantissa_bits = 23;
  79. static const unsigned mantissa_max = (1 << 23) - 1;
  80. static const int exponent_bias = 127;
  81. static const int exponent_bits = 8;
  82. static const unsigned exponent_max = 255;
  83. struct {
  84. unsigned long long mantissa : 23;
  85. unsigned exponent : 8;
  86. unsigned sign : 1;
  87. };
  88. float d;
  89. };
  90. // This is much branchier than it really needs to be
  91. template<typename FloatType>
  92. static FloatType internal_to_integer(FloatType x, RoundingMode rounding_mode)
  93. {
  94. if (!isfinite(x))
  95. return x;
  96. using Extractor = FloatExtractor<decltype(x)>;
  97. Extractor extractor;
  98. extractor.d = x;
  99. auto unbiased_exponent = extractor.exponent - Extractor::exponent_bias;
  100. bool round = false;
  101. bool guard = false;
  102. if (unbiased_exponent < 0) {
  103. // it was easier to special case [0..1) as it saves us from
  104. // handling subnormals, underflows, etc
  105. if (unbiased_exponent == -1) {
  106. round = true;
  107. }
  108. guard = extractor.mantissa != 0;
  109. extractor.mantissa = 0;
  110. extractor.exponent = 0;
  111. } else {
  112. if (unbiased_exponent >= Extractor::mantissa_bits)
  113. return x;
  114. auto dead_bitcount = Extractor::mantissa_bits - unbiased_exponent;
  115. auto dead_mask = (1ull << dead_bitcount) - 1;
  116. auto dead_bits = extractor.mantissa & dead_mask;
  117. extractor.mantissa &= ~dead_mask;
  118. auto guard_mask = dead_mask >> 1;
  119. guard = (dead_bits & guard_mask) != 0;
  120. round = (dead_bits & ~guard_mask) != 0;
  121. }
  122. bool should_round = false;
  123. switch (rounding_mode) {
  124. case RoundingMode::ToEven:
  125. should_round = round;
  126. break;
  127. case RoundingMode::Up:
  128. if (!extractor.sign)
  129. should_round = guard || round;
  130. break;
  131. case RoundingMode::Down:
  132. if (extractor.sign)
  133. should_round = guard || round;
  134. break;
  135. case RoundingMode::ToZero:
  136. break;
  137. }
  138. if (should_round) {
  139. // We could do this ourselves, but this saves us from manually
  140. // handling overflow.
  141. if (extractor.sign)
  142. extractor.d -= 1.0;
  143. else
  144. extractor.d += 1.0;
  145. }
  146. return extractor.d;
  147. }
  148. // This is much branchier than it really needs to be
  149. template<typename FloatType>
  150. static FloatType internal_nextafter(FloatType x, bool up)
  151. {
  152. if (!isfinite(x))
  153. return x;
  154. using Extractor = FloatExtractor<decltype(x)>;
  155. Extractor extractor;
  156. extractor.d = x;
  157. if (x == 0) {
  158. if (!extractor.sign) {
  159. extractor.mantissa = 1;
  160. extractor.sign = !up;
  161. return extractor.d;
  162. }
  163. if (up) {
  164. extractor.sign = false;
  165. extractor.mantissa = 1;
  166. return extractor.d;
  167. }
  168. extractor.mantissa = 1;
  169. extractor.sign = up != extractor.sign;
  170. return extractor.d;
  171. }
  172. if (up != extractor.sign) {
  173. extractor.mantissa++;
  174. if (!extractor.mantissa) {
  175. // no need to normalize the mantissa as we just hit a power
  176. // of two.
  177. extractor.exponent++;
  178. if (extractor.exponent == Extractor::exponent_max) {
  179. extractor.exponent = Extractor::exponent_max - 1;
  180. extractor.mantissa = Extractor::mantissa_max;
  181. }
  182. }
  183. return extractor.d;
  184. }
  185. if (!extractor.mantissa) {
  186. if (extractor.exponent) {
  187. extractor.exponent--;
  188. extractor.mantissa = Extractor::mantissa_max;
  189. } else {
  190. extractor.d = 0;
  191. }
  192. return extractor.d;
  193. }
  194. extractor.mantissa--;
  195. if (extractor.mantissa != Extractor::mantissa_max)
  196. return extractor.d;
  197. if (extractor.exponent) {
  198. extractor.exponent--;
  199. // normalize
  200. extractor.mantissa <<= 1;
  201. } else {
  202. if (extractor.sign) {
  203. // Negative infinity
  204. extractor.mantissa = 0;
  205. extractor.exponent = Extractor::exponent_max;
  206. }
  207. }
  208. return extractor.d;
  209. }
  210. extern "C" {
  211. double trunc(double x) NOEXCEPT
  212. {
  213. return internal_to_integer(x, RoundingMode::ToZero);
  214. }
  215. double cos(double angle) NOEXCEPT
  216. {
  217. return sin(angle + M_PI_2);
  218. }
  219. float cosf(float angle) NOEXCEPT
  220. {
  221. return sinf(angle + M_PI_2);
  222. }
  223. // This can also be done with a taylor expansion, but for
  224. // now this works pretty well (and doesn't mess anything up
  225. // in quake in particular, which is very Floating-Point precision
  226. // heavy)
  227. double sin(double angle) NOEXCEPT
  228. {
  229. double ret = 0.0;
  230. __asm__(
  231. "fsin"
  232. : "=t"(ret)
  233. : "0"(angle));
  234. return ret;
  235. }
  236. float sinf(float angle) NOEXCEPT
  237. {
  238. float ret = 0.0f;
  239. __asm__(
  240. "fsin"
  241. : "=t"(ret)
  242. : "0"(angle));
  243. return ret;
  244. }
  245. double pow(double x, double y) NOEXCEPT
  246. {
  247. // FIXME: Please fix me. I am naive.
  248. if (isnan(y))
  249. return y;
  250. if (y == 0)
  251. return 1;
  252. if (x == 0)
  253. return 0;
  254. if (y == 1)
  255. return x;
  256. int y_as_int = (int)y;
  257. if (y == (double)y_as_int) {
  258. double result = x;
  259. for (int i = 0; i < fabs(y) - 1; ++i)
  260. result *= x;
  261. if (y < 0)
  262. result = 1.0 / result;
  263. return result;
  264. }
  265. return exp2(y * log2(x));
  266. }
  267. float powf(float x, float y) NOEXCEPT
  268. {
  269. return (float)pow(x, y);
  270. }
  271. double ldexp(double x, int exp) NOEXCEPT
  272. {
  273. return x * exp2(exp);
  274. }
  275. float ldexpf(float x, int exp) NOEXCEPT
  276. {
  277. return x * exp2f(exp);
  278. }
  279. double tanh(double x) NOEXCEPT
  280. {
  281. if (x > 0) {
  282. double exponentiated = exp(2 * x);
  283. return (exponentiated - 1) / (exponentiated + 1);
  284. }
  285. double plusX = exp(x);
  286. double minusX = 1 / plusX;
  287. return (plusX - minusX) / (plusX + minusX);
  288. }
  289. static double ampsin(double angle) NOEXCEPT
  290. {
  291. double looped_angle = fmod(M_PI + angle, M_TAU) - M_PI;
  292. double looped_angle_squared = looped_angle * looped_angle;
  293. double quadratic_term;
  294. if (looped_angle > 0) {
  295. quadratic_term = -looped_angle_squared;
  296. } else {
  297. quadratic_term = looped_angle_squared;
  298. }
  299. double linear_term = M_PI * looped_angle;
  300. return quadratic_term + linear_term;
  301. }
  302. double tan(double angle) NOEXCEPT
  303. {
  304. return ampsin(angle) / ampsin(M_PI_2 + angle);
  305. }
  306. double sqrt(double x) NOEXCEPT
  307. {
  308. double res;
  309. __asm__("fsqrt"
  310. : "=t"(res)
  311. : "0"(x));
  312. return res;
  313. }
  314. float sqrtf(float x) NOEXCEPT
  315. {
  316. float res;
  317. __asm__("fsqrt"
  318. : "=t"(res)
  319. : "0"(x));
  320. return res;
  321. }
  322. double sinh(double x) NOEXCEPT
  323. {
  324. double exponentiated = exp(x);
  325. if (x > 0)
  326. return (exponentiated * exponentiated - 1) / 2 / exponentiated;
  327. return (exponentiated - 1 / exponentiated) / 2;
  328. }
  329. double log10(double x) NOEXCEPT
  330. {
  331. double ret = 0.0;
  332. __asm__(
  333. "fldlg2\n"
  334. "fld %%st(1)\n"
  335. "fyl2x\n"
  336. "fstp %%st(1)"
  337. : "=t"(ret)
  338. : "0"(x));
  339. return ret;
  340. }
  341. double log(double x) NOEXCEPT
  342. {
  343. double ret = 0.0;
  344. __asm__(
  345. "fldln2\n"
  346. "fld %%st(1)\n"
  347. "fyl2x\n"
  348. "fstp %%st(1)"
  349. : "=t"(ret)
  350. : "0"(x));
  351. return ret;
  352. }
  353. float logf(float x) NOEXCEPT
  354. {
  355. return (float)log(x);
  356. }
  357. double fmod(double index, double period) NOEXCEPT
  358. {
  359. return index - trunc(index / period) * period;
  360. }
  361. float fmodf(float index, float period) NOEXCEPT
  362. {
  363. return index - trunc(index / period) * period;
  364. }
  365. double exp(double exponent) NOEXCEPT
  366. {
  367. double res = 0;
  368. __asm__("fldl2e\n"
  369. "fmulp\n"
  370. "fld1\n"
  371. "fld %%st(1)\n"
  372. "fprem\n"
  373. "f2xm1\n"
  374. "faddp\n"
  375. "fscale\n"
  376. "fstp %%st(1)"
  377. : "=t"(res)
  378. : "0"(exponent));
  379. return res;
  380. }
  381. float expf(float exponent) NOEXCEPT
  382. {
  383. return (float)exp(exponent);
  384. }
  385. double exp2(double exponent) NOEXCEPT
  386. {
  387. double res = 0;
  388. __asm__("fld1\n"
  389. "fld %%st(1)\n"
  390. "fprem\n"
  391. "f2xm1\n"
  392. "faddp\n"
  393. "fscale\n"
  394. "fstp %%st(1)"
  395. : "=t"(res)
  396. : "0"(exponent));
  397. return res;
  398. }
  399. float exp2f(float exponent) NOEXCEPT
  400. {
  401. return (float)exp2(exponent);
  402. }
  403. double cosh(double x) NOEXCEPT
  404. {
  405. double exponentiated = exp(-x);
  406. if (x < 0)
  407. return (1 + exponentiated * exponentiated) / 2 / exponentiated;
  408. return (1 / exponentiated + exponentiated) / 2;
  409. }
  410. double atan2(double y, double x) NOEXCEPT
  411. {
  412. if (x > 0)
  413. return atan(y / x);
  414. if (x == 0) {
  415. if (y > 0)
  416. return M_PI_2;
  417. if (y < 0)
  418. return -M_PI_2;
  419. return 0;
  420. }
  421. if (y >= 0)
  422. return atan(y / x) + M_PI;
  423. return atan(y / x) - M_PI;
  424. }
  425. float atan2f(float y, float x) NOEXCEPT
  426. {
  427. return (float)atan2(y, x);
  428. }
  429. double atan(double x) NOEXCEPT
  430. {
  431. if (x < 0)
  432. return -atan(-x);
  433. if (x > 1)
  434. return M_PI_2 - atan(1 / x);
  435. double squared = x * x;
  436. return x / (1 + 1 * 1 * squared / (3 + 2 * 2 * squared / (5 + 3 * 3 * squared / (7 + 4 * 4 * squared / (9 + 5 * 5 * squared / (11 + 6 * 6 * squared / (13 + 7 * 7 * squared)))))));
  437. }
  438. double asin(double x) NOEXCEPT
  439. {
  440. if (x > 1 || x < -1)
  441. return NAN;
  442. if (x > 0.5 || x < -0.5)
  443. return 2 * atan(x / (1 + sqrt(1 - x * x)));
  444. double squared = x * x;
  445. double value = x;
  446. double i = x * squared;
  447. value += i * product_odd<1>() / product_even<2>() / 3;
  448. i *= squared;
  449. value += i * product_odd<3>() / product_even<4>() / 5;
  450. i *= squared;
  451. value += i * product_odd<5>() / product_even<6>() / 7;
  452. i *= squared;
  453. value += i * product_odd<7>() / product_even<8>() / 9;
  454. i *= squared;
  455. value += i * product_odd<9>() / product_even<10>() / 11;
  456. i *= squared;
  457. value += i * product_odd<11>() / product_even<12>() / 13;
  458. return value;
  459. }
  460. float asinf(float x) NOEXCEPT
  461. {
  462. return (float)asin(x);
  463. }
  464. double acos(double x) NOEXCEPT
  465. {
  466. return M_PI_2 - asin(x);
  467. }
  468. float acosf(float x) NOEXCEPT
  469. {
  470. return M_PI_2 - asinf(x);
  471. }
  472. double fabs(double value) NOEXCEPT
  473. {
  474. return value < 0 ? -value : value;
  475. }
  476. double log2(double x) NOEXCEPT
  477. {
  478. double ret = 0.0;
  479. __asm__(
  480. "fld1\n"
  481. "fld %%st(1)\n"
  482. "fyl2x\n"
  483. "fstp %%st(1)"
  484. : "=t"(ret)
  485. : "0"(x));
  486. return ret;
  487. }
  488. float log2f(float x) NOEXCEPT
  489. {
  490. return log2(x);
  491. }
  492. long double log2l(long double x) NOEXCEPT
  493. {
  494. return log2(x);
  495. }
  496. double frexp(double, int*) NOEXCEPT
  497. {
  498. VERIFY_NOT_REACHED();
  499. return 0;
  500. }
  501. float frexpf(float, int*) NOEXCEPT
  502. {
  503. VERIFY_NOT_REACHED();
  504. return 0;
  505. }
  506. long double frexpl(long double, int*) NOEXCEPT
  507. {
  508. VERIFY_NOT_REACHED();
  509. return 0;
  510. }
  511. double round(double value) NOEXCEPT
  512. {
  513. return internal_to_integer(value, RoundingMode::ToEven);
  514. }
  515. float roundf(float value) NOEXCEPT
  516. {
  517. return internal_to_integer(value, RoundingMode::ToEven);
  518. }
  519. float floorf(float value) NOEXCEPT
  520. {
  521. return internal_to_integer(value, RoundingMode::Down);
  522. }
  523. double floor(double value) NOEXCEPT
  524. {
  525. return internal_to_integer(value, RoundingMode::Down);
  526. }
  527. double rint(double value) NOEXCEPT
  528. {
  529. // This should be the current rounding mode
  530. return internal_to_integer(value, RoundingMode::ToEven);
  531. }
  532. float ceilf(float value) NOEXCEPT
  533. {
  534. return internal_to_integer(value, RoundingMode::Up);
  535. }
  536. double ceil(double value) NOEXCEPT
  537. {
  538. return internal_to_integer(value, RoundingMode::Up);
  539. }
  540. double modf(double x, double* intpart) NOEXCEPT
  541. {
  542. double integer_part = internal_to_integer(x, RoundingMode::ToZero);
  543. *intpart = integer_part;
  544. auto fraction = x - integer_part;
  545. if (signbit(fraction) != signbit(x))
  546. fraction = -fraction;
  547. return fraction;
  548. }
  549. double gamma(double x) NOEXCEPT
  550. {
  551. // Stirling approximation
  552. return sqrt(2.0 * M_PI / x) * pow(x / M_E, x);
  553. }
  554. double expm1(double x) NOEXCEPT
  555. {
  556. return exp(x) - 1;
  557. }
  558. double cbrt(double x) NOEXCEPT
  559. {
  560. if (isinf(x) || x == 0)
  561. return x;
  562. if (x < 0)
  563. return -cbrt(-x);
  564. double r = x;
  565. double ex = 0;
  566. while (r < 0.125) {
  567. r *= 8;
  568. ex--;
  569. }
  570. while (r > 1.0) {
  571. r *= 0.125;
  572. ex++;
  573. }
  574. r = (-0.46946116 * r + 1.072302) * r + 0.3812513;
  575. while (ex < 0) {
  576. r *= 0.5;
  577. ex++;
  578. }
  579. while (ex > 0) {
  580. r *= 2;
  581. ex--;
  582. }
  583. r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r);
  584. r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r);
  585. r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r);
  586. r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r);
  587. return r;
  588. }
  589. double log1p(double x) NOEXCEPT
  590. {
  591. return log(1 + x);
  592. }
  593. double acosh(double x) NOEXCEPT
  594. {
  595. return log(x + sqrt(x * x - 1));
  596. }
  597. double asinh(double x) NOEXCEPT
  598. {
  599. return log(x + sqrt(x * x + 1));
  600. }
  601. double atanh(double x) NOEXCEPT
  602. {
  603. return log((1 + x) / (1 - x)) / 2.0;
  604. }
  605. double hypot(double x, double y) NOEXCEPT
  606. {
  607. return sqrt(x * x + y * y);
  608. }
  609. double erf(double x) NOEXCEPT
  610. {
  611. // algorithm taken from Abramowitz and Stegun (no. 26.2.17)
  612. double t = 1 / (1 + 0.47047 * fabs(x));
  613. double poly = t * (0.3480242 + t * (-0.958798 + t * 0.7478556));
  614. double answer = 1 - poly * exp(-x * x);
  615. if (x < 0)
  616. return -answer;
  617. return answer;
  618. }
  619. double erfc(double x) NOEXCEPT
  620. {
  621. return 1 - erf(x);
  622. }
  623. double nextafter(double x, double target) NOEXCEPT
  624. {
  625. if (x == target)
  626. return target;
  627. return internal_nextafter(x, target >= x);
  628. }
  629. float nextafterf(float x, float target) NOEXCEPT
  630. {
  631. if (x == target)
  632. return target;
  633. return internal_nextafter(x, target >= x);
  634. }
  635. long double nextafterl(long double, long double) NOEXCEPT
  636. {
  637. TODO();
  638. }
  639. double nexttoward(double x, long double target) NOEXCEPT
  640. {
  641. if (x == target)
  642. return target;
  643. return internal_nextafter(x, target >= x);
  644. }
  645. float nexttowardf(float x, long double target) NOEXCEPT
  646. {
  647. if (x == target)
  648. return target;
  649. return internal_nextafter(x, target >= x);
  650. }
  651. long double nexttowardl(long double, long double) NOEXCEPT
  652. {
  653. TODO();
  654. }
  655. double copysign(double x, double y)
  656. {
  657. if (x < 0 && y < 0)
  658. return x;
  659. if (x >= 0 && y < 0)
  660. return -x;
  661. if (x < 0 && y >= 0)
  662. return -x;
  663. return x;
  664. }
  665. }