complex.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* complex.cpp
  2. *
  3. * Copyright (C) 1992-2011,2017 Paul Boersma
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This code is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. * See the GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this work. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <math.h>
  19. #include "complex.h"
  20. dcomplex dcomplex_sqrt (dcomplex z) {
  21. dcomplex result;
  22. double x, y, w, r;
  23. if (z.re == 0 && z.im == 0) {
  24. result.re = 0;
  25. result.im = 0;
  26. return result;
  27. }
  28. x = fabs (z.re);
  29. y = fabs (z.im);
  30. if (x >= y) {
  31. r = y / x;
  32. w = sqrt (x) * sqrt (0.5 * (1.0 + sqrt (1.0 + r * r)));
  33. } else {
  34. r = x / y;
  35. w = sqrt (y) * sqrt (0.5 * (r + sqrt (1.0 + r * r)));
  36. }
  37. if (z.re >= 0.0) {
  38. result.re = w;
  39. result.im = z.im / (2.0 * w);
  40. } else {
  41. result.im = (z.im >= 0) ? w : -w;
  42. result.re = z.im / (2.0 * result.im);
  43. }
  44. return result;
  45. }
  46. /* End of file complex.cpp */