1
0
mirror of https://github.com/golang/go synced 2024-10-04 18:21:21 -06:00
go/src/pkg/math/mod.go

51 lines
997 B
Go
Raw Normal View History

// Copyright 2009-2010 The Go Authors. All rights reserved.
2008-03-28 14:56:47 -06:00
// 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
/*
Floating-point mod function.
*/
2008-03-28 14:56:47 -06:00
// Mod returns the floating-point remainder of x/y.
// The magnitude of the result is less than y and its
// sign agrees with that of x.
//
// Special cases are:
// Mod(±Inf, y) = NaN
// Mod(NaN, y) = NaN
// Mod(x, 0) = NaN
// Mod(x, ±Inf) = x
// Mod(x, NaN) = NaN
func Mod(x, y float64) float64 {
// TODO(rsc): Remove manual inlining of IsNaN, IsInf
// when compiler does it for us.
if y == 0 || x > MaxFloat64 || x < -MaxFloat64 || x != x || y != y { // y == 0 || IsInf(x, 0) || IsNaN(x) || IsNan(y)
return NaN()
2008-03-28 14:56:47 -06:00
}
if y < 0 {
y = -y
2008-03-28 14:56:47 -06:00
}
yfr, yexp := Frexp(y)
sign := false
r := x
2008-03-28 14:56:47 -06:00
if x < 0 {
r = -x
sign = true
2008-03-28 14:56:47 -06:00
}
for r >= y {
rfr, rexp := Frexp(r)
2008-03-28 14:56:47 -06:00
if rfr < yfr {
rexp = rexp - 1
2008-03-28 14:56:47 -06:00
}
r = r - Ldexp(y, rexp-yexp)
2008-03-28 14:56:47 -06:00
}
if sign {
r = -r
2008-03-28 14:56:47 -06:00
}
return r
2008-03-28 14:56:47 -06:00
}