我正在尝试解决LP问题,即找到最佳的货币分配方式以最快的速度偿还多笔债务。
首先,我定义了一个函数来确定还清债务需要多长时间。
'''payment must exceeds the accrued interest each month
accrued interest = PV * (1+i) '''
def how_long(PV, APR, PMT):
i = (APR/12)/100
accrued_interest = PV * i
try:
N = round(-(log(1-((PV*i)/PMT)))/log(1+i))
return N
except:
print(f"Your payment must be greater than accrued_interest which is {'%.2f' % accrued_interest}.")
接下来,我创建了一个示例数据和常量:
My_Loans = {
'Name' : ['BOA', 'Sapire','Southwest','SallieMae'],
'Principal' : [350.59, 1672.04, 597.32, 766.63],
'APR' : [6, 4, 4, 5]
}
My_Loans = pd.DataFrame(My_Loans)
# Constants
# Create a list of the food items
loan_items = list(My_Loans['Name'])
# Principals
PV = My_Loans['Principal']
# APR
APR = My_Loans['APR']
# Maximum PMT ----- This will be an input
Max_PMT = 2000
然后,我创建了一个LpProblem:
problem = LpProblem("Loan Repayment", LpMinimize)
此外,这是决策变量和约束条件。
# Decision Variable --- PMT
num_loans = len(My_Loans)
loan_items
PMT = LpVariable.dicts("PMT", list(range(num_loans)), 0, Max_PMT, cat="Continuous")
# Goal Constraint
c1 = sum(PMT) == Max_PMT
# adding the constraints to the problem
problem += c1
我的主要问题是,如何对目标函数使用“ how_long”函数?
我想从“ how_long”函数中找到给我最小“ N之和”的PMT(决策变量)。
这是我从博客复制的示例目标函数:
# objective function
problem += -factory_days[0]*cf0*f0 - factory_days[1]*cf1*f1 - factory_days[2]*cf2*f2
如您所见,上面的示例中决策变量的数目是固定的,但是由于我希望它具有灵活性,所以我觉得我必须循环它,但我不知道该怎么做。
感谢您的帮助。如果有任何不清楚的地方,请告诉我。