【问题标题】:MIT 6.0001 Pset 1c Bisectional Search questionMIT 6.0001 Pset 1c Bisection Search 问题
【发布时间】:2022-07-16 21:21:53
【问题描述】:

链接到 pset 1(https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/MIT6_0001F16_ps1.pdf)

你好,

我一直在研究 MIT 6.0001 课程的 pset1 的二等分搜索问题。我觉得我的所有组件都已关闭,但无论我提供什么输入,它都会一直给我相同的储蓄率和二分搜索步骤的答案。谁能告诉我我在这里做错了什么?


# User input
annual_salary = float(input('Enter the starting salary: ' ))

# Given sets of assumption
total_cost = 1000000
semi_annual_raise = 0.07
portion_down_payment = 0.25
current_savings = 0
r = 0.04   # Annual investment interest rate of current savings 
down_payment = portion_down_payment * total_cost

num_guess = 0  # Bisectional search guess count starts at 0

# Lowest and highest integer savings rate in intial bisection search 
low = 0
high = 10000
guess = (high + low)//2.0

while abs(down_payment - current_savings) >= 100:
    current_savings = 0
    rate = guess/10000
    for month in range(36):
        if month%6 == 0 and month > 0:
            annual_salary += annual_salary * semi_annual_raise  
        monthly_salary = annual_salary/12
        current_savings += (rate * monthly_salary) + current_savings*(r/12)
# Bisectional search introduced
    if current_savings < down_payment:
        low = guess
    else:
        high = guess
    guess = (high + low)//2.0
    num_guess += 1 
    if num_guess > 13:
        break
print('Best savings rate:', rate)
print('Steps in bisection search:', num_guess)


【问题讨论】:

  • 你不能只做中间打印来找出逻辑出错的地方吗?

标签: python


【解决方案1】:

您应该在每次通过 [for 循环] 之前将 annual_salary 变量重置为其原始值(来自输入的值),因为每次迭代都会尝试以相同的起薪猜测不同的储蓄率。

我建议您使用不同的变量(例如,updated_annual_salary)并将起薪分配给它,以便能够一遍又一遍地重置它。

另一件事是,当年薪更新时,月薪也会更新,节省的部分也会更新。所以,你的 [while 循环] 应该像这样开始:

while abs(down_payment - current_savings) >= 100:
    updated_annual_salary = annual_salary
    current_savings = 0
    rate = guess / 10000
    for month in range(36):
        if month % 6 == 0 and month > 0:
            updated_annual_salary += updated_annual_salary * semi_annual_raise
        monthly_salary = updated_annual_salary / 12
        current_savings += (rate * monthly_salary) + current_savings * (r / 12)

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2018-06-22
    • 1970-01-01
    相关资源
    最近更新 更多