Lesson 8. Big numbers

 

After reading lesson 8, you’ll be able to

  • Save your zero key by specifying an exponent
  • Use Go’s big package for really big numbers
  • Use big constants and literal values

Computer programming is full of trade-offs. Floating-point types can store numbers of any size, but they lack precision and accuracy at times. Integers are accurate but have a limited range. What if you need a really big, accurate number? This lesson explores two alternatives to the native float64 and int types.

Consider this

CPUs are optimized for integer and floating-point math, but other numeric representations are possible. When you need to go big, Go has you covered.

What are some situations where integers are too small, floating-point too imprecise, or another numeric type would be more suitable?

8.1. Hitting the ceiling

If you haven’t realized it yet, 64-bit integers are mind-bogglingly big—much bigger than their 32-bit counterparts.

For some perspective, the nearest star, Alpha Centauri, is 41.3 trillion kilometers away. A trillion: that’s one followed by 12 zeros, or 1012. Rather than painstakingly typing every zero, you can write such numbers in Go with an exponent, like so:

var distance int64 = 41.3e12

An int32 or uint32 can’t contain such a large number, but an int64 doesn’t break a sweat. Now you can go about your business, perhaps calculating how many days it would take to travel to Alpha Centauri, a task tackled in the following listing.

8.2. The big package

8.3. Constants of unusual size

Summary

sitemap