func TestRunSeries(z *testing.T) { assert := assert.New(z) var assertFloat = func(a, b float64) { if math.IsNaN(a) && math.IsNaN(b) { return // ok } assert.Equal(a, b) } tests := []Series{ {1, 2, 3, 4, 5}, {0.38809179, 0.94113008, 0.15350705, 0.03311646, 0.68168087, 0.21719990}, {0.32123922, 0.57085251, 0.53576882, 0.38965630, 0.27487263, 0.90783122}, {0, 0, 0, 0, 0}, {-1, -2, -3}, {}, } for _, t := range tests { var r Run for _, f := range t { r.Add(f) } assertFloat(t.Min(), r.Min()) assertFloat(t.Max(), r.Max()) assertFloat(t.Mean(), r.Mean()) assertFloat(t.Var(), r.Var()) assertFloat(t.Std(), r.Std()) assertFloat(t.VarP(), r.VarP()) assertFloat(t.StdP(), r.StdP()) } }
func calculateLessThan(left Value, right Value, leftFirst bool) _lessThanResult { x := Value{} y := x if leftFirst { x = toNumberPrimitive(left) y = toNumberPrimitive(right) } else { y = toNumberPrimitive(right) x = toNumberPrimitive(left) } result := false if x.kind != valueString || y.kind != valueString { x, y := x.float64(), y.float64() if math.IsNaN(x) || math.IsNaN(y) { return lessThanUndefined } result = x < y } else { x, y := x.string(), y.string() result = x < y } if result { return lessThanTrue } return lessThanFalse }
func strictEqualityComparison(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 = false } else { result = x == 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 }
// GenericBoxes draws box plots. (Default implementation for box plots). // The values for each box in boxes are in screen coordinates! func GenericBoxes(bg BasicGraphics, boxes []Box, width int, style Style) { if width%2 == 0 { width += 1 } hbw := (width - 1) / 2 for _, d := range boxes { x := int(d.X) q1, q3 := int(d.Q1), int(d.Q3) // DebugLogger.Printf("q1=%d q3=%d q3-q1=%d", q1,q3,q3-q1) bg.Rect(x-hbw, q1, width, q3-q1, style) if !math.IsNaN(d.Med) { med := int(d.Med) bg.Line(x-hbw, med, x+hbw, med, style) } if !math.IsNaN(d.Avg) { bg.Symbol(x, int(d.Avg), style) } if !math.IsNaN(d.High) { bg.Line(x, q3, x, int(d.High), style) } if !math.IsNaN(d.Low) { bg.Line(x, q1, x, int(d.Low), style) } for _, y := range d.Outliers { bg.Symbol(x, int(y), style) } } }
// Compare implements the Datum interface. func (d *DFloat) Compare(other Datum) int { if other == DNull { // NULL is less than any non-NULL value. return 1 } v, ok := other.(*DFloat) if !ok { cmp, ok := mixedTypeCompare(d, other) if !ok { panic(makeUnsupportedComparisonMessage(d, other)) } return cmp } if *d < *v { return -1 } if *d > *v { return 1 } // NaN sorts before non-NaN (#10109). if *d == *v { return 0 } if math.IsNaN(float64(*d)) { if math.IsNaN(float64(*v)) { return 0 } return -1 } return 1 }
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 }
func (w *Windowed) Push(n float64) { old := w.data[w.head] w.length++ w.data[w.head] = n w.head++ if w.head >= len(w.data) { w.head = 0 } if !math.IsNaN(old) { w.sum -= old w.sumsq -= (old * old) } else { w.nans-- } if !math.IsNaN(n) { w.sum += n w.sumsq += (n * n) } else { w.nans++ } }
func noNaN(v data.Vector, pol int) data.Vector { if math.IsNaN(v[X]) || math.IsNaN(v[Y]) || math.IsNaN(v[Z]) { return data.Vector{0, 0, float64(pol)} } else { return v } }
func Pearson(a, b []float64) float64 { if len(a) != len(b) { panic("len(a) != len(b)") } var abar, bbar float64 var n int for i := range a { if !math.IsNaN(a[i]) && !math.IsNaN(b[i]) { abar += a[i] bbar += b[i] n++ } } nf := float64(n) abar, bbar = abar/nf, bbar/nf var numerator float64 var sumAA, sumBB float64 for i := range a { if !math.IsNaN(a[i]) && !math.IsNaN(b[i]) { numerator += (a[i] - abar) * (b[i] - bbar) sumAA += (a[i] - abar) * (a[i] - abar) sumBB += (b[i] - bbar) * (b[i] - bbar) } } return numerator / (math.Sqrt(sumAA) * math.Sqrt(sumBB)) }
func (o Sfloat64) Equal(n Any) bool { m := n.(Sfloat64) if math.IsNaN(float64(o)) && math.IsNaN(float64(m)) { return false } return o == m }
func TestAbs(result, expected, absolute_error float64, test_description string) (status int) { switch { case math.IsNaN(result) || math.IsNaN(expected): status = NaN case math.IsInf(result, 0) || math.IsInf(expected, 0): status = Inf case (expected > 0 && expected < DBL_MIN) || (expected < 0 && expected > -DBL_MIN): status = NotEqual default: if math.Abs(result-expected) > absolute_error { status = NotEqual } else { status = Equal } } if test_description != "" { io.Pf(test_description) switch status { case NaN: io.Pf(" [1;31mNaN[0m\n %v observed\n %v expected. diff = %v\n", result, expected, result-expected) case Inf: io.Pf(" [1;31mInf[0m\n %v observed\n %v expected. diff = %v\n", result, expected, result-expected) case Equal: io.Pf(" [1;32mOk[0m\n %v observed\n %v expected. diff = %v\n", result, expected, result-expected) case NotEqual: io.Pf(" [1;31mError[0m\n %v observed\n %v expected. diff = %v\n", result, expected, result-expected) } } return }
// PrioritizeWorkUnits changes the priorities of some number of work // units. The actual work units are in options["work_unit_keys"]. A // higher priority results in the work units being scheduled sooner. func (jobs *JobServer) PrioritizeWorkUnits(workSpecName string, options map[string]interface{}) (bool, string, error) { var ( err error query coordinate.WorkUnitQuery workSpec coordinate.WorkSpec ) pwuOptions := PrioritizeWorkUnitsOptions{ Priority: math.NaN(), Adjustment: math.NaN(), } workSpec, err = jobs.Namespace.WorkSpec(workSpecName) if err == nil { err = decode(&pwuOptions, options) } if err == nil && pwuOptions.WorkUnitKeys == nil { return false, "missing work_unit_keys", err } if err == nil { query.Names = pwuOptions.WorkUnitKeys if !math.IsNaN(pwuOptions.Priority) { err = workSpec.SetWorkUnitPriorities(query, pwuOptions.Priority) } else if !math.IsNaN(pwuOptions.Adjustment) { err = workSpec.AdjustWorkUnitPriorities(query, pwuOptions.Adjustment) } } return err == nil, "", err }
func (t *GoTracker) updateWeights(vertex int) { if t.board[vertex] != EMPTY { for i := 0; i < 4; i++ { adj := t.adj[vertex][i] if adj != -1 && t.board[adj] == EMPTY { t.updateWeights(adj) } } } else { black_weight := t.weights.Get(BLACK, vertex) if black_weight != 0 { weight := t.get_weight(BLACK, vertex) if math.IsNaN(weight) { black_weight = 0 } else if black_weight+weight > 0 { black_weight += weight } } t.weights.Set(BLACK, vertex, black_weight) white_weight := t.weights.Get(WHITE, vertex) if white_weight != 0 { weight := t.get_weight(WHITE, vertex) if math.IsNaN(weight) { white_weight = 0 } else if white_weight+weight > 0 { white_weight += weight } } t.weights.Set(WHITE, vertex, white_weight) } }
// parseAverages takes a slice of averages and returns a string representation for flot to graph func parseAverages(averages []*models.Average, useBtcField bool) string { var format string if useBtcField { format = "[%g, %.8f]" } else { format = "[%g, %.2f]" } parsed := "" for i, average := range averages { if math.IsNaN(average.Cryptsy.Usd) || math.IsNaN(average.Cryptsy.Btc) { continue } timeIndex := float64(average.TimeBlock.Unix()) * 1000.0 var value float64 if useBtcField { value = average.Cryptsy.Btc } else { value = average.Cryptsy.Usd } parsed += fmt.Sprintf(format, timeIndex, value) if i < len(averages)-1 { parsed += "," } } return parsed }
// === changes(matrix model.ValMatrix) Vector === func funcChanges(ev *evaluator, args Expressions) model.Value { in := ev.evalMatrix(args[0]) out := make(vector, 0, len(in)) for _, samples := range in { changes := 0 prev := model.SampleValue(samples.Values[0].Value) for _, sample := range samples.Values[1:] { current := sample.Value if current != prev && !(math.IsNaN(float64(current)) && math.IsNaN(float64(prev))) { changes++ } prev = current } rs := &sample{ Metric: samples.Metric, Value: model.SampleValue(changes), Timestamp: ev.Timestamp, } rs.Metric.Del(model.MetricNameLabel) out = append(out, rs) } return out }
func KindFromSides(a, b, c float64) Kind { if math.IsNaN(a) || math.IsNaN(b) || math.IsNaN(c) { return NaT } if a > b { a, b = b, a } if b > c { b, c = c, b } if a > b { a, b = b, a } // sides are now sorted switch { case a <= 0: return NaT case a+b <= c: // triangle inequality return NaT case a == b: if b == c { return Equ } return Iso case a == c || b == c: return Iso } return Sca }
// Appends a position to the stack func (vm *Machine) move(x, y, z float64) { if math.IsNaN(x) || math.IsNaN(y) || math.IsNaN(z) { panic("Internal failure: Move attempted with NaN value") } pos := Position{vm.State, x, y, z} vm.Positions = append(vm.Positions, pos) }
func (g *TextGraphics) Scatter(points []chart.EPoint, plotstyle chart.PlotStyle, style chart.Style) { // First pass: Error bars for _, p := range points { xl, yl, xh, yh := p.BoundingBox() if !math.IsNaN(p.DeltaX) { g.tb.Line(int(xl), int(p.Y), int(xh), int(p.Y), '-') } if !math.IsNaN(p.DeltaY) { g.tb.Line(int(p.X), int(yl), int(p.X), int(yh), '|') } } // Second pass: Line if (plotstyle&chart.PlotStyleLines) != 0 && len(points) > 0 { lastx, lasty := int(points[0].X), int(points[0].Y) for i := 1; i < len(points); i++ { x, y := int(points[i].X), int(points[i].Y) // fmt.Printf("LineSegment %d (%d,%d) -> (%d,%d)\n", i, lastx,lasty,x,y) g.tb.Line(lastx, lasty, x, y, rune(style.Symbol)) lastx, lasty = x, y } } // Third pass: symbols if (plotstyle&chart.PlotStylePoints) != 0 && len(points) != 0 { for _, p := range points { g.tb.Put(int(p.X), int(p.Y), rune(style.Symbol)) } } // chart.GenericScatter(g, points, plotstyle, style) }
func calculateLessThan(left Value, right Value, leftFirst bool) _lessThanResult { x := UndefinedValue() y := x if leftFirst { x = toNumberPrimitive(left) y = toNumberPrimitive(right) } else { y = toNumberPrimitive(right) x = toNumberPrimitive(left) } result := false if x._valueType != valueString || y._valueType != valueString { x, y := x.toFloat(), y.toFloat() if math.IsNaN(x) || math.IsNaN(y) { return lessThanUndefined } result = x < y } else { x, y := x.toString(), y.toString() result = x < y } if result { return lessThanTrue } return lessThanFalse }
// Plot implements the Plotter interface, drawing a line // that connects each point in the Line. func (f *Function) Plot(c draw.Canvas, p *plot.Plot) { trX, trY := p.Transforms(&c) d := (p.X.Max - p.X.Min) / float64(f.Samples-1) line := make([]draw.Point, f.Samples) for i := range line { x := p.X.Min + float64(i)*d line[i].X = trX(x) line[i].Y = trY(f.F(x)) } // For every continuous block of non-NaN Y values, stroke lines for i := 0; i < len(line); i++ { if !math.IsNaN(float64(line[i].Y)) { j := i + 1 for ; j < len(line); j++ { if math.IsNaN(float64(line[j].Y)) { break } } c.StrokeLines(f.LineStyle, c.ClipLinesXY(line[i:j])...) i = j } } }
// Validate checks whether the given value is writeable to this schema. func (*NullSchema) Validate(v reflect.Value) bool { // Check if the value is something that can be null switch v.Kind() { case reflect.Interface: return v.IsNil() case reflect.Array: return v.Cap() == 0 case reflect.Slice: return v.IsNil() || v.Cap() == 0 case reflect.Map: return len(v.MapKeys()) == 0 case reflect.String: return len(v.String()) == 0 case reflect.Float32: // Should NaN floats be treated as null? return math.IsNaN(v.Float()) case reflect.Float64: // Should NaN floats be treated as null? return math.IsNaN(v.Float()) case reflect.Ptr: return v.IsNil() case reflect.Invalid: return true } // Nothing else in particular, so this should not validate? return false }
func (d *DatasourceAbstract) ProcessPdp(pdpValue float64, elapsed ElapsedPdpSteps, step time.Duration) float64 { var preUnknown float64 if math.IsNaN(pdpValue) { preUnknown = elapsed.PreInt } else { if math.IsNaN(d.PdpValue) { d.PdpValue = 0 } d.PdpValue += pdpValue / elapsed.Interval * elapsed.PreInt } var pdpTemp float64 if elapsed.Interval > float64(d.Heartbeat) || uint64(step/time.Second/2) < d.UnknownSecCount { pdpTemp = math.NaN() } else { diffPdpSteps := (elapsed.Steps * uint64(step)) / uint64(time.Second) pdpTemp = d.PdpValue / (float64(diffPdpSteps-d.UnknownSecCount) - preUnknown) } if math.IsNaN(pdpValue) { d.UnknownSecCount = uint64(elapsed.PostInt) d.PdpValue = math.NaN() } else { d.UnknownSecCount = 0 d.PdpValue = pdpValue / elapsed.Interval * elapsed.PostInt } return pdpTemp }
// FloatStddevReduceSlice returns the stddev value within a window. func FloatStddevReduceSlice(a []FloatPoint) []FloatPoint { // If there is only one point then return 0. if len(a) < 2 { return []FloatPoint{{Time: ZeroTime, Nil: true}} } // Calculate the mean. var mean float64 var count int for _, p := range a { if math.IsNaN(p.Value) { continue } count++ mean += (p.Value - mean) / float64(count) } // Calculate the variance. var variance float64 for _, p := range a { if math.IsNaN(p.Value) { continue } variance += math.Pow(p.Value-mean, 2) } return []FloatPoint{{ Time: ZeroTime, Value: math.Sqrt(variance / float64(count-1)), }} }
func (u *uniGradStruct) Initialize() error { initLoc := u.loc.Init() initObj := u.obj.Init() initGrad := u.grad.Init() // The initial values need to both be NaN or both not nan if math.IsNaN(initObj) { if !math.IsNaN(initGrad) { return errors.New("gofunopter: cubic: initial function value and gradient must either both be set or neither set") } // Both nan, so compute the initial fuction value and gradient initObj, initGrad, err := u.fun.ObjGrad(initLoc) if err != nil { return errors.New("gofunopter: cubic: error calling function during optimization") } u.obj.SetInit(initObj) u.grad.SetInit(initGrad) } else { if math.IsNaN(initGrad) { return errors.New("gofunopter: cubic: initial function value and gradient must either both be set or neither set") } } err := optimize.Initialize(u.loc, u.obj, u.grad) if err != nil { return err } err = u.optimizer.Initialize(u.loc, u.obj, u.grad) if err != nil { return err } return nil }
func (self *_runtime) evaluateDivide(left float64, right float64) Value { if math.IsNaN(left) || math.IsNaN(right) { return NaNValue() } if math.IsInf(left, 0) && math.IsInf(right, 0) { return NaNValue() } if left == 0 && right == 0 { return NaNValue() } if math.IsInf(left, 0) { if math.Signbit(left) == math.Signbit(right) { return positiveInfinityValue() } else { return negativeInfinityValue() } } if math.IsInf(right, 0) { if math.Signbit(left) == math.Signbit(right) { return positiveZeroValue() } else { return negativeZeroValue() } } if right == 0 { if math.Signbit(left) == math.Signbit(right) { return positiveInfinityValue() } else { return negativeInfinityValue() } } return toValue_float64(left / right) }
// InitBoundedLog initializes a Histogram instance from the given array // of values with the given number of bins which fall between the given limits. // The logarithms of bin centers are uniformly dist. Any // values outside of these limits are ignored. The returned integer is the // number of such ignored values. Because of this, infinte and non-positive // values do not cause a panic. // // The first returned value is the initialized Histogram. // // InitBoundedLog panics if given a non-positive number of bins or // a low bound as large or larger than the high bound or if given infinite bounds. func (hist *Histogram) InitBoundedLog(xs []float64, binNum int, low, high float64) (*Histogram, int) { if hist.init { panic("stats.Histogram.InitBoundedLog called on initialized struct.") } else if binNum < 1 { panic(fmt.Sprintf("stats.Histogram.InitBoundedLog given binNum of %d", binNum)) } else if low >= high || low <= 0 || math.IsInf(low, 0) || math.IsInf(high, 0) || math.IsNaN(low) || math.IsNaN(high) { panic(fmt.Sprintf("stats.Histogram.InitBoundedLog given range [%d, %d]", low, high)) } hist.init = true hist.Bins = make([]int, binNum) hist.BinValues = make([]float64, binNum) hist.BinEdges = make([]float64, binNum+1) hist.logHistogram = true hist.lowLim = math.Log(low) hist.highLim = math.Log(high) hist.binWidth = (hist.highLim - hist.lowLim) / float64(binNum) for i := 0; i < binNum; i++ { hist.BinEdges[i] = math.Exp(hist.lowLim + hist.binWidth*float64(i)) hist.BinValues[i] = math.Exp(hist.lowLim + hist.binWidth*(float64(i)+0.5)) } hist.BinEdges[binNum] = hist.highLim return hist, hist.AddArray(xs) }
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 }
func TestSumSpecialValues(t *testing.T) { sum := NewSum() if !assert.EqualFloat64(0.0, sum.GetResult(), 1e-10, 1) { t.Errorf("Sum: result: %f, but expect: %f\n", sum.GetResult(), 0.0) } sum.Increment(1.0) if !assert.EqualFloat64(1.0, sum.GetResult(), 1e-10, 1) { t.Errorf("Sum: result: %f, but expect: %f\n", sum.GetResult(), 1.0) } sum.Increment(math.Inf(0)) if !assert.EqualFloat64(math.Inf(0), sum.GetResult(), 1e-10, 1) { t.Errorf("Sum: result: %f, but expect: %f\n", sum.GetResult(), math.Inf(0)) } sum.Increment(math.Inf(-1)) if !math.IsNaN(sum.GetResult()) { t.Error("Sum: result should be NaN") } sum.Increment(1.0) if !math.IsNaN(sum.GetResult()) { t.Error("Sum: result should be NaN") } }
func (this floatValue) Collate(other Value) int { other = other.unwrap() switch other := other.(type) { case floatValue: if math.IsNaN(float64(other)) { if math.IsNaN(float64(this)) { return 0 } else { return 1 } } result := float64(this - other) switch { case result < 0.0: return -1 case result > 0.0: return 1 } return 0 default: return int(NUMBER - other.Type()) } }
//Cmp performs a comparison between the two values, and returns the result //of the comparison (LessThan, GreaterThan, Equals, CantCompare), which are defined as ints func Cmp(arg1 interface{}, arg2 interface{}) int { eq, ok := Equal(arg1, arg2) if !ok { return CantCompare } if eq { return Equals } lt, _ := Lt(arg1, arg2) if lt { return LessThan } f1, ok := Float(arg1) if !ok { return CantCompare } f2, ok := Float(arg2) if !ok { return CantCompare } if math.IsNaN(f1) || math.IsNaN(f2) { return CantCompare } return GreaterThan }