Source file src/math/logb.go

     1  // Copyright 2010 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  // Logb returns the binary exponent of x.
     8  //
     9  // Special cases are:
    10  //
    11  //	Logb(±Inf) = +Inf
    12  //	Logb(0) = -Inf
    13  //	Logb(NaN) = NaN
    14  func Logb(x float64) float64 {
    15  	// special cases
    16  	switch {
    17  	case x == 0:
    18  		return Inf(-1)
    19  	case IsInf(x, 0):
    20  		return Inf(1)
    21  	case IsNaN(x):
    22  		return x
    23  	}
    24  	return float64(ilogb(x))
    25  }
    26  
    27  // Ilogb returns the binary exponent of x as an integer.
    28  //
    29  // Special cases are:
    30  //
    31  //	Ilogb(±Inf) = MaxInt32
    32  //	Ilogb(0) = MinInt32
    33  //	Ilogb(NaN) = MaxInt32
    34  func Ilogb(x float64) int {
    35  	// special cases
    36  	switch {
    37  	case x == 0:
    38  		return MinInt32
    39  	case IsNaN(x):
    40  		return MaxInt32
    41  	case IsInf(x, 0):
    42  		return MaxInt32
    43  	}
    44  	return ilogb(x)
    45  }
    46  
    47  // ilogb returns the binary exponent of x. It assumes x is finite and
    48  // non-zero.
    49  func ilogb(x float64) int {
    50  	x, exp := normalize(x)
    51  	return int((Float64bits(x)>>shift)&mask) - bias + exp
    52  }
    53  

View as plain text