コード例 #1
0
ファイル: path_test.go プロジェクト: thomaspeugeot/go.geo
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)
			}
		}
	}
}
コード例 #2
0
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)

	}
}
コード例 #3
0
ファイル: vector3d.go プロジェクト: kasworld/go4game
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],
	}
}
コード例 #4
0
ファイル: drawSpiral.go プロジェクト: meysampg/fractals-in-go
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)
}
コード例 #5
0
ファイル: symmetric_test.go プロジェクト: adamdrake/matrix
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)
}
コード例 #6
0
/*
	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
}
コード例 #7
0
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))
}
コード例 #8
0
ファイル: cntl1_test.go プロジェクト: philipz/ntm
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)
}
コード例 #9
0
ファイル: population.go プロジェクト: igorcoding/go-genpath
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)
}
コード例 #10
0
ファイル: liquidhandling_test.go プロジェクト: cgravill/antha
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)
	}
}
コード例 #11
0
ファイル: cntl1_test.go プロジェクト: philipz/ntm
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)
}
コード例 #12
0
ファイル: arp2.go プロジェクト: kierdavis/gosound-demos
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
}
コード例 #13
0
ファイル: arp2.go プロジェクト: kierdavis/gosound-demos
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)
		}
	}
}
コード例 #14
0
ファイル: main.go プロジェクト: joyrexus/gopl-exercises
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
}
コード例 #15
0
ファイル: randDemo.go プロジェクト: qiangmzsx/golang
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()
}
コード例 #16
0
ファイル: metrics.go プロジェクト: wangy1931/grafana
func GetTestMetrics(c *middleware.Context) {
	from := c.QueryInt64("from")
	to := c.QueryInt64("to")
	maxDataPoints := c.QueryInt64("maxDataPoints")
	stepInSeconds := (to - from) / maxDataPoints

	result := dtos.MetricQueryResultDto{}
	result.Data = make([]dtos.MetricQueryResultDataDto, 1)

	for seriesIndex := range result.Data {
		points := make([][2]float64, maxDataPoints)
		walker := rand.Float64() * 100
		time := from

		for i := range points {
			points[i][0] = walker
			points[i][1] = float64(time)
			walker += rand.Float64() - 0.5
			time += stepInSeconds
		}

		result.Data[seriesIndex].Target = "test-series-" + strconv.Itoa(seriesIndex)
		result.Data[seriesIndex].DataPoints = points
	}

	c.JSON(200, &result)
}
コード例 #17
0
ファイル: smallpt.go プロジェクト: ShadowIce/smallpt.go
func renderPixel(x int, y int, cx Vec, cy Vec) {
	var r1, r2 float64
	var dx, dy float64
	var radiance Vec
	var direction Vec

	for sy, i := 0, (h-y-1)*w+x; sy < 2; sy++ {
		for sx := 0; sx < 2; sx++ {
			radiance.x = 0
			radiance.y = 0
			radiance.z = 0
			for s := 0; s < samps; s++ {
				r1, r2 = 2*rand.Float64(), 2*rand.Float64()
				if r1 < 1 {
					dx = math.Sqrt(r1) - 1
				} else {
					dx = 1 - math.Sqrt(2-r1)
				}
				if r2 < 1 {
					dy = math.Sqrt(r2) - 1
				} else {
					dy = 1 - math.Sqrt(2-r2)
				}
				direction = Add(Add(SMul(cx, ((float64(sx)*.5+dx)/2+float64(x))/float64(w)-.5),
					SMul(cy, ((float64(sy)+.5+dy)/2+float64(y))/float64(h)-.5)), cam.Direction)
				radiance = Add(radiance, SMul(Radiance(&Ray{Add(cam.Origin, SMul(direction, 140.0)), Norm(direction)}, 0), 1.0/float64(samps)))
			}
			colors[i] = Add(colors[i], SMul(radiance, 0.25))
		}
	}
}
コード例 #18
0
ファイル: picserv.go プロジェクト: stanim/svgof
func flower(w http.ResponseWriter, req *http.Request) {

	log.Printf("flower: %s", req.RemoteAddr)
	query := req.URL.Query()

	n := qint(query, "n", 200.0, 10.0, 200.0)          // number of "flowers"
	np := qint(query, "petals", 15.0, 10.0, 60.0)      // number of "petals" per flower
	opacity := qint(query, "op", 50.0, 20.0, 100.0)    // opacity
	psize := qint(query, "size", 30.0, 5.0, 50.0)      // length of the petals
	thickness := qint(query, "thick", 10.0, 3.0, 20.0) // petal thickness

	limit := 2.0 * math.Pi

	w.Header().Set("Content-type", "image/svg+xml")
	canvas := svg.New(w)
	canvas.Start(width, height)
	canvas.Title("Flowers")
	canvas.Rect(0, 0, width, height, "fill:white")

	for i := 0; i < int(n); i++ {
		x := float64(rand.Float64() * width)
		y := float64(rand.Float64() * height)
		r := float64(random(10.0, psize))

		canvas.Gstyle(fmt.Sprintf(flowerfmt, float64(rand.Float64()*255), float64(rand.Float64()*255), float64(rand.Float64()*255), float64(random(10, opacity))/100.0, random(2, thickness)))
		for theta := 0.0; theta < limit; theta += limit / float64(random(10, np)) {
			xr := r * math.Cos(theta)
			yr := r * math.Sin(theta)
			canvas.Line(x, y, x+float64(xr), y+float64(yr))
		}
		canvas.Gend()
	}
	canvas.End()
}
コード例 #19
0
func main() {
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	fmt.Println(rand.Float64())
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1)

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

	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))
}
コード例 #20
0
ファイル: valuelocmap.go プロジェクト: wreese/valuestore
func New(opts ...func(*config)) *DefaultValueLocMap {
	cfg := resolveConfig(opts...)
	vlm := &DefaultValueLocMap{workers: uint32(cfg.workers)}
	est := uint32(cfg.pageSize / int(unsafe.Sizeof(entry{})))
	if est < 4 {
		est = 4
	}
	vlm.bits = 1
	c := uint32(2)
	for c < est {
		vlm.bits++
		c <<= 1
	}
	vlm.lowMask = c - 1
	vlm.rootShift = 63
	c = 2
	for c < uint32(cfg.roots) {
		vlm.rootShift--
		c <<= 1
	}
	vlm.entriesLockMask = c - 1
	vlm.splitLevel = uint32(float64(uint32(1<<vlm.bits)) * cfg.splitMultiplier)
	vlm.roots = make([]node, c)
	for i := 0; i < len(vlm.roots); i++ {
		vlm.roots[i].highMask = uint64(1) << (vlm.rootShift - 1)
		vlm.roots[i].rangeStart = uint64(i) << vlm.rootShift
		vlm.roots[i].rangeStop = uint64(1)<<vlm.rootShift - 1 + vlm.roots[i].rangeStart
		vlm.roots[i].splitLevel = uint32(float64(vlm.splitLevel) + (rand.Float64()-.5)/5*float64(vlm.splitLevel))
		vlm.roots[i].mergeLevel = uint32(rand.Float64() / 10 * float64(vlm.splitLevel))
	}
	return vlm
}
コード例 #21
0
ファイル: network.go プロジェクト: hanscj1/mantle
func (rn *raftNetwork) send(m raftpb.Message) {
	rn.mu.Lock()
	to := rn.recvQueues[m.To]
	if rn.disconnected[m.To] {
		to = nil
	}
	drop := rn.dropmap[conn{m.From, m.To}]
	delay := rn.delaymap[conn{m.From, m.To}]
	rn.mu.Unlock()

	if to == nil {
		return
	}
	if drop != 0 && rand.Float64() < drop {
		return
	}
	// TODO: shall we delay without blocking the send call?
	if delay.d != 0 && rand.Float64() < delay.rate {
		rd := rand.Int63n(int64(delay.d))
		time.Sleep(time.Duration(rd))
	}

	select {
	case to <- m:
	default:
		// drop messages when the receiver queue is full.
	}
}
コード例 #22
0
ファイル: level2bench.go プロジェクト: gidden/cloudlus
func DgemvBenchmark(b *testing.B, blasser Dgemver, tA blas.Transpose, m, n, incX, incY int) {
	var lenX, lenY int
	if tA == blas.NoTrans {
		lenX = n
		lenY = m
	} else {
		lenX = m
		lenY = n
	}
	xr := make([]float64, lenX)
	for i := range xr {
		xr[i] = rand.Float64()
	}
	x := makeIncremented(xr, incX, 0)
	yr := make([]float64, lenY)
	for i := range yr {
		yr[i] = rand.Float64()
	}
	y := makeIncremented(yr, incY, 0)
	a := make([]float64, m*n)
	for i := range a {
		a[i] = rand.Float64()
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		blasser.Dgemv(tA, m, n, 2, a, n, x, incX, 3, y, incY)
	}
}
コード例 #23
0
ファイル: raft_sm.go プロジェクト: sidutta/cs733
func (sm *StateMachine) VoteReq(msg VoteReq) {
	// //fmt.Println(sm.ServerID, "reached votereq")
	if sm.CurrentTerm < msg.Term {
		sm.State = "follower"
		sm.CurrentTerm = msg.Term
		sm.VotedFor = 0
		sm.updateCh <- SaveVotedFor{sm.VotedFor}
		sm.actionCh <- Alarm{Delay: (float64(1.0) + rand.Float64()) * sm.ELECTION_TIMEOUT}
	}

	switch sm.State {
	case "follower", "candidate", "leader":
		if sm.CurrentTerm == msg.Term &&
			(sm.VotedFor == 0 ||
				sm.VotedFor == msg.CandidateId) &&
			(msg.LastLogTerm > sm.getLogTerm(len(sm.Log)-1) ||
				(msg.LastLogTerm == sm.getLogTerm(len(sm.Log)-1) &&
					msg.LastLogIndex >= len(sm.Log)-1)) {
			sm.CurrentTerm = msg.Term
			sm.VotedFor = msg.CandidateId
			sm.updateCh <- SaveVotedFor{sm.VotedFor}
			sm.actionCh <- Send{msg.CandidateId, VoteResp{sm.ServerID, sm.CurrentTerm, true}}
			sm.actionCh <- Alarm{(float64(1.0) + rand.Float64()) * sm.ELECTION_TIMEOUT}
			//fmt.Println(sm.ServerID, "+ voted for", sm.VotedFor, "when candidate", msg.CandidateId)
		} else {
			sm.actionCh <- Send{msg.CandidateId, VoteResp{sm.ServerID, sm.CurrentTerm, false}}
			//fmt.Println(sm.ServerID, "- voted for", sm.VotedFor, "when candidate", msg.CandidateId)
			//fmt.Println(msg.LastLogTerm, sm.getLogTerm(len(sm.Log)-1),
			//msg.LastLogTerm, sm.getLogTerm(len(sm.Log)-1),
			//msg.LastLogIndex, len(sm.Log)-1)
		}

	}

}
コード例 #24
0
ファイル: gradients.go プロジェクト: jdjkelly/playground
func main() {
	width, height := 1024, 128
	canvas := NewCanvas(image.Rect(0, 0, width, height))
	canvas.DrawGradient()

	rand.Seed(time.Now().UTC().UnixNano())
	for i := 0; i < 100; 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}
		canvas.DrawSpiral(color, Vector{x, y})
	}

	outFilename := "canvas.png"
	outFile, err := os.Create(outFilename)
	if err != nil {
		log.Fatal(err)
	}
	defer outFile.Close()
	log.Print("Saving image to: ", outFilename)
	png.Encode(outFile, canvas)
}
コード例 #25
0
func TestUnstackLayerRProp(t *testing.T) {
	width := 3
	height := 4
	depth := 18

	inputVal := make(linalg.Vector, width*height*depth)
	inputR := make(linalg.Vector, len(inputVal))
	for i := range inputVal {
		inputVal[i] = rand.Float64()*2 - 1
		inputR[i] = rand.Float64()*2 - 1
	}
	variable := &autofunc.Variable{inputVal}
	rVec := autofunc.RVector{
		variable: inputR,
	}

	layer := &UnstackLayer{
		InputWidth:    width,
		InputHeight:   height,
		InputDepth:    depth,
		InverseStride: 3,
	}

	funcTest := &functest.RFuncChecker{
		F:     layer,
		Vars:  []*autofunc.Variable{variable},
		Input: variable,
		RV:    rVec,
	}
	funcTest.FullCheck(t)
}
コード例 #26
0
ファイル: read_test.go プロジェクト: nolenroyalty/bangarang
func TestReadComplex128(t *testing.T) {
	var buf bytes.Buffer
	wr := NewWriter(&buf)
	rd := NewReader(&buf)

	for i := 0; i < 10; i++ {
		buf.Reset()
		f := complex(rand.Float64()*math.MaxFloat64, rand.Float64()*math.MaxFloat64)

		wr.WriteComplex128(f)
		err := wr.Flush()
		if err != nil {
			t.Fatal(err)
		}

		out, err := rd.ReadComplex128()
		if err != nil {
			t.Error(err)
			continue
		}
		if out != f {
			t.Errorf("Wrote %f; read %f", f, out)
		}

	}
}
コード例 #27
0
ファイル: vector3d.go プロジェクト: kasworld/go4game
func RandVector3D(st, end float64) Vector3D {
	return Vector3D{
		rand.Float64()*(end-st) + st,
		rand.Float64()*(end-st) + st,
		rand.Float64()*(end-st) + st,
	}
}
コード例 #28
0
ファイル: random-numbers.go プロジェクト: novakr/goexample
func main() {
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	fmt.Println(rand.Float64())

	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	s1 := rand.NewSource(42)
	r1 := rand.New(s1)

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

	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()

}
コード例 #29
0
ファイル: vector3d.go プロジェクト: kasworld/go4game
func (h *HyperRect) RandVector() Vector3D {
	return Vector3D{
		rand.Float64()*(h.Max[0]-h.Min[0]) + h.Min[0],
		rand.Float64()*(h.Max[1]-h.Min[1]) + h.Min[1],
		rand.Float64()*(h.Max[2]-h.Min[2]) + h.Min[2],
	}
}
コード例 #30
0
ファイル: errorpoints_test.go プロジェクト: vron/plotinum
func ExampleErrorPoints() {
	// Get some random data.
	n, m := 5, 10
	pts := make([]plotter.XYer, n)
	for i := range pts {
		xys := make(plotter.XYs, m)
		pts[i] = xys
		center := float64(i)
		for j := range xys {
			xys[j].X = center + (rand.Float64() - 0.5)
			xys[j].Y = center + (rand.Float64() - 0.5)
		}
	}

	plt, err := plot.New()
	if err != nil {
		panic(err)
	}

	mean95 := NewErrorPoints(MeanAndConf95, pts...)
	medMinMax := NewErrorPoints(MedianAndMinMax, pts...)
	AddLinePoints(plt,
		"mean and 95% confidence", mean95,
		"median and minimum and maximum", medMinMax)
	AddErrorBars(plt, mean95, medMinMax)
	AddScatters(plt, pts[0], pts[1], pts[2], pts[3], pts[4])

	plt.Save(4, 4, "centroids.png")
}