gitee.com/quant1x/num@v0.3.2/math32/hypot.go (about) 1 package math32 2 3 /* 4 Hypot -- sqrt(p*p + q*q), but overflows only if the result does. 5 */ 6 7 // Hypot returns Sqrt(p*p + q*q), taking care to avoid 8 // unnecessary overflow and underflow. 9 // 10 // Special cases are: 11 // 12 // Hypot(±Inf, q) = +Inf 13 // Hypot(p, ±Inf) = +Inf 14 // Hypot(NaN, q) = NaN 15 // Hypot(p, NaN) = NaN 16 func Hypot(p, q float32) float32 { 17 return hypot(p, q) 18 } 19 20 func hypot(p, q float32) float32 { 21 // special cases 22 switch { 23 case IsInf(p, 0) || IsInf(q, 0): 24 return Inf(1) 25 case IsNaN(p) || IsNaN(q): 26 return NaN() 27 } 28 if p < 0 { 29 p = -p 30 } 31 if q < 0 { 32 q = -q 33 } 34 if p < q { 35 p, q = q, p 36 } 37 if p == 0 { 38 return 0 39 } 40 q = q / p 41 return p * Sqrt(1+q*q) 42 }