Source file src/pkg/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 computes Sqrt(p*p + q*q), taking care to avoid
12 // unnecessary overflow and underflow.
13 //
14 // Special cases are:
15 // Hypot(p, q) = +Inf if p or q is infinite
16 // Hypot(p, q) = NaN if p or q is NaN
17 func Hypot(p, q float64) float64
18
19 func hypot(p, q float64) float64 {
20 // special cases
21 switch {
22 case IsInf(p, 0) || IsInf(q, 0):
23 return Inf(1)
24 case IsNaN(p) || IsNaN(q):
25 return NaN()
26 }
27 if p < 0 {
28 p = -p
29 }
30 if q < 0 {
31 q = -q
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 }