Use math/big for exact arithmetic
Use math/big for exact arithmetic
Use big.Int for integers beyond machine word limits and big.Rat for exact rational numbers. The receiver of arithmetic methods stores the result. big.Float offers configurable binary precision, not unlimited exact rational arithmetic.
package main
import ( "fmt" "math/big")
func main() { a := big.NewInt(10000000000) b := new(big.Int).Mul(a, a) fmt.Println(b) fmt.Println(a)}The product exceeds int64 range but fits big.Int, subject to available memory. The new receiver leaves a unchanged. Assigning a pointer does not copy the numeric object; use Set for an independent value.
Expected output:
10000000000000000000010000000000Add fractions exactly
package main
import ( "fmt" "math/big")
func main() { a := big.NewRat(1, 10) b := big.NewRat(1, 5) fmt.Println(new(big.Rat).Add(a, b).RatString())}The sum is exactly three tenths. Parse decimal input with Rat.SetString and check success rather than passing an already-rounded float64. Denominators must not be zero.
Expected output:
3/10Try it locally
Add 1/3 and 1/6 and print the reduced fraction.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric engineering 05: Use math/big for exact arithmetic
Check the lesson objective before moving on.
Which type represents exact fractions?
Where does z.Add(a,b) store the result?