首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python二分搜索逻辑错误-返回不准确的结果

Python二分搜索逻辑错误-返回不准确的结果
EN

Stack Overflow用户
提问于 2016-11-26 16:37:24
回答 1查看 172关注 0票数 0

我正试图解决这个麻省理工学院开放式课程作业上的第三个问题。它要求您使用二分搜索方法计算在一年内清偿给定债务所需的每月付款。我得到了预期的输出类型,但结果非常不准确。有人能指出我哪里出了问题吗?谢谢

代码语言:javascript
运行
复制
# Problem Set 1("C")
# Time Spent: xx hours

def payInOne_BisectionSearch (balance,annualRate):
    #initialize variables
    initialBalance = balance
    monthlyRate = float(annualRate/12.0)
    minMonthly = float(balance/12.0)
    maxMonthly = float((balance * (1 + monthlyRate ** 12.0 ))/12.0)
    monthlyPayment = float((minMonthly + maxMonthly)/2)
    numMonths = 1
    #define function to check balance after 12 months       
    def balanceAfterYear (balance, monthlyRate, monthlyPayment):
        for numMonths in range (1,13):
            interest = balance * monthlyRate
            balance += interest - monthlyPayment
            if balance <= 0:
                  break
        return [balance, numMonths]

    while maxMonthly - minMonthly >= .005:
        balance = initialBalance
        monthlyPayment = float((minMonthly + maxMonthly)/2)
        if balanceAfterYear(balance,monthlyRate,monthlyPayment)[0] < 0:#paying too much
            maxMonthly = monthlyPayment
        elif balanceAfterYear(balance,monthlyRate,monthlyPayment)[0] > 0:#paying too little
            minMonthly = monthlyPayment
        else:
            break
    print "Monthly payment to pay off debt in 1 year:", round(monthlyPayment,2)
    print "Number of months needed:", round(balanceAfterYear(balance,monthlyRate,monthlyPayment)[1], 2) 
    print "Balance:", round(balanceAfterYear(balance,monthlyRate,monthlyPayment)[0], 2) 

payInOne_BisectionSearch (float(raw_input("Enter the outstanding balance")),float(raw_input("Enter annual rate as a decimal")))


    '''Test Case Expected:
       Enter the outstanding balance on your credit card: 320000
       Enter the annual credit card interest rate as a decimal: .2
       RESULT
       Monthly payment to pay off debt in 1 year: 29643.05
       Number of months needed: 12
       Balance: -0.1

       Test Case Actual Output:
       Enter the outstanding balance320000
       Enter annual rate as a decimal.2
       Monthly payment to pay off debt in 1 year: 26666.67
       Number of months needed: 12.0
       Balance: 39179.43'''
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-27 12:31:17

您的问题在于初始的maxMonthly值。我想你真正想要的是把它定义为

代码语言:javascript
运行
复制
maxMonthly = float((balance * ((1 + monthlyRate) ** 12.0 ))/12.0)

否则,monthlyRate**12将只计算到一个接近于零的数字(对于0到1之间的monthlyRate),这将使maxMonthly计算为balance/12.0与您的minMonthly相同,从而使结束时的even循环永远不会启动。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40820550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档