I've got an assignment for my MITx CS class and I am stuck on the following problem:
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
To recap the problem: we are searching for the smallest monthly
payment such that we can pay off the entire balance within a year.
What is a reasonable lower bound for this payment value? $0 is the
obvious anwer, but you can do better than that. If there was no
interest, the debt can be paid off by monthly payments of one-twelfth
of the original balance, so we must pay at least this much every
month. One-twelfth of the original balance is a good lower bound.
What is a good upper bound? Imagine that instead of paying monthly, we
paid off the entire balance at the end of the year. What we ultimately
pay must be greater than what we would've paid in monthly
installments, because the interest was compounded on the balance we
didn't pay off each month. So a good upper bound for the monthly
payment would be one-twelfth of the balance, after having its interest
compounded monthly for an entire year.
In short:
Monthly interest rate = (Annual interest rate) / 12.0 Monthly payment
lower bound = Balance / 12 Monthly payment upper bound = (Balance x (1
+ Monthly interest rate)12) / 12.0
Write a program that uses these bounds and bisection search (for more
info check out the Wikipedia page on bisection search) to find the
smallest monthly payment to the cent (no more multiples of $10) such
that we can pay off the debt within a year. Try it out with large
inputs, and notice how fast it is (try the same large inputs in your
solution to Problem 2 to compare!). Produce the same return value as
you did in Problem 2.
Now, this is what I've been able to come up with but it actually generates a wrong output. I have no idea what's going on wrong with this code:
#------------Defined variables---------------#
balance = 999999
annualInterestRate = 0.18
#------------Defined variables---------------#
monthlyInterestRate = annualInterestRate / 12.0
monthlyPaymentLower = balance / 12
monthlyPaymentUpper = (balance * (1 + monthlyInterestRate)**12) / 12.0
month = 1
total = 0
while (total < balance) and month < 13:
pay = (monthlyPaymentLower + monthlyPaymentUpper) / 2
total += pay
if total < balance:
monthlyPaymentLower = pay
elif total > balance:
monthlyPaymentHigher = pay
month += 1
if month == 13:
total = 0
month = 1
print 'Lowest Payment: ' + str(round(pay, 2))
Help?
Like always, not looking for a complete solution or the source code, just drop some hints on where I've gone wrong. (I always get negative votes. :/ )
In place
total += pay
you have to count balance for 12 mount like in problem 2
for month in range(12):
balance = balance - pay
balance = balance + monthlyInterest
than you have to compare balance with 0 and change monthlyPaymentLower or monthlyPaymentUpper
You have to compare monthlyPaymentLower to monthlyPaymentUpper to see if you can finish
if monthlyPaymentUpper - monthlyPaymentLower < 0.001 :
print "now I can finish searching"
Of course in this situation you will have to change more things in your code :)
Related
Write a program to calculate how many months it will take you to save up enough money for a down
payment. You will want your main variables to be floats, so you should cast user inputs to floats.
Your program should ask the user to enter the following variables:
The starting annual salary (annual_salary)
The portion of salary to be saved (portion_saved)
The cost of your dream home (total_cost)
Call the cost of your dream home total_cost.
Call the portion of the cost needed for a down payment portion_down_payment. For
simplicity, assume that portion_down_payment = 0.25 (25%).
Call the amount that you have saved thus far current_savings. You start with a current
savings of $0.
Assume that you invest your current savings wisely, with an annual return of r (in other words,
at the end of each month, you receive an additional current_savings*r/12 funds to put into
your savings – the 12 is because r is an annual rate). Assume that your investments earn a
return of r = 0.04 (4%).
Assume your annual salary is annual_salary.
Assume you are going to dedicate a certain amount of your salary each month to saving for
the down payment. Call that portion_saved. This variable should be in decimal form (i.e. 0.1
for 10%).
At the end of each month, your savings will be increased by the return on your investment,
plus a percentage of your monthly salary (annual salary / 12).
Expected case
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
Number of months: 183
My code text output
Number of months = 178
r = 0.04
current_savings = 0
potion_down_payment = 0.25
annual_salary = input('Enter your annual salary: ')
print(int(annual_salary))
monthly_salary = (int(annual_salary) / 12)
potion_saved = input('Enter the percent of your salary to save, as a decimal: ')
print(float(potion_saved))
cost_dream_home = input('Enter the cost of your dream home : ')
print(int(cost_dream_home))
invest_return = ((float(r) * float(annual_salary)) / 12)
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))
potion_saved_f = (float(monthly_salary) * float(potion_saved))
total_saved = (float(invest_return) + potion_saved_f)
number_of_months = (float(amount_to_save) // float(total_saved))
print(int(number_of_months))
I did this quickly, but you need a while loop, like:
months = 0
target = 250000
monthly_save = 1000.0
saved = 0.0
rate = .04
subtotal = 0.0
while subtotal < target:
saved += monthly_save
subtotal = (subtotal + monthly_save) * (1+(rate/12))
months += 1
print(months), print(int(subtotal))
OK, I have more time now. I think that you are just lucky that your code came out so close to the expected answer because your computations are off base. Unless you know of a better formula, you really need a loop in order to compute compound interest month by month. I have analyzed your method below.
invest_return = ((float(r) * float(annual_salary)) / 12) #.04*120000/12=400
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))#.25*1000000=250000
potion_saved_f = (float(monthly_salary) * float(potion_saved))#10000*.1=1000
total_saved = (float(invest_return) + potion_saved_f) #400+1000
number_of_months = (float(amount_to_save) // float(total_saved)) #250000//1400 = 178
print(int(number_of_months))
Assuming, I am running a weekly business and making profits every week at a constant interest rate of 5% per week and assuming my investment is recursive every week, I want to print all values for first 21 weeks. How do i right a code in python to achieve this?
Note: Investment is recursive, (i.e) every week my investment will be previous investment plus profit made in that week and also I am my rounding off the values and I have written this code but For loop I am struggling to write the logic , could some one help please. I have written the logic /calculations in excel - please check for expected results the excel screenshot.
maximum_number_of_weeks = int(input("maximum_number_of_weeks:"))
Initial_investment_Amount = int(input("Enter Initial Investment Amount Value ($) : "))
Interest_rate = float(input("Enter Interest Rate Value (%) : "))
Amount_Earned = Initial_investment_Amount * Interest_rate
Total_Amount_at_Disposal = Initial_investment_Amount + Amount_Earned
print("Total_Amount_at_Disposal ($) : ",Total_Amount_at_Disposal)
I suggest using a more simple approach:
Amount at disposal = Initial investment * (1 + interest rate) ^ (number of weeks)
maximum_number_of_weeks = int(input("maximum_number_of_weeks:"))
Initial_investment_Amount = int(input("Enter Initial Investment Amount Value ($) : "))
Interest_rate = float(input("Enter Interest Rate Value (%) : "))
for week in range(1, maximum_number_of_weeks + 1):
Total_Amount_at_Disposal = Initial_investment_Amount * (1 + Interest_rate/100) ** week
print("Total_Amount_at_Disposal ($) : ",round(Total_Amount_at_Disposal, 2))
I am trying to update values within a list, each iteration. I am not sure if this is the best approach. I know about string accumulators, int / float accumulators.
The values that I want to update is:
Minimum monthly payment
Principle Paid
and Remaining Balance
I want to update the values with the updated calculations that are done in the for loop.
More details on the problem.
Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.
Use raw_input() to ask for the following three floating point numbers:
1. the outstanding balance on the credit card
2. annual interest rate
3. minimum monthly payment rate
For each month, print the minimum monthly payment, remaining balance, principle paid in the
format shown in the test cases below. All numbers should be rounded to the nearest penny.
Finally, print the result, which should include the total amount paid that year and the remaining
balance.
[4800.0, 0.18, 0.02]
The output is like this:
Month: 1
Minimum payment: 96.0
Principle paid: 24.0
Remaining Balance: 4776.0
Month: 2
Month: 3
store_val_list = list()
outstanding_balance = float(raw_input('Enter the outstanding balance on your credit card: '))
store_val_list.append(outstanding_balance)
annual_interest_rate = float(raw_input('Enter the annual credit card interest rate as a decimal: '))
store_val_list.append(annual_interest_rate)
minimum_monthly_payment_rate = float(raw_input('Enter the minimum monthly payment rate as a decimal: '))
store_val_list.append(minimum_monthly_payment_rate)
print(store_val_list)
def pay_minimum(val_list):
calc_store_list = list()
for month in range(1, 13):
print('Month:', month)
if month == 1:
# 1. Minimum monthly payment (Minimum monthly payment rate X Balance)
min_payment = val_list[2] * val_list[0]
calc_store_list.append(min_payment)
print('Minimum payment:', min_payment)
# 1.5. Interest Paid (Annual interest rate / 12 months X Balance)
interest_paid = val_list[1] / 12 * val_list[0]
calc_store_list.append(interest_paid)
# print('Interest paid:', interest_paid)
# 2. Principle Paid (Minimum monthly payment - Interest Paid)
principle_paid = min_payment - interest_paid
calc_store_list.append(principle_paid)
print('Principle paid:', round(principle_paid))
# 3. Remaining Balance (Balance - Principal paid)
remaining_balance = val_list[0] - principle_paid
calc_store_list.append(remaining_balance)
print('Remaining Balance:', remaining_balance, '\n')
continue
I am using lists because it's easier to calculate the indexes of the list, than single variables.
This program runs fine, but the monthly payment it returns is totally off. For a principal amount of $400,000, interest rate of 11%, and a 10-year payment period, it returns the monthly payment of $44000.16. I googled the equation (algorithm?) for mortgage payments and put it in, not sure where I'm going wrong.
import locale
locale.setlocale(locale.LC_ALL, '')
def mortgage(principal, interest, n):
payment = principal*((interest*(1+interest)**n) / ((1+interest)**n-1))
return payment
principal = float(input("What is the amount of the loan you are taking out? $"))
interest = float(input("What is the interest rate? (%) ")) / 100
n = float(input("How many years? ")) * 12
print
print "Your monthly payment would be", locale.currency(mortgage(principal, interest, n))
The problem is in your interest rate used. You request the annual interest rate and never convert to a monthly interest rate.
From https://en.wikipedia.org/wiki/Mortgage_calculator#Monthly_payment_formula:
r - the monthly interest rate, expressed as a decimal, not a
percentage. Since the quoted yearly percentage rate is not a
compounded rate, the monthly percentage rate is simply the yearly
percentage rate divided by 12; dividing the monthly percentage rate by
100 gives r, the monthly rate expressed as a decimal.
I just tried this on my computer and dividing the interest rate by 12 calculated $5510/month which agrees with other mortgage calculators.
Here is my assignment:
Write a program to calculate the credit card balance after one year if
a person only pays the minimum monthly payment required by the credit
card company each month.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
For each month, calculate statements on the monthly payment and
remaining balance, and print to screen something of the format:
Month: 1
Minimum monthly payment: 96.0
Remaining balance: 4784.0
Finally, print out the total amount paid that year and the remaining
balance at the end of the year in the format:
It should not specify the values for the variables balance,
annualInterestRate, or monthlyPaymentRate - our test code will define
those values before testing your submission.
And here is the code I wrote:
def minpayment(balance, annualInterestRate, monthlyPaymentRate):
totalPaid = 0
month = 1
while month <= 12:
minPayment = monthlyPaymentRate * balance
balance -= minPayment
balance += (annualInterestRate/12.0)*balance
print 'Month:',month
print 'Minimum monthly payment:',round(minPayment,2)
print 'Remaining balance:',round(balance,2)
totalPaid += minPayment
month += 1
print 'Total paid:', round(totalPaid,2)
print 'Remaining balance:', round(balance,2)
Now, my question is, now that I've created the function, how do I call it?
You can call it like:
minpayment(10000, 0.1, 0.3)
or in general:
# You can modify the values below
balance = 10000
annualInterestRate = 0.1
monthlyPaymentRate = 0.3
minpayment(balance, annualInterestRate, monthlyPaymentRate)