二等分搜索付款金额Edx练习。 Python计算机科学概论

时间:2018-06-22 19:00:40

标签: python-3.x bisection

我确定我缺少明显的东西。我定义了一个函数,用于在给定年度利率的情况下,将还款一年后的余额返还给您。如果返回的余额小于原始余额,则将下限值设置为等于功能值(高+低)/ 2。如果从功能返回的余额高于原始余额,则将高设置为等于功能(高+低)/ 2。我的高值和低值似乎收敛到无法给出正确答案的程度。

Balance = 2000
AnnualInterestRate = .2
IntRate = (AnnualInterestRate) / 12.0
low = Balance / 12
high = (Balance * (1 + IntRate)**12) / 12.0
ans = (high+low)/2
epsilon = .01
numGuesses = 0

def at_end(ans, Balance):
        for i in range(1,13):
            Balance = Balance - ans
            Balance = Balance + (Balance*(AnnualInterestRate/12))
        return Balance


while abs(at_end(ans, Balance) - Balance)>= epsilon:# and numGuesses<20:
    numGuesses +=1
    if at_end(ans, Balance)< Balance:
        low = ans
        print('Balance is low. New low value is {}. Balance is {} and balance at the end is {}'.format(low, Balance,at_end(ans, Balance)))
    else:
        high = ans
        print('Balance is high. New high value is {}. Balance is {} and balance at the end is {}'.format(high, Balance,at_end(ans, Balance)))
    ans = (high + low)/2.0

从讲座进行的二等分搜索的此示例运行良好。我似乎无法查明我的错误在哪里。

x = 25
epsilon = 0.001
numGuesses = 0
low = 1.0
high = x
ans = (high + low)/2.0

while abs(ans**2 -x)>= epsilon:
    print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
    numGuesses +=1
    if ans**2< x:
        low = ans
    else:
        high = ans
    ans = (high + low)/2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))

0 个答案:

没有答案