// exitAxis reports which axis the directed line L exits the cube face F on. // The directed line L is represented by its CCW normal N in the (u,v,w) coordinates // of F. It returns axisU if L exits through the u=-1 or u=+1 edge, and axisV if L exits // through the v=-1 or v=+1 edge. Either result is acceptable if L exits exactly // through a corner vertex of the cube face. func (p pointUVW) exitAxis() axis { if p.intersectsOppositeEdges() { // The line passes through through opposite edges of the face. // It exits through the v=+1 or v=-1 edge if the u-component of N has a // larger absolute magnitude than the v-component. if math.Abs(p.X) >= math.Abs(p.Y) { return axisV } return axisU } // The line passes through through two adjacent edges of the face. // It exits the v=+1 or v=-1 edge if an even number of the components of N // are negative. We test this using signbit() rather than multiplication // to avoid the possibility of underflow. var x, y, z int if math.Signbit(p.X) { x = 1 } if math.Signbit(p.Y) { y = 1 } if math.Signbit(p.Z) { z = 1 } if x^y^z == 0 { return axisV } return axisU }
//'true' if opposite signs; false otherwise func opp(x float64, y float64) bool { if math.Signbit(x) == math.Signbit(y) { return false } else { return true } }
// randomSchurCanonical returns a random, general matrix in Schur canonical // form, that is, block upper triangular with 1×1 and 2×2 diagonal blocks where // each 2×2 diagonal block has its diagonal elements equal and its off-diagonal // elements of opposite sign. func randomSchurCanonical(n, stride int, rnd *rand.Rand) blas64.General { t := randomGeneral(n, n, stride, rnd) // Zero out the lower triangle. for i := 0; i < t.Rows; i++ { for j := 0; j < i; j++ { t.Data[i*t.Stride+j] = 0 } } // Randomly create 2×2 diagonal blocks. for i := 0; i < t.Rows; { if i == t.Rows-1 || rnd.Float64() < 0.5 { // 1×1 block. i++ continue } // 2×2 block. // Diagonal elements equal. t.Data[(i+1)*t.Stride+i+1] = t.Data[i*t.Stride+i] // Off-diagonal elements of opposite sign. c := rnd.NormFloat64() if math.Signbit(c) == math.Signbit(t.Data[i*t.Stride+i+1]) { c *= -1 } t.Data[(i+1)*t.Stride+i] = c i += 2 } return t }
func sameValue(x Value, y Value) bool { if x.kind != y.kind { return false } result := false switch x.kind { case valueUndefined, valueNull: result = true case valueNumber: x := x.float64() y := y.float64() if math.IsNaN(x) && math.IsNaN(y) { result = true } else { result = x == y if result && x == 0 { // Since +0 != -0 result = math.Signbit(x) == math.Signbit(y) } } case valueString: result = x.string() == y.string() case valueBoolean: result = x.bool() == y.bool() case valueObject: result = x._object() == y._object() default: panic(hereBeDragons()) } return result }
// Creates knockback for a vehicle func (p *Physics) VehicleKnockback(vehicle *state.Vehicle, kbAngle, kbVelocity float64) { // Get vehicle velocity vectors vehAngleX, vehAngleY := splitComponent(vehicle.Angle) vehVectorX := vehAngleX * vehicle.Velocity vehVectorY := vehAngleY * vehicle.Velocity // Get knockback velocity vectors kbAngleX, kbAngleY := splitComponent(kbAngle) kbVectorX := kbAngleX * kbVelocity kbVectorY := kbAngleY * kbVelocity // Combine vectors vectorX := vehVectorX + kbVectorX vectorY := vehVectorY + kbVectorY vehVelocity := combineComponents(vectorX, vectorY) // Calculate angle perpendicularity as a percent angleFactor := math.Mod(math.Abs(vehicle.Angle-kbAngle+90), 180) / 90.0 // Set vehicle velocity if math.Signbit(vehicle.Velocity) == math.Signbit(vehVelocity) { vehicle.Velocity = -vehVelocity * angleFactor } else { vehicle.Velocity = vehVelocity * angleFactor } }
func (f *andFeature) Predict(e Example) float64 { if !math.Signbit(f.f1.Predict(e)) && !math.Signbit(f.f2.Predict(e)) { return 1.0 } else { return -1.0 } }
// CombineClusters combines freshly found clusters with existing clusters. // // Algorithm: // Run clustering and pick out the "Interesting" clusters. // Compare all the Interesting clusters to all the existing relevant clusters, // where "relevant" clusters are ones whose Hash/timestamp of the step // exists in the current tile. // Start with an empty "list". // For each cluster: // For each relevant existing cluster: // Take the top 20 keys from the existing cluster and count how many appear // in the cluster. // If there are no matches then this is a new cluster, add it to the "list". // If there are matches, possibly to multiple existing clusters, find the // existing cluster with the most matches. // Take the cluster (old/new) with the most members, or the best fit if // they have the same number of matches. // Return all the updated clusters. func CombineClusters(freshSummaries, oldSummaries []*types.ClusterSummary) []*types.ClusterSummary { ret := []*types.ClusterSummary{} stillFresh := []*types.ClusterSummary{} // If two cluster summaries have the same hash and same Regression direction // then they are the same, merge them together. for _, fresh := range freshSummaries { for _, old := range oldSummaries { if fresh.Hash == old.Hash && math.Signbit(fresh.StepFit.Regression) == math.Signbit(old.StepFit.Regression) { old.Merge(fresh) ret = append(ret, old) break } } stillFresh = append(stillFresh, fresh) } // Even if a summary has a different hash it might still be the same event if // there is an overlap in the traces each summary contains. for _, fresh := range stillFresh { var bestMatch *types.ClusterSummary = nil bestMatchHits := 0 for _, old := range oldSummaries { hits := 0 for _, key := range util.AtMost(old.Keys, 20) { if util.In(key, fresh.Keys) { hits += 1 } } if hits > bestMatchHits { bestMatchHits = hits bestMatch = old } } if bestMatch != nil { keysLengthEqual := len(fresh.Keys) == len(bestMatch.Keys) regressionInSameDirection := math.Signbit(fresh.StepFit.Regression) == math.Signbit(bestMatch.StepFit.Regression) freshHasBetterFit := math.Abs(fresh.StepFit.Regression) > math.Abs(bestMatch.StepFit.Regression) freshHasMoreKeys := len(fresh.Keys) > len(bestMatch.Keys) if freshHasMoreKeys || (keysLengthEqual && regressionInSameDirection && freshHasBetterFit) { fresh.Status = bestMatch.Status fresh.Message = bestMatch.Message fresh.ID = bestMatch.ID fresh.Bugs = bestMatch.Bugs ret = append(ret, fresh) // Find the bestMatch in oldSummaries and replace it with fresh. for i, oldBest := range oldSummaries { if oldBest == bestMatch { oldSummaries[i] = fresh break } } } } else { ret = append(ret, fresh) } } return ret }
func alike(a, b float64) bool { switch { case math.IsNaN(a) && math.IsNaN(b): return true case a == b: return math.Signbit(a) == math.Signbit(b) } return false }
func cAlike(a, b complex128) bool { switch { case IsNaN(a) && IsNaN(b): return true case a == b: return math.Signbit(real(a)) == math.Signbit(real(b)) && math.Signbit(imag(a)) == math.Signbit(imag(b)) } return false }
// AreDifferent(x, y) bekaves like x != y, but sees NaN() as equal to NaN() func AreDifferent(x float64, y float64) bool { if math.IsNaN(x) && math.IsNaN(y) { return false } if x == y && math.Signbit(x) != math.Signbit(y) { // 0 != -0 return true } return x != y }
// EqualWithinULP returns true if a and b are equal to within // the specified number of floating point units in the last place. func EqualWithinULP(a, b float64, ulp uint) bool { if a == b { return true } if math.IsNaN(a) || math.IsNaN(b) { return false } if math.Signbit(a) != math.Signbit(b) { return math.Float64bits(math.Abs(a))+math.Float64bits(math.Abs(b)) <= uint64(ulp) } return ulpDiff(math.Float64bits(a), math.Float64bits(b)) <= uint64(ulp) }
func testPrefixBoundary(t *testing.T, scales []float64, prefixes string, mode int, wrap func(string) string) { var str, str1, str2, pre string var flt, fabs, fnum float64 var err error base := 1024.0 if mode == SI { base = 1000.0 } for _, sign := range []float64{-1, +1} { for i, f := range scales { // Round towards zero. str = FormatPrefix(math.Nextafter(sign*f, sign*ninf), mode, -1) flt, err = ParsePrefix(str, mode) fabs = math.Abs(flt) pre = string(prefixes[0]) if i > 0 { pre = string(prefixes[i-1]) } pre = wrap(pre) str1, str2 = split(str) fnum = math.Abs(atof(str1)) if i == 0 { assert.True(t, 1.0*loThres <= fnum && fnum <= 1.0) } else { assert.True(t, base*loThres <= fnum && fnum <= base) } assert.Equal(t, pre, str2) assert.True(t, f*loThres <= fabs && fabs <= f) assert.Equal(t, math.Signbit(flt), math.Signbit(sign)) assert.Equal(t, nil, err) // Round away from zero. str = FormatPrefix(math.Nextafter(sign*f, sign*pinf), mode, -1) flt, err = ParsePrefix(str, mode) fabs = math.Abs(flt) pre = wrap(string(prefixes[i])) str1, str2 = split(str) fnum = math.Abs(atof(str1)) assert.True(t, 1.0 <= fnum && fnum <= 1.0*hiThres) assert.Equal(t, pre, str2) assert.True(t, f <= fabs && fabs <= f*hiThres) assert.Equal(t, math.Signbit(flt), math.Signbit(sign)) assert.Equal(t, nil, err) } } }
func numberOperator(left, right tree.Result, f *xpFilt, op string) error { lt, lOK := left.(tree.IsNum) rt, rOK := right.(tree.IsNum) if !lOK || !rOK { return fmt.Errorf("Cannot convert data type to number") } ln, rn := lt.Num(), rt.Num() switch op { case "*": f.ctx = ln * rn case "div": if rn != 0 { f.ctx = ln / rn } else { if ln == 0 { f.ctx = tree.Num(math.NaN()) } else { if math.Signbit(float64(ln)) == math.Signbit(float64(rn)) { f.ctx = tree.Num(math.Inf(1)) } else { f.ctx = tree.Num(math.Inf(-1)) } } } case "mod": f.ctx = tree.Num(int(ln) % int(rn)) case "+": f.ctx = ln + rn case "-": f.ctx = ln - rn case "=": f.ctx = tree.Bool(ln == rn) case "!=": f.ctx = tree.Bool(ln != rn) case "<": f.ctx = tree.Bool(ln < rn) case "<=": f.ctx = tree.Bool(ln <= rn) case ">": f.ctx = tree.Bool(ln > rn) case ">=": f.ctx = tree.Bool(ln >= rn) } return nil }
// convert float64 to int64 where f == i / 2^exp func float64ToIntExp(f float64) (i int64, exp int) { if f == 0 { return 0, 0 } isNegative := math.Signbit(f) f = math.Abs(f) machineEpsilon := math.Nextafter(1, 2) - 1 exp = 0 // really large float, bring down to within MaxInt64 for f > float64(math.MaxInt64) { f /= 2 exp-- } for !float64IsInt(f, machineEpsilon) { f *= 2 exp++ } if isNegative { f *= -1 } return int64(f), exp }
func genVolumeTable() { // 0/127 = -INFdB // 63/127 = -14dB // 127/127 = 0dB for n := uint8(0); n <= 127; n++ { db := MIDItoDB(n) //fmt.Printf("\"%+5.1f\", // %d == %d\n", db, n, dBtoMIDI(db)) posdb := math.Abs(db) // Represent as u16 in BCD: bcd0 := uint16((posdb - math.Floor(posdb)) * 10) bcd1 := uint16(((posdb / 10.0) - math.Floor(posdb/10.0)) * 10) bcd2 := uint16(((posdb / 100.0) - math.Floor(posdb/100.0)) * 10) var bcd3 uint16 if math.Signbit(db) { bcd3 = 0x0F } else { bcd3 = 0x00 } db10s := (bcd3 << 12) | (bcd2 << 8) | (bcd1 << 4) | bcd0 if math.IsInf(db, -1) { db10s = math.MaxUint16 } fmt.Printf("0x%04X, // %d\n", db10s, n) } }
func extractFeatures(examples []ml.Example) (features []ml.Feature) { features = nil featureDeDup := make(map[string]ml.Feature) for _, example := range examples { for word := range example.(*IssueExample).titleWords { feature := &titleFeature{word} featureDeDup[feature.String()] = feature } for word := range example.(*IssueExample).contentWords { feature := &contentFeature{word} featureDeDup[feature.String()] = feature } } minExamples := int(0.001 * float64(len(examples))) maxExamples := len(examples) for _, feature := range featureDeDup { count := 0 for _, example := range examples { if !math.Signbit(feature.Predict(example)) { count++ } } if minExamples <= count && count <= maxExamples { features = append(features, feature) } } return }
// Reference implementation of Drotg func refDrotg(a, b float64) (c, s, r, z float64) { roe := b if math.Abs(a) > math.Abs(b) { roe = a } scale := math.Abs(a) + math.Abs(b) if scale == 0 { c = 1 } else { r = scale * math.Sqrt((a/scale)*(a/scale)+(b/scale)*(b/scale)) if math.Signbit(roe) { r = -r } c = a / r s = b / r z = 1 if math.Abs(a) > math.Abs(b) { z = s } if math.Abs(b) >= math.Abs(a) && c != 0 { z = 1 / c } } return }
/* From LAPACK/dlarfg.f * * DLARFG generates a real elementary reflector H of order n, such * that * * H * ( alpha ) = ( beta ), H**T * H = I. * ( x ) ( 0 ) * * where alpha and beta are scalars, and x is an (n-1)-element real * vector. H is represented in the form * * H = I - tau * ( 1 ) * ( 1 v**T ) , * ( v ) * * where tau is a real scalar and v is a real (n-1)-element * vector. * * If the elements of x are all zero, then tau = 0 and H is taken to be * the unit matrix. * * Otherwise 1 <= tau <= 2. */ func computeHouseholder(a11, x, tau *matrix.FloatMatrix, flags Flags) { // norm_x2 = ||x||_2 norm_x2 := Norm2(x) if norm_x2 == 0.0 { //a11.SetAt(0, 0, -a11.GetAt(0, 0)) tau.SetAt(0, 0, 0.0) return } alpha := a11.GetAt(0, 0) sign := 1.0 if math.Signbit(alpha) { sign = -1.0 } // beta = -(alpha / |alpha|) * ||alpha x|| // = -sign(alpha) * sqrt(alpha**2, norm_x2**2) beta := -sign * sqrtX2Y2(alpha, norm_x2) // x = x /(a11 - beta) InvScale(x, alpha-beta) tau.SetAt(0, 0, (beta-alpha)/beta) a11.SetAt(0, 0, beta) }
func (n *FeatureNode) Predict(e Example) float64 { if math.Signbit(n.feature.Predict(e)) { return n.negative.Predict(e) } else { return n.positive.Predict(e) } }
func roundSliceDown(coord, slice float64) float64 { remainder := math.Mod(coord, slice) if math.Signbit(coord) { return coord - remainder } return coord - remainder + slice }
// Reference implementation of Srotg func refSrotg(a, b float32) (c, s, r, z float32) { roe := b if fabs(a) > fabs(b) { roe = a } scale := fabs(a) + fabs(b) if scale == 0 { c = 1 } else { r = scale * fsqrt((a/scale)*(a/scale)+(b/scale)*(b/scale)) if math.Signbit(float64(roe)) { r = -r } c = a / r s = b / r z = 1 if fabs(a) > fabs(b) { z = s } if fabs(b) >= fabs(a) && c != 0 { z = 1 / c } } return }
// SetFloat64 sets z to the (possibly rounded) value of x and returns z. // If z's precision is 0, it is changed to 53 (and rounding will have // no effect). SetFloat64 panics with ErrNaN if x is a NaN. func (z *Float) SetFloat64(x float64) *Float { if z.prec == 0 { z.prec = 53 } if math.IsNaN(x) { panic(ErrNaN{"Float.SetFloat64(NaN)"}) } z.acc = Exact z.neg = math.Signbit(x) // handle -0, -Inf correctly if x == 0 { z.form = zero return z } if math.IsInf(x, 0) { z.form = inf return z } // normalized x != 0 z.form = finite fmant, exp := math.Frexp(x) // get normalized mantissa z.mant = z.mant.setUint64(1<<63 | math.Float64bits(fmant)<<11) z.exp = int32(exp) // always fits if z.prec < 53 { z.round(0) } return z }
/* * 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 }
func (p placesByY) Less(i, j int) bool { diff := p.places[i].Center().Y - p.places[j].Center().Y if math.Abs(diff) > 1 { return math.Signbit(diff) } else { return p.places[i].Center().X > p.places[j].Center().X } }
// BinaryRoot finds a root between given bounds by binary search. // // Inputs are a function on x and the bounds on x. A root must exist between // the given bounds, otherwise the result is not meaningful. func BinaryRoot(f RootFunc, lower, upper float64) float64 { yLower := f(lower) var mid float64 for j := 0; j < 52; j++ { mid = (lower + upper) / 2 yMid := f(mid) if yMid == 0 { break } if math.Signbit(yLower) == math.Signbit(yMid) { lower = mid yLower = yMid } else { upper = mid } } return mid }
func evaluateClassifierWeighted(c Classifier, examples []Example, d *Distribution) float64 { misclassifications := 0.0 for i, example := range examples { if !math.Signbit(c.Predict(example)) != bool(example.Label()) { misclassifications += d.P[i] } } return misclassifications }
func (file *ClassificationFile) Accuracy(set *SVMFile) float64 { totalInstances := float64(len(set.Instances)) correctPreds := 0. if len(file.Results) <= len(set.Instances) { for i, res := range file.Results { if math.Signbit(float64(res)) == math.Signbit(float64(set.Instances[i].Label)) { correctPreds++ } } } else { for i, instance := range set.Instances { if math.Signbit(float64(file.Results[i])) == math.Signbit(float64(instance.Label)) { correctPreds++ } } } return correctPreds / totalInstances }
// Solves f(x) = 0 within a bracket (a,b) to precision eps. Terminates after a maximum of Nmax iterations. // Returns the solution and value of the function achieved or an error. func Bisection(f func(float64) float64, a, b, eps float64, Nmax int) (x, fx float64, err error) { if a == b { err = fmt.Errorf("Range (%g,%g) is zero", a, b) return } // a < b is requirement if a > b { a, b = b, a } fa := f(a) fb := f(b) // a and b must bracket root if math.Signbit(fa) == math.Signbit(fb) { err = fmt.Errorf("Interval does not bracket root: f(%g)=%g, f(%g)=%g", a, fa, b, fb) return } for i := 0; i < Nmax; i++ { x = 0.5 * (a + b) fx = f(x) // Found adequate solution if fx == 0 || 0.5*(b-a) < eps { return } // Calculate new interval if math.Signbit(fx) == math.Signbit(fa) { a = x fa = fx } else { b = x fb = fx } } err = fmt.Errorf("Exceeded iteration limit (%d)\n", Nmax) return }
func writeByteSortableFloat(b []byte, f float64) { if math.Signbit(f) { binary.BigEndian.PutUint64(b, math.Float64bits(f)) for i, v := range b[:8] { b[i] = v ^ 255 } } else { binary.BigEndian.PutUint64(b, math.Float64bits(-f)) } }
func TestComparison(t *testing.T) { Terst(t) test := runTest() test("undefined = 1") test("undefined", "1") test("result = undefined == undefined") test("result", "true") test("result = undefined != undefined") test("result", "false") test("result = null == null") test("result", "true") test("result = null != null") test("result", "false") test("result = 0 == 1") test("result", "false") Is(negativeZero(), "-0") Is(positiveZero(), "0") IsTrue(math.Signbit(negativeZero())) IsTrue(positiveZero() == negativeZero()) test("result = 1 == 1") test("result", "true") test("result = 'Hello, World.' == 'Goodbye, World.'") test("result", "false") test("result = 'Hello, World.' == true") test("result", "false") test("result = 'Hello, World.' == false") test("result", "false") test("result = 'Hello, World.' == 1") test("result", "false") test("result = 1 == 'Hello, World.'") test("result", "false") Is(stringToFloat("-1"), -1) if false { fmt.Printf("Hello, World.: %v", toNumber(toValue("Hello, World."))) } test("result = 0+Object") test("result", "0[function]") }