Mortgage calculator math error - python

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.

Related

Working on a Python project for a salesman. Getting "cannot assign to operator" error

I'm working on a project in Python for a salesman. The project takes the pay from hours worked for the week and the percentage from commission of sales per week and adds them together to give the total weekly pay of the salesman. The problem I'm running into is dividing the sales amount with the percent they receive from each sale. The error is "cannot assign to operator"
#Prompt user for the number of hours worked that week
hours_worked = int(input("How many hours did you work this week? \n"))
#Define hourly wage
per_hour = 30
#Multiply the hourly wage and hours worked that week
total_hours_pay = hours_worked * per_hour
#Prompt user for the number of sales made that week
sales_made = int(input("How many sales did you make this week? \n"))
#Amount of each sale
sales = 250
#Determine commission of each sale
25 / sales = commission
#Multiply the commission times the amount of sales made to retrieve amount of total commission pay
total_sales_pay = sales_made * commission
#Add total commission pay from sales with the total hours pay to get the weekly total
total_week_pay = total_sales_pay + total_hours_pay
print(total_week_pay)
You wrote:
25 / sales = commission
But when assigning something to a variable, you need to put the variable at the start of the statement.
Try
commission = 25 / sales
25 / sales = commission this line throws the error. I think it should be comission = 25 / sales. You try to assign the value of comission to the result of 25 / sales which does not work.

Building a calculator with set of input values and fixed interest rate

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))

How do I update elements in a list, in a for loop

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.

program for loan amount and loan period

Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 3% to 5%, with an increment of 1/8. The formula of calculating the monthly payment and total payment are as follows:
I need help with the increment of 1/8. I've thought of a for loop but Python does not allow floats. I researched a bit and found something called numpy, but I haven't learned that yet. Is there a way to do it?
Here is what I have so far:
monthlyPay = 0
total = 0
#Prompt the user to enter loan amount and loan period in years
loanAmount = float(input("Enter loan amount: $"))
years = int(input("Enter loan period in years: "))
#Display Table Header
print("Interest\tMonthly Pay\tTotal")
#Display Table Results
for yr in range(0,years):
interestRate = 3/(100*12)
#Calculate Monthly Payment
monthlyPay = loanAmount*interestRate/(1-(1/((1+interestRate)**(years*12))))
#Calculate Total Payment
total = monthlyPay * years * 12
print(format(interestRate, '.3f'), '%\t\t', format(monthlyPay, '.2f'),\
'\t\t', format(total, '.2f'), sep = '')
I'm not sure about how to calculate the values you need, but from what I understand is that you need the interest rate to be starting with 3% and increase every year with 1/8, which is 0.125, and stops at five. If this is the case, numPy would be helpful. You could make interestRate as an array like this:
import numpy as np
interestRate = np.arange(3, 3 + 0.125*years, 0.125).clip(max=5)
arange gives an array of your need and clip makes all the values above 5 be equal to 5.

What's wrong with this bisection search algorith?

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 :)

Categories