简体   繁体   English

为什么我的二等分算法不起作用? 蟒蛇

[英]Why doesn't my bisection algorithm work? Python

I'm writing a credit card payment calculator for my Python class. 我正在为我的Python类编写一个信用卡支付计算器。 The assignment is to write a definition for a calculator that figures out the monthly payment necessary to bring your balance to zero in x number of months. 任务是为计算器写一个定义,计算出使您的余额在x个月内达到零所需的每月付款。

The definition takes 3 parameters: initialBalance, apr, months. 该定义采用3个参数:initialBalance,apr,months。

As much as I can figure, the point of the assignment is to get us to use bisection method to find our answer, and I have written two other definitions that aid the assignment: 据我所知,分配的重点是让我们使用二等分法找到答案,并且我写了另外两个有助于分配的定义:

1) newBalance() - which determines the new balance after a payment is made; 1)newBalance()-确定付款后的新余额; 2) balances() - which returns a list of balances after the payments were made; 2)balances()-返回付款后的余额清单;

In that light, balances()[-1] returns the final balance, so my plan of action has been to evaluate the last item in the list as equal to 0 (or at least within 0.005 of 0!) and if so, return the payment that got me there. 因此,balances()[-1]返回最终余额,因此我的行动计划是将列表中的最后一项评估为等于0(或至少在0.005的0!之内!),如果是,则返回付款使我到了那里。

if the final balance is negative (I've paid too much!): payment = payment - (payment / 2); 如果最终余额为负(我支付了太多!):付款=付款-(付款/ 2); if the balance is positive (I haven't paid enough!): payment = payment + (payment / 2); 如果余额为正(我还没有付清!):付款=付款+(付款/ 2);

As best as I can figure it, my algorithm should eventually conclude, but it NEVER finds a close enough answer... 尽我所能,我的算法应该最终得出结论,但是它永远找不到足够接近的答案...

Here is my code, (and the Prof's testing def at the end): 这是我的代码,(以及教授的测试定义最后):

def newBalance(prevBalance, apr, payment):
    """
    - prevBalance: the balance on the credit card statement.
    - apr: the annual percentage rate (15.9 here means 15.9%).
    - payment: the amount paid this month to the credit card company.
    - returns: the new balance that will be owed on the credit card
      (assumes no purchases are made). 
    """
    interestCharge = float(((apr / 12.0) / 100) * prevBalance)
    return float((interestCharge + prevBalance) - payment)




def balances(initialBalance, apr, payments):
    """
    - initialBalance: the initial balance on the credit card.
    - apr: the annual percentage rate (15.9 here means 15.9%).
    - payments: a list of monthly payments made on the credit card.
    - returns: a list giving the balance on the credit card each
      month. The first number in the list is the initial
      balance, the next number is the balance after the first
      payment is made, and so on. Note that the length of the returned
      list is len(payments) + 1.
      """
    balancelist = []
    balancelist.append(initialBalance)
    for x in range(0, len(payments)):
        balancelist.append(newBalance(balancelist[x], apr, payments[x]))
    return balancelist




def findMonthlyPayment(initialBalance, apr, months):
    """
    - initialBalance: the starting balance on the card.
    - apr: the APR.
    - months: the number of equal monthly payments you wish to
      make in order to reduce the balance to zero.
    - returns: the monthly payment amount needed to reduce the
      balance to zero (well, "zero" to within $0.005, anyway)
      in the given number of months.
    """
    guess = float(initialBalance / months)
    listo = months*[guess]

    while True:

        if abs(float(balances(initialBalance, apr, listo)[-1]) - initialBalance) < 0.006:
            print "BINGO", guess  ##for debugging
            print balances(initialBalance, apr, listo)[-1]
            return guess

        else:
            if float(balances(initialBalance, apr, listo)[-1]) < -0.005:
                guess = guess - (guess / 2)

                print "BOO", guess ##for debugging
                print balances(initialBalance, apr, listo)[-1]

            else:
                guess = guess + (guess / 2)
                print "NAY", guess  ##for debugging
                print balances(initialBalance, apr, listo)[-1]

        listo = months*[guess]



def testFindMonthlyPayment():
    answer = findMonthlyPayment(1000, 18.9, 60)
    print
    myString = "Monthly payment to pay off $%.2f in %d months at %.2f%% APR:"
    print myString % (1000, 60, 18.9)
    print "$%.2f" % answer
    # Output should look approximately like this:
    """
    iteration: 1 guess: 500.0 final bal: -46777.3384635
    iteration: 2   guess: 250.0   final balance: -22111.7016729
    iteration: 3   guess: 125.0   final balance: -9778.88327752
    iteration: 4   guess: 62.5   final balance: -3612.47407985
    iteration: 5   guess: 31.25   final balance: -529.269481021
    iteration: 6   guess: 15.625   final balance: 1012.3328184
    iteration: 7   guess: 23.4375   final balance: 241.531668687
    iteration: 8   guess: 27.34375   final balance: -143.868906167
    iteration: 9   guess: 25.390625   final balance: 48.83138126
    iteration: 10   guess: 26.3671875   final balance: -47.5187624535
    iteration: 11   guess: 25.87890625   final balance: 0.656309403241
    iteration: 12   guess: 26.123046875   final balance: -23.4312265251
    iteration: 13   guess: 26.0009765625   final balance: -11.387458561
    iteration: 14   guess: 25.9399414062   final balance: -5.36557457885
    iteration: 15   guess: 25.9094238281   final balance: -2.35463258781
    iteration: 16   guess: 25.8941650391   final balance: -0.849161592282
    iteration: 17   guess: 25.8865356445   final balance: -0.0964260945206
    iteration: 18   guess: 25.8827209473   final balance: 0.27994165436
    iteration: 19   guess: 25.8846282959   final balance: 0.0917577799204
    iteration: 20   guess: 25.8855819702   final balance: -0.00233415730086

    Monthly payment to pay off $1000.00 in 60 months at 18.90 APR:
    $25.89
    """

Thanks for the help. 谢谢您的帮助。 Probably wouldn't have joined compsci unless everything I ever googled was on stackoverflow. 除非我用Google搜索的所有内容都在stackoverflow上,否则大概不会加入compsci。

This isn't how you bisect 这不是你一分为二的方法

guess = guess - (guess / 2)

Normally you keep a low_guess and a high_guess. 通常,您保持low_guess和high_guess。 You try 你试试

guess = (low_guess+high_guess)/2

and then based on the result, you either set 然后根据结果,您可以设置

low_guess = guess

or 要么

high_guess = guess

and repeat 并重复

Note: In Python2, / is integer divison if the denominator and numerator are both ints, so it's best to just make sure the initial guess is a float 注意:在Python2中,如果分母和分子均为整数,则/是整数除法,因此最好确保最初的guess是浮点数

def findMonthlyPayment(initialBalance, apr, months):
    """
    - initialBalance: the starting balance on the card.
    - apr: the APR.
    - months: the number of equal monthly payments you wish to
      make in order to reduce the balance to zero.
    - returns: the monthly payment amount needed to reduce the
      balance to zero (well, "zero" to within $0.005, anyway)
      in the given number of months.
    """
    low_guess = 0
    high_guess = initialBalance
    guess = float((low_guess + high_guess) / 2)
    listo = months*[guess]

    while True:

        if abs(float(balances(initialBalance, apr, listo)[-1])) < 0.006:
            print "BINGO", guess  ##for debugging
            print balances(initialBalance, apr, listo)[-1]
            return guess

        elif float(balances(initialBalance, apr, listo)[-1]) < -0.005:
            high_guess = guess
            print "BOO", guess ##for debugging
            print balances(initialBalance, apr, listo)[-1]

        else:
            low_guess = guess
            print "NAY", guess  ##for debugging
            print balances(initialBalance, apr, listo)[-1]
        guess = float((low_guess + high_guess) / 2)
        listo = months*[guess]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM