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.
我正在寻找这个线程的拟议答案的混合解决方案。第一个代码片段使用了更具象征性的方式,我追溯到第二个代码片段的属性,其中变量的数量发生了变化。所以接近这个变量n的数量可以改变。
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 个解决方案
#1
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?
还有什么建议?
#1
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?
还有什么建议?