0

i am new into python and my task is to minimize math functions which have 3 return values (as provided in a template I must use), but I only need the first one of these returns. Here is an example

```
def exponential_function(x):

   value = -np.exp(-0.5 * (x[0]**2 + x[1]**2))
   grad = np.array([-value * x[0], -value * x[1]])

   return value, grad, np.array([0,0])

```

this has to be the first argument of optimize.minimize. This would work for only one return (=value), but in this case I have no idea. I tried wrapper functions, which I failed.

Thank you in advance

2
  • 2
    "I tried wrapper functions, which I failed." Show exactly what you tried and what errors you got. A wrapper function should work. Commented May 31, 2021 at 15:46
  • I'm like 4 hours into this, I tried several things so I have really nothing to show... Commented May 31, 2021 at 15:52

3 Answers 3

1

A function object suitable as the first argument of optimize.minimize which takes the first one of these returns is:

lambda x: exponential_function(x)[0]
Sign up to request clarification or add additional context in comments.

Comments

1

What kind(s) of wrapper did you try. You don't need anything fancy, just something that calls the given function, but returns only the first result, value:

def exponential_function(x):

   value = -np.exp(-0.5 * (x[0]**2 + x[1]**2))
   grad = np.array([-value * x[0], -value * x[1]])

   return value, grad, np.array([0,0])

def myfunc(x):
   value, grad, arr = exponential_function(x)
   return value

You can use lambda as suggesting in other answers, but I tried to make a more explicit wrapper function, that might be easier to understand.

When we ask what you tried, we don't expect working tries. We want to see what you try, and get a better idea of what you understand (or are missing). The goal is to get you to think, and where possible end up solving your own problems, not to spoon feed answers.

Comments

0

Hey you can just call the function with three variables to store the returned values, e.g.:

value_return, grad_return, array_return = exponential_function(x)

So every return is stored in the appropriate variable. Afterwards you can use these variables (outside of the function!). Alternatively just delete the other returns, that you do not need.

Does this answer your question?

2 Comments

hey steTATO, thank you for your answer. I'm afraid that this won't work. I can't just use a variable as first argument of minmize
Since minimize can only take a function, define a wrapper function or lambda as Armali's response shows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.