Exemple #1
0
// parseFilesize converts strings of form 10GB to a size in bytes. Fractional
// sizes are truncated at the byte size.
func parseFilesize(strSize string) (string, error) {
	units := []struct {
		suffix     string
		multiplier int64
	}{
		{"kb", 1e3},
		{"mb", 1e6},
		{"gb", 1e9},
		{"tb", 1e12},
		{"kib", 1 << 10},
		{"mib", 1 << 20},
		{"gib", 1 << 30},
		{"tib", 1 << 40},
		{"b", 1}, // must be after others else it'll match on them all
		{"", 1},  // no suffix is still a valid suffix
	}

	strSize = strings.ToLower(strSize)
	for _, unit := range units {
		if strings.HasSuffix(strSize, unit.suffix) {
			r, ok := new(big.Rat).SetString(strings.TrimSuffix(strSize, unit.suffix))
			if !ok {
				return "", errUnableToParseSize
			}
			r.Mul(r, new(big.Rat).SetInt(big.NewInt(unit.multiplier)))
			if !r.IsInt() {
				f, _ := r.Float64()
				return fmt.Sprintf("%d", int64(f)), nil
			}
			return r.RatString(), nil
		}
	}

	return "", errUnableToParseSize
}
Exemple #2
0
Fichier : graph.go Projet : rsc/tmp
func ratProb(mode int) func(*big.Rat) *big.Rat {
	return func(x *big.Rat) *big.Rat {
		lo := big.NewInt(0)
		hi := new(big.Int).Set(big2p63)
		n := 0
		for lo.Cmp(hi) != 0 {
			m := new(big.Int).Add(lo, hi)
			m = m.Rsh(m, 1)
			if n++; n > 100 {
				fmt.Printf("??? %v %v %v\n", lo, hi, m)
				break
			}
			v := new(big.Rat).SetFrac(m, big2p63)
			f, _ := v.Float64()
			v.SetFloat64(f)
			if v.Cmp(x) < 0 {
				lo.Add(m, bigOne)
			} else {
				hi.Set(m)
			}
		}
		switch mode {
		default: // case 0
			return new(big.Rat).SetFrac(lo, big2p63)
		case 1:
			if lo.Cmp(big.NewInt(cutoff1)) <= 0 {
				lo.Add(lo, big.NewInt(1<<63-cutoff1))
			}
			return new(big.Rat).SetFrac(lo, big2p63)
		case 2:
			return new(big.Rat).SetFrac(lo, big.NewInt(cutoff1))
		}
	}
}
Exemple #3
0
// walletbalancecmd retrieves and displays information about the wallet.
func walletbalancecmd() {
	status := new(api.WalletGET)
	err := getAPI("/wallet", status)
	if err != nil {
		die("Could not get wallet status:", err)
	}
	encStatus := "Unencrypted"
	if status.Encrypted {
		encStatus = "Encrypted"
	}
	lockStatus := "Locked"
	balance := "Unlock the wallet to view balance"
	if status.Unlocked {
		lockStatus = "Unlocked"
		// Divide by 1e24 to get SC.
		r := new(big.Rat).SetFrac(status.ConfirmedSiacoinBalance.Big(), new(big.Int).Exp(big.NewInt(10), big.NewInt(24), nil))
		sc, _ := r.Float64()
		unconfirmedBalance := status.ConfirmedSiacoinBalance.Add(status.UnconfirmedIncomingSiacoins).Sub(status.UnconfirmedOutgoingSiacoins)
		unconfirmedDifference := new(big.Int).Sub(unconfirmedBalance.Big(), status.ConfirmedSiacoinBalance.Big())
		r = new(big.Rat).SetFrac(unconfirmedDifference, new(big.Int).Exp(big.NewInt(10), big.NewInt(24), nil))
		usc, _ := r.Float64()
		balance = fmt.Sprintf(`Confirmed Balance:   %.2f SC
Unconfirmed Delta:  %+.2f SC
Exact:               %v H
Siafunds:            %v SF
Siafund Claims:      %v H
`, sc, usc, status.ConfirmedSiacoinBalance, status.SiafundBalance, status.SiacoinClaimBalance)
	}
	fmt.Printf(`Wallet status:
%s, %s
%s
`, encStatus, lockStatus, balance)
}
Exemple #4
0
// walletstatuscmd retrieves and displays information about the wallet
func walletstatuscmd() {
	status := new(api.WalletGET)
	err := getAPI("/wallet", status)
	if err != nil {
		fmt.Println("Could not get wallet status:", err)
		return
	}
	encStatus := "Unencrypted"
	if status.Encrypted {
		encStatus = "Encrypted"
	}
	lockStatus := "Locked"
	if status.Unlocked {
		lockStatus = "Unlocked"
	}
	// divide by 1e24 to get SC
	r := new(big.Rat).SetFrac(status.ConfirmedSiacoinBalance.Big(), new(big.Int).Exp(big.NewInt(10), big.NewInt(24), nil))
	sc, _ := r.Float64()
	unconfirmedBalance := status.ConfirmedSiacoinBalance.Add(status.UnconfirmedIncomingSiacoins)
	unconfirmedBalance = unconfirmedBalance.Sub(status.UnconfirmedOutgoingSiacoins)
	r = new(big.Rat).SetFrac(unconfirmedBalance.Big(), new(big.Int).Exp(big.NewInt(10), big.NewInt(24), nil))
	usc, _ := r.Float64()
	fmt.Printf(`Wallet status:
%s, %s
Confirmed Balance:   %.2f SC
Unconfirmed Balance: %.2f SC
Exact:               %v H
`, encStatus, lockStatus, sc, usc, status.ConfirmedSiacoinBalance)
}
Exemple #5
0
func ratToFloat32(x *big.Rat) (float32, bool) {
	// Before 1.4, there's no Rat.Float32.
	// Emulate it, albeit at the cost of
	// imprecision in corner cases.
	x64, exact := x.Float64()
	x32 := float32(x64)
	if math.IsInf(float64(x32), 0) {
		exact = false
	}
	return x32, exact
}
Exemple #6
0
// Returns the parsed duration in nanoseconds, support 'u', 's', 'm',
// 'h', 'd', 'W', 'M', and 'Y' suffixes.
func ParseTimeDuration(value string) (int64, error) {
	var constant time.Duration

	prefixSize := 1

	switch value[len(value)-1] {
	case 'u':
		constant = time.Microsecond
	case 's':
		constant = time.Second
	case 'm':
		constant = time.Minute
	case 'h':
		constant = time.Hour
	case 'd':
		constant = 24 * time.Hour
	case 'w', 'W':
		constant = Week
	case 'M':
		constant = Month
	case 'y', 'Y':
		constant = Year
	default:
		prefixSize = 0
	}

	if value[len(value)-2:] == "ms" {
		constant = time.Millisecond
		prefixSize = 2
	}

	t := big.Rat{}
	timeString := value
	if prefixSize > 0 {
		timeString = value[:len(value)-prefixSize]
	}

	_, err := fmt.Sscan(timeString, &t)
	if err != nil {
		return 0, err
	}

	if prefixSize > 0 {
		c := big.Rat{}
		c.SetFrac64(int64(constant), 1)
		t.Mul(&t, &c)
	}

	if t.IsInt() {
		return t.Num().Int64(), nil
	}
	f, _ := t.Float64()
	return int64(f), nil
}
func main() {
	ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
	h := big.NewRat(1, 2)
	h.Quo(h, ln2)
	var f big.Rat
	var w big.Int
	for i := int64(1); i <= 17; i++ {
		h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
		w.Quo(h.Num(), h.Denom())
		f.Sub(h, f.SetInt(&w))
		y, _ := f.Float64()
		d := fmt.Sprintf("%.3f", y)
		fmt.Printf("n: %2d  h: %18d%s  Nearly integer: %t\n",
			i, &w, d[1:], d[2] == '0' || d[2] == '9')
	}
}
Exemple #8
0
func walletstatuscmd() {
	status := new(modules.WalletInfo)
	err := getAPI("/wallet/status", status)
	if err != nil {
		fmt.Println("Could not get wallet status:", err)
		return
	}
	// divide by 1e24 to get SC
	r := new(big.Rat).SetFrac(status.Balance.Big(), new(big.Int).Exp(big.NewInt(10), big.NewInt(24), nil))
	sc, _ := r.Float64()
	fmt.Printf(`Wallet status:
Balance:   %.2f SC
Exact:     %v H
Addresses: %d
`, sc, status.Balance, status.NumAddresses)
}
Exemple #9
0
Fichier : graph.go Projet : rsc/tmp
func plotPath(f func(*big.Rat) *big.Rat, fminx, fminy, fmaxx, fmaxy *big.Rat, r fixed.Rectangle26_6) raster.Path {
	px := r.Min.X
	var path raster.Path
	for ; px <= r.Max.X; px += 1 << 6 {
		fx := new(big.Rat).Add(fminx, new(big.Rat).Mul(new(big.Rat).Sub(fmaxx, fminx), new(big.Rat).Quo(big.NewRat(int64(px-r.Min.X), 1<<6), big.NewRat(int64(r.Max.X-r.Min.X), 1<<6))))
		fy := f(fx)
		fdy := new(big.Rat).Mul(new(big.Rat).Sub(fy, fminy), new(big.Rat).Quo(big.NewRat(int64(r.Max.Y-r.Min.Y), 1), new(big.Rat).Sub(fmaxy, fminy)))
		dy, _ := fdy.Float64()
		py := r.Min.Y + fixed.Int26_6(dy+0.5)
		if len(path) == 0 {
			path.Start(fixed.Point26_6{px, py})
		} else {
			path.Add1(fixed.Point26_6{px, py})
		}
	}
	return path
}
Exemple #10
0
// Returns an approximate Birthday probability calculation
// based on the number of blocks given and the hash size.
//
// It uses the simplified calculation:  p = k(k-1) / (2N)
//
// From http://preshing.com/20110504/hash-collision-probabilities/
func BirthdayProblem(blocks int) string {
	k := big.NewInt(int64(blocks))
	km1 := big.NewInt(int64(blocks - 1))
	ksq := k.Mul(k, km1)
	n := big.NewInt(0)
	n = n.Exp(big.NewInt(2), big.NewInt(int64(HashSize)*8), nil)
	twoN := n.Add(n, n)
	var t, t2 big.Rat
	var res *big.Rat
	//
	res = t.SetFrac(ksq, twoN)
	f64, _ := res.Float64()
	inv := t2.Inv(res).FloatString(0)
	invs := fmt.Sprintf(" ~ 1/%s ~ %v", inv, f64)

	return "Collision probability is" + invs
}
Exemple #11
0
// returns number of  Nanoseconds
func (t *milliSecsOf256th) MilliSecs(m Measure) uint {
	r := new(big.Rat)
	r.Mul(t.Rat, big.NewRat(int64(int(m)), 1))
	f, _ := r.Float64()
	// fmt.Printf("Nanoseconds: %0.2f\n", f*1000000)
	return uint(f * 1000000)
	/*
		a := big.NewRat(64, 60)
		b := big.NewRat(1, int64(uint(t)))
		z := new(big.Rat)
		z = z.Mul(a, b)
		z = z.Mul(z, big.NewRat(int64(int(m)), 1))
		f, _ := z.Float64()
		fmt.Printf("ticksPerMinute: %0.2f", f*1000)
		return uint(f * 1000)
	*/
}
Exemple #12
0
// Returns the parsed duration in nanoseconds, support 'u', 's', 'm',
// 'h', 'd' and 'w' suffixes.
func ParseTimeDuration(value string) (int64, error) {
	var constant time.Duration
	hasPrefix := true

	switch value[len(value)-1] {
	case 'u':
		constant = time.Microsecond
	case 's':
		constant = time.Second
	case 'm':
		constant = time.Minute
	case 'h':
		constant = time.Hour
	case 'd':
		constant = 24 * time.Hour
	case 'w':
		constant = 7 * 24 * time.Hour
	case 'y':
		constant = 365 * 24 * time.Hour
	default:
		hasPrefix = false
	}

	t := big.Rat{}
	timeString := value
	if hasPrefix {
		timeString = value[:len(value)-1]
	}

	_, err := fmt.Sscan(timeString, &t)
	if err != nil {
		return 0, err
	}

	if hasPrefix {
		c := big.Rat{}
		c.SetFrac64(int64(constant), 1)
		t.Mul(&t, &c)
	}
	if t.IsInt() {
		return t.Num().Int64(), nil
	}
	f, _ := t.Float64()
	return int64(f), nil
}
Exemple #13
0
// measure via string
//func m_(s string) Measure {
func m_(s string) float64 {
	r := new(big.Rat)
	_, ok := r.SetString(s)
	if !ok {
		panic("can't convert to measure")
	}

	x := new(big.Rat)

	// d := big.NewRat(1, 256)
	d := big.NewRat(256, 1)

	x.Mul(r, d)

	f, _ := x.Float64()

	//return Measure(int(f))
	return f

}
// bigRatToValue converts 'number' to an SQL value with SQL type: valueType.
// If valueType is integral it truncates 'number' to the integer part according to the
// semantics of the big.Rat.Int method.
func bigRatToValue(number *big.Rat, valueType querypb.Type) sqltypes.Value {
	var numberAsBytes []byte
	switch {
	case sqltypes.IsIntegral(valueType):
		// 'number.Num()' returns a reference to the numerator of 'number'.
		// We copy it here to avoid changing 'number'.
		truncatedNumber := new(big.Int).Set(number.Num())
		truncatedNumber.Quo(truncatedNumber, number.Denom())
		numberAsBytes = bigIntToSliceOfBytes(truncatedNumber)
	case sqltypes.IsFloat(valueType):
		// Truncate to the closest 'float'.
		// There's not much we can do if there isn't an exact representation.
		numberAsFloat64, _ := number.Float64()
		numberAsBytes = strconv.AppendFloat([]byte{}, numberAsFloat64, 'f', -1, 64)
	default:
		panic(fmt.Sprintf("Unsupported type: %v", valueType))
	}
	result, err := sqltypes.ValueFromBytes(valueType, numberAsBytes)
	if err != nil {
		panic(fmt.Sprintf("sqltypes.ValueFromBytes failed with: %v", err))
	}
	return result
}
Exemple #15
0
// PriceString returns a human reprensetation of a price with a currency
func PriceString(price *big.Rat, currency string) string {
	floatVal, _ := price.Float64()
	return fmt.Sprintf("%s %s", humanize.Ftoa(floatVal), currency)
}
Exemple #16
0
func ratFloat(rat *big.Rat) float64 {
	f, _ := rat.Float64()
	return f
}
Exemple #17
0
func RatToFloat(v *big.Rat) float64 {
	f, _ := v.Float64()
	return f
}
Exemple #18
0
Fichier : graph.go Projet : rsc/tmp
func ratSin(x *big.Rat) *big.Rat {
	fx, _ := x.Float64()
	fy := math.Sin(fx)
	return new(big.Rat).SetFloat64(fy)
}