blob: f2769d4fd754457594d92ccb6530050bc1bbff2c [file] [log] [blame]
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -08001// 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
5package math
6
Charles L. Dorianf2734872012-04-06 14:01:12 -04007// Logb returns the binary exponent of x.
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -08008//
9// Special cases are:
10// Logb(±Inf) = +Inf
11// Logb(0) = -Inf
12// Logb(NaN) = NaN
13func Logb(x float64) float64 {
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080014 // special cases
15 switch {
16 case x == 0:
17 return Inf(-1)
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010018 case IsInf(x, 0):
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080019 return Inf(1)
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010020 case IsNaN(x):
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080021 return x
22 }
Eoghan Sherry13c2e622011-01-19 14:23:59 -050023 return float64(ilogb(x))
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080024}
25
Charles L. Dorianf2734872012-04-06 14:01:12 -040026// Ilogb returns the binary exponent of x as an integer.
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080027//
28// Special cases are:
29// Ilogb(±Inf) = MaxInt32
30// Ilogb(0) = MinInt32
31// Ilogb(NaN) = MaxInt32
32func Ilogb(x float64) int {
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080033 // special cases
34 switch {
35 case x == 0:
36 return MinInt32
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010037 case IsNaN(x):
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080038 return MaxInt32
Luuk van Dijk8dd3de42012-02-01 16:08:31 +010039 case IsInf(x, 0):
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080040 return MaxInt32
41 }
Eoghan Sherry13c2e622011-01-19 14:23:59 -050042 return ilogb(x)
43}
44
45// logb returns the binary exponent of x. It assumes x is finite and
46// non-zero.
47func ilogb(x float64) int {
48 x, exp := normalize(x)
49 return int((Float64bits(x)>>shift)&mask) - bias + exp
Charles L. Dorian6b80a5f2010-03-03 18:17:13 -080050}