Execute Program

Python for Programmers: Size and Precision of Numbers

Welcome to the Size and Precision of Numbers lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Python integers don't have a maximum value, as long as there's enough memory to hold them.

  • (The next example shows an extremely large number. We added some extra code to insert spaces after commas so the number wraps cleanly, rather than going off-screen. That extra code uses some language features that we'll see in later lessons.)

  • >
    # This number is huge!
    number = 2**2000
    f"{number:,}".replace(",", ", ")
    Result:
  • The fact that we can compute this integer is very important! In many languages, all of the basic number types have upper limits. Adding 1 to a very large number might cross the limit and raise an exception, or give us infinity, or wrap around to become a negative number instead.

  • Python's integers have no limit. That costs us some performance, but it frees us from having to ask "will this integer get too big?" In Python, no integer is too big!

  • However, Python's floating point numbers do have an upper limit. (Like most programming languages, Python uses IEEE 754 double-precision floating point numbers. Most languages call these "floats", but JavaScript simply calls them "numbers".)

  • Above, we calculated 2**2000, a huge integer. That number is too large to represent as a floating point number. If we try to calculate it as a float, Python raises (or "throws") an OverflowError exception.

  • (If you think that a code example will raise an exception, you can type error.)

  • >
    2.0**2000
    Result:
    OverflowError: (68, 'Result not representable')Pass Icon
  • However, Python doesn't always raise an OverflowError with very large floats. For example, we can use scientific notation to write a number that's too big to fit in a float. In that case we get infinity, not an exception.

  • >
    str(1e309)
    Result:
  • The other important consideration with floats is that they aren't guaranteed to be precise.

  • >
    0.1 + 0.2
    Result:
  • >
    0.1 + 0.2 == 0.3
    Result:
    FalsePass Icon
  • The size and precision limitations on floats aren't specific to Python. IEEE 754 floating point numbers are almost universal in programming, so floats have these downsides in any language. But we tolerate their downsides because they're very efficient, both in terms of memory and in terms of runtime performance.