blob: c5bb89455f91856d788afb2133095c535c80eee7 [file] [log] [blame]
Charles L. Dorian04217ee2010-02-05 00:41:30 -08001// Copyright 2009 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
5package math
6
7// Modf returns integer and fractional floating-point numbers
Brad Fitzpatrick5fea2cc2016-03-01 23:21:55 +00008// that sum to f. Both values have the same sign as f.
Charles L. Dorian04217ee2010-02-05 00:41:30 -08009//
10// Special cases are:
Charles L. Dorianc8d25442011-11-28 13:04:52 -080011// Modf(±Inf) = ±Inf, NaN
Charles L. Dorian04217ee2010-02-05 00:41:30 -080012// Modf(NaN) = NaN, NaN
Russ Coxdd8dc6f2011-12-13 15:20:12 -050013func Modf(f float64) (int float64, frac float64)
14
15func modf(f float64) (int float64, frac float64) {
Charles L. Dorian04217ee2010-02-05 00:41:30 -080016 if f < 1 {
Charlie Dorian6fed2a62015-10-07 18:23:28 -040017 switch {
18 case f < 0:
Charles L. Dorian04217ee2010-02-05 00:41:30 -080019 int, frac = Modf(-f)
20 return -int, -frac
Charlie Dorian6fed2a62015-10-07 18:23:28 -040021 case f == 0:
22 return f, f // Return -0, -0 when f == -0
Charles L. Dorian04217ee2010-02-05 00:41:30 -080023 }
24 return 0, f
25 }
26
27 x := Float64bits(f)
28 e := uint(x>>shift)&mask - bias
29
Eoghan Sherry976e4572010-12-15 13:20:52 -050030 // Keep the top 12+e bits, the integer part; clear the rest.
31 if e < 64-12 {
32 x &^= 1<<(64-12-e) - 1
Charles L. Dorian04217ee2010-02-05 00:41:30 -080033 }
34 int = Float64frombits(x)
35 frac = f - int
36 return
37}