Accurate Computations and the big Package

This lesson discusses how Go ensures accurate computations in its program via the big package.

We'll cover the following

A major problem

We know that programmatically performed floating-point computations are sometimes not accurate. If you use Go’s float64 type in floating-point numbers computation, the results are accurate to about 15 decimal digits, enough for most tasks. When computing with very big whole numbers, the range of the types int64 or uint64 might also be too small. In that case, float32 or float64 can be used if accuracy is not a concern, but if it is, we cannot use floating-point numbers because they are only represented in an approximated way in memory.

Solution provided by Go

For performing perfectly accurate computations with integer values Go provides the math/big package contained in math: big.Int for integers, big.Rat for rational numbers (these are numbers than can be represented by a fraction like 2/5 or 3.1416 but not irrational numbers like e or π) and big.Float. These types can hold an arbitrary number of digits, only limited by the machine’s available memory. The downside is the bigger memory usage and the processing overhead, which means they are a lot slower to process than built-in integers.

A big integer is constructed with the function big.NewInt(n), where n is an int64. A big rational number with big.NewRat(n, d), where both n (the numerator) and d (the denominator) are of type int64. A big float number is constructed with the function big.NewFloat(x), where x is a float64.

Because Go does not support operator overloading, all the methods of the big types have names like Add() for addition and Mul() for multiplication. They are methods (see Chapter 8) acting on the integer, rational or float as a receiver. In most cases, they modify their receiver and return the receiver as a result, so that the operations can be chained. This saves memory because no temporary big.Int variables have to be created to hold intermediate results.

We see this in action in the following program:

Get hands-on with 1200+ tech skills courses.