github.com/primecitizens/pcz/std@v0.2.1/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  	return hypot(p, q)
    22  }
    23  
    24  func hypot(p, q float64) float64 {
    25  	p, q = Abs(p), Abs(q)
    26  	// special cases
    27  	switch {
    28  	case IsInf(p, 1) || IsInf(q, 1):
    29  		return Inf(1)
    30  	case IsNaN(p) || IsNaN(q):
    31  		return NaN()
    32  	}
    33  	if p < q {
    34  		p, q = q, p
    35  	}
    36  	if p == 0 {
    37  		return 0
    38  	}
    39  	q = q / p
    40  	return p * Sqrt(1+q*q)
    41  }