繁体   English   中英

Python Bisect搜索-导致失败的abs()

[英]Python Bisect Search- abs() causing failure

因此,我尝试在Python中实现对分搜索算法 ,该算法返回“最佳”节省率。

我尝试创建几个不同的函数,但我不明白为什么程序会陷入无限循环。 我确实知道abs(当前储蓄-首付)是导致递归无限循环的原因,但我不知道为什么。

首先,这并不能真正解释为什么我的程序无法正常工作,但可以这样做:

每个月末,我都会从经常性储蓄中赚取利息,该利息会被首先应用,然后我将收到月薪,仅为月薪的1/12。

我试图找到适用于我的月薪的最佳费率,然后再添加到当前的储蓄中。

我的第一个功能只是检查自己的薪水是否足够高,以至可以节省25万首付。 如果他们的薪水不够高,它将打印出薪水不足并返回False。

我的第二个功能试图找到最优惠的价格(“已节省的部分”),或者找到节省月薪的最佳价格,以使首付不超过100美元。 另外,我必须记录对分搜索功能为找到最佳速率而采取的“步数”。

这是代码:

    #Givens
annual_salary = 150000
initial_salary = annual_salary
interest_rate = float(0.04/12.0)
down_payment = float(250000.0)
semi_annual_raise = 0.07

#Bisect-search
low = float(0.0)
high = float(10000.0)
portion_saved = float((low+high)/2)
current_savings = 0
months = 0
steps = 0

def isPossible(annual_salary):
    count = 0
    current_savings = 0
    while count < 36:
        current_savings += (current_savings*interest_rate) + (annual_salary/12)
        count += 1
        if count % 6 == 0:
            annual_salary += (annual_salary*semi_annual_raise)
    if current_savings < down_payment:
        print("It is not possible to pay the down payment in three years.")
        return False
    else:
        return True


def bisearch(initial_salary,interest_rate,down_payment,semi_annual_raise,low,high,portion_saved,steps):
    current_savings = 0
    months = 0
    while abs(current_savings - down_payment) > 100.0:
        months = 0
        current_savings = 0
        while months < 36:
            current_savings = current_savings + (initial_salary*interest_rate)
            current_savings = current_savings + (initial_salary/12*portion_saved/10000.0)
            months += 1
            if months % 6 == 0:
                initial_salary += (initial_salary*semi_annual_raise)
        steps += 1
        if current_savings > down_payment:
            high = portion_saved
        else:
            low = portion_saved
        portion_saved = ((low+high)/2.0)
    print("Best saving rate: ", (portion_saved/10000.0))
    print("Steps in bisection search: ", steps)




if isPossible(annual_salary) == True:
    bisearch(initial_salary,interest_rate,down_payment,semi_annual_raise,low,high,portion_saved,steps)

和测试用例:

注意:二等分搜索步骤的数量不必相同,但速率应相同

测试用例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

如果有人可以帮助我,我将不胜感激,已经花了几个小时试图提出解决方案。

我对同样的问题感到困惑,终于找到了解决方案。 尝试在对分函数的第一个while循环内将initial_salary重置为annual_salary,否则每次您在内部循环中点击六个月时,这种情况就会持续增加。 那样有用吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM