Search code examples
pythonscipyminimize

How can I pass fixed arguments using scipy minimize()?


How can I optimize two variables in a three variable function? My understanding was that I can include the last variable in the args parameter, but I cannot make this work. What am I doing wrong here? The idea is that I want to optimize x and y and that z is fixed.

> from scipy.optimize import minimize
> def f(x,y,z):return x**2 * y**2 - x*y*z*32 +10
> minimize(f,[1,2,3],args=[2])
TypeError: f() takes exactly 3 arguments (2 given)

Solution

  • The idea here is that the function that you want to minimize has to accept an array of parameters for minimization and optional arguments. So you have to assign manually input array to function parameters:

    >>> def f(xs, z):
    ...     x, y = xs
    ...     return x**2 * y**2 - x*y*z*32 +10
    ... 
    >>> minimize(f, [1,3], args=(2,))
       status: 2
      success: False
         njev: 18
         nfev: 84
     hess_inv: array([[ 0.02619011, -0.02104178],
           [-0.02104178,  0.02982305]])
          fun: -1014.0000000000002
            x: array([ 5.79312665,  5.52378745])
      message: 'Desired error not necessarily achieved due to precision loss.'
          jac: array([  3.05175781e-05,   1.52587891e-05])
          nit: 6