// encodeGrid encodes a location using the grid refinement method into // an OLC string. // // Appends to the given code byte slice! // // The grid refinement method divides the area into a grid of 4x5, and uses a // single character to refine the area. This allows default accuracy OLC codes // to be refined with just a single character. func encodeGrid(code []byte, lat, lng float64, codeLen int) ([]byte, error) { latPlaceValue, lngPlaceValue := gridSizeDegrees, gridSizeDegrees lat = math.Remainder((lat + latMax), latPlaceValue) if lat < 0 { lat += latPlaceValue } lng = math.Remainder((lng + lngMax), lngPlaceValue) if lng < 0 { lng += lngPlaceValue } for i := 0; i < codeLen; i++ { row := int(math.Floor(lat / (latPlaceValue / gridRows))) col := int(math.Floor(lng / (lngPlaceValue / gridCols))) pos := row*gridCols + col if !(0 <= pos && pos < len(Alphabet)) { return nil, fmt.Errorf("pos=%d is out of alphabet", pos) } code = append(code, Alphabet[pos]) if i == codeLen-1 { break } latPlaceValue /= gridRows lngPlaceValue /= gridCols lat -= float64(row) * latPlaceValue lng -= float64(col) * lngPlaceValue } return code, nil }
// encodeGrid encodes a location using the grid refinement method into // an OLC string. // // Appends to the given code byte slice! // // The grid refinement method divides the area into a grid of 4x5, and uses a // single character to refine the area. This allows default accuracy OLC codes // to be refined with just a single character. func encodeGrid(code []byte, lat, lng float64, codeLen int) []byte { latPlaceValue, lngPlaceValue := gridSizeDegrees, gridSizeDegrees lat = math.Remainder((lat + latMax), latPlaceValue) if lat < 0 { lat += latPlaceValue } lng = math.Remainder((lng + lngMax), lngPlaceValue) if lng < 0 { lng += lngPlaceValue } for i := 0; i < codeLen; i++ { row := int(math.Floor(lat / (latPlaceValue / gridRows))) col := int(math.Floor(lng / (lngPlaceValue / gridCols))) pos := row*gridCols + col if !(0 <= pos && pos < len(Alphabet)) { panic(fmt.Sprintf("encodeGrid loc=(%f,%f) row=%d col=%d latVal=%f lngVal=%f", lat, lng, row, col, latPlaceValue, lngPlaceValue)) } code = append(code, Alphabet[pos]) if i == codeLen-1 { break } latPlaceValue /= gridRows lngPlaceValue /= gridCols lat -= float64(row) * latPlaceValue lng -= float64(col) * lngPlaceValue } return code }
// Expanded returns an interval that has been expanded on each side by margin. // If margin is negative, then the function shrinks the interval on // each side by margin instead. The resulting interval may be empty or // full. Any expansion (positive or negative) of a full interval remains // full, and any expansion of an empty interval remains empty. func (i Interval) Expanded(margin float64) Interval { if margin >= 0 { if i.IsEmpty() { return i } // Check whether this interval will be full after expansion, allowing // for a 1-bit rounding error when computing each endpoint. if i.Length()+2*margin+2*epsilon >= 2*math.Pi { return FullInterval() } } else { if i.IsFull() { return i } // Check whether this interval will be empty after expansion, allowing // for a 1-bit rounding error when computing each endpoint. if i.Length()+2*margin-2*epsilon <= 0 { return EmptyInterval() } } result := IntervalFromEndpoints( math.Remainder(i.Lo-margin, 2*math.Pi), math.Remainder(i.Hi+margin, 2*math.Pi), ) if result.Lo <= -math.Pi { result.Lo = math.Pi } return result }
func testViewProcedure(t *testing.T, A viewProcedureVector) { b := A.ViewProcedure(func(element float64) bool { return math.Remainder(element, 2) == 0 }) for i := 0; i < b.Size(); i++ { el := b.GetQuick(i) if math.Remainder(el, 2) != 0 { t.Fail() } } }
func (c *Counter) Incr() { now := glfw.GetTime() if int32(c.Last) != int32(now) { c.Total += math.Remainder(now-c.Last, 1) c.Count += 1 avg := c.Total / float64(c.Count) c.Avg = float32(avg * 1000) c.Total = math.Remainder(now, 1) c.Count = 1 } else { c.Total += (now - c.Last) c.Count += 1 } c.Last = now }
func is_even(x float64) bool { var result bool = false if math.Remainder(x, 2) == 0 { result = true } return result }
func intOp(op token.Token, x, y *BasicLit, combine bool) (*BasicLit, error) { out := &BasicLit{ Kind: x.Kind, } l, err := strconv.Atoi(x.Value) if err != nil { return out, err } r, err := strconv.Atoi(y.Value) if err != nil { return out, err } var t int switch op { case token.ADD: t = l + r case token.SUB: t = l - r case token.QUO: // Sass division can create floats, so much treat // ints as floats then test for fitting inside INT fl, fr := float64(l), float64(r) if math.Remainder(fl, fr) != 0 { return floatOp(op, x, y, combine) } t = l / r case token.MUL: t = l * r default: panic("unsupported intOp" + op.String()) } out.Value = strconv.Itoa(t) return out, nil }
func div_by_3(x float64) bool { var result bool = false if math.Remainder(x, 3) == 0 { result = true } return result }
// CapBound returns a cap that countains Rect. func (r Rect) CapBound() Cap { // We consider two possible bounding caps, one whose axis passes // through the center of the lat-long rectangle and one whose axis // is the north or south pole. We return the smaller of the two caps. if r.IsEmpty() { return EmptyCap() } var poleZ, poleAngle float64 if r.Lat.Hi+r.Lat.Lo < 0 { // South pole axis yields smaller cap. poleZ = -1 poleAngle = math.Pi/2 + r.Lat.Hi } else { poleZ = 1 poleAngle = math.Pi/2 - r.Lat.Lo } poleCap := CapFromCenterAngle(PointFromCoords(0, 0, poleZ), s1.Angle(poleAngle)*s1.Radian) // For bounding rectangles that span 180 degrees or less in longitude, the // maximum cap size is achieved at one of the rectangle vertices. For // rectangles that are larger than 180 degrees, we punt and always return a // bounding cap centered at one of the two poles. if math.Remainder(r.Lng.Hi-r.Lng.Lo, 2*math.Pi) >= 0 && r.Lng.Hi-r.Lng.Lo < 2*math.Pi { midCap := CapFromPoint(PointFromLatLng(r.Center())).AddPoint(PointFromLatLng(r.Lo())).AddPoint(PointFromLatLng(r.Hi())) if midCap.Height() < poleCap.Height() { return midCap } } return poleCap }
func (rx *PhysReceiver) GainBeam(tx EmitterInt, ch int) float64 { if ch > 0 && rx.Orientation[ch] >= 0 { p := tx.GetPos().Minus(rx.Pos) theta := math.Atan2(p.Y, p.X) * 180 / math.Pi if theta < 0 { theta += 360 } theta -= rx.Orientation[ch] theta = math.Remainder(theta, 360) // t1:=o-theta // t2:=theta-o // if t1>t2 {theta=t1} else {theta=t2} if theta > 180 { theta += 360 } if theta < -180 || theta > 180 { fmt.Println("ThetaError") } g := 12 * (theta / 65) * (theta / 65) if g > 20 { g = 20 } g = math.Pow(10, (-g+10)/10) return g } return 1.0 }
// Andoyer computes approximate geodesic distance between two // points p1 and p2 on the spheroid s. // Computations use Andoyer-Lambert first order (in flattening) approximation. // // Reference: P.D. Thomas, Mathematical Models for Navigation Systems, TR-182, // US Naval Oceanographic Office (1965). func Andoyer(s *Spheroid, p1, p2 LL) float64 { a, f := s.A(), s.F() lat1, lon1 := p1.LatLon() lat2, lon2 := p2.LatLon() F, G := (lat1+lat2)/2.0, (lat1-lat2)/2.0 L := math.Remainder(lon1-lon2, 360.0) / 2.0 sinF, cosF := math.Sincos((math.Pi / 180.0) * F) sinG, cosG := math.Sincos((math.Pi / 180.0) * G) sinL, cosL := math.Sincos((math.Pi / 180.0) * L) S2 := sq(sinG*cosL) + sq(cosF*sinL) C2 := sq(cosG*cosL) + sq(sinF*sinL) S, C := math.Sqrt(S2), math.Sqrt(C2) omega := math.Atan2(S, C) R := (S * C) / omega D := 2.0 * omega * a H1 := (3.0*R - 1.0) / (2.0 * C2) H2 := (3.0*R + 1.0) / (2.0 * S2) dist := D * (1.0 + f*(H1*sq(sinF*cosG)-H2*sq(cosF*sinG))) if finite(dist) { return dist } // Antipodal points. if finite(R) { return 2.0 * s.Quad() } // Identical points. return 0.0 }
func (c *Camera) handleCommands() { Pi2 := math.Pi / 2 for cmd := range c.cmds { switch cmd := cmd.(type) { case cameraCommandTurn: if cmd.X != 0 { c.alpha += cmd.X / (float64(c.screenw) / Pi2) c.alpha = math.Remainder(c.alpha, 2*math.Pi) } if cmd.Y != 0 { c.theta -= cmd.Y / (float64(c.screenh) / Pi2) c.theta = math.Max(-Pi2, math.Min(Pi2, c.theta)) } case cameraCommandMove: if cmd.Y != 0 { c.Pos.X += float64(cmd.Y) * math.Cos(c.alpha) c.Pos.Y += float64(cmd.Y) * math.Sin(c.alpha) c.Pos.Z += float64(cmd.Y) * math.Sin(c.theta) } if cmd.X != 0 { c.Pos.X += float64(cmd.X) * math.Cos(c.alpha+Pi2) c.Pos.Y += float64(cmd.X) * math.Sin(c.alpha+Pi2) } case cameraCommandReset: c.Pos = vector.V3{} c.alpha = 0 c.theta = 0 } } }
func fmtEvents(events []loggly.Event) string { result := make([]string, 0) for _, e := range events { var text string if v, ok := e.Event["json"]; ok { v := v.(map[string]interface{}) logTime, _ := time.Parse(time.RFC3339Nano, v["time"].(string)) text = fmt.Sprintf("*%v* %v %v %v u:%v", logTime.Format("01-02 15:04:05.000"), v["method"], v["path"], v["status"], v["user_id"]) } else { text = e.Logmsg if strings.Contains(e.Logmsg, "#012") { text = loggly.FmtHit(e.Logmsg) } loc, err := time.LoadLocation("Asia/Shanghai") if err != nil { loc = time.Local } t := time.Unix( e.Timestamp/1000, int64(math.Remainder(float64(e.Timestamp), 1000))*time.Millisecond.Nanoseconds(), ).In(loc).Format("01-02 15:04:05.000") text = fmt.Sprintf("*%v* %s", t, text) } result = append(result, text) } return strings.Join(result, "\n") }
// LoadTileSpec loads a TileSpec from JSON data. // JSON data should look like: // { // "0": { "Resolution": [3.1, 3.1, 40.0], "TileSize": [512, 512, 40] }, // "1": { "Resolution": [6.2, 6.2, 40.0], "TileSize": [512, 512, 80] }, // ... // } // Each line is a scale with a n-D resolution/voxel and a n-D tile size in voxels. func LoadTileSpec(data []byte) (TileSpec, error) { var config specJSON err := json.Unmarshal(data, &config) if err != nil { return nil, err } // Allocate the tile specs numLevels := len(config) specs := make(TileSpec, numLevels) dvid.Infof("Found %d scaling levels for imagetile specification.\n", numLevels) // Store resolution and tile sizes per level. var hires, lores float64 for scaleStr, levelSpec := range config { fmt.Printf("scale %s, levelSpec %v\n", scaleStr, levelSpec) scaleLevel, err := strconv.Atoi(scaleStr) if err != nil { return nil, fmt.Errorf("Scaling '%s' needs to be a number for the scale level.", scaleStr) } if scaleLevel >= numLevels { return nil, fmt.Errorf("Tile levels must be consecutive integers from [0,Max]: Got scale level %d > # levels (%d)\n", scaleLevel, numLevels) } specs[Scaling(scaleLevel)] = TileScaleSpec{LevelSpec: levelSpec} } // Compute the magnification between each level. for scaling := Scaling(0); scaling < Scaling(numLevels-1); scaling++ { levelSpec, found := specs[scaling] if !found { return nil, fmt.Errorf("Could not find tile spec for level %d", scaling) } nextSpec, found := specs[scaling+1] if !found { return nil, fmt.Errorf("Could not find tile spec for level %d", scaling+1) } var levelMag dvid.Point3d for i, curRes := range levelSpec.Resolution { hires = float64(curRes) lores = float64(nextSpec.Resolution[i]) rem := math.Remainder(lores, hires) if rem > 0.001 { return nil, fmt.Errorf("Resolutions between scale %d and %d aren't integral magnifications!", scaling, scaling+1) } mag := lores / hires if mag < 0.99 { return nil, fmt.Errorf("A resolution between scale %d and %d actually increases!", scaling, scaling+1) } mag += 0.5 levelMag[i] = int32(mag) } levelSpec.levelMag = levelMag specs[scaling] = levelSpec } return specs, nil }
// RectBound returns a bounding latitude-longitude rectangle. // The bounds are not guaranteed to be tight. func (c Cap) RectBound() Rect { if c.IsEmpty() { return EmptyRect() } capAngle := c.Radius().Radians() allLongitudes := false lat := r1.Interval{ Lo: latitude(c.center).Radians() - capAngle, Hi: latitude(c.center).Radians() + capAngle, } lng := s1.FullInterval() // Check whether cap includes the south pole. if lat.Lo <= -math.Pi/2 { lat.Lo = -math.Pi / 2 allLongitudes = true } // Check whether cap includes the north pole. if lat.Hi >= math.Pi/2 { lat.Hi = math.Pi / 2 allLongitudes = true } if !allLongitudes { // Compute the range of longitudes covered by the cap. We use the law // of sines for spherical triangles. Consider the triangle ABC where // A is the north pole, B is the center of the cap, and C is the point // of tangency between the cap boundary and a line of longitude. Then // C is a right angle, and letting a,b,c denote the sides opposite A,B,C, // we have sin(a)/sin(A) = sin(c)/sin(C), or sin(A) = sin(a)/sin(c). // Here "a" is the cap angle, and "c" is the colatitude (90 degrees // minus the latitude). This formula also works for negative latitudes. // // The formula for sin(a) follows from the relationship h = 1 - cos(a). sinA := math.Sqrt(c.height * (2 - c.height)) sinC := math.Cos(latitude(c.center).Radians()) if sinA <= sinC { angleA := math.Asin(sinA / sinC) lng.Lo = math.Remainder(longitude(c.center).Radians()-angleA, math.Pi*2) lng.Hi = math.Remainder(longitude(c.center).Radians()+angleA, math.Pi*2) } } return Rect{lat, lng} }
// Normalized returns the normalized version of the LatLng, // with Lat clamped to [-π/2,π/2] and Lng wrapped in [-π,π]. func (ll LatLng) Normalized() LatLng { lat := ll.Lat if lat > northPoleLat { lat = northPoleLat } else if lat < southPoleLat { lat = southPoleLat } lng := s1.Angle(math.Remainder(ll.Lng.Radians(), 2*math.Pi)) * s1.Radian return LatLng{lat, lng} }
func TestRectVertexCCWOrder(t *testing.T) { for i := 0; i < 4; i++ { lat := math.Pi / 4 * float64(i-2) lng := math.Pi/2*float64(i-2) + 0.2 r := Rect{ r1.Interval{lat, lat + math.Pi/4}, s1.Interval{ math.Remainder(lng, 2*math.Pi), math.Remainder(lng+math.Pi/2, 2*math.Pi), }, } for k := 0; k < 4; k++ { if !Sign(PointFromLatLng(r.Vertex((k-1)&3)), PointFromLatLng(r.Vertex(k)), PointFromLatLng(r.Vertex((k+1)&3))) { t.Errorf("%v.Vertex(%v), vertices were not in CCW order", r, k) } } } }
func getBearingDetails(degrees float64) (direction string) { windDeg := (degrees + 11.25) / 22.5 directionInt := int(math.Abs(math.Remainder(windDeg, 16))) if len(Directions) > directionInt && directionInt >= 0 { direction = Directions[directionInt] } return direction }
func (ctx *DrawContext) drawParticle(p *orrery.Particle) { p.L.Lock() defer p.L.Unlock() c := colorful.Hcl(math.Remainder((math.Pi/p.M)*360, 360), 0.9, 0.9) ctx.drawSphere(p.Pos, p.R, c) for i, pos := range p.Trail { ctx.drawSphere(pos, 1/float64(len(p.Trail)-i+1), c) } }
func testcrc32(path string) (ok bool) { ok = true d := filepath.Dir(path) var err = filepath.Walk(d, func(fpath string, f os.FileInfo, _ error) error { if filepath.Ext(fpath) == ".sfv" { printDebug("Found sfv\n%s\n", fpath) dat, err := ioutil.ReadFile(fpath) if err != nil { return err } temp := strings.Split(string(dat), "\n") for i, x := range temp { if math.Remainder(float64(i), 25) == 0 { fmt.Println("") } if len(x) < 1 { continue } if string(x[0]) == ";" { continue } result := strings.Fields(x) if len(result) > 0 { rcrc32 := result[len(result)-1] h, err := getHash(d + "\\" + result[0]) if err != nil { //fmt.Println(err) } s := strconv.FormatInt(int64(h), 16) s = strings.TrimLeft(s, "0") rcrc32 = strings.TrimLeft(rcrc32, "0") s = strings.ToUpper(s) rcrc32 = strings.ToUpper(rcrc32) if s != rcrc32 { ok = false printDebug("CRC does not match:\n%s\n%s - %s\n", result[0], rcrc32, s) } else { printDebug("%s", ".") } } } printDebug("%s\n", "") } return nil }) if err != nil { ok = false fmt.Println(err) } return }
func (hb *Rectangle) Footprint(center *terrain.Position, angle float64) []*terrain.Position { contour := hb.Contour(center) angle = math.Remainder(angle, math.Pi) if angle == 0 { return []*terrain.Position{contour[1], contour[2]} } else if angle < math.Pi/2 { // Between 0 and pi/2 return []*terrain.Position{contour[0], contour[2]} } else if angle == math.Pi/2 { return []*terrain.Position{contour[0], contour[1]} } else { // Between pi/2 and pi return []*terrain.Position{contour[1], contour[3]} } }
func (db *DB) Getbit(key string, offset int) int { db.validateKeyType(key, "string") val := db.StringsMap[key] if val == nil { return 0 } pos := math.Ceil(float64(offset) / 8.0) if len(val) < int(pos) { return 0 } offsetRem := math.Remainder(float64(val[int(pos-1)]), 8.0) return int(val[int(pos-1)]) & int(offsetRem) }
// Divide computes the number of times the denominator fits in the numerator // SEE: http://tour.golang.org/basics/3 (exportable function) // SEE: http://tour.golang.org/basics/5 (shorthand declaration) // SEE: http://tour.golang.org/basics/6 (multiple return values) func Divide(numerator, denominator float64) (quotient, remainder int) { // Guard against dividing by zero if isZero(denominator) { return } // SEE: http://tour.golang.org/basics/13 (type conversion) quotient = int(numerator / denominator) remainder = int(math.Remainder(numerator, denominator)) // SEE: http://tour.golang.org/basics/7 (named or "naked" return) return }
func (f fizzBuzz) Resolve(size int) []string { var result = make([]string, size) for i := 1; i <= size; i++ { var isMultipleOfTree = (math.Remainder(float64(i), 3) == 0) var isMultipleOfFive = (math.Remainder(float64(i), 5) == 0) if isMultipleOfTree && isMultipleOfFive { result[i-1] = "fizzbuzz" } else { if isMultipleOfTree { result[i-1] = "fizz" } else if isMultipleOfFive { result[i-1] = "buzz" } else { result[i-1] = strconv.Itoa(i) } } } return result }
func mod(v1, v2 value) value { _, ok1 := v1.(uint64) n2, ok2 := v2.(uint64) if ok1 && ok2 { if n2 == 0 { panic("divide by 0") } return Ival(v1) % Ival(v2) } f2 := Nval(v2) if f2 == 0 { panic("divide by 0") } return math.Remainder(Nval(v1), f2) }
func TestContinuity(t *testing.T) { const maxWalkLevel = 8 const cellSize = 1.0 / (1 << maxWalkLevel) // Make sure that sequentially increasing cell ids form a continuous // path over the surface of the sphere, i.e. there are no // discontinuous jumps from one region to another. maxDist := MaxWidthMetric.Value(maxWalkLevel) end := CellIDFromFace(5).ChildEndAtLevel(maxWalkLevel) id := CellIDFromFace(0).ChildBeginAtLevel(maxWalkLevel) for ; id != end; id = id.Next() { if got := id.rawPoint().Angle(id.NextWrap().rawPoint()); float64(got) > maxDist { t.Errorf("%v.rawPoint().Angle(%v.NextWrap().rawPoint()) = %v > %v", id, id, got, maxDist) } if id.NextWrap() != id.AdvanceWrap(1) { t.Errorf("%v.NextWrap() != %v.AdvanceWrap(1) %v != %v)", id, id, id.NextWrap(), id.AdvanceWrap(1)) } if id != id.NextWrap().AdvanceWrap(-1) { t.Errorf("%v.NextWrap().AdvanceWrap(-1) = %v want %v)", id, id.NextWrap().AdvanceWrap(-1), id) } // Check that the rawPoint() returns the center of each cell // in (s,t) coordinates. _, u, v := xyzToFaceUV(id.rawPoint()) if !float64Eq(math.Remainder(uvToST(u), 0.5*cellSize), 0.0) { t.Errorf("uvToST(%v) = %v, want %v", u, uvToST(u), 0.5*cellSize) } if !float64Eq(math.Remainder(uvToST(v), 0.5*cellSize), 0.0) { t.Errorf("uvToST(%v) = %v, want %v", v, uvToST(v), 0.5*cellSize) } } }
func main() { var a float64 var b float64 var z float64 fmt.Printf("%s", "Please enter a number") fmt.Scanln(&a) fmt.Printf("%s", "Please enter a larger number") fmt.Scanln(&b) fmt.Printf("%s\n", "When the second number is divided by the first number, the remainder is: ") z = math.Remainder(a, b) fmt.Printf("%f\n", z) }
func mod(v1, v2 value) value { n2, _ := v2.(int64) if uints(v1, v2) { if n2 == 0 { panic("divide by 0") } return Uval(v1) % Uval(v2) } if ints(v1, v2) { if n2 == 0 { panic("divide by 0") } return Ival(v1) % Ival(v2) } f2 := Nval(v2) if f2 == 0 { panic("divide by 0") } return math.Remainder(Nval(v1), f2) }
// Calculates the quantile func QuantileSorted(list []float64, p float64) (float64, error) { index := float64(len(list)) * p if len(list) == 0 { return 0.0, errors.New("List empty") } if p < 0 || p > 1 { return 0.0, errors.New("Quantile must be between 0 and 1") } else if p == 1 { return list[len(list)-1], nil } else if p == 0 { return list[0], nil } else if math.Remainder(p, 1) != 0 { return list[int(math.Ceil(index))-1], nil } else if len(list)%2 == 0 { return (list[int(index)-1] + list[int(index)]) / 2, nil } else { return list[int(index)], nil } }
func main() { // // 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. // What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? // // var res int64 = 20 // save some division later by skipping composite values or squares for i := 19; i > 2; i-- { prime := true for j := i - 1; j > 1; j-- { if i%j == 0 { prime = false } } if prime || math.Remainder(math.Sqrt(float64(i)), 1.0) == 0 { res *= int64(i) } } fmt.Println() fmt.Println("Testing solution...") if !valid(res) { panic("The algorithm is incorrect") } fmt.Println("value is valid, continuing") res = reduce(res) fmt.Printf("Final answer: %v\n", res) if valid(res) { fmt.Printf("and its ok\n") } else { fmt.Printf("NOT OK\n") } }