To calculate the final amount, you can utilize the following formula:
A = Pert
Here, A
represents the resulting amount; P
is the initial principal amount; e
is Euler's Number, approximately 2.718281828459045
; r
denotes the interest rate as a decimal; and t
stands for the time in years, usually divided by 360
.
If the starting principal is 0
, the result would also be 0
since no interest can accumulate on a principal of 0
. To begin with a nominal value of .01
, update the principal to include the accrued interest.
In javascript
, you can employ a do..while
loop to compute the new principal. Set the loop limit at half the initial rate, or .05/2
. Inside the loop, create an immediately invoked function expression to pass the current principal, push a function that returns a Promise
after either current
or current * duration
, where duration
is a positive integer. Use Array.prototype.reduce()
to execute functions sequentially, increasing the duration of each setTimeout
call based on the current principal or current * duration
.
You can also modify the formula to incorporate continuous compounding:
A = Per(t/n)
For instance, when setting n
to 360
, continuously compound interest from a principal of 1
at a rate of .05
over one fiscal year (360
iterations) would yield incremental results leading up to 1.0512710963760241
, with a total interest accumulation of .0512710963760241
.
Calling the compound
function with 1
as input will return 1.0512710963760241
.
var current = 0; // principal
var max = 20; // maturity, in years
var rate = .05; // annual rate as decimal
var time = 1; // time in years, alternatively `1/360`
var N = 360; // fiscal year
var arr = []; // store functions which return a `Promise`
var duration = 500;
var output = document.querySelector("output");
function compound(p, r, t) {
return ((p||.01) * Math.exp(r * t)); // or `Math.exp(r * (t/N))`
}
do {
current = compound(current, rate, time);
(function(curr) {
arr.push(
function() {
return new Promise(function(resolve) {
setTimeout(function() {
output.innerHTML += `current principal: ${curr}<br>`;
resolve();
}, curr * duration)
})
}
)
})(current)
} while (current < max - (rate / 2));
arr.reduce(function(promise, next) {
return promise.then(next)
}, Promise.resolve())
.then(function() {
output.innerHTML += `<br>max - current: ${max - current}`;
});
<output></output>