func (me *StatisticalAccumulator) PutString(x string) {

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

	me.PutRat(xx)
}
Example #2
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 #3
0
// MakeConst makes an ideal constant from a literal
// token and the corresponding literal string.
func MakeConst(tok token.Token, lit string) Const {
	switch tok {
	case token.INT:
		var x big.Int
		_, ok := x.SetString(lit, 0)
		assert(ok)
		return Const{&x}
	case token.FLOAT:
		var y big.Rat
		_, ok := y.SetString(lit)
		assert(ok)
		return Const{&y}
	case token.IMAG:
		assert(lit[len(lit)-1] == 'i')
		var im big.Rat
		_, ok := im.SetString(lit[0 : len(lit)-1])
		assert(ok)
		return Const{cmplx{big.NewRat(0, 1), &im}}
	case token.CHAR:
		assert(lit[0] == '\'' && lit[len(lit)-1] == '\'')
		code, _, _, err := strconv.UnquoteChar(lit[1:len(lit)-1], '\'')
		assert(err == nil)
		return Const{big.NewInt(int64(code))}
	case token.STRING:
		s, err := strconv.Unquote(lit)
		assert(err == nil)
		return Const{s}
	}
	panic("unreachable")
}
Example #4
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 #5
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 #6
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 #7
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 #8
0
func Mul(a, b string) string {
	ra := new(big.Rat)
	rb := new(big.Rat)

	ra.SetString(a)
	rb.SetString(b)

	return ra.Mul(ra, rb).FloatString(4)
}
func TestPutRat(t *testing.T) {

	testsOfTests := [][]struct {
		x                string
		expectedN        string
		expectedMean     string
		expectedVariance string
	}{
		{
			{"5/3", "1/1", "5/3", "0/1"},
			{"5/3", "2/1", "5/3", "0/1"},
			{"5/3", "3/1", "5/3", "0/1"},
			{"5/3", "4/1", "5/3", "0/1"},
		},

		{
			{"4/7", "1/1", "4/7", "0/1"},
		},

		{
			{"1", "1/1", "1/1", "0/1"},
			{"2/1", "2/1", "3/2", "1/4"},
			{"3.0", "3/1", "2/1", "2/3"},
			{"8/2", "4/1", "5/2", "5/4"},
			{"5", "5/1", "3/1", "2/1"},
		},
	}

	for testSetNumber, tests := range testsOfTests {

		statisticalAccumulator := New()

		for datumNumber, datum := range tests {

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

			statisticalAccumulator.PutRat(x)

			if actualN := statisticalAccumulator.N(); actualN.String() != datum.expectedN {
				t.Errorf("With test set number [%v], when putting [%v] (i.e., datum number [%v]) into the statistical accumulator, expected N to be [%v], but instead got [%v].", testSetNumber, datum.x, datumNumber, datum.expectedN, actualN)
				continue
			}

			if actualMean := statisticalAccumulator.Mean(); actualMean.String() != datum.expectedMean {
				t.Errorf("With test set number [%v], when putting [%v] (i.e., datum number [%v]) into the statistical accumulator, expected Mean to be [%v], but instead got [%v].", testSetNumber, datum.x, datumNumber, datum.expectedMean, actualMean)
				continue
			}

			if actualVariance := statisticalAccumulator.Variance(); actualVariance.String() != datum.expectedVariance {
				t.Errorf("With test set number [%v], when putting [%v] (i.e., datum number [%v]) into the statistical accumulator, expected Variance to be [%v], but instead got [%v].", testSetNumber, datum.x, datumNumber, datum.expectedVariance, actualVariance)
				continue
			}
		}
	}

}
Example #10
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
}
Example #11
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 #12
0
// Parse takes a string and constructs a Decimal from the string
func Parse(s string) (Decimal, error) {
	rat := new(big.Rat)
	_, success := rat.SetString(s)
	if success {
		return Decimal{true, *rat}, nil
	} else if s == "Inf" || s == "Infinity" {
		// Return a decimal of 1 but note not finite
		return Decimal{false, *big.NewRat(1, 1)}, nil
	} else if s == "-Inf" || s == "-Infinity" {
		// Return a decimal of -1 but note not finite
		return Decimal{false, *big.NewRat(-1, 1)}, nil
	}
	// Return Decimal of 0 but note note finite and error
	return Decimal{false, *big.NewRat(0, 1)}, errors.New("Cannot create Decimal '" + s + "'")
}
Example #13
0
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
}
Example #14
0
//"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))

}
Example #15
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

}
func mul(args []string, m Matrix) (Matrix, error) {
	if len(args) != 2 {
		return nil, fmt.Errorf("expected row and constant")
	}

	r, err := rows(m, args[0])
	if err != nil {
		return nil, err
	}

	n := m.Clone()
	x := r[0]
	c := new(big.Rat)
	c.SetString(args[1])
	for i := range n[x] {
		n[x][i].Mul(n[x][i], c)
	}

	return n, nil
}
Example #17
0
File: p26.go Project: yzx226/Euler
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)
}
Example #18
0
func (c Test) NumTest1() revel.Result {
	text := fmt.Sprint(94.85 / 100.0)
	text += "____"
	rat := big.Rat{}
	rat.SetString("94.85/100.0")
	text += rat.FloatString(10)
	text += "____"
	text += fmt.Sprint(c.getFloat("0.1") + c.getFloat("0.7"))
	text += "____"
	text += fmt.Sprint(c.getFloat("0.1") + c.getFloat("0.6"))
	text += "____"
	text += fmt.Sprint(c.getFloat("0.13") + c.getFloat("3.59"))
	text += "_dec_"
	dec1 := c.add("0.1", "0.7")
	text += dec1.String()
	text += "____"
	dec1 = c.add("0.1", "0.6")
	text += dec1.String()
	text += "____"
	dec1 = c.add("0.13", "3.59")
	text += dec1.String()
	return c.RenderText(text)
}
func load(args []string) (Matrix, error) {
	if len(args) != 1 {
		return nil, fmt.Errorf("expected filename")
	}

	f, err := os.Open(args[0])
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var m Matrix
	s := bufio.NewScanner(f)
	r := -1
	for s.Scan() {
		toks := strings.Split(strings.TrimSpace(s.Text()), " ")
		if r >= 0 && len(toks) != r {
			return nil, fmt.Errorf("row with size %v doesn't match previous row size: %v", len(toks), r)
		} else {
			r = len(toks)
		}

		var n Vector
		for i := range toks {
			x := new(big.Rat)
			y, _ := x.SetString(toks[i])
			if y == nil {
				return nil, fmt.Errorf("invalid row %v: %q", i, s.Text())
			}
			n = append(n, x)
		}
		m = append(m, n)
	}

	return m, nil
}
Example #20
0
func ExampleRat_SetString() {
	r := new(big.Rat)
	r.SetString("355/113")
	fmt.Println(r.FloatString(3))
	// Output: 3.142
}
Example #21
0
File: order.go Project: sdvdxl/wine
// 上传订单
func OrderUploadHandler(c *gin.Context) {

	//销售不允许上传
	auth := userauth.Auth(c)
	if auth.IsRole(bean.ROLE_SALES) {
		c.HTML(http.StatusOK, "order_upload.tmpl", gin.H{"successCount": 0, "isUpload": true, "errMsg": "您没有权限"})
		return
	}

	request := c.Request
	request.ParseMultipartForm(2 << 10)
	file, fileHeader, err := request.FormFile("file")
	if err != nil {
		Logger.Error("upload file error, %v", err)
		panic(err)
	}

	_ = fileHeader

	csvReader := csv.NewReader(file)

	sql := insertSQL
	values := make([]interface{}, 0, 40)

	_, err = csvReader.Read()
	if err != nil {
		panic(err)
	} else if err == io.EOF {
		Logger.Debug("read file end")
		return
	}

	rowsCount := 0
	for {
		if row, err := csvReader.Read(); err != nil && err == io.EOF {
			break
		} else if err != io.EOF {
			rowsCount++
			// 49 params  47 ?
			sql += `(?, now(), now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
			?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ),`
			values = append(values, uuid.New())
			r := new(big.Rat)
			r.SetString(row[0])
			values = append(values, r.RatString())
			values = append(values, appendValues(row, 1, 12)...)
			Logger.Debug("address: %v", row[13])
			address := strings.Fields(row[13]) //dizhi

			Logger.Debug("address args len:%v", len(address))
			if len(address) == 4 {
				values = append(values, address[0])
				values = append(values, address[1])
				values = append(values, address[2])
				values = append(values, address[3])
				for i := 0; i < 3; i++ {
					values = append(values, nil)
				}
			} else {
				for i := 0; i < 7; i++ {
					values = append(values, nil)
				}
			}

			values = append(values, appendValues(row, 14, 15)...)

			runes := []rune(row[16])
			if strings.HasPrefix(row[16], "'") {
				runes = runes[1:]
			}
			values = append(values, string(runes))

			values = append(values, appendValues(row, 17, 28)...)

			runes = []rune(row[29])
			if strings.HasSuffix(row[29], "元") {
				runes = runes[:len(runes)-1]
			}
			buyerServiceFee, err := strconv.Atoi(string(runes))
			if err != nil {
				buyerServiceFee = 0
			}
			values = append(values, buyerServiceFee)
			values = append(values, appendValues(row, 30, 32)...)

			address = strings.Fields(row[35]) //dizhirow[36] //fixed dizhi
			Logger.Debug("fixed address: %v", row[35])
			Logger.Debug("fixed address args len:%v", len(address))
			// 7
			if len(address) == 4 {
				values = append(values, address[0])
				values = append(values, address[1])
				values = append(values, address[2])
				values = append(values, address[3])
				for i := 0; i < 3; i++ {
					values = append(values, nil)
				}
			} else {
				for i := 0; i < 7; i++ {
					values = append(values, nil)
				}
			}
		}
	}

	sql = sql[:len(sql)-1]

	Logger.Debug("sql:%v", sql)
	Logger.Debug("values len:%v", len(values))
	Logger.Debug("values:%v", values)

	if len(values) > 0 {
		stmt, err := db.Engine.DB().Prepare(sql)
		util.PanicError(err)
		defer stmt.Close()
		result, err := stmt.Exec(values...)
		util.PanicError(err)

		count, err := result.RowsAffected()
		util.PanicError(err)
		Logger.Debug("inserted rows count:%v", count)
	}

	c.HTML(http.StatusOK, "order_upload.tmpl", gin.H{"successCount": rowsCount, "isUpload": true, "errMsg": "上传成功"})

}
Example #22
0
func ToDecimal(v string) Decimal {
	r := new(big.Rat)
	r.SetString(v)
	return Decimal{Value: r}
}
Example #23
0
// Converts a string into a `*big.Rat` which is an arbitrary precision rational number stored in decimal format
func ToRat(v string) *big.Rat {
	rat := new(big.Rat)
	rat.SetString(v)
	return rat
}
Example #24
0
// Parses a ledger file and returns a list of Transactions.
//
// Transactions are sorted by date.
func ParseLedger(ledgerReader io.Reader) (generalLedger []*Transaction, err error) {
	var trans *Transaction
	scanner := bufio.NewScanner(ledgerReader)
	var line string
	var lineCount int
	for scanner.Scan() {
		line = scanner.Text()
		lineCount++
		if strings.HasPrefix(line, ";") {
			// nop
		} else if len(line) == 0 {
			if trans != nil {
				transErr := balanceTransaction(trans)
				if transErr != nil {
					return generalLedger, fmt.Errorf("%d: Unable to balance transaction, %s", lineCount, transErr)
				}
				generalLedger = append(generalLedger, trans)
				trans = nil
			}
		} else if trans == nil {
			lineSplit := strings.SplitN(line, " ", 2)
			if len(lineSplit) != 2 {
				return generalLedger, fmt.Errorf("%d: Unable to parse payee line: %s", lineCount, line)
			}
			dateString := lineSplit[0]
			transDate, dateErr := time.Parse(TransactionDateFormat, dateString)
			if dateErr != nil {
				return generalLedger, fmt.Errorf("%d: Unable to parse date: %s", lineCount, dateString)
			}
			payeeString := lineSplit[1]
			trans = &Transaction{Payee: payeeString, Date: transDate}
		} else {
			var accChange Account
			lineSplit := strings.Split(line, " ")
			nonEmptyWords := []string{}
			for _, word := range lineSplit {
				if len(word) > 0 {
					nonEmptyWords = append(nonEmptyWords, word)
				}
			}
			lastIndex := len(nonEmptyWords) - 1
			rationalNum := new(big.Rat)
			_, balErr := rationalNum.SetString(nonEmptyWords[lastIndex])
			if balErr == false {
				// Assuming no balance and whole line is account name
				accChange.Name = strings.Join(nonEmptyWords, " ")
			} else {
				accChange.Name = strings.Join(nonEmptyWords[:lastIndex], " ")
				accChange.Balance = rationalNum
			}
			trans.AccountChanges = append(trans.AccountChanges, accChange)
		}
	}
	// If the file does not end on empty line, we must attempt to balance last
	// transaction of the file.
	if trans != nil {
		transErr := balanceTransaction(trans)
		if transErr != nil {
			return generalLedger, fmt.Errorf("%d: Unable to balance transaction, %s", lineCount, transErr)
		}
		generalLedger = append(generalLedger, trans)
		trans = nil
	}
	sort.Sort(sortTransactionsByDate{generalLedger})
	return generalLedger, scanner.Err()
}