Esempio n. 1
0
func NewSpoils(x, y float64) *Spoils {
	s := new(Spoils)
	if rand.Float64() > 0.2 {
		s.X, s.Y = -100, -100
		s.Dead = true
		return s
	}

	s.X = x
	s.Y = y
	s.Type = rand.Intn(2)

	s.Velocity = Vector64{(rand.Float64()*10 - 5) * 20, (rand.Float64()*10 - 5) * 20}

	switch s.Type {
	case SP_HEART:
		s.W = float64(IM.Misc[0].W)
		s.H = float64(IM.Misc[0].H)
	case SP_UPGRADE:
		s.W = 10
		s.H = 10
	}

	return s
}
Esempio n. 2
0
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))
		}
	}
}
Esempio n. 3
0
func (m *RandomMutator) Mutate(s *Subject) {
	for i := range s.Genome {
		v := rand.Float64()
		if v < m.prob {
			s.Genome[i] = rand.Float64()
		}
	}
	return
}
Esempio n. 4
0
func GenerateRectangles(n int) []Rect {
	res := make([]Rect, n)
	for y := 0; y < n; y++ {
		res[y].h = rand.Float64()
		res[y].w = rand.Float64()
		res[y].x = rand.Float64()
		res[y].y = rand.Float64()
	}
	return res
}
Esempio n. 5
0
func main() {
	var t float64 = 0
	for i := 0; i < 100000000; i++ {
		t += rand.Float64()
	}
	fmt.Printf("total:%f\n", t)
}
Esempio n. 6
0
// use win-rate distribution of node to play a legal move in tracker
func (node *Node) seed(t Tracker, path []int) bool {
	if node.parent == nil {
		return false
	}
	dist := new(vector.Vector)
	sum := 0.0
	for sibling := node.parent.Child; sibling != nil; sibling = sibling.Sibling {
		for i := 0; i < len(path); i++ {
			if sibling.Vertex == path[i] {
				continue
			}
		}
		dist.Push(sibling.blendedMean)
		sum += sibling.blendedMean
	}
	node.totalseeds++
	r := rand.Float64() * sum
	for i := 0; i < dist.Len(); i++ {
		r -= dist.At(i).(float64)
		if r <= 0 {
			if t.Legal(node.Color, i) {
				t.Play(node.Color, i)
				node.seeds++
				return true
			}
			return false
		}
	}
	return false
}
Esempio n. 7
0
func (init *RandomInitializer) NewGenome(len int) (g Genome) {
	g = make(Genome, len)
	for i := range g {
		g[i] = rand.Float64()
	}
	return
}
Esempio n. 8
0
File: syx.go Progetto: mkb218/mkfseq
func dither(d float64) int {
	dec := d - math.Floor(d)
	if rand.Float64() < dec {
		return int(math.Ceil(d))
	}
	return int(math.Floor(d))
}
Esempio n. 9
0
func (t *HexTracker) suggestion(color byte, last int) int {
	if last == -1 || !t.config.PlayoutSuggest {
		return -1
	}
	var weights [6]float64
	weightSum := 0.0
	for i := range t.neighbors[1][last] {
		n := t.neighbors[1][last][i]
		if n != -1 && t.board[n] == EMPTY {
			if t.config.PlayoutSuggestUniform {
				weights[i] = 1
			} else {
				hash := hex_min_hash[hex_hash(color, t.board, t.neighbors[1][n])]
				hash |= 1 << 30
				weights[i] = t.config.policy_weights.Get(hash)
			}
			weightSum += weights[i]
		}
	}
	if weightSum > 0 {
		r := rand.Float64() * weightSum
		for i := range weights {
			if weights[i] > 0 {
				r -= weights[i]
				if r <= 0 {
					return t.neighbors[1][last][i]
				}
			}
		}
	}
	return -1
}
Esempio n. 10
0
func (g *GAFloatGenome) Randomize() {
	l := len(g.Gene)
	for i := 0; i < l; i++ {
		g.Gene[i] = rand.Float64()*g.Max + g.Min
	}
	g.Reset()
}
Esempio n. 11
0
func (self *Coordinator) ProcessTurns(complete chan bool) {
	for i := 0; i < 3; /* <3 <3 <3 */ i++ { // TODO: THREE TIMES IS ARBITRARY AND FOR TESTING

		self.log.Printf("Making turn %d available", i)
		for pi, _ := range self.peers {
			self.nextTurnAvailableSignals[pi] <- i
		}

		responses := self.peerDataForTurn(i)
		_ = self.transformsForNextTurn(responses)

		if self.conf.RandomlyDelayProcessing {
			time.Sleep(int64(float64(1e9) * rand.Float64()))
		}

		// Wait for all RPC requests from peers to go through the other goroutine
		for _, _ = range self.peers {
			<-self.rpcRequestsReceivedConfirmation
		}

		self.availableGameState.Advance()
		//  i, agent
		for _, _ = range self.availableGameState.Agents {
			// agent.Apply(transforms[i])
		}
	}

	self.log.Printf("Sending complete")

	if complete != nil {
		complete <- true
	}
}
Esempio n. 12
0
func (c *Chatter) SendChats() {
	for {
		duration := -1 * math.Log(rand.Float64()) * c.average * 1e9
		time.Sleep(int64(duration))
		c.Messages <- c.mark.Generate()
	}
}
Esempio n. 13
0
func GenIndividual() Individual {
	var i Individual
	i.bets[0] = (rand.Float64() * money)
	if i.bets[0] < MINBET {
		i.bets[0] = 0
	}
	i.bets[1] = (rand.Float64() * (money - i.bets[0]))
	if i.bets[1] < MINBET {
		i.bets[1] = 0
	}
	i.bets[2] = rand.Float64() * (money - (i.bets[0] + i.bets[1]))
	if i.bets[2] < MINBET {
		i.bets[2] = 0
	}
	return i
}
Esempio n. 14
0
func PickWanderForAnt(state *State, ant *Ant) []*Square {
	valid := ant.square.Neighbors().Minus(ant.square.Blacklist())
	if len(valid) == 0 {
		return make(Route, 0)
	}

	var randomSquare *Square = nil
	maxScore := -1.0
	for _, neighbor := range valid {
		// better to wander to a square that's well-connected
		neighborValid := neighbor.Neighbors().Minus(neighbor.Blacklist())
		score := rand.Float64() * (float64)(len(neighborValid))

		// best to wander to a square we've never visited
		if !neighbor.visited {
			score += 3.0
		}

		if score > maxScore {
			maxScore = score
			randomSquare = neighbor
		}
	}

	route := make(Route, 1)
	route[0] = randomSquare
	return route
}
Esempio n. 15
0
func GenPatternRule(alpha string, min int, max int) *PatternRule {
	leftSide := RandomString(alpha, min, max)
	rightSide := RandomString(alpha, min, max)
	cost := rand.Float64() * 10

	return &PatternRule{leftSide, rightSide, cost}
}
Esempio n. 16
0
func (d DFSPSolver) TakeStepFsp(n int, tau float64, D float64, l float64) []int {
	if !d.CacheInitialized {
		a := d.GenerateAMatrix(1)
		tauParam := tau * D / (l * l)
		w := d.CalculateProbabilities(a, tauParam)
		d.CacheInitialized = true
		d.Cache = w
	}

	out := make([]int, 2*d.MaxJumps+1)
	for i := 0; i < n; i++ {
		rnd := rand.Float64()
		sum := 0.0
		ndx := 0
		for k := 0; k < len(d.Cache); k++ {
			sum += d.Cache[k]
			if sum > rnd {
				ndx = k
				break
			}
		}
		finalPos := d.GenerateStates(1, ndx)
		for j := 0; j < 2*d.MaxJumps+1; j++ {
			out[j] += finalPos[j]
		}
	}
	return out
}
Esempio n. 17
0
func makeArray(size int, width, min float64) []float64 {
	a := make([]float64, size)
	for i := 0; i < size; i++ {
		x := rand.Float64()*width + min // uniform samples in {-25, 75}
		a[i] = x
	}
	return a
}
Esempio n. 18
0
func (sel *StochasticSelector) Select(num int, population *Population) (p *Population) {
	p = NewPopulation(num)
	for i := 0; i < num; i++ {
		val := rand.Float64() * float64(population.FitnessSum)
		p.Subjects[i] = getSubjectByProbability(val, population)
	}
	return
}
Esempio n. 19
0
func (node *Node) recalc() {
	if node.Visits == 10 {
		node.value = 1 + 0.1*rand.Float64()
		return
	}
	node.Mean = node.Wins / node.Visits
	node.blendedMean = node.Mean
	rave := node.config.AMAF || node.config.Neighbors || node.config.Ancestor
	if rave {
		beta := math.Sqrt(node.config.RAVE / (3*node.Visits + node.config.RAVE))
		if beta > 0 {
			node.amafMean = node.amafWins / node.amafVisits
			node.ancestorMean = node.ancestorWins / node.ancestorVisits
			if math.IsNaN(node.Mean) {
				node.Mean = 0
			}
			if math.IsNaN(node.amafMean) {
				node.amafMean = 0
			}
			if math.IsNaN(node.ancestorMean) {
				node.ancestorMean = 0
			}
			estimatedMean := 0.0
			Samples := 0.0
			if node.config.AMAF {
				estimatedMean += node.amafMean
				Samples++
			}
			if node.config.Neighbors {
				neighborWins := 0.0
				neighborVisits := 0.0
				for sibling := node.parent.Child; sibling != nil; sibling = sibling.Sibling {
					if sibling.Vertex != node.Vertex {
						neighborWins += sibling.Wins
						neighborVisits += sibling.Visits
					}
				}
				estimatedMean += neighborWins / neighborVisits
			}
			if node.config.Ancestor {
				estimatedMean += node.ancestorMean
				Samples++
			}
			estimatedMean /= Samples
			if math.IsNaN(estimatedMean) {
				estimatedMean = 0
			}
			node.blendedMean = beta*estimatedMean + (1-beta)*node.Mean
		}
	}
	r := math.Log1p(node.parent.Visits) / node.Visits
	v := 1.0
	if node.config.Var {
		v = math.Fmin(0.25, node.blendedMean-(node.blendedMean*node.blendedMean)+math.Sqrt(2*r))
	}
	node.value = node.blendedMean + node.config.Explore*math.Sqrt(r*v)
}
Esempio n. 20
0
func computePrice(iters int, agent *Agent) {
	exptdProd := agent.totProd / (float64)(iters)
	priceChange := rand.Float64() * (exptdProd - agent.unsoldProd) / agent.maxProd * agent.adjust
	agent.price += priceChange
	minPrice := 0.00001
	if agent.price < minPrice {
		agent.price = minPrice
	}
}
Esempio n. 21
0
func (self *SendMachine) PerformSends(comm agent.Comm) {
	if self.agent.Time() >= 750 && self.agent.Time() <= 1000 {
		self.log("info", self.agent.Time(), "current state", self.state)
	}
	switch self.state {
	case 0:
		self.heard_last = false
		sent, isack := self.send_message(comm)
		if sent && !isack {
			self.state = 1
		} else if sent {
			self.state = 4
		} else {
			self.state = 3
		}
	case 1:
		if self.confirm_acked(comm) {
			if !self.sendq.Empty() {
				m, _ := self.sendq.Dequeue()
				self.log("info", self.agent.Time(), "dequeued msg", m)
			}
			self.state = 2
			self.next_state = 3
			self.backoff = BACKOFF
			self.wait = SEND_HOLDTIME
		}
	case 2:
		self.wait -= 1
		if self.wait == 0 {
			self.state = self.next_state
		}
	case 3:
		if !self.sendq.Empty() {
			self.state = 0
			self.backoff = BACKOFF
			self.ack_backoff = ACK_WAIT
			self.wait = uint32(self.backoff)
			self.ack_wait = uint32(self.ack_backoff)
		}
	case 4:
		self.next_state = 3
		if self.confirm_last(comm) {
			if !self.sendq.Empty() {
				self.sendq.Dequeue()
			}
			self.backoff = BACKOFF
			self.state = 2
			self.wait = 1
		} else {
			self.state = 2
			self.backoff = self.backoff * (pseudo_rand.Float64()*2 + 1)
			self.wait = uint32(self.backoff)
		}
	default:
		//             self.log("debug", self.agent.Time(), "nop")
	}
}
Esempio n. 22
0
func Random(m int, n int) *Matrix {
	a := NewMatrixFromMandN(m, n)
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			a.Data[i][j] = rand.Float64()
		}
	}
	return a
}
Esempio n. 23
0
func (ed EdgeDetector) Proposal(bounds Float64Rectangle) EdgeDetector {

	new_ed := ed.CloneEdgeDetector()

	// rotations and shifts must be correlated
	independent_scale := 0.1
	mean_theta := (rand.Float64()*2.0 - 1.0) * (math.Pi / 180.0 * ed.proposal_variance)
	mean_dx := (rand.Float64()*2.0 - 1.0) * ed.proposal_variance
	mean_dy := (rand.Float64()*2.0 - 1.0) * ed.proposal_variance

	for i, l := range ed.lines {

		nl := *new(Line) // new line
		nl.radius = l.radius

		// first rotate the line
		theta := mean_theta + independent_scale*(rand.Float64()*2.0-1.0)*(math.Pi/180.0*ed.proposal_variance)
		v := PointMinus(l.right, l.left)
		z := v.Rotate(theta)

		// scale back up to the correct length
		// new and old vecs share a midpoint, add/subtract half of the difference
		z.Scale(0.5)
		nl.left = PointMinus(Midpoint(l.left, l.right), z)
		nl.right = PointPlus(Midpoint(l.left, l.right), z)

		// now apply left-right and up-down shifts
		// TODO the indepented scale for dx dy shifts should be higher to allow for when
		// the original distance between lines is too great or small
		dx := mean_dx + independent_scale*(rand.Float64()*2.0-1.0)*ed.proposal_variance // left-right movement
		dy := mean_dy + independent_scale*(rand.Float64()*2.0-1.0)*ed.proposal_variance // up-down movement
		nl.left.X += dx
		nl.left.Y += dy
		nl.right.X += dx
		nl.right.Y += dy

		// now make sure it's in the bounds
		nl.ProjectInto(bounds)
		new_ed.lines[i] = nl
	}

	// scalings (shrinks and stretches) in x and y directions
	// TODO write variance struct that includes L/R, U/D shift amounts in (0,1)
	stretch := (rand.Float64()*2.0 - 1.0) * ed.proposal_variance
	center := Float64Point{0.0, 0.0} // find center of all lines, stretch to/from this point
	for _, l := range new_ed.lines {
		center := PointPlus(center, Midpoint(l))
	}
	center.Scale(1.0 / len(new_ed.lines))
	amount := 0.0 // TODO
	for _, l := range new_ed.lines {
		nmp := ShiftedMidpoint(l, center, amount)
		half := PointMinus(l.right, Midpoint(l))
		l.right = PointPlus(half, nmp)
		l.left = PointMinus(nmp, half)
	}

	return new_ed
}
Esempio n. 24
0
func (f *RandomSample) Evaluate(data JSONData) (result interface{}, err os.Error) {
	sampleRate, err := f.rate.Evaluate(data)
	if err != nil {
		return false, err
	}
	if sampleRate, ok := sampleRate.(float64); !ok {
		return false, fmt.Errorf("RandomSample takes a single argument, a float between 0 and 1. Got %v", sampleRate)
	}
	return rand.Float64() < sampleRate.(float64), nil
}
Esempio n. 25
0
func NewParticle(swarm *Swarm, min, max float64) *Particle {
	p := new(Particle)
	p.swarm = swarm
	p.Strategy = rand.Float64() * 0.05
	p.Position = make(map[uint32]float64)
	p.Min = min
	p.Max = max
	p.Fitness = 0
	return p
}
Esempio n. 26
0
func (c *TwoParentBreeder) Breed(oldpop *Population, sel Selector) (newpop *Population) {
	newpop = NewPopulation(oldpop.Size())
	for i := range newpop.Subjects {
		parents := sel.Select(2, oldpop)
		crosspoint := int(rand.Float64() * float64(parents.Subjects[0].GenomeLength()))
		g1, g2 := crossover(parents.Subjects[0].Genome, parents.Subjects[1].Genome, crosspoint)
		newpop.Subjects[i] = &Subject{Genome: selectAChild(g1, g2)}
	}
	return
}
Esempio n. 27
0
func (i *Individual) Fix() {
	for n, _ := range i.bets {
		if ((*i).bets[n]) < 2 {
			if rand.Float64() > .6 {
				(*i).bets[n] = 2
			} else {
				(*i).bets[n] = 0
			}
		}
	}
}
Esempio n. 28
0
func BenchmarkUpdateCellOne(b *testing.B) {
	d := NewDsl(0, 0, 800, 600)

	x := int32(rand.Intn(800))
	y := int32(rand.Intn(600))
	cost := rand.Float64() * 100.0

	for j := 0; j < b.N; j++ {
		d.UpdateCell(x, y, cost)
	}
	d.Replan()
}
Esempio n. 29
0
// Find the time to calculate Sample Kurtosis on an input array 100k random values.
// The benchmark will repeat this test b.N times to determine a stable time. The
// resulting stable time is the time for the calculation on 100k values.
func BenchmarkCalcSampleKurtosis100k(b *testing.B) {
	b.StopTimer()
	rand.Seed(time.Nanoseconds())
	n := 100000 // not the same as b.N
	a := make([]float64, n)
	for i := 0; i < n; i++ {
		a[i] = rand.Float64()
	}
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		StatsSampleKurtosis(a)
	}
}
Esempio n. 30
0
func (ga *GA) RunGeneration() {
	l := len(ga.pop) // Do not try to breed/mutate new in this gen
	for p := 0; p < l; p++ {
		//Breed two inviduals selected with selector.
		if ga.PBreed > rand.Float64() {
			children := make(GAGenomes, 2)
			children[0], children[1] = ga.breeder.Breed(ga.selector.SelectOne(ga.pop), ga.selector.SelectOne(ga.pop))
			ga.pop = AppendGenomes(ga.pop, children)
		}
		//Mutate
		if ga.PMutate > rand.Float64() {
			children := make(GAGenomes, 1)
			children[0] = ga.mutator.Mutate(ga.pop[p])
			ga.pop = AppendGenomes(ga.pop, children)
		}
	}
	//cleanup remove some from pop
	// this should probably use a type of selector
	sort.Sort(ga.pop)
	ga.pop = ga.pop[0:ga.popsize]
	ga.generationsCnt++
}