Debug School

ashley
ashley

Posted on

Modeling Compound Interest in Code: Why Loop Iteration Accumulates Floating-Point Drift

When building financial algorithms or growth projections, developers often write a simple loop that multiplies capital by $(1 + r/12)$ at each step. Over multi-year horizons, this iterative accumulation in IEEE 754 floating-point arithmetic introduces drift compared to the exact mathematical closed form.

The Closed-Form Equation

For initial capital $PV$, nominal annual interest rate $r$, and $m$ compounding periods per year, the compound value after $t$ years is:

FV = PV * ((1 + r / m) ** (m * t))

The effective annual rate (APY) derived from $m$ compounding periods is:

APY = ((1 + r / m) ** m) - 1

Comparison of Compounding Frequency (on $10,000 at 6% Nominal Rate)

Compounding Frequency ($m$) Formula APY Final Balance ($1 Year)
Annual ($m = 1$) $(1 + 0.06)^1 - 1$ $6.0000\%$ $10,600.00
Quarterly ($m = 4$) $(1 + 0.015)^4 - 1$ $6.1364\%$ $10,613.64
Monthly ($m = 12$) $(1 + 0.005)^{12} - 1$ $6.1678\%$ $10,616.78
Daily ($m = 365$) $(1 + 0.06/365)^{365} - 1$ $6.1831\%$ $10,618.31
Continuous ($m \to \infty$) $e^{0.06} - 1$ $6.1837\%$ $10,618.37

Python Implementation

import math

def calculate_compound_interest(pv: float, annual_rate: float, years: float, comp_freq: int = 12) -> float:
    if pv < 0 or annual_rate < 0 or years <= 0:
        raise ValueError("Invalid negative input values.")

    if comp_freq == 0:
        # Continuous compounding
        return pv * math.exp(annual_rate * years)

    period_rate = annual_rate / comp_freq
    total_periods = comp_freq * years
    return pv * math.pow(1.0 + period_rate, total_periods)
Enter fullscreen mode Exit fullscreen mode

Verification and Interactive Recheck

To test custom compounding parameters and view period-by-period growth charts, verify calculations with the compound interest calculator at Miryori.


Disclosure: The author leads content at Miryori, the free online calculator suite linked above. Educational arithmetic only, not financial advice.

Top comments (0)