Home | History | Annotate | Download | only in math
      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 	mask     = 0x7FF
     12 	shift    = 64 - 11 - 1
     13 	bias     = 1023
     14 )
     15 
     16 // Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.
     17 func Inf(sign int) float64 {
     18 	var v uint64
     19 	if sign >= 0 {
     20 		v = uvinf
     21 	} else {
     22 		v = uvneginf
     23 	}
     24 	return Float64frombits(v)
     25 }
     26 
     27 // NaN returns an IEEE 754 ``not-a-number'' value.
     28 func NaN() float64 { return Float64frombits(uvnan) }
     29 
     30 // IsNaN reports whether f is an IEEE 754 ``not-a-number'' value.
     31 func IsNaN(f float64) (is bool) {
     32 	// IEEE 754 says that only NaNs satisfy f != f.
     33 	// To avoid the floating-point hardware, could use:
     34 	//	x := Float64bits(f);
     35 	//	return uint32(x>>shift)&mask == mask && x != uvinf && x != uvneginf
     36 	return f != f
     37 }
     38 
     39 // IsInf reports whether f is an infinity, according to sign.
     40 // If sign > 0, IsInf reports whether f is positive infinity.
     41 // If sign < 0, IsInf reports whether f is negative infinity.
     42 // If sign == 0, IsInf reports whether f is either infinity.
     43 func IsInf(f float64, sign int) bool {
     44 	// Test for infinity by comparing against maximum float.
     45 	// To avoid the floating-point hardware, could use:
     46 	//	x := Float64bits(f);
     47 	//	return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf;
     48 	return sign >= 0 && f > MaxFloat64 || sign <= 0 && f < -MaxFloat64
     49 }
     50 
     51 // normalize returns a normal number y and exponent exp
     52 // satisfying x == y  2**exp. It assumes x is finite and non-zero.
     53 func normalize(x float64) (y float64, exp int) {
     54 	const SmallestNormal = 2.2250738585072014e-308 // 2**-1022
     55 	if Abs(x) < SmallestNormal {
     56 		return x * (1 << 52), -52
     57 	}
     58 	return x, 0
     59 }
     60