-1

The following code is supposed to calcualte what the savings rate would be to pay off my down payment in exactly 36 months given certain factors like (salary raises and annual return rates. I am having trouble getting the output of the range function to interact with my bisection search method.


    # Cost
    total_cost = 1000000
    portion_down_payment = .25 * total_cost

    # Salary
    annual_salary = 150000
    semi_annual_raise = .07
    annual_return_rate = .04
    current_savings = 0
    month = 0

    # Bisection
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 1
    saving_rate = (high + low) / 2.0
    portion_saved_monthly = annual_salary / 12 * saving_rate
    # range()function
    for x in range(36):
        current_savings += (current_savings * annual_return_rate / 12) + portion_saved_monthly
        month += 1
        if month % 6 == 0:
            annual_salary += annual_salary * semi_annual_raise
            portion_saved_monthly = annual_salary / 12 * saving_rate

    while abs(current_savings - portion_down_payment) >= epsilon:
        if current_savings < portion_down_payment:
            low = saving_rate
        else:
            high = saving_rate
        saving_rate = (high + low) / 2.0
        num_guesses += 1

    print('Best savings rate: ', saving_rate)
    print('Steps in bisection search: ', num_guesses)
chanXVI
  • 23
  • 5

1 Answers1

0

I started with the while loop and nested the for loop inside. I also moved some variables inside the while loop which helped me get the right answer.

'''

   # Cost of House
total_cost = 1000000
portion_down_payment = .25 * total_cost

# Salary
annual_salary_input = float(input('Enter the starting salary: '))
current_savings = 0

# Bisection
epsilon = 100
num_guesses = 0
low = 0
high = 1
saving_rate = (high + low) / 2.0
portion_saved_monthly = annual_salary_input / 12 * saving_rate

while abs(current_savings - portion_down_payment) >= epsilon:
    annual_salary = annual_salary_input
    semi_annual_raise = .07
    annual_return_rate = .04
    current_savings = 0
    month = 0
    portion_saved_monthly = annual_salary / 12 * saving_rate
    saving_rate = (high + low) / 2.0

    # Loop
    for x in range(36):
        current_savings += (current_savings * annual_return_rate / 12) + portion_saved_monthly
        month += 1
        if month % 6 == 0:
            annual_salary += annual_salary * semi_annual_raise
            portion_saved_monthly = annual_salary / 12 * saving_rate

    if current_savings < portion_down_payment:
        low = saving_rate
    else:
        high = saving_rate

    saving_rate = (high + low) / 2.0
    num_guesses += 1

    if num_guesses > 1000:
        break

if saving_rate < 1.0:
    print('Best savings rate: ', "%.4f" % saving_rate)
    print('Steps in bisection search: ', num_guesses)
else:
    print('It is not possible to pay the down payment in three years.')

'''

chanXVI
  • 23
  • 5