x2y2m1q.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Compute x^2 + y^2 - 1, without large cancellation error.
  2. Copyright (C) 2012-2018 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include "quadmath-imp.h"
  16. /* Calculate X + Y exactly and store the result in *HI + *LO. It is
  17. given that |X| >= |Y| and the values are small enough that no
  18. overflow occurs. */
  19. static inline void
  20. add_split (__float128 *hi, __float128 *lo, __float128 x, __float128 y)
  21. {
  22. /* Apply Dekker's algorithm. */
  23. *hi = x + y;
  24. *lo = (x - *hi) + y;
  25. }
  26. /* Compare absolute values of floating-point values pointed to by P
  27. and Q for qsort. */
  28. static int
  29. compare (const void *p, const void *q)
  30. {
  31. __float128 pld = fabsq (*(const __float128 *) p);
  32. __float128 qld = fabsq (*(const __float128 *) q);
  33. if (pld < qld)
  34. return -1;
  35. else if (pld == qld)
  36. return 0;
  37. else
  38. return 1;
  39. }
  40. /* Return X^2 + Y^2 - 1, computed without large cancellation error.
  41. It is given that 1 > X >= Y >= epsilon / 2, and that X^2 + Y^2 >=
  42. 0.5. */
  43. __float128
  44. __quadmath_x2y2m1q (__float128 x, __float128 y)
  45. {
  46. __float128 vals[5];
  47. SET_RESTORE_ROUNDF128 (FE_TONEAREST);
  48. mul_splitq (&vals[1], &vals[0], x, x);
  49. mul_splitq (&vals[3], &vals[2], y, y);
  50. vals[4] = -1;
  51. qsort (vals, 5, sizeof (__float128), compare);
  52. /* Add up the values so that each element of VALS has absolute value
  53. at most equal to the last set bit of the next nonzero
  54. element. */
  55. for (size_t i = 0; i <= 3; i++)
  56. {
  57. add_split (&vals[i + 1], &vals[i], vals[i + 1], vals[i]);
  58. qsort (vals + i + 1, 4 - i, sizeof (__float128), compare);
  59. }
  60. /* Now any error from this addition will be small. */
  61. return vals[4] + vals[3] + vals[2] + vals[1] + vals[0];
  62. }