Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - Divide big.Float

Tags:

math

go

I'm dealing with numbers that require a big.Float type, and I need to divide them. I'm aware that big.Int has a .Div() function, but if I'm correct, that truncates the value and loses the precision I get from using big.Float.

Relevant code

func e(prec int64) (res *big.Float) {
    res = big.NewFloat(float64(1.0))
    base := big.NewInt(prec)

    for i := base; i.Cmp(big.NewInt(int64(0))) == 1; _ = i.Sub(i, big.NewInt(1)) {
        d := big.NewFloat(float64(1.0))
        _ = d.Div(fact(i)) // error here
        res.Add(d)
    }

    return
}
like image 805
Valkyrie Avatar asked Apr 22 '16 15:04

Valkyrie


People also ask

How do you divide in go?

Multiplication and Division The sign we'll use in Go for multiplication is * and the sign we'll use for division is / .

What is big int Golang?

Golang doesn't check for overflows implicitly and so this may lead to unexpected results when a number larger than 64 bits are stored in a int64. To solve this problem, Go provides the Package “big” which implements arbitrary-precision arithmetic (big numbers).


1 Answers

Use Float.Quo for big.Float division:

x, y := big.NewFloat(10), big.NewFloat(3)
z := new(big.Float).Quo(x, y)

http://play.golang.org/p/GRPAKQNkq0

like image 179
JimB Avatar answered Sep 22 '22 00:09

JimB