@prestamype/financial-functions
Version:
Implementación de funciones financieras
62 lines (50 loc) • 1.22 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.bisection = bisection;
exports.newton = newton;
function bisection(flow) {
var MAX_ITERATIONS = 100;
var PRECISION = 1E-9;
var min = 0.0;
var max = 1.0;
var i = 0;
var x, npv, factor;
while (i < MAX_ITERATIONS) {
x = (min + max) / 2;
factor = x + 1.0;
npv = flow.slice().reverse().reduce((c, a) => c / factor + a, 0);
if (npv > 0) {
min = x;
} else {
max = x;
}
if (Math.abs(max - min) <= 2 * PRECISION) {
// console.log(`converged after ${i} iterations`)
return x;
}
i++;
}
return null;
}
function newton(flow, guess) {
var MAX_ITERATIONS = 100;
var PRECISION = 1E-9;
var x0 = guess,
i = 0;
var x1, factor, npv, npv_dot;
while (i < MAX_ITERATIONS) {
factor = x0 + 1.0;
npv = flow.slice().reverse().reduce((c, a) => c / factor + a, 0);
npv_dot = flow.slice(1).reverse().reduce((c, a, i) => c / factor - (i + 1) * a, 0);
x1 = x0 - npv / npv_dot;
if (Math.abs(x1 - x0) <= PRECISION) {
// console.log(`converged after ${i} iterations`)
return x1;
}
x0 = x1;
i++;
}
return null;
}
;