#PROBLEM 3: USING BISECTION SEARCH TO MAKE THE PROGRAM FASTER (25 points possible) #You'll notice that in Problem 2, your monthly payment had to be a multiple of $10. Why did we make it that way? #You can try running your code locally so that the payment can be any dollar and cent amount (in other words, the monthly #payment is a multiple of $0.01). Does your code still work? It should, but you may notice that your code runs more slowly, #especially in cases with very large balances and interest rates. (Note: when your code is running on our servers, there are #limits on the amount of computing time each submission is allowed, so your observations from running this experiment on the #grading system might be limited to an error message complaining about too much time taken.) #Well then, how can we calculate a more accurate fixed monthly payment than we did in Problem 2 without running into the #problem of slow code? We can make this program run faster using a technique introduced in lecture - bisection search! #The following variables contain values as described below: balance =28774.23 annualInterestRate = 0.2 #The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: monthlyIntRate = annualInterestRate/12.0 low = balance/12.0 high = (balance *(1 + monthlyIntRate)**12) / 12.0 lowestPayment = (low+high)/2 finding = True def payment(balance,annualInterestRate,lowestPayment): month = 1 while month <= 12: #Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) balance -= lowestPayment #Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) balance += (monthlyIntRate*balance) month +=1 return balance while finding: x=payment(balance,annualInterestRate,lowestPayment) if round(x) < 0: high = lowestPayment lowestPayment = (high + low)/2 elif round(x) > 0: low = lowestPayment lowestPayment = (high + low)/2 elif round(x) == 0: finding = False print 'Lowest Payment:',round(lowestPayment,2)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question