本文整理汇总了Golang中math.Abs函数的典型用法代码示例。如果您正苦于以下问题:Golang Abs函数的具体用法?Golang Abs怎么用?Golang Abs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Abs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: run_rootsol_test
// run_rootsol_test runs root solution test
// Note: xguess is the trial solution for Newton's method (not Brent's)
func run_rootsol_test(tst *testing.T, xa, xb, xguess, tolcmp float64, ffcnA Cb_yxe, ffcnB Cb_f, JfcnB Cb_Jd, fname string, save, show bool) (xbrent float64) {
// Brent
io.Pfcyan("\n - - - - - - - using Brent's method - - -- - - - \n")
var o Brent
o.Init(ffcnA)
var err error
xbrent, err = o.Solve(xa, xb, false)
if err != nil {
chk.Panic("%v", err)
}
var ybrent float64
ybrent, err = ffcnA(xbrent)
if err != nil {
chk.Panic("%v", err)
}
io.Pforan("x = %v\n", xbrent)
io.Pforan("f(x) = %v\n", ybrent)
io.Pforan("nfeval = %v\n", o.NFeval)
io.Pforan("nit = %v\n", o.It)
if math.Abs(ybrent) > 1e-10 {
chk.Panic("Brent failed: f(x) = %g > 1e-10\n", ybrent)
}
// Newton
io.Pfcyan("\n - - - - - - - using Newton's method - - -- - - - \n")
var p NlSolver
p.Init(1, ffcnB, nil, JfcnB, true, false, nil)
xnewt := []float64{xguess}
var cnd float64
cnd, err = p.CheckJ(xnewt, 1e-6, true, !chk.Verbose)
io.Pforan("cond(J) = %v\n", cnd)
if err != nil {
chk.Panic("%v", err.Error())
}
err = p.Solve(xnewt, false)
if err != nil {
chk.Panic("%v", err.Error())
}
var ynewt float64
ynewt, err = ffcnA(xnewt[0])
if err != nil {
chk.Panic("%v", err)
}
io.Pforan("x = %v\n", xnewt[0])
io.Pforan("f(x) = %v\n", ynewt)
io.Pforan("nfeval = %v\n", p.NFeval)
io.Pforan("nJeval = %v\n", p.NJeval)
io.Pforan("nit = %v\n", p.It)
if math.Abs(ynewt) > 1e-9 {
chk.Panic("Newton failed: f(x) = %g > 1e-10\n", ynewt)
}
// compare Brent's and Newton's solutions
PlotYxe(ffcnA, "results", fname, xbrent, xa, xb, 101, "Brent", "'b-'", save, show, func() {
plt.PlotOne(xnewt[0], ynewt, "'g+', ms=15, label='Newton'")
})
chk.Scalar(tst, "xbrent - xnewt", tolcmp, xbrent, xnewt[0])
return
}
示例2: LateUpdate
func (sp *SmoothFollow) LateUpdate() {
camera := engine.CurrentCamera()
if camera != nil {
myPos := sp.Target.Transform().Position()
camPos := camera.Transform().Position()
if sp.Speed > 0 {
camPos = engine.Lerp(camPos, myPos, float32(engine.DeltaTime())*sp.Speed)
disX := camPos.X - myPos.X
disY := camPos.Y - myPos.Y
if float32(math.Abs(float64(disX))) > sp.MaxDis {
if disX < 0 {
camPos.X = myPos.X - sp.MaxDis
} else {
camPos.X = myPos.X + sp.MaxDis
}
}
if float32(math.Abs(float64(disY))) > sp.MaxDis {
if disY < 0 {
camPos.Y = myPos.Y - sp.MaxDis
} else {
camPos.Y = myPos.Y + sp.MaxDis
}
}
} else {
camPos = myPos
}
camera.Transform().SetPosition(camPos)
}
}
示例3: nearEqual
func nearEqual(a, b, closeEnough, maxError float64) bool {
absDiff := math.Abs(a - b)
if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero.
return true
}
return absDiff/max(math.Abs(a), math.Abs(b)) < maxError
}
示例4: bestScaleAndPrefix
func bestScaleAndPrefix(unit *pb.TelemetryDatumSchema_Unit,
values ...float64) (scale float64, prefix string) {
// Heuristic (can be improved):
// Use the smallest value.
m := math.Abs(values[0])
for _, v := range values {
v = math.Abs(v)
if v > m {
m = v
}
}
prefixes := []struct {
string
float64
}{
{"T", 1e12},
{"G", 1e9},
{"M", 1e6},
{"k", 1e3},
{"", 1e0},
{"m", 1e-3},
{"μ", 1e-6},
{"n", 1e-9},
{"p", 1e-12}}
for _, s := range prefixes {
if m >= s.float64 {
return s.float64, s.string
}
}
return 1.0, ""
}
示例5: DrawRamp
// PlotRamp plots the ramp function (contour)
func (o *Plotter) DrawRamp(xmi, xma, ymi, yma float64) {
if o.Rmpf == nil {
o.set_empty()
return
}
if o.NptsRmp < 2 {
o.NptsRmp = 101
}
if math.Abs(xma-xmi) < 1e-5 {
xmi, xma = -0.1, 0.1
}
if math.Abs(yma-ymi) < 1e-5 {
ymi, yma = -0.1, 0.1
}
xx := la.MatAlloc(o.NptsRmp, o.NptsRmp)
yy := la.MatAlloc(o.NptsRmp, o.NptsRmp)
zz := la.MatAlloc(o.NptsRmp, o.NptsRmp)
dx := (xma - xmi) / float64(o.NptsRmp-1)
dy := (yma - ymi) / float64(o.NptsRmp-1)
for i := 0; i < o.NptsRmp; i++ {
for j := 0; j < o.NptsRmp; j++ {
xx[i][j] = xmi + float64(i)*dx
yy[i][j] = ymi + float64(j)*dy
zz[i][j] = xx[i][j] - o.Rmpf(xx[i][j]+yy[i][j])
}
}
plt.ContourSimple(xx, yy, zz, "colors=['blue'], linewidths=[2], levels=[0]")
}
示例6: Quantize
// Determine the symbol that exists at each sample of the signal.
func (p Parser) Quantize() {
// 0 0011, 3 1100
// 1 0101, 4 1010
// 2 0110, 5 1001
for idx, vec := range p.filtered {
argmax := byte(0)
max := math.Abs(vec[0])
// If v1 is larger than v0, update max and argmax.
if v1 := math.Abs(vec[1]); v1 > max {
max = v1
argmax = 1
}
// If v2 is larger than the greater of v1 or v0, update max and argmax.
if v2 := math.Abs(vec[2]); v2 > max {
max = v2
argmax = 2
}
// Set the output symbol index.
p.quantized[idx] = argmax
// If the sign is negative, jump to the index of the inverted symbol.
if vec[argmax] > 0 {
p.quantized[idx] += 3
}
}
}
示例7: debug_print_up_results
func debug_print_up_results(d *Domain) {
io.Pf("\ntime = %23.10f\n", d.Sol.T)
for _, v := range d.Msh.Verts {
n := d.Vid2node[v.Id]
eqpl := n.GetEq("pl")
equx := n.GetEq("ux")
equy := n.GetEq("uy")
var pl, ux, uy float64
if eqpl >= 0 {
pl = d.Sol.Y[eqpl]
}
if equx >= 0 {
ux = d.Sol.Y[equx]
}
if equy >= 0 {
uy = d.Sol.Y[equy]
}
if math.Abs(pl) < 1e-13 {
pl = 0
}
if math.Abs(ux) < 1e-13 {
ux = 0
}
if math.Abs(uy) < 1e-13 {
uy = 0
}
io.Pf("%3d : pl=%23.10v ux=%23.10f uy=%23.10f\n", v.Id, pl, ux, uy)
}
}
示例8: Horizontal
// Horizontal computes data for a horizontal sundial.
//
// Argument φ is geographic latitude at which the sundial will be located,
// a is the length of a straight stylus perpendicular to the plane of the
// sundial.
//
// Results consist of a set of lines, a center point, and u, the length of a
// polar stylus. They are in units of a, the stylus length.
func Horizontal(φ, a float64) (lines []Line, center Point, u float64) {
sφ, cφ := math.Sincos(φ)
tφ := sφ / cφ
for i := 0; i < 24; i++ {
l := Line{Hour: i}
H := float64(i-12) * 15 * math.Pi / 180
aH := math.Abs(H)
sH, cH := math.Sincos(H)
for _, d := range m {
tδ := math.Tan(d * math.Pi / 180)
H0 := math.Acos(-tφ * tδ)
if aH > H0 {
continue // sun below horizon
}
Q := cφ*cH + sφ*tδ
x := a * sH / Q
y := a * (sφ*cH - cφ*tδ) / Q
l.Points = append(l.Points, Point{x, y})
}
if len(l.Points) > 0 {
lines = append(lines, l)
}
}
center.Y = -a / tφ
u = a / math.Abs(sφ)
return
}
示例9: Vertical
// Vertical computes data for a vertical sundial.
//
// Argument φ is geographic latitude at which the sundial will be located.
// D is gnomonic declination, the azimuth of the perpendicular to the plane
// of the sundial, measured from the southern meridian towards the west.
// Argument a is the length of a straight stylus perpendicular to the plane
// of the sundial.
//
// Results consist of a set of lines, a center point, and u, the length of a
// polar stylus. They are in units of a, the stylus length.
func Vertical(φ, D, a float64) (lines []Line, center Point, u float64) {
sφ, cφ := math.Sincos(φ)
tφ := sφ / cφ
sD, cD := math.Sincos(D)
for i := 0; i < 24; i++ {
l := Line{Hour: i}
H := float64(i-12) * 15 * math.Pi / 180
aH := math.Abs(H)
sH, cH := math.Sincos(H)
for _, d := range m {
tδ := math.Tan(d * math.Pi / 180)
H0 := math.Acos(-tφ * tδ)
if aH > H0 {
continue // sun below horizon
}
Q := sD*sH + sφ*cD*cH - cφ*cD*tδ
if Q < 0 {
continue // sun below plane of sundial
}
x := a * (cD*sH - sφ*sD*cH + cφ*sD*tδ) / Q
y := -a * (cφ*cH + sφ*tδ) / Q
l.Points = append(l.Points, Point{x, y})
}
if len(l.Points) > 0 {
lines = append(lines, l)
}
}
center.X = -a * sD / cD
center.Y = a * tφ / cD
u = a / math.Abs(cφ*cD)
return
}
示例10: checkClockSkew
func (hm HMACMiddleware) checkClockSkew(dateHeaderValue string) bool {
// Reference layout for parsing time: "Mon Jan 2 15:04:05 MST 2006"
refDate := "Mon, 02 Jan 2006 15:04:05 MST"
tim, err := time.Parse(refDate, dateHeaderValue)
if err != nil {
log.Error("Date parsing failed")
return false
}
inSec := tim.UnixNano()
now := time.Now().UnixNano()
diff := now - inSec
in_ms := diff / 1000000
if math.Abs(float64(in_ms)) > HMACClockSkewLimitInMs {
log.Debug("Difference is: ", math.Abs(float64(in_ms)))
return false
}
return true
}
示例11: TestGauss
func TestGauss(t *testing.T) {
src := rand.NewSource(time.Now().Unix())
gen := rand.New(src)
// gaussian
gaussian := NewDist(128)
for i := 0; i < 1000; i++ {
v := gen.Intn(200)
gaussian.Add(v)
}
fmt.Println("N-samples:", gaussian.N, ", σ:", gaussian.Sigma)
// testing
fmt.Println("range [0,200]")
sigma := gaussian.Sigma
mean := gaussian.Mean
for i := 0; i < 10; i++ {
v := gen.Intn(200)
fmt.Printf("X:%4d: P(v)=%0.4f, deriv:%.2fσ\n", v, gaussian.P(v), math.Abs(float64(v)-mean)/sigma)
}
fmt.Println("range [0,400]")
for i := 0; i < 10; i++ {
v := gen.Intn(400)
fmt.Printf("X:%4d: P(v)=%0.4f, deriv:%.2fσ\n", v, gaussian.P(v), math.Abs(float64(v)-mean)/sigma)
}
}
示例12: assertLatLon
func assertLatLon(t *testing.T, pos Position, doc SampleDoc) {
slat, haslat := doc.Result["latitude"].(float64)
slon, haslon := doc.Result["longitude"].(float64)
if !(haslat && haslon) {
return
}
if math.Abs(pos.Lat-slat) > 0.001 || math.Abs(pos.Lon-slon) > 0.001 {
t.Fatalf("Error parsing lat/lon from %v, got %v; expected %v,%v",
doc.Src, pos, slat, slon)
}
tbl := doc.Result["symboltable"].(string)[0]
if pos.Symbol.Table != tbl {
t.Fatalf("Expected symbol table %v, got %v for %v",
tbl, pos.Symbol.Table, doc.Src)
}
symbol := doc.Result["symbolcode"].(string)[0]
if pos.Symbol.Symbol != symbol {
t.Fatalf("Expected symbol %v, got %v for %v",
symbol, pos.Symbol.Symbol, doc.Src)
}
course, _ := doc.Result["course"].(float64)
assertEpsilon(t, "course of "+doc.Src, course, pos.Velocity.Course)
speed, _ := doc.Result["speed"].(float64)
assertEpsilon(t, "speed of "+doc.Src, speed, pos.Velocity.Speed)
}
示例13: Norm
// 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)
}
示例14: Distance
// 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)
}
示例15: TestIntensityMeasuredV1
func TestIntensityMeasuredV1(t *testing.T) {
setup()
defer teardown()
b, err := wt.Request{Accept: V1GeoJSON, URL: "/intensity?type=measured"}.Do(ts.URL)
if err != nil {
t.Fatal(err)
}
var i intensityMeasuredV1Features
err = json.Unmarshal(b, &i)
if err != nil {
t.Fatal(err)
}
if len(i.Features) != 1 {
t.Error("found wrong number of intensities.")
}
if math.Abs(i.Features[0].Geometry.Longitude()-175.49) > tolerance {
t.Error("incorrect Longitude")
}
if math.Abs(i.Features[0].Geometry.Latitude()+40.2) > tolerance {
t.Error("incorrect Latitude")
}
if i.Features[0].Properties.MMI != 4 {
t.Error("incorrect MMI")
}
}