I've read the Mathematica documentation and am certain there's way to do this with functional programming, but can't quite conceive yet how. I've taken a simple example (stating the series for remaining balance on a fixed-interest loan - ignoring the hairsplitting about whether the interest is calculated before or after the first payment is made. I have randomly chosen interest to be applied before payment).
Pj = principal at period j
pmt = payment
i = interest per period
month 0: P1 = P0(1 + i) - pmt
month 1: p2 = (P0(1 + i) - pmt)(1 + i) - pmt
month 2: p3 = ((P0(1 + i) - pmt)(1 + i) - pmt )
month 3: p4 = (((P0 (1 + i) - pmt)(1 + i) - pmt))(1 + i) - pmt
What I want to do is build the state at month N. This is purely practice/learning for building nested functions using Mathematica code. I know the fixed-interest loan-repayment equation is easily derived and easily solved, but my goal here is to learn how to do repeated function application for real-world things -- Nest[f, x, 3]
is reminiscent of what I want to do but can't see how to make it work.
Here is what I have tried: pure function:
f = #1 (1 + i) - #2 &
apply it:
f[principal, payment]
response:
(1 + i) P - payment
so, some progress.
I can manually repeatedly apply the pure function thus:
f[(1 + i) P - payment, payment]
to get
(1 + i) ((1 + i) P - payment) - payment
obviously correct, but I can't help thinking that I could get the correct formula by means other than manual application (or a do-while kind of loop).
EDIT: I should point out that as soon as I reduce the pure function to one parameter (P - the remaining principal, which is the only thing that changes), the `Next function works.
I am trying to find out how to Nest
functions of more than one variable
Nest
see alsoNestList
, and while you're at itFold
andFoldList
as well. If these answer your question I think this can be closed either as a duplicate or easily found in the documentation. If not please indicate how your needs differ. $\endgroup$RSolve
, which may be able to derive a closed form solution for you. $\endgroup$