當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Rand.Float64方法代碼示例

本文整理匯總了Golang中math/rand.Rand.Float64方法的典型用法代碼示例。如果您正苦於以下問題:Golang Rand.Float64方法的具體用法?Golang Rand.Float64怎麽用?Golang Rand.Float64使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在math/rand.Rand的用法示例。


在下文中一共展示了Rand.Float64方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: randomSchurCanonical

// randomSchurCanonical returns a random, general matrix in Schur canonical
// form, that is, block upper triangular with 1×1 and 2×2 diagonal blocks where
// each 2×2 diagonal block has its diagonal elements equal and its off-diagonal
// elements of opposite sign.
func randomSchurCanonical(n, stride int, rnd *rand.Rand) blas64.General {
	t := randomGeneral(n, n, stride, rnd)
	// Zero out the lower triangle.
	for i := 0; i < t.Rows; i++ {
		for j := 0; j < i; j++ {
			t.Data[i*t.Stride+j] = 0
		}
	}
	// Randomly create 2×2 diagonal blocks.
	for i := 0; i < t.Rows; {
		if i == t.Rows-1 || rnd.Float64() < 0.5 {
			// 1×1 block.
			i++
			continue
		}
		// 2×2 block.
		// Diagonal elements equal.
		t.Data[(i+1)*t.Stride+i+1] = t.Data[i*t.Stride+i]
		// Off-diagonal elements of opposite sign.
		c := rnd.NormFloat64()
		if math.Signbit(c) == math.Signbit(t.Data[i*t.Stride+i+1]) {
			c *= -1
		}
		t.Data[(i+1)*t.Stride+i] = c
		i += 2
	}
	return t
}
開發者ID:rawlingsj,項目名稱:gofabric8,代碼行數:32,代碼來源:general.go

示例2: testRandomSimplex

func testRandomSimplex(t *testing.T, nTest int, pZero float64, maxN int, rnd *rand.Rand) {
	// Try a bunch of random LPs
	for i := 0; i < nTest; i++ {
		n := rnd.Intn(maxN) + 2 // n must be at least two.
		m := rnd.Intn(n-1) + 1  // m must be between 1 and n
		if m == 0 || n == 0 {
			continue
		}
		randValue := func() float64 {
			//var pZero float64
			v := rnd.Float64()
			if v < pZero {
				return 0
			}
			return rnd.NormFloat64()
		}
		a := mat64.NewDense(m, n, nil)
		for i := 0; i < m; i++ {
			for j := 0; j < n; j++ {
				a.Set(i, j, randValue())
			}
		}
		b := make([]float64, m)
		for i := range b {
			b[i] = randValue()
		}

		c := make([]float64, n)
		for i := range c {
			c[i] = randValue()
		}

		testSimplex(t, nil, c, a, b, convergenceTol)
	}
}
開發者ID:sbinet,項目名稱:gonum-optimize,代碼行數:35,代碼來源:simplex_test.go

示例3: newTieredMergePolicy

// L883
func newTieredMergePolicy(r *rand.Rand) *index.TieredMergePolicy {
	tmp := index.NewTieredMergePolicy()
	if Rarely(r) {
		log.Println("Use crazy value for max merge at once")
		tmp.SetMaxMergeAtOnce(NextInt(r, 2, 9))
		tmp.SetMaxMergeAtOnceExplicit(NextInt(r, 2, 9))
	} else {
		tmp.SetMaxMergeAtOnce(NextInt(r, 10, 50))
		tmp.SetMaxMergeAtOnceExplicit(NextInt(r, 10, 50))
	}
	if Rarely(r) {
		log.Println("Use crazy value for max merge segment MB")
		tmp.SetMaxMergedSegmentMB(0.2 + r.Float64()*100)
	} else {
		tmp.SetMaxMergedSegmentMB(r.Float64() * 100)
	}
	tmp.SetFloorSegmentMB(0.2 + r.Float64()*2)
	tmp.SetForceMergeDeletesPctAllowed(0 + r.Float64()*30)
	if Rarely(r) {
		log.Println("Use crazy value for max merge per tire")
		tmp.SetSegmentsPerTier(float64(NextInt(r, 2, 20)))
	} else {
		tmp.SetSegmentsPerTier(float64(NextInt(r, 10, 50)))
	}
	configureRandom(r, tmp)
	tmp.SetReclaimDeletesWeight(r.Float64() * 4)
	return tmp
}
開發者ID:voidException,項目名稱:golucene,代碼行數:29,代碼來源:testcase.go

示例4: Parenthood

// Parenthood crossover combines two individuals (the parents) into one (the
// offspring). Each parent's contribution to the DNA is determined by the toss
// of a coin. The offspring can inherit from it's mother's genes (coin <= 0.33),
// from it's father's genes (0.33 < coin <= 0.66) or from a random mix of both
// (0.66 < coin <= 1). A coin is thrown for each gene. With this method only the
// two first selected individuals are considered, hence the CrossSize parameter
// should be set to 2.
func Parenthood(indis Individuals, generator *rand.Rand) Individual {
	var mother = indis[0]
	var father = indis[1]
	// Create an individual with an empty DNA
	var offspring = Individual{make([]float64, len(mother.Dna)), 0.0}
	// For every gene in the parent's DNA
	for i := range offspring.Dna {
		// Flip a coin and decide what to do
		var coin = rand.Float64()
		switch {
		// The offspring receives the mother's gene
		case coin <= 0.33:
			offspring.Dna[i] = mother.Dna[i]
		// The offspring receives the father's gene
		case coin <= 0.66:
			offspring.Dna[i] = father.Dna[i]
		// The offspring receives a mixture of his parent's genes
		default:
			// Random weight for each individual
			var pMother = generator.Float64()
			var pFather = 1 - pMother
			offspring.Dna[i] = pMother*mother.Dna[i] + pFather*father.Dna[i]
		}
	}
	return offspring
}
開發者ID:NyorJa,項目名稱:gago,代碼行數:33,代碼來源:crossover.go

示例5: Mutate

// Mutate is a convenience function for mutating each individual in a slice of individuals.
func (indis Individuals) Mutate(mutator Mutator, mutRate float64, rng *rand.Rand) {
	for i := range indis {
		if rng.Float64() < mutRate {
			indis[i].Mutate(mutator, rng)
		}
	}
}
開發者ID:MaxHalford,項目名稱:gago,代碼行數:8,代碼來源:individual.go

示例6: randomCircle

func randomCircle(r *rand.Rand) {
	colors := [12]string{
		"#ff66cc",
		"#ff6680",
		"#ff9966",
		"#ffe666",
		"#ccff66",
		"#80ff66",
		"#66ff99",
		"#66ffe6",
		"#66ccff",
		"#6680ff",
		"#9966ff",
		"#e566ff",
	}
	x := int(r.Float64()*width + 1)
	y := int(r.Float64()*height + 1)
	radius := int((r.Float64() * width / 5) + 1)
	strokeColor := colors[r.Intn(len(colors))]
	strokeWidth := 4
	color := colors[r.Intn(len(colors))]

	fmt.Printf("<circle cx='%d' cy='%d' r='%d' stroke='%s' "+
		"stroke-width='%d' fill='%s' />\n", x, y, radius,
		strokeColor, strokeWidth, color)
}
開發者ID:sshitaime,項目名稱:daily-go,代碼行數:26,代碼來源:circle.go

示例7: sample

// return the sample index to the other public functions
func sample(x index, n int, replace bool, weights vector, rnd *rand.Rand) ([]uint, error) {
	if weights != nil && len(x) != len(weights) {
		return nil, fmt.Errorf("length of x (%d) unequal to length of weights (%d)", len(x), len(weights))
	}

	if !replace && n > len(x) {
		return nil, fmt.Errorf("cannot sample with replacement when n (%d) is greater than x (%d)", n, len(x))
	}

	// cumulative probabilities
	var cumprob vector
	if weights != nil {
		cumprob = weights.CumProb()
	} else {
		cumprob = make(vector, len(x))
		nx := float64(len(x))
		for i, _ := range x {
			cumprob[i] = float64(i) / nx
		}
	}

	results := make([]uint, n)
	for i := 0; i < n; i++ {
		index := uint(Find(cumprob, rnd.Float64()))
		results[i] = x[index]

		// if sampling w/o replacement, remove the index and re-scale weights
		if !replace {
			x = x.Remove(index)
			cumprob = cumprob.Remove(index).Scale()
		}
	}

	return results, nil
}
開發者ID:postfix,項目名稱:sample,代碼行數:36,代碼來源:sample.go

示例8: random_gradient

func random_gradient(r *rand.Rand) Vec2 {
	v := r.Float64() * PI * 2
	return Vec2{
		float32(math.Cos(v)),
		float32(math.Sin(v)),
	}
}
開發者ID:9il,項目名稱:pnoise,代碼行數:7,代碼來源:test.go

示例9: RandMat

// RandMat returns a new matrix random values.
func RandMat(r *rand.Rand) *Mat4 {
	m := Mat4{}
	for i := 0; i < len(m); i++ {
		m[i] = r.Float64()
	}
	return &m
}
開發者ID:amsibamsi,項目名稱:three,代碼行數:8,代碼來源:geom.go

示例10: randomFloatAsString

func randomFloatAsString(val string, r *rand.Rand) string {
	// val should be in the format: [lo-]hi[ format]
	var lo, hi float64
	var err error
	format := "%.0f"
	// If there's a space in the string, we also have a format.
	sp := strings.Index(val, " ")
	if sp != -1 {
		format = strings.TrimSpace(val[sp:])
		val = val[:sp]
	}
	// If there's a dash in var, we have a range lo-hi, rather than just 0-hi.
	if dash := strings.Index(val, "-"); dash != -1 {
		if lo, err = strconv.ParseFloat(val[:dash], 32); err != nil {
			lo = 0
		}
		if hi, err = strconv.ParseFloat(val[dash+1:], 32); err != nil {
			hi = 0
		}
	} else {
		lo = 0
		if hi, err = strconv.ParseFloat(val, 32); err != nil {
			hi = 0
		}
	}
	rnd := r.Float64()*(hi-lo) + lo
	return fmt.Sprintf(format, rnd)
}
開發者ID:pzsz,項目名稱:sp0rkle,代碼行數:28,代碼來源:decisiondriver.go

示例11: pickRandom

// Picks a random index from a, with a probability proportional to its value.
// Using a local random-generator to prevent waiting on rand's default source.
func pickRandom(a []float64, rnd *rand.Rand) int {
	if len(a) == 0 {
		panic("Cannot pick element from an empty distribution.")
	}

	sum := float64(0)
	for i := range a {
		if a[i] < 0 {
			panic(fmt.Sprintf("Got negative value in distribution: %v", a[i]))
		}
		sum += a[i]
	}
	if sum == 0 {
		return rnd.Intn(len(a))
	}

	r := rnd.Float64() * sum
	i := 0
	for i < len(a) && r > a[i] {
		r -= a[i]
		i++
	}
	if i == len(a) {
		i--
	}
	return i
}
開發者ID:fluhus,項目名稱:gostuff,代碼行數:29,代碼來源:lda.go

示例12: Sample

func (m *Multinomial) Sample(n int, rng *rand.Rand) map[string]int {
	ret := make(map[string]int)

	// We have to copy keys out from map m.Hist to a slice and sort
	// them. Otherwise, we would have to access m.Hist directly using
	// range, which introduces randomness and leads to random output
	// even given a fix-seeded rng.
	keys := make([]string, 0, len(m.Hist))
	for k, _ := range m.Hist {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for i := 0; i < n; i++ {
		p := rng.Float64() * m.Sum
		sum := 0.0
		for _, k := range keys {
			sum += m.Hist[k]
			if p < sum {
				ret[k]++
				break
			}
		}
	}
	return ret
}
開發者ID:postfix,項目名稱:hmm-1,代碼行數:26,代碼來源:multinomial.go

示例13: uniform

func uniform(r *rand.Rand) float64 {
	if r == nil {
		return rand.Float64()
	} else {
		return r.Float64()
	}
}
開發者ID:postfix,項目名稱:rbm-1,代碼行數:7,代碼來源:rbm.go

示例14: recordToSink

func recordToSink(sink EventSink, event *api.Event, eventCorrelator *EventCorrelator, randGen *rand.Rand, sleepDuration time.Duration) {
	// Make a copy before modification, because there could be multiple listeners.
	// Events are safe to copy like this.
	eventCopy := *event
	event = &eventCopy
	result, err := eventCorrelator.EventCorrelate(event)
	if err != nil {
		utilruntime.HandleError(err)
	}
	if result.Skip {
		return
	}
	tries := 0
	for {
		if recordEvent(sink, result.Event, result.Patch, result.Event.Count > 1, eventCorrelator) {
			break
		}
		tries++
		if tries >= maxTriesPerEvent {
			glog.Errorf("Unable to write event '%#v' (retry limit exceeded!)", event)
			break
		}
		// Randomize the first sleep so that various clients won't all be
		// synced up if the master goes down.
		if tries == 1 {
			time.Sleep(time.Duration(float64(sleepDuration) * randGen.Float64()))
		} else {
			time.Sleep(sleepDuration)
		}
	}
}
開發者ID:RyanBinfeng,項目名稱:kubernetes,代碼行數:31,代碼來源:event.go

示例15: addConn

// Adds a new connection to the genome
//
// In the add connection mutation, a single new connection gene is added connecting two previously
// unconnected nodes. (Stanley, 35)
func (m *Complexify) addConn(rng *rand.Rand, g *neat.Genome) {

	// Identify two unconnected nodes
	conns := make(map[int]neat.Connection)
	c := 0
	for _, src := range g.Nodes {
		for _, tgt := range g.Nodes {
			if src.Y >= tgt.Y {
				continue // do not allow recurrent
			}
			found := false
			for _, c2 := range g.Conns {
				if c2.Source == src.Innovation && c2.Target == tgt.Innovation {
					found = true
					break
				}
			}
			if !found {
				conns[c] = neat.Connection{Source: src.Innovation, Target: tgt.Innovation}
				c += 1
			}
		}
	}

	// Go's range over maps is random, so take the first, if any, availble connection
	for _, conn := range conns {
		conn.Enabled = true
		conn.Weight = (rng.Float64()*2.0 - 1.0) * m.WeightRange()
		conn.Innovation = m.ctx.Innovation(neat.ConnInnovation, conn.Key())
		g.Conns[conn.Innovation] = conn
		break
	}
}
開發者ID:NioTeX,項目名稱:neat,代碼行數:37,代碼來源:complexify.go


注:本文中的math/rand.Rand.Float64方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。