func TestEarth2(t *testing.T) { // p. 274 v, err := pp.LoadPlanet(pp.Earth) if err != nil { t.Fatal(err) } for _, d := range ep { yf := float64(d.y) + (float64(d.m)-.5)/12 u, r := pa.Perihelion2(pa.Earth, yf, .0004, v) y, m, df := julian.JDToCalendar(u) dd, f := math.Modf(df) if y != d.y || m != d.m || int(dd) != d.d || math.Abs(f*24-d.h) > .01 || math.Abs(r-d.r) > .000001 { t.Log(d) t.Fatal(y, m, int(dd), f*24, r) } } for _, d := range ea { yf := float64(d.y) + (float64(d.m)-.5)/12 u, r := pa.Aphelion2(pa.Earth, yf, .0004, v) y, m, df := julian.JDToCalendar(u) dd, f := math.Modf(df) if y != d.y || m != d.m || int(dd) != d.d || math.Abs(f*24-d.h) > .01 || math.Abs(r-d.r) > .000001 { t.Log(d) t.Fatal(y, m, int(dd), f*24, r) } } }
/* Medium returns a map of New Zealand at medium resolution. The underlying longitude latitude grid is in 0.1 increments. Linear interpolation is used between grid points to estimate the location of each Point on the map. */ func (pts Points) Medium(b *bytes.Buffer) { b.WriteString(nzMedium) // the long/lat grid is accurate to 0.1 degree below that use a linear approximation between // the grid values. This removes liniations in the plot var p, pp pt for i, v := range pts { if v.Longitude < 0 { v.Longitude = v.Longitude + 360.0 } xi, xf := math.Modf(v.Longitude*10 - 1650.0) x := int(xi) yi, yf := math.Modf(v.Latitude*10 + 480.0) y := int(yi) if x >= 0 && x <= 150 && y >= 0 && y <= 140 { p = nzMediumPts[int(x)][y] pp = nzMediumPts[x+1][y+1] pts[i].x = p.x + int(float64(pp.x-p.x)*xf) pts[i].y = p.y + int(float64(pp.y-p.y)*yf) pts[i].visible = true } else { pts[i].x = -1000 pts[i].y = -1000 } } return }
func (g *stereoSine) processAudio(out [][]float32) { for i := range out[0] { val1 := g.volume * math.Sin(2*math.Pi*g.phase1) val2 := g.volume * math.Sin(2*math.Pi*g.phase2) val1l := math.Max(val1*g.pan1, 0) * 0.5 val2l := math.Max(val2*g.pan2, 0) * 0.5 val1r := math.Max(val1*-g.pan1, 0) * 0.5 val2r := math.Max(val2*-g.pan2, 0) * 0.5 out[0][i] = float32(val1l + val2l) out[1][i] = float32(val1r + val2r) _, g.phase1 = math.Modf(g.phase1 + g.step1) _, g.phase2 = math.Modf(g.phase2 + g.step2) g.volume += g.fade if g.volume < 0 { g.volume = 0 g.fade = 0 g.control <- true } if g.volume > 1 { g.volume = 1 g.fade = 0 g.control <- true } } }
func generateRandomNetwork(address *net.IPNet) string { tick := float64(time.Now().UnixNano() / 1000000) ones, bits := address.Mask.Size() zeros := bits - ones uniqIPsAmount := math.Pow(2.0, float64(zeros)) rawIP := math.Mod(tick, uniqIPsAmount) remainder := rawIP remainder, octet4 := math.Modf(remainder / 255.0) remainder, octet3 := math.Modf(remainder / 255.0) remainder, octet2 := math.Modf(remainder / 255.0) base := address.IP address.IP = net.IPv4( byte(remainder)|base[0], byte(octet2*255)|base[1], byte(octet3*255)|base[2], byte(octet4*255)|base[3], ) address.IP.Mask(address.Mask) return address.String() }
func LatLongToString(pc *PolarCoord, format LatLongFormat) (string, string) { var lat, long, latrem, longrem, latmin, longmin, latsec, longsec float64 var latitude, longitude string switch format { case LLFdeg: latitude = f64toa(pc.Latitude, 6) longitude = f64toa(pc.Longitude, 6) case LLFdms: lat, latrem = math.Modf(pc.Latitude) if lat < 0 { lat *= -1 latrem *= -1 } long, longrem = math.Modf(pc.Longitude) if long < 0 { long *= -1 longrem *= -1 } latmin, latrem = math.Modf(latrem / 100 * 6000) longmin, longrem = math.Modf(longrem / 100 * 6000) latsec = latrem / 100 * 6000 longsec = longrem / 100 * 6000 if pc.Latitude < 0 { latitude = "S " } else { latitude = "N " } latitude += fmt.Sprintf("%d°", int(lat)) if latmin != 0.0 || latsec != 0.0 { latitude += fmt.Sprintf("%d'", int(latmin)) } if latsec != 0.0 { latitude += fmt.Sprintf("%s''", f64toa(latsec, 2)) } if pc.Longitude < 0 { longitude = "W " } else { longitude = "E " } longitude += fmt.Sprintf("%d°", int(long)) if longmin != 0.0 || longsec != 0.0 { longitude += fmt.Sprintf("%d'", int(longmin)) } if longsec != 0.0 { longitude += fmt.Sprintf("%s''", f64toa(longsec, 2)) } } return latitude, longitude }
// ProcessAudio processes the audio func (sine *Sine) ProcessAudio(out [][2]float32) { for i := range out { out[i][0] = float32(math.Sin(2 * math.Pi * sine.phaseL)) _, sine.phaseL = math.Modf(sine.phaseL + sine.stepL) out[i][1] = float32(math.Sin(2 * math.Pi * sine.phaseR)) _, sine.phaseR = math.Modf(sine.phaseR + sine.stepR) } }
func (g *stereoSine) processAudio(out [][]float32) { for i := range out[0] { out[0][i] = float32(math.Sin(2 * math.Pi * g.phaseL)) _, g.phaseL = math.Modf(g.phaseL + g.stepL) out[1][i] = float32(math.Sin(2 * math.Pi * g.phaseR)) _, g.phaseR = math.Modf(g.phaseR + g.stepR) } }
func GetChunkCoords(x float32, y float32) (float32, float32) { chunkSize := float64(100) xRoot, _ := math.Modf(float64(x) / chunkSize) yRoot, _ := math.Modf(float64(y) / chunkSize) return float32(xRoot * chunkSize), float32(yRoot * chunkSize) }
func julianDateToGregorianTime(part1, part2 float64) time.Time { part1I, part1F := math.Modf(part1) part2I, part2F := math.Modf(part2) julianDays := part1I + part2I julianFraction := part1F + part2F julianDays, julianFraction = shiftJulianToNoon(julianDays, julianFraction) day, month, year := doTheFliegelAndVanFlandernAlgorithm(int(julianDays)) hours, minutes, seconds, nanoseconds := fractionOfADay(julianFraction) return time.Date(year, time.Month(month), day, hours, minutes, seconds, nanoseconds, time.UTC) }
// durationToSQL converts a time.Duration to ISO standard SQL syntax, // e.g. "1 2:3:4" for one day, two hours, three minutes, and four seconds. func durationToSQL(d time.Duration) []byte { dSeconds := d.Seconds() dMinutes, fSeconds := math.Modf(dSeconds / 60) seconds := fSeconds * 60 dHours, fMinutes := math.Modf(dMinutes / 60) minutes := fMinutes * 60 days, fHours := math.Modf(dHours / 24) hours := fHours * 24 sql := fmt.Sprintf("%.0f %.0f:%.0f:%f", days, hours, minutes, seconds) return []byte(sql) }
func (g *stereoSine) processAudio(out [][]float32) { var t float64 = 0 for i := range out[0] { out[0][i] = float32(math.Sin(2*math.Pi*g.phaseL*(t/float64(bpm)))) / 2 //out[0][i] = float32(math.Sin(2 * math.Pi * float64(tcp%400) * (t / float64(bpm)))) _, g.phaseL = math.Modf(g.phaseL + g.stepL) out[1][i] = float32(math.Sin(2*math.Pi*g.phaseR*(t/float64(bpm)))) / 2 //out[1][i] = float32(math.Sin(2 * math.Pi * float64(tcp%400) * (t / float64(bpm)))) _, g.phaseR = math.Modf(g.phaseR + g.stepR) t++ } }
// NumberFormat convert float or int to string (like PHP number_format() ) // in local format, for example: // NumberFormat( 123456.12, 4, ",", " " ) // >> 123 456,1200 // // Special cases are: // NumberFormat(±Inf) = formatted 0.0 // NumberFormat(NaN) = formatted 0.0 func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string { if math.IsNaN(number) || math.IsInf(number, 0) { number = 0 } var ret string var negative bool if number < 0 { number *= -1 negative = true } d, fract := math.Modf(number) if decimals <= 0 { fract = 0 } else { pow := math.Pow(10, float64(decimals)) fract = RoundPrec(fract*pow, 0) } if thousandsSep == "" { ret = strconv.FormatFloat(d, 'f', 0, 64) } else if d >= 1 { var x float64 for d >= 1 { d, x = math.Modf(d / 1000) x = x * 1000 ret = strconv.FormatFloat(x, 'f', 0, 64) + ret if d >= 1 { ret = thousandsSep + ret } } } else { ret = "0" } fracts := strconv.FormatFloat(fract, 'f', 0, 64) // "0" pad left for i := len(fracts); i < decimals; i++ { fracts = "0" + fracts } ret += decPoint + fracts if negative { ret = "-" + ret } return ret }
// 范围随机数 float64 // 只随机精度的值,随机精度范围[0.x... -- 0.x...] func RandBetweenFloat(s, n float64) float64 { if s > n { s, n = n, s } _, sFrac := math.Modf(s) _, nFrac := math.Modf(n) mathrand.Seed(time.Now().UnixNano()) rf := float64(mathrand.Int63()) / (1 << 63) rf = sFrac + rf*(nFrac-sFrac) return rf }
func (me *renderTile) CastRay(x, y int, col *color.RGBA) { me.fx, me.fy = float64(x), float64(y) col.R, col.G, col.B, col.A = 0, 0, 0, 0 me.rayPos.X, me.rayPos.Y, me.rayPos.Z = ((me.fx / width) - 0.5), ((me.fy / height) - 0.5), 0 me.rayPos.MultMat(cmat1) me.rayTmp.X, me.rayTmp.Y, me.rayTmp.Z = 0, 0, planeDist me.rayTmp.MultMat(cmat1) // if (CamRot.Y != 0) && ((x == 0) || (x == 39) || (x == 79) || (x == 119) || (x == 159)) && ((y == 0) || (y == 44) || (y == 89)) { log.Printf("[%v,%v] 0,0,%v ==> %+v (for %+v)", x, y, planeDist, me.rayTmp, me.rayDir) } me.rayDir.X, me.rayDir.Y, me.rayDir.Z = me.rayPos.X, me.rayPos.Y, me.rayPos.Z-me.rayTmp.Z me.rayDir.Normalize() me.rayDir.MultMat(pmat) me.rayPos.Add(CamPos) // me.rayDir.X, me.rayDir.Y, me.rayDir.Z = -((me.fx / width) - 0.5), -((me.fy / height) - 0.5), planeDist if true { // if ((x == 0) || (x == 159)) && ((y == 0) || (y == 89)) { log.Printf("RAYPOS[%v,%v]=%+v", x, y, me.rayPos) } me.numSteps = 0 for (col.A < 255) && me.rayPos.AllInRange(vmin, vmax) && (me.numSteps <= (vboth)) { me.numSteps++ if me.rayPos.AllInRange(0, fs) { if col.A == 0 { if (int(me.rayPos.X) == 0) || (int(me.rayPos.X) == (SceneSize - 1)) { col.R, col.G, col.B, col.A = 0, 0, 64, 64 } else if (int(me.rayPos.Y) == 0) || (int(me.rayPos.Y) == (SceneSize - 1)) { col.R, col.G, col.B, col.A = 0, 64, 0, 64 } else { col.R, col.G, col.B, col.A = 32, 32, 32, 48 } } if samples { _, me.fracx = math.Modf(me.rayPos.X) _, me.fracy = math.Modf(me.rayPos.Y) _, me.fracz = math.Modf(me.rayPos.Z) me.rayIntX, me.rayIntY, me.rayIntZ = int(me.rayPos.X), int(me.rayPos.Y), int(me.rayPos.Z) me.lrayIntX, me.lrayIntY, me.lrayIntZ = int(me.rayPos.X+1), int(me.rayPos.Y+1), int(me.rayPos.Z+1) me.getSample(me.rayIntX, me.rayIntY, me.rayIntZ, col) me.getSample(me.lrayIntX, me.rayIntY, me.rayIntZ, &me.colx) me.getSample(me.rayIntX, me.lrayIntY, me.rayIntZ, &me.coly) me.getSample(me.rayIntX, me.rayIntY, me.lrayIntZ, &me.colz) //me.mixAll() } else { me.rayIntX, me.rayIntY, me.rayIntZ = int(me.rayPos.X), int(me.rayPos.Y), int(me.rayPos.Z) me.getSample(me.rayIntX, me.rayIntY, me.rayIntZ, col) } } me.rayPos.Add(me.rayDir) } } }
func preComputeFilter(scale float64, outSize, srcSize int, scaleBpp float64) []filter { ret := make([]filter, outSize) // The minimum worthwhile fraction of a pixel. This value is also used // to avoid direct floating-point comparisons; instead of comparing two // values for equality, we test if their difference is smaller than this // value. const minFrac = 1.0 / 256.0 for i := 0; i < outSize; i++ { // compute the address and first weight addr, invw := math.Modf(float64(i) * scale) ret[i].idx = int(addr) frstw := 1.0 - invw if frstw < minFrac { ret[i].idx++ frstw = 0.0 } else { ret[i].n = 1 } // compute the number of pixels count, frac := math.Modf(scale - frstw) ret[i].n = ret[i].n + int(count) if frac >= minFrac { ret[i].n++ } else { frac = 0.0 } // allocate the slice of weights ret[i].weights = make([]float64, ret[i].n) var windx int if frstw > 0.0 { ret[i].weights[windx] = frstw / scale * scaleBpp windx++ } for j := 0; j < int(count); j++ { ret[i].weights[windx] = 1.0 / scale * scaleBpp windx++ } if frac > 0.0 { ret[i].weights[windx] = frac / scale * scaleBpp } } return ret }
// 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 }
func ExampleTime() { // Example 19.a, p. 121. // convert degree data to radians r1 := 113.56833 * math.Pi / 180 d1 := 31.89756 * math.Pi / 180 r2 := 116.25042 * math.Pi / 180 d2 := 28.03681 * math.Pi / 180 r3 := make([]float64, 5) for i, ri := range []float64{ 118.98067, 119.59396, 120.20413, 120.81108, 121.41475} { r3[i] = ri * math.Pi / 180 } d3 := make([]float64, 5) for i, di := range []float64{ 21.68417, 21.58983, 21.49394, 21.39653, 21.29761} { d3[i] = di * math.Pi / 180 } // use JD as time to handle month boundary jd, err := line.Time(r1, d1, r2, d2, r3, d3, julian.CalendarGregorianToJD(1994, 9, 29), julian.CalendarGregorianToJD(1994, 10, 3)) if err != nil { fmt.Println(err) return } y, m, d := julian.JDToCalendar(jd) dInt, dFrac := math.Modf(d) fmt.Printf("%d %s %.4f\n", y, time.Month(m), d) fmt.Printf("%d %s %d, at %h TD(UT)\n", y, time.Month(m), int(dInt), sexa.NewFmtTime(dFrac*24*3600)) // Output: // 1994 October 1.2233 // 1994 October 1, at 5ʰ TD(UT) }
func Round(v float64) float64 { var frac float64 if _, frac = math.Modf(v); frac >= 0.5 { return math.Ceil(v) } return math.Floor(v) }
// Validate validates and normalize integer based value func (v Integer) Validate(value interface{}) (interface{}, error) { if f, ok := value.(float64); ok { // JSON unmarshaling treat all numbers as float64, try to convert it to int if not fraction i, frac := math.Modf(f) if frac == 0.0 { v := int(i) value = &v } } i, ok := value.(*int) if !ok { return nil, errors.New("not an integer") } if v.Min != nil && *i < *v.Min { return nil, fmt.Errorf("is lower than %d", *v.Min) } if v.Max != nil && *i > *v.Max { return nil, fmt.Errorf("is greater than %d", *v.Max) } if len(v.Allowed) > 0 { found := false for _, allowed := range v.Allowed { if *i == allowed { found = true break } } if !found { // TODO: build the list of allowed values return nil, fmt.Errorf("not one of the allowed values") } } return i, nil }
// Round a float to a specific decimal place or precision func Round(input float64, places int) (rounded float64, err error) { // If the float is not a number if math.IsNaN(input) { return 0.0, errors.New("Not a number") } // Find out the actual sign and correct the input for later sign := 1.0 if input < 0 { sign = -1 input *= -1 } // Use the places arg to get the amount of precision wanted precision := math.Pow(10, float64(places)) // Find the decimal place we are looking to round digit := input * precision // Get the actual decimal number as a fraction to be compared _, decimal := math.Modf(digit) // If the decimal is less than .5 we round down otherwise up if decimal >= 0.5 { rounded = math.Ceil(digit) } else { rounded = math.Floor(digit) } // Finally we do the math to actually create a rounded number return rounded / precision * sign, nil }
func (p Palette) Color(x float64) color.Color { n := x * float64(len(p)) c1 := p[int(math.Floor(n))] c2 := p[int(math.Min(math.Ceil(n), float64(len(p)-1)))] _, t := math.Modf(n) return blendRGBA(c1, c2, t) }
func Round32(x float32) float32 { i, f := math.Modf(float64(x)) if f >= 0.5 { return float32(i) + 1.0 } return float32(i) }
func reqlTimeToNativeTime(timestamp float64, timezone string) (time.Time, error) { sec, ms := math.Modf(timestamp) // Convert to native time rounding to milliseconds t := time.Unix(int64(sec), int64(math.Floor(ms*1000+0.5))*1000*1000) // Caclulate the timezone if timezone != "" { hours, err := strconv.Atoi(timezone[1:3]) if err != nil { return time.Time{}, err } minutes, err := strconv.Atoi(timezone[4:6]) if err != nil { return time.Time{}, err } tzOffset := ((hours * 60) + minutes) * 60 if timezone[:1] == "-" { tzOffset = 0 - tzOffset } t = t.In(time.FixedZone(timezone, tzOffset)) } return t, nil }
func (c *FanMetrics) GetPercentile(p float64) time.Duration { var percentile float64 r := (float64(len(c.Results)) + 1.0) * p ir, fr := math.Modf(r) if len(c.Results) == 0 { return 0 } var v1 float64 if ir >= float64(len(c.Results)) { v1 = float64(c.Results[len(c.Results)-1]) } else { v1 = float64(c.Results[int(ir)-1]) } if fr > 0.0 && ir < float64(len(c.Results)) { v2 := float64(c.Results[int(ir)]) percentile = (v2-v1)*fr + v1 } else { percentile = v1 } return time.Duration(percentile) }
func Round64(x float64) float64 { i, f := math.Modf(x) if f >= 0.5 { return i + 1.0 } return i }
func ExampleLen3_Extremum() { // Example 3.b, p. 26. d3, err := interp.NewLen3(12, 20, []float64{ 1.3814294, 1.3812213, 1.3812453, }) if err != nil { fmt.Println(err) return } x, y, err := d3.Extremum() if err != nil { fmt.Println(err) return } fmt.Printf("distance: %.7f AU\n", y) fmt.Printf("date: %.4f\n", x) i, frac := math.Modf(x) fmt.Printf("1992 May %d, at %.64s TD", int(i), base.NewFmtTime(frac*24*3600)) // Output: // distance: 1.3812030 AU // date: 17.5864 // 1992 May 17, at 14ʰ TD }
func ExampleLen3_Zero() { // Example 3.c, p. 26. x1 := 26. x3 := 28. // the y unit doesn't matter. working in degrees is fine yTable := []float64{ base.DMSToDeg(true, 0, 28, 13.4), base.DMSToDeg(false, 0, 6, 46.3), base.DMSToDeg(false, 0, 38, 23.2), } d3, err := interp.NewLen3(x1, x3, yTable) if err != nil { fmt.Println(err) return } x, err := d3.Zero(false) if err != nil { fmt.Println(err) return } fmt.Printf("February %.5f\n", x) i, frac := math.Modf(x) fmt.Printf("February %d, at %.62s TD", int(i), base.NewFmtTime(frac*24*3600)) // Output: // February 26.79873 // February 26, at 19ʰ10ᵐ TD }
// FormatFloat converts a float64 to a formatted string. The float is rounded // to the given precision and formatted using a comma separator for thousands. func FormatFloat(x float64, precision int) string { // Round the float and get the decimal and fractional parts r := RoundFloat(x, precision) i, f := math.Modf(r) is := FormatThousands(int64(i)) // If precision is less than one return the formatted integer part if precision <= 0 { return is } // Otherwise convert the fractional part to a string fs := strconv.FormatFloat(f, 'f', precision, 64) // And get the digits after the decimal point if x < 0 { fs = fs[3:] } else { fs = fs[2:] } // Concatenate the decimal and fractional parts and return return is + "." + fs }
/* getBestReadSize returns the best guess as to how much data should be read to reach the target message count. Logic used: 1 - If the target count is 1 message, recommend double the average message size of the segment, or 1k if empty. 2 - Find the largest number that will align the read to the sparse array of offsets. */ func (seg *Segment) getBestReadSize(msgIndex int64, msgPosition int64, targetCount int) (bestSize int) { if targetCount == 1 { if seg.msgCount == 0 { return 1024 } return int(2 * seg.fileSize / int64(seg.msgCount)) } localIndex := msgIndex - seg.firstIndex nearestIndexf, _ := math.Modf(float64(localIndex) / float64(default_index_offset_density)) nearestIndex := int(nearestIndexf) // If nearest sparse index is already at the end of the file, just return end of file information. if nearestIndex == len(seg.sparseIndexOffsetList)-1 { return int(seg.fileSize - msgPosition) } // Is there an offset between the end and where we are that makes more sense? for i, offset := range seg.sparseIndexOffsetList[nearestIndex:] { if (i+nearestIndex)*default_index_offset_density-int(localIndex) >= targetCount { // Use this offset. return int(offset - msgPosition) } } // If our maximum is so big that we hit the end - just send the whole file. return int(seg.fileSize - msgPosition) }
// IntoWords convert numbers (float64) to words func IntoWords(number float64) string { if number == 0 { return zero } words := []string{} // Minus if number < 0 { words = append(words, minus) } number = math.Abs(number) integer, fractional := math.Modf(number) if integer != 0 || fractional == 0 { numberIntoWords := writeOutNumbersInWords(integer) words = append(words, numberIntoWords...) } if fractional > 0 { words = append(words, point) fractional := round(math.Abs(fractional) * 100) fracIntoWords := writeOutNumbersInWords(fractional) words = append(words, fracIntoWords...) } return sanitize(words) }