I am trying to find the best rate of savings to achieve a down payment on a $1million house in 36 months. savings need to be within 100$ of required down payment. downpayment is 25% of total cost. I have to search for an integer between 0 and 10000 (using integer division), and then convert it to a decimal percentage (using float division) to use when we are calculating the current_savings after 36 months.
This is my code which is not working (I am really new to programming)
annual_salary = 150000
total_cost = 1000000
low=0
high=10000
portion_saved=(low+high)/20000.0
epsilon=100
current_savings = 0
portion_down_payment=0.25*total_cost
steps = 0
rate = 0.04
number_of_months = 0
semi_annual_raise = 0.07
while current_savings-portion_down_payment>=epsilon and number_of_months<=36:
current_savings += annual_salary * portion_saved / 12
current_savings += current_savings * rate / 12
number_of_months += 1
if number_of_months % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
if current_savings<portion_down_payment:
low=portion_saved
else:
high=portion_saved
portion_saved=(low+high)/20000.0
steps+=1
print("Best savings rate: ", portion_saved)
print("Steps in bisection search", steps)
Any help is greatly appreciated !!!
The monthly income does not vary with savings rate, so it makes sense to only calculate it once:
If the monthly savings do not earn interest, the problem is trivial:
so you would have to save 46.6% of income.
If monthly savings earn interest, the problem is more interesting (bad pun absolutely intended).
Let's test it based on our calculation above,
so that looks like what we expected.
You can think of this function as iteratively evaluating a 36th-degree polynomial. Given known
monthly_incomes
andinterest_rate
, we want to findsavings_rate
to produce a desiredtotal
, ie find the only real positive root ofpolynomial - target == 0
. There is no analytic solution ifinterest_rate > 0.
, so we will try for a numeric solution.and now we run it like
which gives a savings rate of 45.4%.