divtc3.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Copyright (C) 2005-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Richard Henderson <rth@redhat.com>, 2005.
  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 <stdbool.h>
  16. #include <math.h>
  17. #include <complex.h>
  18. attribute_hidden
  19. long double _Complex
  20. __divtc3 (long double a, long double b, long double c, long double d)
  21. {
  22. long double denom, ratio, x, y;
  23. /* ??? We can get better behavior from logarithmic scaling instead of
  24. the division. But that would mean starting to link libgcc against
  25. libm. We could implement something akin to ldexp/frexp as gcc builtins
  26. fairly easily... */
  27. if (fabsl (c) < fabsl (d))
  28. {
  29. ratio = c / d;
  30. denom = (c * ratio) + d;
  31. x = ((a * ratio) + b) / denom;
  32. y = ((b * ratio) - a) / denom;
  33. }
  34. else
  35. {
  36. ratio = d / c;
  37. denom = (d * ratio) + c;
  38. x = ((b * ratio) + a) / denom;
  39. y = (b - (a * ratio)) / denom;
  40. }
  41. /* Recover infinities and zeros that computed as NaN+iNaN; the only cases
  42. are nonzero/zero, infinite/finite, and finite/infinite. */
  43. if (isnan (x) && isnan (y))
  44. {
  45. if (denom == 0.0 && (!isnan (a) || !isnan (b)))
  46. {
  47. x = copysignl (INFINITY, c) * a;
  48. y = copysignl (INFINITY, c) * b;
  49. }
  50. else if ((isinf (a) || isinf (b))
  51. && isfinite (c) && isfinite (d))
  52. {
  53. a = copysignl (isinf (a) ? 1 : 0, a);
  54. b = copysignl (isinf (b) ? 1 : 0, b);
  55. x = INFINITY * (a * c + b * d);
  56. y = INFINITY * (b * c - a * d);
  57. }
  58. else if ((isinf (c) || isinf (d))
  59. && isfinite (a) && isfinite (b))
  60. {
  61. c = copysignl (isinf (c) ? 1 : 0, c);
  62. d = copysignl (isinf (d) ? 1 : 0, d);
  63. x = 0.0 * (a * c + b * d);
  64. y = 0.0 * (b * c - a * d);
  65. }
  66. }
  67. return x + I * y;
  68. }