【问题标题】:How to fix infinite loop during bisection search如何在二分搜索期间修复无限循环
【发布时间】:2019-05-31 14:43:48
【问题描述】:

我的代码通过了测试用例,但如果输入了大约 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

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

【问题讨论】:

  • 您是否尝试在代码中设置断点以查看为什么某些测试通过而其他测试不通过?
  • 或者甚至只是一些打印语句,在每次通过循环时打印出变量,看看它们的行为是否符合您的预期?
  • 积攒了 36 个月节省的 for 循环: 把它放在一个函数中并测试它——它有效吗?如果是这样,您知道不是这样 - 这会在 if/elif/else 逻辑或您计算/确定新节省百分比的方式中留下错误。
  • int((low + high) / 2.0 - 为什么要转换为 int? (percent_saved / 10000) 是做什么的?

标签: python bisection epsilon


【解决方案1】:

基本上,当年薪越高时,最佳储蓄率就越小。当最佳储蓄率变得小于您所需的精度水平时

abs(current_savings - portion_down_payment) <= epsilon

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

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

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

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

【讨论】:

  • 我这样做了,并且还删除了我在程序早期的低和高的 int 转换。为了限制有效数字,我使用了best_savings_rate = best_savings_rate[0:5] print("Best savings rate: ", (best_savings_rate + "%"))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多