當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。