github.com/leanovate/gopter@v0.2.9/gen/floats.go (about)

     1  package gen
     2  
     3  import (
     4  	"math"
     5  	"reflect"
     6  
     7  	"github.com/leanovate/gopter"
     8  )
     9  
    10  // Float64Range generates float64 numbers within a given range
    11  func Float64Range(min, max float64) gopter.Gen {
    12  	d := max - min
    13  	if d < 0 || d > math.MaxFloat64 {
    14  		return Fail(reflect.TypeOf(float64(0)))
    15  	}
    16  
    17  	return func(genParams *gopter.GenParameters) *gopter.GenResult {
    18  		genResult := gopter.NewGenResult(min+genParams.Rng.Float64()*d, Float64Shrinker)
    19  		genResult.Sieve = func(v interface{}) bool {
    20  			return v.(float64) >= min && v.(float64) <= max
    21  		}
    22  		return genResult
    23  	}
    24  }
    25  
    26  // Float64 generates arbitrary float64 numbers that do not contain NaN or Inf
    27  func Float64() gopter.Gen {
    28  	return gopter.CombineGens(
    29  		Int64Range(0, 1),
    30  		Int64Range(0, 0x7fe),
    31  		Int64Range(0, 0xfffffffffffff),
    32  	).Map(func(values []interface{}) float64 {
    33  		sign := uint64(values[0].(int64))
    34  		exponent := uint64(values[1].(int64))
    35  		mantissa := uint64(values[2].(int64))
    36  
    37  		return math.Float64frombits((sign << 63) | (exponent << 52) | mantissa)
    38  	}).WithShrinker(Float64Shrinker)
    39  }
    40  
    41  // Float32Range generates float32 numbers within a given range
    42  func Float32Range(min, max float32) gopter.Gen {
    43  	d := max - min
    44  	if d < 0 || d > math.MaxFloat32 {
    45  		return Fail(reflect.TypeOf(float32(0)))
    46  	}
    47  	return func(genParams *gopter.GenParameters) *gopter.GenResult {
    48  		genResult := gopter.NewGenResult(min+genParams.Rng.Float32()*d, Float32Shrinker)
    49  		genResult.Sieve = func(v interface{}) bool {
    50  			return v.(float32) >= min && v.(float32) <= max
    51  		}
    52  		return genResult
    53  	}
    54  }
    55  
    56  // Float32 generates arbitrary float32 numbers that do not contain NaN or Inf
    57  func Float32() gopter.Gen {
    58  	return gopter.CombineGens(
    59  		Int32Range(0, 1),
    60  		Int32Range(0, 0xfe),
    61  		Int32Range(0, 0x7fffff),
    62  	).Map(func(values []interface{}) float32 {
    63  		sign := uint32(values[0].(int32))
    64  		exponent := uint32(values[1].(int32))
    65  		mantissa := uint32(values[2].(int32))
    66  
    67  		return math.Float32frombits((sign << 31) | (exponent << 23) | mantissa)
    68  	}).WithShrinker(Float32Shrinker)
    69  }