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