2008-03-28 14:56:47 -06:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2008-06-27 18:06:23 -06:00
|
|
|
package math
|
2008-03-28 14:56:47 -06:00
|
|
|
|
|
|
|
/*
|
2010-01-11 13:38:31 -07:00
|
|
|
Hypot -- sqrt(p*p + q*q), but overflows only if the result does.
|
|
|
|
See:
|
|
|
|
Cleve Moler and Donald Morrison,
|
|
|
|
Replacing Square Roots by Pythagorean Sums
|
|
|
|
IBM Journal of Research and Development,
|
|
|
|
Vol. 27, Number 6, pp. 577-581, Nov. 1983
|
|
|
|
*/
|
2008-03-28 14:56:47 -06:00
|
|
|
|
2009-03-05 14:31:01 -07:00
|
|
|
// Hypot computes Sqrt(p*p + q*q), taking care to avoid
|
|
|
|
// unnecessary overflow and underflow.
|
2009-01-20 15:40:40 -07:00
|
|
|
func Hypot(p, q float64) float64 {
|
2008-03-28 14:56:47 -06:00
|
|
|
if p < 0 {
|
2009-11-09 13:07:39 -07:00
|
|
|
p = -p
|
2008-03-28 14:56:47 -06:00
|
|
|
}
|
|
|
|
if q < 0 {
|
2009-11-09 13:07:39 -07:00
|
|
|
q = -q
|
2008-03-28 14:56:47 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if p < q {
|
2009-11-09 13:07:39 -07:00
|
|
|
p, q = q, p
|
2008-03-28 14:56:47 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if p == 0 {
|
2009-11-09 13:07:39 -07:00
|
|
|
return 0
|
2008-03-28 14:56:47 -06:00
|
|
|
}
|
|
|
|
|
2009-12-15 16:35:38 -07:00
|
|
|
pfac := p
|
|
|
|
q = q / p
|
|
|
|
r := q
|
|
|
|
p = 1
|
2008-07-08 21:48:41 -06:00
|
|
|
for {
|
2009-12-15 16:35:38 -07:00
|
|
|
r = r * r
|
|
|
|
s := r + 4
|
2008-03-28 14:56:47 -06:00
|
|
|
if s == 4 {
|
2009-11-09 22:23:52 -07:00
|
|
|
return p * pfac
|
2008-03-28 14:56:47 -06:00
|
|
|
}
|
2009-12-15 16:35:38 -07:00
|
|
|
r = r / s
|
|
|
|
p = p + 2*r*p
|
|
|
|
q = q * r
|
|
|
|
r = q / p
|
2008-03-28 14:56:47 -06:00
|
|
|
}
|
2009-12-15 16:35:38 -07:00
|
|
|
panic("unreachable")
|
2008-03-28 14:56:47 -06:00
|
|
|
}
|