带约束和界的SciPy函数的极小化

2024-04-19 12:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列收取利息的账户,每天我都要决定从哪个账户借钱。我每个账户都有一个借款限额。 显然,最简单的答案是先用尽最便宜的价格,以此类推

因为我们一天要计算好几次,账户的数量会有所不同,我们计划了一个前滚现金流,我正在尝试编写一些Python代码来实现自动化

最小化的目标函数是加权平均利率,确定从每个账户(x)借款的金额,从0到一个整数(取决于每个协议),以覆盖未偿贷款

下面的代码似乎工作得很好,但我在一张纸上做了计算,它没有达到全局最小值。我有什么遗漏吗

import numpy as np
from scipy.optimize import minimize

outstanding = -106332403


limit = [15000000, 29250000, 15000000, 22000000, 52567324, 5000000, 5000000, 40000000, 7398262]
interest = [0.73, 0.63, 0.78, 0.75, 0.6084, 0.97, 0.84, 0.625, 0.40]

limit = np.asarray(limit)
interest = np.asarray(interest)

def objective(x):
    product = x * interest
    sumproduct = sum(product)
    return sumproduct / -outstanding

def constraint1(x):
    return sum(x) + outstanding

# initial guesses
n = len(interest)
x0 = [1,1,1,1,1,1,1,1,1]

bnds = []

for value in limit:
    b= (0,value)
    bnds.append(b)


con1 = {'type': 'eq', 'fun': constraint1}
cons = (con1)

solution = minimize(objective,x0,method='SLSQP',bounds=bnds,constraints=cons)

x = solution.x

Tags: 代码importdefnp账户productlimitasarray
1条回答
网友
1楼 · 发布于 2024-04-19 12:44:07

我对你的剧本做了一些修改。最重要的是设置一个较大的最大迭代,并发挥了有限差分步长和收敛公差位。我也重写了你的目标,改变了数量级。这样我就得到了一个接近您在评论中提供的值的解决方案

import numpy as np
from scipy.optimize import minimize

outstanding = -106332403


limit = np.array([15000000, 29250000, 15000000, 22000000, 52567324, 5000000, 5000000, 40000000, 7398262])
interest = np.array([0.73, 0.63, 0.78, 0.75, 0.6084, 0.97, 0.84, 0.625, 0.40])

# initial guesses
n = len(interest)
x0 = np.ones(len(interest)) * 1e6 * 1

def objective(x):
    return np.dot(x, interest)

def constraint1(x):
    con = sum(x) + outstanding
    return con

bnds = [(0, value) for value in limit]

con1 = {'type': 'eq', 'fun': constraint1}

solution = minimize(objective,x0,method='SLSQP',bounds=bnds,constraints=con1, 
                    options={"eps": 01e-3, "maxiter": 1000}, tol=1e-8)

print(solution)

结果:

     fun: 63952359.431600004
     jac: array([0.72999299, 0.62999874, 0.77999383, 0.74999779, 0.60839951,
       0.96999854, 0.84000081, 0.6249994 , 0.40000677])
 message: 'Optimization terminated successfully.'
    nfev: 1635
     nit: 147
    njev: 145
  status: 0
 success: True
       x: array([0.00000000e+00, 6.36681700e+06, 0.00000000e+00, 0.00000000e+00,
       5.25673240e+07, 1.77575799e-16, 2.32417370e-17, 4.00000000e+07,
       7.39826200e+06])

相关问题 更多 >