github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/math/floor.go (about)

     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  // Floor returns the greatest integer value less than or equal to x.
     8  //
     9  // Special cases are:
    10  //	Floor(±0) = ±0
    11  //	Floor(±Inf) = ±Inf
    12  //	Floor(NaN) = NaN
    13  func Floor(x float64) float64
    14  
    15  func floor(x float64) float64 {
    16  	if x == 0 || IsNaN(x) || IsInf(x, 0) {
    17  		return x
    18  	}
    19  	if x < 0 {
    20  		d, fract := Modf(-x)
    21  		if fract != 0.0 {
    22  			d = d + 1
    23  		}
    24  		return -d
    25  	}
    26  	d, _ := Modf(x)
    27  	return d
    28  }
    29  
    30  // Ceil returns the least integer value greater than or equal to x.
    31  //
    32  // Special cases are:
    33  //	Ceil(±0) = ±0
    34  //	Ceil(±Inf) = ±Inf
    35  //	Ceil(NaN) = NaN
    36  func Ceil(x float64) float64
    37  
    38  func ceil(x float64) float64 {
    39  	return -Floor(-x)
    40  }
    41  
    42  // Trunc returns the integer value of x.
    43  //
    44  // Special cases are:
    45  //	Trunc(±0) = ±0
    46  //	Trunc(±Inf) = ±Inf
    47  //	Trunc(NaN) = NaN
    48  func Trunc(x float64) float64
    49  
    50  func trunc(x float64) float64 {
    51  	if x == 0 || IsNaN(x) || IsInf(x, 0) {
    52  		return x
    53  	}
    54  	d, _ := Modf(x)
    55  	return d
    56  }
    57  
    58  // Round returns the nearest integer, rounding half away from zero.
    59  //
    60  // Special cases are:
    61  //	Round(±0) = ±0
    62  //	Round(±Inf) = ±Inf
    63  //	Round(NaN) = NaN
    64  func Round(x float64) float64 {
    65  	// Round is a faster implementation of:
    66  	//
    67  	// func Round(x float64) float64 {
    68  	//   t := Trunc(x)
    69  	//   if Abs(x-t) >= 0.5 {
    70  	//     return t + Copysign(1, x)
    71  	//   }
    72  	//   return t
    73  	// }
    74  	const (
    75  		signMask = 1 << 63
    76  		fracMask = 1<<shift - 1
    77  		half     = 1 << (shift - 1)
    78  		one      = bias << shift
    79  	)
    80  
    81  	bits := Float64bits(x)
    82  	e := uint(bits>>shift) & mask
    83  	if e < bias {
    84  		// Round abs(x) < 1 including denormals.
    85  		bits &= signMask // +-0
    86  		if e == bias-1 {
    87  			bits |= one // +-1
    88  		}
    89  	} else if e < bias+shift {
    90  		// Round any abs(x) >= 1 containing a fractional component [0,1).
    91  		//
    92  		// Numbers with larger exponents are returned unchanged since they
    93  		// must be either an integer, infinity, or NaN.
    94  		e -= bias
    95  		bits += half >> e
    96  		bits &^= fracMask >> e
    97  	}
    98  	return Float64frombits(bits)
    99  }