Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 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 | |
Charles L. Dorian | f273487 | 2012-04-06 14:01:12 -0400 | [diff] [blame] | 7 | // Logb returns the binary exponent of x. |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 8 | // |
| 9 | // Special cases are: |
| 10 | // Logb(±Inf) = +Inf |
| 11 | // Logb(0) = -Inf |
| 12 | // Logb(NaN) = NaN |
| 13 | func Logb(x float64) float64 { |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 14 | // special cases |
| 15 | switch { |
| 16 | case x == 0: |
| 17 | return Inf(-1) |
Luuk van Dijk | 8dd3de4 | 2012-02-01 16:08:31 +0100 | [diff] [blame] | 18 | case IsInf(x, 0): |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 19 | return Inf(1) |
Luuk van Dijk | 8dd3de4 | 2012-02-01 16:08:31 +0100 | [diff] [blame] | 20 | case IsNaN(x): |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 21 | return x |
| 22 | } |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 23 | return float64(ilogb(x)) |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 24 | } |
| 25 | |
Charles L. Dorian | f273487 | 2012-04-06 14:01:12 -0400 | [diff] [blame] | 26 | // Ilogb returns the binary exponent of x as an integer. |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 27 | // |
| 28 | // Special cases are: |
| 29 | // Ilogb(±Inf) = MaxInt32 |
| 30 | // Ilogb(0) = MinInt32 |
| 31 | // Ilogb(NaN) = MaxInt32 |
| 32 | func Ilogb(x float64) int { |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 33 | // special cases |
| 34 | switch { |
| 35 | case x == 0: |
| 36 | return MinInt32 |
Luuk van Dijk | 8dd3de4 | 2012-02-01 16:08:31 +0100 | [diff] [blame] | 37 | case IsNaN(x): |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 38 | return MaxInt32 |
Luuk van Dijk | 8dd3de4 | 2012-02-01 16:08:31 +0100 | [diff] [blame] | 39 | case IsInf(x, 0): |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 40 | return MaxInt32 |
| 41 | } |
Eoghan Sherry | 13c2e62 | 2011-01-19 14:23:59 -0500 | [diff] [blame] | 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 |
Charles L. Dorian | 6b80a5f | 2010-03-03 18:17:13 -0800 | [diff] [blame] | 50 | } |