home *** CD-ROM | disk | FTP | other *** search
- /*
- CxSqrt -- compute square root of complex number
-
- CxSqrt( &c ) replaces c by sqrt(c) and returns &c
-
- Note: This is a double-valued function; the result of
- CxSqrt() always has nonnegative imaginary part.
-
- inspired by Jeff Hanes' version
-
- last edit: 86/01/04 D A Gwyn
-
- SCCS ID: @(#)cxsqrt.c 1.1 (modified for public version)
- */
-
- #include <math.h>
-
- #include <complex.h>
-
- #define Sgn( x ) ((x) == 0 ? 0 : (x) > 0 ? 1 : -1)
-
- complex *
- CxSqrt( cp )
- register complex *cp;
- {
- /* record signs of original real & imaginary parts */
- int re_sign = Sgn( cp->re );
- int im_sign = Sgn( cp->im );
-
- /* special cases are not necessary; they are here for speed */
-
- if ( re_sign == 0 )
- if ( im_sign == 0 )
- ; /* (0,0) already there */
- else if ( im_sign > 0 )
- cp->re = cp->im = sqrt( cp->im / 2.0 );
- else /* im_sign < 0 */
- cp->re = -(cp->im = sqrt( -cp->im / 2.0 ));
- else if ( im_sign == 0 )
- if ( re_sign > 0 )
- cp->re = sqrt( cp->re );
- /* cp->im = 0.0; /* 0 already there */
- else { /* re_sign < 0 */
- cp->im = sqrt( -cp->re );
- cp->re = 0.0;
- }
- else { /* no shortcuts */
- double ampl = CxAmpl( cp );
-
- cp->im = sqrt( (ampl - cp->re) /2.0 );
-
- if ( im_sign > 0 )
- cp->re = sqrt( (ampl + cp->re) / 2.0 );
- else /* im_sign < 0 */
- cp->re = -sqrt( (ampl + cp->re) / 2.0 );
- }
-
- return cp;
- }
-