LEFT | RIGHT |
(no file at all) | |
1 // Copyright 2010 The Go Authors. All rights reserved. | 1 // Copyright 2010 The Go Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style | 2 // Use of this source code is governed by a BSD-style |
3 // license that can be found in the LICENSE file. | 3 // license that can be found in the LICENSE file. |
4 | 4 |
5 package math | 5 package math |
6 | 6 |
7 // Logb(x) returns the binary exponent of x. | 7 // Logb(x) returns the binary exponent of x. |
8 // | 8 // |
9 // Special cases are: | 9 // Special cases are: |
10 // Logb(±Inf) = +Inf | 10 // Logb(±Inf) = +Inf |
11 // Logb(0) = -Inf | 11 // Logb(0) = -Inf |
12 // Logb(NaN) = NaN | 12 // Logb(NaN) = NaN |
13 func Logb(x float64) float64 { | 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 | 14 // special cases |
17 switch { | 15 switch { |
18 case x == 0: | 16 case x == 0: |
19 return Inf(-1) | 17 return Inf(-1) |
20 » case x < -MaxFloat64 || x > MaxFloat64: // IsInf(x, 0): | 18 » case IsInf(x, 0): |
21 return Inf(1) | 19 return Inf(1) |
22 » case x != x: // IsNaN(x): | 20 » case IsNaN(x): |
23 return x | 21 return x |
24 } | 22 } |
25 return float64(ilogb(x)) | 23 return float64(ilogb(x)) |
26 } | 24 } |
27 | 25 |
28 // Ilogb(x) returns the binary exponent of x as an integer. | 26 // Ilogb(x) returns the binary exponent of x as an integer. |
29 // | 27 // |
30 // Special cases are: | 28 // Special cases are: |
31 // Ilogb(±Inf) = MaxInt32 | 29 // Ilogb(±Inf) = MaxInt32 |
32 // Ilogb(0) = MinInt32 | 30 // Ilogb(0) = MinInt32 |
33 // Ilogb(NaN) = MaxInt32 | 31 // Ilogb(NaN) = MaxInt32 |
34 func Ilogb(x float64) int { | 32 func Ilogb(x float64) int { |
35 // TODO(rsc): Remove manual inlining of IsNaN, IsInf | |
36 // when compiler does it for us | |
37 // special cases | 33 // special cases |
38 switch { | 34 switch { |
39 case x == 0: | 35 case x == 0: |
40 return MinInt32 | 36 return MinInt32 |
41 » case x != x: // IsNaN(x): | 37 » case IsNaN(x): |
42 return MaxInt32 | 38 return MaxInt32 |
43 » case x < -MaxFloat64 || x > MaxFloat64: // IsInf(x, 0): | 39 » case IsInf(x, 0): |
44 return MaxInt32 | 40 return MaxInt32 |
45 } | 41 } |
46 return ilogb(x) | 42 return ilogb(x) |
47 } | 43 } |
48 | 44 |
49 // logb returns the binary exponent of x. It assumes x is finite and | 45 // logb returns the binary exponent of x. It assumes x is finite and |
50 // non-zero. | 46 // non-zero. |
51 func ilogb(x float64) int { | 47 func ilogb(x float64) int { |
52 x, exp := normalize(x) | 48 x, exp := normalize(x) |
53 return int((Float64bits(x)>>shift)&mask) - bias + exp | 49 return int((Float64bits(x)>>shift)&mask) - bias + exp |
54 } | 50 } |
LEFT | RIGHT |