github.com/yaricom/goNEAT@v0.0.0-20210507221059-e2110b885482/neat/utils/math.go (about)

     1  package utils
     2  
     3  import (
     4  	"math/rand"
     5  )
     6  
     7  // Returns subsequent random positive or negative integer value (1 or -1) to randomize value sign
     8  func RandSign() int32 {
     9  	v := rand.Int()
    10  	if (v % 2) == 0 {
    11  		return -1
    12  	} else {
    13  		return 1
    14  	}
    15  }
    16  
    17  // Performs a single thrown onto a roulette wheel where the wheel's space is unevenly divided.
    18  // The probability that a segment will be selected is given by that segment's value in the probabilities array.
    19  // Returns segment index or -1 if something goes awfully wrong
    20  func SingleRouletteThrow(probabilities []float64) int  {
    21  	total := 0.0
    22  
    23  	// collect all probabilities
    24  	for _, v := range probabilities {
    25  		total += v
    26  	}
    27  
    28  	// throw the ball and collect result
    29  	throwValue := rand.Float64() * total
    30  
    31  	accumulator := 0.0
    32  	for i, v := range probabilities {
    33  		accumulator += v
    34  		if throwValue <= accumulator {
    35  			return i
    36  		}
    37  	}
    38  	return -1
    39  }