Need help creating a compound interest calculator - python

I'm trying out making a compound interest calculator, managed to make one work but I'm now trying to add a part where the user inputs an amount they want to get their account to and then find the amount of years until they reach the goal. I want my output to be the amount of money in the account next to the amount of years it took to get there, plus all previous years outputs.I'm not really sure how to make the loop for this, any help?
Code so far:
percent = float(input("Interest %: "))
Interest = float((percent + 100) / 100)
money = float(input("How much did you originally have in the bank?"))
num_years = float(input("How many years has it been in the bank?"))
Total_money = float((Interest ** num_years) * money)
while Total_money < 1000000:
num_years += 1
print([Total_money, num_years])
if Total_money >= 1000000:
break

As it goes through the for loop, you need to change the amount of total_money:
percent = float(input("Interest %: "))
Interest = float((percent + 100) / 100)
money = float(input("How much did you originally have in the bank?"))
num_years = float(input("How many years has it been in the bank?"))
Total_money = float((Interest ** num_years) * money)
while Total_money < 1000000:
num_years += 1
Total_money *= Interest
print([Total_money, num_years])
if Total_money >= 1000000:
break
The line Total_money *= Interest is the same as:
Total_money = Total_money * interest

This should work.
percent = float(input("Interest %: "))
Interest = float((percent + 100) / 100)
money = float(input("How much did you originally have in the bank?"))
num_years = float(input("How many years has it been in the bank?"))
n=0
while n < num_years:
Total_money = float((Interest ** n) * money)
n += 1
print(round(Total_money, 2), n)
if Total_money >= 1000000:
break

Related

Why am I printing different values?

What's different between lines 16 and 17?
#user input
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
#static vars
portion_down_payment = total_cost*.25
monthly_salary = annual_salary/12
r = .04 #annual rate of return
months_to_save = 0
current_savings = 0
investment_return = current_savings * r / 12
while current_savings < portion_down_payment:
#current_savings += (current_savings * r / 12) + (portion_saved * monthly_salary) # Line 16
current_savings += (investment_return) + (portion_saved*monthly_salary) # Line 17
months_to_save += 1
print("Number of months: ", months_to_save)
I tried running it through pythontutor and the variation happens on step 15 of execution, but I can't quite figure out what's different.
When you use current_savings += investment_return, it adds the same amount of interest to current_savings each time through the loop. That interest is equal to current_savings * r / 12 calculated before you started the loop.
But when you use current_savings += (current_savings * r / 12), you recalculate the interest each time through the loop. So the interest is calculated based on the current value of current_savings, which gets bigger each time the loop runs.
In other words, the first one calculates simple interest, and the second one calculates compound interest.

Python: for loop with counter and scheduled increase in increase

Python Learner. Working on a recurring monthly deposit, interest problem. Except I am being asked to build in a raise after every 6th month in this hypothetical. I am reaching the goal amount in fewer months than I'm supposed to.
Currently using the % function along with += function
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment= total_cost*.25
savings = 0
for i in range(300):
savings = monthly_savings*(((1+.04/12)**i) - 1)/(.04/12)
if float(savings) >= down_payment:
break
if i % 6 == 0 :
monthly_salary += monthly_salary * .03
monthly_savings = monthly_salary * portion_saved
Thanks for the advice all. My code is getting clearer and I reached correct outputs! The problem was with how and when I was calculating interest. In the case of a static contribution I successfully used the formula for interest on a recurring deposit, here, the simpler move of calculating interest at each month was needed to work with the flow of the loop.
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment = total_cost*.25
savings = 0
month = 1
while savings < down_payment :
print(savings)
savings += monthly_savings
savings = savings * (1+(.04/12))
month += 1
if month % 6 == 0 :
monthly_salary += (monthly_salary * semi_annual_raise)
monthly_savings = (monthly_salary * portion_saved)
print("")
print("it will take " + str(month) + " months to meet your savings goal.")
Does something like this work for you? Typically, we want to use while loops over for loops when we don't know how many iterations the loop will ultimately need.
monthly_savings = 1.1 # saving 10% each month
monthly_salary = 5000
down_payment = 2500
interest = .02
savings = 0
months = 0
while savings < goal:
print(savings)
savings = (monthly_salary * monthly_savings) + (savings * interest)
months += 1
if months % 6 == 0 :
monthly_salary += monthly_salary * .03
print("Took " + str(months) + " to save enough")

Python bisection search not running and no error message. MIT edX

The problem is from the MIT edX Python Course 6.00.1 Problem Set 1 Part C. Here are the problems. Scroll to part C. I'm aware that there are countless questions asked about the edX course but none of them have really helped me. Whenever I run my bisection search code, nothing happens. No error message, nothing. Could someone help me find the issue in my code? Sorry if code is horribly inefficient, very new to python and programming.
#Python script for finding optimal saving rate of monthly salary in order to purchase 1M house in 36 months
salary = float(input("Enter salary: "))
total_cost = 1000000
salary_raise = 0.07 #semiannual raise rate
down = 0.25 * total_cost #downpayment
steps = 0
r = 0.04 #annual investments returns
low = 0 #low parameter for bisection search
high = 10000 #high parameter
current_savings = 0
while (current_savings <= (down - 100)) or (current_savings >= (down + 100)):
current_savings = 0
monthly_salary = salary/12
guess_raw = (high + low)/2
guess = guess_raw/10000.0
months = 0
steps += 1
while months < 36: #Finds end amount of money after 36 months based on guess
months += 1
multiple = months%6
monthly_savings = monthly_salary * guess
current_savings = current_savings + monthly_savings + current_savings*r/12
if multiple == 0:
monthly_salary += salary_raise * monthly_salary
if (current_savings >= (down - 100)) and (current_savings <= (down + 100)): #If the guess is close enough, print the rate and number of steps taken
print ("Best savings rate: ",guess)
print ("Steps in bisection search: ",steps)
break
elif current_savings < (down - 100): #If the guess is low, set the low bound to the guess
if guess == 9999:
print ("It is not possible to pay the down payment in three years.")
break
else:
low = guess
elif current_savings > (down + 100): #If the guess is high, set the high bound to the guess
high = guess

MIT 6.00.1x Set 2 P3 || Almost done and very close, but failed

First of all, I feel sorry. This is my first time to use this website so I don't know the rules.
I try to show my attempt but I don't know how to do this. I just rewrite the code directly day by day and don't have the saved drafts. I use many methods to work out, but I am fresh to coding and as you know, I keep on going the MIT CS introduction course.
For this problem, I would like to paste the original link but you need to sign in the website first. So I google it and find a Github page which contained the problem. enter link description here The problem set has three problems and I have solved first two of them.
It's about how to calculate credit cards latest monthly payment, and must use bisection search.
I have worked out once. However, I can only do one bisection search and then minus 0.01 step to step to approach the result. I show you my code before, here is the only old version which I saved.
balance = 999999
annualInterestRate = 0.18
monthly_interest_rate = annualInterestRate /12.0
lower_bound = balance / 12.0
upper_bound = (balance * (1 + monthly_interest_rate)**12) / 12.0
def calculate_balance(balance, fixed):
month = 0
while month < 12:
balance = (balance - fixed) * (monthly_interest_rate + 1)
month += 1
return balance
while True:
if calculate_balance(balance, lower_bound) > 0:
lower_bound = (lower_bound + upper_bound) / 2
else:
skipped_answer = lower_bound
break
#print(skipped_answer)
while True:
#print(balance, skipped_answer)
if calculate_balance(balance, skipped_answer) < 0:
skipped_answer -= 0.01
else:
break
print(round(skipped_answer+0.01, 2))
Anyway, this code works fine but the grader of edx says my code takes too much time.
So I think out of dual-directed bisection search and it takes me hours again. But this is the limit of my ability. I have no ideas. Here's the code below.
balance = 999999
annualInterestRate = 0.18
monthly_interest_rate = annualInterestRate /12.0
lower_bound = balance / 12.0
upper_bound = (balance * (1 + monthly_interest_rate)**12) / 12.0
def calculate_balance(balance, fixed):
month = 0
while month < 12:
balance = (balance - fixed) * (monthly_interest_rate + 1)
month += 1
balance
return balance
while True:
if abs(calculate_balance(balance, lower_bound) - balance) > 0.01:
if calculate_balance(balance, lower_bound) > 0:
mark = lower_bound
lower_bound = (lower_bound + upper_bound) / 2
elif calculate_balance(balance, lower_bound) < 0:
upper_bound = lower_bound
lower_bound = mark
else:
break
print(lower_bound)
I don't know why it will be an infinite loop. And how to solve it? What's wrong?
Thinking this for hours. I have tried all the methods that I know.
I worked out all of the exercises by myself and takes me too much time. This time, I know I must get help of experienced people. There must be something I don't know.
I don't knew is it now of any interest to see my code that works very fast. It is little
bit different then yours:
balance = 999999
annualInterestRate = 0.18
payment = 0
lower = balance/12.0
upper = (balance*(1+annualInterestRate/12)**12)/12.0
lbalance = 0
while payment < balance :
oldbalance = lbalance
lbalance = balance
payment = round((lower + upper)/2,3)
for i in range(0,12):
unpaidBalance = lbalance - payment
interest = unpaidBalance * annualInterestRate / 12.0
lbalance = unpaidBalance + interest
if round(lbalance,2) == 0 or oldbalance == lbalance:
print('Lowest Payment: ' + str(payment))
break
elif lbalance > 0 :
lower = payment
else:
upper = payment
Why both of your codes in some cases use bisection and in some don't? This is the main problem.
All the best to all of you
Have a nice day

Why do I have an infinite loop in my code?

Below I have a piece of code which calculates credit card balance, but it doesn't work when balance has an extreme value (such as balance=9999999999below). It throws the code through an infinite loop. I have a couple of theories as to how to fix this flaw, but don't know how to move forward with them. Here's my code:
balance = 9999999999
annualInterestRate = 0.2
monthlyPayment = 0
monthlyInterestRate = annualInterestRate /12
newbalance = balance
month = 0
while newbalance > 0:
monthlyPayment += .1
newbalance = balance
for month in range(1,13):
newbalance -= monthlyPayment
newbalance += monthlyInterestRate * newbalance
month += 1
print("Lowest Payment:" + str(round(monthlyPayment,2)))
My theory is that
while newbalance > 0
is causing the infinite loop, because newbalance is always larger than 0.
How can I change this while loop so that it doesn't cause my code to run infinitely?
By the way:
With moderate numbers, the program runs for a long time and finally gives an answer. For the larger numbers, the program just keeps on going.
This loop is not infinite, but will take a long time to resolve. For very large values of balance, monthlyPayment will have to get very large in order to drop it past zero.
The bisection method will execute much quicker if you're allowed to use it in your assignment. Will not help you though, if you're required to increment the monthly payment by .01.
static_balance = balance
interest = (annualInterestRate/12)
epsilon = 0.01
lo = balance/12
hi = balance
while abs(balance) > epsilon:
balance = static_balance
min_pmt = (hi+lo)/2
for i in range(12):
balance -= min_pmt
balance *= 1+interest
if balance > 0:
lo = min_pmt
else:
hi = min_pmt
print("Lowest payment: ", round(min_pmt, 2))

Categories