首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只有当解决方案为负值时,才能进行我的搜索(MIT6.00)

只有当解决方案为负值时,才能进行我的搜索(MIT6.00)
EN

Stack Overflow用户
提问于 2014-07-03 15:52:46
回答 1查看 107关注 0票数 1

各位,

在MIT6.00中,我的头被PS1的问题3缠住了。我写了几个函数(一个二分法搜索,一个函数建模信用卡债务)。问题是,它集中在一个解决方案,给出一个略微正馀的信用卡余额。我可以降低二分法搜索的容忍度,但我想知道是否有更优雅的方法使这个优化器只返回负面的结果。

干杯,

艾登

代码:

代码语言:javascript
复制
import numpy as np

def bisection(a, b, fun, tol, var = None):
    """Note that this only works if you put the independant variable
    as the first argument in the parameter """
    #def tstr(x):
    #    return 2*(x**2) - 3*x + 1
    #sol = bisection(0,0.9,tstr,0.1)

    c = (a+b)/2.0  

    if var != None:
        arga = var[:]
        argc = var[:]
        arga.insert(0,a)
        argc.insert(0,c)
    else:
        arga = a
        argc = c

    if (b-a)/2.0 <= tol:
        #Debugging print statement 1:
        #print 'SOL1: c = ', c
        if var != None:
            return [c] + fun(argc)
        else:
            return c

    if fun(argc)[0] == 0:
        if var != None:
            return [c] + fun(argc)
        else:
            return c
    elif fun(arga)[0]*fun(argc)[0] < 0:
        b = c
    else:
        a = c
    return bisection(a, b, fun, tol, var)


"""
Now we have defined a version of the paidOff function to work
with the bisection method"""

def paidOffBis(args):#(Pay, Bal, Apr):
    """Tester for Bisection Implementation"""
    # TEST SIZE OF args:
    if (type(args) != list)|(np.size(args) != 3):
        print 'Incorrect size or type of input, input size:', np.size(args), '-', args
        return None
    Pay, Bal, Apr = args
    Mpr = Apr/12.0
    Baln = Bal
    Nm = 0
    for n in range(12):
        Baln = Baln*(1 + Mpr) - Pay
        if (Baln < 0)&(Nm == 0):
            Nm = n + 1   
    if Baln < 0:
        return [Baln, Nm]
    else:
        return [Baln, Nm]

Out_Bal = float(raw_input('Enter the outstanding balance on your credit card: '))
Apr = float(raw_input('Enter the annual credit card interest rate as a decimal: '))

varin = [Out_Bal, Apr]

#(Out_Bal*(1 + (Apr/12.0))**12.0)/12.0
sol = bisection(Out_Bal/12.0, Out_Bal, paidOffBis, 0.01, varin)

print 'RESULT'
print 'Monthly payment to pay off debt in 1 year: $%.2f' % sol[0]
print 'Number of months needed:', sol[2]
print 'Balance: $%.2f' % sol[1]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-03 17:53:01

要确保余额小于或等于零,您需要正确地设置条件语句--您需要继续搜索,直到满足该条件为止。你要的是... a more elegant way ...。对变量使用描述性名称并保持简单,肯定会改进您的代码。这里有一种使用二分法搜索来构造一个解的方法。

代码语言:javascript
复制
annualInterestRate = .1
balance = 1000

def balance_after_one_year(balance, annualInterestRate, payment):
    '''Calculate the balance after one year of interest and payments.

    balance --> int or float
    annualInterestRate --> float between 0 and 1
    payment --> float

    returns float
    '''
    for _ in xrange(12):
        balance = (balance - payment) * (1 + annualInterestRate / 12.0)
    return balance

def min_payment(balance, annualInterestRate, tolerance = .01):
    '''Find the minimum payment to pay off a loan.

    Uses a bisection search.
    Ensures balance is not positive.

    balance --> float, int
    annualInterestRate --> float less than one
    tolerance --> float
   '''

    # we want the tolerance to be negative
    # this isn't strictly a tolerance, it is a lower limit
    tolerance = -abs(tolerance)

    hi = balance
    lo = 0
    while True:
        payment = (hi + lo) / 2.0
        tmp_balance = balance_after_one_year(balance, annualInterestRate, payment)
        if tmp_balance < tolerance:
            hi = payment
        # ensure balance is not positive
        elif tmp_balance > 0:
            lo = payment
        else:
            return payment, tmp_balance

用法:

代码语言:javascript
复制
min_pmt, final_balance = min_payment(balance, annualInterestRate)
print 'minimum payment', min_pmt
print 'final balance', final_balance
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24558302

复制
相关文章

相似问题

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