Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I require converting this for loop into a recursion function

rate, cashflows = 0.05,[-1100,300,450,800]

def npv_for_loop(rate,cashflows):
  NPV=0
  for i in range(len(cashflows)):
    NPV+=cashflows[i]/(1+rate)**i
    print(round(NPV,3))

i generally have no idea how a recursion works and would really appreciate if anybody can help me.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is an example of how you could convert the given for loop into a recursive function:

def npv(rate, cashflows, i=0, NPV=0):
    # Stop the recursion when we reach the end of the cash flows
    if i == len(cashflows):
        return NPV

    # Compute the present value of the ith cash flow
    present_value = cashflows[i] / (1 + rate) ** i

    # Recursively call the function to compute the present value of the remaining cash flows
    return npv(rate, cashflows, i + 1, NPV + present_value)

rate, cashflows = 0.05,[-1100,300,450,800]

# Compute the NPV of the cash flows using the recursive function
npv = npv(rate, cashflows)
print(npv)

In this code, the npv() function computes the present value of each cash flow in the given cashflows array and sums them up to compute the NPV of the cash flows. The i parameter is the index of the current cash flow being considered, and the NPV parameter is the running total of the present values of the cash flows that have been considered so far. The npv() function calls itself recursively with an updated value of i and NPV until all of the cash flows have been considered.

Recursive functions work by calling themselves with updated values for their parameters, and then using the updated values to compute a result. In the case of the npv() function, it calls itself with an updated value of i and NPV until all of the cash flows have been considered, and then it returns the final value of NPV as the result. This is an example of a tail-recursive function, where the final result is computed by the base case (i.e., when i == len(cashflows)) and then passed back up the recursive calls.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading