Peterhack
Peterhack

Reputation: 1061

Python optimization indexed sum using sympy lambdify and scipy

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?

Upvotes: 1

Views: 606

Answers (1)

Peterhack
Peterhack

Reputation: 1061

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?

Upvotes: 1

Related Questions