Python Bisection search overshoots target - python

I have to create a code to find the exact payment, to the cent, needed to pay off a loan in 12 months using bisection. The code I created for this works but it overshoots it's target. The loan will be payed off within the 12 months but after making 12 payments the final balance should be around 0. However it is a way bigger negative number.
The code I am using is:
StartBalance = float(raw_input('Credit Balance in $: '))
AnnualRate = float(raw_input('Annual interest rate in decimals: '))
MonthlyRate = AnnualRate / 12.0
MinPaymentLow = StartBalance / 12.0
MinPaymentHigh = (StartBalance*(1+MonthlyRate)**12.0)/12.0
cent = 0.01
Payment = (MinPaymentHigh+MinPaymentLow)/2.0
while (Payment*12-StartBalance) >= cent:
for month in range(0, 12):
Balance = (StartBalance-Payment)/10*(1+MonthlyRate)
if Balance < 0:
MinPaymentLow = Payment
elif Balance > 0:
MinPaymentHigh = Payment
Payment = (MinPaymentHigh + MinPaymentLow)/ 2.0
print 'RESULT'
print 'Number of months needed: 12'
print 'Montly pay: $', round(Balance,2)

It looks like these lines:
for month in range(0, 12):
Balance = (StartBalance-Payment)/10*(1+MonthlyRate)
Should be:
Balance = StartBalance
for month in range(0, 12):
Balance = (Balance-Payment) * (1 + MonthlyRate)
Or something similar, depending on how you want to calculate interest, and whether you consider payments occurring at the start or end of the month.

Your code seemed to work fine for me, but if you're getting results that are "way off" it's probably because you're using the float datatype. Float is untrustable, because it rounds on every operation. Given enough iterations and you've rounded off a lot of money. Try using decimal instead. This module keeps track of decimals as indexed integer values.

Related

Unsure why output is 0. Trying to count months to pay downpayment

print("Please enter you starting annual salary: ")
annual_salary = float(input())
monthly_salary = annual_salary/12
print("Please enter your portion of salary to be saved: ")
portion_saved = float(input())
print ("Please enter the cost of your dream home: ")
total_cost = float(input())
current_savings = 0
r = 0.04/12
n = 0
portion_down_payment = total_cost*int(.25)
if current_savings < portion_down_payment:
monthly_savings = monthly_salary*portion_saved
interest = monthly_savings*r
current_savings = current_savings + monthly_savings + interest
n =+ 1
else:
print(n)
The above is my code. I keep getting output = 0 but unsure why.
This the problem statement, I am a HS student attempting OCW coursework.
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). 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)
Test Case 1
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
You have n =+ 1 but I think you mean n += 1
Also int(.25) evaluates to 0, I think you want int(total_cost*.25). As your code is, the if statement will always evaluate to False because current_savings == 0 and portion_down_payment == 0
More generally, when your code isn't working as expected, you should put in either print() or assert statements to narrow down where your code is deviating from what you expect. For example, before the if statement you could have it print the two values you are comparing.

Modification of Future Value

For this you have to add the annual contribution to the beginning of the year (the principal total) before computing interest for that year.
I am stuck and need help. This is what I have so far:
def main():
print("Future Value Program - Version 2")
print()
principal = eval(input("Enter Initial Principal:"))
contribution = eval(input("Enter Annual Contribution:"))
apr = eval(input("Enter Annual Percentage Rate (decimal):"))
yrs = eval(input("Enter Number of Years:"))
for k in range (1, yrs):
principal= principal * (1 + apr)
print()
print( yrs,) ": Amount $", int(principal * 100 + 0.5)/100)
main()
It is supposed to look like this:
Future Value Program - Version 2
Enter Initial Principal: 1000.00
Enter Annual Contribution: 100.00
Enter Annual Percentage Rate (decimal): 0.034
Enter Number of Years: 5
Year 1: Amount $ 1137.4
Year 2: Amount $ 1279.47
Year 3: Amount $ 1426.37
Year 4: Amount $ 1578.27
Year 5: Amount $ 1735.33
The value in 5 years is $ 1735.33
Here's a working example that produces the expected output:
def main():
print("Future Value Program - Version 2")
print()
principal = float(input("Enter Initial Principal: "))
contribution = float(input("Enter Annual Contribution: "))
apr = float(input("Enter Annual Percentage Rate (decimal): "))
yrs = int(input("Enter Number of Years: "))
print()
for yr in range(1, yrs + 1):
principal += contribution
principal = int(((principal * (1 + apr)) * 100) + 0.5) / 100
print("Year {0}: Amount $ {1}".format(yr, principal))
print()
print("The value in {0} years is $ {1}".format(yrs, principal))
if __name__ == '__main__':
main()
There were a few problems with the example in the question:
A syntax error in the print statement on line 12. Calling print with parens means all the arguments should be enclosed inside the parens. Python interpreted the errant paren as the end of arguments passed to print.
As noted by others, you shouldn't call eval on the inputs. Call float for floating point numbers, int for integers.
The range operator had an off by one error.
As noted by others, print is called outside of the loop, so intermediate states of the principal aren't output.
As far as basic maths, it seems as though adding the contribution was left out.
As per the expected output, the final print was missing.

Python CD annual precentage

I am doing this assignment. when i input the number of months it is one printing one month. rather it be 5 months or 17 months its only printing 1 months total.
https://drive.google.com/file/d/0B_K2RFTege5uZ2M5cWFuaGVvMzA/view?usp=sharing
Here is what i have so far what am i over looking thank you
calc = input('Enter y or n to calculate your CDs worth?')
month= int(input('Select your number of months'))
while calc == 'y':
while month > 0:
amount = int(input('Please enter the amount:'))
percent= float(input('Please enter the annual percentage:'))
calc= amount + amount* percent/ 1200
print(calc)
You would want to use a for loop rather than while in this sense since you are doing a set amount of operations. You also were reusing calc and assigning calc to from a String to a float, generally a bad idea. The main problem is the formula builds upon the previously calculated number, it starts off with the initial amount entered, 10000 + 10000 * 5.75 / 1200 = 10047.91, then uses 10047.91 in the next calculation, instead of 10000, you never were reusing the previously calculated number, so you weren't getting the right answer. This should do it:
calc = input('Enter y or n to calculate your CDs worth?')
if calc == 'y':
month = int(input('Select your number of months'))
amount = int(input('Please enter the amount:'))
percent = float(input('Please enter the annual percentage:'))
for i in range(month):
if i == 0:
calcAmount = amount + ((amount * percent) / 1200)
else:
calcAmount = calcAmount + ((calcAmount * percent) / 1200)
print calcAmount

Fixed payment is returned as 0. Why? What corrections to make?

Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example:
Lowest Payment: 180
Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below:
Monthly interest rate = (Annual interest rate) / 12.0
Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
Here is my code. I do not know where I'm going wrong:
balance = float(raw_input('enter the outsanding balance on your card'))
annualInterestRate = float(raw_input('enter the anual interest rate as a decimal'))
month = 0
checkBalance = balance
monthlyFixedPayment = 0
while checkBalance <= 0:
checkBalance = balance
monthlyFixedPayment += 10
while month <= 11:
monthlyInterestRate = annualInterestRate/12.0
monthlyUnpaidBalance = checkBalance - monthlyFixedPayment
checkBalance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)
print('lowest payment:' + str(monthlyFixedPayment))
I think this is the program you are looking for:
balance = 500
annualInterestRate = .5
checkBalance = balance
monthlyFixedPayment = 10
count = 0
while checkBalance > 0:
month = 0
while month <= 11 and checkBalance > 0:
count+=1
monthlyInterestRate = annualInterestRate/12.0
monthlyUnpaidBalance = checkBalance - monthlyFixedPayment
checkBalance = monthlyUnpaidBalance - (monthlyInterestRate * monthlyUnpaidBalance)
print "\t"+str(checkBalance)
month+=1
print checkBalance
print "lowest amount: "
print count*monthlyFixedPayment+checkBalance
I have left the print statements, so that you can see what is going on in each iteration.
Some problems i noticed in your code:
1) you were doing a monthlyFixedPayment += 10 that was changing the fixed payemnt. you are not supposed to change the fixed payment according to your problem definition.
2) you were doing a checkBalance = balance in each iteration of outer while loop. This was causing the calculated value to be resetted.
3) I have introduced a count variable to check how many times these decuctions were happening, as month was getting reset in each iteration.
while checkBalance <= 0: to while checkBalance >= 0:
Also, you need to increment month in the while month <= 11: loop.
You are going at it the hard way; there is an analytic solution for fixed_payment:
from math import ceil
def find_fixed_monthly_payment(balance, months, yearly_rate):
i = 1. + yearly_rate / 12.
im = i ** months
return balance * (im * (1. - i)) / (i * (1. - im))
def find_final_balance(balance, months, yearly_rate, fixed_payment):
i = 1. + yearly_rate / 12.
for _ in range(months):
# make payment
balance -= fixed_payment
# add interest
balance *= i
return balance
def get_float(prompt):
while True:
try:
return float(raw_input(prompt))
except ValueError:
# input could not be cast to float; try again
pass
def main():
balance = get_float("Please enter starting balance: ")
annual_rate = get_float("Annual interest rate (in percent): ") / 100.
fixed_payment = find_fixed_monthly_payment(balance, 12, annual_rate)
# round up to the nearest $10
fixed_payment = ceil(fixed_payment / 10.) * 10.
# double-check value of fixed_payment:
assert find_final_balance(balance, 12, annual_rate, fixed_payment ) <= 0., "fixed_payment is too low!"
assert find_final_balance(balance, 12, annual_rate, fixed_payment - 10.) > 0., "fixed_payment is too high!"
print("Lowest payment: ${:0.2f}".format(fixed_payment))
if __name__ == "__main__":
main()

Beginner Python exercise

I'm having trouble solving problem 2 from this page
Here
Here's my code:
#Problem set 1 b
out_bal = float(raw_input("Enter the outstanding balance on your credit card: "))
ann_interest = float(raw_input("Enter the annual interest rate as a decimal: "))
min_pmnt = 10
months = 1
prev_bal = out_bal
month_interest = ann_interest / 12.0
updated_bal = prev_bal * (1 + month_interest) - min_pmnt
while out_bal > 0:
for i in range(1,13):
out_bal = updated_bal
prev_bal = out_bal
months += 1
if out_bal <= 0:
break
else:
min_pmnt = min_pmnt + 10
months = 0
print out_bal
print "RESULT"
print "Monthly payment to pay off debt in 1 year: $", min_pmnt
print "Number of months needed: ", months
print "Balance: ", round(out_bal, 2)
I want to take 1200 and .18 for the first two inputs, respectively. However when I do this the program gets caught in my while loop and keeps printing 1208.00.
When I read the code to myself it seems like it should be working. But I think I'm not using the prev_bal variable correctly.
Also, it's performing the math the way I expect it to the first time it goes through the loop but then it seems like it's not adding 10 to min_pmnt and going through the loop again. It seems like it's just using 10 over and over.
How can I write this so it does actually add 10 and perform the loop again?
Thanks!
Your problem is that updated_bal isn't changing, yet you are setting out_bal to it each time you iterate, and then conditioning the loop on out_bal becoming reduced in value.
It looks to me like you are thinking that updated_bal changes on each loop iteration, based on its component parts. In order for that to work, you would need to instead use a function that calculates an updated balance each time around.

Categories