0

I have an array of number [350000, 350000, 350000]

I have the following code:

function getNPV(rate, periods, Cashflow) {
    var npv = 0;
    for (var i = 0; i < Cashflow.length; i++) {
        npv += Cashflow[i] / Math.pow(1 + rate, periods);
    }
    return npv;
}

Here, cashflow is our array, rate = 6% and period = 91days.

When I take :

 npv = Cashflow[i] / Math.pow(1 + rate, periods);

The output is [348328,346664,344952] when 6% discount rate is applied to 350000 each time.

I am trying to take the sum of [348328,346664,344952] which is $1,039,944 But, it is giving me $1034856 as the result.

Trying the console, it's actually taking the sum of the 3rd value 3 times instead. [344952+344952+344952] for some reason.

Can someone please tell me how to fix this error. Any help is appreciated. Thank you.

CODE

Logic

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
ace23
  • 142
  • 1
  • 16
  • 2
    Post your code here in the question as formatted text, not an external screenshot. – takendarkk Oct 08 '18 at 16:36
  • 1
    You are not varying the period at all in your loop, all three run of the loops are using same value for period, hence same output – Aragorn Oct 08 '18 at 16:38
  • 1
    There's a bug in your algorithm, not in the code. This is a mathematical problem, not a programming problem. – user247702 Oct 08 '18 at 16:40

2 Answers2

0

As I refer to your spreadsheet, you need an array for period not cashflow.

Pass periods and cashflow like:

var periods = [30, 60, 91];
var cashflow = 350000;
getNPV(rate, periods, cashflow);

Your cash flow is same, so no need an array (You may still have an array if you want to vary cashflow)

And use it in the loop:

function getNPV(rate, periods, Cashflow) {
    var npv = rate;

    for (var i = 0; i < periods.length; i++) {
        npv += Cashflow / Math.pow(1 + rate, periods[i]);
    }
    return npv;
}
Aragorn
  • 5,021
  • 5
  • 26
  • 37
  • Thank you. This works so far but i had to hard code it. I am not able to create and array with number of days in each month. I tried to create an array and it gives me dates in between 2 dates. But not the days. Could you give an idea on how to do this. – ace23 Oct 08 '18 at 23:52
  • Not sure I understand where you are struggling. An array would simply be like, `var daysInMonths = [31, 28, 30, 31, ......].` I don't think there is anything that can give you a dynamic array, you'll have to build it yourself. Try json like `{"01":"31", "02": "28", ....}` – Aragorn Oct 09 '18 at 02:26
  • I'd use Date object. Refer this: https://stackoverflow.com/a/315767/1205647 – Aragorn Oct 09 '18 at 14:41
0

You can use returnSum to get the sum of the array

function returnSum(arr) {

  function sum(a, b) {
    return a + b;
  }
  return arr.reduce(sum, 0);
}

let array = [348328,346664,344952]

returnSum(array); //result 1039944
Lenny86
  • 120
  • 1
  • 9