Source file src/pkg/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(x) 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 // TODO(rsc): Remove manual inlining of IsNaN, IsInf 15 // when compiler does it for us 16 // special cases 17 switch { 18 case x == 0: 19 return Inf(-1) 20 case x < -MaxFloat64 || x > MaxFloat64: // IsInf(x, 0): 21 return Inf(1) 22 case x != x: // IsNaN(x): 23 return x 24 } 25 return float64(ilogb(x)) 26 } 27 28 // Ilogb(x) returns the binary exponent of x as an integer. 29 // 30 // Special cases are: 31 // Ilogb(±Inf) = MaxInt32 32 // Ilogb(0) = MinInt32 33 // Ilogb(NaN) = MaxInt32 34 func Ilogb(x float64) int { 35 // TODO(rsc): Remove manual inlining of IsNaN, IsInf 36 // when compiler does it for us 37 // special cases 38 switch { 39 case x == 0: 40 return MinInt32 41 case x != x: // IsNaN(x): 42 return MaxInt32 43 case x < -MaxFloat64 || x > MaxFloat64: // IsInf(x, 0): 44 return MaxInt32 45 } 46 return ilogb(x) 47 } 48 49 // logb returns the binary exponent of x. It assumes x is finite and 50 // non-zero. 51 func ilogb(x float64) int { 52 x, exp := normalize(x) 53 return int((Float64bits(x)>>shift)&mask) - bias + exp 54 }