如何在二等分搜索过程中解决无限循环问题

时间:2019-01-05 04:10:18

标签: python bisection epsilon

我的代码通过了测试用例,但是如果输入了约949,000的任何内容,则会进入无限循环。

为了计算36个月内首付2位有效数字的首付,我需要计算节省一部分每月收入的最佳利率。我认为这与我不太了解epsilon的计算方式有关-我尝试将epsilon计算为0.0001 * total_cost,0.0004 * part_down_payment和0.0001 * Annual_income全部无效。

#House Hunting ps1c

low = int(0)
high = int(10000)
percent_saved = (low + high)/2.0

current_savings = 0
annual_salary = int(input("What is your starting anual salary? "))
total_cost = 1000000
semi_annual_raise = 0.07
portion_down_payment = total_cost * 0.25
epsilon = 100

r = 0.04

total_months = 0
steps = 0
while True:
    current_savings = 0
    monthly_salary = annual_salary/12
    for i in range(1,37):
        current_savings += (current_savings*r/12)
        current_savings += (monthly_salary * (percent_saved / 10000))     
        total_months += 1
        if total_months % 6 == 0:
            monthly_salary += monthly_salary * semi_annual_raise
    steps +=1   

    if abs(current_savings - portion_down_payment) <= epsilon:
        print("Steps in bisectional search: ", steps)
        best_savings_rate = str(percent_saved / 100)
        print("Best savings rate: ", (best_savings_rate + "%"))
        break
    elif (portion_down_payment - 100) - current_savings > 0:
        low = percent_saved
        percent_saved = int((low + high) / 2.0)
    else:
        high = percent_saved       
        percent_saved = int((low + high) / 2.0)

    if percent_saved >= 9999:
        print("It is not possible to afford this in 3 years")
        break

测试案例1

Enter the starting salary: 150000
Best savings rate: 0.4411  
Steps in bisection search: 12 

测试案例2

Enter the starting salary: 300000
Best savings rate: 0.2206 
Steps in bisection search: 9 

测试案例3

Enter the starting salary: 10000
It is not possible to pay the down payment in three years

我的代码通过了所有测试用例,但是当输入过高时,它将进入一个无限循环,我不知道该如何协调。

1 个答案:

答案 0 :(得分:0)

基本上,当年薪增加时,最佳储蓄率就会变小。当最佳储蓄率变小时,您需要的精度水平

abs(current_savings - portion_down_payment) <= epsilon

变得更高。 当您将percent_saved转换为int时

percent_saved = int((low + high) / 2.0)

它人为地限制了精度,然后代码进入了无限循环。

删除演员表,代码将始终有效。