blob: 2087cb05b36b361265913b5ecfbd1eda9e1c4b04 [file] [log] [blame]
Charles L. Dorian067fe282010-03-05 16:45:39 -08001// Copyright 2010 The Go Authors. All rights reserved.
Ken Thompson21810982008-03-28 13:56:47 -07002// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Rob Pike43312932008-06-27 17:06:23 -07005package math
Ken Thompson21810982008-03-28 13:56:47 -07006
Ken Thompson21810982008-03-28 13:56:47 -07007/*
Rob Pike00e2cda2010-01-12 07:38:31 +11008 Hypot -- sqrt(p*p + q*q), but overflows only if the result does.
Rob Pike00e2cda2010-01-12 07:38:31 +11009*/
Ken Thompson21810982008-03-28 13:56:47 -070010
Charles L. Dorianf2734872012-04-06 14:01:12 -040011// Hypot returns Sqrt(p*p + q*q), taking care to avoid
Russ Coxdfc39102009-03-05 13:31:01 -080012// unnecessary overflow and underflow.
Charles L. Dorian9a6b8e22010-01-15 13:21:47 -080013//
14// Special cases are:
Russ Cox60a1f542013-03-25 17:01:40 -040015// Hypot(±Inf, q) = +Inf
16// Hypot(p, ±Inf) = +Inf
17// Hypot(NaN, q) = NaN
18// Hypot(p, NaN) = NaN
Russ Coxdd8dc6f2011-12-13 15:20:12 -050019func Hypot(p, q float64) float64
20
Russ Cox25728032011-12-13 17:08:56 -050021func hypot(p, q float64) float64 {
Charles L. Dorian9a6b8e22010-01-15 13:21:47 -080022 // special cases
23 switch {
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010024 case IsInf(p, 0) || IsInf(q, 0):
Charles L. Dorian9a6b8e22010-01-15 13:21:47 -080025 return Inf(1)
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010026 case IsNaN(p) || IsNaN(q):
Charles L. Dorian9a6b8e22010-01-15 13:21:47 -080027 return NaN()
28 }
Ken Thompson21810982008-03-28 13:56:47 -070029 if p < 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -080030 p = -p
Ken Thompson21810982008-03-28 13:56:47 -070031 }
32 if q < 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -080033 q = -q
Ken Thompson21810982008-03-28 13:56:47 -070034 }
Ken Thompson21810982008-03-28 13:56:47 -070035 if p < q {
Robert Griesemer40621d52009-11-09 12:07:39 -080036 p, q = q, p
Ken Thompson21810982008-03-28 13:56:47 -070037 }
Ken Thompson21810982008-03-28 13:56:47 -070038 if p == 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -080039 return 0
Ken Thompson21810982008-03-28 13:56:47 -070040 }
Robert Griesemera3d10452009-12-15 15:35:38 -080041 q = q / p
Charles L. Dorian067fe282010-03-05 16:45:39 -080042 return p * Sqrt(1+q*q)
Ken Thompson21810982008-03-28 13:56:47 -070043}