Created
February 22, 2017 09:16
-
-
Save peter-jung/c0535c1744a409cdecdb79a45a390250 to your computer and use it in GitHub Desktop.
Solving an Annuity Loan for any of the parameters with Newton Raphson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
calculate annuities | |
''' | |
''' | |
annuities kernel | |
s: total amount | |
r: nominal annual rate | |
t: duration/years | |
a: monthly payment | |
''' | |
def annuities(s,r,t,a): | |
return (1+r)**t * (a-s*((1+r)**(1./12)-1)) - a | |
''' | |
newton raphson | |
kernel: kernel (function with n numeric arguments) | |
params: starting parameters for the kernel | |
idx: index of the parameter to be varied | |
err: desired accuracy | |
assuming differentiability of kernel in all | |
parameters in the vicinity of the starting values. | |
''' | |
def newtonraphson(kernel, params, idx, err=1e-6): | |
dx = 1e-2*err | |
p0 = params | |
p1 = p0[:] | |
for x in range(50): | |
p1[idx] = p0[idx] + dx | |
f0 = kernel(*p0) | |
df = (kernel(*p1) - f0)/dx | |
xi = f0/df | |
p0[idx] -= xi | |
print kernel(*p0) | |
if abs(xi) < err * abs(p0[idx]): | |
return p0 | |
print 'WARNING: Newton Raphson did not converge.' | |
return None | |
# solve for the rate. | |
print newtonraphson(annuities, [10000,0.039,10,100], 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment