Brandon Dorris
Brandon Dorris

Reputation: 138

Why do I get unexpected results from this simple python function?

I am working through MIT OpenCourseWare and I have run into a problem with what should be a very simple function. The code below seems to work, but I get answers that are either correct for very close to what I should. For example, if you enter:

annual_salary = 120000
portion_saved = .10
total_cost = 1000000

It outputs 182, but the expected result is 183. However, if I enter:

annual_salary = 80000
portion_saved = .15
total_cost = 500000

I get 105, which is the expected result. If I remove the if branch and use the same inputs, I get 183 (correct) and 106 (incorrect). I am completely baffled.

def calc_savings(annual_salary, portion_saved, total_cost):
    portion_down_payment = .25
    r = 0.04 # return on investment
    monthly_salary = annual_salary / 12
    num_months = 1
    current_savings = 0

    while current_savings < total_cost * portion_down_payment:
        pre_interest = current_savings + (monthly_salary * portion_saved)
        current_savings = pre_interest + (pre_interest * r / 12)
        if current_savings >= total_cost * portion_down_payment:
            return num_months
        num_months += 1
    return num_months
    
annual_salary = int(input("Enter your annual_salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = int(input("Enter the cost of your dream home: "))

print("Number of months: ", calc_savings(annual_salary, portion_saved, total_cost))

Upvotes: 0

Views: 29

Answers (1)

zack256
zack256

Reputation: 171

If you add the investment return (current_savings * r / 12) and then add the monthly investment (monthly_salary * portion_saved) it will return the correct answers. You just need to switch the order you add them.

Upvotes: 1

Related Questions