我的while循环中嵌套了一个for循环,是什么导致代码中的无限循环?

时间:2018-11-20 03:44:19

标签: python-3.x for-loop if-statement while-loop bisection

我是Python和编码的新手。我正在尝试使用带有嵌套的for循环的while循环来计算可以节省的最低工资百分比,该百分比将在36个月内达到节省目标。该代码还包含一些功能,用于每6个月对薪水进行一次半年度加薪,并将所获得的利息应用于储蓄。

当我运行代码时,它会导致无限循环,而我无法看到是什么原因造成的。

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)

1 个答案:

答案 0 :(得分:0)

您为什么使用(monthly_salary*portion_saved/10000?由于您需要每月将portion_saved添加到current_savings中,因此我建议您使用

current_savings+=(current_savings*r/12) + portion_saved

我认为您还可以通过使用以下公式找到要保存的百分比来简化此过程

monthly_salary*(save_percent/100)* 36 = down_payment-epsilon