I'm writing software and I'm trying to calculate interest on a principal value that changes daily in a predictable way. For example, if you saved $5 each day for five years at a 4% annual interest rate.
I can brute force this calculation, but I imagine there's a better way, which I'm just not aware of. What's the best way to calculate the final principal + interest for the above example?
This can be solved with a recurrence relation.
Say you deposit $d$ at the beginning of each day. Overnight, interest is calculated at periodic rate $r$ on the balance in your account, and credited to your account. Then your balance on day $n$, $B(n)$, satisfies the following:
$$B(1) = d, \\ B(n) = (1+r) \cdot B(n-1) + d, n \geq 2.$$
The solution of this first-order, non-homogeneous difference equation is:
$$B(n) = d\frac{(1+r)^n - 1}{r}.$$
Practically, though, you'll need to carry your values with enough precision so that you don't run into rounding errors too quickly. If you do, then brute-force calculating each $B(n)$ and rounding as needed each day (as the banks do) will be the most accurate.