Пример #1
0
// adjustFracToPrec adapts the fractal value of a float64 number to the format
// precision. Rounds the value.
func (f *format) adjustFracToPrec(frac int64, prec int) int64 {

	if f.precision > prec {
		// Moving frac values to the correct precision.
		// Edge case when format has a higher precision than prec.
		// E.G.: Format is #,##0.000 and prec=2 and frac=8 (1234.08)
		// the re-calculated frac is then 8*(10^2) = 80 to move
		// 8 to the second place. The new number would be then 1234.080 because
		// the format requires to have 3 fractal digits
		frac *= int64(math.Pow10(f.precision - prec))
	}

	// if the prec is higher than the formatted precision then we have to round
	// the frac value to fit into the precision of the format.
	if prec > 0 && prec > f.precision {
		il10 := math.Pow10(prec)
		ilf := float64(frac) / il10
		prec10 := math.Pow10(f.precision)
		fracf := float64((ilf*prec10)+0.55) / prec10 // hmmm that .55 needs to be monitored. everywhere else we have just .5
		fracf *= prec10
		fracf += floatRoundingCorrection // I'm lovin it 8-)
		return int64(fracf)
	}
	return frac
}
Пример #2
0
// make the prefix structure
func MakePrefices() map[string]SIPrefix {
	pref_map := make(map[string]SIPrefix, 20)
	exponent := -24
	pfcs := "yzafpnum"

	for _, rune := range pfcs {
		prefix := SIPrefix{string(rune), math.Pow10(exponent)}
		//	fmt.Println(prefix)
		pref_map[string(rune)] = prefix
		exponent += 3
	}

	pfcs = "cd h"

	exponent = -2

	for _, rune := range pfcs {
		prefix := SIPrefix{string(rune), math.Pow10(exponent)}
		pref_map[string(rune)] = prefix
		exponent += 1
	}

	exponent = 3

	pfcs = "kMGTPEZY"

	for _, rune := range pfcs {
		prefix := SIPrefix{string(rune), math.Pow10(exponent)}
		//	fmt.Println(prefix)
		pref_map[string(rune)] = prefix
		exponent += 3
	}

	return pref_map
}
Пример #3
0
func maxPalindrome3(digits int) long {
	top := long(math.Pow10(digits) - 1)
	min := long(math.Pow10(digits - 1))
	largestPalindrome := long(0)
	pow11 := top - top%11 //The largest number less than or equal top and divisible by 11
	//n := 0
	for a := top; a >= min; a-- {
		//n++
		b := pow11
		db := long(11)
		if a%11 == 0 {
			b = top
			db = 1
		}
		for ; b >= min; b -= db {
			//n++
			c := a * b
			if c < largestPalindrome {
				break
			}
			if isPalindrome(c) {
				largestPalindrome = c
			}
		}
	}
	//fmt.Println("n", n)
	return largestPalindrome
}
Пример #4
0
// NiceNum finds a "nice" number approximately equal to x. Round the number if round is true, otherwise take the
// ceiling.  Described on Graphics Gems pg. 63
func NiceNum(x float64, round bool) float64 {
	exp := int(math.Floor(math.Log10(x)))
	f := x / math.Pow10(exp)

	var nf int
	if round {
		if f < 1.5 {
			nf = 1
		} else if f < 3 {
			nf = 2
		} else if f < 7 {
			nf = 5
		} else {
			nf = 10
		}
	} else {
		if f <= 1 {
			nf = 1
		} else if f <= 2 {
			nf = 2
		} else if f <= 5 {
			nf = 5
		} else {
			nf = 10
		}
	}

	return float64(nf) * math.Pow10(exp)
}
Пример #5
0
func NewData(digit, substart, sublen uint) *Data {
	maxL := int(sublen)
	maxNum := int(math.Pow10(maxL)) - 1
	maxDiv := int(math.Sqrt(float64(maxNum)))

	pb := make([]bool, maxDiv+1)
	for i, _ := range pb {
		pb[i] = false
	}
	pb[0] = true
	pb[1] = true
	maxPb := int(math.Sqrt(float64(maxDiv + 1)))
	for i := 2; i <= maxPb; i++ {
		if pb[i] {
			continue
		}
		for j := i * i; j < maxDiv+1; j += i {
			pb[j] = true
		}
	}
	fmt.Println("prime buffer")
	for _, j := range pb {
		fmt.Print(" ", j)
	}
	fmt.Println()

	b := make([]int, digit)
	for i, _ := range b {
		b[i] = i
	}

	base := int(math.Pow10(int(sublen) - 1))
	return &Data{pb, b, int(digit), int(substart), int(sublen), base}
}
Пример #6
0
func Round(input float64, decimals int) float64 {
	input = input * math.Pow10(decimals)

	if input < 0 {
		return math.Ceil(input-0.5) / math.Pow10(decimals)
	}
	return math.Floor(input+0.5) / math.Pow10(decimals)
}
Пример #7
0
func extractDigit(number int, digit int) int {
	x := number
	//cut off via modula
	x = x % int(math.Pow10(1+digit))

	//cut off the remainder
	x = x / int(math.Pow10(digit))

	return x
}
Пример #8
0
func over(n, k, d int) int {
	x := k * int(math.Pow10(d))
	y := n % int(math.Pow10(d+1))
	y /= int(math.Pow10(d))
	y *= int(math.Pow10(d))
	if x > y {
		return 1
	} else if x < y {
		return -1
	}
	return 0
}
Пример #9
0
// scaledValue scales given unscaled value from scale to new Scale and returns
// an int64. It ALWAYS rounds up the result when scale down. The final result might
// overflow.
//
// scale, newScale represents the scale of the unscaled decimal.
// The mathematical value of the decimal is unscaled * 10**(-scale).
func scaledValue(unscaled *big.Int, scale, newScale int) int64 {
	dif := scale - newScale
	if dif == 0 {
		return unscaled.Int64()
	}

	// Handle scale up
	// This is an easy case, we do not need to care about rounding and overflow.
	// If any intermediate operation causes overflow, the result will overflow.
	if dif < 0 {
		return unscaled.Int64() * int64(math.Pow10(-dif))
	}

	// Handle scale down
	// We have to be careful about the intermediate operations.

	// fast path when unscaled < max.Int64 and exp(10,dif) < max.Int64
	const log10MaxInt64 = 19
	if unscaled.Cmp(maxInt64) < 0 && dif < log10MaxInt64 {
		divide := int64(math.Pow10(dif))
		result := unscaled.Int64() / divide
		mod := unscaled.Int64() % divide
		if mod != 0 {
			return result + 1
		}
		return result
	}

	// We should only convert back to int64 when getting the result.
	divisor := intPool.Get().(*big.Int)
	exp := intPool.Get().(*big.Int)
	result := intPool.Get().(*big.Int)
	defer func() {
		intPool.Put(divisor)
		intPool.Put(exp)
		intPool.Put(result)
	}()

	// divisor = 10^(dif)
	// TODO: create loop up table if exp costs too much.
	divisor.Exp(bigTen, exp.SetInt64(int64(dif)), nil)
	// reuse exp
	remainder := exp

	// result = unscaled / divisor
	// remainder = unscaled % divisor
	result.DivMod(unscaled, divisor, remainder)
	if remainder.Sign() != 0 {
		return result.Int64() + 1
	}

	return result.Int64()
}
Пример #10
0
func (cons *Profiler) generateTemplate() []byte {
	var dummyValues []interface{}
	messageLen := len(cons.message)

	for idx, char := range cons.message {
		if char == '%' {
			// Get the required length
			size := 0
			searchIdx := idx + 1

			// Get format size
			for searchIdx < messageLen && cons.message[searchIdx] >= '0' && cons.message[searchIdx] <= '9' {
				size = size*10 + int(cons.message[searchIdx]-'0')
				searchIdx++
			}

			// Skip decimal places
			if cons.message[searchIdx] == '.' {
				searchIdx++
				for searchIdx < messageLen && cons.message[searchIdx] >= '0' && cons.message[searchIdx] <= '9' {
					searchIdx++
				}
			}

			// Make sure there is at least 1 number / character
			if size == 0 {
				size = 1
			}

			// Generate values
			switch cons.message[searchIdx] {
			case '%':
				// ignore

			case 'e', 'E', 'f', 'F', 'g', 'G':
				dummyValues = append(dummyValues, rand.Float64()*math.Pow10(size))

			case 'U', 'c':
				dummyValues = append(dummyValues, rune(rand.Intn(1<<16)+32))

			case 'd', 'b', 'o', 'x', 'X':
				dummyValues = append(dummyValues, rand.Intn(int(math.Pow10(size))))

			case 's', 'q', 'v', 'T':
				fallthrough
			default:
				dummyValues = append(dummyValues, cons.generateString(size))
			}
		}
	}

	return []byte(fmt.Sprintf(cons.message, dummyValues...))
}
Пример #11
0
// ADC Correction
func adjustValue(v float64, adj AdjustmentTable) float64 {
	if adj.Orders == 4 {
		return adj.Order[0] + adj.Order[1]*v + adj.Order[2]*math.Pow10(-9)*math.Pow(v, 2) + adj.Order[3]*math.Pow10(-13)*math.Pow(v, 3)
	} else if adj.Orders == 3 {
		return adj.Order[0] + adj.Order[1]*v + adj.Order[2]*math.Pow10(-9)*math.Pow(v, 2)
	} else if adj.Orders == 2 {
		return adj.Order[0] + adj.Order[1]*v
	} else if adj.Orders == 1 {
		return adj.Order[0] + v
	}
	return v
}
Пример #12
0
func abc() {
	type T struct {
		a int
		b int
		c float64
	}

	type SliceHeader struct {
		addr uintptr
		len  int
		cap  int
	}

	t := &T{a: 1, b: 2, c: 3.2}
	p := unsafe.Sizeof(*t)
	println("t size:", int(p))
	fmt.Println("t value:", t)

	sl := &SliceHeader{
		addr: uintptr(unsafe.Pointer(t)),
		len:  int(p),
		cap:  int(p),
	}

	b := *(*[]byte)(unsafe.Pointer(sl))
	println("byte size: ", len(b))
	fmt.Println("byte content: ", b)

	b[0] = 12
	b[7] = 0
	b[8] = 24

	fmt.Println("last t value: ", t)
	fmt.Println("last byte content: ", b)

	ft := 10.1234567
	ftval := 0.0
	lastVal := math.Pow10(-4)
	addVal := math.Pow10(-5)
	fmt.Printf("add val: %f\n", addVal)
	tmp := math.Mod(math.Trunc(ft/addVal), 10)
	fmt.Printf("tmp val: %f\n", tmp)
	if tmp >= 5 {
		ftval = ft + lastVal
	} else {
		ftval = ft
	}
	fmt.Println(math.Trunc(ftval/lastVal) / math.Pow10(4))

}
Пример #13
0
// RoundDec64 round to prec precision.
func RoundDec64(x float64, prec int) float64 {
	if prec < 1 {
		return x
	}
	dec1 := math.Pow10(prec)
	dec2 := math.Pow10(prec + 1)
	tmp := int(x * dec1)
	last := int(x*dec2) - tmp*10
	if norm(last) >= 5 && last >= 0 {
		tmp += 1
	} else if norm(last) >= 5 && last < 0 {
		tmp -= 1
	}
	return float64(tmp) / dec1
}
Пример #14
0
func getDigit(h int64, r int) int {
	max := MaxZoom(h)

	p1 := int64(math.Pow10(max - r))
	p2 := int64(math.Pow10(max - r + 1))

	r1 := int(h / p1)
	r2 := int(h/p2) * 10

	if r2 == 0 {
		return r1
	}

	return r1 - r2
}
Пример #15
0
/* Gets digits of an integer */
func IntToDig(n int64) []int64 {
	var (
		f            []int64
		t            int64
		exp          int64
		last         int
		search_digit bool
	)
	search_digit = false
	for e := 19; e >= 0; e-- {
		exp = int64(math.Pow10(e))
		t = n / exp
		if search_digit {
			f[last-e] = t
			n = n % exp
		} else if t != 0 {
			f = make([]int64, e+1)
			last = e
			f[0] = t
			n = n % exp
			search_digit = true
		}
	}
	return f
}
Пример #16
0
func DigToInt(digits []int64) int64 {
	var out int64
	for i := len(digits); i > 0; i-- {
		out += digits[len(digits)-i] * int64(math.Pow10(i-1))
	}
	return out
}
Пример #17
0
//evaluate the unknown word frequency, according to 'beautiful data' algorithm
func (s *DNASegment) getUnknownWordProb(word string) float64 {
	m := float64(s.all_freq) * math.Pow10(len(word))
	m = 10.0 / m
	//fmt.Println(m)
	//return math.Log10(m)
	return m
}
Пример #18
0
// 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
}
Пример #19
0
func TestParse2(t *testing.T) {
	var l []time.Duration
	for i := 0; i < 15; i++ {
		l = append(l, (time.Duration(math.Pow10(i)))*time.Nanosecond)
	}
	test_parse(l, t)
}
Пример #20
0
// Round returns the half away from zero rounded value of x with prec precision.
//
// Special cases are:
// 	Round(±0) = +0
// 	Round(±Inf) = ±Inf
// 	Round(NaN) = NaN
func Round(x float64, prec int) float64 {
	if x == 0 {
		// Make sure zero is returned
		// without the negative bit set.
		return 0
	}
	// Fast path for positive precision on integers.
	if prec >= 0 && x == math.Trunc(x) {
		return x
	}
	pow := math.Pow10(prec)
	intermed := x * pow
	if math.IsInf(intermed, 0) {
		return x
	}
	if x < 0 {
		x = math.Ceil(intermed - 0.5)
	} else {
		x = math.Floor(intermed + 0.5)
	}

	if x == 0 {
		return 0
	}

	return x / pow
}
func (p *mathematicalPendulum) GetPhi() float64 {
	if (p.start == time.Time{}) {
		p.start = time.Now()
	}
	t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)
	return PHI_ZERO * omath.Cos(t*freq)
}
Пример #22
0
func main() {
	n := nextInt()

	bl := make([][]int, n)
	time := make([]int, n)
	for i := range bl {
		bl[i] = make([]int, 2)
		bl[i][0] = nextInt()
		bl[i][1] = nextInt()
	}

	min := 0
	max := int(math.Pow10(16))
	for i := range bl {
		if min < bl[i][0] {
			min = bl[i][0]
		}
	}
	min -= 1
	for max-min > 1 {
		med := (max + min) / 2
		if isOK(med, bl, time) {
			max = med
		} else {
			min = med
		}
	}
	fmt.Println(max)
}
Пример #23
0
func (d *TimeDecoder) decodeRLE(b []byte) {
	var i, n int

	// Lower 4 bits hold the 10 based exponent so we can scale the values back up
	mod := int64(math.Pow10(int(b[i] & 0xF)))
	i++

	// Next 8 bytes is the starting timestamp
	first := binary.BigEndian.Uint64(b[i : i+8])
	i += 8

	// Next 1-10 bytes is our (scaled down by factor of 10) run length values
	value, n := binary.Uvarint(b[i:])

	// Scale the value back up
	value *= uint64(mod)
	i += n

	// Last 1-10 bytes is how many times the value repeats
	count, _ := binary.Uvarint(b[i:])

	d.v = int64(first - value)
	d.rleDelta = int64(value)

	d.i = -1
	d.n = int(count)
}
Пример #24
0
// FloatPrecision float指定精度; round为true时, 表示支持四舍五入
func FloatPrecision(f float64, prec int, round bool) float64 {
	pow10N := math.Pow10(prec)
	if round {
		return math.Trunc((f+0.5/pow10N)*pow10N) / pow10N
	}
	return math.Trunc((f)*pow10N) / pow10N
}
Пример #25
0
func (d *TimeDecoder) decodePacked(b []byte) {
	if len(b) < 9 {
		d.err = fmt.Errorf("TimeDecoder: not enough data to decode packed timestamps")
		return
	}
	div := uint64(math.Pow10(int(b[0] & 0xF)))
	first := uint64(binary.BigEndian.Uint64(b[1:9]))

	d.dec.SetBytes(b[9:])

	d.i = 0
	deltas := d.ts[:0]
	deltas = append(deltas, first)
	for d.dec.Next() {
		deltas = append(deltas, d.dec.Read())
	}

	// Compute the prefix sum and scale the deltas back up
	for i := 1; i < len(deltas); i++ {
		dgap := deltas[i] * div
		deltas[i] = deltas[i-1] + dgap
	}

	d.i = 0
	d.ts = deltas
}
Пример #26
0
func rotator(start int) chan int {

	// for a number with 6 digits there can be at most 10 ^ (log10(n) / 2) palindromes
	maxpal := int(math.Pow10(int(math.Log10(1000000) / 2)))

	// 001100
	// 010010
	// 100001
	ch := make(chan int)

	// pow10(4) + pow10(3)
	// pow10(5) + pow10(2)
	// pow10(6) + pow10(1)
	// etc
	base := []int{1100, 10010, 100001}

	go func() {
		for i := 0; i < maxpal; i++ {
			v := (i % 10) * base[0]
			v += ((i % 100) / 10) * base[1]
			v += ((i % 1000) / 100) * base[2]
			ch <- start - v
		}
	}()
	return ch
}
Пример #27
0
// Determine appropriate tic delta for normal (non dat/time) axis from desired delta and minimal delta.
func (r *Range) fDelta(delta, mindelta float64) float64 {
	if r.Log {
		return 10
	}

	// Set up nice tic delta of the form 1,2,5 * 10^n
	// TODO: deltas of 25 and 250 would be suitable too...
	de := math.Pow10(int(math.Floor(math.Log10(delta))))
	f := delta / de
	switch {
	case f < 2:
		f = 1
	case f < 4:
		f = 2
	case f < 9:
		f = 5
	default:
		f = 1
		de *= 10
	}
	delta = f * de
	if delta < mindelta {
		DebugLogger.Printf("Redoing delta: %g < %g", delta, mindelta)
		// recalculate tic delta
		switch f {
		case 1, 5:
			delta *= 2
		case 2:
			delta *= 2.5
		default:
			fmt.Printf("Oooops. Strange f: %g\n", f)
		}
	}
	return delta
}
Пример #28
0
// Round(3.1556,2)=3.16
// Round(3.1556,0)=3
func Round(val float64, places int) float64 {
	var t float64
	f := math.Pow10(places)
	x := val * f
	if math.IsInf(x, 0) || math.IsNaN(x) {
		return val
	}
	if x >= 0.0 {
		t = math.Ceil(x)
		if (t - x) > 0.50000000001 {
			t -= 1.0
		}
	} else {
		t = math.Ceil(-x)
		if (t + x) > 0.50000000001 {
			t -= 1.0
		}
		t = -t
	}
	x = t / f

	if !math.IsInf(x, 0) {
		return x
	}
	return t
}
Пример #29
0
//以一个基准数据,输出相对浮点精度
func Float64RoundToRelativePrecOnOneFloat(f float64, prec int, precBaseF float64) float64 {
	if precBaseF == 0 { //避免输出NaN
		return 0
	}
	absPrec := math.Floor(math.Log10(precBaseF)) - float64(prec)
	return f - math.Mod(f, math.Pow10(int(absPrec)))
}
Пример #30
0
// Format cost as string on export
func (cdr *CDR) FormatCost(shiftDecimals, roundDecimals int) string {
	cost := cdr.Cost
	if shiftDecimals != 0 {
		cost = cost * math.Pow10(shiftDecimals)
	}
	return strconv.FormatFloat(cost, 'f', roundDecimals, 64)
}