github.com/hongwozai/go-src-1.4.3@v0.0.0-20191127132709-dc3fce3dbccb/src/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  //	Hypot(±Inf, q) = +Inf
    16  //	Hypot(p, ±Inf) = +Inf
    17  //	Hypot(NaN, q) = NaN
    18  //	Hypot(p, NaN) = NaN
    19  func Hypot(p, q float64) float64
    20  
    21  func hypot(p, q float64) float64 {
    22  	// special cases
    23  	switch {
    24  	case IsInf(p, 0) || IsInf(q, 0):
    25  		return Inf(1)
    26  	case IsNaN(p) || IsNaN(q):
    27  		return NaN()
    28  	}
    29  	if p < 0 {
    30  		p = -p
    31  	}
    32  	if q < 0 {
    33  		q = -q
    34  	}
    35  	if p < q {
    36  		p, q = q, p
    37  	}
    38  	if p == 0 {
    39  		return 0
    40  	}
    41  	q = q / p
    42  	return p * Sqrt(1+q*q)
    43  }