hypot.go 822 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. package math
  5. /*
  6. Hypot -- sqrt(p*p + q*q), but overflows only if the result does.
  7. */
  8. // Hypot returns Sqrt(p*p + q*q), taking care to avoid
  9. // unnecessary overflow and underflow.
  10. //
  11. // Special cases are:
  12. // Hypot(±Inf, q) = +Inf
  13. // Hypot(p, ±Inf) = +Inf
  14. // Hypot(NaN, q) = NaN
  15. // Hypot(p, NaN) = NaN
  16. func Hypot(p, q float64) float64 {
  17. return hypot(p, q)
  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. }