Work the Shell - Calculating Mortgage Rates
I used to work at Hewlett-Packard years ago (pre-Fiorina), and back then, one of our mantras was the “next bench syndrome”. You've probably heard of it: build things that you'd want to use. It's logical, and although often we aren't in that position, it's certainly the basis of many great hobby projects.
It's also the basis for this month's script project. As I write this column, the house I'm in is “under contract” to sell, and I have an offer in on a new place that's four miles away and lots bigger—more room for those servers, natch! You can't talk about buying a house, townhouse, condo or even apartment without talking about getting a loan from a friendly bank—at least, I don't have a spare half-mil burning a hole in my bank account!
When looking at houses, the key question always becomes “how much can I afford?”, and the variables that go into that equation are the amount of your down payment, the duration of the loan, the interest rate the bank is going to charge you and, of course, the base cost of the house you're considering.
There are more factors, including mortgage insurance if your down payment is less than 20% of the house price, taxes, points, closing costs and so on, but we're going to skip those because, well, they're bafflingly complex and way beyond the scope of this column—or magazine!
The basic calculation we need is rather complicated:
M = P [ i((1 + i)**n) ] / [ ((1 + i)**n) - 1]
In this calculation, M is the required monthly payment; n is the total number of monthly payments (on a 30-year mortgage, it's 30 * 12); P is the principal/amount of the loan itself, and i is the annual interest rate divided by 12 for a monthly interest rate.
So, let's say the current mortgage rate at your bank is 5.00% APR. That means i would be 5/12 = 0.42.
How does this convert into a shell script? Surprisingly, it's not too difficult to duplicate the formula if we tap the power of bc and do some intermediate calculations to make it easy to work with and ensure we've no mathematical errors.
The real trick is to make sure we are getting sufficient precision from the calculations, so we don't see egregious rounding errors, which multiply dramatically with this sort of formula.
To accomplish that, each time I call bc, I'll specify scale=6, which gives six post-decimal digits of precision. That means the 5/12 calculation above would be calculated more correctly as 0.426667.
The script starts by having a default duration of 30 years and a default interest rate of 4.85% APR, which is, at the time of this writing, a typical rate. Here's how I encode those:
dfltduration=30 # 30 year loan dfltint=4.85 # 4.85% APR is the default pmts=$(( $dfltduration * 12 ))
The script will expect two variables to be specified, although only one is required, principal and actual interest rate:
princ=$1 ; int=$2
That's a lazy way to assign those variables because, as should be immediately obvious, if they're not specified, we now have empty variables. My general approach to writing scripts is always to start with the core functionality, then graft on all the error tests and friendly errors. I bet you're the same.
This gets a bit tricky because we need to normalize percentages; otherwise, users will assume they're entering 5.25%, and the formula will calculate payments based on 525% (for example, 5.25 not 0.0525). I wrap it all up in one:
if [ -z "$int" ] ; then int="$(echo "scale=6; $dfltint / (100*12)" | bc -q)" else int="$(echo "scale=6; $int / (100*12)" | bc -q)" fi
That's the setup. Now the calculations can be configured as a variable prior to pushing it at bc, for ease of debugging:
calculation="$princ * ( $int * ((1 + $int) ^ $pmts )) / ↪( ((1 + $int) ^ $pmts) - 1)"
Before I go further, let's look at an example. Say I want a loan for a $300,000 house at 4.85% APR for a typical 30-year mortgage. Here's what the above formula actually looks like:
300000 * ( .004041 * ((1 + .004041) ^ 360 )) / ( ((1 + .004041) ^ 360) - 1)
Hopefully, all of those numbers make sense given my explanation so far.
The last step is simply to run the calculation by feeding it to bc:
payment="$(echo "scale=6; $calculation" | bc -q)"
This still is not quite right because the resultant value ends up looking like 1582.859358 / month, which is a bit confusing when we're used to two digits after the decimal point!
I could tweak that within bc, but changing the scale has the bad side effect of reducing the accuracy of all calculations. Instead, here's a simple tweak that I've shown before and like:
payment="$(echo "$payment" | rev | cut -c5- | rev)"
I'll let you figure out what that does.
Finally, the output:
echo Payments: \$$payment/month for $pmts payments to pay off $princ
Let's run a few calculations given this functional script:
$ mortgage-calc.sh 300000 Payments: $1582.85/month for 360 payments to pay off 300000 $ mortgage-calc.sh 300000 7 Payments: $1995.78/month for 360 payments to pay off 300000 $ mortgage-calc.sh 500000 Payments: $2638.09/month for 360 payments to pay off 500000
You can see that even a few points of interest (7% instead of 4.85% makes a dramatic difference in those monthly payments).
Now, to find a really nice house to buy!
Dave Taylor has been hacking shell scripts for a really long time, 30 years. He's the author of the popular Wicked Cool Shell Scripts and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
- RSS Feeds
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- Dynamic DNS—an Object Lesson in Problem Solving
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Download the Free Red Hat White Paper "Using an Open Source Framework to Catch the Bad Guy"
- Tech Tip: Really Simple HTTP Server with Python
- Roll your own dynamic dns
3 hours 15 min ago - Please correct the URL for Salt Stack's web site
6 hours 26 min ago - Android is Linux -- why no better inter-operation
8 hours 41 min ago - Connecting Android device to desktop Linux via USB
9 hours 10 min ago - Find new cell phone and tablet pc
10 hours 8 min ago - Epistle
11 hours 37 min ago - Automatically updating Guest Additions
12 hours 45 min ago - I like your topic on android
13 hours 32 min ago - This is the easiest tutorial
20 hours 8 min ago - Ahh, the Koolaid.
1 day 1 hour ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
How to Make Red hat Cluster to run Photoshop on main Node
I want to make a 15 node cluster with one node as the main node for graphic work, I want to use Adobe Photoshop CS5, is it possible to use all the systems on the cluster to make the Main node more faster, any help with this project would be very helpful, also im not sure what OS would be best fit for this job, Windows, Red Hat, or Ubuntu. Also looking for team members for start up company.. alimsabree@gmail.com ....Thanks Alim Sabree