0

When use the scipy.optimize, the objective function I tried successfully can only take one variable, scalar or vector.

for example, this code works:

from scipy import optimize

def f(x, a=2, b=-5, c=3):
    return a*x*x+b*x+c

res=optimize.minimize_scalar(f)

print(res.x)

however, if what I want is to track the res.x changing with a, b, c? the following code doesn't work, but how to make it work?

from scipy import optimize

def f(x, a, b, c):
    return a*x*x+b*x+c

def change(a, b, c):
    res=optimize.minimize_scalar(f(x, a, b, c))
    print(res.x)
    return res.x

change(3, 2, 1)
change(3, -9, 0)

the only way I can think of is like this:

from scipy import optimize

def change(a, b, c):
    def f(x):
        return a*x*x+b*x+c
    res=optimize.minimize_scalar(f)
    print(res.x)
    return res.x

change(3, 2, 1)
change(3, -9, 0)

function inside another function makes me feel bad, is there any other way? Thanks.

Westack
  • 105
  • 5
  • `a,b,c` can be passed in via the `args` parameter (pay attention to the `tuple` requirement). – hpaulj Aug 08 '19 at 01:50
  • I don't get your meanning, could you show some codes? Thank you very much! – Westack Aug 08 '19 at 01:52
  • https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize_scalar.html#scipy.optimize.minimize_scalar - Do you see the `args` parameter?? – hpaulj Aug 08 '19 at 02:06
  • Thanks, I just saw it, ha, wondering how to use it... – Westack Aug 08 '19 at 05:04

1 Answers1

0

Simply doing this will work:

from scipy import optimize

def f(x, a, b, c):
    return a*x*x+b*x+c

def change(a, b, c):
    tup=(a, b, c)
    res=optimize.minimize_scalar(f, args=tup)
    print(res.x)
    return res.x

change(3, 2, 1)
change(3, -9, 0)
Westack
  • 105
  • 5