Example #1
0
//strip everything that is not red
//this is probably more complicated than it needs to be - but it works
func stripColors(img image.Image) *image.RGBA {
	rgb := rgba(img)

	pix := rgb.Pix[0]
	var avg float64
	min_dist := 30.0
	for i := 0; i < len(rgb.Pix); i++ {
		pix = rgb.Pix[i]

		//first we need to kill everything that is some shade of grey
		avg = (float64(pix.R) + float64(pix.G) + float64(pix.B)) / 3.0

		dist_r := math.Fabs(float64(pix.R) - avg)
		dist_g := math.Fabs(float64(pix.G) - avg)
		dist_b := math.Fabs(float64(pix.B) - avg)

		if dist_r <= min_dist && dist_g <= min_dist && dist_b <= min_dist {
			rgb.Pix[i].R = 0
			rgb.Pix[i].G = 0
			rgb.Pix[i].B = 0
		}

		//now keep only the red data (which is the current one)
		if (pix.R > pix.G && pix.R > pix.B) &&
			(pix.R-pix.G) > 125 && (pix.R-pix.B) > 125 {
			//keep pixel
		} else {
			rgb.Pix[i].R = 0
			rgb.Pix[i].G = 0
			rgb.Pix[i].B = 0
		}
	}

	return rgb
}
Example #2
0
func nearEqual(a, b, closeEnough, maxError float64) bool {
	absDiff := math.Fabs(a - b)
	if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero.
		return true
	}
	return absDiff/max(math.Fabs(a), math.Fabs(b)) < maxError
}
Example #3
0
func (l Line) WeightedIterator() (pix []WeightedPoint) {

	max_delta := 2.0 * l.radius // will miss prob mass outside of 2 std dev
	normalizer := 1.0 / math.Sqrt(2.0*math.Pi*l.radius*l.radius)

	var p image.Point
	cur := l.left
	iter := int(math.Fmax(math.Fabs(l.Dx()), math.Fabs(l.Dy()))) + 1
	dx := l.Dx() / float64(iter)
	dy := l.Dy() / float64(iter)

	for i := 0; i < iter; i++ {
		for d := -max_delta; d < max_delta; d += 1.0 {

			if dx > dy { // vertical sweeps
				p = image.Point{int(cur.X), int(cur.Y + d)}
			} else { // horizontal sweeps
				p = image.Point{int(cur.X + d), int(cur.Y)}
			}

			fp := NewFloat64Point(p)
			dist := l.Distance(fp.X, fp.Y)
			dist = math.Fmin(dist, Distance(fp, l.left))
			dist = math.Fmin(dist, Distance(fp, l.right))
			weight := normalizer * math.Exp(-dist*dist/(2.0*l.radius*l.radius))

			pix = append(pix, WeightedPoint{p, weight})
		}
		cur.X += dx
		cur.Y += dy
	}
	return pix
}
Example #4
0
// calculate the closest distance between to locations
func (m *Map) Distance(srcLoc, destLoc Location) float64 {
	row1, col1 := m.FromLocation(srcLoc)
	row2, col2 := m.FromLocation(destLoc)
	dCol := math.Fmin(math.Fabs(float64(col1-col2)), float64(m.Cols)-math.Fabs(float64(col1-col2)))
	dRow := math.Fmin(math.Fabs(float64(row1-row2)), float64(m.Rows)-math.Fabs(float64(row1-row2)))
	return dCol + dRow
}
Example #5
0
func (w *World) moveEnt(ent *EntityDesc, vel *s3dm.V3) {
	// Compute new position vector
	old_pos, ok := w.pos[ent.Uid]
	if !ok { // Entity hasn't been added for some reason, bail
		log.Println("No position for", ent.Uid)
		return
	}
	new_pos := old_pos.Add(vel)
	hash := hashV3(new_pos)

	// See if destination cell is occupied
	if ent_ch, ok := w.ents[hash]; ok {
		// TODO: HACK remove following if block when spider AI uses time based move
		// Update position if movement is less than 1, this lets spider move slowly
		if math.Fabs(vel.X) < 1 && math.Fabs(vel.Y) < 1 {
			w.pos[ent.Uid] = new_pos
			Send(w, ent.Chan, MsgSetState{Position{new_pos}})
		}
		// Can't move there, attack instead
		Send(w, ent_ch, MsgRunAction{Attack{ent}, false})
		return
	}
	// If not, move the entity to the new pos
	w.setPos(ent, new_pos, old_pos)
	// Update entity position state
	Send(w, ent.Chan, MsgSetState{Position{new_pos}})

	// Spawn spiders as players move around
	if ent.Id == cmpId.Player {
		w.spawnSpiders(new_pos)
	}
}
Example #6
0
// returns true if a and b are very close, else false
func ComplexEqual(a, b complex128) bool {
	r_a := real(a)
	r_b := real(b)
	i_a := imag(a)
	i_b := imag(b)

	return ((math.Fabs(r_a-r_b) <= closeFactor || math.Fabs(1-r_a/r_b) <= closeFactor) &&
		(math.Fabs(i_a-i_b) <= closeFactor || math.Fabs(1-i_a/i_b) <= closeFactor))
}
Example #7
0
func genString(stddev float64) string {
	n := int(math.Fabs(rand.NormFloat64()*stddev + stddev/2))
	c := make([]int, n)
	for i := range c {
		f := math.Fabs(rand.NormFloat64()*64 + 32)
		if f > 0x10ffff {
			f = 0x10ffff
		}
		c[i] = int(f)
	}
	return string(c)
}
Example #8
0
func TestDotProduct(T *testing.T) {
	var (
		p1 = Point{-1.23456, 7.890987}
		p2 = Point{7.890987, 1.23456}
	)
	if math.Fabs(p1.Dot(p2)-p2.Dot(p1)) > 1.0e-12 {
		T.Errorf("Symmetric dot product failure %e", math.Fabs(p1.Dot(p2)-p2.Dot(p1)))
	}
	if math.Fabs(p1.Dot(p2)) > 1.0e-12 {
		T.Errorf("Symmetric dot product failure %e", math.Fabs(p1.Dot(p2)-p2.Dot(p1)))
	}
}
Example #9
0
func TestNorm(T *testing.T) {
	var (
		e1 = Point{1, 0}
		e2 = Point{0, -1}
	)
	if math.Fabs(e1.Norm()-1) > 1.0e-15 {
		T.Errorf("Unit vector e1 norm is not one %f", e1.Norm())
	}
	if math.Fabs(e2.Norm()-1) > 1.0e-15 {
		T.Errorf("Unit vector -e2 norm is not one %f", e2.Norm())
	}
}
Example #10
0
File: util.go Project: eadf/math3d
func AbsMin3(a, b, c float64) float64 {
	fabsa := math.Fabs(a)
	fabsb := math.Fabs(b)
	fabsc := math.Fabs(c)

	if fabsa < fabsb && fabsa < fabsc {
		return a
	}
	if fabsb < fabsa && fabsb < fabsc {
		return b
	}
	return c
}
Example #11
0
func (this *DragTracker) MouseDrag(e *MouseEvent) {
	this.DefaultTool.MouseDrag(e)
	this.hasMoved = math.Fabs(float64(e.X-this.anchorX)) > 3 ||
		math.Fabs(float64(e.Y-this.anchorY)) > 3
	if this.hasMoved {
		selectedFigures := this.editor.GetView().GetSelection()
		for i := 0; i < selectedFigures.Len(); i++ {
			selectedFigure := selectedFigures.At(i).(Figure)
			selectedFigure.MoveBy(selectedFigure, e.X-this.lastX, e.Y-this.lastY)
		}
	}
	this.lastX = e.X
	this.lastY = e.Y
}
Example #12
0
func (v *Subtitle) ShortStartTime() string {

	seconds := v.StartTimeInSecondsFixed()

	sign := ""
	if seconds < 0 {
		sign = "-"
	}

	m := int(math.Fabs(seconds) / 60)
	s := int(math.Fmod(math.Fabs(seconds), 60))

	return sign + fmt.Sprintf("%02d:%02d", m, s)
}
Example #13
0
func analyze(s *source) {
	fmt.Fprintf(os.Stderr, "starting file %s\n", s.filename)
	//		tracks = tracks[:1+len(tracks)]
	// loop over bands
	for index := 0; index < len(s.beats); index++ {
		s.beats[index].buckets = make([]bucket, bands)
	}

	for band := uint(0); band < bands; band++ {
		i := uint(0)
		var bi uint
		samplelength, datachan := opensrcband(s.filename, band)
		beatlength := samplelength / uint(len(s.beats))
		fmt.Fprint(os.Stderr, "got channels\n")
		fmt.Fprintf(os.Stderr, "beatlength %d, band %d / %d, beats %d\n", beatlength, band, bands, len(s.beats))
		for {
			f := <-datachan
			if f.empty() && closed(datachan) {
				break
			}
			bi = 0
			//			fmt.Println(samplelength, len(s.beats))
			dex := i / beatlength
			defer func() {
				e := recover()
				if e != nil {
					fmt.Println(bi, beatlength, dex, len(s.beats), len(f.left), len(f.right))
					panic(e)
				}
			}()
			for ; (dex < uint(len(s.beats)) && bi < beatlength) && bi < uint(len(f.left)); bi++ {
				b := bucket{float64(f.left[bi]), float64(f.right[bi])}
				if dex >= uint(len(s.beats)) {
					dex = uint(len(s.beats)) - 1
					// rolloff
					b.left = b.left * float64(dex/uint(len(s.beats)))
					b.right = b.right * float64(dex/uint(len(s.beats)))
				}
				s.beats[dex].buckets[band].left += math.Fabs(b.left)
				s.beats[dex].buckets[band].right += math.Fabs(b.right)
				//				if i%10000 == 0 {
				fmt.Fprintf(os.Stderr, "%d %d %f %d %f %f %f\n", i, f.left[bi], float64(f.left[bi]), f.right[bi], float64(f.right[bi]), s.beats[dex].buckets[band].left, s.beats[dex].buckets[band].right)
				//				}

				i++
			}
		}
	}
}
Example #14
0
func (m Matrix) Solve(rhs Matrix) *Matrix {
	if m.M != m.N || rhs.M != m.N || rhs.N != 1 {
		fmt.Fprintf(os.Stderr, "Illegal matrix dimensions.")
		os.Exit(1)
	}

	a := NewMatrixFromMatrix(m)
	b := NewMatrixFromMatrix(rhs)

	for i := 0; i < m.N; i++ {
		max := i
		for j := i + 1; j < m.N; j++ {
			if math.Fabs(a.Data[j][i]) > math.Fabs(a.Data[max][i]) {
				max = j
			}
		}

		a.Swap(i, max)
		b.Swap(i, max)

		if a.Data[i][i] == 0.0 {
			fmt.Fprintf(os.Stderr, "Matrix is singular.")
			os.Exit(1)
		}

		for j := i + 1; j < m.N; j++ {
			b.Data[j][0] -= b.Data[i][0] * a.Data[j][i] / a.Data[i][i]
		}

		for j := i + 1; j < m.N; j++ {
			temp := a.Data[j][i] / a.Data[i][i]
			for k := i + 1; k < m.N; k++ {
				a.Data[j][k] -= a.Data[i][k] * temp
			}
			a.Data[j][i] = 0.0
		}
	}

	x := NewMatrixFromMandN(m.N, 1)
	for j := m.N - 1; j >= 0; j-- {
		t := 0.0
		for k := j + 1; k < m.N; k++ {
			t += a.Data[j][k] * x.Data[k][0]
		}
		x.Data[j][0] = (b.Data[j][0] - t) / a.Data[j][j]
	}
	return x
}
Example #15
0
func notNearEqual(a, b, closeEnough float64) bool {
	absDiff := math.Fabs(a - b)
	if absDiff < closeEnough {
		return false
	}
	return true
}
Example #16
0
// Convert Cartesian coordinates to polar.
// The reference ellipsoid is copied verbatim to the result.
// The resulting polar coordinates are in decimal degrees.
// Inspired by http://www.movable-type.co.uk/scripts/latlong-convert-coords.html
func CartesianToPolar(pt *CartPoint) *PolarCoord {

	var gc PolarCoord

	el := pt.El

	esq := (el.a*el.a - el.b*el.b) / (el.a * el.a)
	p := math.Hypot(pt.X, pt.Y)

	lat := math.Atan2(pt.Z, p*(1-esq))
	lat0 := 2.0 * math.Pi

	precision := 4.0 / el.a
	var v float64
	for math.Fabs(lat-lat0) > precision {
		v = el.a / math.Sqrt(1-esq*math.Pow(math.Sin(lat), 2))

		lat0 = lat
		lat = math.Atan2(pt.Z+esq*v*math.Sin(lat), p)
	}

	gc.Height = p/math.Cos(lat) - v
	gc.Latitude = radtodeg(lat)
	gc.Longitude = radtodeg(math.Atan2(pt.Y, pt.X))

	gc.El = el

	return &gc
}
Example #17
0
// Spherical linear interpolation.
// t is the interpolation value from 0. to 1.
// p and q are 'const'. m is *not*
func (m Quaternion) Slerp(t float64, p, q Quaternion) Quaternion {

	cs := p.Dot(q)
	angle := math.Acos(cs)

	if math.Fabs(angle) >= internalε {
		sn := math.Sin(angle)
		invSn := 1. / sn
		tAngle := t * angle
		coeff0 := math.Sin(angle-tAngle) * invSn
		coeff1 := math.Sin(tAngle) * invSn

		m[0] = float64(coeff0*p[0] + coeff1*q[0])
		m[1] = float64(coeff0*p[1] + coeff1*q[1])
		m[2] = float64(coeff0*p[2] + coeff1*q[2])
		m[3] = float64(coeff0*p[3] + coeff1*q[3])
	} else {
		m[0] = p[0]
		m[1] = p[1]
		m[2] = p[2]
		m[3] = p[3]
	}

	return m
}
Example #18
0
func TestCalcPI(t *testing.T) {
	result := math.Fabs(CalcPI(5000, 10) - math.Pi)
	expected := float64(0.1)
	if result > expected {
		t.Errorf("Expected %s found %s", expected, result)
	}
}
Example #19
0
File: ttt.go Project: qrush/go
// Determines if the game is over. Game is over if:
// * All board elements are marked (draw)
// * A winning outcome is on the board and is owned by one player
func (this *tttRef) Done(player1, player2 games.View) (done bool) {
	draw := true

	for _, value := range this.board {
		if value == 0 {
			draw = false
			break
		}
	}

	if draw {
		player1.Done(games.Draw)
		player2.Done(games.Draw)
		return draw
	}

	for _, outcome := range outcomes {
		first := this.board[outcome[0]]
		if math.Fabs(float64(first+this.board[outcome[1]]+this.board[outcome[2]])) == 3 {
			if first == p1mark {
				player1.Done(games.Win)
				player2.Done(games.Lose)
			} else {
				player1.Done(games.Lose)
				player2.Done(games.Win)
			}

			done = true
		}
	}

	return done
}
Example #20
0
func main() {
	fmt.Print("")

	minDeviation := 2000000

	sumOfIs := 0
	for i := 1; sumOfIs < 3000000; i += 1 {
		sumOfIs += i

		sumOfJs := sumOfIs - i
		for j := i; sumOfJs < 3000000; j += 1 {
			sumOfJs += j

			//fmt.Println(sumOfIs, sumOfJs)

			product := sumOfIs * sumOfJs

			deviation := int(math.Fabs(float64(2000000 - product)))

			if deviation < minDeviation {
				fmt.Println("  ", deviation, i, j)

				minDeviation = deviation
			}

		}
	}

}
Example #21
0
File: util.go Project: eadf/math3d
/*
Tests to see if the difference between two floats exceeds ε.
*/
func ApproxEquals(f1, f2 float64, ε float64) bool {
	if math.Fabs(f1-f2) > ε {
		//print ("diff is ", math.Fabs(f1-f2))
		return false
	}
	return true
}
Example #22
0
// Sqrt returns the square root of x.
func Sqrt(x complex128) complex128 {
	if imag(x) == 0 {
		if real(x) == 0 {
			return complex(0, 0)
		}
		if real(x) < 0 {
			return complex(0, math.Sqrt(-real(x)))
		}
		return complex(math.Sqrt(real(x)), 0)
	}
	if real(x) == 0 {
		if imag(x) < 0 {
			r := math.Sqrt(-0.5 * imag(x))
			return complex(r, -r)
		}
		r := math.Sqrt(0.5 * imag(x))
		return complex(r, r)
	}
	a := real(x)
	b := imag(x)
	var scale float64
	// Rescale to avoid internal overflow or underflow.
	if math.Fabs(a) > 4 || math.Fabs(b) > 4 {
		a *= 0.25
		b *= 0.25
		scale = 2
	} else {
		a *= 1.8014398509481984e16 // 2**54
		b *= 1.8014398509481984e16
		scale = 7.450580596923828125e-9 // 2**-27
	}
	r := math.Hypot(a, b)
	var t float64
	if a > 0 {
		t = math.Sqrt(0.5*r + 0.5*a)
		r = scale * math.Fabs((0.5*b)/t)
		t *= scale
	} else {
		r = math.Sqrt(0.5*r - 0.5*a)
		t = scale * math.Fabs((0.5*b)/r)
		r *= scale
	}
	if b < 0 {
		return complex(t, -r)
	}
	return complex(t, r)
}
Example #23
0
/*
Tests to see if the difference between two matrices,
element-wise, exceeds ε.
*/
func (a Matrix3) ApproxEquals(b Matrix3, ε float64) bool {
	for i := 0; i < 9; i++ {
		if math.Fabs(a[i]-b[i]) > ε {
			return false
		}
	}
	return true
}
Example #24
0
/*
Tests to see if the difference between two matrices,
element-wise, exceeds ε.
*/
func (a Vector3) ApproxEquals(b Vector3, ε float64) bool {
	for i := 0; i < 3; i++ {
		if math.Fabs(a[i]-b[i]) > ε {
			return false
		}
	}
	return true
}
Example #25
0
// it would be nice to use goroutines for the interator, but
// it appears to be way too slow:
// http://groups.google.com/group/golang-nuts/browse_thread/thread/a717e1286a8736fd#
// for now i'll use a fully blocking producer-consumer model
func (l Line) UnweightedIterator() (pix []WeightedPoint) {

	cur := l.left
	iter := int(math.Fmax(math.Fabs(l.Dx()), math.Fabs(l.Dy())))
	if iter == 0 {
		p := image.Point{int(l.left.X), int(l.right.Y)}
		return append(pix, WeightedPoint{p, 1.0})
	}
	dx := l.Dx() / float64(iter)
	dy := l.Dy() / float64(iter)
	for i := 0; i < iter; i++ {
		p := image.Point{int(cur.X), int(cur.Y)}
		pix = append(pix, WeightedPoint{p, 1.0})
		cur.X += dx
		cur.Y += dy
	}
	return pix
}
Example #26
0
func ApproxEqNanzero(f, g float64, additiveAccu float64) bool {
	if math.IsNaN(f) {
		f = 0.0
	}
	if math.IsNaN(g) {
		g = 0.0
	}
	return math.Fabs(f-g) <= additiveAccu
}
Example #27
0
// Computes L-infinity norm of A, ignoring NaN entries
func EllInf(A Matrix) float64 {
	r := float64(0.0)
	for i := 0; i < A.M(); i++ {
		for j := 0; j < A.N(); j++ {
			r = Fmax(r, math.Fabs(A.Get(i, j)))
		}
	}
	return r
}
Example #28
0
// calculate sinh and cosh
func sinhcosh(x float64) (sh, ch float64) {
	if math.Fabs(x) <= 0.5 {
		return math.Sinh(x), math.Cosh(x)
	}
	e := math.Exp(x)
	ei := 0.5 / e
	e *= 0.5
	return e - ei, e + ei
}
Example #29
0
/*
Tests to see if the difference between two matrices,
element-wise, exceeds ε.
*/
func (a Matrix4) ApproxEquals(b Matrix4, ε float64) bool {
	for i := 0; i < 16; i++ {
		delta := math.Fabs(a[i] - b[i])
		if delta > ε {
			//fmt.Printf("delta between %f and %f is %f. ε=%f\n",a[i],b[i],delta,ε)
			return false
		}
	}
	return true
}
Example #30
0
// Tan returns the tangent of x.
func Tan(x complex128) complex128 {
	d := math.Cos(2*real(x)) + math.Cosh(2*imag(x))
	if math.Fabs(d) < 0.25 {
		d = tanSeries(x)
	}
	if d == 0 {
		return Inf()
	}
	return complex(math.Sin(2*real(x))/d, math.Sinh(2*imag(x))/d)
}