balance = int(100)
balance *= 0.05 + balance
balance *= 0.05 + balance
balance *= 0.05 + balance
print (int(round ( balance, '.2f' )))
im trying to calculate what 100$ interest would be after 3 years compound interest.
I originally tried this
balance = 100
balance *= 0.05 + balance
balance *= 0.05 + balance
balance *= 0.05 + balance
print (format( balance, '.2f' ))
but my formatting caused the answer to be in the trillions instead of a 5 digit float.
You're multiplying the balances. Try this:
balance = int(100)
balance = balance * 0.05 + balance
balance = balance * 0.05 + balance
balance = balance * 0.05 + balance
print("{:.02f}".format(balance))
You have your operator precedence incorrect: the assignment operator is last. Thus, what you've done is
balance = balance * (0.05 + balance)
Instead, try one of the canonical ways to express interest:
rate = 0.05
balance += balance * rate
or
balance *= (1 + rate)
The parentheses aren't needed, but will help you read this.
Also, you might make a parameter (variable) for your repetition:
limit = 3
for year in range(limit):
balance *= 1 + rate
print("{:.02f}".format(balance))
You should pay attention to order of operations. balance *= 0.05 + balance will add 0.05 and balance before multiplying it to balance. What you'd want is balance = balance + balance * 0.05 or balance = balance * 1.05.
You can create a function to calculate compound interest to make it easier:
def comp_int(balance, rate, years):
return balance * (1 + rate)**years
balance = 100
rate = 0.05
years = 3
new_bal = comp_int(balance, rate, years)
print(f'{new_bal:.2f}')
Related
I am taking a course on edx and trying to solve a problem using bisection to calculate a monthly payment at which we can pay off the debt in a year. I have coded a solution but the results are a bit off than expected. Code is below. Answer code shared by edx is also listed beneath. Can you please share why my code is not giving same results? I am trying to get to to 2 decimal places accuracy.
balance=float(input('balance = '))
annualInterestRate=float(input('annualInterestRate = '))
remainingbalance=balance
low=float(remainingbalance/12)
high=float(remainingbalance*((1+(annualInterestRate/12))**12)/12.0)
if remainingbalance>0.01 or remaningbalance<0.01:
remainingbalance=balance
increment=round(float((high+low)/2), 2)
for i in range(1, 13):
unpaidbalance=remainingbalance-increment
interest=(annualInterestRate/12) * unpaidbalance
remainingbalance=round(unpaidbalance + interest, 2)
if remainingbalance>0.01:
low=increment
elif remainingbalance<-0.01:
high=increment
print('Lowest Payment: ', increment)
Sample code for solution provided by edx
init_balance = balance
monthlyInterestRate = annualInterestRate/12
lower = init_balance/12
upper = (init_balance * (1 + monthlyInterestRate)**12)/12.0
epsilon = 0.03
while abs(balance) > epsilon:
monthlyPaymentRate = (upper + lower)/2
balance = init_balance
for i in range(12):
balance = balance - monthlyPaymentRate + ((balance - monthlyPaymentRate) * monthlyInterestRate)
if balance > epsilon:
lower = monthlyPaymentRate
elif balance < -epsilon:
upper = monthlyPaymentRate
else:
break
print('Lowest Payment:', round(monthlyPaymentRate, 2))
My Code Results:
balance = 320000
annualInterestRate = 0.2
Lowest Payment: 29591.88
Edx Results:
balance = 320000
annualInterestRate = 0.2
Lowest Payment: 29157.09
Actually I am used to c++ and I am stuck in python. I can't seem to understand what's causing the infinite while loop.
The main goal of the code is to calculate how many months are required to save enough money for upfront payment.
#*******Initializing all the required variables***********
home_price = float(input("Enter the price of your dream home:")) # cost of the home
down_payment_portion = 0.25 # initial upfront pay for the home which is 25%
stamp_duty_portion = 0.03 # 3%
annual_salary = float(input("Enter your annual salary:"))
tax_portion = 0.2 # 20%
save_amount = 0
save_portion = float(input("Enter the amount of money you want to save after tax-cut:"))
annual_return = 0.05 # 5%
months = 0
#*********************************************************
#------------Calculating all the necessary values---------
down_payment_portion = down_payment_portion * home_price # calculating the down payment for the dream home
stamp_duty_portion = stamp_duty_portion * home_price # calculating the stamp duty for the home
tax_portion = tax_portion * annual_salary # calculating the tax cut
save_portion = save_portion * save_amount # calculating the portion of tax-cut income to be put into savings
annual_return = (save_amount * annual_return) / 12
upfront_payment = down_payment_portion + stamp_duty_portion
while(save_amount < upfront_payment):
save_amount = save_amount + annual_return
save_amount = save_amount + (annual_salary - tax_portion) * save_portion / 12
months = months + 1
print(f'You will need {months} month to save enough for your upfront payment{upfront_payment}.')
You initialise save_amount = 0
you get annual_return as annual_return = (save_amount * annual_return) / 12 which would be zero
you also get save_portion as save_portion = save_portion * save_amount which is again zero
Therefore your save_amount in the while loop is never incremented it too remains zero, save_amount < upfront_payment is always true ==> Infinite loop
In your code
while(save_amount < upfront_payment):
save_amount = save_amount + annual_return # 0 + 0 = 0
# 0 + (some value * 0)/12 = 0
save_amount = save_amount + (annual_salary - tax_portion) * save_portion / 12
Why is this code creating an infinite loop? I would think this should be an appropriate solution for this type of problem. For example, if the price was $5 and you paid $5.47, the program would print:
Quarters: 1
Dimes: 2
Nickels: 0
Pennies: 2
However, an infinite loop occurs and I'm not sure why. Anyone know the reason?
price = round(float(input("Enter the price: ")), 2)
print price
paid = round(float(input("Enter the amount paid: ")), 2)
print paid
change = round(float(paid - price), 2)
print change
quarters = 0
dimes = 0
nickels = 0
pennies = 0
while change > 0.00:
print change
if change >= .25:
change = change - .25
quarters += 1
continue
elif change >= .1:
change = change - .1
dimes += 1
continue
elif change >= .05:
change = change - .05
nickels += 1
elif change >= .01:
change = change - .01
pennies += 1
print "Quarters: " + str(quarters)
print "Dimes: " + str(dimes)
print "Nickels: " + str(nickels)
print "Pennies: " + str(pennies)
Rather than dealing with loops, I would suggest just subtracing off the change that you already gathered, prioritizing larger coins.
price = float(input("Enter the price: "))
paid = float(input("Enter the amount paid: "))
change = paid - price
if change < 0:
raise ValueError('Not enough paid')
quarters = change // 0.25
dimes = (change - (0.25 * quarters)) // 0.10
nickels = (change - (0.25 * quarters) - (0.10 * dimes)) // 0.05
pennies = 100 * (change - (0.25 * quarters) - (0.10 * dimes) - (0.05 * nickels))
print("Quarters: {:.0f}".format(quarters))
print("Dimes: {:.0f}".format(dimes))
print("Nickels: {:.0f}".format(nickels))
print("Pennies: {:.0f}".format(pennies))
There's one minor bug in the code which causes the program to only work correctly if price and amount paid are interchanged (e.g. price = 2, paid = 1). But that is not the issue causing the infinite loop.
Your code creates an infinite loop for e.g. the following arguments:
price: 5.6
paid: 5.4
The reason for the infinite loop can be seen from your own print output:
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
...
Since change < 0.01, no if clause applies and thus the loop is never left.
How could you solve the problem more robustly?
Here's a sketch
from math import floor
change = paid - price
quarters = int(floor(change / 0.25))
change -= quarters * 0.25
dimes = int(floor(change / 0.1))
change -= dimes * 0.1
nickels = int(floor(change / 0.05))
change -= nickels * 0.05
pennies = int(floor(change / 0.01))
change -= pennies * 0.01
remaining = change
print("Quarters:", quarters)
print("Dimes:", dimes)
print("Nickels:", nickels)
print("Pennies:", pennies)
Personally I would also condense this into a loop over the coin type:
increments = {"quarter":0.25, "dimes": 0.1, "nickels": 0.05, "pennies": 0.01}
change_parts = {}
for inc_name, inc in increments.items():
amount = int(floor(change / inc))
print(inc_name, inc, amount)
change -= amount * inc
change_parts[inc_name] = amount
for inc_name, amount in change_parts.items():
print(inc_name + ":", amount)
So if
balance = int(100)
balance *= 0.05
since balance is mutable should'nt that equal to 105? instead i just get 5.
and if i add another line of code such as
balance = int(100)
balance *= 0.05
balance *= 0.05
the output would be 0.25, essentially my variable is not carrying over and im just multiplying the end outcome to 5%
if i add
balance= int(100)
balance *= 0.05 + balance
i get 10005
I thought += or *= function could be used for an equation that would take a variable, do the equation then carry over the variable + the outcome as the new variable.
How do i do that for a multi step equation.
balance = int(100)
balance *= 0.05
is the same as
balance = int(100)
balance = balance * 0.05
Wouldn't you say that that's 5, not 105?
A *= B is just a shorthand for A = A * B.
Your third example is the same as:
balance= int(100)
balance = balance * (0.05 + balance)
Again, you're getting what I would think you'd expect from this code.
BTW, you don't need the int(). 100 by itself is a literal value of type 'int'. So the most concise way to state your first code block is:
balance = 100 * .05
Sorry for saying this but you have to first under the python or any programming language basics.
'+' is addition sigh
'*' is multiplication sign
A = 2 + 3
gives 5 as answer, and
A = 2 * 3 will give 6 as answer.
Secondly, '+=' , '*=' are shorthand where the operation's first value is the same space where you want to save the result.
like
A = 5
and want to add 3 in this same 'A'
A = A + 3 or can also be written as A += 3,
similarly for multiplication
A = 100
A = 100 * 0.05 can also be written as A *= 0.05
it will give A as 5
So, good luck.
So I'm very new to Python... The problem is as follows:
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.
My current code is as follows:
month = 1
minimumMonthlyPayment = (balance * monthlyPaymentRate)
totalPaid = 0.0
while month < 13:
print "Month: " + str(month)
print "Minimum Monthly Payment: " + str(round(minimumMonthlyPayment, 2))
balance = (balance - (balance * monthlyPaymentRate)) * (1 + (annualInterestRate/12))
minimumMonthlyPayment = (balance * monthlyPaymentRate)
print "Remaining Balance: " + str(round(balance, 2))
totalPaid += minimumMonthlyPayment
month += 1
print "Total Paid: " + str(round(totalPaid, 2))
print "Remaining Balance: " + str(round(balance, 2))
Here's the correct output:
So all the numbers are identical in both outputs but my Total Paid ends up being 1732.94 instead of the correct amount which is 1775.55. I added the numbers from my output up on a side calculator and it came out to 1775.55 as well. Is there something in my code that's borking this?
Here are the values for the variables that the test code uses:
balance = 4213;
annualInterestRate = 0.2;
monthlyPaymentRate = 0.04;
Great job! Your code is almost perfect. The only mistake is that line 8 needs to run before line 9. You're changing the balance and then using that changed balance to calculate the minimum monthly payment. You need to calculate the minimum monthly payment for each month before you update the balance.
Hope this helps!
balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
totalPaid = 0.0
month = 1
minimumMonthlyPayment = balance * monthlyPaymentRate
while month < 13:
print "Month: " + str(month)
print "Minimum Monthly Payment: " + str(round(minimumMonthlyPayment, 2))
minimumMonthlyPayment = balance * monthlyPaymentRate
balance = (balance - (balance*monthlyPaymentRate))*(1+(annualInterestRate/12))
print "Remaining Balance: " + str(round(balance, 2))
totalPaid += minimumMonthlyPayment
month += 1
print "Total Paid: " + str(round(totalPaid, 2))
print "Remaining Balance: " + str(round(balance, 2))
You are recalculating your balance before calculating your minimumMonthlyPayment rate.
So balance * monthlyPaymentRate comes to a different amount on line 8 and 9 since balance has changed.
If you assign balance * monthlyPaymentRate to a variable before those lines and use it for both calculations it would correct this.