Example #1
1
func floor(n *big.Rat) *big.Rat {
	f := &big.Rat{}
	z := new(big.Int)
	z.Div(n.Num(), n.Denom())
	f.SetInt(z)
	return f
}
Example #2
0
// currencyUnits converts a types.Currency to a string with human-readable
// units. The unit used will be the largest unit that results in a value
// greater than 1. The value is rounded to 4 significant digits.
func currencyUnits(c types.Currency) string {
	pico := types.SiacoinPrecision.Div64(1e12)
	if c.Cmp(pico) < 0 {
		return c.String() + " H"
	}

	// iterate until we find a unit greater than c
	mag := pico
	unit := ""
	for _, unit = range []string{"pS", "nS", "uS", "mS", "SC", "KS", "MS", "GS", "TS"} {
		if c.Cmp(mag.Mul64(1e3)) < 0 {
			break
		} else if unit != "TS" {
			// don't want to perform this multiply on the last iter; that
			// would give us 1.235 TS instead of 1235 TS
			mag = mag.Mul64(1e3)
		}
	}

	num := new(big.Rat).SetInt(c.Big())
	denom := new(big.Rat).SetInt(mag.Big())
	res, _ := new(big.Rat).Mul(num, denom.Inv(denom)).Float64()

	return fmt.Sprintf("%.4g %s", res, unit)
}
func (me *StatisticalAccumulator) PutString(x string) {

	xx := new(big.Rat)
	xx.SetString(x)

	me.PutRat(xx)
}
func (me *StatisticalAccumulator) PutInt64(x int64) {

	xx := new(big.Rat)
	xx.SetInt64(x)

	me.PutRat(xx)
}
func (me *StatisticalAccumulator) PutFrac64(a, b int64) {

	xx := new(big.Rat)
	xx.SetFrac64(a, b)

	me.PutRat(xx)
}
func (me *StatisticalAccumulator) PutFrac(a, b *big.Int) {

	xx := new(big.Rat)
	xx.SetFrac(a, b)

	me.PutRat(xx)
}
Example #7
0
func convertMeasure(in Measure) string {
	if in == Measure(0) {
		return "0"
	}
	measureNamesKeys := []int{}

	for m := range measureNames {
		measureNamesKeys = append(measureNamesKeys, int(m))
	}

	sort.Ints(measureNamesKeys)
	inInt := int(in)
	_ = inInt
	for i := len(measureNamesKeys) - 1; i >= 0; i-- {
		key := measureNamesKeys[i]

		if inInt > key {
			a := big.NewRat(int64(inInt), 256)
			b := measureNames[Measure(key)].Rat
			r := new(big.Rat)
			s := r.Sub(a, b)
			return b.RatString() + " + " + s.RatString()
		}
	}
	return "not found"
}
Example #8
0
// Total returns the total of an Usage
func (u *Usage) Total() *big.Rat {
	//return math.Min(u.Object.UnitPrice * u.BillableQuantity(), u.Object.UnitPriceCap)

	total := new(big.Rat).Mul(u.BillableQuantity(), u.Object.UnitPrice)
	total = total.Quo(total, u.Object.UnitQuantity)
	return ratMin(total, u.Object.UnitPriceCap)
}
Example #9
0
// Total computes the Usage.Total() of all the Usages of a Basket
func (b *Basket) Total() *big.Rat {
	total := new(big.Rat)
	for _, usage := range *b {
		total = total.Add(total, usage.Total())
	}
	return total
}
Example #10
0
func TestAmountJSON(t *testing.T) {
	type item struct {
		Price *Amount
	}
	const expected = `{"Price":"367/100"}`
	p := new(big.Rat)
	p.SetString("367/100")
	x := &item{Price: (*Amount)(p)}

	s, err := json.Marshal(x)
	if err != nil {
		t.Fatal(err)
	}
	if string(s) != expected {
		t.Errorf("got %q, expected %q", string(s), expected)
	}

	x = new(item)
	err = json.Unmarshal([]byte(expected), x)
	if err != nil {
		t.Fatal(err)
	}
	if str := x.Price.String(); str != "3.67" {
		t.Errorf("got %s, expected %s", str, "3.67")
	}
}
Example #11
0
// Rat returns the rational number representation of z.
// If x is non-nil, Rat stores the result in x instead of
// allocating a new Rat.
func (z *Decimal) Rat(x *big.Rat) *big.Rat {
	// TODO(eric):
	// We use big.Ints here when technically we could use our
	// int64 with big.Rat's SetInt64 methoz.
	// I'm not sure if it'll be an optimization or not.
	var num, denom big.Int
	if z.compact != overflown {
		c := big.NewInt(z.compact)
		if z.scale >= 0 {
			num.Set(c)
			denom.Set(mulBigPow10(oneInt, z.scale))
		} else {
			num.Set(mulBigPow10(c, -z.scale))
			denom.SetInt64(1)
		}
	} else {
		if z.scale >= 0 {
			num.Set(&z.mantissa)
			denom.Set(mulBigPow10(oneInt, z.scale))
		} else {
			num.Set(mulBigPow10(&z.mantissa, -z.scale))
			denom.SetInt64(1)
		}
	}
	if x != nil {
		return x.SetFrac(&num, &denom)
	}
	return new(big.Rat).SetFrac(&num, &denom)
}
Example #12
0
func EstimatePiFromPrevious(iteration, previousIndex int, sum *big.Rat) (*big.Rat, *big.Rat) {
	for i := previousIndex; i < iteration; i++ {
		sum.Add(sum, sn(i))
	}
	pi := getPiFromSum(sum)
	return pi, sum
}
Example #13
0
File: lex.go Project: suzuken/calc
// Unary evaluate unary expression
// include () expression
func UnaryExp(lex *Lex) (*big.Rat, error) {
	if lex.Token == '(' {
		lex.NextToken()
		x, err := AddSubExp(lex)
		if err != nil {
			return nil, err
		}
		if lex.Token != ')' {
			return nil, lex.Error("')' expected but not found. exit.")
		}
		lex.NextToken()
		return x, nil
	}
	if lex.Token != scanner.Int && lex.Token != scanner.Float {
		return nil, lex.Error("number expected. Given token is not number.")
	}

	// found if string can represent as rational.
	var r big.Rat
	rat, ok := r.SetString(lex.Scanner.TokenText())
	if !ok {
		return nil, lex.Error("invalid number")
	}
	lex.NextToken()
	return rat, nil
}
Example #14
0
func (t *lft) extr(x *big.Int) *big.Rat {
	var n, d big.Int
	var r big.Rat
	return r.SetFrac(
		n.Add(n.Mul(&t.q, x), &t.r),
		d.Add(d.Mul(&t.s, x), &t.t))
}
Example #15
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)
}
Example #16
0
// BigratToInt converts a *big.Rat to a *big.Int (with truncation)
func BigratToBigint(bigrat *big.Rat) *big.Int {
	int_string := bigrat.FloatString(0)
	bigint := new(big.Int)
	// no error scenario could be imagined in testing, so discard err
	fmt.Sscan(int_string, bigint)
	return bigint
}
Example #17
0
// Prints each transaction that matches the given filters.
func PrintRegister(generalLedger []*ledger.Transaction, filterArr []string, columns int) {
	runningBalance := new(big.Rat)
	for _, trans := range generalLedger {
		for _, accChange := range trans.AccountChanges {
			inFilter := len(filterArr) == 0
			for _, filter := range filterArr {
				if strings.Contains(accChange.Name, filter) {
					inFilter = true
				}
			}
			if inFilter {
				runningBalance.Add(runningBalance, accChange.Balance)
				writtenBytes, _ := fmt.Printf("%s %s", trans.Date.Format(ledger.TransactionDateFormat), trans.Payee)
				outBalanceString := accChange.Balance.FloatString(ledger.DisplayPrecision)
				outRunningBalanceString := runningBalance.FloatString(ledger.DisplayPrecision)
				spaceCount := columns - writtenBytes - 2 - len(outBalanceString) - len(outRunningBalanceString)
				if spaceCount < 0 {
					spaceCount = 0
				}
				fmt.Printf("%s%s %s", strings.Repeat(" ", spaceCount), outBalanceString, outRunningBalanceString)
				fmt.Println("")
			}
		}
	}
}
Example #18
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)
}
Example #19
0
func ToNullDecimal(v string) NullDecimal {
	if v == "" {
		return NullDecimal{Valid: false}
	}
	r := new(big.Rat)
	r.SetString(v)
	return NullDecimal{Value: r, Valid: true}
}
Example #20
0
func cumulFlows(flows []*types.Flow) (bals []*types.Amount) {
	x := new(big.Rat)
	for _, f := range flows {
		x = x.Add(x, (*big.Rat)(f.Price))
		bals = append(bals, new(types.Amount).SetRat(x))
	}
	return
}
Example #21
0
func GetBigAmount(amt string) (*big.Rat, error) {
	var r big.Rat
	_, success := r.SetString(amt)
	if !success {
		return nil, errors.New("Couldn't convert string amount to big.Rat via SetString()")
	}
	return &r, nil
}
Example #22
0
func fromDbDecimal(v string) Decimal {
	if v == "" {
		panic("Unexpected empty string value in fromDbDecimal!")
	}
	d := new(big.Rat)
	d.SetString(v)
	return Decimal{Value: d}
}
Example #23
0
// clampTargetAdjustment returns a clamped version of the base adjustment
// value. The clamp keeps the maximum adjustment to ~7x every 2000 blocks. This
// ensures that raising and lowering the difficulty requires a minimum amount
// of total work, which prevents certain classes of difficulty adjusting
// attacks.
func clampTargetAdjustment(base *big.Rat) *big.Rat {
	if base.Cmp(types.MaxAdjustmentUp) > 0 {
		return types.MaxAdjustmentUp
	} else if base.Cmp(types.MaxAdjustmentDown) < 0 {
		return types.MaxAdjustmentDown
	}
	return base
}
Example #24
0
// FloatString returns a string representation of decimal form with precision digits of precision after the decimal point and the last digit rounded.
func (this Decimal) FloatString(precision int) string {
	this.ensureValid()

	x := new(big.Rat).SetInt(this.integer)
	y := new(big.Rat).Inv(new(big.Rat).SetInt(new(big.Int).Exp(big.NewInt(int64(10)), big.NewInt(int64(this.scale)), nil)))
	z := new(big.Rat).Mul(x, y)
	return z.FloatString(precision)
}
Example #25
0
func BigratToBool(bigrat *big.Rat) bool {
	cmp := bigrat.Cmp(big.NewRat(0, 1))
	if cmp == 0 {
		return false
	} else {
		return true
	}
}
Example #26
0
// Returns a new big.Int set to the ceiling of x.
func ratCeil(x *big.Rat) *big.Int {
	z := new(big.Int)
	m := new(big.Int)
	z.DivMod(x.Num(), x.Denom(), m)
	if m.Cmp(intZero) == 1 {
		z.Add(z, intOne)
	}
	return z
}
func (me *StatisticalAccumulator) Mean() *big.Rat {
	mean := new(big.Rat)

	mean.Inv(me.n)

	mean.Mul(mean, me.sigmaXI)

	return mean
}
Example #28
0
func GasPrice(bp, gl, ep *big.Int) *big.Int {
	BP := new(big.Rat).SetInt(bp)
	GL := new(big.Rat).SetInt(gl)
	EP := new(big.Rat).SetInt(ep)
	GP := new(big.Rat).Quo(BP, GL)
	GP = GP.Quo(GP, EP)

	return GP.Mul(GP, etherInWei).Num()
}
Example #29
0
// Parse the value from the arguments
func parseAmount(text string) (*big.Rat, error) {
	amount := new(big.Rat)

	if r, _ := amount.SetString(text); r != nil {
		return amount, nil
	}

	return nil, errors.New("No value found")
}
Example #30
0
func getBalance(balance string) (bool, *big.Rat) {
	rationalNum := new(big.Rat)
	if strings.Contains(balance, "(") {
		rationalNum.SetFloat64(calc.Solve(balance))
		return true, rationalNum
	}
	_, isValid := rationalNum.SetString(balance)
	return isValid, rationalNum
}