问题描述
我一直在尝试在MIT OCW 6.0001(Python的CS简介)PSET 1 C部分中实现对分搜索算法,但是它不起作用。目标是根据用户的输入工资(在我的代码中均定义了固定变量)找到理想的储蓄率,以支付新房的首付。我是二等分搜索的新手,并且在尝试实现此代码方面确实很挣扎。
semi_annual_raise = 0.07
r = 0.04
total_cost = 1000000
down_payment = 0.25 * total_cost
annual_salary = int(input("Enter your annual salary: "))
current_savings = 0
epsilon = 100
low = 0
high = 10000
savings_rate = ((high + low)/2)
num_guesses = 0
#to find: best rate of savings to achieve the money
month = 0
while current_savings <= down_payment - epsilon and month < 37:
if (month != 0 and month % 6 == 0):
annual_salary += annual_salary*semi_annual_raise
current_savings += ((annual_salary/12 *savings_rate/(10**4)) + current_savings*r/12)
if current_savings < down_payment - epsilon:
low = savings_rate
else:
high = savings_rate
savings_rate = (high + low)/2
num_guesses+=1
month += 1
if (month > 36 or current_savings < down_payment - epsilon):
print("Sorry,can't afford that")
else:
print("Best savings rate: ",savings_rate/10**4)
print("Steps in bisection search: ",num_guesses)
理想的输出:
Enter your annual salary: 150000
Best Savings rate: 0.4411
Steps in bisection search: 12
Enter your annual salary: 150000
Best savings rate: 0.9999971389770508
Steps in bisection search: 19
该问题表明,根据我实现对分搜索的方式,我的值可能与理想的输出语句略有不同。但是我很难为正确理解这意味着什么。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)