在lambda函数中索引以优化求和的多个变量

时间:2017-11-10 10:22:23

标签: python lambda scipy sympy

我想解决this线程中提出的优化问题。现在,我不仅想要求解x[1]...x[n],还求解变量y。看起来索引有问题。

from sympy import Sum, symbols, Indexed, lambdify
from scipy.optimize import minimize
import numpy as np

def _eqn(y, variables, periods, sign=-1.0):
    x, i = symbols("x i")
    n = periods-1
    s = Sum(Indexed('x', i)/(1+0.06)**i, (i, 1, n))
    f = lambdify(x, s, modules=['sympy'])
    return float(sign*(y + f(variables)))

z = 3
results = minimize(lambda xy: _eqn(xy[0], xy[1:z], z),np.zeros(z))
print(results.x)

2 个答案:

答案 0 :(得分:0)

如果您只需要可变数量的参数来进行最小化,那么以下代码是否适用于您?

from sympy import var
from scipy.optimize import minimize
import numpy as np

def _eqn(y, variables, periods, sign=-1.0):    
    f = 0
    for i,x in enumerate(variables):
        f += x/(1+0.06)**(i+1)
    return float(sign*(y + f))

z = 3
results = minimize(lambda xy: _eqn(xy[0], xy[1:z], z),np.zeros(z))
print(results.x)

答案 1 :(得分:0)

从错误消息中,您的索引中似乎存在问题。求和从1到n运行,但默认情况下,Python中列表类型对象的索引从0到n-1。如果我在你的代码中更改它似乎工作。看看吧。

import sympy as sp
from scipy.optimize import minimize
import numpy as np

sp.init_printing()

def _eqn(y, variables, periods, sign=-1.0):
    x, i = sp.symbols("x i")
    n = periods-1
    s = sp.Sum(sp.Indexed('x', i)/(1+0.06)**(i+1), (i, 0, n-1)).doit()
    f = sp.lambdify(x, s, modules=['sympy'])
    return float(sign*(y + f(variables)))

z = 3
results = minimize(lambda xy: _eqn(xy[0], xy[1:z], z),np.zeros(z))
print(results.x)