mod.go 959 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2009-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. Floating-point mod function.
  7. */
  8. // Mod returns the floating-point remainder of x/y.
  9. // The magnitude of the result is less than y and its
  10. // sign agrees with that of x.
  11. //
  12. // Special cases are:
  13. // Mod(±Inf, y) = NaN
  14. // Mod(NaN, y) = NaN
  15. // Mod(x, 0) = NaN
  16. // Mod(x, ±Inf) = x
  17. // Mod(x, NaN) = NaN
  18. //extern fmod
  19. func libc_fmod(float64, float64) float64
  20. func Mod(x, y float64) float64 {
  21. return libc_fmod(x, y)
  22. }
  23. func mod(x, y float64) float64 {
  24. if y == 0 || IsInf(x, 0) || IsNaN(x) || IsNaN(y) {
  25. return NaN()
  26. }
  27. if y < 0 {
  28. y = -y
  29. }
  30. yfr, yexp := Frexp(y)
  31. sign := false
  32. r := x
  33. if x < 0 {
  34. r = -x
  35. sign = true
  36. }
  37. for r >= y {
  38. rfr, rexp := Frexp(r)
  39. if rfr < yfr {
  40. rexp = rexp - 1
  41. }
  42. r = r - Ldexp(y, rexp-yexp)
  43. }
  44. if sign {
  45. r = -r
  46. }
  47. return r
  48. }