| 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 |
// According to https://github.com/golang/go/issues/20100, the Go stdlib will |
| 6 |
// include math.Round beginning with Go 1.10. |
| 7 |
// |
| 8 |
// The following implementation was taken from https://golang.org/cl/43652. |
| 9 |
|
| 10 |
package math |
| 11 |
|
| 12 |
import "math" |
| 13 |
|
| 14 |
const ( |
| 15 |
mask = 0x7FF |
| 16 |
shift = 64 - 11 - 1 |
| 17 |
bias = 1023 |
| 18 |
) |
| 19 |
|
| 20 |
// Round returns the nearest integer, rounding half away from zero. |
| 21 |
// |
| 22 |
// Special cases are: |
| 23 |
// |
| 24 |
// Round(±0) = ±0 |
| 25 |
// Round(±Inf) = ±Inf |
| 26 |
// Round(NaN) = NaN |
| 27 |
func _round(x float64) float64 { |
| 28 |
// Round is a faster implementation of: |
| 29 |
// |
| 30 |
// func Round(x float64) float64 { |
| 31 |
// t := Trunc(x) |
| 32 |
// if Abs(x-t) >= 0.5 { |
| 33 |
// return t + Copysign(1, x) |
| 34 |
// } |
| 35 |
// return t |
| 36 |
// } |
| 37 |
const ( |
| 38 |
signMask = 1 << 63 |
| 39 |
fracMask = 1<<shift - 1 |
| 40 |
half = 1 << (shift - 1) |
| 41 |
one = bias << shift |
| 42 |
) |
| 43 |
|
| 44 |
bits := math.Float64bits(x) |
| 45 |
e := uint(bits>>shift) & mask |
| 46 |
if e < bias { |
| 47 |
// Round abs(x) < 1 including denormals. |
| 48 |
bits &= signMask // +-0 |
| 49 |
if e == bias-1 { |
| 50 |
bits |= one // +-1 |
| 51 |
} |
| 52 |
} else if e < bias+shift { |
| 53 |
// Round any abs(x) >= 1 containing a fractional component [0,1). |
| 54 |
// |
| 55 |
// Numbers with larger exponents are returned unchanged since they |
| 56 |
// must be either an integer, infinity, or NaN. |
| 57 |
e -= bias |
| 58 |
bits += half >> e |
| 59 |
bits &^= fracMask >> e |
| 60 |
} |
| 61 |
return math.Float64frombits(bits) |
| 62 |
} |