Python's Built-in int is Already Arbitrary-Precision
You're ahead of the game because Python's built-in int type automatically handles arbitrary-precision integers. You don't need an external library like you would in C++, Java, or JavaScript. Operations like 10**1000, 2**10000, or even factorial(1000) just work.
The Real Bottleneck: Operations on Extremely Large Numbers
However, when you reach numbers on the order of 10^100,000 or 10^1,000,000 (googleplex is 10^100, after all), even Python's highly optimized int arithmetic starts to slow down dramatically. Here's why:
- Memory Usage: Storing a number like 10^100,000 requires approximately 100,000 / 3 ≈ 33,333 bytes (since 2^10 ≈ 10^3, each byte stores ~3 decimal digits). That's manageable. But 10^1,000,000? That's ~333,333 bytes per number. If you have multiple such numbers, memory starts becoming a concern.
- Operation Complexity:
- Addition/Subtraction: Roughly linear in the number of digits (O(n)). Still relatively fast.
- Multiplication: Python uses Karatsuba multiplication (O(n^log2(3)) ≈ O(n^1.585)) for large numbers, which is efficient but grows non-linearly. For 10^100,000 * 10^100,000, you're doing hundreds of thousands of digit-wise operations.
- Division and Modulo: Even worse (O(n^2) or slightly better with advanced algorithms). Dividing two googleplex-sized numbers is a multi-second operation even in optimized C code.
- Exponentiation (
a ** b): Python's pow(a, b, [mod]) is very efficient due to modular exponentiation (when mod is given) and exponentiation by squaring. But plain a ** b without modulo reduction materializes the enormous result, which is slow.
Practical Optimizations for Incremental Games
Since your game likely doesn't need the exact value of 10^100,000.00003 every frame, here are strategies to regain performance:
1. Store Numbers in Logarithmic Form (Most of the Time)
Instead of storing resource = 10**100000 + 12345 (which is impractical), store:
resource_log = 100000.0 (a float, representing the logarithm)
resource_mantissa = 1.0 (or some small value near 1.0, as a float)
Now, most operations become operations on floats, which are blazing fast:
- Multiplication:
new_log = log1 + log2; new_mantissa = mantissa1 * mantissa2 (if mantissa product exceeds 10, renormalize by incrementing log and dividing mantissa by 10).
- Addition: Tricky, but approximate using log rules. If
log1 >> log2, then result_log ≈ log1, result_mantissa ≈ mantissa1. If logs are close, use log_sum ≈ max(log1, log2) + log10(1 + 10**(min(log1,log2) - max(log1,log2))). There are fast approximations for this "log-sum-exp" trick.
- Displaying:
format_string = f"{resource_mantissa:.2f}e{int(resource_log)}"
Example Class:
import math
class LogNumber:
def __init__(self, log_value, mantissa=1.0):
self.log = log_value
self.mantissa = mantissa
def __mul__(self, other):
new_mantissa = self.mantissa * other.mantissa
if new_mantissa >= 10:
new_mantissa /= 10
new_log = self.log + other.log + 1
else:
new_log = self.log + other.log
return LogNumber(new_log, new_mantissa)
def __add__(self, other):
if self.log > other.log + 10: # self dominates
return LogNumber(self.log, self.mantissa)
elif other.log > self.log + 10: # other dominates
return LogNumber(other.log, other.mantissa)
else:
# Log-sum-exp trick (base 10)
max_log = max(self.log, other.log)
delta = min(self.log, other.log) - max_log
sum_mantissa = (self.mantissa if self.log == max_log else other.mantissa) * (1 + 10**delta)
if sum_mantissa >= 10:
sum_mantissa /= 10
max_log += 1
return LogNumber(max_log, sum_mantissa)
def __str__(self):
return f"{self.mantissa:.2f}e{int(self.log)}"
# Usage
a = LogNumber(100000, 1.23)
b = LogNumber(99999, 4.56)
c = a * b # Fast
d = a + b # Approximate, fast
print(c) # Something like 1.23e+199999
2. Only Materialize Exact Values When Necessary
- User Interface: Display
log_value formatted as scientific notation (e.g., 1.23e100000). Players don't care about the +12345 part when the exponent is that large.
- Saving: Store
log_value and mantissa as floats. Conversion to/from string is trivial: "log:{self.log};mantissa:{self.mantissa}".
- Critical Calculations: If you must compare
a == b exactly (rare in incremental games), and both a and b are near the same enormous magnitude, then (and only then) materialize a few hundred digits around the "tip" of each number using mpmath or decimal (below).
3. Use decimal Module for Non-Integer Exponents (Optional)
If your game involves resource growth rates like 1.05 ** (10**6) (5% compound growth for a million ticks), Python's float has rounding issues. The decimal module offers configurable precision:
from decimal import Decimal, getcontext
getcontext().prec = 50 # Not 100,000, just enough for display precision
base = Decimal('1.05')
exponent = Decimal(10**6)
result = base ** exponent
print(result) # Still slow for huge exponents, but accurate
4. mpmath for Arbitrary-Precision Floats (If decimal Isn't Enough)
mpmath is an external library (pip install mpmath) for arbitrary-precision floating-point arithmetic. It's slower than int or float but faster than naively trying to exactly multiply 100,000-digit numbers:
import mpmath
mpmath.mp.dps = 100 # 100 decimal places (not digits)
a = mpmath.mpf('1e100000')
b = mpmath.mpf('1.23456789e99999')
c = a * b
print(c) # Fast enough for interactive use, not real-time rendering
Summary:
- Most of the time, work with
LogNumber-style approximations (logarithmic representation). This reduces googleplex-sized numbers to ~2 floats.
- Only when displaying or doing rare critical checks, materialize a small part of the number (e.g., 50 digits) using
decimal or mpmath if needed.
- Forget exact arithmetic on numbers > 10^1000 unless absolutely necessary. It's computationally infeasible in real-time.
By switching to logarithmic storage and approximate arithmetic, your Python game should handle "googleplex"-scale numbers interactively rather than taking forever. The human eye can't tell the difference between 1.00000000000001e100000 and 1.00000000000000e100000 anyway!