amath  1.8.5 Simple command line calculator
csqrt.c File Reference
`#include "prim.h"`
Include dependency graph for csqrt.c:

Go to the source code of this file.

## Functions

complex csqrt (complex z)
Square root of complex number. More...

## ◆ csqrt()

 complex csqrt ( complex z )

Square root of complex number.

Definition at line 42 of file csqrt.c.

References cabs(), cimag(), cpack(), creal(), fabs(), and sqrt().

Referenced by cacos(), cacosh(), cacsc(), cacsch(), casec(), casech(), casin(), casinh(), and ComplexNumber::SquareRoot().

43 {
44  complex w;
45  double x, y, r, t, scale;
46
47  x = creal(z);
48  y = cimag(z);
49
50  if (y == 0.0)
51  {
52  if (x == 0.0)
53  {
54  w = cpack(0.0, y);
55  }
56  else
57  {
58  r = fabs(x);
59  r = sqrt(r);
60  if (x < 0.0)
61  {
62  w = cpack(0.0, r);
63  }
64  else
65  {
66  w = cpack(r, y);
67  }
68  }
69  return w;
70  }
71  if (x == 0.0)
72  {
73  r = fabs(y);
74  r = sqrt(0.5 * r);
75  if (y > 0)
76  w = cpack(r, r);
77  else
78  w = cpack(r, -r);
79  return w;
80  }
81  /* Rescale to avoid internal overflow or underflow. */
82  if ((fabs(x) > 4.0) || (fabs(y) > 4.0))
83  {
84  x *= 0.25;
85  y *= 0.25;
86  scale = 2.0;
87  }
88  else
89  {
90 #if 1
91  x *= 1.8014398509481984e16; /* 2^54 */
92  y *= 1.8014398509481984e16;
93  scale = 7.450580596923828125e-9; /* 2^-27 */
94 #else
95  x *= 4.0;
96  y *= 4.0;
97  scale = 0.5;
98 #endif
99  }
100  w = cpack(x, y);
101  r = cabs(w);
102  if (x > 0)
103  {
104  t = sqrt(0.5 * r + 0.5 * x);
105  r = scale * fabs((0.5 * y) / t);
106  t *= scale;
107  }
108  else
109  {
110  r = sqrt(0.5 * r - 0.5 * x);
111  t = scale * fabs((0.5 * y) / r);
112  r *= scale;
113  }
114  if (y < 0)
115  w = cpack(t, -r);
116  else
117  w = cpack(t, r);
118  return w;
119 }
Definition: mathi.h:48
complex cpack(double x, double y)
Pack two real numbers into a complex number.
Definition: prim.c:68
double cimag(complex z)
Imaginary part of complex number.
Definition: prim.c:46
double creal(complex z)
Real part of complex number.
Definition: prim.c:38
double sqrt(double x)
Square root function.
Definition: sqrt.c:119
double fabs(double x)
Returns the absolute value of x.
Definition: fabs.c:51
double cabs(complex z)
Absolute value of complex number.
Definition: prim.c:54
Here is the call graph for this function:
Here is the caller graph for this function: