Golang Mod示例

说明

golang mod示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: math

示例#1
文件: engine.go 项目: ralreegorganon/vaal

func (r *Robot) TurnGun(degrees float64) {
	d := clamp(degrees, -20, 20)
	r.State.GunHeading += d
	r.State.RadarHeading += d
	r.State.GunHeading = math.Mod(r.State.GunHeading, 360)
	r.State.RadarHeading = math.Mod(r.State.RadarHeading, 360)
}

示例#2
文件: 1.go 项目: tebriel/codeeval-go

func main() {
	file, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		var i float64
		//'scanner.Text()' represents the test case, do something with it
		bounds := strings.Split(scanner.Text(), " ")
		fizz, _ := strconv.ParseFloat(bounds[0], 64)
		buzz, _ := strconv.ParseFloat(bounds[1], 64)
		stop, _ := strconv.ParseFloat(bounds[2], 64)

		for i = 1; i <= stop; i++ {
			var output string
			if math.Mod(i, fizz) == 0 {
				output = "F"
			}

			if math.Mod(i, buzz) == 0 {
				output = output + "B"
			}

			if len(output) == 0 {
				output = strconv.Itoa(int(i))
			}

			fmt.Print(output + " ")
		}
		fmt.Print("\n")
	}
}

示例#3
文件: Final_Server.go 项目: diganth1/ChordProtocol_Golang

func (d *DICT3) GetKeyOrRelation(tnH TripletAndHash, resp *Response) error {

	if tnH.T.Key == "" {
		rel := tnH.T.Relationship
		for kr, val := range myDictionary {
			rHash := hashIt(kr.Relationship, 2)
			kHash := hashIt(kr.Key, 3)
			krHash, _ := strconv.Atoi(strconv.Itoa(kHash) + strconv.Itoa(rHash))
			krHash = int(math.Mod(float64(krHash), float64(32)))

			if kr.Relationship == rel && tnH.H == krHash {
				resp.Reply.Result = Triplet{kr.Key, kr.Relationship, val}
			}
		}
	} else {
		key := tnH.T.Key
		for kr, val := range myDictionary {
			rHash := hashIt(kr.Relationship, 2)
			kHash := hashIt(kr.Key, 3)
			krHash, _ := strconv.Atoi(strconv.Itoa(kHash) + strconv.Itoa(rHash))
			krHash = int(math.Mod(float64(krHash), float64(32)))

			if kr.Key == key && tnH.H == krHash {
				resp.Reply.Result = Triplet{kr.Key, kr.Relationship, val}

			}
		}
	}
	return nil
}

示例#4
文件: numbers.gen.go 项目: nbaum/golem

func init() {
	Core.Function("%", func(env *Env, args []Value) (result Value) {
		CheckArgs("%", 1, -1, args)
		result = args[0]
		for _, arg := range args[1:] {
			switch a := result.(type) {
			case Int:
				switch b := arg.(type) {
				case Int:
					result = Int(a % b)
				case Float:
					result = Float(math.Mod(float64(a), float64(b)))
				default:
					panic("bad-type")
				}
			case Float:
				switch b := args[1].(type) {
				case Int:
					result = Float(math.Mod(float64(a), float64(b)))
				case Float:
					result = Float(math.Mod(float64(a), float64(b)))
				default:
					panic("bad-type")
				}
			default:
				panic("bad-type")
			}
		}
		return
	})
}

示例#5
文件: isprime.go 项目: dbeecham/isprime

// This function will eventually get it's own module.
func isPrime(t int64) bool {

	// math.Mod requires floats.
	x := float64(t)

	// 1 or less aren't primes.
	if x <= 1 {
		return false
	}

	// Solve half of the integer set directly
	if math.Mod(x, 2) == 0 {
		return x == 2
	}

	// Main loop. i needs to be float because of math.Mod.
	for i := 3.0; i <= math.Floor(math.Sqrt(x)); i += 2.0 {
		if math.Mod(x, i) == 0 {
			return false
		}
	}

	// It's a prime!
	return true
}

示例#6
文件: ansiout.go 项目: surven/go-ansiout

/**
 *
 *	Set forground and background color.
 *
 *	integer f Forground color value 0-15
 *	integer b background color value 0-7
 *
 */
func Color(f int, b int) {
	var tmp string
	var colors = [8]int{0, 4, 2, 6, 1, 5, 3, 7}

	// Prevent sending color codes if they haven't changed.
	if curFg != f || curBg != b {
		curFg = f
		curBg = b

		fg := colors[int(math.Mod(float64(f), 8))] + 30
		bg := colors[int(math.Mod(float64(b), 8))] + 40

		if b > 7 {
			tmp += "5;"
		} else {
			tmp += "0;"
		}

		if f > 7 {
			tmp += "1;"
		}

		fmt.Printf(ESC+"%s%d;%dm", tmp, fg, bg)
	}
}

示例#7
文件: recipe.go 项目: youtube/doorman

// parseQPSChangeFunc augments a recipe with the pointer to a Go function
// that actually implements the recipe function. If the function specified
// in --recipes is unknown or an incorrect number of arguments were passed,
// it returns false, otherwise not false.
func parseQPSChangeFunc(r *Recipe) bool {
	switch r.name {
	case "constant_increase":
		checkArg(r, 1)
		r.fun = func(w *WorkerState) {
			w.CurrentQPS += w.Recipe.arg[0]
		}
		return true

	case "random_change":
		checkArg(r, 1)
		r.fun = func(w *WorkerState) {
			w.CurrentQPS = w.Recipe.baseQPS + w.Recipe.arg[0]*(1.0-2.0*rand.Float64())
		}
		return true

	case "sin":
		checkArg(r, 1)
		r.fun = func(w *WorkerState) {
			t := math.Mod(time.Now().Sub(startingTime).Seconds(), recipeReset.Seconds())
			w.CurrentQPS = w.Recipe.arg[0] * math.Sin(t/recipeReset.Seconds()*math.Pi)
		}
		return true

	case "inc_sin":
		checkArg(r, 1)
		r.fun = func(w *WorkerState) {
			t := math.Mod(time.Now().Sub(startingTime).Seconds(), recipeReset.Seconds())
			w.CurrentQPS = float64(w.resetCount) * w.Recipe.arg[0] * math.Sin(t/recipeReset.Seconds()*math.Pi)
		}
		return true
	}

	return false
}

示例#8
文件: math_test.go 项目: thecc4re/meeus

// Section "Trigonometric functions of large angles":
//
// Meeus makes his point, but an example with integer values is a bit unfair
// when trigonometric functions inherently work on floating point numbers.
func ExamplePMod_integer() {
	const large = 36000030

	// The direct function call loses precition as expected.
	fmt.Println("Direct:    ", math.Sin(large*math.Pi/180))

	// When the value is manually reduced to the integer 30, the Go constant
	// evaluaton does a good job of delivering a radian value to math.Sin that
	// evaluates to .5 exactly.
	fmt.Println("Integer 30:", math.Sin(30*math.Pi/180))

	// Math.Mod takes float64s and returns float64s.  The integer constants
	// here however can be represented exactly as float64s, and the returned
	// result is exact as well.
	fmt.Println("Math.Mod:  ", math.Mod(large, 360))

	// But when math.Mod is substituted into the Sin function, float64s
	// are multiplied instead of the high precision constants, and the result
	// comes back slightly inexact.
	fmt.Println("Sin Mod:   ", math.Sin(math.Mod(large, 360)*math.Pi/180))

	// Use of PMod on integer constants produces results identical to above.
	fmt.Println("PMod int:  ", math.Sin(base.PMod(large, 360)*math.Pi/180))

	// As soon as the large integer is scaled to a non-integer value though,
	// precision is lost and PMod is of no help recovering at this point.
	fmt.Println("PMod float:", math.Sin(base.PMod(large*math.Pi/180, 2*math.Pi)))
	// Output:
	// Direct:     0.49999999995724154
	// Integer 30: 0.5
	// Math.Mod:   30
	// Sin Mod:    0.49999999999999994
	// PMod int:   0.49999999999999994
	// PMod float: 0.49999999997845307
}

示例#9
文件: main.go 项目: smillingrainbow/ProjetAlgoC

func main() {

	var (
		nbLigne uint
		result  [][]int
		r       *rand.Rand
		i       uint
	)

	nbLigne = Initialisation()

	result = make([][]int, nbLigne)

	r = rand.New(rand.NewSource(time.Now().UnixNano()))

	for i = 0; i < nbLigne; i++ {
		result[i] = make([]int, 3)
		result[i][0] = int(math.Mod(float64(r.Int()), 200)) - 100
		result[i][1] = int(math.Mod(float64(r.Int()), 200)) - 100
		result[i][2] = int(math.Mod(float64(r.Int()), 9)) + 1

	}

	ecrireFichier("fichierTest", nbLigne, result)
}

示例#10
文件: libdmt.go 项目: bhepp/cgrates

// Returns reqType, requestNr and ccTime in seconds
func disectUsageForCCR(usage time.Duration, debitInterval time.Duration, callEnded bool) (reqType, reqNr, reqCCTime, usedCCTime int) {
	usageSecs := usage.Seconds()
	debitIntervalSecs := debitInterval.Seconds()
	reqType = 1
	if usage > 0 {
		reqType = 2
	}
	if callEnded {
		reqType = 3
	}
	reqNr = int(usageSecs / debitIntervalSecs)
	if callEnded {
		reqNr += 1
	}
	ccTimeFloat := debitInterval.Seconds()
	if callEnded {
		ccTimeFloat = math.Mod(usageSecs, debitIntervalSecs)
	}
	if reqType == 1 { // Initial does not have usedCCTime
		reqCCTime = int(ccTimeFloat)
	} else if reqType == 2 {
		reqCCTime = int(ccTimeFloat)
		usedCCTime = int(math.Mod(usageSecs, debitIntervalSecs))
	} else if reqType == 3 {
		usedCCTime = int(ccTimeFloat) // Termination does not have requestCCTime
	}
	return
}

示例#11
文件: fizzbuzz.go 项目: zgohr/codeeval

func main() {
	f, _ := os.Open(os.Args[1])
	r := bufio.NewReader(f)
	for {
		l, err := r.ReadString('\n')
		if err != nil {
			break
		}
		l = strings.TrimSpace(l)
		nums := strings.Split(l, " ")
		a, _ := strconv.ParseInt(strings.TrimSpace(nums[0]), 0, 0)
		b, _ := strconv.ParseInt(strings.TrimSpace(nums[1]), 0, 0)
		n, _ := strconv.ParseInt(strings.TrimSpace(nums[2]), 0, 0)
		str := ""
		for j := int64(0); j < n; j++ {
			modA := math.Mod(float64(j+1), float64(a))
			modB := math.Mod(float64(j+1), float64(b))
			if modA == 0 && modB == 0 {
				str += "FB "
			} else if modA == 0 {
				str += "F "
			} else if modB == 0 {
				str += "B "
			} else {
				str += fmt.Sprintf("%d ", j+1)
			}
		}
		fmt.Println(strings.TrimSpace(str))
	}
}

示例#12
文件: coreutils.go 项目: cgrates/cgrates

// returns a number equal or larger than the amount that exactly
// is divisible to whole
func RoundDuration(whole, amount time.Duration) time.Duration {
	a, w := float64(amount), float64(whole)
	if math.Mod(a, w) == 0 {
		return amount
	}
	return time.Duration((w - math.Mod(a, w)) + a)
}

示例#13
文件: glutil.go 项目: hyl87/2011_Go_Geo_Gfx

func FindTexSize2D(maxSize, numTexels, minSize float64) (float64, float64) {
	var wh float64
	if math.Floor(numTexels) != numTexels {
		log.Panicf("AAAAH %v", numTexels)
	}
	if numTexels <= maxSize {
		return numTexels, 1
	}
	for h := 2.0; h < maxSize; h++ {
		for w := 2.0; w < maxSize; w++ {
			wh = w * h
			if wh == numTexels {
				if minSize > 0 {
					for (math.Mod(w, 2) == 0) && (math.Mod(h, 2) == 0) && ((w / 2) >= minSize) && ((h / 2) >= minSize) {
						w, h = w/2, h/2
					}
				}
				for ((h * 2) < w) && (math.Mod(w, 2) == 0) {
					w, h = w/2, h*2
				}
				if minSize > 0 {
					for (math.Mod(w, 2) == 0) && (math.Mod(h, 2) == 0) && ((w / 2) >= minSize) && ((h / 2) >= minSize) {
						w, h = w/2, h/2
					}
				}
				return w, h
			} else if wh > numTexels {
				break
			}
		}
	}
	return 0, 0
}

示例#14
文件: input.go 项目: vron/fm

func move(x, y int) {
	if isHeld {
		dx, dy := float64(x-ox), float64(y-oy)
		s := 100.0
		dt, dp := dy/s, dx/s
		theta, phi = math.Mod(ot+dt, math.Pi), math.Mod(op+dp, math.Pi*2)
	}
}

示例#15
文件: binop.go 项目: eeertekin/tidb

func (o *BinaryOperation) evalMod(a interface{}, b interface{}) (interface{}, error) {
	switch x := a.(type) {
	case int64:
		switch y := b.(type) {
		case int64:
			if y == 0 {
				return nil, nil
			}
			return x % y, nil
		case uint64:
			if y == 0 {
				return nil, nil
			} else if x < 0 {
				// TODO: check overflow
				return -int64(uint64(-x) % y), nil
			}
			// TODO: check overflow
			return uint64(x) % y, nil
		}
	case uint64:
		switch y := b.(type) {
		case int64:
			if y == 0 {
				return nil, nil
			} else if y < 0 {
				// TODO: check overflow
				return -int64(x % uint64(-y)), nil
			}
			// TODO: check overflow
			return x % uint64(y), nil
		case uint64:
			if y == 0 {
				return nil, nil
			}
			return x % y, nil
		}
	case float64:
		switch y := b.(type) {
		case float64:
			if y == 0 {
				return nil, nil
			}
			return math.Mod(x, y), nil
		}
	case mysql.Decimal:
		switch y := b.(type) {
		case mysql.Decimal:
			xf, _ := x.Float64()
			yf, _ := y.Float64()
			if yf == 0 {
				return nil, nil
			}
			return math.Mod(xf, yf), nil
		}
	}

	return types.InvOp2(a, b, opcode.Mod)
}

示例#16
文件: multiples.go 项目: tzwaan/project_euler

func main() {
	result := 0
	for i := 0; i < 1000; i++ {
		if math.Mod(float64(i), 3) == 0 || math.Mod(float64(i), 5) == 0 {
			result = result + i
		}
	}
	fmt.Println(result)
}

示例#17
文件: solve.go 项目: neilb14/euler

func SumMultiples(n int) int {
	sum := 0
	for i := 0; i < n; i++ {
		if math.Mod(float64(i), float64(3)) == 0 || math.Mod(float64(i), float64(5)) == 0 {
			sum += i
		}
	}
	return sum
}

示例#18
文件: 0001.go 项目: BenBergman/euler

func SumOfNumbersDivisibleByThreeAndFive(n int) int {
	sum := 0
	for i := 0; i < n; i++ {
		if math.Mod(float64(i), 3) == 0 || math.Mod(float64(i), 5) == 0 {
			sum += i
		}
	}
	return sum
}

示例#19
文件: main.go 项目: jabong/imagick

// Set the affine array to rotate image by 'degrees' clockwise
func set_rotate_affine(r []float64, degrees float64) []float64 {
	r[0] = math.Cos(DegreesToRadians(math.Mod(degrees, 360.0)))
	r[1] = math.Sin(DegreesToRadians(math.Mod(degrees, 360.0)))
	r[2] = -math.Sin(DegreesToRadians(math.Mod(degrees, 360.0)))
	r[3] = math.Cos(DegreesToRadians(math.Mod(degrees, 360.0)))
	r[4] = 0
	r[5] = 0
	return r
}

示例#20
文件: evaluator_binop.go 项目: lovedboy/tidb

func computeMod(a, b interface{}) (interface{}, error) {
	switch x := a.(type) {
	case int64:
		switch y := b.(type) {
		case int64:
			if y == 0 {
				return nil, nil
			}
			return x % y, nil
		case uint64:
			if y == 0 {
				return nil, nil
			} else if x < 0 {
				// first is int64, return int64.
				return -int64(uint64(-x) % y), nil
			}
			return int64(uint64(x) % y), nil
		}
	case uint64:
		switch y := b.(type) {
		case int64:
			if y == 0 {
				return nil, nil
			} else if y < 0 {
				// first is uint64, return uint64.
				return uint64(x % uint64(-y)), nil
			}
			return x % uint64(y), nil
		case uint64:
			if y == 0 {
				return nil, nil
			}
			return x % y, nil
		}
	case float64:
		switch y := b.(type) {
		case float64:
			if y == 0 {
				return nil, nil
			}
			return math.Mod(x, y), nil
		}
	case mysql.Decimal:
		switch y := b.(type) {
		case mysql.Decimal:
			xf, _ := x.Float64()
			yf, _ := y.Float64()
			if yf == 0 {
				return nil, nil
			}
			return math.Mod(xf, yf), nil
		}
	}

	return types.InvOp2(a, b, opcode.Mod)
}

示例#21
文件: geoquery.go 项目: meetizer/go-geofire

func wrapLongitude(longitude float64) float64 {
	if longitude >= -180 && longitude <= 180 {
		return longitude
	}
	adjusted := longitude + 180.0

	if adjusted > 0 {
		return math.Mod(adjusted, 360.0) - 180
	}
	return 180 - math.Mod(-adjusted, 360.0)
}

示例#22
文件: ring.go 项目: mohae/firkin

// Enqueue enques an item, If the buffer is full, the oldest item will
// be evicted.
func (r *Ring) Enqueue(item interface{}) error {
	r.Lock()
	// if the buffer is full, move the head forward
	if r.isFull() {
		r.Head = int(math.Mod(float64(r.Head+1), float64(cap(r.Items))))
	}
	r.Items[r.Tail] = item
	r.Tail = int(math.Mod(float64(r.Tail+1), float64(cap(r.Items))))
	r.Unlock()
	return nil
}

示例#23
文件: plot.go 项目: bernhard-hofmann/GearGen

func plotGrid(cx int, cy int, width int, height int, canvas *svg.SVG) {
	spaceing := 5 * factor // 5mm

	gx := int(math.Mod(float64(cx), float64(spaceing)))
	gy := int(math.Mod(float64(cy), float64(spaceing)))

	gw := width - (2 * gx)
	gh := height - (2 * gy)

	canvas.Grid(gx, gy, gw, gh, spaceing, style("grid"))
}

示例#24
文件: gorender.go 项目: Nightgunner5/goray

//////////////////
// Utility
//////////////////
func PrintDuration(t time.Duration) {
	if hours := math.Floor(t.Hours()); hours > 0 {
		fmt.Printf("%vh ", int(hours))
	}
	if minutes := math.Mod(math.Floor(t.Minutes()), 60); minutes > 0 {
		fmt.Printf("%1.0vm ", int(minutes))
	}
	if seconds := math.Mod(t.Seconds(), 60); seconds > 0 {
		fmt.Printf("%2.3vs", seconds)
	}
}

示例#25
文件: date.go 项目: sywxf/xls

// Return the integer values for hour, minutes, seconds and
// nanoseconds that comprised a given fraction of a day.
func fractionOfADay(fraction float64) (hours, minutes, seconds, nanoseconds int) {
	f := 5184000000000000 * fraction
	nanoseconds = int(math.Mod(f, 1000000000))
	f = f / 1000000000
	seconds = int(math.Mod(f, 60))
	f = f / 3600
	minutes = int(math.Mod(f, 60))
	f = f / 60
	hours = int(f)
	return hours, minutes, seconds, nanoseconds
}

示例#26
文件: main.go 项目: mattludwigs/puzzles

func main() {
	multiples := []int{}

	for i := 1; i < max; i++ {
		if math.Mod(float64(i), 3) == 0 || math.Mod(float64(i), 5) == 0 {
			multiples = append(multiples, i)
		}
	}

	fmt.Println(add(multiples))
}

示例#27
文件: 001-multiples-of-3-and-five.go 项目: enricodangelo/exercises-in-style

func main() {
	var result = 0
	for i := 3; i < 1000; i++ {
		if math.Mod(float64(i), float64(3)) == 0 {
			result += i
		} else if math.Mod(float64(i), float64(5)) == 0 {
			result += i
		}
	}
	fmt.Println(result)
}

示例#28
文件: helper.go 项目: archcra/srtAdjuster

func Milliseconds2str(timestamp int) string {
	// return string should be format as: 00:00:10,000
	rMilliseconds := int(math.Mod(float64(timestamp), 1000))
	seconds := (timestamp - rMilliseconds) / 1000
	rSeconds := int(math.Mod(float64(seconds), 60))
	minutes := (seconds - rSeconds) / 60
	rMinutes := int(math.Mod(float64(minutes), 60))
	hours := int(math.Floor(float64(minutes-rMinutes))) / 60

	return fmt.Sprintf("%02d:%02d:%02d,%03d", hours, rMinutes, rSeconds, rMilliseconds)
}

示例#29
文件: be_BY.go 项目: luizbafilho/fusis

// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'be_BY'
func (be *be_BY) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {

	n := math.Abs(num)
	nMod10 := math.Mod(n, 10)
	nMod100 := math.Mod(n, 100)

	if (nMod10 == 2 || nMod10 == 3) && (nMod100 != 12 && nMod100 != 13) {
		return locales.PluralRuleFew
	}

	return locales.PluralRuleOther
}

示例#30
文件: hsla.go 项目: surma-dump/img

// BUG: Conversion is broken _somewhere_, check against IM results.
func (col HSLA) RGBA() (red, green, blue, alpha uint32) {
	h := col.H
	s := col.S
	l := col.L
	a := col.A

	h = math.Mod(h, 360)

	c := (1.0 - math.Abs(2.0*l-1.0)) * s

	hdash := h / 60.0
	x := c * (1 - math.Abs(math.Mod(hdash, 2)-1))

	var r, g, b float64
	if h == 0 {
		r = 0
		g = 0
		b = 0
	} else if hdash < 1 {
		r = c
		g = x
		b = 0
	} else if hdash < 2 {
		r = x
		g = c
		b = 0
	} else if hdash < 3 {
		r = 0
		g = c
		b = x
	} else if hdash < 4 {
		r = 0
		g = x
		b = c
	} else if hdash < 5 {
		r = x
		g = 0
		b = c
	} else if hdash < 6 {
		r = c
		g = 0
		b = x
	}

	m := l - 0.5*c

	red = uint32(utils.Truncatef((r+m)*a*255)) << 8
	green = uint32(utils.Truncatef((g+m)*a*255)) << 8
	blue = uint32(utils.Truncatef((b+m)*a*255)) << 8
	alpha = uint32(a*255) << 8

	return
}

展开阅读全文