]> Cypherpunks.ru repositories - gostls13.git/blob - src/math/bits.go
cmd/compile/internal/inline: score call sites exposed by inlines
[gostls13.git] / src / math / bits.go
1 // Copyright 2009 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 const (
8         uvnan    = 0x7FF8000000000001
9         uvinf    = 0x7FF0000000000000
10         uvneginf = 0xFFF0000000000000
11         uvone    = 0x3FF0000000000000
12         mask     = 0x7FF
13         shift    = 64 - 11 - 1
14         bias     = 1023
15         signMask = 1 << 63
16         fracMask = 1<<shift - 1
17 )
18
19 // Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.
20 func Inf(sign int) float64 {
21         var v uint64
22         if sign >= 0 {
23                 v = uvinf
24         } else {
25                 v = uvneginf
26         }
27         return Float64frombits(v)
28 }
29
30 // NaN returns an IEEE 754 “not-a-number” value.
31 func NaN() float64 { return Float64frombits(uvnan) }
32
33 // IsNaN reports whether f is an IEEE 754 “not-a-number” value.
34 func IsNaN(f float64) (is bool) {
35         // IEEE 754 says that only NaNs satisfy f != f.
36         // To avoid the floating-point hardware, could use:
37         //      x := Float64bits(f);
38         //      return uint32(x>>shift)&mask == mask && x != uvinf && x != uvneginf
39         return f != f
40 }
41
42 // IsInf reports whether f is an infinity, according to sign.
43 // If sign > 0, IsInf reports whether f is positive infinity.
44 // If sign < 0, IsInf reports whether f is negative infinity.
45 // If sign == 0, IsInf reports whether f is either infinity.
46 func IsInf(f float64, sign int) bool {
47         // Test for infinity by comparing against maximum float.
48         // To avoid the floating-point hardware, could use:
49         //      x := Float64bits(f);
50         //      return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf;
51         return sign >= 0 && f > MaxFloat64 || sign <= 0 && f < -MaxFloat64
52 }
53
54 // normalize returns a normal number y and exponent exp
55 // satisfying x == y × 2**exp. It assumes x is finite and non-zero.
56 func normalize(x float64) (y float64, exp int) {
57         const SmallestNormal = 2.2250738585072014e-308 // 2**-1022
58         if Abs(x) < SmallestNormal {
59                 return x * (1 << 52), -52
60         }
61         return x, 0
62 }