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


Golang rand.Float64函数代码示例

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


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

示例1: TestNewPathFromEncoding

func TestNewPathFromEncoding(t *testing.T) {
	for loop := 0; loop < 100; loop++ {
		p := NewPath()
		for i := 0; i < 100; i++ {
			p.Push(&Point{rand.Float64(), rand.Float64()})
		}

		encoded := p.Encode(int(1.0 / epsilon))
		path := Decode(encoded, int(1.0/epsilon))

		if path.Length() != 100 {
			t.Fatalf("path, encodeDecode length mismatch: %d != 100", path.Length())
		}

		for i := 0; i < 100; i++ {
			a := p.GetAt(i)
			b := path.GetAt(i)

			if e := math.Abs(a[0] - b[0]); e > epsilon {
				t.Errorf("path, encodeDecode X error too big: %f", e)
			}

			if e := math.Abs(a[1] - b[1]); e > epsilon {
				t.Errorf("path, encodeDecode Y error too big: %f", e)
			}
		}
	}
}
开发者ID:thomaspeugeot,项目名称:go.geo,代码行数:28,代码来源:path_test.go

示例2: SpawnAsteroid

func (u *Universe) SpawnAsteroid(redis_client *redis.Client) {
	if rand.Float32() < 0.1 {
		live_asteroids := redis_client.Cmd("KEYS", "asteroid-*")
		num_asteroids := 1000
		if len(live_asteroids.Elems) < num_asteroids {

			temp_asteroid := &asteroid.Asteroid{gameobject.GameObject{
				Id:   rand.Intn(500000),
				X:    rand.Float64(),
				Y:    rand.Float64(),
				Velx: rand.Float64() * 100,
				Vely: rand.Float64() * 100},
				100}

			u.Asteroids = append(u.Asteroids, temp_asteroid)
			asteroid_json, _ := json.Marshal(temp_asteroid)

			redis_client.Cmd("SET", fmt.Sprintf("asteroid-%v", temp_asteroid.Id), asteroid_json)
		}

		// temp_bullet := &bullet.Bullet{gameobject.GameObject{
		//                     Id: rand.Intn(500000),
		//                     X: rand.Float64(),
		//                     Y: rand.Float64(),
		//                     Velx: rand.Float64() * 100,
		//                     Vely: rand.Float64() * 100},
		//                     100}

		// u.Bullets = append(u.Bullets,temp_bullet)

		// redis_client.Cmd("SET", fmt.Sprintf("bullet-%v", temp_bullet.Id), temp_bullet)

	}
}
开发者ID:cleblanc87,项目名称:asteroids-go-server,代码行数:34,代码来源:universe.go

示例3: RandVector

func RandVector(st, end Vector3D) Vector3D {
	return Vector3D{
		rand.Float64()*(end[0]-st[0]) + st[0],
		rand.Float64()*(end[1]-st[1]) + st[1],
		rand.Float64()*(end[2]-st[2]) + st[2],
	}
}
开发者ID:kasworld,项目名称:go4game,代码行数:7,代码来源:vector3d.go

示例4: createImage

func createImage(iterations uint32, degree float64, factor float64) {
	// Declare image size
	width, height := 2048, 1024

	// Create a new image
	img := image.Rect(0, 0, width, height)
	c := NewCanvas(img)
	c.DrawGradient()

	rand.Seed(time.Now().UTC().UnixNano())
	for i := 0; i < 300; i++ {
		x := float64(width) * rand.Float64()
		y := float64(height) * rand.Float64()
		color := color.RGBA{uint8(rand.Intn(255)),
			uint8(rand.Intn(255)),
			uint8(rand.Intn(255)),
			255}
		c.DrawSpiral(color, Coordinate{x, y}, iterations, degree, factor)
	}

	name := fmt.Sprintf("spiral_%d_%f_%f.png", iterations, degree, factor)
	file, err := os.Create(name)
	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()
	png.Encode(file, c)
}
开发者ID:meysampg,项目名称:fractals-in-go,代码行数:29,代码来源:drawSpiral.go

示例5: TestSymAdd

func TestSymAdd(t *testing.T) {
	for _, test := range []struct {
		n int
	}{
		{n: 1},
		{n: 2},
		{n: 3},
		{n: 4},
		{n: 5},
		{n: 10},
	} {
		n := test.n
		a := NewSymDense(n, nil)
		for i := range a.mat.Data {
			a.mat.Data[i] = rand.Float64()
		}
		b := NewSymDense(n, nil)
		for i := range a.mat.Data {
			b.mat.Data[i] = rand.Float64()
		}
		var m Dense
		m.Add(a, b)

		// Check with new receiver
		var s SymDense
		s.AddSym(a, b)
		for i := 0; i < n; i++ {
			for j := i; j < n; j++ {
				want := m.At(i, j)
				if got := s.At(i, j); got != want {
					t.Errorf("unexpected value for At(%d, %d): got: %v want: %v", i, j, got, want)
				}
			}
		}

		// Check with equal receiver
		s.CopySym(a)
		s.AddSym(&s, b)
		for i := 0; i < n; i++ {
			for j := i; j < n; j++ {
				want := m.At(i, j)
				if got := s.At(i, j); got != want {
					t.Errorf("unexpected value for At(%d, %d): got: %v want: %v", i, j, got, want)
				}
			}
		}
	}

	method := func(receiver, a, b Matrix) {
		type addSymer interface {
			AddSym(a, b Symmetric)
		}
		rd := receiver.(addSymer)
		rd.AddSym(a.(Symmetric), b.(Symmetric))
	}
	denseComparison := func(receiver, a, b *Dense) {
		receiver.Add(a, b)
	}
	testTwoInput(t, "AddSym", &SymDense{}, method, denseComparison, legalTypesSym, legalSizeSameSquare, 1e-14)
}
开发者ID:adamdrake,项目名称:matrix,代码行数:60,代码来源:symmetric_test.go

示例6: unfair

/*
	How to arrive at a fair coin
*/
func unfair(p float64) bool {
	// Input validation
	if p > 1 || p < 0 {
		return false // error code
	}

	// Generate a float between 0 and 1.
	// Use this to test whether you are working with a success of failure
	rng1 := rand.Float64()
	rng2 := rand.Float64()

	result1 := rng1 < float64(p) // Heads = true; Tails = false
	result2 := rng2 < float64(p)

	for result1 == result2 { // If result1 and result2 have the same outcome, re-run
		rng1 = rand.Float64()
		rng2 = rand.Float64()

		result1 = rng1 < float64(p)
		result2 = rng2 < float64(p)
	}

	if result1 == true && result2 == false {
		return true
	} else if result1 == false && result2 == true {
		return false
	}

	return false
}
开发者ID:LorenzoFernando,项目名称:AlgosInGo,代码行数:33,代码来源:unfairCoin.go

示例7: main

func main() {
	//For example, rand.Intn returns a random int n, 0 <= n < 100.
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	//rand.Float64 returns a float64 f, 0.0 <= f < 1.0.
	fmt.Println(rand.Float64())

	//This can be used to generate random floats in other ranges, for example 5.0 <= f' < 10.0.
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	//The default number generator is deterministic, so it’ll produce the same sequence of numbers each time by default. To produce varying sequences, give it a seed that changes. Note that this is not safe to use for random numbers you intend to be secret, use crypto/rand for those.
	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1)

	//Call the resulting rand.Rand just like the functions on the rand package.
	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	//If you seed a source with the same number, it produces the same sequence of random numbers.
	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
	s3 := rand.NewSource(42)
	r3 := rand.New(s3)
	fmt.Print(r3.Intn(100), ",")
	fmt.Print(r3.Intn(100))
}
开发者ID:kiddlu,项目名称:oh-my-examples,代码行数:34,代码来源:random-numbers.go

示例8: TestLogisticModel

func TestLogisticModel(t *testing.T) {
	times := 9
	x := makeTensor2(times, 4)
	for i := 0; i < len(x); i++ {
		for j := 0; j < len(x[i]); j++ {
			x[i][j] = rand.Float64()
		}
	}
	y := makeTensor2(times, 4)
	for i := 0; i < len(y); i++ {
		for j := 0; j < len(y[i]); j++ {
			y[i][j] = rand.Float64()
		}
	}
	n := 3
	m := 2
	h1Size := 3
	numHeads := 2
	c := NewEmptyController1(len(x[0]), len(y[0]), h1Size, numHeads, n, m)
	weights := c.WeightsVal()
	for i := range weights {
		weights[i] = 2 * rand.Float64()
	}

	model := &LogisticModel{Y: y}
	ForwardBackward(c, x, model)
	checkGradients(t, c, Controller1Forward, x, model)
}
开发者ID:philipz,项目名称:ntm,代码行数:28,代码来源:cntl1_test.go

示例9: evaluate

func (self *Population) evaluate() {
	for k := 0; k < self.conf.CrossoversCount; k++ {
		if rand.Float64() < self.conf.CrossoverProb {
			g1 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]
			g2 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]

			child := g1.Crossover(g2)

			if rand.Float64() < self.conf.MutationProb {
				child.Mutate()
			}
			child.EvalFitness()

			self.P = append(self.P, child)
		}
	}

	self.sort()
	if self.conf.RemoveDuplicates {
		self.removeDuplicates()
	}
	for i := range self.P {
		self.P[i].EvalFitness()
	}
	if len(self.P) > self.conf.PopulationSize {
		self.P = self.P[:self.conf.PopulationSize]
	}
	//	pretty.Println(self.P)
}
开发者ID:igorcoding,项目名称:go-genpath,代码行数:29,代码来源:population.go

示例10: TestStockConcs

func TestStockConcs(*testing.T) {
	names := []string{"tea", "milk", "sugar"}

	minrequired := make(map[string]float64, len(names))
	maxrequired := make(map[string]float64, len(names))
	Smax := make(map[string]float64, len(names))
	T := make(map[string]float64, len(names))
	vmin := 10.0

	for _, name := range names {
		r := rand.Float64() + 1.0
		r2 := rand.Float64() + 1.0
		r3 := rand.Float64() + 1.0

		minrequired[name] = r * r2 * 20.0
		maxrequired[name] = r * r2 * 30.0
		Smax[name] = r * r2 * r3 * 70.0
		T[name] = 100.0
	}

	cncs := choose_stock_concentrations(minrequired, maxrequired, Smax, vmin, T)
	cncs = cncs
	for k, v := range cncs {
		fmt.Println(k, " ", minrequired[k], " ", maxrequired[k], " ", T[k], " ", v)
	}
}
开发者ID:cgravill,项目名称:antha,代码行数:26,代码来源:liquidhandling_test.go

示例11: TestMultinomialModel

func TestMultinomialModel(t *testing.T) {
	times := 9
	x := makeTensor2(times, 4)
	for i := 0; i < len(x); i++ {
		for j := 0; j < len(x[i]); j++ {
			x[i][j] = rand.Float64()
		}
	}
	outputSize := 4
	y := make([]int, times)
	for i := range y {
		y[i] = rand.Intn(outputSize)
	}
	n := 3
	m := 2
	h1Size := 3
	numHeads := 2
	c := NewEmptyController1(len(x[0]), outputSize, h1Size, numHeads, n, m)
	weights := c.WeightsVal()
	for i := range weights {
		weights[i] = 2 * rand.Float64()
	}

	model := &MultinomialModel{Y: y}
	ForwardBackward(c, x, model)
	checkGradients(t, c, Controller1Forward, x, model)
}
开发者ID:philipz,项目名称:ntm,代码行数:27,代码来源:cntl1_test.go

示例12: SequenceBass

func SequenceBass(ctx sound.Context) (seq *sound.Sequencer) {
	melody := GenerateBassMelody()
	seq = sound.NewSequencer(ctx)

	var pos time.Duration

	for i := 0; i < NumBars; i++ {
		if rand.Float64() < 0.05 {
			freqInput := ctx.Const((<-melody).Frequency())
			note := PlayBassNote(ctx, freqInput, NoteDuration*3)
			seq.Add(pos, note)

		} else if rand.Float64() < 0.05 {
			freqInput1, freqInput2 := ctx.Fork2(ctx.Const((<-melody).Frequency()))
			note1 := PlayBassNote(ctx, freqInput1, NoteDuration)
			note2 := PlayBassNote(ctx, freqInput2, NoteDuration)
			seq.Add(pos, note1)
			seq.Add(pos+NoteDuration*2, note2)

		} else {
			freqInput := ctx.Const((<-melody).Frequency())
			note := PlayBassNote(ctx, freqInput, NoteDuration)
			seq.Add(pos, note)
		}

		pos += NoteDuration * 3
	}

	return seq
}
开发者ID:kierdavis,项目名称:gosound-demos,代码行数:30,代码来源:arp2.go

示例13: NextNote

func NextNote(scale *music.Scale, root music.Note) {
	x := rand.Float64()
	switch {
	case x < 0.20:
		scale.Next(1)
	case x < 0.35:
		scale.Next(2)
	case x < 0.45:
		scale.Next(3)
	case x < 0.50:
		scale.Next(4)
	case x < 0.70:
		scale.Prev(1)
	case x < 0.85:
		scale.Prev(2)
	case x < 0.95:
		scale.Prev(3)
	default:
		scale.Prev(4)
	}

	d := scale.Root.Sub(root)
	if d <= -18 {
		scale.Root = scale.Root.Add(24)
	} else if d >= 18 {
		scale.Root = scale.Root.Add(-24)
	} else if rand.Float64() < 0.02 {
		if d < 0 {
			scale.Root = scale.Root.Add(12)
		} else {
			scale.Root = scale.Root.Add(-12)
		}
	}
}
开发者ID:kierdavis,项目名称:gosound-demos,代码行数:34,代码来源:arp2.go

示例14: lissajous

func lissajous(out io.Writer) {
	const (
		cycles  = 1     // number of complete x oscillator revolutions
		res     = 0.001 // angular resolution
		size    = 100   // image canvas covers [-size..+size]
		nframes = 64    // number of animation frames
		delay   = 8     // delay between frames in 10ms units
	)
	freq := rand.Float64() * 3.0 // relative frequency of y oscillator
	anim := gif.GIF{LoopCount: nframes}
	phase := 0.0 // phase difference
	for i := 0; i < nframes; i++ {
		rect := image.Rect(0, 0, 2*size+1, 2*size+1)
		img := image.NewPaletted(rect, palette)
		for t := 0.0; t < cycles*2*math.Pi; t += res {
			x := math.Sin(t)
			y := math.Sin(t*freq + phase)
			xPos := size + int(x*size+0.5)
			yPos := size + int(y*size+0.5)
			i := uint8(1 + rand.Float64()*3.0) // randomize color index
			img.SetColorIndex(xPos, yPos, i)
			img.SetColorIndex(
				xPos+1,
				yPos+1,
				i,
			)
		}
		phase += 0.1
		anim.Delay = append(anim.Delay, delay)
		anim.Image = append(anim.Image, img)
	}
	gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
开发者ID:joyrexus,项目名称:gopl-exercises,代码行数:33,代码来源:main.go

示例15: main

func main() {
	// 例如`rand.Intn`返回一个整型随机数n,0<=n<100
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	// `rand.Float64` 返回一个`float64` `f`,
	// `0.0 <= f < 1.0`
	fmt.Println(rand.Float64())

	// 这个方法可以用来生成其他数值范围内的随机数,
	// 例如`5.0 <= f < 10.0`
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	// 为了使随机数生成器具有确定性,可以给它一个seed
	s1 := rand.NewSource(42)
	r1 := rand.New(s1)

	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	// 如果源使用一个和上面相同的seed,将生成一样的随机数
	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
}
开发者ID:qiangmzsx,项目名称:golang,代码行数:31,代码来源:randDemo.go


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