func EaseInOutElastic(start, end, value float32) float32 { end -= start var d float32 = 1.0 var p float32 = d * 0.3 var s float32 = 0.0 var a float32 = 0.0 if value == 0 { return start } value /= d if value == 1 { return start + end } if a == 0 || a < float32(math.Abs(float64(end))) { a = end s = p / 4 } else { s = p / (2 * float32(math.Pi)) * float32(math.Asin(float64(end/a))) } if value < 1 { return -0.5*(a*float32(math.Pow(2, 10*(float64(value)-1)))*float32(math.Sin(float64((value*d-s)*(2*math.Pi)/p)))) + start } return a*float32(math.Pow(2, -10*(float64(value)-1)))*float32(math.Sin(float64((value*d-s)*(2*math.Pi)/p)))*0.5 + end + start }
func f(x, y float64) float64 { v := math.Pow(2.0, math.Sin(y)) * math.Pow(2.0, math.Sin(x)) / 12 if math.IsNaN(v) { return 0 } return v }
// Lp Norm of an array, given p >= 1 func LPNorm(vector []float64, p float64) (float64, error) { distance := 0. for _, jj := range vector { distance += math.Pow(math.Abs(jj), p) } return math.Pow(distance, 1/p), nil }
func (r *Richard) SimPearson(v1, v2 InnerStruct) float64 { common := r.CommonKeys(v1, v2) n := float64(len(common)) if n == 0 { return 0 } var sum1, sum2, sumsq1, sumsq2, sump float64 for key, _ := range common { sum1 += v1[key] sumsq1 += math.Pow(v1[key], 2) sum2 += v2[key] sumsq2 += math.Pow(v2[key], 2) sump += v1[key] * v2[key] } num := sump - ((sum1 * sum2) / n) den := math.Sqrt((sumsq1 - (math.Pow(sum1, 2))/n) * (sumsq2 - (math.Pow(sum2, 2))/n)) if den == 0 { return 0 } return num / den }
func p205() { // p can score from 9 to 36 pScoresSum := make(map[int]int) throw(4, 9, 0, pScoresSum) pScoresProb := make(map[int]float64) pTot := math.Pow(4.0, 9.0) for id, cnt := range pScoresSum { pScoresProb[id] = float64(cnt) / pTot } cScoresSum := make(map[int]int) throw(6, 6, 0, cScoresSum) cTot := math.Pow(6.0, 6.0) cScoresProb := make(map[int]float64) for id, cnt := range cScoresSum { cScoresProb[id] = float64(cnt) / cTot } // P(p wins) // = P( p has x ) * P( c has less than x) // = P(p has x) * (P(c has x-1) + P(c has x-2) + ... + P(c has 1)) pWinProb := 0.0 for pScore := 9; pScore <= 36; pScore++ { probCLower := 0.0 for cScore := 6; cScore < pScore; cScore++ { probCLower += cScoresProb[cScore] } pWinProb += pScoresProb[pScore] * probCLower } //bruteForce() fmt.Printf("Prob P Wins %.7f\n", pWinProb) }
func main() { var list list.List scanner := bufio.NewScanner(os.Stdin) p := getNumber(scanner) q := getNumber(scanner) for i := p; i <= q; i++ { square := i * i squareStr := strconv.Itoa(square) mid := len(squareStr) / 2 power := float64(len(squareStr) - mid) rem := square % int(math.Pow(10, power)) quo := square / int(math.Pow(10, power)) sum := rem + quo if sum == i { list.PushBack(i) } } if list.Len() <= 0 { fmt.Println("INVALID RANGE") } else { for e := list.Front(); e != nil; e = e.Next() { fmt.Printf("%d ", e.Value) } } }
// Distance computes the L-norm of s - t. See Norm for special cases. // A panic will occur if the lengths of s and t do not match. func Distance(s, t []float64, L float64) float64 { if len(s) != len(t) { panic("floats: slice lengths do not match") } if len(s) == 0 { return 0 } var norm float64 if L == 2 { for i, v := range s { diff := t[i] - v norm = math.Hypot(norm, diff) } return norm } if L == 1 { for i, v := range s { norm += math.Abs(t[i] - v) } return norm } if math.IsInf(L, 1) { for i, v := range s { absDiff := math.Abs(t[i] - v) if absDiff > norm { norm = absDiff } } return norm } for i, v := range s { norm += math.Pow(math.Abs(t[i]-v), L) } return math.Pow(norm, 1/L) }
func PixelDistance(image image.Image, x, y int, r, g, b, a uint32) float64 { if x < image.Bounds().Min.X || y < image.Bounds().Min.Y || x > image.Bounds().Max.X || y > image.Bounds().Max.Y { log.Printf("Invalid pixel at %d, %d", x, y) return 0.0 } targetR, targetG, targetB, targetA := image.At(x, y).RGBA() distance := 0.0 distance += math.Pow(float64(r-targetR), 2) if math.IsNaN(distance) { log.Printf("Distance is NaN after red at %d, %d", x, y) } distance += math.Pow(float64(g-targetG), 2) if math.IsNaN(distance) { log.Printf("Distance is NaN after green at %d, %d", x, y) } distance += math.Pow(float64(b-targetB), 2) if math.IsNaN(distance) { log.Printf("Distance is NaN after blue at %d, %d", x, y) } distance += math.Pow(float64(a-targetA), 2) if math.IsNaN(distance) { log.Printf("Distance is NaN after alpha at %d, %d", x, y) } distance = math.Sqrt(distance) if math.IsNaN(distance) { log.Printf("Distance is NaN after sqrt at %d, %d", x, y) } return distance }
// ScoreFit is used to score the fit based on the Google work published here: // http://www.columbia.edu/~cs2035/courses/ieor4405.S13/datacenter_scheduling.ppt // This is equivalent to their BestFit v3 func ScoreFit(node *Node, util *Resources) float64 { // Determine the node availability nodeCpu := float64(node.Resources.CPU) if node.Reserved != nil { nodeCpu -= float64(node.Reserved.CPU) } nodeMem := float64(node.Resources.MemoryMB) if node.Reserved != nil { nodeMem -= float64(node.Reserved.MemoryMB) } // Compute the free percentage freePctCpu := 1 - (float64(util.CPU) / nodeCpu) freePctRam := 1 - (float64(util.MemoryMB) / nodeMem) // Total will be "maximized" the smaller the value is. // At 100% utilization, the total is 2, while at 0% util it is 20. total := math.Pow(10, freePctCpu) + math.Pow(10, freePctRam) // Invert so that the "maximized" total represents a high-value // score. Because the floor is 20, we simply use that as an anchor. // This means at a perfect fit, we return 18 as the score. score := 20.0 - total // Bound the score, just in case // If the score is over 18, that means we've overfit the node. if score > 18.0 { score = 18.0 } else if score < 0 { score = 0 } return score }
func main() { i := 1 for i <= 10 { fmt.Println(i, math.Pow(2, float64(i)), math.Pow(2, 1/float64(i))) i = i + 1 } // A more standard initial condition, iterate to final condition loop for j := 3; j <= 9; j++ { fmt.Println(j * j) } k := 1 for { if k > 8 { fmt.Println("k equals", k, "and the loop stops NOW!") break } else if k == 5 { fmt.Println("k equals", k, "?! That's just swell!") k++ } else { fmt.Println("k equals", k, "and the loop goes around again...") k++ } } }
// Estimate runtime for job func (m *Machine) ETA() time.Duration { var eta time.Duration var lx, ly, lz float64 for _, pos := range m.Positions { feed := pos.State.Feedrate if feed <= 0 { // Just to use something... feed = 300 } // Convert from minutes to microseconds feed /= 60000000 switch pos.State.MoveMode { case MoveModeNone: continue case MoveModeRapid: // This is silly, but it gives something to calculate with feed *= 8 case MoveModeDwell: eta += time.Duration(pos.State.DwellTime) * time.Second continue } dx, dy, dz := pos.X-lx, pos.Y-ly, pos.Z-lz lx, ly, lz = pos.X, pos.Y, pos.Z dist := math.Sqrt(math.Pow(dx, 2) + math.Pow(dy, 2) + math.Pow(dz, 2)) eta += time.Duration(dist/feed) * time.Microsecond } return eta }
// This method finds the closest color for a given RGB tuple and returns the name of the color in given mode func FindClosestColor(RequestedColor []int, mode string) string { MinColors := make(map[int]string) var ColorMap map[string]string // css3 gives the shades while css21 gives the primary or base colors if mode == "css3" { ColorMap = gwc.CSS3NamesToHex } else { ColorMap = gwc.HTML4NamesToHex } for name, hexcode := range ColorMap { rgb_triplet := gwc.HexToRGB(hexcode) rd := math.Pow(float64(rgb_triplet[0]-RequestedColor[0]), float64(2)) gd := math.Pow(float64(rgb_triplet[1]-RequestedColor[1]), float64(2)) bd := math.Pow(float64(rgb_triplet[2]-RequestedColor[2]), float64(2)) MinColors[int(rd+gd+bd)] = name } keys := make([]int, 0, len(MinColors)) for key := range MinColors { keys = append(keys, key) } sort.Ints(keys) return MinColors[keys[0]] }
func qk(k, n, p float64) float64 { result := 1.0 for i := 1.0; i <= k; i++ { result *= (1.0 - math.Pow(1.0-math.Pow(2, -i), n)*(1.0-p)) } return result }
func TestGoertzel(t *testing.T) { samplerate := 1024 blocksize := 1024 freq := 128 samples := make([]float64, blocksize) w := 2 * math.Pi / float64(samplerate) for i := 0; i < blocksize; i++ { samples[i] = math.Sin(float64(i) * float64(freq) * w) } g := NewGoertzel([]uint64{128, 129}, samplerate, blocksize) g.Feed(samples) m := g.Magnitude() if e := math.Pow(float64(blocksize)/2, 2); !approxEqual(m[0], e, 1e-8) { t.Errorf("Goertzel magnitude = %f. Want %f", m[0], e) } if !approxEqual(float64(m[1]), 0.0, 1e-10) { t.Errorf("Foertzel magnitude = %f. Want 0.0", m[1]) } c := g.Complex() if e, m := math.Sqrt(math.Pow(float64(blocksize)/2, 2)), cmplx.Abs(complex128(c[0])); !approxEqual(m, e, 1e-8) { t.Errorf("Goertzel magnitude = %f. Want %f", m, e) } if e, p := -math.Pi/2, cmplx.Phase(complex128(c[0])); !approxEqual(p, e, 1e-12) { t.Errorf("Goertzel phase = %f. Want %f", p, e) } }
// ExponentialRegression returns an exponential regression on data series func ExponentialRegression(s Series) (regressions Series, err error) { if len(s) == 0 { return nil, errors.New("Input must not be empty") } var sum [6]float64 for i := 0; i < len(s); i++ { sum[0] += s[i].X sum[1] += s[i].Y sum[2] += s[i].X * s[i].X * s[i].Y sum[3] += s[i].Y * math.Log(s[i].Y) sum[4] += s[i].X * s[i].Y * math.Log(s[i].Y) sum[5] += s[i].X * s[i].Y } denominator := (sum[1]*sum[2] - sum[5]*sum[5]) a := math.Pow(math.E, (sum[2]*sum[3]-sum[5]*sum[4])/denominator) b := (sum[1]*sum[4] - sum[5]*sum[3]) / denominator for j := 0; j < len(s); j++ { regressions = append(regressions, Coordinate{ X: s[j].X, Y: a * math.Pow(2.718281828459045, b*s[j].X), }) } return regressions, nil }
// ElasticInOut Acceleration until halfway, then deceleration func ElasticInOut(t, b, c, d float64) float64 { if t > d { return c } s := math.SqrtPi p := d * (0.3 * 1.5) a := c if t == 0 { return b } t /= d / 2 if t == 2 { return b + c } if a < math.Abs(c) { s = p / 4 } else { s = p / DoublePi * math.Asin(c/a) } t-- if t < 0 { return -0.5*(a*math.Pow(2, 10*t)*math.Sin((t*d-s)*DoublePi/p)) + b } return a*math.Pow(2, -10*t)*math.Sin((t*d-s)*DoublePi/p)*0.5 + c + b }
func (a *activeSet) pruneLinearlyDependent(grad linalg.Vector) bool { var biggestViolation float64 var violationI, violationJ int for i := 0; i < len(a.Constraints)-1; i++ { iConstraint := float64(a.Constraints[i]) for j := i + 1; j < len(a.Constraints); j++ { jConstraint := float64(a.Constraints[j]) signVec := [2]float64{a.SignVec[i], a.SignVec[j]} gradVec := [2]float64{grad[i], grad[j]} gradDot := gradVec[0]*signVec[0] + gradVec[1]*signVec[1] k := -gradDot / 2.0 gradProj := [2]float64{gradVec[0] + k*signVec[0], gradVec[1] + k*signVec[1]} if gradProj[0]*iConstraint < 0 && gradProj[1]*jConstraint < 0 { gradProjMag := math.Pow(gradProj[0], 2) + math.Pow(gradProj[1], 2) if gradProjMag >= biggestViolation || violationJ == 0 { biggestViolation = gradProjMag violationI = i violationJ = j } } } } if violationJ > 0 { a.Constraints[violationI] = 0 a.Constraints[violationJ] = 0 return true } return false }
/* * matrix is the input matrix of integers * */ func (ts *TravellingSalesman) Init(matrix [][]int) { // Find locations and coordinates coords := map[int][2]int{} for i := range matrix { for j := range matrix[i] { if matrix[i][j] != 0 { value := matrix[i][j] coords[value] = [2]int{i + 1, j + 1} } } } // Gene length equals the number of coordinates ts.geneLength = len(coords) // Calculate distances var size = ts.geneLength ts.distMatrix = util.NewDistanceMatrix(ts.geneLength) for i := 0; i < size*size; i++ { row := i % size col := i / size area1 := coords[row+1] // X coordinate (Row) area2 := coords[col+1] // Y coordinate (Column) if area1[0] == area2[0] { // Same Column so distance eq diff(row2-row1) ts.distMatrix.SetDistance( row, col, math.Abs(float64(area2[1]-area1[1]))) } else if area1[1] == area2[1] { // Same Row so distance eq diff(col2-col1) ts.distMatrix.SetDistance( row, col, math.Abs(float64(area2[0]-area1[0]))) } else { a := math.Pow(float64(area2[1]-area1[1]), 2) b := math.Pow(float64(area2[0]-area1[0]), 2) c := math.Sqrt(a + b) ts.distMatrix.SetDistance(row, col, c) } //fmt.Printf("%d -> %d: %f\n", row+1, col+1, ts.distMatrix.GetDistance(row,col)) } // Generate random genes ts.genes = make([]ga.Gene, ts.nGenes) var proto = make([]int, ts.geneLength) var i int = 0 for key, _ := range coords { proto[i] = key i++ } // Initialize all len(genes) and shuffle for i := 0; i < len(ts.genes); i++ { ts.genes[i].Data = make([]int, len(proto)) copy(ts.genes[i].Data, proto) shuffleArray(&(ts.genes[i].Data)) } }
func Test_brent01(tst *testing.T) { //verbose() chk.PrintTitle("brent01. root finding") ffcnA := func(x float64) (res float64, err error) { res = math.Pow(x, 3.0) - 0.165*math.Pow(x, 2.0) + 3.993e-4 return } ffcnB := func(fx, x []float64) (err error) { fx[0], err = ffcnA(x[0]) return } JfcnB := func(dfdx [][]float64, x []float64) (err error) { dfdx[0][0] = 3.0*x[0]*x[0] - 2.0*0.165*x[0] return } xa, xb := 0.0, 0.11 //xguess := 0.001 // ===> this one converges to the right-hand solution xguess := 0.03 //save := true save := false run_rootsol_test(tst, xa, xb, xguess, 1e-7, ffcnA, ffcnB, JfcnB, "brent01.png", save, false) }
func ExampleDrawer_floydSteinberg() { const width = 130 const height = 50 im := image.NewGray(image.Rectangle{Max: image.Point{X: width, Y: height}}) for x := 0; x < width; x++ { for y := 0; y < height; y++ { dist := math.Sqrt(math.Pow(float64(x-width/2), 2)/3+math.Pow(float64(y-height/2), 2)) / (height / 1.5) * 255 var gray uint8 if dist > 255 { gray = 255 } else { gray = uint8(dist) } im.SetGray(x, y, color.Gray{Y: 255 - gray}) } } pi := image.NewPaletted(im.Bounds(), []color.Color{ color.Gray{Y: 255}, color.Gray{Y: 160}, color.Gray{Y: 70}, color.Gray{Y: 35}, color.Gray{Y: 0}, }) draw.FloydSteinberg.Draw(pi, im.Bounds(), im, image.ZP) shade := []string{" ", "░", "▒", "▓", "█"} for i, p := range pi.Pix { fmt.Print(shade[p]) if (i+1)%width == 0 { fmt.Print("\n") } } }
// Norm returns the L norm of the slice S, defined as // (sum_{i=1}^N s[i]^L)^{1/L} // Special cases: // L = math.Inf(1) gives the maximum absolute value. // Does not correctly compute the zero norm (use Count). func Norm(s []float64, L float64) float64 { // Should this complain if L is not positive? // Should this be done in log space for better numerical stability? // would be more cost // maybe only if L is high? if len(s) == 0 { return 0 } if L == 2 { twoNorm := math.Abs(s[0]) for i := 1; i < len(s); i++ { twoNorm = math.Hypot(twoNorm, s[i]) } return twoNorm } var norm float64 if L == 1 { for _, val := range s { norm += math.Abs(val) } return norm } if math.IsInf(L, 1) { for _, val := range s { norm = math.Max(norm, math.Abs(val)) } return norm } for _, val := range s { norm += math.Pow(math.Abs(val), L) } return math.Pow(norm, 1/L) }
func (t triangle) getThirdSide() float64 { a := t.sides[0] b := t.sides[1] c2 := math.Pow(a, 2) + math.Pow(b, 2) - 2*a*b*math.Cos(t.angle) c := math.Sqrt(c2) return c }
func ExpOut(value, power float32) Interpolation { min := float32(math.Pow(float64(value), float64(-power))) scale := float32(1 / (1 - min)) return func(a float32) float32 { return 1 - (float32(math.Pow(float64(value), float64(-power*a-min))))*scale } }
// StyblinskiTang minimum is -39.16599d reached in (-2.903534, ..., -2.903534) // Recommended search domain is [-5, 5] func styblinskiTang(X []float64) float64 { sum := 0.0 for _, x := range X { sum += m.Pow(x, 4) - 16*m.Pow(x, 2) + 5*x } return sum / 2 }
func (hb *Rectangle) intersects(center *terrain.Position, other Hitbox, otherCenter *terrain.Position) (intersects bool, err error) { switch o := other.(type) { case *Rectangle: b1 := hb.bounds(center) b2 := o.bounds(otherCenter) intersects = (b1[0].X <= b2[1].X && b1[1].X >= b2[0].X && b1[0].Y <= b2[1].Y && b1[1].Y >= b2[0].Y) case *Circle: // See http://stackoverflow.com/a/402010 bounds := hb.bounds(center) dx := math.Abs(otherCenter.X - bounds[0].X) dy := math.Abs(otherCenter.Y - bounds[0].Y) if dx > hb.width/2+o.radius || dy > hb.height/2+o.radius { intersects = false } else if dx <= hb.width/2 || dy <= hb.height/2 { intersects = true } else { dc := math.Pow(dx-hb.width/2, 2) + math.Pow(dy-hb.height/2, 2) intersects = (dc <= math.Pow(o.radius, 2)) } default: err = errUnsupportedHitbox } return }
// http://www.easyrgb.com/index.php?X=MATH func xyzToLabAB(x, y, z float64) (float64, float64, float64) { normalizedX := x / 95.047 normalizedY := y / 100.0 normalizedZ := z / 108.883 if normalizedX > 0.008856 { normalizedX = math.Pow(normalizedX, (1.0 / 3.0)) } else { normalizedX = (7.787 * normalizedX) + (16.0 / 116.0) } if normalizedY > 0.008856 { normalizedY = math.Pow(normalizedY, (1.0 / 3.0)) } else { normalizedY = (7.787 * normalizedY) + (16.0 / 116.0) } if normalizedZ > 0.008856 { normalizedZ = math.Pow(normalizedZ, (1.0 / 3.0)) } else { normalizedZ = (7.787 * normalizedZ) + (16.0 / 116.0) } l := (116 * normalizedY) - 16 a := 500 * (normalizedX - normalizedY) b := 200 * (normalizedY - normalizedZ) return l, a, b }
// 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 }
// http://www.easyrgb.com/index.php?X=MATH func rgbToXyz(r, g, b uint32) (float64, float64, float64) { normalizedR := float64(r) / 0xFFFF normalizedG := float64(g) / 0xFFFF normalizedB := float64(b) / 0xFFFF if normalizedR > 0.04045 { normalizedR = math.Pow(((normalizedR + 0.055) / 1.055), 2.4) } else { normalizedR = normalizedR / 12.92 } if normalizedG > 0.04045 { normalizedG = math.Pow(((normalizedG + 0.055) / 1.055), 2.4) } else { normalizedG = normalizedG / 12.92 } if normalizedB > 0.04045 { normalizedB = math.Pow(((normalizedB + 0.055) / 1.055), 2.4) } else { normalizedB = normalizedB / 12.92 } normalizedR *= 100 normalizedG *= 100 normalizedB *= 100 x := normalizedR*0.4124 + normalizedG*0.3576 + normalizedB*0.1805 y := normalizedR*0.2126 + normalizedG*0.7152 + normalizedB*0.0722 z := normalizedR*0.0193 + normalizedG*0.1192 + normalizedB*0.9505 return x, y, z }
// p-norm distance with weights (weighted l_p distance) func WeightedMinkowskiDistance(firstVector, secondVector, weightVector []float64, p float64) (float64, error) { distance := 0. for ii := range firstVector { distance += weightVector[ii] * math.Pow(math.Abs(firstVector[ii]-secondVector[ii]), p) } return math.Pow(distance, 1/p), nil }
func deltafov(uId uint32, r, dx, dy float64) { //TODO unit := Units[uId] for i, u := range Units { if fovUnits[uId][i] { continue } if math.Pow(u.X.A-unit.X.A-dx, 2)+math.Pow(u.Y.A-unit.Y.A-dy, 2) <= r { fovUnits[uId][i] = true u.X.SetInform(unit.Owner.A) u.Y.SetInform(unit.Owner.A) //I see him now } } for k, v := range fovUnits[uId] { if !v { continue } if math.Pow(Units[k].X.A-unit.X.A-dx, 2)+math.Pow(Units[k].Y.A-unit.Y.A-dy, 2) > r { fovUnits[uId][k] = false Units[k].X.inform[unit.Owner.A]-- if Units[k].X.inform[unit.Owner.A] <= 0 { delete(Units[k].X.inform, unit.Owner.A) } Units[k].Y.inform[unit.Owner.A]-- if Units[k].Y.inform[unit.Owner.A] <= 0 { delete(Units[k].Y.inform, unit.Owner.A) } //I don't see him anymore } } }