blob: 6ae70c1333f335410613777eac3f704b2d1e92a7 [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 Cox19309772022-02-03 14:12:08 -050015//
Russ Cox60a1f542013-03-25 17:01:40 -040016// Hypot(±Inf, q) = +Inf
17// Hypot(p, ±Inf) = +Inf
18// Hypot(NaN, q) = NaN
19// Hypot(p, NaN) = NaN
Austin Clements1d20a362021-04-14 21:57:24 -040020func Hypot(p, q float64) float64 {
21 if haveArchHypot {
22 return archHypot(p, q)
23 }
24 return hypot(p, q)
25}
Russ Coxdd8dc6f2011-12-13 15:20:12 -050026
Russ Cox25728032011-12-13 17:08:56 -050027func hypot(p, q float64) float64 {
eric fangdd7ce262022-06-29 03:09:54 +000028 p, q = Abs(p), Abs(q)
Charles L. Dorian9a6b8e22010-01-15 13:21:47 -080029 // special cases
30 switch {
eric fangdd7ce262022-06-29 03:09:54 +000031 case IsInf(p, 1) || IsInf(q, 1):
Charles L. Dorian9a6b8e22010-01-15 13:21:47 -080032 return Inf(1)
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010033 case IsNaN(p) || IsNaN(q):
Charles L. Dorian9a6b8e22010-01-15 13:21:47 -080034 return NaN()
35 }
Ken Thompson21810982008-03-28 13:56:47 -070036 if p < q {
Robert Griesemer40621d52009-11-09 12:07:39 -080037 p, q = q, p
Ken Thompson21810982008-03-28 13:56:47 -070038 }
Ken Thompson21810982008-03-28 13:56:47 -070039 if p == 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -080040 return 0
Ken Thompson21810982008-03-28 13:56:47 -070041 }
Robert Griesemera3d10452009-12-15 15:35:38 -080042 q = q / p
Charles L. Dorian067fe282010-03-05 16:45:39 -080043 return p * Sqrt(1+q*q)
Ken Thompson21810982008-03-28 13:56:47 -070044}