I'm writing a Javascript program to display a mortgage amortization from a user input form that asks for typical things such as loan amount, interest rate, etc...
A lot of sites, such as this one, attempt to explain the math equations for computing the fundamentals of a home mortgage loan as some variant of the following:
$P = L[c(1 + c)^n]/[(1 + c)^n - 1]$
In the first equation, P is the computation of the monthly principal based on the loan amount (L), the number of payments (n), and interest (c).
The problem with this equation is that when c is $zero$ or sufficiently close, the result can not be computed in software code. Since the denominator, $[(1+0)^n-1]=0$ This results in divide by zero issues.
Now I can obviously write code that says if (interest == 0) then payment=L/n but that just feels wrong to have to special case that condition. The code will still hit a floating point error if the user types in ".000000000001" for interest rate.
Is there a better formula for computing interest and principal payments that works even when interest rates approach zero?
Here is a rather gross solution, but it avoids the zero cancellation:
Since $(1+c)^n = \sum_{k=0}^m \binom{n}{k} c^k$, we have $(1+c)^n -1 = \sum_{k=1}^m \binom{n}{k} c^k$, and hence we can write $\frac{c}{(1+c)^n-1} = \frac{1}{\sum_{k=1}^m \binom{n}{k} c^{k-1}}$, hence $$\frac{c(1+c)^n}{(1+c)^n-1} = \frac{(1+c)^n}{\sum_{k=1}^m \binom{n}{k} c^{k-1}} $$
Alternatively:
Note that the real issue is computing $\frac{(1+x)^n-1}{x}$ for small $x \neq 0$ (if $x=0$, use $\frac{1}{n}$). This is equivalent to computing $\frac{e^{n\ln(1+x)}-1}{x}$
Many libraries have an $\operatorname{expm1}$ and $\operatorname{log1p}$ functions, which compute (accurately for small $x$) the functions $x \mapsto e^x -1$ and $x \mapsto \ln(1+x)$.
So, you could try something like for $x=0$ use $\frac{1}{n}$, if $x<1$ use $\frac{\operatorname{expm1}(n\operatorname{log1p})}{x}$, else use $\frac{(1+x)^n-1}{x}$.