func main() { a := make([][]float64, size*size) b := make([][]float64, size*size) c := make([][]float64, size*size) for j := 0; j < size; j++ { a[j] = make([]float64, size) b[j] = make([]float64, size) c[j] = make([]float64, size) } for i := 0; i < size; i++ { for j := 0; j < size; j++ { a[i][j] = math.Floor(10 * rand.Float64()) b[i][j] = math.Floor(10 * rand.Float64()) } } print(a) fmt.Println(determinant(a)) fmt.Printf("\n") print(b) c = addition(a, b) print(c) c = multiplication(a, b) print(c) c = transpose(c) print(c) }
func (effect *FadeEffect) ComposeEffect() chan SimpleColor { c := make(chan SimpleColor, 1) keepLooping := false if effect.Repeat < 0 { keepLooping = true } max := max(effect.Color.R, effect.Color.B, effect.Color.G) go func() { for { if effect.Repeat <= 0 && !keepLooping { break } r := int(math.Floor(float64(effect.Color.R) / float64(max) * 100.0)) g := int(math.Floor(float64(effect.Color.G) / float64(max) * 100.0)) b := int(math.Floor(float64(effect.Color.B) / float64(max) * 100.0)) for i := 0; i < int(max); i += 1 { c <- SimpleColor{uint8((i * r) / 100), uint8((i * g) / 100), uint8((i * b) / 100)} time.Sleep(effect.Delay) } for i := int(max - 1); i >= 0; i -= 1 { c <- SimpleColor{uint8((i * r) / 100), uint8((i * g) / 100), uint8((i * b) / 100)} time.Sleep(effect.Delay) } effect.Repeat-- } close(c) }() return c }
func (v3 *Vector3) Floor() *Vector3 { v3.X = math.Floor(v3.X) v3.Y = math.Floor(v3.Y) v3.Z = math.Floor(v3.Z) return v3 }
// Get finds a value within (quantile - tolerance) * n <= value <= (quantile + tolerance) * n // or 0 if no values have been observed. func (est *Estimator) Get(quantile float64) float64 { if est.observations == 0 { return 0 } est.flush() cur := est.head if cur == nil { return 0 } midrank := math.Floor(quantile * est.observations) maxrank := midrank + math.Floor(est.invariant(midrank, est.observations)/2) rank := 0.0 for cur.next != nil { rank += cur.rank if rank+cur.next.rank+cur.next.delta > maxrank { return cur.v } cur = cur.next } return cur.v }
// Encode converts the path to a string using the Google Maps Polyline Encoding method. // Factor defaults to 1.0e5, the same used by Google for polyline encoding. func (p *Path) Encode(factor ...int) string { f := 1.0e5 if len(factor) != 0 { f = float64(factor[0]) } var pLat int var pLng int var result bytes.Buffer scratch1 := make([]byte, 0, 50) scratch2 := make([]byte, 0, 50) for _, p := range p.PointSet { lat5 := int(math.Floor(p.Lat()*f + 0.5)) lng5 := int(math.Floor(p.Lng()*f + 0.5)) deltaLat := lat5 - pLat deltaLng := lng5 - pLng pLat = lat5 pLng = lng5 result.Write(append(encodeSignedNumber(deltaLat, scratch1), encodeSignedNumber(deltaLng, scratch2)...)) scratch1 = scratch1[:0] scratch2 = scratch2[:0] } return result.String() }
func (p *GesturePane) Render() (*image.RGBA, error) { img := image.NewRGBA(image.Rect(0, 0, 16, 16)) if p.last != nil { x := math.Floor(float64(p.last.Position.X)/float64(0xffff)*float64(16)) + 0.5 y := math.Floor(float64(p.last.Position.Y)/float64(0xffff)*float64(16)) + 0.5 z := math.Floor(float64(p.last.Position.Z)/float64(0xffff)*float64(16)) + 0.5 r, _ := colorful.Hex("#FF000") g, _ := colorful.Hex("#00FF00") b, _ := colorful.Hex("#0000FF") gc := draw2d.NewGraphicContext(img) gc.SetStrokeColor(r) gc.MoveTo(0, x) gc.LineTo(16, x) gc.Stroke() gc.SetStrokeColor(g) gc.MoveTo(y, 0) gc.LineTo(y, 16) gc.Stroke() gc.SetStrokeColor(b) gc.MoveTo(16-z, 0) gc.LineTo(16-z, 16) gc.Stroke() } return img, nil }
func RGBColorDivNumber(c *ast.RGBColor, n *ast.Number) *ast.RGBColor { var val = n.Value var r = math.Floor(float64(c.R) / val) var g = math.Floor(float64(c.G) / val) var b = math.Floor(float64(c.B) / val) return ast.NewRGBColor(uint32(r), uint32(g), uint32(b), nil) }
func main() { bi := bufio.NewReader(os.Stdin) bo := bufio.NewWriter(os.Stdout) defer bo.Flush() var p_fl, q_fl float64 fmt.Fscan(bi, &p_fl, &q_fl) p := int64(math.Floor(p_fl*100.0 + .5)) q := int64(math.Floor(q_fl*100.0 + .5)) var k int64 for k = 1; true; k++ { kk := 10000 * k pp := kk / p qq := kk / q if qq < pp { if kk%p == 0 && pp-qq == 1 { // special case: 10000 * k ~ p } else { break } } } fmt.Fprintln(bo, 10000*k/q+1) }
func CheckCollision(pb *box, dx, dy float64) (col bool, nx, ny float64) { for x := int(math.Floor(pb.x/tileSize) - 1); x <= int(math.Ceil((pb.x+pb.w)/tileSize)+1); x++ { for y := int(math.Floor(pb.y/tileSize) - 1); y <= int(math.Ceil((pb.y+pb.h)/tileSize)+1); y++ { t := GetTile(x, y) if t.IsSolid() { b := &box{ x: float64(x) * tileSize, y: float64(y) * tileSize, w: tileSize, h: tileSize, } if b.collides(pb) { col = true if dx < 0 { nx = b.x + b.w + 0.001 } else if dx > 0 { nx = b.x - pb.w - 0.001 } if dy < 0 { ny = b.y + b.h + 0.001 } else if dy > 0 { ny = b.y - pb.h - 0.001 } nx /= tileSize ny /= tileSize return } } } } return }
// TrimMean returns the mean of the interior of a supplied set of values // Array - An array of numeric values, for which you want to calculate the trimmed mean // Percent - The percentage of values that you want to be discarded from the supplied array func TrimMean(percent float64, arrays ...float64) (float64, error) { // First find n = number of observations n := float64(len(arrays)) // Reorder them as "order statistics" Xi from the smallest to the largest sort.Sort(SmallNums(arrays)) if math.IsNaN(percent) { return 0.0, errors.New("#VALUE! - Occurred because the percent argument cannot be interpreted as a Numeric value") } // Find lower case p=P/100 = proportion trimmed p := percent / 100.00 if p < 0 || p > 1 { return 0.0, errors.New("#NUM!, Occurred the supplied percent argument is < 0 or > 1") } // If np is an integer use k=np and trim k observations at both ends. k := math.Floor((n * p) / 2) //r = remaining observations = n−2k r := n - (2 * k) k = math.Floor(k) // Trimmed mean = (1/R)(Xk+1+Xk+2+…+Xn−k) sum := 0.0 for i := int(k); i <= int(n-k-1); i++ { sum += arrays[i] } return (1 / r) * sum, nil }
func (g Raster) Accept(visitor Visitor) { c := new(Composite) hc := math.Floor(g.Width / g.Dx / 2) vc := math.Floor(g.Height / g.Dy / 2) hw := g.Width / 2 hh := g.Height / 2 if g.Dx != 0 { for i := -hc; i <= hc; i++ { x := i*g.Dx + g.Center.X segment := LineSegment{P(x, g.Center.Y-hh), P(x, g.Center.Y+hh)} c.Add(segment) } } else { segment := LineSegment{P(g.Center.X, g.Center.Y-hh), P(g.Center.X, g.Center.Y+hh)} c.Add(segment) } if g.Dy != 0 { for i := -vc; i <= vc; i++ { y := i*g.Dy + g.Center.Y segment := LineSegment{P(g.Center.X-hw, y), P(g.Center.X+hw, y)} c.Add(segment) } } else { segment := LineSegment{P(g.Center.X-hw, g.Center.Y), P(g.Center.X+hw, g.Center.Y)} c.Add(segment) } c.Accept(visitor) }
func (e *Entity) Colliding() bool { playerSize := .5 sx := int(math.Floor(e.x - playerSize/2)) sy := int(math.Floor(e.y - playerSize/2)) sz := int(math.Floor(e.z - playerSize/2)) lx := int(math.Ceil(e.x + playerSize/2)) ly := int(math.Ceil(e.y + playerSize/2)) lz := int(math.Ceil(e.z + playerSize/2)) if sx < 0 || lx >= worldW || sz < 0 || lz >= worldD { return true } if sy < 0 || ly >= worldH { return false } for ix := sx; ix < lx; ix += 1 { for iy := sy; iy < ly; iy += 1 { for iz := sz; iz < lz; iz += 1 { blockType := level[ix][iy][iz] if blockType > 0 { return true } } } } return false }
func square(im *webimg.Image, size int) error { im_cols, _ := webimg.Wi_get_cols(im) im_rows, _ := webimg.Wi_get_rows(im) var x, y, cols int if im_cols > im_rows { cols = im_rows y = 0 x = int(math.Floor(float64(im_cols-im_rows) / 2.0)) } else { cols = im_cols x = 0 y = int(math.Floor(float64(im_rows-im_cols) / 2.0)) } _, err := webimg.Wi_crop(im, x, y, cols, cols) if err != nil { return err } _, err = webimg.Wi_scale(im, size, 0) if err != nil { return err } return nil }
func mouseButtonCallback(button, state int) { if currExX != -1 || currExY != -1 || mouseLock || len(selectedHex) < 3 { return } x, y := glfw.MousePos() if state == glfw.KeyPress { switch button { case glfw.MouseLeft: // fmt.Println(x, y) currExX = int(math.Floor((float64(x) - 80) / 33)) currExY = int(math.Floor((float64(y) - 80 - 19) / 38)) if currExX%2 == 1 { currExY = (y - 80) / 36 } if currExX > 9 || currExY > 8 || currExX < 0 || currExY < 0 { currExX = -1 currExY = -1 return } if hexMap[currExX][currExY] == 6 && currExX > 0 && currExX < 9 && currExY > 0 && (currExX%2 == 0 && currExY < 7 || currExX%2 == 1 && currExY < 8) { starRotate = true } timesToRotate = 2 mouseLock = true fmt.Println("Mouse locked") // fmt.Println(currExX, currExY) // renderHexMap(currExX, currExY) } } }
// AsInt accepts an int or float64 value and converts it to an int value. func AsInt(v interface{}) int { switch t := v.(type) { case int: return t case float64: if math.Floor(t) == t { return int(t) } panic("precision") case complex128: if imag(t) != 0 { panic("imaginary integers") } f := real(t) if math.Floor(f) == f { return int(f) } panic("real precision") case string: i, err := strconv.Atoi(t) if err != nil { panic("illegible integer") } return i } panic(4) }
func (this *Summary) getCycleInfo(pTime time.Time) (*Cycle, error) { lengthSeconds := this.Length.Seconds() passedSeconds := pTime.Sub(this.Created).Seconds() if passedSeconds < 0 { return nil, ErrCycleTimeTooEarlier } periodsFloat := float64(this.Periods) periodLength := math.Ceil(lengthSeconds / periodsFloat) periodFloat := math.Floor(passedSeconds / periodLength) periodID := int64(periodFloat) resetFloat := int64(math.Floor(periodFloat / periodsFloat)) segmentScrollID := periodID % int64(this.Periods) segmentID := resetFloat % int64(this.Reset) // Following result // Make sure all the number below is larger than 0 return &Cycle{ Period: periodID + 1, Segments: segmentScrollID + 1, Segment: segmentID + 1, }, nil }
func (api *DistanceMatrixAPI) groupCoordinates(origins []Coordinates, destinations []Coordinates, maxGroupSize int) (apiCalls []ApiCall) { if maxGroupSize == 1 { apiCalls = append(apiCalls, ApiCall{origins, destinations}) return apiCalls } destinationsSize := len(destinations) originsSize := len(origins) if destinationsSize > originsSize { //Split destinations maxBlockSize := math.Floor(float64(destinationsSize) / float64(maxGroupSize)) blocks := splitSliceIntoBlocks(destinations, int(maxBlockSize)) for _, b := range blocks { apiCalls = append(apiCalls, ApiCall{ Origins: origins, Destinations: b, }) } } else { //Split origins maxBlockSize := math.Floor(float64(originsSize) / float64(maxGroupSize)) blocks := splitSliceIntoBlocks(origins, int(maxBlockSize)) for _, o := range blocks { apiCalls = append(apiCalls, ApiCall{ Origins: o, Destinations: destinations, }) } } return apiCalls }
// fast nearest-neighbor resize, no filtering func resizeNearest(src *image.NRGBA, width, height int) *image.NRGBA { dstW, dstH := width, height srcBounds := src.Bounds() srcW := srcBounds.Max.X srcH := srcBounds.Max.Y dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH)) dx := float64(srcW) / float64(dstW) dy := float64(srcH) / float64(dstH) Parallel(dstH, func(partStart, partEnd int) { for dstY := partStart; dstY < partEnd; dstY++ { fy := (float64(dstY)+0.5)*dy - 0.5 for dstX := 0; dstX < dstW; dstX++ { fx := (float64(dstX)+0.5)*dx - 0.5 srcX := int(math.Min(math.Max(math.Floor(fx+0.5), 0.0), float64(srcW))) srcY := int(math.Min(math.Max(math.Floor(fy+0.5), 0.0), float64(srcH))) srcOff := srcY*src.Stride + srcX*4 dstOff := dstY*dst.Stride + dstX*4 copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4]) } } }) return dst }
func HexColorDivNumber(color *ast.HexColor, num *ast.Number) *ast.HexColor { r := uint32(math.Floor(float64(color.R) / num.Value)) g := uint32(math.Floor(float64(color.G) / num.Value)) b := uint32(math.Floor(float64(color.B) / num.Value)) hex := ast.Hex(fmt.Sprintf("#%02X%02X%02X", r, g, b)) return &ast.HexColor{hex, r, g, b, nil} }
func Deg2num(lng, lat float64, zoom int) (x, y int) { n := math.Exp2(float64(zoom)) x = int(math.Floor((lng + 180.0) / 360.0 * n)) lat_rad := lat * math.Pi / 180 y = int(math.Floor((1.0 - math.Log(math.Tan(lat_rad)+1.0/math.Cos(lat_rad))/math.Pi) / 2.0 * n)) return }
func formatTime(t time.Time) string { s := time.Since(t) switch { case s.Seconds() < 60: f := "second" if math.Floor(s.Seconds()) > 1 { f += "s" } return fmt.Sprintf("%d "+f+" ago", int(s.Seconds())) case s.Minutes() < 60: f := "minute" if math.Floor(s.Minutes()) > 1 { f += "s" } return fmt.Sprintf("%d "+f+" ago", int(s.Minutes())) case s.Hours() < 24: f := "hour" if math.Floor(s.Hours()) > 1 { f += "s" } return fmt.Sprintf("%d "+f+" ago", int(s.Hours())) default: layout := "Jan 2, 2006 at 3:04pm (MST)" return t.Format(layout) } }
func EncodeInt(value int64) string { var output string var remainder int64 var numberOfCycles int64 base := int64(62) remainder = value % base output = encodeStd2[remainder] numberOfCycles = int64(math.Floor(float64(value/base))) - 1 if numberOfCycles >= 0 && numberOfCycles < 62 { output = strings.Join([]string{encodeStd2[numberOfCycles], output}, "") } for i := 0; i < 10; i++ { if numberOfCycles < 62 { break } i = 0 remainder = numberOfCycles % base numberOfCycles = int64(math.Floor(float64(numberOfCycles/base))) - 1 output = strings.Join([]string{encodeStd2[remainder], output}, "") if numberOfCycles <= 0 { i = 10 } } return output }
func (p *AbsXyz) ToBlockXyz() *BlockXyz { return &BlockXyz{ BlockCoord(math.Floor(float64(p.X))), BlockYCoord(math.Floor(float64(p.Y))), BlockCoord(math.Floor(float64(p.Z))), } }
func continuedFracSqrt(S float64) []int { // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Continued_fraction_expansion // Using variables S, m, d, a as in the URL above. m := 0.0 d := 1.0 a := math.Floor(math.Sqrt(S)) result := []int{} seen := make(map[string]bool) for { seen[k([]float64{m, d, a})] = true result = append(result, int(a)) m = (d * a) - m d = (S - math.Pow(m, 2.0)) / d if d == 0 { // S is a perfect square. return result } a = math.Floor((math.Floor(math.Sqrt(S)) + m) / d) // The algorithm terminates when [m d a] repeats. if seen[k([]float64{m, d, a})] { return result } } }
// Round return rounded version of x with prec precision. // // Special cases are: // Round(±0) = ±0 // Round(±Inf) = ±Inf // Round(NaN) = NaN func Round(x float64, prec int, method string) float64 { var rounder float64 maxPrec := 7 // define a max precison to cut float errors if maxPrec < prec { maxPrec = prec } pow := math.Pow(10, float64(prec)) intermed := x * pow _, frac := math.Modf(intermed) switch method { case ROUNDING_UP: if frac >= math.Pow10(-maxPrec) { // Max precision we go, rest is float chaos rounder = math.Ceil(intermed) } else { rounder = math.Floor(intermed) } case ROUNDING_DOWN: rounder = math.Floor(intermed) case ROUNDING_MIDDLE: if frac >= 0.5 { rounder = math.Ceil(intermed) } else { rounder = math.Floor(intermed) } default: rounder = intermed } return rounder / pow }
// NewArbSlice returns an image with arbitrary 3D orientation. // The 3d points are in real world space definited by resolution, e.g., nanometer space. func (d *Data) NewArbSlice(topLeft, topRight, bottomLeft dvid.Vector3d, res float64) (*ArbSlice, error) { // Compute the increments in x,y and number of pixes in each direction. dx := topRight.Distance(topLeft) dy := bottomLeft.Distance(topLeft) nxFloat := math.Floor(dx / res) nyFloat := math.Floor(dy / res) incrX := topRight.Subtract(topLeft).DivideScalar(nxFloat) incrY := bottomLeft.Subtract(topLeft).DivideScalar(nyFloat) size := dvid.Point2d{int32(nxFloat) + 1, int32(nyFloat) + 1} bytesPerVoxel := d.Properties.Values.BytesPerElement() arb := &ArbSlice{topLeft, topRight, bottomLeft, res, size, incrX, incrY, bytesPerVoxel, nil} // Allocate the image buffer numVoxels := size[0] * size[1] if numVoxels <= 0 { return nil, fmt.Errorf("Bad arbitrary image size requested: %s", arb) } requestSize := int64(bytesPerVoxel) * int64(numVoxels) if requestSize > server.MaxDataRequest { return nil, fmt.Errorf("Requested payload (%d bytes) exceeds this DVID server's set limit (%d)", requestSize, server.MaxDataRequest) } arb.data = make([]byte, requestSize) return arb, nil }
// Small test program to get things running func main() { window := window.NewWindow("My Application", 800, 600) // Create window to draw on window.Create() defer window.Destroy() // Calculate midpoints midX := math.Floor(float64(window.Width) / 2.0) midY := math.Floor(float64(window.Height) / 2.0) maxRadius := math.Min(float64(window.Height), float64(window.Width)) for frame := 0.0; ; frame++ { window.Backbuffer.Fill(0xFF000000) radius := float64(int(frame)%int(maxRadius)) / 2.0 // Draw something weird on-screen for i := 0.0; i < 5.0; i++ { for theta := 0.0; theta < 2.0*math.Pi; theta += 0.005 { y := int(math.Floor(midY - (radius-(i+theta*20.0))*math.Sin(theta*i+(frame)))) x := int(math.Floor(midX - (radius-(i+theta*50.0))*math.Cos(theta*i+(frame)))) window.Backbuffer.DrawPixel( x, y, uint32(0xFF0000FF)|((uint32(frame)%255)<<8)) } window.Update() } time.Sleep(time.Millisecond * (1000 / 30)) } }
func imageCalculations(o *Options, inWidth, inHeight int) float64 { factor := 1.0 xfactor := float64(inWidth) / float64(o.Width) yfactor := float64(inHeight) / float64(o.Height) switch { // Fixed width and height case o.Width > 0 && o.Height > 0: if o.Crop { factor = math.Min(xfactor, yfactor) } else { factor = math.Max(xfactor, yfactor) } // Fixed width, auto height case o.Width > 0: factor = xfactor o.Height = int(math.Floor(float64(inHeight) / factor)) // Fixed height, auto width case o.Height > 0: factor = yfactor o.Width = int(math.Floor(float64(inWidth) / factor)) // Identity transform default: o.Width = inWidth o.Height = inHeight break } return factor }
func glitchImage(wand *imagick.MagickWand, q url.Values) ([]byte, error) { data := wand.GetImage().GetImageBlob() jpgHeaderLength := getJpegHeaderSize(data) maxIndex := len(data) - jpgHeaderLength - 4 params := getParams(q) length := int(params["iterations"]) for i := 0; i < length; i++ { pxMin := math.Floor(float64(maxIndex) / params["iterations"] * float64(i)) pxMax := math.Floor(float64(maxIndex) / params["iterations"] * float64((i + 1))) delta := pxMax - pxMin pxI := math.Floor(pxMin + delta*params["seed"]) if int(pxI) > maxIndex { pxI = float64(maxIndex) } index := math.Floor(float64(jpgHeaderLength) + pxI) data[int(index)] = byte(math.Floor(params["amount"] * float64(256))) } wand2 := imagick.NewMagickWand() if err := wand2.ReadImageBlob(data); err != nil { return nil, err } if err := wand2.SetImageFormat("PNG"); err != nil { return nil, err } return wand2.GetImage().GetImageBlob(), nil }
// as reference, this is similar to the opencv one // Sampler func elbp(m *Matrix, pos, radius int) (way uint8) { way = 0 cen := m.e[pos] for n := uint8(0); n < 8; n++ { x := float64(-radius) * math.Sin(math.Pi*float64(n)/4.0) y := float64(radius) * math.Cos(math.Pi*float64(n)/4.0) fx := math.Floor(x) fy := math.Floor(y) cx := math.Ceil(x) cy := math.Ceil(y) // fractional part ty := y - fy tx := x - fx // set interpolation weights w1 := (1.0 - tx) * (1.0 - ty) w2 := tx * (1.0 - ty) w3 := (1.0 - tx) * ty w4 := tx * ty t := w1 * float64(m.e[pos+int(fx)+int(fy)*m.w]) t += w2 * float64(m.e[pos+int(cx)+int(fy)*m.w]) t += w3 * float64(m.e[pos+int(fx)+int(cy)*m.w]) t += w4 * float64(m.e[pos+int(cx)+int(cy)*m.w]) if uint8(t) > cen { way |= 1 << n } } return }