View Full Version : Calculating Program, Need Help Quickly

10-09-2008, 01:41 AM
Hey all, I was trying to create a program that calculates mortgage, it's entry-based, and I'm having a hard time doing anything past what my professor has shown us. It's all very confusing and I'd love help with it since I have a test on this stuff soon and need to see how it's done properly. Right now, I'm sort of floundering (didn't know the class was a javascript focus class :confused:).

Here's the assignment he linked us:


“If I borrow X dollars for Y years at Z percent interest, what will my monthly payments be?”

When you take out a loan for a car or a house, you specify three parameters: the amount of the loan (how much do you want to borrow), the period of the loan (how many years do you want to take to repay), and the annual interest rate. From these three numbers, the monthly payment can be calculated. There are several ways to calculate the monthly payment. One way is a direct solution to an algebraic equation; this is the practical way to do it, but it is NOT what we will be doing.

In this assignment you will do it by brute force using a simple mathematical technique called bisection. We are using a brute force method in order to practice writing loops, functions, and function calls. We will essentially be taking a guess at what the monthly payment is, and then computing out how the amount we borrowed drops towards zero month by month as we pay. If we hit zero after the full number of payments, we have guessed the payment correctly; if we do not hit zero, we guessed badly and need to try another guess. The cleverness in bisection is in how we make the guesses.

Basics of Bisection

If you are trying to guess the answer to a math question and you have some way of knowing if your guess is too high or too low, then there’s an easy and efficient way to get the answer (or very close to it). You start by determining two extremes: one that is clearly too low (which we’ll call min) and one that is clearly too high (which we’ll call max). You then know that the right answer is trapped between min and max. You then guess at the midpoint between the extremes: mid = (min + max)/2. If this is too high, then you know the correct answer must lie in the range min…mid. If your guess is too low, then you know the answer is in the range mid…max. We’ve now cut the possible range in half. We continue this way successively halving the possible range until we get close enough.

For example, on the quiz show The Price is Right, you are asked to guess the price of a fabulous prize: a big screen television. You make a guess and then Bob Barker tells you if your guess is too high or too low. You start with min of 0 (the prize clearly costs more than nothing) and a max of, say, $10,000 – clearly more than the TV is worth. You first guess is (min+max)/2 or $5000. Bob says that’s too high, so now you know that the price is between 0 and $5000. So your next guess is (0+5000)/2 or $2500. Bob says that is too low. So now you know the price is in $2500…$5000. Your next guess is (2500+5000)/2 or $3750. You continue this way until you get the correct price. Because you are halving the size of the possible range at each step, you arrive at the correct price very quickly. For example, starting with min of $0 and max of $10,000, you can get the correct price (within one dollar) in fourteen guesses or fewer .

Determining monthly payment

If you borrow $10,000 at 6% annual interest, here’s how the process goes. First, we have to convert annual interest to monthly fraction by dividing by 1200. (You are dividing annual percentage by 100 to get the annual fraction and then by 12 to get the monthly fraction.) So the monthly rate is 0.5%; the monthly fraction is 0.005. Then each month, the balance you owe is increased because of the interest and decreased by your payment.

new balance =
old_balance + ( old_balance * monthly_int_fraction ) – payment

The perfect monthly payment is the one that will reduce your balance to zero (or, in this case, within a penny of zero) after the specified number of payments.

Determining the initial min and max

If you borrow $10,000 for 10 years at 6% interest, your monthly payment is clearly more than $0 and clearly less than $10,000. So these will be our starting points. Our first guess will be (0+10000)/2 or 5000. Paying 5000 per month for 10 years will result in a negative balance (we paid too much), so our next guess will be (0+5000)/2 or 2500. This is also too big. The process continues until we discover, after about 28 steps that $111.02 is the perfect monthly payment. The perfect monthly payment is the one that has a final balance (the amount left to pay after the final payment) between $0.00 and $0.01 (that is, between zero and one cent). The loan will cost us a total of $111.02*120 = $13,322.40 (the monthly payment multiplied times the number of months.)


Your job is to build a monthly payment calculator. The user will enter a loan amount, a period (in years) and a rate (as a percent, possibly with fractional part), press a button, and the calculator will display the monthly payment, the total amount paid, and the number of steps required to reach the solution.

Your page should contain the following fields and buttons (in this order):
• Appropriately labeled text boxes for the loan amount, loan period, and rate.
• A “Calculate payment” button
• Text box for the perfect monthly payment

In addition to producing the monthly payment in the text box, your program should use “alert” to tell the user the total paid over the life of the loan, and the number of steps needed to guess the payment (both in one alert box). As before, the HTML should give proper documentation for your program as well.

Error checking

Your program should detect and handle the following errors. An alert message is sufficient to inform the user:

1. A loan amount that is zero or less (no one borrows zero).
2. A loan amount that is not a number (e.g. “Hello”).
3. A loan period that is not an integer , is less than one, or not a number.
4. A rate that is less than zero or not a number

Writing functions

In this program you will write a main function (called when you click the button) and at least one helper function. There are several obvious candidates for helper functions. One is a function that takes the current payment guess and returns the final balance once that payment has been paid for all the months of the loan. Another is a function that will generate a new guess at a monthly payment, given the current interval.

Rounding dollar amounts

You should display both the perfect monthly payment and the total paid with two decimal places (see monthly payment above). You can easily round a value to 2 decimal places by multiplying by 100, rounding using Math.round, then dividing by 100. If the ones digit happens to be zero, you will get one decimal place rather than 2 (see total payment above). Don’t worry about this.

Here's what I've copied so far from class, it's basically just a skeleton that needs to have a lot of function added to calculate properly the numbers he wants:

<title>Mortgage Calculator</title><script type=text/javascript>function calcMortgage (amountText, yearsText, rateText ) {

// params are passed in as text...
// so convert them to numbers var amount = Number(amountText);
var years = Number(yearsText);
var rate = Number(rateText);
var payment = 0; // initial value
var guessPay = 0;
var finalBalance = 0;
var lowEnd = 0;
var highEnd = amount;
// while we are not done {
// loop until we get the guess right // make a guess
guessPay = makeGuess(highEnd,lowEnd); // check to see if it is ok
finalBalance = endBalance(amount,years,rate,guessPay);

// check the finalBalance to see if it is
if (finalBalance is near 0) // between -0.01 and 0.01
then get out of the guessing loop
if (finalBalance is negative)
then negative: guess too big, move highEnd down
means give highEnd a new value... the midpoint
if (finalBalance is positive)
then guess too low, move lowEnd up
means give lowEnd a new value... the midpoint
*/ // } end while loop return guessPay; // send the appropriate value for your code
}function endBalance (amount, years, rate, payment) {
// this function will return the balance that remains
// after paying back this loan for all these years// you will need to create a loop that executes once
// for each month in the loan// each month you take the amount owed the bank,
// add in the interest you now owe for the month on that balance,
// and substract the payment you are making
// this gives a new balance for the next month
// at the moment we are "faking" this function by simply returning a 0
// for testing the main code we can also try returning a positive amount
// and try returning a negative amount
return 0;}function makeGuess ( high, low ) {
// since we are using bisection, our guess will be
// whatever the midpoint is between high and low
var mid;
mid = (high+low)/2 ;
return mid;
}</script></head><body><h1>Mortgage calculator: Forms and text field input/output</h1><br><form name="dForm"><input type=text name="amount" >
Loan amount? (in dollars)
<input type=text name="years" >
Loan period (in years)?
<input type=text name="rate" >
Interest rate (percentage)?
<input type=button value="calculate payment"
onclick = "document.dForm.payment.value =
calcMortgage (
); "
<input type=text name="payment"> Monthly payment (in dollars)</form>
This program does input via an HTML form, with text fields on the form.

Sadly, I have no idea how to fix this setup since I'm not exactly aiming to be a Javascript programmer, and this is a bit more complicated than I expected from an introductory class. Any help would be appreciated, since a well-done program will let me review the way it's correctly done for the upcoming test we're having.

10-09-2008, 02:19 AM
Meant to say as well, any help would be greatly appreciated, thanks in advance.