Posted on April 3, 2006 at 11:18 am

Lately I’ve been assigning myself these little programming challenges. I allow myself no more than 2 hours to work on them, but I rarely spend longer than 30-60 minutes on them. These are not usually things I intend to take any further, rather they are just fun projects to stretch my mind a little.

My little challenge last night was to come up with the smallest program that calculates an amortization schedule. It could probably be a little smaller, but here it is:

def amortize(p, i, m)
  Array.new(m){|n|p=(b=p-(cp=(mp=p*((mi=i/(1200))/(1-(1+mi)**-m)))-(ci=p*mi)));[n+1,b,ci,cp]}
end

Just call amortize with the principle, interest, and number of payments and you get back an array of month, balance, current month’s interest, and current month’s principle. Calling it like so will produce comma-delimited output that you can open in Excel or whatever.

puts "month,balance,interest,principle"
amortize(200000, 7.5, 360).each{|p|printf("%i, %1.2f, %1.2f, %1.2f\n",p[0],p[1],p[2],p[3])}

Partial output:

month,balance,interest,principle
1, 199851.57, 1250.00, 148.43
2, 199703.25, 1249.07, 148.32
3, 199555.04, 1248.15, 148.21
4, 199406.94, 1247.22, 148.10
5, 199258.96, 1246.29, 147.99
6, 199111.08, 1245.37, 147.88
7, 198963.31, 1244.44, 147.77
8, 198815.65, 1243.52, 147.66
9, 198668.10, 1242.60, 147.55
10, 198520.66, 1241.68, 147.44
11, 198373.33, 1240.75, 147.33
12, 198226.10, 1239.83, 147.22
One Comment:
Posted on April 15, 2006 at 11:44 pm by infused.org » Tinier

[...] I think this is a small as the amortization program can get without losing functionality. If you can make it smaller, please let me know about it! def a(p,i,m)j=i/1200;Array.new(m){|n|p=(b=p-k=p*(j/(1-(1+j)**-m))-q=p*j);[n+1,b,q,k]}end [...]

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>