Source file src/math/hypot.go

     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  	// special cases
    29  	switch {
    30  	case IsInf(p, 0) || IsInf(q, 0):
    31  		return Inf(1)
    32  	case IsNaN(p) || IsNaN(q):
    33  		return NaN()
    34  	}
    35  	p, q = Abs(p), Abs(q)
    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  }
    45  

View as plain text