Source file src/math/nextafter.go

     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  
     7  // Nextafter32 returns the next representable float32 value after x towards y.
     8  //
     9  // Special cases are:
    10  //
    11  //	Nextafter32(x, y)   = x when x == y
    12  //	Nextafter32(0, y)   = ±SmallestNonzeroFloat32 towards y, for y ≠ 0
    13  //	Nextafter32(NaN, y) = NaN
    14  //	Nextafter32(x, NaN) = NaN
    15  func Nextafter32(x, y float32) (r float32) {
    16  	switch {
    17  	case IsNaN(float64(x)) || IsNaN(float64(y)): // special case
    18  		r = float32(NaN())
    19  	case x == y:
    20  		r = x
    21  	case x == 0:
    22  		r = float32(Copysign(float64(Float32frombits(1)), float64(y)))
    23  	case (y > x) == (x > 0):
    24  		r = Float32frombits(Float32bits(x) + 1)
    25  	default:
    26  		r = Float32frombits(Float32bits(x) - 1)
    27  	}
    28  	return
    29  }
    30  
    31  // Nextafter returns the next representable float64 value after x towards y.
    32  //
    33  // Special cases are:
    34  //
    35  //	Nextafter(x, y)   = x when x == y
    36  //	Nextafter(0, y)   = ±SmallestNonzeroFloat64 towards y, for y ≠ 0
    37  //	Nextafter(NaN, y) = NaN
    38  //	Nextafter(x, NaN) = NaN
    39  func Nextafter(x, y float64) (r float64) {
    40  	switch {
    41  	case IsNaN(x) || IsNaN(y): // special case
    42  		r = NaN()
    43  	case x == y:
    44  		r = x
    45  	case x == 0:
    46  		r = Copysign(Float64frombits(1), y)
    47  	case (y > x) == (x > 0):
    48  		r = Float64frombits(Float64bits(x) + 1)
    49  	default:
    50  		r = Float64frombits(Float64bits(x) - 1)
    51  	}
    52  	return
    53  }
    54  

View as plain text