使用sympy lambdify和scipy进行Python优化索引和 [英] Python optimization indexed sum using sympy lambdify and scipy
本文介绍了使用sympy lambdify和scipy进行Python优化索引和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找此问题的建议答案的混合解决方案线程.第一个代码段使用的是更具象征性的方式,在此之后,我使用了第二个代码段的属性,其中变量的数量发生了变化.因此,与此接近的变量数量n可以改变.
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))
有什么想法吗?
推荐答案
所以这似乎可以解决问题:
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)
还有其他建议吗?
这篇关于使用sympy lambdify和scipy进行Python优化索引和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文