Skip to content

Instantly share code, notes, and snippets.

@viniciusss
Created April 1, 2016 13:41
Show Gist options
  • Save viniciusss/81a59acd82bb1365db5af2c86056f06e to your computer and use it in GitHub Desktop.
Save viniciusss/81a59acd82bb1365db5af2c86056f06e to your computer and use it in GitHub Desktop.
Função para cálculo de juros baseado no calc.js
<?php
function calculo_taxa_juros($numeroParcelas, $valorParcelas, $valorTotal, $fv = null, $tipo = null, $guess = null) {
print('$numeroParcelas: ' . $numeroParcelas) . PHP_EOL;
print('$valorParcelas: ' . $valorParcelas) . PHP_EOL;
print('$valorTotal: ' . $valorTotal) . PHP_EOL;
print('$fv: ' . $fv) . PHP_EOL;
print('$tipo: ' . $tipo) . PHP_EOL;
print('$guess: ' . $guess) . PHP_EOL;
//function comp_ir(np,ir,$valorParcelas,$valorTotal,$fv,pb)
if ($guess == null) $guess = 0.01;
if ($fv == null) $fv = 0;
if ($tipo == null) $tipo = 0;
//FROM MS http://office.microsoft.com/en-us/excel-help/rate-HP005209232.aspx
define('FINANCIAL_MAX_ITERATIONS', 128);//Bet accuracy with 128
define('FINANCIAL_PRECISION', 0.0000001);//1.0e-8
$y = null;
$y0 = null;
$y1 = null;
$x0 = null;
$x1 = 0;
$f = 0;
$i = 0;
$rate = $guess;
if (abs($rate) < FINANCIAL_PRECISION) {
$y = $valorTotal * (1 + $numeroParcelas * $rate) + $valorParcelas * (1 + $rate * $tipo) * $numeroParcelas + $fv;
} else {
$f = exp($numeroParcelas * log(1 + $rate));
$y = $valorTotal * $f + $valorParcelas * (1 / $rate + $tipo) * ($f - 1) + $fv;
}
$y0 = $valorTotal + $valorParcelas * $numeroParcelas + $fv;
$y1 = $valorTotal * $f + $valorParcelas * (1 / $rate + $tipo) * ($f - 1) + $fv;
// find root by Newton secant method
$i = $x0 = 0.0;
$x1 = $rate;
while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
$rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
$x0 = $x1;
$x1 = $rate;
if (abs($rate) < FINANCIAL_PRECISION) {
$y = $valorTotal * (1 + $numeroParcelas * $rate) + $valorParcelas * (1 + $rate * $tipo) * $numeroParcelas + $fv;
} else {
$f = exp($numeroParcelas * log(1 + $rate));
$y = $valorTotal * $f + $valorParcelas * (1 / $rate + $tipo) * ($f - 1) + $fv;
}
$y0 = $y1;
$y1 = $y;
++$i;
}
return round($rate*100, 2);
}
echo comp_ir(50, 787, -30000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment