complex.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 runtime
  5. func complex128div(n complex128, d complex128) complex128 {
  6. // Special cases as in C99.
  7. ninf := real(n) == posinf || real(n) == neginf ||
  8. imag(n) == posinf || imag(n) == neginf
  9. dinf := real(d) == posinf || real(d) == neginf ||
  10. imag(d) == posinf || imag(d) == neginf
  11. nnan := !ninf && (real(n) != real(n) || imag(n) != imag(n))
  12. dnan := !dinf && (real(d) != real(d) || imag(d) != imag(d))
  13. switch {
  14. case nnan || dnan:
  15. return complex(nan, nan)
  16. case ninf && !dinf:
  17. return complex(posinf, posinf)
  18. case !ninf && dinf:
  19. return complex(0, 0)
  20. case real(d) == 0 && imag(d) == 0:
  21. if real(n) == 0 && imag(n) == 0 {
  22. return complex(nan, nan)
  23. } else {
  24. return complex(posinf, posinf)
  25. }
  26. default:
  27. // Standard complex arithmetic, factored to avoid unnecessary overflow.
  28. a := real(d)
  29. if a < 0 {
  30. a = -a
  31. }
  32. b := imag(d)
  33. if b < 0 {
  34. b = -b
  35. }
  36. if a <= b {
  37. ratio := real(d) / imag(d)
  38. denom := real(d)*ratio + imag(d)
  39. return complex((real(n)*ratio+imag(n))/denom,
  40. (imag(n)*ratio-real(n))/denom)
  41. } else {
  42. ratio := imag(d) / real(d)
  43. denom := imag(d)*ratio + real(d)
  44. return complex((imag(n)*ratio+real(n))/denom,
  45. (imag(n)-real(n)*ratio)/denom)
  46. }
  47. }
  48. }