Menu

Three invariants every fixed-rate loan calculator should pass
📰

Three invariants every fixed-rate loan calculator should pass

DEV Community: typescript·Nick from QuantStock·20 days ago
#RkPZFfW2
#devtotypescript#devto#dev#principal#interest
Long article (846 words) — no AI summary yet.
Reading 0:00
15s threshold

Financial calculators are deceptively easy to demo. A form accepts a principal, a rate, and a number of periods; a plausible monthly payment appears. But a plausible number is not a guarantee of a correct amortization schedule.

Here are three useful invariants for a basic fixed-rate, end-of-period, fully amortizing loan. They are simple enough to test without a second implementation of the whole product.

1. Payment formula should have an explicit zero-rate branch

If principal is P , the periodic interest rate is r , and the number of payments is n , the level payment is

payment = P * r / (1 - (1 + r) ** (-n))

When r = 0 , this expression divides zero by zero. The correct result is just P / n .

A small teaching implementation:

function fixedPayment ( principal : number , annualRate : number , months : number ) : number { if ( ! Number . isFinite ( principal ) || principal <= 0 ) throw new Error ( "Invalid principal" ) ; if ( ! Number .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.