首页 > 解决方案 > 如何获得 range() 函数的输出以与我的二分搜索方法进行交互?

问题描述

考虑到某些因素,例如(加薪和年回报率),下面的代码应该计算储蓄率将在 36 个月内还清我的首付。我无法让 range 函数的输出与我的交互二分搜索法。


    # Cost
    total_cost = 1000000
    portion_down_payment = .25 * total_cost

    # Salary
    annual_salary = 150000
    semi_annual_raise = .07
    annual_return_rate = .04
    current_savings = 0
    month = 0

    # Bisection
    epsilon = 100
    num_guesses = 0
    low = 0
    high = 1
    saving_rate = (high + low) / 2.0
    portion_saved_monthly = annual_salary / 12 * saving_rate
    # range()function
    for x in range(36):
        current_savings += (current_savings * annual_return_rate / 12) + portion_saved_monthly
        month += 1
        if month % 6 == 0:
            annual_salary += annual_salary * semi_annual_raise
            portion_saved_monthly = annual_salary / 12 * saving_rate

    while abs(current_savings - portion_down_payment) >= epsilon:
        if current_savings < portion_down_payment:
            low = saving_rate
        else:
            high = saving_rate
        saving_rate = (high + low) / 2.0
        num_guesses += 1

    print('Best savings rate: ', saving_rate)
    print('Steps in bisection search: ', num_guesses)

标签: pythonpython-3.xalgorithmrangebisection

解决方案


我从 while 循环开始,将 for 循环嵌套在里面。我还在 while 循环中移动了一些变量,这有助于我得到正确的答案。

'''

   # Cost of House
total_cost = 1000000
portion_down_payment = .25 * total_cost

# Salary
annual_salary_input = float(input('Enter the starting salary: '))
current_savings = 0

# Bisection
epsilon = 100
num_guesses = 0
low = 0
high = 1
saving_rate = (high + low) / 2.0
portion_saved_monthly = annual_salary_input / 12 * saving_rate

while abs(current_savings - portion_down_payment) >= epsilon:
    annual_salary = annual_salary_input
    semi_annual_raise = .07
    annual_return_rate = .04
    current_savings = 0
    month = 0
    portion_saved_monthly = annual_salary / 12 * saving_rate
    saving_rate = (high + low) / 2.0

    # Loop
    for x in range(36):
        current_savings += (current_savings * annual_return_rate / 12) + portion_saved_monthly
        month += 1
        if month % 6 == 0:
            annual_salary += annual_salary * semi_annual_raise
            portion_saved_monthly = annual_salary / 12 * saving_rate

    if current_savings < portion_down_payment:
        low = saving_rate
    else:
        high = saving_rate

    saving_rate = (high + low) / 2.0
    num_guesses += 1

    if num_guesses > 1000:
        break

if saving_rate < 1.0:
    print('Best savings rate: ', "%.4f" % saving_rate)
    print('Steps in bisection search: ', num_guesses)
else:
    print('It is not possible to pay the down payment in three years.')

'''


推荐阅读