0

I am trying to minimize a function using scipy.optimize. Here is my programme and the last line is the error message.

import sympy as s
from scipy.optimize import minimize
x,y,z=s.symbols('x y z')
f= lambda z: x**2-y**2
bnds = ((70,None),(4,6))
res = minimize(lambda z: fun(*x),(70,4), bounds=bnds)



<lambda>() argument after * must be an iterable, not Symbol

How to convert symbol to an iterable or define an iterable directly ?

Nick ODell
  • 15,465
  • 3
  • 32
  • 66
Shareef
  • 11
  • 5

1 Answers1

1

In Python, calling a function with f(*x) means f(x[0], x[1], ...). That is it expects x to a tuple (or other iterable), and the function should have a definition like

def f(*args):
    <use args tuple>

I'm not quite sure what you are trying to do with the sympy code, or why you are using it instead of defining a function in Python/numpy directly.

A function like:

def f(z):
    x,y = z  # expand it to 2 variables
    return x**2 - y**2

should work in a minimize call with:

minimize(f, (10,3))

which will vary x and y starting with (10,3) seeking to minimize the f value.

In [20]: minimize(f, (70,4), bounds=((70,None),(4,6)))
Out[20]: 
      fun: 4864.0
 hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
      jac: array([ 139.99988369,  -11.99996404])
  message: b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
     nfev: 9
      nit: 1
   status: 0
  success: True
        x: array([ 70.,   6.])
hpaulj
  • 221,503
  • 14
  • 230
  • 353