Charles L. Dorian | 04217ee | 2010-02-05 00:41:30 -0800 | [diff] [blame] | 1 | // 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 | |
| 5 | package math |
| 6 | |
| 7 | // Modf returns integer and fractional floating-point numbers |
Brad Fitzpatrick | 5fea2cc | 2016-03-01 23:21:55 +0000 | [diff] [blame] | 8 | // that sum to f. Both values have the same sign as f. |
Charles L. Dorian | 04217ee | 2010-02-05 00:41:30 -0800 | [diff] [blame] | 9 | // |
| 10 | // Special cases are: |
Charles L. Dorian | c8d2544 | 2011-11-28 13:04:52 -0800 | [diff] [blame] | 11 | // Modf(±Inf) = ±Inf, NaN |
Charles L. Dorian | 04217ee | 2010-02-05 00:41:30 -0800 | [diff] [blame] | 12 | // Modf(NaN) = NaN, NaN |
Russ Cox | dd8dc6f | 2011-12-13 15:20:12 -0500 | [diff] [blame] | 13 | func Modf(f float64) (int float64, frac float64) |
| 14 | |
| 15 | func modf(f float64) (int float64, frac float64) { |
Charles L. Dorian | 04217ee | 2010-02-05 00:41:30 -0800 | [diff] [blame] | 16 | if f < 1 { |
Charlie Dorian | 6fed2a6 | 2015-10-07 18:23:28 -0400 | [diff] [blame] | 17 | switch { |
| 18 | case f < 0: |
Charles L. Dorian | 04217ee | 2010-02-05 00:41:30 -0800 | [diff] [blame] | 19 | int, frac = Modf(-f) |
| 20 | return -int, -frac |
Charlie Dorian | 6fed2a6 | 2015-10-07 18:23:28 -0400 | [diff] [blame] | 21 | case f == 0: |
| 22 | return f, f // Return -0, -0 when f == -0 |
Charles L. Dorian | 04217ee | 2010-02-05 00:41:30 -0800 | [diff] [blame] | 23 | } |
| 24 | return 0, f |
| 25 | } |
| 26 | |
| 27 | x := Float64bits(f) |
| 28 | e := uint(x>>shift)&mask - bias |
| 29 | |
Eoghan Sherry | 976e457 | 2010-12-15 13:20:52 -0500 | [diff] [blame] | 30 | // 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. Dorian | 04217ee | 2010-02-05 00:41:30 -0800 | [diff] [blame] | 33 | } |
| 34 | int = Float64frombits(x) |
| 35 | frac = f - int |
| 36 | return |
| 37 | } |