1/* $NetBSD: csqrtf.c,v 1.4 2017/01/01 19:32:14 maya Exp $ */ 2 3/*- 4 * Copyright (c) 2007 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software written by Stephen L. Moshier. 8 * It is redistributed by the NetBSD Foundation by permission of the author. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32#include <complex.h> 33#include <math.h> 34 35float complex 36csqrtf(float complex z) 37{ 38 float complex w; 39 float x, y, r, t, scale; 40 41 x = crealf (z); 42 y = cimagf (z); 43 44 /* 45 * input is a real number and imaginary part isn't -0.0. 46 * negative zero is on the branch cut. 47 */ 48 if ((y == 0.0f) && !signbit(y)) { 49 if (x < 0.0f) { 50 w = 0.0f + sqrtf(-x) * I; 51 return w; 52 } else if (x == 0.0f) { 53 return (0.0f + y * I); 54 } else { 55 w = sqrtf(x) + y * I; 56 return w; 57 } 58 } 59 60 if (x == 0.0f) { 61 if (y > 0) { 62 r = sqrtf(0.5f * y); 63 w = r + r * I; 64 } else { 65 r = sqrtf(-0.5f * y); 66 w = r - r * I; 67 } 68 return w; 69 } 70 71 /* Rescale to avoid internal overflow or underflow. */ 72 if ((fabsf(x) > 4.0f) || (fabsf(y) > 4.0f)) { 73 x *= 0.25f; 74 y *= 0.25f; 75 scale = 2.0f; 76 } else { 77#if 1 78 x *= 6.7108864e7f; /* 2^26 */ 79 y *= 6.7108864e7f; 80 scale = 1.220703125e-4f; /* 2^-13 */ 81#else 82 x *= 4.0f; 83 y *= 4.0f; 84 scale = 0.5f; 85#endif 86 } 87 w = x + y * I; 88 r = cabsf(w); 89 if( x > 0 ) { 90 t = sqrtf(0.5f * r + 0.5f * x); 91 r = scale * fabsf((0.5f * y) / t); 92 t *= scale; 93 } else { 94 r = sqrtf(0.5f * r - 0.5f * x); 95 t = scale * fabsf((0.5f * y) / r); 96 r *= scale; 97 } 98 99 if (y > 0) 100 w = t + r * I; 101 else 102 w = t - r * I; 103 return w; 104} 105