Ejemplo n.º 1
0
// checkIsBestApprox checks that f is the best possible float64
// approximation of r.
// Returns true on success.
func checkIsBestApprox(t *testing.T, f float64, r *Rat) bool {
	if math.Abs(f) >= math.MaxFloat64 {
		// Cannot check +Inf, -Inf, nor the float next to them (MaxFloat64).
		// But we have tests for these special cases.
		return true
	}

	// r must be strictly between f0 and f1, the floats bracketing f.
	f0 := math.Nextafter(f, math.Inf(-1))
	f1 := math.Nextafter(f, math.Inf(+1))

	// For f to be correct, r must be closer to f than to f0 or f1.
	df := delta(r, f)
	df0 := delta(r, f0)
	df1 := delta(r, f1)
	if df.Cmp(df0) > 0 {
		t.Errorf("Rat(%v).Float64() = %g (%b), but previous float64 %g (%b) is closer", r, f, f, f0, f0)
		return false
	}
	if df.Cmp(df1) > 0 {
		t.Errorf("Rat(%v).Float64() = %g (%b), but next float64 %g (%b) is closer", r, f, f, f1, f1)
		return false
	}
	if df.Cmp(df0) == 0 && !isEven(f) {
		t.Errorf("Rat(%v).Float64() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f0, f0)
		return false
	}
	if df.Cmp(df1) == 0 && !isEven(f) {
		t.Errorf("Rat(%v).Float64() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f1, f1)
		return false
	}
	return true
}
Ejemplo n.º 2
0
func TestVariance(t *testing.T) {
	var ed EuclidDist
	_, dim := DATAPOINTS_D.GetSize()
	// Model D
	c := cluster{DATAPOINTS_D, CENTROIDS_D, dim, 0}
	v := variance(c, ed)

	E := 20.571429
	epsilon := .000001
	na := math.Nextafter(E, E+1)
	diff := math.Abs(v - na)

	if diff > epsilon {
		t.Errorf("TestVariance: for model D excpected %f but received %f.  The difference %f exceeds epsilon %f.", E, v, diff, epsilon)
	}

	// Variance a cluster with a perfectly centered centroids
	_, dim0 := DATAPOINTS_D0.GetSize()
	c0 := cluster{DATAPOINTS_D0, CENTROID_D0, dim0, 0}
	v0 := variance(c0, ed)

	E = 1.333333
	na = math.Nextafter(E, E+1)
	diff = math.Abs(v0 - na)

	if diff > epsilon {
		t.Errorf("TestVariance: for model D excpected %f but received %f.  The difference %f exceeds epsilon %f.", E, v0, diff, epsilon)
	}
}
Ejemplo n.º 3
0
Archivo: axis.go Proyecto: skiesel/plot
// Ticks returns Ticks in a specified range
func (DefaultTicks) Ticks(min, max float64) (ticks []Tick) {
	const SuggestedTicks = 3
	if max < min {
		panic("illegal range")
	}
	tens := math.Pow10(int(math.Floor(math.Log10(max - min))))
	n := (max - min) / tens
	for n < SuggestedTicks {
		tens /= 10
		n = (max - min) / tens
	}

	majorMult := int(n / SuggestedTicks)
	switch majorMult {
	case 7:
		majorMult = 6
	case 9:
		majorMult = 8
	}
	majorDelta := float64(majorMult) * tens
	val := math.Floor(min/majorDelta) * majorDelta
	prec := maxInt(precisionOf(min), precisionOf(max))
	for val <= max {
		if val >= min && val <= max {
			ticks = append(ticks, Tick{Value: val, Label: formatFloatTick(val, prec)})
		}
		if math.Nextafter(val, val+majorDelta) == val {
			break
		}
		val += majorDelta
	}

	minorDelta := majorDelta / 2
	switch majorMult {
	case 3, 6:
		minorDelta = majorDelta / 3
	case 5:
		minorDelta = majorDelta / 5
	}

	val = math.Floor(min/minorDelta) * minorDelta
	for val <= max {
		found := false
		for _, t := range ticks {
			if t.Value == val {
				found = true
			}
		}
		if val >= min && val <= max && !found {
			ticks = append(ticks, Tick{Value: val})
		}
		if math.Nextafter(val, val+minorDelta) == val {
			break
		}
		val += minorDelta
	}
	return
}
Ejemplo n.º 4
0
func init() {
	onePlusEps := math.Nextafter(1, math.Inf(1))
	eps := (math.Nextafter(1, math.Inf(1)) - 1) * 0.5
	dlamchE = eps
	sfmin := math.SmallestNonzeroFloat64
	small := 1 / math.MaxFloat64
	if small >= sfmin {
		sfmin = small * onePlusEps
	}
	dlamchS = sfmin
	radix := 2.0
	dlamchP = radix * eps
}
Ejemplo n.º 5
0
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)
		}
	}
}
Ejemplo n.º 6
0
func main() {

	fmt.Printf("Now you have %g problems.vv\n",
		math.Nextafter(2, 3))
	fmt.Printf("Hello World!\n")

}
Ejemplo n.º 7
0
func testVars() {
	fmt.Println("The time is", time.Now().Unix())
	fmt.Printf("Now you have %g problems.\n", math.Nextafter(3, 50))
	fmt.Println(math.Pi)
	fmt.Println(add(42, 13))
	a, b := swap("ololo", "trololo")
	fmt.Println(a, b)
	fmt.Println(split(17))
	var i int
	fmt.Println(i, c, python, java)
	const f = "%T(%v)\n"
	fmt.Printf(f, ToBe, ToBe)
	fmt.Printf(f, MaxInt, MaxInt)
	fmt.Printf(f, z, z)
	fmt.Println("Pi = ", Pi+5)

	var ii int
	var ff float64
	var bb bool
	var ss string
	fmt.Printf("%v %v %v %q\n", ii, ff, bb, ss)

	var xxx, yyy int = 3, 4
	var fff float64 = math.Sqrt(float64(xxx*xxx + yyy*yyy))
	var zzz int = int(fff)
	fmt.Println(xxx, yyy, zzz)

	v := 42 // change me!
	fmt.Printf("v is of type %T\n", v)
}
Ejemplo n.º 8
0
// 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 rayIntersectsSegment(p, a, b xy) bool {
	if a.y > b.y {
		a, b = b, a
	}
	for p.y == a.y || p.y == b.y {
		p.y = math.Nextafter(p.y, math.Inf(1))
	}
	if p.y < a.y || p.y > b.y {
		return false
	}
	if a.x > b.x {
		if p.x > a.x {
			return false
		}
		if p.x < b.x {
			return true
		}
	} else {
		if p.x > b.x {
			return false
		}
		if p.x < a.x {
			return true
		}
	}
	return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)
}
func rayIntersectsSegment(p xy, s seg) bool {
	var a, b xy
	if s.p1.y < s.p2.y {
		a, b = s.p1, s.p2
	} else {
		a, b = s.p2, s.p1
	}
	for p.y == a.y || p.y == b.y {
		p.y = math.Nextafter(p.y, math.Inf(1))
	}
	if p.y < a.y || p.y > b.y {
		return false
	}
	if a.x > b.x {
		if p.x > a.x {
			return false
		}
		if p.x < b.x {
			return true
		}
	} else {
		if p.x > b.x {
			return false
		}
		if p.x < a.x {
			return true
		}
	}
	return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)
}
Ejemplo n.º 11
0
func main() {
	fmt.Println("Randome number without seed", rand.Intn(10))
	rand.Seed(time.Now().UnixNano())
	fmt.Println("My lucky number is", rand.Intn(10))
	fmt.Printf("Now you have %g problems.\n", math.Nextafter(2, 3))
	fmt.Println(math.Pi)
}
Ejemplo n.º 12
0
Archivo: world.go Proyecto: 529/golang
func main() {
	fmt.Println("wlecome to the playground")
	fmt.Println("This time is ", time.Now())
	fmt.Println("My favorite number is ", rand.Intn(10))
	fmt.Printf("Now you have %g problems.", math.Nextafter(2, 3))
	fmt.Println("\n")
	fmt.Println(math.Pi)
	fmt.Println(add(2, 3))
	fmt.Println(minus(2, 3))
	fmt.Println(split(11))

	var i, j int = 1, 2
	k := 3
	c, python, java := true, false, "hogehoge"
	fmt.Println(i, j, k, c, python, java)

	const f = "%T(%v)\n"
	fmt.Printf(f, ToBe, ToBe)
	fmt.Printf(f, MaxInt, MaxInt)
	fmt.Printf(f, z, z)

	const Truth = true
	fmt.Println("Go rules?", Truth)

}
Ejemplo n.º 13
0
// Decompose computes an m-by-n matrix M for an m-by-m covariance matrix Σ such
// that, for an n-element vector X with uncorrelated components, M * X is an
// m-element vector whose components are correlated according to Σ. The
// function reduces the number of dimensions from m to n such that a certain
// portion of the variance is preserved, which is controlled by λ ∈ (0, 1].
func Decompose(Σ []float64, m uint, λ float64) ([]float64, uint, error) {
	U, Λ, err := decomposition.CovPCA(Σ, m, math.Sqrt(math.Nextafter(1, 2)-1))
	if err != nil {
		return nil, 0, err
	}

	n := m

	// NOTE: Λ is in the descending order and nonnegative.
	var cum, sum float64
	for i := uint(0); i < m; i++ {
		sum += Λ[i]
	}
	for i := uint(0); i < m; i++ {
		cum += Λ[i]
		if cum/sum >= λ {
			n = i + 1
			break
		}
	}

	for i := uint(0); i < n; i++ {
		coef := math.Sqrt(Λ[i])
		for j := uint(0); j < m; j++ {
			U[i*m+j] *= coef
		}
	}

	return U[:m*n], n, nil
}
Ejemplo n.º 14
0
func cellIDFromFaceIJWrap(f, i, j int) CellID {
	// Convert i and j to the coordinates of a leaf cell just beyond the
	// boundary of this face.  This prevents 32-bit overflow in the case
	// of finding the neighbors of a face cell.
	i = clamp(i, -1, maxSize)
	j = clamp(j, -1, maxSize)

	// We want to wrap these coordinates onto the appropriate adjacent face.
	// The easiest way to do this is to convert the (i,j) coordinates to (x,y,z)
	// (which yields a point outside the normal face boundary), and then call
	// xyzToFaceUV to project back onto the correct face.
	//
	// The code below converts (i,j) to (si,ti), and then (si,ti) to (u,v) using
	// the linear projection (u=2*s-1 and v=2*t-1).  (The code further below
	// converts back using the inverse projection, s=0.5*(u+1) and t=0.5*(v+1).
	// Any projection would work here, so we use the simplest.)  We also clamp
	// the (u,v) coordinates so that the point is barely outside the
	// [-1,1]x[-1,1] face rectangle, since otherwise the reprojection step
	// (which divides by the new z coordinate) might change the other
	// coordinates enough so that we end up in the wrong leaf cell.
	const scale = 1.0 / maxSize
	limit := math.Nextafter(1, 2)
	u := math.Max(-limit, math.Min(limit, scale*float64((i<<1)+1-maxSize)))
	v := math.Max(-limit, math.Min(limit, scale*float64((j<<1)+1-maxSize)))

	// Find the leaf cell coordinates on the adjacent face, and convert
	// them to a cell id at the appropriate level.
	f, u, v = xyzToFaceUV(faceUVToXYZ(f, u, v))
	return cellIDFromFaceIJ(f, stToIJ(0.5*(u+1)), stToIJ(0.5*(v+1)))
}
Ejemplo n.º 15
0
func main() {
	fmt.Println("Hello, Golang!")
	fmt.Println("rand number: ", rand.Intn(10))
	fmt.Printf("rand number: %g\n", math.Nextafter(2, 3))
	fmt.Println(add(2, 3))
	fmt.Println(swap("hello", "world"))
	fmt.Println(split(111))

	// local variable
	var i int = 1000

	// short declaration
	k := 3
	s := "hello"

	fmt.Println(i, c, python, java, k, s)

	const f = "%T(%v)\n"
	var (
		ToBe   bool       = false
		MaxInt uint64     = 1<<64 - 1
		z      complex128 = cmplx.Sqrt(-5 + 2i)
	)
	fmt.Printf(f, ToBe, ToBe)
	fmt.Printf(f, MaxInt, MaxInt)
	fmt.Printf(f, z, z)

	fmt.Printf(f, Pi, Pi)
	fmt.Printf(f, s, s)
}
Ejemplo n.º 16
0
func main() {
	fmt.Println("Hello, the time is : ", time.Now())
	fmt.Println("my fav number is ", rand.Intn(10))
	fmt.Printf("the number after 2 is %g\n", math.Nextafter(2, 3))
	fmt.Printf("Pi: %g\n", math.Pi)
	fmt.Println("add test: ", add(1, 5), add2(30, 42))

	a, b := swap("b", "a")
	fmt.Println(a, b)
	fmt.Println(split(70))

	var c, python, java = true, false, "no"
	fmt.Println(c, python, java, wow, cool, vars)

	implicit := "the := is only available in functions"
	fmt.Println(implicit)

	const tx = "%T(%v)\n"
	fmt.Printf(tx, ToBe, ToBe)
	fmt.Printf(tx, MaxInt, MaxInt)
	fmt.Printf(tx, z, z)

	// type conversion
	_f := 34.32
	var i int = int(_f)

	var f float32 = float32(i) / 2.3

	fmt.Printf("%T %v \n", i, i)
	fmt.Printf("%T %v \n", f, f)

}
Ejemplo n.º 17
0
func main() {
	fmt.Println("The time is, ", time.Now())

	fmt.Printf("Now you have %g problems.", math.Nextafter(2, 3))

	fmt.Println("When's Saturday?")
	today := time.Now().Weekday()
	fmt.Println(today)
	switch time.Saturday {
	case today + 0:
		fmt.Println("Today.")
	case today + 1:
		fmt.Println("Tomorrow.")
	case today + 2:
		fmt.Println("In two days.")
	default:
		fmt.Println("Too far away.")
	}

	t := time.Now()
	fmt.Println(t.Hour())
	switch {
	case t.Hour() < 12:
		fmt.Println("Good morning!")
	case t.Hour() < 17:
		fmt.Println("Good afternoon.")
	default:
		fmt.Println("Good evening.")
	}

}
Ejemplo n.º 18
0
func TestPointProb(t *testing.T) {
	R := 10010.0
	Ri := 100.0
	M := 2.0
	V := 20.000000

	point := matrix.MakeDenseMatrix([]float64{5, 7},
		1, 2)

	mean := matrix.MakeDenseMatrix([]float64{6, 8},
		1, 2)

	var ed EuclidDist

	//	pointProb(R, Ri, M int, V float64, point, mean *matrix.DenseMatrix, measurer VectorMeasurer) (float64, error)
	pp := pointProb(R, Ri, M, V, point, mean, ed)

	E := 0.011473
	epsilon := .000001
	na := math.Nextafter(E, E+1)
	diff := math.Abs(pp - na)

	if diff > epsilon {
		t.Errorf("TestPointProb: expected %f but received %f.  The difference %f exceeds epsilon %f", E, pp, diff, epsilon)
	}
}
Ejemplo n.º 19
0
func main() {
	var a []int
	fmt.Println(a, len(a), cap(a))

	// 可用类似数组的方式初始化slice
	var b []int = []int{0, 1, 2}
	fmt.Println(b, len(b), cap(b))
	var c = []string{2: "123", 3: "345"}
	fmt.Println(c)

	var d = make([]int, 0)
	fmt.Println(d, len(d), cap(d))

	var e = make([]int, 3, 10)
	fmt.Println(e, len(e), cap(e))

	var f = new([]int)
	fmt.Println(f, len(*f), cap(*f))

	s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	//2个参数 slice[beginIndex:endIndex]
	sa := s[1:3]
	sb := s[:4]
	sc := s[1:]
	sd := s[1:1]
	se := s[:]
	fmt.Println(sa, sb, sc, sd, se)

	x := make([]int, 5, 10)
	//3个参数 slice[beginIndex:endIndex:capIndex]
	xa := x[9:10:10]
	xb := x[:3:5]
	fmt.Println(x, len(x), cap(x))
	fmt.Println(xa, len(xa), cap(xa))
	fmt.Println(xb, len(xb), cap(xb))

	ss := []string{}
	fmt.Println(ss)
	ss = append(ss, "a")
	fmt.Println(ss)
	ss = append(ss, "b", "c", "d")
	fmt.Println(ss)
	t := []string{"e", "f", "g"}
	ss = append(ss, t...)
	fmt.Println(ss)
	ss = append(ss, t[:2]...)
	fmt.Println(ss)

	ss[0] = "aa"
	fmt.Println(ss)

	ss[len(ss)-1] = "end"
	fmt.Println(ss)

	fmt.Printf("Now ,you have %g problems.", math.Nextafter(2, 3))

	deleteByAppend()
	deleteByCopy()
}
Ejemplo n.º 20
0
func main() {
	fmt.Println("Hello World")
	fmt.Println(time.Now())           //Print current time
	rand.Seed(10)                     //
	fmt.Println(rand.Intn(25))        //Print random number less than 25
	fmt.Println(math.Nextafter(3, 7)) //Print value immediately after 3

}
Ejemplo n.º 21
0
func tour1() {
	fmt.Printf("hello, world")
	fmt.Printf("\tgood night")
	fmt.Println("\tmorning call")
	fmt.Println("Happy", math.Pi, "day")
	fmt.Printf("Now you have %g problems.\n",
		math.Nextafter(2, 3))
}
Ejemplo n.º 22
0
func TestCorrelateLarge(t *testing.T) {
	_, application, _ := system.Load("fixtures/016_160.tgff")

	ε := math.Sqrt(math.Nextafter(1.0, 2.0) - 1.0)
	R := Compute(application, index(160), 5)
	_, _, err := decomposition.CovPCA(R, 160, ε)
	assert.Success(err, t)
}
Ejemplo n.º 23
0
func main() {
	fmt.Println("Happy", math.Pi, "Day")
	fmt.Printf("Now you have %g problems. \n", math.Nextafter(2, 3))
	fmt.Println("1 << 10 :", 1<<10) // 1 * 1 ^ 10
	fmt.Println("2 << 10 :", 2<<10) // 2 * 2 ^ 10
	fmt.Println("8 >> 2:", 8>>2)    // 8 * 2 ^ -2 or 8 / 2 ^ 2
	fmt.Println("math.Pow(2, 10)", math.Pow(2, 10))
}
Ejemplo n.º 24
0
func TestLogLikelih(t *testing.T) {
	// Model D - one cluster
	R, M := DATAPOINTS_D.GetSize()
	var ed EuclidDist

	cd := cluster{DATAPOINTS_D, CENTROIDS_D, M, 0}
	vard := variance(cd, ed)
	cd.Variance = vard

	cslice := make([]cluster, 1)
	cslice[0] = cd

	ll := loglikelih(R, cslice)

	epsilon := .000001
	E := -42.394242
	na := math.Nextafter(E, E+1)
	diff := math.Abs(ll - na)

	if diff > epsilon {
		t.Errorf("TestLoglikeli: For model D expected %f but received %f.  The difference %f exceeds epsilon %f", E, ll, diff, epsilon)
	}

	// Model Dn - two clusters
	c0 := cluster{DATAPOINTS_D0, CENTROID_D0, M, 0}
	v0 := variance(c0, ed)
	c0.Variance = v0

	c1 := cluster{DATAPOINTS_D1, CENTROID_D1, M, 0}
	v1 := variance(c1, ed)
	c1.Variance = v1

	cslicen := []cluster{c0, c1}

	ll_n := loglikelih(R, cslicen)

	E = -25.549651
	na = math.Nextafter(E, E+1)
	diff = math.Abs(ll_n - na)

	if diff > epsilon {
		t.Errorf("TestLoglikeli: For model Dn expected %f but received %f.  The difference %f exceeds epsilon %f", E, ll_n, diff, epsilon)
	}
}
Ejemplo n.º 25
0
func (a *attributeView) Paint() {
	r := InnerRect(a)
	min := a.from(r.Min)
	max := a.from(r.Max)
	for t := a.pattern.timeGrid.next(math.Nextafter(math.Max(0, min.X), -math.MaxFloat64), true); t < max.X; t = a.pattern.timeGrid.next(t, true) {
		SetColor(Color{.2, .2, .2, 1})
		SetLineWidth(2)
		if t == 0 {
			SetColor(Color{.3, .3, .3, 1})
			SetLineWidth(5)
		}
		DrawLine(a.to(Pt(t, min.Y)), a.to(Pt(t, max.Y)))
	}
	if a.valueGrid != nil {
		prev := -math.MaxFloat64
		for v := a.valueGrid.next(math.Nextafter(min.Y, -math.MaxFloat64), true); v < max.Y && v != prev; v = a.valueGrid.next(v, true) {
			SetColor(Color{.2, .2, .2, 1})
			SetLineWidth(2)
			if v == a.valueGrid.defaultValue() {
				SetColor(Color{.3, .3, .3, 1})
				SetLineWidth(5)
			}
			DrawLine(a.to(Pt(math.Max(0, min.X), v)), a.to(Pt(max.X, v)))
			prev = v
		}
	}

	if p, ok := KeyFocus(a).(*controlPointView); !ok || p.note.attr == a {
		SetLineWidth(3)
		SetColor(Color{.2, .2, .35, 1})
		if a.focused {
			SetColor(Color{.3, .3, .5, 1})
		}
		DrawLine(a.to(Pt(a.pattern.cursorTime, min.Y)), a.to(Pt(a.pattern.cursorTime, max.Y)))
		if n, ok := KeyFocus(a).(*noteView); !ok || n.attr == a {
			DrawLine(a.to(Pt(math.Max(0, min.X), a.cursorVal)), a.to(Pt(max.X, a.cursorVal)))
		}
	}

	SetLineWidth(1)
	SetColor(Color{1, 1, 1, 1})
	DrawLine(r.Min, Pt(r.Max.X, r.Min.Y))
}
Ejemplo n.º 26
0
func feq(x float64, y float64, within int) bool {
	z := x
	for i := 0; i < within; i++ {
		z = math.Nextafter(z, y)
		if y == z {
			return true
		}
	}
	return false
}
Ejemplo n.º 27
0
func main() {
	// 定义整型变量
	// 注意:go 是静态类型的语言
	var i, j int = 1, 2
	var c, python, java = true, false, "no!"

	// 不用指定变量类型的定义,系统会根据初始赋值自己确定类型
	k := 3 // 等价于 var k int = 3

	fmt.Println(i, j, k, c, python, java)
	// 结果:1 2 3 true false no!

	// 注意:Println不支持,Printf才支持%式的输出
	fmt.Printf("Now you have %g problems.", math.Nextafter(2, 3))

	fmt.Printf("%t\n", 1 == 2)
	fmt.Printf("255的二进制:%b\n", 255)
	fmt.Printf("255的八进制:%o\n", 255)
	fmt.Printf("浮点数-Pai:%f\n", math.Pi)

	// 定义数组
	var a [5]int
	fmt.Println("array a:", a)
	a[1] = 10
	a[3] = 30
	fmt.Println("assign:", a)
	fmt.Println("len:", len(a))

	// 常量:可以是字符型, string, boolean, 或者数字
	// 常量不能用 := 语法来声明
	const World = "世界"
	fmt.Println("这是const常量的例子:hello", World)

	// 定义复数
	var (
		ToBe   bool       = false
		MaxInt uint64     = 1<<64 - 1
		z      complex128 = cmplx.Sqrt(-5 + 12i)
	)

	const f = "%T(%v)\n"
	fmt.Printf(f, ToBe, ToBe)
	fmt.Printf(f, MaxInt, MaxInt)
	fmt.Printf(f, z, z)

	// 数字常量
	fmt.Println("数字常量例子:")
	fmt.Println(needInt(Small)) // 21
	// fmt.Println(needInt(Big))
	// constant 1267650600228229401496703205376 overflows int
	fmt.Println(needFloat(Small)) // 0.2
	fmt.Println(needFloat(Big))   // 1.2676506002282295e+29

}
Ejemplo n.º 28
0
func TestRoundTrips(t *testing.T) {
	assertRoundTrips := func(v Value) {
		vs := NewTestValueStore()
		out := DecodeValue(EncodeValue(v, vs), vs)
		assert.True(t, v.Equals(out))
	}

	assertRoundTrips(Bool(false))
	assertRoundTrips(Bool(true))

	assertRoundTrips(Number(0))
	assertRoundTrips(Number(-0))
	assertRoundTrips(Number(math.Copysign(0, -1)))

	intTest := []int64{1, 2, 3, 7, 15, 16, 17,
		127, 128, 129,
		254, 255, 256, 257,
		1023, 1024, 1025,
		2048, 4096, 8192, 32767, 32768, 65535, 65536,
		4294967295, 4294967296,
		9223372036854779,
		92233720368547760,
	}
	for _, v := range intTest {
		f := float64(v)
		assertRoundTrips(Number(f))
		f = math.Copysign(f, -1)
		assertRoundTrips(Number(f))
	}
	floatTest := []float64{1.01, 1.001, 1.0001, 1.00001, 1.000001, 100.01, 1000.000001}
	for _, f := range floatTest {
		assertRoundTrips(Number(f))
		f = math.Copysign(f, -1)
		assertRoundTrips(Number(f))
	}
	assertRoundTrips(Number(math.MaxFloat64))
	assertRoundTrips(Number(math.Nextafter(1, 2) - 1))

	assertRoundTrips(String(""))
	assertRoundTrips(String("foo"))
	assertRoundTrips(String("AINT NO THANG"))
	assertRoundTrips(String("💩"))

	assertRoundTrips(NewStruct("", StructData{"a": Bool(true), "b": String("foo"), "c": Number(2.3)}))

	listLeaf := newList(newListLeafSequence(nil, Number(4), Number(5), Number(6), Number(7)))
	assertRoundTrips(listLeaf)

	assertRoundTrips(newList(newListMetaSequence([]metaTuple{
		newMetaTuple(NewRef(listLeaf), orderedKeyFromInt(10), 10, nil),
		newMetaTuple(NewRef(listLeaf), orderedKeyFromInt(20), 20, nil),
	}, nil)))
}
Ejemplo n.º 29
0
func main() {
	fmt.Println(a)
	for i, v := range a {
		fmt.Printf("Id: %d contain string: %s\n", i, v)
	}

	changeMap(&a)
	fmt.Println(a)

	fmt.Printf(token.EOF.String())
	fmt.Printf("Now you have %g problems.", math.Nextafter(2, 3))
}
Ejemplo n.º 30
0
func TestGreaterThan(t *testing.T) {

	for _, tt := range []struct {
		a, b     interface{}
		expected bool
	}{
		// a = int, b = float
		{int64(1), float64(2), false},
		{int64(2), float64(1), true},
		// a = float, b = int
		{float64(1), int64(2), false},
		{float64(2), int64(1), true},
		// float > float
		{float64(1), float64(2), false},
		{float64(2), float64(1), true},
		// int > int
		{int64(1), int64(2), false},
		{int64(2), int64(1), true},
		// precision at high end of int64 range
		{int64(math.MaxInt64), int64(math.MaxInt64 - 1), true},
		{int64(math.MaxInt64 - 1), int64(math.MaxInt64), false},
		// precision at low end of int64 range
		{int64(math.MinInt64 + 1), int64(math.MinInt64), true},
		{int64(math.MinInt64), int64(math.MinInt64 + 1), false},
		// loss of precision
		{float64(math.MaxInt64 + 255), int64(math.MaxInt64), false},
		// smallest float64 delta
		{math.SmallestNonzeroFloat64, int64(0), true},
		// comparison at the far reaches of the float64 range
		{float64(math.MaxFloat64), math.Nextafter(math.MaxFloat64, math.Inf(-1)), true},
		{math.Nextafter(-math.MaxFloat64, math.Inf(1)), float64(-math.MaxFloat64), true},
	} {
		got := greaterThan(tt.a, tt.b)
		if got != tt.expected {
			t.Errorf("greaterThan failed for %T(%[1]v) > %T(%[2]v), got %v, expected %v.", tt.a, tt.b, got, tt.expected)
		}
	}

}