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