python-使用二等分搜索

时间:2018-09-06 09:21:52

标签: loops for-loop while-loop range bisection

我正在尝试使用MIT开源课件自学编程,并进行了讲座和作业,但遇到了麻烦。在这项作业中,我将使用两等式搜索来尝试计算36个月内的最佳储蓄率,具体如下:1.半年度加息为.07(7%)2.投资的年收益为0.04( 4%)3.首付是房屋成本的0.25(25%)4.您要节省的房屋成本是$ 1M。 我似乎没有得到理想的结果,目前无法弄清楚我做错了什么

n.b。 起始薪水为15万 没有。步骤是12 最佳储蓄率为0.4411

semi_annual_raise = 0.07
r = 0.04
portion_down_payment = 0.25
total_cost = 1000000
annual_salary = float(input("Enter the starting salary: "))
monthly_salary = annual_salary/12
current_savings = 0
number_months = 0
i = 6
total_time = 36
steps = 0

low = 0
high = 10000

for y in range (0,10000):
    y = (high + low) / 2.0
    portion_saved = y / 10000
    while current_savings <= total_cost*portion_down_payment:
        investment = current_savings*(r/12)
        current_savings = current_savings + monthly_salary*portion_saved + investment
        number_months += 1
        if number_months == i:
            monthly_salary = monthly_salary*(semi_annual_raise+1)
            i += 6
        if   current_savings >= total_cost*portion_down_payment and number_months < total_time:
            high = y
        elif current_savings < total_cost*portion_down_payment and number_months > total_time:
            low = y
        y = (high + low) / 2.0
        portion_saved = y / 10000
        steps += 1
print("Amount of salary to be saved per month: ", portion_saved)
print("Steps in bisection search: ", steps)

0 个答案:

没有答案