goarithmetic-expressions

Is there a standard type to do "accurate division" in Go?


I would like to do some "accurate division" in go. Is there a standard type for that?

For example, I would like to store the value "1/3" and "2/3" and be able to add them.

I can define my own type like this:

type MyType struct {
    Numerator   int
    Denominator int
}

and define functions like:

func (a MyType) Plus(b MyType) MyType {
    d := a.Denominator * b.Denominator
    n := (a.Numerator * b.Denominator) + (b.Numerator * a.Denominator)

    return MyType{Numerator: n, Denominator: d}
}

but there is probably a more elegant way to do this or a "standard type" that already does that.


Solution

  • I didn't know about big.Rat. This is all I need! Thank you for your help