本文整理汇总了Golang中math/big.Rat.FloatString方法的典型用法代码示例。如果您正苦于以下问题:Golang Rat.FloatString方法的具体用法?Golang Rat.FloatString怎么用?Golang Rat.FloatString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math/big.Rat
的用法示例。
在下文中一共展示了Rat.FloatString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: BigratToBigint
// 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
}
示例2: PrintRegister
// 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("")
}
}
}
}
示例3: FloatString
// 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)
}
示例4: floatString
func (r BigRat) floatString(verb byte, prec int) string {
switch verb {
case 'f', 'F':
return r.Rat.FloatString(prec)
case 'e', 'E':
// The exponent will alway be >= 0.
sign := ""
var x, t big.Rat
x.Set(r.Rat)
if x.Sign() < 0 {
sign = "-"
x.Neg(&x)
}
t.Set(&x)
exp := ratExponent(&x)
ratScale(&t, exp)
str := t.FloatString(prec + 1) // +1 because first digit might be zero.
// Drop the decimal.
if str[0] == '0' {
str = str[2:]
exp--
} else if len(str) > 1 && str[1] == '.' {
str = str[0:1] + str[2:]
}
return eFormat(verb, prec, sign, str, exp)
case 'g', 'G':
var x big.Rat
x.Set(r.Rat)
exp := ratExponent(&x)
// Exponent could be positive or negative
if exp < -4 || prec <= exp {
// Use e format.
verb -= 2 // g becomes e.
return trimEZeros(verb, r.floatString(verb, prec-1))
}
// Use f format.
// If it's got zeros right of the decimal, they count as digits in the precision.
// If it's got digits left of the decimal, they count as digits in the precision.
// Both are handled by adjusting prec by exp.
str := r.floatString(verb-1, prec-exp-1) // -1 for the one digit left of the decimal.
// Trim trailing decimals.
point := strings.IndexByte(str, '.')
if point > 0 {
n := len(str)
for str[n-1] == '0' {
n--
}
str = str[:n]
if str[n-1] == '.' {
str = str[:n-1]
}
}
return str
default:
Errorf("can't handle verb %c for rational", verb)
}
return ""
}
示例5: String
func String(v xdr.Int64) string {
var f, o, r big.Rat
f.SetInt64(int64(v))
o.SetInt64(One)
r.Quo(&f, &o)
return r.FloatString(7)
}
示例6: floatString
func floatString(r *big.Rat) string {
const prec = 50
s := r.FloatString(prec)
if strings.ContainsRune(s, '.') {
s = strings.TrimRight(s, "0")
if s[len(s)-1] == '.' {
s += "0"
}
}
return s
}
示例7: floatString
// floatString returns the string representation for a
// numeric value v in normalized floating-point format.
func floatString(v exact.Value) string {
if exact.Sign(v) == 0 {
return "0.0"
}
// x != 0
// convert |v| into a big.Rat x
x := new(big.Rat).SetFrac(absInt(exact.Num(v)), absInt(exact.Denom(v)))
// normalize x and determine exponent e
// (This is not very efficient, but also not speed-critical.)
var e int
for x.Cmp(ten) >= 0 {
x.Quo(x, ten)
e++
}
for x.Cmp(one) < 0 {
x.Mul(x, ten)
e--
}
// TODO(gri) Values such as 1/2 are easier to read in form 0.5
// rather than 5.0e-1. Similarly, 1.0e1 is easier to read as
// 10.0. Fine-tune best exponent range for readability.
s := x.FloatString(100) // good-enough precision
// trim trailing 0's
i := len(s)
for i > 0 && s[i-1] == '0' {
i--
}
s = s[:i]
// add a 0 if the number ends in decimal point
if len(s) > 0 && s[len(s)-1] == '.' {
s += "0"
}
// add exponent and sign
if e != 0 {
s += fmt.Sprintf("e%+d", e)
}
if exact.Sign(v) < 0 {
s = "-" + s
}
// TODO(gri) If v is a "small" fraction (i.e., numerator and denominator
// are just a small number of decimal digits), add the exact fraction as
// a comment. For instance: 3.3333...e-1 /* = 1/3 */
return s
}
示例8: main
// Compute 4*(1 - 1/3 + 1/5 - 1/7 + 1/9 - ...)
func main() {
sum := big.NewRat(0, 1)
var sumTimes4 big.Rat
for i, sign := int64(1), int64(1); i < 10000000; i, sign = i+2, -sign {
part := big.NewRat(sign, i)
sum.Add(sum, part)
if (i+1)%1000 == 0 {
sumTimes4.Mul(big.NewRat(4, 1), sum)
fmt.Printf("%v, %v\n", i+1, sumTimes4.FloatString(10))
}
}
}
示例9: getDifficultyRatio
// getDifficultyRatio returns the proof-of-work difficulty as a multiple of the
// minimum difficulty using the passed bits field from the header of a block.
func getDifficultyRatio(bits uint32) float64 {
// The minimum difficulty is the max possible proof-of-work limit bits
// converted back to a number. Note this is not the same as the the
// proof of work limit directly because the block difficulty is encoded
// in a block with the compact form which loses precision.
max := btcchain.CompactToBig(activeNetParams.powLimitBits)
target := btcchain.CompactToBig(bits)
difficulty := new(big.Rat).SetFrac(max, target)
outString := difficulty.FloatString(2)
diff, err := strconv.ParseFloat(outString, 64)
if err != nil {
rpcsLog.Errorf("Cannot get difficulty: %v", err)
return 0
}
return diff
}
示例10: hostcmd
// hostcmd is the handler for the command `siac host`.
// Prints info about the host.
func hostcmd() {
hg := new(api.HostGET)
err := getAPI("/host", &hg)
if err != nil {
die("Could not fetch host settings:", err)
}
// convert accepting bool
accept := yesNo(hg.AcceptingContracts)
// convert price to SC/GB/mo
price := new(big.Rat).SetInt(hg.Price.Big())
price.Mul(price, big.NewRat(4320, 1e24/1e9))
fmt.Printf(`Host info:
Storage: %v (%v used)
Price: %v SC per GB per month
Max Duration: %v Blocks
Contracts: %v
Accepting Contracts: %v
Anticipated Revenue: %v
Revenue: %v
Lost Revenue: %v
`, filesizeUnits(hg.TotalStorage), filesizeUnits(hg.TotalStorage-hg.StorageRemaining),
price.FloatString(3), hg.MaxDuration, hg.NumContracts, accept,
hg.AnticipatedRevenue, hg.Revenue, hg.LostRevenue)
// display more info if verbose flag is set
if !hostVerbose {
return
}
fmt.Printf(`
Net Address: %v
Unlock Hash: %v
(NOT a wallet address!)
RPC Stats:
Error Calls: %v
Unrecognized Calls: %v
Download Calls: %v
Renew Calls: %v
Revise Calls: %v
Settings Calls: %v
Upload Calls: %v
`, hg.NetAddress, hg.UnlockHash, hg.RPCErrorCalls, hg.RPCUnrecognizedCalls, hg.RPCDownloadCalls,
hg.RPCRenewCalls, hg.RPCReviseCalls, hg.RPCSettingsCalls, hg.RPCUploadCalls)
}
示例11: PrintBalances
// Prints out account balances formated to a windows of a width of columns.
// Only shows accounts with names less than or equal to the given depth.
func PrintBalances(accountList []*ledger.Account, printZeroBalances bool, depth, columns int) {
overallBalance := new(big.Rat)
for _, account := range accountList {
accDepth := len(strings.Split(account.Name, ":"))
if accDepth == 1 {
overallBalance.Add(overallBalance, account.Balance)
}
if (printZeroBalances || account.Balance.Sign() != 0) && (depth < 0 || accDepth <= depth) {
outBalanceString := account.Balance.FloatString(ledger.DisplayPrecision)
spaceCount := columns - len(account.Name) - len(outBalanceString)
fmt.Printf("%s%s%s\n", account.Name, strings.Repeat(" ", spaceCount), outBalanceString)
}
}
fmt.Println(strings.Repeat("-", columns))
outBalanceString := overallBalance.FloatString(ledger.DisplayPrecision)
spaceCount := columns - len(outBalanceString)
fmt.Printf("%s%s\n", strings.Repeat(" ", spaceCount), outBalanceString)
}
示例12: Parse
func Parse(v string) (xdr.Int64, error) {
var f, o, r big.Rat
_, ok := f.SetString(v)
if !ok {
return xdr.Int64(0), fmt.Errorf("cannot parse amount: %s", v)
}
o.SetInt64(One)
r.Mul(&f, &o)
is := r.FloatString(0)
i, err := strconv.ParseInt(is, 10, 64)
if err != nil {
return xdr.Int64(0), err
}
return xdr.Int64(i), nil
}
示例13: main
//"Pell Equation"
func main() {
starttime := time.Now()
total := 0
for rad := 2; rad <= 100; rad++ {
if !isSquare(rad) {
convergentList := make([]int, 1)
test := frac{a: 0, b: 1, R: rad, d: 1}
n := 0
n, test = nextFrac(test)
convergentList[0] = n
for i := 0; i < 200; i++ {
n, test = nextFrac(test)
convergentList = append(convergentList, n)
}
fLength := len(convergentList) - 1
p, q := ctdFrac(convergentList[:fLength])
var r big.Rat
r.SetString(p + "/" + q)
deciString := r.FloatString(105) //A bit too long in order to avoid rounding
total += sumDigits(deciString[:101]) //The extra 1 is the decimal point
}
}
fmt.Println(total)
fmt.Println("Elapsed time:", time.Since(starttime))
}
示例14: hoststatuscmd
func hoststatuscmd() {
info := new(modules.HostInfo)
err := getAPI("/host/status", info)
if err != nil {
fmt.Println("Could not fetch host settings:", err)
return
}
// convert price to SC/GB/mo
price := new(big.Rat).SetInt(info.Price.Big())
price.Mul(price, big.NewRat(4320, 1e24/1e9))
fmt.Printf(`Host settings:
Storage: %v (%v used)
Price: %v SC per GB per month
Collateral: %v
Max Filesize: %v
Max Duration: %v
Contracts: %v
`, filesizeUnits(info.TotalStorage), filesizeUnits(info.TotalStorage-info.StorageRemaining),
price.FloatString(3), info.Collateral, info.MaxFilesize, info.MaxDuration, info.NumContracts)
}
示例15: f1
func f1() {
max := 1
ii := 2
for i := 2; i < 1000; i++ {
r := new(big.Rat)
r.SetString("1/" + strconv.Itoa(i))
s := r.FloatString(10000)[2:9999]
//s = strings.TrimLeft(s, "0")
//fmt.Println(s)
v := dup(&s)
d := len(v)
if max < d {
max = d
ii = i
//fmt.Println(i, d, s, v)
}
}
fmt.Println(ii, max)
}