lundi 19 novembre 2018

I have a for loop nested within my while loop, what is causing an infinite loop within my code?

I'm new to Python and coding in general. I am trying to use a while loop with a nested for loop to calculate the lowest % of salary that can be saved that will reach the savings goal within 36 months. The code also includes functions to apply a semi-annual raise to the salary every 6 months and to apply interest gained to the savings.

When I run my code it results in an infinite loop and I haven't been able to see what is causing it.

total_cost = 1000000
semi_annual_raise = 0.07
down_payment = 0.25*total_cost
starting_salary = float(input("What is your annual salary?: "))
monthly_salary = starting_salary/12.0
r = 0.04
steps = 0
epsilon = 100
low = 0
high = 10000
portion_saved = (high + low)/2.0
current_savings = 0
raise_counter = 0

while abs(current_savings - down_payment) > epsilon:
    current_savings = 0

    for months in range(36):
        current_savings += (current_savings*r/12) + (monthly_salary* 
        (portion_saved/10000))

        if raise_counter == 6:
            monthly_salary += monthly_salary*semi_annual_raise
            raise_counter = 0
        raise_counter += 1

    if current_savings < down_payment:
        low = portion_saved
    else:
        high = portion_saved
    portion_saved = (high + low)/2.0
    steps += 1
    raise_counter = 0
print ("Number of steps =", steps)
print ("Optimal % to save:", portion_saved/10000)

Aucun commentaire:

Enregistrer un commentaire