github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/testing/random_test.gno (about)

     1  package testing
     2  
     3  import (
     4  	"math"
     5  	"strconv"
     6  	"time"
     7  )
     8  
     9  func updateSeed() {
    10  	seed := time.Now().UnixNano()
    11  	_srand(seed)
    12  }
    13  
    14  func Test_UniformRand(t *T) {
    15  	valueMap := make(map[uint64]int)
    16  	maxIter := 1000
    17  
    18  	for i := 0; i < maxIter; i++ {
    19  		result := UniformRand()
    20  
    21  		if result < 0 || result >= 32768 {
    22  			t.Errorf("rand() = %v, want in range [0, 32767]", result)
    23  		}
    24  
    25  		if _, ok := valueMap[result]; ok {
    26  			valueMap[result]++
    27  		} else {
    28  			valueMap[result] = 1
    29  		}
    30  	}
    31  
    32  	lvm := len(valueMap)
    33  	if lvm > maxIter || lvm == 0 {
    34  		t.Errorf("len(valueMap) = %v, want <= %v", lvm, maxIter)
    35  	}
    36  }
    37  
    38  func Test_nrand(t *T) {
    39  	sum := 0.0
    40  	for i := 0; i < 1000; i++ {
    41  		result := nrand()
    42  		sum += result
    43  	}
    44  	avg := sum / float64(1000)
    45  
    46  	// The value returned by nrand() should be close to 0
    47  	// on average for large sample sizes.
    48  	// The expectation of the standard deviation should be
    49  	// close to 1 for large sample sizes.
    50  	if math.Abs(avg) > 0.1 { // can be adjusted based on sample size
    51  		t.Errorf("nrand() = %v, want in range [-0.1, 0.1]", avg)
    52  	}
    53  }
    54  
    55  func Test_GenerateRandomBool(t *T) {
    56  	updateSeed()
    57  
    58  	for _, bias := range []float64{0, 0.5, 1} {
    59  		trueCount, falseCount := 0, 0
    60  		sampleSize := 1000
    61  
    62  		for i := 0; i < sampleSize; i++ {
    63  			result := GenerateRandomBool(bias)
    64  			if result {
    65  				trueCount++
    66  			} else {
    67  				falseCount++
    68  			}
    69  		}
    70  
    71  		if trueCount == 0 || falseCount == 0 {
    72  			t.Errorf("Bias = %v, trueCount = %v, falseCount = %v, want both > 0", bias, trueCount, falseCount)
    73  		}
    74  
    75  		if bias < 0 || bias > 1 {
    76  			t.Errorf("Bias = %v, want in range [0, 1]", bias)
    77  		}
    78  	}
    79  }
    80  
    81  func TestRandRange(t *T) {
    82  	nums := make(map[uint64]int)
    83  	for i := 0; i < 1000; i++ {
    84  		res := randRange(0, 10)
    85  		if res < 0 || res > 10 {
    86  			t.Errorf("gerandRangenerateRange() = %v, want in range [0, 9]", res)
    87  		}
    88  
    89  		if _, ok := nums[res]; ok {
    90  			nums[res]++
    91  		} else {
    92  			nums[res] = 1
    93  		}
    94  	}
    95  
    96  	if len(nums) != 11 {
    97  		t.Errorf("len(nums) = %v, want in range [0, 10]", len(nums))
    98  	}
    99  }