Exemple #1
0
/*
   Copy x to y using packed storage.

   The vector x is an element of S, with the 's' components stored in
   unpacked storage.  On return, x is copied to y with the 's' components
   stored in packed storage and the off-diagonal entries scaled by
   sqrt(2).
*/
func pack(x, y *matrix.FloatMatrix, dims *DimensionSet, opts ...la_.Option) (err error) {
	/*DEBUGGED*/
	err = nil
	mnl := la_.GetIntOpt("mnl", 0, opts...)
	offsetx := la_.GetIntOpt("offsetx", 0, opts...)
	offsety := la_.GetIntOpt("offsety", 0, opts...)

	nlq := mnl + dims.At("l")[0] + dims.Sum("q")
	blas.Copy(x, y, &la_.IOpt{"n", nlq}, &la_.IOpt{"offsetx", offsetx},
		&la_.IOpt{"offsety", offsety})

	iu, ip := offsetx+nlq, offsety+nlq
	for _, n := range dims.At("s") {
		for k := 0; k < n; k++ {
			blas.Copy(x, y, &la_.IOpt{"n", n - k}, &la_.IOpt{"offsetx", iu + k*(n+1)},
				&la_.IOpt{"offsety", ip})
			y.SetIndex(ip, (y.GetIndex(ip) / math.Sqrt(2.0)))
			ip += n - k
		}
		iu += n * n
	}
	np := dims.SumPacked("s")
	blas.ScalFloat(y, math.Sqrt(2.0), &la_.IOpt{"n", np}, &la_.IOpt{"offset", offsety + nlq})
	return
}
Exemple #2
0
// Computes the error estimate based on fNew:
func (p *peer) computeErrorModel(in *integration) (errorEstimate float64) {
	var i_n, j_stg uint

	// Loop: EmFactors
	for i_n = 0; i_n < in.n; i_n++ {
		var factor float64 = 0.0
		for j_stg = 0; j_stg < p.Stages; j_stg++ {
			factor += p.errorModelWeights[j_stg] * in.fNew[j_stg][i_n]
		}
		in.errorFactors[i_n] = math.Pow(factor/(in.AbsoluteTolerance+in.RelativeTolerance*math.Abs(in.yOld[p.Stages-1][i_n])), 2.0)
	}

	// compute error quotient/20070803
	// step ratio from error model ((1+a)^p-a^p)/est+a^p)^(1/p)-a, p=order/2:
	errorRelative := 0.0
	for i_n = 0; i_n < in.n; i_n++ {
		errorRelative += in.errorFactors[i_n]
	}

	errorEstimate = in.stepEstimate*math.Sqrt(errorRelative/float64(in.n)) + 1e-8
	errorModelDenom := math.Pow(math.Pow(in.stepRatio, 2.0)+p.errorModelA, float64(p.Order)/2.0) - p.errorModelA0
	errorStepRatio := math.Pow(errorModelDenom/errorEstimate+p.errorModelA0, 2.0/float64(p.Order)) - p.errorModelA
	in.stepEstimate = in.stepPrevious * math.Max(in.stepRatioMin, math.Min(0.95*math.Sqrt(errorStepRatio), p.stepRatioMax)) // safety interval

	return
}
Exemple #3
0
// Convert the given coordinate from X,Y to polar in the given PolarSystem
func (coord Coordinate) ToPolar(system PolarSystem) (polarCoord PolarCoordinate) {

	coord.X += system.XOffset
	coord.Y += system.YOffset

	// clip coordinates to system's area
	if coord.X < system.XMin {
		fmt.Println("WARNING: X value was outside left bounds, clipping", coord.X, "to", system.XMin)
		coord.X = system.XMin
	}
	if coord.X > system.XMax {
		fmt.Println("WARNING: X value was outside right bounds, clipping", coord.X, "to", system.XMax)
		coord.X = system.XMax
	}
	if coord.Y < system.YMin {
		fmt.Println("WARNING: Y value was outside top bounds, clipping", coord.Y, "to", system.YMin)
		coord.Y = system.YMin
	}
	if coord.Y > system.YMax {
		fmt.Println("WARNING: Y value was outside bottom bounds, clipping", coord.Y, "to", system.YMax)
		coord.Y = system.YMax
	}

	polarCoord.LeftDist = math.Sqrt(coord.X*coord.X + coord.Y*coord.Y)
	xDiff := system.RightMotorDist - coord.X
	polarCoord.RightDist = math.Sqrt(xDiff*xDiff + coord.Y*coord.Y)
	polarCoord.PenUp = coord.PenUp
	return
}
func ellipse(dst *sdl.Surface, org Point, a, b int) {
	colour := image.RGBAColor{0, 255, 0, 255}

	// set the poles
	dst.Set(int(org.X), int(org.Y)+b, colour)
	dst.Set(int(org.X), int(org.Y)-b, colour)
	dst.Set(int(org.X)+a, int(org.Y), colour)
	dst.Set(int(org.X)-a, int(org.Y), colour)

	// add a bias to a and b for smoother poles
	ba := float64(a) + 0.5
	bb := float64(b) + 0.5

	// draw and rotate a quadrant
	for x := 1; x < a; x++ {
		y1 := (-bb * float64(x)) / (ba * math.Sqrt(ba*ba-float64(x*x)))
		y := int(math.Sqrt((bb * bb) * (1.0 - float64(x*x)/(ba*ba))))
		if y1 > -1.0 {
			dst.Set(int(org.X)+x, int(org.Y)+y, colour)
			dst.Set(int(org.X)-x, int(org.Y)+y, colour)
			dst.Set(int(org.X)+x, int(org.Y)-y, colour)
			dst.Set(int(org.X)-x, int(org.Y)-y, colour)
		} else {
			for dy := 1; dy <= y; dy++ {
				dx := int(math.Sqrt((ba * ba) * (1.0 - float64(dy*dy)/(bb*bb))))
				dst.Set(int(org.X)+dx, int(org.Y)+dy, colour)
				dst.Set(int(org.X)-dx, int(org.Y)+dy, colour)
				dst.Set(int(org.X)+dx, int(org.Y)-dy, colour)
				dst.Set(int(org.X)-dx, int(org.Y)-dy, colour)
			}
			break
		}
	}
}
Exemple #5
0
/*
 * Compute Givens rotation such that
 *
 *   G(s,c)*v = (r)   ==  (  c s ).T ( a ) = ( r )
 *              (0)       ( -s c )   ( b )   ( 0 )
 *
 * and
 *
 *   v*G(s,c) = (r 0 ) == (a b ) (  c  s ) = ( r 0 )
 *                               ( -s  c )
 *
 */
func ComputeGivens(a, b float64) (c float64, s float64, r float64) {

	if b == 0.0 {
		c = 1.0
		s = 0.0
		r = a
	} else if a == 0.0 {
		c = 0.0
		s = 1.0
		r = b
	} else if math.Abs(b) > math.Abs(a) {
		t := a / b
		u := math.Sqrt(1.0 + t*t)
		if math.Signbit(b) {
			u = -u
		}
		s = 1.0 / u
		c = s * t
		r = b * u
	} else {
		t := b / a
		u := math.Sqrt(1.0 + t*t)
		r = a * u
		c = 1.0 / u
		s = c * t
	}
	return
}
Exemple #6
0
// Correlation describes the degree of relationship between two sets of data
func Correlation(data1, data2 Float64Data) (float64, error) {

	l1 := data1.Len()
	l2 := data2.Len()

	if l1 == 0 || l2 == 0 {
		return 0, errors.New("Input data must not be empty")
	}

	if l1 != l2 {
		return 0, errors.New("Input data must be same length")
	}

	var sum_xsq, sum_ysq, sum_cross float64

	mean_x := data1.Get(0)
	mean_y := data2.Get(0)

	for i := 1; i < l1; i++ {
		ratio := float64(i) / float64(i+1)
		delta_x := data1.Get(i) - mean_x
		delta_y := data2.Get(i) - mean_y
		sum_xsq += delta_x * delta_x * ratio
		sum_ysq += delta_y * delta_y * ratio
		sum_cross += delta_x * delta_y * ratio
		mean_x += delta_x / float64(i+1)
		mean_y += delta_y / float64(i+1)
	}

	return sum_cross / (math.Sqrt(sum_xsq) * math.Sqrt(sum_ysq)), nil
}
Exemple #7
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))
		}
	}
}
func TestGenSparseVector(t *testing.T) {

	si1 := StringIndex{"a", "b", "c"}
	v1 := []Value{1, 2, 3}

	sv1 := NewGenSparseVector(si1, v1)

	if sv1.Mag() != Value(math.Sqrt(1+4+9)) {
		t.Fatalf("Mag wrong - have %f", sv1.Mag())
	}

	si2 := StringIndex{"b", "d", "a"}
	v2 := []Value{1, 2, 7}
	sv2 := NewGenSparseVector(si2, v2)

	dot := sv1.Dot(sv2)
	if dot != 7+2 {
		t.Fatalf("Dot not as expected. Have %f", dot)
	}

	cos := sv1.Cos(sv2)
	if cos != Value((7+2)/(math.Sqrt(1+4+9)*math.Sqrt(1+4+49))) {
		t.Fatalf("cos wrong. Have %f", cos)
	}

	mean := sv1.Mean()
	if mean != 2 {
		t.Fatalf("Mean not as expected, have %f", mean)
	}

	sv1.AddConst(2)
	if sv1.Mag() != 7.071068 {
		t.Fatalf("Mag (2) not as expected, have %f", sv1.Mag())
	}
	mean = sv1.Mean()
	if mean != 4 {
		t.Fatalf("Mean (2) not as expected. Have %f", mean)
	}

	sv1.SubConst(2)
	mean = sv1.Mean()
	if mean != 2 {
		t.Fatalf("Mean (3) not as expected. Have %f", mean)
	}

	vals := make([]Value, 0, 3)
	sv1.Iter(func(index interface{}, value Value) {
		vals = append(vals, value)
	})
	if !reflect.DeepEqual(vals, v1) {
		t.Fatalf("iter values not as expected. Have %v", vals)
	}

	sv1.IterUpdate(func(index interface{}, value Value) Value {
		return 3
	})
	if sv1.Mean() != 3 {
		t.Fatalf("that didn't work")
	}
}
Exemple #9
0
// Change the aspect ratio of a rectangle.
// The mode can be "area", "width", "height", "fit", "fill" or "stretch".
// Panics if mode is empty or unrecognized.
func SetAspect(w, h, aspect float64, mode string) (float64, float64) {
	switch mode {
	case "area":
		// aspect = width / height
		// width = height * aspect
		// width^2 = width * height * aspect
		// height = width / aspect
		// height^2 = width * height / aspect
		w, h = math.Sqrt(w*h*aspect), math.Sqrt(w*h/aspect)
	case "width":
		// Set height from width.
		h = w / aspect
	case "height":
		// Set width from height.
		w = h * aspect
	case "fit":
		// Shrink one dimension.
		w, h = math.Min(w, h*aspect), math.Min(h, w/aspect)
	case "fill":
		// Grow one dimension.
		w, h = math.Max(w, h*aspect), math.Max(h, w/aspect)
	case "stretch":
		// Do nothing.
	case "":
		panic("no mode specified")
	default:
		panic("unknown mode: " + mode)
	}
	return w, h
}
Exemple #10
0
func testReadUniformity(t *testing.T, n int, seed int64) {
	r := New(NewSource(seed))
	buf := make([]byte, n)
	nRead, err := r.Read(buf)
	if err != nil {
		t.Errorf("Read err %v", err)
	}
	if nRead != n {
		t.Errorf("Read returned unexpected n; %d != %d", nRead, n)
	}

	// Expect a uniform distribution of byte values, which lie in [0, 255].
	var (
		mean       = 255.0 / 2
		stddev     = math.Sqrt(255.0 * 255.0 / 12.0)
		errorScale = stddev / math.Sqrt(float64(n))
	)

	expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale}

	// Cast bytes as floats to use the common distribution-validity checks.
	samples := make([]float64, n)
	for i, val := range buf {
		samples[i] = float64(val)
	}
	// Make sure that the entire set matches the expected distribution.
	checkSampleDistribution(t, samples, expected)
}
Exemple #11
0
func calculateConfidenceInterval2(nt, nc, mt, mc, sdt, sdc float64) confInterval2 {

	var ci confInterval2
	//var z = 1.96 // http://www.dummies.com/how-to/content/creating-a-confidence-interval-for-the-difference-.html
	//var z = 2.58 // http://www.dummies.com/how-to/content/creating-a-confidence-interval-for-the-difference-.html

	ci.t1min = mt - zScore*(sdt/math.Sqrt(nt))
	ci.t0min = mc - zScore*(sdt/math.Sqrt(nc))

	ci.t1max = mt + zScore*(sdt/math.Sqrt(nt))
	ci.t0max = mt + zScore*(sdt/math.Sqrt(nc))

	ci.overlap = false

	if ci.t1max <= ci.t0max && ci.t1max >= ci.t0min {
		ci.overlap = true
	}

	if ci.t1min <= ci.t0max && ci.t1min >= ci.t0min {
		ci.overlap = true
	}

	// check for encirclement
	if ci.t0min <= ci.t1max && ci.t0min >= ci.t1min {
		ci.overlap = true
	}

	return ci
}
Exemple #12
0
func Correlation(data1 interface{}, stride1 int, data2 interface{}, stride2 int, n int) (r float64) {
	var ratio, delta_x, delta_y, sum_xsq, sum_ysq, sum_cross, mean_x, mean_y float64

	arry1 := reflect.ValueOf(data1)
	arry2 := reflect.ValueOf(data2)

	/*
	 Compute:
	 sum_xsq = Sum [ (x_i - mu_x)^2 ],
	 sum_ysq = Sum [ (y_i - mu_y)^2 ] and
	 sum_cross = Sum [ (x_i - mu_x) * (y_i - mu_y) ]
	 using the above relation from Welford's paper
	*/

	mean_x = number.Float(arry1.Index(0 * stride1))
	mean_y = number.Float(arry2.Index(0 * stride2))

	for i := 0; i < n; i++ {
		v1 := number.Float(arry1.Index(i * stride1))
		v2 := number.Float(arry2.Index(i * stride2))
		ratio = float64(i) / float64(i+1)
		delta_x = v1 - mean_x
		delta_y = v2 - mean_y
		sum_xsq += delta_x * delta_x * ratio
		sum_ysq += delta_y * delta_y * ratio
		sum_cross += delta_x * delta_y * ratio
		mean_x += delta_x / float64(i+1)
		mean_y += delta_y / float64(i+1)
	}

	r = sum_cross / (math.Sqrt(sum_xsq) * math.Sqrt(sum_ysq))

	return
}
Exemple #13
0
// Randomize randomizes the weights and biases
// such that the sum of the weights has a mean
// of 0 and a variance of 1.
//
// This will create d.Weights and d.Biases if
// they are nil.
func (d *DenseLayer) Randomize() {
	if d.Biases == nil {
		d.Biases = &autofunc.LinAdd{
			Var: &autofunc.Variable{
				Vector: make(linalg.Vector, d.OutputCount),
			},
		}
	}
	if d.Weights == nil {
		d.Weights = &autofunc.LinTran{
			Rows: d.OutputCount,
			Cols: d.InputCount,
			Data: &autofunc.Variable{
				Vector: make(linalg.Vector, d.OutputCount*d.InputCount),
			},
		}
	}

	sqrt3 := math.Sqrt(3)
	for i := 0; i < d.OutputCount; i++ {
		d.Biases.Var.Vector[i] = sqrt3 * ((rand.Float64() * 2) - 1)
	}

	weightCoeff := math.Sqrt(3.0 / float64(d.InputCount))
	for i := range d.Weights.Data.Vector {
		d.Weights.Data.Vector[i] = weightCoeff * ((rand.Float64() * 2) - 1)
	}
}
Exemple #14
0
func C206() (interface{}, error) {
	min := int(math.Sqrt(10203040506070809))
	max := int(math.Sqrt(19293949596979899)) + 1

	checks := map[int]int{
		9: 1,
		8: 100,
		7: 10000,
		6: 1000000,
		5: 100000000,
		4: 10000000000,
		3: 1000000000000,
		2: 100000000000000,
		1: 10000000000000000,
	}

	for i := min; i < max; i++ {
		pow := i * i
		matched := true
		for target, divisor := range checks {
			if pow/divisor%10 != target {
				matched = false
				break
			}
		}
		if matched {
			return i * 10, nil
		}
	}

	return nil, nil
}
Exemple #15
0
// check that the integration function works
func TestIntegrateMid(t *testing.T) {
	tests := []struct {
		fn     smoothFn
		x1, x2 float64
		Tot    float64
	}{
		// linear
		{func(x float64) float64 { return 0.5 * x }, 0.0, 1.0, 0.25},
		// normal distribution
		{func(x float64) float64 { return 1 / math.Sqrt(2*math.Pi) * math.Exp(-(x*x)/2) }, -100, 100, 1.0},
		// normal distribution half
		{func(x float64) float64 { return 1 / math.Sqrt(2*math.Pi) * math.Exp(-(x*x)/2) }, -100, 0, 0.5},
		// normal distribution segment
		{func(x float64) float64 { return 1 / math.Sqrt(2*math.Pi) * math.Exp(-(x*x)/2) }, -2, -1, .1359051219835},
		// scaled gamma distribution (similar to my dissertation experiment 3)
		{func(x float64) float64 {
			k, theta, a := 1.5, 2.0, 1.0/600
			return a / (math.Gamma(k) * math.Pow(theta, k)) * math.Sqrt(x*a) * math.Exp(-x*a/2)
		}, 0, 2400, 0.73853606463},
	}

	for i, test := range tests {
		got := integrateMid(test.fn, test.x1, test.x2, 10000)
		if diff := math.Abs(got - test.Tot); diff > 1e-10 {
			t.Errorf("case %v (integral from %v to %v): got %v, want %v", i+1, test.x1, test.x2, got, test.Tot)
		}
	}
}
Exemple #16
0
func main() {
	z1, i1 := Sqrt(1)
	fmt.Printf("z = %f (loop#%d)\n", z1, i1)
	fmt.Printf("math.Sqrt(1) = %f\n", math.Sqrt(1))
	fmt.Printf("delta = %f\n\n", math.Abs(z1-math.Sqrt(1)))

	z2, i2 := Sqrt(2)
	fmt.Printf("z = %f (loop#%d)\n", z2, i2)
	fmt.Printf("math.Sqrt(2) = %f\n", math.Sqrt(2))
	fmt.Printf("delta = %f\n\n", math.Abs(z2-math.Sqrt(2)))

	z3, i3 := Sqrt(3)
	fmt.Printf("z = %f (loop#%d)\n", z3, i3)
	fmt.Printf("math.Sqrt(3) = %f\n", math.Sqrt(3))
	fmt.Printf("delta = %f\n\n", math.Abs(z3-math.Sqrt(3)))

	z5, i5 := Sqrt(5)
	fmt.Printf("z = %f (loop#%d)\n", z5, i5)
	fmt.Printf("math.Sqrt(5) = %f\n", math.Sqrt(5))
	fmt.Printf("delta = %f\n\n", math.Abs(z5-math.Sqrt(5)))

	z7, i7 := Sqrt(7)
	fmt.Printf("z = %f (loop#%d)\n", z7, i7)
	fmt.Printf("math.Sqrt(7) = %f\n", math.Sqrt(7))
	fmt.Printf("delta = %f\n\n", math.Abs(z7-math.Sqrt(7)))
}
Exemple #17
0
// AstrometricJ2000 is a utility function for computing astrometric coordinates.
//
// It is used internally and only exported so that it can be used from
// multiple packages.  It is not otherwise expected to be used.
//
// Argument f is a function that returns J2000 equatorial rectangular
// coodinates of a body.
//
// Results are J2000 right ascention, declination, and elongation.
func AstrometricJ2000(f func(float64) (x, y, z float64), jde float64, e *pp.V87Planet) (α, δ, ψ float64) {
	X, Y, Z := solarxyz.PositionJ2000(e, jde)
	x, y, z := f(jde)
	// (33.10) p. 229
	ξ := X + x
	η := Y + y
	ζ := Z + z
	Δ := math.Sqrt(ξ*ξ + η*η + ζ*ζ)
	{
		τ := base.LightTime(Δ)
		x, y, z = f(jde - τ)
		ξ = X + x
		η = Y + y
		ζ = Z + z
		Δ = math.Sqrt(ξ*ξ + η*η + ζ*ζ)
	}
	α = math.Atan2(η, ξ)
	if α < 0 {
		α += 2 * math.Pi
	}
	δ = math.Asin(ζ / Δ)
	R0 := math.Sqrt(X*X + Y*Y + Z*Z)
	ψ = math.Acos((ξ*X + η*Y + ζ*Z) / R0 / Δ)
	return
}
Exemple #18
0
func continuedFracSqrt(S float64) []int {
	// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Continued_fraction_expansion
	// Using variables S, m, d, a as in the URL above.
	m := 0.0
	d := 1.0
	a := math.Floor(math.Sqrt(S))
	result := []int{}
	seen := make(map[string]bool)
	for {
		seen[k([]float64{m, d, a})] = true
		result = append(result, int(a))

		m = (d * a) - m
		d = (S - math.Pow(m, 2.0)) / d
		if d == 0 {
			// S is a perfect square.
			return result
		}
		a = math.Floor((math.Floor(math.Sqrt(S)) + m) / d)

		// The algorithm terminates when [m d a] repeats.
		if seen[k([]float64{m, d, a})] {
			return result
		}
	}

}
Exemple #19
0
// Dlae2 computes the eigenvalues of a 2×2 symmetric matrix
//  [a b]
//  [b c]
// and returns the eigenvalue with the larger absolute value as rt1 and the
// smaller as rt2.
//
// Dlae2 is an internal routine. It is exported for testing purposes.
func (impl Implementation) Dlae2(a, b, c float64) (rt1, rt2 float64) {
	sm := a + c
	df := a - c
	adf := math.Abs(df)
	tb := b + b
	ab := math.Abs(tb)
	acmx := c
	acmn := a
	if math.Abs(a) > math.Abs(c) {
		acmx = a
		acmn = c
	}
	var rt float64
	if adf > ab {
		rt = adf * math.Sqrt(1+(ab/adf)*(ab/adf))
	} else if adf < ab {
		rt = ab * math.Sqrt(1+(adf/ab)*(adf/ab))
	} else {
		rt = ab * math.Sqrt2
	}
	if sm < 0 {
		rt1 = 0.5 * (sm - rt)
		rt2 = (acmx/rt1)*acmn - (b/rt1)*b
		return rt1, rt2
	}
	if sm > 0 {
		rt1 = 0.5 * (sm + rt)
		rt2 = (acmx/rt1)*acmn - (b/rt1)*b
		return rt1, rt2
	}
	rt1 = 0.5 * rt
	rt2 = -0.5 * rt
	return rt1, rt2
}
Exemple #20
0
func (item *Item) UpdateScore() {
	result := item.Time + int64(math.Sqrt(float64(item.Ncomments))*mill_day/2)
	if item.BestComment != nil {
		result += int64(math.Sqrt(float64(item.BestComment.Likes)) * mill_day / 2)
	}
	item.Score = result
}
Exemple #21
0
func (d *TMP006) measureObjTemp() (float64, error) {
	if err := d.setup(); err != nil {
		return 0, err
	}
	tDie, err := d.measureRawDieTemp()
	if err != nil {
		return 0, err
	}
	glog.V(2).Infof("tmp006: tdie = %.2f C", tDie)
	tDie += 273.15 // Convert to K
	vo, err := d.measureRawVoltage()
	if err != nil {
		return 0, err
	}
	vObj := float64(vo)
	vObj *= 156.25 // 156.25 nV per LSB
	vObj /= 1000   // nV -> uV
	glog.V(2).Infof("tmp006: vObj = %.5f uV", vObj)
	vObj /= 1000 // uV -> mV
	vObj /= 1000 // mV -> V

	tdie_tref := tDie - tref
	s := 1 + a1*tdie_tref + a2*tdie_tref*tdie_tref
	s *= s0
	s /= 10000000
	s /= 10000000

	Vos := b0 + b1*tdie_tref + b2*tdie_tref*tdie_tref
	fVobj := (vObj - Vos) + c2*(vObj-Vos)*(vObj-Vos)

	temp := math.Sqrt(math.Sqrt(tDie*tDie*tDie*tDie + fVobj/s))
	temp -= 273.15

	return temp, nil
}
Exemple #22
0
// IDCTOrthogonal returns Inverse DCT (DCT-III) coefficients given a input
// signal.
func IDCTOrthogonal(dctCoef []float64) []float64 {
	n := len(dctCoef)
	nh := n / 2
	array := make([]complex128, n)

	theta := math.Pi / (2.0 * float64(n))

	c0 := math.Sqrt(1.0 / float64(n))
	c1 := math.Sqrt(2.0 / float64(n))

	// -1/4 Shift
	for k := 1; k < nh; k++ {
		w := cmplx.Exp(complex(0, float64(k)*theta))
		wCont := complex(imag(w), real(w))
		array[k] = w * complex(c1*dctCoef[k], 0)
		array[n-k] = wCont * complex(c1*dctCoef[n-k], 0)
	}
	array[0] = complex(c0*dctCoef[0], 0)
	array[nh] = complex(c1*dctCoef[nh], 0) *
		cmplx.Exp(complex(0, float64(nh)*theta))

	y := fft.IFFT(array)

	x := make([]float64, n)
	for i := 0; i < nh; i++ {
		x[2*i] = float64(n) * real(y[i])
		x[2*i+1] = float64(n) * real(y[n-1-i])
	}

	return x
}
Exemple #23
0
// Spearman returns the rank correlation coefficient between data1 and data2, and the associated p-value
func Spearman(data1, data2 []float64) (rs float64, p float64) {
	n := len(data1)
	wksp1, wksp2 := make([]float64, n), make([]float64, n)
	copy(wksp1, data1)
	copy(wksp2, data2)

	sort.Sort(sort2{wksp1, wksp2})
	sf := crank(wksp1)
	sort.Sort(sort2{wksp2, wksp1})
	sg := crank(wksp2)
	d := 0.0
	for j := 0; j < n; j++ {
		sq := wksp1[j] - wksp2[j]
		d += (sq * sq)
	}

	en := float64(n)
	en3n := en*en*en - en

	fac := (1.0 - sf/en3n) * (1.0 - sg/en3n)
	rs = (1.0 - (6.0/en3n)*(d+(sf+sg)/12.0)) / math.Sqrt(fac)

	if fac = (rs + 1.0) * (1.0 - rs); fac > 0 {
		t := rs * math.Sqrt((en-2.0)/fac)
		df := en - 2.0
		p = mathx.BetaInc(df/(df+t*t), 0.5*df, 0.5)
	}

	return rs, p
}
Exemple #24
0
/// <summary>
/// To calculate Burke ratio we take the difference between the portfolio
/// return and the risk free rate and we divide it by the square root of the
/// sum of the square of the drawdowns. To calculate the modified Burke ratio
/// we just multiply the Burke ratio by the square root of the number of datas.
/// (一种调整收益率的计算方式,调整是通过drawdown的平方和进行的)
/// </summary>
func BurkeRatio(Ra *utils.SlidingWindow, Rf float64, scale float64) (float64, error) {
	var len = Ra.Count()
	var in_drawdown = false
	var peak = 1
	var temp = 0.0
	drawdown, err := utils.NewSlidingWindow(len)
	if err != nil {
		return math.NaN(), err
	}
	for i := 1; i < len; i++ {
		if Ra.Data()[i] < 0 {
			if !in_drawdown {
				peak = i - 1
				in_drawdown = true
			}
		} else {
			if in_drawdown {
				temp = 1.0
				for j := peak + 1; j < i; j++ {
					temp = temp * (1.0 + Ra.Data()[j])
				}
				drawdown.Add(temp - 1.0) //Source
				in_drawdown = false
			}
		}
	}

	if in_drawdown {
		temp = 1.0
		for j := peak + 1; j < len; j++ {
			temp = temp * (1.0 + Ra.Data()[j])
		}
		drawdown.Add(temp - 1.0) //Source
		//drawdown.Add((temp - 1.0) * 100.0)
		in_drawdown = false
	}
	//var Rp = Annualized(Ra, scale, true) - 1.0--->Source
	Rp, err := Annualized(Ra, scale, true)
	if err != nil {
		return math.NaN(), err
	}
	var result float64

	if drawdown.Count() != 0 {
		pow_Sliding, err := utils.Power(drawdown, 2)
		if err != nil {
			return math.NaN(), err
		}
		Rf = Rf * scale
		result = (Rp - Rf) / math.Sqrt(pow_Sliding.Sum())
	} else {
		result = 0
	}

	modified := true
	if modified {
		result = result * math.Sqrt(float64(len))
	}
	return result, nil
}
Exemple #25
0
// ToLatLon converts the Vector3d cartesian coordinates to
// latitude longitude according to the WGS84 datum.
// It returns a lat/lon coordinates struct.
func (v *Vector3d) ToLatLon(datum Datum) Coordinates {
	aa := datum.a
	bb := datum.b

	e2 := (aa*aa - bb*bb) / (aa * aa) // 1st eccentricity squared
	ε2 := (aa*aa - bb*bb) / (bb * bb) // 2nd eccentricity squared
	p := math.Sqrt(v.x*v.x + v.y*v.y) // distance from minor axis
	R := math.Sqrt(p*p + v.z*v.z)     // polar radius

	// parametric latitude
	tanβ := (bb * v.z) / (aa * p) * (1 + ε2*b/R)
	sinβ := tanβ / math.Sqrt(1+tanβ*tanβ)
	cosβ := sinβ / tanβ

	// geodetic latitude
	φ := math.Atan2(v.z+ε2*bb*sinβ*sinβ*sinβ, p-e2*aa*cosβ*cosβ*cosβ)

	// longitude
	λ := math.Atan2(v.y, v.x)

	coords := Coordinates{
		Lat: toDegrees(φ),
		Lon: toDegrees(λ),
	}

	return coords
}
// Andoyer computes approximate geodesic distance between two
// points p1 and p2 on the spheroid s.
// Computations use Andoyer-Lambert first order (in flattening) approximation.
//
// Reference: P.D. Thomas, Mathematical Models for Navigation Systems, TR-182,
// US Naval Oceanographic Office (1965).
func Andoyer(s *Spheroid, p1, p2 LL) float64 {
	a, f := s.A(), s.F()
	lat1, lon1 := p1.LatLon()
	lat2, lon2 := p2.LatLon()

	F, G := (lat1+lat2)/2.0, (lat1-lat2)/2.0
	L := math.Remainder(lon1-lon2, 360.0) / 2.0
	sinF, cosF := math.Sincos((math.Pi / 180.0) * F)
	sinG, cosG := math.Sincos((math.Pi / 180.0) * G)
	sinL, cosL := math.Sincos((math.Pi / 180.0) * L)

	S2 := sq(sinG*cosL) + sq(cosF*sinL)
	C2 := sq(cosG*cosL) + sq(sinF*sinL)
	S, C := math.Sqrt(S2), math.Sqrt(C2)

	omega := math.Atan2(S, C)
	R := (S * C) / omega
	D := 2.0 * omega * a
	H1 := (3.0*R - 1.0) / (2.0 * C2)
	H2 := (3.0*R + 1.0) / (2.0 * S2)
	dist := D * (1.0 + f*(H1*sq(sinF*cosG)-H2*sq(cosF*sinG)))

	if finite(dist) {
		return dist
	}

	// Antipodal points.
	if finite(R) {
		return 2.0 * s.Quad()
	}

	// Identical points.
	return 0.0
}
Exemple #27
0
// https://stackoverflow.com/questions/5971830/need-code-for-inverse-error-function
func erfinv(y float64) float64 {
	if y < -1.0 || y > 1.0 {
		panic("invalid input")
	}

	var (
		a = [4]float64{0.886226899, -1.645349621, 0.914624893, -0.140543331}
		b = [4]float64{-2.118377725, 1.442710462, -0.329097515, 0.012229801}
		c = [4]float64{-1.970840454, -1.624906493, 3.429567803, 1.641345311}
		d = [2]float64{3.543889200, 1.637067800}
	)

	const y0 = 0.7
	var x, z float64

	if math.Abs(y) == 1.0 {
		x = -y * math.Log(0.0)
	} else if y < -y0 {
		z = math.Sqrt(-math.Log((1.0 + y) / 2.0))
		x = -(((c[3]*z+c[2])*z+c[1])*z + c[0]) / ((d[1]*z+d[0])*z + 1.0)
	} else {
		if y < y0 {
			z = y * y
			x = y * (((a[3]*z+a[2])*z+a[1])*z + a[0]) / ((((b[3]*z+b[3])*z+b[1])*z+b[0])*z + 1.0)
		} else {
			z = math.Sqrt(-math.Log((1.0 - y) / 2.0))
			x = (((c[3]*z+c[2])*z+c[1])*z + c[0]) / ((d[1]*z+d[0])*z + 1.0)
		}
		x = x - (math.Erf(x)-y)/(2.0/math.SqrtPi*math.Exp(-x*x))
		x = x - (math.Erf(x)-y)/(2.0/math.SqrtPi*math.Exp(-x*x))
	}

	return x
}
Exemple #28
0
func delayGPS(source string, destination string) (int, error) {
	src := strings.Split(source, "/")
	lat1, err := strconv.ParseFloat(src[0], 64)
	if err != nil {
		return -1, err
	}

	lon1, err := strconv.ParseFloat(src[1], 64)
	if err != nil {
		return -1, err
	}

	dest := strings.Split(destination, "/")
	lat2, err := strconv.ParseFloat(dest[0], 64)
	if err != nil {
		return -1, err
	}

	lon2, err := strconv.ParseFloat(dest[1], 64)
	if err != nil {
		return -1, err
	}

	radius := float64(6371)

	dlat := (lat2 - lat1) / (180 / math.Pi)
	dlon := (lon2 - lon1) / (180 / math.Pi)

	a := math.Sin(dlat/2)*math.Sin(dlat/2) + math.Cos(lat1/(180*math.Pi))*math.Cos(lat2/(180*math.Pi))*math.Sin(dlon/2)*math.Sin(dlon/2)
	c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
	d := radius * c
	speed := float64(139)

	return int(math.Floor(d/speed + 0.5)), nil
}
Exemple #29
0
/* ToECEF takes the latitude, longitude, elevation list and
   returns three cartesian coordinates x, y, z */
func (ellipsoid Ellipsoid) ToECEF(lat1, lon1, alt1 float64) (x, y, z float64) {
	a := ellipsoid.Ellipse.Equatorial
	f := 1 / ellipsoid.Ellipse.InvFlattening

	b := a * (1.0 - f)
	e := math.Sqrt((a*a - b*b) / (a * a))
	esq := e * e // e squared

	if ellipsoid.Units == Degrees {
		lat1 = deg2rad(lat1)
		lon1 = deg2rad(lon1)
	}

	h := alt1 // renamed for convenience
	phi := lat1
	lambda := lon1

	cphi := math.Cos(phi)
	sphi := math.Sin(phi)
	sphisq := sphi * sphi
	clam := math.Cos(lambda)
	slam := math.Sin(lambda)
	N := a / (math.Sqrt(1 - esq*sphisq))
	x = (N + h) * cphi * clam
	y = (N + h) * cphi * slam
	z = ((b*b*N)/(a*a) + h) * sphi

	return x, y, z
}
Exemple #30
0
func sqrt(x float64) string {
	if x < 0 {
		return fmt.Sprint(math.Sqrt(-x)) + "i"
	}

	return fmt.Sprint(math.Sqrt(x))
}