I made a Python script to calculate factorials and tested it with 1000! but when I put 1000! into my mac's built in calculator to check the calculation it returns "Not a number". I did some testing and found the built in calculator can only calculate up-to 101 factorial. Why is this?
The number corresponding to 1000! is larger than what your calculator uses to store numbers. That number actually has 2568 digits, i.e.:
import math
print(len(str(math.factorial(1000))))
# 2568
Your calculator uses a predetermined amount of memory to store a single number. There are several different ways to store numbers in a given amount of bits. Popular such methods are float
and int
.
Assuming that your calculator uses 64 bit, these would become float64
or int64
, which can hold up to 2 ** 1023 ~ 9e+307
or 2 ** 63 ~ 9223372036854775808
respectively.
By contrast, Python integers have arbitrary precision, meaning that any arbitrarily large number (for as long as you have available memory in your system) will be represented exactly in Python.
The price of this choice is eventually speed and memory consumption:
There are applications where these shortcomings are mostly irrelevant, and other applications (e.g. numerical analysis) where they are very important. But fear not, Python offers a number of tools and libraries to use fixed-precision numbers when needed, the most prominent of which is probably NumPy.