@prestamype/financial-functions
Version:
Implementación de funciones financieras
61 lines (44 loc) • 998 B
JavaScript
export function bisection(flow) {
const MAX_ITERATIONS = 100
const PRECISION = 1E-9
let min = 0.0
let max = 1.0
let i = 0
let 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
}
export function newton(flow, guess) {
const MAX_ITERATIONS = 100
const PRECISION = 1E-9
let x0 = guess,
i = 0
let 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
}