当前位置: 首页>>代码示例>>Golang>>正文


Golang rand.Rand类代码示例

本文整理汇总了Golang中math/rand.Rand的典型用法代码示例。如果您正苦于以下问题:Golang Rand类的具体用法?Golang Rand怎么用?Golang Rand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Rand类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: 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

示例2: GenerateDense

func GenerateDense(r *rand.Rand, size int) Undirected {
	for {
		u := Undirected{
			Nodes: make([]NodeID, size),
			Edges: make(map[Edge]struct{}),
		}

		for i := 0; i < size; i++ {
			u.Nodes[i] = NodeID(strconv.Itoa(i))
		}

		// Form a fully-connected graph
		for i := 0; i < size; i++ {
			for j := 0; j < i; j++ {
				u.Add(Edge{u.Nodes[i], u.Nodes[j]})
			}
		}

		// Remove some edges
		for i := r.Intn(size); i > 0; i-- {
			u.Remove(u.RandomEdge(r))
		}

		if u.Graph().Connected() {
			return u
		}
	}
}
开发者ID:squaremo,项目名称:monotreme,代码行数:28,代码来源:testutils.go

示例3: 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

示例4: NewField

func NewField(r *rand.Rand, name, value string, typ *index.FieldType) *index.Field {
	if Usually(r) || !typ.Indexed() {
		// most of the time, don't modify the params
		return index.NewStringField(name, value, typ)
	}

	newType := index.NewFieldTypeFrom(typ)
	if !newType.Stored() && r.Intn(2) == 0 {
		newType.SetStored(true) // randonly store it
	}

	if !newType.StoreTermVectors() && r.Intn(2) == 0 {
		newType.SetStoreTermVectors(true)
		if !newType.StoreTermVectorOffsets() {
			newType.SetStoreTermVectorOffsets(r.Intn(2) == 0)
		}
		if !newType.StoreTermVectorPositions() {
			newType.SetStoreTermVectorPositions(r.Intn(2) == 0)

			if newType.StoreTermVectorPositions() && !newType.StoreTermVectorPayloads() && !PREFLEX_IMPERSONATION_IS_ACTIVE {
				newType.SetStoreTermVectorPayloads(r.Intn(2) == 2)
			}
		}
	}

	return index.NewStringField(name, value, newType)
}
开发者ID:voidException,项目名称:golucene,代码行数:27,代码来源:testcase.go

示例5: MakePriority

// MakePriority generates a random priority value, biased by the
// specified userPriority. If userPriority=100, the resulting
// priority is 100x more likely to be probabilistically greater
// than a similar invocation with userPriority=1.
func MakePriority(r *rand.Rand, userPriority int32) int32 {
	// A currently undocumented feature allows an explicit priority to
	// be set by specifying priority < 1. The explicit priority is
	// simply -userPriority in this case. This is hacky, but currently
	// used for unittesting. Perhaps this should be documented and allowed.
	if userPriority < 0 {
		return -userPriority
	}
	if userPriority == 0 {
		userPriority = 1
	}
	// The idea here is to bias selection of a random priority from the
	// range [1, 2^31-1) such that if userPriority=100, it's 100x more
	// likely to be a higher int32 than if userPriority=1. The formula
	// below chooses random values according to the following table:
	//   userPriority  |  range
	//   1             |  all positive int32s
	//   10            |  top 9/10ths of positive int32s
	//   100           |  top 99/100ths of positive int32s
	//   1000          |  top 999/1000ths of positive int32s
	//   ...etc
	if r != nil {
		return math.MaxInt32 - r.Int31n(math.MaxInt32/userPriority)
	}
	return math.MaxInt32 - rand.Int31n(math.MaxInt32/userPriority)
}
开发者ID:Gardenya,项目名称:cockroach,代码行数:30,代码来源:data.go

示例6: randFloat64

// randFloat64 generates a random float taking the full range of a float64.
func randFloat64(rand *rand.Rand) float64 {
	f := rand.Float64() * math.MaxFloat64
	if rand.Int()&1 == 1 {
		f = -f
	}
	return f
}
开发者ID:achanda,项目名称:go,代码行数:8,代码来源:quick.go

示例7: Qsort

func Qsort(a Interface, prng *rand.Rand) Interface {
	if a.Len() < 2 {
		return a
	}

	left, right := 0, a.Len()-1

	pivotIndex := prng.Int() % a.Len()
	a.Swap(pivotIndex, right)

	for i := 0; i < a.Len(); i++ {
		if a.Less(i, right) {

			a.Swap(i, left)
			left++
		}
	}

	a.Swap(left, right)

	leftSide, rightSide := a.Partition(left)
	Qsort(leftSide, prng)
	Qsort(rightSide, prng)

	return a
}
开发者ID:qwertmax,项目名称:interview_tasks,代码行数:26,代码来源:qsort.go

示例8: Shuffle

// iterate through the deck, and swap values with
// a random card from another location in the deck
func (sd *StandardDeck) Shuffle(r *rand.Rand) {
	s := sd.Size()
	for k := range sd.cards {
		i := r.Intn(s)
		sd.cards[k], sd.cards[i] = sd.cards[i], sd.cards[k]
	}
}
开发者ID:stensonb,项目名称:blackjack,代码行数:9,代码来源:standarddeck.go

示例9: Emitter

func (self *Scene) Emitter(r *rand.Rand) *memit.Emitter {
	if len(self.emitters) == 0 {
		return nil
	}
	i := r.Int() % len(self.emitters)
	return &self.emitters[i]
}
开发者ID:kellpossible,项目名称:minilight,代码行数:7,代码来源:scene.go

示例10: NewMockDirectoryWrapper

func NewMockDirectoryWrapper(random *rand.Rand, delegate store.Directory) *MockDirectoryWrapper {
	ans := &MockDirectoryWrapper{
		noDeleteOpenFile:                 true,
		preventDoubleWrite:               true,
		trackDiskUsage:                   false,
		wrapLockFactory:                  true,
		openFilesForWrite:                make(map[string]bool),
		openLocks:                        make(map[string]bool),
		openLocksLock:                    &sync.Mutex{},
		throttling:                       THROTTLING_SOMETIMES,
		inputCloneCount:                  0,
		openFileHandles:                  make(map[io.Closer]error),
		failOnCreateOutput:               true,
		failOnOpenInput:                  true,
		assertNoUnreferencedFilesOnClose: true,
	}
	ans.BaseDirectoryWrapperImpl = NewBaseDirectoryWrapper(delegate)
	ans.Locker = &sync.Mutex{}
	// must make a private random since our methods are called from different
	// methods; else test failures may not be reproducible from the original
	// seed
	ans.randomState = rand.New(rand.NewSource(random.Int63()))
	ans.throttledOutput = NewThrottledIndexOutput(
		MBitsToBytes(40+ans.randomState.Intn(10)), 5+ans.randomState.Int63n(5), nil)
	// force wrapping of LockFactory
	ans.myLockFactory = newMockLockFactoryWrapper(ans, delegate.LockFactory())
	ans.init()
	return ans
}
开发者ID:voidException,项目名称:golucene,代码行数:29,代码来源:mockDirectoryWrapper.go

示例11: shuffleStrings

// Shuffle a slice of strings.
func shuffleStrings(strings []string, rng *rand.Rand) []string {
	var shuffled = make([]string, len(strings))
	for i, j := range rng.Perm(len(strings)) {
		shuffled[j] = strings[i]
	}
	return shuffled
}
开发者ID:MaxHalford,项目名称:gago,代码行数:8,代码来源:util.go

示例12: randomData

func randomData(r *rand.Rand, bytes int) []byte {
	data := make([]byte, bytes)
	for i, _ := range data {
		data[i] = byte(r.Uint32() % 256)
	}
	return data
}
开发者ID:runeaune,项目名称:bitcoin-wallet,代码行数:7,代码来源:der_test.go

示例13: MonteCarloPixel

func MonteCarloPixel(results chan Result, scene *geometry.Scene, diffuseMap /*, causticsMap*/ *kd.KDNode, start, rows int, rand *rand.Rand) {
	samples := Config.NumRays
	var px, py, dy, dx geometry.Float
	var direction, contribution geometry.Vec3

	for y := start; y < start+rows; y++ {
		py = scene.Height - scene.Height*2*geometry.Float(y)/geometry.Float(scene.Rows)
		for x := 0; x < scene.Cols; x++ {
			px = -scene.Width + scene.Width*2*geometry.Float(x)/geometry.Float(scene.Cols)
			var colourSamples geometry.Vec3
			if x >= Config.Skip.Left && x < scene.Cols-Config.Skip.Right &&
				y >= Config.Skip.Top && y < scene.Rows-Config.Skip.Bottom {
				for sample := 0; sample < samples; sample++ {
					dy, dx = geometry.Float(rand.Float32())*scene.PixH, geometry.Float(rand.Float32())*scene.PixW
					direction = geometry.Vec3{
						px + dx - scene.Camera.Origin.X,
						py + dy - scene.Camera.Origin.Y,
						-scene.Camera.Origin.Z,
					}.Normalize()

					contribution = Radiance(geometry.Ray{scene.Camera.Origin, direction}, scene, diffuseMap /*causticsMap,*/, 0, 1.0, rand)
					colourSamples.AddInPlace(contribution)
				}
			}
			results <- Result{x, y, colourSamples.Mult(1.0 / geometry.Float(samples))}
		}
	}
}
开发者ID:Nightgunner5,项目名称:goray,代码行数:28,代码来源:gorender.go

示例14: New

func New(r *rand.Rand) *Simplex {
	var s Simplex
	perm := r.Perm(256)
	copy(s[:256], perm)
	copy(s[256:], perm)
	return &s
}
开发者ID:BenLubar,项目名称:untitled-game,代码行数:7,代码来源:simplex.go

示例15: GenerateDomain

func GenerateDomain(r *rand.Rand, size int) []byte {
	dnLen := size % 70 // artificially limit size so there's less to intrepret if a failure occurs
	var dn []byte
	done := false
	for i := 0; i < dnLen && !done; {
		max := dnLen - i
		if max > 63 {
			max = 63
		}
		lLen := max
		if lLen != 0 {
			lLen = int(r.Int31()) % max
		}
		done = lLen == 0
		if done {
			continue
		}
		l := make([]byte, lLen+1)
		l[0] = byte(lLen)
		for j := 0; j < lLen; j++ {
			l[j+1] = byte(rand.Int31())
		}
		dn = append(dn, l...)
		i += 1 + lLen
	}
	return append(dn, 0)
}
开发者ID:abh,项目名称:dns,代码行数:27,代码来源:parse_test.go


注:本文中的math/rand.Rand类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。