所以我试图在Python中实现一个二分搜索算法,它会返回一个“最优”的储蓄率。
我尝试过创建几个不同的函数,我不明白为什么程序会陷入无限循环。我知道abs(current_savings - down_payment)是导致递归无限循环的原因,但我不知道为什么。
首先,这并没有真正解释为什么我的程序不起作用,但这里有:
在每个月末,我都可以获得当前储蓄的利息 首先应用,然后我收到我的月薪,这是公正的 我年薪的1/12。
我试图找到适用于我的月薪的最佳费率,然后加上我目前的储蓄。
我的第一个功能只是检查一个人的工资是否足够高,可以节省250K的首付款。如果他们的工资不够高,则会打印出不合适的工资并返回False。
我的第二个功能是尝试找到最佳费率(“保存部分”),或者保存月薪的最佳费率,以便在down_payment的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
如果有人能帮助我,我会非常感激,在这几个小时试图想出一个修复。
答案 0 :(得分:0)
我对同样的问题感到困惑,终于找到了解决方案。尝试将initial_salary重置为在二分函数中的第一个while循环内的annual_salary,否则每次在内循环上达到六个月时,这将继续增加。这有用吗?