github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/math/hypot.go (about) 1 // Copyright 2010 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package math 6 7 /* 8 Hypot -- sqrt(p*p + q*q), but overflows only if the result does. 9 */ 10 11 // Hypot returns [Sqrt](p*p + q*q), taking care to avoid 12 // unnecessary overflow and underflow. 13 // 14 // Special cases are: 15 // 16 // Hypot(±Inf, q) = +Inf 17 // Hypot(p, ±Inf) = +Inf 18 // Hypot(NaN, q) = NaN 19 // Hypot(p, NaN) = NaN 20 func Hypot(p, q float64) float64 { 21 if haveArchHypot { 22 return archHypot(p, q) 23 } 24 return hypot(p, q) 25 } 26 27 func hypot(p, q float64) float64 { 28 p, q = Abs(p), Abs(q) 29 // special cases 30 switch { 31 case IsInf(p, 1) || IsInf(q, 1): 32 return Inf(1) 33 case IsNaN(p) || IsNaN(q): 34 return NaN() 35 } 36 if p < q { 37 p, q = q, p 38 } 39 if p == 0 { 40 return 0 41 } 42 q = q / p 43 return p * Sqrt(1+q*q) 44 }