Python optimization indexed sum using sympy lambdify and scipy

青春壹個敷衍的年華 提交于 2019-12-24 07:57:49

问题


I am kind of looking for a mixed solution of the proposed answer of this thread. The first code snippet is using a more symbolic way, which I am after with the property of the second code snippet where the number of variables change. So something close to this where number of variables n can change.

from sympy import *
from scipy.optimize import minimize
from sympy.utilities.lambdify import lambdify

x, i, n = symbols("x i n")
n = 10
func = Sum((Indexed('x',i)-3)/(1+0.2)**i,(i,1,n))
my_func = lambdify((x, i, n), func)


def my_func_v(x):
    return my_func(*tuple(x))

results = minimize(my_func_v, np.zeros(n))

Any ideas?


回答1:


So this seems to do the trick:

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, 0, n))
    f = lambdify(x, s, modules=['sympy'])
    return float(sign*(y + f(variables)))

z = 3
results = minimize(lambda x: _eqn(3, x, z),np.zeros(z))
print(results.x)

Any further suggestions?



来源:https://stackoverflow.com/questions/47187841/python-optimization-indexed-sum-using-sympy-lambdify-and-scipy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!