1
0
mirror of https://github.com/golang/go synced 2024-11-19 15:14:45 -07:00
go/src/pkg/math/hypot.go

51 lines
842 B
Go
Raw Normal View History

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.
package math
2008-03-28 14:56:47 -06: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
// 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 {
p = -p
2008-03-28 14:56:47 -06:00
}
if q < 0 {
q = -q
2008-03-28 14:56:47 -06:00
}
if p < q {
p, q = q, p
2008-03-28 14:56:47 -06:00
}
if p == 0 {
return 0
2008-03-28 14:56:47 -06:00
}
pfac := p
q = q / p
r := q
p = 1
2008-07-08 21:48:41 -06:00
for {
r = r * r
s := r + 4
2008-03-28 14:56:47 -06:00
if s == 4 {
return p * pfac
2008-03-28 14:56:47 -06:00
}
r = r / s
p = p + 2*r*p
q = q * r
r = q / p
2008-03-28 14:56:47 -06:00
}
panic("unreachable")
2008-03-28 14:56:47 -06:00
}