annual_salary = int(input("Your annual salary "))
semi_annual_raise = 0.07
r = 0.04
down_payment = 250000
epsilon = 100
low = 0
high = 10000
guess = (high + low)//2
best_saving_rate = (guess/10000)
months = 0
current_savings = 0
steps = 0
while abs(current_savings - down_payment) >= 100:
for i in range(36):
current_savings += best_saving_rate*(annual_salary/12) + (current_savings*r)/12
months +=1
if months%6 == 0:
annual_salary = annual_salary + semi_annual_raise*annual_salary
if current_savings < down_payment:
low = guess
else:
high = guess
steps += 1
guess = (high + low)//2
best_saving_rate = float(guess/10000)
print(steps)
print(best_saving_rate)
print(current_savings)
This code is supposed to find the best saving rate for someone who is trying to have enough money for a payment of 250000 dollars in 36 months. I use bisection search and I think I'm in the right track but it won't work. I think the problem is that the variable current savings is not reinitializing with every iteration and I do not know how to make it do that. PLEASE HELP.
Why are you expecting the current_savings
to be reset to 0
with every iteration? You do not do that in the code, so what would cause that to happen? Also by the looks of the code, you should be resetting months
to 0
as well (though it appears that the for
loop index variable i
should actually be the month).
This fixes the obvious errors that I could see:
while abs(current_savings - down_payment) >= 100:
current_savings = 0 # add this
for month in range(36): # Change this
current_savings += best_saving_rate * (annual_salary / 12) + (current_savings * r) / 12
# months += 1 <-- remove this
if months % 6 == 0: