← Home

021. Exponentiation

Power operations for mathematical modeling

021. Exponentiation

RAM Manager — Exponential Memory Growth Alert

Aryan’s RAM manager needs to predict when memory usage will hit a threshold. A process that doubles its RAM every minute starts at initial_mb and after minutes minutes holds initial_mb * 2^minutes MB.

He writes projected_ram(initial_mb, minutes) to forecast usage, but uses * (multiplication) where he needs ** (exponentiation). So after 10 minutes, projected_ram(100, 10) returns 100 * 10 = 1000 instead of 100 * 2**10 = 102400. The alert never fires because the projected value is 100x too small.

The lesson: * multiplies two numbers; ** raises the left operand to the power of the right. Exponential growth is real — Python’s ** operator handles it natively without needing math.pow().


💡 Fun fact: Python’s ** operator is right-associative: 2 ** 3 ** 2 evaluates as 2 ** (3 ** 2) = 2 ** 9 = 512, not (2 ** 3) ** 2 = 64. This matches standard mathematical notation. In C, there is no ** operator — you must call pow() from <math.h>, which only handles double precision floats.

⚠️ Watch out: -2 ** 2 evaluates as -(2 ** 2) = -4, not (-2) ** 2 = 4. The ** operator binds tighter than unary minus. If you intend to square a negative number, always wrap it in parentheses: (-2) ** 2.

🤔 Think about it: Compound interest uses (1 + r/n) ** (n*t). If n (compounding frequency) grows toward infinity, the formula approaches e ** (r*t) — continuous compounding. How does this connect Python’s ** operator to the mathematical constant e?

Learning objectives

  • Use ** for exponentiation
  • Apply ** to financial and scientific formulas
  • Understand ** operator precedence

Key concepts

  • exponentiation
  • **
  • power

Try it

Concept detail

** is Python’s exponentiation (power) operator. 23 = 8, 40.5 = 2.0 (square root). ** has higher precedence than , /, +, -. So 2**34 = (23)4 = 32, not 2(3*4). -22 = -(2*2) = -4, not (-2)2 = 4. Use parentheses to be explicit. Python integers can be arbitrarily large: 21000 works! For precise financial math, use the Decimal module to avoid float rounding errors.

Solution

def compound_interest(principal, rate, n, years):
    growth_factor = (1 + rate / n) ** (n * years)
    return principal * growth_factor

Tests

def test_simple_doubling():
    # P=1000, r=100%(1.0), n=1, t=1 → 1000*(1+1)^1 = 2000
    result = compound_interest(1000, 1.0, 1, 1)
    assert abs(result - 2000.0) < 0.01

def test_standard_case():
    # P=1000, r=10%(0.1), n=1, t=1 → 1100.0
    result = compound_interest(1000, 0.1, 1, 1)
    assert abs(result - 1100.0) < 0.01

def test_two_years():
    # P=1000, r=10%, n=1, t=2 → 1210.0
    result = compound_interest(1000, 0.1, 1, 2)
    assert abs(result - 1210.0) < 0.01

def test_monthly_compounding():
    # P=1000, r=12%, n=12, t=1 → ~1126.83
    result = compound_interest(1000, 0.12, 12, 1)
    assert abs(result - 1126.83) < 0.1

Resources