Reputation: 201
I'm coding a 'Future Value of Annuity Due' calculator, that allows a user to find an unknown in the formula. The formula is fv = (1 + i) * pp * ((1 + i)**n - 1) / i
; where fv
is future value, pp
is periodic payment, i
is interest rate and n
is number of periods. As an example, assuming pp = 100
, i = .2735 (27.35%)
, and n = 11
, one obtains fv = 6187.56
. Without knowing i
, I can interpolate the rate to be say 25%, and would like to use Newton-Raphson iteration to get a more exact answer. However, my code below is off, as it's diverging (it seems to work for small values of i
, i.e. 5%).
fv = 11807.795
pp = 1000
n = 10
i = .03
def newton_raphson_method(fv,pp,i,n):
newton_raphson_i = i
for num in range(1,20):
newton_raphson_i = i - (1+i)*(pp*(1+i)**n - pp-fv*i) / ((n +1)*pp*(1+i)**n - fv)
i = newton_raphson_i
print(i)
i = round(i,11)
print('')
print ('The newton interest rate is ' + str("%.9f" % (i * 100)) + '%')
print('')
Upvotes: 1
Views: 373
Reputation: 201
For the Future Value of an Annuity Due Formula, the above formulas were both missing the periodic payment (pp) at the end. The below works with positive and negative interest rates.
newton_raphson_i = i - ((1+i)*pp*((1+i)**n - 1) - fv*i) / ((n+1)*pp*(1+i)**n - fv - pp)
Upvotes: 0
Reputation: 2461
It looks like you are missing a (well-placed) parentheses pair in your implementation of the function value. The 9th line of your script should probably read
newton_raphson_i = i - ((1+i)*(pp*(1+i)**n - pp) - fv*i) / ((n +1)*pp*(1+i)**n - fv)
or, equivalently,
newton_raphson_i = i - ((1+i)*pp*((1+i)**n - 1) - fv*i) / ((n +1)*pp*(1+i)**n - fv)
More generally, I would advise you to implement future_value(pp, i, n)
as a function in your script and test it. You could then also implement the function of which you want to find the root, which is (future_value - fv) * i
, as well as its derivative, test them, and use these tested functions in the Newton-Raphson method.
By the way, the Newton-Raphson method itself is already implemented in the scipy package (see here), as well as other root-finding methods.
Upvotes: 2